【问题标题】:Flutter: Is it possible to format (bold, italicize, etc) with-in the string only before passing to the text widget?Flutter:是否可以仅在传递给文本小部件之前在字符串中格式化(粗体、斜体等)?
【发布时间】:2018-12-08 03:59:19
【问题描述】:

例如:

String desc = "<bold>Hello<bold> World";
new Text(desc);

【问题讨论】:

标签: string dart flutter


【解决方案1】:

您可以为此使用flutter_html_view 包。

String html = '&lt;bold&gt;Hello&lt;bold&gt; World';

new HtmlTextView(data: html);

如果您只是想要不同的样式,您可以使用带有TextSpansRichText 小部件,例如this

new RichText( text: new TextSpan(text: 'Hello ', style: DefaultTextStyle.of(context).style, children:          
<TextSpan>[
new TextSpan(text: 'bold', style: new TextStyle(fontWeight: FontWeight.bold)), 
new TextSpan(text: ' world!'), 
], ), )

【讨论】:

    【解决方案2】:

    您可以拥有一个 RichText 小部件,它可以将 TextSpan 作为其子级。然后 TextSpan 可以将多个 TextSpan 作为其子级,并且每个 TextSpan 可以有自己的样式和手势检测器。下面是如何使用 onTap 手势检测器创建“阅读更多”隐私声明的示例。这将给出如下所示的输出,当单击“读取”时,应用程序将被路由到“/privacy”页面。

    class _LoginViewState extends State<LoginView> {
      TapGestureRecognizer _routeToPrivacy;
    
      @override
      void initState() {
        super.initState();
        _routeToPrivacy= TapGestureRecognizer()..onTap = routeToPrivacy;
      }
    
      void routeToPrivacy() {
        Navigator.pushNamed(context, '/privacy');
      }
    
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: Center(
            child: Container(
              width: 200,
              child: Column(  
                  RichText(
                    text: TextSpan(
                      style: TextStyle(
                          color: Colors.blue.shade900,
                          fontFamily: GoogleFonts.lato().fontFamily),
                      children: [
                        TextSpan(
                          text: 'By signing up you accepts our privacy policy. ',
                        ),
                        TextSpan(
                            recognizer: _routeToPrivacy,
                            text: "Read",
                            style: TextStyle(
                                color: Colors.red.shade500,
                                fontWeight: FontWeight.bold))
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    

    【讨论】:

      【解决方案3】:

      StyledText 小部件可用于此。

      StyledText(text:desc, 
                 styles: { 'bold': ActionTextStyle(fontWeight: FontWeight.bold)},
                );
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      相关资源
      最近更新 更多