27/09/2025
ADDING STYLE TO FLUTTER PROJECTS
Adding style to Flutter projects involves several key methods and best practices to achieve a consistent and visually appealing user interface.
1. Themes:
App-wide Themes: Define a ThemeData object within your MaterialApp to apply a consistent theme across your entire application. This includes colors, font styles, and other visual properties for various Material widgets.
Code
MaterialApp(
title: 'My App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
textTheme: TextTheme(
displayLarge: TextStyle(fontSize: 72, fontWeight: FontWeight.bold),
// ... other text styles
),
),
home: MyHomePage(),
);
Local Themes: Use the Theme widget to apply a different theme to a specific part of your widget tree, overriding the global theme for that section.
2. Custom Fonts:
Add custom font files (e.g., .ttf) to your project's fonts directory.
Declare these fonts in your pubspec.yaml file under the flutter section.
Code
flutter:
fonts:
- family: MyCustomFont
fonts:
- asset: fonts/MyCustomFont-Regular.ttf
- asset: fonts/MyCustomFont-Bold.ttf
weight: 700
Apply the custom font using TextStyle properties (e.g., fontFamily: 'MyCustomFont').
3. Styling Individual Widgets:
Text: Use TextStyle within a Text widget to customize properties like fontSize, color, fontWeight, fontStyle, wordSpacing, etc.
Code
Text(
'Hello, Flutter!',
style: TextStyle(
fontSize: 24,
color: Colors.blue,
fontWeight: FontWeight.bold,
),
);
Containers and other Widgets: Utilize widget properties like color, decoration, padding, margin, borderRadius, boxShadow, etc., to style various UI elements.
4. Organizing Styles:
Separate Files: Create dedicated files (e.g., app_colors.dart, app_text_styles.dart) to define and organize your colors, text styles, and other theme-related constants for better maintainability and reusability.
Reusable Classes/Functions: Define custom classes or functions to encapsulate common styles, promoting modularity and reducing code duplication.
5. Global CSS (for Flutter WebViews):
When working with WebView widgets in Flutter, you can use CSS files to style the web content displayed within them, similar to traditional web development.
Best Practices:
Avoid Hardcoding: Use constants or theme properties instead of hardcoding values directly in your widgets.
Modularity: Keep your styles modular and reusable.
Consistency: Strive for a consistent look and feel throughout your application by leveraging themes and organized styling.