我正在制作一个类似于to-do's app的应用程序,我可以从textfield添加一个项目到listview.builder。在这种情况下,每当我在listview.builder中添加一个新项时,它都会出现在todo的列表下面。现在的问题是,我在reverse: true内部listview.builder,如果我添加一个项目,这一次,它是在顶部,而不是底部。如何在底部显示新项目,即使它是reverse: true在listview.builder中。
发布于 2022-05-19 14:14:07
如果这是你想要的
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);
}发布于 2022-05-19 13:17:09
假设您的状态中存储了一个布尔值(用于反向存储),那么在添加该项时,可以根据此值将其添加到前面或后面。
// 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]https://stackoverflow.com/questions/72305012
复制相似问题