Home > Software design >  How to have different status bar color in flutter for dark and light mode with safe area?
How to have different status bar color in flutter for dark and light mode with safe area?

Time:11-02

I have my Scaffold in Safe Area widget and I want to apply status bar theming but I guess Safe Area isn't allowing to do so.

HomePage:

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: Theme.of(context).brightness == Brightness.light
                ? const AssetImage('assets/images/lgt_bg.png')
                : const AssetImage('assets/images/drk_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            title: const Text(
              "MnbPub",
            ),
          ),
          body: Container(),
        ),
      ),
    );

Theme file:

class LightTheme {
  static final apptheme = ThemeData.light().copyWith(
    appBarTheme: const AppBarTheme(
      systemOverlayStyle: SystemUiOverlayStyle(
        statusBarColor: Color.fromARGB(255, 254, 222, 225),
        statusBarIconBrightness: Brightness.light,
        systemNavigationBarColor: Color.fromARGB(255, 254, 222, 225),
        systemNavigationBarIconBrightness: Brightness.light,
      ),
...

Also I want the change to happen globally and not only for home page.

Any help?

CodePudding user response:

I've created a custom widget called the ThemedStatusBar that automatically ensures your status bar is the proper color based on the app's theme. Simply wrap your Scaffold with it:

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

class ThemedStatusBar extends StatelessWidget {
  const ThemedStatusBar({super.key, required this.child});

  final Widget child;

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion(
      value: Theme.of(context).brightness == Brightness.dark
          ? SystemUiOverlayStyle.light
          : SystemUiOverlayStyle.dark,
      child: child,
    );
  }
}
 

Your order of widgets should be ThemedStatusBar -> Scaffold -> then somewhere lower (not necessarily directly) a SafeArea -> <THE_REST_OF_YOUR_WIDGETS>

CodePudding user response:

Put the SafeArea around the Container in the body parameter.

The SafeArea will always clip your app bar & status bar theme if it is around the entire Scaffold.

  • Related