如果可用,我有一个简单的页面呈现信息,否则“未找到”。
数据是从Map<String,Data>
取回的,也就是说取错key的数据会导致null
。所以我正在检查数据是否为空,然后使用信息。下面的示例代码(下面是完整代码)
我希望 dart 能够识别 if-else 语句,但它没有。我不想添加强制运算符 (data!.text
)
final String id = "id";
final Data? data = MyCustomWidget.of(context).info[id];
Widget build(context) {
if(data != null) {
//Error: The property 'text' can't be unconditionally
//accessed because the receiver can be 'null'.
//Try making the access conditional (using '?.')
//or adding a null check to the target ('!').
return Text(data.text);
}
return Text("Not Found");
}
完整代码:
class ArtistPage extends StatefulWidget {
final String id;
const ArtistPage({Key? key, required this.id}) : super(key: key);
@override
_ArtistPageState createState() => _ArtistPageState();
}
class _ArtistPageState extends State<ArtistPage> {
late final Data? data;
@override
void initState() {
//App.of(context).info = Map<String,Data>
data = App.of(context).info[widget.id];
super.initState();
}
@override
Widget build(BuildContext context) {
Widget _body() {
if (data == null) {
return Text("");
} else {
//Simplified
//Error: The property 'name' can't be unconditionally accessed because the receiver can be 'null'.\nTry making the access conditional (using '?.') or adding a null check to the target ('!').
return Text(data.name);
}
}
return Scaffold(appBar: AppBar(), body: _body());
}
}