RichText does not style text as expected

The usage of DefaultTextStyle.of(context) would look if there is any DefaultTextStyle parent and fetch style from the parent. So, try wrapping the whole HomePage widget in a DefaultTextStyle widget with some style. Or make RichText a separate widget and wrap in DefaultTextStyle.

Example:

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DefaultTextStyle(style: Theme.of(context).textTheme.title, child: RichWidget()),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class RichWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
        text: 'Hello ',
        style: DefaultTextStyle.of(context).style,
        children: <TextSpan>[
          TextSpan(
              text: 'bold',
              style: TextStyle(fontWeight: FontWeight.bold)),
          TextSpan(text: ' world!'),
        ],
      ),
    );
  }
}

Hope this helps!


What you can do now is much simpler.

If you want to create a RichText with default TextStyle, just use Text.rich:

Text.rich(
  TextSpan(
    children: [
      TextSpan(text: 'Hello '),
      TextSpan(
        text: 'bold',
        style: TextStyle(fontWeight: FontWeight.bold),
      ),
      TextSpan(text: ' world!'),
    ],
  ),
)

  RichText(
      text: const TextSpan(
        text: 'Hello',
        style: TextStyle(
          fontFamily: 'Your App Font Family',
        ),
        children: [
          TextSpan(
            text: 'Bold',
            style: TextStyle(
              fontWeight: FontWeight.w500,
            ),
          ),
          TextSpan(
            text: 'word',
          ),
        ],
      ),
    )

You have to give the font family externally when you use RichText Widget, It is not taking the default font family from your app config.

Tags:

Flutter