Flutter: I want to apply font on runtime to whole

2020-07-22 17:23发布

问题:

I have language selection settings in my app. On the basis of language selection English or Arabic , I want to use different font family. I did it inside MaterialApp() but it will not achieve my target.

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'OnlyTick',  
      theme: ThemeData(
        primarySwatch: Colors.indigo,
        buttonColor: Colors.indigo,
        iconTheme: IconThemeData(color: Colors.indigo),
        accentIconTheme: IconThemeData(color: Colors.indigoAccent),
        fontFamily: appLang == 'English'?'Proxima':'DroidKufi',
      ),
      debugShowCheckedModeBanner: false,
      home: SplashScreenPage(),
      localizationsDelegates: [
        // const TranslationsDelegate(), //TODO: will create it later, refer https://www.didierboelens.com/2018/04/internationalization---make-an-flutter-application-multi-lingual/
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', ''),
        const Locale('ar', ''),
      ],
      // setHome(),
      routes: routes,
    );
  }

回答1:

Assuming you're running your project using the following structure:

    void main() => runApp(new App());

Add the function setAppFontFamily to your App class which will be responsible for changing you application fontFamily:

    class App extends StatefulWidget {
      App({Key key,}) :

     super(key: key);

     @override
     _AppState createState() => new _AppState();

      static void setAppFontFamily(BuildContext context, String _selectedFontFamily) {
      _AppState state = context.ancestorStateOfType(TypeMatcher<_AppState>());
         state.setState(() {
            state._fontFamily = _selectedFontFamily;
         });
      }


     }

After that add a local variable to your _AppState class or whatever the name you're currently using for your State class;

     String _fontFamily = 'Proxima' ; //Initial value before any selection is made

Then assign _fontFamily to the fontFamily property of your Material App Theme:

     theme: ThemeData(
     primarySwatch: Colors.indigo,
     buttonColor: Colors.indigo,
     iconTheme: IconThemeData(color: Colors.indigo),
     accentIconTheme: IconThemeData(color: Colors.indigoAccent),
     fontFamily: _fontFamily,
     ),

After doing all these steps, you'll be able to change the fontFamily of your app from anywhere in your application using the below line:

     App.setAppFontFamily(context, 'DroidKufi');


标签: flutter