skip to Main Content

I am a new developer in FLUTTER.
I have a class in which I want to receive in CTR an instance of BLOC.

In addition, in the class itself I want to use STATES from the BLOC and listen to changes in STATE.
How can I do that??

2

Answers


  1. Chosen as BEST ANSWER

    I sent the instance of the bloc to the class in this way:

    Aclass(context.read<MyBloc>());
    

    And I used the instance of the bloc in the Aclass:

    class Aclass{
    final MyBloc myBloc;
    Aclass(this.myBloc)
    {
     myBloc.stream.listen((state) {
      if(state is ...)
      {}
    }
    }
    

  2. Block (BLoC, from Business Logic Component) is an architecture pattern widely used in the development of Flutter applications for state management. It helps separate business logic from the user interface, making the code more modular, testable, and scalable.

    Let’s look at an example of how we can use this state manager to pull in data and display it on the screen

    After connecting the Block to the project using the library, create a class and extends it from the block

    class DogListBloc extends Bloc<LoadingDogsEvent, DogListState> {
      Repository repo;
      DogListBloc(this.repo) : super(InitialState()) {
        on<LoadingDogsEvent>((event, emit) async {
          emit(LoadingDogs());
          try {
            // A repository, the place from which data is returned
            // let's imagine that a network request to receive data is implemented inside it
            final breeds = await repo.fetchDogs();
            emit(LoadedDogs(breeds));
          } catch (e) {
            emit(ErrorDogs(e));
          }
        });
      }
    }
    

    We send an event to perform some action in the block, in our case receiving data in initState method

    class DogListLayout extends StatefulWidget {
      const DogListLayout({Key? key}) : super(key: key);
    
      @override
      State<DogListLayout> createState() => _DogListLayoutState();
    }
    
    class _DogListLayoutState extends State<DogListLayout> {
      @override
      void initState() {
        super.initState();
        // We send an event to perform some action in the block, in our case receiving data
        context.read<DogListBloc>().add(LoadingDogsEvent());
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            backgroundColor: Colors.black87,
            title: const Text('DogsListScreen'),
          ),
          body: Center(
            child: BlocBuilder<DogListBloc, DogListState>(
              builder: (context, state) {
                if (state is InitialState) {
                  return const Center(child: Text('expectation'));
                } else if (state is ErrorDogs) {
                  return const DogListErrorWidget();
                } else if (state is LoadingDogs) {
                  return const CircularProgressIndicator();
                } else if (state is LoadedDogs) {
                  return ListView.separated(
                    itemCount: state.breedList.length,
                    itemBuilder: (_, index) => BreedWidget(state.breedList[index]),
                    separatorBuilder: (_, __) => const Divider(thickness: 4),
                  );
                } else {
                  throw Exception('unprocessed state $state in DogListLayout');
                }
              },
            ),
          ),
        );
      }
    }
    
    
    class DogsListScreen extends StatelessWidget {
      const DogsListScreen({Key? key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return BlocProvider<DogListBloc>(
          // we forward the necessary data to the block
          create: (_) => DogListBloc(getIt<Repository>()),
          child: const DogListLayout(),
        );
      }
    }
    

    His way we get a modular architecture and a built user interface that knows nothing about the data, because only the block has access to it, this way we can use the block correctly in our class, you can read more in the documentation – https://pub.dev/packages/flutter_bloc

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search