SRel
SRel

Reputation: 423

Flutter: Reuse of AppBar widget

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):

enter image description here

Upvotes: 5

Views: 1943

Answers (2)

CNK
CNK

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

Luiz Filipe Medeira
Luiz Filipe Medeira

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

Related Questions