之前遇到這樣一個(gè)需求,根據(jù)后臺(tái)返回的數(shù)據(jù)循環(huán)創(chuàng)建多個(gè)輸入框,個(gè)人思路是:初始化一個(gè)
Map,key為后臺(tái)返回的數(shù)據(jù),value為TextEditingController,簡(jiǎn)單實(shí)現(xiàn)代碼如下:
//初始化輸入框Map
Map<String, TextEditingController> _textControllers = Map();
//數(shù)據(jù)源
List dataList = ['指標(biāo)1', '指標(biāo)2', '指標(biāo)3', '指標(biāo)4', '指標(biāo)5','指標(biāo)6', '指標(biāo)7','指標(biāo)8', '指標(biāo)9','指標(biāo)10', '指標(biāo)11', '指標(biāo)12', '指標(biāo)13', '指標(biāo)14','指標(biāo)15' ];
//綁定
dataList.forEach((element) {
_textControllers[element] = TextEditingController();
});
//UI
Expanded(
child: ListView.separated(
itemBuilder: (context, index) {
return Row(
children: <Widget>[
Container(
alignment: Alignment.centerLeft,
padding: EdgeInsets.only(left: 15, top: 10, bottom: 10),
child: Text(
'${dataList[index]}',
style: TextStyle(color: Colors.red, fontSize: 17),
),
),
Padding(padding: EdgeInsets.only(left: 10)),
Expanded(
child: TextField(
controller: _textControllers[dataList[index]],
maxLines: 1,
keyboardType: TextInputType.text,
autofocus: false,
style: TextStyle(fontSize: 17, color: Colors.black),
decoration: InputDecoration(
border: InputBorder.none,
hintText: '請(qǐng)輸入',
hintStyle: TextStyle(
color: Colors.grey[400],
fontSize: 15,
),
),
onTap: () {},
onChanged: (value) => {},
onEditingComplete: () {
FocusScope.of(context).requestFocus(FocusNode());
},
),
),
],
);
},
separatorBuilder: (context, index) {
return Divider(
height: .5,
indent: 15,
endIndent: 15,
color: Colors.grey,
);
},
itemCount: dataList.length),
),
//取值
List valueList = List();
dataList.forEach((item) {
Map valueMap = Map();
if (_textControllers[item].text.isNotEmpty) {
valueMap[item] = _textControllers[item].text;
print(valueMap);
valueList.add(valueMap);
}
});
print(valueList);
}

效果圖
具體實(shí)現(xiàn)還請(qǐng)根據(jù)項(xiàng)目需求,做相關(guān)優(yōu)化。