Dart check if many variable is null

783 Views Asked by At

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.

4

There are 4 best solutions below

0
Robert Pietraru On

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.

0
jamesdlin On

If you really want, you could do:

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

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 }
1
zgorawski On
if (![var1, var2, var3, var4, var5].contains(null)){ ShowMyWidget }