我需要帮助伙计们。 我有 2 个 Dart 文件:main.dart 和 alertform.dart。有些情况需要在我的应用程序中使用此方法。 我想尝试通过 main.dart 上的按钮从 alertform.dart 访问 alerdialog。那可能吗?这是我的代码:
主.dart
import 'package:flutter/material.dart';
import 'alertform.dart';
class MainPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text('Test'),
),
body: new Column(
children: <Widget>[
RaisedButton(
child: new Text('Show Alert'),
onPressed: (){
CommentForm();
},
)
],
),
);
}
}
alertform.dart
import 'package:flutter/material.dart';
class AlertForm extends StatefulWidget {
@override
_AlertFormState createState() => _AlertFormState();
}
class _AlertFormState extends State<AlertForm> {
void _showDialog() {
// flutter defined function
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Alert Dialog title"),
content: new Text("Alert Dialog body"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Container(
);
}
}
最佳答案
我不知道你为什么要从课外调用这个_dialog,你可以在课内调用。但如果你想这样做,那么你可以试试这段代码。
import 'package:flutter/material.dart';
import 'alertform.dart';
class MainPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text('Test'),
),
body: new Column(
children: <Widget>[
RaisedButton(
child: new Text('Show Alert'),
onPressed: (){
AlertFormState(context).showDialogBox;
},
)
],
),
);
}
}**
import 'package:flutter/material.dart';
class AlertForm extends StatefulWidget {
@override
AlertFormState createState() => AlertFormState();
}
class AlertFormState extends State<AlertForm> {
void showDialogBox(BuildContext context) {
// flutter defined function
showDialog(
context: context,
builder: (BuildContext context) {
// return object of type Dialog
return AlertDialog(
title: new Text("Alert Dialog title"),
content: new Text("Alert Dialog body"),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text("Close"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
@override
Widget build(BuildContext context) {
return Container(
);
}
}
关于dart - flutter : Get AlertDialog From Another Dart File,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566636/