Sub topic 2
Adding custom fonts
This chapter assumes you know Dart classes and named parameters, can write a StatelessWidget, and have a Flutter project with a pubspec.yaml file.
Registering a font family
Flutter does not load font files on its own. You declare each font in pubspec.yaml under the flutter section, then refer to it by family name:
flutter:
uses-material-design: true
assets:
- assets/images/
fonts:
- family: Lora
fonts:
- asset: assets/fonts/Lora-Regular.ttf
- asset: assets/fonts/Lora-Bold.ttf
weight: 700Run flutter pub get after editing the file. Then set fontFamily in a TextStyle. Flutter picks the bold file when fontWeight is FontWeight.bold.
Text(
'Hello, Flutter',
style: TextStyle(fontFamily: 'Lora', fontSize: 24),
)Text scaling and user font settings
Users change the system font size in their device settings. Flutter reads this value through MediaQuery. Do not fix text sizes in pixels if you want the layout to adapt. Test with the largest setting, and use maxLines or a flexible layout so text does not overflow.
Displaying images with the Image widget
The Image widget shows a picture. It has named constructors for each source: Image.asset, Image.network, Image.file, and Image.memory. Use Image.file only on mobile and desktop, because the web has no file system access.
Declaring assets and resolution variants
List each image folder in pubspec.yaml. For resolution variants, put the 2x and 3x copies in subfolders such as assets/images/2.0x/. Flutter chooses the variant that matches the screen's pixel ratio. You declare only the base folder.
Sizing and cropping images with BoxFit
BoxFit controls how an image fills its box. BoxFit.cover fills the box and crops the overflow. BoxFit.contain shows the whole image and may leave empty space.
Image.asset(
'assets/images/hero.png',
width: 300,
height: 180,
fit: BoxFit.cover,
semanticLabel: 'Mountain landscape at sunrise',
):::callout note Network images need a loading state and an error state. Pass loadingBuilder and errorBuilder to Image.network to handle both. :::
Exercise
Your 300 by 180 hero image looks stretched on a tall screen. Which BoxFit value keeps the aspect ratio and still fills the box?
Show answer
BoxFit.cover. It keeps the aspect ratio and crops the overflow. BoxFit.fill stretches the image to the box size and distorts it.