Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid [] called on null in Flutter

Tags:

flutter

dart

Is there is a method in dart to judge whether an object is null or not, and then decide to get ['data'] or do nothing?

This is the error message:

The following NoSuchMethodError was thrown building Builder: The method '[]' was called on null. Receiver: null Tried calling:

like image 903
Zhongrui Avatar asked Apr 12 '19 03:04

Zhongrui


People also ask

How can you avoid NULL check operator used on a NULL value flutter?

Solution 3: Using Fallback Operator: Here, "str" is null, and we set the fallback operator with fallback value in case of "str" is null. You need to do this before using it on the code. You can use this method to handle Null values to escape the "Null check operator used on a null value" error in Flutter or Dart.

WHAT IS NULL operator in flutter?

Null-aware operators in dart allow you to make computations based on whether or not a value is null. It's shorthand for longer expressions. A null-aware operator is a nice tool for making nullable types usable in Dart instead of throwing an error.


1 Answers

The simplest way to answer your question:

final data = list != null ? list[0] : null;

There is a shorthand method to do the same with properties and methods of any object : a?.b or a?.b() would first null check a and then get b or call b respectively, if a is null return null.

Such shorthand is not available for subscript only for properties and methods.

like image 112
Harsh Bhikadia Avatar answered Sep 28 '22 05:09

Harsh Bhikadia