Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: RichText does not work with theme

I am trying to display some text in different colors. I learned about the RichText widget and used it as follows;

Future<List<TextSpan>> listOfEventsAtDay({String day, String monthNum}) async {
  final result = await DatabaseHelper.instance
      .queryForEventsAtDay(mnth: monthNum, dy: day);
  List<TextSpan> textSpans = [];
  int count = result.length;
  for (int i = 0; i < count; i++) {
    final String string = "-${result[i]['year']}: ${result[i]['title']}\n";
    textSpans.add(TextSpan(
        text: string,
        ));
  }

  return textSpans;
}

which is later called on;

ListTile( title: RichText(text: TextSpan(children: snapshot.data),

I don't want any complex stylings for now. In dark mode, the text should be in white, and in the light mode, it should be in black. That's all. But problem is, the text is always white. Why doesn't it adjust with brightness settings? Is there any way to accomplish this? Please help me...

like image 893
mig001 Avatar asked Jul 14 '26 02:07

mig001


2 Answers

You can use Text.rich instead of RichText. Text.rich is using default TextStyle.

https://api.flutter.dev/flutter/widgets/Text/Text.rich.html

Text.rich(
  TextSpan(
    text: 'Welcome'
    children: [
      TextSpan(text: 'to the'),
      TextSpan(
        text: 'Jungle',
        style: TextStyle(fontWeight: FontWeight.bold),
      ),
    ],
  ),
)
like image 180
DrzwiPercepcji Avatar answered Jul 17 '26 19:07

DrzwiPercepcji


Found a solution.

style: DefaultTextStyle.of(context).style

Full snippet;

Future<List<TextSpan>> listOfEventsAtDay({String day, String monthNum, BuildContext context}) async {
  final result = await DatabaseHelper.instance
      .queryForEventsAtDay(mnth: monthNum, dy: day);
  List<TextSpan> textSpans = [];
  int count = result.length;
  for (int i = 0; i < count; i++) {
    final String string = "-${result[i]['year']}: ${result[i]['title']}\n";
    textSpans.add(TextSpan(
        text: string,
        style: DefaultTextStyle.of(context).style,
        ));
  }

This fixed it.

like image 27
mig001 Avatar answered Jul 17 '26 18:07

mig001



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!