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

后端 未结 6 1041
逝去的感伤
逝去的感伤 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:10

    I would write a helper function instead of doing everything inline.

    bool isNullEmptyOrFalse(Object o) =>
      o == null || false == o || "" == o;
    
    bool isNullEmptyFalseOrZero(Object o) =>
      o == null || false == o || 0 == o || "" == o;
    

    That avoids the repeated lookup (like the contains operation), but it is much more readable. It also doesn't create a new List literal for each check (making the list const could fix that).

    if (isNullEmptyOrFalse(routeinfo["no_route"])) { ... }
    

    When struggling with making something short and readable, making a well-named helper function is usually the best solution.

    (Addition: Now that Dart has extension methods, it's possible to add the functionality as methods or getters that are seemingly on the object, so you can write value.isNullOrEmpty directly).

提交回复
热议问题