-
-
Save jibiel/f2d0b101fb788b032682c7a063446f30 to your computer and use it in GitHub Desktop.
/// 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'; | |
} |
Note: SchedulerBinding.instance.window.platformBrightness
in my case returns the device brightness mode.
Since I'm overriding the theme mode with custom state management (to enable in-app theme switching [system/light/dark]). I needed to check the theme mode from state management first then check for device brightness mode (if the user chosen system theme)
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.
Make sure flutter/flutter#44482 is unresolved. Otherwise, this workaround is unnecessary.