Flutter:重用AppBar小部件 [英] Flutter: Reuse of AppBar widget

查看:60
本文介绍了Flutter:重用AppBar小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您的应用栏必须实现PreferredSizeWidget.

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

}

这篇关于Flutter:重用AppBar小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆