0

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 Answers4

2
if (![var1, var2, var3, var4, var5].contains(null)){ ShowMyWidget }
zgorawski
  • 2,597
  • 4
  • 30
  • 43
0

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

If you really want, you could do:

if ([var1, var2, var3, var4, var5].any((x) => x != null)) {
  ShowMyWidget();
}
jamesdlin
  • 81,374
  • 13
  • 159
  • 204
0

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 }
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 30 '21 at 00:44