简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM