You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 05:45:32