So I'm working on an app. Every time when I have to make a new page I always have to make the same appBar from Scratch.
Is it possible to assign this appBar to a constant and use that constant everywhere I need it.?
OR
Is there another way to just have one appBar for the entire app?
CodePudding user response:
This is another way of going about it. By doing this you can customize this appbar to the way you want. That way, if you continue with that style, you don't have to recreate it on every page. You create it once and call on it within any widget.
Class
import 'package:flutter/material.dart';
class BaseAppBar extends StatelessWidget implements PreferredSizeWidget {
final Color backgroundColor = Colors.red;
final Text title;
final AppBar appBar;
final List<Widget> widgets;
/// you can add more fields that meet your needs
const BaseAppBar({Key key, this.title, this.appBar, this.widgets})
: super(key: key);
@override
Widget build(BuildContext context) {
return AppBar(
title: title,
backgroundColor: backgroundColor,
actions: widgets,
);
}
@override
Size get preferredSize => new Size.fromHeight(appBar.preferredSize.height);
}
Implementation within desired page
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: BaseAppBar(
title: Text('title'),
appBar: AppBar(),
widgets: <Widget>[Icon(Icons.more_vert)],
),
body: Container());
}
CodePudding user response:
Yes, write your own:
class MyAppBar extends StatelessWidget implements PreferredSizeWidget{
const MyAppBar({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container();
}
@override
// TODO: implement preferredSize
Size get preferredSize => throw UnimplementedError();
}
The AppBar Widget hasn't a constant constructor so you can't make it const
CodePudding user response:
To make your Custom Appbar you need to implement PreferredSizeWidget because the AppBar itself implements it.
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
final String screenTitle;
MyAppBar({@required this.screenTitle});
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(screenTitle),
actions: // Whatever you need
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}