如何为父变量设置空安全,这样我们就不需要为子变量循环
How to set null safety to parent variable so we do not need to loop for the children vars
我在将空安全性放入子变量时遇到问题,因为有很多。我只想将它设置为父级。我已经做到了,但是有什么捷径可以让我们只输入父变量然后我们不需要为子变量循环
return ListView.separated(
itemBuilder: (context, index){
final DataAd object = snapshot.data![index]; => Here is the parent
final images = object.images!['images']; => I dont want to repeat here
if(object!=null) {
return Card(
child: Column(
children: [
Text(object.title!), => this one
Image(image: NetworkImage('${globals.domain}${object.dir}/${images![0]}')), => and this one for example
],
),
);
}
else{
return CallLoading();
}
},
separatorBuilder: (context,index) => Divider(),
itemCount: snapshot.data!.length,
);
我是 flutter 的新手,非常感谢任何给定的答案。谢谢。
只要给你的函数添加一个守卫,Dart 编译器就会发现这个值不能是 null
.
示例:
void foo(String? data) {
String _data;
if (data == null) return; // The guard.
_data = data; // Will not ask for null check because it cannot be null.
print(_data);
}
// Without guard:
void foo(String? data) {
String _data;
//if (data == null) return;
_data = data; // Error: A value of type ‘String?’ can’t be assigned to a variable of type ‘String’.
print(_data);
}
// With default value.
void foo(String? data) {
String _data = data ?? 'Empty'; // <- Convert to non nullable.
// Do what you want with _data
print(_data);
}
我在将空安全性放入子变量时遇到问题,因为有很多。我只想将它设置为父级。我已经做到了,但是有什么捷径可以让我们只输入父变量然后我们不需要为子变量循环
return ListView.separated(
itemBuilder: (context, index){
final DataAd object = snapshot.data![index]; => Here is the parent
final images = object.images!['images']; => I dont want to repeat here
if(object!=null) {
return Card(
child: Column(
children: [
Text(object.title!), => this one
Image(image: NetworkImage('${globals.domain}${object.dir}/${images![0]}')), => and this one for example
],
),
);
}
else{
return CallLoading();
}
},
separatorBuilder: (context,index) => Divider(),
itemCount: snapshot.data!.length,
);
我是 flutter 的新手,非常感谢任何给定的答案。谢谢。
只要给你的函数添加一个守卫,Dart 编译器就会发现这个值不能是 null
.
示例:
void foo(String? data) {
String _data;
if (data == null) return; // The guard.
_data = data; // Will not ask for null check because it cannot be null.
print(_data);
}
// Without guard:
void foo(String? data) {
String _data;
//if (data == null) return;
_data = data; // Error: A value of type ‘String?’ can’t be assigned to a variable of type ‘String’.
print(_data);
}
// With default value.
void foo(String? data) {
String _data = data ?? 'Empty'; // <- Convert to non nullable.
// Do what you want with _data
print(_data);
}