Home > Mobile >  What is the best way to extract widgets to create your own configuration?
What is the best way to extract widgets to create your own configuration?

Time:01-25

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?

CodePudding user response:

If you want to use simple configuration, you can use the follwing 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 PrefferedSizeWidget. So when it comes to extracting other widgets, I will always choose to create Stateless/Stateful widgets.

Here's the demo code of extrscting 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.

CodePudding user response:

    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

  • Related