1

I know how to initialize other variables such as int or String in constructor but I have no clue how to do it for List and Map.

class StackOverFlowQuestion{
StackOverFlowQuestion({this.test='', this.map=?, this.list=?});
String test;
Map map;
List list;
}

What shall I replace the question marks with?

Thanks.

1 Answer 1

5

The answer depends on whether your default list and map are constant. Let's assume your list is, but map is not.

You'd write:

class StackOverFlowQuestion {
  StackOverFlowQuestion({
    this.test = '',
    Map map,
    this.list = const [1, 2, 3],
  }) {
    this.map = map ?? {};
  }

  String test;
  Map map;
  List list;
}

If the list optional parameter is omitted, then it will be initialized to [1, 2, 3]. If the map is omitted or null, it will be initialized with a mutable empty map.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.