Search code examples
flutterdartblocstream-builder

How to get data from bloc stream from other page in flutter


I have a problem like this : In Splash Page , i check in sharedpreference to get saved token when login successfully .If i have token , i request Api to get account information and move to next page like this:

 Future check() async {
    String _getToken = await splashBloc.getTokenFormSharedPref();
    if (_getToken=='0') {
      Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => LoginMain()));
    } else {
      splashBloc.getAccountInfo();
      Navigator.of(context).pushReplacement(
          MaterialPageRoute(builder: (context) => HomeScreenMain()));
    }
  }

and this is BLoC class:

class SplashBloc extends BlocBase{

  String _getToken = '';
  Future<String> getTokenFormSharedPref() async{
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _getToken = (prefs.getString('token') ?? '0');
    return _getToken;
  }

  final accountInfoController = new StreamController<Account>();
  Sink<Account> get accountInfoSink => accountInfoController.sink;
  Stream<Account> get accountInfoStream => accountInfoController.stream;

  Future getAccountInfo() async{
    Account account = await NetworkService().getAccountInfo2(_getToken);
    accountInfoSink.add(account);
    print('from splash: '+account.fullName);
  }
  @override
  void dispose() {
    accountInfoController.close();
  }

}

When i check log , it totally request successfully and the problem is how can i acesss data in streambuilder in next page that is HomeScreenMain()? Thanks for help!!


Solution

  • You can declare a variable in HomeScreenMain() and send the data you received before to the class constructor like this:

    HomeScreenMain() {
    final data;
    HomeScreenMain(this.data)
    
    //....
    }
    

    and when you want to call this widget you can pass that data from block to this widget