I'm a beginner in Dart/Flutter and tried reading this but I still couldn't understand when to use a semicolon. Why aren't we inserting a semicolon at the end of every bracket of a widget?
There are two kinds of statements in Dart: simple statements and compound statements.
Examples:
print('hello world');return myValue;var x = 4;Compound statements have code blocks whose scope is defined by curly braces { }. You don't use semicolons after the closing curly brace.
if-statement example:
if (x > 2) {
print(x);
}
Here print(x) is a simple statement so it needed a semicolon, but the if-statement closing brace didn't need one.
Other examples of compound statements include loops, switch statements, and function blocks.
In Dart, the items of a list are separated by commas, like so:
var myList = [1, 2, 3];
The semicolon goes after the list's closing square bracket to indicate that the statement is complete, but the list items themselves used commas.
You can also format lists vertically if you add a comma after the last item, like so:
var myList = [
1,
2,
3,
];
In Flutter layouts you often have lists of widgets that follow this same pattern.
Have a look at this example in Flutter:
class MyWidet extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(
child: Container(
width: 300,
color: Colors.blue,
margin: EdgeInsets.all(10),
padding: EdgeInsets.all(10),
child:
Wrap(
children: [
MyWidget(),
MyWidget(),
MyWidget(),
MyWidget(),
MyWidget(),
],
),
),
); // end of the return statement
}
}
Note the following things:
} closing braces (for the MyWidet class and build method) use semicolons.width, color, child, etc) are lists. They use commas.return statement, so there is only one semicolon.Statements end with a semicolon (e.g. print, assignments, increments ...) Code blocks do not need semicolons (e.g. classes, functions, if blocks)
To answer your question, usually you'll pass in a widget into a parameter of a parent widget. In this case, you'll use commas, just like in any other class i.e. each widget is not a statement but rather a code block or more specifically, instance of a class
However, in the build function, you'll use semicolon since the widget is being returned (a statement).
For example,
Widget build(BuildContext context) {
return Scaffold(...); // semicolon used to signify the end of a statement
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With