Skip to content

Commit

Permalink
feat: Add validation against passing both color and foreground to Inl…
Browse files Browse the repository at this point in the history
…ineTextStyle
  • Loading branch information
luanpotter committed Dec 30, 2024
1 parent 1f9b0ea commit b110b35
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
12 changes: 10 additions & 2 deletions packages/flame/lib/src/text/styles/inline_text_style.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ class InlineTextStyle extends FlameTextStyle {
this.decorationThickness,
this.background,
this.foreground,
});
}) : assert(
color == null || foreground == null,
'Cannot provide both color and foreground',
);

final Color? color;
final String? fontFamily;
Expand Down Expand Up @@ -84,10 +87,15 @@ class InlineTextStyle extends FlameTextStyle {
}

TextStyle asTextStyle() {
final fontSize = this.fontSize;
if (fontSize == null) {
throw Exception('fontSize must be set');
}

return TextStyle(
color: color,
fontFamily: fontFamily,
fontSize: fontSize! * (fontScale ?? 1.0),
fontSize: fontSize * (fontScale ?? 1.0),
fontWeight: fontWeight,
fontStyle: fontStyle,
letterSpacing: letterSpacing,
Expand Down
32 changes: 32 additions & 0 deletions packages/flame/test/text/text_style_test.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:flame/text.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart' show throwsAssertionError;
import 'package:test/test.dart';

void main() {
Expand Down Expand Up @@ -140,5 +141,36 @@ void main() {
expect(styles[3].fontStyle, FontStyle.italic);
expect(styles[3].fontFamily, 'Arial');
});

test("inline text style can be converted to Flutter's text style", () {
final withColor = InlineTextStyle(
color: const Color(0xFF00FF00),
fontSize: 12,
);
final withColorTextStyle = withColor.asTextStyle();
expect(withColorTextStyle.color, const Color(0xFF00FF00));
expect(withColorTextStyle.foreground, isNull);

final paint = Paint()..color = const Color(0xFF00FF00);
final withForeground = InlineTextStyle(
foreground: paint,
fontSize: 12,
);
final withForegroundTextStyle = withForeground.asTextStyle();
expect(withForegroundTextStyle.foreground, paint);
expect(withForegroundTextStyle.color, isNull);

// try setting both options will throw an error
expect(
() {
InlineTextStyle(
color: const Color(0xFF00FF00),
foreground: paint,
fontSize: 12,
).asTextStyle();
},
throwsAssertionError,
);
});
});
}

0 comments on commit b110b35

Please sign in to comment.