gpt4 book ai didi

flutter - Flutter-为什么setstate在弹出窗口上不起作用?

转载 作者:行者123 更新时间:2023-12-03 04:14:05 25 4
gpt4 key购买 nike

嗨,我想通过用户交互更改弹出窗口上的文本,但没有更改。我已经尝试过navigator.pop(context)并重新启动show方法。它可以正常工作,但是是正确的方法吗?我是否可以在没有Navigator.pop的情况下更改弹出窗口的值。为什么不起作用?

这是我的代码。

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

void main() => runApp(RatelApp());

class RatelApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
title: Text('RFlutter Alert by Ratel'),
),
body: Home(),
),
);
}
}



class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
String val = "Deneme";
showAlertDialog(BuildContext context, Function onPressed) {
// set up the button
Widget okButton = FlatButton(
child: Text(val),
onPressed: onPressed,
);

// set up the AlertDialog
AlertDialog alert = AlertDialog(
title: Text("My title"),
content: Text("This is my message."),
actions: [
okButton,
],
);

// show the dialog
showDialog(
context: context,
builder: (BuildContext context) {
return alert;
},
);
}
@override
Widget build(BuildContext context) {
return Container(
child: RaisedButton(
child: Text("Show Popup"),
onPressed: () {
showAlertDialog(context, (){
setState(() {
val = "changed";

});
});
},

),
);
}
}

最佳答案

对话框通常是无状态的,也不是调用Widget的状态的一部分,因此,调用setState方法不会为对话框做任何事情。要创建一个内容可以更改的对话框,请使用StatefulBuilder

docs的示例显示了如何在对话框中使用它,就像在您的应用程序中一样。

文档示例:

await showDialog<void>(
context: context,
builder: (BuildContext context) {
int selectedRadio = 0;
return AlertDialog(
content: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Column(
mainAxisSize: MainAxisSize.min,
children: List<Widget>.generate(4, (int index) {
return Radio<int>(
value: index,
groupValue: selectedRadio,
onChanged: (int value) {
setState(() => selectedRadio = value);
},
);
}),
);
},
),
);
},
);

关于flutter - Flutter-为什么setstate在弹出窗口上不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61976315/

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