Vaibhav
Vaibhav

Reputation: 13

Accessing context within my custom appbar which is extending AppBar in Flutter

I am extending AppBar widget in flutter to create my custom appbar as given below. The problem is that I am not able to access "Context" within the widget. Questions :-

  1. is this the right way to extend appbar?
  2. how can I get access to context?

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,
        );
}

Upvotes: 0

Views: 773

Answers (1)

Afridi Kayal
Afridi Kayal

Reputation: 2285

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,
    );

Now, whenever you want to create a DashboardAppBar, pass the context in the constructor as you would do with normal AppBar. But, as @UTKARSHSharma mentioned, It's not a good idea to create a new class and extend AppBar if you are not going to use this widget anywhere else (or add some extra functionality to your appbar). If you want to use it in multiple places, then go for it. For a single place, just use a normal AppBar passing these properties directly.

Upvotes: 1

Related Questions