Search code examples
flutterdartdarkmode

Switch images on dark mode with flutter


I would like to know how to implement switching image on dark mode and light mode. I don't image to put toggle on app. Just switch the dark mode on setting in iOS or Android.

Here is the sample code on light mode. I want to know how to change or add codes to switch logo.png to darkmode_logo.png.

*darkmode_logo.png is for logo on dark mode.

V/r,

import 'package:flutter/material.dart';

class TopPage extends StatefulWidget {
  const TopPage({Key key}) : super(key: key);

  @override
  _TopPageState createState() => _TopPageState();
}

class _TopPageState extends State<TopPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Theme.of(context).backgroundColor,
      drawer: SlideMenu(),
      appBar: AppBar(
        centerTitle: true,
        title: Image.asset(
          'assets/images/header_icn/logo.png',
          fit: BoxFit.cover,
        ),
      ),
      body: Container(),
    );
  }
}

Solution

  • Check the theme mode using the Brightness property of the theme.

    final isDarkMode = Theme.of(context).brightness == Brightness.dark;
    

    Then change the image using the isDarkMode.

    Image.asset(
      isDarkMode
          ? 'assets/images/header_icn/darkmode_logo.png'
          : 'assets/images/header_icn/logo.png',
      fit: BoxFit.cover,
    )