【发布时间】:2018-11-06 04:41:06
【问题描述】:
我正在编写一个应用程序,它以不同的颜色显示几个单词。
我尝试使用插件 flutter_html_view 加载 HTML 文件,但该插件不支持样式(内联)。我也尝试过使用markdown。
我怎样才能做到这一点?
【问题讨论】:
-
我想出了一个办法,我现在正在使用 RichText。
标签: android flutter dart text inline
我正在编写一个应用程序,它以不同的颜色显示几个单词。
我尝试使用插件 flutter_html_view 加载 HTML 文件,但该插件不支持样式(内联)。我也尝试过使用markdown。
我怎样才能做到这一点?
【问题讨论】:
标签: android flutter dart text inline
使用RichText类
var text = new RichText(
text: new TextSpan(
// Note: Styles for TextSpans must be explicitly defined.
// Child text spans will inherit styles from parent
style: new TextStyle(
fontSize: 14.0,
color: Colors.black,
),
children: <TextSpan>[
new TextSpan(text: 'Hello'),
new TextSpan(text: 'World', style: new TextStyle(fontWeight: FontWeight.bold)),
],
),
);
【讨论】:
如下图所示,使用 RichText、TextSpan 和 TextStyle。
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Center(
child: RichText(
text: TextSpan(
text: 'Default',
style: TextStyle(color: Colors.red), /*defining default style is optional */
children: <TextSpan>[
TextSpan(
text: ' bold', style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(
text: ' colorful',
style: TextStyle(color: Colors.lightGreenAccent)),
TextSpan(
text: ' large',
style: TextStyle(color: Colors.cyanAccent, fontSize: 40)),
],
),
),
),
);
}
}
【讨论】:
您可以通过使用带有TextStyle class 的RichText class 类来实现此目的
RichText小部件有助于回答和实现上述案例
RichText(
textAlign: TextAlign.center,
text: TextSpan(children: <TextSpan>[
TextSpan(
text: "I agree to the ",
style: TextStyle(color: Colors.black87)),
TextSpan(
text: "Terms and Conditions",
style: TextStyle(
color: Colors.deepPurple,
fontWeight: FontWeight.bold)),
]),
)
【讨论】: