dart - Flutter:从另一个 Dart 文件中获取 AlertDialog
问题描述
我需要帮助伙计们。我有 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(
);
}
}
推荐阅读
- centos7 - 使用过多 CPU 的脉冲音频
- java - 如何使用现有片段模板扩展 Thymeleaf 方言
- python - 如果给出了 id,我如何在这个列表中找到其他属性的其他值,里面有字典
- networking - 当您有本地 IP 地址时,为什么我们需要 MAC 地址
- r - 如何在 R 中的单个数据框中转换(标准化)类别内的数据?
- java - 春季启动中的@value没有从application.properties中提供价值
- arrays - 如何编写动态数量的行并将它们分配给 C 中的数组
- c - 整数 x; 是句法错误还是语义错误?
- python - 计算给定掩码中两个 numpy 数组中相等元素的数量
- sql - PostgreSQL - 计算出售计数的机构数量