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

Flutter中如何在AppBar上方展示自定义文本消息?

Flutter 实现AppBar上方展示文本消息的方案

下面提供两种主流实现方式,可根据你的业务场景选择:


方案1:外层嵌套Column实现固定消息条

适合需要消息条固定在AppBar上方、不随页面滚动消失的场景,实现成本最低:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Column(
        children: [
          // AppBar上方的自定义消息条
          Container(
            width: double.infinity,
            padding: EdgeInsets.only(
              top: MediaQuery.of(context).padding.top + 8, // 适配状态栏高度
              bottom: 8,
              left: 16,
              right: 16,
            ),
            color: Colors.lightBlueAccent,
            child: const Text(
              "这是AppBar上方的消息提示",
              style: TextStyle(color: Colors.white, fontSize: 14),
              textAlign: TextAlign.center,
            ),
          ),
          const Expanded(
            child: Scaffold(
              appBar: AppBar(
                title: Text("页面标题"),
                backgroundColor: Colors.blue,
                elevation: 0,
              ),
              body: Center(child: Text("页面内容区域")),
            ),
          )
        ],
      ),
    );
  }
}

核心逻辑是把Scaffold用Expanded包裹后放在Column的第二层,消息条放在Column第一层,自然就会显示在AppBar的上方。


方案2:Overlay实现全局浮动消息条

适合需要消息条跨页面展示、支持自动消失/手动关闭的浮动通知场景,不会侵入原有页面的布局结构:

// 调用此方法即可在页面最顶部弹出消息条
void showTopNotification(BuildContext context, String message) {
  final overlay = Overlay.of(context);
  late OverlayEntry entry;

  entry = OverlayEntry(
    builder: (context) => Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: Material(
        color: Colors.lightBlueAccent,
        child: Container(
          padding: EdgeInsets.only(
            top: MediaQuery.of(context).padding.top + 8,
            bottom: 8,
            left: 16,
            right: 16,
          ),
          child: Text(
            message,
            style: const TextStyle(color: Colors.white, fontSize: 14),
            textAlign: TextAlign.center,
          ),
        ),
      ),
    ),
  );

  overlay.insert(entry);
  // 如需3秒后自动隐藏,添加下方代码即可
  Future.delayed(const Duration(seconds: 3), () => entry.remove());
}

补充说明

  • 如需实现消息条可滑动删除,可在消息条外层嵌套Dismissible组件
  • 两种方案都已经适配了状态栏高度,不会出现内容被状态栏遮挡的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:36:09