1、判断空,标准写法--d如过是null或者没有isEmpty方法,就会抛异常
if (d?.isEmpty ?? true) {}
3、如果为null为解析成null字符串用$
字面量
'订单编号: ${str}'
3、如果为null,会抛异常
Text(str);
data != null "A non-null String must be provided to a Text widget."
测试一段代码
void main() {
String str = ''; //isEmpty可以判断长度为0的字符串
String str2 = null; //需要用?
List d1 = [];
List d2 = null;//给对象传null,正常操作
Map d3 = {};
Map d4 = null;
if (d1?.isEmpty) {
print('空');
}
if (d2?.isEmpty ?? true) {
print('空');
}
try {
if (d2?.isEmpty) {//Assertion failed: "boolean expression must not be null"
print('空');
}
} catch (e) {
print(e);
}
if (d3?.isEmpty) {
print('空');
}
if (d4?.isEmpty ?? true) {
print('空');
}
if (str?.isEmpty ?? true) {
print('空');
}
if (str2?.isEmpty ?? true) {
print('空');
}
try {
str.isEmpty;
} catch (e) {
print("1:$e");
}
try {
str2.isEmpty; //NoSuchMethodError: method not found
} catch (e) {
print("2: $e");
}
print('订单编号: ${str}');
print('订单编号: ${str2}');
}
运行结果
空
空
Assertion failed: "boolean expression must not be null"
空
空
空
空
2: NoSuchMethodError: method not found: 'get$isEmpty' on null
订单编号:
订单编号: null
再测试:
@override
Widget build(BuildContext context) {
String str;
try {
str = null;
} catch (e) {
print("e1: $e");
}
try {
Text txt = Text(str, style: Theme.of(context).textTheme.headline4);
return txt;
} catch (e) {
print("e2: $e");
}
return SizedBox();
}
运行结果
e2: Assertion failed: file:///Users/brettmorgan/Documents/GitHub/dart-services/flutter/packages/flutter/lib/src/widgets/text.dart:379:10
data != null
"A non-null String must be provided to a Text widget."
网友评论