Home > Software engineering >  Sending data to other page with bloc cubit
Sending data to other page with bloc cubit

Time:07-04

My problem is this. I created cubit for 2 different pages. When I am on the first page, I can fill the list inside the 2nd page and I can read it from the log. However, when I go to the second page, the list I filled in from the previous page is still empty.

Main.dart

home:
          
          
           MultiBlocProvider(
            providers: [
              BlocProvider(create: (_) => HomeCubit(PhotoService())),
              
              BlocProvider(create: (_)=> FavoritesCubit())//Gerekiyor,homeviewda içerisindeki methoda erişmem gerekiyor
            ],
            child: const HomeView())

HomeView.dart

where I run the function in favoritescubit and add it to the list
 onTap: () {
                        

                        BlocProvider.of<FavoritesCubit>(context).addFavorite(
                            context,
                            state.selectItem![index],
                            );
                        print(state.selectItem?[index].isSelected);
                        context.read<FavoritesCubit>().getAllFavorites();

                        // print("UI --- ${state.selectItem![index].isSelected}");
                        //  context.read<FavoriteBloc>().add(
                        //      AddFavorite(photoList, photoList.isSelected));
                        //  print(" ispressed ${photoList.isSelected}");
                      },

FavoritesCubit.dart

class FavoritesCubit extends Cubit<FavoritesState> {
  FavoritesCubit() : super(const FavoritesState());

  final List<PhotoModel> favoriteList = <PhotoModel>[];

  Future<void> getAllFavorites() async {
    print("FavoriteList : ${favoriteList.length}");
    emit(state.copyWith(favoriteList: favoriteList));
  }



 

     Future<void> addFavorite(
        BuildContext context,
        PhotoModel photo,
      ) async {
        photo.isSelected = !photo.isSelected;
        if (favoriteList.contains(photo) == false) {
          favoriteList.add(photo);
          emit(state.copyWith(
              favoriteList: favoriteList, isFavorite: photo.isSelected));
          print("${state.favoriteList!.length}asdasd");
        } else if (favoriteList.contains(photo) == true) {
          favoriteList.remove(photo);
          emit(state.copyWith(
              favoriteList: favoriteList, isFavorite: photo.isSelected));
          print("${state.favoriteList!.length}asdasd");
        }

FavoriteView.dart

class FavoriteView extends StatefulWidget {
  const FavoriteView({Key? key}) : super(key: key);

  @override
  State<FavoriteView> createState() => _FavoriteViewState();
}

class _FavoriteViewState extends State<FavoriteView> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => FavoritesCubit()..getAllFavorites(),
      child: Scaffold(
        appBar: AppBar(
          title: const Text("Bloc Example"),
        ),
        body: buildFavoriteList(context),
      ),
    );
  }
}




Widget buildFavoriteList(BuildContext context) {
 
  return BlocConsumer<FavoritesCubit, FavoritesState>(
    listener: (context, state) {
      // TODO: implement listener
    },
    builder: (context, state) {
      return ListView.builder(
          itemCount: state.favoriteList?.length,
          itemBuilder: (context, index) {
            return GestureDetector(
              onTap: (() {
                // navigateToPostDetailPage(context, photos[index]);
              }),
              child: Padding(
                padding: const EdgeInsets.all(10),
                child: PhotoListTile(
                  isPressed: state.favoriteList![index].isSelected,
                  imageUrl: state.favoriteList![index].thumbnailUrl.toString(),
                  title: state.favoriteList![index].title.toString(),
                  url: state.favoriteList![index].url.toString(),
                  onTap: () {
                    // context.read<HomeCubit>().addFavorite(
                    //     context,
                    //     state.favoriteList![index],
                    //     state.favoriteList![index].isSelected);
                    // context
                    //     .read<FavoriteBloc>()
                    //     .add(RemoveFavorite(photos[index]));
                  },
                ),
              ),
            );
          });
    },
  );

CodePudding user response:

Okey, now with your added information about your FavoriteView it is clear what the problem is.

In your FavoriteView you create a new cubit, which is not the same as you created in the MultiBlocProvider. That is why it is always empty on your FavoriteView

create: (context) => FavoritesCubit()..getAllFavorites(), // This is the issue

Make sure that your FavoriteView is a child somewhere under your MultiBlocProvider and remove the creation of a new FavoritesCubit in that view. I.e. remove the BlocProvider in your FavoriteView

  • Related