Kostnesm
Kostnesm

Reputation: 1

Changing state of a List of objects in Flutter Cubit

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
  ),
);

Upvotes: 0

Views: 2336

Answers (2)

Loren.A
Loren.A

Reputation: 5595

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

  void deletePosts() {
    return emit([]); // this will update the state to an empty list
  }

If you need to modify the list without wiping it, it could look like this

  void modifyPosts() {

   // this is a copy of the list, a new instance in memory, using the spread operator

   final updatedPostsList = [...state]; 

   updatedPostsList[0] = Post(
        /// some modification
        );
    return emit(updatedPostsList); // this will emit the modified list
  }

Upvotes: 0

Kherel
Kherel

Reputation: 16215

If you deleting all posts you can emit new empty array;

    void deletePosts() {
        return emit(const []);
    }

Upvotes: 0

Related Questions