Flutter:删除项目时,不会更新ListView内的小部件值

时间:2020-06-07 04:05:29

标签: listview flutter flutter-widget flutter-listview fluttermap

您好,我是新手,我在一个名为split row的小部件中工作,我使用一个带三个子级的ListView:Text Widget,ListView Builder Widget和Container Widget。

我使用文本作为标题,使用地图填充ListView Builder,并使用容器将小部件添加到ListView Builder,一切正常,但是当我删除一个项目时,该项目将从地图上的ListView中删除。生成器也一样,但不会更新值。

为了更好地说明自己,我举了一个textField和Text的例子,第一次输入了map键的值三次,第二次输入了word数据和map键组成了文本。这就是发生的事情

enter image description here

您可以看到,当我删除data1时,该项目消失了,仅保留了数据0,数据2和数据3,但保留了值111,而值333消失了。显然值不对应于地图元素,除了000 => data 0

我已经在论坛上进行过研究,已经在网站上搜索了stackoverflow,但没有找到任何对我有帮助的

这是代码:

import 'package:flutter/material.dart';

class SplitRow extends StatefulWidget {
  @override
  _SplitRowState createState() => _SplitRowState();
}

class _SplitRowState extends State<SplitRow> {
  int _index = 0;
  Map<String, Widget> splitRows = {};
  Map records = {};
  Map col1 = {};

  // Crete Widget Split Row
  Widget _splitRow(index) {
    return Column(
      children: <Widget>[
        Container(
          color: Colors.white,
          height: 40.0,
          child: Row(
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.remove_circle),
                iconSize: 24,
                color: Color(0xFFFF3B30),
                onPressed: () {
                  removeItem(index);
                },
              ),
              Container(
                width: 100,
                child: TextField(
                  keyboardType: TextInputType.numberWithOptions(
                    signed: false,
                    decimal: true,
                  ),
                  decoration: InputDecoration(
                    hintText: 'Put direction here...',
                    border: InputBorder.none,
                  ),
                  style: TextStyle(fontFamily: 'Lekton'),
                  onChanged: (value) {
                    col1["$index"] = value;
                  },
                ),
              ),
              _VerticalDivider(),
              Text('data $index'),
            ],
          ),
        ),
        _HorizontalDivider(),
      ],
    );
  }

  // Create Widget Add Row
  Widget _addRow() {
    return Container(
      height: 40,
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            height: 40,
            color: Colors.white,
            child: IconButton(
              icon: Icon(Icons.add_circle),
              iconSize: 24,
              color: Color(0xFF34C759),
              onPressed: () {
                addItem();
              },
            ),
          ),
          Text('New Item')
        ],
      ),
    );
  }

  // Add splitRow
  void addItem() {
    int key = _index;
    print('Index antes $_index');
    setState(() {
      splitRows['$key'] = _splitRow(key);
      ++_index;
    });
    print(splitRows);
  }

  // Remove splitRow
  void removeItem(key) {
    setState(() {
      splitRows.remove('$key');
      col1.remove('$key');
    });
  }

  // Save Values
  void saveItems() {
    records = {'qty': col1};
    print(records);
  }

  @override
  void initState() {
    super.initState();
    splitRows['$_index'] = _splitRow(_index);
    ++_index;
    // splitRows['$_index'] = _addRow(_index);
    // ++_index;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('Directions'),
          actions: <Widget>[
            FlatButton(
              child: Text(
                'Save',
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                saveItems();
              },
            )
          ],
        ),
        backgroundColor: Color(0xFFE5E5EA),
        body: Column(
          children: <Widget>[
            Container(
                constraints: BoxConstraints(
                  minHeight: 40.0,
                  maxHeight: 500.0,
                  minWidth: double.infinity,
                  maxWidth: double.infinity,
                ),
                child: ListView(
                  children: <Widget>[
                    Padding(padding: EdgeInsets.only(top: 10.0)),
                    Text('DIRECTIONS'),
                    ListView.builder(
                      shrinkWrap: true,
                      itemCount: splitRows.length,
                      itemBuilder: (BuildContext context, int index) {
                        String key = splitRows.keys.elementAt(index);
                        return splitRows[key];
                      },
                      physics: NeverScrollableScrollPhysics(),
                    ),
                    _addRow()
                  ],
                ))
          ],
        ));
  }
}

class _HorizontalDivider extends StatelessWidget {
  const _HorizontalDivider({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Divider(
        height: 2.0,
      ),
    );
  }
}

class _VerticalDivider extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 20,
      width: 2,
      margin: EdgeInsets.symmetric(horizontal: 5.0, vertical: 5.0),
      child: VerticalDivider(
        width: 2.0,
      ),
    );
  }
}

我将永远感激您能给我的任何帮助或建议,我已经很长时间没有解决办法了

1 个答案:

答案 0 :(得分:1)

ListView.builder生成要显示的窗口小部件列表,当您删除一个窗口小部件并更新状态ListView.builder时,只需重新运行这些窗口小部件即可进行构建,并查看TextField已经存在,将它们看起来像的元素进行比较相同的小部件,因此它不会更改任何内容,文本字段也不会保存任何已保存的状态,因此即使进行了重建,它也只会返回“在此处放置方向...”。即使您认为已将窗口小部件的状态保存在不更改任何内容的Map中,也会保存要构建的窗口小部件,但不存在任何状态。您可以添加一个Key以使它们看起来有所不同,也可以向TextField中添加一个Textcontroller(它不会保存状态,但是您可以为其添加初始文本值)

class MySplitRow extends StatelessWidget{
  final Map col1;
  final String index;
  final VoidCallback onPressed;

  MySplitRow({this.col1, this.index, this.onPressed, Key key}) : super(key: key);


  @override
  Widget build(BuildContext context){
    return Column(
      children: <Widget>[
        Container(
          color: Colors.white,
          height: 40.0,
          child: Row(
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.remove_circle),
                iconSize: 24,
                color: Color(0xFFFF3B30),
                onPressed: onPressed,
              ),
              Container(
                width: 100,
                child: TextField(
                  controller: TextEditingController(text: col1["$index"]), //it will check the map col1 and if its not null it will give you the value that was saved at that key
                  keyboardType: TextInputType.numberWithOptions(
                    signed: false,
                    decimal: true,
                  ),
                  decoration: InputDecoration(
                    hintText: 'Put direction here...',
                    border: InputBorder.none,
                  ),
                  style: TextStyle(fontFamily: 'Lekton'),
                  onChanged: (value) {
                    col1["$index"] = value;
                  },
                ),
              ),
              const VerticalDivider(width: 10, endIndent: 10, indent: 10), //Works exactly as _VerticalDivider with less code
              Text('data $index')
            ],
          ),
        ),
        const Divider(color: Colors.white, height: 2) //Works exactly as _HorizontalDivider with less code
      ],
    );
  }
}

并在Listview.builder中

 (BuildContext context, int index) {
  String key = splitRows.keys.elementAt(index);
  return MySplitRow(
     key: ValueKey<String>(key),
     col1: col1,
     index: key,
     onPressed: () => removeItem(key),
  );
}

一些建议,宁愿使用Class而不是使用方法来构建Widget。您无需构建容器中的分隔线就可以构建_Horizo​​ntalDivider和_VerticalDivider