CookieMonster
CookieMonster

Reputation: 846

How to use the same BLoC for different widgets in Flutter?

I have 2 custom widgets, and I want to use the same Bloc file. My Bloc file gets data from the internet in the constructor.

class MyBloc {
// StreamControllers, StreamSinks, Streams ...

  MyBloc() {
    getDataFromInternet();
  }
}
class MyWidget1 extends StatefulWidget {
  MyWidget1({Key key}) : super(key: key);

  @override
  _MyWidget1State createState() => _MyWidget1State();
}

class _MyWidget1State extends State<MyWidget1> {
  MyBloc _bloc;

  @override
  void initState() {
    _bloc = MyBloc();
    super.initState();
  }
}
class MyWidget2 extends StatefulWidget {
  MyWidget2({Key key}) : super(key: key);

  @override
  _MyWidget2State createState() => _MyWidget2State();
}

class _MyWidget2State extends State<MyWidget2> {
  MyBloc _bloc;

  @override
  void initState() {
    _bloc = MyBloc();
    super.initState();
  }
}

My problem is, that it downloads the data every time the screen changes (any of the two widgets appear on the screen). Should I pass the initialized bloc object to the widgets in the constructors, and not create a new Bloc in the widgets constructor? I don't want to save the data and write logic to check if I already downloaded it or not.

Upvotes: 1

Views: 1753

Answers (1)

Dmitry_Kovalov
Dmitry_Kovalov

Reputation: 2172

Use this bloc implementation https://bloclibrary.dev/ Your bloc will have single instance with it's single state at the moment. Invoke new state depending on previous and you will never has problems with unneeded queries or something like this.

Upvotes: -1

Related Questions