【问题标题】:How to convert Widget? to Widget如何转换小部件?到小部件
【发布时间】:2021-09-03 23:18:20
【问题描述】:
  • 以下代码会报错,返回值为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;
        }),
      ),
    );
  }
}

【问题讨论】:

    标签: flutter dart widget dart-null-safety


    【解决方案1】:

    虽然最短的方法是使用 Bang ! 运算符

    Widget widget = nullableWidget!;
    

    但我建议你使用?. 来防止this error

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

    回答你的问题:

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

    【讨论】:

    • 能解释一下第一种情况的解题原理吗?谢谢。 - “返回小部件 ?? Container(); // 安全”
    • @pigfly 假设原因,假设AppBar 中没有标题(标题为null),这使您的widget1 null 并从@987654332 返回null @ 是一个错误。通过使用widget ?? Container(),我们确保至少返回一个Container 小部件以防止出现此错误。希望你能明白。
    • 明白。谢谢。
    【解决方案2】:

    使用Null assertion operator / bang operator( ! )

    return widget1!;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      • 2022-07-30
      • 2015-07-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 2017-04-16
      相关资源
      最近更新 更多