/// 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;
}),
),
);
}
}
发布于 2021-06-19 15:55:27
虽然最短的方法是使用Bang !
运算符
Widget widget = nullableWidget!;
但我建议你用?.
来预防这一错误
Widget widget = nullableWidget ?? Container(); // Or some other widget.
回答你的问题:
return widget ?? Container(); // Safe
return widget!; // Could cause runtime error.
发布于 2021-06-19 15:46:13
使用空断言运算符/邦运算符( ! )
return widget1!;
https://stackoverflow.com/questions/68048371
复制相似问题