I have an app with 2 pages, when tab on Home page button it navigates to Settings page.
IconButton(
onPressed:(){
Navigator.push(
context,
MaterialPageRoute( builder: (context) => Settings())
);
},
),
But on settings page, stream data from my bloc are all NULL. I have no idea why, on home page is all good.
I added new data into the Bloc in Settings page as a test, it shows up fine, so the Bloc implementation is working fine, just not getting the initiated data in the bloc constructor.
what did I do wrong?
Bloc data are initiated inside the bloc constructor, here is my Bloc code
class StateBloc implements BlocBase {
var selectedCurrencies;
StreamController<List> _selectedCurrencies = StreamController<List>.broadcast();
Stream<List> get getSelectedCurrencies => _selectedCurrencies.stream;
StreamSink get modifySelectedCurrencies => _selectedCurrencies.sink;
StateBloc() {
selectedCurrencies = ['cny','aud','usd'];
modifySelectedCurrencies.add(selectedCurrencies);
}
}
Here is how bloc is provided to main.dart
Future<void> main() async{
return runApp(
BlocProvider<StateBloc>(
child: MyApp(),
bloc: StateBloc(),
),
);
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Exchange',
debugShowCheckedModeBanner: false,
theme: ThemeData(fontFamily: 'Poppins'),
home: MyHomePage(),
);
}
}
Here is my Settings page
class Settings extends StatelessWidget {
@override
Widget build(BuildContext context) {
final StateBloc appBloc = BlocProvider.of<StateBloc>(context);
return MaterialApp(
home: Scaffold(
body: ListView(
children: <Widget>[
StreamBuilder(
stream: appBloc.getSelectedCurrencies,
builder: (context, selectedCurrenciesSnap) {
print('alllll --> ${allCurrenciesSnap.data}');
}
)
]
)
)
)
}
}
I found the issue. This is meant to happen, when the StreamBuilder in Settings page is built, it is only listening to upcoming data, not the previous data. In order get the previous data, we need refactor a few things.
In Bloc, uses a BehaviorSubject from rxdart package instead of a streamController, and define a ValueObservable instead of a Stream
StreamController _selectedCurrencies = BehaviorSubject();
ValueObservable get getSelectedCurrencies => _selectedCurrencies.stream;
StreamSink get modifySelectedCurrencies => _selectedCurrencies.sink;
Then in Settings page, supply the streamBuilder with initial data
initialData: appBloc.getSelectedCurrencies.value,
This works :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With