get all user name from all documents in Firestore flutter
long story short that I need to get a List< title > of all todos, but now I just have a List< Todo >, so how can I return this List?
get a Stream<List>
static Stream<List<Todo>> readTodos() => FirebaseFirestore.instance
.collection('todo')
.orderBy(TodoField.createdTime, descending: true)
.snapshots()
.transform(Utils.transformer(Todo.fromJson));
and then with StreamBuilder I am able to get a List, but for a method I just need all name of these todos, so I hope in the end it will look like this:
todoTitle: [
'eat',
'drink',
'run',
]
so what I can do? Thanks a lot!
Update I dont know if the following is a solution, but it does not work yet:
final provider = Provider.of<TodosProvider>(context);
final todos = provider.todos;
List<String> userTitle = todos.map['Todo'].where((todo) => todo['title'] != null).map((value) => value['title']).toList();
and then i got an error from map['Todo'], the error is (The operator '[]' isn't defined for the type 'Iterable<T> Function<T>(T Function(Todo))'.
), please help T T thanks!
There are two solution(thanks Frank's reply from another stack):
a. create another collection which just contains title, and then get List< Title > easily.
b. fetch all data as current solution, and I use forEach to seperate the value to a List(I still don't know how to do it in map(), plz help me if anyone has any idea):
-
create List< String > to get all titles
List< String > titles = [];
-
get List< Todos > as above displayed in the way of StreamBuilder, and then get all List with provider
final provider = Provider.of<TodosProvider>(context);
final todos = provider.todos;
- User forEach to put just
todo.title
inList< String > titles
getAllTitles(todos){
todos.forEach((todo) {
titles.add(todo.title);
});
}
I believe there is a smart way like h8moss showed me, to create another Stream<List> todoTitles, but then I need to listen another stream, I am new to firestore and flutter world, i dont know which one is better or how to do Stream<List> in the right way.. I just put my solution here in case I forget in the future.