I'm making an app similar to to-do's app
and i can able to add an item from textfield
to listview.builder
. In this whenever i add a new item it comes below of the todo's list in listview.builder
. Now the problem is i make reverse: true
inside listview.builder
and if i add an item this time it is coming at the top instead at bottom. How can i display the new item at bottom even if it is reverse: true
inside listview.builder
.
CodePudding user response:
this works, if this is what you wants
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);
}
CodePudding user response:
Say you have a boolean (for reverse) stored in your state, you could then, when adding the item, add it either to the front or the back depending on this value
// 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);
}
}
Though I'd intuitively say that when the list is reversed, you expect new items to end up at the top.
Order example
To illustrate this insertion at index 0 and reverse, I've put the following code and ran it on 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()}');
}
The output of which is
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]