Pierre Huret
Pierre Huret

Reputation: 51

Dart check if many variable is null

Hello im new in dart language, is someone can help me to write this condition better, it works but it's a lot repetitive and i feel theres a better ways to write it :

 if (var1 != null || var2 != null || var3 != null || var4 != null || var5 != null){ ShowMyWidget }

thank you.

Upvotes: 1

Views: 1230

Answers (5)

Dartist
Dartist

Reputation: 507

When testing a lot of variables for non-nullity, it's better to put them into an array and use the nonNulls property:

 if ([var1, var2, var3, var4, var5].nonNulls.isNotEmpty) {
    ShowMyWidget();
  }

Using the nonNulls property, it will also become easy to just process the ones that you need to display:

[link1, link2, link3, link4, link5].nonNulls.forEach((link) => ShowMyWidget(link));

Or shorter, if the parameter of ShowMyWidget is the same type as your links:

[link1, link2, link3, link4, link5].nonNulls.forEach(ShowMyWidget);

Upvotes: 0

zgorawski
zgorawski

Reputation: 2727

if (![var1, var2, var3, var4, var5].contains(null)){ ShowMyWidget }

Upvotes: 4

Pierre Huret
Pierre Huret

Reputation: 51

ok thanks you your answers, I'll explain my goal a litle bit more : I have a detail page in may app with many custom widget and i want to check if the variables inside my widgets are null in order to either show or hide it.

My app screenshot

So here for exemple I wanna check if one of the booking link isn't null to display the title.

if (link1 != null || link2 != null || link3 != null || link4 != null || var5 != null){ ShowMyTitle }

Upvotes: 0

jamesdlin
jamesdlin

Reputation: 90015

If you really want, you could do:

if ([var1, var2, var3, var4, var5].any((x) => x != null)) {
  ShowMyWidget();
}

Upvotes: 2

Robert Pietraru
Robert Pietraru

Reputation: 79

Rather than checking all those variables, I'd make them optional parameters to the widget. If you do that, you can just check if they're null using null-safety inside it, whenever you actually need them.

class TestWidget extends StatelessWidget {
  final String? testPar1;
  final String? testPar2;
  final String? testPar3;
  final String? testPar4;
  const TestWidget({
    this.testPar1,
    this.testPar2,
    this.testPar3,
    this.testPar4,
    Key? key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text(testPar1 ?? 'nope'),
        Text(testPar2 ?? 'nope'),
        Text(testPar3 ?? 'nope'),
        Text(testPar4 ?? 'nope'),
      ],
    );
  }
}

Keep in mind that your way of doing it isn't wrong.

Upvotes: 0

Related Questions