flutter - 为什么列表在添加新元素时表现不同?

标签 flutter dart flutter-layout

当我追加新元素到现有列表中并在屏幕上显示列表后,有时新元素显示在列表顶部,有时显示在最后。
为什么List会这样?
在下面的代码中,我想在列表顶部显示这个新添加的元素。有没有办法做到这一点?

class _TransactionListState extends State<TransactionList> {

// Existing List with two transactions

  final List<Transaction> transactions = [
    Transaction(
      title: 'New Books',
      id: 't1',
      amount: 44.55,
      date: DateTime.now(),
    ),
    Transaction(
      title: 'Weekly Items',
      id: 't2',
      amount: 22.44,
      date: DateTime.now(),
    ),
  ];

  final titleController = TextEditingController();
  final amountController = TextEditingController();

  void addTransactions() {
// Add new transaction
    Transaction tx = Transaction(
        title: titleController.text,
        amount: double.parse(amountController.text),
        date: DateTime.now(),
        id: DateTime.now().toString());

    setState(() {
// Add new transaction to existing List. I want this new element on top of screen
      transactions.add(tx);
    });
  }


最佳答案

使用List的insert()方法添加项目,此处的索引将为0,以将其开头添加。示例:

List<String> transactions = ["Items1", "Items2", "Items3"];


transactions.insert(0, "New Value");

关于flutter - 为什么列表在添加新元素时表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63504177/

相关文章:

html - 如何修复 HTML-<ul> 列表在 flutter 中显示长列表项?

dart - 在 Flutter 中,导航到新的 Widget,同时保持 AppBar 和 Bottom TabBar

Flutter:最小高度,扩展和 SingleChildScrollView?

Flutter Null安全迁移-StreamBuilder快照-无法通过索引访问长度或数据

flutter - 如何在 flutter 中为文本添加阴影?

flutter - Dart//Flutter:如何根据输入内容从列表中删除项目

flutter getx, getview 有两个 Controller

ios - fcm onMessage 在模拟器上工作,但在物理设备上不起作用

dart - 为什么我的更新的可观察列表未反射(reflect)在模板中?

Flutter: NoSuchMethodError : 方法 'fetchByID' 在 null 上被调用。接收方:null 尝试调用:fetchByID(2)