Elementary-team / flutter-elementary

This is a home to a family of Elementary library packages.
MIT License
133 stars 45 forks source link

when initWidgetModel() initializing? #89

Closed pishguy closed 7 months ago

pishguy commented 1 year ago

in this code i pasted my simplified MVVM which in that i defined width, but in widget i get

LateInitializationError: Field '_width@234398598' has not been initialized.

error and i'm not sure how can i resolve that

class ManageAddressesWidgetModel extends ...{

  late double _width;

  @override
  double get width => _width;

  @override
  void initWidgetModel() {
    super.initWidgetModel();
    Future.microtask(() => _width = context.size!.width);
  }
}

abstract interface class IManageAddressesWidgetModel implements IWidgetModel {
  double get width;
}
MbIXjkee commented 1 year ago

Hi, you use there a microtask, which is run asynchronously later. So when you use this property in a widget, it is not initialized yet. You can do the same without microtask, initWidgetModel is called when the element related to this WidgetModel is already in the element tree. And generally, not relative to Elementary, it is not good for an application performance to use microtask for something like this.