'Add an item at bottom in listview in Flutter
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.
Solution 1:[1]
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]
Solution 2:[2]
With some more research after posting the question I was able to find a workable solution to the issue. I was wrong assuming that localStorage would work for mobile platform as well. I should have used AsyncStorage to set and get JWT token. This is how I solved the problem:
- I installed AsyncStorage in my expo project using import AsyncStorage from '@react-native-async-storage/async-storage'.
- I used AsyncStorage.setItem('loginToken', response.data.token) instead of localStorage.setItem('loginToken', response.data.token).
- I used const loginToken = await AsyncStorage.getItem('loginToken') instead of const loginToken = await localStorage.getItem('loginToken'). That did the rest. Now I am being able to login from web as well as android simulator and my android phone and being successfully able to fetch the user credentials in authenticated page(s).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | MIK |
