假设我有一个AppBar:

final AppBar myAppBar = AppBar(
  leading: IconButton(
    icon: Icon(Icons.delete),
    onPressed: () {},
  ),
);

如果我想在该onPressed函数中引用主父上下文,是否可以在不创建新类或创建将上下文作为构造新组件的参数的函数的情况下引用变量?
final AppBar myAppBar = AppBar(
  leading: IconButton(
    icon: Icon(Icons.delete),
    onPressed: () { print(this.context); },
  ),
);

最佳答案

您说父WidgetMaterialApp,因此为了访问父BuildContextWidget,可以通过以下方式使用子BuildContextWidget:

class Foo extends StatefulWidget {
  ...
}

class FooState extends State<Foo> {
  ...

  BuildContext getParentContext() {
    return context.ancestorStateOfType(const TypeMatcher<MaterialApp>()).context;
  }
}

如果您无权访问 child 的BuildContext,那么您还有另外两个选择:
  • 传递一个回调,该回调在 child 需要时提供 parent 的BuildContext:

  • class FooParent extends StatelessWidget {
      ...
    
      @override
      Widget build(BuildContext context) {
        return Foo(onProvideParentContext: () => context);
      }
    }
    
    typedef ContextProvider = BuildContext Function();
    
    class Foo extends StatefulWidget {
      final ContextProvider onProvideParentContext;
    
      Foo({
        @required this.onProvideParentContext,
      });
    
      ...
    }
    
    class FooState extends State<Foo> {
      ...
    
      BuildContext getParentContext() {
        return widget.onProvideParentContext();
      }
    }
    
  • BuildContext直接作为参数传递给 child 。

  • class FooParent extends StatelessWidget {
      ...
    
      @override
      Widget build(BuildContext context) {
        return Foo(parentContext: context);
      }
    }
    
    class Foo extends StatefulWidget {
      final BuildContext parentContext;
    
      Foo({
        @required this.parentContext,
      });
    
      ...
    }
    
    class FooState extends State<Foo> {
      ...
    
      BuildContext getParentContext() {
        return widget.parentContext;
      }
    }
    

    关于dart - 在Dart/Flutter中定义变量并引用父上下文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56194859/

    10-11 22:16