list - 在颤动中将项目添加到列表时,该项目不会保存在该列表中
问题描述
我有一个用户列表,它显示在表单的下拉列表中,然后提交,列表为空,我创建了一个函数,允许用户在 TextFormField 中键入“名称”,然后将该名称添加到列表中,然后它出现在下拉列表中,但是当页面重新加载时,列表项已经消失。
例子:
void savePerson() {
String newperson = _newPersonController.text;
_persons.add(newperson);
}
The function to save string to list
List<String> _persons = [
];
The List
TextFormField(
controller: _newPersonController,
decoration: InputDecoration(
hintText: 'Add New Person',
prefixIcon: Icon(
Icons.local_hospital,
size: 30,
),
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(15),
)),
The TextFormField where the user inserts the name to be added
FlatButton(
onPressed: () {
savePerson();
setState(() {
_newPersonController.clear();
});
},
child: Text('Add Person'))
Button code
为了清楚起见,它将它添加到列表/下拉列表中 - 这有效,但我的列表似乎无法将信息保存到其中。
我对颤动相当陌生 - 对任何明显的事情感到抱歉。
解决方案
问题可能是下拉的逻辑,并在将项目添加到人员列表时添加 setState()
我使用这段代码:
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final TextEditingController _newPersonController =
new TextEditingController();
List<String> _persons = [];
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
appBar: AppBar(
title: Text('Material App Bar'),
),
body: Center(
child: Column(
children: <Widget>[
DropdownButton(
items: List.generate(
_persons.length,
(i) => DropdownMenuItem(
child: Text(_persons[i]),
)),
onChanged: (_) {}),
TextFormField(
controller: _newPersonController,
decoration: InputDecoration(
hintText: 'Add New Person',
prefixIcon: Icon(
Icons.local_hospital,
size: 30,
),
fillColor: Colors.white,
filled: true,
contentPadding: EdgeInsets.all(15),
)),
FlatButton(
onPressed: () {
savePerson();
setState(() {
_newPersonController.clear();
});
},
child: Text('Add Person'))
],
),
),
),
);
}
void savePerson() {
String newperson = _newPersonController.text;
setState(() {
_persons.add(newperson);
});
}
}
大概能帮到你
推荐阅读
- javascript - 反应滚动到顶部在另一台计算机上不起作用
- app-store - How to apple developer organisation name to nickname in individual?
- reactjs - "Apply() is only allowed in ready status" (unhandled runtime error)
- java - JTable 自定义渲染器不改变颜色
- spring - using Flyway for MongoDb in Spring
- javascript - 在 tableau 服务器上使用 window.location.href 调用当前 url
- java - Apache pulsar 2.8.0 独立失败
- android - Flutter中如何获取StatefulWidget的生命周期?我想确定当前屏幕上小部件的生命周期而不是完整的应用程序
- php - PHP中的日期转换
- ios - iOS 抛硬币动画