Reputation: 423
I created several screens, for some reasons I have to individually create a Scaffold which represents the screen. However, as the AppBar should be everytime the same, I thought of create it once in a stateless widget and the just reuse this:
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget {
@override
Widget build(BuildContext context) {
return AppBar(
centerTitle: true,
backgroundColor: Colors.black,
title: Text(
"Places Near You",
style: TextStyle(
color: Colors.black, fontFamily: "Billabong", fontSize: 35),
),
);
}
}
and then on every Screen i wanting to use this by writting:
class _CreatePostScreenState extends State<CreatePostScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(),
body: Center(
child: Text("Hello"),
));
}
}
However, I get the following error which I dont know how to solve (I imported everything correctly):
Upvotes: 5
Views: 1943
Reputation: 703
For me the following solution went fine too:
class YourAppBar extends AppBar {
YourAppBar({Key key, Widget title})
: super(key: key, title: title, actions: <Widget>[
new IconButton(
onPressed: (){},
icon: new Icon(Icons.access_alarm)),
]);
}
And can be used as follow:
return Scaffold(
appBar: YourAppBar(
title: Text('Hi'),
),
body: Center(
child: Text('Home page'),
),
);
Upvotes: 1
Reputation: 1320
Your app bar must implement PreferredSizeWidget.
class YourAppbar extends StatelessWidget implements PreferredSizeWidget {
@override
Widget build(BuildContext context) {
return AppBar();
}
@override
Size get preferredSize => const Size.fromHeight(kToolbarHeight);
}
Upvotes: 10