Flutter开发圈

Flutter 循环创建多个输入框

2020-09-05  本文已影响0人  aCodeApe

之前遇到这样一个需求,根据后台返回的数据循环创建多个输入框,个人思路是:初始化一个Map,key为后台返回的数据,value为TextEditingController,简单实现代码如下:

//初始化输入框Map
Map<String, TextEditingController> _textControllers = Map();
//数据源
List dataList = ['指标1', '指标2', '指标3', '指标4', '指标5','指标6', '指标7','指标8', '指标9','指标10', '指标11', '指标12', '指标13', '指标14','指标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: '请输入',
                  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);
}
效果图

具体实现还请根据项目需求,做相关优化。

上一篇下一篇

猜你喜欢

热点阅读