0

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");
  },
),
Takrem
  • 41
  • 6
  • It's logical that you need to check for `null` because you declared it as `nullable`. One option is to declare it as `non-nullable` but then you need to assign it some initial value (e.g. `SomeObjectModel _someObjectModel = SomeObjectModel();`) – Ante Bule Dec 14 '22 at 10:57
  • use a ternary operator null check or declare a default value in your model class constructor – Ilyas Arafath Dec 14 '22 at 11:37
  • Make Text Widget in FutureBuilder & make double getActualTemperature as Future getActualTemperature for display , so you don't need to check null & defined SomeObjectModel? as late SomeObjectModel _someObjectModel; & your function is like Future getActualTemperature() async { return await _someObjectModel!.actualTemperature; } – Dharini Dec 14 '22 at 12:06
  • Okay then I'll keep checking null and try to get it a bit shorter. An initial value for the object model would also be an idea, but for that I would have to pass a lot of parameters. – Takrem Dec 14 '22 at 13:39

0 Answers0