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

Flutter中如何根据屏幕方向调整status bar、navigation bar颜色及AppBar标题

根据屏幕方向调整系统栏与AppBar样式实现方案

核心实现逻辑

  • 用OrientationBuilder组件实时监听屏幕方向变化
  • 调用SystemChrome.setSystemUIOverlayStyle()方法动态修改状态栏(status bar)和导航栏(navigation bar)颜色
  • 根据方向参数动态赋值AppBar的title属性

完整示例代码

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: OrientationBuilder(
          builder: (context, orientation) {
            // 根据方向设置系统栏样式
            if (orientation == Orientation.portrait) {
              SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
                statusBarColor: Colors.pink,
                systemNavigationBarColor: Colors.pink,
              ));
            } else {
              SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
                statusBarColor: Colors.yellow,
                systemNavigationBarColor: Colors.yellow,
              ));
            }

            return CustomScrollView(
              slivers: [
                SliverAppBar(
                  // 动态设置标题
                  title: Text(
                    orientation == Orientation.portrait ? 'PORTRAIT' : 'LANDSCAPE',
                  ),
                  pinned: true,
                ),
                // 页面其他内容区域
                const SliverFillRemaining(
                  child: Center(child: Text('页面主体内容')),
                )
              ],
            );
          },
        ),
      ),
    );
  }
}

注意事项

  • 安卓端修改系统导航栏颜色需要安卓5.0(API 21)及以上系统版本支持
  • 若需要同时调整状态栏图标/文字颜色,可以在SystemUiOverlayStyle中补充设置statusBarIconBrightness属性
  • 多页面场景建议把方向监听和系统栏设置逻辑封装到公共工具类中,避免重复代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:54:01