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

Flutter报错:Widget无法分配给PreferredSizeWidget?参数的解决方法

解决Flutter中AppBar类型不匹配的错误

错误原因

Scaffold的appBar参数要求传入PreferredSizeWidget类型,但你的header()函数默认返回Widget类型——即便实际返回的PreferredSize实现了PreferredSizeWidget,编译器也无法自动推断类型,最终导致类型不匹配报错。

两种解决方案

方案一:明确指定header函数的返回类型

把header()函数的返回类型从Widget改为PreferredSizeWidget,让编译器识别返回值的正确类型:

import "package:flutter/material.dart";

import "../../theme.dart";

class DetailChatPage extends StatelessWidget{
  const DetailChatPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    // 修改返回类型为PreferredSizeWidget
    PreferredSizeWidget header() {
      return PreferredSize(
        preferredSize: Size.fromHeight(70),
        child: AppBar(
          backgroundColor: backgroundColor1,
          title: Row(
            children: [
              Image.asset("assets/image_shop_logo_online.png", width: 50, height: 50,),
              const SizedBox(
                width: 12,
              ),
              Column(
                children: [
                  Text("Shoe Store", style: primaryTextStyle.copyWith(fontWeight: medium),)
                ],
              )
            ],
          ),
          elevation: 0,
        ),
      );
    }

    return Scaffold(
      backgroundColor: backgroundColor3,
      appBar: header(),
    );
  }
}

方案二:直接用AppBar的toolbarHeight属性(更简洁)

AppBar本身就是PreferredSizeWidget,如果只是想自定义高度,完全不需要用PreferredSize包裹,直接设置toolbarHeight属性即可:

import "package:flutter/material.dart";

import "../../theme.dart";

class DetailChatPage extends StatelessWidget{
  const DetailChatPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    PreferredSizeWidget header() {
      return AppBar(
        backgroundColor: backgroundColor1,
        toolbarHeight: 70, // 直接设置高度
        title: Row(
          children: [
            Image.asset("assets/image_shop_logo_online.png", width: 50, height: 50,),
            const SizedBox(
              width: 12,
            ),
            Column(
              children: [
                Text("Shoe Store", style: primaryTextStyle.copyWith(fontWeight: medium),)
              ],
            )
          ],
        ),
        elevation: 0,
      );
    }

    return Scaffold(
      backgroundColor: backgroundColor3,
      appBar: header(),
    );
  }
}

内容的提问来源于stack exchange,提问作者leo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 12:22:50