initial
This commit is contained in:
commit
74ae93a96e
1 changed files with 94691 additions and 0 deletions
77
_resources/conditional widgets.txt
Normal file
77
_resources/conditional widgets.txt
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
|
||||
|
||||
Actually you can use if/else and switch and any other statement inline in dart / flutter.
|
||||
Use a builder
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
if (true) //
|
||||
return "tis true";
|
||||
|
||||
return "anything but true";
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
or an immediate anonymous function
|
||||
|
||||
Widget build(BuildContext context) {
|
||||
return Container(child: () {
|
||||
if (value == 1) {
|
||||
return Text('tis true');
|
||||
}
|
||||
return Text('anything but true');
|
||||
}());
|
||||
}
|
||||
|
||||
I would heavily recommend against putting too much logic directly with your UI 'markup' but I found that type inference in Dart needs a little bit of work so it can be sometimes useful in scenarios like that.
|
||||
Use the ternary operator
|
||||
|
||||
condition ? Text("True") : null,
|
||||
|
||||
Use If or For statements or spread operators in collections
|
||||
|
||||
children: [
|
||||
...manyItems,
|
||||
oneItem,
|
||||
if(canIKickIt)
|
||||
...kickTheCan
|
||||
for (item in items)
|
||||
Text(item)
|
||||
|
||||
Use a method
|
||||
|
||||
child: getWidget()
|
||||
|
||||
Widget getWidget() {
|
||||
if (x > 5) ...
|
||||
//more logic here and return a Widget
|
||||
|
||||
EDIT - new with Dart 3.0
|
||||
|
||||
Dart 3.0 adds new functionality such as if-case & switch expressions in order to use pattern matching, destructuring, guard clauses.
|
||||
https://dart.dev/language/patterns
|
||||
Switch Expressions
|
||||
|
||||
We can now use switch as an expression. https://dart.dev/language/branches#switch-expressions
|
||||
|
||||
child: switch (task) {
|
||||
Task_completed(:date) => Text("completed on $date"),
|
||||
Task_overdue(:priority) => Text("$priority"),
|
||||
},
|
||||
|
||||
if-case (new to Dart 3.0)
|
||||
|
||||
Use if-case instead of switch when you have a single or small number of conditions to check. https://dart.dev/language/branches#if-case
|
||||
|
||||
return ListView(children: [
|
||||
Text('header'),
|
||||
if (pair case [int x, int y]) //
|
||||
Text('Coordinates: ($x, $y)') //
|
||||
else
|
||||
Text('No coordinates given'),
|
||||
]);
|
||||
|
||||
Loading…
Reference in a new issue