gpt4 book ai didi

flutter - 在 flutter 中自动在应用程序主屏幕加载上显示警报对话框

转载 作者:IT老高 更新时间:2023-10-28 12:33:18 25 4
gpt4 key购买 nike

我想根据条件显示警报对话框。不基于用户交互,例如按钮按下事件。

如果在应用状态数据警报对话框中设置了标志,则显示,否则不显示。

下面是我要显示的示例警报对话框

  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();
},
),
],
);
},
);
}

我试图在主屏幕小部件的构建方法中调用该方法,但它给了我错误 -

 The context used to push or pop routes from the Navigator must be that of a widget that is a descendant of a Navigator widget.
E/flutter ( 3667): #0 Navigator.of.<anonymous closure> (package:flutter/src/widgets/navigator.dart:1179:9)
E/flutter ( 3667): #1 Navigator.of (package:flutter/src/widgets/navigator.dart:1186:6)
E/flutter ( 3667): #2 showDialog (package:flutter/src/material/dialog.dart:642:20)

问题是我不知道应该从哪里调用 _showDialog 方法?

最佳答案

您必须将内容包装在另一个 Widget 中(最好是无状态的)。

示例:

更改自:

  import 'package:flutter/material.dart';

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('List scroll')),
body: Container(
child: Text("Hello world"),
)));
}
}

对此:

  import 'dart:async';
import 'package:flutter/material.dart';

void main() {
runApp(new MyApp());
}

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Trial',
home: Scaffold(
appBar: AppBar(title: Text('List scroll')), body: new MyHome()));
}
}

class MyHome extends StatelessWidget { // Wrapper Widget
@override
Widget build(BuildContext context) {
Future.delayed(Duration.zero, () => showAlert(context));
return Container(
child: Text("Hello world"),
);
}

void showAlert(BuildContext context) {
showDialog(
context: context,
builder: (context) => AlertDialog(
content: Text("hi"),
));
}
}

注意:请参阅 here用于在 Future.delayed(Duration.zero,..)

中包装显示警报

关于flutter - 在 flutter 中自动在应用程序主屏幕加载上显示警报对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com