LazyTaz / multi_state_bloc

multi_state_bloc allows you to easily use different states in one bloc.
BSD 3-Clause "New" or "Revised" License
1 stars 1 forks source link

[Question] How to access state outside widget's "build" or without using BlocBuilder, etc. #1

Open adummy832 opened 1 year ago

adummy832 commented 1 year ago

Really loving your work here. Greatly appreciated! @LazyTaz

Is it possible to access bloc's state with these kind of scenario whilst also listening to state changes?

class MyWidget extends StatefulWidget {
  const MyWidget({super.key});

  @override
  State<MyWidget> createState() => _MyWidgetState();
}

class _MyWidgetState extends State<MyWidget> {
  final myVar = {
    "myKey": (BuildContext context) {
      var myBloc = BlocProvider.of<MyBloc>(context);
      var myStateLoaded = myBloc.states<MyStateLoaded>();

      // Listen for state change. Watch or something?
      print('state: ${myStateLoaded.myValue}');
    }
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('MyWidget'),
      ),
      body: const Center(
        child: Text('MyWidget'),
      ),
    );
  }
}
LazyTaz commented 9 months ago

Hey @adummy832, So sorry for the late answer.

As I understand your question, you want to listen for bloc state changes inside a place that is not a build method. The best way of doing it is to listen to the bloc stream itself (a bloc is a decorated stream).

But you will need to close the stream subscription by yourself which can lead to memory leaks.

If you really want to watch() outside build methods Riverpod may be more suitable for your need (https://github.com/rrousselGit/riverpod).

Regards,