How create global theme for colors and fonts in flutter
To create a global theme for colors and fonts in Flutter, you can utilize the Theme
widget provided by the Flutter framework. The Theme
widget allows you to define a common set of styles that will be applied throughout your app.
Here’s an example of how you can create a global theme for colors and fonts in Flutter:
- Define your color scheme:
// Define your color scheme
class AppColors {
static const primaryColor = Color(0xFF123456);
static const secondaryColor = Color(0xFF789ABC);
// Add more colors as needed
}
2. Define your font styles:
// Define your font styles
class AppFonts {
static const TextStyle heading = TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
);
static const TextStyle body = TextStyle(
fontSize: 16,
fontWeight: FontWeight.normal,
);
// Add more font styles as needed
}
3. Create a global theme:
// Create a global theme
ThemeData appTheme() {
return ThemeData(
primaryColor: AppColors.primaryColor,
accentColor: AppColors.secondaryColor,
textTheme: TextTheme(
headline1: AppFonts.heading,
bodyText1: AppFonts.body,
),
// Add more theme properties as needed
);
}
4. Wrap your app with the MaterialApp
widget and provide the global theme:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My App',
theme: appTheme(),
home: MyHomePage(),
);
}
}
With this setup, you can now use the defined colors and font styles throughout your app. For example:
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('My App'),
),
body: Center(
child: Text(
'Hello, world!',
style: Theme.of(context).textTheme.headline1,
),
),
);
}
}
By utilizing the Theme
widget and defining your global color scheme and font styles, you can easily maintain a consistent look and feel across your Flutter app.