在Dart / Flutter中定义变量并引用父上下文

时间:2019-05-17 23:55:38

标签: dart flutter

假设我有一个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); },
  ),
);

2 个答案:

答案 0 :(得分:1)

您说父级WidgetMaterialApp,因此,要访问父级BuildContext的{​​{1}},您可以使用WidgetBuildContext的方式如下:

Widget

如果您无权访问孩子的class Foo extends StatefulWidget { ... } class FooState extends State<Foo> { ... BuildContext getParentContext() { return context.ancestorStateOfType(const TypeMatcher<MaterialApp>()).context; } } ,那么您还有两个选择:

  1. 传递一个回调,该回调在孩子需要时提供父母的BuildContext
BuildContext
  1. 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

答案 1 :(得分:0)

经过一番挖掘,我在Flutter API文档中遇到了BuilderStatefulBuilder

https://api.flutter.dev/flutter/widgets/Builder-class.html
https://api.flutter.dev/flutter/widgets/StatefulBuilder-class.html

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

将成为:

final AppBar myAppBar = AppBar(
  leading: Builder(
    builder: (BuildContext context) => IconButton(
      icon: Icon(Icons.delete),
      onPressed: () { print(context); },
    ),
  ),
);

或者,如果我需要状态:

int totalClicks = 0;

final PreferredSizeWidget myAppBar = PreferredSize(
  preferredSize: Size.fromHeight(50.0),
  child: StatefulBuilder(
    builder: (
      BuildContext context,
      StateSetter setState,
    ) {
      return AppBar(
        leading: IconButton(
          icon: Icon(Icons.thumb_up),
          onPressed: () => setState(() => totalClicks++),
        ),
        title: Text('Clicked: $totalClicks times!')
      );
    }
  ),
);