I’m trying to delete a List of objects (Posts), which comes from Flutter Cubit method getPosts(), but I am absolutely not able to get these data in the second method of the cubit deletePosts(). From what I’ve searched on the internet, it seems there is a variable called "state", which should contain all the data of the Cubit, but if I print the "state" variable, it returns just an empty array.
I am missing some basic thing, but I am out of ideas what it is. Any advice will be highly appreciated.
The code:
class PostsCubit extends Cubit<List<Post>> {
final _dataService = DataService();
PostsCubit() : super([]);
// WORKS PERFECTLY - IT GETS ALL POSTS
Future<void> getPosts() async {
print('Getting posts');
return emit(await _dataService.getPosts());
}
// CANNOT FIGURE OUT, HOW TO DELETE DATA FROM getPosts() (STATE OF THE CUBIT)
void deletePosts() {
print(state); // Prints empty array "[]"
return emit(?????????);
// return emit(state.clear()); // DOES NOT WORK
}
}
The widget displaying posts:
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BlocProvider<PostsCubit>(
create: (BuildContext context) {
return PostsCubit()..getPosts();
},
child: PostsView(), // DISPLAYS ALL POSTS FROM getPosts() WITHOUT ANY PROBLEM
),
);
2
Answers
If you deleting all posts
you can emit new empty array;
Since Bloc depends on your state parameters being immutable, you need to create a copy of the list first, then it will treat it as an updated state.
If you’re trying to just wipe the entire list, you can just emit a new empty list
If you need to modify the list without wiping it, it could look like this