[英]Flutter: Set global variable using OK button on AlertDialog in StatefulBuilder
How to set global variable using OK button on AlertDialog in StatefulBuilder?如何使用 StatefulBuilder 中 AlertDialog 上的 OK 按钮设置全局变量?
String stringMain = "My String";
Future<String?> dialogChangeMainContent(BuildContext context) { return showDialog<String>( context: context, builder: (BuildContext context) { return StatefulBuilder(builder: (context, setState) { return AlertDialog( title: const Text('AlertDialog Title'), content: const Text('AlertDialog description'), actions: <Widget>[ TextButton( onPressed: () { Navigator.pop(context, 'OK'); setState(() { // setState2(); stringMain = "New String"; }); }, child: const Text('OK'), ), ], ); }); }); }
I changed StatefulWidget from StatelessWidget, but nothing changes.我从 StatelessWidget 更改了 StatefulWidget,但没有任何变化。 What I know is the problem is because the button is in the StatefulBuilder.
我所知道的问题是因为按钮在 StatefulBuilder 中。 If using BLoC etc, it's too wasteful for only small applications.
如果使用 BLoC 等,对于小型应用程序来说太浪费了。
I found a way to solve my problem, redrawing (refreshing) the Text (or other widget) in a Stateless Widget from an AlertDialog in a StatefulBuilder.我找到了解决问题的方法,从 StatefulBuilder 中的 AlertDialog 重绘(刷新)无状态小部件中的文本(或其他小部件)。 By creating a setState with a different name , for example setStateTarget .
通过创建具有不同名称的 setState ,例如setStateTarget 。 Without having to rebuild the entire page, or without state management like BLoC.
无需重新构建整个页面,也无需像 BLoC 那样进行 state 管理。 My code:
我的代码:
String stringMain = "My String";
@override Widget build(BuildContext context) { return Column( //.... children: [ StatefulBuilder(builder: (BuildContext context, setStateTarget) { return Column(children: [ Text(stringMain), // <--- target TextButton( onPressed: () => dialogChangeMainContent(context, setStateTarget), child: const Text('Show Dialog')) ]); }) ], ); } Future<String?> dialogChangeMainContent(BuildContext context, StateSetter setStateTarget) { return showDialog<String>( context: context, builder: (BuildContext context) { return StatefulBuilder(builder: (context, setState) { return AlertDialog( title: const Text('AlertDialog Title'), content: const Text('AlertDialog description'), actions: <Widget>[ TextButton( onPressed: () { Navigator.pop(context, 'OK'); setStateTarget(() { // setState2(); stringMain = "New String"; }); }, child: const Text('OK'), ), ], ); }); }); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.