如何解决如何转换小部件?到小部件
- 下面的代码会报错,返回值是Widget?而不是小部件。我希望能够强制 Widget?小部件,但如何做到这一点?
/// Get the parent widget in the subtree
class ContextRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Context test"),),body: Container(
child: Builder(builder: (context) {
// Find the nearest parent up in the Widget tree `Scaffold` widget
Scaffold? scaffold = context.findAncestorWidgetofExactType<Scaffold>();
// Return the title of AppBar directly,here is actually Text ("Context test")
Widget? widget1 = (scaffold!.appBar as AppBar).title;
return widget1;
}),);
}
}
解决方法
虽然最短的方法是使用 Bang !
运算符
Widget widget = nullableWidget!;
但我建议您使用 ?.
来防止 this error
Widget widget = nullableWidget ?? Container(); // Or some other widget.
回答您的问题:
return widget ?? Container(); // Safe
return widget!; // Could cause runtime error.
,
使用Null assertion operator / bang operator( ! )
return widget1!;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。