'Flutter conditional statement for getter

I've this in my application:

LocalTextItem? get text =>
      FocusedItemModel.of(context).focused as LocalTextItem;

The idea was if user taps a text item and then goes to text editor page, the text can be customized.

But right now I need to implement adding new text. So the user might not tap any existing text and navigate straight to text editor page and customize a new text.

For this I need some conditional statements like:

if(text = null){
    initEmptyText();
}

Or in the text canvas for building styles and others:

fontFamily: text != null ? text.fontFamily : GoogleFonts.lato().fontFamily,

But I am getting an: Unexpected Null value error.

So in short if the user has not selected any text I need to initialize an empty textCanvas and if the user did select a text I will simply put all the properties on the textCanvas. FocusedItemModel is as below:

class FocusedItemModel extends ChangeNotifier {
  static FocusedItemModel of(BuildContext context) =>
      Provider.of<FocusedItemModel>(
        context,
        listen: false,
      );

  LocalMovableItem? _focused;
  LocalMovableItem get focused => _focused!;
  bool get hasFocus => _focused != false;

  /*
    Set an item to focus
  */
  void focus(LocalMovableItem? item) {
    if (_focused != null) {
      unfocus();
    }
    if ((_focused != item && item!.focusable)) {
      _focused = item;
      notifyListeners();
    }
  }

  bool hasFocusOn(LocalMovableItem? item) => _focused == item;

  void unfocus() {
    if (_focused != null) {
      _focused = null;
      notifyListeners();
    }
  }

  /*
    Notify all listeners
  */
  void redraw() {
    notifyListeners();
  }

  void notifyChange() {
    notifyListeners();
  }
}

I've also defined the providers in Multiproviders



Solution 1:[1]

I may need more code to understand what's happening here, but first problem is here :

LocalMovableItem get focused => _focused!;

You're basically asserting that _focused can't be null with the ! operator, which is wrong since this variable is set to null in your unfocus method.

You should update your Getter with the following

LocalMovableItem? get focused => _focused;

After doing so, you should update your cast to

LocalTextItem? get text =>
      FocusedItemModel.of(context).focused as LocalTextItem?;

Btw, note that this cast won't work if your models LocalTextItem and LocalMovableItem aren't related.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FDuhen