Dart null / false / empty checking: How to write this shorter?

后端 未结 6 1017
逝去的感伤
逝去的感伤 2020-12-04 23:49

This is my code for true on everything but empty string, null and false:

if (routeinfo[\"no_route\"] == \"\" || routeinfo[\"no_route\"] == null || routeinfo[         


        
6条回答
  •  离开以前
    2020-12-05 00:25

    As coming from Android and Kotlin, I prefer extension methods over a static helper method. And with Dart 2.7 you can now use that as well:

    extension Extension on Object {
      bool isNullOrEmpty() => this == null || this == '';
    
      bool isNullEmptyOrFalse() => this == null || this == '' || !this;
    
      bool isNullEmptyZeroOrFalse() =>
          this == null || this == '' || !this || this == 0;
    }
    

    Now you can just call these methods from anywhere in your code:

    if (anyVariable.isNullOrEmpty()) {
      // do something here
    }
    

    You might need to manually import the dart class, where you put your extension methods, for example:

    import 'package:sampleproject/utils/extensions.dart';
    

提交回复
热议问题