I need to how to handle a stream builder with boolean data.
I need to know how to send bool data to my StreamBuilder in the HomePage,
I was using (!snapshot.hasData) but this method only see if theres data or not no matter if they are true or false.
and i need that know the difference betwen false and true,
to show me a widget only when geolocator returns true and another widget only when it returns false
HOMEPAGE
@override
Widget build(BuildContext context) {
final locationService = Provider.of<GeolocatorService>(context);
return Scaffold(
body: StreamBuilder(
stream: locationService.refreshLocation,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return _EnableGpsMessage();
}
return _AccessButton();
}));
}
}
PROVIDER
bool _gpsEnabled = false;
bool get gpsEnabled => _gpsEnabled;
set gpsEnabled(bool value) {
_gpsEnabled = value;
notifyListeners();
}
final StreamController _refreshLocation = new StreamController.broadcast();
Stream get refreshLocation => this._refreshLocation.stream;
_checkGpsStatus() async {
final isEnabled = await Geolocator.isLocationServiceEnabled();
print('FROM GEOLOCATOR SERVICE $isEnabled');
// this._refreshLocation.sink.add(isEnabled);
Geolocator.getServiceStatusStream().listen((event) {
final statusStream =
(event.index == 1) ? gpsEnabled = true : gpsEnabled = false;
print(statusStream);
this._refreshLocation.sink.add(statusStream);
});
// return (!isEnabled) ? gpsEnabled = false : gpsEnabled = true;
}
3
Answers
snapshot.data is the one which contains the value (which can be
bool
,Object
, or something else).hasData
is the method to know ifdata
is available or not.To show different widgets based on the boolean value received in a StreamBuilder, you can use this code also i have explain in comments for your help –
And in the provider, where you handle the GPS status changes, you can update the stream with the boolean value like this –
i hope it will work let me know if it works or not..
The value is in
snapshot.data
: