Search code examples
flutterresponsive-designdarkmode

Flutter - Switching images depending on Theme


Hello I'm having trouble changing my Logo depending on the Theme. In Dark Theme I can't see the black outlines of my logo, whilst I can on white background in light theme mode.

Here's the main.dart Code Line:

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(builder: (context, constraints) {
      return OrientationBuilder(builder: (context, orientation) {
        SizeConfig().init(constraints, orientation);
        return MaterialApp(
          debugShowCheckedModeBanner: false,
          themeMode: ThemeMode.system,
          theme: AppTheme.lightTheme,
          darkTheme: AppTheme.darkTheme,

Theme customised in a seperate Theme file:

    static final lightTheme = ThemeData(
    scaffoldBackgroundColor: AppTheme.lightBackground,
    brightness: Brightness.light,
    primaryColor: blackText,
  );

  static final darkTheme = ThemeData(
    scaffoldBackgroundColor: AppTheme.darkBackground,
    brightness: Brightness.dark,
    primaryColor: whiteText,
  );

Here's the code where I want to switch between dark & light mode version of the image (2 different asset files):

InkWell(
            onTap: () {},
            child: CircularPercentIndicator(
                radius: 27 * SizeConfig.heightMultiplier, //250.0,
                lineWidth: 1.62 * SizeConfig.heightMultiplier, //15.0,
                percent: 1.0,
                animation: true,
                animationDuration: 8000,
                center: Padding(
                  padding: EdgeInsets.all(
                    5.4 * SizeConfig.heightMultiplier,
                  ), //50.0),
                  child: new SvgPicture.asset(Res.logoClear),
                ),
                progressColor: AppTheme.green,
                backgroundColor: AppTheme.lightGrey),
          )

Image ("logoClear") in the center of a circular PercentageView Widget. logoClear is a const string connected to the the image file path in a different .dart file


Solution

  • If you want to change dynamically the asset path, you can check the theme like this

    final brightness = MediaQuery.of(context).platformBrightness;
    final darkModeOn = (brightness == Brightness.dark);
    

    and depending the result pass the string path like this

    SvgPicture.asset((darkModeOn)
      ? 'your_path_for_dark_theme'
      : 'your_path_for_light_theme',
    

    and you can do the same for progress color and background color, return different value depending on current theme