Sub topic 2
Resolution-aware images and custom fonts
This chapter assumes you can edit pubspec.yaml, run flutter pub get, and build a basic widget tree. You should also know how TextStyle and ThemeData work.
Resolution-aware images with 2.0x and 3.0x folders
Flutter uses the device pixel ratio to choose an image file. A phone with a ratio of 2.0 needs twice as many pixels per logical unit as the base image. You supply one file per ratio and Flutter picks the closest match.
Place the files in folders named after the ratio:
assets/images/logo.png
assets/images/2.0x/logo.png
assets/images/3.0x/logo.pngDeclare only the base path in pubspec.yaml. Flutter bundles the variant folders automatically:
flutter:
assets:
- assets/images/logo.pngYour code still refers to the base path:
Image.asset('assets/images/logo.png', width: 120)Registering a custom font family
Declare a font family under the flutter: key. Each entry maps a weight or style to a file:
flutter:
fonts:
- family: Raleway
fonts:
- asset: assets/fonts/Raleway-Regular.ttf
- asset: assets/fonts/Raleway-Bold.ttf
weight: 700
- asset: assets/fonts/Raleway-Italic.ttf
style: italicRun flutter pub get after editing the file.
Using fonts in a widget and in the app theme
Set fontFamily in ThemeData to apply the font to the whole app. Use fontWeight in a TextStyle to pick the bold file:
import 'package:flutter/material.dart';
class App extends StatelessWidget {
const App({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(fontFamily: 'Raleway'),
home: const Scaffold(
body: Center(
child: Text(
'Hello, fonts',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
),
);
}
}Exercise
You declare Raleway-Bold.ttf with weight 700 and set the theme's fontFamily to Raleway. What does a Text widget with FontWeight.w700 display, and why?
Show answer
It displays the bold file. The theme sets the family to Raleway, and the weight 700 selects the file declared with weight 700.