问题
I have many confusion about Brackets in Dart(Flutter). Which bracket "(), {}, []" is used for what?
回答1:
()
can group expressions:var x = (1 + 2) * 3;
or can designate parameter lists for functions:
var getAnswer = () => 42; int square(int x) => x * x;
or can designate function calls:
var answer = getAnswer(); var squared = square(4);
or is part of the syntax to some keywords. This includes (but is not limited to)
if
,assert
,for
,while
,switch
,catch
:if (condition) { ... } assert(condition); for (var item in collection) { ... } while (condition) { ... } switch (value) { ... } try { ... } on Exception catch (e) { ... }
[]
by itself creates List literals:var list = [1, 2, 3]; var emptyList = []; // Creates a List<dynamic>.
or when used on an object, calls operator [], which usually accesses an element of a collection:
var element = list[index]; var value = map[key];
or in a parameter list, specifies optional positional parameters:
int function(int x, [int y, int z]) { return x + y ?? 0 + z ?? 0; } function(1, 2);
or in dartdoc comments, creates linked references to other symbols:
/// Creates a [Bar] from a [Foo]. Bar fooToBar(Foo foo) { // ... }
{}
can create a block of code, grouping lines together and limiting variable scope. This includes (but is not limited to) function bodies, class declarations,if
-else
blocks,try
-catch
blocks,for
blocks,while
blocks,switch
blocks, etc.:class Class { int member; } void doNothing() {} void function(bool condition) { { int x = 'Hello world!'; print(x); } if (condition) { int x = 42; // No name collision due to separate scopes. print(x); } }
or by itself can create Set or Map literals:
var set = {1, 2, 3}; var emptySet = <int>{}; var map = {'one': 1, 'two': 2, 'three': 3}; var emptyMap = {}; // Creates a Map<dynamic, dynamic>
or in a parameter list, specifies optional named parameters:
int function(int x, {int y, int z}) { return x + y ?? 0 + z ?? 0; } function(1, y: 2);
or creates enumerations:
enum SomeEnumeration { foo, bar, baz, }
or in
String
s is used to disambiguate interpolated expressions:var foo = 'foo'; var foobar = '${foo}bar'; var s = '${function(1, 2)}';
<>
when used as a pair in function or class declarations creates generics:class GenericClass<T> { T member; } T function<T>(T x) { // ... }
or specifies explicit types when using generics:
var map = <String, int>{};
来源:https://stackoverflow.com/questions/61947930/understanding-brackets-in-dart-flutter