首页 > 建站教程 > APP开发,混合APP >  Flutter如何修改和设置状态栏颜色正文

Flutter如何修改和设置状态栏颜色

    手机状态栏,即手机顶部显示电池、网络、时间、信号等的位置,沉浸式状态下,状态栏的背景可能是深色,也可能是浅色,这时如果状态栏里面的内容文字也是和背景一样黑色或白色(只有这两种色),可能会导致看不清楚,需要设置与背景色明度相反的颜色。
在Flutter的系统文件system_chrome.dart中,有两段代码用来更改状态栏内容的颜色是黑色(dark)还是白色(light):

亮色(白色)
// 系统状态栏内容使用亮色(即白色)绘制,适用于深色背景的应用:
  static const SystemUiOverlayStyle light = SystemUiOverlayStyle(
    systemNavigationBarColor: Color(0xFF000000),
    systemNavigationBarDividerColor: null,
    statusBarColor: null,
    systemNavigationBarIconBrightness: Brightness.light,
    statusBarIconBrightness: Brightness.light,
    statusBarBrightness: Brightness.dark,
  );
深色(黑色)
// 系统状态栏内容使用深色(即黑色)绘制,适用于浅色背景的应用:
  static const SystemUiOverlayStyle dark = SystemUiOverlayStyle(
    systemNavigationBarColor: Color(0xFF000000),
    systemNavigationBarDividerColor: null,
    statusBarColor: null,
    systemNavigationBarIconBrightness: Brightness.light,
    statusBarIconBrightness: Brightness.dark,
    statusBarBrightness: Brightness.light,
  );
如何使用:
1、引入material包和services包
import 'package:flutter/material.dart';
// 必须引入services包,才能使用 SystemChrome
import 'package:flutter/services.dart';
2、设置白色状态栏
void main() {
  runApp(MyApp());
  //白色
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.light);
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '我爱模板网',
      home: Scaffold(
        backgroundColor: Colors.blue,
        body: Container(),
      ),
    );
  }
}
3、设置黑色状态栏:
void main() {
  runApp(MyApp());
  //黑色
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '我爱模板网',
      home: Scaffold(
        backgroundColor: Colors.white,
        body: Container(),
      ),
    );
  }
}