skip to Main Content

In the fromJSON initialiser in Flutter class, sometimes a double value will not exist. What is the best way to check for null, if not null, use toDouble()

This does not work because the toDouble is called on null

myValue = json['myValue'].toDouble() ?? null;

I really want short hand for

if (json['myValue'] != null) {
    myValue = json['myValue'].toDouble();
}

Thanks

3

Answers


  1. You can use try parse like

    double? val = double.tryParse(json['myValue'].toString());
    
    Login or Signup to reply.
  2. This instruction will do the job.

    myValue = json['myValue']?.toDouble();
    
    Login or Signup to reply.
  3. These operators provide a concise and efficient way to handle null values when working with JSON data in Flutter.

    var name = jsonData[‘user’]?.[‘name’] ?? ‘Default Name’;

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search