单击按钮更改TextField中的文本格式



我希望用户可以选择将文本加粗、斜体、在中的文本上添加下划线和超链接单击按钮后的文本字段。

我已经实现了这一点,我需要一个选项,当用户点击图标按钮(在代码中定义(时,文本字段中的文本应该会改变。

PS-我已经尝试过zefyr包,但我需要在我自己的有状态小部件上实现这些功能,而不是zefyrScaffold。

我还没有尝试过制作一个存储文本格式属性(如FontWeight.Bold(的函数,然后将其与条件和布尔一起使用,因为我很肯定这不是最好的解决方案。

在这之后,我需要文本来保持它的状态,因为我将以base64格式对文本进行编码。所以,如果我更改文本格式,在我将其编码为base64后,其他用户的格式会相同吗?

TextField(
decoration: InputDecoration(
border: InputBorder.none,
hintText: 'Start Typing your Message here',
hintStyle: TextStyle(
fontSize: 17,
color: Theme.of(context).textTheme.subtitle.color
)
),
maxLines: null,
minLines: 1,
autocorrect: true,
keyboardType: TextInputType.multiline,
onChanged: (String str){
print(str);
},
style: TextStyle(
color: Theme.of(context).textTheme.title.color,
fontSize: 19,
),
),
Row(
children: <Widget>[
Expanded(
child: IconButton(
icon: Icon(LineIcons.times),
iconSize: 27,
onPressed: () {
bottomChangeFunc();
},
),
),
Expanded(
child: IconButton(
icon: Icon(LineIcons.bold),
iconSize: 27,
color: Theme
.of(context)
.iconTheme
.color,
onPressed: () {
},
),
),
Expanded(
child: IconButton(
icon: Icon(LineIcons.italic),
iconSize: 27,
color: Theme
.of(context)
.iconTheme
.color,
onPressed: () {
},
),
),
Expanded(
child: IconButton(
icon: Icon(LineIcons.underline),
iconSize: 27,
color: Theme
.of(context)
.iconTheme
.color,
onPressed: () {
},
),
),
Expanded(
child: IconButton(
icon: Icon(LineIcons.link),
iconSize: 27,
color: Theme
.of(context)
.iconTheme
.color,
onPressed: () {},
),
),
],
),

您可以使用枚举和一些样式常量来设置它。

enum TextMode {
normal,
bold,
italic,
underline,
// link,  <- I'm not sure what you want to have happen with this one
}
const normalStyle = TextStyle();
const boldStyle = TextStyle(fontWeight: FontWeight.bold);
const italicStyle = TextStyle(fontStyle: FontStyle.italic);
const underlineStyle = TextStyle(textDecoration: TextDecoration.underline);
// Helper method
TextStyle getStyle(TextMode mode) {
switch(mode) {
case TextMode.bold: return boldStyle();
case TextMode.italic: return italicStyle();
case TextMode.underline: return underlineStyle();
default: return normalStyle();
}
}

然后,您可以根据当前选择的枚举值在TextField上显示相关样式:

TextField(
...,
style: TextStyle(
color: Theme.of(context).textTheme.title.color,
fontSize: 19,
).merge(getStyle(currentMode)),
),

要更改样式,只需更改按钮处理程序中的当前FontMode

IconButton(
...
icon: Icon(LineIcons.bold),
onPressed: () => setState(() => currentMode = FontMode.bold),
),
// and so on for the other modes

存储和检索状态很容易,因为枚举基本上是美化的整数。

最新更新