Flutter: Where should I call SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark)

The reason behind this is the fact that your new screen will have its own lifecycle and thus, might use another color for the status bar.

You can call SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark) in your initState method but that won't trigger after a stacked screen is popped. There are two problems here, you can, however, call that back again after returning from a screen pop(). Simple enough right? Almost there.

When you press the back button on the AppBar widget, will return immediately from your Navigator.of(context).push(someroute), even if the navigation animation is still being rendered from the stacked screen. To handle this, you can add a little "tweak" that will set the status bar color again after 500 milseconds, that should be enough for the animation to fully complete. So, you'll want something more or less like this:

class HomeScreen extends StatefulWidget {
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  void initState() {
    _updateAppbar();
    super.initState();
  }

  void _updateAppbar() {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle.dark);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: RaisedButton(
            child: Text('Navigate to second screen'),
            onPressed: () => Navigator.of(context)
                .push(MaterialPageRoute(builder: (BuildContext context) => SecondScreen()))
                .whenComplete(() => Future.delayed(Duration(milliseconds: 500)).then((_) => _updateAppbar()))));
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
    );
  }
}

Although this works, I'm still curious to know if someone knows a better way to handle this though and keep a status bar color binding to each screen.

Tags:

Dart

Flutter