【问题标题】:How to simplify null checks in dart如何简化飞镖中的空检查
【发布时间】:2019-03-17 07:16:44
【问题描述】:

在下面给出的 dart 代码中简化 null 检查的可能方法是什么:

下面给出的代码检查传递的参数是否为空或空,并将它们分配给正确的值。

bool showBasicDialog = false;
String startPath = '';
String frameToolID = '';
String path = '';
String host = '';
String frameToolName = '';

/// for opening a frame tool
void openFrameTool(
  String frameToolNameInp,
  String toolIDInp,
  String pathInp,
  String hostInp,
) async {
  if (frameToolNameInp != null && frameToolNameInp.isNotEmpty) {
    frameToolName = frameToolNameInp;
  }
  if (toolIDInp != null && toolIDInp.isNotEmpty) {
    frameToolID = toolIDInp;
  }
  if (pathInp != null && pathInp.isNotEmpty) {
    path = pathInp;
  }
  if (hostInp != null && hostInp.isNotEmpty) {
    host = hostInp;
  }
  showBasicDialog = true;
}

【问题讨论】:

    标签: dart


    【解决方案1】:
      String _valueOrDefault(String value, String defaultValue) => (value?.isNotEmpty ?? false) ? value : defaultValue;
    
      ...
    
      frameToolName = _valueOrDefault(frameToolNameInp, frameToolName);
    
      frameToolID = _valueOrDefault(toolIDInp, frameToolID);
    
      path = _valueOrDefault(pathInp, path);
      
      host = _valueOrDefault(hostInp, host);
      
      showBasicDialog = true;
    

    【讨论】:

    • 在 dart 2.10 default 是保留字,因此不能用作参数。但即使在修复之后,上述函数也不会在 dart 中编译,并出现许多错误,包括。 A value of type 'bool' can't be returned from function '_valueOrDefault' because it has a return type of 'String'.
    • 我搞错了?和 :。感谢您的提示 - 已修复。
    猜你喜欢
    • 1970-01-01
    • 2019-02-12
    • 2021-08-09
    • 2022-07-20
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多