Flutter从UI中动态插入和删除`TextFormField`

时间:2020-02-12 09:31:30

标签: flutter flutter-layout

我正试图在单击中插入TextFormField以采用学生的名字。这个东西工作正常。但是问题是当我集成删除功能时,它无法按预期工作。 我确实使用List<Student>来插入和删除项目,并将此List转换为Map以将项目绘制到UI并将用户输入名称值更新为特定的索引Student对象值。

如果我们尝试添加项目并依次删除它们,将可以正常工作,但是唯一的问题是,当我从中间删除单个项目时,它只会更新我的ListMap,但是用户界面不会更新。这是我的代码

import 'package:dynamic_input_add_flutter/student.dart';
import 'package:flutter/material.dart';

class SingleListUse extends StatefulWidget {
  static final String tag = 'single-list-use';
  @override
  _SingleListUseState createState() => _SingleListUseState();
}

class Student1 {
  String _name;
  int _sessionId;

  Student1(this._name, this._sessionId);

  String get name => _name;

  set name(String value) {
    _name = value;
  }

  int get sessionId => _sessionId;

  set sessionId(int value) {
    _sessionId = value;
  }

  @override
  String toString() {
    return 'Student $_name from session $_sessionId';
  }
}

class _SingleListUseState extends State<SingleListUse> {
  List<Student1> _studentList = [];
  Map<int, Student1> _studentMap = {};

  void _addNewStudent() {
    setState(() {
      _studentList.add(Student1('', 1));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(
          Icons.done,
          color: Colors.white,
        ),
        onPressed: () {
          if (_studentList.length != 0) {
            _studentList.forEach((student) => print(student.toString()));
          } else {
            print('map list empty');
          }
        },
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButtonAnimator: FloatingActionButtonAnimator.scaling,
      appBar: AppBar(
        title: Text('Single Map Use'),
        actions: <Widget>[
          FlatButton(
            onPressed: () {
              _addNewStudent();
            },
            child: Icon(
              Icons.add,
              color: Colors.white,
            ),
          )
        ],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 20.0),
        child: Builder(
          builder: (context) {
            print("List : ${_studentList.toString()}");
            _studentMap = _studentList.asMap();
            print("MAP : ${_studentMap.toString()}");
            return ListView.builder(
              itemCount: _studentMap.length,
              itemBuilder: (context, position) {
                print('Item Position $position');
                return Padding(
                  padding: EdgeInsets.only(top: 5.0),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        child: TextFormField(
                          initialValue: _studentMap[position].name.length != 0
                              ? _studentMap[position].name
                              : '',
                          onFieldSubmitted: (name) {
                            setState(() {
                              _studentList[position].name = name;
                            });
                          },
                          decoration: InputDecoration(
                            hintText: 'enter student name',
                            hintStyle: TextStyle(
                              fontSize: 16.0,
                              color: Colors.black26,
                            ),
                            border: OutlineInputBorder(
                              borderSide: BorderSide(
                                color: Colors.black12,
                              ),
                              borderRadius: BorderRadius.all(
                                Radius.circular(15.0),
                              ),
                            ),
                          ),
                        ),
                      ),
                      IconButton(
                        icon: Icon(
                          Icons.delete,
                          color: Colors.red,
                        ),
                        onPressed: () {
                          setState(() {
                            _studentList.removeAt(position);
                          });
                        },
                      )
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}

enter image description here enter image description here

第一张图片是当我们在加号的图标点击中添加一个学生姓名时。(List中的每一项都是TextFormField。当我从用户界面中删除第二项时,从技术上讲它会删除第三项从我曾经使用过的数据结构(ListMap中删除第二个数据(没关系)。在之间执行任何删除操作后,UI出现了问题。

1 个答案:

答案 0 :(得分:0)

因为这是全状态的小部件,所以在状态类中创建一个变量bool showTextFormField = false

现在在小部件中使用if(showTextFormField) <Widget>

立即单击按钮

setState(){
  showTextFormField = true;
}