Skip to content

Instantly share code, notes, and snippets.

@jibiel
Created April 3, 2021 03:48
Show Gist options
  • Save jibiel/f2d0b101fb788b032682c7a063446f30 to your computer and use it in GitHub Desktop.
Save jibiel/f2d0b101fb788b032682c7a063446f30 to your computer and use it in GitHub Desktop.
Dark Mode-aware asset images in Flutter
/// lib/utilities/assets.dart
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
/// Usage:
///
/// The image file is located at lib/assets/images/path/to/image.png.
///
/// 1. Image has no dark mode variant.
///
/// Assets.image('path/to/image.png');
///
/// 2. Image has a dark mode variant.
///
/// Dark mode variant should be placed at lib/assets/images/dark_mode/path/to/image.png.
///
/// Assets.image('path/to/image.png', isDarkModeAware: true);
///
abstract class Assets {
static AssetImage image(String imagePath, {bool isDarkModeAware}) {
final isDarkMode = isDarkModeAware &&
SchedulerBinding.instance.window.platformBrightness == Brightness.dark;
return isDarkMode
? AssetImage('$_imagesFolder/dark_mode/$imagePath')
: AssetImage('$_imagesFolder/$imagePath');
}
static const _imagesFolder = 'lib/assets/images';
}
@MihMihai
Copy link

This workaround no longer works after the merge of flutter/flutter@cb5b5c34. You can see a short discussion here: flutter/flutter#121474.

As far as I know, you'll have to manually add every variant to pubspec.yaml or use a different naming convention (e.g.: suppose you have mountain.png as a light theme image, then you'll need a mountain-dark.png or mountain_dark.png (or whatever you like) for both images to be detected by Flutter properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment