0

我正在扩展 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,
        );
}
4

1 回答 1

0
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 一样在构造函数中传递上下文。但是,正如@UTKARSHSharma 所提到的,如果您不打算在其他任何地方使用此小部件(或向您的应用栏添加一些额外功能),那么创建一个新类并扩展 AppBar 并不是一个好主意。如果你想在多个地方使用它,那就去吧。对于单个位置,只需使用直接传递这些属性的普通 AppBar。

于 2020-10-10T15:11:29.977 回答