我正在制作一個類似于的應用程式,to-do's app并且我可以從 to 添加一個textfield專案listview.builder。在此,每當我添加一個新專案時,它都會出現在待辦事項串列的下方listview.builder。現在的問題是我在reverse: true里面做listview.builder,如果我這次添加一個專案,它會出現在頂部而不是底部。即使它在reverse: true里面,我如何才能在底部顯示新專案listview.builder。
uj5u.com熱心網友回復:
這行得通,如果這是你想要的
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);
}
uj5u.com熱心網友回復:
假設您的狀態中存盤了一個布林值(用于反向),那么您可以在添加專案時根據此值將其添加到前面或后面
// 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://www.uj5u.com/shujuku/477911.html
