I have an object model in my app which needs to be accessed on different pages. I get the object model via a REST interface and store it in a variable (here simplified SomeObjectModel
). Since the object model can change through various events, I decided to use a ChangeNotifier
to update the UI.
My problem: The return value from the REST call is an object of type Future<SomeObjectModel>
which I assign to my private variable in the asynchronous method _getCurrentState
. If I want to read a value from the object model (e.g. actualTemperature
) I always have to check if the object model is not null. Is there a better way to implement this?
Here my simplified Code:
ChangeNotifier Class
class CarouselItemModel extends ChangeNotifier {
SomeObjectModel? _someObjectModel;
CarouselItemModel() {
_getCurrentState();
}
_getCurrentState() async {
_someObjectModel = await Rest().getCurrentState();
notifyListeners();
}
double getActualTemperature() {
if (_someObjectModel != null) {
return _someObjectModel!.actualTemperature;
} else {
return 0.0; // Default value if no connection to the server is possible.
}
}
}
Consumer in Widget
Consumer<CarouselItemModel>(
builder: (context, carouselItemModel, child) {
return Text(
"Temperature: ${carouselItemModel.getActualTemperature()} °C");
},
),