我正在创建一个应用程序,用户可以在“文本字段”中输入一些文本。有3个文本字段。我希望在“文本字段”中输入的输入文本存储在列表中。我正在尝试通过运行以下代码来实现这一目标。但是它总是输出一个空列表。似乎找不到问题。
class _ListPageState extends State<ListPage> {
List<String> items = [];
var counter = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Create Your Need List', style: TextStyle(color: Colors.grey[500]),), backgroundColor: Colors.white, elevation: 0,),
body: Padding(
padding: const EdgeInsets.fromLTRB(15, 25, 15, 0),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Add item'
),
onChanged: (String str){
setState(() {
items[counter] = str;
counter +=1;
});
},
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Add item'
),
onChanged: (String str){
setState(() {
items[counter] = str;
counter +=1;
});
},
),
TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: 'Add item'
),
onChanged: (String str){
setState(() {
items[counter] = str;
counter +=1;
});
},
),
SizedBox(height: 10,),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.pushAndRemoveUntil(context, SlideFromLeft(widget: Dashboard()), ModalRoute.withName('/dashboard'));
print(items);
},
child: Icon(Icons.navigate_next),
backgroundColor: Colors.pink,
)
);
}
}
答案 0 :(得分:1)
我认为您可能希望将List用作字典。您也可以这样做
List<String> items = ['', '', ''];
而不是
List<String> items = [];
只需初始化一个空列表。同时修改计数器+ = 1;固定索引。
答案 1 :(得分:0)
您没有添加到列表中。
您需要将items[counter] = str;
更改为
list.add(str);