Home > Net >  Applying borderSide color to TextField only when darkTheme is enabled
Applying borderSide color to TextField only when darkTheme is enabled

Time:11-26

I was wondering if there was a way to apply a specific color to the enabledBorder of a TextField() when darkTheme is enabled. This is my TextField():

TextField(
  obscureText: true,
  decoration: InputDecoration(
    border: OutlineInputBorder(),
    labelText: 'Password',
  ),
),

However, using the following code in my dark theme will apply a border coloring to every enabledBorder, which I want to avoid for obvious reasons:

inputDecorationTheme: InputDecorationTheme(
  enabledBorder: OutlineInputBorder(
  borderSide: BorderSide(color: Colors.grey[700]!)
  )
),

I also do not want to have the same color applied when using the regular theme, so I cannot apply it to just the TextField(). What can I do to solve this problem?

CodePudding user response:

You can check if the theme is darkTheme or not in the TextField and give the border color accordingly. First we get the current theme data. Place the below code inside build:

ThemeData themeData = Theme.of(context);

Now we can check the value of Brightness to determine if dark theme is enabled. If dark theme is enabled, the value of brightness will be light. So your TextField would be:

TextField(
  obscureText: true,
  decoration: InputDecoration(
    enabledBorder: Theme.of(context).brightness == Brightness.light ? OutlineInputBorder(
        borderSide: BorderSide(color: Colors.grey[700]!)
    ) : InputBorder.none,
    labelText: 'Password',
  ),
),

CodePudding user response:

The answer of Suvash inspired me to the following code:

TextField(
  obscureText: true,
  decoration: Theme.of(context).scaffoldBackgroundColor == bgColorDark
  ? InputDecoration(
    enabledBorder: OutlineInputBorder(
    borderSide: BorderSide(color: Colors.grey[700]!)
    ),
    border: OutlineInputBorder(),
    labelText: 'Password',
  )
  : InputDecoration(
    border: OutlineInputBorder(),
    labelText: 'Password',
  ),
),

Note that bgColorDark is a dark background color used in my dark theme. I am aware that this creates some code repetition, but this is easier to read in my opinion.

  • Related