Joey Yi Zhao
Joey Yi Zhao

Reputation: 42454

what is the better way to give a string default value if it is null in flutter?

I have a code like below. It initiates an instance of Model. There are some values like json['status'] can be null. What is the best way to give them a default value ''? I am from javascript world, so I am looking for a way like json['status'] || ''.

factory Model.fromJson(Map<String, dynamic> json) {
    return Model(
        id: json['id'],
        status: json['status'],
        amount: json['amount'],
        scheme: json['scheme'],
        type: json['type']);
  }

Upvotes: 0

Views: 36

Answers (1)

Stefano Amorelli
Stefano Amorelli

Reputation: 4854

We can use the null-coalescing (??) operator as follows:

factory Model.fromJson(Map<String, dynamic> json) {
    return Model(
        id: json['id'] ?? 0,
        status: json['status'] ?? 'status',
        amount: json['amount'] ?? 0,
        scheme: json['scheme'] ?? 'scheme',
        type: json['type'] ?? 'defaultType');
  }

You can also read more about null-aware operators in the official Dart cheatsheet.

Upvotes: 2

Related Questions