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

实现可复用的PreferredSizeWidget以用作Scaffold的AppBar

嘿,这个思路完全没问题!自定义一个实现了PreferredSizeWidget的组件来做复用的双列标题栏,确实是避免重复造轮子的好办法。我来给你捋捋具体怎么落地:

实现可复用的双列标题AppBar

核心就是创建一个符合PreferredSizeWidget规范的自定义组件,这样它就能直接对接Scaffold的appBar参数,完美搭配body里的ListView。

1. 基础组件实现

我们用Row来搭建双列布局,同时保留自定义样式、高度的灵活性:

import 'package:flutter/material.dart';

class DualColumnAppBar extends StatelessWidget implements PreferredSizeWidget {
  // 左右列标题文本
  final String leftTitle;
  final String rightTitle;
  // 可选的标题样式,默认继承主题的AppBar样式
  final TextStyle? titleStyle;
  // 自定义高度,默认和系统AppBar一致
  final double height;

  const DualColumnAppBar({
    super.key,
    required this.leftTitle,
    required this.rightTitle,
    this.titleStyle,
    this.height = kToolbarHeight,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      height: height,
      padding: const EdgeInsets.symmetric(horizontal: 16.0),
      alignment: Alignment.center,
      // 可以根据需求添加背景色,比如继承主题的AppBar背景
      color: Theme.of(context).appBarTheme.backgroundColor,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            leftTitle,
            style: titleStyle ?? Theme.of(context).appBarTheme.titleTextStyle,
          ),
          Text(
            rightTitle,
            style: titleStyle ?? Theme.of(context).appBarTheme.titleTextStyle,
          ),
        ],
      ),
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(height);
}

2. 快速复用示例

现在你可以在任何Scaffold里直接调用这个组件,body区域正常实现你的ListView即可:

Scaffold(
  appBar: DualColumnAppBar(
    leftTitle: "用户ID",
    rightTitle: "用户名称",
    titleStyle: const TextStyle(
      fontSize: 16,
      fontWeight: FontWeight.w600,
      color: Colors.black87,
    ),
  ),
  body: ListView.builder(
    itemCount: 30,
    itemBuilder: (context, index) {
      return ListTile(
        leading: Text("#${index + 1}"),
        trailing: Text("用户${index + 1}"),
      );
    },
  ),
);

3. 进阶优化(可选)

如果需要更灵活的场景适配,可以给组件加这些扩展:

  • 给左右标题添加点击事件(比如增加VoidCallback? leftOnTap参数)
  • 支持自定义左右侧的Widget(把leftTitle改成Widget leftChild,让用户可以传入图标、按钮等)
  • 添加分割线,让双列标题和下方ListView的边界更清晰

这样一来,你就不用每次都重复写简陋的标题栏,直接复用这个组件就能快速实现统一的布局模式啦~

内容的提问来源于stack exchange,提问作者jared-nelsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:50:38