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,
);
}
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.findAncestorStateOfType<_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');
Declare the font in the pubspec.yaml
flutter:
fonts:
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Italic.ttf
style: italic
- family: RobotoMono
fonts:
- asset: fonts/RobotoMono-Regular.ttf
- asset: fonts/RobotoMono-Bold.ttf
weight: 700
Set a font as the default
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Custom Fonts',
// Set Raleway as the default app font.
theme: ThemeData(fontFamily: 'Raleway'),
home: MyHomePage(),
);
}
}
For more reference Flutter Documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With