Reputation:
I have many confusion about Brackets in Dart(Flutter). Which bracket "(), {}, []" is used for what?
Upvotes: 5
Views: 6031
Reputation: 89965
()
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 (including calls to a .call
method on callable classes):
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) {
...
}
In Dart 3, specifies a record:
var emptyRecord = ();
var singleField = (123,);
var namedFields = (123, foo: 456);
[]
By itself, creates List
literals:
var list = [1, 2, 3];
var emptyList = []; // Creates a List<dynamic>.
When used on an object, calls operator []
or operator []=
, which usually accesses or sets an element of a collection respectively:
var element = list[index];
var value = map[key];
list[index] = element;
map[key] = value;
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);
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) {
{
String x = 'Hello world!';
print(x);
}
if (condition) {
int x = 42; // No name collision due to separate scopes.
print(x);
}
}
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>
In a parameter list, specifies named parameters:
int function(int x, {required int y, int? z}) {
return x + y + z ?? 0;
}
function(1, y: 2);
Creates enumerations:
enum SomeEnumeration {
foo,
bar,
baz,
}
In String
s can be used to disambiguate interpolated expressions:
var foo = 'foo';
var foobar = '${foo}bar';
var s = '${function(1, 2)}';
Or in String
s is used to specify Unicode code points with more than 4 hexadecimal digits:
var bullseye = '\u{1F3AF}'; // 🎯
<>
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>{};
Note that the above does not include the meaning of ()
, []
, {}
, and <>
when used in RegExp
patterns. Regular expression syntax is its own language and isn't Dart-specific.
Upvotes: 13