首页 > 解决方案 > 如何转换小部件?到小部件

问题描述

/// 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;
        }),
      ),
    );
  }
}

标签: flutterdartwidgetdart-null-safety

解决方案


虽然做到这一点的最短方法是使用 Bang!运算符

Widget widget = nullableWidget!;

但我建议您使用?.以防止此错误

Widget widget = nullableWidget ?? Container(); // Or some other widget. 

要回答您的问题:

return widget ?? Container(); // Safe
return widget!; // Could cause runtime error.

推荐阅读