简体   繁体   中英

What are the brackets in constructor in dart

@immutable
abstract class MyGithubReposState extends Equatable {
  MyGithubReposState([List props = const []]) : super(props);
}

I have seen above code in one of the libraries I use. What does the [List props = const []] mean? List of list of props?

This is optional parameter as explained below.

  • A function can have two types of parameters: required and optional .

The required parameters are listed first, followed by any optional parameters. Optional parameters can be named or positional.

  • Optional parameters can be either named or positional, but not both.

Named parameters

When calling a function, you can specify named parameters using paramName: value. For example:

this is calling of function

enableFlags(bold: true, hidden: false);

When defining a function, use {param1, param2, …} to specify named parameters:

this is how we define them

/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}

Positional parameters

Wrapping a set of function parameters in [] marks them as optional positional parameters:

String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

so that we can call this function by two way

Without optional positional parameter

say('Bob', 'Howdy')

With optional positional parameter

say('Bob', 'Howdy', 'smoke signal')

Reference here

[within this is optional]表示这些参数是可选的

From the official docs ,

Wrapping a set of function parameters in [] marks them as optional positional parameters

String say(String from, String msg, [String device]) {
  var result = '$from says $msg';
  if (device != null) {
    result = '$result with a $device';
  }
  return result;
}

Here's an example of calling this function without the optional parameter:

assert(say('Bob', 'Howdy') == 'Bob says Howdy');

And here's an example of calling this function with the third parameter:

assert(say('Bob', 'Howdy', 'smoke signal') ==
    'Bob says Howdy with a smoke signal');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM