Skip to content

Inline if assignment instead of ternary operator with null else branch #1714

Closed
@petrnymsa

Description

@petrnymsa

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.

  1. Example - simple conditional parameter:
BoxDecoration(
    gradient: gradientColors != null
        ? LinearGradient(
            colors: gradientColors!,
          )
        : null,
)
  1. Example - Suppose I have some default Scaffold widget with shared settings and I can pass drawerBuilder 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problemsstate-duplicateThis issue or pull request already exists

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions