Search code examples
flutterdartflutter-dependenciesflutter-provider

Use a different colour for containers depending on the theme


I implemented a Dark Mode in my App with this Tutorial:

https://developer.school/flutter-dynamic-theming-with-provider/

Everything is working fine but i have a little Problem with a single Container.

I specified a specific color for it.

return Container(
  width: double.infinity,
  padding: EdgeInsets.symmetric(
    vertical: 32.0,
    horizontal: 24.0,
  ),
  margin: EdgeInsets.only(
    bottom: 20.0,
  ),
  decoration: BoxDecoration(
    color:  Color(0xFFD3D3D3),
    borderRadius: BorderRadius.circular(20.0),
  ),

Now i need to change the Color of the Container depending on my current Theme.

Thanks for the Help.


Solution

  • would be of best practice to use a bool value to switch from Dark to Light Mode

    then you can do this.

    import 'package:flutter/material.dart';
    
    class ThemeChanger with ChangeNotifier {
      bool isDark == false;
    
      void changeTheme() {
        isDark = !isDark;
        notifyListeners();
      }
    }
    

    then call it like this

    class MaterialAppWithTheme extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final theme = Provider.of<ThemeChanger>(context);
    
        return MaterialApp(
          home: HomePage(),
          theme: theme.isDark == false ? ThemeData.light() : ThemeData.dark(),
        );
      }
    }
    

    to change a Container style

    class MaterialAppWithTheme extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        final theme = Provider.of<ThemeChanger>(context);
    
        return Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(
            vertical: 32.0,
            horizontal: 24.0,
          ),
          margin: EdgeInsets.only(
            bottom: 20.0,
          ),
          decoration: BoxDecoration(
            color: theme.isDark == false ? Color(0xFFD3D3D3) : Colors.black,
            borderRadius: BorderRadius.circular(20.0),
          ),
        );
      }
    }