tajihiro
tajihiro

Reputation: 2443

How to manage colors in Flutter

I would like to change page color to black in main.dart. I also want my other pages' background color to be black.

However the other components in Page 1-3 like TextFormField border are black colors. This would make it render invincible because the background color is black. How would I be able to change the TextFormField border's color when my background color is black?

main.dart
 MaterialApp
   ThemeData(
     scaffoldBackgroundColor: Colors.black,
   )
   home: Scaffold
     body: Page01


Page01.dart       Page02.dart       Page03.dart

What is the smartest way all components colors are set.

Upvotes: 1

Views: 1646

Answers (2)

JustCodeNinja
JustCodeNinja

Reputation: 79

Define a class AppTheme with static variable.

class AppTheme {
static Color backgroundColor = Colors.black ;
static Color textFieldBorderColor = Colors.white ;
}

use AppTheme.backgroundColor to provide ThemeData

main.dart
 MaterialApp
   ThemeData(
     scaffoldBackgroundColor: AppTheme.backgroundColor,
   )
   home: Scaffold
     body: Page01

and AppTheme.textFieldBorderColor to provide textField Border Color

decoration: InputDecoration(
  color: AppTheme.textFieldBorderColor,
),

Upvotes: 2

CoderUni
CoderUni

Reputation: 6134

One way you can do this is set a variable in your SharedPreferences to let your app know when you want to change your main.dart's background color to black or not. SharedPreferences saves that value to the local storage so it remembers your preference even after you close the app. Don't forget to import the SharedPreferences package: https://pub.dev/packages/shared_preferences#-readme-tab-

You can set a variable in SharedPreferences like this:

var prefs = await SharedPreferences.getInstance(); //instantiate shared preferences
prefs.setBool("key",false) //set a boolean using key value pairs

After that you have to get the value by calling a function, preferably in initState()

bool bg_gray=false; //place this on top of widget build
getValue() async{
 if (prefs.getBool("key") == null){ //retrieve the value
     bg_grey=false;
 }
 bg_gray=prefs.getBool("key");//retrieve the value
}

Now that you retrieved your value, simply use ternary operators to set the color of your TextFormField background color

decoration: InputDecoration(
  color: bg_gray? Colors.white:Colors.grey,
),

Upvotes: 0

Related Questions