Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,42 @@ Widget build(BuildContext context) {
}
```

To customize the generated SVG API, set `flutter_svg_class` to a class that extends the generated `SvgGenImage`.
SVG assets are then typed and instantiated with that class, so overridden methods such as `svg()` and any added methods are available on every asset.

```yaml
# pubspec.yaml
flutter_gen:
integrations:
flutter_svg: true
flutter_svg_class:
name: AppSvgGenImage
import: package:my_app/app_svg_gen_image.dart
```

```dart
// lib/app_svg_gen_image.dart
import 'package:flutter/widgets.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:my_app/gen/assets.gen.dart';

class AppSvgGenImage extends SvgGenImage {
const AppSvgGenImage(super.assetName, {super.size, super.flavors});

const AppSvgGenImage.vec(super.assetName, {super.size, super.flavors})
: super.vec();

Widget square(double dimension, {Color? color}) {
return svg(
width: dimension,
height: dimension,
colorFilter:
color == null ? null : ColorFilter.mode(color, BlendMode.srcIn),
);
}
}
```

**Available Integrations**

| Packages | File extension | Setting | Usage |
Expand Down
2 changes: 2 additions & 0 deletions examples/example/lib/gen/assets.gen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,7 @@ class SvgGenImage {
AlignmentGeometry alignment = Alignment.center,
bool allowDrawingOutsideViewBox = false,
WidgetBuilder? placeholderBuilder,
_svg.SvgErrorWidgetBuilder? errorBuilder,
String? semanticsLabel,
bool excludeFromSemantics = false,
_svg.SvgTheme? theme,
Expand Down Expand Up @@ -395,6 +396,7 @@ class SvgGenImage {
alignment: alignment,
allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
placeholderBuilder: placeholderBuilder,
errorBuilder: errorBuilder,
semanticsLabel: semanticsLabel,
excludeFromSemantics: excludeFromSemantics,
colorFilter: colorFilter ??
Expand Down
2 changes: 2 additions & 0 deletions examples/example_resources/lib/gen/assets.gen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,7 @@ class SvgGenImage {
AlignmentGeometry alignment = Alignment.center,
bool allowDrawingOutsideViewBox = false,
WidgetBuilder? placeholderBuilder,
_svg.SvgErrorWidgetBuilder? errorBuilder,
String? semanticsLabel,
bool excludeFromSemantics = false,
_svg.SvgTheme? theme,
Expand Down Expand Up @@ -230,6 +231,7 @@ class SvgGenImage {
alignment: alignment,
allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
placeholderBuilder: placeholderBuilder,
errorBuilder: errorBuilder,
semanticsLabel: semanticsLabel,
excludeFromSemantics: excludeFromSemantics,
colorFilter: colorFilter ??
Expand Down
6 changes: 6 additions & 0 deletions packages/core/lib/generators/assets_generator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,12 @@ Future<String> generateAssets(
SvgIntegration(
config.packageParameterLiteral,
parseMetadata: config.flutterGen.parseMetadata,
customClassName: config.flutterGen.integrations.flutterSvgClass?.name,
customClassImport:
config.flutterGen.integrations.flutterSvgClass?.import,
resolvedVersion: config.integrationResolvedVersions[SvgIntegration],
resolvedVersionConstraint:
config.integrationResolvedVersionConstraints[SvgIntegration],
),
if (config.flutterGen.integrations.rive)
RiveIntegration(
Expand Down
62 changes: 53 additions & 9 deletions packages/core/lib/generators/integrations/svg_integration.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,66 @@ import 'dart:io';

import 'package:flutter_gen_core/generators/integrations/integration.dart';
import 'package:flutter_gen_core/utils/log.dart';
import 'package:pub_semver/pub_semver.dart'
show Version, VersionConstraint, VersionRange;
import 'package:vector_graphics_compiler/vector_graphics_compiler.dart';

class SvgIntegration extends Integration {
SvgIntegration(
String packageName, {
super.parseMetadata,
}) : super(packageName);
this.customClassName,
this.customClassImport,
Version? resolvedVersion,
VersionConstraint? resolvedVersionConstraint,
}) : supportsErrorBuilder = _resolveErrorBuilderSupport(
resolvedVersion,
resolvedVersionConstraint,
),
super(packageName);

/// A user-defined subclass of `SvgGenImage` used to instantiate assets.
final String? customClassName;

/// The import URI of the library that declares [customClassName].
final String? customClassImport;

/// The minimum flutter_svg version that provides `SvgPicture.errorBuilder`.
static final errorBuilderMinimumSupportVersion = Version(2, 0, 17);

/// Whether the generated `svg()` exposes `errorBuilder`.
final bool supportsErrorBuilder;

static bool _resolveErrorBuilderSupport(
Version? resolvedVersion,
VersionConstraint? resolvedVersionConstraint,
) {
// Resolve by version.
if (resolvedVersion != null) {
return resolvedVersion >= errorBuilderMinimumSupportVersion;
}
// Resolve by version constraint.
if (resolvedVersionConstraint != null) {
return resolvedVersionConstraint.allowsAny(
VersionRange(min: errorBuilderMinimumSupportVersion, includeMin: true),
);
}
// Use the latest version as the fallback.
return true;
}

String get packageExpression => isPackage ? ' = package' : '';

@override
List<Import> get requiredImports => const [
Import('package:flutter/widgets.dart'),
Import('package:flutter/services.dart'),
Import('package:flutter_svg/flutter_svg.dart', alias: '_svg'),
Import('package:vector_graphics/vector_graphics.dart', alias: '_vg'),
List<Import> get requiredImports => [
const Import('package:flutter/widgets.dart'),
const Import('package:flutter/services.dart'),
const Import('package:flutter_svg/flutter_svg.dart', alias: '_svg'),
const Import(
'package:vector_graphics/vector_graphics.dart',
alias: '_vg',
),
if (customClassImport case final import?) Import(import),
];

@override
Expand Down Expand Up @@ -54,7 +98,7 @@ ${isPackage ? "\n static const String package = '$packageName';" : ''}
AlignmentGeometry alignment = Alignment.center,
bool allowDrawingOutsideViewBox = false,
WidgetBuilder? placeholderBuilder,
String? semanticsLabel,
${supportsErrorBuilder ? '_svg.SvgErrorWidgetBuilder? errorBuilder,\n ' : ''}String? semanticsLabel,
bool excludeFromSemantics = false,
_svg.SvgTheme? theme,
_svg.ColorMapper? colorMapper,
Expand Down Expand Up @@ -90,7 +134,7 @@ ${isPackage ? "\n static const String package = '$packageName';" : ''}
alignment: alignment,
allowDrawingOutsideViewBox: allowDrawingOutsideViewBox,
placeholderBuilder: placeholderBuilder,
semanticsLabel: semanticsLabel,
${supportsErrorBuilder ? 'errorBuilder: errorBuilder,\n ' : ''}semanticsLabel: semanticsLabel,
excludeFromSemantics: excludeFromSemantics,
colorFilter: colorFilter ?? (color == null ? null : ColorFilter.mode(color, colorBlendMode)),
clipBehavior: clipBehavior,
Expand All @@ -104,7 +148,7 @@ ${isPackage ? "\n static const String package = '$packageName';" : ''}
}''';

@override
String get className => 'SvgGenImage';
String get className => customClassName ?? 'SvgGenImage';

static const vectorCompileTransformer = 'vector_graphics_compiler';

Expand Down
24 changes: 24 additions & 0 deletions packages/core/lib/settings/pubspec.dart
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ class FlutterGenIntegrations {
required this.flutterSvg,
required this.rive,
required this.lottie,
this.flutterSvgClass,
});

factory FlutterGenIntegrations.fromJson(Map json) =>
Expand All @@ -272,6 +273,29 @@ class FlutterGenIntegrations {

@JsonKey(name: 'lottie', required: true)
final bool lottie;

/// A user-defined subclass of `SvgGenImage` used to instantiate SVG assets.
@JsonKey(name: 'flutter_svg_class')
final FlutterGenIntegrationClass? flutterSvgClass;
}

@JsonSerializable()
class FlutterGenIntegrationClass {
const FlutterGenIntegrationClass({
required this.name,
required this.import,
});

factory FlutterGenIntegrationClass.fromJson(Map json) =>
_$FlutterGenIntegrationClassFromJson(json);

/// The class name, which must extend the generated integration class.
@JsonKey(name: 'name', required: true)
final String name;

/// The import URI of the library that declares the class.
@JsonKey(name: 'import', required: true)
final String import;
}

@JsonSerializable()
Expand Down
36 changes: 34 additions & 2 deletions packages/core/lib/settings/pubspec.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

101 changes: 101 additions & 0 deletions packages/core/test/assets_gen_integrations_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,107 @@ void main() {
);
});

test('Assets with a custom Svg class on pubspec.yaml', () async {
const pubspec = 'test_resources/pubspec_assets_svg_custom_class.yaml';
await expectedAssetsGen(pubspec);

final integration = SvgIntegration(
'',
customClassName: 'AppSvgGenImage',
customClassImport: 'package:test/app_svg_gen_image.dart',
);
// Assets are typed and instantiated with the custom class.
expect(integration.className, 'AppSvgGenImage');
expect(
integration.classInstantiate(
AssetType(
rootPath: resPath,
path: 'assets/path/dog.svg',
flavors: {},
transformers: {},
),
),
'AppSvgGenImage(\'assets/path/dog.svg\')',
);
expect(
integration.classInstantiate(
AssetType(
rootPath: resPath,
path: 'assets/path/dog.vec',
flavors: {},
transformers: {},
),
),
'AppSvgGenImage.vec(\'assets/path/dog.vec\')',
);
expect(
integration.requiredImports,
contains(const Import('package:test/app_svg_gen_image.dart')),
);
// The base class is still generated for the custom class to extend.
expect(integration.classOutput.contains('class SvgGenImage {'), isTrue);
});

test('SvgIntegration errorBuilder resolution with resolvedVersion', () {
// Test with version < 2.0.17 (should not expose errorBuilder)
final oldIntegration = SvgIntegration(
'',
resolvedVersion: Version(2, 0, 16),
);
expect(oldIntegration.supportsErrorBuilder, isFalse);
expect(oldIntegration.classOutput.contains('errorBuilder'), isFalse);

// Test with version >= 2.0.17 (should expose errorBuilder)
final supportedIntegration = SvgIntegration(
'',
resolvedVersion: Version(2, 0, 17),
);
expect(supportedIntegration.supportsErrorBuilder, isTrue);
expect(
supportedIntegration.classOutput.contains(
'_svg.SvgErrorWidgetBuilder? errorBuilder,',
),
isTrue,
);
expect(
supportedIntegration.classOutput.contains(
'errorBuilder: errorBuilder,',
),
isTrue,
);
});

test('SvgIntegration errorBuilder resolution with version constraint', () {
// Test with constraint that allows 2.0.17 (should expose errorBuilder)
final allowsSupported = SvgIntegration(
'',
resolvedVersionConstraint: VersionConstraint.parse('^2.0.0'),
);
expect(allowsSupported.supportsErrorBuilder, isTrue);

// Test with constraint that excludes 2.0.17 (should not expose errorBuilder)
final excludesSupported = SvgIntegration(
'',
resolvedVersionConstraint: VersionConstraint.parse('>=2.0.0 <2.0.17'),
);
expect(excludesSupported.supportsErrorBuilder, isFalse);
expect(excludesSupported.classOutput.contains('errorBuilder'), isFalse);
});

test('SvgIntegration errorBuilder resolution priority and fallback', () {
// resolvedVersion should take priority over resolvedVersionConstraint
final integration = SvgIntegration(
'',
resolvedVersion: Version(2, 0, 9),
resolvedVersionConstraint: VersionConstraint.parse('^2.0.0'),
);
expect(integration.supportsErrorBuilder, isFalse);

// Test with no version information (should expose errorBuilder as fallback)
final fallbackIntegration = SvgIntegration('');
expect(fallbackIntegration.supportsErrorBuilder, isTrue);
});

test('Assets with Rive integrations on pubspec.yaml', () async {
const pubspec = 'test_resources/pubspec_assets_rive_integrations.yaml';
await expectedAssetsGen(pubspec);
Expand Down
Loading