Home > Mobile >  How to change color based on theme flutter
How to change color based on theme flutter

Time:02-14

I'm trying to change my container's color based on the system theme mode. Is there a way to change it using conditional if?

Here is the code:

     Container(
            color: //this is what I'm trying to change based on the theme,
            padding: EdgeInsets.only(right: 10, left: 10, top: 7, bottom: 25),
            child: Row(
              children: [
                Flexible(
                          ...

And this is my theme_provider:

class MyThemes {
  static final darkTheme = ThemeData(
    ...
  );

  static final lightTheme = ThemeData(
    ...
  );
}

CodePudding user response:

Use color: Theme.of(context).colorScheme.colorName

 Container(
     color: Theme.of(context).colorScheme.primary,//replace primary with your colorName 

More about using theme.

CodePudding user response:

If you are trying to change theme using provider proceed with following code and structure hope it will work for you.

final darkTheme = ThemeData(
scaffoldBackgroundColor: Colors.grey.shade900,
primaryColor: Colors.black,
colorScheme: ColorScheme.dark(),
iconTheme: IconThemeData(color: Colors.blue, opacity: 0.8),
primarySwatch: Colors.grey,
);

final lightTheme = ThemeData(
scaffoldBackgroundColor: Colors.white,
primaryColor: Colors.white,
iconTheme: IconThemeData(color: Colors.red, opacity: 0.8),
primarySwatch: Colors.blue,
);

Then create a class with ChangeNotifier

class ThemeProvider with ChangeNotifier {
  ThemeData themesData;
  ThemeProvider(this.themesData);

  getTheme() => themesData;

  setTheme(ThemeData themeData) async {
    print('Inside set theme');

    themesData = themeData;
    notifyListeners();
  }
}

In your View write the following code to toogle the theme and call this function with Button or Switch whatever you want to use

void onThemeChanged(bool value, ThemeProvider themeNotifier) async {
value ? themeNotifier.setTheme(darkTheme) : themeNotifier.setTheme(lightTheme)}

And now you can change the color based on the selected,

 final themeNotifier = Provider.of<ThemeProvider>(context);

 Color ContainerColor = themeNotifier.getTheme() == darkTheme ? Colors.grey[700] : Colors.blue[400];

Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: ContainerColor
        ),

CodePudding user response:

Try to use computed property in the development. If you change any property, that will be refreshing and you can see data changes directly

ThemeData get darkTheme => ThemeData(
    ...
  );
  • Related