Search code examples
flutterdartfontsstylesfont-family

Change numbers only font family in flutter


I have a complete application and I'm using a custom font.

Is there a way to use two font families one for Text and one for numbers only?

Bearing in mind that the texts and numbers from API and they are mixed.


Solution

  • Here's an example of how to do it. I used GoogleFonts for getting different fonts but you can replace it with any style you want to get the font you need. As you can see you can even adjust colors and sizes like this

    import 'package:flutter/material.dart';
    import 'package:google_fonts/google_fonts.dart';
    
    void main() => runApp(const MyApp());
    
    class MyApp extends StatelessWidget {
      const MyApp({super.key});
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
            home: Scaffold(
                body: Center(
                    child: Column(children: [
          MyText('test test 123 32123 tter213'),
          MyText('qqqqqq'),
          MyText('11111111'),
          MyText('123bla, 123 blablabla'),
        ]))));
      }
    }
    
    class MyText extends StatelessWidget {
      final String text;
    
      MyText(this.text, {Key? key}) : super(key: key);
    
      final RegExp regExp = RegExp(r'(?<=\d)(?=\D)|(?=\d)(?<=\D)');
      final RegExp number = RegExp(r'\d');
    
      late final List<String> split = text.split(regExp);
    
      @override
      Widget build(BuildContext context) {
        return RichText(
          text: TextSpan(
              children: split
                  .map((e) => number.hasMatch(e)
                      ? TextSpan(
                          text: e,
                          style: GoogleFonts.vampiroOne(
                              color: Colors.red, fontSize: 30),
                        )
                      : TextSpan(
                          text: e,
                          style: GoogleFonts.poppins(),
                        ))
                  .toList()),
        );
      }
    }
    

    Output:

    enter image description here