【发布时间】:2019-09-21 05:26:54
【问题描述】:
我创建了一个类来扩展 Flutter 中的 AppBar 类,以便我可以在需要时重用它。 我的问题是如何访问有状态/无状态小部件构建上下文?
class AppBarLayout extends AppBar {
static final AppController _appController = new AppController();
final GlobalKey<ScaffoldState> _scaffoldKey;
final String appBarTitle;
AppBarLayout(this.appBarTitle,this._scaffoldKey): super(
title: Text(appBarTitle),
leading: IconButton(
onPressed: () => _scaffoldKey.currentState.openDrawer(),
iconSize: 28,
icon: Icon(Icons.menu,color: Colors.white),
),
actions: <Widget>[
IconButton(
onPressed: () => _appController.signOut().then((_) {
_appController.navigateTo(context, new GoogleSignView());
}),
icon: Icon(Icons.account_box),
padding: EdgeInsets.all(0.0),
),
],
);
}
【问题讨论】:
-
你需要在构造函数中传递上下文,就像你传递 appBarTitle 一样
-
@Hosar 我使用以下代码做到了这一点:
static BuildContext _context = HomeState().context;但是当我在构造函数中传递 _context 并运行应用程序时出现错误:Reading static variable '_context@25445118' during its initialization -
你在哪里使用 AppBarLayout,在 Scaffold 中?
-
@Hosar 是的,我的意图是让它可用于所有屏幕。只有标题是需要更改的属性,当然还有一些抽屉操作的脚手架键
-
为什么需要获取另一个小部件的上下文?
AppBar本身就是一个小部件,所以它有自己的context字段。