Keywords: Flutter | TextField | underline color | InputDecoration | Theme
Abstract: A guide to changing the underline color of TextField in Flutter, exploring default theme settings and providing step-by-step solutions using InputDecoration properties like enabledBorder and focusedBorder, as well as Theme overrides, with detailed code examples.
Introduction
In Flutter development, TextField widgets are commonly used for user input. By default, the underline of a TextField is styled based on the app's theme, often appearing in blue. However, developers may need to customize this color to match specific design requirements. This article addresses how to change the underline color effectively.
Default Underline Color Behavior
The underline color of a TextField in Flutter is determined by the active color from the ThemeData. According to the Flutter source code, the color varies based on the theme brightness and focus state. For example, in light mode, the focused color uses the primaryColor, while in dark mode, it uses the accentColor. Understanding this default behavior is crucial for effective customization.
Solutions to Change Underline Color
Using InputDecoration Borders
The most straightforward method is to use the enabledBorder and focusedBorder properties of the InputDecoration. By setting these to UnderlineInputBorder with a custom BorderSide color, you can override the default underline color for both enabled and focused states.
Using Theme Overrides
Alternatively, you can wrap the TextField in a Theme widget to change the theme colors globally for that subtree. This approach is useful when you want to apply consistent styling across multiple widgets without repeating code.
Code Examples
Here is a code example based on the best answer from the provided Q&A data:
TextField(
decoration: InputDecoration(
hintText: "Enter your email",
labelText: "Email",
labelStyle: TextStyle(color: const Color(0xFF424242)),
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.cyan),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.cyan),
),
border: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.cyan),
),
),
)
This code sets the underline color to cyan for all states. Note that the border property is included for completeness, but enabledBorder and focusedBorder are sufficient in most cases.
For theme-based customization:
Theme(
data: ThemeData(
primaryColor: Colors.red,
accentColor: Colors.orange,
hintColor: Colors.green,
),
child: TextField(
decoration: InputDecoration(
hintText: "Enter your email",
labelText: "Email",
),
),
)
Conclusion
Changing the underline color of a TextField in Flutter can be achieved through InputDecoration properties or Theme overrides. The recommended approach is to use enabledBorder and focusedBorder for precise control. By understanding the default theme behavior, developers can effectively customize UI elements to meet design needs.