Home > Net >  Dart: What's the best practice between using ternary and if conditions in a widget tree
Dart: What's the best practice between using ternary and if conditions in a widget tree

Time:06-08

I've been wondering what's the best practice for conditional widget trees between using ternaries and if-else-blocks.

Following guides online, I feel people use mostly ternaries but I find them quite unreadable when they exceed a single line :

double ternary

So I tend to create a fonction and make an if-else-block when my ternary are too long :

floatingActionButton: selectedLicences.isEmpty //
          ? Container()
          : LicencesWidget(selectedLicences: selectedLicences)
Widget _buildFAB(List<X> licences) {
    if (licences.isEmpty) {
      return Container();
    } else {
      return LicencesWidget(selectedLicences: licences);
    }
  }

What's the best practice?

CodePudding user response:

floatingActionButton: selectedLicences.isEmpty ? Container()
      : LicencesWidget(selectedLicences: selectedLicences)`

This is the best practice for sort conditions as per my knowledge.

CodePudding user response:

Using ternary is Conditional expressions and if-else are statements.

Sometimes on widget tree if-else won't work, because it seeks for expression. Like you cant use conditional if-else statements on MaterialApp's home and scaffold's body

/// theses wont work
 MaterialApp(
   home: if(1<4) Text("") else Text('') 
   home: Scaffold(body: if(1<4) Text("") else Text(''),) 
or 
  Text(1 < 4 ? Text("") : Text(''))

But If you use ternary expression here it will work

body: 1 < 4 ? Text("") : Text('')

Inside a Column widget or the widget that takes children, you can use conditional if-else statement.

You can check Benefits of ternary operator vs. if statement

In summery: Not all the time you can use if-else statement inside a widget, you will need to provide expression in that case. I prefer using ternary expression over if-else statements.

Also, you can check about inline function, [It is recommended not to do heavy operation]

  home: () {
        if (1 < 4) {
          return Text("");
        } else {
          return Text('');
        }
      }(),

About your snippet answer I will pass null instead of empty container.

floatingActionButton: selectedLicences.isEmpty
      ? null
      : LicencesWidget(selectedLicences: licences)
  • Related