[英]How can i change color of hashtags flutter on textformfield?
i want to change the input text color when i include hashtags(#) without changing the other texts colors that doesn't include hashtag我想在包含主题标签(#)时更改输入文本颜色,而不更改不包含主题标签的其他文本 colors
TextFormField(
minLines: 1,
maxLines:
5, // allow user to enter 5 line in textfield
keyboardType: TextInputType
.multiline, // user keyboard will have a button to move cursor to next line
controller:
postController.captionController,
decoration: const InputDecoration.collapsed(
hintText: 'caption',
hintStyle: TextStyle(
fontSize: 15,
)
),
style: const TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.bold),
validator: (value) {
return postController
.validateCaption(value!);
},
),
I was able to implement this feature by using rich_text_controller package.我能够通过使用rich_text_controller package 来实现这个功能。
Here is my example:这是我的例子:
class AppContent extends StatefulWidget {
const AppContent({Key? key}) : super(key: key);
@override
_AppContentState createState() => _AppContentState();
}
class _AppContentState extends State<AppContent> {
// Add a controller
late RichTextController _controller;
@override
void initState() {
_controller = RichTextController(
patternMatchMap: {
RegExp(r"\B#[a-zA-Z0-9]+\b"): TextStyle(color: Colors.cyan),
},
onMatch: (List<String> matches) {
// Do something with matches.
},
deleteOnBack: true,
);
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: [
TextField(
controller: _controller,
)
],
);
}
}
You can use the.contains() method like this:您可以像这样使用 .contains() 方法:
String myString = "#Text";
bool hasHash = myString.contains('#'); // yields true
Then in your TextStyle() use a ternary expression:然后在您的 TextStyle() 中使用三元表达式:
TextStyle(color:hasHash ? Colors.green : Colors.red;)
Now apply this to your input controller.现在将此应用于您的输入 controller。 See this link from the Flutter cookbock.请参阅 Flutter 烹饪箱中的此链接。 Here is the short form, I recommend to follow the steps from the docs step by step though:这是简短的表格,我建议逐步按照文档中的步骤进行操作:
final myController = TextEditingController();
创建 controller: final myController = TextEditingController();
TextField(controller: myController);
将其添加到表单中的字段: TextField(controller: myController);
myController.text
检索当前值: myController.text
bool hasHash = myController.text.contains('#')
使用上面的逻辑: bool hasHash = myController.text.contains('#')
TextStyle( color:hasHash? Colors.green: Colors.red;
Output 动态颜色: TextStyle( color:hasHash? Colors.green: Colors.red;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.