Sometimes our requirements demand a more complex AppBar that cannot be achieved with the default Flutter AppBar.
In such cases, we can create our own Custom AppBar by building a new class that implements the abstract class PreferredSizeWidget.
When implementing PreferredSizeWidget, we must also override the preferredSize property, which is used to define the height of the AppBar.
- kToolbarHeight → gives the default height of the AppBar.
- Size.fromHeight(60) → allows you to set a custom dynamic height.
In this implementation, an appTitle and a callback function (onBackPressed) are included, allowing the CustomAppBar to be reused across different parts of the app. More parameters (e.g., actions, icons, or colors) can be introduced as needed.
Finally, the CustomAppBar is used in the Homepage by passing the appTitle and onBackPressed.
Code:
import 'package:flutter/material.dart';
class Homepage extends StatefulWidget {
const Homepage({super.key});
@override
State<Homepage> createState() => _HomepageState();
}
class _HomepageState extends State<Homepage> {
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: CustomAppBar(
onBackPressed: () {
Navigator.of(context).pop();
},
appTitle: 'CustomAppbar',
),
body: Center(child: Text('Homepage', style: TextStyle(fontSize: 18))),
),
);
}
}
class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
final String appTitle;
final Function() onBackPressed;
const CustomAppBar({
super.key,
this.appTitle = 'appTitle',
required this.onBackPressed,
});
@override
Widget build(BuildContext context) {
return Container(
height: preferredSize.height,
padding: EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Theme.of(context).primaryColor,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(12),
bottomRight: Radius.circular(12),
),
),
child: Row(
children: [
Icon(Icons.arrow_back, color: Colors.white),
SizedBox(width: 10),
Text(
appTitle,
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
],
),
);
}
@override
//default height
// Size get preferredSize => Size.fromHeight(kToolbarHeight);
Size get preferredSize => Size.fromHeight(60);
}
Dart
Output:
