1
  • The following code will make an error, and the return value is Widget? instead of Widget. I want to be able to force Widget? to Widget, but how to do it?
/// 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;
        }),
      ),
    );
  }
}
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
pig fly
  • 11
  • 3

2 Answers2

2

Although the shortest way to do it is using the Bang ! operator

Widget widget = nullableWidget!;

But I'd recommend you to use ?. to prevent this error

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

To answer your question:

return widget ?? Container(); // Safe
return widget!; // Could cause runtime error.
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
  • Can you explain the principle of solving the problem in the first case? thanks. - "return widget ?? Container(); // Safe" – pig fly Jun 19 '21 at 17:16
  • @pigfly For hypothetical reason, let's say there's was no title in the `AppBar` (title was `null`), this makes your `widget1` `null` and returning `null` from `Widget` is an error. By using `widget ?? Container()`, we make sure that we return at least a `Container` widget to prevent this error. Hope you get the idea. – CopsOnRoad Jun 19 '21 at 17:19
  • Understood. Thank you. – pig fly Jun 20 '21 at 01:04
1

Use Null assertion operator / bang operator( ! )

return widget1!;
p2kr
  • 606
  • 6
  • 18