Wouter Vandenputte
Wouter Vandenputte

Reputation: 2093

Flutter: RichText with darktheme

I use some RichText throughout my application to switch colors between text and display widgets in between.

E.g.

RichText(
 text: TextSpan(text: 'text1', style: TextStyle(color: Colors.black), 
 children: [
   WidgetSpan(alignment: PlaceholderAlignment.middle, child: SomeWidget()),
   TextSpan(text: 'text2', style: TextStyle(color: Colors.blue),
   WidgetSpan(alignment: PlaceholderAlignment.middle, child: Icon(Icons.someIcon)),
   TextSpan(text: 'text3'),
  ]
));

The problem now is that when switching to dark mode, the black test is contrasted to a black background and thus invisible. The regular Text('some text') widget will automatically display black by default but will become white in dark mode. How can I achieve the same or something similar when using RichtText?

Upvotes: 1

Views: 938

Answers (1)

Josip Domazet
Josip Domazet

Reputation: 2870

Well you defined your RichText like this:

TextSpan(text: 'text1', style: TextStyle(color: Colors.black)

As you know the color argument that you pass to a Widget has the highest priority, therefore, your TextSpan will always be black.


One solution is instead of hardcoding the color you can do this:

Theme.of(context).textTheme.bodyText2?.color

If we look at the definition of this theme it looks like this:

/// The default text style for [Material].
TextStyle? get bodyText2 => bodyMedium;

If you use this approach your TextSpan and normal Text widgets should have the same color. In general one should always prefer working with themes over hardcoding colors. If your user switches to dark mode the theme will switch too and therefore, all styles should be switched correctly as well.

Upvotes: 2

Related Questions