访问我的自定义应用程序栏中的上下文,该应用程序栏正在Flutter中扩展应用程序栏



我正在flutter中扩展AppBar小部件,以创建我的自定义AppBar,如下所示。问题是我无法访问";上下文";在小部件中。问题:-

  1. 这是扩展appbar的正确方法吗
  2. 如何访问上下文

class DashboardAppBar extends AppBar {
final String myTitle;

DashboardAppBar({Key key, @required this.myTitle})
: super(
key: key,
leading: IconButton(icon: Icon(Icons.dehaze_outlined), onPressed: () {}),
actions: [
FlatButton(
onPressed: () => Navigator.pop(context), //This line is the problem
child: Text(
'Logout',
style: TextStyle(fontSize: Sizes.dimen_20.sp),
),
),
IconButton(
icon: Icon(
Icons.notifications_none_outlined,
),
onPressed: () {})
],
title: Text(myTitle),
backgroundColor: Colors.transparent,
);
}
DashboardAppBar({Key key,
@required BuildContext context, // Just add this Line :)
@required this.myTitle})
: super(
key: key,
leading: IconButton(icon: Icon(Icons.dehaze_outlined), onPressed: () {}),
actions: [
FlatButton(
onPressed: () => Navigator.pop(context), // No more a problem
child: Text(
'Logout',
style: TextStyle(fontSize: Sizes.dimen_20.sp),
),
),
IconButton(
icon: Icon(
Icons.notifications_none_outlined,
),
onPressed: () {})
],
title: Text(myTitle),
backgroundColor: Colors.transparent,
);

现在,无论何时要创建DashboardAppBar,都可以像处理普通AppBar一样在构造函数中传递上下文。但是,正如@UTKARShhSharma所提到的,如果你不打算在其他地方使用这个小部件(或为你的AppBar添加一些额外的功能(,那么创建一个新的类并扩展AppBar不是一个好主意。如果你想在多个地方使用它,那就去吧。对于一个地方,只需使用一个直接传递这些属性的普通AppBar。

最新更新