Text Style
Summary
In this lesson we'll cover: how to style text using TextTheme
, custom fonts and basic Material Design theming with TextStyle
. We'll also cover code organization when working with style.
The Code for This Lesson
Check out the tourismandco repo's step/step04
branch for the code we'll cover in this lesson.
Styling text using TextTheme
, fonts assets and TextStyle
- In order to style our text, let's use a custom font.
- Create a new directory called
assets/fonts
. - Copy the font files located at
assets/fonts
in thestep/step03
branch of this repo and copy it to our new directory. - Update our
pubspec.yaml
file so we can use our fonts.
Adding fonts
to pubspec.yaml
# pubspec.yaml
flutter:
# ...
fonts:
- family: Montserrat
fonts:
- asset: assets/fonts/Montserrat-Regular.ttf
weight: 300
- asset: assets/fonts/Montserrat-Bold.ttf
weight: 600
# ...
Again, be careful of the indentation here.
Note: this screen isn't currently scrollable, so if the content for this screen overflows, we'll see some weird rendering issues. Later, we'll take care of this issue.
Using an App-Wide TextTheme
- We can define app-wide style using the
theme
parameter of ourMaterialApp
widget, located inapp.dart
. - Update our
app.dart
to the following:
// app.dart
import 'package:flutter/material.dart';
import 'screens/location_detail/location_detail.dart';
import 'style.dart';
class App extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: LocationDetail(),
theme: ThemeData(textTheme: TextTheme(body1: Body1Style)),
);
}
}
// ...
- Here, we can style all text using the
textTheme
param ofThemeData
. - Warning: note that we'll importing a new file here,
style.dart
. - Next, let's create a
style.dart
file so we can cleanly keep all our app styles in one place.
Adding style.dart
// style.dart
import 'package:flutter/material.dart';
const String FontNameDefault = 'Montserrat';
const Body1Style = TextStyle(
fontFamily: FontNameDefault,
fontWeight: FontWeight.w300,
fontSize: 26.0,
color: Colors.black,
);
- Note that we're using
const
here (a "constant"), which ensures that the value of this constant is assigned at compile-time rather than runtime. A small optimization. TextStyle
allows to style an individualText
widget using itsstyle
param.- Yet we won't do this, as we using
ThemeData
, no code changes will be needed. Pretty cool. - Stop and re-start the app to see the changes.
- Note that if we add new files or make changes to any
const
variables, we'll need to restart our app, as these changes aren't supported by Flutter's Hot Reload feature.
Summary
In this lesson, we covered the basics of layout, imagesand text. Our "Tourism & Co." app is taking shape.