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
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 forAppBar
only because it implementsPreferredSizeWidget
. So when it comes to extracting other widgets, I will always choose to createStateless/Stateful
widgets.Here’s the demo code of extracting an
AppBar
:You can add or remove the variables as per your choice but I use this approach only for extracting the AppBar.
I always use like that