flutter - 如何转换小部件?到小部件
问题描述
- 下面的代码会报错,返回值为Widget?而不是小部件。我希望能够强制使用 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!;
但我建议您使用?.
以防止此错误
Widget widget = nullableWidget ?? Container(); // Or some other widget.
要回答您的问题:
return widget ?? Container(); // Safe
return widget!; // Could cause runtime error.
推荐阅读
- javascript - List.js 默认应用过滤器
- python - `/bin/sh` 在 docker 内的 Jenkins 内的 tox 中找不到
- python - 为什么对 python 服务器使用 struct 而不是 pickle
- javascript - JS API 根据某些参数的值获取数据库项
- mysql - mysql 错误代码:1066。不是唯一的表/别名:'t2'
- javascript - 条件为真时添加数字的逻辑
- jquery - 格式化文本的数据标题中的 HTML 代码
- android - 在按钮单击时过滤 Firebase 数据库返回单个回收视图列表项
- opencv - 通过 OpenCV 查找表格的轮廓
- html - Bootstrap 两列布局图像和文本响应式