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



我正在制作一个类似于to-do's app的应用程序,我可以从textfield添加一个项目到listview.builder。每当我添加一个新项目时,它就会出现在listview.builder的待办事项列表下面。现在的问题是我让reverse: truelistview.builder里面,如果我这次添加一个项目,它会在顶部而不是底部。我怎么能在底部显示新项目,即使它是reverse: truelistview.builder

如果这是你想要的

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);
}

假设您的状态中存储了一个布尔值(用于反向),那么在添加项时,您可以根据该值将其添加到前面或后面

// 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]

最新更新