Search code examples
flutterdartflutter-layoutwidgetflutter-dependencies

Dynamic Font Size Changes - Flutter


Here, What I needed is :

"Changing Overall Application Font's Size" according to selected values from Application's Setting as below :

enter image description here

Here, I am not talking about the support of font size in different screen sizes of device. This is different thing, means font size should change according to selected values as 'small' , 'medium', 'large'.

Is there any better way to achieve this? Thanks.


Solution

  • Use ChangeNotifierProvider and ChangeNotifier. This will allow to rebuild your entire app if you wrap your root widget i.e. MyApp which contains your MaterialApp within the ChangeNotifierProvider. Below is a sample piece of code:

    // Changable Settings class
    class AppSettings extends ChangeNotifier
    {
       double fontSize;
       // TextStyle textStyle;
       
        void update() {     
            notifyListeners();
        }
    }
    
    // ChangeNotifier setup in main
    main()
    {
        runApp(
          MultiProvider(
            providers: [
              ChangeNotifierProvider(create: (_) => AppSettings()),
            ],
            child: MyApp(),
          ),
        );
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
       Consumer<AppSettings >(builder: (context, appSettings, child) {
          return MaterialApp(
            theme: ThemeData().copyWith(   // Apply the theme to whole app
              textTheme: TextTheme(
                titleSmall: Theme.of(context)
                    .textTheme
                    .titleSmall
                    .copyWith(fontSize: appSettings.fontSize), // Font Size apply
              ),
            ),
            home: homePage,
          );
        });
      }
    }
    
    // Get the change from user from the settings page
    class SettingsPage extends StatelessWidget {
    
      @override
      Widget build(BuildContext context) {
       ...
      }
      
      onSave(){
        var appSettings = Provider.of<AppSettings>(context);
        appSettings.fontSize = fontSize; // from the UI
        appSettings.update();
      }
    }
    

    Hope it gives some start point to you.