假设我有一个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); },
),
);
答案 0 :(得分:1)
您说父级Widget
是MaterialApp
,因此,要访问父级BuildContext
的{{1}},您可以使用Widget
子BuildContext
的方式如下:
Widget
如果您无权访问孩子的class Foo extends StatefulWidget {
...
}
class FooState extends State<Foo> {
...
BuildContext getParentContext() {
return context.ancestorStateOfType(const TypeMatcher<MaterialApp>()).context;
}
}
,那么您还有两个选择:
BuildContext
: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
答案 1 :(得分:0)
经过一番挖掘,我在Flutter API文档中遇到了Builder
和StatefulBuilder
:
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!')
);
}
),
);