Flutter:AppBar widget 的复用

Flutter: Reuse of AppBar widget

我创建了几个屏幕,由于某些原因我必须单独创建一个代表屏幕的脚手架。但是,由于 AppBar 应该每次都相同,所以我想在无状态小部件中创建一次,然后重用它:

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),
      ),
    );
  }
}

然后在每个屏幕上我想通过写作来使用它:

class _CreatePostScreenState extends State<CreatePostScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: MyAppBar(),
        body: Center(
          child: Text("Hello"),
        ));
  }
}

但是,我收到以下错误,我不知道如何解决(我正确导入了所有内容):

您的应用栏必须实施 PreferredSizeWidget。

class YourAppbar extends StatelessWidget implements PreferredSizeWidget {
 
  @override
  Widget build(BuildContext context) {
     return AppBar();
 }

 @override
 Size get preferredSize => const Size.fromHeight(kToolbarHeight);

}

对我来说,以下解决方案也很好:

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)),
  ]);
  
}

并且可以如下使用:

return Scaffold(
      appBar: YourAppBar(
        title: Text('Hi'),
      ),
      body: Center(
        child: Text('Home page'),
      ),
    );