在Flutter中以不同的颜色显示几个单词

Caf*_*olf 2 android flutter

我正在编写一个应用程序,它会在颤动中显示不同颜色的几个单词.

我尝试使用插件flutter_html_view加载HTML文件但是那个不支持样式(内联).我也尝试过降价.

我怎样才能做到这一点?

Shy*_*hil 19

使用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)),
    ],
  ),
 );
Run Code Online (Sandbox Code Playgroud)


met*_*tis 9

使用 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)),
            ],
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Par*_*iya 5

您可以通过使用带有TextStyle 类RichText 类来实现此目的

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)),
   ]),
)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明