flutter - 如何在 Flutter 中更新 AnimatedList 中的数据

标签 flutter listview dart flutter-animation flutter-animatedlist

如何在 Flutter 的 AnimatedList 中更新数据(添加、删除行)?我只需更新支持数据并调用 setState 即可在 ListView 中完成此操作。例如,

setState(() {
  _data.insert(2, 'pig');
});

虽然在 AnimatedList 中看起来更复杂。

最佳答案

下面演示了更新 AnimatedList 的各种方法。该过程每次包括两个主要步骤:

  1. 更新数据集
  2. 将更改通知 AnimatedList 的全局键

插入单个项目

在索引 2 处添加“Pig”。

enter image description here

String item = "Pig";
int insertIndex = 2;
_data.insert(insertIndex, item);
_listKey.currentState.insertItem(insertIndex);

插入多个项目

在索引 2 处插入三只动物。

enter image description here

final items = ['Pig', 'Chichen', 'Dog'];
int insertIndex = 2;
_data.insertAll(insertIndex, items);
// This is a bit of a hack because currentState doesn't have
// an insertAll() method.
for (int offset = 0; offset < items.length; offset++) {
  _listKey.currentState.insertItem(insertIndex + offset);
}

删除单个项目

从列表中删除“ pig ”。

enter image description here

int removeIndex = 2;
String removedItem = _data.removeAt(removeIndex);
// This builder is just so that the animation has something
// to work with before it disappears from view since the original
// has already been deleted.
AnimatedListRemovedItemBuilder builder = (context, animation) {
  // A method to build the Card widget.
  return _buildItem(removedItem, animation);
};
_listKey.currentState.removeItem(removeIndex, builder);

删除多个项目

从列表中删除“ Camel ”和“绵羊”。

enter image description here

int removeIndex = 2;
int count = 2;
for (int i = 0; i < count; i++) {
  String removedItem = _data.removeAt(removeIndex);
  AnimatedListRemovedItemBuilder builder = (context, animation) {
    return _buildItem(removedItem, animation);
  };
  _listKey.currentState.removeItem(removeIndex, builder);
}

补充代码

主.dart

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text('Update AnimatedList data')),
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatefulWidget {
  @override
  BodyWidgetState createState() {
    return new BodyWidgetState();
  }
}

class BodyWidgetState extends State<BodyWidget> {

  // the GlobalKey is needed to animate the list
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();

  // backing data
  List<String> _data = ['Horse', 'Cow', 'Camel', 'Sheep', 'Goat'];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 400,
          child: AnimatedList(
            key: _listKey,
            initialItemCount: _data.length,
            itemBuilder: (context, index, animation) {
              return _buildItem(_data[index], animation);
            },
          ),
        ),
        RaisedButton(
          child: Text(
            'Insert single item',
            style: TextStyle(fontSize: 20),
          ),
          onPressed: () {
            _onButtonPress();
          },
        )
      ],
    );
  }

  Widget _buildItem(String item, Animation animation) {
    return SizeTransition(
      sizeFactor: animation,
      child: Card(
        child: ListTile(
          title: Text(
            item,
            style: TextStyle(fontSize: 20),
          ),
        ),
      ),
    );
  }

  void _onButtonPress() {
    // replace this with method choice below
    _insertSingleItem();
  }

  void _insertSingleItem() {
    String item = "Pig";
    int insertIndex = 2;
    _data.insert(insertIndex, item);
    _listKey.currentState.insertItem(insertIndex);
  }

  void _insertMultipleItems() {
    final items = ['Pig', 'Chichen', 'Dog'];
    int insertIndex = 2;
    _data.insertAll(insertIndex, items);
    // This is a bit of a hack because currentState doesn't have
    // an insertAll() method.
    for (int offset = 0; offset < items.length; offset++) {
      _listKey.currentState.insertItem(insertIndex + offset);
    }
  }

  void _removeSingleItems() {
    int removeIndex = 2;
    String removedItem = _data.removeAt(removeIndex);
    // This builder is just so that the animation has something
    // to work with before it disappears from view since the original
    // has already been deleted.
    AnimatedListRemovedItemBuilder builder = (context, animation) {
      // A method to build the Card widget.
      return _buildItem(removedItem, animation);
    };
    _listKey.currentState.removeItem(removeIndex, builder);
  }

  void _removeMultipleItems() {
    int removeIndex = 2;
    int count = 2;
    for (int i = 0; i < count; i++) {
      String removedItem = _data.removeAt(removeIndex);
      AnimatedListRemovedItemBuilder builder = (context, animation) {
        return _buildItem(removedItem, animation);
      };
      _listKey.currentState.removeItem(removeIndex, builder);
    }
  }
}

注意

  • 如果您的列表项包含任何有状态的小部件,那么您需要为它们提供 key ,以便系统可以跟踪它们。
  • 虽然我在写 Medium 文章之前写了这个答案,但我现在正在维护 my answer on Medium .在那里查看最新更新。

关于flutter - 如何在 Flutter 中更新 AnimatedList 中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54376420/

相关文章:

Flutter SizedBox 与 LimitedBox

azure - 使用 Azure Function 将视频上传到 Blob 存储

android listview 设置某些项目的背景(滚动时出现问题)

dart - 在另一个字符串中间连接字符串,跳过最后一个

android - 如何优化具有不同项目布局的 ListView

java - 在 Android 中使用 Listview 从 Firebase 搜索数据

Angular2 - 如何在模板中引用图像

dart - RangeError : Invalid value: Not in range 0. .1114111,包括:-1 尝试使用升级命令时

Firebase Firestore 换行命令

android-studio - Flutter:任务 ':app:transformClassesAndResourcesWithProguardForRelease' 执行失败