top of page

[Flutter/dart] Private and final class variable


Overview


Suppose adding a class variable in dart like below.

  • Private (don't want to be accessed from outside)

  • Determine the value by referring to the arguments of the constructor

  • Once the value is set above, it will not change after that

In such a case, this variable should be final.

I will introduce this method.



Method


The first thing that comes to mind is, why not just set the value inside the constructor.

A final variable cannot be set inside the constructor.

class AClass{
  
  final String _title;
  ・・・
  
  Genre({required String name}){
    _title = setTitle(name);   //compile error
  }
}

Set value in an initializer.

class AClass{
  
  final String _title;
  ・・・
  
  Genre({required String name}):
    _title = setTitle(name);   
}


Lastly


It's easy once you know how, but it took me a while to figure it out, because

I haven't used final much so far...

Recent Posts

See All

Comments


category

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