Home > database >  How to initialize a static variable and set various value for it?
How to initialize a static variable and set various value for it?

Time:10-20

In java, if you want to initialize a static variable once, you can write code in Static Initialization Block just like this:

abstract class Dummy {
    static final Map<String, object> cache = new HashMap();

    static {
        cache.add('foo', new Foo());
        cache.add('bar', new Bar());
    }
}

Here I want to ask if there have a similar way in Dart? What is the best coding practice in Dart programming?

abstract class Dummy {
  static final Map<String, dynamic> cache = <String, dynamic>{};
}

CodePudding user response:

Well, there is no static initialization block in dart, but there are some other approaches you could take here.

Firstly, if all you want to do is add a few items to a map, you can just use map literal syntax:

abstract class Dummy {
  static final Map<String, dynamic> cache = <String, dynamic>{
    'foo': Foo(),
    'bar': Bar(),
  };
}

Also if you just want to initialize a static value by calling a few methods on it, you can use cascade notation .., which for this specific example would look like this:

abstract class Dummy {
  static final Map<String, dynamic> cache = <String, dynamic>{}
    ..['foo'] = Foo()
    ..['bar'] = Bar();
}

The above is using cascade to call the []= operator on the map instance, but you can call any method on the map instance using cascade. For example, I could also call the remove method:

abstract class Dummy {
  static final Map<String, dynamic> cache = <String, dynamic>{}
    ..['foo'] = Foo()
    ..['bar'] = Bar()
    ..remove('foo');
}
  •  Tags:  
  • dart
  • Related