skip to Main Content

So let’s say I want to have the same or very similar AppBar in a lot of screens.

To reduce duplicated code for most cases I would create a new widget that has the layout/configuration that I want. In this case it would look like this:

class MyAppBar extends StatelessWidget {
  final String title;

  const MyAppBar({Key? key, required this.title}) : super(key: key);

  void handlePress(){
    // handle press
  }

  @override
  Widget build(BuildContext context) {
    return AppBar(
      centerTitle: true,
      title: Text(title),
      actions: <Widget>[
        IconButton(onPressed: handlePress, icon: const Icon(Icons.notifications))
      ],
    );
  }
}

However, if I try to use this in a Scaffold I get the following error:

The argument type 'MyAppBar' can't be assigned to the parameter type 'PreferredSizeWidget?'

I have seen in other solutions that people extend the widget in question like this:

class IAppBar extends AppBar {
  final String label;

  IAppBar({super.key, required this.label})
      : super(
          title: Text(label),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              onPressed: handlePress,
              icon: Icon(Icons.notifications),
            ),
          ],
        );

  void handlePress() {
    // handle press
  }
}

This is very clean and simple, but this produces the following error:

The instance member 'handlePress' can't be accessed in an initializer.

Is there a way to provide a simple, reusable configuration for widgets where a specific widget type is required?

2

Answers


  1. If you want to use simple configuration, you can use the following way.

    In case of extracting an AppBar, what I would do is I will create a function that returns AppBar. I said this for AppBar only because it implements PreferredSizeWidget. So when it comes to extracting other widgets, I will always choose to create Stateless/Stateful widgets.

    Here’s the demo code of extracting an AppBar:

    getAppBar(String? title, void Function()? onPressed) {
      return AppBar(
        title: Text(title ?? "Demo title"),
        centerTitle: true,
        actions: <Widget>[
          IconButton(
            onPressed: onPressed ?? () {},
            icon: const Icon(Icons.notifications),
          ),
        ],
      );
    }
    

    You can add or remove the variables as per your choice but I use this approach only for extracting the AppBar.

    Login or Signup to reply.
  2.     AppBar projectAppBar(String title)     {
      return AppBar(
            backgroundColor:           ProjectColors.mainColor,
            elevation: 0,
            title: Text(title, style:         FontPath.bold21, textAlign:         TextAlign.center),
    centerTitle: true,
    
                    
              ),
      );
    }
    

    I always use like that

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search