在 Flutter 的列表视图底部添加一个项目

Add an item at bottom in listview in Flutter

我正在制作一个类似于 to-do's app 的应用程序,我可以添加从 textfieldlistview.builder 的项目。每当我添加一个新项目时,它都会出现在 listview.builder 待办事项列表的下方。现在的问题是我在 listview.builder 中创建了 reverse: true,如果我这次添加一个项目,它会出现在顶部而不是底部。即使 reverse: truelistview.builder.

中,我如何在底部显示新项目

假设您在状态中存储了一个布尔值(反向),然后您可以在添加项目时根据此值将其添加到前面或后面

// State variables
bool isReverse;
List<Todo> todos;

void addListItem(Todo item) {
  if (isReverse) {
    // add to the front of the original array
    todos.insert(0, item);
  } else {
    // add to the back (default case)
    todos.add(item);
  }
}

虽然我直觉上说当列表颠倒时,您希望新项目最终出现在顶部。

订单示例

为了说明索引 0 处的插入和反向插入,我将以下代码 运行 放在 https://dartpad.dev/

void main() {
  List<String> todos = [];
  
  todos.addAll(['Clean Bedroom', 'Do dishes', 'Cook food']);
  
  print('Normal order: $todos');
  print('Reversed order: ${todos.reversed.toList()}');
  
  // Add item at index 0 (start of the normal list, end of the reversed list)
  todos.insert(0, 'Buy Groceries');
  
  print('Normal order with groceries: $todos');
  print('Reversed order with groceries: ${todos.reversed.toList()}');
}

其输出为

Normal order: [Clean Bedroom, Do dishes, Cook food]
Reversed order: [Cook food, Do dishes, Clean Bedroom]
Normal order with groceries: [Buy Groceries, Clean Bedroom, Do dishes, Cook food]
Reversed order with groceries: [Cook food, Do dishes, Clean Bedroom, Buy Groceries]

这行得通,如果这是你想要的

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  List<TodoItem> items = [
    TodoItem('first name', ' first body'),
    TodoItem('second name', ' second body'),
    TodoItem('third name', ' third body'),
    TodoItem('fourh name', ' fourh body'),
  ];

  int newCount = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
          floatingActionButton: FloatingActionButton(onPressed: () {
            //items.add(TodoItem('${newCount.toString()} new ', ' added ${newCount.toString()} '));
            items.insert(0, TodoItem('${newCount.toString()} new ', ' added ${newCount.toString()} '));
            newCount++;
            setState(() {});
          }),
          appBar: AppBar(
            title: const Text('Material App Bar'),
          ),
          body: ListView.builder(
              itemCount: items.length,
              reverse: true,
              itemBuilder: ((context, index) {
                return ListTile(
                  title: Text(items[index].name),
                  subtitle: Text(items[index].body),
                );
              }))),
    );
  }
}

class TodoItem {
  final String name;
  final String body;

  TodoItem(this.name, this.body);
}