Flutter自定义AppBar报错及动态设置高度问题求助
问题解决步骤
1. 修复类型错误
Scaffold的appBar参数要求传入PreferredSizeWidget类型组件,你的CustomAppbar当前继承自StatelessWidget,因此触发类型不匹配错误。解决方式是让CustomAppbar实现PreferredSizeWidget接口,并实现preferredSize getter方法:
class CustomAppbar extends StatelessWidget implements PreferredSizeWidget { final Widget title; final double height; const CustomAppbar({Key? key, required this.title, required this.height}) : super(key: key); @override Widget build(BuildContext context) { return AppBar( toolbarHeight: height, // 设置AppBar的高度 title: title, ); } @override Size get preferredSize => Size.fromHeight(height); // 满足PreferredSizeWidget的接口要求 }
2. 获取默认AppBar高度
Flutter内置了kToolbarHeight常量(需导入package:flutter/material.dart),这是AppBar的默认工具栏高度(移动端通常为56.0),可直接用来获取默认高度。
3. 状态类中调整AppBar高度逻辑
在状态类里根据选中状态切换默认高度和双倍高度:
import 'package:flutter/material.dart'; // 确保导入此包以使用kToolbarHeight class _Stack13State extends State<Stack13> { bool islongpressed = false; List<Movie> selectedmovies = []; @override Widget build(BuildContext context) { return Scaffold( appBar: islongpressed ? CustomAppbar(title: const Text('Select Any'), height: kToolbarHeight) : CustomAppbar(title: const Text('Selected'), height: kToolbarHeight * 2), body: showlistview(), ); } // 补充你原代码中未实现的showlistview方法 Widget showlistview() { // 你的ListView实现逻辑 return const Placeholder(); } }
额外说明
- 若你的AppBar需要包含底部组件(如TabBar),需将底部组件的高度也加入
preferredSize计算,例如:Size.fromHeight(height + bottomWidget.preferredSize.height)。 - 你当前代码中
islongpressed为true时显示默认高度,与描述的"选中时显示双倍高度"需求可能相反,可根据实际业务调整条件判断逻辑。
内容的提问来源于stack exchange,提问作者Irfan Ganatra
相关产品推荐
相关产品推荐

