【问题标题】:Is it possible to pass arguments to PreferredSizeWidget?是否可以将参数传递给 PreferredSizeWidget?
【发布时间】:2021-11-11 02:20:50
【问题描述】:

我将Scaffold 的appBar 声明为超出范围的变量。

PreferredSizeWidget originAppBar = AppBar(
  centerTitle: true,
          backgroundColor: Colors.white,
          title: ....

这允许我通过将originAppBar 分配给appBar: 来使用它。

appBar: originAppBar,

但是,我在originAppBar 中包含了以下代码。

Navigator.of(context).pushNamed(Profile.route);

这是一个需要BuildContext 且不在originAppBar 中的函数。

是否可以有一个带参数的 PreferredSizeWidget?像这样的 C#;

//C# 
PreferredSizeWidget originAppBar = new PreferredSizeWidget(BuildContext context)

Widget build(BuildContext xontext){ 
....
    appBar: originAppBar(context)
....
}

谢谢。

【问题讨论】:

    标签: flutter dart flutter-web


    【解决方案1】:

    使用 GlobalKey - 将其分配给您的小部件

    Global keys uniquely identify elements. Global keys provide access to other objects that are associated with those elements, such as BuildContext.

    https://api.flutter.dev/flutter/widgets/GlobalKey-class.html

    【讨论】:

    • 感谢您的回答。 GlobalKey不能只用于appBar吗?在网上的大部分示例中,GlobalKey是在类中声明的,所以我认为它不能和PreferredSizeWidget一起使用。我太新了,不能在这里学习,有人可以告诉我吗?
    【解决方案2】:

    看来定义是错误的。 以下是正确的。

    PreferredSizeWidget originAppBar(BuildContext context) {
      return AppBar(....
    }
    
    ....
    
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: originAppBar(context),
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-22
      • 2020-09-14
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      • 1970-01-01
      • 2010-09-15
      相关资源
      最近更新 更多