Home > Blockchain >  Dart check if many variable is null
Dart check if many variable is null

Time:12-29

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.

CodePudding user response:

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.

CodePudding user response:

If you really want, you could do:

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