Search code examples
flutterdartblocflutter-bloc

How to access **state** outside of BlocBuilder?


I'm doing a meal-recipe App in which I am wrapping in a BlocBuilder as below:

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: const Text("The Recipe Bloc"),
        backgroundColor: Colors.orange[800],
      ),
      body: Center(child: BlocBuilder<RecipeCubit, RecipeState>(
        builder: (context, state) {
          if (state is RecipeInitial) {
            return const CircularProgressIndicator(color: Colors.orange);
          }
          if (state is RecipeLoaded) {
            return state.recipeList.isEmpty
                ? const Center(child: Text("No Recipes Registered Yet!"))
                : ListView.builder(
                    itemCount: state.recipeList.length,
                    itemBuilder: (context, index) {
                      return RecipeListTile(parentContext: context, recipeItem: state.recipeList[index]).display;
                    });
          } else {
            // In Case The App Reads from Outside of Standard States
            return const Text("Something Went Wrong!");
          }
        },
      )),

      //Add New Recipes
      floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.orange[800],
          onPressed: () {
            List<Recipe> outofContext_recipeList =context.select((value) => null)
            showDialog(context: context, builder: (BuildContext context) => CreateRecipeDialog(lastID: state.recipeList.isNotEmpty ? state.recipeList.last.id : "-1"));
          },
          child: const Icon(Icons.add_rounded)),
    );
  }
}

regardless of options I put in the screen, I want to have a FloatingActionButton() for adding new recipes.

So here comes my question, How can I access my CubitState/state outside of BlocBuilder?


Solution

  • Hey to get the state of your Recipe Cubit you can use

    context.read<RecipeCubit>().state 
    

    or

    BlocProvider.of<RecipeCubit>(context).state
    

    anyone can be used as per your preference to get the state of your Recipe Cubit outside the BlocBuilder.