Introduction ๐๐ป
Designers always design custom UI, which cannot be implemented using Material widgets of Flutter. Recently, I got a design in which I was supposed to give a multi color hint text in a TextField.
Problem ๐ค
The TextField widget of Flutter has different arguments like:
Controller
Style
OnChanged
decoration and much more
InputDecoration class is used to define the decoration in a TextField. The class has hintText as an argument which is of type string, and a String can be of a single color.
Approach
As we know that we can give multiple colors to a text by using Text.rich class which takes TextSpan as a child. In the TextSpan we can define multiple text with different styles. For example:
Text.rich(
TextSpan(
text: "Hello",
style: TextStyle(color: Colors.black, fontSize: 16),
children:[
TextSpan(
text: "World",
style: TextStyle(color: Colors.red, fontSize: 18),
),
],
),
);
Output:
Now, as we know how to give multi color text we can implement this with our text field, but the above implementation is based on a Widget and hintText is a String.
Solution
The solution for the problem using the defined approach is as follows:
Container(
padding: const EdgeInsets symmetric (horizontal: 20),
child: Row(
children: [
Expanded (
child: Stack(
alignment: Alignment.centerLeft,
children:[
Visibility(
visible: iSHintTextVisible,
child: const Text.rich(
TextSpan (
text: 'Enter your ', style: TextStyle( fontSize: 14, color: Colors. black),
children: [
TextSpan (
text: 'username', style: TextStyle( fontSize: 14, color: colors.red),
],
),
),
TextField(
controller: controller,
onChanged: (value) {
setState (() {
isHintTextVisible = value.isEmpty;
});
},
),
],
),
),
],
),
);
In this code, we are wrapping a TextField in a Stack and at the top of the stack we have the Text.rich widget (as demonstrated in the approach) which is having the desired colorful hint text. We did not given the hintText so it will be null by default. The visibility is used to hide the text once we are writing in the textfield.
Conclusion
We used 4 basic flutter widgets to solve this problem:
Stack
Visibility
TextRich
TextField
In case of any queries do reach out to me on my email (ashutoshkapoor8965@gmail.com)
If you liked the blog, do hit a like and give your valuable comments.
Thank you โจ