本文介绍了Flutter:重用 AppBar 小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了几个屏幕,出于某些原因,我必须单独创建一个代表屏幕的 Scaffold.但是,由于 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 小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!