Description
Use case
Many times in Flutter I've found myself writing conditional rendering using ternary operator where "else" branch returns null.
For example, a custom Widget has a parameter that will set some property of the nested widget or even add another widget to the tree.
Within Column
or Row
(or whenever we use array []
) it is possible to use if statement
, however elsewhere I am forced to use ternary operator where else does nothing other than returning null.
- Example - simple conditional parameter:
BoxDecoration(
gradient: gradientColors != null
? LinearGradient(
colors: gradientColors!,
)
: null,
)
- Example - Suppose I have some default
Scaffold
widget with shared settings and I can passdrawerBuilder
to add a drawer to that Scaffold
return Scaffold(
resizeToAvoidBottomInset: true,
... // more shared settings etc...
body: Padding(
padding: padding,
child: ...., // shortened
),
drawer: drawerBuilder != null
? Builder(builder: (context) => drawerBuilder!(context))
: null,
);
Proposal
Probably this request will need support from dart-lang itself. I am coming from React background and in JS / TS is possible to use &&
operator for such inline rendering without an explicit else
branch. E.g, example 2 could be rewritten into
return Scaffold(
drawer: drawerBuilder != null && Builder(builder: (context) => drawerBuilder!(context))l,
);
It is maybe just personal preference, but I found this more clear than cluttering : null
with a ternary operator.