gpt4 book ai didi

android - Flutter-在子孙中调用setState后重建父对象

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

我有一类带有主页,另一类带有Dialog(当用户单击 float 按钮时出现)。

从对话框中的下拉菜单中选择某项后,主页上有一个TextField,我想立即更新它(该对话框与TextField距离很远,在另一个类中)。我如何告诉flutter重建该(父)类?

它对我不起作用,在按您的书写方式应用更改后,我的下拉菜单中没有选项,并且无法单击。

DropdownButton<double>(
hint: Text("Specify sleep lenght"),
value: dropdownValue,
onChanged: onValueChange,
items: availableLengthHours.map((l) {
return DropdownMenuItem(
child: new Center(child: Text(l.toString())),
value: l,
);
}).toList(),
),

最佳答案

Jacek,不确定您尝试了什么,但是实现所需目标的一种方法是使用对话框选项作为Navigator.push的结果。这是一个简单的例子,

class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}

class MyAppState extends State<MyApp> {
String text = 'Original text';

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('Test'),),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(
left: 10.0, right: 10.0),
child: Column(children: <Widget>[
Text(text, style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold)),
]))
])),
floatingActionButton: Builder( builder: (context) => FloatingActionButton(
child: Icon(Icons.refresh),
onPressed: () async {
update(context);
},
)),
),
);
}

update(BuildContext context) async {
final result = await Navigator.push(
context,
MaterialPageRoute(builder: (context) => Dialog()),
);

setState(() {
text= result;
});
}
}

class Dialog extends StatelessWidget {
String dropdownValue = 'Updated item 1';
@override
Widget build(BuildContext context) {
return AlertDialog(
title: new Text('Test dialog'),
content: DropdownButton<String>(
value: dropdownValue,
icon: Icon(Icons.arrow_downward),
iconSize: 24,
elevation: 16,
style: TextStyle(color: Colors.deepPurple),
underline: Container(
height: 2,
color: Colors.deepPurpleAccent,
),
onChanged: (String newValue) {
Navigator.pop(context, newValue);
},
items: <String>[
'Updated item 1',
'Updated item 2',
'Updated item 3',
'Updated item 4'
].map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
),
actions: <Widget>[
// usually buttons at the bottom of the dialog
new FlatButton(
child: new Text('Cancel'),
onPressed: () {
Navigator.pop(context, true);
},
)
],
);
}
}

demo

希望这会好起来。

关于android - Flutter-在子孙中调用setState后重建父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59329808/

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