Search code examples
fluttercolorsstatusbarnavigationbardarkmode

Change color of system navigation and status bar when entering the dark mode in flutter


I want to change the color of the system navigation and status bar when entering the dark mode.

This is my code:

void main() async {
SystemChrome.setSystemUIOverlayStyle(
SystemUiOverlayStyle(
  statusBarBrightness: Brightness.dark,
  statusBarColor: Colors.white,
  statusBarIconBrightness: Brightness.dark,
  systemNavigationBarColor: Colors.white,
  systemNavigationBarDividerColor: Colors.white,
  systemNavigationBarIconBrightness: Brightness.dark,
),
);
...
}

I use SystemChrome and it works fine. But my problem is, I can only change the color manual via code, not when switching to dark or light mode or when I use the system settings.


Solution

  • After trying many things, I found the following solution to my problem. I don't know if it's the cleanest solution, but it works. This solution is interesting for those who don't use an AppBar like in my case.

    The trick is as follows ...

    @override
    Widget build(BuildContext context) {
     Theme.of(context).scaffoldBackgroundColor == Colors.white
        ? _lightStatusAndNavigationBar()
        : _darkStatusAndNavigationBar();
    return Scaffold(
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
    ...
    }
    

    The query is in the build of my class, in which I have the NavigationBar of my app. All other screens are connected there.

    Using Theme.of (context) .scaffoldBackgroundColor, I ask which design should be used for the status and navigation bar.

    These are the two functions for the different colors:

    void _darkStatusAndNavigationBar() {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarBrightness: Brightness.light,
        statusBarColor: Colors.grey.shade900,
        statusBarIconBrightness: Brightness.light,
        systemNavigationBarColor: Colors.grey.shade900,
        systemNavigationBarDividerColor: Colors.grey.shade900,
        systemNavigationBarIconBrightness: Brightness.light,
      ),
    );
    }
    
     void _lightStatusAndNavigationBar() {
    SystemChrome.setSystemUIOverlayStyle(
      SystemUiOverlayStyle(
        statusBarBrightness: Brightness.dark,
        statusBarColor: Colors.white,
        statusBarIconBrightness: Brightness.dark,
        systemNavigationBarColor: Colors.white,
        systemNavigationBarDividerColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.dark,
      ),
    );
    }
    

    If something is still incomprehensible, just ask. :)