我需要一些帮助。如何在flutter中的变量上动态设置数据?我在listview.builder中有一个表单。动态生成多少个TextFormField。因此,很难为每个TextFormField创建不同的变量。当用户名文本在TextFormField中时,我希望setState该数据在var
上,以便我可以将该数据存储在firebase中。这是我的代码的简单版本:
Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: widget.stops,
itemBuilder: (context, index) {
var stops = 1;
return Row(
children: <Widget>[
Flexible(
child: Container(
child: TextFormField(
decoration: InputDecoration(
labelText: 'Stop ' +
(stops + index).toString(),
),
validator: (val) => val.isEmpty
? 'Cannot be empty'
: null,
onChanged: (val) {
setState(() {
//here i want setdata dynamically
});
},
),
),
),
Flexible(
child: Container(
child: TextFormField(
cursorColor: Color(0xFF127772),
decoration: InputDecoration(
labelText: 'Ticket Price',
),
),
),
validator: (val) => val.isEmpty
? 'Cannot be empty'
: null,
onChanged: (val) {
setState(() {
//here i want setdata dynamically
});
},
),
),
)
],
);
}),
),
Container(
child: RaisedButton(
),
onPressed: () async {
if (_formKey.currentState.validate()) {}
},
child: Text('CREATE'),
),
),
],
),
),
您可以在项目中有两个textField时创建两个String列表,并在onsave方法上将val分配给此列表。
以下代码可帮助您更多地理解。
class DeleteWidget extends StatefulWidget {
final stops = 2;
@override
_DeleteWidgetState createState() => _DeleteWidgetState();
}
class _DeleteWidgetState extends State<DeleteWidget> {
List<String> _list1;
List<String> _list2;
GlobalKey<FormState> _formKey = GlobalKey<FormState>();
@override
void initState() {
super.initState();
_list2 = List(widget.stops);
_list1 = List(widget.stops);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Form(
key: _formKey,
child: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: widget.stops,
itemBuilder: (_, index) {
return Row(
children: [
Flexible(
child: TextFormField(
validator: (val) =>
val.isEmpty ? 'Cannot be empty' : null,
onChanged: (val) {
setState(
() {
_list1[index] = val;
},
);
},
),
),
SizedBox(
width: 20,
),
Flexible(
child: TextFormField(
validator: (val) =>
val.isEmpty ? 'Cannot be empty' : null,
onChanged: (val) {
setState(
() {
_list2[index] = val;
},
);
},
),
)
],
);
},
),
),
Container(
child: RaisedButton(
onPressed: () async {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
for (int i = 0; i < widget.stops; i++) {
print("item $i form field 1 ${_list1[i]}");
print("item $i form field 2 ${_list2[i]}");
}
}
},
child: Text('CREATE'),
),
),
],
),
),
);
}
}