Display a few words in different colors in Flutter
Asked Answered
A

2

42

I am writing an application which shows a few words in different colors in flutter.

I tried to load HTML files using the plugin flutter_html_view but that one doesn't support styles(inline). I also tried to use markdown.

How can I achieve this?

Amphimixis answered 27/5, 2018 at 12:3 Comment(1)
I figured out a way, I am now using RichText.Amphimixis
J
79

Use RichText class

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)),
    ],
  ),
 );
Jobie answered 27/5, 2018 at 12:56 Comment(0)
W
17

Use RichText, TextSpan and TextStyle as i explained in below picture.

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

enter image description here

Width answered 26/3, 2020 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.