gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 07:16:46 25 4
gpt4 key购买 nike

此代码中的 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/

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