Flutter custom font doesn't change - flutter

I tried to use a custom font for my AppBar, but it didn't change. I tried with two different fonts, RobotoMono and DancingScript, but nothing, the app did't change the font. I tried to unistall the app from the virtual phone too, too create another virtual device, but nothing. That's my main.dart :
import 'package:flutter/material.dart';
import 'background_image_task-9.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Blumax',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: 'Dancing',
primarySwatch: myColour
),
home: BackgroundImage(
),
);
}
}
const MaterialColor myColour = const MaterialColor(
0xFF0009FF,
const <int, Color>{
50: const Color(0xFF0009FF),
100: const Color(0xFF0009FF),
200: const Color(0xFF0009FF),
300: const Color(0xFF0009FF),
400: const Color(0xFF0009FF),
500: const Color(0xFF0009FF),
600: const Color(0xFF0009FF),
700: const Color(0xFF0009FF),
800: const Color(0xFF0009FF),
900: const Color(0xFF0009FF),
},
);
This is where i use the custom font, background_image_task-9.dart :
import 'package:flutter/material.dart';
class BackgroundImage extends StatelessWidget{
#override
Widget build(BuildContext context){
return Scaffold(
appBar: AppBar(
elevation: 0,
title: Text('Blumax', style: TextStyle(
fontWeight: FontWeight.w500,
fontFamily: 'RobotoMono',
fontSize: 40
),),
centerTitle: true,
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(image: AssetImage("assets/blumax.jpg"), fit: BoxFit.cover),
),
),
);
}
}
And that's my pubspec.yaml :
name: iphone_prj
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
english_words: ^3.1.0
cupertino_icons: ^0.1.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
assets:
- assets/
uses-material-design: true
fonts:
- family: RobotoMono
fonts:
- asset: assets/fonts/RobotoMono-Bold.ttf
- family: DancingScript
fonts:
- asset: assets/fonts/DancingScript-Bold.ttf
weight: 300

Just add your font-family name properly in your main ThemeData as per pubspec.yaml file
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Blumax',
debugShowCheckedModeBanner: false,
theme: ThemeData(
fontFamily: 'DancingScript',
primarySwatch: myColour
),
home: BackgroundImage(
),
);
}
}
The problem in your case is your font-family name is DancingScript and your providing it in the ThemeData as Dancing. So it will not effect to your app fonts.
Also, in your BackgroundImage class you have added RobotoMono font. But, the "fontWeight: FontWeight.w500" you have added is not matching as per your pubspec.yaml as you have added there RobotoMono-Bold fonts.
So, by matching your font names and font style will effect your app fonts as per your requirements.

There can be many reasons that avoid changing font in flutter :
1- Notice that the pubsec.yaml file is Space sensitive , It means that you need to use 2 or 4 spaces for declaring blocks. That's why you have to use indentation before declaring fonts. you can see the correct example in the snippet below:
flutter:
fonts:
- family: Raleway
fonts:
- asset: fonts/Raleway-Regular.ttf
- asset: fonts/Raleway-Italic.ttf
style: italic
- family: RobotoMono
fonts:
- asset: fonts/RobotoMono-Regular.ttf
- asset: fonts/RobotoMono-Bold.ttf
weight: 700
2- As the document mentioned the Folder Structure should be like :
awesome_app/
fonts/
Raleway-Regular.ttf
Raleway-Italic.ttf
RobotoMono-Regular.ttf
RobotoMono-Bold.ttf
3- Add your font-family name correctly in your main ThemeData as per pubspec.yaml file:
MaterialApp(
title: 'Custom Fonts',
// Set Raleway as the default app font.
theme: ThemeData(fontFamily: 'Raleway'),
home: MyHomePage(),);

your using asset prefix while declaring fonts in pubspec.yaml
Here is the solution https://stackoverflow.com/a/59113335/5557479

Related

Having an issue using the audioplayers package for flutter

Im creating a flutter app that requires a user to complete certain tasks in order to stop an alarm clock. Its a more imersive alarm clock app that could help stimulate the brain in order to aid in the process of waking up.
Im having some issues working with the hardware for the application, so to simulate an alarm going off im trying to use the audioplayers package to play an mp3 file once a button is pressed. Im aware that in order to use a local mp3 file I must utilize audio_cache with audioplayers.
when trying to import 'package:audioplayers/audio_cache.dart'; I recive this error
"Target of URI doesn't exist: 'package:audioplayers/audio_cache.dart'. Try creating the file referenced by the URI, or Try using a URI for a file that does exist"
Im also having trouble putting the local mp3 file that I want into my pubspec.yaml. The readMe for audio cache states that I have to place the file in my assest folder and specify the file path in my pubspec under assets. However I do not see an assets folder. I created a file named assets and placed the mp3 in there, but I dont belive this is what I was supposed to do. I also belive that I am placing the file path into my pubspec wrong as well.
Here is my code:
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:audioplayers/audio_cache.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Time Attack',
theme: ThemeData(
primarySwatch: Colors.red,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Time Attack'),
centerTitle: true,
),
floatingActionButton: FloatingActionButton(
onPressed: () {
final player = AudioCache();
//bool isPLaying = false;
player.play('musicForapp.mp3');
},
backgroundColor: Colors.red,
child: const Icon(Icons.punch_clock),
),
body: Padding(
padding: const EdgeInsets.all(170),
child: Column(
children: [
Container(
color: Colors.red,
child: const Text(
"Click the Icon in the bottem left to simulate an alarm",
style: TextStyle(
color: Colors.white,
fontSize: 30.0,
),
),
),
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const TasksPage(),
),
);
}, //on pressed
child: const Text(
"Navigate",
style: TextStyle(color: Colors.white),
),
)
],
),
),
),
);
} //widget build
}
class TasksPage extends StatefulWidget {
const TasksPage({super.key});
#override
State<TasksPage> createState() => _TasksPageState();
}
class _TasksPageState extends State<TasksPage> {
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
backgroundColor: Colors.red,
title: const Text('Tasks'),
centerTitle: true,
),
body: Center(
child: Column(
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => const MyHomePage(),
),
);
}, //on pressed
child: const Text(
"Navigate",
style: TextStyle(color: Colors.white),
),
)
],
),
),
),
);
} //widget build
}
Here is my pubspec.yaml:
name: timeattack2
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1
environment:
sdk: '>=2.18.2 <3.0.0'
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
audioplayers: ^1.1.1
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^2.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
# To add assets to your application, add an assets section, like this:
assets:
-assets/musicForapp.mp3
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/assets-and-images/#from-packages
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/custom-fonts/#from-packages
All in all Here are my issues:
1.) issue importing audio cache package for code
2.) placing the mp3 file in the correct "assest" folder
3.) Specifiying the file path in pubspec.yaml as to where my mp3 file is
Remove cache import section and try this way
onPressed: () async {
AudioPlayer p = AudioPlayer();
await p.play(AssetSource('assets/musicForapp.mp3'));
},
And yaml
assets:
- assets/musicForapp.mp3

Flutter: Material icons not showing when importing a custom Font

the original Material Icons in FLutter Icon(Icons.access_alarms) stop working every time I try to define a new custom font for my app.
What I do is to import the font in the pubspec.yamlfile correctly, include the "uses-material-design:true" and define the font in main ThemeData using the fontFamily property.
flutter:
uses-material-design: true
assets:
- images/
fonts:
- family: Core Sans C
fonts:
- asset: Fonts/coresansc-45regular-webfont.ttf
style: normal
weight: 500
screenshot of the pubspec.yaml including the font definition
ThemeData kThemeLB = ThemeData(
fontFamily: 'Core Sans C',
backgroundColor: kBgColor1,
primaryColor: kMainColor,
// primarySwatch: kMainColor,
textTheme: const TextTheme(
bodyText1: TextStyle(
color: kSecondaryColor,
),
),
scaffoldBackgroundColor: kBgColor1);
And my main.dart
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: kThemeLB,
home: LoadLogin(),
My fonts DIR
Fonts dir
I can use FontAwesome Icons correctly, but still I'd like to know what the issue is.
I've been looking for a solution for a long time now but I can't seem to figure out what's the problem here. Any help is much appreciated thank!
Try move your files inside your assets dir, for example:
- assets
-- fonts
--- **"your fonts inside fonts dir"**
after that modify your pubspec file, like this:
fonts:
- family: coreSansC
- fonts:
- asset: assets/fonts/coresansc-45regular-webfont.ttf
finally modify your ThemeData, like this:
ThemeData kThemeLB = ThemeData(
fontFamily: 'coreSansC',
backgroundColor: kBgColor1,
primaryColor: kMainColor,
// primarySwatch: kMainColor,
textTheme: const TextTheme(
bodyText1: TextStyle(
color: kSecondaryColor,
),
),
I recommend you use camelCase names.

Issues with Flutter's MaterialLocalizations

I have issues with my Material Widgets (AppBar widget as an example). I tried to find a solution in other SO questions but nothing is working. In production App bar's back button, and some other material files aren't working too, even material clipboard.
[Edit] I found out that the issue was with not supported language (Turkmen/Russian - two main languages of my app) in some non-global (Chinese, Hindu) phones. There were no issues with other iOS / Android devices.
So there is my MaterialApp file:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:peydaly.market/blocs/markets_provider.dart';
import 'package:peydaly.market/generated/l10n.dart';
import 'package:peydaly.market/screens/loading_screen.dart';
import 'blocs/markets_provider.dart';
class App extends StatelessWidget {
#override
Widget build(context) {
return MarketsProvider(
child: MaterialApp(
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
debugShowCheckedModeBanner: false,
darkTheme: buildDarkMode(),
theme: buildLightMode(),
title: 'Peýdaly.Market',
home: LoadingScreen(),
),
);
}
ThemeData buildLightMode() {
return ThemeData.light().copyWith(
buttonTheme: ButtonThemeData(
minWidth: 10,
),
primaryColor: Colors.grey[100],
backgroundColor: Colors.white,
iconTheme: IconThemeData(
color: Colors.grey[900],
),
appBarTheme: AppBarTheme(
centerTitle: true,
brightness: Brightness.light,
iconTheme: IconThemeData(
color: Colors.grey[900],
),
actionsIconTheme: IconThemeData(
color: Colors.grey[900],
),
// brightness: Brightness.light,
color: Colors.white,
textTheme: TextTheme(
headline6: TextStyle(
color: Colors.grey[900],
fontWeight: FontWeight.w600,
),
),
elevation: 0,
),
);
}
ThemeData buildDarkMode() {
return ThemeData.dark().copyWith(
buttonTheme: ButtonThemeData(
minWidth: 10,
),
backgroundColor: Colors.grey[900],
primaryColor: Colors.grey[850],
iconTheme: IconThemeData(
color: Colors.white,
),
appBarTheme: AppBarTheme(
centerTitle: true,
brightness: Brightness.dark,
iconTheme: IconThemeData(
color: Colors.white,
),
actionsIconTheme: IconThemeData(
color: Colors.white,
),
// brightness: Brightness.dark,
color: Colors.grey[900],
textTheme: TextTheme(
headline6: TextStyle(
color: Colors.grey[100],
fontWeight: FontWeight.w600,
),
),
elevation: 0,
),
);
}
}
My pubspec.yaml file:
name: peydaly.market
description: Subscription Online Groceries delivery service app for mobile devices.
version: 0.2+23
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
animations: ^1.1.2
cached_network_image: ^2.2.0+1
carousel_slider: ^2.3.1
crypto: ^2.1.5
cupertino_icons: ^1.0.0
cupertino_rounded_corners: ^1.0.3
date_format: ^1.0.9
flare_flutter: ^2.0.6
flutter_polyline_points: ^0.2.4
futuristic: ^0.1.3
google_maps_flutter: ^1.0.6
http: ^0.12.1
intl: 0.16.1
location: ^3.0.2
modal_bottom_sheet: ^0.2.2
path_provider: ^1.6.14
rive: ^0.6.3
rxdart: ^0.24.1
shimmer: ^1.1.1
splashscreen: ^1.3.4
sqflite: ^1.3.1+1
superellipse_shape: ^0.1.5
dev_dependencies:
flutter_test:
sdk: flutter
pedantic: ^1.4.0
flutter:
uses-material-design: true
generate: true
assets:
- assets/social/
- assets/playlists/
- assets/avatar/
- assets/sql/
flutter_localizations:
sdk: flutter
flutter_intl:
enabled: true
class_name: S
main_locale: tm
flutter_icons:
android: "launcher_icon"
ios: true
image_path: "assets/icon/icon.png"
And my debug console error.
═══════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown building AppBar(dirty, dependencies: [_LocalizationsScope-[GlobalKey#2fd79]], state: _AppBarState#848b3):
No MaterialLocalizations found.
AppBar widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
The material library uses Localizations to generate messages, labels, and abbreviations.
To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to include them automatically or add a Localization widget with a MaterialLocalizations delegate.
The specific widget that could not find a MaterialLocalizations ancestor was: AppBar
dirty
dependencies: [_LocalizationsScope-[GlobalKey#2fd79]]
state: _AppBarState#848b3
The ancestors of this widget were
Scaffold
dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#2fd79], Directionality, MediaQuery, _EffectiveTickerMode]
state: ScaffoldState#0f235(tickers: tracking 2 tickers)
CitySelectionScreen
dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#2fd79], MarketsProvider]
state: _CitySelectionScreenState#fb711
MaterialApp
state: _MaterialAppState#44c02
MarketsProvider
App
...
The relevant error-causing widget was
AppBar
lib/screens/city_selection_screen.dart:53
When the exception was thrown, this was the stack
#0 debugCheckHasMaterialLocalizations.<anonymous closure>
package:flutter/…/material/debug.dart:74
#1 debugCheckHasMaterialLocalizations
package:flutter/…/material/debug.dart:94
#2 _AppBarState.build
package:flutter/…/material/app_bar.dart:509
#3 StatefulElement.build
package:flutter/…/widgets/framework.dart:4744
#4 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4627
...
════════════════════════════════════════════════════════════════════════════════
════════ Exception caught by widgets library ═══════════════════════════════════
No MaterialLocalizations found.
The ancestors of this widget were
Scaffold
dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#2fd79], Directionality, MediaQuery, _EffectiveTickerMode]
state: ScaffoldState#0f235(tickers: tracking 2 tickers)
CitySelectionScreen
dependencies: [_InheritedTheme, _LocalizationsScope-[GlobalKey#2fd79], MarketsProvider]
state: _CitySelectionScreenState#fb711
MaterialApp
state: _MaterialAppState#44c02
MarketsProvider
App
...
The relevant error-causing widget was
AppBar
lib/screens/city_selection_screen.dart:53
════════════════════════════════════════════════════════════════════════════════
So the issue was with App localization issues of Material UI elements on unsupported devices, so to add support to it, I added these lines to my App file:
supportedLocales: [
const Locale('ru'),
const Locale('tm'),
...S.delegate.supportedLocales,
],

Floating Action Button in Flutter

I was trying to create the Floating Action button but I am missing icon.
My code is:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.blue,
centerTitle: true,
title: Text(
"Lessons of Flutter",
style: TextStyle(
color: Colors.white,
),
),
),
body: Center(
child: const Text('Press the button below!')
),
floatingActionButton: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
},
child: Icon(Icons.mouse),
backgroundColor: Colors.green,
),
),
);
}
}
it is a screen from the virtual device.( You can see icon looks weird.)
To use this class, make sure you set uses-material-design: true in your project's pubspec.yaml file in the flutter section. This ensures that the MaterialIcons font is included in your application. This font is used to display the icons. For example:
Refer this link: https://api.flutter.dev/flutter/material/Icons-class.html
The Icon is not rendering because of the missing font from the material design library. You have to enable the material design library in your pubspec.yml file as given below,
flutter:
uses-material-design: true
Just make uses-material-design to true and the error will be gone. This ensures that the MaterialIcons font is included in your application. This font is used to display the icons Here is the official docs of Icon class

How to use a specific font from a list of fonts specified in a asset family in pubspec.yaml

Let's say i have added following lines to the pubspec.yaml file
fonts:
fonts:
- family: GreatVibes
fonts:
- asset: fonts/GreatVibes-Regular.ttf
- asset: fonts/GreatVibes-Bold.ttf
I am using it in my app with the following lines of code.
new Text('My New Font',
style: new TextStyle(
color: Colors.white,
fontFamily: 'GreatVibes',
fontSize: 16.0,
)),
My question is that ,among the two .ttf files provided earlier, how does flutter decides which file to use?
And Let's say if flutter decides to use GreatVibes-Bold.ttf, what can i do to make it use GreatVibes-regular.ttf
If I understand these font things correctly - it has to be like this:
fonts:
- family: GreatVibes
fonts:
- asset: fonts/GreatVibes-Regular.ttf
- asset: fonts/GreatVibes-Bold.ttf
weight: 700
- asset: fonts/GreatVibes-Italic.ttf
style: italic
And then
new Text('My New Font',
style: new TextStyle(
color: Colors.white,
fontFamily: 'GreatVibes',
fontWeight: FontWeight.w700,
fontSize: 16.0,
)),
you may use it directly into widget style,or using Theme object which i prefer to control overall app from one location, here an example for main.dart:
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.purple,
accentColor: Colors.deepOrange,
**fontFamily: 'Lato'**),
....
},
);
Checkout these links :
How to use a custom font style in flutter?
https://flutter.io/docs/cookbook/design/fonts