Repository: FlutterGen/flutter_gen

Issue:
[FR]: `package_parameter_enabled` flag in `fonts.outputs`
### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the problem

Thanks for the package! Right now it's only possible to provide `package_parameter_enabled` for assets, but not fonts. But if the pub-package project only contains fonts but not assets it could be nice to have a `package_parameter_enabled` flag for fonts too. This will be especially for those devs who don't won't to rely on Text's widget `packageName` parameter and want to use font family directly.

### Describe the solution

`package_parameter_enabled` flag (optional, default to false), will additionally generate strings with 'packages/<package_name>/<font_family_name>'

### Additional context

https://medium.com/flutter-community/including-assets-in-a-flutter-package-dd4a82a38ca9

### Code of Conduct

- [X] I agree to follow this project's Code of Conduct



Fix patch:
diff --git a/README.md b/README.md
index 771014cff..3de22f9bf 100644
--- a/README.md
+++ b/README.md
@@ -470,6 +470,31 @@ flutter:
 
 These configurations will generate **`fonts.gen.dart`** under the **`lib/gen/`** directory by default.
 
+#### Generate for packages
+
+If you want to generate fonts for a package,
+use `package_parameter_enabled` under `flutter_gen > fonts > outputs`.
+
+```yaml
+flutter_gen:
+  fonts:
+    outputs:
+      package_parameter_enabled: true # <- Add this line.
+```
+
+This would add the package constant to the generated class. For example:
+
+```dart
+class Fonts {
+  Fonts._();
+
+  static const String package = 'test';
+
+  static const String raleway = 'packages/$package/Raleway';
+  static const String robotoMono = 'packages/$package/RobotoMono';
+}
+```
+
 #### Usage Example
 
 ```dart
diff --git a/packages/core/lib/flutter_generator.dart b/packages/core/lib/flutter_generator.dart
index ec35cd09e..626a0cbbb 100644
--- a/packages/core/lib/flutter_generator.dart
+++ b/packages/core/lib/flutter_generator.dart
@@ -70,8 +70,10 @@ class FlutterGenerator {
     }
 
     if (flutterGen.fonts.enabled && flutter.fonts.isNotEmpty) {
-      final generated =
-          generateFonts(formatter, flutter.fonts, flutterGen.fonts);
+      final generated = generateFonts(
+        FontsGenConfig.fromConfig(config),
+        formatter,
+      );
       final fontsPath =
           normalize(join(pubspecFile.parent.path, output, fontsName));
       writer(generated, fontsPath);
diff --git a/packages/core/lib/generators/fonts_generator.dart b/packages/core/lib/generators/fonts_generator.dart
index 719f15c58..ee5204114 100644
--- a/packages/core/lib/generators/fonts_generator.dart
+++ b/packages/core/lib/generators/fonts_generator.dart
@@ -3,15 +3,40 @@
 import 'package:dart_style/dart_style.dart';
 import 'package:dartx/dartx.dart';
 import 'package:flutter_gen_core/generators/generator_helper.dart';
+import 'package:flutter_gen_core/settings/config.dart';
 import 'package:flutter_gen_core/settings/pubspec.dart';
 import 'package:flutter_gen_core/utils/error.dart';
 import 'package:flutter_gen_core/utils/string.dart';
 
+class FontsGenConfig {
+  FontsGenConfig._(
+    this._packageName,
+    this.flutterGen,
+    this.fonts,
+  );
+
+  factory FontsGenConfig.fromConfig(Config config) {
+    return FontsGenConfig._(
+      config.pubspec.packageName,
+      config.pubspec.flutterGen,
+      config.pubspec.flutter.fonts,
+    );
+  }
+
+  final String _packageName;
+  final FlutterGen flutterGen;
+  final List<FlutterFonts> fonts;
+
+  String get packageParameterLiteral =>
+      flutterGen.fonts.outputs.packageParameterEnabled ? _packageName : '';
+}
+
 String generateFonts(
+  FontsGenConfig config,
   DartFormatter formatter,
-  List<FlutterFonts> fonts,
-  FlutterGenFonts fontsConfig,
 ) {
+  final fonts = config.fonts;
+  final fontsConfig = config.flutterGen.fonts;
   if (fonts.isEmpty) {
     throw InvalidSettingsException(
         'The value of "flutter/fonts:" is incorrect.');
@@ -25,9 +50,16 @@ String generateFonts(
   buffer.writeln('$className._();');
   buffer.writeln();
 
+  final isPackage = config.packageParameterLiteral.isNotEmpty;
+  if (isPackage) {
+    buffer.writeln("static const String package = '${config._packageName}';");
+    buffer.writeln();
+  }
+
   fonts.map((element) => element.family).distinct().sorted().forEach((family) {
+    final keyName = isPackage ? 'packages/\$package/$family' : family;
     buffer.writeln("""/// Font family: $family
-    static const String ${family.camelCase()} = '$family';""");
+    static const String ${family.camelCase()} = '$keyName';""");
   });
 
   buffer.writeln('}');
diff --git a/packages/core/lib/settings/pubspec.dart b/packages/core/lib/settings/pubspec.dart
index 62436f6b5..6f8b96494 100644
--- a/packages/core/lib/settings/pubspec.dart
+++ b/packages/core/lib/settings/pubspec.dart
@@ -149,7 +149,7 @@ class FlutterGenFonts {
   final bool enabled;
 
   @JsonKey(name: 'outputs', required: true)
-  final FlutterGenElementOutputs outputs;
+  final FlutterGenElementFontsOutputs outputs;
 
   factory FlutterGenFonts.fromJson(Map json) => _$FlutterGenFontsFromJson(json);
 }
@@ -229,3 +229,17 @@ class FlutterGenElementAssetsOutputs extends FlutterGenElementOutputs {
   factory FlutterGenElementAssetsOutputs.fromJson(Map json) =>
       _$FlutterGenElementAssetsOutputsFromJson(json);
 }
+
+@JsonSerializable()
+class FlutterGenElementFontsOutputs extends FlutterGenElementOutputs {
+  FlutterGenElementFontsOutputs({
+    required super.className,
+    required this.packageParameterEnabled,
+  });
+
+  @JsonKey(name: 'package_parameter_enabled', defaultValue: false)
+  final bool packageParameterEnabled;
+
+  factory FlutterGenElementFontsOutputs.fromJson(Map json) =>
+      _$FlutterGenElementFontsOutputsFromJson(json);
+}
diff --git a/packages/core/lib/settings/pubspec.g.dart b/packages/core/lib/settings/pubspec.g.dart
index 1c077df8e..88be3070e 100644
--- a/packages/core/lib/settings/pubspec.g.dart
+++ b/packages/core/lib/settings/pubspec.g.dart
@@ -153,8 +153,8 @@ FlutterGenFonts _$FlutterGenFontsFromJson(Map json) => $checkedCreate(
         );
         final val = FlutterGenFonts(
           enabled: $checkedConvert('enabled', (v) => v as bool),
-          outputs: $checkedConvert(
-              'outputs', (v) => FlutterGenElementOutputs.fromJson(v as Map)),
+          outputs: $checkedConvert('outputs',
+              (v) => FlutterGenElementFontsOutputs.fromJson(v as Map)),
         );
         return val;
       },
@@ -231,3 +231,26 @@ FlutterGenElementAssetsOutputs _$FlutterGenElementAssetsOutputsFromJson(
         'directoryPathEnabled': 'directory_path_enabled'
       },
     );
+
+FlutterGenElementFontsOutputs _$FlutterGenElementFontsOutputsFromJson(
+        Map json) =>
+    $checkedCreate(
+      'FlutterGenElementFontsOutputs',
+      json,
+      ($checkedConvert) {
+        $checkKeys(
+          json,
+          requiredKeys: const ['class_name'],
+        );
+        final val = FlutterGenElementFontsOutputs(
+          className: $checkedConvert('class_name', (v) => v as String),
+          packageParameterEnabled: $checkedConvert(
+              'package_parameter_enabled', (v) => v as bool? ?? false),
+        );
+        return val;
+      },
+      fieldKeyMap: const {
+        'className': 'class_name',
+        'packageParameterEnabled': 'package_parameter_enabled'
+      },
+    );


Test patch:
diff --git a/packages/core/test/fonts_gen_test.dart b/packages/core/test/fonts_gen_test.dart
index 0f8ac0852..64f1e5ccc 100644
--- a/packages/core/test/fonts_gen_test.dart
+++ b/packages/core/test/fonts_gen_test.dart
@@ -26,8 +26,7 @@ void main() {
           pageWidth: config.pubspec.flutterGen.lineLength, lineEnding: '\n');
 
       expect(() {
-        return generateFonts(formatter, config.pubspec.flutter.fonts,
-            config.pubspec.flutterGen.fonts);
+        return generateFonts(FontsGenConfig.fromConfig(config), formatter);
       }, throwsA(isA<InvalidSettingsException>()));
     });
 
@@ -40,5 +39,15 @@ void main() {
 
       await expectedFontsGen(pubspec, generated, fact);
     });
+
+    test('Package parameter enabled', () async {
+      const pubspec = 'test_resources/pubspec_fonts_package_parameter.yaml';
+      const fact =
+          'test_resources/actual_data/fonts_package_parameter.gen.dart';
+      const generated =
+          'test_resources/lib/gen/fonts_package_parameter.gen.dart';
+
+      await expectedFontsGen(pubspec, generated, fact);
+    });
   });
 }
diff --git a/packages/core/test/gen_test_helper.dart b/packages/core/test/gen_test_helper.dart
index cf7c51459..f3c997ba8 100644
--- a/packages/core/test/gen_test_helper.dart
+++ b/packages/core/test/gen_test_helper.dart
@@ -121,9 +121,8 @@ Future<List<String>> runFontsGen(
   );
 
   final actual = generateFonts(
+    FontsGenConfig.fromConfig(config),
     formatter,
-    config.pubspec.flutter.fonts,
-    config.pubspec.flutterGen.fonts,
   );
   final expected = formatter.format(
     File(fact).readAsStringSync().replaceAll('\r\n', '\n'),
diff --git a/packages/core/test_resources/actual_data/fonts_package_parameter.gen.dart b/packages/core/test_resources/actual_data/fonts_package_parameter.gen.dart
new file mode 100644
index 000000000..02de3bfa4
--- /dev/null
+++ b/packages/core/test_resources/actual_data/fonts_package_parameter.gen.dart
@@ -0,0 +1,17 @@
+/// GENERATED CODE - DO NOT MODIFY BY HAND
+/// *****************************************************
+///  FlutterGen
+/// *****************************************************
+
+// coverage:ignore-file
+// ignore_for_file: type=lint
+// ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use
+
+class FontFamily {
+  FontFamily._();
+
+  static const String package = 'test';
+
+  /// Font family: Raleway
+  static const String raleway = 'packages/$package/Raleway';
+}
diff --git a/packages/core/test_resources/pubspec_fonts_package_parameter.yaml b/packages/core/test_resources/pubspec_fonts_package_parameter.yaml
new file mode 100644
index 000000000..8d0150759
--- /dev/null
+++ b/packages/core/test_resources/pubspec_fonts_package_parameter.yaml
@@ -0,0 +1,17 @@
+name: test
+
+flutter_gen:
+  output: lib/gen/ # Optional (default: lib/gen/)
+  line_length: 80 # Optional (default: 80)
+
+  fonts:
+    outputs:
+      package_parameter_enabled: true
+
+flutter:
+  fonts:
+    - family: Raleway
+      fonts:
+        - asset: assets/fonts/Raleway-Regular.ttf
+        - asset: assets/fonts/Raleway-Italic.ttf
+          style: italic