How to add a custom font? - flutter

I want to add a custom font to a specific widget, I did everything but it is not changing
I imported the font files into the project and created a "fonts" folder for it then declared the font in the pubspec
I am using PlayfairDisplay and I've tried Roboto but it is still not changing
uses-material-design: true
fonts:
- family: PlayfairDispaly
fonts:
- asset: fonts/PlayfairDisplay-Bold.ttf
style: bold

You may incorrectly defined the Font Family name
family: PlayfairDispaly fonts: - asset: fonts/PlayfairDisplay-Bold.ttf style: bold
you should write it as PlayfairDisplay not PlayfairDispaly
as maybe you use it in your widget with this code :
Text(
"Hello World",
style: TextStyle(
fontFamily: "PlayfairDisplay",
),
),

When using google fonts in flutter you must take care of the spaces and the tabs,
also you should make sure that the font family name is exactly the same 'case sensitive' in both the dart file and the pubspec.yaml file
the main.dart file should has a code like this :-
Text(
'FullStack Developer',
style: TextStyle(
fontSize: 20.0,
color: Colors.black,
fontFamily: 'Playfair Display',
letterSpacing: 2.0,
fontWeight: FontWeight.bold,
),
),
and for the pubspec.yaml try this:-
flutter:
uses-material-design: true
fonts:
- family: PlayfairDisplay
fonts:
- asset: fonts/PlayfairDisplay-Regular.ttf

Related

how to add close outside dialog in flutter using getx

hello I am trying to add like this closing in default dialog in flutter using getx
here is the image
here is my code Get.defaultDialog(
radius: 8,
title: "Test",
titleStyle: const TextStyle(
fontSize: 25, fontWeight: FontWeight.bold),)

Why my font family aint working in Flutter?

Everything seems working just fine except the font family.Text animation is working but everytime i run my Flutter apps it runs on the normal default font.What should i do now?
children: [
AnimatedTextKit(
animatedTexts: [
TypewriterAnimatedText(
'Hello world!',
textStyle: const TextStyle(
fontSize: 32.0,
fontWeight: FontWeight.bold,
fontFamily: 'Canterbury'
),
speed: const Duration(milliseconds: 200),
),
],
totalRepeatCount: 4,
pause: const Duration(milliseconds: 1000),
displayFullTextOnTap: true,
stopPauseOnTap: true,
)
],
)
),
);
}
}
Make sure to add the fonts to your pubspec.yaml file. Here is an example of how to properly implement them assuming the file storing your fonts is in the root folder of your project (not the lib)
assets:
...
fonts:
- family: Schyler
fonts:
- asset: fonts/Schyler-Regular.ttf
- asset: fonts/Schyler-Italic.ttf
style: italic

Flutter and custom fonts

I have an app in flutter using different fonts from the same family, declared in pubspec.yaml like this:
fonts:
- family: Poppins
fonts:
- asset: assets/fonts/Poppins-Light.ttf
weight: 100
- asset: assets/fonts/Poppins-Medium.ttf
weight: 400
- asset: assets/fonts/Poppins-Bold.ttf
weight: 600
In my main.dart, to use Poppins as my default font for the whole app, I have declared:
theme: ThemeData(fontFamily: 'Poppins'),
However, now comes my doubts:
by declaring theme: ThemeData(fontFamily: 'Poppins'), which one of the 3 fonts is used by default?
How do I make the difference in a Text() widget when I want to use Light/Medium/Bold?.
Do I really need to declare the weight for each font type Light/Medium/Bold in pubspe.yaml?
You can use a TextTheme to define how the fonts will be used.
final TextTheme textTheme = TextTheme(
headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold, fontFamily: 'Poppins'),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic, fontFamily: 'Poppins'),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Poppins'),
)
ThemeData(textTheme: textTheme)

How to create a global TextStyle in Flutter?

In my home page in build widget before return statement I use below code.
If I create an another widget in my home page I have to copy below code before each return statement. If you create another stateless/stateful dart file I need to copy below code again.
My question is How to create a global TextStyle in Flutter? I don't want to change Theme data, all want to use my TextStyle across the my flutter project. Thanks.
TextStyle myNormalStyle = TextStyle(
fontSize: SizerUtil.deviceType == DeviceType.Mobile ? 14.0.sp : 13.0.sp,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
color: Colors.black);
You can easily you that using by using Theme. As described on the flutter docs you can use it like :
MaterialApp(
title: title,
theme: ThemeData(
// Define the default brightness and colors.
brightness: Brightness.dark,
primaryColor: Colors.lightBlue[800],
accentColor: Colors.cyan[600],
// Define the default font family.
fontFamily: 'Georgia',
// Define the default TextTheme. Use this to specify the default
// text styling for headlines, titles, bodies of text, and more.
textTheme: TextTheme(
headline1: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold),
headline6: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic),
bodyText2: TextStyle(fontSize: 14.0, fontFamily: 'Hind'),
),
)
);
or you can also use DefaultTextStyle widget to provide a default TextStyle to all the children of this widget. Read more about DefaultTextStyle.
1º create a class file:
import 'package:flutter/material.dart';
class MyTextStyle {
static const TextStyle textStyle = TextStyle(
color: Color.fromARGB(255, 247, 240, 201),
fontSize: 20,
fontWeight: FontWeight.bold,
);
}
2º import and use in your screen:
import 'package:MyApp/MyTextStyle.dart';
const Text(
'You have pushed the button this many times:',
style: MyTextStyle.textStyle,
),

Custom font is not rendered to golden images when package is provided

I have a custom font defined in module theme. This module is a dependency in module widgets.
A widget in widgets module applies custom font like below
style: TextStyle(
fontSize: fontSize,
fontFamily: "IconActions",
package: "theme"
)
It works fine.
Unfortunately this custom font is not rendered on golden images. I have to remove the package: "theme" to fix that. But that breaks the app and the font is not displayed any more.
So basically I can have the font working correctly in the production code or the test code, but never both.
The custom font is loaded in setUp method of the test
final fontData = File('assets/fonts/IconActions.ttf')
.readAsBytes()
.then((bytes) => ByteData.view(Uint8List.fromList(bytes).buffer));
final fontLoader = FontLoader('IconActions')..addFont(fontData);
await fontLoader.load();
Am I missing something, or is it a bug?
So basically the solution is to remove package: "theme" from the TextStyle to make it work. But that's the half of the solution, because as I mentioned in the question now golden files have the font renderer correctly, but the font doesn't work in the app.
To make it work in the app we need given project structure:
pubspec.yaml (module theme)
flutter:
fonts:
- family 'ComicSans'
fonts:
- asset: packages/theme/fonts/ComicSans.ttf
widget.dart (module theme)
style: TextStyle(
fontSize: fontSize,
fontFamily: "ComicSans",
)
Now in module widgets, which is the module that contains main.dart with its main function that you run, you have to define the font again:
pubspec.yaml (module widgets)
dependencies:
flutter:
sdk: flutter
theme:
path: ../path/to/theme/module
flutter:
fonts:
- family 'ComicSans'
fonts:
- asset: packages/theme/fonts/ComicSans.ttf
Now the font is correctly displayed in both the app and the golden images.
I've had this exact issue for the last year and also couldn't get font loading to work within tests.. did not know that it was specifically the package argument that was breaking it, so thank you for updating with that result.
As for another workaround, there is a way to have the best of both worlds where you can have your standalone font package and not have to declare your packaged font files in your app that is using it.
For example, we have a company branding/typography package which we use across multiple apps that contains all our pre-configured TextStyle declarations, and another standalone package which has custom generated IconData that is stored within a *.ttf file (like FontAwesome).
The package side:
pubspec.yaml
flutter:
uses-material-design: true
assets:
- assets/fonts/
fonts:
- family: MyFont
fonts:
- asset: assets/fonts/MyFont.ttf
weight: 400
# etc
The packaged TextStyle:
class BrandStyles {
static const _packageName = '<package_name>';
static const headline1Style = TextStyle(
color: Colors.black,
fontFamily: 'MyFont',
fontSize: 60.0,
fontStyle: FontStyle.normal,
fontWeight: FontWeight.w400,
height: 1.16,
letterSpacing: 0,
package: _packageName,
);
// etc
}
Golden test
void main() {
final widget = MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
// use custom extension method to remove `package` value
headline1: BrandStyles.headline1Style.trimFontPackage(),
),
),
home: Scaffold(
body: SafeArea(child: StylesExample()),
),
);
setUp(() async {
TestWidgetsFlutterBinding.ensureInitialized();
final file = File('path/to/packaged/asset/MyFont.ttf').readAsBytesSync();
final bytes = Future<ByteData>.value(file.buffer.asByteData());
await (FontLoader('MyFont')..addFont(bytes)).load();
});
testWidgets('Golden typography test', (WidgetTester tester) async {
await tester.pumpWidget(widget);
await expectLater(
find.byType(MaterialApp), matchesGoldenFile('goldens/typography.png'));
});
}
extension StylingExtensions on TextStyle {
TextStyle trimFontPackage() {
return TextStyle(
inherit: inherit,
color: color,
backgroundColor: backgroundColor,
fontSize: fontSize,
fontWeight: fontWeight,
fontStyle: fontStyle,
letterSpacing: letterSpacing,
wordSpacing: wordSpacing,
textBaseline: textBaseline,
height: height,
locale: locale,
foreground: foreground,
background: background,
shadows: shadows,
fontFeatures: fontFeatures,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
decorationThickness: decorationThickness,
debugLabel: debugLabel,
/// `replaceAll` only required if loading multiple fonts,
/// otherwise set value to your single `fontFamily` name
fontFamily: fontFamily.replaceAll('packages/<package_name>/', ''),
);
}
}
Or if like me, you have the same issue with custom icons, the same can be done within your golden test for your custom IconData with a similar extension method, removing the fontPackage value:
extension IconExtensions on IconData {
IconData convertToGolden() => IconData(
this.codePoint,
fontFamily: this.fontFamily,
);
}
Your app side
pubspec.yaml
# ...
dependencies:
flutter:
sdk: flutter
<package_name>:
git:
url: <url_to_hosted_package>.git
ref: <release_tag>
main.dart
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData.light().copyWith(
textTheme: TextTheme(
headline1: BrandStyles.headline1Style,
),
),
);
}
}
There is now no longer a need to declare your fonts within your apps pubspec.yaml, or even have the style package(s) within the same project/repository as your implementing app.