如何转换小部件?到小部件

问题描述

  • 下面的代码会报错,返回值是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!;