Home > Blockchain >  Correct way to handle variable initialisation in flutter? Late or make it nullable?
Correct way to handle variable initialisation in flutter? Late or make it nullable?

Time:10-25

Hello good folk of stack overflow, teaching myself flutter and have come across null safety.

I believe I 'understand' the difference between making a variable nullable and telling dart I will initialise later. But is there a correct way to do it?

In what instance would you choose late over making a variable nullable?

Consider the small class I have below, I've chosen to use the late method (admittedly I don't really know why) Would you chose this same method or should I be making the variables nullable?

Thanks!

class Quote{

  late String text;
  late String author;


  Quote(String text, String author){
    this.text = text;
    this.author=author;

  }
}

CodePudding user response:

There is also a third solution and forth (done in two ways) solution here.

You can add a non-null default value to the field.

String text = '';

But I would go here with initializing the fields directly in the constructor argument list.

class Quote {
  String text;
  String author;

  Quote(this.text, this.author);
}

...or using a constructor initializer list:

class Quote {
  String text;
  String author;

  Quote(String text, String author)
    : text = text,
      author = author;
}

Using the forth solution (second and third code snippet) you can also make those fields final and the constructor constant.

Lastly, quoting the documentation Classes - Language Tour | Dart:

Instance variables can be final, in which case they must be set exactly once. Initialize final, non-late instance variables at declaration, using a constructor parameter, or using a constructor’s initializer list (...)

If you need to assign the value of a final instance variable after the constructor body starts, you can use one of the following:

  • Use a factory constructor.
  • Use late final, but be careful: a late final without an initializer adds a setter to the API.

CodePudding user response:

You mentioned the answer in the question too. If your business logic requires to check if a value is null use nullable variable and if you want some definite value then use late. For example you may not know if you will get a response from an api as expected. So better to define as nullable.

  • Related