Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dart 如果其中一个字符串为null,如何处理concating字符串?_Dart - Fatal编程技术网

Dart 如果其中一个字符串为null,如何处理concating字符串?

Dart 如果其中一个字符串为null,如何处理concating字符串?,dart,Dart,字符串path1由两个字符串串联而成。一个字符串是硬编码的,另一个字符串可能为空。如果id字符串为null,我希望path1为null。我正在考虑尝试/抓住选民。立法机构[lt.type].id。我只是想知道有没有一种优雅的方法可以做到这一点 path1='/legistrations/'+electorates.legistrations[lt.type].id,您可以创建一个类似这样的扩展方法,在那里添加一个方法,在字符串对象上执行您想要的操作: void main() { print(

字符串
path1
由两个字符串串联而成。一个字符串是硬编码的,另一个字符串可能为空。如果
id
字符串为null,我希望path1为null。我正在考虑尝试/抓住
选民。立法机构[lt.type].id
。我只是想知道有没有一种优雅的方法可以做到这一点


path1='/legistrations/'+electorates.legistrations[lt.type].id

您可以创建一个类似这样的扩展方法,在那里添加一个方法,在
字符串
对象上执行您想要的操作:

void main() {
  print('test'.concatOrNull(null)); // null
  print('test'.concatOrNull('123')); // test123
}

extension concatOrNullExtension on String {
  String concatOrNull(String other) => other == null ? null : this + other;
}

由于希望生成的字符串为
null
,因此可以执行以下操作:

var concatenation=后缀?.replaceRange(0,0,前缀);
在你的情况下,这将是:

path1=electorates.legistrations[lt.type].id?.replaceRange(0,0,“/legistrations/”);

(如果可以选择消除
null
值,而不是传播它们,典型的方法是执行
var串联=前缀???+后缀??;

我必须说,如果我在pull请求中看到此代码,它将被拒绝,因为几乎没有可读性,因为很难查看代码并完全理解其后果。但不管怎样,这都是很酷的解决方案。:)