Why my font family aint working in Flutter? - 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

Related

How to change dropdown default text color, when it is disabled?

When the dropdown is disabled it has this default black text color, which I want to change. There is an option to change the icon color but no option for text color.
Any help would be greatly appreciated.
DropdownButtonFormField(
value: widget.selectedValue,
items: widget.dropdownItems,
dropdownColor: customTheme.colors.black30,
iconEnabledColor: customTheme.colors.textColor,
iconDisabledColor: Color.fromARGB(143, 144, 144, 144),
Change the property disabledColor of your app theme or use Theme widget:
Theme(
data: Theme.of(context).copyWith(disabledColor: customTheme.colors.black30),
child: DropdownButtonFormField(
value: widget.selectedValue,
items: widget.dropdownItems,
dropdownColor: customTheme.colors.black30,
iconEnabledColor: customTheme.colors.textColor,
iconDisabledColor: Color.fromARGB(143, 144, 144, 144),
),
),
You can change using style
style: const TextStyle(
color: Colors.pink,
backgroundColor: Colors.grey,
),
Here you can find more:
https://www.flutter-code.com/2021/06/flutter-dropdownbutton-selected-text.html

Flutter named parameter and OneSignal issue

I am working on a project which was built on Flutter 2.2.3 but I updated all the dependencies. Also, I have fixed many errors which were the result of upgrading the flutter from 2.2.3 to 2.5.2. Now i am facing an issue with two files. One issue is with the PersistentTabController and it is saying 'The named parameter is not found' for many lines like controller, navBarHeight, onItemSelected, screens, items. Well I am sharing the code. The left side is totally red. How can I fix that?
PersistentTabController(
controller: controller,
navBarHeight: MediaQuery.of(context).size.width > 768 ? 90 : 64,
onItemSelected: (item) {
int index = controller.index;
if (index == 0) {
setState(() {
appbarTitle = Languages.of(context).homeScreenTitle;
});
} else if (index == 1) {
setState(() {
appbarTitle = Languages.of(context).appointmentsScreenTitle;
});
} else if (index == 2) {
setState(() {
appbarTitle = Languages.of(context).favouriteScreenTitle;
});
} else if (index == 3) {
setState(() {
appbarTitle =
Languages.of(context).notificationsScreenTitle;
});
} else if (index == 4) {
setState(() {
appbarTitle = Languages.of(context).accountScreenTitle;
});
}
},
screens: _pages,
items: [
PersistentBottomNavBarItem(
icon: Icon(
Icons.home_outlined,
size: MediaQuery.of(context).size.width > 768 ? 40 : 24,
),
title: Languages.of(context).bottomNavHome,
activeColor: ColorConstants.primaryColor,
inactiveColor: ColorConstants.iconColor,
titleStyle: TextStyle(
fontSize:
MediaQuery.of(context).size.width > 768 ? 20 : 12)),
PersistentBottomNavBarItem(
icon: Icon(
Icons.calendar_today_outlined,
size: MediaQuery.of(context).size.width > 768 ? 40 : 24,
),
title: Languages.of(context).bottomNavAppointments,
activeColor: ColorConstants.primaryColor,
inactiveColor: ColorConstants.iconColor,
titleStyle: TextStyle(
fontSize:
MediaQuery.of(context).size.width > 768 ? 20 : 12)),
PersistentBottomNavBarItem(
icon: Icon(
Icons.favorite_border,
size: MediaQuery.of(context).size.width > 768 ? 40 : 24,
),
title: Languages.of(context).bottomNavFavourites,
activeColor: ColorConstants.primaryColor,
inactiveColor: ColorConstants.iconColor,
titleStyle: TextStyle(
fontSize:
MediaQuery.of(context).size.width > 768 ? 20 : 12)),
PersistentBottomNavBarItem(
icon: Icon(
Icons.notifications,
size: MediaQuery.of(context).size.width > 768 ? 40 : 24,
),
title: Languages.of(context).bottomNavNotifications,
activeColor: ColorConstants.primaryColor,
inactiveColor: ColorConstants.iconColor,
titleStyle: TextStyle(
fontSize:
MediaQuery.of(context).size.width > 768 ? 20 : 12)),
PersistentBottomNavBarItem(
icon: Icon(
Icons.person_outline,
size: MediaQuery.of(context).size.width > 768 ? 40 : 24,
),
title: Languages.of(context).bottomNavAccount,
activeColor: ColorConstants.primaryColor,
inactiveColor: ColorConstants.iconColor,
titleStyle: TextStyle(
fontSize:
MediaQuery.of(context).size.width > 768 ? 20 : 12)),
],
confineInSafeArea: true,
backgroundColor: Colors.white,
handleAndroidBackButtonPress: true,
resizeToAvoidBottomInset: true,
// This needs to be true if you want to move up the screen when keyboard appears.
stateManagement: false,
hideNavigationBarWhenKeyboardShows: true,
// Recommended to set 'resizeToAvoidBottomInset' as true while using this argument.
decoration: NavBarDecoration(
border: Border.all(color: Colors.white),
borderRadius: BorderRadius.circular(1.0),
colorBehindNavBar: Colors.black,
),
popAllScreensOnTapOfSelectedTab: true,
popActionScreens: PopActionScreensType.all,
itemAnimationProperties: ItemAnimationProperties(
// Navigation Bar's items animation properties.
duration: Duration(milliseconds: 200),
curve: Curves.ease,
),
screenTransitionAnimation: ScreenTransitionAnimation(
// Screen transition animation on change of selected tab.
animateTabTransition: true,
curve: Curves.ease,
duration: Duration(milliseconds: 200),
),
navBarStyle: NavBarStyle.style6,
),
Also in another file, I am facing OneSignal issues like 'The method setInFocusDisplayType isn't defined for the type 'OneSignal' and 'The method 'setNotificationReceivedHandler isn't defined for the type 'OneSignal'.
Here is the code
OneSignal.shared
.setInFocusDisplayType(OSNotificationDisplayType.notification);
OneSignal.shared
.setNotificationReceivedHandler((OSNotification notification) {
this.setState(() {
outPutString =
"Received notification: \n${notification.jsonRepresentation().replaceAll("\\n", "\n")}";
});
How can i fix these?
I am sharing my pubspec.yaml file here.
name: test_app
description: A Test Application
publish_to: 'none'
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
cupertino_icons: ^1.0.0
shared_preferences: ^2.0.8
cached_network_image: ^3.1.0
flutter_rating_bar: ^4.0.0
url_launcher: ^6.0.12
country_code_picker: ^2.0.2
flutter_range_slider: "^1.5.0"
group_radio_button: ^1.0.1
carousel_slider: ^4.0.0
persistent_bottom_nav_bar: ^4.0.2
intl: ^0.17.0
provider: ^6.0.1
flutter_bloc: ^7.3.0
equatable: ^2.0.3
image_picker: ^0.8.4+2
dio: ^4.0.0
otp_text_field: ^1.0.2
path: ^1.7.0
mime: ^1.0.0
fluttertoast: ^8.0.8
date_format: ^2.0.4
html: ^0.15.0
flutter_calendar_carousel: ^2.0.3
onesignal_flutter: ^3.2.3
flutter_paytabs_bridge: ^2.1.1
http:
share: ^2.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
fonts:
- family: Quicksand
fonts:
- asset: assets/fonts/Quicksand/Quicksand-Bold.ttf
- asset: assets/fonts/Quicksand/Quicksand-Light.ttf
- asset: assets/fonts/Quicksand/Quicksand-Medium.ttf
- asset: assets/fonts/Quicksand/Quicksand-Regular.ttf
- asset: assets/fonts/Quicksand/Quicksand-SemiBold.ttf
- asset: assets/fonts/Quicksand/Quicksand-VariableFont_wght.ttf
assets:
- assets/images/
- assets/icons/
The problem is your plugins are updated but you are using methods outdated.
First issue seems like you are using PersistentTabController instead PersistentTabView or PersistentTabView.custom. Link documentation PersistentTab
And OneSignal plugin has the following methods:
OneSignal.shared.setNotificationWillShowInForegroundHandler((OSNotificationReceivedEvent event) {
// Will be called whenever a notification is received in foreground
// Display Notification, pass null param for not displaying the notification
event.complete(event.notification);
});
OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
// Will be called whenever a notification is opened/button pressed.
});
Link OneSignal documentation

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)

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.

How to add a custom font?

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