Flutter 循環(huán)創(chuàng)建多個(gè)輸入框

之前遇到這樣一個(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)化。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容