[Flutter/dart] Default value of a class instance in null safety
top of page

[Flutter/dart] Default value of a class instance in null safety


Overview

When creating an instance of a certain class, there are cases where it is optional to set arguments to the instance, and if not set, we want to set a default value.

I had a little trouble with this pattern after introducing null safety, so I'll summarize it.



Promblem

For primitive types such as int, default values can be specified in constructor.

class SomeClass{
  int a;
  
  SomeCless({this.a = 0});
}

However, this is not possible for instances of other classes.

class SomeClass{
  OtherClass other;
  
  SomeCless({this.other = Other(b:1)});  //compile error
}

class OtherClass{

  final int b;
  
  OtherClass({this.b});
}

Without null safety, it was written in the following way, but it is no longer possible.

class SomeClass{
  OtherClass other;
  
  SomeCless({OtherClass o}):
    other = o?? OtherClass(b:1);
}


Solution

Make the argument a nullable type and check null and set default value in the initializer.

class SomeClass{
  OtherClass other;
  
  SomeCless({OtherClass? o}):
    other = o?? OtherClass(b:1);
}


Lastly

With null safety, the way of writing that had no problem until now becomes an error, so I'm confused in various situations...



Recent Posts

See All

[Flutter/Dart] Format string with TextField

What want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to display it in 3-digit delimiters with a ¥ prefix. Rather than ha

Let's do our best with our partner:​ ChatReminder

iphone6.5p2.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Let's do our best with our partner:​ ChatReminder

納品:iPhone6.5①.png

It is an application that achieves goals in a chat format with partners.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png

Theme diary: Decide the theme and record for each genre

It is a diary application that allows you to post and record with themes and sub-themes for each genre.

google-play-badge.png
Download_on_the_App_Store_Badge_JP_RGB_blk_100317.png
bottom of page