flutter - AlertDialog 函数在 flutter 的每个页面上运行

标签 flutter dart android-alertdialog

此代码中的 AlertDialog 应该仅在用户访问帐户页面时运行(很明显),但在测试它时,它会在帐户页面和所有下一页上运行,甚至重复,我的意思是当我从Account页面到另一个页面AlertDialog会显示两次

    class Account extends StatefulWidget {
    @override
      _AccountState createState() => _AccountState();
}

class _AccountState extends State<Account> {
  @override
  Widget build(BuildContext context) {
    Future.delayed(Duration.zero, () => FirstRun(context));
    return Scaffold(
    //there are alot of widgets here like drawer but all of it works fine
    //i don't think its necessary to write it
    );
  }
FirstRun(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool first = (prefs.getBool('firstUse'));
print('Pressed $first');
if (first == null) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        backgroundColor: Color(0xaa6b6b6b),
        elevation: 10,
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text(
              'first run dialog',
              overflow: TextOverflow.ellipsis,
              maxLines: 6,
              style: TextStyle(
                color: Colors.white,
                fontSize: 24,
              ),
              textAlign: TextAlign.center,
            ),
            Container(
                child: MaterialButton(
                  onPressed: () {
                    prefs.setBool('firstUse', false);
                    Navigator.of(context).pop();
                    print('Pressed $first');
                  },
                  child: Text(
                    'ok',
                      ),
                    ))
              ],
            ),
          );
        },
      );
    }
  }
}

enter image description here enter image description here

最佳答案

可能是因为您开始在 build 方法上显示警报。尝试在 Account 小部件的 initState 方法上显示它。

class _AccountState extends State<Account> {
  @override
  initState() {
     Future.delayed(Duration.zero, () => FirstRun(this.context));
     super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
    //there are alot of widgets here like drawer but all of it works fine
    //i don't think its necessary to write it
    );
  }

关于flutter - AlertDialog 函数在 flutter 的每个页面上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57135956/

相关文章:

火力地堡数据库 : how can I change value of list item?

flutter radio 值不变

google-maps - Flutter如何带上前端widget

dart - 为什么可以使用反射来调用外部类的私有(private)方法?

java - 如何在 AlertDialog 之后显示 ProgressDialog

firebase - 函数的返回类型为 'Future<String>' 但不以 return 语句结尾

dart - Flutter:折叠 FlexibleSpaceBar 时更改文本

flutter - var 和 final 变量中的 UI 实现部分之间的区别

java - 无法在 android 中启动 AlertDialog 框

android - 将背景图像应用于 AlertDialog