【问题标题】:Display a few words in different colors in Flutter在 Flutter 中显示几个不同颜色的单词
【发布时间】:2018-11-06 04:41:06
【问题描述】:

我正在编写一个应用程序,它以不同的颜色显示几个单词。

我尝试使用插件 flutter_html_view 加载 HTML 文件,但该插件不支持样式(内联)。我也尝试过使用markdown。

我怎样才能做到这一点?

【问题讨论】:

  • 我想出了一个办法,我现在正在使用 RichText。

标签: android flutter dart text inline


【解决方案1】:

使用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)),
    ],
  ),
 );

【讨论】:

    【解决方案2】:

    如下图所示,使用 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)),
                ],
              ),
            ),
          ),
        );
      }
    }
    

    【讨论】:

      【解决方案3】:

      您可以通过使用带有TextStyle classRichText 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)),
         ]),
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-22
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 2015-11-03
        • 1970-01-01
        • 2012-11-29
        • 2016-02-24
        相关资源
        最近更新 更多