diff --git a/packages/syncfusion_flutter_barcodes/CHANGELOG.md b/packages/syncfusion_flutter_barcodes/CHANGELOG.md index 2181d1b23..2533f0f63 100644 --- a/packages/syncfusion_flutter_barcodes/CHANGELOG.md +++ b/packages/syncfusion_flutter_barcodes/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of our Flutter barcodes widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter barcodes widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter barcodes example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter barcodes example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_barcodes/example/lib/main.dart b/packages/syncfusion_flutter_barcodes/example/lib/main.dart index 8d333b1eb..ddec1a8fe 100644 --- a/packages/syncfusion_flutter_barcodes/example/lib/main.dart +++ b/packages/syncfusion_flutter_barcodes/example/lib/main.dart @@ -11,18 +11,18 @@ class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( - appBar: AppBar( - title: const Text('Barcode Generator Demo'), - ), - body: Center( - child: Container( + appBar: AppBar(title: const Text('Barcode Generator Demo')), + body: Center( + child: Container( height: 200, child: SfBarcodeGenerator( value: 'www.syncfusion.com', symbology: QRCode(), showValue: true, ), - ))), + ), + ), + ), ); } } diff --git a/packages/syncfusion_flutter_barcodes/example/pubspec.yaml b/packages/syncfusion_flutter_barcodes/example/pubspec.yaml index 76d0b94a8..deef8cd6a 100644 --- a/packages/syncfusion_flutter_barcodes/example/pubspec.yaml +++ b/packages/syncfusion_flutter_barcodes/example/pubspec.yaml @@ -1,20 +1,10 @@ name: example description: A new Flutter project. -# 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 used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -22,53 +12,12 @@ dependencies: syncfusion_flutter_barcodes: path: ../ - # 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 - -# 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. 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: - # - 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 diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/barcode_generator.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/barcode_generator.dart index 6f45d19d3..9c1d85f4e 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/barcode_generator.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/barcode_generator.dart @@ -84,18 +84,18 @@ class SfBarcodeGenerator extends StatefulWidget { /// must not be null or empty. /// /// Default symbology is [Code128]. - SfBarcodeGenerator( - {Key? key, - required this.value, - Symbology? symbology, - this.barColor, - this.backgroundColor, - this.showValue = false, - this.textSpacing = 2, - this.textAlign = TextAlign.center, - this.textStyle}) - : symbology = symbology ?? Code128(), - super(key: key); + SfBarcodeGenerator({ + Key? key, + required this.value, + Symbology? symbology, + this.barColor, + this.backgroundColor, + this.showValue = false, + this.textSpacing = 2, + this.textAlign = TextAlign.center, + this.textStyle, + }) : symbology = symbology ?? Code128(), + super(key: key); /// Defines the value of the barcode to be rendered. /// @@ -268,40 +268,51 @@ class _SfBarcodeGeneratorState extends State { @override void didChangeDependencies() { - _barcodeThemeData = - _updateThemeData(Theme.of(context), SfBarcodeTheme.of(context)); + _barcodeThemeData = _updateThemeData( + Theme.of(context), + SfBarcodeTheme.of(context), + ); super.didChangeDependencies(); } SfBarcodeThemeData _updateThemeData( - ThemeData themeData, SfBarcodeThemeData barcodeThemeData) { + ThemeData themeData, + SfBarcodeThemeData barcodeThemeData, + ) { final SfBarcodeThemeData effectiveThemeData = BarcodeThemeData(context); barcodeThemeData = barcodeThemeData.copyWith( - backgroundColor: barcodeThemeData.backgroundColor ?? - widget.backgroundColor ?? - effectiveThemeData.backgroundColor, - barColor: barcodeThemeData.barColor ?? - widget.barColor ?? - effectiveThemeData.barColor, - textStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: - barcodeThemeData.textColor ?? effectiveThemeData.textColor) - .merge(barcodeThemeData.textStyle) - .merge(widget.textStyle)); + backgroundColor: + barcodeThemeData.backgroundColor ?? + widget.backgroundColor ?? + effectiveThemeData.backgroundColor, + barColor: + barcodeThemeData.barColor ?? + widget.barColor ?? + effectiveThemeData.barColor, + textStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: barcodeThemeData.textColor ?? effectiveThemeData.textColor, + ) + .merge(barcodeThemeData.textStyle) + .merge(widget.textStyle), + ); return barcodeThemeData; } @override void didUpdateWidget(SfBarcodeGenerator oldWidget) { - _barcodeThemeData = - _updateThemeData(Theme.of(context), SfBarcodeTheme.of(context)); + _barcodeThemeData = _updateThemeData( + Theme.of(context), + SfBarcodeTheme.of(context), + ); if (widget.showValue && (oldWidget.value != widget.value || oldWidget.textStyle != widget.textStyle)) { - _textSize = - measureText(widget.value.toString(), _barcodeThemeData.textStyle!); + _textSize = measureText( + widget.value.toString(), + _barcodeThemeData.textStyle!, + ); } if (widget.symbology != oldWidget.symbology) { @@ -352,23 +363,26 @@ class _SfBarcodeGeneratorState extends State { @override Widget build(BuildContext context) { if (widget.showValue && _textSize == null) { - _textSize = - measureText(widget.value.toString(), _barcodeThemeData.textStyle!); + _textSize = measureText( + widget.value.toString(), + _barcodeThemeData.textStyle!, + ); } _symbologyRenderer.getIsValidateInput(widget.value!); _symbologyRenderer.textSize = _textSize; return Container( color: widget.backgroundColor ?? _barcodeThemeData.backgroundColor, child: SfBarcodeGeneratorRenderObjectWidget( - value: widget.value!, - symbology: widget.symbology, - foregroundColor: widget.barColor ?? _barcodeThemeData.barColor, - showText: widget.showValue, - textSpacing: widget.textSpacing, - textStyle: _barcodeThemeData.textStyle!, - symbologyRenderer: _symbologyRenderer, - textSize: _textSize, - textAlign: widget.textAlign), + value: widget.value!, + symbology: widget.symbology, + foregroundColor: widget.barColor ?? _barcodeThemeData.barColor, + showText: widget.showValue, + textSpacing: widget.textSpacing, + textStyle: _barcodeThemeData.textStyle!, + symbologyRenderer: _symbologyRenderer, + textSize: _textSize, + textAlign: widget.textAlign, + ), ); } } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/symbology_base.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/symbology_base.dart index 408e65e8d..80760587e 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/symbology_base.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/base/symbology_base.dart @@ -11,10 +11,11 @@ abstract class Symbology { /// The arguments [module] must be non-negative and greater than 0. /// Symbology({this.module}) - : assert( - (module != null && module > 0) || module == null, - 'Module must' - ' not be a non-negative value or else it must be equal to null.'); + : assert( + (module != null && module > 0) || module == null, + 'Module must' + ' not be a non-negative value or else it must be equal to null.', + ); /// Specifies the size of the smallest line or dot of the barcode. /// diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/common/barcode_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/common/barcode_renderer.dart index fa961a972..d9bb362f2 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/common/barcode_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/common/barcode_renderer.dart @@ -5,18 +5,18 @@ import '../renderers/one_dimensional/symbology_base_renderer.dart'; /// Represents the render object widget class SfBarcodeGeneratorRenderObjectWidget extends LeafRenderObjectWidget { /// Creates the render object widget - const SfBarcodeGeneratorRenderObjectWidget( - {Key? key, - this.value, - this.symbology, - this.foregroundColor, - this.showText, - this.textSpacing, - this.textStyle, - this.textSize, - this.symbologyRenderer, - this.textAlign}) - : super(key: key); + const SfBarcodeGeneratorRenderObjectWidget({ + Key? key, + this.value, + this.symbology, + this.foregroundColor, + this.showText, + this.textSpacing, + this.textStyle, + this.textSize, + this.symbologyRenderer, + this.textAlign, + }) : super(key: key); ///Defines the value of the barcode to be rendered. final String? value; @@ -49,15 +49,16 @@ class SfBarcodeGeneratorRenderObjectWidget extends LeafRenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return _RenderBarcode( - value: value!, - symbology: symbology!, - foregroundColor: foregroundColor!, - showText: showText!, - textSpacing: textSpacing!, - symbologyRenderer: symbologyRenderer!, - textStyle: textStyle!, - textSize: textSize, - textAlign: textAlign!); + value: value!, + symbology: symbology!, + foregroundColor: foregroundColor!, + showText: showText!, + textSpacing: textSpacing!, + symbologyRenderer: symbologyRenderer!, + textStyle: textStyle!, + textSize: textSize, + textAlign: textAlign!, + ); } @override @@ -79,25 +80,25 @@ class SfBarcodeGeneratorRenderObjectWidget extends LeafRenderObjectWidget { /// Represents the RenderBarcode class class _RenderBarcode extends RenderBox { /// Creates the RenderBarcode - _RenderBarcode( - {required String value, - required Symbology symbology, - required SymbologyRenderer symbologyRenderer, - required Color foregroundColor, - required bool showText, - required double textSpacing, - required TextStyle textStyle, - Size? textSize, - required TextAlign textAlign}) - : _value = value, - _symbology = symbology, - _symbologyRenderer = symbologyRenderer, - _foregroundColor = foregroundColor, - _showText = showText, - _textSpacing = textSpacing, - _textStyle = textStyle, - _textSize = textSize, - _textAlign = textAlign; + _RenderBarcode({ + required String value, + required Symbology symbology, + required SymbologyRenderer symbologyRenderer, + required Color foregroundColor, + required bool showText, + required double textSpacing, + required TextStyle textStyle, + Size? textSize, + required TextAlign textAlign, + }) : _value = value, + _symbology = symbology, + _symbologyRenderer = symbologyRenderer, + _foregroundColor = foregroundColor, + _showText = showText, + _textSpacing = textSpacing, + _textStyle = textStyle, + _textSize = textSize, + _textAlign = textAlign; /// Represents the barcode value String _value; @@ -245,20 +246,21 @@ class _RenderBarcode extends RenderBox { @override void paint(PaintingContext context, Offset offset) { symbologyRenderer.renderBarcode( - context.canvas, - Size( - size.width, - size.height - - (showText - ? (_textSpacing + - (_textSize != null ? _textSize!.height : 0)) - : 0)), - offset, - value, - foregroundColor, - textStyle, - textSpacing, - textAlign, - showText); + context.canvas, + Size( + size.width, + size.height - + (showText + ? (_textSpacing + (_textSize != null ? _textSize!.height : 0)) + : 0), + ), + offset, + value, + foregroundColor, + textStyle, + textSpacing, + textAlign, + showText, + ); } } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code128_symbology.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code128_symbology.dart index 729d578e3..e6a412ba6 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code128_symbology.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code128_symbology.dart @@ -18,8 +18,5 @@ class Code128 extends Symbology { /// This is a very large method. This method could be /// refactor to a smaller methods, but it degrades the performance.Since it /// adds the character corresponding to this symbology is added in to the list - Code128({int? module}) - : super( - module: module, - ); + Code128({int? module}) : super(module: module); } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code39_extended_symbology.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code39_extended_symbology.dart index 305fc0f65..59775e72f 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code39_extended_symbology.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/one_dimensional/code39_extended_symbology.dart @@ -18,5 +18,5 @@ class Code39Extended extends Code39 { /// refactored to a smaller methods, but it degrades the performance.Since it /// adds character corresponding to this symbology is added in to the list Code39Extended({int? module, bool? enableCheckSum}) - : super(module: module, enableCheckSum: enableCheckSum ?? true); + : super(module: module, enableCheckSum: enableCheckSum ?? true); } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/codabar_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/codabar_renderer.dart index d4be76371..2d83daaba 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/codabar_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/codabar_renderer.dart @@ -27,7 +27,7 @@ class CodabarRenderer extends SymbologyRenderer { 'A': '1011001001', 'B': '1001001011', 'C': '1010010011', - 'D': '1010011001' + 'D': '1010011001', }; } @@ -43,7 +43,8 @@ class CodabarRenderer extends SymbologyRenderer { value[i] == 'C' || value[i] == 'D') { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; @@ -51,24 +52,34 @@ class CodabarRenderer extends SymbologyRenderer { @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { final Paint paint = getBarPaint(foregroundColor); final List code = _getCodeValues(value); final int barTotalLength = _getTotalLength(code); - double left = symbology!.module == null - ? offset.dx - : getLeftPosition( - barTotalLength, symbology!.module!, size.width, offset.dx); + double left = + symbology!.module == null + ? offset.dx + : getLeftPosition( + barTotalLength, + symbology!.module!, + size.width, + offset.dx, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology!.module != null) { ratio = symbology!.module!.toDouble(); @@ -91,7 +102,11 @@ class CodabarRenderer extends SymbologyRenderer { if (canDraw && (left >= barCodeRect.left && left + ratio < barCodeRect.right)) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + barHeight); + left, + offset.dy, + left + ratio, + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } left += ratio; @@ -124,8 +139,10 @@ class CodabarRenderer extends SymbologyRenderer { /// Returns the encoded value of the provided input value List _getCodeValues(String value) { valueWithStartAndStopSymbol = _getValueWithStartAndStopSymbol(value); - final List codeBarValues = - List.filled(valueWithStartAndStopSymbol.length, null); + final List codeBarValues = List.filled( + valueWithStartAndStopSymbol.length, + null, + ); for (int i = 0; i < valueWithStartAndStopSymbol.length; i++) { for (int j = 0; j < _codeBarMap.length; j++) { if (valueWithStartAndStopSymbol[i] == diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128_renderer.dart index b153815b2..ebdb6b788 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128_renderer.dart @@ -421,7 +421,7 @@ class Code128Renderer extends SymbologyRenderer { [2, 1, 1, 4, 1, 2], [2, 1, 1, 2, 1, 4], [2, 1, 1, 2, 3, 2], - [2, 3, 3, 1, 1, 1, 2] + [2, 3, 3, 1, 1, 1, 2], ]; } @@ -439,7 +439,8 @@ class Code128Renderer extends SymbologyRenderer { return true; } else { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return false; @@ -454,8 +455,11 @@ class Code128Renderer extends SymbologyRenderer { int codeTypeValue = 0; int currentPosition = 0; while (currentPosition < value.length) { - final int currentCodeType = - _getValidatedCode(currentPosition, codeTypeValue, value); + final int currentCodeType = _getValidatedCode( + currentPosition, + codeTypeValue, + value, + ); int currentIndex; if (currentCodeType == codeTypeValue) { final int currentValue = value[currentPosition].codeUnitAt(0); @@ -484,7 +488,8 @@ class Code128Renderer extends SymbologyRenderer { value[currentPosition].codeUnitAt(0) - ' '.codeUnitAt(0); } else { currentIndex = int.parse( - value.substring(currentPosition, currentPosition + 2)); + value.substring(currentPosition, currentPosition + 2), + ); currentPosition++; } } @@ -526,8 +531,12 @@ class Code128Renderer extends SymbologyRenderer { /// Method to validate the corresponding code set based on the input int _getValidatedCode(int start, int previousCodeSet, String value) { CodeType codeType = _getCodeType(start, value); - final int? currentCodeType = - _getValidatedCodeTypes(start, previousCodeSet, value, codeType); + final int? currentCodeType = _getValidatedCodeTypes( + start, + previousCodeSet, + value, + codeType, + ); if (currentCodeType != null) { return currentCodeType; } @@ -569,7 +578,11 @@ class Code128Renderer extends SymbologyRenderer { /// Method to get the validated types int? _getValidatedCodeTypes( - int start, int previousCodeSet, String value, CodeType codeType) { + int start, + int previousCodeSet, + String value, + CodeType codeType, + ) { if (codeType == CodeType.singleDigit) { if (previousCodeSet == _codeA) { return _codeA; @@ -629,22 +642,28 @@ class Code128Renderer extends SymbologyRenderer { @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { final Paint paint = getBarPaint(foregroundColor); final List> encodedValue = _getEncodedValue(value); final int totalBarLength = _getTotalBarLength(encodedValue); - double left = symbology?.module == null - ? offset.dx - : getLeftPosition( - totalBarLength, symbology?.module, size.width, offset.dx); + double left = + symbology?.module == null + ? offset.dx + : getLeftPosition( + totalBarLength, + symbology?.module, + size.width, + offset.dx, + ); double ratio = 0; if (symbology?.module != null) { ratio = symbology!.module!.toDouble(); @@ -665,7 +684,11 @@ class Code128Renderer extends SymbologyRenderer { for (int k = 0; k < currentValue; k++) { if (canDraw) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + size.height); + left, + offset.dy, + left + ratio, + offset.dy + size.height, + ); canvas.drawRect(individualBarRect, paint); } left += ratio; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128a_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128a_renderer.dart index ebfcc94b2..84713cf41 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128a_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128a_renderer.dart @@ -11,7 +11,8 @@ class Code128ARenderer extends Code128Renderer { for (int i = 0; i < value.length; i++) { if (!code128ACharacterSets.contains(value[i])) { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128b_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128b_renderer.dart index f4fd12440..83203783d 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128b_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128b_renderer.dart @@ -11,7 +11,8 @@ class Code128BRenderer extends Code128Renderer { for (int i = 0; i < value.length; i++) { if (!code128BCharacterSets.contains(value[i])) { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128c_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128c_renderer.dart index 155f410fd..3a8a7fcd5 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128c_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code128c_renderer.dart @@ -11,7 +11,8 @@ class Code128CRenderer extends Code128Renderer { for (int i = 0; i < value.length; i++) { if (!code128CCharacterSets.contains(value[i])) { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_extended_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_extended_renderer.dart index 5646a19c0..203f6207c 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_extended_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_extended_renderer.dart @@ -146,7 +146,8 @@ class Code39ExtendedRenderer extends Code39Renderer { for (int i = 0; i < value.length; i++) { if (value[i].codeUnitAt(0) > 127) { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_renderer.dart index 99d12b119..565b2cd0b 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code39_renderer.dart @@ -52,7 +52,7 @@ class Code39Renderer extends SymbologyRenderer { '121212111', '121211121', '121112121', - '111212121' + '111212121', ]; _character = _getCode39Character(); @@ -69,7 +69,8 @@ class Code39Renderer extends SymbologyRenderer { for (int i = 0; i < value.length; i++) { if (!_character.contains(value[i])) { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; @@ -93,7 +94,9 @@ class Code39Renderer extends SymbologyRenderer { /// Returns the pattern collection based on the provided input List _getPatternCollection( - String providedValue, String code39Characters) { + String providedValue, + String code39Characters, + ) { final List code39Values = []; for (int i = 0; i < providedValue.length; i++) { final int currentIndex = code39Characters.indexOf(providedValue[i]); @@ -104,24 +107,34 @@ class Code39Renderer extends SymbologyRenderer { @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { final Paint paint = getBarPaint(foregroundColor); final List code = getCodeValues(value); final int barTotalLength = _getTotalLength(code); - double left = symbology?.module == null - ? offset.dx - : getLeftPosition( - barTotalLength, symbology?.module, size.width, offset.dx); + double left = + symbology?.module == null + ? offset.dx + : getLeftPosition( + barTotalLength, + symbology?.module, + size.width, + offset.dx, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology?.module != null) { ratio = symbology!.module!.toDouble(); @@ -144,8 +157,12 @@ class Code39Renderer extends SymbologyRenderer { if (canDraw && (left >= barCodeRect.left && left + (currentValue * ratio) < barCodeRect.right)) { - final Rect individualBarRect = Rect.fromLTRB(left, offset.dy, - left + (currentValue * ratio), offset.dy + barHeight); + final Rect individualBarRect = Rect.fromLTRB( + left, + offset.dy, + left + (currentValue * ratio), + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } left += currentValue * ratio; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code93_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code93_renderer.dart index 07c206e21..ba2fce3bd 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code93_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/code93_renderer.dart @@ -18,7 +18,8 @@ class Code93Renderer extends SymbologyRenderer { for (int i = 0; i < value.length; i++) { if (!_character.contains(value[i])) { throw ArgumentError( - 'The provided input cannot be encoded : ${value[i]}'); + 'The provided input cannot be encoded : ${value[i]}', + ); } } return true; @@ -132,24 +133,34 @@ class Code93Renderer extends SymbologyRenderer { @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { final Paint paint = getBarPaint(foregroundColor); final List code = _getCodeValues(value); final int barTotalLength = _getTotalLength(code); - double left = symbology?.module == null - ? offset.dx - : getLeftPosition( - barTotalLength, symbology?.module, size.width, offset.dx); + double left = + symbology?.module == null + ? offset.dx + : getLeftPosition( + barTotalLength, + symbology?.module, + size.width, + offset.dx, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology?.module != null) { ratio = symbology!.module!.toDouble(); @@ -171,7 +182,11 @@ class Code93Renderer extends SymbologyRenderer { if (canDraw && (left >= barCodeRect.left && left + ratio < barCodeRect.right)) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + barHeight); + left, + offset.dy, + left + ratio, + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } left += ratio; @@ -183,8 +198,11 @@ class Code93Renderer extends SymbologyRenderer { } /// Represents the pattern collection based on the provided input - List _getPatternCollection(String givenCharacter, - Map codes, List encodingValue) { + List _getPatternCollection( + String givenCharacter, + Map codes, + List encodingValue, + ) { final List codeKey = codes.keys.toList(); for (int i = 0; i < givenCharacter.length; i++) { final int index = codeKey.indexOf(givenCharacter[i]); diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean13_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean13_renderer.dart index f9e6599db..427c51c20 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean13_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean13_renderer.dart @@ -18,16 +18,20 @@ class EAN13Renderer extends SymbologyRenderer { if (int.parse(value[12]) == _getCheckSumData(value)) { _encodedValue = value; } else { - throw ArgumentError('Invalid check digit at the trailing end. ' - 'Provide the valid check digit or remove it. ' - 'Since, it has been calculated automatically.'); + throw ArgumentError( + 'Invalid check digit at the trailing end. ' + 'Provide the valid check digit or remove it. ' + 'Since, it has been calculated automatically.', + ); } } else if (value.contains(RegExp(r'^(?=.*?[0-9]).{12}$'))) { _encodedValue = value + _getCheckSumData(value).toString(); } else { - throw ArgumentError('EAN13 supports only numeric characters. ' - 'The provided value should have 12 digits (without check digit) or' - ' with 13 digits.'); + throw ArgumentError( + 'EAN13 supports only numeric characters. ' + 'The provided value should have 12 digits (without check digit) or' + ' with 13 digits.', + ); } return true; } @@ -37,15 +41,16 @@ class EAN13Renderer extends SymbologyRenderer { /// to be passed @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { /// _singleDigitValues[0] specifies left value of start digit /// _singleDigitValues[1] specifies width of start digit final List singleDigitValues = List.filled(2, null); @@ -63,12 +68,21 @@ class EAN13Renderer extends SymbologyRenderer { const int additionalWidth = 2; singleDigitValues[1] = singleDigitValues[1]! + additionalWidth; final double width = size.width - singleDigitValues[1]!; - double left = symbology?.module == null - ? offset.dx + singleDigitValues[1]! - : getLeftPosition(barTotalLength, symbology?.module, width, - offset.dx + singleDigitValues[1]!); + double left = + symbology?.module == null + ? offset.dx + singleDigitValues[1]! + : getLeftPosition( + barTotalLength, + symbology?.module, + width, + offset.dx + singleDigitValues[1]!, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology?.module != null) { ratio = symbology!.module!.toDouble(); @@ -85,12 +99,13 @@ class EAN13Renderer extends SymbologyRenderer { final String codeValue = code[i]; final bool hasExtraHeight = getHasExtraHeight(i, code); final double additionalHeight = i == 2 ? 0.4 : 0.5; - final double barHeight = hasExtraHeight - ? size.height + - (showValue - ? (textSize!.height * additionalHeight) + textSpacing - : 0) - : size.height; + final double barHeight = + hasExtraHeight + ? size.height + + (showValue + ? (textSize!.height * additionalHeight) + textSpacing + : 0) + : size.height; final int codeLength = codeValue.length; for (int j = 0; j < codeLength; j++) { // Draw the barcode when the current code value is 1 @@ -98,7 +113,11 @@ class EAN13Renderer extends SymbologyRenderer { if (canDraw && (left >= barCodeRect.left && left + ratio < barCodeRect.right)) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + barHeight); + left, + offset.dy, + left + ratio, + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } left += ratio; @@ -118,8 +137,17 @@ class EAN13Renderer extends SymbologyRenderer { } } if (showValue) { - _paintText(canvas, offset, size, _encodedValue, textStyle, textSpacing, - textAlign, positions, singleDigitValues); + _paintText( + canvas, + offset, + size, + _encodedValue, + textStyle, + textSpacing, + textAlign, + positions, + singleDigitValues, + ); } } @@ -149,28 +177,28 @@ class EAN13Renderer extends SymbologyRenderer { 'L': [ // The L (left) type of encoding '0001101', '0011001', '0010011', '0111101', '0100011', - '0110001', '0101111', '0111011', '0110111', '0001011' + '0110001', '0101111', '0111011', '0110111', '0001011', ], 'G': [ // The G type of encoding '0100111', '0110011', '0011011', '0100001', '0011101', - '0111001', '0000101', '0010001', '0001001', '0010111' + '0111001', '0000101', '0010001', '0001001', '0010111', ], 'R': [ // The R (right) type of encoding '1110010', '1100110', '1101100', '1000010', '1011100', - '1001110', '1010000', '1000100', '1001000', '1110100' + '1001110', '1010000', '1000100', '1001000', '1110100', ], 'O': [ // The O (odd) encoding for UPC-E '0001101', '0011001', '0010011', '0111101', '0100011', - '0110001', '0101111', '0111011', '0110111', '0001011' + '0110001', '0101111', '0111011', '0110111', '0001011', ], 'E': [ // The E (even) encoding for UPC-E '0100111', '0110011', '0011011', '0100001', '0011101', - '0111001', '0000101', '0010001', '0001001', '0010111' - ] + '0111001', '0000101', '0010001', '0001001', '0010111', + ], }; } @@ -196,20 +224,22 @@ class EAN13Renderer extends SymbologyRenderer { '6': 'LGGGLL', '7': 'LGLGLG', '8': 'LGLGGL', - '9': 'LGGLGL' + '9': 'LGGLGL', }; } /// Method to calculate the check sum digit int _getCheckSumData(String value) { - final int sum1 = 3 * + final int sum1 = + 3 * (int.parse(value[11]) + int.parse(value[9]) + int.parse(value[7]) + int.parse(value[5]) + int.parse(value[3]) + int.parse(value[1])); - final int sum2 = int.parse(value[10]) + + final int sum2 = + int.parse(value[10]) + int.parse(value[8]) + int.parse(value[6]) + int.parse(value[4]) + @@ -250,15 +280,16 @@ class EAN13Renderer extends SymbologyRenderer { /// Method to render the input value of the barcode void _paintText( - Canvas canvas, - Offset offset, - Size size, - String value, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - List positions, - List singleDigitValues) { + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + List positions, + List singleDigitValues, + ) { final String value1 = value[0]; final String value2 = value.substring(1, 7); final String value3 = value.substring(7, 13); @@ -267,38 +298,41 @@ class EAN13Renderer extends SymbologyRenderer { // Renders the first digit of the input drawText( - canvas, - Offset(singleDigitValues[0]!, offset.dy + size.height + textSpacing), - Size(singleDigitValues[1]!, size.height), - value1, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(singleDigitValues[0]!, offset.dy + size.height + textSpacing), + Size(singleDigitValues[1]!, size.height), + value1, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the first six digits of encoded text drawText( - canvas, - Offset(positions[0]!, offset.dy), - Size(secondTextWidth, size.height), - value2, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[0]!, offset.dy), + Size(secondTextWidth, size.height), + value2, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the second six digits of encoded text drawText( - canvas, - Offset(positions[2]!, offset.dy), - Size(thirdTextWidth, size.height), - value3, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[2]!, offset.dy), + Size(thirdTextWidth, size.height), + value3, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); } } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean8_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean8_renderer.dart index ac0d3693a..c5b8321f2 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean8_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/ean8_renderer.dart @@ -17,31 +17,36 @@ class EAN8Renderer extends SymbologyRenderer { if (int.parse(value[7]) == _getCheckSumData(value)) { _encodedValue = value; } else { - throw ArgumentError('Invalid check digit at the trailing end. ' - 'Provide the valid check digit or remove it. ' - 'Since, it has been calculated automatically.'); + throw ArgumentError( + 'Invalid check digit at the trailing end. ' + 'Provide the valid check digit or remove it. ' + 'Since, it has been calculated automatically.', + ); } } else if (value.contains(RegExp(r'^(?=.*?[0-9]).{7}$'))) { _encodedValue = value + _getCheckSumData(value).toString(); } else { - throw ArgumentError('EAN8 supports only numeric characters.' - ' The provided value should have 7 digits (without check digit)' - ' or with 8 digits.'); + throw ArgumentError( + 'EAN8 supports only numeric characters.' + ' The provided value should have 7 digits (without check digit)' + ' or with 8 digits.', + ); } return true; } @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { /// _positions[0] specifies end position of start bar /// _positions[1] specifies start position of middle bar /// _positions[2] specifies end position of middle bar @@ -50,12 +55,21 @@ class EAN8Renderer extends SymbologyRenderer { final Paint paint = getBarPaint(foregroundColor); final List code = _getCodeValues(); final int barTotalLength = _getTotalLength(code); - double left = symbology?.module == null - ? offset.dx - : getLeftPosition( - barTotalLength, symbology?.module, size.width, offset.dx); + double left = + symbology?.module == null + ? offset.dx + : getLeftPosition( + barTotalLength, + symbology?.module, + size.width, + offset.dx, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology?.module != null) { @@ -72,12 +86,13 @@ class EAN8Renderer extends SymbologyRenderer { final String codeValue = code[i]; final bool hasExtraHeight = getHasExtraHeight(i, code); final double additionalHeight = i == 2 ? 0.4 : 0.5; - final double barHeight = hasExtraHeight - ? size.height + - (showValue - ? (textSize!.height * additionalHeight) + textSpacing - : 0) - : size.height; + final double barHeight = + hasExtraHeight + ? size.height + + (showValue + ? (textSize!.height * additionalHeight) + textSpacing + : 0) + : size.height; final int codeLength = codeValue.length; for (int j = 0; j < codeLength; j++) { // Draw the barcode when the current code value is 1 @@ -85,7 +100,11 @@ class EAN8Renderer extends SymbologyRenderer { if (canDraw && (left >= barCodeRect.left && left + ratio < barCodeRect.right)) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + barHeight); + left, + offset.dy, + left + ratio, + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } left += ratio; @@ -105,8 +124,16 @@ class EAN8Renderer extends SymbologyRenderer { } } if (showValue) { - _paintText(canvas, offset, size, _encodedValue, textStyle, textSpacing, - textAlign, positions); + _paintText( + canvas, + offset, + size, + _encodedValue, + textStyle, + textSpacing, + textAlign, + positions, + ); } } @@ -138,9 +165,11 @@ class EAN8Renderer extends SymbologyRenderer { /// Represents the encoded value for the first 6 digits of the input value String _getLeftValue(Map codes, bool isLeft) { String code = ''; - for (int i = isLeft ? 0 : _encodedValue.length - 4; - i < (isLeft ? _encodedValue.length - 4 : _encodedValue.length); - i++) { + for ( + int i = isLeft ? 0 : _encodedValue.length - 4; + i < (isLeft ? _encodedValue.length - 4 : _encodedValue.length); + i++ + ) { final int currentValue = int.parse(_encodedValue[i]); if (i == 0 || i == 4) { code = codes.entries.elementAt(currentValue).value; @@ -157,7 +186,8 @@ class EAN8Renderer extends SymbologyRenderer { for (int i = 0; i < value.length; i++) { final int sum1 = int.parse(value[1]) + int.parse(value[3]) + int.parse(value[5]); - final int sum2 = 3 * + final int sum2 = + 3 * (int.parse(value[0]) + int.parse(value[2]) + int.parse(value[4]) + @@ -196,7 +226,7 @@ class EAN8Renderer extends SymbologyRenderer { '6': '1010000', '7': '1000100', '8': '1001000', - '9': '1110100' + '9': '1110100', }; } return codes; @@ -204,14 +234,15 @@ class EAN8Renderer extends SymbologyRenderer { /// Method to render the input value of the barcode void _paintText( - Canvas canvas, - Offset offset, - Size size, - String value, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - List positions) { + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + List positions, + ) { final String value1 = value.substring(0, 4); final String value2 = value.substring(4, 8); final double firstTextWidth = positions[1]! - positions[0]!; @@ -219,26 +250,28 @@ class EAN8Renderer extends SymbologyRenderer { // Renders the first four digits of input drawText( - canvas, - Offset(positions[0]!, offset.dy), - Size(firstTextWidth, size.height), - value1, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[0]!, offset.dy), + Size(firstTextWidth, size.height), + value1, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the last four digits of input drawText( - canvas, - Offset(positions[2]!, offset.dy), - Size(secondTextWidth, size.height), - value2, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[2]!, offset.dy), + Size(secondTextWidth, size.height), + value2, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); } } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/symbology_base_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/symbology_base_renderer.dart index 52a29d4e0..78619c40a 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/symbology_base_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/symbology_base_renderer.dart @@ -28,15 +28,16 @@ abstract class SymbologyRenderer { /// Method to render the barcode value void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue); + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ); /// Renders the paint for the bar code Paint getBarPaint(Color foregroundColor) { @@ -48,7 +49,11 @@ abstract class SymbologyRenderer { /// Calculates the left value of the initial bar code double getLeftPosition( - int barWidth, int? module, double width, double offsetX) { + int barWidth, + int? module, + double width, + double offsetX, + ) { final int calculatedWidth = barWidth * module!; // Calculates the left position of the barcode based on the provided // module value @@ -58,12 +63,23 @@ abstract class SymbologyRenderer { } /// Method to render the input value of the barcode - void drawText(Canvas canvas, Offset offset, Size size, String value, - TextStyle textStyle, double textSpacing, TextAlign textAlign, - [Offset? actualOffset, Size? actualSize]) { + void drawText( + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, [ + Offset? actualOffset, + Size? actualSize, + ]) { final TextSpan span = TextSpan(text: value, style: textStyle); final TextPainter textPainter = TextPainter( - text: span, textDirection: TextDirection.ltr, textAlign: textAlign); + text: span, + textDirection: TextDirection.ltr, + textAlign: textAlign, + ); textPainter.layout(); double x; double y; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upca_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upca_renderer.dart index ee6265045..cc45289ad 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upca_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upca_renderer.dart @@ -20,14 +20,18 @@ class UPCARenderer extends SymbologyRenderer { if (int.parse(value[11]) == _getCheckSumData(value)) { _encodedValue = value; } else { - throw ArgumentError('Invalid check digit at the trailing end.' - ' Provide the valid check digit or remove it.' - ' Since, it has been calculated automatically.'); + throw ArgumentError( + 'Invalid check digit at the trailing end.' + ' Provide the valid check digit or remove it.' + ' Since, it has been calculated automatically.', + ); } } else { - throw ArgumentError('UPCA supports only numeric characters. ' - 'The provided value should have 11 digits (without check digit) ' - 'or with 12 digits.'); + throw ArgumentError( + 'UPCA supports only numeric characters. ' + 'The provided value should have 11 digits (without check digit) ' + 'or with 12 digits.', + ); } return true; } @@ -37,15 +41,16 @@ class UPCARenderer extends SymbologyRenderer { /// to be passed @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { final Paint paint = getBarPaint(foregroundColor); final List code = _getCodeValues(); final int barTotalLength = _getTotalLength(code); @@ -73,12 +78,21 @@ class UPCARenderer extends SymbologyRenderer { } final double width = size.width - (singleDigitValues[1]! + singleDigitValues[3]!); - double left = symbology?.module == null - ? offset.dx + singleDigitValues[1]! - : getLeftPosition(barTotalLength, symbology?.module, width, - offset.dx + singleDigitValues[1]!); + double left = + symbology?.module == null + ? offset.dx + singleDigitValues[1]! + : getLeftPosition( + barTotalLength, + symbology?.module, + width, + offset.dx + singleDigitValues[1]!, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology?.module != null) { ratio = symbology!.module!.toDouble(); @@ -96,19 +110,24 @@ class UPCARenderer extends SymbologyRenderer { final String codeValue = code[i]; final bool hasExtraHeight = getHasExtraHeight(i, code); final double additionalHeight = i == code.length - 4 ? 0.4 : 0.5; - final double barHeight = hasExtraHeight - ? size.height + - (showValue - ? (textSize!.height * additionalHeight) + textSpacing - : 0) - : size.height; + final double barHeight = + hasExtraHeight + ? size.height + + (showValue + ? (textSize!.height * additionalHeight) + textSpacing + : 0) + : size.height; final int codeLength = codeValue.length; for (int j = 0; j < codeLength; j++) { final bool canDraw = codeValue[j] == '1'; if (canDraw && (left >= barCodeRect.left && left + ratio < barCodeRect.right)) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + barHeight); + left, + offset.dy, + left + ratio, + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } left += ratio; @@ -136,8 +155,17 @@ class UPCARenderer extends SymbologyRenderer { } if (showValue) { - _paintText(canvas, offset, size, _encodedValue, textStyle, textSpacing, - textAlign, positions, singleDigitValues); + _paintText( + canvas, + offset, + size, + _encodedValue, + textStyle, + textSpacing, + textAlign, + positions, + singleDigitValues, + ); } } @@ -179,7 +207,7 @@ class UPCARenderer extends SymbologyRenderer { '0101111', '0111011', '0110111', - '0001011' + '0001011', ], 'R': [ '1110010', @@ -191,8 +219,8 @@ class UPCARenderer extends SymbologyRenderer { '1010000', '1000100', '1001000', - '1110100' - ] + '1110100', + ], }; return codes; @@ -222,14 +250,16 @@ class UPCARenderer extends SymbologyRenderer { /// Method to calculate the check sum digit int _getCheckSumData(String value) { - final int sum1 = 3 * + final int sum1 = + 3 * (int.parse(value[0]) + int.parse(value[2]) + int.parse(value[4]) + int.parse(value[6]) + int.parse(value[8]) + int.parse(value[10])); - final int sum2 = int.parse(value[9]) + + final int sum2 = + int.parse(value[9]) + int.parse(value[7]) + int.parse(value[5]) + int.parse(value[3]) + @@ -240,15 +270,16 @@ class UPCARenderer extends SymbologyRenderer { /// Method to render the input value of the barcode void _paintText( - Canvas canvas, - Offset offset, - Size size, - String value, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - List positions, - List singleDigitValues) { + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + List positions, + List singleDigitValues, + ) { final String value1 = value[0]; final String value2 = value.substring(1, 6); final String value3 = value.substring(6, 11); @@ -258,50 +289,54 @@ class UPCARenderer extends SymbologyRenderer { // Renders the first digit of encoded value drawText( - canvas, - Offset(singleDigitValues[0]!, offset.dy + size.height + textSpacing), - Size(singleDigitValues[1]!, size.height), - value1, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(singleDigitValues[0]!, offset.dy + size.height + textSpacing), + Size(singleDigitValues[1]!, size.height), + value1, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the first five digits of encoded input value drawText( - canvas, - Offset(positions[0]!, offset.dy), - Size(secondTextWidth, size.height), - value2, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[0]!, offset.dy), + Size(secondTextWidth, size.height), + value2, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the second five digits of encoded input value drawText( - canvas, - Offset(positions[2]!, offset.dy), - Size(thirdTextWidth, size.height), - value3, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[2]!, offset.dy), + Size(thirdTextWidth, size.height), + value3, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the last digit of the encoded input value drawText( - canvas, - Offset(singleDigitValues[2]!, offset.dy + size.height + textSpacing), - Size(singleDigitValues[3]!, size.height), - value[value.length - 1], - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(singleDigitValues[2]!, offset.dy + size.height + textSpacing), + Size(singleDigitValues[3]!, size.height), + value[value.length - 1], + textStyle, + textSpacing, + textAlign, + offset, + size, + ); } } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upce_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upce_renderer.dart index c49b89b07..38b944db8 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upce_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/one_dimensional/upce_renderer.dart @@ -17,8 +17,10 @@ class UPCERenderer extends SymbologyRenderer { if (value.contains(RegExp(r'^(?=.*?[0-9]).{6}$'))) { return true; } - throw ArgumentError('UPCE supports only numeric characters. ' - 'The provided value should have 6 digits.'); + throw ArgumentError( + 'UPCE supports only numeric characters. ' + 'The provided value should have 6 digits.', + ); } /// This is quite a large method. This method could not be @@ -26,15 +28,16 @@ class UPCERenderer extends SymbologyRenderer { /// to be passed @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { final Paint paint = getBarPaint(foregroundColor); final List code = _getCodeValues(value); final int barTotalLength = _getTotalLength(code); @@ -61,12 +64,21 @@ class UPCERenderer extends SymbologyRenderer { final double width = size.width - (singleDigitValues[1]! + singleDigitValues[3]!); - double left = symbology?.module == null - ? offset.dx - : getLeftPosition(barTotalLength, symbology?.module, width, - offset.dx + singleDigitValues[1]!); + double left = + symbology?.module == null + ? offset.dx + : getLeftPosition( + barTotalLength, + symbology?.module, + width, + offset.dx + singleDigitValues[1]!, + ); final Rect barCodeRect = Rect.fromLTRB( - offset.dx, offset.dy, offset.dx + size.width, offset.dy + size.height); + offset.dx, + offset.dy, + offset.dx + size.width, + offset.dy + size.height, + ); double ratio = 0; if (symbology?.module != null) { ratio = symbology!.module!.toDouble(); @@ -81,17 +93,22 @@ class UPCERenderer extends SymbologyRenderer { for (int i = 0; i < code.length; i++) { final String codeValue = code[i]; final bool hasExtraHeight = getHasExtraHeight(i, code); - final double barHeight = hasExtraHeight - ? size.height + - (showValue ? (textSize!.height * 0.5) + textSpacing : 0) - : size.height; + final double barHeight = + hasExtraHeight + ? size.height + + (showValue ? (textSize!.height * 0.5) + textSpacing : 0) + : size.height; final int codeLength = codeValue.length; for (int j = 0; j < codeLength; j++) { final bool canDraw = codeValue[j] == '1'; if (canDraw && (left >= barCodeRect.left && left + ratio < barCodeRect.right)) { final Rect individualBarRect = Rect.fromLTRB( - left, offset.dy, left + ratio, offset.dy + barHeight); + left, + offset.dy, + left + ratio, + offset.dy + barHeight, + ); canvas.drawRect(individualBarRect, paint); } @@ -113,22 +130,32 @@ class UPCERenderer extends SymbologyRenderer { } } if (showValue) { - _paintText(canvas, offset, size, _encodedValue, textStyle, textSpacing, - textAlign, positions, singleDigitValues); + _paintText( + canvas, + offset, + size, + _encodedValue, + textStyle, + textSpacing, + textAlign, + positions, + singleDigitValues, + ); } } /// Method to render the input value of the barcode void _paintText( - Canvas canvas, - Offset offset, - Size size, - String value, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - List positions, - List singleDigitValues) { + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + List positions, + List singleDigitValues, + ) { const String value1 = '0'; final String value2 = value.substring(1, 7); @@ -136,37 +163,40 @@ class UPCERenderer extends SymbologyRenderer { // Renders the first digit of encoded value drawText( - canvas, - Offset(singleDigitValues[0]!, offset.dy + size.height + textSpacing), - Size(singleDigitValues[1]!, size.height), - value1, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(singleDigitValues[0]!, offset.dy + size.height + textSpacing), + Size(singleDigitValues[1]!, size.height), + value1, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); //Renders the middle six digits of encoded value drawText( - canvas, - Offset(positions[0]!, offset.dy), - Size(secondTextWidth, size.height), - value2, - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(positions[0]!, offset.dy), + Size(secondTextWidth, size.height), + value2, + textStyle, + textSpacing, + textAlign, + offset, + size, + ); // Renders the last digit of encoded value drawText( - canvas, - Offset(singleDigitValues[2]!, offset.dy + size.height + textSpacing), - Size(singleDigitValues[3]!, size.height), - value[value.length - 1], - textStyle, - textSpacing, - textAlign, - offset, - size); + canvas, + Offset(singleDigitValues[2]!, offset.dy + size.height + textSpacing), + Size(singleDigitValues[3]!, size.height), + value[value.length - 1], + textStyle, + textSpacing, + textAlign, + offset, + size, + ); } /// Calculate the total length from given value @@ -203,7 +233,7 @@ class UPCERenderer extends SymbologyRenderer { '6': 'EOOOEE', '7': 'EOEOEO', '8': 'EOEOOE', - '9': 'EOOEOE' + '9': 'EOOEOE', }; return upceSymbology; } @@ -220,7 +250,7 @@ class UPCERenderer extends SymbologyRenderer { 'XXXXX00006', 'XXXXX00007', 'XXXXX00008', - 'XXXXX00009' + 'XXXXX00009', ]; } @@ -266,13 +296,13 @@ class UPCERenderer extends SymbologyRenderer { '0101111', '0111011', '0110111', - '0001011' + '0001011', ], 'E': [ // The E (even) encoding for UPC-E '0100111', '0110011', '0011011', '0100001', '0011101', - '0111001', '0000101', '0010001', '0001001', '0010111' - ] + '0111001', '0000101', '0010001', '0001001', '0010111', + ], }; } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/datamatrix_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/datamatrix_renderer.dart index cfc22f547..b4781413b 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/datamatrix_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/datamatrix_renderer.dart @@ -54,277 +54,307 @@ class DataMatrixRenderer extends SymbologyRenderer { void _initialize() { _symbolAttributes = <_DataMatrixSymbolAttribute>[ _DataMatrixSymbolAttribute( - symbolRow: 10, - symbolColumn: 10, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 3, - correctionCodeWords: 5, - interLeavedBlock: 1, - interLeavedDataBlock: 3), + symbolRow: 10, + symbolColumn: 10, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 3, + correctionCodeWords: 5, + interLeavedBlock: 1, + interLeavedDataBlock: 3, + ), _DataMatrixSymbolAttribute( - symbolRow: 12, - symbolColumn: 12, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 5, - correctionCodeWords: 7, - interLeavedBlock: 1, - interLeavedDataBlock: 5), + symbolRow: 12, + symbolColumn: 12, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 5, + correctionCodeWords: 7, + interLeavedBlock: 1, + interLeavedDataBlock: 5, + ), _DataMatrixSymbolAttribute( - symbolRow: 14, - symbolColumn: 14, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 8, - correctionCodeWords: 10, - interLeavedBlock: 1, - interLeavedDataBlock: 8), + symbolRow: 14, + symbolColumn: 14, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 8, + correctionCodeWords: 10, + interLeavedBlock: 1, + interLeavedDataBlock: 8, + ), _DataMatrixSymbolAttribute( - symbolRow: 16, - symbolColumn: 16, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 12, - correctionCodeWords: 12, - interLeavedBlock: 1, - interLeavedDataBlock: 12), + symbolRow: 16, + symbolColumn: 16, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 12, + correctionCodeWords: 12, + interLeavedBlock: 1, + interLeavedDataBlock: 12, + ), _DataMatrixSymbolAttribute( - symbolRow: 18, - symbolColumn: 18, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 18, - correctionCodeWords: 14, - interLeavedBlock: 1, - interLeavedDataBlock: 18), + symbolRow: 18, + symbolColumn: 18, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 18, + correctionCodeWords: 14, + interLeavedBlock: 1, + interLeavedDataBlock: 18, + ), _DataMatrixSymbolAttribute( - symbolRow: 20, - symbolColumn: 20, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 22, - correctionCodeWords: 18, - interLeavedBlock: 1, - interLeavedDataBlock: 22), + symbolRow: 20, + symbolColumn: 20, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 22, + correctionCodeWords: 18, + interLeavedBlock: 1, + interLeavedDataBlock: 22, + ), _DataMatrixSymbolAttribute( - symbolRow: 22, - symbolColumn: 22, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 30, - correctionCodeWords: 20, - interLeavedBlock: 1, - interLeavedDataBlock: 30), + symbolRow: 22, + symbolColumn: 22, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 30, + correctionCodeWords: 20, + interLeavedBlock: 1, + interLeavedDataBlock: 30, + ), _DataMatrixSymbolAttribute( - symbolRow: 24, - symbolColumn: 24, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 36, - correctionCodeWords: 24, - interLeavedBlock: 1, - interLeavedDataBlock: 36), + symbolRow: 24, + symbolColumn: 24, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 36, + correctionCodeWords: 24, + interLeavedBlock: 1, + interLeavedDataBlock: 36, + ), _DataMatrixSymbolAttribute( - symbolRow: 26, - symbolColumn: 26, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 44, - correctionCodeWords: 28, - interLeavedBlock: 1, - interLeavedDataBlock: 44), + symbolRow: 26, + symbolColumn: 26, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 44, + correctionCodeWords: 28, + interLeavedBlock: 1, + interLeavedDataBlock: 44, + ), _DataMatrixSymbolAttribute( - symbolRow: 32, - symbolColumn: 32, - horizontalDataRegion: 2, - verticalDataRegion: 2, - dataCodeWords: 62, - correctionCodeWords: 36, - interLeavedBlock: 1, - interLeavedDataBlock: 62), + symbolRow: 32, + symbolColumn: 32, + horizontalDataRegion: 2, + verticalDataRegion: 2, + dataCodeWords: 62, + correctionCodeWords: 36, + interLeavedBlock: 1, + interLeavedDataBlock: 62, + ), _DataMatrixSymbolAttribute( - symbolRow: 36, - symbolColumn: 36, - horizontalDataRegion: 2, - verticalDataRegion: 2, - dataCodeWords: 86, - correctionCodeWords: 42, - interLeavedBlock: 1, - interLeavedDataBlock: 86), + symbolRow: 36, + symbolColumn: 36, + horizontalDataRegion: 2, + verticalDataRegion: 2, + dataCodeWords: 86, + correctionCodeWords: 42, + interLeavedBlock: 1, + interLeavedDataBlock: 86, + ), _DataMatrixSymbolAttribute( - symbolRow: 40, - symbolColumn: 40, - horizontalDataRegion: 2, - verticalDataRegion: 2, - dataCodeWords: 114, - correctionCodeWords: 48, - interLeavedBlock: 1, - interLeavedDataBlock: 114), + symbolRow: 40, + symbolColumn: 40, + horizontalDataRegion: 2, + verticalDataRegion: 2, + dataCodeWords: 114, + correctionCodeWords: 48, + interLeavedBlock: 1, + interLeavedDataBlock: 114, + ), _DataMatrixSymbolAttribute( - symbolRow: 44, - symbolColumn: 44, - horizontalDataRegion: 2, - verticalDataRegion: 2, - dataCodeWords: 144, - correctionCodeWords: 56, - interLeavedBlock: 1, - interLeavedDataBlock: 144), + symbolRow: 44, + symbolColumn: 44, + horizontalDataRegion: 2, + verticalDataRegion: 2, + dataCodeWords: 144, + correctionCodeWords: 56, + interLeavedBlock: 1, + interLeavedDataBlock: 144, + ), _DataMatrixSymbolAttribute( - symbolRow: 48, - symbolColumn: 48, - horizontalDataRegion: 2, - verticalDataRegion: 2, - dataCodeWords: 174, - correctionCodeWords: 68, - interLeavedBlock: 1, - interLeavedDataBlock: 174), + symbolRow: 48, + symbolColumn: 48, + horizontalDataRegion: 2, + verticalDataRegion: 2, + dataCodeWords: 174, + correctionCodeWords: 68, + interLeavedBlock: 1, + interLeavedDataBlock: 174, + ), _DataMatrixSymbolAttribute( - symbolRow: 52, - symbolColumn: 52, - horizontalDataRegion: 2, - verticalDataRegion: 2, - dataCodeWords: 204, - correctionCodeWords: 84, - interLeavedBlock: 2, - interLeavedDataBlock: 102), + symbolRow: 52, + symbolColumn: 52, + horizontalDataRegion: 2, + verticalDataRegion: 2, + dataCodeWords: 204, + correctionCodeWords: 84, + interLeavedBlock: 2, + interLeavedDataBlock: 102, + ), _DataMatrixSymbolAttribute( - symbolRow: 64, - symbolColumn: 64, - horizontalDataRegion: 4, - verticalDataRegion: 4, - dataCodeWords: 280, - correctionCodeWords: 112, - interLeavedBlock: 2, - interLeavedDataBlock: 140), + symbolRow: 64, + symbolColumn: 64, + horizontalDataRegion: 4, + verticalDataRegion: 4, + dataCodeWords: 280, + correctionCodeWords: 112, + interLeavedBlock: 2, + interLeavedDataBlock: 140, + ), _DataMatrixSymbolAttribute( - symbolRow: 72, - symbolColumn: 72, - horizontalDataRegion: 4, - verticalDataRegion: 4, - dataCodeWords: 368, - correctionCodeWords: 144, - interLeavedBlock: 4, - interLeavedDataBlock: 92), + symbolRow: 72, + symbolColumn: 72, + horizontalDataRegion: 4, + verticalDataRegion: 4, + dataCodeWords: 368, + correctionCodeWords: 144, + interLeavedBlock: 4, + interLeavedDataBlock: 92, + ), _DataMatrixSymbolAttribute( - symbolRow: 80, - symbolColumn: 80, - horizontalDataRegion: 4, - verticalDataRegion: 4, - dataCodeWords: 456, - correctionCodeWords: 192, - interLeavedBlock: 4, - interLeavedDataBlock: 114), + symbolRow: 80, + symbolColumn: 80, + horizontalDataRegion: 4, + verticalDataRegion: 4, + dataCodeWords: 456, + correctionCodeWords: 192, + interLeavedBlock: 4, + interLeavedDataBlock: 114, + ), _DataMatrixSymbolAttribute( - symbolRow: 88, - symbolColumn: 88, - horizontalDataRegion: 4, - verticalDataRegion: 4, - dataCodeWords: 576, - correctionCodeWords: 224, - interLeavedBlock: 4, - interLeavedDataBlock: 144), + symbolRow: 88, + symbolColumn: 88, + horizontalDataRegion: 4, + verticalDataRegion: 4, + dataCodeWords: 576, + correctionCodeWords: 224, + interLeavedBlock: 4, + interLeavedDataBlock: 144, + ), _DataMatrixSymbolAttribute( - symbolRow: 96, - symbolColumn: 96, - horizontalDataRegion: 4, - verticalDataRegion: 4, - dataCodeWords: 696, - correctionCodeWords: 272, - interLeavedBlock: 4, - interLeavedDataBlock: 174), + symbolRow: 96, + symbolColumn: 96, + horizontalDataRegion: 4, + verticalDataRegion: 4, + dataCodeWords: 696, + correctionCodeWords: 272, + interLeavedBlock: 4, + interLeavedDataBlock: 174, + ), _DataMatrixSymbolAttribute( - symbolRow: 104, - symbolColumn: 104, - horizontalDataRegion: 4, - verticalDataRegion: 4, - dataCodeWords: 816, - correctionCodeWords: 336, - interLeavedBlock: 6, - interLeavedDataBlock: 136), + symbolRow: 104, + symbolColumn: 104, + horizontalDataRegion: 4, + verticalDataRegion: 4, + dataCodeWords: 816, + correctionCodeWords: 336, + interLeavedBlock: 6, + interLeavedDataBlock: 136, + ), _DataMatrixSymbolAttribute( - symbolRow: 120, - symbolColumn: 120, - horizontalDataRegion: 6, - verticalDataRegion: 6, - dataCodeWords: 1050, - correctionCodeWords: 408, - interLeavedBlock: 6, - interLeavedDataBlock: 175), + symbolRow: 120, + symbolColumn: 120, + horizontalDataRegion: 6, + verticalDataRegion: 6, + dataCodeWords: 1050, + correctionCodeWords: 408, + interLeavedBlock: 6, + interLeavedDataBlock: 175, + ), _DataMatrixSymbolAttribute( - symbolRow: 132, - symbolColumn: 132, - horizontalDataRegion: 6, - verticalDataRegion: 6, - dataCodeWords: 1304, - correctionCodeWords: 496, - interLeavedBlock: 8, - interLeavedDataBlock: 163), + symbolRow: 132, + symbolColumn: 132, + horizontalDataRegion: 6, + verticalDataRegion: 6, + dataCodeWords: 1304, + correctionCodeWords: 496, + interLeavedBlock: 8, + interLeavedDataBlock: 163, + ), _DataMatrixSymbolAttribute( - symbolRow: 144, - symbolColumn: 144, - horizontalDataRegion: 6, - verticalDataRegion: 6, - dataCodeWords: 1558, - correctionCodeWords: 620, - interLeavedBlock: 10, - interLeavedDataBlock: 156), + symbolRow: 144, + symbolColumn: 144, + horizontalDataRegion: 6, + verticalDataRegion: 6, + dataCodeWords: 1558, + correctionCodeWords: 620, + interLeavedBlock: 10, + interLeavedDataBlock: 156, + ), // Rectangle matrix _DataMatrixSymbolAttribute( - symbolRow: 8, - symbolColumn: 18, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 5, - correctionCodeWords: 7, - interLeavedBlock: 1, - interLeavedDataBlock: 5), + symbolRow: 8, + symbolColumn: 18, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 5, + correctionCodeWords: 7, + interLeavedBlock: 1, + interLeavedDataBlock: 5, + ), _DataMatrixSymbolAttribute( - symbolRow: 8, - symbolColumn: 32, - horizontalDataRegion: 2, - verticalDataRegion: 1, - dataCodeWords: 10, - correctionCodeWords: 11, - interLeavedBlock: 1, - interLeavedDataBlock: 10), + symbolRow: 8, + symbolColumn: 32, + horizontalDataRegion: 2, + verticalDataRegion: 1, + dataCodeWords: 10, + correctionCodeWords: 11, + interLeavedBlock: 1, + interLeavedDataBlock: 10, + ), _DataMatrixSymbolAttribute( - symbolRow: 12, - symbolColumn: 26, - horizontalDataRegion: 1, - verticalDataRegion: 1, - dataCodeWords: 16, - correctionCodeWords: 14, - interLeavedBlock: 1, - interLeavedDataBlock: 16), + symbolRow: 12, + symbolColumn: 26, + horizontalDataRegion: 1, + verticalDataRegion: 1, + dataCodeWords: 16, + correctionCodeWords: 14, + interLeavedBlock: 1, + interLeavedDataBlock: 16, + ), _DataMatrixSymbolAttribute( - symbolRow: 12, - symbolColumn: 36, - horizontalDataRegion: 2, - verticalDataRegion: 1, - dataCodeWords: 22, - correctionCodeWords: 18, - interLeavedBlock: 1, - interLeavedDataBlock: 22), + symbolRow: 12, + symbolColumn: 36, + horizontalDataRegion: 2, + verticalDataRegion: 1, + dataCodeWords: 22, + correctionCodeWords: 18, + interLeavedBlock: 1, + interLeavedDataBlock: 22, + ), _DataMatrixSymbolAttribute( - symbolRow: 16, - symbolColumn: 36, - horizontalDataRegion: 2, - verticalDataRegion: 1, - dataCodeWords: 32, - correctionCodeWords: 24, - interLeavedBlock: 1, - interLeavedDataBlock: 32), + symbolRow: 16, + symbolColumn: 36, + horizontalDataRegion: 2, + verticalDataRegion: 1, + dataCodeWords: 32, + correctionCodeWords: 24, + interLeavedBlock: 1, + interLeavedDataBlock: 32, + ), _DataMatrixSymbolAttribute( - symbolRow: 16, - symbolColumn: 48, - horizontalDataRegion: 2, - verticalDataRegion: 1, - dataCodeWords: 49, - correctionCodeWords: 28, - interLeavedBlock: 1, - interLeavedDataBlock: 49) + symbolRow: 16, + symbolColumn: 48, + horizontalDataRegion: 2, + verticalDataRegion: 1, + dataCodeWords: 49, + correctionCodeWords: 28, + interLeavedBlock: 1, + interLeavedDataBlock: 49, + ), ]; _createLogList(); @@ -393,9 +423,10 @@ class DataMatrixRenderer extends SymbologyRenderer { if (v == 1 || v > 7 && (codeword[(v >> 3) - 1]! & (1 << (v & 7))) != 0) { matrix[(1 + y + 2 * (y ~/ (fieldHeight - 2))) * width + - 1 + - x + - 2 * (x ~/ (fieldWidth - 2))] = 1; + 1 + + x + + 2 * (x ~/ (fieldWidth - 2))] = + 1; } } } @@ -409,7 +440,9 @@ class DataMatrixRenderer extends SymbologyRenderer { symbolRow = _symbolAttribute.symbolRow!; final List> tempArray = List>.generate( - symbolColumn, (int j) => List.filled(symbolRow, null)); + symbolColumn, + (int j) => List.filled(symbolRow, null), + ); for (int m = 0; m < symbolColumn; m++) { for (int n = 0; n < symbolRow; n++) { @@ -418,7 +451,9 @@ class DataMatrixRenderer extends SymbologyRenderer { } final List> tempArray2 = List>.generate( - symbolRow, (int j) => List.filled(symbolColumn, null)); + symbolRow, + (int j) => List.filled(symbolColumn, null), + ); for (int i = 0; i < symbolRow; i++) { for (int j = 0; j < symbolColumn; j++) { @@ -434,8 +469,10 @@ class DataMatrixRenderer extends SymbologyRenderer { const int quietZone = 1; final int w = _symbolAttribute.symbolRow! + (2 * quietZone); final int h = _symbolAttribute.symbolColumn! + (2 * quietZone); - _dataMatrixList = - List>.generate(w, (int j) => List.filled(h, null)); + _dataMatrixList = List>.generate( + w, + (int j) => List.filled(h, null), + ); // Top quietzone. for (int i = 0; i < h; i++) { _dataMatrixList[0][i] = 0; @@ -458,8 +495,15 @@ class DataMatrixRenderer extends SymbologyRenderer { } /// Method to encode the error correcting code word - void _errorCorrectingCode200PlacementBit(List array, int numOfRows, - int numOfColumns, int row, int column, int place, String character) { + void _errorCorrectingCode200PlacementBit( + List array, + int numOfRows, + int numOfColumns, + int row, + int column, + int place, + String character, + ) { if (row < 0) { row += numOfRows; column += 4 - ((numOfRows + 4) % 8); @@ -475,112 +519,417 @@ class DataMatrixRenderer extends SymbologyRenderer { /// Method to encode the error correcting code word void _errorCorrectingCode200PlacementCornerA( - List array, int numOfRows, int numOfColumns, int place) { - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, 0, place, String.fromCharCode(7)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, 1, place, String.fromCharCode(6)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, 2, place, String.fromCharCode(5)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 2, place, String.fromCharCode(4)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 1, place, String.fromCharCode(3)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 1, - numOfColumns - 1, place, String.fromCharCode(2)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 2, - numOfColumns - 1, place, String.fromCharCode(1)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 3, - numOfColumns - 1, place, String.fromCharCode(0)); + List array, + int numOfRows, + int numOfColumns, + int place, + ) { + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + 0, + place, + String.fromCharCode(7), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + 1, + place, + String.fromCharCode(6), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + 2, + place, + String.fromCharCode(5), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 2, + place, + String.fromCharCode(4), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 1, + place, + String.fromCharCode(3), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 1, + numOfColumns - 1, + place, + String.fromCharCode(2), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 2, + numOfColumns - 1, + place, + String.fromCharCode(1), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 3, + numOfColumns - 1, + place, + String.fromCharCode(0), + ); } /// Method to encode the error correcting code word void _errorCorrectingCode200PlacementCornerB( - List array, int numOfRows, int numOfColumns, int place) { - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 3, 0, place, String.fromCharCode(7)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 2, 0, place, String.fromCharCode(6)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, 0, place, String.fromCharCode(5)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 4, place, String.fromCharCode(4)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 3, place, String.fromCharCode(3)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 2, place, String.fromCharCode(2)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 1, place, String.fromCharCode(1)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 1, - numOfColumns - 1, place, String.fromCharCode(0)); + List array, + int numOfRows, + int numOfColumns, + int place, + ) { + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 3, + 0, + place, + String.fromCharCode(7), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 2, + 0, + place, + String.fromCharCode(6), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + 0, + place, + String.fromCharCode(5), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 4, + place, + String.fromCharCode(4), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 3, + place, + String.fromCharCode(3), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 2, + place, + String.fromCharCode(2), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 1, + place, + String.fromCharCode(1), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 1, + numOfColumns - 1, + place, + String.fromCharCode(0), + ); } /// Method to encode the error correcting code word void _errorCorrectingCode200PlacementCornerC( - List array, int numOfRows, int numOfColumns, int place) { - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 3, 0, place, String.fromCharCode(7)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 2, 0, place, String.fromCharCode(6)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, 0, place, String.fromCharCode(5)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 2, place, String.fromCharCode(4)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 1, place, String.fromCharCode(3)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 1, - numOfColumns - 1, place, String.fromCharCode(2)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 2, - numOfColumns - 1, place, String.fromCharCode(1)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 3, - numOfColumns - 1, place, String.fromCharCode(0)); + List array, + int numOfRows, + int numOfColumns, + int place, + ) { + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 3, + 0, + place, + String.fromCharCode(7), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 2, + 0, + place, + String.fromCharCode(6), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + 0, + place, + String.fromCharCode(5), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 2, + place, + String.fromCharCode(4), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 1, + place, + String.fromCharCode(3), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 1, + numOfColumns - 1, + place, + String.fromCharCode(2), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 2, + numOfColumns - 1, + place, + String.fromCharCode(1), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 3, + numOfColumns - 1, + place, + String.fromCharCode(0), + ); } /// Method to encode the error correcting code word void _errorCorrectingCode200PlacementCornerD( - List array, int numOfRows, int numOfColumns, int place) { - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, 0, place, String.fromCharCode(7)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, - numOfRows - 1, numOfColumns - 1, place, String.fromCharCode(6)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 3, place, String.fromCharCode(5)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 2, place, String.fromCharCode(4)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 0, - numOfColumns - 1, place, String.fromCharCode(3)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 1, - numOfColumns - 3, place, String.fromCharCode(2)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 1, - numOfColumns - 2, place, String.fromCharCode(1)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, 1, - numOfColumns - 1, place, String.fromCharCode(0)); + List array, + int numOfRows, + int numOfColumns, + int place, + ) { + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + 0, + place, + String.fromCharCode(7), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + numOfRows - 1, + numOfColumns - 1, + place, + String.fromCharCode(6), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 3, + place, + String.fromCharCode(5), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 2, + place, + String.fromCharCode(4), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 0, + numOfColumns - 1, + place, + String.fromCharCode(3), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 1, + numOfColumns - 3, + place, + String.fromCharCode(2), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 1, + numOfColumns - 2, + place, + String.fromCharCode(1), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + 1, + numOfColumns - 1, + place, + String.fromCharCode(0), + ); } /// Method to encode the error correcting code word - void _errorCorrectingCode200PlacementBlock(List array, int numOfRows, - int numOfColumns, int row, int column, int place) { - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row - 2, - column - 2, place, String.fromCharCode(7)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row - 2, - column - 1, place, String.fromCharCode(6)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row - 1, - column - 2, place, String.fromCharCode(5)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row - 1, - column - 1, place, String.fromCharCode(4)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row - 1, - column, place, String.fromCharCode(3)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row, - column - 2, place, String.fromCharCode(2)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row, - column - 1, place, String.fromCharCode(1)); - _errorCorrectingCode200PlacementBit(array, numOfRows, numOfColumns, row, - column, place, String.fromCharCode(0)); + void _errorCorrectingCode200PlacementBlock( + List array, + int numOfRows, + int numOfColumns, + int row, + int column, + int place, + ) { + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row - 2, + column - 2, + place, + String.fromCharCode(7), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row - 2, + column - 1, + place, + String.fromCharCode(6), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row - 1, + column - 2, + place, + String.fromCharCode(5), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row - 1, + column - 1, + place, + String.fromCharCode(4), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row - 1, + column, + place, + String.fromCharCode(3), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row, + column - 2, + place, + String.fromCharCode(2), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row, + column - 1, + place, + String.fromCharCode(1), + ); + _errorCorrectingCode200PlacementBit( + array, + numOfRows, + numOfColumns, + row, + column, + place, + String.fromCharCode(0), + ); } /// Method to encode the error correcting code word void _errorCorrectingCode200Placement( - List array, int numOfRows, int numOfColumns) { + List array, + int numOfRows, + int numOfColumns, + ) { int row, column, place; for (row = 0; row < numOfRows; row++) { for (column = 0; column < numOfColumns; column++) { @@ -594,24 +943,40 @@ class DataMatrixRenderer extends SymbologyRenderer { do { if (row == numOfRows && !(column != 0)) { _errorCorrectingCode200PlacementCornerA( - array, numOfRows, numOfColumns, place++); + array, + numOfRows, + numOfColumns, + place++, + ); } if ((row == numOfRows - 2) && !(column != 0) && ((numOfColumns % 4) != 0)) { _errorCorrectingCode200PlacementCornerB( - array, numOfRows, numOfColumns, place++); + array, + numOfRows, + numOfColumns, + place++, + ); } if (row == numOfRows - 2 && !(column != 0) && (numOfColumns % 8) == 4) { _errorCorrectingCode200PlacementCornerC( - array, numOfRows, numOfColumns, place++); + array, + numOfRows, + numOfColumns, + place++, + ); } if (row == numOfRows + 4 && column == 2 && !((numOfColumns % 8) != 0)) { _errorCorrectingCode200PlacementCornerD( - array, numOfRows, numOfColumns, place++); + array, + numOfRows, + numOfColumns, + place++, + ); } // enocoding placement (up/right) do { @@ -619,7 +984,13 @@ class DataMatrixRenderer extends SymbologyRenderer { column >= 0 && !(array[row * numOfColumns + column] != 0)) { _errorCorrectingCode200PlacementBlock( - array, numOfRows, numOfColumns, row, column, place++); + array, + numOfRows, + numOfColumns, + row, + column, + place++, + ); } row -= 2; @@ -633,7 +1004,13 @@ class DataMatrixRenderer extends SymbologyRenderer { column < numOfColumns && !(array[row * numOfColumns + column] != 0)) { _errorCorrectingCode200PlacementBlock( - array, numOfRows, numOfColumns, row, column, place++); + array, + numOfRows, + numOfColumns, + row, + column, + place++, + ); } row += 2; @@ -710,8 +1087,10 @@ class DataMatrixRenderer extends SymbologyRenderer { num++; } - final List result = - List.filled((1 + num) + dataCodeword.length, null); + final List result = List.filled( + (1 + num) + dataCodeword.length, + null, + ); result[0] = 231; if (dataCodeword.length <= 249) { result[1] = dataCodeword.length; @@ -755,13 +1134,16 @@ class DataMatrixRenderer extends SymbologyRenderer { } } - final List result = - List.filled(destinationArray.length ~/ 2, null); + final List result = List.filled( + destinationArray.length ~/ 2, + null, + ); for (int i = 0; i < result.length; i++) { if (!isEven && i == result.length - 1) { result[i] = destinationArray[2 * i]! + 1; } else { - result[i] = (((destinationArray[2 * i]! - 48) * 10) + + result[i] = + (((destinationArray[2 * i]! - 48) * 10) + (destinationArray[(2 * i) + 1]! - 48)) + 130; } @@ -815,7 +1197,9 @@ class DataMatrixRenderer extends SymbologyRenderer { final int numCorrectionCodeword = _symbolAttribute.correctionCodeWords!; // Create error correction array. final List correctionCodeWordArray = List.filled( - numCorrectionCodeword + _symbolAttribute.dataCodeWords!, null); + numCorrectionCodeword + _symbolAttribute.dataCodeWords!, + null, + ); for (int i = 0; i < correctionCodeWordArray.length; i++) { correctionCodeWordArray[i] = 0; } @@ -836,10 +1220,14 @@ class DataMatrixRenderer extends SymbologyRenderer { for (int i = block; i < symbolDataWords; i += step) { final int val = _getErrorCorrectingCodeSum( - blockByte[blockErrorWords - 1]!, _encodedCodeword![i]!); + blockByte[blockErrorWords - 1]!, + _encodedCodeword![i]!, + ); for (int j = blockErrorWords - 1; j > 0; j--) { - blockByte[j] = _getErrorCorrectingCodeSum(blockByte[j - 1]!, - _getErrorCorrectingCodeProduct(_polynomial[j]!, val)); + blockByte[j] = _getErrorCorrectingCodeSum( + blockByte[j - 1]!, + _getErrorCorrectingCodeProduct(_polynomial[j]!, val), + ); } blockByte[0] = _getErrorCorrectingCodeProduct(_polynomial[0]!, val); @@ -865,12 +1253,16 @@ class DataMatrixRenderer extends SymbologyRenderer { } return _getCorrectionCodeWordArray( - correctionCodeWordArray, numCorrectionCodeword); + correctionCodeWordArray, + numCorrectionCodeword, + ); } /// Method to get the correction code word List _getCorrectionCodeWordArray( - List correctionCodeWordArray, int numCorrectionCodeword) { + List correctionCodeWordArray, + int numCorrectionCodeword, + ) { if (correctionCodeWordArray.length > numCorrectionCodeword) { final List tmp = correctionCodeWordArray; correctionCodeWordArray = List.filled(numCorrectionCodeword, null); @@ -901,8 +1293,11 @@ class DataMatrixRenderer extends SymbologyRenderer { } } } else { - _symbolAttribute = _symbolAttributes[ - getDataMatrixSize(_dataMatrixSymbology.dataMatrixSize) - 1]; + _symbolAttribute = + _symbolAttributes[getDataMatrixSize( + _dataMatrixSymbology.dataMatrixSize, + ) - + 1]; } List temp; @@ -918,7 +1313,8 @@ class DataMatrixRenderer extends SymbologyRenderer { final String symbolRow = _symbolAttribute.symbolRow.toString(); final String symbolColumn = _symbolAttribute.symbolColumn.toString(); throw ArgumentError( - 'Data too long for $symbolRow x $symbolColumn barcode.'); + 'Data too long for $symbolRow x $symbolColumn barcode.', + ); } } @@ -936,8 +1332,10 @@ class DataMatrixRenderer extends SymbologyRenderer { for (int j = i - 1; j >= 0; j--) { _polynomial[j] = _getErrorCorrectingCodeDoublify(_polynomial[j]!, i); if (j > 0) { - _polynomial[j] = - _getErrorCorrectingCodeSum(_polynomial[j]!, _polynomial[j - 1]!); + _polynomial[j] = _getErrorCorrectingCodeSum( + _polynomial[j]!, + _polynomial[j - 1]!, + ); } } } @@ -946,10 +1344,13 @@ class DataMatrixRenderer extends SymbologyRenderer { /// Method to get the code word List _getCodeword(List dataCodeword) { _encodedCodeword = _getDataCodeword(dataCodeword); - final List correctCodeword = - _getComputedErrorCorrection(_encodedCodeword!); + final List correctCodeword = _getComputedErrorCorrection( + _encodedCodeword!, + ); final List finalCodeword = List.filled( - _encodedCodeword!.length + correctCodeword.length, null); + _encodedCodeword!.length + correctCodeword.length, + null, + ); for (int i = 0; i < _encodedCodeword!.length; i++) { finalCodeword[i] = _encodedCodeword![i]; } @@ -994,7 +1395,8 @@ class DataMatrixRenderer extends SymbologyRenderer { if (actualEncoding == DataMatrixEncoding.asciiNumeric && _dataMatrixSymbology.encoding != actualEncoding) { throw ArgumentError( - 'Data contains invalid characters and cannot be encoded as ASCIINumeric.'); + 'Data contains invalid characters and cannot be encoded as ASCIINumeric.', + ); } _encoding = actualEncoding; @@ -1030,15 +1432,16 @@ class DataMatrixRenderer extends SymbologyRenderer { @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { _inputValue = value; _buildDataMatrix(); @@ -1053,7 +1456,8 @@ class DataMatrixRenderer extends SymbologyRenderer { getDataMatrixSize(_dataMatrixSymbology.dataMatrixSize) < 25; int dimension = minSize ~/ _dataMatrixList.length; final int rectDimension = minSize ~/ _dataMatrixList[0].length; - final int xDimension = _dataMatrixSymbology.module ?? + final int xDimension = + _dataMatrixSymbology.module ?? (isSquareMatrix ? dimension : rectDimension); dimension = _dataMatrixSymbology.module ?? dimension; for (int i = 0; i < w; i++) { @@ -1073,7 +1477,11 @@ class DataMatrixRenderer extends SymbologyRenderer { for (int j = 0; j < h; j++) { if (_dataMatrixList[i][j] == 1) { final Rect matrixRect = Rect.fromLTRB( - x, yPosition, x + xDimension, yPosition + dimension); + x, + yPosition, + x + xDimension, + yPosition + dimension, + ); canvas.drawRect(matrixRect, paint); } @@ -1086,23 +1494,39 @@ class DataMatrixRenderer extends SymbologyRenderer { if (showValue) { final Offset textOffset = Offset(offset.dx, yPosition.toDouble()); drawText( - canvas, textOffset, size, value, textStyle, textSpacing, textAlign); + canvas, + textOffset, + size, + value, + textStyle, + textSpacing, + textAlign, + ); } } /// Method to render the input value of the barcode @override - void drawText(Canvas canvas, Offset offset, Size size, String value, - TextStyle textStyle, double textSpacing, TextAlign textAlign, - [Offset? actualOffset, Size? actualSize]) { + void drawText( + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, [ + Offset? actualOffset, + Size? actualSize, + ]) { final TextSpan span = TextSpan(text: value, style: textStyle); final TextPainter textPainter = TextPainter( - maxLines: 1, - ellipsis: '.....', - text: span, - textDirection: TextDirection.ltr, - textAlign: textAlign); + maxLines: 1, + ellipsis: '.....', + text: span, + textDirection: TextDirection.ltr, + textAlign: textAlign, + ); textPainter.layout(maxWidth: size.width); double x; double y; @@ -1141,15 +1565,16 @@ class DataMatrixRenderer extends SymbologyRenderer { /// Represents the data matrix symbol attribute class _DataMatrixSymbolAttribute { /// Creates the data matrix symbol attribute - _DataMatrixSymbolAttribute( - {this.symbolRow, - this.symbolColumn, - this.horizontalDataRegion, - this.verticalDataRegion, - this.dataCodeWords, - this.correctionCodeWords, - this.interLeavedBlock, - this.interLeavedDataBlock}); + _DataMatrixSymbolAttribute({ + this.symbolRow, + this.symbolColumn, + this.horizontalDataRegion, + this.verticalDataRegion, + this.dataCodeWords, + this.correctionCodeWords, + this.interLeavedBlock, + this.interLeavedDataBlock, + }); /// Defines the symbol row final int? symbolRow; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/error_correction_codewords.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/error_correction_codewords.dart index c3297ba16..ccb2da71c 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/error_correction_codewords.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/error_correction_codewords.dart @@ -6,7 +6,9 @@ class ErrorCorrectionCodeWords { /// Creates the error correction code word ErrorCorrectionCodeWords({this.codeVersion, this.correctionLevel}) { _codeValue = QRCodeValue( - qrCodeVersion: codeVersion!, errorCorrectionLevel: correctionLevel!); + qrCodeVersion: codeVersion!, + errorCorrectionLevel: correctionLevel!, + ); eccw = _codeValue.noOfErrorCorrectionCodeWord; } @@ -272,7 +274,7 @@ class ErrorCorrectionCodeWords { 216, 173, 71, - 142 + 142, ]; /// Specifies the error corrcetion code word @@ -325,7 +327,7 @@ class ErrorCorrectionCodeWords { 218, 206, 140, - 78 + 78, ]; break; case 15: @@ -345,7 +347,7 @@ class ErrorCorrectionCodeWords { 124, 5, 99, - 105 + 105, ]; break; case 16: @@ -366,7 +368,7 @@ class ErrorCorrectionCodeWords { 182, 194, 225, - 120 + 120, ]; break; case 17: @@ -388,7 +390,7 @@ class ErrorCorrectionCodeWords { 39, 243, 163, - 136 + 136, ]; break; case 18: @@ -411,7 +413,7 @@ class ErrorCorrectionCodeWords { 5, 98, 96, - 153 + 153, ]; break; case 20: @@ -436,7 +438,7 @@ class ErrorCorrectionCodeWords { 212, 212, 188, - 190 + 190, ]; break; case 22: @@ -463,7 +465,7 @@ class ErrorCorrectionCodeWords { 160, 105, 165, - 231 + 231, ]; break; case 24: @@ -492,7 +494,7 @@ class ErrorCorrectionCodeWords { 87, 96, 227, - 21 + 21, ]; break; case 26: @@ -523,7 +525,7 @@ class ErrorCorrectionCodeWords { 153, 145, 218, - 70 + 70, ]; break; case 28: @@ -556,7 +558,7 @@ class ErrorCorrectionCodeWords { 242, 37, 9, - 123 + 123, ]; break; case 30: @@ -591,7 +593,7 @@ class ErrorCorrectionCodeWords { 238, 40, 192, - 180 + 180, ]; break; case 32: @@ -628,7 +630,7 @@ class ErrorCorrectionCodeWords { 254, 185, 220, - 241 + 241, ]; break; case 34: @@ -667,7 +669,7 @@ class ErrorCorrectionCodeWords { 98, 62, 129, - 51 + 51, ]; break; case 36: @@ -708,7 +710,7 @@ class ErrorCorrectionCodeWords { 113, 233, 30, - 120 + 120, ]; break; case 40: @@ -753,7 +755,7 @@ class ErrorCorrectionCodeWords { 232, 53, 35, - 15 + 15, ]; break; case 42: @@ -800,7 +802,7 @@ class ErrorCorrectionCodeWords { 194, 117, 50, - 96 + 96, ]; break; case 44: @@ -849,7 +851,7 @@ class ErrorCorrectionCodeWords { 113, 102, 73, - 181 + 181, ]; break; case 46: @@ -900,7 +902,7 @@ class ErrorCorrectionCodeWords { 223, 19, 82, - 15 + 15, ]; break; case 48: @@ -953,7 +955,7 @@ class ErrorCorrectionCodeWords { 163, 39, 34, - 108 + 108, ]; break; case 50: @@ -1008,7 +1010,7 @@ class ErrorCorrectionCodeWords { 215, 232, 133, - 205 + 205, ]; break; case 52: @@ -1065,7 +1067,7 @@ class ErrorCorrectionCodeWords { 239, 254, 116, - 51 + 51, ]; break; case 54: @@ -1124,7 +1126,7 @@ class ErrorCorrectionCodeWords { 198, 76, 31, - 156 + 156, ]; break; case 56: @@ -1185,7 +1187,7 @@ class ErrorCorrectionCodeWords { 207, 20, 61, - 10 + 10, ]; break; case 58: @@ -1248,7 +1250,7 @@ class ErrorCorrectionCodeWords { 233, 125, 148, - 123 + 123, ]; break; case 60: @@ -1313,7 +1315,7 @@ class ErrorCorrectionCodeWords { 89, 7, 33, - 240 + 240, ]; break; case 62: @@ -1380,7 +1382,7 @@ class ErrorCorrectionCodeWords { 36, 186, 110, - 106 + 106, ]; break; case 64: @@ -1449,7 +1451,7 @@ class ErrorCorrectionCodeWords { 217, 156, 213, - 231 + 231, ]; break; case 66: @@ -1520,7 +1522,7 @@ class ErrorCorrectionCodeWords { 132, 93, 45, - 105 + 105, ]; break; case 68: @@ -1593,7 +1595,7 @@ class ErrorCorrectionCodeWords { 5, 8, 163, - 238 + 238, ]; break; } @@ -1641,14 +1643,17 @@ class ErrorCorrectionCodeWords { Map generatorPolynom = {}; for (int i = 0; i < _gx.length; i++) { - generatorPolynom[_gx.length - 1 - i] = - _getElementFromAlpha(_gx[i], _alpha); + generatorPolynom[_gx.length - 1 - i] = _getElementFromAlpha( + _gx[i], + _alpha, + ); } Map tempMessagePolynom = {}; for (int i = 0; i < messagePolynom.length; i++) { - final MapEntry currentEntry = - messagePolynom.entries.elementAt(i); + final MapEntry currentEntry = messagePolynom.entries.elementAt( + i, + ); tempMessagePolynom[currentEntry.key + eccw] = currentEntry.value; } @@ -1657,8 +1662,8 @@ class ErrorCorrectionCodeWords { tempMessagePolynom = {}; for (int i = 0; i < generatorPolynom.length; i++) { - final MapEntry currentEntry = - generatorPolynom.entries.elementAt(i); + final MapEntry currentEntry = generatorPolynom.entries + .elementAt(i); tempMessagePolynom[currentEntry.key + leadTermFactor] = currentEntry.value; } @@ -1670,12 +1675,18 @@ class ErrorCorrectionCodeWords { if (leadTermSource[largestExponent] == 0) { leadTermSource.remove(largestExponent); if (i == 0) { - leadTermSource = - _updateLeadTermSource(i, leadTermSource, generatorPolynom); + leadTermSource = _updateLeadTermSource( + i, + leadTermSource, + generatorPolynom, + ); } } else { - leadTermSource = - _updateLeadTermSource(i, leadTermSource, generatorPolynom); + leadTermSource = _updateLeadTermSource( + i, + leadTermSource, + generatorPolynom, + ); } } @@ -1691,10 +1702,16 @@ class ErrorCorrectionCodeWords { /// Updates the lead term source value Map _updateLeadTermSource( - int index, Map leadTermSource, Map generatorPolynom) { + int index, + Map leadTermSource, + Map generatorPolynom, + ) { final Map alphaNotation = _getAlphaNotation(leadTermSource); - Map resPoly = _getGeneratorPolynomByLeadTerm(generatorPolynom, - alphaNotation[_getLargestExponent(alphaNotation)]!, index); + Map resPoly = _getGeneratorPolynomByLeadTerm( + generatorPolynom, + alphaNotation[_getLargestExponent(alphaNotation)]!, + index, + ); resPoly = _getDecimalNotation(resPoly); resPoly = _getXORPolynoms(leadTermSource, resPoly); return resPoly; @@ -1702,7 +1719,9 @@ class ErrorCorrectionCodeWords { /// Calculates the polynomial value Map _getXORPolynoms( - Map messagePolynom, Map resPolynom) { + Map messagePolynom, + Map resPolynom, + ) { final Map resultPolynom = {}; Map longPoly = {}; Map shortPoly = {}; @@ -1720,10 +1739,11 @@ class ErrorCorrectionCodeWords { for (int i = 0; i < longPoly.length; i++) { resultPolynom.putIfAbsent( - messagePolyExponent - i, - () => - longPoly.entries.elementAt(i).value ^ - (shortPoly.length > i ? shortPoly[shortPolyExponent - i]! : 0)); + messagePolyExponent - i, + () => + longPoly.entries.elementAt(i).value ^ + (shortPoly.length > i ? shortPoly[shortPolyExponent - i]! : 0), + ); } final int resultPolyExponent = _getLargestExponent(resultPolynom); @@ -1733,12 +1753,17 @@ class ErrorCorrectionCodeWords { /// Calculates the polynomial value Map _getGeneratorPolynomByLeadTerm( - Map genPolynom, int leadTermCoefficient, int lowerExponentBy) { + Map genPolynom, + int leadTermCoefficient, + int lowerExponentBy, + ) { final Map tempPolynom = {}; for (int i = 0; i < genPolynom.length; i++) { final MapEntry currentEntry = genPolynom.entries.elementAt(i); - tempPolynom.putIfAbsent(currentEntry.key - lowerExponentBy, - () => (currentEntry.value + leadTermCoefficient) % 255); + tempPolynom.putIfAbsent( + currentEntry.key - lowerExponentBy, + () => (currentEntry.value + leadTermCoefficient) % 255, + ); } return tempPolynom; @@ -1749,8 +1774,10 @@ class ErrorCorrectionCodeWords { final Map tempPolynom = {}; for (int i = 0; i < poly.length; i++) { final MapEntry currentEntry = poly.entries.elementAt(i); - tempPolynom[currentEntry.key] = - _getIntValFromAlphaExp(currentEntry.value, _alpha); + tempPolynom[currentEntry.key] = _getIntValFromAlphaExp( + currentEntry.value, + _alpha, + ); } return tempPolynom; @@ -1762,8 +1789,10 @@ class ErrorCorrectionCodeWords { for (int i = 0; i < polynom.length; i++) { final MapEntry currentEntry = polynom.entries.elementAt(i); if (currentEntry.value != 0) { - tempPolynom.putIfAbsent(currentEntry.key, - () => _getElementFromAlpha(currentEntry.value, _alpha)); + tempPolynom.putIfAbsent( + currentEntry.key, + () => _getElementFromAlpha(currentEntry.value, _alpha), + ); } } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_renderer.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_renderer.dart index 729fe6c68..0ce548cd0 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_renderer.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_renderer.dart @@ -91,7 +91,7 @@ class QRCodeRenderer extends SymbologyRenderer { '258C', '2590', '2580', - '25A0' + '25A0', ]; /// Specifies the latin2 character set @@ -152,7 +152,7 @@ class QRCodeRenderer extends SymbologyRenderer { '16F', '171', '163', - '2D9' + '2D9', ]; /// Specifies the latin3 character set @@ -182,7 +182,7 @@ class QRCodeRenderer extends SymbologyRenderer { '121', '11D', '16D', - '15D' + '15D', ]; /// Specifies the latin4 character set @@ -235,7 +235,7 @@ class QRCodeRenderer extends SymbologyRenderer { '137', '173', '169', - '16B' + '16B', ]; /// Specifies the windows 1250 character set @@ -249,7 +249,7 @@ class QRCodeRenderer extends SymbologyRenderer { '15F', '13D', '13E', - '17C' + '17C', ]; /// Specifies the windows 1251 character set @@ -283,7 +283,7 @@ class QRCodeRenderer extends SymbologyRenderer { '458', '405', '455', - '457' + '457', ]; /// Specifies the windows 1252 character set @@ -314,7 +314,7 @@ class QRCodeRenderer extends SymbologyRenderer { '203A', '153', '17E', - '178' + '178', ]; /// Specifies the QR code value @@ -516,7 +516,7 @@ class QRCodeRenderer extends SymbologyRenderer { '153', '6BA', '6BE', - '6C1' + '6C1', ]; if (windows1256CharSet.contains(inputChar)) { @@ -717,9 +717,10 @@ class QRCodeRenderer extends SymbologyRenderer { ///Methods to creates the block value based on the encoded data List> _getBlocks(List encodeData, int noOfBlocks) { final List> encodedBlocks = List>.generate( - noOfBlocks, - (int i) => - List.filled(encodeData.length ~/ 8 ~/ noOfBlocks, null)); + noOfBlocks, + (int i) => + List.filled(encodeData.length ~/ 8 ~/ noOfBlocks, null), + ); String stringValue = ''; int j = 0; @@ -746,7 +747,10 @@ class QRCodeRenderer extends SymbologyRenderer { /// Method to the split code word List _splitCodeWord( - List> encodeData, int block, int count) { + List> encodeData, + int block, + int count, + ) { final List encodeDataString = List.filled(count, null); for (int i = 0; i < count; i++) { encodeDataString[i] = encodeData[block][i]; @@ -820,7 +824,6 @@ class QRCodeRenderer extends SymbologyRenderer { _eciAssignmentNumber = 2; break; } - //Check for ISO/IEC 8859-2 else if (_getIsISO8859_2CharacterSet(_encodedText[i].codeUnitAt(0))) { _eciAssignmentNumber = 4; @@ -861,7 +864,6 @@ class QRCodeRenderer extends SymbologyRenderer { _eciAssignmentNumber = 13; break; } - //Check for Windows1250 else if (_getIsWindows1250Character(_encodedText[i].codeUnitAt(0))) { _eciAssignmentNumber = 21; @@ -938,17 +940,24 @@ class QRCodeRenderer extends SymbologyRenderer { int capacity = 0; if (_inputMode == QRInputMode.alphaNumeric) { capacity = QRCodeValue.getAlphaNumericDataCapacity( - _errorCorrectionLevel, _codeVersion); + _errorCorrectionLevel, + _codeVersion, + ); } else if (_inputMode == QRInputMode.numeric) { capacity = QRCodeValue.getNumericDataCapacity( - _errorCorrectionLevel, _codeVersion); + _errorCorrectionLevel, + _codeVersion, + ); } else if (_inputMode == QRInputMode.binary) { capacity = QRCodeValue.getBinaryDataCapacity( - _errorCorrectionLevel, _codeVersion); + _errorCorrectionLevel, + _codeVersion, + ); } if (capacity < _encodedText.length) { throw ArgumentError( - 'The input value length is greater than version capacity'); + 'The input value length is greater than version capacity', + ); } } else { int capacityLow = 0, @@ -957,31 +966,55 @@ class QRCodeRenderer extends SymbologyRenderer { capacityHigh = 0; if (_inputMode == QRInputMode.alphaNumeric) { capacityLow = QRCodeValue.getAlphaNumericDataCapacity( - ErrorCorrectionLevel.low, _codeVersion); + ErrorCorrectionLevel.low, + _codeVersion, + ); capacityMedium = QRCodeValue.getAlphaNumericDataCapacity( - ErrorCorrectionLevel.medium, _codeVersion); + ErrorCorrectionLevel.medium, + _codeVersion, + ); capacityQuartile = QRCodeValue.getAlphaNumericDataCapacity( - ErrorCorrectionLevel.quartile, _codeVersion); + ErrorCorrectionLevel.quartile, + _codeVersion, + ); capacityHigh = QRCodeValue.getAlphaNumericDataCapacity( - ErrorCorrectionLevel.high, _codeVersion); + ErrorCorrectionLevel.high, + _codeVersion, + ); } else if (_inputMode == QRInputMode.numeric) { capacityLow = QRCodeValue.getNumericDataCapacity( - ErrorCorrectionLevel.low, _codeVersion); + ErrorCorrectionLevel.low, + _codeVersion, + ); capacityMedium = QRCodeValue.getNumericDataCapacity( - ErrorCorrectionLevel.medium, _codeVersion); + ErrorCorrectionLevel.medium, + _codeVersion, + ); capacityQuartile = QRCodeValue.getNumericDataCapacity( - ErrorCorrectionLevel.quartile, _codeVersion); + ErrorCorrectionLevel.quartile, + _codeVersion, + ); capacityHigh = QRCodeValue.getNumericDataCapacity( - ErrorCorrectionLevel.high, _codeVersion); + ErrorCorrectionLevel.high, + _codeVersion, + ); } else if (_inputMode == QRInputMode.binary) { capacityLow = QRCodeValue.getBinaryDataCapacity( - ErrorCorrectionLevel.low, _codeVersion); + ErrorCorrectionLevel.low, + _codeVersion, + ); capacityMedium = QRCodeValue.getBinaryDataCapacity( - ErrorCorrectionLevel.medium, _codeVersion); + ErrorCorrectionLevel.medium, + _codeVersion, + ); capacityQuartile = QRCodeValue.getBinaryDataCapacity( - ErrorCorrectionLevel.quartile, _codeVersion); + ErrorCorrectionLevel.quartile, + _codeVersion, + ); capacityHigh = QRCodeValue.getBinaryDataCapacity( - ErrorCorrectionLevel.high, _codeVersion); + ErrorCorrectionLevel.high, + _codeVersion, + ); } if (capacityHigh > _encodedText.length) { @@ -994,7 +1027,8 @@ class QRCodeRenderer extends SymbologyRenderer { _errorCorrectionLevel = ErrorCorrectionLevel.low; } else { throw ArgumentError( - 'The input value length is greater than version capacity'); + 'The input value length is greater than version capacity', + ); } } } @@ -1130,9 +1164,10 @@ class QRCodeRenderer extends SymbologyRenderer { /// uses single for loop for calculating the data allocation values void _dataAllocationAndMasking(List data) { _dataAllocationValues = List>.generate( - _noOfModules, - (int i) => - List.generate(_noOfModules, (int j) => ModuleValue())); + _noOfModules, + (int i) => + List.generate(_noOfModules, (int j) => ModuleValue()), + ); int point = 0; @@ -1421,12 +1456,14 @@ class QRCodeRenderer extends SymbologyRenderer { void _generateValues() { _initialize(); _qrCodeValues = QRCodeValue( - qrCodeVersion: _codeVersion, - errorCorrectionLevel: _errorCorrectionLevel); + qrCodeVersion: _codeVersion, + errorCorrectionLevel: _errorCorrectionLevel, + ); _moduleValues = List>.generate( - _noOfModules, - (int i) => - List.generate(_noOfModules, (int j) => ModuleValue())); + _noOfModules, + (int i) => + List.generate(_noOfModules, (int j) => ModuleValue()), + ); _drawPDP(0, 0); _drawPDP(_noOfModules - 7, 0); _drawPDP(0, _noOfModules - 7); @@ -1475,8 +1512,10 @@ class QRCodeRenderer extends SymbologyRenderer { _encodeDataCodeWords.add(true); //Add ECI assignment number - final List numberInBool = - _getStringToBoolArray(_eciAssignmentNumber.toString(), 8); + final List numberInBool = _getStringToBoolArray( + _eciAssignmentNumber.toString(), + 8, + ); for (int i = 0; i < numberInBool.length; i++) { _encodeDataCodeWords.add(numberInBool[i]!); } @@ -1629,7 +1668,8 @@ class QRCodeRenderer extends SymbologyRenderer { /// European Encoding } else { throw ArgumentError( - 'The provided input value contains non-convertible characters'); + 'The provided input value contains non-convertible characters', + ); } final List numberInBool = _getIntToBoolArray(number, 8); @@ -1695,8 +1735,10 @@ class QRCodeRenderer extends SymbologyRenderer { if (_blocks!.length == 6) { totalBlockSize = _blocks![0] + _blocks![3]; } - final List> ds1 = - List>.generate(totalBlockSize, (int i) => []); + final List> ds1 = List>.generate( + totalBlockSize, + (int i) => [], + ); List testEncodeData = _encodeDataCodeWords; if (_blocks!.length == 6) { @@ -1708,33 +1750,45 @@ class QRCodeRenderer extends SymbologyRenderer { } List> dsOne = List>.generate( - _blocks![0], - (int i) => List.filled( - testEncodeData.length ~/ 8 ~/ _blocks![0], null)); + _blocks![0], + (int i) => + List.filled(testEncodeData.length ~/ 8 ~/ _blocks![0], null), + ); dsOne = _getBlocks(testEncodeData, _blocks![0]); for (int i = 0; i < _blocks![0]; i++) { - ds1[i] = - _splitCodeWord(dsOne, i, testEncodeData.length ~/ 8 ~/ _blocks![0]); + ds1[i] = _splitCodeWord( + dsOne, + i, + testEncodeData.length ~/ 8 ~/ _blocks![0], + ); } if (_blocks!.length == 6) { testEncodeData = []; - for (int i = _blocks![0] * _blocks![2] * 8; - i < _encodeDataCodeWords.length; - i++) { + for ( + int i = _blocks![0] * _blocks![2] * 8; + i < _encodeDataCodeWords.length; + i++ + ) { testEncodeData.add(_encodeDataCodeWords[i]); } List> dsTwo = List>.generate( - _blocks![0], - (int i) => List.filled( - testEncodeData.length ~/ 8 ~/ _blocks![3], null)); + _blocks![0], + (int i) => List.filled( + testEncodeData.length ~/ 8 ~/ _blocks![3], + null, + ), + ); dsTwo = _getBlocks(testEncodeData, _blocks![3]); for (int i = _blocks![0], count = 0; i < totalBlockSize; i++) { ds1[i] = _splitCodeWord( - dsTwo, count++, testEncodeData.length ~/ 8 ~/ _blocks![3]); + dsTwo, + count++, + testEncodeData.length ~/ 8 ~/ _blocks![3], + ); } } @@ -1771,7 +1825,9 @@ class QRCodeRenderer extends SymbologyRenderer { final List numberOfBitsInCharacterCountIndicatorInBool = _getIntToBoolArray( - _encodedText.length, numberOfBitsInCharacterCountIndicator); + _encodedText.length, + numberOfBitsInCharacterCountIndicator, + ); for (int i = 0; i < numberOfBitsInCharacterCountIndicator; i++) { _encodeDataCodeWords.add(numberOfBitsInCharacterCountIndicatorInBool[i]!); @@ -1795,10 +1851,14 @@ class QRCodeRenderer extends SymbologyRenderer { /// Method to calculate the error correcting code word void _calculateErrorCorrectingCodeWord( - int totalBlockSize, List> ds1) { + int totalBlockSize, + List> ds1, + ) { final ErrorCorrectionCodeWords errorCorrectionCodeWord = ErrorCorrectionCodeWords( - codeVersion: _codeVersion, correctionLevel: _errorCorrectionLevel); + codeVersion: _codeVersion, + correctionLevel: _errorCorrectionLevel, + ); _dataBits = _qrCodeValues.noOfDataCodeWord; final int eccw = _qrCodeValues.noOfErrorCorrectionCodeWord; @@ -1813,8 +1873,10 @@ class QRCodeRenderer extends SymbologyRenderer { errorCorrectionCodeWord.eccw = eccw ~/ totalBlockSize; - final List> polynomial = - List>.generate(totalBlockSize, (int i) => []); + final List> polynomial = List>.generate( + totalBlockSize, + (int i) => [], + ); int count = 0; for (int i = 0; i < _blocks![0]; i++) { @@ -1856,15 +1918,16 @@ class QRCodeRenderer extends SymbologyRenderer { @override void renderBarcode( - Canvas canvas, - Size size, - Offset offset, - String value, - Color foregroundColor, - TextStyle textStyle, - double textSpacing, - TextAlign textAlign, - bool showValue) { + Canvas canvas, + Size size, + Offset offset, + String value, + Color foregroundColor, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, + bool showValue, + ) { _encodedText = value; _generateValues(); @@ -1899,8 +1962,12 @@ class QRCodeRenderer extends SymbologyRenderer { } } - final Rect rect = Rect.fromLTRB(x.toDouble(), yPosition.toDouble(), - (x + dimension).toDouble(), (yPosition + dimension).toDouble()); + final Rect rect = Rect.fromLTRB( + x.toDouble(), + yPosition.toDouble(), + (x + dimension).toDouble(), + (yPosition + dimension).toDouble(), + ); canvas.drawRect(rect, paint); x = (x + dimension).toInt(); @@ -1912,23 +1979,39 @@ class QRCodeRenderer extends SymbologyRenderer { if (showValue) { final Offset textOffset = Offset(offset.dx, yPosition.toDouble()); drawText( - canvas, textOffset, size, value, textStyle, textSpacing, textAlign); + canvas, + textOffset, + size, + value, + textStyle, + textSpacing, + textAlign, + ); } } /// Method to render the input value of the barcode @override - void drawText(Canvas canvas, Offset offset, Size size, String value, - TextStyle textStyle, double textSpacing, TextAlign textAlign, - [Offset? actualOffset, Size? actualSize]) { + void drawText( + Canvas canvas, + Offset offset, + Size size, + String value, + TextStyle textStyle, + double textSpacing, + TextAlign textAlign, [ + Offset? actualOffset, + Size? actualSize, + ]) { final TextSpan span = TextSpan(text: value, style: textStyle); final TextPainter textPainter = TextPainter( - maxLines: 1, - ellipsis: '.....', - text: span, - textDirection: TextDirection.ltr, - textAlign: textAlign); + maxLines: 1, + ellipsis: '.....', + text: span, + textDirection: TextDirection.ltr, + textAlign: textAlign, + ); textPainter.layout(maxWidth: size.width); double x; double y; diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_values.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_values.dart index d88600794..3f948a99b 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_values.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/renderers/two_dimensional/qr_code_values.dart @@ -200,7 +200,7 @@ class QRCodeValue { 750, 1372, 2040, - 2430 + 2430, ]; /// Specifies the value of numeric data capacity of low error correction level @@ -379,7 +379,7 @@ class QRCodeValue { 2625, 2735, 2927, - 3057 + 3057, ]; /// Specifies the value of alpha numeric data capacity of low error @@ -424,7 +424,7 @@ class QRCodeValue { 3729, 3927, 4087, - 4296 + 4296, ]; /// Specifies the value of alpha numeric data capacity of high error @@ -469,7 +469,7 @@ class QRCodeValue { 2894, 3054, 3220, - 3391 + 3391, ]; /// Specifies the value of alpha numeric data capacity of quartile error @@ -514,7 +514,7 @@ class QRCodeValue { 2071, 2181, 2298, - 2420 + 2420, ]; /// Specifies the value of alpha numeric data capacity of high error @@ -559,7 +559,7 @@ class QRCodeValue { 1591, 1658, 1774, - 1852 + 1852, ]; /// Specifies the value of binary data capacity of low error correction level @@ -603,7 +603,7 @@ class QRCodeValue { 2563, 2699, 2809, - 2953 + 2953, ]; /// Specifies the value of binary data capacity of medium error correction @@ -648,7 +648,7 @@ class QRCodeValue { 1989, 2099, 2213, - 2331 + 2331, ]; /// Specifies the value of binary data capacity of quartile error correction @@ -693,7 +693,7 @@ class QRCodeValue { 1423, 1499, 1579, - 1663 + 1663, ]; /// Specifies the value of binary data capacity of high error correction level @@ -737,12 +737,14 @@ class QRCodeValue { 1093, 1139, 1219, - 1273 + 1273, ]; /// Returns the numeric data capacity static int getNumericDataCapacity( - ErrorCorrectionLevel level, QRCodeVersion codeVersion) { + ErrorCorrectionLevel level, + QRCodeVersion codeVersion, + ) { List capacity; switch (level) { case ErrorCorrectionLevel.low: @@ -765,7 +767,9 @@ class QRCodeValue { /// Specifies the alpha numeric data capcity static int getAlphaNumericDataCapacity( - ErrorCorrectionLevel level, QRCodeVersion codeVersion) { + ErrorCorrectionLevel level, + QRCodeVersion codeVersion, + ) { List capacity; switch (level) { case ErrorCorrectionLevel.low: @@ -789,7 +793,9 @@ class QRCodeValue { /// Specifies the bunary data capacity static int getBinaryDataCapacity( - ErrorCorrectionLevel level, QRCodeVersion codeVersion) { + ErrorCorrectionLevel level, + QRCodeVersion codeVersion, + ) { List capacity; switch (level) { case ErrorCorrectionLevel.low: @@ -3080,7 +3086,7 @@ class QRCodeValue { 1, 0, 0, - 0 + 0, ]; break; case 8: @@ -3102,7 +3108,7 @@ class QRCodeValue { 0, 1, 0, - 0 + 0, ]; break; case 9: @@ -3124,7 +3130,7 @@ class QRCodeValue { 0, 1, 0, - 0 + 0, ]; break; case 10: @@ -3146,7 +3152,7 @@ class QRCodeValue { 0, 1, 0, - 0 + 0, ]; break; case 11: @@ -3168,7 +3174,7 @@ class QRCodeValue { 0, 1, 0, - 0 + 0, ]; break; case 12: @@ -3190,7 +3196,7 @@ class QRCodeValue { 1, 1, 0, - 0 + 0, ]; break; case 13: @@ -3212,7 +3218,7 @@ class QRCodeValue { 1, 1, 0, - 0 + 0, ]; break; case 14: @@ -3234,7 +3240,7 @@ class QRCodeValue { 1, 1, 0, - 0 + 0, ]; break; case 15: @@ -3256,7 +3262,7 @@ class QRCodeValue { 1, 1, 0, - 0 + 0, ]; break; case 16: @@ -3278,7 +3284,7 @@ class QRCodeValue { 0, 0, 1, - 0 + 0, ]; break; case 17: @@ -3300,7 +3306,7 @@ class QRCodeValue { 0, 0, 1, - 0 + 0, ]; break; case 18: @@ -3322,7 +3328,7 @@ class QRCodeValue { 0, 0, 1, - 0 + 0, ]; break; case 19: @@ -3344,7 +3350,7 @@ class QRCodeValue { 0, 0, 1, - 0 + 0, ]; break; case 20: @@ -3366,7 +3372,7 @@ class QRCodeValue { 1, 0, 1, - 0 + 0, ]; break; case 21: @@ -3388,7 +3394,7 @@ class QRCodeValue { 1, 0, 1, - 0 + 0, ]; break; case 22: @@ -3410,7 +3416,7 @@ class QRCodeValue { 1, 0, 1, - 0 + 0, ]; break; case 23: @@ -3432,7 +3438,7 @@ class QRCodeValue { 1, 0, 1, - 0 + 0, ]; break; case 24: @@ -3454,7 +3460,7 @@ class QRCodeValue { 0, 1, 1, - 0 + 0, ]; break; case 25: @@ -3476,7 +3482,7 @@ class QRCodeValue { 0, 1, 1, - 0 + 0, ]; break; case 26: @@ -3498,7 +3504,7 @@ class QRCodeValue { 0, 1, 1, - 0 + 0, ]; break; case 27: @@ -3520,7 +3526,7 @@ class QRCodeValue { 0, 1, 1, - 0 + 0, ]; break; case 28: @@ -3542,7 +3548,7 @@ class QRCodeValue { 1, 1, 1, - 0 + 0, ]; break; case 29: @@ -3564,7 +3570,7 @@ class QRCodeValue { 1, 1, 1, - 0 + 0, ]; break; case 30: @@ -3586,7 +3592,7 @@ class QRCodeValue { 1, 1, 1, - 0 + 0, ]; break; case 31: @@ -3608,7 +3614,7 @@ class QRCodeValue { 1, 1, 1, - 0 + 0, ]; break; case 32: @@ -3630,7 +3636,7 @@ class QRCodeValue { 0, 0, 0, - 1 + 1, ]; break; case 33: @@ -3652,7 +3658,7 @@ class QRCodeValue { 0, 0, 0, - 1 + 1, ]; break; case 34: @@ -3674,7 +3680,7 @@ class QRCodeValue { 0, 0, 0, - 1 + 1, ]; break; case 35: @@ -3696,7 +3702,7 @@ class QRCodeValue { 0, 0, 0, - 1 + 1, ]; break; case 36: @@ -3718,7 +3724,7 @@ class QRCodeValue { 1, 0, 0, - 1 + 1, ]; break; case 37: @@ -3740,7 +3746,7 @@ class QRCodeValue { 1, 0, 0, - 1 + 1, ]; break; case 38: @@ -3762,7 +3768,7 @@ class QRCodeValue { 1, 0, 0, - 1 + 1, ]; break; case 39: @@ -3784,7 +3790,7 @@ class QRCodeValue { 1, 0, 0, - 1 + 1, ]; break; case 40: @@ -3806,7 +3812,7 @@ class QRCodeValue { 0, 1, 0, - 1 + 1, ]; break; } diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/datamatrix_symbology.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/datamatrix_symbology.dart index ffa636fef..bfbf02525 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/datamatrix_symbology.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/datamatrix_symbology.dart @@ -16,11 +16,11 @@ class DataMatrix extends Symbology { /// /// The arguments [module] must be non-negative and greater than 0. /// - DataMatrix( - {int? module, - this.dataMatrixSize = DataMatrixSize.auto, - this.encoding = DataMatrixEncoding.auto}) - : super(module: module); + DataMatrix({ + int? module, + this.dataMatrixSize = DataMatrixSize.auto, + this.encoding = DataMatrixEncoding.auto, + }) : super(module: module); /// Define the size that is used to encode the amount of data. /// diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/qr_code_symbology.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/qr_code_symbology.dart index 66a97945a..7bb95df42 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/qr_code_symbology.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/two_dimensional/qr_code_symbology.dart @@ -30,12 +30,12 @@ class QRCode extends Symbology { /// /// The arguments [module] must be non-negative and greater than 0. /// - QRCode( - {this.codeVersion, - this.errorCorrectionLevel = ErrorCorrectionLevel.high, - this.inputMode = QRInputMode.binary, - int? module}) - : super(module: module); + QRCode({ + this.codeVersion, + this.errorCorrectionLevel = ErrorCorrectionLevel.high, + this.inputMode = QRInputMode.binary, + int? module, + }) : super(module: module); /// Define the version that is used to encode the amount of data. /// diff --git a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/utils/enum.dart b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/utils/enum.dart index 3fd6a47c9..3f1a8988e 100644 --- a/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/utils/enum.dart +++ b/packages/syncfusion_flutter_barcodes/lib/src/barcode_generator/utils/enum.dart @@ -10,7 +10,7 @@ enum CodeType { doubleDigit, ///CodeType.fnc1 represents the input symbol is special character. - fnc1 + fnc1, } /// Versions that is used to encode the amount of data. @@ -136,7 +136,7 @@ enum QRCodeVersion { version39, ///QRCodeVersion.version40 specifies the qr code version is 40. - version40 + version40, } /// Encode recovery capacity of the barcode. @@ -152,7 +152,7 @@ enum ErrorCorrectionLevel { quartile, ///ErrorCorrectionLevel.high is recover approximately 30% of the codewords. - high + high, } /// Specific set of input mode characters. @@ -164,7 +164,7 @@ enum QRInputMode { alphaNumeric, ///QRInputMode.binary represents the input data as binary. - binary + binary, } /// Encoding type for the [DataMatrix] code. @@ -179,7 +179,7 @@ enum DataMatrixEncoding { asciiNumeric, /// DataMatrixEncoding.base256 represents the base256 encoding. - base256 + base256, } /// Sizes that is used to encode the amount of [DataMatrix] data. @@ -275,5 +275,5 @@ enum DataMatrixSize { size16x36, /// DataMatrixSize.size16x48 represents the 16x48 matrix. - size16x48 + size16x48, } diff --git a/packages/syncfusion_flutter_barcodes/pubspec.yaml b/packages/syncfusion_flutter_barcodes/pubspec.yaml index d54bd6693..aa8e7860e 100644 --- a/packages/syncfusion_flutter_barcodes/pubspec.yaml +++ b/packages/syncfusion_flutter_barcodes/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_barcodes description: Flutter Barcodes generator library is used to generate and display data in the machine-readable, industry-standard 1D and 2D barcodes. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_barcodes screenshots: @@ -12,13 +12,13 @@ screenshots: environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: sdk: flutter syncfusion_flutter_core: - path: ../syncfusion_flutter_core + path: ../syncfusion_flutter_core diff --git a/packages/syncfusion_flutter_calendar/CHANGELOG.md b/packages/syncfusion_flutter_calendar/CHANGELOG.md index a96556a8f..6a0ed1d4f 100644 --- a/packages/syncfusion_flutter_calendar/CHANGELOG.md +++ b/packages/syncfusion_flutter_calendar/CHANGELOG.md @@ -2,6 +2,36 @@ **General** +* Upgraded the `timezone` package to the latest version 0.10.1. + +* The compatible version of our Flutter calendar widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +**Bugs** + +* \#FB66714 - Now, the font size is no longer calculated with a negative value in [SfCalendar](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar-class.html) when placed in a constrained space. + +* \#FB66695 - Now, the [headerDateFormat](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/headerDateFormat.html) is applied correctly in the resource view of [SfCalendar](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar-class.html), displaying the date in the expected format. + +* \#FB66695 - Now, the week number in the resource view of [SfCalendar](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar-class.html), is fully visible and no longer gets cut off when sufficient space is available. + +* \#FB66690 - Now, the calendar cell overlay position updates correctly in the month view when the [timeRulerSize](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/TimeSlotViewSettings/timeRulerSize.html) is added in the [timeSlotViewSettings](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/timeSlotViewSettings.html) of SfCalendar. + +## [29.1.37] - 08/04/2025 + +**Bugs** + +* \#FB66610 - Now, the interactive widgets will work on the [appointmentBuilder](https://pub.dev/documentation/syncfusion_flutter_calendar/latest/calendar/SfCalendar/appointmentBuilder.html) in SfCalendar. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter calendar widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter calendar example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter calendar example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_calendar/assets/fonts/Roboto-Medium.ttf b/packages/syncfusion_flutter_calendar/assets/fonts/Roboto-Medium.ttf new file mode 100644 index 000000000..d629e9848 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/fonts/Roboto-Medium.ttf differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/May.png b/packages/syncfusion_flutter_calendar/assets/images/May.png new file mode 100644 index 000000000..568ef2af5 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/May.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle11.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle11.png new file mode 100644 index 000000000..657adc38f Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle11.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle13.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle13.png new file mode 100644 index 000000000..0f7a0da09 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle13.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle15.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle15.png new file mode 100644 index 000000000..b8c08e671 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle15.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle18.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle18.png new file mode 100644 index 000000000..4f31688b0 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle18.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle20.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle20.png new file mode 100644 index 000000000..6a13793d2 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle20.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle23.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle23.png new file mode 100644 index 000000000..d7a12ee96 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle23.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle24.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle24.png new file mode 100644 index 000000000..d59cc5781 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle24.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle25.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle25.png new file mode 100644 index 000000000..e047277d6 Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle25.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle26.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle26.png new file mode 100644 index 000000000..f88ab438e Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle26.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle27.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle27.png new file mode 100644 index 000000000..4359bd60b Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle27.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle5.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle5.png new file mode 100644 index 000000000..9a1f4b34a Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle5.png differ diff --git a/packages/syncfusion_flutter_calendar/assets/images/People_Circle8.png b/packages/syncfusion_flutter_calendar/assets/images/People_Circle8.png new file mode 100644 index 000000000..f4fd0f82c Binary files /dev/null and b/packages/syncfusion_flutter_calendar/assets/images/People_Circle8.png differ diff --git a/packages/syncfusion_flutter_calendar/example/lib/main.dart b/packages/syncfusion_flutter_calendar/example/lib/main.dart index 0bf68386a..f7eef85b8 100644 --- a/packages/syncfusion_flutter_calendar/example/lib/main.dart +++ b/packages/syncfusion_flutter_calendar/example/lib/main.dart @@ -29,15 +29,17 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( - body: SfCalendar( - view: CalendarView.month, - dataSource: MeetingDataSource(_getDataSource()), - // by default the month appointment display mode set as Indicator, we can - // change the display mode as appointment using the appointment display - // mode property - monthViewSettings: const MonthViewSettings( - appointmentDisplayMode: MonthAppointmentDisplayMode.appointment), - )); + body: SfCalendar( + view: CalendarView.month, + dataSource: MeetingDataSource(_getDataSource()), + // by default the month appointment display mode set as Indicator, we can + // change the display mode as appointment using the appointment display + // mode property + monthViewSettings: const MonthViewSettings( + appointmentDisplayMode: MonthAppointmentDisplayMode.appointment, + ), + ), + ); } List _getDataSource() { @@ -45,8 +47,9 @@ class _MyHomePageState extends State { final DateTime today = DateTime.now(); final DateTime startTime = DateTime(today.year, today.month, today.day, 9); final DateTime endTime = startTime.add(const Duration(hours: 2)); - meetings.add(Meeting( - 'Conference', startTime, endTime, const Color(0xFF0F8644), false)); + meetings.add( + Meeting('Conference', startTime, endTime, const Color(0xFF0F8644), false), + ); return meetings; } } diff --git a/packages/syncfusion_flutter_calendar/example/pubspec.yaml b/packages/syncfusion_flutter_calendar/example/pubspec.yaml index 9f5cc4b3a..8b21f28ed 100644 --- a/packages/syncfusion_flutter_calendar/example/pubspec.yaml +++ b/packages/syncfusion_flutter_calendar/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Syncfusion calendar example. version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment.dart index fdc7028eb..91ea50cd9 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment.dart @@ -85,10 +85,11 @@ class Appointment with Diagnosticable { this.subject = '', this.color = Colors.lightBlue, this.recurrenceExceptionDates, - }) : notes = notes != null && notes.contains('isOccurrenceAppointment') - ? notes.replaceAll('isOccurrenceAppointment', '') - : notes, - _notes = notes { + }) : notes = + notes != null && notes.contains('isOccurrenceAppointment') + ? notes.replaceAll('isOccurrenceAppointment', '') + : notes, + _notes = notes { recurrenceRule = recurrenceId != null ? null : recurrenceRule; _appointmentType = _getAppointmentType(); id = id ?? hashCode; @@ -1021,14 +1022,21 @@ class Appointment with Diagnosticable { properties.add(ColorProperty('color', color)); properties.add(DiagnosticsProperty('recurrenceId', recurrenceId)); properties.add(DiagnosticsProperty('id', id)); - properties - .add(EnumProperty('appointmentType', appointmentType)); + properties.add( + EnumProperty('appointmentType', appointmentType), + ); properties.add(DiagnosticsProperty('startTime', startTime)); properties.add(DiagnosticsProperty('endTime', endTime)); - properties.add(IterableDiagnostics(recurrenceExceptionDates) - .toDiagnosticsNode(name: 'recurrenceExceptionDates')); - properties.add(IterableDiagnostics(resourceIds) - .toDiagnosticsNode(name: 'resourceIds')); + properties.add( + IterableDiagnostics( + recurrenceExceptionDates, + ).toDiagnosticsNode(name: 'recurrenceExceptionDates'), + ); + properties.add( + IterableDiagnostics( + resourceIds, + ).toDiagnosticsNode(name: 'resourceIds'), + ); properties.add(DiagnosticsProperty('isAllDay', isAllDay)); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment_helper.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment_helper.dart index 3658d9b5f..8a48020b0 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment_helper.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/appointment_helper.dart @@ -48,11 +48,23 @@ class AppointmentHelper { /// Return the date time value by adding the days in date. static DateTime addDaysWithTime( - DateTime date, int days, int hour, int minute, int second) { - final DateTime newDate = - DateTimeHelper.getDateTimeValue(addDays(date, days)); + DateTime date, + int days, + int hour, + int minute, + int second, + ) { + final DateTime newDate = DateTimeHelper.getDateTimeValue( + addDays(date, days), + ); return DateTime( - newDate.year, newDate.month, newDate.day, hour, minute, second); + newDate.year, + newDate.month, + newDate.day, + hour, + minute, + second, + ); } /// Check whether the data source has calendar appointment type or not. @@ -72,21 +84,27 @@ class AppointmentHelper { appointment.actualStartTime.month && appointment.actualEndTime.year == appointment.actualStartTime.year) && - getDifference(appointment.actualStartTime, appointment.actualEndTime) - .inDays > + getDifference( + appointment.actualStartTime, + appointment.actualEndTime, + ).inDays > 0; } /// Check and returns whether the span icon can be added for the spanning /// appointment. - static bool canAddSpanIcon(List visibleDates, - CalendarAppointment appointment, CalendarView view, - {DateTime? visibleStartDate, - DateTime? visibleEndDate, - bool? showTrailingLeadingDates}) { + static bool canAddSpanIcon( + List visibleDates, + CalendarAppointment appointment, + CalendarView view, { + DateTime? visibleStartDate, + DateTime? visibleEndDate, + bool? showTrailingLeadingDates, + }) { final DateTime viewStartDate = convertToStartTime(visibleDates[0]); - final DateTime viewEndDate = - convertToEndTime(visibleDates[visibleDates.length - 1]); + final DateTime viewEndDate = convertToEndTime( + visibleDates[visibleDates.length - 1], + ); final DateTime appStartTime = appointment.exactStartTime; final DateTime appEndTime = appointment.exactEndTime; @@ -122,10 +140,10 @@ class AppointmentHelper { if (appStartTime.isAfter(viewStartDate)) { final int appointmentStartWeek = getDifference(viewStartDate, appStartTime).inDays ~/ - DateTime.daysPerWeek; + DateTime.daysPerWeek; final int appointmentEndWeek = getDifference(viewStartDate, appEndTime).inDays ~/ - DateTime.daysPerWeek; + DateTime.daysPerWeek; return appointmentStartWeek != appointmentEndWeek; } } @@ -136,28 +154,36 @@ class AppointmentHelper { /// Returns recurrence icon details for appointment view. static TextSpan getRecurrenceIcon( - Color color, double textSize, bool isRecurrenceAppointment) { + Color color, + double textSize, + bool isRecurrenceAppointment, + ) { final IconData recurrenceIconData = isRecurrenceAppointment ? Icons.autorenew : Icons.sync_disabled; return TextSpan( - text: String.fromCharCode(recurrenceIconData.codePoint), - style: TextStyle( - color: color, - fontSize: textSize, - fontFamily: recurrenceIconData.fontFamily, - )); + text: String.fromCharCode(recurrenceIconData.codePoint), + style: TextStyle( + color: color, + fontSize: textSize, + fontFamily: recurrenceIconData.fontFamily, + ), + ); } /// Calculate and returns the centered y position for the span icon in the /// spanning appointment UI. static double getYPositionForSpanIcon( - TextSpan icon, TextPainter textPainter, RRect rect) { + TextSpan icon, + TextPainter textPainter, + RRect rect, + ) { /// There is a space around the font, hence to get the start position we /// must calculate the icon start position, apart from the space, and the /// value 1.5 used since the space on top and bottom of icon is not even, /// hence to rectify this tha value 1.5 used, and tested with multiple /// device. - final int iconStartPosition = (textPainter.height - + final int iconStartPosition = + (textPainter.height - (textPainter.textScaler.scale(icon.style!.fontSize!))) ~/ 1.5; return rect.top - @@ -169,15 +195,21 @@ class AppointmentHelper { /// appointments on day, timeline day, schedule and month agenda view. /// The text will display the current date, and total dates of the spanning /// appointment - static String getSpanAppointmentText(CalendarAppointment appointment, - DateTime date, SfLocalizations localization) { - final DateTime exactStartTime = - convertToStartTime(appointment.exactStartTime); - final String totalDays = (getDifference( - exactStartTime, convertToEndTime(appointment.exactEndTime)) - .inDays + - 1) - .toString(); + static String getSpanAppointmentText( + CalendarAppointment appointment, + DateTime date, + SfLocalizations localization, + ) { + final DateTime exactStartTime = convertToStartTime( + appointment.exactStartTime, + ); + final String totalDays = + (getDifference( + exactStartTime, + convertToEndTime(appointment.exactEndTime), + ).inDays + + 1) + .toString(); final String currentDate = (getDifference(exactStartTime, convertToEndTime(date)).inDays + 1) .toString(); @@ -190,26 +222,35 @@ class AppointmentHelper { /// Text size multiplied by two, to align the icon, since the icon itself /// covered by some space in the top and bottom side, hence size multiplied. return TextSpan( - text: isForward ? '\u00BB' : '\u00AB', - style: TextStyle( - color: color, - fontSize: textSize * 2, - fontFamily: 'Roboto', - )); + text: isForward ? '\u00BB' : '\u00AB', + style: TextStyle( + color: color, + fontSize: textSize * 2, + fontFamily: 'Roboto', + ), + ); } /// Check and returns whether the forward icon can be added for the spanning /// appointment. - static bool canAddForwardSpanIcon(DateTime appStartTime, DateTime appEndTime, - DateTime viewStartDate, DateTime viewEndDate) { + static bool canAddForwardSpanIcon( + DateTime appStartTime, + DateTime appEndTime, + DateTime viewStartDate, + DateTime viewEndDate, + ) { return isSameOrAfterDate(viewStartDate, appStartTime) && appEndTime.isAfter(viewEndDate); } /// Check and returns whether the backward icon can be added for the spanning /// appointment. - static bool canAddBackwardSpanIcon(DateTime appStartTime, DateTime appEndTime, - DateTime viewStartDate, DateTime viewEndDate) { + static bool canAddBackwardSpanIcon( + DateTime appStartTime, + DateTime appEndTime, + DateTime viewStartDate, + DateTime viewEndDate, + ) { return appStartTime.isBefore(viewStartDate) && isSameOrBeforeDate(viewEndDate, appEndTime); } @@ -217,7 +258,9 @@ class AppointmentHelper { /// Returns the specific date appointment collection by filtering the /// appointments from passed visible appointment collection. static List getSpecificDateVisibleAppointment( - DateTime? date, List? visibleAppointments) { + DateTime? date, + List? visibleAppointments, + ) { final List appointmentCollection = []; if (date == null || visibleAppointments == null) { @@ -230,7 +273,10 @@ class AppointmentHelper { for (int j = 0; j < visibleAppointments.length; j++) { final CalendarAppointment appointment = visibleAppointments[j]; if (isAppointmentWithinVisibleDateRange( - appointment, startDate, endDate)) { + appointment, + startDate, + endDate, + )) { appointmentCollection.add(appointment); } } @@ -240,9 +286,10 @@ class AppointmentHelper { /// Return appointment collection based on the date. static List getSelectedDateAppointments( - List? appointments, - String? timeZone, - DateTime? date) { + List? appointments, + String? timeZone, + DateTime? date, + ) { final List appointmentCollection = []; if (appointments == null || appointments.isEmpty || date == null) { @@ -256,16 +303,25 @@ class AppointmentHelper { for (int j = 0; j < count; j++) { final CalendarAppointment appointment = appointments[j]; appointment.actualStartTime = convertTimeToAppointmentTimeZone( - appointment.startTime, appointment.startTimeZone, timeZone); + appointment.startTime, + appointment.startTimeZone, + timeZone, + ); appointment.actualEndTime = convertTimeToAppointmentTimeZone( - appointment.endTime, appointment.endTimeZone, timeZone); + appointment.endTime, + appointment.endTimeZone, + timeZone, + ); appointment.exactStartTime = appointment.actualStartTime; appointment.exactEndTime = appointment.actualEndTime; if (appointment.recurrenceRule == null || appointment.recurrenceRule == '') { if (isAppointmentWithinVisibleDateRange( - appointment, startDate, endDate)) { + appointment, + startDate, + endDate, + )) { appointmentCollection.add(appointment); } @@ -273,7 +329,12 @@ class AppointmentHelper { } _getRecurrenceAppointments( - appointment, appointmentCollection, startDate, endDate, timeZone); + appointment, + appointmentCollection, + startDate, + endDate, + timeZone, + ); } return appointmentCollection; @@ -281,32 +342,37 @@ class AppointmentHelper { /// Return calendar appointment text style. static TextStyle getAppointmentTextStyle( - TextStyle appointmentTextStyle, CalendarView view, ThemeData themeData) { + TextStyle appointmentTextStyle, + CalendarView view, + ThemeData themeData, + ) { if (appointmentTextStyle.fontSize != -1) { return themeData.textTheme.bodyMedium!.merge(appointmentTextStyle); } - return themeData.textTheme.bodyMedium! - .merge(appointmentTextStyle.copyWith(fontSize: 12)); + return themeData.textTheme.bodyMedium!.merge( + appointmentTextStyle.copyWith(fontSize: 12), + ); } static CalendarAppointment _copy(CalendarAppointment appointment) { final CalendarAppointment copyAppointment = CalendarAppointment( - startTime: appointment.startTime, - endTime: appointment.endTime, - isAllDay: appointment.isAllDay, - subject: appointment.subject, - color: appointment.color, - startTimeZone: appointment.startTimeZone, - endTimeZone: appointment.endTimeZone, - recurrenceRule: appointment.recurrenceRule, - recurrenceExceptionDates: appointment.recurrenceExceptionDates, - notes: appointment.notes, - location: appointment.location, - isSpanned: appointment.isSpanned, - resourceIds: CalendarViewHelper.cloneList(appointment.resourceIds), - recurrenceId: appointment.recurrenceId, - id: appointment.id); + startTime: appointment.startTime, + endTime: appointment.endTime, + isAllDay: appointment.isAllDay, + subject: appointment.subject, + color: appointment.color, + startTimeZone: appointment.startTimeZone, + endTimeZone: appointment.endTimeZone, + recurrenceRule: appointment.recurrenceRule, + recurrenceExceptionDates: appointment.recurrenceExceptionDates, + notes: appointment.notes, + location: appointment.location, + isSpanned: appointment.isSpanned, + resourceIds: CalendarViewHelper.cloneList(appointment.resourceIds), + recurrenceId: appointment.recurrenceId, + id: appointment.id, + ); copyAppointment.actualStartTime = appointment.actualStartTime; copyAppointment.actualEndTime = appointment.actualEndTime; copyAppointment.data = appointment.data; @@ -317,16 +383,25 @@ class AppointmentHelper { /// Check the appointment in between the visible date range. static bool isAppointmentWithinVisibleDateRange( - CalendarAppointment appointment, - DateTime visibleStart, - DateTime visibleEnd) { - return isDateRangeWithinVisibleDateRange(appointment.actualStartTime, - appointment.actualEndTime, visibleStart, visibleEnd); + CalendarAppointment appointment, + DateTime visibleStart, + DateTime visibleEnd, + ) { + return isDateRangeWithinVisibleDateRange( + appointment.actualStartTime, + appointment.actualEndTime, + visibleStart, + visibleEnd, + ); } /// Check the date range in between the visible date range. - static bool isDateRangeWithinVisibleDateRange(DateTime startDate, - DateTime endDate, DateTime visibleStart, DateTime visibleEnd) { + static bool isDateRangeWithinVisibleDateRange( + DateTime startDate, + DateTime endDate, + DateTime visibleStart, + DateTime visibleEnd, + ) { if (startDate.isAfter(visibleStart)) { if (startDate.isBefore(visibleEnd)) { return true; @@ -342,8 +417,11 @@ class AppointmentHelper { return false; } - static bool _isAppointmentInVisibleDateRange(CalendarAppointment appointment, - DateTime visibleStart, DateTime visibleEnd) { + static bool _isAppointmentInVisibleDateRange( + CalendarAppointment appointment, + DateTime visibleStart, + DateTime visibleEnd, + ) { final DateTime appStartTime = appointment.actualStartTime; final DateTime appEndTime = appointment.actualEndTime; if ((appStartTime.isAfter(visibleStart) || @@ -371,7 +449,10 @@ class AppointmentHelper { /// Check and returns whether the appointment's start or end date falls within /// the visible dates passed to the method. static bool _isAppointmentDateWithinVisibleDateRange( - DateTime appointmentDate, DateTime visibleStart, DateTime visibleEnd) { + DateTime appointmentDate, + DateTime visibleStart, + DateTime visibleEnd, + ) { if (appointmentDate.isAfter(visibleStart)) { if (appointmentDate.isBefore(visibleEnd)) { return true; @@ -508,25 +589,28 @@ class AppointmentHelper { final DateTime actualConvertedDate; if (targetTimezone == 'Dateline Standard Time') { - actualConvertedDate = - convertedDate.toUtc().subtract(const Duration(hours: 12)); + actualConvertedDate = convertedDate.toUtc().subtract( + const Duration(hours: 12), + ); } else { final Location location = _timeZoneInfoToOlsonTimeZone(targetTimezone!); actualConvertedDate = TZDateTime.from(convertedDate, location); } return DateTime( - actualConvertedDate.year, - actualConvertedDate.month, - actualConvertedDate.day, - actualConvertedDate.hour, - actualConvertedDate.minute, - actualConvertedDate.second); + actualConvertedDate.year, + actualConvertedDate.month, + actualConvertedDate.day, + actualConvertedDate.hour, + actualConvertedDate.minute, + actualConvertedDate.second, + ); } /// Resets the appointment views used on appointment layout rendering. static void resetAppointmentView( - List appointmentCollection) { + List appointmentCollection, + ) { for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView obj = appointmentCollection[i]; obj.canReuse = true; @@ -541,8 +625,12 @@ class AppointmentHelper { /// Returns the position from time passed, based on the time interval height. static double timeToPosition( - SfCalendar calendar, DateTime date, double timeIntervalHeight) { - final double singleIntervalHeightForAnHour = (60 / + SfCalendar calendar, + DateTime date, + double timeIntervalHeight, + ) { + final double singleIntervalHeightForAnHour = + (60 / CalendarViewHelper.getTimeInterval(calendar.timeSlotViewSettings)) * timeIntervalHeight; @@ -553,25 +641,30 @@ class AppointmentHelper { } /// Returns the appointment height from the duration passed. - static double getAppointmentHeightFromDuration(Duration? minimumDuration, - SfCalendar calendar, double timeIntervalHeight) { + static double getAppointmentHeightFromDuration( + Duration? minimumDuration, + SfCalendar calendar, + double timeIntervalHeight, + ) { if (minimumDuration == null || minimumDuration.inMinutes <= 0) { return 0; } - final double hourHeight = (60 / + final double hourHeight = + (60 / CalendarViewHelper.getTimeInterval(calendar.timeSlotViewSettings)) * timeIntervalHeight; return minimumDuration.inMinutes * (hourHeight / 60); } static bool _isIntersectingAppointmentInDayView( - SfCalendar calendar, - CalendarView view, - CalendarAppointment currentApp, - AppointmentView appView, - CalendarAppointment appointment, - int timeIntervalMinutes) { + SfCalendar calendar, + CalendarView view, + CalendarAppointment currentApp, + AppointmentView appView, + CalendarAppointment appointment, + int timeIntervalMinutes, + ) { if (currentApp == appointment) { return false; } @@ -584,11 +677,14 @@ class AppointmentHelper { int minimumAppointmentMinutes = calendar.timeSlotViewSettings.minimumAppointmentDuration != null ? calendar - .timeSlotViewSettings.minimumAppointmentDuration!.inMinutes + .timeSlotViewSettings + .minimumAppointmentDuration! + .inMinutes : 0; - minimumAppointmentMinutes = minimumAppointmentMinutes > timeIntervalMinutes - ? timeIntervalMinutes - : minimumAppointmentMinutes; + minimumAppointmentMinutes = + minimumAppointmentMinutes > timeIntervalMinutes + ? timeIntervalMinutes + : minimumAppointmentMinutes; if (minimumAppointmentMinutes > 0 && !isTimelineMonth) { final int timeIntervalMinutes = calendar.timeSlotViewSettings.timeInterval.inMinutes; @@ -596,17 +692,21 @@ class AppointmentHelper { minimumAppointmentMinutes > timeIntervalMinutes ? timeIntervalMinutes : minimumAppointmentMinutes; - if (getDifference(currentAppointmentStartTime, currentAppointmentEndTime) - .inMinutes < + if (getDifference( + currentAppointmentStartTime, + currentAppointmentEndTime, + ).inMinutes < minimumAppointmentMinutes) { - currentAppointmentEndTime = currentAppointmentStartTime - .add(Duration(minutes: minimumAppointmentMinutes)); + currentAppointmentEndTime = currentAppointmentStartTime.add( + Duration(minutes: minimumAppointmentMinutes), + ); } if (getDifference(appointmentStartTime, appointmentEndTime).inMinutes < minimumAppointmentMinutes) { - appointmentEndTime = appointmentStartTime - .add(Duration(minutes: minimumAppointmentMinutes)); + appointmentEndTime = appointmentStartTime.add( + Duration(minutes: minimumAppointmentMinutes), + ); } } @@ -630,15 +730,21 @@ class AppointmentHelper { /// condition and returned that it's a intercept appointment or not. if (isTimelineMonth) { return isSameDate( - currentApp.actualStartTime, appointment.actualStartTime) || + currentApp.actualStartTime, + appointment.actualStartTime, + ) || isSameDate(currentApp.actualStartTime, appointment.actualEndTime) || isSameDate(currentApp.actualEndTime, appointment.actualStartTime); } if (CalendarViewHelper.isSameTimeSlot( - currentAppointmentStartTime, appointmentStartTime) || + currentAppointmentStartTime, + appointmentStartTime, + ) || CalendarViewHelper.isSameTimeSlot( - currentAppointmentEndTime, appointmentEndTime)) { + currentAppointmentEndTime, + appointmentEndTime, + )) { return true; } @@ -646,7 +752,10 @@ class AppointmentHelper { } static bool _iterateAppointment( - CalendarAppointment app, bool isTimeline, bool isAllDay) { + CalendarAppointment app, + bool isTimeline, + bool isAllDay, + ) { if (isAllDay) { if (!isTimeline && app.isAllDay) { app.actualEndTime = convertToEndTime(app.actualEndTime); @@ -700,8 +809,11 @@ class AppointmentHelper { return boolValue1.compareTo(boolValue2); } - static AppointmentView _getAppointmentView(CalendarAppointment appointment, - List appointmentCollection, int? resourceIndex) { + static AppointmentView _getAppointmentView( + CalendarAppointment appointment, + List appointmentCollection, + int? resourceIndex, + ) { AppointmentView? appointmentRenderer; for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView view = appointmentCollection[i]; @@ -728,56 +840,71 @@ class AppointmentHelper { /// Update the appointment view collection position and its max position /// details. static void setAppointmentPositionAndMaxPosition( - List appointmentCollection, - SfCalendar calendar, - CalendarView view, - List visibleAppointments, - bool isAllDay, - [int? resourceIndex]) { + List appointmentCollection, + SfCalendar calendar, + CalendarView view, + List visibleAppointments, + bool isAllDay, [ + int? resourceIndex, + ]) { final bool isTimeline = CalendarViewHelper.isTimelineView(view); - final List normalAppointments = visibleAppointments - .where((CalendarAppointment app) => - _iterateAppointment(app, isTimeline, isAllDay)) - .toList(); + final List normalAppointments = + visibleAppointments + .where( + (CalendarAppointment app) => + _iterateAppointment(app, isTimeline, isAllDay), + ) + .toList(); normalAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); if (!isTimeline) { normalAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - _orderAppointmentsDescending(app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + _orderAppointmentsDescending(app1.isSpanned, app2.isSpanned), + ); normalAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - _orderAppointmentsDescending(app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + _orderAppointmentsDescending(app1.isAllDay, app2.isAllDay), + ); } else { normalAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - orderAppointmentsAscending(app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + orderAppointmentsAscending(app1.isAllDay, app2.isAllDay), + ); normalAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - orderAppointmentsAscending(app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + orderAppointmentsAscending(app1.isSpanned, app2.isSpanned), + ); } final Map> dict = >{}; final List processedViews = []; int maxColsCount = 1; - final int timeIntervalMinutes = - CalendarViewHelper.getTimeInterval(calendar.timeSlotViewSettings); + final int timeIntervalMinutes = CalendarViewHelper.getTimeInterval( + calendar.timeSlotViewSettings, + ); for (int count = 0; count < normalAppointments.length; count++) { final CalendarAppointment currentAppointment = normalAppointments[count]; if ((view == CalendarView.workWeek || view == CalendarView.timelineWorkWeek) && - calendar.timeSlotViewSettings.nonWorkingDays - .contains(currentAppointment.actualStartTime.weekday) && - calendar.timeSlotViewSettings.nonWorkingDays - .contains(currentAppointment.actualEndTime.weekday)) { + calendar.timeSlotViewSettings.nonWorkingDays.contains( + currentAppointment.actualStartTime.weekday, + ) && + calendar.timeSlotViewSettings.nonWorkingDays.contains( + currentAppointment.actualEndTime.weekday, + )) { continue; } List? intersectingApps; final AppointmentView currentAppView = _getAppointmentView( - currentAppointment, appointmentCollection, resourceIndex); + currentAppointment, + appointmentCollection, + resourceIndex, + ); for (int position = 0; position < maxColsCount; position++) { bool isIntersecting = false; @@ -788,12 +915,13 @@ class AppointmentHelper { } if (_isIntersectingAppointmentInDayView( - calendar, - view, - currentAppointment, - previousApp, - previousApp.appointment!, - timeIntervalMinutes)) { + calendar, + view, + currentAppointment, + previousApp, + previousApp.appointment!, + timeIntervalMinutes, + )) { isIntersecting = true; if (intersectingApps == null) { @@ -828,13 +956,18 @@ class AppointmentHelper { intersectingApps = []; dict[dict.keys.length] = intersectingApps; } else if (intersectingApps.isNotEmpty) { - position = intersectingApps - .reduce((AppointmentView currentAppview, - AppointmentView nextAppview) => - currentAppview.maxPositions > nextAppview.maxPositions - ? currentAppview - : nextAppview) - .maxPositions; + position = + intersectingApps + .reduce( + ( + AppointmentView currentAppview, + AppointmentView nextAppview, + ) => + currentAppview.maxPositions > nextAppview.maxPositions + ? currentAppview + : nextAppview, + ) + .maxPositions; } intersectingApps.add(currentAppView); @@ -852,13 +985,18 @@ class AppointmentHelper { intersectingApps = []; dict[dict.keys.length] = intersectingApps; } else if (intersectingApps.isNotEmpty) { - maxPosition = intersectingApps - .reduce((AppointmentView currentAppview, - AppointmentView nextAppview) => - currentAppview.maxPositions > nextAppview.maxPositions - ? currentAppview - : nextAppview) - .maxPositions; + maxPosition = + intersectingApps + .reduce( + ( + AppointmentView currentAppview, + AppointmentView nextAppview, + ) => + currentAppview.maxPositions > nextAppview.maxPositions + ? currentAppview + : nextAppview, + ) + .maxPositions; if (currentAppView.position == maxPosition) { maxPosition++; @@ -885,7 +1023,10 @@ class AppointmentHelper { /// value. If calendar timezone value as null or empty then it convert /// it to local timezone value. static DateTime convertTimeToAppointmentTimeZone( - DateTime date, String? appTimeZoneId, String? calendarTimeZoneId) { + DateTime date, + String? appTimeZoneId, + String? calendarTimeZoneId, + ) { if (((appTimeZoneId == null || appTimeZoneId == '') && (calendarTimeZoneId == null || calendarTimeZoneId == '')) || calendarTimeZoneId == appTimeZoneId) { @@ -901,24 +1042,26 @@ class AppointmentHelper { //// E.g., Nov 3- 9.00 AM IST equal to Nov 2- 10.30 PM EST //// So convert the Appointment time zone date to current time zone date. convertedDate = DateTime( - date.year - (convertedDate.year - date.year), - date.month - (convertedDate.month - date.month), - date.day - (convertedDate.day - date.day), - date.hour - (convertedDate.hour - date.hour), - date.minute - (convertedDate.minute - date.minute), - date.second); + date.year - (convertedDate.year - date.year), + date.month - (convertedDate.month - date.month), + date.day - (convertedDate.day - date.day), + date.hour - (convertedDate.hour - date.hour), + date.minute - (convertedDate.minute - date.minute), + date.second, + ); } else { /// Create the specified date on appointment time zone. /// Eg., Appointment Time zone as Eastern time zone(-5.00) and it /// date is Nov 1 10AM, create the date using location. final DateTime timeZoneDate = TZDateTime( - _timeZoneInfoToOlsonTimeZone(appTimeZoneId), - date.year, - date.month, - date.day, - date.hour, - date.minute, - date.second); + _timeZoneInfoToOlsonTimeZone(appTimeZoneId), + date.year, + date.month, + date.day, + date.hour, + date.minute, + date.second, + ); final Duration offset = DateTime.now().timeZoneOffset; @@ -932,12 +1075,13 @@ class AppointmentHelper { /// We does not use from method in TZDateTime because we does not /// know the local time zone location. convertedDate = DateTime( - localTimeZoneDate.year, - localTimeZoneDate.month, - localTimeZoneDate.day, - localTimeZoneDate.hour, - localTimeZoneDate.minute, - localTimeZoneDate.second); + localTimeZoneDate.year, + localTimeZoneDate.month, + localTimeZoneDate.day, + localTimeZoneDate.hour, + localTimeZoneDate.minute, + localTimeZoneDate.second, + ); } } @@ -945,36 +1089,38 @@ class AppointmentHelper { DateTime actualConvertedDate; //// Convert the converted date with calendar time zone if (calendarTimeZoneId == 'Dateline Standard Time') { - actualConvertedDate = - convertedDate.toUtc().subtract(const Duration(hours: 12)); + actualConvertedDate = convertedDate.toUtc().subtract( + const Duration(hours: 12), + ); //// Above mentioned actual converted date hold the date value which is equal to converted date, but the time zone value changed. //// So convert the schedule time zone date to current time zone date for rendering the appointment. return DateTime( - convertedDate.year + - (actualConvertedDate.year - convertedDate.year), - convertedDate.month + - (actualConvertedDate.month - convertedDate.month), - convertedDate.day + (actualConvertedDate.day - convertedDate.day), - convertedDate.hour + - (actualConvertedDate.hour - convertedDate.hour), - convertedDate.minute + - (actualConvertedDate.minute - convertedDate.minute), - convertedDate.second); + convertedDate.year + (actualConvertedDate.year - convertedDate.year), + convertedDate.month + + (actualConvertedDate.month - convertedDate.month), + convertedDate.day + (actualConvertedDate.day - convertedDate.day), + convertedDate.hour + (actualConvertedDate.hour - convertedDate.hour), + convertedDate.minute + + (actualConvertedDate.minute - convertedDate.minute), + convertedDate.second, + ); } else { - final Location location = - _timeZoneInfoToOlsonTimeZone(calendarTimeZoneId); + final Location location = _timeZoneInfoToOlsonTimeZone( + calendarTimeZoneId, + ); /// Convert the local time to calendar time zone. actualConvertedDate = TZDateTime.from(convertedDate, location); /// Return the calendar time zone value with local time zone. return DateTime( - actualConvertedDate.year, - actualConvertedDate.month, - actualConvertedDate.day, - actualConvertedDate.hour, - actualConvertedDate.minute, - actualConvertedDate.second); + actualConvertedDate.year, + actualConvertedDate.month, + actualConvertedDate.day, + actualConvertedDate.hour, + actualConvertedDate.minute, + actualConvertedDate.second, + ); } } @@ -984,12 +1130,13 @@ class AppointmentHelper { /// Return the visible appointment collection based on visible start and /// end date. static List getVisibleAppointments( - DateTime visibleStartDate, - DateTime visibleEndDate, - List appointments, - String? calendarTimeZone, - bool isTimelineView, - {bool canCreateNewAppointment = true}) { + DateTime visibleStartDate, + DateTime visibleEndDate, + List appointments, + String? calendarTimeZone, + bool isTimelineView, { + bool canCreateNewAppointment = true, + }) { final List appointmentColl = []; final DateTime startDate = convertToStartTime(visibleStartDate); final DateTime endDate = convertToEndTime(visibleEndDate); @@ -998,13 +1145,15 @@ class AppointmentHelper { for (int j = 0; j < count; j++) { final CalendarAppointment calendarAppointment = appointments[j]; calendarAppointment.actualStartTime = convertTimeToAppointmentTimeZone( - calendarAppointment.startTime, - calendarAppointment.startTimeZone, - calendarTimeZone); + calendarAppointment.startTime, + calendarAppointment.startTimeZone, + calendarTimeZone, + ); calendarAppointment.actualEndTime = convertTimeToAppointmentTimeZone( - calendarAppointment.endTime, - calendarAppointment.endTimeZone, - calendarTimeZone); + calendarAppointment.endTime, + calendarAppointment.endTimeZone, + calendarTimeZone, + ); final List tempAppointments = []; @@ -1018,8 +1167,13 @@ class AppointmentHelper { calendarAppointment.exactEndTime = calendarAppointment.actualEndTime; if (calendarAppointment.recurrenceRule != null && calendarAppointment.recurrenceRule != '') { - _getRecurrenceAppointments(calendarAppointment, tempAppointments, - startDate, endDate, calendarTimeZone); + _getRecurrenceAppointments( + calendarAppointment, + tempAppointments, + startDate, + endDate, + calendarTimeZone, + ); } else { tempAppointments.add(calendarAppointment); } @@ -1028,7 +1182,10 @@ class AppointmentHelper { for (int i = 0; i < appointmentLength; i++) { final CalendarAppointment appointment = tempAppointments[i]; if (isAppointmentWithinVisibleDateRange( - appointment, startDate, endDate)) { + appointment, + startDate, + endDate, + )) { /// can create new appointment boolean is used to skip the new /// appointment creation while the appointment start and end date as /// different and appointment duration is not more than 24 hours. @@ -1043,8 +1200,9 @@ class AppointmentHelper { appointment.exactEndTime.month) && appointment.exactStartTime.isBefore(appointment.exactEndTime) && getDifference( - appointment.exactStartTime, appointment.exactEndTime) - .inDays == + appointment.exactStartTime, + appointment.exactEndTime, + ).inDays == 0 && (appointment.exactEndTime.hour != 0 || appointment.exactEndTime.minute != 0) && @@ -1054,34 +1212,45 @@ class AppointmentHelper { final CalendarAppointment spannedAppointment = _copy(appointment); if (i == 0) { spannedAppointment.actualEndTime = DateTime( - appointment.exactStartTime.year, - appointment.exactStartTime.month, - appointment.exactStartTime.day, - 23, - 59, - 59); + appointment.exactStartTime.year, + appointment.exactStartTime.month, + appointment.exactStartTime.day, + 23, + 59, + 59, + ); } else { spannedAppointment.actualStartTime = DateTime( - appointment.exactEndTime.year, - appointment.exactEndTime.month, - appointment.exactEndTime.day); + appointment.exactEndTime.year, + appointment.exactEndTime.month, + appointment.exactEndTime.day, + ); } - spannedAppointment.startTime = spannedAppointment.isAllDay - ? appointment.actualStartTime - : convertTimeToAppointmentTimeZone( - appointment.actualStartTime, - calendarTimeZone, - appointment.startTimeZone); - spannedAppointment.endTime = spannedAppointment.isAllDay - ? appointment.actualEndTime - : convertTimeToAppointmentTimeZone(appointment.actualEndTime, - calendarTimeZone, appointment.endTimeZone); + spannedAppointment.startTime = + spannedAppointment.isAllDay + ? appointment.actualStartTime + : convertTimeToAppointmentTimeZone( + appointment.actualStartTime, + calendarTimeZone, + appointment.startTimeZone, + ); + spannedAppointment.endTime = + spannedAppointment.isAllDay + ? appointment.actualEndTime + : convertTimeToAppointmentTimeZone( + appointment.actualEndTime, + calendarTimeZone, + appointment.endTimeZone, + ); // Adding Spanned Appointment only when the Appointment range // within the VisibleDate if (isAppointmentWithinVisibleDateRange( - spannedAppointment, startDate, endDate)) { + spannedAppointment, + startDate, + endDate, + )) { appointmentColl.add(spannedAppointment); } } @@ -1096,128 +1265,206 @@ class AppointmentHelper { //// Check the spanned appointment with in current visible dates. example visible date 21 to 27 and //// the appointment start and end date as 23 and 25. if (_isAppointmentInVisibleDateRange( - appointment, startDate, endDate)) { + appointment, + startDate, + endDate, + )) { appointment.isSpanned = _isSpanned(appointment); appointmentColl.add(appointment); } else if (_isAppointmentDateWithinVisibleDateRange( - appointment.actualStartTime, startDate, endDate)) { + appointment.actualStartTime, + startDate, + endDate, + )) { //// Check the spanned appointment start date with in current visible dates. //// example visible date 21 to 27 and the appointment start and end date as 23 and 28. for (int i = 0; i < 2; i++) { - final CalendarAppointment spannedAppointment = - _copy(appointment); + final CalendarAppointment spannedAppointment = _copy( + appointment, + ); if (i == 0) { spannedAppointment.actualEndTime = DateTime( - endDate.year, endDate.month, endDate.day, 23, 59, 59); + endDate.year, + endDate.month, + endDate.day, + 23, + 59, + 59, + ); } else { - spannedAppointment.actualStartTime = - DateTime(endDate.year, endDate.month, endDate.day); + spannedAppointment.actualStartTime = DateTime( + endDate.year, + endDate.month, + endDate.day, + ); } - spannedAppointment.startTime = spannedAppointment.isAllDay - ? appointment.actualStartTime - : convertTimeToAppointmentTimeZone( - appointment.actualStartTime, - calendarTimeZone, - appointment.startTimeZone); - spannedAppointment.endTime = spannedAppointment.isAllDay - ? appointment.actualEndTime - : convertTimeToAppointmentTimeZone( - appointment.actualEndTime, - calendarTimeZone, - appointment.endTimeZone); + spannedAppointment.startTime = + spannedAppointment.isAllDay + ? appointment.actualStartTime + : convertTimeToAppointmentTimeZone( + appointment.actualStartTime, + calendarTimeZone, + appointment.startTimeZone, + ); + spannedAppointment.endTime = + spannedAppointment.isAllDay + ? appointment.actualEndTime + : convertTimeToAppointmentTimeZone( + appointment.actualEndTime, + calendarTimeZone, + appointment.endTimeZone, + ); // Adding Spanned Appointment only when the Appointment range // within the VisibleDate if (_isAppointmentInVisibleDateRange( - spannedAppointment, startDate, endDate)) { + spannedAppointment, + startDate, + endDate, + )) { spannedAppointment.isSpanned = _isSpanned(spannedAppointment); appointmentColl.add(spannedAppointment); } } } else if (_isAppointmentDateWithinVisibleDateRange( - appointment.actualEndTime, startDate, endDate)) { + appointment.actualEndTime, + startDate, + endDate, + )) { //// Check the spanned appointment end date with in current visible dates. example visible date 21 to 27 and //// the appointment start and end date as 18 and 24. for (int i = 0; i < 2; i++) { - final CalendarAppointment spannedAppointment = - _copy(appointment); + final CalendarAppointment spannedAppointment = _copy( + appointment, + ); if (i == 0) { spannedAppointment.actualStartTime = appointment.actualStartTime; - final DateTime date = - DateTimeHelper.getDateTimeValue(addDays(startDate, -1)); - spannedAppointment.actualEndTime = - DateTime(date.year, date.month, date.day, 23, 59, 59); + final DateTime date = DateTimeHelper.getDateTimeValue( + addDays(startDate, -1), + ); + spannedAppointment.actualEndTime = DateTime( + date.year, + date.month, + date.day, + 23, + 59, + 59, + ); } else { - spannedAppointment.actualStartTime = - DateTime(startDate.year, startDate.month, startDate.day); + spannedAppointment.actualStartTime = DateTime( + startDate.year, + startDate.month, + startDate.day, + ); } - spannedAppointment.startTime = spannedAppointment.isAllDay - ? appointment.actualStartTime - : convertTimeToAppointmentTimeZone( - appointment.actualStartTime, - calendarTimeZone, - appointment.startTimeZone); - spannedAppointment.endTime = spannedAppointment.isAllDay - ? appointment.actualEndTime - : convertTimeToAppointmentTimeZone( - appointment.actualEndTime, - calendarTimeZone, - appointment.endTimeZone); + spannedAppointment.startTime = + spannedAppointment.isAllDay + ? appointment.actualStartTime + : convertTimeToAppointmentTimeZone( + appointment.actualStartTime, + calendarTimeZone, + appointment.startTimeZone, + ); + spannedAppointment.endTime = + spannedAppointment.isAllDay + ? appointment.actualEndTime + : convertTimeToAppointmentTimeZone( + appointment.actualEndTime, + calendarTimeZone, + appointment.endTimeZone, + ); // Adding Spanned Appointment only when the Appointment range // within the VisibleDate if (_isAppointmentInVisibleDateRange( - spannedAppointment, startDate, endDate)) { + spannedAppointment, + startDate, + endDate, + )) { spannedAppointment.isSpanned = _isSpanned(spannedAppointment); appointmentColl.add(spannedAppointment); } } } else if (!_isAppointmentDateWithinVisibleDateRange( - appointment.actualEndTime, startDate, endDate) && + appointment.actualEndTime, + startDate, + endDate, + ) && !_isAppointmentDateWithinVisibleDateRange( - appointment.actualStartTime, startDate, endDate)) { + appointment.actualStartTime, + startDate, + endDate, + )) { //// Check the spanned appointment start and end date not in current visible dates. example visible date 21 to 27 and //// the appointment start and end date as 18 and 28. for (int i = 0; i < 3; i++) { - final CalendarAppointment spannedAppointment = - _copy(appointment); + final CalendarAppointment spannedAppointment = _copy( + appointment, + ); if (i == 0) { - final DateTime date = - DateTimeHelper.getDateTimeValue(addDays(startDate, -1)); - spannedAppointment.actualEndTime = - DateTime(date.year, date.month, date.day, 23, 59, 59); + final DateTime date = DateTimeHelper.getDateTimeValue( + addDays(startDate, -1), + ); + spannedAppointment.actualEndTime = DateTime( + date.year, + date.month, + date.day, + 23, + 59, + 59, + ); } else if (i == 1) { - spannedAppointment.actualStartTime = - DateTime(startDate.year, startDate.month, startDate.day); + spannedAppointment.actualStartTime = DateTime( + startDate.year, + startDate.month, + startDate.day, + ); spannedAppointment.actualEndTime = DateTime( - endDate.year, endDate.month, endDate.day, 23, 59, 59); + endDate.year, + endDate.month, + endDate.day, + 23, + 59, + 59, + ); } else { - final DateTime date = - DateTimeHelper.getDateTimeValue(addDays(endDate, 1)); - spannedAppointment.actualStartTime = - DateTime(date.year, date.month, date.day); + final DateTime date = DateTimeHelper.getDateTimeValue( + addDays(endDate, 1), + ); + spannedAppointment.actualStartTime = DateTime( + date.year, + date.month, + date.day, + ); } - spannedAppointment.startTime = spannedAppointment.isAllDay - ? appointment.actualStartTime - : convertTimeToAppointmentTimeZone( - appointment.actualStartTime, - calendarTimeZone, - appointment.startTimeZone); - spannedAppointment.endTime = spannedAppointment.isAllDay - ? appointment.actualEndTime - : convertTimeToAppointmentTimeZone( - appointment.actualEndTime, - calendarTimeZone, - appointment.endTimeZone); + spannedAppointment.startTime = + spannedAppointment.isAllDay + ? appointment.actualStartTime + : convertTimeToAppointmentTimeZone( + appointment.actualStartTime, + calendarTimeZone, + appointment.startTimeZone, + ); + spannedAppointment.endTime = + spannedAppointment.isAllDay + ? appointment.actualEndTime + : convertTimeToAppointmentTimeZone( + appointment.actualEndTime, + calendarTimeZone, + appointment.endTimeZone, + ); // Adding Spanned Appointment only when the Appointment range // within the VisibleDate if (_isAppointmentInVisibleDateRange( - spannedAppointment, startDate, endDate)) { + spannedAppointment, + startDate, + endDate, + )) { spannedAppointment.isSpanned = _isSpanned(spannedAppointment); appointmentColl.add(spannedAppointment); } @@ -1237,32 +1484,46 @@ class AppointmentHelper { } static CalendarAppointment _cloneRecurrenceAppointment( - CalendarAppointment appointment, - DateTime recursiveDate, - String? calendarTimeZone) { + CalendarAppointment appointment, + DateTime recursiveDate, + String? calendarTimeZone, + ) { final CalendarAppointment occurrenceAppointment = _copy(appointment); occurrenceAppointment.actualStartTime = recursiveDate; - occurrenceAppointment.startTime = occurrenceAppointment.isAllDay - ? occurrenceAppointment.actualStartTime - : convertTimeToAppointmentTimeZone( - occurrenceAppointment.actualStartTime, - calendarTimeZone, - occurrenceAppointment.startTimeZone); + occurrenceAppointment.startTime = + occurrenceAppointment.isAllDay + ? occurrenceAppointment.actualStartTime + : convertTimeToAppointmentTimeZone( + occurrenceAppointment.actualStartTime, + calendarTimeZone, + occurrenceAppointment.startTimeZone, + ); final int minutes = - getDifference(appointment.actualStartTime, appointment.actualEndTime) - .inMinutes; + getDifference( + appointment.actualStartTime, + appointment.actualEndTime, + ).inMinutes; occurrenceAppointment.actualEndTime = DateTimeHelper.getDateTimeValue( - addDuration( - occurrenceAppointment.actualStartTime, Duration(minutes: minutes))); - occurrenceAppointment.endTime = occurrenceAppointment.isAllDay - ? occurrenceAppointment.actualEndTime - : convertTimeToAppointmentTimeZone(occurrenceAppointment.actualEndTime, - calendarTimeZone, occurrenceAppointment.endTimeZone); - occurrenceAppointment.isSpanned = _isSpanned(occurrenceAppointment) && - getDifference(occurrenceAppointment.startTime, - occurrenceAppointment.endTime) - .inDays > + addDuration( + occurrenceAppointment.actualStartTime, + Duration(minutes: minutes), + ), + ); + occurrenceAppointment.endTime = + occurrenceAppointment.isAllDay + ? occurrenceAppointment.actualEndTime + : convertTimeToAppointmentTimeZone( + occurrenceAppointment.actualEndTime, + calendarTimeZone, + occurrenceAppointment.endTimeZone, + ); + occurrenceAppointment.isSpanned = + _isSpanned(occurrenceAppointment) && + getDifference( + occurrenceAppointment.startTime, + occurrenceAppointment.endTime, + ).inDays > 0; occurrenceAppointment.exactStartTime = occurrenceAppointment.actualStartTime; @@ -1274,8 +1535,10 @@ class AppointmentHelper { /// Generate the calendar appointment collection from custom appointment /// collection. static List generateCalendarAppointments( - CalendarDataSource? calendarData, String? calendarTimeZone, - [List? appointments]) { + CalendarDataSource? calendarData, + String? calendarTimeZone, [ + List? appointments, + ]) { final List calendarAppointmentCollection = []; if (calendarData == null) { @@ -1297,29 +1560,42 @@ class AppointmentHelper { final DateTime appStartTime = item.startTime; final DateTime appEndTime = item.endTime; item.data = item; - item.actualStartTime = !item.isAllDay - ? convertTimeToAppointmentTimeZone( - item.startTime, item.startTimeZone, calendarTimeZone) - : item.startTime; - item.actualEndTime = !item.isAllDay - ? convertTimeToAppointmentTimeZone( - item.endTime, item.endTimeZone, calendarTimeZone) - : item.endTime; + item.actualStartTime = + !item.isAllDay + ? convertTimeToAppointmentTimeZone( + item.startTime, + item.startTimeZone, + calendarTimeZone, + ) + : item.startTime; + item.actualEndTime = + !item.isAllDay + ? convertTimeToAppointmentTimeZone( + item.endTime, + item.endTimeZone, + calendarTimeZone, + ) + : item.endTime; _updateTimeForInvalidEndTime(item, calendarTimeZone); calendarAppointmentCollection.add(item); - item.isSpanned = _isSpanned(item) && + item.isSpanned = + _isSpanned(item) && getDifference(appStartTime, appEndTime).inDays > 0; } } else { for (int i = 0; i < dataSource.length; i++) { final dynamic item = dataSource[i]; - final CalendarAppointment app = - _createAppointment(item, calendarData, calendarTimeZone); + final CalendarAppointment app = _createAppointment( + item, + calendarData, + calendarTimeZone, + ); final DateTime appStartTime = app.startTime; final DateTime appEndTime = app.endTime; - app.isSpanned = _isSpanned(app) && + app.isSpanned = + _isSpanned(app) && getDifference(appStartTime, appEndTime).inDays > 0; calendarAppointmentCollection.add(app); } @@ -1328,79 +1604,101 @@ class AppointmentHelper { return calendarAppointmentCollection; } - static CalendarAppointment _createAppointment(Object appointmentObject, - CalendarDataSource calendarData, String? calendarTimeZone) { + static CalendarAppointment _createAppointment( + Object appointmentObject, + CalendarDataSource calendarData, + String? calendarTimeZone, + ) { CalendarAppointment app; if (appointmentObject is Appointment) { app = CalendarAppointment( - startTime: appointmentObject.startTime, - endTime: appointmentObject.endTime, - subject: appointmentObject.subject, - isAllDay: appointmentObject.isAllDay, - color: appointmentObject.color, - notes: appointmentObject.notes, - location: appointmentObject.location, - startTimeZone: appointmentObject.startTimeZone, - endTimeZone: appointmentObject.endTimeZone, - recurrenceRule: appointmentObject.recurrenceRule, - recurrenceExceptionDates: appointmentObject.recurrenceExceptionDates, - resourceIds: appointmentObject.resourceIds, - recurrenceId: appointmentObject.recurrenceId, - id: appointmentObject.id); + startTime: appointmentObject.startTime, + endTime: appointmentObject.endTime, + subject: appointmentObject.subject, + isAllDay: appointmentObject.isAllDay, + color: appointmentObject.color, + notes: appointmentObject.notes, + location: appointmentObject.location, + startTimeZone: appointmentObject.startTimeZone, + endTimeZone: appointmentObject.endTimeZone, + recurrenceRule: appointmentObject.recurrenceRule, + recurrenceExceptionDates: appointmentObject.recurrenceExceptionDates, + resourceIds: appointmentObject.resourceIds, + recurrenceId: appointmentObject.recurrenceId, + id: appointmentObject.id, + ); } else { final int index = calendarData.appointments!.indexOf(appointmentObject); app = CalendarAppointment( - startTime: calendarData.getStartTime(index), - endTime: calendarData.getEndTime(index), - subject: calendarData.getSubject(index), - isAllDay: calendarData.isAllDay(index), - color: calendarData.getColor(index), - notes: calendarData.getNotes(index), - location: calendarData.getLocation(index), - startTimeZone: calendarData.getStartTimeZone(index), - endTimeZone: calendarData.getEndTimeZone(index), - recurrenceRule: calendarData.getRecurrenceRule(index), - recurrenceExceptionDates: - calendarData.getRecurrenceExceptionDates(index), - resourceIds: calendarData.getResourceIds(index), - recurrenceId: calendarData.getRecurrenceId(index), - id: calendarData.getId(index)); + startTime: calendarData.getStartTime(index), + endTime: calendarData.getEndTime(index), + subject: calendarData.getSubject(index), + isAllDay: calendarData.isAllDay(index), + color: calendarData.getColor(index), + notes: calendarData.getNotes(index), + location: calendarData.getLocation(index), + startTimeZone: calendarData.getStartTimeZone(index), + endTimeZone: calendarData.getEndTimeZone(index), + recurrenceRule: calendarData.getRecurrenceRule(index), + recurrenceExceptionDates: calendarData.getRecurrenceExceptionDates( + index, + ), + resourceIds: calendarData.getResourceIds(index), + recurrenceId: calendarData.getRecurrenceId(index), + id: calendarData.getId(index), + ); } app.data = appointmentObject; - app.actualStartTime = !app.isAllDay - ? convertTimeToAppointmentTimeZone( - app.startTime, app.startTimeZone, calendarTimeZone) - : app.startTime; - app.actualEndTime = !app.isAllDay - ? convertTimeToAppointmentTimeZone( - app.endTime, app.endTimeZone, calendarTimeZone) - : app.endTime; + app.actualStartTime = + !app.isAllDay + ? convertTimeToAppointmentTimeZone( + app.startTime, + app.startTimeZone, + calendarTimeZone, + ) + : app.startTime; + app.actualEndTime = + !app.isAllDay + ? convertTimeToAppointmentTimeZone( + app.endTime, + app.endTimeZone, + calendarTimeZone, + ) + : app.endTime; _updateTimeForInvalidEndTime(app, calendarTimeZone); return app; } static void _updateTimeForInvalidEndTime( - CalendarAppointment appointment, String? scheduleTimeZone) { + CalendarAppointment appointment, + String? scheduleTimeZone, + ) { if (appointment.actualEndTime.isBefore(appointment.actualStartTime) && !appointment.isAllDay) { appointment.endTime = convertTimeToAppointmentTimeZone( - addDuration(appointment.actualStartTime, const Duration(minutes: 30)), - scheduleTimeZone, - appointment.endTimeZone); - appointment.actualEndTime = !appointment.isAllDay - ? convertTimeToAppointmentTimeZone( - appointment.endTime, appointment.endTimeZone, scheduleTimeZone) - : appointment.endTime; + addDuration(appointment.actualStartTime, const Duration(minutes: 30)), + scheduleTimeZone, + appointment.endTimeZone, + ); + appointment.actualEndTime = + !appointment.isAllDay + ? convertTimeToAppointmentTimeZone( + appointment.endTime, + appointment.endTimeZone, + scheduleTimeZone, + ) + : appointment.endTime; } } static void _getRecurrenceAppointments( - CalendarAppointment appointment, - List appointments, - DateTime visibleStartDate, - DateTime visibleEndDate, - String? scheduleTimeZone) { + CalendarAppointment appointment, + List appointments, + DateTime visibleStartDate, + DateTime visibleEndDate, + String? scheduleTimeZone, + ) { final DateTime appStartTime = appointment.actualStartTime; if (appStartTime.isAfter(visibleEndDate)) { return; @@ -1416,11 +1714,15 @@ class AppointmentHelper { final List recursiveDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - rule, appointment.actualStartTime, - recurrenceDuration: getDifference( - appointment.exactStartTime, appointment.exactEndTime), - specificStartDate: visibleStartDate, - specificEndDate: visibleEndDate); + rule, + appointment.actualStartTime, + recurrenceDuration: getDifference( + appointment.exactStartTime, + appointment.exactEndTime, + ), + specificStartDate: visibleStartDate, + specificEndDate: visibleEndDate, + ); List recDates = []; if (recursiveDates.isNotEmpty) { @@ -1436,8 +1738,10 @@ class AppointmentHelper { } recDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - countRule, appointment.actualStartTime, - specificStartDate: appointment.startTime); + countRule, + appointment.actualStartTime, + specificStartDate: appointment.startTime, + ); } for (int j = 0; j < recursiveDates.length; j++) { @@ -1446,7 +1750,10 @@ class AppointmentHelper { bool isDateContains = false; for (int i = 0; i < appointment.recurrenceExceptionDates!.length; i++) { final DateTime date = convertTimeToAppointmentTimeZone( - appointment.recurrenceExceptionDates![i], '', scheduleTimeZone); + appointment.recurrenceExceptionDates![i], + '', + scheduleTimeZone, + ); if (date.year == recursiveDate.year && date.month == recursiveDate.month && date.day == recursiveDate.day) { @@ -1461,16 +1768,20 @@ class AppointmentHelper { final CalendarAppointment occurrenceAppointment = _cloneRecurrenceAppointment( - appointment, recursiveDate, scheduleTimeZone); + appointment, + recursiveDate, + scheduleTimeZone, + ); /// Here we used isOccurrenceAppointment keyword to identify the /// occurrence appointment When we clone the pattern appointment for /// occurrence appointment we have append the string in the notes and /// here we identify based on the string and removed the appended string. - occurrenceAppointment.notes = recDates.isNotEmpty && - isSameDate(occurrenceAppointment.startTime, recDates[0]) - ? appointment.notes - : appointment.notes == null + occurrenceAppointment.notes = + recDates.isNotEmpty && + isSameDate(occurrenceAppointment.startTime, recDates[0]) + ? appointment.notes + : appointment.notes == null ? 'isOccurrenceAppointment' : '${appointment.notes!}isOccurrenceAppointment'; appointments.add(occurrenceAppointment); diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/calendar_datasource.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/calendar_datasource.dart index 1ddf38507..8c746bce8 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/calendar_datasource.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/calendar_datasource.dart @@ -281,8 +281,10 @@ abstract class CalendarDataSource /// } /// ``` List getVisibleAppointments( - DateTime startDate, String calendarTimeZone, - [DateTime? endDate]) { + DateTime startDate, + String calendarTimeZone, [ + DateTime? endDate, + ]) { endDate ??= startDate; /// Converts the given appointment type to calendar appointment, to handle @@ -293,14 +295,20 @@ abstract class CalendarDataSource AppointmentHelper.generateCalendarAppointments(this, calendarTimeZone); calendarAppointments = AppointmentHelper.getVisibleAppointments( - startDate, endDate, calendarAppointments, calendarTimeZone, false, - canCreateNewAppointment: false); + startDate, + endDate, + calendarAppointments, + calendarTimeZone, + false, + canCreateNewAppointment: false, + ); final List visibleAppointments = []; for (int i = 0; i < calendarAppointments.length; i++) { - visibleAppointments - .add(calendarAppointments[i].convertToCalendarAppointment()); + visibleAppointments.add( + calendarAppointments[i].convertToCalendarAppointment(), + ); } return visibleAppointments; @@ -394,7 +402,10 @@ abstract class CalendarDataSource /// /// ``` Appointment? getOccurrenceAppointment( - Object? patternAppointment, DateTime date, String calendarTimeZone) { + Object? patternAppointment, + DateTime date, + String calendarTimeZone, + ) { if (patternAppointment == null) { return null; } @@ -402,7 +413,10 @@ abstract class CalendarDataSource final List patternAppointmentColl = [patternAppointment]; final List patternAppointments = AppointmentHelper.generateCalendarAppointments( - this, calendarTimeZone, patternAppointmentColl); + this, + calendarTimeZone, + patternAppointmentColl, + ); final CalendarAppointment patternCalendarAppointment = patternAppointments[0]; @@ -410,10 +424,14 @@ abstract class CalendarDataSource patternCalendarAppointment.recurrenceRule!.isEmpty) { return null; } else if (CalendarViewHelper.isDateInDateCollection( - patternCalendarAppointment.recurrenceExceptionDates, date)) { + patternCalendarAppointment.recurrenceExceptionDates, + date, + )) { final List dataSourceAppointments = AppointmentHelper.generateCalendarAppointments( - this, calendarTimeZone); + this, + calendarTimeZone, + ); for (int i = 0; i < dataSourceAppointments.length; i++) { final CalendarAppointment dataSourceAppointment = dataSourceAppointments[i]; @@ -426,8 +444,13 @@ abstract class CalendarDataSource } else { final List occurrenceAppointments = AppointmentHelper.getVisibleAppointments( - date, date, patternAppointments, calendarTimeZone, false, - canCreateNewAppointment: false); + date, + date, + patternAppointments, + calendarTimeZone, + false, + canCreateNewAppointment: false, + ); if (occurrenceAppointments.isEmpty) { return null; @@ -519,16 +542,21 @@ abstract class CalendarDataSource /// /// ``` Object? getPatternAppointment( - Object? occurrenceAppointment, String calendarTimeZone) { + Object? occurrenceAppointment, + String calendarTimeZone, + ) { if (occurrenceAppointment == null) { return null; } final List occurrenceAppointmentColl = [ - occurrenceAppointment + occurrenceAppointment, ]; final List occurrenceAppointments = AppointmentHelper.generateCalendarAppointments( - this, calendarTimeZone, occurrenceAppointmentColl); + this, + calendarTimeZone, + occurrenceAppointmentColl, + ); final CalendarAppointment occurrenceCalendarAppointment = occurrenceAppointments[0]; if ((occurrenceCalendarAppointment.recurrenceRule == null || @@ -538,7 +566,10 @@ abstract class CalendarDataSource } final List dataSourceAppointments = AppointmentHelper.generateCalendarAppointments( - this, calendarTimeZone, appointments); + this, + calendarTimeZone, + appointments, + ); for (int i = 0; i < dataSourceAppointments.length; i++) { final CalendarAppointment dataSourceAppointment = @@ -1033,10 +1064,16 @@ abstract class CalendarDataSource @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(IterableDiagnostics(appointments) - .toDiagnosticsNode(name: 'appointments')); - properties.add(IterableDiagnostics(resources) - .toDiagnosticsNode(name: 'resources')); + properties.add( + IterableDiagnostics( + appointments, + ).toDiagnosticsNode(name: 'appointments'), + ); + properties.add( + IterableDiagnostics( + resources, + ).toDiagnosticsNode(name: 'resources'), + ); } } @@ -1046,8 +1083,8 @@ abstract class CalendarDataSource /// See also: /// [CalendarDataSourceAction], the actions which can be performed using the /// calendar. -typedef CalendarDataSourceCallback = void Function( - CalendarDataSourceAction, List); +typedef CalendarDataSourceCallback = + void Function(CalendarDataSourceAction, List); /// Notifier used to notify the action performed in the [CalendarDataSource] class CalendarDataSourceChangeNotifier with Diagnosticable { diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/month_appointment_helper.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/month_appointment_helper.dart index fc0d2a1f4..646109fed 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/month_appointment_helper.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/month_appointment_helper.dart @@ -9,11 +9,12 @@ import 'appointment_helper.dart'; /// month view. class MonthAppointmentHelper { static void _createVisibleAppointments( - List appointmentCollection, - List visibleAppointments, - List visibleDates, - int startIndex, - int endIndex) { + List appointmentCollection, + List visibleAppointments, + List visibleDates, + int startIndex, + int endIndex, + ) { for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView appointmentView = appointmentCollection[i]; appointmentView.endIndex = -1; @@ -30,12 +31,15 @@ class MonthAppointmentHelper { appointment.actualStartTime.day == appointment.actualEndTime.day && appointment.actualStartTime.month == appointment.actualEndTime.month) { - final AppointmentView appointmentView = - _createAppointmentView(appointmentCollection); + final AppointmentView appointmentView = _createAppointmentView( + appointmentCollection, + ); appointmentView.appointment = appointment; appointmentView.canReuse = false; - appointmentView.startIndex = - getDateIndex(appointment.actualStartTime, visibleDates); + appointmentView.startIndex = getDateIndex( + appointment.actualStartTime, + visibleDates, + ); /// Check the index value before the view start index then assign the /// start index as visible start index @@ -50,8 +54,10 @@ class MonthAppointmentHelper { appointmentView.startIndex = startIndex; } - appointmentView.endIndex = - getDateIndex(appointment.actualEndTime, visibleDates); + appointmentView.endIndex = getDateIndex( + appointment.actualEndTime, + visibleDates, + ); /// Check the index value after the view end index then assign the /// end index as visible end index @@ -70,12 +76,15 @@ class MonthAppointmentHelper { appointmentCollection.add(appointmentView); } } else { - final AppointmentView appointmentView = - _createAppointmentView(appointmentCollection); + final AppointmentView appointmentView = _createAppointmentView( + appointmentCollection, + ); appointmentView.appointment = appointment; appointmentView.canReuse = false; - appointmentView.startIndex = - getDateIndex(appointment.actualStartTime, visibleDates); + appointmentView.startIndex = getDateIndex( + appointment.actualStartTime, + visibleDates, + ); /// Check the index value before the view start index then assign the /// start index as visible start index @@ -90,8 +99,10 @@ class MonthAppointmentHelper { appointmentView.startIndex = startIndex; } - appointmentView.endIndex = - getDateIndex(appointment.actualEndTime, visibleDates); + appointmentView.endIndex = getDateIndex( + appointment.actualEndTime, + visibleDates, + ); /// Check the index value after the view end index then assign the /// end index as visible end index @@ -107,34 +118,40 @@ class MonthAppointmentHelper { } _createAppointmentInfoForSpannedAppointment( - appointmentView, appointmentCollection); + appointmentView, + appointmentCollection, + ); } } } static void _createAppointmentInfoForSpannedAppointment( - AppointmentView appointmentView, - List appointmentCollection) { + AppointmentView appointmentView, + List appointmentCollection, + ) { if (appointmentView.startIndex ~/ DateTime.daysPerWeek != appointmentView.endIndex ~/ DateTime.daysPerWeek) { final int endIndex = appointmentView.endIndex; appointmentView.endIndex = (((appointmentView.startIndex ~/ DateTime.daysPerWeek) + 1) * - DateTime.daysPerWeek) - - 1; + DateTime.daysPerWeek) - + 1; appointmentView.isSpanned = true; if (!appointmentCollection.contains(appointmentView)) { appointmentCollection.add(appointmentView); } - final AppointmentView appointmentView1 = - _createAppointmentView(appointmentCollection); + final AppointmentView appointmentView1 = _createAppointmentView( + appointmentCollection, + ); appointmentView1.appointment = appointmentView.appointment; appointmentView1.canReuse = false; appointmentView1.startIndex = appointmentView.endIndex + 1; appointmentView1.endIndex = endIndex; _createAppointmentInfoForSpannedAppointment( - appointmentView1, appointmentCollection); + appointmentView1, + appointmentCollection, + ); } else { appointmentView.isSpanned = true; if (!appointmentCollection.contains(appointmentView)) { @@ -144,9 +161,10 @@ class MonthAppointmentHelper { } static void _setAppointmentPosition( - List appointmentViewCollection, - AppointmentView appointmentView, - int viewIndex) { + List appointmentViewCollection, + AppointmentView appointmentView, + int viewIndex, + ) { for (int j = 0; j < appointmentViewCollection.length; j++) { //// Break when the collection reaches current appointment if (j >= viewIndex) { @@ -163,14 +181,19 @@ class MonthAppointmentHelper { appointmentView.maxPositions = appointmentView.position; prevAppointmentView.maxPositions = appointmentView.position; _setAppointmentPosition( - appointmentViewCollection, appointmentView, viewIndex); + appointmentViewCollection, + appointmentView, + viewIndex, + ); break; } } } static bool _isInterceptAppointments( - AppointmentView appointmentView1, AppointmentView appointmentView2) { + AppointmentView appointmentView1, + AppointmentView appointmentView2, + ) { if (appointmentView1.startIndex <= appointmentView2.startIndex && appointmentView1.endIndex >= appointmentView2.startIndex || appointmentView2.startIndex <= appointmentView1.startIndex && @@ -192,7 +215,9 @@ class MonthAppointmentHelper { /// the appointments have same start date then the appointment sorted based on /// end date and its interval(difference between end time and start time). static int _orderAppointmentViewBySpanned( - AppointmentView appointmentView1, AppointmentView appointmentView2) { + AppointmentView appointmentView1, + AppointmentView appointmentView2, + ) { if (appointmentView1.appointment == null || appointmentView2.appointment == null) { return 0; @@ -202,12 +227,14 @@ class MonthAppointmentHelper { final CalendarAppointment appointment2 = appointmentView2.appointment!; /// Calculate the both appointment start time based on isAllDay property. - final DateTime startTime1 = appointment1.isAllDay - ? AppointmentHelper.convertToStartTime(appointment1.exactStartTime) - : appointment1.exactStartTime; - final DateTime startTime2 = appointment2.isAllDay - ? AppointmentHelper.convertToStartTime(appointment2.exactStartTime) - : appointment2.exactStartTime; + final DateTime startTime1 = + appointment1.isAllDay + ? AppointmentHelper.convertToStartTime(appointment1.exactStartTime) + : appointment1.exactStartTime; + final DateTime startTime2 = + appointment2.isAllDay + ? AppointmentHelper.convertToStartTime(appointment2.exactStartTime) + : appointment2.exactStartTime; /// Check if both the appointments does not starts with same date then /// order the appointment based on its start time value. @@ -220,12 +247,14 @@ class MonthAppointmentHelper { return startTime1.compareTo(startTime2); } - final DateTime endTime1 = appointment1.isAllDay - ? AppointmentHelper.convertToEndTime(appointment1.exactEndTime) - : appointment1.exactEndTime; - final DateTime endTime2 = appointment2.isAllDay - ? AppointmentHelper.convertToEndTime(appointment2.exactEndTime) - : appointment2.exactEndTime; + final DateTime endTime1 = + appointment1.isAllDay + ? AppointmentHelper.convertToEndTime(appointment1.exactEndTime) + : appointment1.exactEndTime; + final DateTime endTime2 = + appointment2.isAllDay + ? AppointmentHelper.convertToEndTime(appointment2.exactEndTime) + : appointment2.exactEndTime; /// Check both the appointments have same start and end time then sort the /// appointments based on start time value. @@ -249,17 +278,18 @@ class MonthAppointmentHelper { /// swap list index value. /// Eg., app1 start with Nov3 10AM and ends with Nov5 11AM and app2 starts /// with Nov3 9AM and ends with Nov4 11AM then swap the app1 before of app2. - return AppointmentHelper.getDifference(endTime2, startTime2) - .inMinutes - .abs() - .compareTo(AppointmentHelper.getDifference(endTime1, startTime1) - .inMinutes - .abs()); + return AppointmentHelper.getDifference( + endTime2, + startTime2, + ).inMinutes.abs().compareTo( + AppointmentHelper.getDifference(endTime1, startTime1).inMinutes.abs(), + ); } static void _updateAppointmentPosition( - List appointmentCollection, - Map> indexAppointments) { + List appointmentCollection, + Map> indexAppointments, + ) { appointmentCollection.sort(_orderAppointmentViewBySpanned); for (int j = 0; j < appointmentCollection.length; j++) { @@ -274,9 +304,11 @@ class MonthAppointmentHelper { /// Add the appointment views to index appointment based on start and end /// index. It is used to get the visible index appointments. - for (int i = appointmentView.startIndex; - i <= appointmentView.endIndex; - i++) { + for ( + int i = appointmentView.startIndex; + i <= appointmentView.endIndex; + i++ + ) { /// Check the index already have appointments, if exists then add the /// current appointment to that collection, else create the index and /// create new collection with current appointment. @@ -297,9 +329,11 @@ class MonthAppointmentHelper { final int count = visibleDates.length; DateTime dateTime = visibleDates[count - DateTime.daysPerWeek]; int row = 0; - for (int i = count - DateTime.daysPerWeek; - i >= 0; - i -= DateTime.daysPerWeek) { + for ( + int i = count - DateTime.daysPerWeek; + i >= 0; + i -= DateTime.daysPerWeek + ) { final DateTime currentDate = visibleDates[i]; if (currentDate.isBefore(date) || (currentDate.day == date.day && @@ -311,11 +345,12 @@ class MonthAppointmentHelper { } } - final DateTime endDateTime = - DateTimeHelper.getDateTimeValue(addDays(dateTime, 6)); + final DateTime endDateTime = DateTimeHelper.getDateTimeValue( + addDays(dateTime, 6), + ); int currentViewIndex = 0; - while ( - dateTime.isBefore(endDateTime) || isSameDate(dateTime, endDateTime)) { + while (dateTime.isBefore(endDateTime) || + isSameDate(dateTime, endDateTime)) { if (isSameDate(dateTime, date)) { return (row * DateTime.daysPerWeek) + currentViewIndex; } @@ -328,7 +363,8 @@ class MonthAppointmentHelper { } static AppointmentView _createAppointmentView( - List appointmentCollection) { + List appointmentCollection, + ) { AppointmentView? appointmentView; for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView view = appointmentCollection[i]; @@ -352,14 +388,20 @@ class MonthAppointmentHelper { /// Update the appointment view details based on visible appointment and /// visible dates. static void updateAppointmentDetails( - List visibleAppointments, - List appointmentCollection, - List visibleDates, - Map> indexAppointments, - int startIndex, - int endIndex) { - _createVisibleAppointments(appointmentCollection, visibleAppointments, - visibleDates, startIndex, endIndex); + List visibleAppointments, + List appointmentCollection, + List visibleDates, + Map> indexAppointments, + int startIndex, + int endIndex, + ) { + _createVisibleAppointments( + appointmentCollection, + visibleAppointments, + visibleDates, + startIndex, + endIndex, + ); if (visibleAppointments.isNotEmpty) { _updateAppointmentPosition(appointmentCollection, indexAppointments); } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_helper.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_helper.dart index 0bc8a0ebe..1e61a1a1c 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_helper.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_helper.dart @@ -10,29 +10,52 @@ import 'recurrence_properties.dart'; /// Holds the static helper methods used for handling recurrence in calendar. class RecurrenceHelper { /// Check the recurrence appointment in between the visible date range. - static bool _isRecurrenceInBetweenSpecificRange(DateTime appointmentDate, - Duration duration, DateTime visibleStartDate, DateTime visibleEndTime) { - final DateTime appointmentEndDate = - DateTimeHelper.getDateTimeValue(addDuration(appointmentDate, duration)); + static bool _isRecurrenceInBetweenSpecificRange( + DateTime appointmentDate, + Duration duration, + DateTime visibleStartDate, + DateTime visibleEndTime, + ) { + final DateTime appointmentEndDate = DateTimeHelper.getDateTimeValue( + addDuration(appointmentDate, duration), + ); /// ignore: lines_longer_than_80_chars - return isDateWithInDateRange(visibleStartDate, visibleEndTime, appointmentDate) || + return isDateWithInDateRange( + visibleStartDate, + visibleEndTime, + appointmentDate, + ) || isDateWithInDateRange( - visibleStartDate, visibleEndTime, appointmentEndDate) || + visibleStartDate, + visibleEndTime, + appointmentEndDate, + ) || isDateWithInDateRange( - appointmentDate, appointmentEndDate, visibleStartDate); + appointmentDate, + appointmentEndDate, + visibleStartDate, + ); } static List _getDailyRecurrenceDateTimeCollection( - String rRule, DateTime recurrenceStartDate, - {Duration? recurrenceDuration, - DateTime? specificStartDate, - DateTime? specificEndDate}) { + String rRule, + DateTime recurrenceStartDate, { + Duration? recurrenceDuration, + DateTime? specificStartDate, + DateTime? specificEndDate, + }) { final List recDateCollection = []; if (specificEndDate != null) { - specificEndDate = DateTime(specificEndDate.year, specificEndDate.month, - specificEndDate.day, 23, 59, 59); + specificEndDate = DateTime( + specificEndDate.year, + specificEndDate.month, + specificEndDate.day, + 23, + 59, + 59, + ); } recurrenceDuration ??= Duration.zero; @@ -72,12 +95,13 @@ class RecurrenceHelper { endDate = getUntilEndDate(untilValueString); if (isSpecificDateRange) { final DateTime startTime = DateTime( - endDate.year, - endDate.month, - endDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + endDate.year, + endDate.month, + endDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final DateTime endTime = startTime.add(recurrenceDuration); /// Check the visible start date after of recurrence end date, if @@ -91,11 +115,12 @@ class RecurrenceHelper { /// Set the end date value from recurrence start date with /// count and interval values. endDate = AppointmentHelper.addDaysWithTime( - recurrenceStartDate, - (recurrenceCount - 1) * dailyDayGap, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + recurrenceStartDate, + (recurrenceCount - 1) * dailyDayGap, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); /// Return empty collection when the recurrence end date after of visible /// start date. @@ -111,9 +136,10 @@ class RecurrenceHelper { /// NoEndDate specified rule returns empty collection issue fix. if (isSpecificDateRange) { - endDate = endDate == null || endDate.isAfter(specificEndDate) - ? specificEndDate - : endDate; + endDate = + endDate == null || endDate.isAfter(specificEndDate) + ? specificEndDate + : endDate; } int recurrenceIncrementCount = 0; @@ -123,16 +149,24 @@ class RecurrenceHelper { /// recurrence start date is before of visible start date if (isSpecificDateRange && recurrenceStartDate.isBefore(specificStartDate)) { - final DateTime recurrenceInitialDate = DateTime(recurrenceStartDate.year, - recurrenceStartDate.month, recurrenceStartDate.day); - final DateTime visibleInitialDate = DateTime(specificStartDate.year, - specificStartDate.month, specificStartDate.day); + final DateTime recurrenceInitialDate = DateTime( + recurrenceStartDate.year, + recurrenceStartDate.month, + recurrenceStartDate.day, + ); + final DateTime visibleInitialDate = DateTime( + specificStartDate.year, + specificStartDate.month, + specificStartDate.day, + ); /// Total days difference between the visible start date and recurrence /// start date. - final int difference = AppointmentHelper.getDifference( - recurrenceInitialDate, visibleInitialDate) - .inDays; + final int difference = + AppointmentHelper.getDifference( + recurrenceInitialDate, + visibleInitialDate, + ).inDays; final int dayDifference = difference % dailyDayGap; /// Valid recurrences in between the visible start date and recurrence @@ -143,35 +177,43 @@ class RecurrenceHelper { /// and check the previous recurrence date have long recurrence duration. if (dayDifference == 0) { addDate = DateTime( - specificStartDate.year, - specificStartDate.month, - specificStartDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + specificStartDate.year, + specificStartDate.month, + specificStartDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); } else { /// If day difference is not 0 then initial start date is after the /// visible start date so calculate the recurrence from the date before /// the visible start date. check the previous recurrence date have /// long recurrence duration. addDate = AppointmentHelper.addDaysWithTime( - visibleInitialDate, - -dayDifference, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + visibleInitialDate, + -dayDifference, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); } final DateTime recurrenceEndDate = addDate.add(recurrenceDuration); if (incrementCount > 0 && !isSameDate(addDate, recurrenceEndDate)) { - final int durationDifference = recurrenceEndDate.hour > addDate.hour - ? recurrenceDuration.inDays - : recurrenceDuration.inDays + 1; + final int durationDifference = + recurrenceEndDate.hour > addDate.hour + ? recurrenceDuration.inDays + : recurrenceDuration.inDays + 1; final int intervalCount = ((durationDifference ~/ dailyDayGap) * dailyDayGap) + - (durationDifference % dailyDayGap == 0 ? 0 : dailyDayGap); - addDate = AppointmentHelper.addDaysWithTime(addDate, -intervalCount, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + (durationDifference % dailyDayGap == 0 ? 0 : dailyDayGap); + addDate = AppointmentHelper.addDaysWithTime( + addDate, + -intervalCount, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); incrementCount -= intervalCount ~/ dailyDayGap; } @@ -194,7 +236,11 @@ class RecurrenceHelper { (addDate.isBefore(endDate) || addDate == endDate))) { if (isSpecificDateRange) { if (_isRecurrenceInBetweenSpecificRange( - addDate, recurrenceDuration, specificStartDate, specificEndDate)) { + addDate, + recurrenceDuration, + specificStartDate, + specificEndDate, + )) { recDateCollection.add(addDate); } @@ -205,8 +251,13 @@ class RecurrenceHelper { recDateCollection.add(addDate); } - addDate = AppointmentHelper.addDaysWithTime(addDate, dailyDayGap, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + addDate = AppointmentHelper.addDaysWithTime( + addDate, + dailyDayGap, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); recurrenceIncrementCount++; } @@ -214,15 +265,23 @@ class RecurrenceHelper { } static List _getWeeklyRecurrenceDateTimeCollection( - String rRule, DateTime recurrenceStartDate, - {Duration? recurrenceDuration, - DateTime? specificStartDate, - DateTime? specificEndDate}) { + String rRule, + DateTime recurrenceStartDate, { + Duration? recurrenceDuration, + DateTime? specificStartDate, + DateTime? specificEndDate, + }) { final List recDateCollection = []; if (specificEndDate != null) { - specificEndDate = DateTime(specificEndDate.year, specificEndDate.month, - specificEndDate.day, 23, 59, 59); + specificEndDate = DateTime( + specificEndDate.year, + specificEndDate.month, + specificEndDate.day, + 23, + 59, + 59, + ); } recurrenceDuration ??= Duration.zero; @@ -242,7 +301,7 @@ class RecurrenceHelper { 'WE', 'TH', 'FR', - 'SA' + 'SA', ]; final List ruleArray = splitRule(rRule, ruleSeparator); if (ruleArray.isEmpty) { @@ -265,9 +324,10 @@ class RecurrenceHelper { recurrenceCountString.isNotEmpty ? int.parse(recurrenceCountString) : 0; int tempCount = 0; - final int weeklyWeekGap = ruleArray.length > 4 && rRule.contains('INTERVAL') - ? int.parse(intervalCountString) - : 1; + final int weeklyWeekGap = + ruleArray.length > 4 && rRule.contains('INTERVAL') + ? int.parse(intervalCountString) + : 1; assert(weeklyByDayPos != -1, 'Invalid weekly recurrence rule'); final List weekDays = []; final String ruleDaysString = weeklyRule[weeklyByDayPos]; @@ -290,12 +350,13 @@ class RecurrenceHelper { endDate = getUntilEndDate(untilValueString); if (isSpecificDateRange) { final DateTime startTime = DateTime( - endDate.year, - endDate.month, - endDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + endDate.year, + endDate.month, + endDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final DateTime endTime = startTime.add(recurrenceDuration); /// Check the visible start date after of recurrence end date, if @@ -336,7 +397,8 @@ class RecurrenceHelper { /// Add initial week days from recurrence start date to week end and /// add interval time after the initial week. - totalDays += DateTime.daysPerWeek - + totalDays += + DateTime.daysPerWeek - weekDay + (DateTime.daysPerWeek * (weeklyWeekGap - 1)); @@ -408,11 +470,12 @@ class RecurrenceHelper { } endDate = AppointmentHelper.addDaysWithTime( - recurrenceStartDate, - totalDays, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + recurrenceStartDate, + totalDays, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); /// Return empty collection when the recurrence end date after of visible /// start date. @@ -428,16 +491,20 @@ class RecurrenceHelper { /// NoEndDate specified rule returns empty collection issue fix. if (isSpecificDateRange) { - endDate = endDate == null || endDate.isAfter(specificEndDate) - ? specificEndDate - : endDate; + endDate = + endDate == null || endDate.isAfter(specificEndDate) + ? specificEndDate + : endDate; } DateTime addDate = recurrenceStartDate; if (isSpecificDateRange && recurrenceStartDate.isBefore(specificStartDate)) { - final DateTime startDate = - DateTime(addDate.year, addDate.month, addDate.day); + final DateTime startDate = DateTime( + addDate.year, + addDate.month, + addDate.day, + ); /// Calculate the total days between the recurrence start and visible /// start date. @@ -446,9 +513,10 @@ class RecurrenceHelper { final DateTime recurrenceEndDate = addDate.add(recurrenceDuration); /// Calculate day difference between the recurrence start and end date. - final int durationDifference = isSameDate(recurrenceEndDate, addDate) - ? 0 - : recurrenceEndDate.hour > addDate.hour + final int durationDifference = + isSameDate(recurrenceEndDate, addDate) + ? 0 + : recurrenceEndDate.hour > addDate.hour ? recurrenceDuration.inDays : recurrenceDuration.inDays + 1; @@ -484,9 +552,10 @@ class RecurrenceHelper { /// Calculate and remove the interval week after the initial week on /// total days difference. - final int initialWeekGap = isOccurrenceInInitialWeek - ? 0 - : DateTime.daysPerWeek * (weeklyWeekGap - 1); + final int initialWeekGap = + isOccurrenceInInitialWeek + ? 0 + : DateTime.daysPerWeek * (weeklyWeekGap - 1); daysDifference -= initialWeekGap; /// Calculate the total valid weeks(sunday to saturday) in between the @@ -501,15 +570,16 @@ class RecurrenceHelper { /// recurrence start date week remaining days to week end /// (DateTime.daysPerWeek - weekDay) + initialWeekGap. addDate = AppointmentHelper.addDaysWithTime( - addDate, - (totalWeeks * DateTime.daysPerWeek * weeklyWeekGap) + - (isOccurrenceInInitialWeek - ? daysDifference - : DateTime.daysPerWeek - weekDay) + - initialWeekGap, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + addDate, + (totalWeeks * DateTime.daysPerWeek * weeklyWeekGap) + + (isOccurrenceInInitialWeek + ? daysDifference + : DateTime.daysPerWeek - weekDay) + + initialWeekGap, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); tempCount = tempRecurrenceCount; } @@ -522,11 +592,16 @@ class RecurrenceHelper { while ((tempCount < recurrenceCount && isWeeklySelected) || (endDate != null && (addDate.isBefore(endDate) || addDate == endDate))) { - final bool isRecurrenceDate = - weekDays.contains(addDate.weekday % DateTime.daysPerWeek); + final bool isRecurrenceDate = weekDays.contains( + addDate.weekday % DateTime.daysPerWeek, + ); if (isSpecificDateRange) { - if (_isRecurrenceInBetweenSpecificRange(addDate, recurrenceDuration, - specificStartDate, specificEndDate) && + if (_isRecurrenceInBetweenSpecificRange( + addDate, + recurrenceDuration, + specificStartDate, + specificEndDate, + ) && isRecurrenceDate) { recDateCollection.add(addDate); } @@ -542,30 +617,45 @@ class RecurrenceHelper { tempCount++; } - addDate = addDate.weekday == DateTime.saturday - ? AppointmentHelper.addDaysWithTime( - addDate, - ((weeklyWeekGap - 1) * DateTime.daysPerWeek) + 1, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond) - : AppointmentHelper.addDaysWithTime(addDate, 1, recurrenceStartHour, - recurrenceStartMinute, recurrenceStartSecond); + addDate = + addDate.weekday == DateTime.saturday + ? AppointmentHelper.addDaysWithTime( + addDate, + ((weeklyWeekGap - 1) * DateTime.daysPerWeek) + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ) + : AppointmentHelper.addDaysWithTime( + addDate, + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); } return recDateCollection; } static List _getMonthlyRecurrenceDateTimeCollection( - String rRule, DateTime recurrenceStartDate, - {Duration? recurrenceDuration, - DateTime? specificStartDate, - DateTime? specificEndDate}) { + String rRule, + DateTime recurrenceStartDate, { + Duration? recurrenceDuration, + DateTime? specificStartDate, + DateTime? specificEndDate, + }) { final List recDateCollection = []; if (specificEndDate != null) { - specificEndDate = DateTime(specificEndDate.year, specificEndDate.month, - specificEndDate.day, 23, 59, 59); + specificEndDate = DateTime( + specificEndDate.year, + specificEndDate.month, + specificEndDate.day, + 23, + 59, + 59, + ); } recurrenceDuration ??= Duration.zero; @@ -601,21 +691,23 @@ class RecurrenceHelper { recCount = int.parse(recurCount); } - final int monthlyMonthGap = ruleArray.length > 4 && intervalCount.isNotEmpty - ? int.parse(intervalCount) - : 1; + final int monthlyMonthGap = + ruleArray.length > 4 && intervalCount.isNotEmpty + ? int.parse(intervalCount) + : 1; DateTime? endDate; if (rRule.contains('UNTIL')) { endDate = getUntilEndDate(untilValue); if (isSpecificDateRange) { final DateTime startTime = DateTime( - endDate.year, - endDate.month, - endDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + endDate.year, + endDate.month, + endDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final DateTime endTime = startTime.add(recurrenceDuration); /// Check the visible start date after of recurrence end date, if @@ -629,9 +721,10 @@ class RecurrenceHelper { /// NoEndDate specified rule returns empty collection issue fix. if (isSpecificDateRange && !rRule.contains('COUNT')) { - endDate = endDate == null || endDate.isAfter(specificEndDate) - ? specificEndDate - : endDate; + endDate = + endDate == null || endDate.isAfter(specificEndDate) + ? specificEndDate + : endDate; final int addedDateMonth = addDate.month; final int addedDateYear = addDate.year; @@ -642,14 +735,17 @@ class RecurrenceHelper { viewStartDateYear == addedDateYear)) { /// Calculate the total months between the recurrence start date and /// visible start date. - final int totalMonths = (viewStartDateMonth - addedDateMonth) + + final int totalMonths = + (viewStartDateMonth - addedDateMonth) + ((viewStartDateYear - addedDateYear) * 12); /// Calculate the valid month count between the recurrence start date /// and visible start date. final int validMonths = totalMonths ~/ monthlyMonthGap; addDate = DateTime( - addedDateYear, addedDateMonth + (validMonths * monthlyMonthGap)); + addedDateYear, + addedDateMonth + (validMonths * monthlyMonthGap), + ); if (addDate.isBefore(recurrenceStartDate)) { addDate = recurrenceStartDate; } @@ -662,8 +758,14 @@ class RecurrenceHelper { if (byMonthDay == -1) { monthDate = AppointmentHelper.getMonthEndDate(addDate).day; } - final DateTime temp = DateTime(addDate.year, addDate.month, monthDate, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + final DateTime temp = DateTime( + addDate.year, + addDate.month, + monthDate, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); /// Check the month date greater than recurrence start date and the /// month have the date value. @@ -680,15 +782,22 @@ class RecurrenceHelper { /// 30 and feb 30 does not exist so move the recurrence to next /// month and check next month have date 30 if exists then start the /// recurrence from mar 30. - addDate = DateTime(addDate.year, addDate.month + monthlyMonthGap, 1, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + addDate = DateTime( + addDate.year, + addDate.month + monthlyMonthGap, + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final DateTime tempDate = DateTime( - addDate.year, - addDate.month, - monthDate, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + addDate.year, + addDate.month, + monthDate, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); if (tempDate.day == monthDate) { addDate = tempDate; } @@ -706,18 +815,23 @@ class RecurrenceHelper { /// March 1 or 2 based on leap year. monthValue += monthlyMonthGap; addDate = DateTime( - yearValue, - monthValue, - monthDate, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + yearValue, + monthValue, + monthDate, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); continue; } if (isSpecificDateRange) { - if (_isRecurrenceInBetweenSpecificRange(addDate, recurrenceDuration, - specificStartDate, specificEndDate)) { + if (_isRecurrenceInBetweenSpecificRange( + addDate, + recurrenceDuration, + specificStartDate, + specificEndDate, + )) { recDateCollection.add(addDate); } @@ -729,12 +843,20 @@ class RecurrenceHelper { } monthValue += monthlyMonthGap; - monthDate = byMonthDay == -1 - ? AppointmentHelper.getMonthEndDate(DateTime(yearValue, monthValue)) - .day - : monthDate; - addDate = DateTime(yearValue, monthValue, monthDate, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + monthDate = + byMonthDay == -1 + ? AppointmentHelper.getMonthEndDate( + DateTime(yearValue, monthValue), + ).day + : monthDate; + addDate = DateTime( + yearValue, + monthValue, + monthDate, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); tempCount++; } @@ -744,15 +866,22 @@ class RecurrenceHelper { final int bySetPosValue = int.parse(bySetPosCount); void updateValidDate() { - final DateTime monthStart = DateTime(addDate.year, addDate.month, 1, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + final DateTime monthStart = DateTime( + addDate.year, + addDate.month, + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final int monthStartWeekday = monthStart.weekday % DateTime.daysPerWeek; final DateTime weekStartDate = AppointmentHelper.addDaysWithTime( - monthStart, - -monthStartWeekday, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + monthStart, + -monthStartWeekday, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); int nthWeek = bySetPosValue; if (monthStartWeekday <= nthWeekDay) { nthWeek = bySetPosValue - 1; @@ -760,21 +889,31 @@ class RecurrenceHelper { if (bySetPosValue.isNegative) { addDate = _getRecurrenceDateForNegativeValue( - bySetPosValue, monthStart, nthWeekDay); + bySetPosValue, + monthStart, + nthWeekDay, + ); } else { addDate = AppointmentHelper.addDaysWithTime( - weekStartDate, - (nthWeek * DateTime.daysPerWeek) + nthWeekDay, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + weekStartDate, + (nthWeek * DateTime.daysPerWeek) + nthWeekDay, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); } } updateValidDate(); if (addDate.isBefore(recurrenceStartDate)) { - addDate = DateTime(addDate.year, addDate.month + monthlyMonthGap, 1, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + addDate = DateTime( + addDate.year, + addDate.month + monthlyMonthGap, + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); updateValidDate(); } @@ -782,8 +921,12 @@ class RecurrenceHelper { (endDate != null && (addDate.isBefore(endDate) || addDate == endDate))) { if (isSpecificDateRange) { - if (_isRecurrenceInBetweenSpecificRange(addDate, recurrenceDuration, - specificStartDate, specificEndDate)) { + if (_isRecurrenceInBetweenSpecificRange( + addDate, + recurrenceDuration, + specificStartDate, + specificEndDate, + )) { recDateCollection.add(addDate); } @@ -794,8 +937,14 @@ class RecurrenceHelper { recDateCollection.add(addDate); } - addDate = DateTime(addDate.year, addDate.month + monthlyMonthGap, 1, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + addDate = DateTime( + addDate.year, + addDate.month + monthlyMonthGap, + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); updateValidDate(); tempCount++; } @@ -805,15 +954,23 @@ class RecurrenceHelper { } static List _getYearlyRecurrenceDateTimeCollection( - String rRule, DateTime recurrenceStartDate, - {Duration? recurrenceDuration, - DateTime? specificStartDate, - DateTime? specificEndDate}) { + String rRule, + DateTime recurrenceStartDate, { + Duration? recurrenceDuration, + DateTime? specificStartDate, + DateTime? specificEndDate, + }) { final List recDateCollection = []; if (specificEndDate != null) { - specificEndDate = DateTime(specificEndDate.year, specificEndDate.month, - specificEndDate.day, 23, 59, 59); + specificEndDate = DateTime( + specificEndDate.year, + specificEndDate.month, + specificEndDate.day, + 23, + 59, + 59, + ); } recurrenceDuration ??= Duration.zero; @@ -855,12 +1012,13 @@ class RecurrenceHelper { endDate = getUntilEndDate(untilValue); if (isSpecificDateRange) { final DateTime startTime = DateTime( - endDate.year, - endDate.month, - endDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + endDate.year, + endDate.month, + endDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final DateTime endTime = startTime.add(recurrenceDuration); /// Check the visible start date after of recurrence end date, if @@ -872,15 +1030,17 @@ class RecurrenceHelper { } } - final int yearlyYearGap = ruleArray.length > 4 && intervalCount.isNotEmpty - ? int.parse(intervalCount) - : 1; + final int yearlyYearGap = + ruleArray.length > 4 && intervalCount.isNotEmpty + ? int.parse(intervalCount) + : 1; /// NoEndDate specified rule returns empty collection issue fix. if (isSpecificDateRange && !rRule.contains('COUNT')) { - endDate = endDate == null || endDate.isAfter(specificEndDate) - ? specificEndDate - : endDate; + endDate = + endDate == null || endDate.isAfter(specificEndDate) + ? specificEndDate + : endDate; final int addedDateYear = addDate.year; final int viewStartDateYear = specificStartDate.year; @@ -901,31 +1061,40 @@ class RecurrenceHelper { int dayIndex = int.parse(byMonthDayCount); final int byMonthDay = dayIndex; if (byMonthDay == -1) { - dayIndex = AppointmentHelper.getMonthEndDate( - DateTime(addDate.year, monthIndex)) - .day; + dayIndex = + AppointmentHelper.getMonthEndDate( + DateTime(addDate.year, monthIndex), + ).day; } if (monthIndex < 0 || monthIndex > 12) { return recDateCollection; } - final int daysInMonth = DateTimeHelper.getDateTimeValue( - addDays(DateTime(addDate.year, addDate.month + 1), -1)) - .day; + final int daysInMonth = + DateTimeHelper.getDateTimeValue( + addDays(DateTime(addDate.year, addDate.month + 1), -1), + ).day; if (daysInMonth < dayIndex) { return recDateCollection; } - final DateTime specificDate = DateTime(addDate.year, monthIndex, dayIndex, - recurrenceStartHour, recurrenceStartMinute, recurrenceStartSecond); + final DateTime specificDate = DateTime( + addDate.year, + monthIndex, + dayIndex, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); if (specificDate.isBefore(recurrenceStartDate)) { addDate = DateTime( - specificDate.year + yearlyYearGap, - specificDate.month, - specificDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + specificDate.year + yearlyYearGap, + specificDate.month, + specificDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); } else { addDate = specificDate; } @@ -935,8 +1104,12 @@ class RecurrenceHelper { (endDate != null && (addDate.isBefore(endDate) || addDate == endDate))) { if (isSpecificDateRange) { - if (_isRecurrenceInBetweenSpecificRange(addDate, recurrenceDuration, - specificStartDate, specificEndDate)) { + if (_isRecurrenceInBetweenSpecificRange( + addDate, + recurrenceDuration, + specificStartDate, + specificEndDate, + )) { recDateCollection.add(addDate); } @@ -947,19 +1120,21 @@ class RecurrenceHelper { recDateCollection.add(addDate); } - dayIndex = byMonthDay == -1 - ? AppointmentHelper.getMonthEndDate( - DateTime(addDate.year + yearlyYearGap, monthIndex)) - .day - : addDate.day; + dayIndex = + byMonthDay == -1 + ? AppointmentHelper.getMonthEndDate( + DateTime(addDate.year + yearlyYearGap, monthIndex), + ).day + : addDate.day; addDate = DateTime( - addDate.year + yearlyYearGap, - addDate.month, - dayIndex, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + addDate.year + yearlyYearGap, + addDate.month, + dayIndex, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); tempCount++; } } else if (byDay == 'BYDAY') { @@ -971,20 +1146,22 @@ class RecurrenceHelper { void updateValidNextDate() { while (true) { DateTime monthStart = DateTime( - addDate.year, - monthIndex, - 1, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + addDate.year, + monthIndex, + 1, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); final int monthStartWeekday = monthStart.weekday % DateTime.daysPerWeek; final DateTime weekStartDate = AppointmentHelper.addDaysWithTime( - monthStart, - -monthStartWeekday, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + monthStart, + -monthStartWeekday, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); int nthWeek = bySetPosValue; if (monthStartWeekday <= nthWeekDay) { nthWeek = bySetPosValue - 1; @@ -992,25 +1169,30 @@ class RecurrenceHelper { if (bySetPosValue.isNegative) { monthStart = _getRecurrenceDateForNegativeValue( - bySetPosValue, monthStart, nthWeekDay); + bySetPosValue, + monthStart, + nthWeekDay, + ); } else { monthStart = AppointmentHelper.addDaysWithTime( - weekStartDate, - (nthWeek * DateTime.daysPerWeek) + nthWeekDay, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + weekStartDate, + (nthWeek * DateTime.daysPerWeek) + nthWeekDay, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); } if (monthStart.month != monthIndex || monthStart.isBefore(recurrenceStartDate)) { addDate = DateTime( - monthStart.year + yearlyYearGap, - monthStart.month, - monthStart.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + monthStart.year + yearlyYearGap, + monthStart.month, + monthStart.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); continue; } @@ -1024,8 +1206,12 @@ class RecurrenceHelper { (endDate != null && (addDate.isBefore(endDate) || addDate == endDate))) { if (isSpecificDateRange) { - if (_isRecurrenceInBetweenSpecificRange(addDate, recurrenceDuration, - specificStartDate, specificEndDate)) { + if (_isRecurrenceInBetweenSpecificRange( + addDate, + recurrenceDuration, + specificStartDate, + specificEndDate, + )) { recDateCollection.add(addDate); } @@ -1037,12 +1223,13 @@ class RecurrenceHelper { } addDate = DateTime( - addDate.year + yearlyYearGap, - addDate.month, - addDate.day, - recurrenceStartHour, - recurrenceStartMinute, - recurrenceStartSecond); + addDate.year + yearlyYearGap, + addDate.month, + addDate.day, + recurrenceStartHour, + recurrenceStartMinute, + recurrenceStartSecond, + ); tempCount++; updateValidNextDate(); @@ -1054,35 +1241,49 @@ class RecurrenceHelper { /// Returns the date time collection of recurring appointment. static List getRecurrenceDateTimeCollection( - String rRule, DateTime recurrenceStartDate, - {Duration? recurrenceDuration, - DateTime? specificStartDate, - DateTime? specificEndDate}) { + String rRule, + DateTime recurrenceStartDate, { + Duration? recurrenceDuration, + DateTime? specificStartDate, + DateTime? specificEndDate, + }) { /// Return empty collection when recurrence rule is empty. if (rRule.isEmpty) { return []; } if (rRule.contains('DAILY')) { - return _getDailyRecurrenceDateTimeCollection(rRule, recurrenceStartDate, - recurrenceDuration: recurrenceDuration, - specificStartDate: specificStartDate, - specificEndDate: specificEndDate); + return _getDailyRecurrenceDateTimeCollection( + rRule, + recurrenceStartDate, + recurrenceDuration: recurrenceDuration, + specificStartDate: specificStartDate, + specificEndDate: specificEndDate, + ); } else if (rRule.contains('WEEKLY')) { - return _getWeeklyRecurrenceDateTimeCollection(rRule, recurrenceStartDate, - recurrenceDuration: recurrenceDuration, - specificStartDate: specificStartDate, - specificEndDate: specificEndDate); + return _getWeeklyRecurrenceDateTimeCollection( + rRule, + recurrenceStartDate, + recurrenceDuration: recurrenceDuration, + specificStartDate: specificStartDate, + specificEndDate: specificEndDate, + ); } else if (rRule.contains('MONTHLY')) { - return _getMonthlyRecurrenceDateTimeCollection(rRule, recurrenceStartDate, - recurrenceDuration: recurrenceDuration, - specificStartDate: specificStartDate, - specificEndDate: specificEndDate); + return _getMonthlyRecurrenceDateTimeCollection( + rRule, + recurrenceStartDate, + recurrenceDuration: recurrenceDuration, + specificStartDate: specificStartDate, + specificEndDate: specificEndDate, + ); } else if (rRule.contains('YEARLY')) { - return _getYearlyRecurrenceDateTimeCollection(rRule, recurrenceStartDate, - recurrenceDuration: recurrenceDuration, - specificStartDate: specificStartDate, - specificEndDate: specificEndDate); + return _getYearlyRecurrenceDateTimeCollection( + rRule, + recurrenceStartDate, + recurrenceDuration: recurrenceDuration, + specificStartDate: specificStartDate, + specificEndDate: specificEndDate, + ); } return []; @@ -1091,8 +1292,9 @@ class RecurrenceHelper { /// Returns the recurrence properties based on the given recurrence rule and /// the recurrence start date. static RecurrenceProperties parseRRule(String rRule, DateTime recStartDate) { - final RecurrenceProperties recProp = - RecurrenceProperties(startDate: recStartDate); + final RecurrenceProperties recProp = RecurrenceProperties( + startDate: recStartDate, + ); if (rRule.isEmpty) { return recProp; @@ -1208,12 +1410,13 @@ class RecurrenceHelper { } static String _getRRuleForDaily( - int recCount, - RecurrenceProperties recurrenceProperties, - DateTime startDate, - DateTime? endDate, - bool isValidRecurrence, - Duration diffTimeSpan) { + int recCount, + RecurrenceProperties recurrenceProperties, + DateTime startDate, + DateTime? endDate, + bool isValidRecurrence, + Duration diffTimeSpan, + ) { String rRule = ''; if ((recCount > 0 && recurrenceProperties.recurrenceRange == RecurrenceRange.count) || @@ -1246,13 +1449,14 @@ class RecurrenceHelper { } static String _getRRuleForWeekly( - DateTime startDate, - DateTime? endDate, - int recCount, - RecurrenceProperties recurrenceProperties, - bool isValidRecurrence, - Duration diffTimeSpan, - DateTime prevDate) { + DateTime startDate, + DateTime? endDate, + int recCount, + RecurrenceProperties recurrenceProperties, + bool isValidRecurrence, + Duration diffTimeSpan, + DateTime prevDate, + ) { String rRule = ''; DateTime addDate = startDate; if ((recCount > 0 && @@ -1349,8 +1553,10 @@ class RecurrenceHelper { if (dayKey.isNotEmpty) { if (count != 0) { - final Duration tempTimeSpan = - AppointmentHelper.getDifference(prevDate, addDate); + final Duration tempTimeSpan = AppointmentHelper.getDifference( + prevDate, + addDate, + ); if (tempTimeSpan <= diffTimeSpan) { isValidRecurrence = false; } else { @@ -1373,9 +1579,10 @@ class RecurrenceHelper { } else { prevDate = addDate; count++; - byDay = byDay.isNotEmpty && byDay.substring(byDay.length - 1) == 'A' - ? '$byDay,$dayKey' - : byDay + dayKey; + byDay = + byDay.isNotEmpty && byDay.substring(byDay.length - 1) == 'A' + ? '$byDay,$dayKey' + : byDay + dayKey; dayCount++; } @@ -1432,16 +1639,23 @@ class RecurrenceHelper { dayKey = ''; } - addDate = addDate.weekday == DateTime.saturday - ? AppointmentHelper.addDaysWithTime( - addDate, - ((recurrenceProperties.interval - 1) * DateTime.daysPerWeek) + - 1, - startDate.hour, - startDate.minute, - startDate.second) - : AppointmentHelper.addDaysWithTime( - addDate, 1, startDate.hour, startDate.minute, startDate.second); + addDate = + addDate.weekday == DateTime.saturday + ? AppointmentHelper.addDaysWithTime( + addDate, + ((recurrenceProperties.interval - 1) * DateTime.daysPerWeek) + + 1, + startDate.hour, + startDate.minute, + startDate.second, + ) + : AppointmentHelper.addDaysWithTime( + addDate, + 1, + startDate.hour, + startDate.minute, + startDate.second, + ); i = i + 1; } @@ -1487,11 +1701,15 @@ class RecurrenceHelper { rRule = '$rRule;BYMONTHDAY=${recurrenceProperties.dayOfMonth}'; } else { final DateTime firstDate = DateTimeHelper.getDateTimeValue( - addDays(DateTime.now(), -(DateTime.now().weekday - 1))); + addDays(DateTime.now(), -(DateTime.now().weekday - 1)), + ); final List dayNames = List.generate(DateTime.daysPerWeek, (int index) => index) - .map((int value) => DateFormat(DateFormat.ABBR_WEEKDAY) - .format(addDays(firstDate, value))) + .map( + (int value) => DateFormat( + DateFormat.ABBR_WEEKDAY, + ).format(addDays(firstDate, value)), + ) .toList(); final String byDayString = dayNames[recurrenceProperties.dayOfWeek - 1]; @@ -1515,14 +1733,16 @@ class RecurrenceHelper { } if (AppointmentHelper.getDifference( - startDate, - DateTime( - startDate.year, - startDate.month + recurrenceProperties.interval, - startDate.day, - startDate.hour, - startDate.minute, - startDate.second)) < + startDate, + DateTime( + startDate.year, + startDate.month + recurrenceProperties.interval, + startDate.day, + startDate.hour, + startDate.minute, + startDate.second, + ), + ) < diffTimeSpan) { isValidRecurrence = false; } @@ -1536,12 +1756,13 @@ class RecurrenceHelper { } static String _getRRuleForYearly( - int recCount, - RecurrenceProperties recurrenceProperties, - DateTime startDate, - DateTime? endDate, - Duration diffTimeSpan, - bool isValidRecurrence) { + int recCount, + RecurrenceProperties recurrenceProperties, + DateTime startDate, + DateTime? endDate, + Duration diffTimeSpan, + bool isValidRecurrence, + ) { String rRule = ''; if ((recCount > 0 && recurrenceProperties.recurrenceRange == RecurrenceRange.count) || @@ -1556,11 +1777,15 @@ class RecurrenceHelper { '$rRule;BYMONTHDAY=${recurrenceProperties.dayOfMonth};BYMONTH=${recurrenceProperties.month}'; } else { final DateTime firstDate = DateTimeHelper.getDateTimeValue( - addDays(DateTime.now(), -(DateTime.now().weekday - 1))); + addDays(DateTime.now(), -(DateTime.now().weekday - 1)), + ); final List dayNames = List.generate(DateTime.daysPerWeek, (int index) => index) - .map((int value) => DateFormat(DateFormat.ABBR_WEEKDAY) - .format(addDays(firstDate, value))) + .map( + (int value) => DateFormat( + DateFormat.ABBR_WEEKDAY, + ).format(addDays(firstDate, value)), + ) .toList(); final String byDayString = dayNames[recurrenceProperties.dayOfWeek - 1]; @@ -1584,14 +1809,16 @@ class RecurrenceHelper { } if (AppointmentHelper.getDifference( - startDate, - DateTime( - startDate.year + recurrenceProperties.interval, - startDate.month, - startDate.day, - startDate.hour, - startDate.minute, - startDate.second)) < + startDate, + DateTime( + startDate.year + recurrenceProperties.interval, + startDate.month, + startDate.day, + startDate.hour, + startDate.minute, + startDate.second, + ), + ) < diffTimeSpan) { isValidRecurrence = false; } @@ -1606,16 +1833,22 @@ class RecurrenceHelper { /// Generates the recurrence rule based on the given recurrence properties and /// the start date and end date of the recurrence appointment. - static String generateRRule(RecurrenceProperties recurrenceProperties, - DateTime appStartTime, DateTime appEndTime) { + static String generateRRule( + RecurrenceProperties recurrenceProperties, + DateTime appStartTime, + DateTime appEndTime, + ) { final DateTime recPropStartDate = recurrenceProperties.startDate; final DateTime? recPropEndDate = recurrenceProperties.endDate; - final DateTime startDate = appStartTime.isAfter(recPropStartDate) - ? appStartTime - : recPropStartDate; + final DateTime startDate = + appStartTime.isAfter(recPropStartDate) + ? appStartTime + : recPropStartDate; final DateTime? endDate = recPropEndDate; - final Duration diffTimeSpan = - AppointmentHelper.getDifference(appStartTime, appEndTime); + final Duration diffTimeSpan = AppointmentHelper.getDifference( + appStartTime, + appEndTime, + ); int recCount = 0; final DateTime prevDate = DateTime.utc(1); const bool isValidRecurrence = true; @@ -1623,17 +1856,42 @@ class RecurrenceHelper { recCount = recurrenceProperties.recurrenceCount; switch (recurrenceProperties.recurrenceType) { case RecurrenceType.daily: - return _getRRuleForDaily(recCount, recurrenceProperties, startDate, - endDate, isValidRecurrence, diffTimeSpan); + return _getRRuleForDaily( + recCount, + recurrenceProperties, + startDate, + endDate, + isValidRecurrence, + diffTimeSpan, + ); case RecurrenceType.weekly: - return _getRRuleForWeekly(startDate, endDate, recCount, - recurrenceProperties, isValidRecurrence, diffTimeSpan, prevDate); + return _getRRuleForWeekly( + startDate, + endDate, + recCount, + recurrenceProperties, + isValidRecurrence, + diffTimeSpan, + prevDate, + ); case RecurrenceType.monthly: - return _getRRuleForMonthly(recCount, recurrenceProperties, startDate, - endDate, diffTimeSpan, isValidRecurrence); + return _getRRuleForMonthly( + recCount, + recurrenceProperties, + startDate, + endDate, + diffTimeSpan, + isValidRecurrence, + ); case RecurrenceType.yearly: - return _getRRuleForYearly(recCount, recurrenceProperties, startDate, - endDate, diffTimeSpan, isValidRecurrence); + return _getRRuleForYearly( + recCount, + recurrenceProperties, + startDate, + endDate, + diffTimeSpan, + isValidRecurrence, + ); } } @@ -1747,7 +2005,7 @@ class RecurrenceHelper { byMonthCount, weeklyByDay, byMonthDayPosition.toString(), - byDayPosition.toString() + byDayPosition.toString(), ]; } @@ -1767,11 +2025,15 @@ class RecurrenceHelper { static int _getWeekDay(String weekDay) { int index = 1; final DateTime firstDate = DateTimeHelper.getDateTimeValue( - addDays(DateTime.now(), -(DateTime.now().weekday - 1))); + addDays(DateTime.now(), -(DateTime.now().weekday - 1)), + ); final List dayNames = List.generate(DateTime.daysPerWeek, (int index) => index) - .map((int value) => DateFormat(DateFormat.ABBR_WEEKDAY) - .format(addDays(firstDate, value))) + .map( + (int value) => DateFormat( + DateFormat.ABBR_WEEKDAY, + ).format(addDays(firstDate, value)), + ) .toList(); for (int i = 0; i < DateTime.daysPerWeek; i++) { final String dayName = dayNames[i]; @@ -1817,9 +2079,10 @@ class RecurrenceHelper { if (untilString.contains('T')) { /// Z specifies UTC timezone offset, Checks the time zone is provided in /// the until end date value. - final DateTime endDate = untilString.contains('Z') - ? DateTime.parse(untilString).toLocal() - : DateTime.parse(untilString); + final DateTime endDate = + untilString.contains('Z') + ? DateTime.parse(untilString).toLocal() + : DateTime.parse(untilString); return endDate; } else { DateTime endDate = DateTime.parse(untilString); @@ -1830,13 +2093,17 @@ class RecurrenceHelper { /// Returns the recurrence start date for negative recurrence value. static DateTime _getRecurrenceDateForNegativeValue( - int bySetPosCount, DateTime date, int weekDay) { + int bySetPosCount, + DateTime date, + int weekDay, + ) { DateTime? lastDate; if (bySetPosCount == -1) { lastDate = AppointmentHelper.getMonthEndDate(date); } else if (bySetPosCount == -2) { - lastDate = AppointmentHelper.getMonthEndDate(date) - .subtract(const Duration(days: DateTime.daysPerWeek)); + lastDate = AppointmentHelper.getMonthEndDate( + date, + ).subtract(const Duration(days: DateTime.daysPerWeek)); } if (lastDate == null) { @@ -1845,9 +2112,16 @@ class RecurrenceHelper { } return _getLastWeekDay( - DateTime(lastDate.year, lastDate.month, lastDate.day, date.hour, - date.minute, date.second), - weekDay); + DateTime( + lastDate.year, + lastDate.month, + lastDate.day, + date.hour, + date.minute, + date.second, + ), + weekDay, + ); } /// Returns the last week date for the given weekday. @@ -1870,7 +2144,7 @@ class RecurrenceHelper { 'WE', 'TH', 'FR', - 'SA' + 'SA', ]; String weeklyDayString = ''; int count = 0; diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_properties.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_properties.dart index 171277f9c..c66dfac08 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_properties.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_engine/recurrence_properties.dart @@ -72,29 +72,33 @@ class RecurrenceProperties with Diagnosticable { /// An object contains properties that hold data for the creation of /// [Appointment.recurrenceRule] for [Appointment] using the /// [SfCalendar.generateRRule] method. - RecurrenceProperties( - {this.recurrenceType = RecurrenceType.daily, - this.recurrenceCount = 0, - required this.startDate, - this.endDate, - this.interval = 1, - this.recurrenceRange = RecurrenceRange.noEndDate, - List? weekDays, - this.week = 0, - this.dayOfMonth = 1, - this.dayOfWeek = 1, - this.month = 1}) - : weekDays = weekDays ?? [], - assert(recurrenceCount >= 0), - assert(endDate == null || - CalendarViewHelper.isSameOrBeforeDateTime(endDate, startDate)), - assert(endDate == null || - CalendarViewHelper.isSameOrAfterDateTime(startDate, endDate)), - assert(interval >= 1), - assert(week >= -2 && week <= 5), - assert(dayOfMonth >= 1 && dayOfMonth <= 31), - assert(dayOfWeek >= 1 && dayOfWeek <= 7), - assert(month >= 1 && month <= 12); + RecurrenceProperties({ + this.recurrenceType = RecurrenceType.daily, + this.recurrenceCount = 0, + required this.startDate, + this.endDate, + this.interval = 1, + this.recurrenceRange = RecurrenceRange.noEndDate, + List? weekDays, + this.week = 0, + this.dayOfMonth = 1, + this.dayOfWeek = 1, + this.month = 1, + }) : weekDays = weekDays ?? [], + assert(recurrenceCount >= 0), + assert( + endDate == null || + CalendarViewHelper.isSameOrBeforeDateTime(endDate, startDate), + ), + assert( + endDate == null || + CalendarViewHelper.isSameOrAfterDateTime(startDate, endDate), + ), + assert(interval >= 1), + assert(week >= -2 && week <= 5), + assert(dayOfMonth >= 1 && dayOfMonth <= 31), + assert(dayOfWeek >= 1 && dayOfWeek <= 7), + assert(month >= 1 && month <= 12); /// Defines the recurrence type of an [Appointment]. /// @@ -718,17 +722,18 @@ class RecurrenceProperties with Diagnosticable { // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode { return Object.hash( - recurrenceType, - recurrenceCount, - startDate, - endDate, - interval, - recurrenceRange, - Object.hashAll(weekDays), - week, - dayOfMonth, - dayOfWeek, - month); + recurrenceType, + recurrenceCount, + startDate, + endDate, + interval, + recurrenceRange, + Object.hashAll(weekDays), + week, + dayOfMonth, + dayOfWeek, + month, + ); } @override @@ -742,11 +747,16 @@ class RecurrenceProperties with Diagnosticable { properties.add(IntProperty('month', month)); properties.add(DiagnosticsProperty('startTime', startDate)); properties.add(DiagnosticsProperty('endTime', endDate)); - properties - .add(EnumProperty('recurrenceType', recurrenceType)); - properties - .add(EnumProperty('recurrenceRange', recurrenceRange)); - properties.add(IterableDiagnostics(weekDays) - .toDiagnosticsNode(name: 'weekDays')); + properties.add( + EnumProperty('recurrenceType', recurrenceType), + ); + properties.add( + EnumProperty('recurrenceRange', recurrenceRange), + ); + properties.add( + IterableDiagnostics( + weekDays, + ).toDiagnosticsNode(name: 'weekDays'), + ); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/agenda_view_layout.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/agenda_view_layout.dart index b74d8c54e..e6ae270d2 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/agenda_view_layout.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/agenda_view_layout.dart @@ -14,26 +14,27 @@ class AgendaViewLayout extends StatefulWidget { /// Constructor to create the agenda appointment layout that holds the agenda /// appointment views in calendar widget. const AgendaViewLayout( - this.monthViewSettings, - this.scheduleViewSettings, - this.selectedDate, - this.appointments, - this.isRTL, - this.locale, - this.localizations, - this.calendarTheme, - this.themeData, - this.agendaViewNotifier, - this.appointmentTimeTextFormat, - this.timeLabelWidth, - this.textScaleFactor, - this.isMobilePlatform, - this.appointmentBuilder, - this.width, - this.height, - this.placeholderTextStyle, - this.calendar, - {super.key}); + this.monthViewSettings, + this.scheduleViewSettings, + this.selectedDate, + this.appointments, + this.isRTL, + this.locale, + this.localizations, + this.calendarTheme, + this.themeData, + this.agendaViewNotifier, + this.appointmentTimeTextFormat, + this.timeLabelWidth, + this.textScaleFactor, + this.isMobilePlatform, + this.appointmentBuilder, + this.width, + this.height, + this.placeholderTextStyle, + this.calendar, { + super.key, + }); /// Defines the month view customization details. final MonthViewSettings? monthViewSettings; @@ -140,37 +141,41 @@ class _AgendaViewLayoutState extends State { continue; } final CalendarAppointmentDetails details = CalendarAppointmentDetails( - widget.selectedDate!, - List.unmodifiable([ - CalendarViewHelper.getAppointmentDetail( - view.appointment!, widget.calendar.dataSource) - ]), - view.appointmentRect!.outerRect); + widget.selectedDate!, + List.unmodifiable([ + CalendarViewHelper.getAppointmentDetail( + view.appointment!, + widget.calendar.dataSource, + ), + ]), + view.appointmentRect!.outerRect, + ); final Widget child = widget.appointmentBuilder!(context, details); _children.add(RepaintBoundary(child: child)); } } return _AgendaViewRenderWidget( - widget.monthViewSettings, - widget.scheduleViewSettings, - widget.selectedDate, - widget.appointments, - widget.isRTL, - widget.locale, - widget.localizations, - widget.calendarTheme, - widget.themeData, - widget.agendaViewNotifier, - widget.appointmentTimeTextFormat, - widget.timeLabelWidth, - widget.textScaleFactor, - widget.isMobilePlatform, - _appointmentCollection, - widget.width, - widget.height, - widget.placeholderTextStyle, - widgets: _children); + widget.monthViewSettings, + widget.scheduleViewSettings, + widget.selectedDate, + widget.appointments, + widget.isRTL, + widget.locale, + widget.localizations, + widget.calendarTheme, + widget.themeData, + widget.agendaViewNotifier, + widget.appointmentTimeTextFormat, + widget.timeLabelWidth, + widget.textScaleFactor, + widget.isMobilePlatform, + _appointmentCollection, + widget.width, + widget.height, + widget.placeholderTextStyle, + widgets: _children, + ); } void _updateAppointmentDetails() { @@ -179,7 +184,9 @@ class _AgendaViewLayoutState extends State { final double totalAgendaViewWidth = widget.width + widget.timeLabelWidth; final bool useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( - totalAgendaViewWidth, widget.isMobilePlatform); + totalAgendaViewWidth, + widget.isMobilePlatform, + ); AppointmentHelper.resetAppointmentView(_appointmentCollection); _children.clear(); if (widget.selectedDate == null || @@ -192,36 +199,52 @@ class _AgendaViewLayoutState extends State { widget.scheduleViewSettings != null && !useMobilePlatformUI; widget.appointments!.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); widget.appointments!.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isAllDay, + app2.isAllDay, + ), + ); widget.appointments!.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isSpanned, + app2.isSpanned, + ), + ); final double agendaItemHeight = CalendarViewHelper.getScheduleAppointmentHeight( - widget.monthViewSettings, widget.scheduleViewSettings); + widget.monthViewSettings, + widget.scheduleViewSettings, + ); final double agendaAllDayItemHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - widget.monthViewSettings, widget.scheduleViewSettings); + widget.monthViewSettings, + widget.scheduleViewSettings, + ); for (int i = 0; i < widget.appointments!.length; i++) { final CalendarAppointment appointment = widget.appointments![i]; final bool isSpanned = appointment.actualEndTime.day != appointment.actualStartTime.day || - appointment.isSpanned; + appointment.isSpanned; final double appointmentHeight = (appointment.isAllDay || isSpanned) && !isLargerScheduleUI ? agendaAllDayItemHeight : agendaItemHeight; final Rect rect = Rect.fromLTWH( - padding, yPosition, widget.width - (2 * padding), appointmentHeight); + padding, + yPosition, + widget.width - (2 * padding), + appointmentHeight, + ); final Radius cornerRadius = Radius.circular( - (appointmentHeight * 0.1) > 5 ? 5 : (appointmentHeight * 0.1)); + (appointmentHeight * 0.1) > 5 ? 5 : (appointmentHeight * 0.1), + ); yPosition += appointmentHeight + padding; AppointmentView? appointmentRenderer; for (int i = 0; i < _appointmentCollection.length; i++) { @@ -241,34 +264,36 @@ class _AgendaViewLayoutState extends State { appointmentRenderer.canReuse = false; appointmentRenderer.appointment = appointment; - appointmentRenderer.appointmentRect = - RRect.fromRectAndRadius(rect, cornerRadius); + appointmentRenderer.appointmentRect = RRect.fromRectAndRadius( + rect, + cornerRadius, + ); } } } class _AgendaViewRenderWidget extends MultiChildRenderObjectWidget { const _AgendaViewRenderWidget( - this.monthViewSettings, - this.scheduleViewSettings, - this.selectedDate, - this.appointments, - this.isRTL, - this.locale, - this.localizations, - this.calendarTheme, - this.themeData, - this.agendaViewNotifier, - this.appointmentTimeTextFormat, - this.timeLabelWidth, - this.textScaleFactor, - this.isMobilePlatform, - this.appointmentCollection, - this.width, - this.height, - this.placeholderTextStyle, - {List widgets = const []}) - : super(children: widgets); + this.monthViewSettings, + this.scheduleViewSettings, + this.selectedDate, + this.appointments, + this.isRTL, + this.locale, + this.localizations, + this.calendarTheme, + this.themeData, + this.agendaViewNotifier, + this.appointmentTimeTextFormat, + this.timeLabelWidth, + this.textScaleFactor, + this.isMobilePlatform, + this.appointmentCollection, + this.width, + this.height, + this.placeholderTextStyle, { + List widgets = const [], + }) : super(children: widgets); final MonthViewSettings? monthViewSettings; final ScheduleViewSettings? scheduleViewSettings; @@ -315,7 +340,9 @@ class _AgendaViewRenderWidget extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, _AgendaViewRenderObject renderObject) { + BuildContext context, + _AgendaViewRenderObject renderObject, + ) { renderObject ..monthViewSettings = monthViewSettings ..scheduleViewSettings = scheduleViewSettings @@ -339,24 +366,25 @@ class _AgendaViewRenderWidget extends MultiChildRenderObjectWidget { class _AgendaViewRenderObject extends CustomCalendarRenderObject { _AgendaViewRenderObject( - this._monthViewSettings, - this._scheduleViewSettings, - this._selectedDate, - this._appointments, - this._isRTL, - this._locale, - this._localizations, - this._calendarTheme, - this._themeData, - this._agendaViewNotifier, - this._appointmentTimeTextFormat, - this._timeLabelWidth, - this._textScaleFactor, - this.isMobilePlatform, - this._appointmentCollection, - this._width, - this._height, - this._placeholderTextStyle); + this._monthViewSettings, + this._scheduleViewSettings, + this._selectedDate, + this._appointments, + this._isRTL, + this._locale, + this._localizations, + this._calendarTheme, + this._themeData, + this._agendaViewNotifier, + this._appointmentTimeTextFormat, + this._timeLabelWidth, + this._textScaleFactor, + this.isMobilePlatform, + this._appointmentCollection, + this._width, + this._height, + this._placeholderTextStyle, + ); final bool isMobilePlatform; @@ -661,8 +689,10 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { continue; } - final Offset offset = Offset(appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top); + final Offset offset = Offset( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + ); final bool isHit = result.addWithPaintOffset( offset: offset, position: position, @@ -683,8 +713,10 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView appointmentView = appointmentCollection[i]; @@ -694,15 +726,20 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { continue; } - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: appointmentView.appointmentRect!.height, maxHeight: appointmentView.appointmentRect!.height, minWidth: appointmentView.appointmentRect!.width, - maxWidth: appointmentView.appointmentRect!.width)); + maxWidth: appointmentView.appointmentRect!.width, + ), + ); final CalendarParentData childParentData = child.parentData! as CalendarParentData; - childParentData.offset = Offset(appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top); + childParentData.offset = Offset( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + ); child = childAfter(child); } } @@ -713,7 +750,9 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { final bool isNeedDefaultPaint = childCount == 0; final double totalAgendaViewWidth = size.width + timeLabelWidth; final bool useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( - totalAgendaViewWidth, isMobilePlatform); + totalAgendaViewWidth, + isMobilePlatform, + ); final bool isLargerScheduleUI = scheduleViewSettings != null && !useMobilePlatformUI; if (isNeedDefaultPaint) { @@ -733,7 +772,12 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { if (agendaViewNotifier.value != null && isSameDate(agendaViewNotifier.value!.hoveringDate, selectedDate)) { _addMouseHovering( - context.canvas, size, rect, isLargerScheduleUI, padding); + context.canvas, + size, + rect, + isLargerScheduleUI, + padding, + ); } child = childAfter(child); @@ -758,9 +802,10 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { final List semanticsNodes = []; for (int i = 0; i < semantics.length; i++) { final CustomPainterSemantics currentSemantics = semantics[i]; - final SemanticsNode newChild = _cacheNodes!.isNotEmpty - ? _cacheNodes!.removeAt(0) - : SemanticsNode(key: currentSemantics.key); + final SemanticsNode newChild = + _cacheNodes!.isNotEmpty + ? _cacheNodes!.removeAt(0) + : SemanticsNode(key: currentSemantics.key); final SemanticsProperties properties = currentSemantics.properties; final SemanticsConfiguration config = SemanticsConfiguration(); @@ -808,38 +853,45 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } if (selectedDate == null) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Offset.zero & size, - properties: const SemanticsProperties( - label: 'No selected date', - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Offset.zero & size, + properties: const SemanticsProperties( + label: 'No selected date', + textDirection: TextDirection.ltr, + ), ), - )); + ); } else if (selectedDate != null && (appointments == null || appointments!.isEmpty)) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Offset.zero & size, - properties: SemanticsProperties( - label: - // ignore: lines_longer_than_80_chars - '${DateFormat('EEEEE').format(selectedDate!)}${DateFormat('dd MMMM yyyy').format(selectedDate!)}, No events', - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Offset.zero & size, + properties: SemanticsProperties( + label: + // ignore: lines_longer_than_80_chars + '${DateFormat('EEEEE').format(selectedDate!)}${DateFormat('dd MMMM yyyy').format(selectedDate!)}, No events', + textDirection: TextDirection.ltr, + ), ), - )); + ); } else if (selectedDate != null) { for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView appointmentView = appointmentCollection[i]; if (appointmentView.appointment == null) { continue; } - semanticsBuilder.add(CustomPainterSemantics( - rect: appointmentView.appointmentRect!.outerRect, - properties: SemanticsProperties( - label: CalendarViewHelper.getAppointmentSemanticsText( - appointmentView.appointment!), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: appointmentView.appointmentRect!.outerRect, + properties: SemanticsProperties( + label: CalendarViewHelper.getAppointmentSemanticsText( + appointmentView.appointment!, + ), + textDirection: TextDirection.ltr, + ), ), - )); + ); } } @@ -869,18 +921,21 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { return; } - final TextStyle appointmentTextStyle = monthViewSettings != null - ? themeData.textTheme.bodyMedium! - .copyWith(color: Colors.white, fontSize: 13) - .merge(monthViewSettings!.agendaStyle.appointmentTextStyle) - : themeData.textTheme.bodyMedium! - .copyWith( - color: isLargerScheduleUI && - themeData.brightness == Brightness.light - ? Colors.black87 - : Colors.white, - fontSize: 13) - .merge(scheduleViewSettings!.appointmentTextStyle); + final TextStyle appointmentTextStyle = + monthViewSettings != null + ? themeData.textTheme.bodyMedium! + .copyWith(color: Colors.white, fontSize: 13) + .merge(monthViewSettings!.agendaStyle.appointmentTextStyle) + : themeData.textTheme.bodyMedium! + .copyWith( + color: + isLargerScheduleUI && + themeData.brightness == Brightness.light + ? Colors.black87 + : Colors.white, + fontSize: 13, + ) + .merge(scheduleViewSettings!.appointmentTextStyle); final List appointmentStringFormats = appointmentTimeTextFormat == null @@ -902,7 +957,7 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { _rectPainter.color = appointment.color; final bool isSpanned = appointment.actualEndTime.day != appointment.actualStartTime.day || - appointment.isSpanned; + appointment.isSpanned; final double appointmentHeight = appointmentView.appointmentRect!.height; final RRect rect = appointmentView.appointmentRect!.shift(offset); xPosition = rect.left; @@ -913,19 +968,25 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { canvas.drawRRect(rect, _rectPainter); } - final TextSpan span = - TextSpan(text: appointment.subject, style: appointmentTextStyle); + final TextSpan span = TextSpan( + text: appointment.subject, + style: appointmentTextStyle, + ); _updateTextPainterProperties(span); double timeWidth = isLargerScheduleUI ? (size.width - (2 * padding)) * 0.3 : 0; timeWidth = timeWidth > 200 ? 200 : timeWidth; xPosition += timeWidth; - final bool isRecurrenceAppointment = appointment.recurrenceRule != null && + final bool isRecurrenceAppointment = + appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty; - final double textSize = - _getTextSize(rect, appointmentTextStyle, isMobilePlatform); + final double textSize = _getTextSize( + rect, + appointmentTextStyle, + isMobilePlatform, + ); double topPadding = 0; double spanIconWidth = 0; @@ -933,78 +994,83 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { /// Draw web schedule view. if (isLargerScheduleUI) { topPadding = _addScheduleViewForWeb( + canvas, + size, + padding, + xPosition, + yPosition, + timeWidth, + appointmentHeight, + isSpanned, + isRecurrenceAppointment, + textSize, + appointment, + appointmentTextStyle, + appointmentStringFormats, + sameDateAppointmentStringFormats, + offset, + ); + if (isSpanned) { + final TextSpan icon = AppointmentHelper.getSpanIcon( + appointmentTextStyle.color!, + isMobilePlatform ? textSize : textSize / 1.5, + !isRTL, + ); + spanIconWidth = _drawIcon( canvas, size, + textSize, + rect, padding, - xPosition, - yPosition, - timeWidth, + isLargerScheduleUI, + rect.tlRadius, + icon, appointmentHeight, - isSpanned, - isRecurrenceAppointment, - textSize, - appointment, - appointmentTextStyle, - appointmentStringFormats, - sameDateAppointmentStringFormats, - offset); - if (isSpanned) { - final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, - isMobilePlatform ? textSize : textSize / 1.5, - !isRTL); - spanIconWidth = _drawIcon( - canvas, - size, - textSize, - rect, - padding, - isLargerScheduleUI, - rect.tlRadius, - icon, - appointmentHeight, - topPadding, - true, - false, - spanIconWidth); + topPadding, + true, + false, + spanIconWidth, + ); } } else { /// Draws spanning appointment UI for schedule view. if (isSpanned) { final List iconPositions = _drawSpanningAppointmentForScheduleView( - canvas, - size, - xPosition, - yPosition, - padding, - appointment, - appointmentTextStyle, - appointmentHeight, - rect, - isMobilePlatform, - isLargerScheduleUI, - rect.tlRadius); + canvas, + size, + xPosition, + yPosition, + padding, + appointment, + appointmentTextStyle, + appointmentHeight, + rect, + isMobilePlatform, + isLargerScheduleUI, + rect.tlRadius, + ); spanIconWidth = iconPositions[0]; topPadding = iconPositions[1]; } //// Draw Appointments except All day appointment else if (!appointment.isAllDay) { topPadding = _drawNormalAppointmentUI( - canvas, - size, - xPosition, - yPosition, - padding, - timeWidth, - isRecurrenceAppointment, - textSize, - appointment, - appointmentHeight, - appointmentTextStyle, - appointmentStringFormats, - sameDateAppointmentStringFormats, - diffDateAppointmentStringFormats); + canvas, + size, + xPosition, + yPosition, + padding, + timeWidth, + isRecurrenceAppointment, + textSize, + appointment, + appointmentHeight, + appointmentTextStyle, + appointmentStringFormats, + sameDateAppointmentStringFormats, + diffDateAppointmentStringFormats, + ); } else { //// Draw All day appointment _updatePainterLinesCount(appointmentHeight, isAllDay: true); @@ -1016,27 +1082,33 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { topPadding = (appointmentHeight - _textPainter.height) / 2; _textPainter.paint( - canvas, Offset(xPosition + 5, yPosition + topPadding)); + canvas, + Offset(xPosition + 5, yPosition + topPadding), + ); } } if (isRecurrenceAppointment || appointment.recurrenceId != null) { final TextSpan icon = AppointmentHelper.getRecurrenceIcon( - appointmentTextStyle.color!, textSize, isRecurrenceAppointment); + appointmentTextStyle.color!, + textSize, + isRecurrenceAppointment, + ); _drawIcon( - canvas, - size, - textSize, - rect, - padding, - isLargerScheduleUI, - rect.tlRadius, - icon, - appointmentHeight, - topPadding, - false, - appointment.isAllDay, - spanIconWidth); + canvas, + size, + textSize, + rect, + padding, + isLargerScheduleUI, + rect.tlRadius, + icon, + appointmentHeight, + topPadding, + false, + appointment.isAllDay, + spanIconWidth, + ); } if (agendaViewNotifier.value != null && @@ -1047,14 +1119,18 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } double _getTextSize( - RRect rect, TextStyle appointmentTextStyle, bool isMobilePlatform) { + RRect rect, + TextStyle appointmentTextStyle, + bool isMobilePlatform, + ) { // The default font size if none is specified. // The value taken from framework, for text style when there is no font // size given they have used 14 as the default font size. const double defaultFontSize = 14; - final double textSize = isMobilePlatform - ? appointmentTextStyle.fontSize ?? defaultFontSize - : appointmentTextStyle.fontSize != null + final double textSize = + isMobilePlatform + ? appointmentTextStyle.fontSize ?? defaultFontSize + : appointmentTextStyle.fontSize != null ? appointmentTextStyle.fontSize! * 1.5 : defaultFontSize * 1.5; if (rect.width < textSize || rect.height < textSize) { @@ -1065,19 +1141,20 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } double _drawIcon( - Canvas canvas, - Size size, - double textSize, - RRect rect, - double padding, - bool isLargerScheduleUI, - Radius cornerRadius, - TextSpan icon, - double appointmentHeight, - double yPosition, - bool isSpan, - bool isAllDay, - double spanIconWidth) { + Canvas canvas, + Size size, + double textSize, + RRect rect, + double padding, + bool isLargerScheduleUI, + Radius cornerRadius, + TextSpan icon, + double appointmentHeight, + double yPosition, + bool isSpan, + bool isAllDay, + double spanIconWidth, + ) { _textPainter.text = icon; _textPainter.textScaler = TextScaler.linear(textScaleFactor); _textPainter.layout(maxWidth: size.width - (2 * padding) - padding); @@ -1085,18 +1162,30 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { if (!isLargerScheduleUI) { if (isRTL) { canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(rect.left + spanIconWidth, rect.top, - rect.left + spanIconWidth + iconSize, rect.bottom), - cornerRadius), - _rectPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + rect.left + spanIconWidth, + rect.top, + rect.left + spanIconWidth + iconSize, + rect.bottom, + ), + cornerRadius, + ), + _rectPainter, + ); } else { canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(rect.right - spanIconWidth - iconSize, rect.top, - rect.right - spanIconWidth, rect.bottom), - cornerRadius), - _rectPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + rect.right - spanIconWidth - iconSize, + rect.top, + rect.right - spanIconWidth, + rect.bottom, + ), + cornerRadius, + ), + _rectPainter, + ); } } @@ -1107,7 +1196,8 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { /// value 2 used since the space on top and bottom of icon is not even, /// hence to rectify this tha value 2 used, and tested with multiple /// device. - iconStartPosition = (_textPainter.height - + iconStartPosition = + (_textPainter.height - (icon.style!.fontSize! * textScaleFactor) / 2) / 2; } @@ -1115,19 +1205,27 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { // Value 8 added as a right side padding for the recurrence icon in the // agenda view if (isRTL) { - _textPainter.paint(canvas, - Offset(8 + spanIconWidth, rect.top + yPosition - iconStartPosition)); + _textPainter.paint( + canvas, + Offset(8 + spanIconWidth, rect.top + yPosition - iconStartPosition), + ); } else { _textPainter.paint( - canvas, - Offset(rect.right - _textPainter.width - 8 - spanIconWidth, - rect.top + yPosition - iconStartPosition)); + canvas, + Offset( + rect.right - _textPainter.width - 8 - spanIconWidth, + rect.top + yPosition - iconStartPosition, + ), + ); } return _textPainter.width + 8; } - double _updatePainterLinesCount(double appointmentHeight, - {bool isSpanned = false, bool isAllDay = false}) { + double _updatePainterLinesCount( + double appointmentHeight, { + bool isSpanned = false, + bool isAllDay = false, + }) { final double lineHeight = _textPainter.preferredLineHeight; /// Top and bottom padding 5 @@ -1143,25 +1241,27 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } double _drawNormalAppointmentUI( - Canvas canvas, - Size size, - double xPosition, - double yPosition, - double padding, - double timeWidth, - bool isRecurrence, - double recurrenceTextSize, - CalendarAppointment appointment, - double appointmentHeight, - TextStyle appointmentTextStyle, - List appointmentFormatString, - List sameDateAppointmentFormatString, - List diffDateAppointmentFormatString) { + Canvas canvas, + Size size, + double xPosition, + double yPosition, + double padding, + double timeWidth, + bool isRecurrence, + double recurrenceTextSize, + CalendarAppointment appointment, + double appointmentHeight, + TextStyle appointmentTextStyle, + List appointmentFormatString, + List sameDateAppointmentFormatString, + List diffDateAppointmentFormatString, + ) { _textPainter.textScaler = TextScaler.linear(textScaleFactor); final double lineHeight = _updatePainterLinesCount(appointmentHeight); final double iconSize = isRecurrence ? recurrenceTextSize + 10 : 0; _textPainter.layout( - maxWidth: size.width - (2 * padding) - xPosition - iconSize); + maxWidth: size.width - (2 * padding) - xPosition - iconSize, + ); final double subjectHeight = _textPainter.height; final double topPadding = (appointmentHeight - (subjectHeight + lineHeight)) / 2; @@ -1170,57 +1270,82 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } _textPainter.paint( - canvas, Offset(xPosition + padding, yPosition + topPadding)); + canvas, + Offset(xPosition + padding, yPosition + topPadding), + ); - final List format = appointmentFormatString.isEmpty - ? (isSameDate(appointment.actualStartTime, appointment.actualEndTime) - ? sameDateAppointmentFormatString - : diffDateAppointmentFormatString) - : appointmentFormatString; + final List format = + appointmentFormatString.isEmpty + ? (isSameDate( + appointment.actualStartTime, + appointment.actualEndTime, + ) + ? sameDateAppointmentFormatString + : diffDateAppointmentFormatString) + : appointmentFormatString; final String startDateText = CalendarViewHelper.getLocalizedString( - appointment.actualStartTime, format, locale); + appointment.actualStartTime, + format, + locale, + ); final String endDateText = CalendarViewHelper.getLocalizedString( - appointment.actualEndTime, format, locale); + appointment.actualEndTime, + format, + locale, + ); final TextSpan span = TextSpan( - text: '$startDateText - $endDateText', style: appointmentTextStyle); + text: '$startDateText - $endDateText', + style: appointmentTextStyle, + ); _textPainter.text = span; _textPainter.maxLines = 1; _textPainter.layout( - maxWidth: size.width - (2 * padding) - padding - iconSize); + maxWidth: size.width - (2 * padding) - padding - iconSize, + ); if (isRTL) { xPosition = size.width - _textPainter.width - (3 * padding); } - _textPainter.paint(canvas, - Offset(xPosition + padding, yPosition + topPadding + subjectHeight)); + _textPainter.paint( + canvas, + Offset(xPosition + padding, yPosition + topPadding + subjectHeight), + ); return topPadding; } List _drawSpanningAppointmentForScheduleView( - Canvas canvas, - Size size, - double xPosition, - double yPosition, - double padding, - CalendarAppointment appointment, - TextStyle appointmentTextStyle, - double appointmentHeight, - RRect rect, - bool isMobilePlatform, - bool isLargerScheduleUI, - Radius cornerRadius) { + Canvas canvas, + Size size, + double xPosition, + double yPosition, + double padding, + CalendarAppointment appointment, + TextStyle appointmentTextStyle, + double appointmentHeight, + RRect rect, + bool isMobilePlatform, + bool isLargerScheduleUI, + Radius cornerRadius, + ) { final TextSpan span = TextSpan( - text: AppointmentHelper.getSpanAppointmentText( - appointment, selectedDate!, localizations), - style: appointmentTextStyle); + text: AppointmentHelper.getSpanAppointmentText( + appointment, + selectedDate!, + localizations, + ), + style: appointmentTextStyle, + ); _updateTextPainterProperties(span); _updatePainterLinesCount(appointmentHeight, isSpanned: true); final bool isNeedSpanIcon = !isSameDate(appointment.exactEndTime, selectedDate); - final double textSize = - _getTextSize(rect, appointmentTextStyle, isMobilePlatform); + final double textSize = _getTextSize( + rect, + appointmentTextStyle, + isMobilePlatform, + ); /// Icon padding 8 and 2 additional padding final double iconSize = isNeedSpanIcon ? textSize + 10 : 0; @@ -1233,29 +1358,51 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { final double topPadding = (appointmentHeight - _textPainter.height) / 2; _textPainter.paint( - canvas, Offset(xPosition + padding, yPosition + topPadding)); + canvas, + Offset(xPosition + padding, yPosition + topPadding), + ); if (!isNeedSpanIcon) { return [0, topPadding]; } final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, - isMobilePlatform ? textSize : textSize / 1.5, - !isRTL); + appointmentTextStyle.color!, + isMobilePlatform ? textSize : textSize / 1.5, + !isRTL, + ); return [ - _drawIcon(canvas, size, textSize, rect, padding, isLargerScheduleUI, - cornerRadius, icon, appointmentHeight, topPadding, true, false, 0), - topPadding + _drawIcon( + canvas, + size, + textSize, + rect, + padding, + isLargerScheduleUI, + cornerRadius, + icon, + appointmentHeight, + topPadding, + true, + false, + 0, + ), + topPadding, ]; } - void _drawDefaultView(Canvas canvas, Size size, double xPosition, - double yPosition, double padding) { + void _drawDefaultView( + Canvas canvas, + Size size, + double xPosition, + double yPosition, + double padding, + ) { final TextSpan span = TextSpan( - text: selectedDate == null - ? localizations.noSelectedDateCalendarLabel - : localizations.noEventsCalendarLabel, + text: + selectedDate == null + ? localizations.noSelectedDateCalendarLabel + : localizations.noEventsCalendarLabel, style: themeData.textTheme.bodyMedium!.merge(placeholderTextStyle), ); @@ -1278,47 +1425,55 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } double _addScheduleViewForWeb( - Canvas canvas, - Size size, - double padding, - double xPosition, - double yPosition, - double timeWidth, - double appointmentHeight, - bool isNeedSpanIcon, - bool isNeedRecurrenceIcon, - double textSize, - CalendarAppointment appointment, - TextStyle appointmentTextStyle, - List appointmentFormatString, - List sameDateAppointmentFormatString, - Offset offset) { + Canvas canvas, + Size size, + double padding, + double xPosition, + double yPosition, + double timeWidth, + double appointmentHeight, + bool isNeedSpanIcon, + bool isNeedRecurrenceIcon, + double textSize, + CalendarAppointment appointment, + TextStyle appointmentTextStyle, + List appointmentFormatString, + List sameDateAppointmentFormatString, + Offset offset, + ) { _textPainter.textScaler = TextScaler.linear(textScaleFactor); final double centerYPosition = appointmentHeight / 2; final double circleRadius = centerYPosition > padding ? padding : centerYPosition - 2; final double circleStartPosition = offset.dx + (3 * circleRadius); canvas.drawCircle( - Offset(isRTL ? size.width - circleStartPosition : circleStartPosition, - yPosition + centerYPosition), - circleRadius, - _rectPainter); + Offset( + isRTL ? size.width - circleStartPosition : circleStartPosition, + yPosition + centerYPosition, + ), + circleRadius, + _rectPainter, + ); final double circleWidth = 5 * circleRadius; xPosition += circleWidth; - _updatePainterLinesCount(appointmentHeight, - isAllDay: true, isSpanned: true); + _updatePainterLinesCount( + appointmentHeight, + isAllDay: true, + isSpanned: true, + ); /// Icon padding 8 and 2 additional padding double iconSize = isNeedSpanIcon ? textSize + 10 : 0; iconSize += isNeedRecurrenceIcon ? textSize + 10 : 0; _textPainter.layout( - maxWidth: - offset.dx + size.width - (2 * padding) - xPosition - iconSize); + maxWidth: offset.dx + size.width - (2 * padding) - xPosition - iconSize, + ); if (isRTL) { - xPosition = size.width - + xPosition = + size.width - _textPainter.width - (3 * padding) - timeWidth - @@ -1327,19 +1482,30 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { final double topPadding = (appointmentHeight - _textPainter.height) / 2; _textPainter.paint( - canvas, Offset(xPosition + padding, yPosition + topPadding)); - final List format = appointmentFormatString.isEmpty - ? sameDateAppointmentFormatString - : appointmentFormatString; + canvas, + Offset(xPosition + padding, yPosition + topPadding), + ); + final List format = + appointmentFormatString.isEmpty + ? sameDateAppointmentFormatString + : appointmentFormatString; final String startDateText = CalendarViewHelper.getLocalizedString( - appointment.actualStartTime, format, locale); + appointment.actualStartTime, + format, + locale, + ); final String endDateText = CalendarViewHelper.getLocalizedString( - appointment.actualEndTime, format, locale); + appointment.actualEndTime, + format, + locale, + ); final TextSpan span = TextSpan( - text: appointment.isAllDay || appointment.isSpanned - ? _localizations.allDayLabel - : '$startDateText - $endDateText', - style: appointmentTextStyle); + text: + appointment.isAllDay || appointment.isSpanned + ? _localizations.allDayLabel + : '$startDateText - $endDateText', + style: appointmentTextStyle, + ); _textPainter.text = span; _textPainter.layout(maxWidth: timeWidth - padding); @@ -1349,14 +1515,22 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { } _textPainter.paint( - canvas, - Offset(xPosition + padding, - yPosition + ((appointmentHeight - _textPainter.height) / 2))); + canvas, + Offset( + xPosition + padding, + yPosition + ((appointmentHeight - _textPainter.height) / 2), + ), + ); return topPadding; } - void _addMouseHovering(Canvas canvas, Size size, RRect rect, - bool isLargerScheduleUI, double padding) { + void _addMouseHovering( + Canvas canvas, + Size size, + RRect rect, + bool isLargerScheduleUI, + double padding, + ) { if (rect.left < agendaViewNotifier.value!.hoveringOffset.dx && rect.right > agendaViewNotifier.value!.hoveringOffset.dx && rect.top < agendaViewNotifier.value!.hoveringOffset.dy && @@ -1365,27 +1539,33 @@ class _AgendaViewRenderObject extends CustomCalendarRenderObject { _rectPainter.color = Colors.grey.withValues(alpha: 0.1); const double viewPadding = 2; canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTWH( - rect.left - padding, - rect.top + viewPadding, - size.width - (isRTL ? viewPadding : padding), - rect.height - (2 * viewPadding)), - const Radius.circular(4)), - _rectPainter); + RRect.fromRectAndRadius( + Rect.fromLTWH( + rect.left - padding, + rect.top + viewPadding, + size.width - (isRTL ? viewPadding : padding), + rect.height - (2 * viewPadding), + ), + const Radius.circular(4), + ), + _rectPainter, + ); } else { - _rectPainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + _rectPainter.color = calendarTheme.selectionBorderColor!.withValues( + alpha: 0.4, + ); _rectPainter.style = PaintingStyle.stroke; _rectPainter.strokeWidth = 2; if (childCount == 0) { final Radius cornerRadius = Radius.circular( - (rect.outerRect.height * 0.1) > 5 - ? 5 - : (rect.outerRect.height * 0.1)); + (rect.outerRect.height * 0.1) > 5 + ? 5 + : (rect.outerRect.height * 0.1), + ); canvas.drawRRect( - RRect.fromRectAndRadius(rect.outerRect, cornerRadius), - _rectPainter); + RRect.fromRectAndRadius(rect.outerRect, cornerRadius), + _rectPainter, + ); } else { canvas.drawRect(rect.outerRect, _rectPainter); } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/allday_appointment_layout.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/allday_appointment_layout.dart index b616a43e1..8acb9b83d 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/allday_appointment_layout.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/allday_appointment_layout.dart @@ -13,26 +13,27 @@ class AllDayAppointmentLayout extends StatefulWidget { /// Constructor to create the all day appointment layout that holds the /// all day appointment views in calendar widget. const AllDayAppointmentLayout( - this.calendar, - this.view, - this.visibleDates, - this.visibleAppointments, - this.timeLabelWidth, - this.allDayPainterHeight, - this.isExpandable, - this.isExpanding, - this.isRTL, - this.calendarTheme, - this.themeData, - this.repaintNotifier, - this.allDayHoverPosition, - this.textScaleFactor, - this.isMobilePlatform, - this.width, - this.height, - this.localizations, - this.updateCalendarState, - {super.key}); + this.calendar, + this.view, + this.visibleDates, + this.visibleAppointments, + this.timeLabelWidth, + this.allDayPainterHeight, + this.isExpandable, + this.isExpanding, + this.isRTL, + this.calendarTheme, + this.themeData, + this.repaintNotifier, + this.allDayHoverPosition, + this.textScaleFactor, + this.isMobilePlatform, + this.width, + this.height, + this.localizations, + this.updateCalendarState, { + super.key, + }); /// Holds the calendar instance used the get the properties of calendar. final SfCalendar calendar; @@ -163,26 +164,33 @@ class _AllDayAppointmentLayoutState extends State { } final DateTime appStartTime = DateTime( - appointmentView.appointment!.actualStartTime.year, - appointmentView.appointment!.actualStartTime.month, - appointmentView.appointment!.actualStartTime.day); - final DateTime date = appStartTime.isBefore(initialVisibleDate) - ? initialVisibleDate - : appStartTime; + appointmentView.appointment!.actualStartTime.year, + appointmentView.appointment!.actualStartTime.month, + appointmentView.appointment!.actualStartTime.day, + ); + final DateTime date = + appStartTime.isBefore(initialVisibleDate) + ? initialVisibleDate + : appStartTime; final Widget child = widget.calendar.appointmentBuilder!( - context, - CalendarAppointmentDetails( - date, - List.unmodifiable([ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ]), - Rect.fromLTWH( - appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top, - appointmentView.appointmentRect!.width, - appointmentView.appointmentRect!.right))); + context, + CalendarAppointmentDetails( + date, + List.unmodifiable([ + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ]), + Rect.fromLTWH( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + appointmentView.appointmentRect!.width, + appointmentView.appointmentRect!.right, + ), + ), + ); _children.add(RepaintBoundary(child: child)); } @@ -197,7 +205,9 @@ class _AllDayAppointmentLayoutState extends State { (widget.width - widget.timeLabelWidth) / widget.visibleDates.length; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - widget.calendar.cellEndPadding, widget.isMobilePlatform); + widget.calendar.cellEndPadding, + widget.isMobilePlatform, + ); /// Calculate the maximum appointment width based on cell end padding. final double maxAppointmentWidth = cellWidth - cellEndPadding; @@ -217,20 +227,26 @@ class _AllDayAppointmentLayoutState extends State { moreAppointments.add(currentAppointment.appointment!); } final Widget child = widget.calendar.appointmentBuilder!( - context, - CalendarAppointmentDetails( - date, - List.unmodifiable( - CalendarViewHelper.getCustomAppointments( - moreAppointments, widget.calendar.dataSource)), - Rect.fromLTWH( - widget.isRTL - ? widget.width - xPosition - maxAppointmentWidth - : xPosition, - widget.height - kAllDayAppointmentHeight, - maxAppointmentWidth, - kAllDayAppointmentHeight - 1), - isMoreAppointmentRegion: true)); + context, + CalendarAppointmentDetails( + date, + List.unmodifiable( + CalendarViewHelper.getCustomAppointments( + moreAppointments, + widget.calendar.dataSource, + ), + ), + Rect.fromLTWH( + widget.isRTL + ? widget.width - xPosition - maxAppointmentWidth + : xPosition, + widget.height - kAllDayAppointmentHeight, + maxAppointmentWidth, + kAllDayAppointmentHeight - 1, + ), + isMoreAppointmentRegion: true, + ), + ); _children.add(RepaintBoundary(child: child)); } @@ -276,12 +292,15 @@ class _AllDayAppointmentLayoutState extends State { _updateCalendarStateDetails.allDayAppointmentViewCollection; final double cellWidth = (widget.width - widget.timeLabelWidth) / widget.visibleDates.length; - const double cornerRadius = (kAllDayAppointmentHeight * 0.1) > 2 - ? 2 - : kAllDayAppointmentHeight * 0.1; + const double cornerRadius = + (kAllDayAppointmentHeight * 0.1) > 2 + ? 2 + : kAllDayAppointmentHeight * 0.1; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - widget.calendar.cellEndPadding, widget.isMobilePlatform); + widget.calendar.cellEndPadding, + widget.isMobilePlatform, + ); /// Calculate the maximum position of the appointment this widget can hold. final int position = widget.allDayPainterHeight ~/ kAllDayAppointmentHeight; @@ -294,35 +313,40 @@ class _AllDayAppointmentLayoutState extends State { RRect rect; if (widget.isRTL) { rect = RRect.fromRectAndRadius( - Rect.fromLTRB( - ((widget.visibleDates.length - appointmentView.endIndex) * - cellWidth) + - cellEndPadding, - kAllDayAppointmentHeight * appointmentView.position, - (widget.visibleDates.length - appointmentView.startIndex) * - cellWidth, - (kAllDayAppointmentHeight * appointmentView.position) + - kAllDayAppointmentHeight - - 1), - const Radius.circular(cornerRadius)); + Rect.fromLTRB( + ((widget.visibleDates.length - appointmentView.endIndex) * + cellWidth) + + cellEndPadding, + kAllDayAppointmentHeight * appointmentView.position, + (widget.visibleDates.length - appointmentView.startIndex) * + cellWidth, + (kAllDayAppointmentHeight * appointmentView.position) + + kAllDayAppointmentHeight - + 1, + ), + const Radius.circular(cornerRadius), + ); } else { rect = RRect.fromRectAndRadius( - Rect.fromLTRB( - widget.timeLabelWidth + - (appointmentView.startIndex * cellWidth), - kAllDayAppointmentHeight * appointmentView.position, - (appointmentView.endIndex * cellWidth) + - widget.timeLabelWidth - - cellEndPadding, - (kAllDayAppointmentHeight * appointmentView.position) + - kAllDayAppointmentHeight - - 1), - const Radius.circular(cornerRadius)); + Rect.fromLTRB( + widget.timeLabelWidth + (appointmentView.startIndex * cellWidth), + kAllDayAppointmentHeight * appointmentView.position, + (appointmentView.endIndex * cellWidth) + + widget.timeLabelWidth - + cellEndPadding, + (kAllDayAppointmentHeight * appointmentView.position) + + kAllDayAppointmentHeight - + 1, + ), + const Radius.circular(cornerRadius), + ); } - for (int j = appointmentView.startIndex; - j < appointmentView.endIndex; - j++) { + for ( + int j = appointmentView.startIndex; + j < appointmentView.endIndex; + j++ + ) { List appointmentViews; if (_indexAppointments.containsKey(j)) { appointmentViews = _indexAppointments[j]!; @@ -358,13 +382,15 @@ class _AllDayAppointmentLayoutState extends State { if (_appointmentCollection.isNotEmpty) { /// Calculate the maximum appointment position of all the appointment /// views in the widget. - maxPosition = _appointmentCollection - .reduce( - (AppointmentView currentAppView, AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + maxPosition = + _appointmentCollection + .reduce( + (AppointmentView currentAppView, AppointmentView nextAppView) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; } if (maxPosition == -1) { @@ -382,13 +408,18 @@ class _AllDayAppointmentLayoutState extends State { int count = 0; if (appointmentViews.isNotEmpty) { /// Calculate the current index appointments max position. - maxPosition = appointmentViews - .reduce((AppointmentView currentAppView, - AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + maxPosition = + appointmentViews + .reduce( + ( + AppointmentView currentAppView, + AppointmentView nextAppView, + ) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; } if (maxPosition <= position) { continue; @@ -423,28 +454,28 @@ class _AllDayAppointmentLayoutState extends State { class _AllDayAppointmentRenderWidget extends MultiChildRenderObjectWidget { const _AllDayAppointmentRenderWidget( - this.calendar, - this.view, - this.visibleDates, - this.visibleAppointments, - this.timeLabelWidth, - this.allDayPainterHeight, - this.isExpandable, - this.isExpanding, - this.isRTL, - this.calendarTheme, - this.themeData, - this.repaintNotifier, - this.allDayHoverPosition, - this.textScaleFactor, - this.isMobilePlatform, - this.width, - this.height, - this.localizations, - this.appointmentCollection, - this.moreAppointmentIndex, - {List widgets = const []}) - : super(children: widgets); + this.calendar, + this.view, + this.visibleDates, + this.visibleAppointments, + this.timeLabelWidth, + this.allDayPainterHeight, + this.isExpandable, + this.isExpanding, + this.isRTL, + this.calendarTheme, + this.themeData, + this.repaintNotifier, + this.allDayHoverPosition, + this.textScaleFactor, + this.isMobilePlatform, + this.width, + this.height, + this.localizations, + this.appointmentCollection, + this.moreAppointmentIndex, { + List widgets = const [], + }) : super(children: widgets); final SfCalendar calendar; final CalendarView view; final List visibleDates; @@ -469,31 +500,34 @@ class _AllDayAppointmentRenderWidget extends MultiChildRenderObjectWidget { @override _AllDayAppointmentRenderObject createRenderObject(BuildContext context) { return _AllDayAppointmentRenderObject( - calendar, - view, - visibleDates, - visibleAppointments, - timeLabelWidth, - allDayPainterHeight, - isExpandable, - isExpanding, - isRTL, - calendarTheme, - themeData, - repaintNotifier, - allDayHoverPosition, - textScaleFactor, - isMobilePlatform, - width, - height, - localizations, - appointmentCollection, - moreAppointmentIndex); + calendar, + view, + visibleDates, + visibleAppointments, + timeLabelWidth, + allDayPainterHeight, + isExpandable, + isExpanding, + isRTL, + calendarTheme, + themeData, + repaintNotifier, + allDayHoverPosition, + textScaleFactor, + isMobilePlatform, + width, + height, + localizations, + appointmentCollection, + moreAppointmentIndex, + ); } @override void updateRenderObject( - BuildContext context, _AllDayAppointmentRenderObject renderObject) { + BuildContext context, + _AllDayAppointmentRenderObject renderObject, + ) { renderObject ..appointmentCollection = appointmentCollection ..moreAppointmentIndex = moreAppointmentIndex @@ -520,26 +554,27 @@ class _AllDayAppointmentRenderWidget extends MultiChildRenderObjectWidget { class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { _AllDayAppointmentRenderObject( - this.calendar, - this._view, - this._visibleDates, - this._visibleAppointments, - this._timeLabelWidth, - this._allDayPainterHeight, - this._isExpandable, - this.isExpanding, - this._isRTL, - this._calendarTheme, - this._themeData, - this._selectionNotifier, - this._allDayHoverPosition, - this._textScaleFactor, - this.isMobilePlatform, - this._width, - this._height, - this._localizations, - this.appointmentCollection, - this.moreAppointmentIndex); + this.calendar, + this._view, + this._visibleDates, + this._visibleAppointments, + this._timeLabelWidth, + this._allDayPainterHeight, + this._isExpandable, + this.isExpanding, + this._isRTL, + this._calendarTheme, + this._themeData, + this._selectionNotifier, + this._allDayHoverPosition, + this._textScaleFactor, + this.isMobilePlatform, + this._width, + this._height, + this._localizations, + this.appointmentCollection, + this.moreAppointmentIndex, + ); SfCalendar calendar; bool isMobilePlatform; @@ -790,12 +825,16 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { List? _cacheNodes; final Paint _rectPainter = Paint(); final TextPainter _textPainter = TextPainter( - textDirection: TextDirection.ltr, - maxLines: 1, - textAlign: TextAlign.left, - textWidthBasis: TextWidthBasis.longestLine); + textDirection: TextDirection.ltr, + maxLines: 1, + textAlign: TextAlign.left, + textWidthBasis: TextWidthBasis.longestLine, + ); final TextPainter _expanderTextPainter = TextPainter( - textDirection: TextDirection.ltr, textAlign: TextAlign.left, maxLines: 1); + textDirection: TextDirection.ltr, + textAlign: TextAlign.left, + maxLines: 1, + ); late BoxPainter _boxPainter; bool _isHoveringAppointment = false; int _maxPosition = 0; @@ -866,7 +905,9 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { _cellWidth = (size.width - timeLabelWidth) / visibleDates.length; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - calendar.cellEndPadding, isMobilePlatform); + calendar.cellEndPadding, + isMobilePlatform, + ); final List keys = moreAppointmentIndex.keys.toList(); for (int i = 0; i < keys.length; i++) { if (child == null) { @@ -874,9 +915,11 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { } final int index = keys[i]; - final double leftPosition = isRTL - ? ((visibleDates.length - index - 1) * _cellWidth) + cellEndPadding - : timeLabelWidth + (index * _cellWidth); + final double leftPosition = + isRTL + ? ((visibleDates.length - index - 1) * _cellWidth) + + cellEndPadding + : timeLabelWidth + (index * _cellWidth); final Offset offset = Offset(leftPosition, maximumBottomPosition); final bool isHit = result.addWithPaintOffset( offset: offset, @@ -906,8 +949,10 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; final int position = allDayPainterHeight ~/ kAllDayAppointmentHeight; final double maximumBottomPosition = @@ -937,22 +982,29 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { continue; } - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: appointmentRect.height, maxHeight: appointmentRect.height, minWidth: appointmentRect.width, - maxWidth: appointmentRect.width)); + maxWidth: appointmentRect.width, + ), + ); final CalendarParentData childParentData = child.parentData! as CalendarParentData; - childParentData.offset = - Offset(appointmentRect.left, appointmentRect.top); + childParentData.offset = Offset( + appointmentRect.left, + appointmentRect.top, + ); child = childAfter(child); } _cellWidth = (size.width - timeLabelWidth) / visibleDates.length; const double appointmentHeight = kAllDayAppointmentHeight - 1; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - calendar.cellEndPadding, isMobilePlatform); + calendar.cellEndPadding, + isMobilePlatform, + ); final double maxAppointmentWidth = _cellWidth - cellEndPadding; final List keys = moreAppointmentIndex.keys.toList(); for (int i = 0; i < keys.length; i++) { @@ -960,17 +1012,22 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { continue; } - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: appointmentHeight, maxHeight: appointmentHeight, minWidth: maxAppointmentWidth, - maxWidth: maxAppointmentWidth)); + maxWidth: maxAppointmentWidth, + ), + ); final CalendarParentData childParentData = child.parentData! as CalendarParentData; final int index = keys[i]; - final double leftPosition = isRTL - ? ((visibleDates.length - index - 1) * _cellWidth) + cellEndPadding - : timeLabelWidth + (index * _cellWidth); + final double leftPosition = + isRTL + ? ((visibleDates.length - index - 1) * _cellWidth) + + cellEndPadding + : timeLabelWidth + (index * _cellWidth); childParentData.offset = Offset(leftPosition, maximumBottomPosition); child = childAfter(child); } @@ -981,57 +1038,70 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { _textPainter.textScaler = TextScaler.linear(textScaleFactor); double leftPosition = 0, rightPosition = size.width; if (CalendarViewHelper.isDayView( - view, - calendar.timeSlotViewSettings.numberOfDaysInView, - calendar.timeSlotViewSettings.nonWorkingDays, - calendar.monthViewSettings.numberOfWeeksInView)) { + view, + calendar.timeSlotViewSettings.numberOfDaysInView, + calendar.timeSlotViewSettings.nonWorkingDays, + calendar.monthViewSettings.numberOfWeeksInView, + )) { _rectPainter.strokeWidth = 0.5; _rectPainter.color = calendar.cellBorderColor ?? calendarTheme.cellBorderColor!; //// Decrease the x position by 0.5 because draw the end point of the view /// draws half of the line to current view and hides another half. context.canvas.drawLine( - Offset( - isRTL ? size.width - timeLabelWidth + 0.5 : timeLabelWidth - 0.5, - 0), - Offset( - isRTL ? size.width - timeLabelWidth + 0.5 : timeLabelWidth - 0.5, - size.height), - _rectPainter); + Offset( + isRTL ? size.width - timeLabelWidth + 0.5 : timeLabelWidth - 0.5, + 0, + ), + Offset( + isRTL ? size.width - timeLabelWidth + 0.5 : timeLabelWidth - 0.5, + size.height, + ), + _rectPainter, + ); leftPosition = isRTL ? 0 : timeLabelWidth; rightPosition = isRTL ? size.width - timeLabelWidth : size.width; final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - calendar.viewHeaderHeight, view); - _rectPainter.color = calendar.timeSlotViewSettings.allDayPanelColor ?? + calendar.viewHeaderHeight, + view, + ); + _rectPainter.color = + calendar.timeSlotViewSettings.allDayPanelColor ?? calendarTheme.allDayPanelColor!; context.canvas.drawRect( - Rect.fromLTRB( - isRTL ? size.width - timeLabelWidth : 0, - viewHeaderHeight, - isRTL ? size.width : timeLabelWidth, - size.height), - _rectPainter); + Rect.fromLTRB( + isRTL ? size.width - timeLabelWidth : 0, + viewHeaderHeight, + isRTL ? size.width : timeLabelWidth, + size.height, + ), + _rectPainter, + ); } - _rectPainter.color = calendar.timeSlotViewSettings.allDayPanelColor ?? + _rectPainter.color = + calendar.timeSlotViewSettings.allDayPanelColor ?? calendarTheme.allDayPanelColor!; context.canvas.drawRect( - Rect.fromLTRB(leftPosition, 0, rightPosition, size.height), - _rectPainter); + Rect.fromLTRB(leftPosition, 0, rightPosition, size.height), + _rectPainter, + ); _rectPainter.isAntiAlias = true; _cellWidth = (size.width - timeLabelWidth) / visibleDates.length; const double textPadding = 3; _maxPosition = 0; if (appointmentCollection.isNotEmpty) { - _maxPosition = appointmentCollection - .reduce( - (AppointmentView currentAppView, AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + _maxPosition = + appointmentCollection + .reduce( + (AppointmentView currentAppView, AppointmentView nextAppView) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; } if (_maxPosition == -1) { @@ -1099,17 +1169,20 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { final double endYPosition = allDayPainterHeight - kAllDayAppointmentHeight; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - calendar.cellEndPadding, isMobilePlatform); + calendar.cellEndPadding, + isMobilePlatform, + ); final List keys = moreAppointmentIndex.keys.toList(); for (final int index in keys) { if (child == null) { continue; } - final double xPosition = isRTL - ? ((visibleDates.length - index - 1) * _cellWidth) + - cellEndPadding - : timeLabelWidth + (index * _cellWidth); + final double xPosition = + isRTL + ? ((visibleDates.length - index - 1) * _cellWidth) + + cellEndPadding + : timeLabelWidth + (index * _cellWidth); context.paintChild(child, Offset(xPosition, endYPosition)); child = childAfter(child); } @@ -1133,16 +1206,20 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { /// appointment. String _getAllDayAppointmentText(CalendarAppointment appointment) { if (!CalendarViewHelper.isDayView( - view, - calendar.timeSlotViewSettings.numberOfDaysInView, - calendar.timeSlotViewSettings.nonWorkingDays, - calendar.monthViewSettings.numberOfWeeksInView) || + view, + calendar.timeSlotViewSettings.numberOfDaysInView, + calendar.timeSlotViewSettings.nonWorkingDays, + calendar.monthViewSettings.numberOfWeeksInView, + ) || !appointment.isSpanned) { return appointment.subject; } return AppointmentHelper.getSpanAppointmentText( - appointment, visibleDates[0], _localizations); + appointment, + visibleDates[0], + _localizations, + ); } double _getTextSize(RRect rect, double textSize) { @@ -1154,40 +1231,56 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { } void _addForwardSpanIconForAllDay( - Canvas canvas, - RRect rect, - double iconTextSize, - double forwardIconSize, - TextStyle appointmentTextStyle) { + Canvas canvas, + RRect rect, + double iconTextSize, + double forwardIconSize, + TextStyle appointmentTextStyle, + ) { final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, iconTextSize, !isRTL); + appointmentTextStyle.color!, + iconTextSize, + !isRTL, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: rect.width >= 0 ? rect.width : 0); - final double yPosition = - AppointmentHelper.getYPositionForSpanIcon(icon, _textPainter, rect); + final double yPosition = AppointmentHelper.getYPositionForSpanIcon( + icon, + _textPainter, + rect, + ); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - isRTL ? rect.left : rect.right - forwardIconSize, - rect.top, - isRTL ? rect.left + forwardIconSize : rect.right, - rect.bottom), - rect.brRadius), - _rectPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + isRTL ? rect.left : rect.right - forwardIconSize, + rect.top, + isRTL ? rect.left + forwardIconSize : rect.right, + rect.bottom, + ), + rect.brRadius, + ), + _rectPainter, + ); double iconPadding = (forwardIconSize - _textPainter.width) / 2; if (iconPadding < 0) { iconPadding = 0; } _textPainter.paint( - canvas, - Offset((isRTL ? rect.left : rect.right - forwardIconSize) + iconPadding, - yPosition)); + canvas, + Offset( + (isRTL ? rect.left : rect.right - forwardIconSize) + iconPadding, + yPosition, + ), + ); } void _drawAllDayAppointmentView( - PaintingContext context, Offset offset, AppointmentView appointmentView) { + PaintingContext context, + Offset offset, + AppointmentView appointmentView, + ) { final CalendarAppointment appointment = appointmentView.appointment!; final RRect rect = appointmentView.appointmentRect!; @@ -1196,13 +1289,19 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { final TextStyle appointmentTextStyle = AppointmentHelper.getAppointmentTextStyle( - calendar.appointmentTextStyle, view, themeData); + calendar.appointmentTextStyle, + view, + themeData, + ); final double iconTextSize = _getTextSize( - rect, _textPainter.textScaler.scale(appointmentTextStyle.fontSize!)); + rect, + _textPainter.textScaler.scale(appointmentTextStyle.fontSize!), + ); const double iconPadding = 2; //// Padding 4 is left and right 2 padding. final double iconSize = iconTextSize + (2 * iconPadding); - final bool isRecurrenceAppointment = appointment.recurrenceRule != null && + final bool isRecurrenceAppointment = + appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty; final double recurrenceIconSize = isRecurrenceAppointment || appointment.recurrenceId != null @@ -1211,20 +1310,33 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { double forwardSpanIconSize = 0; double backwardSpanIconSize = 0; - final bool canAddSpanIcon = - AppointmentHelper.canAddSpanIcon(visibleDates, appointment, view); + final bool canAddSpanIcon = AppointmentHelper.canAddSpanIcon( + visibleDates, + appointment, + view, + ); if (canAddSpanIcon) { final DateTime appStartTime = appointment.exactStartTime; final DateTime appEndTime = appointment.exactEndTime; - final DateTime viewStartDate = - AppointmentHelper.convertToStartTime(visibleDates[0]); + final DateTime viewStartDate = AppointmentHelper.convertToStartTime( + visibleDates[0], + ); final DateTime viewEndDate = AppointmentHelper.convertToEndTime( - visibleDates[visibleDates.length - 1]); + visibleDates[visibleDates.length - 1], + ); if (AppointmentHelper.canAddForwardSpanIcon( - appStartTime, appEndTime, viewStartDate, viewEndDate)) { + appStartTime, + appEndTime, + viewStartDate, + viewEndDate, + )) { forwardSpanIconSize = iconSize; } else if (AppointmentHelper.canAddBackwardSpanIcon( - appStartTime, appEndTime, viewStartDate, viewEndDate)) { + appStartTime, + appEndTime, + viewStartDate, + viewEndDate, + )) { backwardSpanIconSize = iconSize; } else { forwardSpanIconSize = iconSize; @@ -1241,72 +1353,103 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { recurrenceIconSize + forwardSpanIconSize + backwardSpanIconSize; const double textPadding = 1; _textPainter.layout( - maxWidth: rect.width - totalIconSize - (2 * textPadding) >= 0 - ? rect.width - totalIconSize - (2 * textPadding) - : 0); + maxWidth: + rect.width - totalIconSize - (2 * textPadding) >= 0 + ? rect.width - totalIconSize - (2 * textPadding) + : 0, + ); if (_textPainter.maxLines == 1 && _textPainter.height > rect.height) { return; } - final double xPosition = isRTL - ? rect.right - _textPainter.width - backwardSpanIconSize - textPadding - : rect.left + backwardSpanIconSize + textPadding; - _textPainter.paint(context.canvas, - Offset(xPosition, rect.top + (rect.height - _textPainter.height) / 2)); + final double xPosition = + isRTL + ? rect.right - + _textPainter.width - + backwardSpanIconSize - + textPadding + : rect.left + backwardSpanIconSize + textPadding; + _textPainter.paint( + context.canvas, + Offset(xPosition, rect.top + (rect.height - _textPainter.height) / 2), + ); if (backwardSpanIconSize != 0) { - _addBackwardSpanIconForAllDay(context.canvas, rect, iconTextSize, - backwardSpanIconSize, appointmentTextStyle); + _addBackwardSpanIconForAllDay( + context.canvas, + rect, + iconTextSize, + backwardSpanIconSize, + appointmentTextStyle, + ); } if (recurrenceIconSize != 0) { _addRecurrenceIcon( - context.canvas, - rect, - isRecurrenceAppointment, - iconTextSize, - recurrenceIconSize, - forwardSpanIconSize, - appointmentTextStyle); + context.canvas, + rect, + isRecurrenceAppointment, + iconTextSize, + recurrenceIconSize, + forwardSpanIconSize, + appointmentTextStyle, + ); } if (forwardSpanIconSize != 0) { - _addForwardSpanIconForAllDay(context.canvas, rect, iconTextSize, - forwardSpanIconSize, appointmentTextStyle); + _addForwardSpanIconForAllDay( + context.canvas, + rect, + iconTextSize, + forwardSpanIconSize, + appointmentTextStyle, + ); } } void _addBackwardSpanIconForAllDay( - Canvas canvas, - RRect rect, - double iconTextSize, - double backwardIconSize, - TextStyle appointmentTextStyle) { + Canvas canvas, + RRect rect, + double iconTextSize, + double backwardIconSize, + TextStyle appointmentTextStyle, + ) { final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, iconTextSize, isRTL); + appointmentTextStyle.color!, + iconTextSize, + isRTL, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: rect.width >= 0 ? rect.width : 0); - final double yPosition = - AppointmentHelper.getYPositionForSpanIcon(icon, _textPainter, rect); + final double yPosition = AppointmentHelper.getYPositionForSpanIcon( + icon, + _textPainter, + rect, + ); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - isRTL ? rect.right - backwardIconSize : rect.left, - rect.top, - isRTL ? rect.right : rect.left + iconTextSize, - rect.bottom), - rect.brRadius), - _rectPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + isRTL ? rect.right - backwardIconSize : rect.left, + rect.top, + isRTL ? rect.right : rect.left + iconTextSize, + rect.bottom, + ), + rect.brRadius, + ), + _rectPainter, + ); double iconPadding = (backwardIconSize - _textPainter.width) / 2; if (iconPadding < 0) { iconPadding = 0; } _textPainter.paint( - canvas, - Offset( - (isRTL ? rect.right - backwardIconSize : rect.left) + iconPadding, - yPosition)); + canvas, + Offset( + (isRTL ? rect.right - backwardIconSize : rect.left) + iconPadding, + yPosition, + ), + ); } void _addExpanderText(Canvas canvas, int position, double textPadding) { @@ -1320,49 +1463,55 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { ); _textPainter.text = span; _textPainter.layout( - maxWidth: - _cellWidth - textPadding >= 0 ? _cellWidth - textPadding : 0); + maxWidth: _cellWidth - textPadding >= 0 ? _cellWidth - textPadding : 0, + ); _textPainter.paint( - canvas, - Offset( - isRTL - ? ((visibleDates.length - index) * _cellWidth) - - _textPainter.width - - textPadding - : timeLabelWidth + (index * _cellWidth) + textPadding, - endYPosition + - ((kAllDayAppointmentHeight - _textPainter.height) / 2))); + canvas, + Offset( + isRTL + ? ((visibleDates.length - index) * _cellWidth) - + _textPainter.width - + textPadding + : timeLabelWidth + (index * _cellWidth) + textPadding, + endYPosition + ((kAllDayAppointmentHeight - _textPainter.height) / 2), + ), + ); } } void _addExpandOrCollapseIcon(Canvas canvas, Size size, int position) { - final int iconCodePoint = _maxPosition <= position - ? Icons.expand_less.codePoint - : Icons.expand_more.codePoint; + final int iconCodePoint = + _maxPosition <= position + ? Icons.expand_less.codePoint + : Icons.expand_more.codePoint; final TextSpan icon = TextSpan( - text: String.fromCharCode(iconCodePoint), - style: TextStyle( - color: calendarTheme.viewHeaderDayTextStyle!.color, - fontSize: calendar.viewHeaderStyle.dayTextStyle != null && - calendar.viewHeaderStyle.dayTextStyle!.fontSize != null - ? calendar.viewHeaderStyle.dayTextStyle!.fontSize! * 2 - : kAllDayAppointmentHeight + 5, - fontFamily: 'MaterialIcons', - )); + text: String.fromCharCode(iconCodePoint), + style: TextStyle( + color: calendarTheme.viewHeaderDayTextStyle!.color, + fontSize: + calendar.viewHeaderStyle.dayTextStyle != null && + calendar.viewHeaderStyle.dayTextStyle!.fontSize != null + ? calendar.viewHeaderStyle.dayTextStyle!.fontSize! * 2 + : kAllDayAppointmentHeight + 5, + fontFamily: 'MaterialIcons', + ), + ); _expanderTextPainter.textScaler = TextScaler.linear(textScaleFactor); _expanderTextPainter.text = icon; _expanderTextPainter.layout(maxWidth: timeLabelWidth); _expanderTextPainter.paint( - canvas, - Offset( - isRTL - ? (size.width - timeLabelWidth) + - ((timeLabelWidth - _expanderTextPainter.width) / 2) - : (timeLabelWidth - _expanderTextPainter.width) / 2, - allDayPainterHeight - - kAllDayAppointmentHeight + - (kAllDayAppointmentHeight - _expanderTextPainter.height) / 2)); + canvas, + Offset( + isRTL + ? (size.width - timeLabelWidth) + + ((timeLabelWidth - _expanderTextPainter.width) / 2) + : (timeLabelWidth - _expanderTextPainter.width) / 2, + allDayPainterHeight - + kAllDayAppointmentHeight + + (kAllDayAppointmentHeight - _expanderTextPainter.height) / 2, + ), + ); } void _addMouseHoveringForAllDayPanel(Canvas canvas, Size size) { @@ -1371,20 +1520,26 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { } final int rowIndex = (allDayHoverPosition.value!.dx - (isRTL ? 0 : timeLabelWidth)) ~/ - _cellWidth; + _cellWidth; final double leftPosition = (rowIndex * _cellWidth) + (isRTL ? 0 : timeLabelWidth); _rectPainter.color = Colors.grey.withValues(alpha: 0.1); canvas.drawRect( - Rect.fromLTWH(leftPosition, 0, _cellWidth, size.height), _rectPainter); + Rect.fromLTWH(leftPosition, 0, _cellWidth, size.height), + _rectPainter, + ); } void _addSelectionForAllDayPanel(Canvas canvas, Size size) { final int index = DateTimeHelper.getIndex( - visibleDates, selectionNotifier.value!.selectedDate!); + visibleDates, + selectionNotifier.value!.selectedDate!, + ); Decoration? selectionDecoration = calendar.selectionDecoration; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - calendar.cellEndPadding, isMobilePlatform); + calendar.cellEndPadding, + isMobilePlatform, + ); /// Set the default selection decoration background color with opacity /// value based on theme brightness when selected date hold all day @@ -1395,11 +1550,14 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { appointmentView.startIndex <= index && appointmentView.endIndex > index) { selectionDecoration ??= BoxDecoration( - color: themeData.brightness == Brightness.light - ? Colors.white.withValues(alpha: 0.3) - : Colors.black.withValues(alpha: 0.4), - border: - Border.all(color: calendarTheme.selectionBorderColor!, width: 2), + color: + themeData.brightness == Brightness.light + ? Colors.white.withValues(alpha: 0.3) + : Colors.black.withValues(alpha: 0.4), + border: Border.all( + color: calendarTheme.selectionBorderColor!, + width: 2, + ), borderRadius: const BorderRadius.all(Radius.circular(2)), ); @@ -1419,17 +1577,29 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { double xValue = timeLabelWidth + (index * _cellWidth); if (isRTL) { xValue = size.width - xValue - _cellWidth; - rect = Rect.fromLTRB(xValue + cellEndPadding, 0, xValue + _cellWidth, - kAllDayAppointmentHeight - 1); + rect = Rect.fromLTRB( + xValue + cellEndPadding, + 0, + xValue + _cellWidth, + kAllDayAppointmentHeight - 1, + ); } else { - rect = Rect.fromLTRB(xValue, 0, xValue + _cellWidth - cellEndPadding, - kAllDayAppointmentHeight - 1); + rect = Rect.fromLTRB( + xValue, + 0, + xValue + _cellWidth - cellEndPadding, + kAllDayAppointmentHeight - 1, + ); } - _boxPainter = - selectionDecoration.createBoxPainter(_updateSelectionDecorationPainter); - _boxPainter.paint(canvas, Offset(rect.left, rect.top), - ImageConfiguration(size: rect.size)); + _boxPainter = selectionDecoration.createBoxPainter( + _updateSelectionDecorationPainter, + ); + _boxPainter.paint( + canvas, + Offset(rect.left, rect.top), + ImageConfiguration(size: rect.size), + ); selectionDecoration = null; } @@ -1438,12 +1608,15 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { /// decoration have asynchronous data like image. void _updateSelectionDecorationPainter() { selectionNotifier.value = AllDayPanelSelectionDetails( - selectionNotifier.value!.appointmentView, - selectionNotifier.value!.selectedDate); + selectionNotifier.value!.appointmentView, + selectionNotifier.value!.selectedDate, + ); } void _addSelectionForAppointment( - Canvas canvas, AppointmentView appointmentView) { + Canvas canvas, + AppointmentView appointmentView, + ) { Decoration? selectionDecoration = calendar.selectionDecoration; selectionDecoration ??= BoxDecoration( color: Colors.transparent, @@ -1453,10 +1626,14 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { Rect rect = appointmentView.appointmentRect!.outerRect; rect = Rect.fromLTRB(rect.left, rect.top, rect.right, rect.bottom); - _boxPainter = - selectionDecoration.createBoxPainter(_updateSelectionDecorationPainter); - _boxPainter.paint(canvas, Offset(rect.left, rect.top), - ImageConfiguration(size: rect.size)); + _boxPainter = selectionDecoration.createBoxPainter( + _updateSelectionDecorationPainter, + ); + _boxPainter.paint( + canvas, + Offset(rect.left, rect.top), + ImageConfiguration(size: rect.size), + ); } void _addMouseHoveringForAppointment(Canvas canvas, RRect rect) { @@ -1468,8 +1645,9 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { rect.right > allDayHoverPosition.value!.dx && rect.top < allDayHoverPosition.value!.dy && rect.bottom > allDayHoverPosition.value!.dy) { - _rectPainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + _rectPainter.color = calendarTheme.selectionBorderColor!.withValues( + alpha: 0.4, + ); _rectPainter.strokeWidth = 2; _rectPainter.style = PaintingStyle.stroke; canvas.drawRRect(rect, _rectPainter); @@ -1479,44 +1657,53 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { } void _addRecurrenceIcon( - Canvas canvas, - RRect rect, - bool isRecurrenceAppointment, - double iconTextSize, - double recurrenceIconSize, - double forwardSpanIconSize, - TextStyle appointmentTextStyle) { + Canvas canvas, + RRect rect, + bool isRecurrenceAppointment, + double iconTextSize, + double recurrenceIconSize, + double forwardSpanIconSize, + TextStyle appointmentTextStyle, + ) { final TextSpan icon = AppointmentHelper.getRecurrenceIcon( - appointmentTextStyle.color!, iconTextSize, isRecurrenceAppointment); + appointmentTextStyle.color!, + iconTextSize, + isRecurrenceAppointment, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: rect.width >= 0 ? rect.width : 0); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - isRTL - ? rect.left + forwardSpanIconSize - : rect.right - recurrenceIconSize - forwardSpanIconSize, - rect.top, - isRTL - ? rect.left + recurrenceIconSize + forwardSpanIconSize - : rect.right - forwardSpanIconSize, - rect.bottom), - rect.brRadius), - _rectPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + isRTL + ? rect.left + forwardSpanIconSize + : rect.right - recurrenceIconSize - forwardSpanIconSize, + rect.top, + isRTL + ? rect.left + recurrenceIconSize + forwardSpanIconSize + : rect.right - forwardSpanIconSize, + rect.bottom, + ), + rect.brRadius, + ), + _rectPainter, + ); double iconPadding = (recurrenceIconSize - _textPainter.width) / 2; if (iconPadding < 0) { iconPadding = 0; } _textPainter.paint( - canvas, - Offset( - (isRTL - ? rect.left + forwardSpanIconSize - : rect.right - recurrenceIconSize - forwardSpanIconSize) + - iconPadding, - rect.top + (rect.height - _textPainter.height) / 2)); + canvas, + Offset( + (isRTL + ? rect.left + forwardSpanIconSize + : rect.right - recurrenceIconSize - forwardSpanIconSize) + + iconPadding, + rect.top + (rect.height - _textPainter.height) / 2, + ), + ); } @override @@ -1536,9 +1723,10 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { final List semanticsNodes = []; for (int i = 0; i < semantics.length; i++) { final CustomPainterSemantics currentSemantics = semantics[i]; - final SemanticsNode newChild = _cacheNodes!.isNotEmpty - ? _cacheNodes!.removeAt(0) - : SemanticsNode(key: currentSemantics.key); + final SemanticsNode newChild = + _cacheNodes!.isNotEmpty + ? _cacheNodes!.removeAt(0) + : SemanticsNode(key: currentSemantics.key); final SemanticsProperties properties = currentSemantics.properties; final SemanticsConfiguration config = SemanticsConfiguration(); @@ -1594,16 +1782,23 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { if (isExpandable) { final double left = isRTL ? size.width - timeLabelWidth : 0; final double top = allDayPainterHeight - kAllDayAppointmentHeight; - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, isRTL ? size.width : timeLabelWidth, - _expanderTextPainter.height), - properties: SemanticsProperties( - label: _maxPosition <= allDayPainterHeight ~/ kAllDayAppointmentHeight - ? 'Collapse all day section' - : 'Expand all day section', - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + left, + top, + isRTL ? size.width : timeLabelWidth, + _expanderTextPainter.height, + ), + properties: SemanticsProperties( + label: + _maxPosition <= allDayPainterHeight ~/ kAllDayAppointmentHeight + ? 'Collapse all day section' + : 'Expand all day section', + textDirection: TextDirection.ltr, + ), ), - )); + ); } if (isExpandable && @@ -1611,19 +1806,22 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { !isExpanding) { final List keys = moreAppointmentIndex.keys.toList(); for (final int index in keys) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH( + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( isRTL ? ((visibleDates.length - index) * _cellWidth) - _cellWidth : timeLabelWidth + (index * _cellWidth), bottom, _cellWidth, - kAllDayAppointmentHeight), - properties: SemanticsProperties( - label: '+${moreAppointmentIndex[index]}', - textDirection: TextDirection.ltr, + kAllDayAppointmentHeight, + ), + properties: SemanticsProperties( + label: '+${moreAppointmentIndex[index]}', + textDirection: TextDirection.ltr, + ), ), - )); + ); } } @@ -1637,14 +1835,17 @@ class _AllDayAppointmentRenderObject extends CustomCalendarRenderObject { continue; } - semanticsBuilder.add(CustomPainterSemantics( - rect: view.appointmentRect!.outerRect, - properties: SemanticsProperties( - label: - CalendarViewHelper.getAppointmentSemanticsText(view.appointment!), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: view.appointmentRect!.outerRect, + properties: SemanticsProperties( + label: CalendarViewHelper.getAppointmentSemanticsText( + view.appointment!, + ), + textDirection: TextDirection.ltr, + ), ), - )); + ); } return semanticsBuilder; diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/appointment_layout.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/appointment_layout.dart index 0458f78db..a51c09531 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/appointment_layout.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/appointment_layout/appointment_layout.dart @@ -21,25 +21,25 @@ class AppointmentLayout extends StatefulWidget { /// Constructor to create the appointment layout that holds the appointment /// views in calendar widget. const AppointmentLayout( - this.calendar, - this.view, - this.visibleDates, - this.visibleAppointments, - this.timeIntervalHeight, - this.calendarTheme, - this.themeData, - this.isRTL, - this.appointmentHoverPosition, - this.resourceCollection, - this.resourceItemHeight, - this.textScaleFactor, - this.isMobilePlatform, - this.width, - this.height, - this.localizations, - this.updateCalendarState, - {Key? key}) - : super(key: key); + this.calendar, + this.view, + this.visibleDates, + this.visibleAppointments, + this.timeIntervalHeight, + this.calendarTheme, + this.themeData, + this.isRTL, + this.appointmentHoverPosition, + this.resourceCollection, + this.resourceItemHeight, + this.textScaleFactor, + this.isMobilePlatform, + this.width, + this.height, + this.localizations, + this.updateCalendarState, { + Key? key, + }) : super(key: key); /// Holds the calendar instance used the get the properties of calendar. final SfCalendar calendar; @@ -142,7 +142,10 @@ class _AppointmentLayoutState extends State { void initState() { widget.updateCalendarState(_updateCalendarStateDetails); _weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, widget.width, widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); _updateAppointmentDetails(); widget.visibleAppointments.addListener(_updateVisibleAppointment); @@ -161,9 +164,10 @@ class _AppointmentLayoutState extends State { (widget.resourceCollection != oldWidget.resourceCollection || widget.resourceItemHeight != oldWidget.resourceItemHeight))) { _weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); isAppointmentDetailsUpdated = true; _updateAppointmentDetails(); } @@ -172,8 +176,9 @@ class _AppointmentLayoutState extends State { oldWidget.visibleAppointments.removeListener(_updateVisibleAppointment); widget.visibleAppointments.addListener(_updateVisibleAppointment); if (!CalendarViewHelper.isCollectionEqual( - widget.visibleAppointments.value, - oldWidget.visibleAppointments.value) && + widget.visibleAppointments.value, + oldWidget.visibleAppointments.value, + ) && !isAppointmentDetailsUpdated) { _updateAppointmentDetails(); } @@ -182,9 +187,10 @@ class _AppointmentLayoutState extends State { if (widget.calendar.showWeekNumber != oldWidget.calendar.showWeekNumber && widget.view == CalendarView.month) { _weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); _updateAppointmentDetails(); } @@ -214,28 +220,35 @@ class _AppointmentLayoutState extends State { } final DateTime appStartTime = DateTime( - appointmentView.appointment!.actualStartTime.year, - appointmentView.appointment!.actualStartTime.month, - appointmentView.appointment!.actualStartTime.day); - final DateTime date = appointmentView.startIndex != -1 - ? widget.visibleDates[appointmentView.startIndex] - : appStartTime.isBefore(initialVisibleDate) + appointmentView.appointment!.actualStartTime.year, + appointmentView.appointment!.actualStartTime.month, + appointmentView.appointment!.actualStartTime.day, + ); + final DateTime date = + appointmentView.startIndex != -1 + ? widget.visibleDates[appointmentView.startIndex] + : appStartTime.isBefore(initialVisibleDate) ? initialVisibleDate : appStartTime; final Widget child = widget.calendar.appointmentBuilder!( - context, - CalendarAppointmentDetails( - date, - List.unmodifiable([ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ]), - Rect.fromLTWH( - appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top, - appointmentView.appointmentRect!.width, - appointmentView.appointmentRect!.height))); + context, + CalendarAppointmentDetails( + date, + List.unmodifiable([ + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ]), + Rect.fromLTWH( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + appointmentView.appointmentRect!.width, + appointmentView.appointmentRect!.height, + ), + ), + ); _children.add(RepaintBoundary(child: child)); } @@ -262,15 +275,24 @@ class _AppointmentLayoutState extends State { final DateTime date = widget.visibleDates[index]; final RRect moreRegionRect = _monthAppointmentCountViews[index]!; final Widget child = widget.calendar.appointmentBuilder!( - context, - CalendarAppointmentDetails( - date, - List.unmodifiable( - CalendarViewHelper.getCustomAppointments( - moreAppointments, widget.calendar.dataSource)), - Rect.fromLTWH(moreRegionRect.left, moreRegionRect.top, - moreRegionRect.width, moreRegionRect.height), - isMoreAppointmentRegion: true)); + context, + CalendarAppointmentDetails( + date, + List.unmodifiable( + CalendarViewHelper.getCustomAppointments( + moreAppointments, + widget.calendar.dataSource, + ), + ), + Rect.fromLTWH( + moreRegionRect.left, + moreRegionRect.top, + moreRegionRect.width, + moreRegionRect.height, + ), + isMoreAppointmentRegion: true, + ), + ); /// Throw exception when builder return widget is null. _children.add(RepaintBoundary(child: child)); @@ -279,27 +301,28 @@ class _AppointmentLayoutState extends State { } return _AppointmentRenderWidget( - widget.calendar, - widget.view, - widget.visibleDates, - widget.visibleAppointments.value, - widget.timeIntervalHeight, - widget.calendarTheme, - widget.themeData, - widget.isRTL, - widget.appointmentHoverPosition, - widget.resourceCollection, - widget.resourceItemHeight, - widget.textScaleFactor, - widget.isMobilePlatform, - widget.width, - widget.height, - widget.localizations, - _appointmentCollection, - _indexAppointments, - _monthAppointmentCountViews, - _weekNumberPanelWidth, - widgets: _children); + widget.calendar, + widget.view, + widget.visibleDates, + widget.visibleAppointments.value, + widget.timeIntervalHeight, + widget.calendarTheme, + widget.themeData, + widget.isRTL, + widget.appointmentHoverPosition, + widget.resourceCollection, + widget.resourceItemHeight, + widget.textScaleFactor, + widget.isMobilePlatform, + widget.width, + widget.height, + widget.localizations, + _appointmentCollection, + _indexAppointments, + _monthAppointmentCountViews, + _weekNumberPanelWidth, + widgets: _children, + ); } AppointmentView? _getAppointmentViewOnPoint(double x, double y) { @@ -358,7 +381,8 @@ class _AppointmentLayoutState extends State { /// Remove the appointments before the calendar time slot start date and /// after the calendar time slot end date. List _getValidAppointments( - List visibleAppointments) { + List visibleAppointments, + ) { if (visibleAppointments.isEmpty || widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth) { @@ -368,12 +392,14 @@ class _AppointmentLayoutState extends State { final List appointments = []; final int viewStartHour = widget.calendar.timeSlotViewSettings.startHour.toInt(); - final int viewStartMinutes = (viewStartHour * 60) + + final int viewStartMinutes = + (viewStartHour * 60) + ((widget.calendar.timeSlotViewSettings.startHour - viewStartHour) * 60) .toInt(); final int viewEndHour = widget.calendar.timeSlotViewSettings.endHour.toInt(); - final int viewEndMinutes = (viewEndHour * 60) + + final int viewEndMinutes = + (viewEndHour * 60) + ((widget.calendar.timeSlotViewSettings.endHour - viewEndHour) * 60) .toInt(); @@ -385,14 +411,16 @@ class _AppointmentLayoutState extends State { if (!isSameDate(appointment.actualEndTime, appointment.actualStartTime)) { /// Check the span appointment is start after time slot end hour and /// end before time slot start hour then skip the rendering. - if (isSameDate(appointment.actualEndTime, - appointment.actualStartTime.add(const Duration(days: 1)))) { + if (isSameDate( + appointment.actualEndTime, + appointment.actualStartTime.add(const Duration(days: 1)), + )) { final int appointmentStartMinutes = (appointment.actualStartTime.hour * 60) + - appointment.actualStartTime.minute; + appointment.actualStartTime.minute; final int appointmentEndMinutes = (appointment.actualEndTime.hour * 60) + - appointment.actualEndTime.minute; + appointment.actualEndTime.minute; if (appointmentStartMinutes >= viewEndMinutes && appointmentEndMinutes <= viewStartMinutes) { continue; @@ -404,8 +432,9 @@ class _AppointmentLayoutState extends State { } final int appointmentStartMinutes = (appointment.actualStartTime.hour * 60) + - appointment.actualStartTime.minute; - final int appointmentEndMinutes = (appointment.actualEndTime.hour * 60) + + appointment.actualStartTime.minute; + final int appointmentEndMinutes = + (appointment.actualEndTime.hour * 60) + appointment.actualEndTime.minute; /// Check the appointment before time slot start hour then skip the @@ -439,8 +468,9 @@ class _AppointmentLayoutState extends State { return; } - final List visibleAppointments = - _getValidAppointments(widget.visibleAppointments.value!); + final List visibleAppointments = _getValidAppointments( + widget.visibleAppointments.value!, + ); switch (widget.view) { case CalendarView.month: { @@ -472,7 +502,8 @@ class _AppointmentLayoutState extends State { } void _updateMonthAppointmentDetails( - List visibleAppointments) { + List visibleAppointments, + ) { final double cellWidth = (widget.width - _weekNumberPanelWidth) / DateTime.daysPerWeek; final double cellHeight = @@ -482,45 +513,62 @@ class _AppointmentLayoutState extends State { return; } - double xPosition = widget.isRTL - ? widget.width - cellWidth - _weekNumberPanelWidth - : _weekNumberPanelWidth; + double xPosition = + widget.isRTL + ? widget.width - cellWidth - _weekNumberPanelWidth + : _weekNumberPanelWidth; double yPosition = 0; final int count = widget.visibleDates.length; - DateTime visibleStartDate = - AppointmentHelper.convertToStartTime(widget.visibleDates[0]); - DateTime visibleEndDate = - AppointmentHelper.convertToEndTime(widget.visibleDates[count - 1]); + DateTime visibleStartDate = AppointmentHelper.convertToStartTime( + widget.visibleDates[0], + ); + DateTime visibleEndDate = AppointmentHelper.convertToEndTime( + widget.visibleDates[count - 1], + ); int visibleStartIndex = 0; int visibleEndIndex = count - 1; final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates); + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + ); if (!showTrailingLeadingDates) { final DateTime currentMonthDate = widget.visibleDates[count ~/ 2]; visibleStartDate = AppointmentHelper.convertToStartTime( - AppointmentHelper.getMonthStartDate(currentMonthDate)); + AppointmentHelper.getMonthStartDate(currentMonthDate), + ); visibleEndDate = AppointmentHelper.convertToEndTime( - AppointmentHelper.getMonthEndDate(currentMonthDate)); - visibleStartIndex = - DateTimeHelper.getIndex(widget.visibleDates, visibleStartDate); - visibleEndIndex = - DateTimeHelper.getIndex(widget.visibleDates, visibleEndDate); + AppointmentHelper.getMonthEndDate(currentMonthDate), + ); + visibleStartIndex = DateTimeHelper.getIndex( + widget.visibleDates, + visibleStartDate, + ); + visibleEndIndex = DateTimeHelper.getIndex( + widget.visibleDates, + visibleEndDate, + ); } MonthAppointmentHelper.updateAppointmentDetails( - visibleAppointments, - _appointmentCollection, - widget.visibleDates, - _indexAppointments, - visibleStartIndex, - visibleEndIndex); + visibleAppointments, + _appointmentCollection, + widget.visibleDates, + _indexAppointments, + visibleStartIndex, + visibleEndIndex, + ); final TextStyle style = widget.calendarTheme.todayTextStyle!; - final TextSpan dateText = - TextSpan(text: DateTime.now().day.toString(), style: style); + final TextSpan dateText = TextSpan( + text: DateTime.now().day.toString(), + style: style, + ); _textPainter = _updateTextPainter( - dateText, _textPainter, widget.isRTL, widget.textScaleFactor); + dateText, + _textPainter, + widget.isRTL, + widget.textScaleFactor, + ); /// cell padding and start position calculated by month date cell /// rendering padding and size. @@ -539,7 +587,9 @@ class _AppointmentLayoutState extends State { // right side padding used to add padding on appointment view right side // in month view final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - widget.calendar.cellEndPadding, widget.isMobilePlatform); + widget.calendar.cellEndPadding, + widget.isMobilePlatform, + ); for (int i = 0; i < _appointmentCollection.length; i++) { final AppointmentView appointmentView = _appointmentCollection[i]; if (appointmentView.canReuse || appointmentView.appointment == null) { @@ -551,15 +601,16 @@ class _AppointmentLayoutState extends State { appointmentView.maxPositions == maximumDisplayCount)) { final double appointmentWidth = (appointmentView.endIndex - appointmentView.startIndex + 1) * - cellWidth; + cellWidth; if (widget.isRTL) { xPosition = (6 - (appointmentView.startIndex % DateTime.daysPerWeek)) * - cellWidth; + cellWidth; xPosition -= appointmentWidth - cellWidth; } else { - xPosition = ((appointmentView.startIndex % DateTime.daysPerWeek) * + xPosition = + ((appointmentView.startIndex % DateTime.daysPerWeek) * cellWidth) + _weekNumberPanelWidth; } @@ -567,26 +618,31 @@ class _AppointmentLayoutState extends State { yPosition = (appointmentView.startIndex ~/ DateTime.daysPerWeek) * cellHeight; if (appointmentView.position <= maximumDisplayCount) { - yPosition = yPosition + + yPosition = + yPosition + startPosition + (appointmentHeight * (appointmentView.position - 1)); } else { - yPosition = yPosition + + yPosition = + yPosition + startPosition + (appointmentHeight * (maximumDisplayCount - 1)); } final Radius cornerRadius = Radius.circular( - (appointmentHeight * 0.1) > 2 ? 2 : (appointmentHeight * 0.1)); + (appointmentHeight * 0.1) > 2 ? 2 : (appointmentHeight * 0.1), + ); final RRect rect = RRect.fromRectAndRadius( - Rect.fromLTWH( - widget.isRTL ? xPosition + cellEndPadding : xPosition, - yPosition, - appointmentWidth - cellEndPadding > 0 - ? appointmentWidth - cellEndPadding - : 0, - appointmentHeight > 1 ? appointmentHeight - 1 : 0), - cornerRadius); + Rect.fromLTWH( + widget.isRTL ? xPosition + cellEndPadding : xPosition, + yPosition, + appointmentWidth - cellEndPadding > 0 + ? appointmentWidth - cellEndPadding + : 0, + appointmentHeight > 1 ? appointmentHeight - 1 : 0, + ), + cornerRadius, + ); appointmentView.appointmentRect = rect; } @@ -595,59 +651,72 @@ class _AppointmentLayoutState extends State { final List keys = _indexAppointments.keys.toList(); for (int i = 0; i < keys.length; i++) { final int index = keys[i]; - final int maxPosition = _indexAppointments[index]! - .reduce( - (AppointmentView currentAppView, AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + final int maxPosition = + _indexAppointments[index]! + .reduce( + (AppointmentView currentAppView, AppointmentView nextAppView) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; if (maxPosition <= maximumDisplayCount) { continue; } if (widget.isRTL) { xPosition = (6 - (index % DateTime.daysPerWeek)) * cellWidth; } else { - xPosition = ((index % DateTime.daysPerWeek) * cellWidth) + + xPosition = + ((index % DateTime.daysPerWeek) * cellWidth) + _weekNumberPanelWidth; } - yPosition = ((index ~/ DateTime.daysPerWeek) * cellHeight) + + yPosition = + ((index ~/ DateTime.daysPerWeek) * cellHeight) + cellHeight - appointmentHeight; final RRect moreRegionRect = RRect.fromRectAndRadius( - Rect.fromLTWH( - widget.isRTL ? xPosition + cellEndPadding : xPosition, - yPosition, - cellWidth - cellEndPadding > 0 ? cellWidth - cellEndPadding : 0, - appointmentHeight - 1), - Radius.zero); + Rect.fromLTWH( + widget.isRTL ? xPosition + cellEndPadding : xPosition, + yPosition, + cellWidth - cellEndPadding > 0 ? cellWidth - cellEndPadding : 0, + appointmentHeight - 1, + ), + Radius.zero, + ); _monthAppointmentCountViews[index] = moreRegionRect; } } void _updateDayAppointmentDetails( - List visibleAppointments) { + List visibleAppointments, + ) { final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final double width = widget.width - timeLabelWidth; AppointmentHelper.setAppointmentPositionAndMaxPosition( - _appointmentCollection, - widget.calendar, - widget.view, - visibleAppointments, - false); + _appointmentCollection, + widget.calendar, + widget.view, + visibleAppointments, + false, + ); final int count = widget.visibleDates.length; final double cellWidth = width / count; final double cellHeight = widget.timeIntervalHeight; double xPosition = timeLabelWidth; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - widget.calendar.cellEndPadding, widget.isMobilePlatform); + widget.calendar.cellEndPadding, + widget.isMobilePlatform, + ); final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); final int viewStartHour = widget.calendar.timeSlotViewSettings.startHour.toInt(); final double viewStartMinutes = @@ -673,8 +742,9 @@ class _AppointmentLayoutState extends State { if (column == -1 || appointment.isSpanned || AppointmentHelper.getDifference( - appointment.startTime, appointment.endTime) - .inDays > + appointment.startTime, + appointment.endTime, + ).inDays > 0 || appointment.isAllDay) { continue; @@ -687,27 +757,36 @@ class _AppointmentLayoutState extends State { final double appointmentWidth = (cellWidth - cellEndPadding) / appointmentView.maxPositions; if (widget.isRTL) { - xPosition = column * cellWidth + + xPosition = + column * cellWidth + (appointmentView.position * appointmentWidth) + cellEndPadding; } else { - xPosition = column * cellWidth + + xPosition = + column * cellWidth + (appointmentView.position * appointmentWidth) + timeLabelWidth; } Duration difference = AppointmentHelper.getDifference( - appointment.actualStartTime, appointment.actualEndTime); + appointment.actualStartTime, + appointment.actualEndTime, + ); final double minuteHeight = cellHeight / timeInterval; double yPosition = totalMins * minuteHeight; double height = difference.inMinutes * minuteHeight; if (widget.calendar.timeSlotViewSettings.minimumAppointmentDuration != null && - widget.calendar.timeSlotViewSettings.minimumAppointmentDuration! + widget + .calendar + .timeSlotViewSettings + .minimumAppointmentDuration! .inMinutes > 0) { if (difference < - widget.calendar.timeSlotViewSettings + widget + .calendar + .timeSlotViewSettings .minimumAppointmentDuration! && difference.inMinutes * minuteHeight < widget.calendar.timeSlotViewSettings.timeIntervalHeight) { @@ -762,23 +841,29 @@ class _AppointmentLayoutState extends State { yPosition = 0; } - final Radius cornerRadius = - Radius.circular((height * 0.1) > 2 ? 2 : (height * 0.1)); + final Radius cornerRadius = Radius.circular( + (height * 0.1) > 2 ? 2 : (height * 0.1), + ); final RRect rect = RRect.fromRectAndRadius( - Rect.fromLTWH( - xPosition, - yPosition, - appointmentWidth > 1 ? appointmentWidth - 1 : 0, - height > 1 ? height - 1 : 0), - cornerRadius); + Rect.fromLTWH( + xPosition, + yPosition, + appointmentWidth > 1 ? appointmentWidth - 1 : 0, + height > 1 ? height - 1 : 0, + ), + cornerRadius, + ); appointmentView.appointmentRect = rect; } } void _updateTimelineMonthAppointmentDetails( - List visibleAppointments) { + List visibleAppointments, + ) { final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); /// Filters the appointment for each resource from the visible appointment /// collection, and assign appointment views for all the collections. @@ -791,26 +876,30 @@ class _AppointmentLayoutState extends State { /// appointment collection. final List appointmentForEachResource = visibleAppointments - .where((CalendarAppointment app) => - app.resourceIds != null && - app.resourceIds!.isNotEmpty && - app.resourceIds!.contains(resource.id)) + .where( + (CalendarAppointment app) => + app.resourceIds != null && + app.resourceIds!.isNotEmpty && + app.resourceIds!.contains(resource.id), + ) .toList(); AppointmentHelper.setAppointmentPositionAndMaxPosition( - _appointmentCollection, - widget.calendar, - widget.view, - appointmentForEachResource, - false, - i); - } - } else { - AppointmentHelper.setAppointmentPositionAndMaxPosition( _appointmentCollection, widget.calendar, widget.view, - visibleAppointments, - false); + appointmentForEachResource, + false, + i, + ); + } + } else { + AppointmentHelper.setAppointmentPositionAndMaxPosition( + _appointmentCollection, + widget.calendar, + widget.view, + visibleAppointments, + false, + ); } final int visibleDatesLength = widget.visibleDates.length; @@ -819,11 +908,15 @@ class _AppointmentLayoutState extends State { double xPosition = 0; double yPosition = 0; final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - widget.calendar.cellEndPadding, widget.isMobilePlatform); + widget.calendar.cellEndPadding, + widget.isMobilePlatform, + ); final double slotHeight = isResourceEnabled ? widget.resourceItemHeight! : widget.height; final double timelineAppointmentHeight = _getTimelineAppointmentHeight( - widget.calendar.timeSlotViewSettings, widget.view); + widget.calendar.timeSlotViewSettings, + widget.view, + ); for (int i = 0; i < _appointmentCollection.length; i++) { final AppointmentView appointmentView = _appointmentCollection[i]; if (appointmentView.canReuse || appointmentView.appointment == null) { @@ -834,8 +927,10 @@ class _AppointmentLayoutState extends State { int column = -1; final DateTime startTime = appointment.actualStartTime; - int index = - DateTimeHelper.getVisibleDateIndex(widget.visibleDates, startTime); + int index = DateTimeHelper.getVisibleDateIndex( + widget.visibleDates, + startTime, + ); if (index == -1 && startTime.isBefore(widget.visibleDates[0])) { index = 0; } @@ -868,8 +963,10 @@ class _AppointmentLayoutState extends State { } final DateTime endTime = appointment.actualEndTime; - final Duration difference = - AppointmentHelper.getDifference(startTime, endTime); + final Duration difference = AppointmentHelper.getDifference( + startTime, + endTime, + ); /// The width for the appointment UI, calculated based on the date /// difference between the start and end time of the appointment. @@ -891,13 +988,13 @@ class _AppointmentLayoutState extends State { final bool isSameHour = exactStartTime.hour == exactEndTime.hour; final bool isMultiDaySpanWithinSameMonth = exactStartTime.year == exactEndTime.year && - exactStartTime.month == exactEndTime.month && - (exactStartTime.hour > exactEndTime.hour || - (isSameHour && exactStartTime.minute > exactEndTime.minute) || - (isSameHour && - exactStartTime.minute == exactEndTime.minute && - exactStartTime.second > exactEndTime.second)) && - difference.inSeconds % (24 * 60 * 60) > 0; + exactStartTime.month == exactEndTime.month && + (exactStartTime.hour > exactEndTime.hour || + (isSameHour && exactStartTime.minute > exactEndTime.minute) || + (isSameHour && + exactStartTime.minute == exactEndTime.minute && + exactStartTime.second > exactEndTime.second)) && + difference.inSeconds % (24 * 60 * 60) > 0; /// For span appointment less than 23 hours the difference will fall /// as 0 hence to render the appointment on the next day, added one @@ -911,22 +1008,28 @@ class _AppointmentLayoutState extends State { width = width - cellEndPadding; final Radius cornerRadius = Radius.circular( - (appointmentHeight * 0.1) > 2 ? 2 : (appointmentHeight * 0.1)); + (appointmentHeight * 0.1) > 2 ? 2 : (appointmentHeight * 0.1), + ); final RRect rect = RRect.fromRectAndRadius( - Rect.fromLTWH( - widget.isRTL ? xPosition - width : xPosition, - yPosition, - width > 0 ? width : 0, - appointmentHeight > 1 ? appointmentHeight - 1 : 0), - cornerRadius); + Rect.fromLTWH( + widget.isRTL ? xPosition - width : xPosition, + yPosition, + width > 0 ? width : 0, + appointmentHeight > 1 ? appointmentHeight - 1 : 0, + ), + cornerRadius, + ); appointmentView.appointmentRect = rect; } } void _updateTimelineAppointmentDetails( - List visibleAppointments) { + List visibleAppointments, + ) { final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); /// Filters the appointment for each resource from the visible appointment /// collection, and assign appointment views for all the collections. @@ -939,26 +1042,30 @@ class _AppointmentLayoutState extends State { /// appointment collection. final List appointmentForEachResource = visibleAppointments - .where((CalendarAppointment app) => - app.resourceIds != null && - app.resourceIds!.isNotEmpty && - app.resourceIds!.contains(resource.id)) + .where( + (CalendarAppointment app) => + app.resourceIds != null && + app.resourceIds!.isNotEmpty && + app.resourceIds!.contains(resource.id), + ) .toList(); AppointmentHelper.setAppointmentPositionAndMaxPosition( - _appointmentCollection, - widget.calendar, - widget.view, - appointmentForEachResource, - false, - i); - } - } else { - AppointmentHelper.setAppointmentPositionAndMaxPosition( _appointmentCollection, widget.calendar, widget.view, - visibleAppointments, - false); + appointmentForEachResource, + false, + i, + ); + } + } else { + AppointmentHelper.setAppointmentPositionAndMaxPosition( + _appointmentCollection, + widget.calendar, + widget.view, + visibleAppointments, + false, + ); } final int count = widget.visibleDates.length; @@ -967,18 +1074,24 @@ class _AppointmentLayoutState extends State { double xPosition = 0; double yPosition = 0; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); final double cellEndPadding = CalendarViewHelper.getCellEndPadding( - widget.calendar.cellEndPadding, widget.isMobilePlatform); + widget.calendar.cellEndPadding, + widget.isMobilePlatform, + ); final int viewStartHour = widget.calendar.timeSlotViewSettings.startHour.toInt(); final double viewStartMinutes = (widget.calendar.timeSlotViewSettings.startHour - viewStartHour) * 60; final double timelineAppointmentHeight = _getTimelineAppointmentHeight( - widget.calendar.timeSlotViewSettings, widget.view); - final double slotHeight = isResourceEnabled - ? widget.resourceItemHeight! - cellEndPadding - : widget.height - cellEndPadding; + widget.calendar.timeSlotViewSettings, + widget.view, + ); + final double slotHeight = + isResourceEnabled + ? widget.resourceItemHeight! - cellEndPadding + : widget.height - cellEndPadding; for (int i = 0; i < _appointmentCollection.length; i++) { final AppointmentView appointmentView = _appointmentCollection[i]; if (appointmentView.canReuse || appointmentView.appointment == null) { @@ -1031,17 +1144,24 @@ class _AppointmentLayoutState extends State { /// Assign the end date time value to visible end date and time value /// when the appointment end date value after the visible end date /// value. - endTime = DateTime(visibleEndDate.year, visibleEndDate.month, - visibleEndDate.day, 23, 59, 59); + endTime = DateTime( + visibleEndDate.year, + visibleEndDate.month, + visibleEndDate.day, + 23, + 59, + 59, + ); } if (column == -1 || endColumn == -1) { continue; } - int totalMinutes = (((startTime.hour - viewStartHour) * 60) + - (startTime.minute - viewStartMinutes)) - .toInt(); + int totalMinutes = + (((startTime.hour - viewStartHour) * 60) + + (startTime.minute - viewStartMinutes)) + .toInt(); final double minuteHeight = cellWidth / timeInterval; @@ -1069,9 +1189,10 @@ class _AppointmentLayoutState extends State { yPosition += appointmentView.resourceIndex * widget.resourceItemHeight!; } - totalMinutes = (((endTime.hour - viewStartHour) * 60) + - (endTime.minute - viewStartMinutes)) - .toInt(); + totalMinutes = + (((endTime.hour - viewStartHour) * 60) + + (endTime.minute - viewStartMinutes)) + .toInt(); double endXPosition = endColumn * viewWidth; timePosition = totalMinutes * minuteHeight; if (timePosition < 0) { @@ -1088,29 +1209,40 @@ class _AppointmentLayoutState extends State { null && widget.calendar.timeSlotViewSettings.minimumAppointmentDuration! > AppointmentHelper.getDifference( - appointment.actualStartTime, appointment.actualEndTime)) { + appointment.actualStartTime, + appointment.actualEndTime, + )) { final double minWidth = AppointmentHelper.getAppointmentHeightFromDuration( - widget.calendar.timeSlotViewSettings.minimumAppointmentDuration, - widget.calendar, - widget.timeIntervalHeight); + widget.calendar.timeSlotViewSettings.minimumAppointmentDuration, + widget.calendar, + widget.timeIntervalHeight, + ); width = width > minWidth ? width : minWidth; } final Radius cornerRadius = Radius.circular( - (appointmentHeight * 0.1) > 2 ? 2 : (appointmentHeight * 0.1)); + (appointmentHeight * 0.1) > 2 ? 2 : (appointmentHeight * 0.1), + ); width = width > 1 ? width - 1 : 0; final RRect rect = RRect.fromRectAndRadius( - Rect.fromLTWH(widget.isRTL ? xPosition - width : xPosition, yPosition, - width, appointmentHeight > 1 ? appointmentHeight - 1 : 0), - cornerRadius); + Rect.fromLTWH( + widget.isRTL ? xPosition - width : xPosition, + yPosition, + width, + appointmentHeight > 1 ? appointmentHeight - 1 : 0, + ), + cornerRadius, + ); appointmentView.appointmentRect = rect; } } /// Returns the timeline appointment height based on the settings value. double _getTimelineAppointmentHeight( - TimeSlotViewSettings settings, CalendarView view) { + TimeSlotViewSettings settings, + CalendarView view, + ) { if (settings.timelineAppointmentHeight != -1) { return settings.timelineAppointmentHeight; } @@ -1125,28 +1257,28 @@ class _AppointmentLayoutState extends State { class _AppointmentRenderWidget extends MultiChildRenderObjectWidget { const _AppointmentRenderWidget( - this.calendar, - this.view, - this.visibleDates, - this.visibleAppointments, - this.timeIntervalHeight, - this.calendarTheme, - this.themeData, - this.isRTL, - this.appointmentHoverPosition, - this.resourceCollection, - this.resourceItemHeight, - this.textScaleFactor, - this.isMobilePlatform, - this.width, - this.height, - this.localizations, - this.appointmentCollection, - this.indexAppointments, - this.monthAppointmentCountViews, - this.weekNumberPanelWidth, - {List widgets = const []}) - : super(children: widgets); + this.calendar, + this.view, + this.visibleDates, + this.visibleAppointments, + this.timeIntervalHeight, + this.calendarTheme, + this.themeData, + this.isRTL, + this.appointmentHoverPosition, + this.resourceCollection, + this.resourceItemHeight, + this.textScaleFactor, + this.isMobilePlatform, + this.width, + this.height, + this.localizations, + this.appointmentCollection, + this.indexAppointments, + this.monthAppointmentCountViews, + this.weekNumberPanelWidth, { + List widgets = const [], + }) : super(children: widgets); final SfCalendar calendar; final double weekNumberPanelWidth; @@ -1172,31 +1304,34 @@ class _AppointmentRenderWidget extends MultiChildRenderObjectWidget { @override _AppointmentRenderObject createRenderObject(BuildContext context) { return _AppointmentRenderObject( - calendar, - view, - visibleDates, - visibleAppointments, - timeIntervalHeight, - calendarTheme, - themeData, - isRTL, - appointmentHoverPosition, - resourceCollection, - resourceItemHeight, - textScaleFactor, - isMobilePlatform, - width, - height, - localizations, - appointmentCollection, - indexAppointments, - monthAppointmentCountViews, - weekNumberPanelWidth); + calendar, + view, + visibleDates, + visibleAppointments, + timeIntervalHeight, + calendarTheme, + themeData, + isRTL, + appointmentHoverPosition, + resourceCollection, + resourceItemHeight, + textScaleFactor, + isMobilePlatform, + width, + height, + localizations, + appointmentCollection, + indexAppointments, + monthAppointmentCountViews, + weekNumberPanelWidth, + ); } @override void updateRenderObject( - BuildContext context, _AppointmentRenderObject renderObject) { + BuildContext context, + _AppointmentRenderObject renderObject, + ) { renderObject ..calendar = calendar ..view = view @@ -1223,26 +1358,27 @@ class _AppointmentRenderWidget extends MultiChildRenderObjectWidget { class _AppointmentRenderObject extends CustomCalendarRenderObject { _AppointmentRenderObject( - this._calendar, - this._view, - this._visibleDates, - this._visibleAppointments, - this._timeIntervalHeight, - this._calendarTheme, - this._themeData, - this._isRTL, - this._appointmentHoverPosition, - this._resourceCollection, - this._resourceItemHeight, - this._textScaleFactor, - this.isMobilePlatform, - this._width, - this._height, - this._localizations, - this.appointmentCollection, - this.indexAppointments, - this.monthAppointmentCountViews, - this._weekNumberPanelWidth); + this._calendar, + this._view, + this._visibleDates, + this._visibleAppointments, + this._timeIntervalHeight, + this._calendarTheme, + this._themeData, + this._isRTL, + this._appointmentHoverPosition, + this._resourceCollection, + this._resourceItemHeight, + this._textScaleFactor, + this.isMobilePlatform, + this._width, + this._height, + this._localizations, + this.appointmentCollection, + this.indexAppointments, + this.monthAppointmentCountViews, + this._weekNumberPanelWidth, + ); List? _visibleAppointments; @@ -1528,14 +1664,17 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { continue; } - semanticsBuilder.add(CustomPainterSemantics( - rect: rect, - properties: SemanticsProperties( - label: CalendarViewHelper.getAppointmentSemanticsText( - appointmentView.appointment!), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: rect, + properties: SemanticsProperties( + label: CalendarViewHelper.getAppointmentSemanticsText( + appointmentView.appointment!, + ), + textDirection: TextDirection.ltr, + ), ), - )); + ); } if (view != CalendarView.month || @@ -1552,13 +1691,15 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { continue; } - semanticsBuilder.add(CustomPainterSemantics( - rect: rect, - properties: const SemanticsProperties( - label: 'More', - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: rect, + properties: const SemanticsProperties( + label: 'More', + textDirection: TextDirection.ltr, + ), ), - )); + ); } return semanticsBuilder; @@ -1591,8 +1732,10 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { continue; } - final Offset offset = Offset(appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top); + final Offset offset = Offset( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + ); final bool isHit = result.addWithPaintOffset( offset: offset, position: position, @@ -1641,8 +1784,10 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView appointmentView = appointmentCollection[i]; @@ -1652,15 +1797,20 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { continue; } - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: appointmentView.appointmentRect!.height, maxHeight: appointmentView.appointmentRect!.height, minWidth: appointmentView.appointmentRect!.width, - maxWidth: appointmentView.appointmentRect!.width)); + maxWidth: appointmentView.appointmentRect!.width, + ), + ); final CalendarParentData childParentData = child.parentData! as CalendarParentData; - childParentData.offset = Offset(appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top); + childParentData.offset = Offset( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + ); child = childAfter(child); } @@ -1677,11 +1827,14 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } final RRect moreRegionRect = monthAppointmentCountViews[keys[i]]!; - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: moreRegionRect.height, maxHeight: moreRegionRect.height, minWidth: moreRegionRect.width, - maxWidth: moreRegionRect.width)); + maxWidth: moreRegionRect.width, + ), + ); final CalendarParentData childParentData = child.parentData! as CalendarParentData; @@ -1706,11 +1859,16 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } context.paintChild( - child, - Offset(appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top)); + child, + Offset( + appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + ), + ); _updateAppointmentHovering( - appointmentView.appointmentRect!, context.canvas); + appointmentView.appointmentRect!, + context.canvas, + ); child = childAfter(child); } @@ -1729,7 +1887,9 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { final RRect moreRegionRect = monthAppointmentCountViews[keys[i]]!; context.paintChild( - child, Offset(moreRegionRect.left, moreRegionRect.top)); + child, + Offset(moreRegionRect.left, moreRegionRect.top), + ); _updateAppointmentHovering(moreRegionRect, context.canvas); child = childAfter(child); @@ -1783,23 +1943,33 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } } - void _drawMonthAppointmentView(Canvas canvas, Size size, double cellWidth, - double cellHeight, Paint paint) { + void _drawMonthAppointmentView( + Canvas canvas, + Size size, + double cellWidth, + double cellHeight, + Paint paint, + ) { final int count = visibleDates.length; - DateTime visibleStartDate = - AppointmentHelper.convertToStartTime(visibleDates[0]); - DateTime visibleEndDate = - AppointmentHelper.convertToEndTime(visibleDates[count - 1]); + DateTime visibleStartDate = AppointmentHelper.convertToStartTime( + visibleDates[0], + ); + DateTime visibleEndDate = AppointmentHelper.convertToEndTime( + visibleDates[count - 1], + ); final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - calendar.monthViewSettings.numberOfWeeksInView, - calendar.monthViewSettings.showTrailingAndLeadingDates); + calendar.monthViewSettings.numberOfWeeksInView, + calendar.monthViewSettings.showTrailingAndLeadingDates, + ); if (!showTrailingLeadingDates) { final DateTime currentMonthDate = visibleDates[count ~/ 2]; visibleStartDate = AppointmentHelper.convertToStartTime( - AppointmentHelper.getMonthStartDate(currentMonthDate)); + AppointmentHelper.getMonthStartDate(currentMonthDate), + ); visibleEndDate = AppointmentHelper.convertToEndTime( - AppointmentHelper.getMonthEndDate(currentMonthDate)); + AppointmentHelper.getMonthEndDate(currentMonthDate), + ); } final int maximumDisplayCount = @@ -1821,17 +1991,27 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { appointmentView.maxPositions == maximumDisplayCount)) { final CalendarAppointment appointment = appointmentView.appointment!; final bool canAddSpanIcon = AppointmentHelper.canAddSpanIcon( - visibleDates, appointment, view, - visibleStartDate: visibleStartDate, - visibleEndDate: visibleEndDate, - showTrailingLeadingDates: showTrailingLeadingDates); + visibleDates, + appointment, + view, + visibleStartDate: visibleStartDate, + visibleEndDate: visibleEndDate, + showTrailingLeadingDates: showTrailingLeadingDates, + ); paint.color = appointment.color; TextStyle style = AppointmentHelper.getAppointmentTextStyle( - calendar.appointmentTextStyle, view, themeData); + calendar.appointmentTextStyle, + view, + themeData, + ); TextSpan span = TextSpan(text: appointment.subject, style: style); - _textPainter = - _updateTextPainter(span, _textPainter, isRTL, _textScaleFactor); + _textPainter = _updateTextPainter( + span, + _textPainter, + isRTL, + _textScaleFactor, + ); if (textSize == -1) { //// left and right side padding value 2 subtracted in appointment width @@ -1843,27 +2023,41 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { style = style.copyWith(fontSize: j); span = TextSpan(text: appointment.subject, style: style); _textPainter = _updateTextPainter( - span, _textPainter, isRTL, _textScaleFactor); + span, + _textPainter, + isRTL, + _textScaleFactor, + ); } else { textSize = j + 1; break; } } + if (textSize < 0) { + textSize = 0; + } } else { span = TextSpan( - text: appointment.subject, - style: style.copyWith(fontSize: textSize)); - _textPainter = - _updateTextPainter(span, _textPainter, isRTL, _textScaleFactor); + text: appointment.subject, + style: style.copyWith(fontSize: textSize), + ); + _textPainter = _updateTextPainter( + span, + _textPainter, + isRTL, + _textScaleFactor, + ); } canvas.drawRRect(appointmentRect, paint); final bool isRecurrenceAppointment = appointment.recurrenceRule != null && - appointment.recurrenceRule!.isNotEmpty; + appointment.recurrenceRule!.isNotEmpty; final double iconTextSize = _getTextSize( - appointmentRect, _textPainter.textScaler.scale(textSize)); + appointmentRect, + _textPainter.textScaler.scale(textSize), + ); const double iconPadding = 2; //// Padding 4 is left and right 2 padding. final double iconSize = iconTextSize + (2 * iconPadding); @@ -1876,9 +2070,13 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { if (canAddSpanIcon) { final int appStartIndex = MonthAppointmentHelper.getDateIndex( - appointment.exactStartTime, visibleDates); + appointment.exactStartTime, + visibleDates, + ); final int appEndIndex = MonthAppointmentHelper.getDateIndex( - appointment.exactEndTime, visibleDates); + appointment.exactEndTime, + visibleDates, + ); if (appStartIndex == appointmentView.startIndex && appEndIndex == appointmentView.endIndex) { continue; @@ -1897,16 +2095,17 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { const double textPadding = 1; _drawSingleLineAppointmentView( - canvas, - appointmentRect, - textPadding, - style, - textSize, - isRecurrenceAppointment, - recurrenceIconSize, - forwardSpanIconSize, - backwardSpanIconSize, - paint); + canvas, + appointmentRect, + textPadding, + style, + textSize, + isRecurrenceAppointment, + recurrenceIconSize, + forwardSpanIconSize, + backwardSpanIconSize, + paint, + ); _updateAppointmentHovering(appointmentRect, canvas); } } @@ -1925,16 +2124,20 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { radius = 3; } } - double startXPosition = isRTL - ? moreRegionRect.right - startPadding - : moreRegionRect.left + startPadding; + double startXPosition = + isRTL + ? moreRegionRect.right - startPadding + : moreRegionRect.left + startPadding; paint.color = Colors.grey[600]!; for (int j = 0; j < 3; j++) { canvas.drawCircle( - Offset(startXPosition, - moreRegionRect.top + (moreRegionRect.height / 2)), - radius, - paint); + Offset( + startXPosition, + moreRegionRect.top + (moreRegionRect.height / 2), + ), + radius, + paint, + ); if (isRTL) { startXPosition -= padding + (2 * radius); } else { @@ -1947,80 +2150,106 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } void _drawSingleLineAppointmentView( - Canvas canvas, - RRect appointmentRect, - double textPadding, - TextStyle style, - double textSize, - bool isRecurrenceAppointment, - double recurrenceIconSize, - double forwardSpanIconSize, - double backwardSpanIconSize, - Paint paint) { + Canvas canvas, + RRect appointmentRect, + double textPadding, + TextStyle style, + double textSize, + bool isRecurrenceAppointment, + double recurrenceIconSize, + double forwardSpanIconSize, + double backwardSpanIconSize, + Paint paint, + ) { final double totalIconsWidth = recurrenceIconSize + forwardSpanIconSize + backwardSpanIconSize; final double textWidth = appointmentRect.width - totalIconsWidth; _textPainter.layout( - maxWidth: textWidth - (2 * textPadding) > 0 - ? textWidth - (2 * textPadding) - : 0); - final double yPosition = appointmentRect.top + + maxWidth: + textWidth - (2 * textPadding) > 0 ? textWidth - (2 * textPadding) : 0, + ); + final double yPosition = + appointmentRect.top + ((appointmentRect.height - _textPainter.height) / 2); - final double xPosition = isRTL - ? appointmentRect.right - - _textPainter.width - - backwardSpanIconSize - - textPadding - : appointmentRect.left + backwardSpanIconSize + textPadding; + final double xPosition = + isRTL + ? appointmentRect.right - + _textPainter.width - + backwardSpanIconSize - + textPadding + : appointmentRect.left + backwardSpanIconSize + textPadding; _textPainter.paint(canvas, Offset(xPosition, yPosition)); if (backwardSpanIconSize != 0) { - _drawBackwardSpanIconForMonth(canvas, style, textSize, appointmentRect, - backwardSpanIconSize, appointmentRect.tlRadius, paint); + _drawBackwardSpanIconForMonth( + canvas, + style, + textSize, + appointmentRect, + backwardSpanIconSize, + appointmentRect.tlRadius, + paint, + ); } if (recurrenceIconSize != 0) { _drawRecurrenceIconForMonth( - canvas, - style, - textSize, - appointmentRect, - appointmentRect.tlRadius, - paint, - isRecurrenceAppointment, - recurrenceIconSize, - forwardSpanIconSize); + canvas, + style, + textSize, + appointmentRect, + appointmentRect.tlRadius, + paint, + isRecurrenceAppointment, + recurrenceIconSize, + forwardSpanIconSize, + ); } if (forwardSpanIconSize != 0) { - _drawForwardSpanIconForMonth(canvas, style, textSize, appointmentRect, - forwardSpanIconSize, appointmentRect.tlRadius, paint); + _drawForwardSpanIconForMonth( + canvas, + style, + textSize, + appointmentRect, + forwardSpanIconSize, + appointmentRect.tlRadius, + paint, + ); } } void _drawForwardSpanIconForMonth( - Canvas canvas, - TextStyle style, - double textSize, - RRect rect, - double iconSize, - Radius cornerRadius, - Paint paint) { - final TextSpan icon = - AppointmentHelper.getSpanIcon(style.color!, textSize, !isRTL); + Canvas canvas, + TextStyle style, + double textSize, + RRect rect, + double iconSize, + Radius cornerRadius, + Paint paint, + ) { + final TextSpan icon = AppointmentHelper.getSpanIcon( + style.color!, + textSize, + !isRTL, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: rect.width > 0 ? rect.width : 0); - final double yPosition = - AppointmentHelper.getYPositionForSpanIcon(icon, _textPainter, rect); + final double yPosition = AppointmentHelper.getYPositionForSpanIcon( + icon, + _textPainter, + rect, + ); final double xPosition = isRTL ? rect.left : rect.right - iconSize; canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - xPosition, rect.top, xPosition + iconSize, rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB(xPosition, rect.top, xPosition + iconSize, rect.bottom), + cornerRadius, + ), + paint, + ); double iconPadding = (iconSize - _textPainter.width) / 2; if (iconPadding < 0) { iconPadding = 0; @@ -2030,20 +2259,27 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } void _drawBackwardSpanIconForMonth( - Canvas canvas, - TextStyle style, - double textSize, - RRect rect, - double iconSize, - Radius cornerRadius, - Paint paint) { - final TextSpan icon = - AppointmentHelper.getSpanIcon(style.color!, textSize, isRTL); + Canvas canvas, + TextStyle style, + double textSize, + RRect rect, + double iconSize, + Radius cornerRadius, + Paint paint, + ) { + final TextSpan icon = AppointmentHelper.getSpanIcon( + style.color!, + textSize, + isRTL, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: rect.width > 0 ? rect.width : 0); - final double yPosition = - AppointmentHelper.getYPositionForSpanIcon(icon, _textPainter, rect); + final double yPosition = AppointmentHelper.getYPositionForSpanIcon( + icon, + _textPainter, + rect, + ); final double xPosition = isRTL ? rect.right - iconSize : rect.left; double iconPadding = (iconSize - _textPainter.width) / 2; if (iconPadding < 0) { @@ -2051,53 +2287,72 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - xPosition, rect.top, xPosition + iconSize, rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB(xPosition, rect.top, xPosition + iconSize, rect.bottom), + cornerRadius, + ), + paint, + ); _textPainter.paint(canvas, Offset(xPosition + iconPadding, yPosition)); } void _drawRecurrenceIconForMonth( - Canvas canvas, - TextStyle style, - double textSize, - RRect rect, - Radius cornerRadius, - Paint paint, - bool isRecurrenceAppointment, - double iconSize, - double forwardSpanIconSize) { + Canvas canvas, + TextStyle style, + double textSize, + RRect rect, + Radius cornerRadius, + Paint paint, + bool isRecurrenceAppointment, + double iconSize, + double forwardSpanIconSize, + ) { final TextSpan icon = AppointmentHelper.getRecurrenceIcon( - style.color!, textSize, isRecurrenceAppointment); + style.color!, + textSize, + isRecurrenceAppointment, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: rect.width > 0 ? rect.width : 0); final double yPosition = rect.top + ((rect.height - _textPainter.height) / 2); - final double recurrenceStartPosition = isRTL - ? rect.left + forwardSpanIconSize - : rect.right - iconSize - forwardSpanIconSize; + final double recurrenceStartPosition = + isRTL + ? rect.left + forwardSpanIconSize + : rect.right - iconSize - forwardSpanIconSize; canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(recurrenceStartPosition, yPosition, - recurrenceStartPosition + iconSize, rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + recurrenceStartPosition, + yPosition, + recurrenceStartPosition + iconSize, + rect.bottom, + ), + cornerRadius, + ), + paint, + ); double iconPadding = (iconSize - _textPainter.width) / 2; if (iconPadding < 0) { iconPadding = 0; } _textPainter.paint( - canvas, Offset(recurrenceStartPosition + iconPadding, yPosition)); + canvas, + Offset(recurrenceStartPosition + iconPadding, yPosition), + ); } void _drawMonthAppointmentIndicator( - Canvas canvas, double cellWidth, double cellHeight, Paint paint) { - double xPosition = isRTL - ? size.width - cellWidth - weekNumberPanelWidth - : weekNumberPanelWidth; + Canvas canvas, + double cellWidth, + double cellHeight, + Paint paint, + ) { + double xPosition = + isRTL + ? size.width - cellWidth - weekNumberPanelWidth + : weekNumberPanelWidth; double yPosition = 0; const double radius = 2.5; const double diameter = radius * 2; @@ -2107,8 +2362,9 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { final int currentMonth = visibleDates[visibleDatesCount ~/ 2].month; final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - calendar.monthViewSettings.numberOfWeeksInView, - calendar.monthViewSettings.showTrailingAndLeadingDates); + calendar.monthViewSettings.numberOfWeeksInView, + calendar.monthViewSettings.showTrailingAndLeadingDates, + ); for (int i = 0; i < visibleDatesCount; i++) { final DateTime currentVisibleDate = visibleDates[i]; @@ -2119,22 +2375,32 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { final List appointmentLists = AppointmentHelper.getSpecificDateVisibleAppointment( - currentVisibleDate, visibleAppointments); + currentVisibleDate, + visibleAppointments, + ); appointmentLists.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); appointmentLists.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isAllDay, + app2.isAllDay, + ), + ); appointmentLists.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isSpanned, app2.isSpanned)); - final int count = appointmentLists.length <= - calendar.monthViewSettings.appointmentDisplayCount - ? appointmentLists.length - : calendar.monthViewSettings.appointmentDisplayCount; + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isSpanned, + app2.isSpanned, + ), + ); + final int count = + appointmentLists.length <= + calendar.monthViewSettings.appointmentDisplayCount + ? appointmentLists.length + : calendar.monthViewSettings.appointmentDisplayCount; const double indicatorPadding = 2; final double indicatorWidth = count * diameter + (count - 1) * indicatorPadding; @@ -2158,7 +2424,10 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { for (int j = 0; j < count; j++) { paint.color = appointmentLists[j].color; canvas.drawCircle( - Offset(xPosition, yPosition - bottomPadding), radius, paint); + Offset(xPosition, yPosition - bottomPadding), + radius, + paint, + ); xPosition += diameter + indicatorPadding; if (startXPosition + cellWidth < xPosition + diameter) { break; @@ -2177,8 +2446,8 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { rect.right > hoverPosition.dx && rect.top < hoverPosition.dy && rect.bottom > hoverPosition.dy) { - _appointmentPainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + _appointmentPainter.color = calendarTheme.selectionBorderColor! + .withValues(alpha: 0.4); _appointmentPainter.strokeWidth = 2; _appointmentPainter.style = PaintingStyle.stroke; canvas.drawRRect(rect, _appointmentPainter); @@ -2189,8 +2458,10 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { void _drawDayAppointments(Canvas canvas, Size size, Paint paint) { const int textStartPadding = 3; - final bool useMobilePlatformUI = - CalendarViewHelper.isMobileLayoutUI(size.width, isMobilePlatform); + final bool useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( + size.width, + isMobilePlatform, + ); for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView appointmentView = appointmentCollection[i]; if (appointmentView.canReuse || @@ -2206,24 +2477,40 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { double xPosition = appointmentRect.left; double yPosition = appointmentRect.top; - final bool canAddSpanIcon = - AppointmentHelper.canAddSpanIcon(visibleDates, appointment, view); + final bool canAddSpanIcon = AppointmentHelper.canAddSpanIcon( + visibleDates, + appointment, + view, + ); bool canAddForwardIcon = false; final TextStyle appointmentTextStyle = AppointmentHelper.getAppointmentTextStyle( - calendar.appointmentTextStyle, view, themeData); + calendar.appointmentTextStyle, + view, + themeData, + ); if (canAddSpanIcon) { if (CalendarViewHelper.isSameTimeSlot( - appointment.exactStartTime, appointment.actualStartTime) && + appointment.exactStartTime, + appointment.actualStartTime, + ) && !CalendarViewHelper.isSameTimeSlot( - appointment.exactEndTime, appointment.actualEndTime)) { + appointment.exactEndTime, + appointment.actualEndTime, + )) { canAddForwardIcon = true; } else if (!CalendarViewHelper.isSameTimeSlot( - appointment.exactStartTime, appointment.actualStartTime) && + appointment.exactStartTime, + appointment.actualStartTime, + ) && CalendarViewHelper.isSameTimeSlot( - appointment.exactEndTime, appointment.actualEndTime)) { - yPosition += _getTextSize(appointmentRect, - appointmentTextStyle.fontSize! * textScaleFactor); + appointment.exactEndTime, + appointment.actualEndTime, + )) { + yPosition += _getTextSize( + appointmentRect, + appointmentTextStyle.fontSize! * textScaleFactor, + ); } } @@ -2232,8 +2519,12 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { style: appointmentTextStyle, ); - _textPainter = - _updateTextPainter(span, _textPainter, isRTL, _textScaleFactor); + _textPainter = _updateTextPainter( + span, + _textPainter, + isRTL, + _textScaleFactor, + ); final double totalHeight = appointmentRect.height - textStartPadding; _updatePainterMaxLines(totalHeight); @@ -2271,56 +2562,92 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } _textPainter.paint( - canvas, - Offset(xPosition + (isRTL ? 0 : textStartPadding), - yPosition + textStartPadding)); - final bool isRecurrenceAppointment = appointment.recurrenceRule != null && + canvas, + Offset( + xPosition + (isRTL ? 0 : textStartPadding), + yPosition + textStartPadding, + ), + ); + final bool isRecurrenceAppointment = + appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty; if (canAddSpanIcon) { if (canAddForwardIcon) { - _addForwardSpanIconForDay(canvas, appointmentRect, size, - appointmentRect.tlRadius, paint, appointmentTextStyle); + _addForwardSpanIconForDay( + canvas, + appointmentRect, + size, + appointmentRect.tlRadius, + paint, + appointmentTextStyle, + ); } else { - _addBackwardSpanIconForDay(canvas, appointmentRect, size, - appointmentRect.tlRadius, paint, appointmentTextStyle); + _addBackwardSpanIconForDay( + canvas, + appointmentRect, + size, + appointmentRect.tlRadius, + paint, + appointmentTextStyle, + ); } } if (isRecurrenceAppointment || appointment.recurrenceId != null) { _addRecurrenceIconForDay( - canvas, - size, - appointmentRect, - appointmentRect.width, - textStartPadding, - paint, - appointmentRect.tlRadius, - useMobilePlatformUI, - isRecurrenceAppointment, - appointmentTextStyle); + canvas, + size, + appointmentRect, + appointmentRect.width, + textStartPadding, + paint, + appointmentRect.tlRadius, + useMobilePlatformUI, + isRecurrenceAppointment, + appointmentTextStyle, + ); } _updateAppointmentHovering(appointmentRect, canvas); } } - void _addBackwardSpanIconForDay(Canvas canvas, RRect rect, Size size, - Radius cornerRadius, Paint paint, TextStyle appointmentTextStyle) { + void _addBackwardSpanIconForDay( + Canvas canvas, + RRect rect, + Size size, + Radius cornerRadius, + Paint paint, + TextStyle appointmentTextStyle, + ) { canvas.save(); const double bottomPadding = 2; final double textSize = _getTextSize(rect, appointmentTextStyle.fontSize!); final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, textSize, false); - _textPainter = - _updateTextPainter(icon, _textPainter, isRTL, _textScaleFactor); + appointmentTextStyle.color!, + textSize, + false, + ); + _textPainter = _updateTextPainter( + icon, + _textPainter, + isRTL, + _textScaleFactor, + ); _textPainter.layout(maxWidth: rect.width); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - rect.left, rect.top, rect.right, rect.top + _textPainter.width), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + rect.left, + rect.top, + rect.right, + rect.top + _textPainter.width, + ), + cornerRadius, + ), + paint, + ); final double xPosition = _getXPositionForSpanIconForDay(icon, rect); @@ -2346,22 +2673,41 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { iconStartPosition; } - void _addForwardSpanIconForDay(Canvas canvas, RRect rect, Size size, - Radius cornerRadius, Paint paint, TextStyle appointmentTextStyle) { + void _addForwardSpanIconForDay( + Canvas canvas, + RRect rect, + Size size, + Radius cornerRadius, + Paint paint, + TextStyle appointmentTextStyle, + ) { canvas.save(); const double bottomPadding = 2; final double textSize = _getTextSize(rect, appointmentTextStyle.fontSize!); final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, textSize, true); - _textPainter = - _updateTextPainter(icon, _textPainter, isRTL, _textScaleFactor); + appointmentTextStyle.color!, + textSize, + true, + ); + _textPainter = _updateTextPainter( + icon, + _textPainter, + isRTL, + _textScaleFactor, + ); _textPainter.layout(maxWidth: rect.width); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(rect.left, rect.bottom - _textPainter.width, - rect.right, rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + rect.left, + rect.bottom - _textPainter.width, + rect.right, + rect.bottom, + ), + cornerRadius, + ), + paint, + ); final double xPosition = _getXPositionForSpanIconForDay(icon, rect); final double yPosition = @@ -2386,16 +2732,17 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } void _addRecurrenceIconForDay( - Canvas canvas, - Size size, - RRect rect, - double appointmentWidth, - int textPadding, - Paint paint, - Radius cornerRadius, - bool useMobilePlatformUI, - bool isRecurrenceAppointment, - TextStyle appointmentTextStyle) { + Canvas canvas, + Size size, + RRect rect, + double appointmentWidth, + int textPadding, + Paint paint, + Radius cornerRadius, + bool useMobilePlatformUI, + bool isRecurrenceAppointment, + TextStyle appointmentTextStyle, + ) { final double xPadding = useMobilePlatformUI ? 1 : 2; const double bottomPadding = 2; double textSize = appointmentTextStyle.fontSize!; @@ -2404,32 +2751,43 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } final TextSpan icon = AppointmentHelper.getRecurrenceIcon( - appointmentTextStyle.color!, textSize, isRecurrenceAppointment); + appointmentTextStyle.color!, + textSize, + isRecurrenceAppointment, + ); _textPainter.text = icon; double maxTextWidth = appointmentWidth - textPadding - 2; maxTextWidth = maxTextWidth > 0 ? maxTextWidth : 0; _textPainter.layout(maxWidth: maxTextWidth); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - isRTL - ? rect.left + textSize + xPadding - : rect.right - textSize - xPadding, - rect.bottom - bottomPadding - textSize, - isRTL ? rect.left : rect.right, - rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + isRTL + ? rect.left + textSize + xPadding + : rect.right - textSize - xPadding, + rect.bottom - bottomPadding - textSize, + isRTL ? rect.left : rect.right, + rect.bottom, + ), + cornerRadius, + ), + paint, + ); _textPainter.paint( - canvas, - Offset(isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, - rect.bottom - bottomPadding - textSize)); + canvas, + Offset( + isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, + rect.bottom - bottomPadding - textSize, + ), + ); } void _drawTimelineAppointments(Canvas canvas, Size size, Paint paint) { const double textStartPadding = 2; - final bool useMobilePlatformUI = - CalendarViewHelper.isMobileLayoutUI(size.width, isMobilePlatform); + final bool useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( + size.width, + isMobilePlatform, + ); for (int i = 0; i < appointmentCollection.length; i++) { final AppointmentView appointmentView = appointmentCollection[i]; if (appointmentView.canReuse || @@ -2442,30 +2800,49 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { paint.color = appointment.color; final RRect appointmentRect = appointmentView.appointmentRect!; canvas.drawRRect(appointmentRect, paint); - final bool canAddSpanIcon = - AppointmentHelper.canAddSpanIcon(visibleDates, appointment, view); + final bool canAddSpanIcon = AppointmentHelper.canAddSpanIcon( + visibleDates, + appointment, + view, + ); double forwardSpanIconSize = 0; double backwardSpanIconSize = 0; const double iconPadding = 2; final TextStyle appointmentTextStyle = AppointmentHelper.getAppointmentTextStyle( - calendar.appointmentTextStyle, view, themeData); - final double iconSize = _getTextSize(appointmentRect, - appointmentTextStyle.fontSize! * textScaleFactor) + + calendar.appointmentTextStyle, + view, + themeData, + ); + final double iconSize = + _getTextSize( + appointmentRect, + appointmentTextStyle.fontSize! * textScaleFactor, + ) + (2 * iconPadding); if (canAddSpanIcon) { final DateTime appStartTime = appointment.exactStartTime; final DateTime appEndTime = appointment.exactEndTime; - final DateTime viewStartDate = - AppointmentHelper.convertToStartTime(visibleDates[0]); + final DateTime viewStartDate = AppointmentHelper.convertToStartTime( + visibleDates[0], + ); final DateTime viewEndDate = AppointmentHelper.convertToEndTime( - visibleDates[visibleDates.length - 1]); + visibleDates[visibleDates.length - 1], + ); if (AppointmentHelper.canAddForwardSpanIcon( - appStartTime, appEndTime, viewStartDate, viewEndDate)) { + appStartTime, + appEndTime, + viewStartDate, + viewEndDate, + )) { forwardSpanIconSize = iconSize; } else if (AppointmentHelper.canAddBackwardSpanIcon( - appStartTime, appEndTime, viewStartDate, viewEndDate)) { + appStartTime, + appEndTime, + viewStartDate, + viewEndDate, + )) { backwardSpanIconSize = iconSize; } else { forwardSpanIconSize = iconSize; @@ -2473,7 +2850,8 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } } - double maxWidth = appointmentRect.width - + double maxWidth = + appointmentRect.width - (2 * textStartPadding) - backwardSpanIconSize - forwardSpanIconSize; @@ -2483,8 +2861,12 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { style: appointmentTextStyle, ); - _textPainter = - _updateTextPainter(span, _textPainter, isRTL, _textScaleFactor); + _textPainter = _updateTextPainter( + span, + _textPainter, + isRTL, + _textScaleFactor, + ); final double totalHeight = appointmentRect.height - (2 * textStartPadding); _updatePainterMaxLines(totalHeight); @@ -2506,70 +2888,78 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { continue; } - final double xPosition = isRTL - ? appointmentRect.right - - backwardSpanIconSize - - _textPainter.width - - textStartPadding - : appointmentRect.left + backwardSpanIconSize + textStartPadding; + final double xPosition = + isRTL + ? appointmentRect.right - + backwardSpanIconSize - + _textPainter.width - + textStartPadding + : appointmentRect.left + backwardSpanIconSize + textStartPadding; final int maxLines = (appointmentRect.height / _textPainter.preferredLineHeight).floor(); - final bool isRecurrenceAppointment = appointment.recurrenceRule != null && + final bool isRecurrenceAppointment = + appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty; if (maxLines == 1) { _drawSingleLineAppointmentView( - canvas, - appointmentRect, - textStartPadding, - appointmentTextStyle, - appointmentTextStyle.fontSize!, - isRecurrenceAppointment, - isRecurrenceAppointment || appointment.recurrenceId != null - ? iconSize - : 0, - forwardSpanIconSize, - backwardSpanIconSize, - paint); + canvas, + appointmentRect, + textStartPadding, + appointmentTextStyle, + appointmentTextStyle.fontSize!, + isRecurrenceAppointment, + isRecurrenceAppointment || appointment.recurrenceId != null + ? iconSize + : 0, + forwardSpanIconSize, + backwardSpanIconSize, + paint, + ); } else { _textPainter.paint( - canvas, Offset(xPosition, appointmentRect.top + textStartPadding)); + canvas, + Offset(xPosition, appointmentRect.top + textStartPadding), + ); if (forwardSpanIconSize != 0) { _addForwardSpanIconForTimeline( - canvas, - size, - appointmentRect, - maxWidth, - appointmentRect.tlRadius, - paint, - isMobilePlatform, - appointmentTextStyle); + canvas, + size, + appointmentRect, + maxWidth, + appointmentRect.tlRadius, + paint, + isMobilePlatform, + appointmentTextStyle, + ); } if (backwardSpanIconSize != 0) { _addBackwardSpanIconForTimeline( - canvas, - size, - appointmentRect, - maxWidth, - appointmentRect.tlRadius, - paint, - isMobilePlatform, - appointmentTextStyle); + canvas, + size, + appointmentRect, + maxWidth, + appointmentRect.tlRadius, + paint, + isMobilePlatform, + appointmentTextStyle, + ); } if (isRecurrenceAppointment || appointment.recurrenceId != null) { _addRecurrenceIconForTimeline( - canvas, - size, - appointmentRect, - maxWidth, - appointmentRect.tlRadius, - paint, - useMobilePlatformUI, - isRecurrenceAppointment, - appointmentTextStyle); + canvas, + size, + appointmentRect, + maxWidth, + appointmentRect.tlRadius, + paint, + useMobilePlatformUI, + isRecurrenceAppointment, + appointmentTextStyle, + ); } } @@ -2582,13 +2972,18 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { /// for timeline day view we display the current date, and total dates of the /// spanning appointment. String _getTimelineAppointmentText( - CalendarAppointment appointment, bool canAddSpanIcon) { + CalendarAppointment appointment, + bool canAddSpanIcon, + ) { if (view != CalendarView.timelineDay || !canAddSpanIcon) { return appointment.subject; } return AppointmentHelper.getSpanAppointmentText( - appointment, visibleDates[0], _localizations); + appointment, + visibleDates[0], + _localizations, + ); } double _getTextSize(RRect rect, double textSize) { @@ -2600,7 +2995,11 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { } double _getYPositionForSpanIconInTimeline( - TextSpan icon, RRect rect, double xPadding, bool isMobilePlatform) { + TextSpan icon, + RRect rect, + double xPadding, + bool isMobilePlatform, + ) { /// There is a space around the font, hence to get the start position we /// must calculate the icon start position, apart from the space, and the /// value 2 used since the space on top and bottom of icon is not even, @@ -2608,108 +3007,160 @@ class _AppointmentRenderObject extends CustomCalendarRenderObject { /// device. final double iconStartPosition = (_textPainter.height - (icon.style!.fontSize! * textScaleFactor) / 2) / - 2; + 2; return rect.top - iconStartPosition + (isMobilePlatform ? 1 : xPadding); } void _addForwardSpanIconForTimeline( - Canvas canvas, - Size size, - RRect rect, - double maxWidth, - Radius cornerRadius, - Paint paint, - bool isMobilePlatform, - TextStyle appointmentTextStyle) { + Canvas canvas, + Size size, + RRect rect, + double maxWidth, + Radius cornerRadius, + Paint paint, + bool isMobilePlatform, + TextStyle appointmentTextStyle, + ) { const double xPadding = 2; final double textSize = _getTextSize(rect, appointmentTextStyle.fontSize!); final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, textSize, !isRTL); - _textPainter = - _updateTextPainter(icon, _textPainter, isRTL, _textScaleFactor); + appointmentTextStyle.color!, + textSize, + !isRTL, + ); + _textPainter = _updateTextPainter( + icon, + _textPainter, + isRTL, + _textScaleFactor, + ); _textPainter.layout(maxWidth: maxWidth); - final double xPosition = isRTL - ? rect.left + xPadding - : rect.right - _textPainter.width - xPadding; + final double xPosition = + isRTL + ? rect.left + xPadding + : rect.right - _textPainter.width - xPadding; final double yPosition = _getYPositionForSpanIconInTimeline( - icon, rect, xPadding, isMobilePlatform); + icon, + rect, + xPadding, + isMobilePlatform, + ); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(xPosition, rect.top + 1, - isRTL ? rect.left : rect.right, rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + xPosition, + rect.top + 1, + isRTL ? rect.left : rect.right, + rect.bottom, + ), + cornerRadius, + ), + paint, + ); _textPainter.paint(canvas, Offset(xPosition, yPosition)); } void _addBackwardSpanIconForTimeline( - Canvas canvas, - Size size, - RRect rect, - double maxWidth, - Radius cornerRadius, - Paint paint, - bool isMobilePlatform, - TextStyle appointmentTextStyle) { + Canvas canvas, + Size size, + RRect rect, + double maxWidth, + Radius cornerRadius, + Paint paint, + bool isMobilePlatform, + TextStyle appointmentTextStyle, + ) { const double xPadding = 2; final double textSize = _getTextSize(rect, appointmentTextStyle.fontSize!); final TextSpan icon = AppointmentHelper.getSpanIcon( - appointmentTextStyle.color!, textSize, isRTL); - _textPainter = - _updateTextPainter(icon, _textPainter, isRTL, _textScaleFactor); + appointmentTextStyle.color!, + textSize, + isRTL, + ); + _textPainter = _updateTextPainter( + icon, + _textPainter, + isRTL, + _textScaleFactor, + ); _textPainter.layout(maxWidth: maxWidth); - final double xPosition = isRTL - ? rect.right - _textPainter.width - xPadding - : rect.left + xPadding; + final double xPosition = + isRTL + ? rect.right - _textPainter.width - xPadding + : rect.left + xPadding; final double yPosition = _getYPositionForSpanIconInTimeline( - icon, rect, xPadding, isMobilePlatform); + icon, + rect, + xPadding, + isMobilePlatform, + ); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(xPosition, rect.top + 1, - isRTL ? rect.right : rect.left, rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + xPosition, + rect.top + 1, + isRTL ? rect.right : rect.left, + rect.bottom, + ), + cornerRadius, + ), + paint, + ); _textPainter.paint(canvas, Offset(xPosition, yPosition)); } void _addRecurrenceIconForTimeline( - Canvas canvas, - Size size, - RRect rect, - double maxWidth, - Radius cornerRadius, - Paint paint, - bool useMobilePlatformUI, - bool isRecurrenceAppointment, - TextStyle appointmentTextStyle) { + Canvas canvas, + Size size, + RRect rect, + double maxWidth, + Radius cornerRadius, + Paint paint, + bool useMobilePlatformUI, + bool isRecurrenceAppointment, + TextStyle appointmentTextStyle, + ) { final double xPadding = useMobilePlatformUI ? 1 : 2; const double bottomPadding = 2; final double textSize = _getTextSize(rect, appointmentTextStyle.fontSize!); final TextSpan icon = AppointmentHelper.getRecurrenceIcon( - appointmentTextStyle.color!, textSize, isRecurrenceAppointment); + appointmentTextStyle.color!, + textSize, + isRecurrenceAppointment, + ); _textPainter.text = icon; _textPainter.layout(maxWidth: maxWidth); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, - rect.bottom - bottomPadding - textSize, - isRTL ? rect.left : rect.right, - rect.bottom), - cornerRadius), - paint); + RRect.fromRectAndRadius( + Rect.fromLTRB( + isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, + rect.bottom - bottomPadding - textSize, + isRTL ? rect.left : rect.right, + rect.bottom, + ), + cornerRadius, + ), + paint, + ); _textPainter.paint( - canvas, - Offset(isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, - rect.bottom - bottomPadding - textSize)); + canvas, + Offset( + isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, + rect.bottom - bottomPadding - textSize, + ), + ); } } -TextPainter _updateTextPainter(TextSpan span, TextPainter textPainter, - bool isRTL, double textScaleFactor) { +TextPainter _updateTextPainter( + TextSpan span, + TextPainter textPainter, + bool isRTL, + double textScaleFactor, +) { textPainter.text = span; textPainter.maxLines = 1; textPainter.textDirection = TextDirection.ltr; diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/calendar_view_helper.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/calendar_view_helper.dart index a66889128..759ad3968 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/calendar_view_helper.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/calendar_view_helper.dart @@ -18,8 +18,8 @@ bool timeZoneLoaded = false; /// Signature for callback that used to get and update the calendar /// state details. -typedef UpdateCalendarState = void Function( - UpdateCalendarStateDetails updateCalendarStateDetails); +typedef UpdateCalendarState = + void Function(UpdateCalendarStateDetails updateCalendarStateDetails); //// Extra small devices (phones, 600px and down) //// @media only screen and (max-width: 600px) {...} @@ -105,7 +105,10 @@ class CalendarViewHelper { /// Return the localized date value based on locale and string format list. static String getLocalizedString( - DateTime date, List stringFormatList, String locale) { + DateTime date, + List stringFormatList, + String locale, + ) { String localizedString = ''; for (int i = 0; i < stringFormatList.length; i++) { final String value = stringFormatList[i]; @@ -118,7 +121,10 @@ class CalendarViewHelper { /// Return the localized date value based on locale and string format. static String getFormattedString( - DateTime date, String currentStringFormat, String locale) { + DateTime date, + String currentStringFormat, + String locale, + ) { String formattedString = currentStringFormat; if (formattedString.isEmpty) { return formattedString; @@ -160,10 +166,16 @@ class CalendarViewHelper { /// Check the date as current month date when the month leading and trailing /// dates not shown and its row count as 6. - static bool isCurrentMonthDate(int weekRowCount, - bool showLeadingTrailingDates, int currentMonth, DateTime date) { + static bool isCurrentMonthDate( + int weekRowCount, + bool showLeadingTrailingDates, + int currentMonth, + DateTime date, + ) { if (isLeadingAndTrailingDatesVisible( - weekRowCount, showLeadingTrailingDates)) { + weekRowCount, + showLeadingTrailingDates, + )) { return true; } @@ -176,13 +188,17 @@ class CalendarViewHelper { /// Check the leading and trailing dates visible or not. static bool isLeadingAndTrailingDatesVisible( - int weekRowCount, bool showLeadingTrailingDates) { + int weekRowCount, + bool showLeadingTrailingDates, + ) { return weekRowCount != 6 || showLeadingTrailingDates; } /// Check both the dates collection dates are equal or not. static bool isDateCollectionEqual( - List? originalDates, List? copyDates) { + List? originalDates, + List? copyDates, + ) { if (originalDates == copyDates) { return true; } @@ -259,8 +275,9 @@ class CalendarViewHelper { /// Return schedule view appointment height and its value based on /// schedule view settings and month view settings. static double getScheduleAppointmentHeight( - MonthViewSettings? monthViewSettings, - ScheduleViewSettings? scheduleViewSettings) { + MonthViewSettings? monthViewSettings, + ScheduleViewSettings? scheduleViewSettings, + ) { return monthViewSettings != null ? (monthViewSettings.agendaItemHeight == -1 ? 50 @@ -274,8 +291,9 @@ class CalendarViewHelper { /// Return schedule view all day appointment height and its value based on /// schedule view settings and month view settings. static double getScheduleAllDayAppointmentHeight( - MonthViewSettings? monthViewSettings, - ScheduleViewSettings? scheduleViewSettings) { + MonthViewSettings? monthViewSettings, + ScheduleViewSettings? scheduleViewSettings, + ) { return monthViewSettings != null ? (monthViewSettings.agendaItemHeight == -1 ? 25 @@ -289,10 +307,11 @@ class CalendarViewHelper { /// Returns the height for an resource item to render the resource within /// it in the resource panel. static double getResourceItemHeight( - double resourceViewSize, - double timelineViewHeight, - ResourceViewSettings resourceViewSettings, - int resourceCount) { + double resourceViewSize, + double timelineViewHeight, + ResourceViewSettings resourceViewSettings, + int resourceCount, + ) { /// The combined padding value between the circle and the display name text final double textPadding = resourceViewSettings.showAvatar ? 10 : 0; @@ -326,7 +345,9 @@ class CalendarViewHelper { /// Check and returns whether the resource panel can be added or not in the /// calendar. static bool isResourceEnabled( - CalendarDataSource? dataSource, CalendarView view) { + CalendarDataSource? dataSource, + CalendarView view, + ) { return isTimelineView(view) && dataSource != null && dataSource.resources != null && @@ -340,8 +361,9 @@ class CalendarViewHelper { return '${appointment.subject}All day'; } else if (appointment.isSpanned || AppointmentHelper.getDifference( - appointment.startTime, appointment.endTime) - .inDays > + appointment.startTime, + appointment.endTime, + ).inDays > 0) { // ignore: lines_longer_than_80_chars return '${appointment.subject}${DateFormat('hh mm a dd/MMMM/yyyy').format(appointment.startTime)}to${DateFormat('hh mm a dd/MMMM/yyyy').format(appointment.endTime)}'; @@ -353,8 +375,11 @@ class CalendarViewHelper { /// Get the today text color based on today highlight color and today text /// style. - static Color? getTodayHighlightTextColor(Color? todayHighlightColor, - TextStyle? todayTextStyle, SfCalendarThemeData calendarTheme) { + static Color? getTodayHighlightTextColor( + Color? todayHighlightColor, + TextStyle? todayTextStyle, + SfCalendarThemeData calendarTheme, + ) { Color? todayTextColor = todayHighlightColor; if (todayTextColor != null && todayTextColor == Colors.transparent) { todayTextColor = calendarTheme.todayTextStyle!.color; @@ -365,12 +390,16 @@ class CalendarViewHelper { /// Get the exact the time from the position and the date time includes /// minutes value. - static double getTimeToPosition(Duration duration, - TimeSlotViewSettings timeSlotViewSettings, double minuteHeight) { + static double getTimeToPosition( + Duration duration, + TimeSlotViewSettings timeSlotViewSettings, + double minuteHeight, + ) { final int startHour = timeSlotViewSettings.startHour.toInt(); final Duration startDuration = Duration( - hours: startHour, - minutes: ((timeSlotViewSettings.startHour - startHour) * 60).toInt()); + hours: startHour, + minutes: ((timeSlotViewSettings.startHour - startHour) * 60).toInt(), + ); final Duration difference = duration - startDuration; return difference.isNegative ? 0 : difference.inMinutes * minuteHeight; } @@ -409,7 +438,9 @@ class CalendarViewHelper { /// Returns the horizontal lines count for a single day in day/week/workweek and time line view static double getHorizontalLinesCount( - TimeSlotViewSettings settings, CalendarView view) { + TimeSlotViewSettings settings, + CalendarView view, + ) { if (view == CalendarView.timelineMonth) { return 1; } @@ -455,8 +486,10 @@ class CalendarViewHelper { /// Return time label size based on calendar view of calendar widget. static double getTimeLabelWidth( - double timeLabelViewWidth, CalendarView view) { - if (view == CalendarView.timelineMonth) { + double timeLabelViewWidth, + CalendarView view, + ) { + if (view == CalendarView.timelineMonth || view == CalendarView.month) { return 0; } @@ -482,7 +515,9 @@ class CalendarViewHelper { /// Return the view header height based on calendar view of calendar widget. static double getViewHeaderHeight( - double viewHeaderHeight, CalendarView view) { + double viewHeaderHeight, + CalendarView view, + ) { if (viewHeaderHeight != -1) { return viewHeaderHeight; } @@ -505,10 +540,18 @@ class CalendarViewHelper { } /// Check the calendar view is day or not. - static bool isDayView(CalendarView view, int numberOfDays, - List? nonWorkingDays, int numberOfWeeks) { + static bool isDayView( + CalendarView view, + int numberOfDays, + List? nonWorkingDays, + int numberOfWeeks, + ) { final int daysCount = DateTimeHelper.getViewDatesCount( - view, numberOfWeeks, numberOfDays, nonWorkingDays); + view, + numberOfWeeks, + numberOfDays, + nonWorkingDays, + ); if ((view == CalendarView.day || view == CalendarView.week || view == CalendarView.workWeek) && @@ -533,7 +576,8 @@ class CalendarViewHelper { /// method to check whether the view changed callback can triggered or not. static bool shouldRaiseViewChangedCallback( - ViewChangedCallback? onViewChanged) { + ViewChangedCallback? onViewChanged, + ) { return onViewChanged != null; } @@ -544,102 +588,128 @@ class CalendarViewHelper { /// method to check whether the long press callback can triggered or not. static bool shouldRaiseCalendarLongPressCallback( - CalendarLongPressCallback? onLongPress) { + CalendarLongPressCallback? onLongPress, + ) { return onLongPress != null; } //// method to check whether the selection changed callback can triggered or not. static bool shouldRaiseCalendarSelectionChangedCallback( - CalendarSelectionChangedCallback? onSelectionChanged) { + CalendarSelectionChangedCallback? onSelectionChanged, + ) { return onSelectionChanged != null; } /// Method to check whether the appointment resize start callback can trigger /// or not. static bool shouldRaiseAppointmentResizeStartCallback( - AppointmentResizeStartCallback? onAppointmentResizeStart) { + AppointmentResizeStartCallback? onAppointmentResizeStart, + ) { return onAppointmentResizeStart != null; } /// Method to check whether the appointment resize update callback can trigger /// or not. static bool shouldRaiseAppointmentResizeUpdateCallback( - AppointmentResizeUpdateCallback? onAppointmentResizeUpdate) { + AppointmentResizeUpdateCallback? onAppointmentResizeUpdate, + ) { return onAppointmentResizeUpdate != null; } /// Method to check whether the appointment resize end callback can trigger /// or not. static bool shouldRaiseAppointmentResizeEndCallback( - AppointmentResizeEndCallback? onAppointmentResizeEnd) { + AppointmentResizeEndCallback? onAppointmentResizeEnd, + ) { return onAppointmentResizeEnd != null; } /// method that raise the calendar tapped callback with the given parameters static void raiseCalendarTapCallback( - SfCalendar calendar, - DateTime? date, - List? appointments, - CalendarElement element, - CalendarResource? resource) { + SfCalendar calendar, + DateTime? date, + List? appointments, + CalendarElement element, + CalendarResource? resource, + ) { calendar.onTap!(CalendarTapDetails(appointments, date, element, resource)); } /// Method that raise the calendar long press callback with given parameters. static void raiseCalendarLongPressCallback( - SfCalendar calendar, - DateTime? date, - List? appointments, - CalendarElement element, - CalendarResource? resource) { + SfCalendar calendar, + DateTime? date, + List? appointments, + CalendarElement element, + CalendarResource? resource, + ) { calendar.onLongPress!( - CalendarLongPressDetails(appointments, date, element, resource)); + CalendarLongPressDetails(appointments, date, element, resource), + ); } /// method that raise the calendar selection changed callback /// with the given parameters static void raiseCalendarSelectionChangedCallback( - SfCalendar calendar, DateTime? date, CalendarResource? resource) { + SfCalendar calendar, + DateTime? date, + CalendarResource? resource, + ) { calendar.onSelectionChanged!(CalendarSelectionDetails(date, resource)); } /// method that raises the visible dates changed callback with the given /// parameters static void raiseViewChangedCallback( - SfCalendar calendar, List visibleDates) { + SfCalendar calendar, + List visibleDates, + ) { calendar.onViewChanged!(ViewChangedDetails(visibleDates)); } /// Method that raises the appointment resize start callback with the given /// parameters. static void raiseAppointmentResizeStartCallback( - SfCalendar calendar, dynamic appointment, CalendarResource? resource) { + SfCalendar calendar, + dynamic appointment, + CalendarResource? resource, + ) { calendar.onAppointmentResizeStart!( - AppointmentResizeStartDetails(appointment, resource)); + AppointmentResizeStartDetails(appointment, resource), + ); } /// Method that raises the appointment resize update callback with the given /// parameters. static void raiseAppointmentResizeUpdateCallback( - SfCalendar calendar, - dynamic appointment, - CalendarResource? resource, - DateTime? resizingTime, - Offset resizingOffset) { - calendar.onAppointmentResizeUpdate!(AppointmentResizeUpdateDetails( - appointment, resource, resizingTime, resizingOffset)); + SfCalendar calendar, + dynamic appointment, + CalendarResource? resource, + DateTime? resizingTime, + Offset resizingOffset, + ) { + calendar.onAppointmentResizeUpdate!( + AppointmentResizeUpdateDetails( + appointment, + resource, + resizingTime, + resizingOffset, + ), + ); } /// Method that raises the appointment resize end callback with the given /// parameters. static void raiseAppointmentResizeEndCallback( - SfCalendar calendar, - dynamic appointment, - CalendarResource? resource, - DateTime? startTime, - DateTime? endTime) { + SfCalendar calendar, + dynamic appointment, + CalendarResource? resource, + DateTime? startTime, + DateTime? endTime, + ) { calendar.onAppointmentResizeEnd!( - AppointmentResizeEndDetails(appointment, resource, startTime, endTime)); + AppointmentResizeEndDetails(appointment, resource, startTime, endTime), + ); } /// Check the calendar view is timeline view or not. @@ -662,7 +732,9 @@ class CalendarViewHelper { /// converts the given schedule appointment collection to their custom /// appointment collection static List getCustomAppointments( - List? appointments, CalendarDataSource? dataSource) { + List? appointments, + CalendarDataSource? dataSource, + ) { final List customAppointments = []; if (appointments == null) { return customAppointments; @@ -677,7 +749,9 @@ class CalendarViewHelper { /// Returns the appointment details with given appointment type. static dynamic getAppointmentDetail( - CalendarAppointment appointment, CalendarDataSource? dataSource) { + CalendarAppointment appointment, + CalendarDataSource? dataSource, + ) { if (appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty) { final Appointment appointmentObject = @@ -686,7 +760,9 @@ class CalendarViewHelper { return appointmentObject; } else { return dataSource!.convertAppointmentToObject( - appointment.data, appointmentObject) ?? + appointment.data, + appointmentObject, + ) ?? appointmentObject; } } else { @@ -697,18 +773,25 @@ class CalendarViewHelper { /// Returns the index of the passed id's resource from the passed resource /// collection. static int getResourceIndex( - List? resourceCollection, Object id) { + List? resourceCollection, + Object id, + ) { if (resourceCollection == null || resourceCollection.isEmpty) { return -1; } - return resourceCollection - .indexWhere((CalendarResource resource) => resource.id == id); + return resourceCollection.indexWhere( + (CalendarResource resource) => resource.id == id, + ); } /// Check the date in between first and last date static bool isDateTimeWithInDateTimeRange( - DateTime startDate, DateTime endDate, DateTime date, int timeInterval) { + DateTime startDate, + DateTime endDate, + DateTime date, + int timeInterval, + ) { if (startDate.isAfter(endDate)) { final dynamic temp = startDate; startDate = endDate; @@ -744,8 +827,11 @@ class CalendarViewHelper { } /// Method to switch the views based on the keyboard interaction. - static KeyEventResult handleViewSwitchKeyBoardEvent(KeyEvent event, - CalendarController controller, List? allowedViews) { + static KeyEventResult handleViewSwitchKeyBoardEvent( + KeyEvent event, + CalendarController controller, + List? allowedViews, + ) { /// Ctrl + and Ctrl - used by browser to zoom the page, hence as referred /// EJ2 scheduler, we have used alt + numeric to switch between views in /// calendar web and windows @@ -784,7 +870,10 @@ class CalendarViewHelper { /// Check the showWeekNumber is true or not and returns the position. static double getWeekNumberPanelWidth( - bool showWeekNumber, double width, bool isMobilePlatform) { + bool showWeekNumber, + double width, + bool isMobilePlatform, + ) { return showWeekNumber ? (width / (DateTime.daysPerWeek + 1)) / (isMobilePlatform ? 1.3 : 4) : 0; @@ -793,17 +882,18 @@ class CalendarViewHelper { /// Method to check that the current dragging appointment range contains any /// disabled date time in it. static bool isDraggingAppointmentHasDisabledCell( - List timeRegions, - List blackoutDates, - DateTime appStartTime, - DateTime appEndTime, - bool isTimelineView, - bool isMonthView, - DateTime minDate, - DateTime maxDate, - int timeInterval, - int resourceIndex, - List? resources) { + List timeRegions, + List blackoutDates, + DateTime appStartTime, + DateTime appEndTime, + bool isTimelineView, + bool isMonthView, + DateTime minDate, + DateTime maxDate, + int timeInterval, + int resourceIndex, + List? resources, + ) { /// Condition added to check and restrict the appointment rescheduling when /// it exceeds the min/max dates in the calendar. if ((isMonthView && @@ -811,9 +901,17 @@ class CalendarViewHelper { !isDateWithInDateRange(minDate, maxDate, appEndTime))) || (!isMonthView && (!CalendarViewHelper.isDateTimeWithInDateTimeRange( - minDate, maxDate, appStartTime, timeInterval) || + minDate, + maxDate, + appStartTime, + timeInterval, + ) || !CalendarViewHelper.isDateTimeWithInDateTimeRange( - minDate, maxDate, appEndTime, timeInterval)))) { + minDate, + maxDate, + appEndTime, + timeInterval, + )))) { return true; } @@ -963,8 +1061,8 @@ class CalendarAppointment { this.color = Colors.lightBlue, this.isSpanned = false, this.recurrenceExceptionDates, - }) : actualStartTime = startTime, - actualEndTime = endTime; + }) : actualStartTime = startTime, + actualEndTime = endTime; /// The start time for an [CalendarAppointment] in [SfCalendar]. /// @@ -1073,20 +1171,21 @@ class CalendarAppointment { /// the passed calendar appointment value Appointment convertToCalendarAppointment() { return Appointment( - startTime: startTime, - endTime: endTime, - subject: subject, - color: color, - recurrenceRule: recurrenceRule, - isAllDay: isAllDay, - resourceIds: resourceIds, - recurrenceId: recurrenceId, - id: id, - startTimeZone: startTimeZone, - endTimeZone: endTimeZone, - notes: notes, - location: location, - recurrenceExceptionDates: recurrenceExceptionDates); + startTime: startTime, + endTime: endTime, + subject: subject, + color: color, + recurrenceRule: recurrenceRule, + isAllDay: isAllDay, + resourceIds: resourceIds, + recurrenceId: recurrenceId, + id: id, + startTimeZone: startTimeZone, + endTimeZone: endTimeZone, + notes: notes, + location: location, + recurrenceExceptionDates: recurrenceExceptionDates, + ); } @override @@ -1105,12 +1204,18 @@ class CalendarAppointment { } return CalendarViewHelper.isSameTimeSlot( - otherAppointment.startTime, startTime) && + otherAppointment.startTime, + startTime, + ) && CalendarViewHelper.isSameTimeSlot(otherAppointment.endTime, endTime) && CalendarViewHelper.isSameTimeSlot( - otherAppointment.actualStartTime, actualStartTime) && + otherAppointment.actualStartTime, + actualStartTime, + ) && CalendarViewHelper.isSameTimeSlot( - otherAppointment.actualEndTime, actualEndTime) && + otherAppointment.actualEndTime, + actualEndTime, + ) && otherAppointment.isSpanned == isSpanned && otherAppointment.startTimeZone == startTimeZone && otherAppointment.endTimeZone == endTimeZone && @@ -1118,7 +1223,9 @@ class CalendarAppointment { otherAppointment.notes == notes && otherAppointment.location == location && CalendarViewHelper.isCollectionEqual( - otherAppointment.resourceIds, resourceIds) && + otherAppointment.resourceIds, + resourceIds, + ) && otherAppointment.recurrenceId == recurrenceId && otherAppointment.id == id && otherAppointment.data == data && @@ -1126,8 +1233,9 @@ class CalendarAppointment { otherAppointment.color == color && otherAppointment.recurrenceRule == recurrenceRule && CalendarViewHelper.isDateCollectionEqual( - otherAppointment.recurrenceExceptionDates, - recurrenceExceptionDates); + otherAppointment.recurrenceExceptionDates, + recurrenceExceptionDates, + ); } @override @@ -1169,20 +1277,20 @@ class CalendarTimeRegion { /// /// The time region used to highlight and block the specific timeslots in /// timeslots view of [SfCalendar]. - CalendarTimeRegion( - {required this.startTime, - required this.endTime, - this.text, - this.recurrenceRule, - this.color, - this.enablePointerInteraction = true, - this.recurrenceExceptionDates, - this.resourceIds, - this.timeZone, - this.iconData, - this.textStyle}) - : actualStartTime = startTime, - actualEndTime = endTime; + CalendarTimeRegion({ + required this.startTime, + required this.endTime, + this.text, + this.recurrenceRule, + this.color, + this.enablePointerInteraction = true, + this.recurrenceExceptionDates, + this.resourceIds, + this.timeZone, + this.iconData, + this.textStyle, + }) : actualStartTime = startTime, + actualEndTime = endTime; /// Used to specify the start time of the [CalendarTimeRegion]. final DateTime startTime; @@ -1231,32 +1339,34 @@ class CalendarTimeRegion { /// Creates a copy of this [CalendarTimeRegion] but with the given fields /// replaced with the new values. - CalendarTimeRegion copyWith( - {DateTime? startTime, - DateTime? endTime, - String? text, - String? recurrenceRule, - Color? color, - bool? enablePointerInteraction, - List? recurrenceExceptionDates, - String? timeZone, - IconData? iconData, - TextStyle? textStyle, - List? resourceIds}) { + CalendarTimeRegion copyWith({ + DateTime? startTime, + DateTime? endTime, + String? text, + String? recurrenceRule, + Color? color, + bool? enablePointerInteraction, + List? recurrenceExceptionDates, + String? timeZone, + IconData? iconData, + TextStyle? textStyle, + List? resourceIds, + }) { return CalendarTimeRegion( - startTime: startTime ?? this.startTime, - endTime: endTime ?? this.endTime, - color: color ?? this.color, - recurrenceRule: recurrenceRule ?? this.recurrenceRule, - textStyle: textStyle ?? this.textStyle, - enablePointerInteraction: - enablePointerInteraction ?? this.enablePointerInteraction, - recurrenceExceptionDates: - recurrenceExceptionDates ?? this.recurrenceExceptionDates, - text: text ?? this.text, - iconData: iconData ?? this.iconData, - timeZone: timeZone ?? this.timeZone, - resourceIds: resourceIds ?? this.resourceIds); + startTime: startTime ?? this.startTime, + endTime: endTime ?? this.endTime, + color: color ?? this.color, + recurrenceRule: recurrenceRule ?? this.recurrenceRule, + textStyle: textStyle ?? this.textStyle, + enablePointerInteraction: + enablePointerInteraction ?? this.enablePointerInteraction, + recurrenceExceptionDates: + recurrenceExceptionDates ?? this.recurrenceExceptionDates, + text: text ?? this.text, + iconData: iconData ?? this.iconData, + timeZone: timeZone ?? this.timeZone, + resourceIds: resourceIds ?? this.resourceIds, + ); } @override @@ -1277,14 +1387,20 @@ class CalendarTimeRegion { CalendarViewHelper.isSameTimeSlot(region.startTime, startTime) && CalendarViewHelper.isSameTimeSlot(region.endTime, endTime) && CalendarViewHelper.isSameTimeSlot( - region.actualStartTime, actualStartTime) && + region.actualStartTime, + actualStartTime, + ) && CalendarViewHelper.isSameTimeSlot( - region.actualStartTime, actualStartTime) && + region.actualStartTime, + actualStartTime, + ) && region.color == color && region.recurrenceRule == recurrenceRule && region.enablePointerInteraction == enablePointerInteraction && CalendarViewHelper.isDateCollectionEqual( - region.recurrenceExceptionDates, recurrenceExceptionDates) && + region.recurrenceExceptionDates, + recurrenceExceptionDates, + ) && region.iconData == iconData && region.timeZone == timeZone && region.resourceIds == resourceIds && @@ -1295,22 +1411,23 @@ class CalendarTimeRegion { // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode { return Object.hash( - startTime, - endTime, - color, - recurrenceRule, - textStyle, - enablePointerInteraction, - - /// Below condition is referred from text style class - /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html - recurrenceExceptionDates == null - ? null - : Object.hashAll(recurrenceExceptionDates!), - resourceIds == null ? null : Object.hashAll(resourceIds!), - text, - iconData, - timeZone); + startTime, + endTime, + color, + recurrenceRule, + textStyle, + enablePointerInteraction, + + /// Below condition is referred from text style class + /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html + recurrenceExceptionDates == null + ? null + : Object.hashAll(recurrenceExceptionDates!), + resourceIds == null ? null : Object.hashAll(resourceIds!), + text, + iconData, + timeZone, + ); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/date_time_engine.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/date_time_engine.dart index 2ccbe10c8..f8df67538 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/date_time_engine.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/date_time_engine.dart @@ -6,8 +6,12 @@ import 'enums.dart'; /// Holds the static helper methods used for date calculation in calendar. class DateTimeHelper { /// Calculate the visible dates count based on calendar view - static int getViewDatesCount(CalendarView calendarView, int numberOfWeeks, - int daysCount, List? nonWorkingDays) { + static int getViewDatesCount( + CalendarView calendarView, + int numberOfWeeks, + int daysCount, + List? nonWorkingDays, + ) { switch (calendarView) { case CalendarView.month: return DateTime.daysPerWeek * numberOfWeeks; @@ -53,25 +57,28 @@ class DateTimeHelper { /// Calculate the next view visible start date based on calendar view. static DateTime getNextViewStartDate( - CalendarView calendarView, - int numberOfWeeksInView, - DateTime date, - int visibleDatesCount, - List? nonWorkingDays) { + CalendarView calendarView, + int numberOfWeeksInView, + DateTime date, + int visibleDatesCount, + List? nonWorkingDays, + ) { switch (calendarView) { case CalendarView.month: { return numberOfWeeksInView == 6 ? DateTimeHelper.getDateTimeValue(getNextMonthDate(date)) : DateTimeHelper.getDateTimeValue( - addDays(date, numberOfWeeksInView * DateTime.daysPerWeek)); + addDays(date, numberOfWeeksInView * DateTime.daysPerWeek), + ); } case CalendarView.timelineMonth: return DateTimeHelper.getDateTimeValue(getNextMonthDate(date)); case CalendarView.week: case CalendarView.timelineWeek: return DateTimeHelper.getDateTimeValue( - addDays(date, visibleDatesCount)); + addDays(date, visibleDatesCount), + ); case CalendarView.workWeek: case CalendarView.timelineWorkWeek: { @@ -79,7 +86,8 @@ class DateTimeHelper { nonWorkingDays == null ? 0 : nonWorkingDays.length; if (visibleDatesCount + nonWorkingDaysCount == 7) { return DateTimeHelper.getDateTimeValue( - addDays(date, visibleDatesCount + nonWorkingDaysCount)); + addDays(date, visibleDatesCount + nonWorkingDaysCount), + ); } for (int i = 0; i <= visibleDatesCount; i++) { @@ -90,12 +98,14 @@ class DateTimeHelper { } } return DateTimeHelper.getDateTimeValue( - addDays(date, visibleDatesCount)); + addDays(date, visibleDatesCount), + ); } case CalendarView.day: case CalendarView.timelineDay: return DateTimeHelper.getDateTimeValue( - addDays(date, visibleDatesCount)); + addDays(date, visibleDatesCount), + ); case CalendarView.schedule: return DateTimeHelper.getDateTimeValue(addDays(date, 1)); } @@ -103,25 +113,28 @@ class DateTimeHelper { /// Calculate the previous view visible start date based on calendar view. static DateTime getPreviousViewStartDate( - CalendarView calendarView, - int numberOfWeeksInView, - DateTime date, - int visibleDatesCount, - List? nonWorkingDays) { + CalendarView calendarView, + int numberOfWeeksInView, + DateTime date, + int visibleDatesCount, + List? nonWorkingDays, + ) { switch (calendarView) { case CalendarView.month: { return numberOfWeeksInView == 6 ? DateTimeHelper.getDateTimeValue(getPreviousMonthDate(date)) : DateTimeHelper.getDateTimeValue( - addDays(date, -numberOfWeeksInView * DateTime.daysPerWeek)); + addDays(date, -numberOfWeeksInView * DateTime.daysPerWeek), + ); } case CalendarView.timelineMonth: return DateTimeHelper.getDateTimeValue(getPreviousMonthDate(date)); case CalendarView.week: case CalendarView.timelineWeek: return DateTimeHelper.getDateTimeValue( - addDays(date, -visibleDatesCount)); + addDays(date, -visibleDatesCount), + ); case CalendarView.workWeek: case CalendarView.timelineWorkWeek: { @@ -129,7 +142,8 @@ class DateTimeHelper { nonWorkingDays == null ? 0 : nonWorkingDays.length; if (visibleDatesCount + nonWorkingDaysCount == 7) { return DateTimeHelper.getDateTimeValue( - addDays(date, -visibleDatesCount - nonWorkingDaysCount)); + addDays(date, -visibleDatesCount - nonWorkingDaysCount), + ); } for (int i = 1; i <= visibleDatesCount; i++) { final dynamic currentDate = addDays(date, -i); @@ -139,21 +153,26 @@ class DateTimeHelper { } } return DateTimeHelper.getDateTimeValue( - addDays(date, -visibleDatesCount)); + addDays(date, -visibleDatesCount), + ); } case CalendarView.day: case CalendarView.timelineDay: return DateTimeHelper.getDateTimeValue( - addDays(date, -visibleDatesCount)); + addDays(date, -visibleDatesCount), + ); case CalendarView.schedule: return DateTimeHelper.getDateTimeValue(addDays(date, -1)); } } static DateTime _getPreviousValidDate( - DateTime prevViewDate, List nonWorkingDays) { - DateTime previousDate = - DateTimeHelper.getDateTimeValue(addDays(prevViewDate, -1)); + DateTime prevViewDate, + List nonWorkingDays, + ) { + DateTime previousDate = DateTimeHelper.getDateTimeValue( + addDays(prevViewDate, -1), + ); while (nonWorkingDays.contains(previousDate.weekday)) { previousDate = DateTimeHelper.getDateTimeValue(addDays(previousDate, -1)); } @@ -161,9 +180,12 @@ class DateTimeHelper { } static DateTime _getNextValidDate( - DateTime nextDate, List nonWorkingDays) { - DateTime nextViewDate = - DateTimeHelper.getDateTimeValue(addDays(nextDate, 1)); + DateTime nextDate, + List nonWorkingDays, + ) { + DateTime nextViewDate = DateTimeHelper.getDateTimeValue( + addDays(nextDate, 1), + ); while (nonWorkingDays.contains(nextViewDate.weekday)) { nextViewDate = DateTimeHelper.getDateTimeValue(addDays(nextViewDate, 1)); } @@ -214,31 +236,40 @@ class DateTimeHelper { /// Check the current calendar view is valid for move to previous view or not. static bool canMoveToPreviousView( - CalendarView calendarView, - int numberOfWeeksInView, - DateTime minDate, - DateTime maxDate, - List visibleDates, - List nonWorkingDays, - [bool isRTL = false]) { + CalendarView calendarView, + int numberOfWeeksInView, + DateTime minDate, + DateTime maxDate, + List visibleDates, + List nonWorkingDays, [ + bool isRTL = false, + ]) { if (isRTL) { - return canMoveToNextView(calendarView, numberOfWeeksInView, minDate, - maxDate, visibleDates, nonWorkingDays); + return canMoveToNextView( + calendarView, + numberOfWeeksInView, + minDate, + maxDate, + visibleDates, + nonWorkingDays, + ); } switch (calendarView) { case CalendarView.month: { if (numberOfWeeksInView != 6) { - final DateTime prevViewDate = - DateTimeHelper.getDateTimeValue(addDays(visibleDates[0], -1)); + final DateTime prevViewDate = DateTimeHelper.getDateTimeValue( + addDays(visibleDates[0], -1), + ); if (!isSameOrAfterDate(minDate, prevViewDate)) { return false; } } else { final DateTime currentDate = visibleDates[visibleDates.length ~/ 2]; final DateTime previousDate = DateTimeHelper.getDateTimeValue( - getPreviousMonthDate(currentDate)); + getPreviousMonthDate(currentDate), + ); if ((previousDate.month < minDate.month && previousDate.year == minDate.year) || previousDate.year < minDate.year) { @@ -249,8 +280,9 @@ class DateTimeHelper { break; case CalendarView.timelineMonth: { - final DateTime prevViewDate = - DateTimeHelper.getDateTimeValue(addDays(visibleDates[0], -1)); + final DateTime prevViewDate = DateTimeHelper.getDateTimeValue( + addDays(visibleDates[0], -1), + ); if (!isSameOrAfterDate(minDate, prevViewDate)) { return false; } @@ -262,8 +294,9 @@ class DateTimeHelper { case CalendarView.timelineWeek: { DateTime prevViewDate = visibleDates[0]; - prevViewDate = - DateTimeHelper.getDateTimeValue(addDays(prevViewDate, -1)); + prevViewDate = DateTimeHelper.getDateTimeValue( + addDays(prevViewDate, -1), + ); if (!isSameOrAfterDate(minDate, prevViewDate)) { return false; } @@ -272,8 +305,10 @@ class DateTimeHelper { case CalendarView.timelineWorkWeek: case CalendarView.workWeek: { - final DateTime previousDate = - _getPreviousValidDate(visibleDates[0], nonWorkingDays); + final DateTime previousDate = _getPreviousValidDate( + visibleDates[0], + nonWorkingDays, + ); if (!isSameOrAfterDate(minDate, previousDate)) { return false; } @@ -288,16 +323,23 @@ class DateTimeHelper { /// Check the current calendar view is valid for move to next view or not. static bool canMoveToNextView( - CalendarView calendarView, - int numberOfWeeksInView, - DateTime minDate, - DateTime maxDate, - List visibleDates, - List nonWorkingDays, - [bool isRTL = false]) { + CalendarView calendarView, + int numberOfWeeksInView, + DateTime minDate, + DateTime maxDate, + List visibleDates, + List nonWorkingDays, [ + bool isRTL = false, + ]) { if (isRTL) { - return canMoveToPreviousView(calendarView, numberOfWeeksInView, minDate, - maxDate, visibleDates, nonWorkingDays); + return canMoveToPreviousView( + calendarView, + numberOfWeeksInView, + minDate, + maxDate, + visibleDates, + nonWorkingDays, + ); } switch (calendarView) { @@ -305,14 +347,16 @@ class DateTimeHelper { { if (numberOfWeeksInView != 6) { final DateTime nextViewDate = DateTimeHelper.getDateTimeValue( - addDays(visibleDates[visibleDates.length - 1], 1)); + addDays(visibleDates[visibleDates.length - 1], 1), + ); if (!isSameOrBeforeDate(maxDate, nextViewDate)) { return false; } } else { final DateTime currentDate = visibleDates[visibleDates.length ~/ 2]; - final DateTime nextDate = - DateTimeHelper.getDateTimeValue(getNextMonthDate(currentDate)); + final DateTime nextDate = DateTimeHelper.getDateTimeValue( + getNextMonthDate(currentDate), + ); if ((nextDate.month > maxDate.month && nextDate.year == maxDate.year) || nextDate.year > maxDate.year) { @@ -324,7 +368,8 @@ class DateTimeHelper { case CalendarView.timelineMonth: { final DateTime nextViewDate = DateTimeHelper.getDateTimeValue( - addDays(visibleDates[visibleDates.length - 1], 1)); + addDays(visibleDates[visibleDates.length - 1], 1), + ); if (!isSameOrBeforeDate(maxDate, nextViewDate)) { return false; } @@ -336,7 +381,8 @@ class DateTimeHelper { case CalendarView.timelineWeek: { final DateTime nextViewDate = DateTimeHelper.getDateTimeValue( - addDays(visibleDates[visibleDates.length - 1], 1)); + addDays(visibleDates[visibleDates.length - 1], 1), + ); if (!isSameOrBeforeDate(maxDate, nextViewDate)) { return false; } @@ -346,7 +392,9 @@ class DateTimeHelper { case CalendarView.timelineWorkWeek: { final DateTime nextDate = _getNextValidDate( - visibleDates[visibleDates.length - 1], nonWorkingDays); + visibleDates[visibleDates.length - 1], + nonWorkingDays, + ); if (!isSameOrBeforeDate(maxDate, nextDate)) { return false; } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/enums.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/enums.dart index e0f12ae25..62a5a0118 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/enums.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/enums.dart @@ -8,7 +8,7 @@ enum MonthNavigationDirection { vertical, /// - MonthNavigationDirection.horizontal, Navigates in left and top direction - horizontal + horizontal, } /// Available views for [SfCalendar]. @@ -46,7 +46,7 @@ enum CalendarView { timelineMonth, /// - CalendarView.schedule, displays the schedule view. - schedule + schedule, } /// Available appointment display mode for [SfCalendar] month cell. @@ -60,7 +60,7 @@ enum MonthAppointmentDisplayMode { appointment, /// - MonthAppointmentDisplayMode.none, doesn't display appointment on view. - none + none, } /// Available recurrence types for [Appointment] in [SfCalendar] @@ -94,7 +94,7 @@ enum RecurrenceRange { /// - RecurrenceRange.count, indicates the appointment occurrence repeated /// with specified count times. - count + count, } /// The week days occurrence of [Appointment]. @@ -118,7 +118,7 @@ enum WeekDays { friday, /// - WeekDays.saturday, indicates the appointment occurred in saturday. - saturday + saturday, } /// The available calendar elements for the [CalendarTapDetails] in [SfCalendar] @@ -167,7 +167,7 @@ enum CalendarElement { /// /// _Note: _This element applies to the timeline views with resource assigned /// to the calendar data source. - resourceHeader + resourceHeader, } /// Action performed in data source @@ -208,7 +208,7 @@ enum CalendarDataSourceAction { /// the resource collection will be reset. /// /// _Note:_ This is applicable only when the resource collection reset. - resetResource + resetResource, } /// Available view navigation modes for [SfCalendar]. @@ -227,7 +227,7 @@ enum ViewNavigationMode { /// It will not impact scrolling timeslot views, /// [controller.forward], [controller.backward] /// and [showNavigationArrow]. - none + none, } /// Available Appointment types for [Appointment] @@ -247,5 +247,5 @@ enum AppointmentType { /// - AppointmentType.pattern, this specifies the pattern appointment /// which has the RRule value and it is the pattern for the /// occurrence appointment in the recurrence series. - pattern + pattern, } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/event_args.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/event_args.dart index a59c046be..51bc89c9e 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/common/event_args.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/common/event_args.dart @@ -32,9 +32,12 @@ class ViewChangedDetails { @immutable class CalendarTapDetails extends CalendarTouchDetails { /// Creates details for [CalendarTapCallback]. - const CalendarTapDetails(List? appointments, DateTime? date, - CalendarElement element, CalendarResource? resource) - : super(appointments, date, element, resource); + const CalendarTapDetails( + List? appointments, + DateTime? date, + CalendarElement element, + CalendarResource? resource, + ) : super(appointments, date, element, resource); } /// The element that long pressed on view in [SfCalendar] @@ -50,9 +53,12 @@ class CalendarTapDetails extends CalendarTouchDetails { @immutable class CalendarLongPressDetails extends CalendarTouchDetails { /// Creates details for [CalendarLongPressCallback] - const CalendarLongPressDetails(List? appointments, DateTime? date, - CalendarElement element, CalendarResource? resource) - : super(appointments, date, element, resource); + const CalendarLongPressDetails( + List? appointments, + DateTime? date, + CalendarElement element, + CalendarResource? resource, + ) : super(appointments, date, element, resource); } /// The element that tapped on view in [SfCalendar] @@ -92,7 +98,11 @@ class CalendarSelectionDetails { class CalendarTouchDetails { /// Creates details for [CalendarTapCallback] and [CalendarLongPressCallback]. const CalendarTouchDetails( - this.appointments, this.date, this.targetElement, this.resource); + this.appointments, + this.date, + this.targetElement, + this.resource, + ); /// The collection of appointments that return from the date. final List? appointments; @@ -141,7 +151,11 @@ class AppointmentResizeStartDetails { class AppointmentResizeUpdateDetails { /// Creates details for [AppointmentResizeUpdateCallback]. const AppointmentResizeUpdateDetails( - this.appointment, this.resource, this.resizingTime, this.resizingOffset); + this.appointment, + this.resource, + this.resizingTime, + this.resizingOffset, + ); /// The appointment that resizing on view in [SfCalendar]. final dynamic appointment; @@ -169,7 +183,11 @@ class AppointmentResizeUpdateDetails { class AppointmentResizeEndDetails { /// Creates details for [AppointmentResizeUpdateCallback]. const AppointmentResizeEndDetails( - this.appointment, this.resource, this.startTime, this.endTime); + this.appointment, + this.resource, + this.startTime, + this.endTime, + ); /// The appointment that resized on view in [SfCalendar]. final dynamic appointment; @@ -220,8 +238,13 @@ class AppointmentDragStartDetails { @immutable class AppointmentDragUpdateDetails { /// Creates details for [AppointmentDragUpdateCallback]. - const AppointmentDragUpdateDetails(this.appointment, this.sourceResource, - this.targetResource, this.draggingPosition, this.draggingTime); + const AppointmentDragUpdateDetails( + this.appointment, + this.sourceResource, + this.targetResource, + this.draggingPosition, + this.draggingTime, + ); /// The dragging appointment. final Object? appointment; @@ -251,8 +274,12 @@ class AppointmentDragUpdateDetails { /// in calendar. class AppointmentDragEndDetails { /// Creates details for [AppointmentDragEndCallback]. - const AppointmentDragEndDetails(this.appointment, this.sourceResource, - this.targetResource, this.droppingTime); + const AppointmentDragEndDetails( + this.appointment, + this.sourceResource, + this.targetResource, + this.droppingTime, + ); /// The dropping appointment. final Object? appointment; @@ -272,9 +299,12 @@ class AppointmentDragEndDetails { @immutable class CalendarDetails extends CalendarTouchDetails { /// creates details for [CalendarDetailsCallback]. - const CalendarDetails(List? appointments, DateTime? date, - CalendarElement element, CalendarResource? resource) - : super(appointments, date, element, resource); + const CalendarDetails( + List? appointments, + DateTime? date, + CalendarElement element, + CalendarResource? resource, + ) : super(appointments, date, element, resource); } /// Signature for a function that creates a widget based on month @@ -283,32 +313,38 @@ class CalendarDetails extends CalendarTouchDetails { /// See also: /// * [SfCalendar.scheduleViewMonthHeaderBuilder], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef ScheduleViewMonthHeaderBuilder = Widget Function( - BuildContext context, ScheduleViewMonthHeaderDetails details); +typedef ScheduleViewMonthHeaderBuilder = + Widget Function( + BuildContext context, + ScheduleViewMonthHeaderDetails details, + ); /// Signature for a function that creates a widget based on month cell details. /// /// See also: /// * [SfCalendar.monthCellBuilder], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef MonthCellBuilder = Widget Function( - BuildContext context, MonthCellDetails details); +typedef MonthCellBuilder = + Widget Function(BuildContext context, MonthCellDetails details); /// Signature for a function that creates a widget based on appointment details. /// /// See also: /// * [SfCalendar.appointmentBuilder], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef CalendarAppointmentBuilder = Widget Function(BuildContext context, - CalendarAppointmentDetails calendarAppointmentDetails); +typedef CalendarAppointmentBuilder = + Widget Function( + BuildContext context, + CalendarAppointmentDetails calendarAppointmentDetails, + ); /// Signature for a function that creates a widget based on time region details. /// /// See also: /// * [SfCalendar.timeRegionBuilder], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef TimeRegionBuilder = Widget Function( - BuildContext context, TimeRegionDetails timeRegionDetails); +typedef TimeRegionBuilder = + Widget Function(BuildContext context, TimeRegionDetails timeRegionDetails); /// Signature for the function that create the widget based on load /// more details. @@ -316,8 +352,11 @@ typedef TimeRegionBuilder = Widget Function( /// See also: /// * [SfCalendar.loadMoreWidgetBuilder], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef LoadMoreWidgetBuilder = Widget Function( - BuildContext context, LoadMoreCallback loadMoreAppointments); +typedef LoadMoreWidgetBuilder = + Widget Function( + BuildContext context, + LoadMoreCallback loadMoreAppointments, + ); /// Signature for the function that have no arguments and return no data, but /// that return a [Future] to indicate when their work is complete. @@ -333,8 +372,8 @@ typedef LoadMoreCallback = Future Function(); /// See also: /// * [SfCalendar.resourceViewHeaderBuilder], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef ResourceViewHeaderBuilder = Widget Function( - BuildContext context, ResourceViewHeaderDetails details); +typedef ResourceViewHeaderBuilder = + Widget Function(BuildContext context, ResourceViewHeaderDetails details); /// Contains the details that needed on month cell builder. /// @@ -347,7 +386,11 @@ typedef ResourceViewHeaderBuilder = Widget Function( class MonthCellDetails { /// Default constructor to store the details needed in month cell builder const MonthCellDetails( - this.date, this.appointments, this.visibleDates, this.bounds); + this.date, + this.appointments, + this.visibleDates, + this.bounds, + ); /// The date value associated with the month cell widget. final DateTime date; @@ -386,8 +429,12 @@ class ScheduleViewMonthHeaderDetails { /// * [SfCalendar], which passes the information to one of its receiver. class CalendarAppointmentDetails { /// Default constructor to store the details needed in appointment builder. - const CalendarAppointmentDetails(this.date, this.appointments, this.bounds, - {this.isMoreAppointmentRegion = false}); + const CalendarAppointmentDetails( + this.date, + this.appointments, + this.bounds, { + this.isMoreAppointmentRegion = false, + }); /// The date value associated with the appointment view widget. final DateTime date; @@ -455,8 +502,8 @@ class ResourceViewHeaderDetails { /// See also: /// * [SfCalendar.onViewChanged], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef ViewChangedCallback = void Function( - ViewChangedDetails viewChangedDetails); +typedef ViewChangedCallback = + void Function(ViewChangedDetails viewChangedDetails); /// Signature for callback that reports that a calendar element tapped on view. /// @@ -468,8 +515,8 @@ typedef ViewChangedCallback = void Function( /// See also: /// * [SfCalendar.onTap], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef CalendarTapCallback = void Function( - CalendarTapDetails calendarTapDetails); +typedef CalendarTapCallback = + void Function(CalendarTapDetails calendarTapDetails); /// Signature for callback that reports that a calendar element long pressed /// on view. @@ -482,8 +529,8 @@ typedef CalendarTapCallback = void Function( /// See also: /// * [SfCalendar.onLongPress], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef CalendarLongPressCallback = void Function( - CalendarLongPressDetails calendarLongPressDetails); +typedef CalendarLongPressCallback = + void Function(CalendarLongPressDetails calendarLongPressDetails); /// Signature for callback that reports that /// a calendar view selection changed on view. @@ -497,8 +544,8 @@ typedef CalendarLongPressCallback = void Function( /// See also: /// * [SfCalendar.onSelectionChanged], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef CalendarSelectionChangedCallback = void Function( - CalendarSelectionDetails calendarSelectionDetails); +typedef CalendarSelectionChangedCallback = + void Function(CalendarSelectionDetails calendarSelectionDetails); /// Signature for callback that reports that a appointment starts resizing in /// [SfCalendar]. @@ -511,8 +558,8 @@ typedef CalendarSelectionChangedCallback = void Function( /// See also: /// * [SfCalendar.onAppointmentResizeStart], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef AppointmentResizeStartCallback = void Function( - AppointmentResizeStartDetails appointmentResizeStartDetails); +typedef AppointmentResizeStartCallback = + void Function(AppointmentResizeStartDetails appointmentResizeStartDetails); /// Signature for callback that reports that a appointment resizing in /// [SfCalendar]. @@ -525,8 +572,10 @@ typedef AppointmentResizeStartCallback = void Function( /// See also: /// * [SfCalendar.onAppointmentResizeUpdate], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef AppointmentResizeUpdateCallback = void Function( - AppointmentResizeUpdateDetails appointmentResizeUpdateDetails); +typedef AppointmentResizeUpdateCallback = + void Function( + AppointmentResizeUpdateDetails appointmentResizeUpdateDetails, + ); /// Signature for callback that reports that a appointment resizing completed in /// [SfCalendar]. @@ -540,8 +589,8 @@ typedef AppointmentResizeUpdateCallback = void Function( /// See also: /// * [SfCalendar.onAppointmentResizeEnd], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef AppointmentResizeEndCallback = void Function( - AppointmentResizeEndDetails appointmentResizeEndDetails); +typedef AppointmentResizeEndCallback = + void Function(AppointmentResizeEndDetails appointmentResizeEndDetails); /// Signature for callback that reports that a appointment starts dragging in /// [SfCalendar]. @@ -554,8 +603,8 @@ typedef AppointmentResizeEndCallback = void Function( /// See also: /// * [SfCalendar.onDragStart], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef AppointmentDragStartCallback = void Function( - AppointmentDragStartDetails appointmentDragStartDetails); +typedef AppointmentDragStartCallback = + void Function(AppointmentDragStartDetails appointmentDragStartDetails); /// Signature for callback that reports that a appointment dragging in /// [SfCalendar]. @@ -569,8 +618,8 @@ typedef AppointmentDragStartCallback = void Function( /// See also: /// * [SfCalendar.onDragUpdate], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef AppointmentDragUpdateCallback = void Function( - AppointmentDragUpdateDetails appointmentDragUpdateDetails); +typedef AppointmentDragUpdateCallback = + void Function(AppointmentDragUpdateDetails appointmentDragUpdateDetails); /// Signature for callback that reports that a appointment dragging completed in /// [SfCalendar]. @@ -584,5 +633,5 @@ typedef AppointmentDragUpdateCallback = void Function( /// See also: /// * [SfCalendar.onDragEnd], which matches this signature. /// * [SfCalendar], which uses this signature in one of it's callback. -typedef AppointmentDragEndCallback = void Function( - AppointmentDragEndDetails appointmentDragEndDetails); +typedef AppointmentDragEndCallback = + void Function(AppointmentDragEndDetails appointmentDragEndDetails); diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/calendar_resource.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/calendar_resource.dart index b807d9302..20aa4f436 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/calendar_resource.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/calendar_resource.dart @@ -82,11 +82,12 @@ class CalendarResource with Diagnosticable { /// /// An object that contains properties to hold the detailed information /// about the data, which will be rendered in [SfCalendar]. - CalendarResource( - {this.displayName = '', - required this.id, - this.image, - this.color = Colors.lightBlue}); + CalendarResource({ + this.displayName = '', + required this.id, + this.image, + this.color = Colors.lightBlue, + }); /// The name which displayed on the [CalendarResource] view of [SfCalendar]. /// diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/resource_view.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/resource_view.dart index 0c1a397a8..76aff4c11 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/resource_view.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/resource_view/resource_view.dart @@ -10,21 +10,22 @@ class ResourceViewWidget extends StatefulWidget { /// Constructor to create the resource view widget to holds resource view on /// all timeline views. const ResourceViewWidget( - this.resources, - this.resourceViewSettings, - this.resourceItemHeight, - this.cellBorderColor, - this.calendarTheme, - this.themeData, - this.notifier, - this.isRTL, - this.textScaleFactor, - this.mouseHoverPosition, - this.imagePainterCollection, - this.width, - this.panelHeight, - this.resourceViewHeaderBuilder, - {super.key}); + this.resources, + this.resourceViewSettings, + this.resourceItemHeight, + this.cellBorderColor, + this.calendarTheme, + this.themeData, + this.notifier, + this.isRTL, + this.textScaleFactor, + this.mouseHoverPosition, + this.imagePainterCollection, + this.width, + this.panelHeight, + this.resourceViewHeaderBuilder, { + super.key, + }); /// Holds the resources of the calendar. final List? resources; @@ -83,11 +84,17 @@ class _ResourceViewWidgetState extends State { for (int i = 0; i < resourceLength; i++) { final CalendarResource currentResource = widget.resources![i]; final Widget child = widget.resourceViewHeaderBuilder!( - context, - ResourceViewHeaderDetails( - currentResource, - Rect.fromLTWH( - 0, yPosition, widget.width, widget.resourceItemHeight))); + context, + ResourceViewHeaderDetails( + currentResource, + Rect.fromLTWH( + 0, + yPosition, + widget.width, + widget.resourceItemHeight, + ), + ), + ); children.add(RepaintBoundary(child: child)); yPosition += widget.resourceItemHeight; } @@ -114,21 +121,21 @@ class _ResourceViewWidgetState extends State { class _ResourceViewRenderObjectWidget extends MultiChildRenderObjectWidget { const _ResourceViewRenderObjectWidget( - this.resources, - this.resourceViewSettings, - this.resourceItemHeight, - this.cellBorderColor, - this.calendarTheme, - this.themeData, - this.notifier, - this.isRTL, - this.textScaleFactor, - this.mouseHoverPosition, - this.imagePainterCollection, - this.width, - this.panelHeight, - {List children = const []}) - : super(children: children); + this.resources, + this.resourceViewSettings, + this.resourceItemHeight, + this.cellBorderColor, + this.calendarTheme, + this.themeData, + this.notifier, + this.isRTL, + this.textScaleFactor, + this.mouseHoverPosition, + this.imagePainterCollection, + this.width, + this.panelHeight, { + List children = const [], + }) : super(children: children); final List? resources; final ResourceViewSettings resourceViewSettings; @@ -147,24 +154,27 @@ class _ResourceViewRenderObjectWidget extends MultiChildRenderObjectWidget { @override _ResourceViewRenderObject createRenderObject(BuildContext context) { return _ResourceViewRenderObject( - resources, - resourceViewSettings, - resourceItemHeight, - cellBorderColor, - calendarTheme, - themeData, - notifier, - isRTL, - textScaleFactor, - mouseHoverPosition, - imagePainterCollection, - width, - panelHeight); + resources, + resourceViewSettings, + resourceItemHeight, + cellBorderColor, + calendarTheme, + themeData, + notifier, + isRTL, + textScaleFactor, + mouseHoverPosition, + imagePainterCollection, + width, + panelHeight, + ); } @override void updateRenderObject( - BuildContext context, _ResourceViewRenderObject renderObject) { + BuildContext context, + _ResourceViewRenderObject renderObject, + ) { renderObject ..resources = resources ..resourceViewSettings = resourceViewSettings @@ -184,19 +194,20 @@ class _ResourceViewRenderObjectWidget extends MultiChildRenderObjectWidget { class _ResourceViewRenderObject extends CustomCalendarRenderObject { _ResourceViewRenderObject( - this._resources, - this._resourceViewSettings, - this._resourceItemHeight, - this._cellBorderColor, - this._calendarTheme, - this._themeData, - this._notifier, - this._isRTL, - this._textScaleFactor, - this._mouseHoverPosition, - this._imagePainterCollection, - this._width, - this._panelHeight); + this._resources, + this._resourceViewSettings, + this._resourceItemHeight, + this._cellBorderColor, + this._calendarTheme, + this._themeData, + this._notifier, + this._isRTL, + this._textScaleFactor, + this._mouseHoverPosition, + this._imagePainterCollection, + this._width, + this._panelHeight, + ); List? _resources; @@ -418,15 +429,20 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? panelHeight : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? panelHeight : widgetSize.height, + ); for (dynamic child = firstChild; child != null; child = childAfter(child)) { - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minWidth: width, minHeight: resourceItemHeight, maxWidth: width, - maxHeight: resourceItemHeight)); + maxHeight: resourceItemHeight, + ), + ); } } @@ -445,11 +461,11 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { child = childAfter(child); if (mouseHoverPosition != null) { - final Color resourceHoveringColor = - (themeData.brightness == Brightness.dark - ? Colors.white - : Colors.black87) - .withValues(alpha: 0.04); + final Color resourceHoveringColor = (themeData.brightness == + Brightness.dark + ? Colors.white + : Colors.black87) + .withValues(alpha: 0.04); _addHovering(context.canvas, size, yPosition, resourceHoveringColor); } @@ -472,9 +488,10 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { final double actualItemHeight = resourceItemHeight * 0.80; double yPosition = 0; _circlePainter.isAntiAlias = true; - final double radius = actualItemHeight < actualItemWidth - ? actualItemHeight / 2 - : actualItemWidth / 2; + final double radius = + actualItemHeight < actualItemWidth + ? actualItemHeight / 2 + : actualItemWidth / 2; final Color resourceCellBorderColor = cellBorderColor ?? calendarTheme.cellBorderColor!; final Color resourceHoveringColor = (themeData.brightness == Brightness.dark @@ -486,25 +503,50 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { _circlePainter.strokeWidth = 0.5; _circlePainter.style = PaintingStyle.stroke; final double lineXPosition = isRTL ? 0.5 : size.width - 0.5; - canvas.drawLine(Offset(lineXPosition, 0), - Offset(lineXPosition, size.height), _circlePainter); + canvas.drawLine( + Offset(lineXPosition, 0), + Offset(lineXPosition, size.height), + _circlePainter, + ); final int count = resources!.length; if (resourceViewSettings.showAvatar) { for (int i = 0; i < count; i++) { canvas.save(); final CalendarResource resource = resources![i]; _drawResourceBorder( - resource, canvas, size, actualItemHeight, yPosition, radius); - _drawDisplayName(resource, displayNameTextStyle, canvas, size, - yPosition, actualItemHeight, radius); + resource, + canvas, + size, + actualItemHeight, + yPosition, + radius, + ); + _drawDisplayName( + resource, + displayNameTextStyle, + canvas, + size, + yPosition, + actualItemHeight, + radius, + ); _circlePainter.style = PaintingStyle.fill; - _drawInnerCircle(resource, canvas, size, actualItemWidth, - actualItemHeight, yPosition); + _drawInnerCircle( + resource, + canvas, + size, + actualItemWidth, + actualItemHeight, + yPosition, + ); _circlePainter.color = resourceCellBorderColor; _circlePainter.strokeWidth = 0.5; _circlePainter.style = PaintingStyle.stroke; - canvas.drawLine(Offset(0, yPosition), Offset(size.width, yPosition), - _circlePainter); + canvas.drawLine( + Offset(0, yPosition), + Offset(size.width, yPosition), + _circlePainter, + ); if (mouseHoverPosition != null) { _addHovering(canvas, size, yPosition, resourceHoveringColor); @@ -517,8 +559,15 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { for (int i = 0; i < count; i++) { final CalendarResource resource = resources![i]; _drawResourceBackground(canvas, size, resource, yPosition); - _drawDisplayName(resource, displayNameTextStyle, canvas, size, - yPosition, actualItemHeight, radius); + _drawDisplayName( + resource, + displayNameTextStyle, + canvas, + size, + yPosition, + actualItemHeight, + radius, + ); _addHovering(canvas, size, yPosition, resourceHoveringColor); yPosition += resourceItemHeight; } @@ -526,7 +575,11 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { } void _addHovering( - Canvas canvas, Size size, double yPosition, Color resourceHoveringColor) { + Canvas canvas, + Size size, + double yPosition, + Color resourceHoveringColor, + ) { if (mouseHoverPosition != null && mouseHoverPosition!.dy > yPosition && mouseHoverPosition!.dy < (yPosition + resourceItemHeight)) { @@ -534,19 +587,25 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { _circlePainter.color = resourceHoveringColor; const double padding = 0.5; canvas.drawRect( - Rect.fromLTWH(0, yPosition, size.width, resourceItemHeight - padding), - _circlePainter); + Rect.fromLTWH(0, yPosition, size.width, resourceItemHeight - padding), + _circlePainter, + ); } } void _drawResourceBackground( - Canvas canvas, Size size, CalendarResource resource, double yPosition) { + Canvas canvas, + Size size, + CalendarResource resource, + double yPosition, + ) { const double padding = 0.5; _circlePainter.color = resource.color; _circlePainter.style = PaintingStyle.fill; canvas.drawRect( - Rect.fromLTWH(0, yPosition, size.width, resourceItemHeight - padding), - _circlePainter); + Rect.fromLTWH(0, yPosition, size.width, resourceItemHeight - padding), + _circlePainter, + ); } /// Updates the text painter with the passed span. @@ -559,12 +618,19 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { } /// Draws the outer circle border for the resource view. - void _drawResourceBorder(CalendarResource resource, Canvas canvas, Size size, - double actualItemHeight, double yPosition, double radius) { + void _drawResourceBorder( + CalendarResource resource, + Canvas canvas, + Size size, + double actualItemHeight, + double yPosition, + double radius, + ) { /// When the large text size given, the text must be cliped instead of /// overflow into next resource view, hence cliped the canvas. - canvas - .clipRect(Rect.fromLTWH(0, yPosition, size.width, resourceItemHeight)); + canvas.clipRect( + Rect.fromLTWH(0, yPosition, size.width, resourceItemHeight), + ); _circlePainter.color = resource.color; _circlePainter.strokeWidth = _borderThickness; _circlePainter.style = PaintingStyle.stroke; @@ -572,49 +638,59 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { final double startYPosition = (_borderThickness / 2) + yPosition + actualItemHeight / 2; canvas.drawCircle( - Offset(startXPosition, startYPosition), radius, _circlePainter); + Offset(startXPosition, startYPosition), + radius, + _circlePainter, + ); } /// Draws the display name of the resource under the circle. void _drawDisplayName( - CalendarResource resource, - TextStyle displayNameTextStyle, - Canvas canvas, - Size size, - double yPosition, - double actualItemHeight, - double radius) { - final TextSpan span = - TextSpan(text: resource.displayName, style: displayNameTextStyle); + CalendarResource resource, + TextStyle displayNameTextStyle, + Canvas canvas, + Size size, + double yPosition, + double actualItemHeight, + double radius, + ) { + final TextSpan span = TextSpan( + text: resource.displayName, + style: displayNameTextStyle, + ); _updateNamePainter(span); _namePainter.layout(maxWidth: size.width); final double startXPosition = (size.width - _namePainter.width) / 2; - final double startYPosition = resourceViewSettings.showAvatar - ? (yPosition + (actualItemHeight / 2)) + - _borderThickness + - radius + - (_borderThickness / 2) - : yPosition + ((resourceItemHeight - _namePainter.height) / 2); + final double startYPosition = + resourceViewSettings.showAvatar + ? (yPosition + (actualItemHeight / 2)) + + _borderThickness + + radius + + (_borderThickness / 2) + : yPosition + ((resourceItemHeight - _namePainter.height) / 2); _namePainter.paint(canvas, Offset(startXPosition, startYPosition)); } /// Draws the image assigned to the resource, in the inside circle. void _drawImage( - Canvas canvas, - Size size, - CalendarResource resource, - double innerCircleYPosition, - double innerCircleXPosition, - double innerCircleWidth, - double innerCircleHeight) { + Canvas canvas, + Size size, + CalendarResource resource, + double innerCircleYPosition, + double innerCircleXPosition, + double innerCircleWidth, + double innerCircleHeight, + ) { final Offset offset = Offset(innerCircleXPosition, innerCircleYPosition); final Size size = Size(innerCircleWidth, innerCircleHeight); final ImageConfiguration configuration = ImageConfiguration(size: size); final Rect rect = offset & size; /// To render the image as circle. - final Rect square = - Rect.fromCircle(center: rect.center, radius: rect.shortestSide / 2.0); + final Rect square = Rect.fromCircle( + center: rect.center, + radius: rect.shortestSide / 2.0, + ); final Path clipPath = Path()..addOval(square); final DecorationImagePainter? imagePainter = _getImagePainter(resource); if (imagePainter == null) { @@ -627,15 +703,17 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { DecorationImagePainter? _getImagePainter(CalendarResource resource) { if (imagePainterCollection.isEmpty || !imagePainterCollection.containsKey(resource.id)) { - return DecorationImage(image: resource.image!) - .createPainter(_onPainterChanged); + return DecorationImage( + image: resource.image!, + ).createPainter(_onPainterChanged); } else if (imagePainterCollection.containsKey(resource.id) && - !imagePainterCollection[resource.id] - .toString() - .contains(resource.image.toString())) { + !imagePainterCollection[resource.id].toString().contains( + resource.image.toString(), + )) { imagePainterCollection[resource.id]!.dispose(); - return DecorationImage(image: resource.image!) - .createPainter(_onPainterChanged); + return DecorationImage( + image: resource.image!, + ).createPainter(_onPainterChanged); } return imagePainterCollection[resource.id]; @@ -654,38 +732,60 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { /// Draws the inner circle for the resource with the short term of the /// display name, and fills the resources color in background. - void _drawInnerCircle(CalendarResource resource, Canvas canvas, Size size, - double actualItemWidth, double actualItemHeight, double yPosition) { + void _drawInnerCircle( + CalendarResource resource, + Canvas canvas, + Size size, + double actualItemWidth, + double actualItemHeight, + double yPosition, + ) { const double padding = 0.3; final double innerCircleWidth = actualItemWidth - (_borderThickness * 2) - (padding * 2); final double innerCircleHeight = actualItemHeight - (_borderThickness * 2) - (padding * 2); - final double innerRadius = innerCircleWidth > innerCircleHeight - ? innerCircleHeight / 2 - : innerCircleWidth / 2; + final double innerRadius = + innerCircleWidth > innerCircleHeight + ? innerCircleHeight / 2 + : innerCircleWidth / 2; final double innerCircleXPosition = (size.width - actualItemWidth) / 2 + _borderThickness + padding; final double innerCircleYPosition = (_borderThickness / 2) + yPosition + _borderThickness + padding; if (resource.image != null) { - _drawImage(canvas, size, resource, innerCircleYPosition, - innerCircleXPosition, innerCircleWidth, innerCircleHeight); + _drawImage( + canvas, + size, + resource, + innerCircleYPosition, + innerCircleXPosition, + innerCircleWidth, + innerCircleHeight, + ); return; } double startXPosition = innerCircleXPosition + (innerCircleWidth / 2); double startYPosition = innerCircleYPosition + (innerCircleHeight / 2); canvas.drawCircle( - Offset(startXPosition, startYPosition), innerRadius, _circlePainter); + Offset(startXPosition, startYPosition), + innerRadius, + _circlePainter, + ); final List splitName = resource.displayName.split(' '); - final String shortName = splitName.length > 1 - ? splitName[0].substring(0, 1) + splitName[1].substring(0, 1) - : splitName[0].substring(0, 1); + final String shortName = + splitName.length > 1 + ? splitName[0].substring(0, 1) + splitName[1].substring(0, 1) + : splitName[0].substring(0, 1); final TextSpan span = TextSpan( - text: shortName, - style: themeData.textTheme.bodyLarge!.copyWith( - color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500)); + text: shortName, + style: themeData.textTheme.bodyLarge!.copyWith( + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.w500, + ), + ); _updateNamePainter(span); _namePainter.layout(maxWidth: innerCircleWidth); startXPosition = @@ -704,13 +804,15 @@ class _ResourceViewRenderObject extends CustomCalendarRenderObject { double top = 0; for (int j = 0; j < resources!.length; j++) { final CalendarResource resource = resources![j]; - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(0, top, size.width, resourceItemHeight), - properties: SemanticsProperties( - label: resource.displayName + resource.id.toString(), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(0, top, size.width, resourceItemHeight), + properties: SemanticsProperties( + label: resource.displayName + resource.id.toString(), + textDirection: TextDirection.ltr, + ), ), - )); + ); top += resourceItemHeight; } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/drag_and_drop_settings.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/drag_and_drop_settings.dart index 50d6a066f..3312fa44d 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/drag_and_drop_settings.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/drag_and_drop_settings.dart @@ -236,22 +236,33 @@ class DragAndDropSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('allowNavigation', allowNavigation)); + properties.add( + DiagnosticsProperty('allowNavigation', allowNavigation), + ); properties.add(DiagnosticsProperty('allowScroll', allowScroll)); - properties - .add(DiagnosticsProperty('showTimeIndicator', showTimeIndicator)); - properties.add(DiagnosticsProperty( - 'timeIndicatorStyle', timeIndicatorStyle)); - properties.add(DiagnosticsProperty( - 'indicatorTimeFormat', indicatorTimeFormat)); properties.add( - DiagnosticsProperty('autoNavigateDelay', autoNavigateDelay)); + DiagnosticsProperty('showTimeIndicator', showTimeIndicator), + ); + properties.add( + DiagnosticsProperty('timeIndicatorStyle', timeIndicatorStyle), + ); + properties.add( + DiagnosticsProperty('indicatorTimeFormat', indicatorTimeFormat), + ); + properties.add( + DiagnosticsProperty('autoNavigateDelay', autoNavigateDelay), + ); } @override int get hashCode { - return Object.hash(allowNavigation, allowScroll, showTimeIndicator, - timeIndicatorStyle, indicatorTimeFormat, autoNavigateDelay); + return Object.hash( + allowNavigation, + allowScroll, + showTimeIndicator, + timeIndicatorStyle, + indicatorTimeFormat, + autoNavigateDelay, + ); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/header_style.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/header_style.dart index e87fd5c1b..4697767ba 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/header_style.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/header_style.dart @@ -35,8 +35,11 @@ class CalendarHeaderStyle with Diagnosticable { /// Creates a header style for calendar. /// /// The properties allows to customize the header view of [SfCalendar]. - const CalendarHeaderStyle( - {this.textAlign = TextAlign.start, this.backgroundColor, this.textStyle}); + const CalendarHeaderStyle({ + this.textAlign = TextAlign.start, + this.backgroundColor, + this.textStyle, + }); /// The text style for the text in the [SfCalendar] header view. /// diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/month_view_settings.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/month_view_settings.dart index 1bfea896f..1453cf8ee 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/month_view_settings.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/month_view_settings.dart @@ -56,22 +56,22 @@ class MonthViewSettings with Diagnosticable { /// Creates a Month view settings for calendar. /// /// The properties allows to customize the month view of [SfCalendar]. - const MonthViewSettings( - {this.appointmentDisplayCount = 3, - this.numberOfWeeksInView = 6, - this.appointmentDisplayMode = MonthAppointmentDisplayMode.indicator, - this.showAgenda = false, - this.navigationDirection = MonthNavigationDirection.horizontal, - this.dayFormat = 'EE', - this.agendaItemHeight = -1, - this.showTrailingAndLeadingDates = true, - this.agendaViewHeight = -1, - this.monthCellStyle = const MonthCellStyle(), - this.agendaStyle = const AgendaStyle()}) - : assert(appointmentDisplayCount >= 0), - assert(numberOfWeeksInView >= 1 && numberOfWeeksInView <= 6), - assert(agendaItemHeight >= -1), - assert(agendaViewHeight >= -1); + const MonthViewSettings({ + this.appointmentDisplayCount = 3, + this.numberOfWeeksInView = 6, + this.appointmentDisplayMode = MonthAppointmentDisplayMode.indicator, + this.showAgenda = false, + this.navigationDirection = MonthNavigationDirection.horizontal, + this.dayFormat = 'EE', + this.agendaItemHeight = -1, + this.showTrailingAndLeadingDates = true, + this.agendaViewHeight = -1, + this.monthCellStyle = const MonthCellStyle(), + this.agendaStyle = const AgendaStyle(), + }) : assert(appointmentDisplayCount >= 0), + assert(numberOfWeeksInView >= 1 && numberOfWeeksInView <= 6), + assert(agendaItemHeight >= -1), + assert(agendaViewHeight >= -1); /// Formats the text in the [SfCalendar] month view view header. /// @@ -650,17 +650,30 @@ class MonthViewSettings with Diagnosticable { properties.add(agendaStyle.toDiagnosticsNode(name: 'agendaStyle')); properties.add(StringProperty('dayFormat', dayFormat)); properties.add(IntProperty('numberOfWeeksInView', numberOfWeeksInView)); - properties - .add(IntProperty('appointmentDisplayCount', appointmentDisplayCount)); - properties.add(EnumProperty( - 'appointmentDisplayMode', appointmentDisplayMode)); - properties.add(EnumProperty( - 'navigationDirection', navigationDirection)); + properties.add( + IntProperty('appointmentDisplayCount', appointmentDisplayCount), + ); + properties.add( + EnumProperty( + 'appointmentDisplayMode', + appointmentDisplayMode, + ), + ); + properties.add( + EnumProperty( + 'navigationDirection', + navigationDirection, + ), + ); properties.add(DoubleProperty('agendaItemHeight', agendaItemHeight)); properties.add(DoubleProperty('agendaViewHeight', agendaViewHeight)); properties.add(DiagnosticsProperty('showAgenda', showAgenda)); - properties.add(DiagnosticsProperty( - 'showTrailingAndLeadingDates', showTrailingAndLeadingDates)); + properties.add( + DiagnosticsProperty( + 'showTrailingAndLeadingDates', + showTrailingAndLeadingDates, + ), + ); } @override @@ -739,13 +752,16 @@ class AgendaStyle with Diagnosticable { /// /// The properties allows to customize the agenda view in month view of /// [SfCalendar]. - const AgendaStyle( - {this.appointmentTextStyle, - this.dayTextStyle, - this.dateTextStyle, - this.backgroundColor, - this.placeholderTextStyle = - const TextStyle(color: Colors.grey, fontSize: 15)}); + const AgendaStyle({ + this.appointmentTextStyle, + this.dayTextStyle, + this.dateTextStyle, + this.backgroundColor, + this.placeholderTextStyle = const TextStyle( + color: Colors.grey, + fontSize: 15, + ), + }); /// The text style for the text in the [Appointment] view in [SfCalendar] /// month agenda view. @@ -1004,15 +1020,25 @@ class AgendaStyle with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty( - 'appointmentTextStyle', appointmentTextStyle)); - properties - .add(DiagnosticsProperty('dateTextStyle', dateTextStyle)); - properties - .add(DiagnosticsProperty('dayTextStyle', dayTextStyle)); + properties.add( + DiagnosticsProperty( + 'appointmentTextStyle', + appointmentTextStyle, + ), + ); + properties.add( + DiagnosticsProperty('dateTextStyle', dateTextStyle), + ); + properties.add( + DiagnosticsProperty('dayTextStyle', dayTextStyle), + ); properties.add(ColorProperty('backgroundColor', backgroundColor)); - properties.add(DiagnosticsProperty( - 'placeholderTextStyle', placeholderTextStyle)); + properties.add( + DiagnosticsProperty( + 'placeholderTextStyle', + placeholderTextStyle, + ), + ); } @override @@ -1118,8 +1144,10 @@ class MonthCellStyle with Diagnosticable { this.trailingDatesBackgroundColor, this.leadingDatesBackgroundColor, this.textStyle, - @Deprecated('Moved the same [todayTextStyle] to SfCalendar class, ' - 'use [todayTextStyle] property from SfCalendar class') + @Deprecated( + 'Moved the same [todayTextStyle] to SfCalendar class, ' + 'use [todayTextStyle] property from SfCalendar class', + ) // ignore: deprecated_member_use_from_same_package, deprecated_member_use this.todayTextStyle, this.trailingDatesTextStyle, @@ -1217,8 +1245,10 @@ class MonthCellStyle with Diagnosticable { /// ); /// } /// ``` - @Deprecated('Moved the same [todayTextStyle] to SfCalendar class, use ' - '[todayTextStyle] property from SfCalendar class') + @Deprecated( + 'Moved the same [todayTextStyle] to SfCalendar class, use ' + '[todayTextStyle] property from SfCalendar class', + ) final TextStyle? todayTextStyle; /// The text style for the text in the trailing dates cell of [SfCalendar] @@ -1578,16 +1608,29 @@ class MonthCellStyle with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('textStyle', textStyle)); - properties.add(DiagnosticsProperty( - 'trailingDatesTextStyle', trailingDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'leadingDatesTextStyle', leadingDatesTextStyle)); + properties.add( + DiagnosticsProperty( + 'trailingDatesTextStyle', + trailingDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'leadingDatesTextStyle', + leadingDatesTextStyle, + ), + ); properties.add(ColorProperty('backgroundColor', backgroundColor)); properties.add(ColorProperty('todayBackgroundColor', todayBackgroundColor)); - properties.add(ColorProperty( - 'trailingDatesBackgroundColor', trailingDatesBackgroundColor)); - properties.add(ColorProperty( - 'leadingDatesBackgroundColor', leadingDatesBackgroundColor)); + properties.add( + ColorProperty( + 'trailingDatesBackgroundColor', + trailingDatesBackgroundColor, + ), + ); + properties.add( + ColorProperty('leadingDatesBackgroundColor', leadingDatesBackgroundColor), + ); } @override diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/resource_view_settings.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/resource_view_settings.dart index f30b8bca5..eeb1fdbf5 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/resource_view_settings.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/resource_view_settings.dart @@ -68,13 +68,13 @@ class ResourceViewSettings with Diagnosticable { /// Creates a resource view settings for calendar. /// /// The properties allows to customize the resource view of [SfCalendar]. - const ResourceViewSettings( - {this.size = 75, - this.visibleResourceCount = -1, - this.showAvatar = true, - this.displayNameTextStyle}) - : assert(size >= 0), - assert(visibleResourceCount >= -1); + const ResourceViewSettings({ + this.size = 75, + this.visibleResourceCount = -1, + this.showAvatar = true, + this.displayNameTextStyle, + }) : assert(size >= 0), + assert(visibleResourceCount >= -1); /// The number of resources to be displayed in the available screen height in /// [SfCalendar] @@ -243,8 +243,12 @@ class ResourceViewSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(DiagnosticsProperty( - 'displayNameTextStyle', displayNameTextStyle)); + properties.add( + DiagnosticsProperty( + 'displayNameTextStyle', + displayNameTextStyle, + ), + ); properties.add(DoubleProperty('size', size)); properties.add(DiagnosticsProperty('showAvatar', showAvatar)); properties.add(IntProperty('visibleResourceCount', visibleResourceCount)); @@ -253,6 +257,10 @@ class ResourceViewSettings with Diagnosticable { @override int get hashCode { return Object.hash( - size, visibleResourceCount, showAvatar, displayNameTextStyle); + size, + visibleResourceCount, + showAvatar, + displayNameTextStyle, + ); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/schedule_view_settings.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/schedule_view_settings.dart index c85f14ca8..06d1f20ac 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/schedule_view_settings.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/schedule_view_settings.dart @@ -46,16 +46,18 @@ class ScheduleViewSettings with Diagnosticable { /// Creates a schedule view settings for calendar. /// /// The properties allows to customize the schedule view of [SfCalendar]. - const ScheduleViewSettings( - {this.appointmentTextStyle, - this.appointmentItemHeight = -1, - this.hideEmptyScheduleWeek = false, - this.monthHeaderSettings = const MonthHeaderSettings(), - this.weekHeaderSettings = const WeekHeaderSettings(), - this.dayHeaderSettings = const DayHeaderSettings(), - this.placeholderTextStyle = - const TextStyle(color: Colors.grey, fontSize: 15)}) - : assert(appointmentItemHeight >= -1); + const ScheduleViewSettings({ + this.appointmentTextStyle, + this.appointmentItemHeight = -1, + this.hideEmptyScheduleWeek = false, + this.monthHeaderSettings = const MonthHeaderSettings(), + this.weekHeaderSettings = const WeekHeaderSettings(), + this.dayHeaderSettings = const DayHeaderSettings(), + this.placeholderTextStyle = const TextStyle( + color: Colors.grey, + fontSize: 15, + ), + }) : assert(appointmentItemHeight >= -1); /// Sets the style to customize month label in [SfCalendar] schedule view. /// @@ -340,31 +342,45 @@ class ScheduleViewSettings with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( - monthHeaderSettings.toDiagnosticsNode(name: 'monthHeaderSettings')); - properties - .add(weekHeaderSettings.toDiagnosticsNode(name: 'weekHeaderSettings')); - properties - .add(dayHeaderSettings.toDiagnosticsNode(name: 'dayHeaderSettings')); - properties.add(DiagnosticsProperty( - 'appointmentTextStyle', appointmentTextStyle)); - properties - .add(DoubleProperty('appointmentItemHeight', appointmentItemHeight)); - properties.add(DiagnosticsProperty( - 'hideEmptyScheduleWeek', hideEmptyScheduleWeek)); - properties.add(DiagnosticsProperty( - 'placeholderTextStyle', placeholderTextStyle)); + monthHeaderSettings.toDiagnosticsNode(name: 'monthHeaderSettings'), + ); + properties.add( + weekHeaderSettings.toDiagnosticsNode(name: 'weekHeaderSettings'), + ); + properties.add( + dayHeaderSettings.toDiagnosticsNode(name: 'dayHeaderSettings'), + ); + properties.add( + DiagnosticsProperty( + 'appointmentTextStyle', + appointmentTextStyle, + ), + ); + properties.add( + DoubleProperty('appointmentItemHeight', appointmentItemHeight), + ); + properties.add( + DiagnosticsProperty('hideEmptyScheduleWeek', hideEmptyScheduleWeek), + ); + properties.add( + DiagnosticsProperty( + 'placeholderTextStyle', + placeholderTextStyle, + ), + ); } @override int get hashCode { return Object.hash( - appointmentTextStyle, - appointmentItemHeight, - hideEmptyScheduleWeek, - monthHeaderSettings, - weekHeaderSettings, - dayHeaderSettings, - placeholderTextStyle); + appointmentTextStyle, + appointmentItemHeight, + hideEmptyScheduleWeek, + monthHeaderSettings, + weekHeaderSettings, + dayHeaderSettings, + placeholderTextStyle, + ); } } @@ -414,13 +430,13 @@ class MonthHeaderSettings with Diagnosticable { /// /// The properties allows to customize the month header in schedule view of /// [SfCalendar]. - const MonthHeaderSettings( - {this.monthFormat = 'MMMM yyyy', - this.height = 150, - this.textAlign = TextAlign.start, - this.backgroundColor = const Color.fromRGBO(17, 178, 199, 1), - this.monthTextStyle}) - : assert(height >= -1); + const MonthHeaderSettings({ + this.monthFormat = 'MMMM yyyy', + this.height = 150, + this.textAlign = TextAlign.start, + this.backgroundColor = const Color.fromRGBO(17, 178, 199, 1), + this.monthTextStyle, + }) : assert(height >= -1); /// Formats the month label text in the month label [SfCalendar] /// schedule view. @@ -619,8 +635,9 @@ class MonthHeaderSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('monthTextStyle', monthTextStyle)); + properties.add( + DiagnosticsProperty('monthTextStyle', monthTextStyle), + ); properties.add(DoubleProperty('height', height)); properties.add(EnumProperty('textAlign', textAlign)); properties.add(ColorProperty('backgroundColor', backgroundColor)); @@ -630,7 +647,12 @@ class MonthHeaderSettings with Diagnosticable { @override int get hashCode { return Object.hash( - monthFormat, height, textAlign, backgroundColor, monthTextStyle); + monthFormat, + height, + textAlign, + backgroundColor, + monthTextStyle, + ); } } @@ -681,14 +703,14 @@ class WeekHeaderSettings with Diagnosticable { /// /// The properties allows to customize the week header in schedule view of /// [SfCalendar]. - const WeekHeaderSettings( - {this.startDateFormat, - this.endDateFormat, - this.height = 30, - this.textAlign = TextAlign.start, - this.backgroundColor = Colors.transparent, - this.weekTextStyle}) - : assert(height >= -1); + const WeekHeaderSettings({ + this.startDateFormat, + this.endDateFormat, + this.height = 30, + this.textAlign = TextAlign.start, + this.backgroundColor = Colors.transparent, + this.weekTextStyle, + }) : assert(height >= -1); /// Formats the week start date text in the week label of [SfCalendar] /// schedule view. @@ -938,8 +960,9 @@ class WeekHeaderSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('weekTextStyle', weekTextStyle)); + properties.add( + DiagnosticsProperty('weekTextStyle', weekTextStyle), + ); properties.add(DoubleProperty('height', height)); properties.add(EnumProperty('textAlign', textAlign)); properties.add(ColorProperty('backgroundColor', backgroundColor)); @@ -949,8 +972,14 @@ class WeekHeaderSettings with Diagnosticable { @override int get hashCode { - return Object.hash(startDateFormat, endDateFormat, height, textAlign, - backgroundColor, weekTextStyle); + return Object.hash( + startDateFormat, + endDateFormat, + height, + textAlign, + backgroundColor, + weekTextStyle, + ); } } @@ -1000,12 +1029,12 @@ class DayHeaderSettings with Diagnosticable { /// /// The properties allows to customize the day header in schedule view of /// [SfCalendar]. - const DayHeaderSettings( - {this.dayFormat = 'EEE', - this.width = -1, - this.dayTextStyle, - this.dateTextStyle}) - : assert(width >= -1); + const DayHeaderSettings({ + this.dayFormat = 'EEE', + this.width = -1, + this.dayTextStyle, + this.dateTextStyle, + }) : assert(width >= -1); /// Formats the day text in the day label of [SfCalendar] schedule view. /// @@ -1173,10 +1202,12 @@ class DayHeaderSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('dayTextStyle', dayTextStyle)); - properties - .add(DiagnosticsProperty('dateTextStyle', dateTextStyle)); + properties.add( + DiagnosticsProperty('dayTextStyle', dayTextStyle), + ); + properties.add( + DiagnosticsProperty('dateTextStyle', dateTextStyle), + ); properties.add(DoubleProperty('width', width)); properties.add(StringProperty('dayFormat', dayFormat)); } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_region.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_region.dart index 9cbc750ac..d4a191cd6 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_region.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_region.dart @@ -54,18 +54,19 @@ class TimeRegion with Diagnosticable { /// /// The time region used to highlight and block the specific timeslots in /// timeslots view of [SfCalendar]. - TimeRegion( - {required this.startTime, - required this.endTime, - this.text, - this.recurrenceRule, - this.color, - this.enablePointerInteraction = true, - this.recurrenceExceptionDates, - this.resourceIds, - this.timeZone, - this.iconData, - this.textStyle}); + TimeRegion({ + required this.startTime, + required this.endTime, + this.text, + this.recurrenceRule, + this.color, + this.enablePointerInteraction = true, + this.recurrenceExceptionDates, + this.resourceIds, + this.timeZone, + this.iconData, + this.textStyle, + }); /// Used to specify the start time of the [TimeRegion]. /// @@ -542,32 +543,34 @@ class TimeRegion with Diagnosticable { /// Creates a copy of this [TimeRegion] but with the given fields replaced /// with the new values. - TimeRegion copyWith( - {DateTime? startTime, - DateTime? endTime, - String? text, - String? recurrenceRule, - Color? color, - bool? enablePointerInteraction, - List? recurrenceExceptionDates, - String? timeZone, - IconData? iconData, - TextStyle? textStyle, - List? resourceIds}) { + TimeRegion copyWith({ + DateTime? startTime, + DateTime? endTime, + String? text, + String? recurrenceRule, + Color? color, + bool? enablePointerInteraction, + List? recurrenceExceptionDates, + String? timeZone, + IconData? iconData, + TextStyle? textStyle, + List? resourceIds, + }) { return TimeRegion( - startTime: startTime ?? this.startTime, - endTime: endTime ?? this.endTime, - color: color ?? this.color, - recurrenceRule: recurrenceRule ?? this.recurrenceRule, - textStyle: textStyle ?? this.textStyle, - enablePointerInteraction: - enablePointerInteraction ?? this.enablePointerInteraction, - recurrenceExceptionDates: - recurrenceExceptionDates ?? this.recurrenceExceptionDates, - text: text ?? this.text, - iconData: iconData ?? this.iconData, - timeZone: timeZone ?? this.timeZone, - resourceIds: resourceIds ?? this.resourceIds); + startTime: startTime ?? this.startTime, + endTime: endTime ?? this.endTime, + color: color ?? this.color, + recurrenceRule: recurrenceRule ?? this.recurrenceRule, + textStyle: textStyle ?? this.textStyle, + enablePointerInteraction: + enablePointerInteraction ?? this.enablePointerInteraction, + recurrenceExceptionDates: + recurrenceExceptionDates ?? this.recurrenceExceptionDates, + text: text ?? this.text, + iconData: iconData ?? this.iconData, + timeZone: timeZone ?? this.timeZone, + resourceIds: resourceIds ?? this.resourceIds, + ); } @override @@ -599,31 +602,38 @@ class TimeRegion with Diagnosticable { @override int get hashCode { return Object.hash( - startTime, - endTime, - color, - recurrenceRule, - textStyle, - enablePointerInteraction, + startTime, + endTime, + color, + recurrenceRule, + textStyle, + enablePointerInteraction, - /// Below condition is referred from text style class - /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html - recurrenceExceptionDates == null - ? null - : Object.hashAll(recurrenceExceptionDates!), - resourceIds == null ? null : Object.hashAll(resourceIds!), - text, - iconData, - timeZone); + /// Below condition is referred from text style class + /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html + recurrenceExceptionDates == null + ? null + : Object.hashAll(recurrenceExceptionDates!), + resourceIds == null ? null : Object.hashAll(resourceIds!), + text, + iconData, + timeZone, + ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(IterableDiagnostics(recurrenceExceptionDates) - .toDiagnosticsNode(name: 'recurrenceExceptionDates')); - properties.add(IterableDiagnostics(resourceIds) - .toDiagnosticsNode(name: 'resourceIds')); + properties.add( + IterableDiagnostics( + recurrenceExceptionDates, + ).toDiagnosticsNode(name: 'recurrenceExceptionDates'), + ); + properties.add( + IterableDiagnostics( + resourceIds, + ).toDiagnosticsNode(name: 'resourceIds'), + ); properties.add(StringProperty('timeZone', timeZone)); properties.add(StringProperty('recurrenceRule', recurrenceRule)); properties.add(StringProperty('text', text)); @@ -632,7 +642,11 @@ class TimeRegion with Diagnosticable { properties.add(DiagnosticsProperty('endTime', endTime)); properties.add(DiagnosticsProperty('textStyle', textStyle)); properties.add(DiagnosticsProperty('iconData', iconData)); - properties.add(DiagnosticsProperty( - 'enablePointerInteraction', enablePointerInteraction)); + properties.add( + DiagnosticsProperty( + 'enablePointerInteraction', + enablePointerInteraction, + ), + ); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_slot_view_settings.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_slot_view_settings.dart index a4102ed83..bd3c5e1fb 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_slot_view_settings.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/time_slot_view_settings.dart @@ -57,29 +57,29 @@ class TimeSlotViewSettings with Diagnosticable { /// Creates a timeslot view settings for calendar. /// /// The properties allows to customize the timeslot views of [SfCalendar]. - const TimeSlotViewSettings( - {this.startHour = 0, - this.endHour = 24, - this.nonWorkingDays = const [DateTime.saturday, DateTime.sunday], - this.timeFormat = 'h a', - this.timeInterval = const Duration(minutes: 60), - this.timeIntervalHeight = 40, - this.timeIntervalWidth = -2, - this.timelineAppointmentHeight = -1, - this.minimumAppointmentDuration, - this.dateFormat = 'd', - this.dayFormat = 'EE', - this.timeRulerSize = -1, - this.timeTextStyle, - this.allDayPanelColor, - this.numberOfDaysInView = -1}) - : assert(startHour >= 0 && startHour <= 24), - assert(endHour >= 0 && endHour <= 24), - assert(timeIntervalHeight >= -1), - assert(timeIntervalWidth >= -2), - assert(timelineAppointmentHeight >= -1), - assert(timeRulerSize >= -1), - assert(numberOfDaysInView >= -1); + const TimeSlotViewSettings({ + this.startHour = 0, + this.endHour = 24, + this.nonWorkingDays = const [DateTime.saturday, DateTime.sunday], + this.timeFormat = 'h a', + this.timeInterval = const Duration(minutes: 60), + this.timeIntervalHeight = 40, + this.timeIntervalWidth = -2, + this.timelineAppointmentHeight = -1, + this.minimumAppointmentDuration, + this.dateFormat = 'd', + this.dayFormat = 'EE', + this.timeRulerSize = -1, + this.timeTextStyle, + this.allDayPanelColor, + this.numberOfDaysInView = -1, + }) : assert(startHour >= 0 && startHour <= 24), + assert(endHour >= 0 && endHour <= 24), + assert(timeIntervalHeight >= -1), + assert(timeIntervalWidth >= -2), + assert(timelineAppointmentHeight >= -1), + assert(timeRulerSize >= -1), + assert(numberOfDaysInView >= -1); /// The start hour for the time slot views in [SfCalendar]. /// @@ -723,8 +723,9 @@ class TimeSlotViewSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('timeTextStyle', timeTextStyle)); + properties.add( + DiagnosticsProperty('timeTextStyle', timeTextStyle), + ); properties.add(DoubleProperty('startHour', startHour)); properties.add(DoubleProperty('endHour', endHour)); properties.add(IterableProperty('nonWorkingDays', nonWorkingDays)); @@ -732,9 +733,14 @@ class TimeSlotViewSettings with Diagnosticable { properties.add(DoubleProperty('timeIntervalHeight', timeIntervalHeight)); properties.add(DoubleProperty('timeIntervalWidth', timeIntervalWidth)); properties.add( - DoubleProperty('timelineAppointmentHeight', timelineAppointmentHeight)); - properties.add(DiagnosticsProperty( - 'minimumAppointmentDuration', minimumAppointmentDuration)); + DoubleProperty('timelineAppointmentHeight', timelineAppointmentHeight), + ); + properties.add( + DiagnosticsProperty( + 'minimumAppointmentDuration', + minimumAppointmentDuration, + ), + ); properties.add(DoubleProperty('timeRulerSize', timeRulerSize)); properties.add(StringProperty('timeFormat', timeFormat)); properties.add(StringProperty('dateFormat', dateFormat)); @@ -745,18 +751,19 @@ class TimeSlotViewSettings with Diagnosticable { @override int get hashCode { return Object.hash( - startHour, - endHour, - Object.hashAll(nonWorkingDays), - timeInterval, - timeIntervalHeight, - timeIntervalWidth, - timeFormat, - timelineAppointmentHeight, - minimumAppointmentDuration, - dateFormat, - dayFormat, - timeRulerSize, - timeTextStyle); + startHour, + endHour, + Object.hashAll(nonWorkingDays), + timeInterval, + timeIntervalHeight, + timeIntervalWidth, + timeFormat, + timelineAppointmentHeight, + minimumAppointmentDuration, + dateFormat, + dayFormat, + timeRulerSize, + timeTextStyle, + ); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/view_header_style.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/view_header_style.dart index 6eb8356ae..a82bae084 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/view_header_style.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/view_header_style.dart @@ -35,8 +35,11 @@ class ViewHeaderStyle with Diagnosticable { /// Creates a view header style for calendar. /// /// The properties allows to customize the view header view of [SfCalendar]. - const ViewHeaderStyle( - {this.backgroundColor, this.dateTextStyle, this.dayTextStyle}); + const ViewHeaderStyle({ + this.backgroundColor, + this.dateTextStyle, + this.dayTextStyle, + }); /// The color which fills the background of [SfCalendar] view header view. /// @@ -152,19 +155,17 @@ class ViewHeaderStyle with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('dayTextStyle', dayTextStyle)); - properties - .add(DiagnosticsProperty('dateTextStyle', dateTextStyle)); + properties.add( + DiagnosticsProperty('dayTextStyle', dayTextStyle), + ); + properties.add( + DiagnosticsProperty('dateTextStyle', dateTextStyle), + ); properties.add(ColorProperty('backgroundColor', backgroundColor)); } @override int get hashCode { - return Object.hash( - backgroundColor, - dayTextStyle, - dateTextStyle, - ); + return Object.hash(backgroundColor, dayTextStyle, dateTextStyle); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/week_number_style.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/week_number_style.dart index 73fde62f2..c0930a588 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/week_number_style.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/settings/week_number_style.dart @@ -106,9 +106,6 @@ class WeekNumberStyle with Diagnosticable { @override int get hashCode { - return Object.hash( - backgroundColor, - textStyle, - ); + return Object.hash(backgroundColor, textStyle); } } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/sfcalendar.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/sfcalendar.dart index b52bd1230..c93e49568 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/sfcalendar.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/sfcalendar.dart @@ -196,7 +196,10 @@ class SfCalendar extends StatefulWidget { DateTime? minDate, DateTime? maxDate, this.appointmentTextStyle = const TextStyle( - color: Colors.white, fontSize: -1, fontWeight: FontWeight.w500), + color: Colors.white, + fontSize: -1, + fontWeight: FontWeight.w500, + ), this.showNavigationArrow = false, this.showDatePickerButton = false, this.showTodayButton = false, @@ -220,18 +223,24 @@ class SfCalendar extends StatefulWidget { this.onDragStart, this.onDragUpdate, this.onDragEnd, - }) : assert(firstDayOfWeek >= 1 && firstDayOfWeek <= 7), - assert(headerHeight >= 0), - assert(viewHeaderHeight >= -1), - assert(minDate == null || maxDate == null || minDate.isBefore(maxDate)), - assert(minDate == null || maxDate == null || maxDate.isAfter(minDate)), - assert(cellEndPadding >= -1), - initialDisplayDate = initialDisplayDate ?? - DateTime(DateTime.now().year, DateTime.now().month, - DateTime.now().day, 08, 45), - minDate = minDate ?? DateTime(01), - maxDate = maxDate ?? DateTime(9999, 12, 31), - super(key: key); + }) : assert(firstDayOfWeek >= 1 && firstDayOfWeek <= 7), + assert(headerHeight >= 0), + assert(viewHeaderHeight >= -1), + assert(minDate == null || maxDate == null || minDate.isBefore(maxDate)), + assert(minDate == null || maxDate == null || maxDate.isAfter(minDate)), + assert(cellEndPadding >= -1), + initialDisplayDate = + initialDisplayDate ?? + DateTime( + DateTime.now().year, + DateTime.now().month, + DateTime.now().day, + 08, + 45, + ), + minDate = minDate ?? DateTime(01), + maxDate = maxDate ?? DateTime(9999, 12, 31), + super(key: key); /// A builder that sets the widget to display on the calendar widget when /// the appointments are being loaded. @@ -2421,19 +2430,33 @@ class SfCalendar extends StatefulWidget { /// /// ``` static List getRecurrenceDateTimeCollection( - String rRule, DateTime recurrenceStartDate, - {DateTime? specificStartDate, DateTime? specificEndDate}) { - assert(specificStartDate == null || - specificEndDate == null || - CalendarViewHelper.isSameOrBeforeDateTime( - specificEndDate, specificStartDate)); - assert(specificStartDate == null || - specificEndDate == null || - CalendarViewHelper.isSameOrAfterDateTime( - specificStartDate, specificEndDate)); + String rRule, + DateTime recurrenceStartDate, { + DateTime? specificStartDate, + DateTime? specificEndDate, + }) { + assert( + specificStartDate == null || + specificEndDate == null || + CalendarViewHelper.isSameOrBeforeDateTime( + specificEndDate, + specificStartDate, + ), + ); + assert( + specificStartDate == null || + specificEndDate == null || + CalendarViewHelper.isSameOrAfterDateTime( + specificStartDate, + specificEndDate, + ), + ); return RecurrenceHelper.getRecurrenceDateTimeCollection( - rRule, recurrenceStartDate, - specificStartDate: specificStartDate, specificEndDate: specificEndDate); + rRule, + recurrenceStartDate, + specificStartDate: specificStartDate, + specificEndDate: specificEndDate, + ); } /// Returns the recurrence properties based on the given recurrence rule and @@ -2506,13 +2529,19 @@ class SfCalendar extends StatefulWidget { /// DateTime(2019, 12, 16, 10), DateTime(2019, 12, 16, 12))); /// /// ``` - static String generateRRule(RecurrenceProperties recurrenceProperties, - DateTime appStartTime, DateTime appEndTime) { + static String generateRRule( + RecurrenceProperties recurrenceProperties, + DateTime appStartTime, + DateTime appEndTime, + ) { assert(CalendarViewHelper.isSameOrBeforeDateTime(appEndTime, appStartTime)); assert(CalendarViewHelper.isSameOrAfterDateTime(appStartTime, appEndTime)); return RecurrenceHelper.generateRRule( - recurrenceProperties, appStartTime, appEndTime); + recurrenceProperties, + appStartTime, + appEndTime, + ); } @override @@ -2525,91 +2554,177 @@ class SfCalendar extends StatefulWidget { properties.add(headerStyle.toDiagnosticsNode(name: 'headerStyle')); properties.add(viewHeaderStyle.toDiagnosticsNode(name: 'viewHeaderStyle')); properties.add( - timeSlotViewSettings.toDiagnosticsNode(name: 'timeSlotViewSettings')); + timeSlotViewSettings.toDiagnosticsNode(name: 'timeSlotViewSettings'), + ); + properties.add( + resourceViewSettings.toDiagnosticsNode(name: 'resourceViewSettings'), + ); properties.add( - resourceViewSettings.toDiagnosticsNode(name: 'resourceViewSettings')); - properties - .add(monthViewSettings.toDiagnosticsNode(name: 'monthViewSettings')); + monthViewSettings.toDiagnosticsNode(name: 'monthViewSettings'), + ); properties.add( - scheduleViewSettings.toDiagnosticsNode(name: 'scheduleViewSettings')); + scheduleViewSettings.toDiagnosticsNode(name: 'scheduleViewSettings'), + ); if (dataSource != null) { properties.add(dataSource!.toDiagnosticsNode(name: 'dataSource')); } - properties - .add(DiagnosticsProperty('controller', controller)); - properties.add(DiagnosticsProperty( - 'appointmentTextStyle', appointmentTextStyle)); - properties.add(DiagnosticsProperty( - 'blackoutDatesTextStyle', blackoutDatesTextStyle)); - properties - .add(DiagnosticsProperty('todayTextStyle', todayTextStyle)); + properties.add( + DiagnosticsProperty('controller', controller), + ); + properties.add( + DiagnosticsProperty( + 'appointmentTextStyle', + appointmentTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'blackoutDatesTextStyle', + blackoutDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty('todayTextStyle', todayTextStyle), + ); properties.add(EnumProperty('view', view)); properties.add( - DiagnosticsProperty('allowViewNavigation', allowViewNavigation)); + DiagnosticsProperty('allowViewNavigation', allowViewNavigation), + ); + properties.add( + DiagnosticsProperty('showNavigationArrow', showNavigationArrow), + ); + properties.add( + DiagnosticsProperty( + 'viewNavigationMode', + viewNavigationMode, + ), + ); + properties.add( + DiagnosticsProperty('showDatePickerButton', showDatePickerButton), + ); + properties.add( + DiagnosticsProperty('showTodayButton', showTodayButton), + ); properties.add( - DiagnosticsProperty('showNavigationArrow', showNavigationArrow)); - properties.add(DiagnosticsProperty( - 'viewNavigationMode', viewNavigationMode)); - properties.add(DiagnosticsProperty( - 'showDatePickerButton', showDatePickerButton)); - properties - .add(DiagnosticsProperty('showTodayButton', showTodayButton)); - properties.add(DiagnosticsProperty( - 'showCurrentTimeIndicator', showCurrentTimeIndicator)); + DiagnosticsProperty( + 'showCurrentTimeIndicator', + showCurrentTimeIndicator, + ), + ); properties.add(IntProperty('firstDayOfWeek', firstDayOfWeek)); properties.add(DoubleProperty('headerHeight', headerHeight)); properties.add(DoubleProperty('viewHeaderHeight', viewHeaderHeight)); properties.add(DoubleProperty('cellEndPadding', cellEndPadding)); properties.add( - StringProperty('appointmentTimeTextFormat', appointmentTimeTextFormat)); - properties.add(DiagnosticsProperty( - 'initialDisplayDate', initialDisplayDate)); - properties.add(DiagnosticsProperty( - 'initialSelectedDate', initialSelectedDate)); + StringProperty('appointmentTimeTextFormat', appointmentTimeTextFormat), + ); + properties.add( + DiagnosticsProperty('initialDisplayDate', initialDisplayDate), + ); + properties.add( + DiagnosticsProperty('initialSelectedDate', initialSelectedDate), + ); properties.add(DiagnosticsProperty('minDate', minDate)); properties.add(DiagnosticsProperty('maxDate', maxDate)); properties.add(ColorProperty('backgroundColor', backgroundColor)); properties.add(ColorProperty('todayHighlightColor', todayHighlightColor)); properties.add(ColorProperty('cellBorderColor', cellBorderColor)); - properties.add(DiagnosticsProperty( - 'onViewChanged', onViewChanged)); + properties.add( + DiagnosticsProperty('onViewChanged', onViewChanged), + ); properties.add(DiagnosticsProperty('onTap', onTap)); - properties.add(DiagnosticsProperty( - 'onLongPress', onLongPress)); - properties.add(DiagnosticsProperty( - 'onSelectionChanged', onSelectionChanged)); - properties.add(DiagnosticsProperty( - 'scheduleViewMonthHeaderBuilder', scheduleViewMonthHeaderBuilder)); - properties.add(DiagnosticsProperty( - 'monthCellBuilder', monthCellBuilder)); - properties.add(DiagnosticsProperty( - 'appointmentBuilder', appointmentBuilder)); - properties.add(DiagnosticsProperty( - 'timeRegionBuilder', timeRegionBuilder)); - properties.add(DiagnosticsProperty( - 'loadMoreWidgetBuilder', loadMoreWidgetBuilder)); + properties.add( + DiagnosticsProperty( + 'onLongPress', + onLongPress, + ), + ); + properties.add( + DiagnosticsProperty( + 'onSelectionChanged', + onSelectionChanged, + ), + ); + properties.add( + DiagnosticsProperty( + 'scheduleViewMonthHeaderBuilder', + scheduleViewMonthHeaderBuilder, + ), + ); + properties.add( + DiagnosticsProperty( + 'monthCellBuilder', + monthCellBuilder, + ), + ); + properties.add( + DiagnosticsProperty( + 'appointmentBuilder', + appointmentBuilder, + ), + ); + properties.add( + DiagnosticsProperty( + 'timeRegionBuilder', + timeRegionBuilder, + ), + ); + properties.add( + DiagnosticsProperty( + 'loadMoreWidgetBuilder', + loadMoreWidgetBuilder, + ), + ); properties.add(StringProperty('headerDateFormat', headerDateFormat)); - properties.add(DiagnosticsProperty( - 'selectionDecoration', selectionDecoration)); + properties.add( + DiagnosticsProperty( + 'selectionDecoration', + selectionDecoration, + ), + ); properties.add(StringProperty('timeZone', timeZone)); - properties.add(IterableDiagnostics(blackoutDates) - .toDiagnosticsNode(name: 'blackoutDates')); - properties.add(IterableDiagnostics(allowedViews) - .toDiagnosticsNode(name: 'allowedViews')); - properties.add(IterableDiagnostics(specialRegions) - .toDiagnosticsNode(name: 'specialRegions')); - properties.add(DiagnosticsProperty( - 'resourceViewHeaderBuilder', resourceViewHeaderBuilder)); - properties - .add(DiagnosticsProperty('allowDragAndDrop', allowDragAndDrop)); properties.add( - dragAndDropSettings.toDiagnosticsNode(name: 'dragAndDropSettings')); - properties.add(DiagnosticsProperty( - 'onDragStart', onDragStart)); - properties.add(DiagnosticsProperty( - 'onDragUpdate', onDragUpdate)); - properties.add(DiagnosticsProperty( - 'onDragEnd', onDragEnd)); + IterableDiagnostics( + blackoutDates, + ).toDiagnosticsNode(name: 'blackoutDates'), + ); + properties.add( + IterableDiagnostics( + allowedViews, + ).toDiagnosticsNode(name: 'allowedViews'), + ); + properties.add( + IterableDiagnostics( + specialRegions, + ).toDiagnosticsNode(name: 'specialRegions'), + ); + properties.add( + DiagnosticsProperty( + 'resourceViewHeaderBuilder', + resourceViewHeaderBuilder, + ), + ); + properties.add( + DiagnosticsProperty('allowDragAndDrop', allowDragAndDrop), + ); + properties.add( + dragAndDropSettings.toDiagnosticsNode(name: 'dragAndDropSettings'), + ); + properties.add( + DiagnosticsProperty( + 'onDragStart', + onDragStart, + ), + ); + properties.add( + DiagnosticsProperty( + 'onDragUpdate', + onDragUpdate, + ), + ); + properties.add( + DiagnosticsProperty('onDragEnd', onDragEnd), + ); } } @@ -2627,8 +2742,9 @@ class _SfCalendarState extends State late ValueNotifier _agendaSelectedDate, _timelineMonthWeekNumberNotifier; - ValueNotifier _headerUpdateNotifier = - ValueNotifier(null); + ValueNotifier _headerUpdateNotifier = ValueNotifier( + null, + ); late String _locale; late SfLocalizations _localizations; late double _minWidth, _minHeight, _textScaleFactor; @@ -2775,21 +2891,28 @@ class _SfCalendarState extends State _selectedDate = _controller.selectedDate; _agendaSelectedDate = ValueNotifier(_selectedDate); _agendaSelectedDate.addListener(_agendaSelectedDateListener); - _currentDate = DateTimeHelper.getDateTimeValue(getValidDate(widget.minDate, - widget.maxDate, _controller.displayDate ?? widget.initialDisplayDate)); + _currentDate = DateTimeHelper.getDateTimeValue( + getValidDate( + widget.minDate, + widget.maxDate, + _controller.displayDate ?? widget.initialDisplayDate, + ), + ); _controller.displayDate = _currentDate; _scheduleDisplayDate = _controller.displayDate!; _controller.view ??= widget.view; _view = _controller.view!; - _timelineMonthWeekNumberNotifier = - ValueNotifier(_controller.displayDate); + _timelineMonthWeekNumberNotifier = ValueNotifier( + _controller.displayDate, + ); if (_selectedDate != null) { _updateSelectionChangedCallback(); } _updateCurrentVisibleDates(); widget.dataSource?.addListener(_dataSourceChangedListener); - _resourceCollection = - CalendarViewHelper.cloneList(widget.dataSource?.resources); + _resourceCollection = CalendarViewHelper.cloneList( + widget.dataSource?.resources, + ); if (_view == CalendarView.month && widget.monthViewSettings.showAgenda) { _agendaScrollController = ScrollController(); } @@ -2801,9 +2924,11 @@ class _SfCalendarState extends State _controller.addPropertyChangedListener(_calendarValueChangedListener); if (_view == CalendarView.schedule && CalendarViewHelper.shouldRaiseViewChangedCallback( - widget.onViewChanged)) { - CalendarViewHelper.raiseViewChangedCallback( - widget, [_controller.displayDate!]); + widget.onViewChanged, + )) { + CalendarViewHelper.raiseViewChangedCallback(widget, [ + _controller.displayDate!, + ]); } _initScheduleViewProperties(); @@ -2839,8 +2964,9 @@ class _SfCalendarState extends State @override void didUpdateWidget(SfCalendar oldWidget) { if (oldWidget.controller != widget.controller) { - oldWidget.controller - ?.removePropertyChangedListener(_calendarValueChangedListener); + oldWidget.controller?.removePropertyChangedListener( + _calendarValueChangedListener, + ); _controller.removePropertyChangedListener(_calendarValueChangedListener); _controller = widget.controller ?? CalendarController(); if (widget.controller != null) { @@ -2852,8 +2978,13 @@ class _SfCalendarState extends State _controller.view = widget.controller!.view ?? _view; } else { _controller.selectedDate = widget.initialSelectedDate; - _currentDate = DateTimeHelper.getDateTimeValue(getValidDate( - widget.minDate, widget.maxDate, widget.initialDisplayDate)); + _currentDate = DateTimeHelper.getDateTimeValue( + getValidDate( + widget.minDate, + widget.maxDate, + widget.initialDisplayDate, + ), + ); _controller.displayDate = _currentDate; _controller.view = widget.view; } @@ -2873,16 +3004,23 @@ class _SfCalendarState extends State _view != widget.controller!.view) { final CalendarView oldView = _view; _view = _controller.view ?? widget.view; - _currentDate = DateTimeHelper.getDateTimeValue(getValidDate( - widget.minDate, widget.maxDate, _updateCurrentDate(oldView))); + _currentDate = DateTimeHelper.getDateTimeValue( + getValidDate( + widget.minDate, + widget.maxDate, + _updateCurrentDate(oldView), + ), + ); _canScrollTimeSlotView = false; _controller.displayDate = _currentDate; _canScrollTimeSlotView = true; if (_view == CalendarView.schedule) { if (CalendarViewHelper.shouldRaiseViewChangedCallback( - widget.onViewChanged)) { - CalendarViewHelper.raiseViewChangedCallback( - widget, [_controller.displayDate!]); + widget.onViewChanged, + )) { + CalendarViewHelper.raiseViewChangedCallback(widget, [ + _controller.displayDate!, + ]); } _agendaScrollController?.removeListener(_handleScheduleViewScrolled); @@ -2906,8 +3044,9 @@ class _SfCalendarState extends State widget.controller != null && oldWidget.controller!.displayDate != widget.controller!.displayDate) { if (_controller.displayDate != null) { - _currentDate = DateTimeHelper.getDateTimeValue(getValidDate( - widget.minDate, widget.maxDate, _controller.displayDate)); + _currentDate = DateTimeHelper.getDateTimeValue( + getValidDate(widget.minDate, widget.maxDate, _controller.displayDate), + ); } _controller.displayDate = _currentDate; @@ -2928,8 +3067,8 @@ class _SfCalendarState extends State } _forwardWidgetHeights = {}; _backwardWidgetHeights = {}; - _agendaScrollController = ScrollController() - ..addListener(_handleScheduleViewScrolled); + _agendaScrollController = + ScrollController()..addListener(_handleScheduleViewScrolled); _scheduleMaxDate = null; _scheduleMinDate = null; _minDate = null; @@ -2937,7 +3076,9 @@ class _SfCalendarState extends State } if (!CalendarViewHelper.isDateCollectionEqual( - widget.blackoutDates, _blackoutDates)) { + widget.blackoutDates, + _blackoutDates, + )) { _blackoutDates = CalendarViewHelper.cloneList(widget.blackoutDates); } @@ -2951,14 +3092,17 @@ class _SfCalendarState extends State if (widget.monthViewSettings.numberOfWeeksInView != oldWidget.monthViewSettings.numberOfWeeksInView) { - _currentDate = DateTimeHelper.getDateTimeValue(getValidDate( - widget.minDate, widget.maxDate, _updateCurrentDate(_view))); + _currentDate = DateTimeHelper.getDateTimeValue( + getValidDate(widget.minDate, widget.maxDate, _updateCurrentDate(_view)), + ); _controller.displayDate = _currentDate; if (_view == CalendarView.schedule) { if (CalendarViewHelper.shouldRaiseViewChangedCallback( - widget.onViewChanged)) { - CalendarViewHelper.raiseViewChangedCallback( - widget, [_controller.displayDate!]); + widget.onViewChanged, + )) { + CalendarViewHelper.raiseViewChangedCallback(widget, [ + _controller.displayDate!, + ]); } _agendaScrollController?.removeListener(_handleScheduleViewScrolled); @@ -2991,15 +3135,19 @@ class _SfCalendarState extends State } if (!CalendarViewHelper.isCollectionEqual( - widget.dataSource?.resources, _resourceCollection)) { - _resourceCollection = - CalendarViewHelper.cloneList(widget.dataSource?.resources); + widget.dataSource?.resources, + _resourceCollection, + )) { + _resourceCollection = CalendarViewHelper.cloneList( + widget.dataSource?.resources, + ); } if (oldWidget.minDate != widget.minDate || oldWidget.maxDate != widget.maxDate) { _currentDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, _currentDate)); + getValidDate(widget.minDate, widget.maxDate, _currentDate), + ); if (_view == CalendarView.schedule) { _minDate = null; _maxDate = null; @@ -3007,9 +3155,11 @@ class _SfCalendarState extends State _scheduleMinDate != null && _scheduleMaxDate != null) { _scheduleMinDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, _scheduleMinDate)); + getValidDate(widget.minDate, widget.maxDate, _scheduleMinDate), + ); _scheduleMaxDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, _scheduleMaxDate)); + getValidDate(widget.minDate, widget.maxDate, _scheduleMaxDate), + ); } } } @@ -3034,78 +3184,85 @@ class _SfCalendarState extends State double height; _isRTL = CalendarViewHelper.isRTLLayout(context); _themeData = Theme.of(context); - _calendarTheme = - _getThemeDataValue(SfCalendarTheme.of(context), _themeData); + _calendarTheme = _getThemeDataValue( + SfCalendarTheme.of(context), + _themeData, + ); return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - _minWidth = constraints.maxWidth == double.infinity - ? _minWidth - : constraints.maxWidth; - _minHeight = constraints.maxHeight == double.infinity - ? _minHeight - : constraints.maxHeight; - - _isMobilePlatform = - CalendarViewHelper.isMobileLayout(Theme.of(context).platform); - _useMobilePlatformUI = - CalendarViewHelper.isMobileLayoutUI(_minWidth, _isMobilePlatform); - - _fadeInController ??= AnimationController( + builder: (BuildContext context, BoxConstraints constraints) { + _minWidth = + constraints.maxWidth == double.infinity + ? _minWidth + : constraints.maxWidth; + _minHeight = + constraints.maxHeight == double.infinity + ? _minHeight + : constraints.maxHeight; + + _isMobilePlatform = CalendarViewHelper.isMobileLayout( + Theme.of(context).platform, + ); + _useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( + _minWidth, + _isMobilePlatform, + ); + + _fadeInController ??= AnimationController( duration: Duration(milliseconds: _isMobilePlatform ? 500 : 600), - vsync: this) - ..addListener(_updateFadeAnimation); - _fadeIn ??= Tween( - begin: 0.1, - end: 1, - ).animate(CurvedAnimation( - parent: _fadeInController!, - curve: Curves.easeIn, - )); - - /// Check the schedule view changes from mobile view to web view or - /// web view to mobile view. - if (_view == CalendarView.schedule && - _actualWidth != null && - _useMobilePlatformUI != - CalendarViewHelper.isMobileLayoutUI( - _actualWidth!, _isMobilePlatform) && - _nextDates.isNotEmpty) { - _agendaScrollController?.removeListener(_handleScheduleViewScrolled); - _initScheduleViewProperties(); - } + vsync: this, + )..addListener(_updateFadeAnimation); + _fadeIn ??= Tween(begin: 0.1, end: 1).animate( + CurvedAnimation(parent: _fadeInController!, curve: Curves.easeIn), + ); - _actualWidth = _minWidth; - height = _minHeight; + /// Check the schedule view changes from mobile view to web view or + /// web view to mobile view. + if (_view == CalendarView.schedule && + _actualWidth != null && + _useMobilePlatformUI != + CalendarViewHelper.isMobileLayoutUI( + _actualWidth!, + _isMobilePlatform, + ) && + _nextDates.isNotEmpty) { + _agendaScrollController?.removeListener(_handleScheduleViewScrolled); + _initScheduleViewProperties(); + } - _agendaDateViewWidth = _minWidth * 0.15; + _actualWidth = _minWidth; + height = _minHeight; - /// Restrict the maximum agenda date view width to 60 on web view. - if (_agendaDateViewWidth > 60 && !_isMobilePlatform) { - _agendaDateViewWidth = 60; - } + _agendaDateViewWidth = _minWidth * 0.15; - height -= widget.headerHeight; - final double agendaHeight = - _view == CalendarView.month && widget.monthViewSettings.showAgenda - ? _getMonthAgendaHeight() - : 0; + /// Restrict the maximum agenda date view width to 60 on web view. + if (_agendaDateViewWidth > 60 && !_isMobilePlatform) { + _agendaDateViewWidth = 60; + } - return GestureDetector( - child: Container( - width: _minWidth, - height: _minHeight, - color: widget.backgroundColor ?? _calendarTheme.backgroundColor, - child: _view == CalendarView.schedule - ? widget.loadMoreWidgetBuilder == null - ? addAgenda(height, _isRTL) - : addAgendaWithLoadMore(height, _isRTL) - : _addChildren(agendaHeight, height, _minWidth, _isRTL), - ), - onTap: () { - _removeDatePicker(); - }, - ); - }); + height -= widget.headerHeight; + final double agendaHeight = + _view == CalendarView.month && widget.monthViewSettings.showAgenda + ? _getMonthAgendaHeight() + : 0; + + return GestureDetector( + child: Container( + width: _minWidth, + height: _minHeight, + color: widget.backgroundColor ?? _calendarTheme.backgroundColor, + child: + _view == CalendarView.schedule + ? widget.loadMoreWidgetBuilder == null + ? addAgenda(height, _isRTL) + : addAgendaWithLoadMore(height, _isRTL) + : _addChildren(agendaHeight, height, _minWidth, _isRTL), + ), + onTap: () { + _removeDatePicker(); + }, + ); + }, + ); } /// Get the calendar details by using the [getCalendarDetailsAtOffset] in @@ -3115,7 +3272,11 @@ class _SfCalendarState extends State /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on header. return CalendarDetails( - null, _getTappedHeaderDate(), CalendarElement.header, null); + null, + _getTappedHeaderDate(), + CalendarElement.header, + null, + ); } else if (position.dy > _minHeight && (position.dx < 0 || position.dx > _minWidth)) { // Return null value when the position placed on @@ -3123,8 +3284,10 @@ class _SfCalendarState extends State return null; } - final Offset updatedPosition = - Offset(position.dx, position.dy - widget.headerHeight); + final Offset updatedPosition = Offset( + position.dx, + position.dy - widget.headerHeight, + ); switch (_controller.view!) { case CalendarView.day: @@ -3142,34 +3305,48 @@ class _SfCalendarState extends State if (position.dy > _minHeight - agendaHeight) { DateTime? currentSelectedDate; if (_selectedDate != null) { - currentSelectedDate = isDateWithInDateRange( - widget.minDate, widget.maxDate, _selectedDate) && - !CalendarViewHelper.isDateInDateCollection( - _blackoutDates, _selectedDate!) - ? _selectedDate - : null; + currentSelectedDate = + isDateWithInDateRange( + widget.minDate, + widget.maxDate, + _selectedDate, + ) && + !CalendarViewHelper.isDateInDateCollection( + _blackoutDates, + _selectedDate!, + ) + ? _selectedDate + : null; } if (currentSelectedDate == null) { return const CalendarDetails( - null, null, CalendarElement.agenda, null); + null, + null, + CalendarElement.agenda, + null, + ); } final List selectedAppointments = _getSelectedAppointments( - Offset(position.dx, - position.dy - (_minHeight - agendaHeight)), - currentSelectedDate); + Offset( + position.dx, + position.dy - (_minHeight - agendaHeight), + ), + currentSelectedDate, + ); /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on agenda in month view. return CalendarDetails( - selectedAppointments, - currentSelectedDate, - selectedAppointments.isNotEmpty - ? CalendarElement.appointment - : CalendarElement.agenda, - null); + selectedAppointments, + currentSelectedDate, + selectedAppointments.isNotEmpty + ? CalendarElement.appointment + : CalendarElement.agenda, + null, + ); } } @@ -3182,17 +3359,23 @@ class _SfCalendarState extends State case CalendarView.timelineWorkWeek: case CalendarView.timelineMonth: { - final bool isResourceEnabled = - CalendarViewHelper.isResourceEnabled(widget.dataSource, _view); + final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( + widget.dataSource, + _view, + ); final double resourceViewSize = isResourceEnabled ? widget.resourceViewSettings.size : 0; if ((!_isRTL && updatedPosition.dx < resourceViewSize) || (_isRTL && updatedPosition.dx > _minWidth - resourceViewSize)) { final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.viewHeaderHeight, _view); + widget.viewHeaderHeight, + _view, + ); final double timeLabelSize = CalendarViewHelper.getTimeLabelWidth( - widget.timeSlotViewSettings.timeRulerSize, _view); + widget.timeSlotViewSettings.timeRulerSize, + _view, + ); final double top = viewHeaderHeight + timeLabelSize; // Return null value when the position placed on empty space // on view header above the resource view. @@ -3201,29 +3384,39 @@ class _SfCalendarState extends State } final double resourceItemHeight = CalendarViewHelper.getResourceItemHeight( - resourceViewSize, - _minHeight - top, - widget.resourceViewSettings, - _resourceCollection!.length); + resourceViewSize, + _minHeight - top, + widget.resourceViewSettings, + _resourceCollection!.length, + ); final CalendarResource resource = _getTappedResource( - updatedPosition.dy - top, resourceItemHeight); + updatedPosition.dy - top, + resourceItemHeight, + ); final List resourceAppointments = _getSelectedResourceAppointments(resource); /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on resource header in timeline views. - return CalendarDetails(resourceAppointments, null, - CalendarElement.resourceHeader, resource); + return CalendarDetails( + resourceAppointments, + null, + CalendarElement.resourceHeader, + resource, + ); } return (_customScrollViewKey.currentWidget! as CustomCalendarScrollView) - .getCalendarDetails(Offset( + .getCalendarDetails( + Offset( _isRTL ? updatedPosition.dx : updatedPosition.dx - resourceViewSize, - updatedPosition.dy)); + updatedPosition.dy, + ), + ); } case CalendarView.schedule: return _getScheduleViewDetails(updatedPosition); @@ -3289,49 +3482,62 @@ class _SfCalendarState extends State /// next dates collection then get the start date from previous dates. /// If the index as last index of previous dates collection then calculate /// by subtract the 7 days to get previous date. - final DateTime prevDate = yPosition >= 0 && index == 0 - ? _previousDates.isEmpty - ? DateTimeHelper.getDateTimeValue( - addDays(startDate, -DateTime.daysPerWeek)) - : _previousDates[0] - : (yPosition >= 0 && index > 0 - ? _nextDates[index - 1] - : index >= _previousDates.length - 1 + final DateTime prevDate = + yPosition >= 0 && index == 0 + ? _previousDates.isEmpty + ? DateTimeHelper.getDateTimeValue( + addDays(startDate, -DateTime.daysPerWeek), + ) + : _previousDates[0] + : (yPosition >= 0 && index > 0 + ? _nextDates[index - 1] + : index >= _previousDates.length - 1 ? DateTimeHelper.getDateTimeValue( - addDays(startDate, -DateTime.daysPerWeek)) + addDays(startDate, -DateTime.daysPerWeek), + ) : _previousDates[index + 1]); - final DateTime prevEndDate = - DateTimeHelper.getDateTimeValue(addDays(prevDate, 6)); - final DateTime endDate = - DateTimeHelper.getDateTimeValue(addDays(startDate, 6)); + final DateTime prevEndDate = DateTimeHelper.getDateTimeValue( + addDays(prevDate, 6), + ); + final DateTime endDate = DateTimeHelper.getDateTimeValue( + addDays(startDate, 6), + ); /// Get the visible week appointment and split the appointments based on /// date. final List appointmentCollection = AppointmentHelper.getVisibleAppointments( - isSameOrAfterDate(_minDate, startDate) ? startDate : _minDate!, - isSameOrBeforeDate(_maxDate, endDate) ? endDate : _maxDate!, - _appointments, - widget.timeZone, - false, - canCreateNewAppointment: false); + isSameOrAfterDate(_minDate, startDate) ? startDate : _minDate!, + isSameOrBeforeDate(_maxDate, endDate) ? endDate : _maxDate!, + _appointments, + widget.timeZone, + false, + canCreateNewAppointment: false, + ); appointmentCollection.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); /// Get the collection of appointment collection listed by date. final Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, startDate, endDate); + appointmentCollection, + startDate, + endDate, + ); final List dateAppointmentKeys = dateAppointments.keys.toList(); const double padding = 5; /// Check the current week view show display date or current date view. - bool isNeedDisplayDateHighlight = - isDateWithInDateRange(startDate, endDate, scheduleDisplayDate); + bool isNeedDisplayDateHighlight = isDateWithInDateRange( + startDate, + endDate, + scheduleDisplayDate, + ); bool isNeedCurrentDateHighlight = isDateWithInDateRange(startDate, endDate, scheduleCurrentDate) && - !isSameDate(scheduleDisplayDate, scheduleCurrentDate); + !isSameDate(scheduleDisplayDate, scheduleCurrentDate); /// Check the schedule display date have appointments if display date /// in between the week @@ -3361,7 +3567,9 @@ class _SfCalendarState extends State /// calculate the day label(eg., May 25) width based on schedule setting. final double viewPadding = _getAgendaViewDayLabelWidth( - widget.scheduleViewSettings, _useMobilePlatformUI); + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); final double viewTopPadding = _useMobilePlatformUI ? padding : 0; @@ -3370,16 +3578,21 @@ class _SfCalendarState extends State /// Check the week date needs month header at first or before of appointment /// view. - final bool isNeedMonthBuilder = _useMobilePlatformUI && + final bool isNeedMonthBuilder = + _useMobilePlatformUI && (prevEndDate.month != startDate.month || prevEndDate.year != startDate.year); final double appointmentViewHeight = CalendarViewHelper.getScheduleAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); /// Calculate the divider height and color when it is web view. final double dividerHeight = _useMobilePlatformUI ? 0 : 1; @@ -3399,10 +3612,11 @@ class _SfCalendarState extends State /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on header in schedule view. return CalendarDetails( - null, - DateTime(startDate.year, startDate.month), - CalendarElement.header, - null); + null, + DateTime(startDate.year, startDate.month), + CalendarElement.header, + null, + ); } topPosition += currentViewHeight; @@ -3416,10 +3630,11 @@ class _SfCalendarState extends State /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on view header in schedule view. return CalendarDetails( - null, - DateTime(startDate.year, startDate.month, startDate.day), - CalendarElement.viewHeader, - null); + null, + DateTime(startDate.year, startDate.month, startDate.day), + CalendarElement.viewHeader, + null, + ); } topPosition += weekHeaderHeight; @@ -3435,7 +3650,8 @@ class _SfCalendarState extends State /// Check the week date needs month header at in between the appointment /// views. - bool isNeedInBetweenMonthBuilder = _useMobilePlatformUI && + bool isNeedInBetweenMonthBuilder = + _useMobilePlatformUI && (startDate.month != (isSameOrBeforeDate(_maxDate, endDate) ? endDate : _maxDate!) .month); @@ -3443,14 +3659,16 @@ class _SfCalendarState extends State /// Check the end date month have appointments or not. bool isNextMonthHasNoAppointment = false; if (isNeedInBetweenMonthBuilder) { - final DateTime? lastAppointmentDate = dateAppointmentKeys.isNotEmpty - ? dateAppointmentKeys[dateAppointmentKeys.length - 1] - : null; - final DateTime? nextWeekDate = index == -1 - ? _nextDates[0] - : (index < 0 - ? _previousDates[-index - 2] - : index >= _nextDates.length - 1 + final DateTime? lastAppointmentDate = + dateAppointmentKeys.isNotEmpty + ? dateAppointmentKeys[dateAppointmentKeys.length - 1] + : null; + final DateTime? nextWeekDate = + index == -1 + ? _nextDates[0] + : (index < 0 + ? _previousDates[-index - 2] + : index >= _nextDates.length - 1 ? null : _nextDates[index + 1]); @@ -3462,13 +3680,15 @@ class _SfCalendarState extends State /// 3. If the week have appointments but next month dates does not have /// an appointments but [hideEmptyScheduleWeek] enabled so the next view /// date month as different with current week end date week. - isNextMonthHasNoAppointment = lastAppointmentDate == null || + isNextMonthHasNoAppointment = + lastAppointmentDate == null || (lastAppointmentDate.month != endDate.month && nextWeekDate != null && nextWeekDate.month == endDate.month && nextWeekDate.year == endDate.year); - isNeedInBetweenMonthBuilder = isNextMonthHasNoAppointment || + isNeedInBetweenMonthBuilder = + isNextMonthHasNoAppointment || lastAppointmentDate.month != startDate.month; } @@ -3565,16 +3785,17 @@ class _SfCalendarState extends State startDate.year != currentDate.year)) { final double monthHeaderHeight = widget.scheduleViewSettings.monthHeaderSettings.height + - viewTopPadding; + viewTopPadding; if (topPosition <= yPosition && topPosition + monthHeaderHeight > yPosition) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on header in schedule view. return CalendarDetails( - null, - DateTime(currentDate.year, currentDate.month), - CalendarElement.header, - null); + null, + DateTime(currentDate.year, currentDate.month), + CalendarElement.header, + null, + ); } topPosition += monthHeaderHeight; @@ -3618,7 +3839,8 @@ class _SfCalendarState extends State } final double totalPadding = (eventsCount + 1) * padding; - final double panelHeight = totalPadding + + final double panelHeight = + totalPadding + ((eventsCount - allDayEventCount) * appointmentViewHeight) + (allDayEventCount * allDayAppointmentHeight); double appointmentViewPadding = 0; @@ -3633,16 +3855,23 @@ class _SfCalendarState extends State appointmentViewPadding + dividerHeight) { currentAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); currentAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isAllDay, + app2.isAllDay, + ), + ); currentAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isSpanned, + app2.isSpanned, + ), + ); if ((!_isRTL && viewPadding >= position.dx) || (_isRTL && _minWidth - viewPadding < position.dx)) { @@ -3656,15 +3885,17 @@ class _SfCalendarState extends State /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on view header in schedule view. return CalendarDetails( - widget.dataSource != null && - !AppointmentHelper.isCalendarAppointment( - widget.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - currentAppointments, widget.dataSource) - : currentAppointments, - DateTime(currentDate.year, currentDate.month, currentDate.day), - CalendarElement.viewHeader, - null); + widget.dataSource != null && + !AppointmentHelper.isCalendarAppointment(widget.dataSource!) + ? CalendarViewHelper.getCustomAppointments( + currentAppointments, + widget.dataSource, + ) + : currentAppointments, + DateTime(currentDate.year, currentDate.month, currentDate.day), + CalendarElement.viewHeader, + null, + ); } else { /// Calculate the touch position appointment from its collection. double currentYPosition = topPosition + padding; @@ -3672,9 +3903,9 @@ class _SfCalendarState extends State final CalendarAppointment appointment = currentAppointments[k]; final double currentAppointmentHeight = (_useMobilePlatformUI && _isAllDayAppointmentView(appointment) - ? allDayAppointmentHeight - : appointmentViewHeight) + - padding; + ? allDayAppointmentHeight + : appointmentViewHeight) + + padding; if (currentYPosition <= yPosition && currentYPosition + currentAppointmentHeight > yPosition) { final List selectedAppointment = @@ -3683,16 +3914,19 @@ class _SfCalendarState extends State /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on appointment in schedule view. return CalendarDetails( - widget.dataSource != null && - !AppointmentHelper.isCalendarAppointment( - widget.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - selectedAppointment, widget.dataSource) - : selectedAppointment, - DateTime( - currentDate.year, currentDate.month, currentDate.day), - CalendarElement.appointment, - null); + widget.dataSource != null && + !AppointmentHelper.isCalendarAppointment( + widget.dataSource!, + ) + ? CalendarViewHelper.getCustomAppointments( + selectedAppointment, + widget.dataSource, + ) + : selectedAppointment, + DateTime(currentDate.year, currentDate.month, currentDate.day), + CalendarElement.appointment, + null, + ); } currentYPosition += currentAppointmentHeight; @@ -3753,13 +3987,17 @@ class _SfCalendarState extends State /// point. final double monthHeaderHeight = widget.scheduleViewSettings.monthHeaderSettings.height + - viewTopPadding; + viewTopPadding; if (topPosition <= yPosition && topPosition + monthHeaderHeight > yPosition) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on header in schedule view. - return CalendarDetails(null, DateTime(endDate.year, endDate.month), - CalendarElement.header, null); + return CalendarDetails( + null, + DateTime(endDate.year, endDate.month), + CalendarElement.header, + null, + ); } topPosition += monthHeaderHeight; } @@ -3836,130 +4074,145 @@ class _SfCalendarState extends State } SfCalendarThemeData _getThemeDataValue( - SfCalendarThemeData calendarThemeData, ThemeData themeData) { + SfCalendarThemeData calendarThemeData, + ThemeData themeData, + ) { final ColorScheme colorScheme = themeData.colorScheme; - final SfCalendarThemeData effectiveThemeData = - SfCalendarThemeColors(context); + final SfCalendarThemeData effectiveThemeData = SfCalendarThemeColors( + context, + ); final bool isMaterial3 = themeData.useMaterial3; return calendarThemeData.copyWith( - backgroundColor: calendarThemeData.backgroundColor ?? - effectiveThemeData.backgroundColor, - headerBackgroundColor: calendarThemeData.headerBackgroundColor ?? - effectiveThemeData.headerBackgroundColor, - agendaBackgroundColor: calendarThemeData.agendaBackgroundColor ?? - effectiveThemeData.agendaBackgroundColor, - activeDatesBackgroundColor: - calendarThemeData.activeDatesBackgroundColor ?? - effectiveThemeData.activeDatesBackgroundColor, - todayBackgroundColor: calendarThemeData.todayBackgroundColor ?? - effectiveThemeData.todayBackgroundColor, - trailingDatesBackgroundColor: - calendarThemeData.trailingDatesBackgroundColor ?? - effectiveThemeData.trailingDatesBackgroundColor, - leadingDatesBackgroundColor: - calendarThemeData.leadingDatesBackgroundColor ?? - effectiveThemeData.leadingDatesBackgroundColor, - viewHeaderBackgroundColor: - calendarThemeData.viewHeaderBackgroundColor ?? - effectiveThemeData.viewHeaderBackgroundColor, - allDayPanelColor: calendarThemeData.allDayPanelColor ?? - effectiveThemeData.allDayPanelColor, - weekNumberBackgroundColor: - calendarThemeData.weekNumberBackgroundColor ?? - effectiveThemeData.weekNumberBackgroundColor, - cellBorderColor: calendarThemeData.cellBorderColor ?? - effectiveThemeData.cellBorderColor, - todayHighlightColor: calendarThemeData.todayHighlightColor ?? - effectiveThemeData.todayHighlightColor, - selectionBorderColor: calendarThemeData.selectionBorderColor ?? - effectiveThemeData.selectionBorderColor, - blackoutDatesTextStyle: calendarThemeData.blackoutDatesTextStyle == null - ? widget.blackoutDatesTextStyle - : calendarThemeData.blackoutDatesTextStyle - ?.merge(widget.blackoutDatesTextStyle), - trailingDatesTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: isMaterial3 ? 14 : 13, - ) - .merge(calendarThemeData.trailingDatesTextStyle) - .merge( - widget.monthViewSettings.monthCellStyle.trailingDatesTextStyle), - leadingDatesTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: isMaterial3 ? 14 : 13, - ) - .merge(calendarThemeData.leadingDatesTextStyle) - // ignore: lines_longer_than_80_chars - .merge(widget.monthViewSettings.monthCellStyle.leadingDatesTextStyle), - todayTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onPrimary, - fontSize: isMaterial3 ? 14 : 13, - ) - .merge(calendarThemeData.todayTextStyle) - .merge(widget.todayTextStyle), - headerTextStyle: themeData.textTheme.bodyLarge! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: isMaterial3 ? 16 : 18, - fontWeight: FontWeight.w400, - ) - .merge(calendarThemeData.headerTextStyle) - .merge(widget.headerStyle.textStyle), - activeDatesTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(calendarThemeData.activeDatesTextStyle) - .merge(widget.monthViewSettings.monthCellStyle.textStyle), - timeTextStyle: themeData.textTheme.bodySmall! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: isMaterial3 ? 12 : 10, - fontWeight: FontWeight.w500, - ) - .merge(calendarThemeData.timeTextStyle) - .merge(widget.timeSlotViewSettings.timeTextStyle), - viewHeaderDateTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: isMaterial3 ? 14 : 15, - ) - .merge(calendarThemeData.viewHeaderDateTextStyle) - .merge(widget.viewHeaderStyle.dateTextStyle), - viewHeaderDayTextStyle: themeData.textTheme.bodySmall! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: isMaterial3 ? 12 : 11, - ) - .merge(calendarThemeData.viewHeaderDayTextStyle) - .merge(widget.viewHeaderStyle.dayTextStyle), - displayNameTextStyle: themeData.textTheme.bodySmall! - .copyWith( - color: colorScheme.onSurface, - fontSize: 10, - fontWeight: FontWeight.w500, - ) - .merge(calendarThemeData.displayNameTextStyle) - .merge(widget.resourceViewSettings.displayNameTextStyle), - weekNumberTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: isMaterial3 ? 14 : 13, - ) - .merge(calendarThemeData.weekNumberTextStyle) - .merge(widget.weekNumberStyle.textStyle), - timeIndicatorTextStyle: themeData.textTheme.bodySmall! - .copyWith( - color: colorScheme.primary, - fontSize: 10, - fontWeight: FontWeight.w500, - ) - .merge(calendarThemeData.timeIndicatorTextStyle) - .merge(widget.dragAndDropSettings.timeIndicatorStyle)); + backgroundColor: + calendarThemeData.backgroundColor ?? + effectiveThemeData.backgroundColor, + headerBackgroundColor: + calendarThemeData.headerBackgroundColor ?? + effectiveThemeData.headerBackgroundColor, + agendaBackgroundColor: + calendarThemeData.agendaBackgroundColor ?? + effectiveThemeData.agendaBackgroundColor, + activeDatesBackgroundColor: + calendarThemeData.activeDatesBackgroundColor ?? + effectiveThemeData.activeDatesBackgroundColor, + todayBackgroundColor: + calendarThemeData.todayBackgroundColor ?? + effectiveThemeData.todayBackgroundColor, + trailingDatesBackgroundColor: + calendarThemeData.trailingDatesBackgroundColor ?? + effectiveThemeData.trailingDatesBackgroundColor, + leadingDatesBackgroundColor: + calendarThemeData.leadingDatesBackgroundColor ?? + effectiveThemeData.leadingDatesBackgroundColor, + viewHeaderBackgroundColor: + calendarThemeData.viewHeaderBackgroundColor ?? + effectiveThemeData.viewHeaderBackgroundColor, + allDayPanelColor: + calendarThemeData.allDayPanelColor ?? + effectiveThemeData.allDayPanelColor, + weekNumberBackgroundColor: + calendarThemeData.weekNumberBackgroundColor ?? + effectiveThemeData.weekNumberBackgroundColor, + cellBorderColor: + calendarThemeData.cellBorderColor ?? + effectiveThemeData.cellBorderColor, + todayHighlightColor: + calendarThemeData.todayHighlightColor ?? + effectiveThemeData.todayHighlightColor, + selectionBorderColor: + calendarThemeData.selectionBorderColor ?? + effectiveThemeData.selectionBorderColor, + blackoutDatesTextStyle: + calendarThemeData.blackoutDatesTextStyle == null + ? widget.blackoutDatesTextStyle + : calendarThemeData.blackoutDatesTextStyle?.merge( + widget.blackoutDatesTextStyle, + ), + trailingDatesTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: isMaterial3 ? 14 : 13, + ) + .merge(calendarThemeData.trailingDatesTextStyle) + .merge( + widget.monthViewSettings.monthCellStyle.trailingDatesTextStyle, + ), + leadingDatesTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: isMaterial3 ? 14 : 13, + ) + .merge(calendarThemeData.leadingDatesTextStyle) + // ignore: lines_longer_than_80_chars + .merge(widget.monthViewSettings.monthCellStyle.leadingDatesTextStyle), + todayTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onPrimary, + fontSize: isMaterial3 ? 14 : 13, + ) + .merge(calendarThemeData.todayTextStyle) + .merge(widget.todayTextStyle), + headerTextStyle: themeData.textTheme.bodyLarge! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: isMaterial3 ? 16 : 18, + fontWeight: FontWeight.w400, + ) + .merge(calendarThemeData.headerTextStyle) + .merge(widget.headerStyle.textStyle), + activeDatesTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(calendarThemeData.activeDatesTextStyle) + .merge(widget.monthViewSettings.monthCellStyle.textStyle), + timeTextStyle: themeData.textTheme.bodySmall! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: isMaterial3 ? 12 : 10, + fontWeight: FontWeight.w500, + ) + .merge(calendarThemeData.timeTextStyle) + .merge(widget.timeSlotViewSettings.timeTextStyle), + viewHeaderDateTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: isMaterial3 ? 14 : 15, + ) + .merge(calendarThemeData.viewHeaderDateTextStyle) + .merge(widget.viewHeaderStyle.dateTextStyle), + viewHeaderDayTextStyle: themeData.textTheme.bodySmall! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: isMaterial3 ? 12 : 11, + ) + .merge(calendarThemeData.viewHeaderDayTextStyle) + .merge(widget.viewHeaderStyle.dayTextStyle), + displayNameTextStyle: themeData.textTheme.bodySmall! + .copyWith( + color: colorScheme.onSurface, + fontSize: 10, + fontWeight: FontWeight.w500, + ) + .merge(calendarThemeData.displayNameTextStyle) + .merge(widget.resourceViewSettings.displayNameTextStyle), + weekNumberTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: isMaterial3 ? 14 : 13, + ) + .merge(calendarThemeData.weekNumberTextStyle) + .merge(widget.weekNumberStyle.textStyle), + timeIndicatorTextStyle: themeData.textTheme.bodySmall! + .copyWith( + color: colorScheme.primary, + fontSize: 10, + fontWeight: FontWeight.w500, + ) + .merge(calendarThemeData.timeIndicatorTextStyle) + .merge(widget.dragAndDropSettings.timeIndicatorStyle), + ); } void _updateFadeAnimation() { @@ -3972,8 +4225,9 @@ class _SfCalendarState extends State /// loads the time zone data base to handle the time zone for calendar Future _loadDataBase() async { - final ByteData byteData = - await rootBundle.load('packages/timezone/data/latest_all.tzf'); + final ByteData byteData = await rootBundle.load( + 'packages/timezone/data/latest_all.tzf', + ); initializeDatabase(byteData.buffer.asUint8List()); _timeZoneLoaded = true; timeZoneLoaded = true; @@ -3984,7 +4238,9 @@ class _SfCalendarState extends State /// time zone details void _getAppointment() { _appointments = AppointmentHelper.generateCalendarAppointments( - widget.dataSource, widget.timeZone); + widget.dataSource, + widget.timeZone, + ); _updateVisibleAppointments(); } @@ -4000,8 +4256,9 @@ class _SfCalendarState extends State DateTime viewEndDate = _currentViewVisibleDates[visibleDatesCount - 1]; if (_view == CalendarView.month && !CalendarViewHelper.isLeadingAndTrailingDatesVisible( - widget.monthViewSettings.numberOfWeeksInView, - widget.monthViewSettings.showTrailingAndLeadingDates)) { + widget.monthViewSettings.numberOfWeeksInView, + widget.monthViewSettings.showTrailingAndLeadingDates, + )) { final DateTime currentMonthDate = _currentViewVisibleDates[visibleDatesCount ~/ 2]; viewStartDate = AppointmentHelper.getMonthStartDate(currentMonthDate); @@ -4010,14 +4267,17 @@ class _SfCalendarState extends State final List tempVisibleAppointment = AppointmentHelper.getVisibleAppointments( - viewStartDate, - viewEndDate, - _appointments, - widget.timeZone, - _view == CalendarView.month || - CalendarViewHelper.isTimelineView(_view)); + viewStartDate, + viewEndDate, + _appointments, + widget.timeZone, + _view == CalendarView.month || + CalendarViewHelper.isTimelineView(_view), + ); if (CalendarViewHelper.isCollectionEqual( - _visibleAppointments, tempVisibleAppointment)) { + _visibleAppointments, + tempVisibleAppointment, + )) { SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { if (mounted) { setState(() { @@ -4115,7 +4375,8 @@ class _SfCalendarState extends State } final DateTime currentViewDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, date)); + getValidDate(widget.minDate, widget.maxDate, date), + ); _currentDate = currentViewDate; if (currentViewDate.month != _headerUpdateNotifier.value!.month || currentViewDate.year != _headerUpdateNotifier.value!.year) { @@ -4154,7 +4415,8 @@ class _SfCalendarState extends State } final DateTime currentViewDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, date)); + getValidDate(widget.minDate, widget.maxDate, date), + ); _currentDate = currentViewDate; if (currentViewDate.month != _headerUpdateNotifier.value!.month || currentViewDate.year != _headerUpdateNotifier.value!.year) { @@ -4179,7 +4441,8 @@ class _SfCalendarState extends State if (_agendaScrollController!.position.pixels == _agendaScrollController!.position.minScrollExtent) { DateTime date = AppointmentHelper.getMonthStartDate( - DateTime(_scheduleMinDate!.year, _scheduleMinDate!.month - 1)); + DateTime(_scheduleMinDate!.year, _scheduleMinDate!.month - 1), + ); if (!isSameOrAfterDate(widget.minDate, date)) { date = widget.minDate; @@ -4193,7 +4456,8 @@ class _SfCalendarState extends State } } else { DateTime date = AppointmentHelper.getMonthEndDate( - DateTime(_scheduleMaxDate!.year, _scheduleMaxDate!.month + 1)); + DateTime(_scheduleMaxDate!.year, _scheduleMaxDate!.month + 1), + ); if (!isSameOrBeforeDate(widget.maxDate, date)) { date = widget.maxDate; @@ -4213,22 +4477,28 @@ class _SfCalendarState extends State /// when selected date changed programmatically. void _updateSelectionChangedCallback() { if (!CalendarViewHelper.shouldRaiseCalendarSelectionChangedCallback( - widget.onSelectionChanged)) { + widget.onSelectionChanged, + )) { return; } - final bool isResourceEnabled = - CalendarViewHelper.isResourceEnabled(widget.dataSource, _view); + final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( + widget.dataSource, + _view, + ); CalendarViewHelper.raiseCalendarSelectionChangedCallback( - widget, - _controller.selectedDate, - isResourceEnabled ? widget.dataSource!.resources![0] : null); + widget, + _controller.selectedDate, + isResourceEnabled ? widget.dataSource!.resources![0] : null, + ); } void _calendarValueChangedListener(String property) { _removeDatePicker(); if (property == 'selectedDate') { if (CalendarViewHelper.isSameTimeSlot( - _selectedDate, _controller.selectedDate)) { + _selectedDate, + _controller.selectedDate, + )) { return; } _updateSelectionChangedCallback(); @@ -4245,8 +4515,13 @@ class _SfCalendarState extends State setState(() { final CalendarView oldView = _view; _view = _controller.view!; - _currentDate = DateTimeHelper.getDateTimeValue(getValidDate( - widget.minDate, widget.maxDate, _updateCurrentDate(oldView))); + _currentDate = DateTimeHelper.getDateTimeValue( + getValidDate( + widget.minDate, + widget.maxDate, + _updateCurrentDate(oldView), + ), + ); if (!isSameDate(_currentDate, _controller.displayDate)) { _canScrollTimeSlotView = false; _controller.displayDate = _currentDate; @@ -4268,9 +4543,11 @@ class _SfCalendarState extends State if (_view == CalendarView.schedule) { _scheduleDisplayDate = _controller.displayDate!; if (CalendarViewHelper.shouldRaiseViewChangedCallback( - widget.onViewChanged)) { - CalendarViewHelper.raiseViewChangedCallback( - widget, [_controller.displayDate!]); + widget.onViewChanged, + )) { + CalendarViewHelper.raiseViewChangedCallback(widget, [ + _controller.displayDate!, + ]); } _agendaScrollController?.removeListener(_handleScheduleViewScrolled); @@ -4281,7 +4558,9 @@ class _SfCalendarState extends State } }); } else if (CalendarViewHelper.isResourceEnabled( - widget.dataSource, _view)) { + widget.dataSource, + _view, + )) { _resourcePanelScrollController ??= ScrollController(); } }); @@ -4313,8 +4592,9 @@ class _SfCalendarState extends State _currentDate = _controller.displayDate!; _scheduleDisplayDate = _currentDate; _updateCurrentVisibleDates(); - _agendaScrollController - ?.removeListener(_handleScheduleViewScrolled); + _agendaScrollController?.removeListener( + _handleScheduleViewScrolled, + ); _agendaScrollController!.dispose(); _initScheduleViewProperties(); }); @@ -4324,15 +4604,17 @@ class _SfCalendarState extends State { if (isSameDate(_currentDate, _controller.displayDate) || (isDateWithInDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[ - _currentViewVisibleDates.length - 1], - _controller.displayDate) && + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - + 1], + _controller.displayDate, + ) && (widget.monthViewSettings.numberOfWeeksInView != 6 || (widget.monthViewSettings.numberOfWeeksInView == 6 && _controller.displayDate!.month == - _currentViewVisibleDates[ - _currentViewVisibleDates.length ~/ 2] + _currentViewVisibleDates[_currentViewVisibleDates + .length ~/ + 2] .month)))) { _currentDate = _controller.displayDate!; return; @@ -4356,9 +4638,10 @@ class _SfCalendarState extends State { if (isSameDate(_currentDate, _controller.displayDate) || isDateWithInDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[_currentViewVisibleDates.length - 1], - _controller.displayDate)) { + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + _controller.displayDate, + )) { if (_canScrollTimeSlotView && _customScrollViewKey.currentWidget != null) { // ignore: avoid_as @@ -4381,23 +4664,30 @@ class _SfCalendarState extends State } void _updateCurrentVisibleDates() { - final List? nonWorkingDays = (_view == CalendarView.workWeek || - _view == CalendarView.timelineWorkWeek) - ? widget.timeSlotViewSettings.nonWorkingDays - : null; + final List? nonWorkingDays = + (_view == CalendarView.workWeek || + _view == CalendarView.timelineWorkWeek) + ? widget.timeSlotViewSettings.nonWorkingDays + : null; final int visibleDatesCount = DateTimeHelper.getViewDatesCount( - _view, - widget.monthViewSettings.numberOfWeeksInView, - widget.timeSlotViewSettings.numberOfDaysInView, - nonWorkingDays); + _view, + widget.monthViewSettings.numberOfWeeksInView, + widget.timeSlotViewSettings.numberOfDaysInView, + nonWorkingDays, + ); - _currentViewVisibleDates = getVisibleDates(_currentDate, nonWorkingDays, - widget.firstDayOfWeek, visibleDatesCount) - .cast(); + _currentViewVisibleDates = + getVisibleDates( + _currentDate, + nonWorkingDays, + widget.firstDayOfWeek, + visibleDatesCount, + ).cast(); if (_view == CalendarView.timelineMonth) { - _currentViewVisibleDates = - DateTimeHelper.getCurrentMonthDates(_currentViewVisibleDates); + _currentViewVisibleDates = DateTimeHelper.getCurrentMonthDates( + _currentViewVisibleDates, + ); if (widget.showWeekNumber) { _timelineMonthWeekNumberNotifier.value = _currentViewVisibleDates[0]; } @@ -4406,7 +4696,9 @@ class _SfCalendarState extends State //// Perform action while data source changed based on data source action. void _dataSourceChangedListener( - CalendarDataSourceAction type, List data) { + CalendarDataSourceAction type, + List data, + ) { if (!_timeZoneLoaded || !mounted) { return; } @@ -4441,7 +4733,10 @@ class _SfCalendarState extends State { final List collection = AppointmentHelper.generateCalendarAppointments( - widget.dataSource, widget.timeZone, data); + widget.dataSource, + widget.timeZone, + data, + ); _loadScheduleViewAppointmentDates(collection); if (_view != CalendarView.schedule) { @@ -4451,23 +4746,27 @@ class _SfCalendarState extends State _currentViewVisibleDates[visibleDatesCount - 1]; if (_view == CalendarView.month && !CalendarViewHelper.isLeadingAndTrailingDatesVisible( - widget.monthViewSettings.numberOfWeeksInView, - widget.monthViewSettings.showTrailingAndLeadingDates)) { + widget.monthViewSettings.numberOfWeeksInView, + widget.monthViewSettings.showTrailingAndLeadingDates, + )) { final DateTime currentMonthDate = _currentViewVisibleDates[visibleDatesCount ~/ 2]; - viewStartDate = - AppointmentHelper.getMonthStartDate(currentMonthDate); + viewStartDate = AppointmentHelper.getMonthStartDate( + currentMonthDate, + ); viewEndDate = AppointmentHelper.getMonthEndDate(currentMonthDate); } visibleAppointmentCollection.addAll( - AppointmentHelper.getVisibleAppointments( - viewStartDate, - viewEndDate, - collection, - widget.timeZone, - _view == CalendarView.month || - CalendarViewHelper.isTimelineView(_view))); + AppointmentHelper.getVisibleAppointments( + viewStartDate, + viewEndDate, + collection, + widget.timeZone, + _view == CalendarView.month || + CalendarViewHelper.isTimelineView(_view), + ), + ); } for (int i = 0; i < collection.length; i++) { @@ -4515,8 +4814,9 @@ class _SfCalendarState extends State if (resourceCollection.isNotEmpty) { _disposeResourceImagePainter(); setState(() { - _resourceCollection = - CalendarViewHelper.cloneList(widget.dataSource?.resources); + _resourceCollection = CalendarViewHelper.cloneList( + widget.dataSource?.resources, + ); /* To render the modified resource collection */ if (CalendarViewHelper.isTimelineView(_view)) { _isNeedLoadMore = true; @@ -4548,39 +4848,57 @@ class _SfCalendarState extends State /// hideEmptyScheduleWeek disabled in web UI with schedule view. final DateTime startDate = _previousDates.isEmpty ? _nextDates[0] : _previousDates[0]; - final DateTime endDate = addDuration(_nextDates[_nextDates.length - 1], - const Duration(days: DateTime.daysPerWeek - 1)) as DateTime; + final DateTime endDate = + addDuration( + _nextDates[_nextDates.length - 1], + const Duration(days: DateTime.daysPerWeek - 1), + ) + as DateTime; for (int i = 0; i < collection.length; i++) { /// recursiveDates list used to store the newly added appointments dates List recursiveDates = []; final CalendarAppointment appointment = collection[i]; final List recursiveExceptionDates = []; final Duration difference = AppointmentHelper.getDifference( - appointment.actualStartTime, appointment.actualEndTime); + appointment.actualStartTime, + appointment.actualEndTime, + ); if (appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty) { /// Calculate the occurrence dates collection. recursiveDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - appointment.recurrenceRule!, appointment.actualStartTime, - recurrenceDuration: difference, - specificStartDate: startDate, - specificEndDate: endDate); + appointment.recurrenceRule!, + appointment.actualStartTime, + recurrenceDuration: difference, + specificStartDate: startDate, + specificEndDate: endDate, + ); if (appointment.recurrenceExceptionDates != null) { - for (int i = 0; - i < appointment.recurrenceExceptionDates!.length; - i++) { + for ( + int i = 0; + i < appointment.recurrenceExceptionDates!.length; + i++ + ) { recursiveExceptionDates.add( - AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.recurrenceExceptionDates![i], - '', - widget.timeZone)); + AppointmentHelper.convertTimeToAppointmentTimeZone( + appointment.recurrenceExceptionDates![i], + '', + widget.timeZone, + ), + ); } } } else { if (!isDateWithInDateRange( - startDate, endDate, appointment.actualStartTime) && + startDate, + endDate, + appointment.actualStartTime, + ) && !isDateWithInDateRange( - startDate, endDate, appointment.actualEndTime)) { + startDate, + endDate, + appointment.actualEndTime, + )) { continue; } @@ -4603,13 +4921,20 @@ class _SfCalendarState extends State DateTime appEndDate = addDuration(appointmentDate, difference) as DateTime; - appEndDate = - DateTime(appEndDate.year, appEndDate.month, appEndDate.day); + appEndDate = DateTime( + appEndDate.year, + appEndDate.month, + appEndDate.day, + ); DateTime appDate = DateTime( - appointmentDate.year, appointmentDate.month, appointmentDate.day); + appointmentDate.year, + appointmentDate.month, + appointmentDate.day, + ); /// Calculate start date of the week. - int value = -(appDate.weekday % DateTime.daysPerWeek) + + int value = + -(appDate.weekday % DateTime.daysPerWeek) + widget.firstDayOfWeek - DateTime.daysPerWeek; if (value.abs() >= DateTime.daysPerWeek) { @@ -4617,7 +4942,8 @@ class _SfCalendarState extends State } appDate = addDuration(appDate, Duration(days: value)) as DateTime; - value = -(appEndDate.weekday % DateTime.daysPerWeek) + + value = + -(appEndDate.weekday % DateTime.daysPerWeek) + widget.firstDayOfWeek - DateTime.daysPerWeek; if (value.abs() >= DateTime.daysPerWeek) { @@ -4643,9 +4969,12 @@ class _SfCalendarState extends State while (appCurrentDate.isBefore(appEndDate) || isSameDate(appCurrentDate, appEndDate)) { addNewAppointmentWeekDate(appCurrentDate); - appCurrentDate = addDuration( - appCurrentDate, const Duration(days: DateTime.daysPerWeek)) - as DateTime; + appCurrentDate = + addDuration( + appCurrentDate, + const Duration(days: DateTime.daysPerWeek), + ) + as DateTime; } } } @@ -4667,16 +4996,24 @@ class _SfCalendarState extends State for (int i = 0; i < _previousDates.length; i++) { final DateTime weekStartDate = _previousDates[i]; - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(weekStartDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(weekStartDate, 6), + ); /// Remove the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled. if (!_isAppointmentBetweenDates( - _appointments, weekStartDate, weekEndDate, widget.timeZone) && + _appointments, + weekStartDate, + weekEndDate, + widget.timeZone, + ) && !isDateWithInDateRange(weekStartDate, weekEndDate, DateTime.now()) && !isDateWithInDateRange( - weekStartDate, weekEndDate, _scheduleDisplayDate)) { + weekStartDate, + weekEndDate, + _scheduleDisplayDate, + )) { _previousDates.remove(weekStartDate); i--; } @@ -4685,16 +5022,24 @@ class _SfCalendarState extends State for (int i = 0; i < _nextDates.length; i++) { final DateTime weekStartDate = _nextDates[i]; - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(weekStartDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(weekStartDate, 6), + ); /// Remove the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled. if (!_isAppointmentBetweenDates( - _appointments, weekStartDate, weekEndDate, widget.timeZone) && + _appointments, + weekStartDate, + weekEndDate, + widget.timeZone, + ) && !isDateWithInDateRange(weekStartDate, weekEndDate, DateTime.now()) && !isDateWithInDateRange( - weekStartDate, weekEndDate, _scheduleDisplayDate)) { + weekStartDate, + weekEndDate, + _scheduleDisplayDate, + )) { _nextDates.remove(weekStartDate); i--; } @@ -4715,7 +5060,8 @@ class _SfCalendarState extends State /// Updates the visible appointments collection based on passed collection, /// the collection modified based on the data source's add and remove action. void _updateVisibleAppointmentCollection( - List visibleAppointmentCollection) { + List visibleAppointmentCollection, + ) { if (_view == CalendarView.schedule) { SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) { setState(() { @@ -4726,7 +5072,9 @@ class _SfCalendarState extends State } if (CalendarViewHelper.isCollectionEqual( - _visibleAppointments, visibleAppointmentCollection)) { + _visibleAppointments, + visibleAppointmentCollection, + )) { return; } @@ -4772,28 +5120,36 @@ class _SfCalendarState extends State view == CalendarView.month || view == CalendarView.timelineMonth; if (_selectedDate != null && isDateWithInDateRange( - visibleStartDate, visibleEndDate, _selectedDate)) { + visibleStartDate, + visibleEndDate, + _selectedDate, + )) { if (isMonthView) { return DateTime( - _selectedDate!.year, - _selectedDate!.month, - _selectedDate!.day, - _controller.displayDate!.hour, - _controller.displayDate!.minute, - _controller.displayDate!.second); + _selectedDate!.year, + _selectedDate!.month, + _selectedDate!.day, + _controller.displayDate!.hour, + _controller.displayDate!.minute, + _controller.displayDate!.second, + ); } else { return _selectedDate!; } } else if (isDateWithInDateRange( - visibleStartDate, visibleEndDate, DateTime.now())) { + visibleStartDate, + visibleEndDate, + DateTime.now(), + )) { final DateTime date = DateTime.now(); return DateTime( - date.year, - date.month, - date.day, - _controller.displayDate!.hour, - _controller.displayDate!.minute, - _controller.displayDate!.second); + date.year, + date.month, + date.day, + _controller.displayDate!.hour, + _controller.displayDate!.minute, + _controller.displayDate!.second, + ); } else { if (isMonthView) { if (widget.monthViewSettings.numberOfWeeksInView > 0 && @@ -4801,21 +5157,23 @@ class _SfCalendarState extends State return visibleStartDate; } return DateTime( - _currentDate.year, - _currentDate.month, - 1, - _controller.displayDate!.hour, - _controller.displayDate!.minute, - _controller.displayDate!.second); + _currentDate.year, + _currentDate.month, + 1, + _controller.displayDate!.hour, + _controller.displayDate!.minute, + _controller.displayDate!.second, + ); } else { final DateTime date = visibleStartDate; return DateTime( - date.year, - date.month, - date.day, - _controller.displayDate!.hour, - _controller.displayDate!.minute, - _controller.displayDate!.second); + date.year, + date.month, + date.day, + _controller.displayDate!.hour, + _controller.displayDate!.minute, + _controller.displayDate!.second, + ); } } } @@ -4842,10 +5200,15 @@ class _SfCalendarState extends State continue; } - final int startIndex = DateTimeHelper.getIndex(_currentViewVisibleDates, - appointmentView.appointment!.actualStartTime); - final int endIndex = DateTimeHelper.getIndex(_currentViewVisibleDates, - appointmentView.appointment!.actualEndTime) + + final int startIndex = DateTimeHelper.getIndex( + _currentViewVisibleDates, + appointmentView.appointment!.actualStartTime, + ); + final int endIndex = + DateTimeHelper.getIndex( + _currentViewVisibleDates, + appointmentView.appointment!.actualEndTime, + ) + 1; if (startIndex == -1 && endIndex == 0) { appointmentView.appointment = null; @@ -4858,7 +5221,8 @@ class _SfCalendarState extends State } void _updateAppointmentPositionAndMaxPosition( - List> allDayAppointmentView) { + List> allDayAppointmentView, + ) { for (int i = 0; i < allDayAppointmentView.length; i++) { final List intersectingAppointments = allDayAppointmentView[i]; @@ -4868,7 +5232,9 @@ class _SfCalendarState extends State currentView.position = 0; for (int k = 0; k < j; k++) { final AppointmentView? intersectView = _getAppointmentOnPosition( - currentView, intersectingAppointments); + currentView, + intersectingAppointments, + ); if (intersectView != null) { currentView.position++; } else { @@ -4879,12 +5245,17 @@ class _SfCalendarState extends State } if (intersectingAppointments.isNotEmpty) { - final int maxPosition = intersectingAppointments - .reduce((AppointmentView currentAppView, - AppointmentView nextAppView) => - currentAppView.position > nextAppView.position - ? currentAppView - : nextAppView) + final int maxPosition = + intersectingAppointments + .reduce( + ( + AppointmentView currentAppView, + AppointmentView nextAppView, + ) => + currentAppView.position > nextAppView.position + ? currentAppView + : nextAppView, + ) .position + 1; @@ -4900,7 +5271,9 @@ class _SfCalendarState extends State } AppointmentView? _getAppointmentOnPosition( - AppointmentView? currentView, List? views) { + AppointmentView? currentView, + List? views, + ) { if (currentView == null || currentView.appointment == null || views == null || @@ -4918,7 +5291,8 @@ class _SfCalendarState extends State } void _updateIntersectAppointmentViewCollection( - List> allDayAppointmentView) { + List> allDayAppointmentView, + ) { for (int i = 0; i < _currentViewVisibleDates.length; i++) { final List intersectingAppointments = []; @@ -4958,8 +5332,9 @@ class _SfCalendarState extends State for (final CalendarAppointment appointment in _visibleAppointments) { if (appointment.isAllDay || AppointmentHelper.getDifference( - appointment.actualStartTime, appointment.actualEndTime) - .inDays > + appointment.actualStartTime, + appointment.actualEndTime, + ).inDays > 0) { allDayAppointments.add(appointment); } @@ -4972,13 +5347,19 @@ class _SfCalendarState extends State _updateAppointmentViewPosition(); //// Sort the appointment view based on appointment view width. - _allDayAppointmentViewCollection - .sort((AppointmentView app1, AppointmentView app2) { + _allDayAppointmentViewCollection.sort(( + AppointmentView app1, + AppointmentView app2, + ) { if (app1.appointment != null && app2.appointment != null) { return AppointmentHelper.getDifference( - app2.appointment!.startTime, app2.appointment!.endTime) > + app2.appointment!.startTime, + app2.appointment!.endTime, + ) > AppointmentHelper.getDifference( - app1.appointment!.startTime, app1.appointment!.endTime) + app1.appointment!.startTime, + app1.appointment!.endTime, + ) ? 1 : 0; } @@ -4987,8 +5368,10 @@ class _SfCalendarState extends State }); //// Sort the appointment view based on appointment view start position. - _allDayAppointmentViewCollection - .sort((AppointmentView app1, AppointmentView app2) { + _allDayAppointmentViewCollection.sort(( + AppointmentView app1, + AppointmentView app2, + ) { if (app1.appointment != null && app2.appointment != null) { return app1.startIndex.compareTo(app2.startIndex); } @@ -5010,13 +5393,15 @@ class _SfCalendarState extends State void _updateAllDayPanelHeight() { int maxPosition = 0; if (_allDayAppointmentViewCollection.isNotEmpty) { - maxPosition = _allDayAppointmentViewCollection - .reduce( - (AppointmentView currentAppView, AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + maxPosition = + _allDayAppointmentViewCollection + .reduce( + (AppointmentView currentAppView, AppointmentView nextAppView) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; } if (maxPosition == -1) { @@ -5049,13 +5434,14 @@ class _SfCalendarState extends State } void _updateMouseHoverPosition( - Offset globalPosition, - bool isScheduleDisplayDate, - bool isRTL, - DateTime? currentDate, - double? startPosition, - [double padding = 0, - bool isResourceEnabled = false]) { + Offset globalPosition, + bool isScheduleDisplayDate, + bool isRTL, + DateTime? currentDate, + double? startPosition, [ + double padding = 0, + bool isResourceEnabled = false, + ]) { if (_isMobilePlatform) { return; } @@ -5075,7 +5461,8 @@ class _SfCalendarState extends State localPosition.dy > startPosition! && (CalendarViewHelper.shouldRaiseCalendarTapCallback(widget.onTap) || CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress))) { + widget.onLongPress, + ))) { if (_headerHoverNotifier.value != null) { _headerHoverNotifier.value = null; } @@ -5094,7 +5481,7 @@ class _SfCalendarState extends State final double yPosition = (_resourcePanelScrollController!.offset + localPosition.dy) - - startPosition; + startPosition; _resourceHoverNotifier.value = Offset(localPosition.dx, yPosition); } @@ -5106,7 +5493,9 @@ class _SfCalendarState extends State double yPosition = localPosition.dy; double xPosition = localPosition.dx; double dateViewWidth = _getAgendaViewDayLabelWidth( - widget.scheduleViewSettings, _useMobilePlatformUI); + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); if (_view == CalendarView.month) { currentDate = _selectedDate; final double agendaHeight = _getMonthAgendaHeight(); @@ -5120,7 +5509,8 @@ class _SfCalendarState extends State dateViewWidth = 60; } } else { - yPosition = (_agendaScrollController!.offset + localPosition.dy) - + yPosition = + (_agendaScrollController!.offset + localPosition.dy) - startPosition! - widget.headerHeight; } @@ -5148,7 +5538,9 @@ class _SfCalendarState extends State xPosition = isRTL ? _minWidth - xPosition : xPosition; _agendaDateNotifier.value = ScheduleViewHoveringDetails( - currentDate!, Offset(xPosition, yPosition)); + currentDate!, + Offset(xPosition, yPosition), + ); } else { /// padding value used to specify the view top padding on agenda view. /// padding value is assigned when the agenda view has top padding @@ -5178,29 +5570,51 @@ class _SfCalendarState extends State return; } _agendaViewNotifier.value = ScheduleViewHoveringDetails( - currentDate!, Offset(xPosition, yPosition)); + currentDate!, + Offset(xPosition, yPosition), + ); } } } void _pointerEnterEvent( - PointerEnterEvent event, bool isScheduleDisplayDate, bool isRTL, - [DateTime? currentDate, - double? startPosition, - double padding = 0, - bool resourceEnabled = false]) { - _updateMouseHoverPosition(event.position, isScheduleDisplayDate, isRTL, - currentDate, startPosition, padding, resourceEnabled); + PointerEnterEvent event, + bool isScheduleDisplayDate, + bool isRTL, [ + DateTime? currentDate, + double? startPosition, + double padding = 0, + bool resourceEnabled = false, + ]) { + _updateMouseHoverPosition( + event.position, + isScheduleDisplayDate, + isRTL, + currentDate, + startPosition, + padding, + resourceEnabled, + ); } void _pointerHoverEvent( - PointerHoverEvent event, bool isScheduleDisplayDate, bool isRTL, - [DateTime? currentDate, - double? startPosition, - double padding = 0, - bool resourceEnabled = false]) { - _updateMouseHoverPosition(event.position, isScheduleDisplayDate, isRTL, - currentDate, startPosition, padding, resourceEnabled); + PointerHoverEvent event, + bool isScheduleDisplayDate, + bool isRTL, [ + DateTime? currentDate, + double? startPosition, + double padding = 0, + bool resourceEnabled = false, + ]) { + _updateMouseHoverPosition( + event.position, + isScheduleDisplayDate, + isRTL, + currentDate, + startPosition, + padding, + resourceEnabled, + ); } void _pointerExitEvent(PointerExitEvent event) { @@ -5213,12 +5627,13 @@ class _SfCalendarState extends State /// Calculate the maximum appointment date based on appointment collection /// and schedule view settings. DateTime _getMaxAppointmentDate( - List appointments, - String? timeZone, - DateTime maxDate, - DateTime displayDate, - ScheduleViewSettings scheduleViewSettings, - bool useMobilePlatformUI) { + List appointments, + String? timeZone, + DateTime maxDate, + DateTime displayDate, + ScheduleViewSettings scheduleViewSettings, + bool useMobilePlatformUI, + ) { /// return default max date when [hideEmptyAgendaDays] as false if (!scheduleViewSettings.hideEmptyScheduleWeek && useMobilePlatformUI) { return maxDate; @@ -5233,9 +5648,12 @@ class _SfCalendarState extends State /// web view enabled or [hideEmptyAgendaDays] property as enabled. for (int j = 0; j < appointments.length; j++) { final CalendarAppointment appointment = appointments[j]; - appointment.actualEndTime = - AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.endTime, appointment.endTimeZone, timeZone); + appointment + .actualEndTime = AppointmentHelper.convertTimeToAppointmentTimeZone( + appointment.endTime, + appointment.endTimeZone, + timeZone, + ); if (appointment.recurrenceRule == null || appointment.recurrenceRule == '') { @@ -5257,12 +5675,21 @@ class _SfCalendarState extends State if (appointment.recurrenceRule!.contains('UNTIL')) { final List ruleSeparator = ['=', ';', ',']; final List rRule = RecurrenceHelper.splitRule( - appointment.recurrenceRule!, ruleSeparator); + appointment.recurrenceRule!, + ruleSeparator, + ); final String untilValue = rRule[rRule.indexOf('UNTIL') + 1]; - DateTime recurrenceEndDate = - RecurrenceHelper.getUntilEndDate(untilValue); - recurrenceEndDate = DateTime(recurrenceEndDate.year, - recurrenceEndDate.month, recurrenceEndDate.day, 23, 59, 59); + DateTime recurrenceEndDate = RecurrenceHelper.getUntilEndDate( + untilValue, + ); + recurrenceEndDate = DateTime( + recurrenceEndDate.year, + recurrenceEndDate.month, + recurrenceEndDate.day, + 23, + 59, + 59, + ); if (recurrenceEndDate.isAfter(currentMaxDate)) { currentMaxDate = recurrenceEndDate; continue; @@ -5271,9 +5698,9 @@ class _SfCalendarState extends State final List recursiveDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - appointment.recurrenceRule!, - appointment.actualStartTime, - ); + appointment.recurrenceRule!, + appointment.actualStartTime, + ); if (recursiveDates.isEmpty) { continue; @@ -5289,14 +5716,18 @@ class _SfCalendarState extends State } final Duration duration = AppointmentHelper.getDifference( - appointment.actualStartTime, appointment.actualEndTime); + appointment.actualStartTime, + appointment.actualEndTime, + ); for (int k = recursiveDates.length - 1; k >= 0; k--) { final DateTime recurrenceDate = recursiveDates[k]; bool isExceptionDate = false; if (appointment.recurrenceExceptionDates != null) { - for (int i = 0; - i < appointment.recurrenceExceptionDates!.length; - i++) { + for ( + int i = 0; + i < appointment.recurrenceExceptionDates!.length; + i++ + ) { final DateTime exceptionDate = appointment.recurrenceExceptionDates![i]; if (isSameDate(recurrenceDate, exceptionDate)) { @@ -5307,7 +5738,8 @@ class _SfCalendarState extends State if (!isExceptionDate) { final DateTime recurrenceEndDate = DateTimeHelper.getDateTimeValue( - addDuration(recurrenceDate, duration)); + addDuration(recurrenceDate, duration), + ); if (recurrenceEndDate.isAfter(currentMaxDate)) { currentMaxDate = recurrenceEndDate; break; @@ -5322,12 +5754,13 @@ class _SfCalendarState extends State /// Calculate the minimum appointment date based on appointment collection /// and schedule view settings. DateTime _getMinAppointmentDate( - List appointments, - String? timeZone, - DateTime minDate, - DateTime displayDate, - ScheduleViewSettings scheduleViewSettings, - bool useMobilePlatformUI) { + List appointments, + String? timeZone, + DateTime minDate, + DateTime displayDate, + ScheduleViewSettings scheduleViewSettings, + bool useMobilePlatformUI, + ) { /// return default min date when hideEmptyAgendaDays as false if (!scheduleViewSettings.hideEmptyScheduleWeek && useMobilePlatformUI) { return minDate; @@ -5342,9 +5775,12 @@ class _SfCalendarState extends State /// web view enabled or [hideEmptyAgendaDays] property as enabled. for (int j = 0; j < appointments.length; j++) { final CalendarAppointment appointment = appointments[j]; - appointment.actualStartTime = - AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.startTime, appointment.startTimeZone, timeZone); + appointment + .actualStartTime = AppointmentHelper.convertTimeToAppointmentTimeZone( + appointment.startTime, + appointment.startTimeZone, + timeZone, + ); if (appointment.actualStartTime.isBefore(currentMinDate)) { currentMinDate = appointment.actualStartTime; @@ -5358,8 +5794,12 @@ class _SfCalendarState extends State /// Check any appointment in appointments collection in between /// the start and end date. - bool _isAppointmentBetweenDates(List appointments, - DateTime startDate, DateTime endDate, String? timeZone) { + bool _isAppointmentBetweenDates( + List appointments, + DateTime startDate, + DateTime endDate, + String? timeZone, + ) { startDate = AppointmentHelper.convertToStartTime(startDate); endDate = AppointmentHelper.convertToEndTime(endDate); if (appointments.isEmpty) { @@ -5368,17 +5808,26 @@ class _SfCalendarState extends State for (int j = 0; j < appointments.length; j++) { final CalendarAppointment appointment = appointments[j]; - appointment.actualStartTime = - AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.startTime, appointment.startTimeZone, timeZone); - appointment.actualEndTime = - AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.endTime, appointment.endTimeZone, timeZone); + appointment + .actualStartTime = AppointmentHelper.convertTimeToAppointmentTimeZone( + appointment.startTime, + appointment.startTimeZone, + timeZone, + ); + appointment + .actualEndTime = AppointmentHelper.convertTimeToAppointmentTimeZone( + appointment.endTime, + appointment.endTimeZone, + timeZone, + ); if (appointment.recurrenceRule == null || appointment.recurrenceRule == '') { if (AppointmentHelper.isAppointmentWithinVisibleDateRange( - appointment, startDate, endDate)) { + appointment, + startDate, + endDate, + )) { return true; } @@ -5397,14 +5846,23 @@ class _SfCalendarState extends State } final List ruleSeparator = ['=', ';', ',']; - final List rRule = - RecurrenceHelper.splitRule(rule, ruleSeparator); + final List rRule = RecurrenceHelper.splitRule( + rule, + ruleSeparator, + ); if (rRule.contains('UNTIL')) { final String untilValue = rRule[rRule.indexOf('UNTIL') + 1]; - DateTime recurrenceEndDate = - RecurrenceHelper.getUntilEndDate(untilValue); - recurrenceEndDate = DateTime(recurrenceEndDate.year, - recurrenceEndDate.month, recurrenceEndDate.day, 23, 59, 59); + DateTime recurrenceEndDate = RecurrenceHelper.getUntilEndDate( + untilValue, + ); + recurrenceEndDate = DateTime( + recurrenceEndDate.year, + recurrenceEndDate.month, + recurrenceEndDate.day, + 23, + 59, + 59, + ); if (recurrenceEndDate.isBefore(startDate)) { continue; } @@ -5412,11 +5870,15 @@ class _SfCalendarState extends State final List recursiveDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - rule, appointment.actualStartTime, - recurrenceDuration: AppointmentHelper.getDifference( - appointment.actualStartTime, appointment.actualEndTime), - specificStartDate: startDate, - specificEndDate: endDate); + rule, + appointment.actualStartTime, + recurrenceDuration: AppointmentHelper.getDifference( + appointment.actualStartTime, + appointment.actualEndTime, + ), + specificStartDate: startDate, + specificEndDate: endDate, + ); if (recursiveDates.isEmpty) { continue; @@ -5467,17 +5929,21 @@ class _SfCalendarState extends State /// Return the collection of appointment collection listed by /// start date of the appointment. Map> _getAppointmentCollectionOnDateBasis( - List appointmentCollection, - DateTime startDate, - DateTime endDate) { + List appointmentCollection, + DateTime startDate, + DateTime endDate, + ) { final Map> dateAppointments = >{}; while (startDate.isBefore(endDate) || isSameDate(endDate, startDate)) { final List appointmentList = []; for (int i = 0; i < appointmentCollection.length; i++) { final CalendarAppointment appointment = appointmentCollection[i]; - if (!isDateWithInDateRange(appointment.actualStartTime, - appointment.actualEndTime, startDate)) { + if (!isDateWithInDateRange( + appointment.actualStartTime, + appointment.actualEndTime, + startDate, + )) { continue; } @@ -5520,45 +5986,50 @@ class _SfCalendarState extends State /// in [ScheduleViewSettings] disabled else it return min /// start date of the appointment collection. _minDate ??= _getMinAppointmentDate( - _appointments, - widget.timeZone, - widget.minDate, - scheduleDisplayDate, - widget.scheduleViewSettings, - _useMobilePlatformUI); + _appointments, + widget.timeZone, + widget.minDate, + scheduleDisplayDate, + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); /// Assign minimum date value to schedule display date when the minimum /// date is after of schedule display date - _minDate = _minDate!.isAfter(scheduleDisplayDate) - ? scheduleDisplayDate - : _minDate; + _minDate = + _minDate!.isAfter(scheduleDisplayDate) + ? scheduleDisplayDate + : _minDate; _minDate = _minDate!.isBefore(widget.minDate) ? widget.minDate : _minDate; final DateTime viewMinDate = DateTimeHelper.getDateTimeValue( - addDays(_minDate, -(_minDate!.weekday % DateTime.daysPerWeek))); + addDays(_minDate, -(_minDate!.weekday % DateTime.daysPerWeek)), + ); /// Get the maximum date of schedule view when it value as null /// It return max date user assigned when the [hideEmptyScheduleWeek] /// in [ScheduleViewSettings] disabled else it return max /// end date of the appointment collection. _maxDate ??= _getMaxAppointmentDate( - _appointments, - widget.timeZone, - widget.maxDate, - scheduleCurrentDate, - widget.scheduleViewSettings, - _useMobilePlatformUI); + _appointments, + widget.timeZone, + widget.maxDate, + scheduleCurrentDate, + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); /// Assign maximum date value to schedule current date when the maximum /// date is before of schedule current date - _maxDate = _maxDate!.isBefore(scheduleCurrentDate) - ? scheduleCurrentDate - : _maxDate; + _maxDate = + _maxDate!.isBefore(scheduleCurrentDate) + ? scheduleCurrentDate + : _maxDate; _maxDate = _maxDate!.isAfter(widget.maxDate) ? widget.maxDate : _maxDate; final bool hideEmptyAgendaDays = widget.scheduleViewSettings.hideEmptyScheduleWeek || - !_useMobilePlatformUI; + !_useMobilePlatformUI; if (index >= 0) { /// Add next 100 dates to next dates collection when index @@ -5572,7 +6043,8 @@ class _SfCalendarState extends State while (count < 20) { for (int i = 1; i <= 100; i++) { final DateTime updateDate = DateTimeHelper.getDateTimeValue( - addDays(date, i * DateTime.daysPerWeek)); + addDays(date, i * DateTime.daysPerWeek), + ); /// Skip the weeks after the max date. if (!isSameOrBeforeDate(_maxDate, updateDate)) { @@ -5580,19 +6052,30 @@ class _SfCalendarState extends State break; } - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(updateDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(updateDate, 6), + ); /// Skip the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled and display date and /// current date not in between the week. if (!hideEmptyAgendaDays || - _isAppointmentBetweenDates(_appointments, updateDate, - weekEndDate, widget.timeZone) || + _isAppointmentBetweenDates( + _appointments, + updateDate, + weekEndDate, + widget.timeZone, + ) || isDateWithInDateRange( - updateDate, weekEndDate, scheduleDisplayDate) || + updateDate, + weekEndDate, + scheduleDisplayDate, + ) || isDateWithInDateRange( - updateDate, weekEndDate, scheduleCurrentDate)) { + updateDate, + weekEndDate, + scheduleCurrentDate, + )) { _nextDates.add(updateDate); count++; } @@ -5615,7 +6098,8 @@ class _SfCalendarState extends State while (count < 20) { for (int i = 1; i <= 100; i++) { final DateTime updatedDate = DateTimeHelper.getDateTimeValue( - addDays(date, -i * DateTime.daysPerWeek)); + addDays(date, -i * DateTime.daysPerWeek), + ); /// Skip the weeks before the min date. if (!isSameOrAfterDate(viewMinDate, updatedDate)) { @@ -5623,19 +6107,30 @@ class _SfCalendarState extends State break; } - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(updatedDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(updatedDate, 6), + ); /// Skip the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled and display date and /// current date not in between the week. if (!hideEmptyAgendaDays || - _isAppointmentBetweenDates(_appointments, updatedDate, - weekEndDate, widget.timeZone) || + _isAppointmentBetweenDates( + _appointments, + updatedDate, + weekEndDate, + widget.timeZone, + ) || isDateWithInDateRange( - updatedDate, weekEndDate, scheduleDisplayDate) || + updatedDate, + weekEndDate, + scheduleDisplayDate, + ) || isDateWithInDateRange( - updatedDate, weekEndDate, scheduleCurrentDate)) { + updatedDate, + weekEndDate, + scheduleCurrentDate, + )) { _previousDates.add(updatedDate); count++; } @@ -5663,21 +6158,26 @@ class _SfCalendarState extends State /// next dates collection then get the start date from previous dates. /// If the index as last index of previous dates collection then calculate /// by subtract the 7 days to get previous date. - final DateTime prevDate = index == 0 - ? _previousDates.isEmpty - ? DateTimeHelper.getDateTimeValue( - addDays(startDate, -DateTime.daysPerWeek)) - : _previousDates[0] - : (index > 0 - ? _nextDates[index - 1] - : -index > _previousDates.length - 1 + final DateTime prevDate = + index == 0 + ? _previousDates.isEmpty + ? DateTimeHelper.getDateTimeValue( + addDays(startDate, -DateTime.daysPerWeek), + ) + : _previousDates[0] + : (index > 0 + ? _nextDates[index - 1] + : -index > _previousDates.length - 1 ? DateTimeHelper.getDateTimeValue( - addDays(startDate, -DateTime.daysPerWeek)) + addDays(startDate, -DateTime.daysPerWeek), + ) : _previousDates[-index]); - final DateTime prevEndDate = - DateTimeHelper.getDateTimeValue(addDays(prevDate, 6)); - final DateTime endDate = - DateTimeHelper.getDateTimeValue(addDays(startDate, 6)); + final DateTime prevEndDate = DateTimeHelper.getDateTimeValue( + addDays(prevDate, 6), + ); + final DateTime endDate = DateTimeHelper.getDateTimeValue( + addDays(startDate, 6), + ); bool initialMonthHeader = false; if (((index == 0 && _previousDates.isEmpty) || @@ -5690,29 +6190,37 @@ class _SfCalendarState extends State /// date. final List appointmentCollection = AppointmentHelper.getVisibleAppointments( - isSameOrAfterDate(_minDate, startDate) ? startDate : _minDate!, - isSameOrBeforeDate(_maxDate, endDate) ? endDate : _maxDate!, - _appointments, - widget.timeZone, - false, - canCreateNewAppointment: false); + isSameOrAfterDate(_minDate, startDate) ? startDate : _minDate!, + isSameOrBeforeDate(_maxDate, endDate) ? endDate : _maxDate!, + _appointments, + widget.timeZone, + false, + canCreateNewAppointment: false, + ); appointmentCollection.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); /// Get the collection of appointment collection listed by date. final Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, startDate, endDate); + appointmentCollection, + startDate, + endDate, + ); final List dateAppointmentKeys = dateAppointments.keys.toList(); const double padding = 5; /// Check the current week view show display date or current date view. - bool isNeedDisplayDateHighlight = - isDateWithInDateRange(startDate, endDate, scheduleDisplayDate); + bool isNeedDisplayDateHighlight = isDateWithInDateRange( + startDate, + endDate, + scheduleDisplayDate, + ); bool isNeedCurrentDateHighlight = isDateWithInDateRange(startDate, endDate, scheduleCurrentDate) && - !isSameDate(scheduleDisplayDate, scheduleCurrentDate); + !isSameDate(scheduleDisplayDate, scheduleCurrentDate); /// Check the schedule display date have appointments if display date /// in between the week @@ -5742,15 +6250,18 @@ class _SfCalendarState extends State /// calculate the day label(eg., May 25) width based on schedule setting. final double viewPadding = _getAgendaViewDayLabelWidth( - widget.scheduleViewSettings, _useMobilePlatformUI); + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); final double viewTopPadding = _useMobilePlatformUI ? padding : 0; /// calculate the total height using height variable /// web view does not have week label. - double height = _useMobilePlatformUI - ? widget.scheduleViewSettings.weekHeaderSettings.height - : 0; + double height = + _useMobilePlatformUI + ? widget.scheduleViewSettings.weekHeaderSettings.height + : 0; /// It is used to current view top position inside the collection of views. double topHeight = 0; @@ -5758,7 +6269,8 @@ class _SfCalendarState extends State /// Check the week date needs month header at first or before of appointment /// view. - bool isNeedMonthBuilder = _useMobilePlatformUI && + bool isNeedMonthBuilder = + _useMobilePlatformUI && (prevEndDate.month != startDate.month || prevEndDate.year != startDate.year || initialMonthHeader); @@ -5789,15 +6301,20 @@ class _SfCalendarState extends State } /// Web view does not have month label. - height += isNeedMonthBuilder - ? widget.scheduleViewSettings.monthHeaderSettings.height - : 0; + height += + isNeedMonthBuilder + ? widget.scheduleViewSettings.monthHeaderSettings.height + : 0; final double appointmentViewHeight = CalendarViewHelper.getScheduleAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); /// Calculate the divider height and color when it is web view. final double dividerHeight = _useMobilePlatformUI ? 0 : 1; @@ -5822,10 +6339,11 @@ class _SfCalendarState extends State double panelHeight = ((eventsCount - allDayEventCount) * appointmentViewHeight) + - (allDayEventCount * allDayAppointmentHeight); - panelHeight = panelHeight > appointmentViewHeight - ? panelHeight - : appointmentViewHeight; + (allDayEventCount * allDayAppointmentHeight); + panelHeight = + panelHeight > appointmentViewHeight + ? panelHeight + : appointmentViewHeight; appointmentHeight += panelHeight + dividerHeight; numberOfEvents += eventsCount; } @@ -5851,13 +6369,15 @@ class _SfCalendarState extends State /// Get the previous view end position used to find the next view end /// position. if (currentIndex >= 0) { - previousHeight = currentIndex == 0 - ? 0 - : _forwardWidgetHeights[currentIndex - 1]!._height; + previousHeight = + currentIndex == 0 + ? 0 + : _forwardWidgetHeights[currentIndex - 1]!._height; } else { - previousHeight = currentIndex == -1 - ? 0 - : _backwardWidgetHeights[-currentIndex - 2]!._height; + previousHeight = + currentIndex == -1 + ? 0 + : _backwardWidgetHeights[-currentIndex - 2]!._height; } final List widgets = []; @@ -5874,8 +6394,16 @@ class _SfCalendarState extends State height += viewTopPadding; } - widgets.add(_getMonthOrWeekHeader(startDate, endDate, isRTL, false, - viewPadding: viewPadding, isNeedTopPadding: isNeedMonthBuilder)); + widgets.add( + _getMonthOrWeekHeader( + startDate, + endDate, + isRTL, + false, + viewPadding: viewPadding, + isNeedTopPadding: isNeedMonthBuilder, + ), + ); /// Add the height of week label to update the top position of next view. topHeight += widget.scheduleViewSettings.weekHeaderSettings.height; @@ -5892,7 +6420,8 @@ class _SfCalendarState extends State /// Check the week date needs month header at in between the appointment /// views. - bool isNeedInBetweenMonthBuilder = _useMobilePlatformUI && + bool isNeedInBetweenMonthBuilder = + _useMobilePlatformUI && (startDate.month != (isSameOrBeforeDate(_maxDate, endDate) ? endDate : _maxDate!) .month); @@ -5900,14 +6429,16 @@ class _SfCalendarState extends State /// Check the end date month have appointments or not. bool isNextMonthHasNoAppointment = false; if (isNeedInBetweenMonthBuilder) { - final DateTime? lastAppointmentDate = dateAppointmentKeys.isNotEmpty - ? dateAppointmentKeys[dateAppointmentKeys.length - 1] - : null; - final DateTime? nextWeekDate = index == -1 - ? _nextDates[0] - : (index < 0 - ? _previousDates[-index - 2] - : index >= _nextDates.length - 1 + final DateTime? lastAppointmentDate = + dateAppointmentKeys.isNotEmpty + ? dateAppointmentKeys[dateAppointmentKeys.length - 1] + : null; + final DateTime? nextWeekDate = + index == -1 + ? _nextDates[0] + : (index < 0 + ? _previousDates[-index - 2] + : index >= _nextDates.length - 1 ? null : _nextDates[index + 1]); @@ -5919,13 +6450,15 @@ class _SfCalendarState extends State /// 3. If the week have appointments but next month dates does not have /// an appointments but [hideEmptyScheduleWeek] enabled so the next view /// date month as different with current week end date week. - isNextMonthHasNoAppointment = lastAppointmentDate == null || + isNextMonthHasNoAppointment = + lastAppointmentDate == null || (lastAppointmentDate.month != endDate.month && nextWeekDate != null && nextWeekDate.month == endDate.month && nextWeekDate.year == endDate.year); - isNeedInBetweenMonthBuilder = isNextMonthHasNoAppointment || + isNeedInBetweenMonthBuilder = + isNextMonthHasNoAppointment || lastAppointmentDate.month != startDate.month; } @@ -5935,26 +6468,31 @@ class _SfCalendarState extends State if (isNeedInBetweenMonthBuilder && (!isNextMonthHasNoAppointment || isSameOrBeforeDate( - _maxDate, DateTime(endDate.year, endDate.month)))) { + _maxDate, + DateTime(endDate.year, endDate.month), + ))) { /// Add the height of month label to total height of view and /// Add the month header top padding value to height when in between /// week needs month header - height += widget.scheduleViewSettings.monthHeaderSettings.height + + height += + widget.scheduleViewSettings.monthHeaderSettings.height + viewTopPadding; } /// Add appointment height to height when the view have display date view. if (isNeedDisplayDateHighlight) { - height += _useMobilePlatformUI - ? appointmentViewHeaderHeight - : appointmentViewHeaderHeight + dividerHeight; + height += + _useMobilePlatformUI + ? appointmentViewHeaderHeight + : appointmentViewHeaderHeight + dividerHeight; } /// Add appointment height to height when the view have current date view. if (isNeedCurrentDateHighlight) { - height += _useMobilePlatformUI - ? appointmentViewHeaderHeight - : appointmentViewHeaderHeight + dividerHeight; + height += + _useMobilePlatformUI + ? appointmentViewHeaderHeight + : appointmentViewHeaderHeight + dividerHeight; } /// display date highlight added boolean variable used to identify the @@ -5980,39 +6518,49 @@ class _SfCalendarState extends State void addMonthHeaderView() { /// Assign the intersection point based on previous view end position. - scheduleViewDetails._intersectPoint = currentIndex >= 0 - ? previousHeight + interSectPoint + viewTopPadding - : previousHeight + height - interSectPoint - viewTopPadding; + scheduleViewDetails._intersectPoint = + currentIndex >= 0 + ? previousHeight + interSectPoint + viewTopPadding + : previousHeight + height - interSectPoint - viewTopPadding; /// Web view does not have month label; if (_useMobilePlatformUI) { interSectPoint += widget.scheduleViewSettings.monthHeaderSettings.height + - viewTopPadding; - widgets.add(_getMonthOrWeekHeader(currentDate, null, isRTL, true, - isNeedTopPadding: true)); + viewTopPadding; + widgets.add( + _getMonthOrWeekHeader( + currentDate, + null, + isRTL, + true, + isNeedTopPadding: true, + ), + ); } } void addDisplayOrCurrentDateView({bool isDisplayDate = true}) { - final double highlightViewStartPosition = currentIndex >= 0 - ? previousHeight + interSectPoint - : -(previousHeight + height - interSectPoint); - widgets.add(_getDisplayDateView( + final double highlightViewStartPosition = + currentIndex >= 0 + ? previousHeight + interSectPoint + : -(previousHeight + height - interSectPoint); + widgets.add( + _getDisplayDateView( isRTL, isDisplayDate ? scheduleDisplayDate : scheduleCurrentDate, highlightViewStartPosition, viewPadding, appointmentViewHeaderHeight, - padding)); + padding, + ), + ); /// Add divider at end of each of the week days in web view. if (!_useMobilePlatformUI) { - widgets.add(Divider( - height: dividerHeight, - thickness: 1, - color: dividerColor, - )); + widgets.add( + Divider(height: dividerHeight, thickness: 1, color: dividerColor), + ); } /// Add intersect value with appointment height and divider height @@ -6078,7 +6626,8 @@ class _SfCalendarState extends State } final double totalPadding = (eventsCount + 1) * padding; - final double panelHeight = totalPadding + + final double panelHeight = + totalPadding + ((eventsCount - allDayEventCount) * appointmentViewHeight) + (allDayEventCount * allDayAppointmentHeight); double appointmentViewTopPadding = 0; @@ -6088,80 +6637,106 @@ class _SfCalendarState extends State appointmentViewTopPadding = appointmentViewPadding / 2; } - final double viewStartPosition = currentIndex >= 0 - ? previousHeight + interSectPoint - : -(previousHeight + height - interSectPoint); + final double viewStartPosition = + currentIndex >= 0 + ? previousHeight + interSectPoint + : -(previousHeight + height - interSectPoint); interSectPoint += appointmentViewPadding; currentAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); currentAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isAllDay, + app2.isAllDay, + ), + ); currentAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isSpanned, + app2.isSpanned, + ), + ); /// Add appointment view to the current views collection. - widgets.add(MouseRegion( + widgets.add( + MouseRegion( onEnter: (PointerEnterEvent event) { - _pointerEnterEvent(event, false, isRTL, currentDate, - viewStartPosition, appointmentViewTopPadding); + _pointerEnterEvent( + event, + false, + isRTL, + currentDate, + viewStartPosition, + appointmentViewTopPadding, + ); }, onExit: _pointerExitEvent, onHover: (PointerHoverEvent event) { - _pointerHoverEvent(event, false, isRTL, currentDate, - viewStartPosition, appointmentViewTopPadding); + _pointerHoverEvent( + event, + false, + isRTL, + currentDate, + viewStartPosition, + appointmentViewTopPadding, + ); }, child: GestureDetector( child: _ScheduleAppointmentView( - header: CustomPaint( - painter: _AgendaDateTimePainter( - currentDate, - null, - widget.scheduleViewSettings, - widget.todayHighlightColor ?? - _calendarTheme.todayHighlightColor, - widget.todayTextStyle, - _locale, - _calendarTheme, - _themeData, - _agendaDateNotifier, - _minWidth, - isRTL, - _textScaleFactor, - _isMobilePlatform), - size: Size(viewPadding, appointmentViewHeaderHeight)), - content: Container( - padding: EdgeInsets.fromLTRB( - isRTL ? 0 : viewPadding, - appointmentViewTopPadding, - isRTL ? viewPadding : 0, - appointmentViewTopPadding), - child: AgendaViewLayout( - null, - widget.scheduleViewSettings, - currentDate, - currentAppointments, - isRTL, - _locale, - _localizations, - _calendarTheme, - _themeData, - _agendaViewNotifier, - widget.appointmentTimeTextFormat, - viewPadding, - _textScaleFactor, - _isMobilePlatform, - widget.appointmentBuilder, - _minWidth - viewPadding, - panelHeight, - widget.monthViewSettings.agendaStyle.placeholderTextStyle, - widget), - )), + header: CustomPaint( + painter: _AgendaDateTimePainter( + currentDate, + null, + widget.scheduleViewSettings, + widget.todayHighlightColor ?? + _calendarTheme.todayHighlightColor, + widget.todayTextStyle, + _locale, + _calendarTheme, + _themeData, + _agendaDateNotifier, + _minWidth, + isRTL, + _textScaleFactor, + _isMobilePlatform, + ), + size: Size(viewPadding, appointmentViewHeaderHeight), + ), + content: Container( + padding: EdgeInsets.fromLTRB( + isRTL ? 0 : viewPadding, + appointmentViewTopPadding, + isRTL ? viewPadding : 0, + appointmentViewTopPadding, + ), + child: AgendaViewLayout( + null, + widget.scheduleViewSettings, + currentDate, + currentAppointments, + isRTL, + _locale, + _localizations, + _calendarTheme, + _themeData, + _agendaViewNotifier, + widget.appointmentTimeTextFormat, + viewPadding, + _textScaleFactor, + _isMobilePlatform, + widget.appointmentBuilder, + _minWidth - viewPadding, + panelHeight, + widget.monthViewSettings.agendaStyle.placeholderTextStyle, + widget, + ), + ), + ), onTapUp: (TapUpDetails details) { _removeDatePicker(); if (widget.allowViewNavigation && @@ -6174,12 +6749,19 @@ class _SfCalendarState extends State } if (!CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.onTap)) { + widget.onTap, + )) { return; } - _raiseCallbackForScheduleView(currentDate, details.localPosition, - currentAppointments, viewPadding, padding, true); + _raiseCallbackForScheduleView( + currentDate, + details.localPosition, + currentAppointments, + viewPadding, + padding, + true, + ); }, onLongPressStart: (LongPressStartDetails details) { _removeDatePicker(); @@ -6193,24 +6775,31 @@ class _SfCalendarState extends State } if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress)) { + widget.onLongPress, + )) { return; } - _raiseCallbackForScheduleView(currentDate, details.localPosition, - currentAppointments, viewPadding, padding, false); + _raiseCallbackForScheduleView( + currentDate, + details.localPosition, + currentAppointments, + viewPadding, + padding, + false, + ); }, - ))); + ), + ), + ); interSectPoint += panelHeight + dividerHeight; /// Add divider at end of each of the week days in web view. if (!_useMobilePlatformUI) { - widgets.add(Divider( - height: dividerHeight, - thickness: 1, - color: dividerColor, - )); + widgets.add( + Divider(height: dividerHeight, thickness: 1, color: dividerColor), + ); } } @@ -6218,24 +6807,26 @@ class _SfCalendarState extends State /// end date month value. if (!isDisplayDateHighlightAdded && endDate.month != scheduleDisplayDate.month) { - final double highlightViewStartPosition = currentIndex >= 0 - ? previousHeight + topHeight + appointmentHeight - : previousHeight + height - topHeight - appointmentHeight; - widgets.add(_getDisplayDateView( + final double highlightViewStartPosition = + currentIndex >= 0 + ? previousHeight + topHeight + appointmentHeight + : previousHeight + height - topHeight - appointmentHeight; + widgets.add( + _getDisplayDateView( isRTL, scheduleDisplayDate, highlightViewStartPosition, viewPadding, appointmentViewHeaderHeight, - padding)); + padding, + ), + ); /// Add divider at end of each of the week days in web view. if (!_useMobilePlatformUI) { - widgets.add(Divider( - height: dividerHeight, - thickness: 1, - color: dividerColor, - )); + widgets.add( + Divider(height: dividerHeight, thickness: 1, color: dividerColor), + ); } /// Add the top height value with display date view height because the @@ -6249,24 +6840,26 @@ class _SfCalendarState extends State /// end date month value. if (!isCurrentDateHighlightAdded && endDate.month != scheduleCurrentDate.month) { - final double highlightViewStartPosition = currentIndex >= 0 - ? previousHeight + topHeight + appointmentHeight - : previousHeight + height - topHeight - appointmentHeight; - widgets.add(_getDisplayDateView( + final double highlightViewStartPosition = + currentIndex >= 0 + ? previousHeight + topHeight + appointmentHeight + : previousHeight + height - topHeight - appointmentHeight; + widgets.add( + _getDisplayDateView( isRTL, scheduleCurrentDate, highlightViewStartPosition, viewPadding, appointmentViewHeaderHeight, - padding)); + padding, + ), + ); /// Add divider at end of each of the week days in web view. if (!_useMobilePlatformUI) { - widgets.add(Divider( - height: dividerHeight, - thickness: 1, - color: dividerColor, - )); + widgets.add( + Divider(height: dividerHeight, thickness: 1, color: dividerColor), + ); } /// Add the top height value with current date view height because the @@ -6288,40 +6881,51 @@ class _SfCalendarState extends State /// view holds next month label. if scrolling reaches this position /// then we update the header date so add the location to intersecting /// point. - scheduleViewDetails._intersectPoint = currentIndex >= 0 - ? previousHeight + topHeight + appointmentHeight + viewTopPadding - : previousHeight + - height - - topHeight - - appointmentHeight - - viewTopPadding; - topHeight += widget.scheduleViewSettings.monthHeaderSettings.height + + scheduleViewDetails._intersectPoint = + currentIndex >= 0 + ? previousHeight + topHeight + appointmentHeight + viewTopPadding + : previousHeight + + height - + topHeight - + appointmentHeight - + viewTopPadding; + topHeight += + widget.scheduleViewSettings.monthHeaderSettings.height + viewTopPadding; - widgets.add(_getMonthOrWeekHeader(endDate, endDate, isRTL, true, - isNeedTopPadding: true)); + widgets.add( + _getMonthOrWeekHeader( + endDate, + endDate, + isRTL, + true, + isNeedTopPadding: true, + ), + ); } /// Add the display date view at end of week view when /// it does not added to widget. if (!isDisplayDateHighlightAdded) { - final double highlightViewStartPosition = currentIndex >= 0 - ? previousHeight + topHeight + appointmentHeight - : previousHeight + height - topHeight - appointmentHeight; - widgets.add(_getDisplayDateView( + final double highlightViewStartPosition = + currentIndex >= 0 + ? previousHeight + topHeight + appointmentHeight + : previousHeight + height - topHeight - appointmentHeight; + widgets.add( + _getDisplayDateView( isRTL, scheduleDisplayDate, highlightViewStartPosition, viewPadding, appointmentViewHeaderHeight, - padding)); + padding, + ), + ); /// Add divider at end of each of the week days in web view. if (!_useMobilePlatformUI) { - widgets.add(Divider( - height: dividerHeight, - thickness: 1, - color: dividerColor, - )); + widgets.add( + Divider(height: dividerHeight, thickness: 1, color: dividerColor), + ); } isDisplayDateHighlightAdded = true; } @@ -6329,24 +6933,26 @@ class _SfCalendarState extends State /// Add the current date view at end of week view /// when it does not added to widget. if (!isCurrentDateHighlightAdded) { - final double highlightViewStartPosition = currentIndex >= 0 - ? previousHeight + topHeight + appointmentHeight - : previousHeight + height - topHeight - appointmentHeight; - widgets.add(_getDisplayDateView( + final double highlightViewStartPosition = + currentIndex >= 0 + ? previousHeight + topHeight + appointmentHeight + : previousHeight + height - topHeight - appointmentHeight; + widgets.add( + _getDisplayDateView( isRTL, scheduleCurrentDate, highlightViewStartPosition, viewPadding, appointmentViewHeaderHeight, - padding)); + padding, + ), + ); /// Add divider at end of each of the week days in web view. if (!_useMobilePlatformUI) { - widgets.add(Divider( - height: dividerHeight, - thickness: 1, - color: dividerColor, - )); + widgets.add( + Divider(height: dividerHeight, thickness: 1, color: dividerColor), + ); } isCurrentDateHighlightAdded = true; } @@ -6364,209 +6970,261 @@ class _SfCalendarState extends State } Widget _getMonthOrWeekHeader( - DateTime startDate, DateTime? endDate, bool isRTL, bool isMonthLabel, - {double viewPadding = 0, bool isNeedTopPadding = false}) { + DateTime startDate, + DateTime? endDate, + bool isRTL, + bool isMonthLabel, { + double viewPadding = 0, + bool isNeedTopPadding = false, + }) { const double padding = 5; Widget? headerWidget; if (isMonthLabel && widget.scheduleViewMonthHeaderBuilder != null) { final ScheduleViewMonthHeaderDetails details = ScheduleViewMonthHeaderDetails( - DateTime(startDate.year, startDate.month), - Rect.fromLTWH(0, 0, _minWidth, - widget.scheduleViewSettings.monthHeaderSettings.height)); + DateTime(startDate.year, startDate.month), + Rect.fromLTWH( + 0, + 0, + _minWidth, + widget.scheduleViewSettings.monthHeaderSettings.height, + ), + ); headerWidget = widget.scheduleViewMonthHeaderBuilder!(context, details); } return GestureDetector( - child: Container( - padding: isMonthLabel + child: Container( + padding: + isMonthLabel ? EdgeInsets.fromLTRB(0, isNeedTopPadding ? padding : 0, 0, 0) - : EdgeInsets.fromLTRB(isRTL ? 0 : viewPadding, - isNeedTopPadding ? padding : 0, isRTL ? viewPadding : 0, 0), - child: RepaintBoundary( - child: headerWidget != null - ? SizedBox( - width: _minWidth, - height: widget - .scheduleViewSettings.monthHeaderSettings.height, - child: headerWidget, - ) - : CustomPaint( - painter: _ScheduleLabelPainter( - startDate, - endDate, - widget.scheduleViewSettings, - isMonthLabel, - isRTL, - _locale, - _useMobilePlatformUI, - _agendaViewNotifier, - _calendarTheme, - _themeData, - _localizations, - _textScaleFactor), - size: isMonthLabel + : EdgeInsets.fromLTRB( + isRTL ? 0 : viewPadding, + isNeedTopPadding ? padding : 0, + isRTL ? viewPadding : 0, + 0, + ), + child: RepaintBoundary( + child: + headerWidget != null + ? SizedBox( + width: _minWidth, + height: + widget.scheduleViewSettings.monthHeaderSettings.height, + child: headerWidget, + ) + : CustomPaint( + painter: _ScheduleLabelPainter( + startDate, + endDate, + widget.scheduleViewSettings, + isMonthLabel, + isRTL, + _locale, + _useMobilePlatformUI, + _agendaViewNotifier, + _calendarTheme, + _themeData, + _localizations, + _textScaleFactor, + ), + size: + isMonthLabel ? Size( - _minWidth, - widget.scheduleViewSettings.monthHeaderSettings - .height) + _minWidth, + widget + .scheduleViewSettings + .monthHeaderSettings + .height, + ) : Size( - _minWidth - viewPadding - (2 * padding), - widget.scheduleViewSettings.weekHeaderSettings - .height), - ))), + _minWidth - viewPadding - (2 * padding), + widget + .scheduleViewSettings + .weekHeaderSettings + .height, + ), + ), + ), + ), + onTapUp: (TapUpDetails details) { + _removeDatePicker(); + if (!CalendarViewHelper.shouldRaiseCalendarTapCallback(widget.onTap)) { + return; + } + + CalendarViewHelper.raiseCalendarTapCallback( + widget, + DateTime(startDate.year, startDate.month, startDate.day), + null, + isMonthLabel ? CalendarElement.header : CalendarElement.viewHeader, + null, + ); + }, + onLongPressStart: (LongPressStartDetails details) { + _removeDatePicker(); + if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( + widget.onLongPress, + )) { + return; + } + + CalendarViewHelper.raiseCalendarLongPressCallback( + widget, + DateTime(startDate.year, startDate.month, startDate.day), + null, + isMonthLabel ? CalendarElement.header : CalendarElement.viewHeader, + null, + ); + }, + ); + } + + Widget _getDisplayDateView( + bool isRTL, + DateTime currentDisplayDate, + double highlightViewStartPosition, + double viewHeaderWidth, + double displayDateHighlightHeight, + double padding, + ) { + return MouseRegion( + onEnter: (PointerEnterEvent event) { + _pointerEnterEvent( + event, + true, + isRTL, + currentDisplayDate, + highlightViewStartPosition, + ); + }, + onExit: _pointerExitEvent, + onHover: (PointerHoverEvent event) { + _pointerHoverEvent( + event, + true, + isRTL, + currentDisplayDate, + highlightViewStartPosition, + ); + }, + child: GestureDetector( + child: _ScheduleAppointmentView( + header: CustomPaint( + painter: _AgendaDateTimePainter( + currentDisplayDate, + null, + widget.scheduleViewSettings, + widget.todayHighlightColor ?? _calendarTheme.todayHighlightColor, + widget.todayTextStyle, + _locale, + _calendarTheme, + _themeData, + _agendaDateNotifier, + _minWidth, + isRTL, + _textScaleFactor, + _isMobilePlatform, + ), + size: Size(viewHeaderWidth, displayDateHighlightHeight), + ), + content: Container( + padding: EdgeInsets.fromLTRB( + isRTL ? 0 : viewHeaderWidth, + 0, + isRTL ? viewHeaderWidth : 0, + 0, + ), + child: CustomPaint( + painter: _ScheduleLabelPainter( + currentDisplayDate, + null, + widget.scheduleViewSettings, + false, + isRTL, + _locale, + _useMobilePlatformUI, + _agendaViewNotifier, + _calendarTheme, + _themeData, + _localizations, + _textScaleFactor, + isDisplayDate: true, + ), + size: Size( + _minWidth - viewHeaderWidth, + displayDateHighlightHeight, + ), + ), + ), + ), onTapUp: (TapUpDetails details) { _removeDatePicker(); + if (widget.allowViewNavigation && + ((!_isRTL && details.localPosition.dx < viewHeaderWidth) || + (_isRTL && + details.localPosition.dx > + _minWidth - viewHeaderWidth))) { + _controller.view = CalendarView.day; + _controller.displayDate = currentDisplayDate; + } + if (!CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.onTap)) { + widget.onTap, + )) { return; } - CalendarViewHelper.raiseCalendarTapCallback( - widget, - DateTime(startDate.year, startDate.month, startDate.day), - null, - isMonthLabel - ? CalendarElement.header - : CalendarElement.viewHeader, - null); + _raiseCallbackForScheduleView( + currentDisplayDate, + details.localPosition, + [], + viewHeaderWidth, + padding, + true, + isDisplayDate: true, + ); }, onLongPressStart: (LongPressStartDetails details) { _removeDatePicker(); + if (widget.allowViewNavigation && + ((!_isRTL && details.localPosition.dx < viewHeaderWidth) || + (_isRTL && + details.localPosition.dx > + _minWidth - viewHeaderWidth))) { + _controller.view = CalendarView.day; + _controller.displayDate = currentDisplayDate; + } + if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress)) { + widget.onLongPress, + )) { return; } - CalendarViewHelper.raiseCalendarLongPressCallback( - widget, - DateTime(startDate.year, startDate.month, startDate.day), - null, - isMonthLabel - ? CalendarElement.header - : CalendarElement.viewHeader, - null); - }); - } - - Widget _getDisplayDateView( - bool isRTL, - DateTime currentDisplayDate, - double highlightViewStartPosition, - double viewHeaderWidth, - double displayDateHighlightHeight, - double padding) { - return MouseRegion( - onEnter: (PointerEnterEvent event) { - _pointerEnterEvent(event, true, isRTL, currentDisplayDate, - highlightViewStartPosition); - }, - onExit: _pointerExitEvent, - onHover: (PointerHoverEvent event) { - _pointerHoverEvent(event, true, isRTL, currentDisplayDate, - highlightViewStartPosition); + _raiseCallbackForScheduleView( + currentDisplayDate, + details.localPosition, + [], + viewHeaderWidth, + padding, + false, + isDisplayDate: true, + ); }, - child: GestureDetector( - child: _ScheduleAppointmentView( - header: CustomPaint( - painter: _AgendaDateTimePainter( - currentDisplayDate, - null, - widget.scheduleViewSettings, - widget.todayHighlightColor ?? - _calendarTheme.todayHighlightColor, - widget.todayTextStyle, - _locale, - _calendarTheme, - _themeData, - _agendaDateNotifier, - _minWidth, - isRTL, - _textScaleFactor, - _isMobilePlatform), - size: Size(viewHeaderWidth, displayDateHighlightHeight)), - content: Container( - padding: EdgeInsets.fromLTRB(isRTL ? 0 : viewHeaderWidth, 0, - isRTL ? viewHeaderWidth : 0, 0), - child: CustomPaint( - painter: _ScheduleLabelPainter( - currentDisplayDate, - null, - widget.scheduleViewSettings, - false, - isRTL, - _locale, - _useMobilePlatformUI, - _agendaViewNotifier, - _calendarTheme, - _themeData, - _localizations, - _textScaleFactor, - isDisplayDate: true), - size: Size(_minWidth - viewHeaderWidth, - displayDateHighlightHeight)), - )), - onTapUp: (TapUpDetails details) { - _removeDatePicker(); - if (widget.allowViewNavigation && - ((!_isRTL && details.localPosition.dx < viewHeaderWidth) || - (_isRTL && - details.localPosition.dx > - _minWidth - viewHeaderWidth))) { - _controller.view = CalendarView.day; - _controller.displayDate = currentDisplayDate; - } - - if (!CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.onTap)) { - return; - } - - _raiseCallbackForScheduleView( - currentDisplayDate, - details.localPosition, - [], - viewHeaderWidth, - padding, - true, - isDisplayDate: true); - }, - onLongPressStart: (LongPressStartDetails details) { - _removeDatePicker(); - if (widget.allowViewNavigation && - ((!_isRTL && details.localPosition.dx < viewHeaderWidth) || - (_isRTL && - details.localPosition.dx > - _minWidth - viewHeaderWidth))) { - _controller.view = CalendarView.day; - _controller.displayDate = currentDisplayDate; - } - - if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress)) { - return; - } - - _raiseCallbackForScheduleView( - currentDisplayDate, - details.localPosition, - [], - viewHeaderWidth, - padding, - false, - isDisplayDate: true); - }, - )); + ), + ); } void _raiseCallbackForScheduleView( - DateTime currentDate, - Offset offset, - List appointments, - double viewHeaderWidth, - double padding, - bool isTapCallback, - {bool isDisplayDate = false}) { + DateTime currentDate, + Offset offset, + List appointments, + double viewHeaderWidth, + double padding, + bool isTapCallback, { + bool isDisplayDate = false, + }) { /// Check the touch position on day label if ((!_isRTL && viewHeaderWidth >= offset.dx) || (_isRTL && _minWidth - viewHeaderWidth < offset.dx)) { @@ -6579,50 +7237,62 @@ class _SfCalendarState extends State if (isTapCallback) { CalendarViewHelper.raiseCalendarTapCallback( - widget, - DateTime(currentDate.year, currentDate.month, currentDate.day), - widget.dataSource != null && - !AppointmentHelper.isCalendarAppointment(widget.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - currentAppointments, widget.dataSource) - : currentAppointments, - CalendarElement.viewHeader, - null); + widget, + DateTime(currentDate.year, currentDate.month, currentDate.day), + widget.dataSource != null && + !AppointmentHelper.isCalendarAppointment(widget.dataSource!) + ? CalendarViewHelper.getCustomAppointments( + currentAppointments, + widget.dataSource, + ) + : currentAppointments, + CalendarElement.viewHeader, + null, + ); } else { CalendarViewHelper.raiseCalendarLongPressCallback( - widget, - DateTime(currentDate.year, currentDate.month, currentDate.day), - widget.dataSource != null && - !AppointmentHelper.isCalendarAppointment(widget.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - currentAppointments, widget.dataSource) - : currentAppointments, - CalendarElement.viewHeader, - null); + widget, + DateTime(currentDate.year, currentDate.month, currentDate.day), + widget.dataSource != null && + !AppointmentHelper.isCalendarAppointment(widget.dataSource!) + ? CalendarViewHelper.getCustomAppointments( + currentAppointments, + widget.dataSource, + ) + : currentAppointments, + CalendarElement.viewHeader, + null, + ); } } else { /// Calculate the touch position appointment from its collection. double currentYPosition = padding; final double itemHeight = CalendarViewHelper.getScheduleAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); final double allDayItemHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); if (isDisplayDate) { if (isTapCallback) { CalendarViewHelper.raiseCalendarTapCallback( - widget, - DateTime(currentDate.year, currentDate.month, currentDate.day), - null, - CalendarElement.calendarCell, - null); + widget, + DateTime(currentDate.year, currentDate.month, currentDate.day), + null, + CalendarElement.calendarCell, + null, + ); } else { CalendarViewHelper.raiseCalendarLongPressCallback( - widget, - DateTime(currentDate.year, currentDate.month, currentDate.day), - null, - CalendarElement.calendarCell, - null); + widget, + DateTime(currentDate.year, currentDate.month, currentDate.day), + null, + CalendarElement.calendarCell, + null, + ); } return; @@ -6632,37 +7302,45 @@ class _SfCalendarState extends State final CalendarAppointment appointment = appointments[k]; final double currentAppointmentHeight = (_useMobilePlatformUI && _isAllDayAppointmentView(appointment) - ? allDayItemHeight - : itemHeight) + - padding; + ? allDayItemHeight + : itemHeight) + + padding; if (currentYPosition <= offset.dy && currentYPosition + currentAppointmentHeight > offset.dy) { final List selectedAppointment = [appointment]; if (isTapCallback) { CalendarViewHelper.raiseCalendarTapCallback( - widget, - DateTime(currentDate.year, currentDate.month, currentDate.day), - widget.dataSource != null && - !AppointmentHelper.isCalendarAppointment( - widget.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - selectedAppointment, widget.dataSource) - : selectedAppointment, - CalendarElement.appointment, - null); + widget, + DateTime(currentDate.year, currentDate.month, currentDate.day), + widget.dataSource != null && + !AppointmentHelper.isCalendarAppointment( + widget.dataSource!, + ) + ? CalendarViewHelper.getCustomAppointments( + selectedAppointment, + widget.dataSource, + ) + : selectedAppointment, + CalendarElement.appointment, + null, + ); } else { CalendarViewHelper.raiseCalendarLongPressCallback( - widget, - DateTime(currentDate.year, currentDate.month, currentDate.day), - widget.dataSource != null && - !AppointmentHelper.isCalendarAppointment( - widget.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - selectedAppointment, widget.dataSource) - : selectedAppointment, - CalendarElement.appointment, - null); + widget, + DateTime(currentDate.year, currentDate.month, currentDate.day), + widget.dataSource != null && + !AppointmentHelper.isCalendarAppointment( + widget.dataSource!, + ) + ? CalendarViewHelper.getCustomAppointments( + selectedAppointment, + widget.dataSource, + ) + : selectedAppointment, + CalendarElement.appointment, + null, + ); } break; } @@ -6675,7 +7353,7 @@ class _SfCalendarState extends State Widget addAgenda(double height, bool isRTL) { final bool hideEmptyAgendaDays = widget.scheduleViewSettings.hideEmptyScheduleWeek || - !_useMobilePlatformUI; + !_useMobilePlatformUI; /// return empty view when [hideEmptyAgendaDays] enabled and /// the appointments as empty. @@ -6684,7 +7362,8 @@ class _SfCalendarState extends State } final DateTime scheduleDisplayDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, _scheduleDisplayDate)); + getValidDate(widget.minDate, widget.maxDate, _scheduleDisplayDate), + ); final DateTime scheduleCurrentDate = DateTime.now(); final DateTime currentMaxDate = scheduleDisplayDate.isAfter(scheduleCurrentDate) @@ -6700,12 +7379,13 @@ class _SfCalendarState extends State /// in [ScheduleViewSettings] disabled else it return min /// start date of the appointment collection. _minDate = _getMinAppointmentDate( - _appointments, - widget.timeZone, - widget.minDate, - currentMinDate, - widget.scheduleViewSettings, - _useMobilePlatformUI); + _appointments, + widget.timeZone, + widget.minDate, + currentMinDate, + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); /// Assign minimum date value to current minimum date when the minimum /// date is before of current minimum date @@ -6713,19 +7393,21 @@ class _SfCalendarState extends State _minDate = _minDate!.isBefore(widget.minDate) ? widget.minDate : _minDate; final DateTime viewMinDate = DateTimeHelper.getDateTimeValue( - addDays(_minDate, -(_minDate!.weekday % DateTime.daysPerWeek))); + addDays(_minDate, -(_minDate!.weekday % DateTime.daysPerWeek)), + ); /// Get the maximum date of schedule view when it value as null /// It return max date user assigned when the [hideEmptyAgendaDays] /// in [ScheduleViewSettings] disabled else it return max /// end date of the appointment collection. _maxDate = _getMaxAppointmentDate( - _appointments, - widget.timeZone, - widget.maxDate, - currentMaxDate, - widget.scheduleViewSettings, - _useMobilePlatformUI); + _appointments, + widget.timeZone, + widget.maxDate, + currentMaxDate, + widget.scheduleViewSettings, + _useMobilePlatformUI, + ); /// Assign maximum date value to current maximum date when the maximum /// date is before of current maximum date @@ -6734,14 +7416,19 @@ class _SfCalendarState extends State final double appointmentViewHeight = CalendarViewHelper.getScheduleAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); /// Get the view first date based on specified /// display date and first day of week. - int value = -(scheduleDisplayDate.weekday % DateTime.daysPerWeek) + + int value = + -(scheduleDisplayDate.weekday % DateTime.daysPerWeek) + widget.firstDayOfWeek - DateTime.daysPerWeek; if (value.abs() >= DateTime.daysPerWeek) { @@ -6751,10 +7438,12 @@ class _SfCalendarState extends State if (_previousDates.isEmpty) { /// Calculate the start date from display date if next view dates /// collection as empty. - DateTime date = _nextDates.isNotEmpty - ? _nextDates[0] - : DateTimeHelper.getDateTimeValue( - addDays(scheduleDisplayDate, value)); + DateTime date = + _nextDates.isNotEmpty + ? _nextDates[0] + : DateTimeHelper.getDateTimeValue( + addDays(scheduleDisplayDate, value), + ); int count = 0; /// Using while for calculate dates because if [hideEmptyAgendaDays] as @@ -6762,7 +7451,8 @@ class _SfCalendarState extends State while (count < 50) { for (int i = 1; i <= 100; i++) { final DateTime updatedDate = DateTimeHelper.getDateTimeValue( - addDays(date, -i * DateTime.daysPerWeek)); + addDays(date, -i * DateTime.daysPerWeek), + ); /// Skip week dates before min date if (!isSameOrAfterDate(viewMinDate, updatedDate)) { @@ -6770,18 +7460,29 @@ class _SfCalendarState extends State break; } - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(updatedDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(updatedDate, 6), + ); /// Skip the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled. if (hideEmptyAgendaDays && !_isAppointmentBetweenDates( - _appointments, updatedDate, weekEndDate, widget.timeZone) && + _appointments, + updatedDate, + weekEndDate, + widget.timeZone, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleDisplayDate) && + updatedDate, + weekEndDate, + scheduleDisplayDate, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleCurrentDate)) { + updatedDate, + weekEndDate, + scheduleCurrentDate, + )) { continue; } @@ -6816,8 +7517,9 @@ class _SfCalendarState extends State if (_nextDates.isEmpty) { /// Calculate the start date from display date - DateTime date = - DateTimeHelper.getDateTimeValue(addDays(scheduleDisplayDate, value)); + DateTime date = DateTimeHelper.getDateTimeValue( + addDays(scheduleDisplayDate, value), + ); int count = 0; /// Using while for calculate dates because if [hideEmptyAgendaDays] as @@ -6825,7 +7527,8 @@ class _SfCalendarState extends State while (count < 50) { for (int i = 0; i < 100; i++) { final DateTime updatedDate = DateTimeHelper.getDateTimeValue( - addDays(date, i * DateTime.daysPerWeek)); + addDays(date, i * DateTime.daysPerWeek), + ); /// Skip week date after max date if (!isSameOrBeforeDate(_maxDate, updatedDate)) { @@ -6833,18 +7536,29 @@ class _SfCalendarState extends State break; } - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(updatedDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(updatedDate, 6), + ); /// Skip the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled. if (hideEmptyAgendaDays && !_isAppointmentBetweenDates( - _appointments, updatedDate, weekEndDate, widget.timeZone) && + _appointments, + updatedDate, + weekEndDate, + widget.timeZone, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleDisplayDate) && + updatedDate, + weekEndDate, + scheduleDisplayDate, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleCurrentDate)) { + updatedDate, + weekEndDate, + scheduleCurrentDate, + )) { continue; } @@ -6882,33 +7596,37 @@ class _SfCalendarState extends State /// appointment fills the view port. DateTime viewStartDate = _nextDates[0]; DateTime viewEndDate = DateTimeHelper.getDateTimeValue( - addDays(_nextDates[_nextDates.length - 1], 6)); + addDays(_nextDates[_nextDates.length - 1], 6), + ); List appointmentCollection = AppointmentHelper.getVisibleAppointments( - viewStartDate, - isSameOrBeforeDate(_maxDate, viewEndDate) - ? viewEndDate - : _maxDate!, - _appointments, - widget.timeZone, - false); + viewStartDate, + isSameOrBeforeDate(_maxDate, viewEndDate) ? viewEndDate : _maxDate!, + _appointments, + widget.timeZone, + false, + ); const double padding = 5; Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, viewStartDate, viewEndDate); + appointmentCollection, + viewStartDate, + viewEndDate, + ); List dateAppointmentKeys = dateAppointments.keys.toList(); double labelHeight = 0; if (_useMobilePlatformUI) { - DateTime previousDate = - DateTimeHelper.getDateTimeValue(addDays(viewStartDate, -1)); + DateTime previousDate = DateTimeHelper.getDateTimeValue( + addDays(viewStartDate, -1), + ); for (int i = 0; i < _nextDates.length; i++) { final DateTime nextDate = _nextDates[i]; if (previousDate.month != nextDate.month) { labelHeight += widget.scheduleViewSettings.monthHeaderSettings.height + - padding; + padding; } previousDate = nextDate; @@ -6943,26 +7661,26 @@ class _SfCalendarState extends State isNewDatesAdded = true; viewStartDate = currentDate; - viewEndDate = - DateTimeHelper.getDateTimeValue(addDays(currentDate, 6)); + viewEndDate = DateTimeHelper.getDateTimeValue( + addDays(currentDate, 6), + ); /// Calculate the newly added date appointment height and add /// the height to existing appointments height. appointmentCollection = AppointmentHelper.getVisibleAppointments( - viewStartDate, - isSameOrBeforeDate(_maxDate, viewEndDate) - ? viewEndDate - : _maxDate!, - _appointments, - widget.timeZone, - false); + viewStartDate, + isSameOrBeforeDate(_maxDate, viewEndDate) ? viewEndDate : _maxDate!, + _appointments, + widget.timeZone, + false, + ); if (_useMobilePlatformUI) { final DateTime nextDate = _nextDates[1]; if (nextDate.month != viewStartDate.month) { labelHeight += widget.scheduleViewSettings.monthHeaderSettings.height + - padding; + padding; } labelHeight += @@ -6970,7 +7688,10 @@ class _SfCalendarState extends State } dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, viewStartDate, viewEndDate); + appointmentCollection, + viewStartDate, + viewEndDate, + ); dateAppointmentKeys = dateAppointments.keys.toList(); for (int i = 0; i < dateAppointmentKeys.length; i++) { final List currentDateAppointment = @@ -6983,7 +7704,8 @@ class _SfCalendarState extends State } } - totalHeight = ((numberOfEvents + 1) * padding) + + totalHeight = + ((numberOfEvents + 1) * padding) + ((numberOfEvents - allDayCount) * appointmentViewHeight) + (allDayCount * allDayAppointmentHeight) + labelHeight; @@ -6993,7 +7715,8 @@ class _SfCalendarState extends State /// dates at initial position. if (_nextDates.isNotEmpty && isNewDatesAdded) { _headerUpdateNotifier.value = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, _nextDates[0])); + getValidDate(widget.minDate, widget.maxDate, _nextDates[0]), + ); } } @@ -7006,61 +7729,69 @@ class _SfCalendarState extends State _agendaScrollController!.initialScrollOffset == 0 && !_agendaScrollController!.hasClients) { final DateTime viewStartDate = _nextDates[0]; - final DateTime viewEndDate = - DateTimeHelper.getDateTimeValue(addDays(viewStartDate, 6)); + final DateTime viewEndDate = DateTimeHelper.getDateTimeValue( + addDays(viewStartDate, 6), + ); if (viewStartDate.isBefore(scheduleDisplayDate) && !isSameDate(viewStartDate, scheduleDisplayDate) && isSameOrBeforeDate(viewEndDate, scheduleDisplayDate)) { - final DateTime viewEndDate = - DateTimeHelper.getDateTimeValue(addDays(scheduleDisplayDate, -1)); + final DateTime viewEndDate = DateTimeHelper.getDateTimeValue( + addDays(scheduleDisplayDate, -1), + ); final double initialScrollPosition = _getInitialScrollPosition( - viewStartDate, - viewEndDate, - scheduleCurrentDate, - appointmentViewHeight, - allDayAppointmentHeight); + viewStartDate, + viewEndDate, + scheduleCurrentDate, + appointmentViewHeight, + allDayAppointmentHeight, + ); if (initialScrollPosition != 0) { _agendaScrollController?.removeListener(_handleScheduleViewScrolled); - _agendaScrollController = - ScrollController(initialScrollOffset: initialScrollPosition) - ..addListener(_handleScheduleViewScrolled); + _agendaScrollController = ScrollController( + initialScrollOffset: initialScrollPosition, + )..addListener(_handleScheduleViewScrolled); } } else if (viewStartDate.isBefore(scheduleDisplayDate)) { DateTime visibleStartDate = viewStartDate; double initialScrollPosition = 0; while (visibleStartDate.isBefore(scheduleDisplayDate) && !isSameDate(visibleStartDate, scheduleDisplayDate)) { - final DateTime viewEndDate = - DateTimeHelper.getDateTimeValue(addDays(visibleStartDate, 6)); + final DateTime viewEndDate = DateTimeHelper.getDateTimeValue( + addDays(visibleStartDate, 6), + ); final DateTime appStartDate = isSameOrAfterDate(_minDate, visibleStartDate) ? visibleStartDate : _minDate!; - DateTime appEndDate = isSameOrBeforeDate(_maxDate, viewEndDate) - ? viewEndDate - : _maxDate!; + DateTime appEndDate = + isSameOrBeforeDate(_maxDate, viewEndDate) + ? viewEndDate + : _maxDate!; if (appEndDate.isAfter(scheduleDisplayDate) || isSameDate(appEndDate, scheduleDisplayDate)) { appEndDate = DateTimeHelper.getDateTimeValue( - addDays(scheduleDisplayDate, -1)); + addDays(scheduleDisplayDate, -1), + ); } initialScrollPosition += _getInitialScrollPosition( - appStartDate, - appEndDate, - scheduleCurrentDate, - appointmentViewHeight, - allDayAppointmentHeight); + appStartDate, + appEndDate, + scheduleCurrentDate, + appointmentViewHeight, + allDayAppointmentHeight, + ); visibleStartDate = DateTimeHelper.getDateTimeValue( - addDays(visibleStartDate, DateTime.daysPerWeek)); + addDays(visibleStartDate, DateTime.daysPerWeek), + ); } if (initialScrollPosition != 0) { _agendaScrollController?.removeListener(_handleScheduleViewScrolled); - _agendaScrollController = - ScrollController(initialScrollOffset: initialScrollPosition) - ..addListener(_handleScheduleViewScrolled); + _agendaScrollController = ScrollController( + initialScrollOffset: initialScrollPosition, + )..addListener(_handleScheduleViewScrolled); } } } @@ -7068,114 +7799,131 @@ class _SfCalendarState extends State return KeyboardListener( focusNode: _focusNode, onKeyEvent: _onKeyDown, - child: Stack(children: [ - Positioned( - top: 0, - right: 0, - left: 0, - height: widget.headerHeight, - child: GestureDetector( - child: Container( - color: widget.headerStyle.backgroundColor ?? + child: Stack( + children: [ + Positioned( + top: 0, + right: 0, + left: 0, + height: widget.headerHeight, + child: GestureDetector( + child: Container( + color: + widget.headerStyle.backgroundColor ?? _calendarTheme.headerBackgroundColor, child: _CalendarHeaderView( - _currentViewVisibleDates, - widget.headerStyle, - null, - _view, - widget.monthViewSettings.numberOfWeeksInView, - _calendarTheme, - isRTL, - _locale, - widget.showNavigationArrow, - _controller, - widget.maxDate, - widget.minDate, - _minWidth, - widget.headerHeight, - widget.timeSlotViewSettings.nonWorkingDays, - widget.monthViewSettings.navigationDirection, - widget.showDatePickerButton, - widget.showTodayButton, - _showHeader, - widget.allowedViews, - widget.allowViewNavigation, - _localizations, - _removeDatePicker, - _headerUpdateNotifier, - _viewChangeNotifier, - _handleOnTapForHeader, - _handleOnLongPressForHeader, - widget.todayHighlightColor, - _textScaleFactor, - _isMobilePlatform, - widget.headerDateFormat, - true, - widget.todayTextStyle, - widget.showWeekNumber, - widget.weekNumberStyle, - _timelineMonthWeekNumberNotifier, - widget.cellBorderColor, - widget.timeSlotViewSettings.numberOfDaysInView)), + _currentViewVisibleDates, + widget.headerStyle, + null, + _view, + widget.monthViewSettings.numberOfWeeksInView, + _calendarTheme, + isRTL, + _locale, + widget.showNavigationArrow, + _controller, + widget.maxDate, + widget.minDate, + _minWidth, + widget.headerHeight, + widget.timeSlotViewSettings.nonWorkingDays, + widget.monthViewSettings.navigationDirection, + widget.showDatePickerButton, + widget.showTodayButton, + _showHeader, + widget.allowedViews, + widget.allowViewNavigation, + _localizations, + _removeDatePicker, + _headerUpdateNotifier, + _viewChangeNotifier, + _handleOnTapForHeader, + _handleOnLongPressForHeader, + widget.todayHighlightColor, + _textScaleFactor, + _isMobilePlatform, + widget.headerDateFormat, + true, + widget.todayTextStyle, + widget.showWeekNumber, + widget.weekNumberStyle, + _timelineMonthWeekNumberNotifier, + widget.cellBorderColor, + widget.timeSlotViewSettings.numberOfDaysInView, + ), + ), + ), ), - ), - Positioned( + Positioned( top: widget.headerHeight, left: 0, right: 0, height: height, child: _OpacityWidget( - opacity: _opacity, - child: CustomScrollView( - key: _scrollKey, - physics: const AlwaysScrollableScrollPhysics(), - controller: _agendaScrollController, - center: _scheduleViewKey, - slivers: [ - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - if (_previousDates.length <= index) { - return null; - } + opacity: _opacity, + child: CustomScrollView( + key: _scrollKey, + physics: const AlwaysScrollableScrollPhysics(), + controller: _agendaScrollController, + center: _scheduleViewKey, + slivers: [ + SliverList( + delegate: SliverChildBuilderDelegate(( + BuildContext context, + int index, + ) { + if (_previousDates.length <= index) { + return null; + } - /// Send negative index value to differentiate the - /// backward view from forward view. - return _getItem(context, -(index + 1), isRTL); - }), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - if (_nextDates.length <= index) { - return null; - } + /// Send negative index value to differentiate the + /// backward view from forward view. + return _getItem(context, -(index + 1), isRTL); + }), + ), + SliverList( + delegate: SliverChildBuilderDelegate(( + BuildContext context, + int index, + ) { + if (_nextDates.length <= index) { + return null; + } - return _getItem(context, index, isRTL); - }), - key: _scheduleViewKey, - ), - ], - ))), - _addDatePicker(widget.headerHeight, isRTL), - _getCalendarViewPopup(), - ]), + return _getItem(context, index, isRTL); + }), + key: _scheduleViewKey, + ), + ], + ), + ), + ), + _addDatePicker(widget.headerHeight, isRTL), + _getCalendarViewPopup(), + ], + ), ); } double _getInitialScrollPosition( - DateTime viewStartDate, - DateTime viewEndDate, - DateTime scheduleCurrentDate, - double appointmentViewHeight, - double allDayAppointmentHeight) { + DateTime viewStartDate, + DateTime viewEndDate, + DateTime scheduleCurrentDate, + double appointmentViewHeight, + double allDayAppointmentHeight, + ) { double initialScrolledPosition = 0; /// Calculate the appointment between the week start date and /// previous date of display date to calculate the scrolling position. final List appointmentCollection = AppointmentHelper.getVisibleAppointments( - viewStartDate, viewEndDate, _appointments, widget.timeZone, false); + viewStartDate, + viewEndDate, + _appointments, + widget.timeZone, + false, + ); const double padding = 5; @@ -7193,7 +7941,10 @@ class _SfCalendarState extends State if (appointmentCollection.isNotEmpty) { final Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, viewStartDate, viewEndDate); + appointmentCollection, + viewStartDate, + viewEndDate, + ); final List dateAppointmentKeys = dateAppointments.keys.toList(); double totalAppointmentHeight = 0; for (int i = 0; i < dateAppointmentKeys.length; i++) { @@ -7210,10 +7961,11 @@ class _SfCalendarState extends State double panelHeight = ((eventsCount - allDayEventCount) * appointmentViewHeight) + - (allDayEventCount * allDayAppointmentHeight); - panelHeight = panelHeight > appointmentViewHeight - ? panelHeight - : appointmentViewHeight; + (allDayEventCount * allDayAppointmentHeight); + panelHeight = + panelHeight > appointmentViewHeight + ? panelHeight + : appointmentViewHeight; /// event count + 1 denotes the appointment padding and end padding. totalAppointmentHeight += panelHeight + ((eventsCount + 1) * padding); @@ -7226,9 +7978,9 @@ class _SfCalendarState extends State } } - initialScrolledPosition = todayNewEventHeight + + initialScrolledPosition = + todayNewEventHeight + totalAppointmentHeight + - /// Add the divider height when it render on web. (!_useMobilePlatformUI ? dateAppointmentKeys.length : 0) + (!_useMobilePlatformUI @@ -7244,7 +7996,8 @@ class _SfCalendarState extends State } else if ((viewStartDate.month != _scheduleDisplayDate.month && _useMobilePlatformUI) || todayNewEventHeight != 0) { - initialScrolledPosition = (!_useMobilePlatformUI + initialScrolledPosition = + (!_useMobilePlatformUI ? 0 : widget.scheduleViewSettings.weekHeaderSettings.height + padding) + @@ -7257,7 +8010,7 @@ class _SfCalendarState extends State Widget addAgendaWithLoadMore(double height, bool isRTL) { final bool hideEmptyAgendaDays = widget.scheduleViewSettings.hideEmptyScheduleWeek || - !_useMobilePlatformUI; + !_useMobilePlatformUI; /// return empty view when [hideEmptyAgendaDays] enabled and /// the appointments as empty. @@ -7266,7 +8019,8 @@ class _SfCalendarState extends State } final DateTime scheduleDisplayDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, _scheduleDisplayDate)); + getValidDate(widget.minDate, widget.maxDate, _scheduleDisplayDate), + ); final DateTime scheduleCurrentDate = DateTime.now(); _scheduleMinDate ??= scheduleDisplayDate; @@ -7279,18 +8033,24 @@ class _SfCalendarState extends State } final DateTime viewMinDate = DateTimeHelper.getDateTimeValue( - addDays(_minDate, -(_minDate!.weekday % DateTime.daysPerWeek))); + addDays(_minDate, -(_minDate!.weekday % DateTime.daysPerWeek)), + ); final double appointmentViewHeight = CalendarViewHelper.getScheduleAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); /// Get the view first date based on specified /// display date and first day of week. - int value = -(scheduleDisplayDate.weekday % DateTime.daysPerWeek) + + int value = + -(scheduleDisplayDate.weekday % DateTime.daysPerWeek) + widget.firstDayOfWeek - DateTime.daysPerWeek; if (value.abs() >= DateTime.daysPerWeek) { @@ -7301,12 +8061,14 @@ class _SfCalendarState extends State !isSameDate(_previousDates[_previousDates.length - 1], viewMinDate)) { /// Calculate the start date from display date if next view dates /// collection as empty. - DateTime date = _previousDates.isNotEmpty - ? _previousDates[_previousDates.length - 1] - : (_nextDates.isNotEmpty - ? _nextDates[0] - : DateTimeHelper.getDateTimeValue( - addDays(scheduleDisplayDate, value))); + DateTime date = + _previousDates.isNotEmpty + ? _previousDates[_previousDates.length - 1] + : (_nextDates.isNotEmpty + ? _nextDates[0] + : DateTimeHelper.getDateTimeValue( + addDays(scheduleDisplayDate, value), + )); int count = 0; /// Using while for calculate dates because if [hideEmptyAgendaDays] as @@ -7314,7 +8076,8 @@ class _SfCalendarState extends State while (count < 50) { for (int i = 1; i <= 100; i++) { final DateTime updatedDate = DateTimeHelper.getDateTimeValue( - addDays(date, -i * DateTime.daysPerWeek)); + addDays(date, -i * DateTime.daysPerWeek), + ); /// Skip week dates before min date if (!isSameOrAfterDate(viewMinDate, updatedDate)) { @@ -7322,18 +8085,29 @@ class _SfCalendarState extends State break; } - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(updatedDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(updatedDate, 6), + ); /// Skip the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled. if (hideEmptyAgendaDays && !_isAppointmentBetweenDates( - _appointments, updatedDate, weekEndDate, widget.timeZone) && + _appointments, + updatedDate, + weekEndDate, + widget.timeZone, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleDisplayDate) && + updatedDate, + weekEndDate, + scheduleDisplayDate, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleCurrentDate)) { + updatedDate, + weekEndDate, + scheduleCurrentDate, + )) { continue; } @@ -7366,16 +8140,26 @@ class _SfCalendarState extends State } } - final DateTime viewMaxDate = DateTimeHelper.getDateTimeValue(addDays( + final DateTime viewMaxDate = DateTimeHelper.getDateTimeValue( + addDays( _maxDate, - (DateTime.daysPerWeek - _maxDate!.weekday) % DateTime.daysPerWeek)); + (DateTime.daysPerWeek - _maxDate!.weekday) % DateTime.daysPerWeek, + ), + ); if (_nextDates.isEmpty || !isSameDate(_nextDates[_nextDates.length - 1], viewMaxDate)) { /// Calculate the start date from display date - DateTime date = _nextDates.isEmpty - ? DateTimeHelper.getDateTimeValue(addDays(scheduleDisplayDate, value)) - : DateTimeHelper.getDateTimeValue( - addDays(_nextDates[_nextDates.length - 1], DateTime.daysPerWeek)); + DateTime date = + _nextDates.isEmpty + ? DateTimeHelper.getDateTimeValue( + addDays(scheduleDisplayDate, value), + ) + : DateTimeHelper.getDateTimeValue( + addDays( + _nextDates[_nextDates.length - 1], + DateTime.daysPerWeek, + ), + ); int count = 0; /// Using while for calculate dates because if [hideEmptyAgendaDays] as @@ -7383,7 +8167,8 @@ class _SfCalendarState extends State while (count < 50) { for (int i = 0; i < 100; i++) { final DateTime updatedDate = DateTimeHelper.getDateTimeValue( - addDays(date, i * DateTime.daysPerWeek)); + addDays(date, i * DateTime.daysPerWeek), + ); /// Skip week date after max date if (!isSameOrBeforeDate(_maxDate, updatedDate)) { @@ -7391,18 +8176,29 @@ class _SfCalendarState extends State break; } - final DateTime weekEndDate = - DateTimeHelper.getDateTimeValue(addDays(updatedDate, 6)); + final DateTime weekEndDate = DateTimeHelper.getDateTimeValue( + addDays(updatedDate, 6), + ); /// Skip the week date when it does not have appointments /// when [hideEmptyAgendaDays] as enabled. if (hideEmptyAgendaDays && !_isAppointmentBetweenDates( - _appointments, updatedDate, weekEndDate, widget.timeZone) && + _appointments, + updatedDate, + weekEndDate, + widget.timeZone, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleDisplayDate) && + updatedDate, + weekEndDate, + scheduleDisplayDate, + ) && !isDateWithInDateRange( - updatedDate, weekEndDate, scheduleCurrentDate)) { + updatedDate, + weekEndDate, + scheduleCurrentDate, + )) { continue; } @@ -7440,33 +8236,37 @@ class _SfCalendarState extends State /// appointment fills the view port. DateTime viewStartDate = _nextDates[0]; DateTime viewEndDate = DateTimeHelper.getDateTimeValue( - addDays(_nextDates[_nextDates.length - 1], 6)); + addDays(_nextDates[_nextDates.length - 1], 6), + ); List appointmentCollection = AppointmentHelper.getVisibleAppointments( - viewStartDate, - isSameOrBeforeDate(_maxDate, viewEndDate) - ? viewEndDate - : _maxDate!, - _appointments, - widget.timeZone, - false); + viewStartDate, + isSameOrBeforeDate(_maxDate, viewEndDate) ? viewEndDate : _maxDate!, + _appointments, + widget.timeZone, + false, + ); const double padding = 5; Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, viewStartDate, viewEndDate); + appointmentCollection, + viewStartDate, + viewEndDate, + ); List dateAppointmentKeys = dateAppointments.keys.toList(); double labelHeight = 0; if (_useMobilePlatformUI) { - DateTime previousDate = - DateTimeHelper.getDateTimeValue(addDays(viewStartDate, -1)); + DateTime previousDate = DateTimeHelper.getDateTimeValue( + addDays(viewStartDate, -1), + ); for (int i = 0; i < _nextDates.length; i++) { final DateTime nextDate = _nextDates[i]; if (previousDate.month != nextDate.month) { labelHeight += widget.scheduleViewSettings.monthHeaderSettings.height + - padding; + padding; } previousDate = nextDate; @@ -7501,26 +8301,26 @@ class _SfCalendarState extends State isNewDatesAdded = true; viewStartDate = currentDate; - viewEndDate = - DateTimeHelper.getDateTimeValue(addDays(currentDate, 6)); + viewEndDate = DateTimeHelper.getDateTimeValue( + addDays(currentDate, 6), + ); /// Calculate the newly added date appointment height and add /// the height to existing appointments height. appointmentCollection = AppointmentHelper.getVisibleAppointments( - viewStartDate, - isSameOrBeforeDate(_maxDate, viewEndDate) - ? viewEndDate - : _maxDate!, - _appointments, - widget.timeZone, - false); + viewStartDate, + isSameOrBeforeDate(_maxDate, viewEndDate) ? viewEndDate : _maxDate!, + _appointments, + widget.timeZone, + false, + ); if (_useMobilePlatformUI) { final DateTime nextDate = _nextDates[1]; if (nextDate.month != viewStartDate.month) { labelHeight += widget.scheduleViewSettings.monthHeaderSettings.height + - padding; + padding; } labelHeight += @@ -7528,7 +8328,10 @@ class _SfCalendarState extends State } dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, viewStartDate, viewEndDate); + appointmentCollection, + viewStartDate, + viewEndDate, + ); dateAppointmentKeys = dateAppointments.keys.toList(); for (int i = 0; i < dateAppointmentKeys.length; i++) { final List currentDateAppointment = @@ -7541,7 +8344,8 @@ class _SfCalendarState extends State } } - totalHeight = ((numberOfEvents + 1) * padding) + + totalHeight = + ((numberOfEvents + 1) * padding) + ((numberOfEvents - allDayCount) * appointmentViewHeight) + (allDayCount * allDayAppointmentHeight) + labelHeight; @@ -7552,26 +8356,34 @@ class _SfCalendarState extends State if (_nextDates.isNotEmpty && isNewDatesAdded) { final DateTime date = _nextDates[0]; _headerUpdateNotifier.value = DateTimeHelper.getDateTimeValue( - getValidDate(_minDate, _maxDate, date)); + getValidDate(_minDate, _maxDate, date), + ); } } /// Check whether the schedule view initially loading because initially /// schedule display date and schedule loaded min date values are equal. - final bool isMinDisplayDate = - isSameDate(_scheduleMinDate, scheduleDisplayDate); + final bool isMinDisplayDate = isSameDate( + _scheduleMinDate, + scheduleDisplayDate, + ); /// Check whether the schedule view initially loading because initially /// schedule display date and schedule loaded max date values are equal. - final bool isMaxDisplayDate = - isSameDate(_scheduleMaxDate, scheduleDisplayDate); - final bool isInitialLoadMore = isMinDisplayDate && + final bool isMaxDisplayDate = isSameDate( + _scheduleMaxDate, + scheduleDisplayDate, + ); + final bool isInitialLoadMore = + isMinDisplayDate && isMaxDisplayDate && widget.loadMoreWidgetBuilder != null; - DateTime visibleMinDate = - AppointmentHelper.getMonthStartDate(scheduleDisplayDate); - DateTime visibleMaxDate = - AppointmentHelper.getMonthEndDate(scheduleDisplayDate); + DateTime visibleMinDate = AppointmentHelper.getMonthStartDate( + scheduleDisplayDate, + ); + DateTime visibleMaxDate = AppointmentHelper.getMonthEndDate( + scheduleDisplayDate, + ); if (!isSameOrBeforeDate(widget.maxDate, visibleMaxDate)) { visibleMaxDate = widget.maxDate; @@ -7597,10 +8409,14 @@ class _SfCalendarState extends State const double padding = 5; final double appointmentViewHeight = CalendarViewHelper.getScheduleAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - null, widget.scheduleViewSettings); + null, + widget.scheduleViewSettings, + ); /// Calculate the day label(May, 25) height based on appointment height /// and assign the label maximum height as 60. @@ -7615,9 +8431,10 @@ class _SfCalendarState extends State final double dividerHeight = _useMobilePlatformUI ? 0 : 1; /// Holds the height of 'No Events' label view. - final double displayEventHeight = _useMobilePlatformUI - ? appointmentViewHeaderHeight - : appointmentViewHeaderHeight + dividerHeight; + final double displayEventHeight = + _useMobilePlatformUI + ? appointmentViewHeaderHeight + : appointmentViewHeaderHeight + dividerHeight; /// Holds the heights of each weeks in month on initial loading. /// Eg., holds Feb 1, 2021 to Feb 28, 2021 month weeks height. @@ -7631,53 +8448,74 @@ class _SfCalendarState extends State /// loading. while (isSameOrBeforeDate(_maxDate, viewStartDate)) { final DateTime viewEndDate = DateTimeHelper.getDateTimeValue( - addDays(viewStartDate, DateTime.daysPerWeek - 1)); - final DateTime appStartDate = isSameOrAfterDate(_minDate, viewStartDate) - ? viewStartDate - : _minDate!; + addDays(viewStartDate, DateTime.daysPerWeek - 1), + ); + final DateTime appStartDate = + isSameOrAfterDate(_minDate, viewStartDate) + ? viewStartDate + : _minDate!; final DateTime appEndDate = isSameOrBeforeDate(_maxDate, viewEndDate) ? viewEndDate : _maxDate!; /// Today date view height. - double todayNewEventHeight = isDateWithInDateRange( - viewStartDate, viewEndDate, scheduleCurrentDate) - ? displayEventHeight - : 0; + double todayNewEventHeight = + isDateWithInDateRange( + viewStartDate, + viewEndDate, + scheduleCurrentDate, + ) + ? displayEventHeight + : 0; /// Display date view height. - double displayNewEventHeight = isDateWithInDateRange( - viewStartDate, viewEndDate, scheduleDisplayDate) - ? displayEventHeight - : 0; + double displayNewEventHeight = + isDateWithInDateRange( + viewStartDate, + viewEndDate, + scheduleDisplayDate, + ) + ? displayEventHeight + : 0; /// Current week appointments heights. final List appointmentCollection = AppointmentHelper.getVisibleAppointments( - appStartDate, appEndDate, _appointments, widget.timeZone, false, - canCreateNewAppointment: false); + appStartDate, + appEndDate, + _appointments, + widget.timeZone, + false, + canCreateNewAppointment: false, + ); /// Check the week date needs month header or not. - final bool isNeedMonthBuilder = _useMobilePlatformUI && + final bool isNeedMonthBuilder = + _useMobilePlatformUI && ((viewStartDate.month != appEndDate.month || viewStartDate.year != appEndDate.year) || viewStartDate.day == 1); /// Web view does not have month label. - double currentWeekHeight = isNeedMonthBuilder - ? widget.scheduleViewSettings.monthHeaderSettings.height - : 0; + double currentWeekHeight = + isNeedMonthBuilder + ? widget.scheduleViewSettings.monthHeaderSettings.height + : 0; /// Add the week header height to the current view height. /// web view does not have week label. - currentWeekHeight += _useMobilePlatformUI - ? widget.scheduleViewSettings.weekHeaderSettings.height - : 0; + currentWeekHeight += + _useMobilePlatformUI + ? widget.scheduleViewSettings.weekHeaderSettings.height + : 0; if (appointmentCollection.isNotEmpty) { /// Get the collection of appointment collection listed by date. final Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, appStartDate, appEndDate); + appointmentCollection, + appStartDate, + appEndDate, + ); final List dateAppointmentKeys = dateAppointments.keys.toList(); @@ -7715,10 +8553,11 @@ class _SfCalendarState extends State double panelHeight = ((eventsCount - allDayEventCount) * appointmentViewHeight) + - (allDayEventCount * allDayAppointmentHeight); - panelHeight = panelHeight > appointmentViewHeight - ? panelHeight - : appointmentViewHeight; + (allDayEventCount * allDayAppointmentHeight); + panelHeight = + panelHeight > appointmentViewHeight + ? panelHeight + : appointmentViewHeight; appointmentHeight += panelHeight + dividerHeight; numberOfEvents += eventsCount; } @@ -7743,7 +8582,8 @@ class _SfCalendarState extends State totalHeight += currentWeekHeight; heights.add(currentWeekHeight); viewStartDate = DateTimeHelper.getDateTimeValue( - addDays(viewStartDate, DateTime.daysPerWeek)); + addDays(viewStartDate, DateTime.daysPerWeek), + ); } /// Get the current display date week index from next dates collection. @@ -7751,9 +8591,13 @@ class _SfCalendarState extends State for (int i = 0; i < _nextDates.length; i++) { final DateTime visibleStartDate = _nextDates[i]; final DateTime visibleEndDate = DateTimeHelper.getDateTimeValue( - addDays(visibleStartDate, DateTime.daysPerWeek)); + addDays(visibleStartDate, DateTime.daysPerWeek), + ); if (!isDateWithInDateRange( - visibleStartDate, visibleEndDate, scheduleDisplayDate)) { + visibleStartDate, + visibleEndDate, + scheduleDisplayDate, + )) { continue; } @@ -7772,33 +8616,45 @@ class _SfCalendarState extends State /// Calculate the scroll position with current display date week. while (viewStartDate.isBefore(scheduleDisplayDate) && !isSameDate(viewStartDate, scheduleDisplayDate)) { - final DateTime viewEndDate = - DateTimeHelper.getDateTimeValue(addDays(viewStartDate, 6)); - final DateTime appStartDate = isSameOrAfterDate(_minDate, viewStartDate) - ? viewStartDate - : _minDate!; + final DateTime viewEndDate = DateTimeHelper.getDateTimeValue( + addDays(viewStartDate, 6), + ); + final DateTime appStartDate = + isSameOrAfterDate(_minDate, viewStartDate) + ? viewStartDate + : _minDate!; DateTime appEndDate = isSameOrBeforeDate(_maxDate, viewEndDate) ? viewEndDate : _maxDate!; if (appEndDate.isAfter(scheduleDisplayDate) || isSameDate(appEndDate, scheduleDisplayDate)) { - appEndDate = - DateTimeHelper.getDateTimeValue(addDays(scheduleDisplayDate, -1)); + appEndDate = DateTimeHelper.getDateTimeValue( + addDays(scheduleDisplayDate, -1), + ); } /// Today date view height. double todayNewEventHeight = !isSameDate(scheduleCurrentDate, scheduleDisplayDate) && isDateWithInDateRange( - appStartDate, appEndDate, scheduleCurrentDate) + appStartDate, + appEndDate, + scheduleCurrentDate, + ) ? displayEventHeight : 0; final List appointmentCollection = AppointmentHelper.getVisibleAppointments( - appStartDate, appEndDate, _appointments, widget.timeZone, false, - canCreateNewAppointment: false); + appStartDate, + appEndDate, + _appointments, + widget.timeZone, + false, + canCreateNewAppointment: false, + ); /// Check the week date needs month header or not. - final bool isNeedMonthBuilder = _useMobilePlatformUI && + final bool isNeedMonthBuilder = + _useMobilePlatformUI && ((viewStartDate.month != appEndDate.month || viewStartDate.year != appEndDate.year) || viewStartDate.day == 1); @@ -7807,20 +8663,26 @@ class _SfCalendarState extends State /// Get the collection of appointment collection listed by date. final Map> dateAppointments = _getAppointmentCollectionOnDateBasis( - appointmentCollection, appStartDate, appEndDate); + appointmentCollection, + appStartDate, + appEndDate, + ); final List dateAppointmentKeys = dateAppointments.keys.toList(); /// calculate the scroll position by adding week header height. /// web view does not have week label. - initialScrolledPosition += _useMobilePlatformUI - ? widget.scheduleViewSettings.weekHeaderSettings.height - : 0; + initialScrolledPosition += + _useMobilePlatformUI + ? widget.scheduleViewSettings.weekHeaderSettings.height + : 0; /// Web view does not have month label. - initialScrolledPosition += isNeedMonthBuilder - ? widget.scheduleViewSettings.monthHeaderSettings.height + padding - : 0; + initialScrolledPosition += + isNeedMonthBuilder + ? widget.scheduleViewSettings.monthHeaderSettings.height + + padding + : 0; int numberOfEvents = 0; @@ -7845,10 +8707,11 @@ class _SfCalendarState extends State double panelHeight = ((eventsCount - allDayEventCount) * appointmentViewHeight) + - (allDayEventCount * allDayAppointmentHeight); - panelHeight = panelHeight > appointmentViewHeight - ? panelHeight - : appointmentViewHeight; + (allDayEventCount * allDayAppointmentHeight); + panelHeight = + panelHeight > appointmentViewHeight + ? panelHeight + : appointmentViewHeight; appointmentHeight += panelHeight + dividerHeight; numberOfEvents += eventsCount; } @@ -7867,7 +8730,8 @@ class _SfCalendarState extends State /// scroll position. initialScrolledPosition += appointmentHeight + todayNewEventHeight; } else if (isNeedMonthBuilder || todayNewEventHeight != 0) { - initialScrolledPosition += (!_useMobilePlatformUI + initialScrolledPosition += + (!_useMobilePlatformUI ? 0 : widget.scheduleViewSettings.weekHeaderSettings.height + padding) + @@ -7875,7 +8739,8 @@ class _SfCalendarState extends State } viewStartDate = DateTimeHelper.getDateTimeValue( - addDays(viewStartDate, DateTime.daysPerWeek)); + addDays(viewStartDate, DateTime.daysPerWeek), + ); } if (initialScrolledPosition != 0) { @@ -7890,9 +8755,9 @@ class _SfCalendarState extends State } _agendaScrollController?.removeListener(_handleScheduleViewScrolled); - _agendaScrollController = - ScrollController(initialScrollOffset: initialScrolledPosition) - ..addListener(_handleScheduleViewScrolled); + _agendaScrollController = ScrollController( + initialScrollOffset: initialScrolledPosition, + )..addListener(_handleScheduleViewScrolled); _scrollKey = UniqueKey(); } } @@ -7919,166 +8784,185 @@ class _SfCalendarState extends State height: widget.headerHeight, child: GestureDetector( child: Container( - color: widget.headerStyle.backgroundColor ?? - _calendarTheme.headerBackgroundColor, - child: _CalendarHeaderView( - _currentViewVisibleDates, - widget.headerStyle, - null, - _view, - widget.monthViewSettings.numberOfWeeksInView, - _calendarTheme, - isRTL, - _locale, - widget.showNavigationArrow, - _controller, - widget.maxDate, - widget.minDate, - _minWidth, - widget.headerHeight, - widget.timeSlotViewSettings.nonWorkingDays, - widget.monthViewSettings.navigationDirection, - widget.showDatePickerButton, - widget.showTodayButton, - _showHeader, - widget.allowedViews, - widget.allowViewNavigation, - _localizations, - _removeDatePicker, - _headerUpdateNotifier, - _viewChangeNotifier, - _handleOnTapForHeader, - _handleOnLongPressForHeader, - widget.todayHighlightColor, - _textScaleFactor, - _isMobilePlatform, - widget.headerDateFormat, - !_isScheduleStartLoadMore && !_isNeedLoadMore, - widget.todayTextStyle, - widget.showWeekNumber, - widget.weekNumberStyle, - _timelineMonthWeekNumberNotifier, - widget.cellBorderColor, - widget.timeSlotViewSettings.numberOfDaysInView)), + color: + widget.headerStyle.backgroundColor ?? + _calendarTheme.headerBackgroundColor, + child: _CalendarHeaderView( + _currentViewVisibleDates, + widget.headerStyle, + null, + _view, + widget.monthViewSettings.numberOfWeeksInView, + _calendarTheme, + isRTL, + _locale, + widget.showNavigationArrow, + _controller, + widget.maxDate, + widget.minDate, + _minWidth, + widget.headerHeight, + widget.timeSlotViewSettings.nonWorkingDays, + widget.monthViewSettings.navigationDirection, + widget.showDatePickerButton, + widget.showTodayButton, + _showHeader, + widget.allowedViews, + widget.allowViewNavigation, + _localizations, + _removeDatePicker, + _headerUpdateNotifier, + _viewChangeNotifier, + _handleOnTapForHeader, + _handleOnLongPressForHeader, + widget.todayHighlightColor, + _textScaleFactor, + _isMobilePlatform, + widget.headerDateFormat, + !_isScheduleStartLoadMore && !_isNeedLoadMore, + widget.todayTextStyle, + widget.showWeekNumber, + widget.weekNumberStyle, + _timelineMonthWeekNumberNotifier, + widget.cellBorderColor, + widget.timeSlotViewSettings.numberOfDaysInView, + ), + ), ), ), Positioned( - top: widget.headerHeight, - left: 0, - right: 0, - height: height, - child: _OpacityWidget( - opacity: _opacity, - child: NotificationListener( - onNotification: (OverscrollNotification notification) { - if (_isNeedLoadMore || - _isScheduleStartLoadMore || - widget.loadMoreWidgetBuilder == null) { - return true; - } - - if (notification.overscroll < 0 && - _agendaScrollController!.position.pixels <= - _agendaScrollController!.position.minScrollExtent) { - DateTime date = AppointmentHelper.getMonthStartDate( - DateTime(_scheduleMinDate!.year, - _scheduleMinDate!.month - 1)); - - if (!isSameOrAfterDate(widget.minDate, date)) { - date = widget.minDate; - } - - if (isSameDate(_scheduleMinDate, date)) { - return true; - } - - setState(() { - _isScheduleStartLoadMore = true; - _scheduleMinDate = date; - }); - } else if (_agendaScrollController!.position.pixels >= - _agendaScrollController!.position.maxScrollExtent) { - DateTime date = AppointmentHelper.getMonthEndDate( - DateTime(_scheduleMaxDate!.year, - _scheduleMaxDate!.month + 1)); - - if (!isSameOrBeforeDate(widget.maxDate, date)) { - date = widget.maxDate; - } - - if (isSameDate(_scheduleMaxDate, date)) { - return true; - } + top: widget.headerHeight, + left: 0, + right: 0, + height: height, + child: _OpacityWidget( + opacity: _opacity, + child: NotificationListener( + onNotification: (OverscrollNotification notification) { + if (_isNeedLoadMore || + _isScheduleStartLoadMore || + widget.loadMoreWidgetBuilder == null) { + return true; + } - setState(() { - _isNeedLoadMore = true; - _scheduleMaxDate = date; - }); + if (notification.overscroll < 0 && + _agendaScrollController!.position.pixels <= + _agendaScrollController!.position.minScrollExtent) { + DateTime date = AppointmentHelper.getMonthStartDate( + DateTime(_scheduleMinDate!.year, _scheduleMinDate!.month - 1), + ); + + if (!isSameOrAfterDate(widget.minDate, date)) { + date = widget.minDate; + } + + if (isSameDate(_scheduleMinDate, date)) { + return true; + } + + setState(() { + _isScheduleStartLoadMore = true; + _scheduleMinDate = date; + }); + } else if (_agendaScrollController!.position.pixels >= + _agendaScrollController!.position.maxScrollExtent) { + DateTime date = AppointmentHelper.getMonthEndDate( + DateTime(_scheduleMaxDate!.year, _scheduleMaxDate!.month + 1), + ); + + if (!isSameOrBeforeDate(widget.maxDate, date)) { + date = widget.maxDate; + } + + if (isSameDate(_scheduleMaxDate, date)) { + return true; + } + + setState(() { + _isNeedLoadMore = true; + _scheduleMaxDate = date; + }); + } + return true; + }, + child: CustomScrollView( + key: _scrollKey, + physics: const AlwaysScrollableScrollPhysics( + parent: ClampingScrollPhysics( + parent: RangeMaintainingScrollPhysics(), + ), + ), + controller: _agendaScrollController, + center: _scheduleViewKey, + slivers: [ + SliverList( + delegate: SliverChildBuilderDelegate(( + BuildContext context, + int index, + ) { + if (_previousDates.length <= index) { + return null; } - return true; - }, - child: CustomScrollView( - key: _scrollKey, - physics: const AlwaysScrollableScrollPhysics( - parent: ClampingScrollPhysics( - parent: RangeMaintainingScrollPhysics())), - controller: _agendaScrollController, - center: _scheduleViewKey, - slivers: [ - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - if (_previousDates.length <= index) { - return null; - } - - /// Send negative index value to differentiate the - /// backward view from forward view. - return _getItem(context, -(index + 1), isRTL); - }), - ), - SliverList( - delegate: SliverChildBuilderDelegate( - (BuildContext context, int index) { - if (_nextDates.length <= index) { - return null; - } - - return _getItem(context, index, isRTL); - }), - key: _scheduleViewKey, - ), - ], - )))), + + /// Send negative index value to differentiate the + /// backward view from forward view. + return _getItem(context, -(index + 1), isRTL); + }), + ), + SliverList( + delegate: SliverChildBuilderDelegate(( + BuildContext context, + int index, + ) { + if (_nextDates.length <= index) { + return null; + } + + return _getItem(context, index, isRTL); + }), + key: _scheduleViewKey, + ), + ], + ), + ), + ), + ), _addDatePicker(widget.headerHeight, isRTL), _getCalendarViewPopup(), ]; if ((_isNeedLoadMore || _isScheduleStartLoadMore) && widget.loadMoreWidgetBuilder != null) { - final Alignment loadMoreAlignment = _agendaScrollController!.hasClients && - _agendaScrollController!.position.pixels <= - _agendaScrollController!.position.minScrollExtent && - _isScheduleStartLoadMore - ? Alignment.topCenter - : Alignment.bottomCenter; - final DateTime visibleStartDate = _isNeedLoadMore - ? AppointmentHelper.getMonthStartDate(_scheduleMaxDate!) - : _scheduleMinDate!; - final DateTime visibleEndDate = _isNeedLoadMore - ? _scheduleMaxDate! - : AppointmentHelper.getMonthEndDate(_scheduleMinDate!); - children.add(Positioned( + final Alignment loadMoreAlignment = + _agendaScrollController!.hasClients && + _agendaScrollController!.position.pixels <= + _agendaScrollController!.position.minScrollExtent && + _isScheduleStartLoadMore + ? Alignment.topCenter + : Alignment.bottomCenter; + final DateTime visibleStartDate = + _isNeedLoadMore + ? AppointmentHelper.getMonthStartDate(_scheduleMaxDate!) + : _scheduleMinDate!; + final DateTime visibleEndDate = + _isNeedLoadMore + ? _scheduleMaxDate! + : AppointmentHelper.getMonthEndDate(_scheduleMinDate!); + children.add( + Positioned( top: widget.headerHeight, left: 0, right: 0, height: height, child: Container( - alignment: loadMoreAlignment, - color: Colors.transparent, - child: widget.loadMoreWidgetBuilder!(context, () async { - await loadMoreAppointments(visibleStartDate, visibleEndDate); - })))); + alignment: loadMoreAlignment, + color: Colors.transparent, + child: widget.loadMoreWidgetBuilder!(context, () async { + await loadMoreAppointments(visibleStartDate, visibleEndDate); + }), + ), + ), + ); } return KeyboardListener( @@ -8095,11 +8979,16 @@ class _SfCalendarState extends State } CalendarViewHelper.handleViewSwitchKeyBoardEvent( - event, _controller, widget.allowedViews); + event, + _controller, + widget.allowedViews, + ); } Future loadMoreAppointments( - DateTime visibleStartDate, DateTime visibleEndDate) async { + DateTime visibleStartDate, + DateTime visibleEndDate, + ) async { if (_isLoadMoreLoaded) { return; } @@ -8137,12 +9026,14 @@ class _SfCalendarState extends State final TextStyle style = TextStyle(color: headerTextColor, fontSize: 12); int selectedIndex = -1; final Color? todayColor = CalendarViewHelper.getTodayHighlightTextColor( - widget.todayHighlightColor ?? _calendarTheme.todayHighlightColor, - widget.todayTextStyle, - _calendarTheme); + widget.todayHighlightColor ?? _calendarTheme.todayHighlightColor, + widget.todayTextStyle, + _calendarTheme, + ); - final Map calendarViews = - _getCalendarViewsText(_localizations); + final Map calendarViews = _getCalendarViewsText( + _localizations, + ); final Alignment alignment = _isRTL ? Alignment.centerRight : Alignment.centerLeft; @@ -8152,32 +9043,38 @@ class _SfCalendarState extends State for (int i = 0; i < allowedViewLength; i++) { final CalendarView view = widget.allowedViews![i]; final String text = calendarViews[view]!; - final double textWidth = _getTextWidgetWidth( - text, calendarViewTextHeight, _minWidth, context, - style: style) - .width; + final double textWidth = + _getTextWidgetWidth( + text, + calendarViewTextHeight, + _minWidth, + context, + style: style, + ).width; width = width < textWidth ? textWidth : width; final bool isSelected = view == _view; if (isSelected) { selectedIndex = i; } - children.add(InkWell( - onTap: () { - _viewChangeNotifier.value = false; - _controller.view = view; - }, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 10.0), - height: calendarViewTextHeight, - alignment: alignment, - child: Text( - text, - style: isSelected ? style.copyWith(color: todayColor) : style, - maxLines: 1, + children.add( + InkWell( + onTap: () { + _viewChangeNotifier.value = false; + _controller.view = view; + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10.0), + height: calendarViewTextHeight, + alignment: alignment, + child: Text( + text, + style: isSelected ? style.copyWith(color: todayColor) : style, + maxLines: 1, + ), ), ), - )); + ); } /// Restrict the pop up height with max height(200) @@ -8203,36 +9100,46 @@ class _SfCalendarState extends State final double headerIconTextWidth = _calendarTheme.headerTextStyle!.fontSize ?? 14; final double totalArrowWidth = 2 * arrowWidth; - final bool isCenterAlignment = !_isMobilePlatform && + final bool isCenterAlignment = + !_isMobilePlatform && (widget.headerStyle.textAlign == TextAlign.center || widget.headerStyle.textAlign == TextAlign.justify); /// Calculate the calendar view button width that placed on header view - final double calendarViewWidth = _useMobilePlatformUI - ? iconWidth - : _getTextWidgetWidth(calendarViews[_view]!, widget.headerHeight, - _minWidth - totalArrowWidth, context, - style: style) - .width + - padding + - headerIconTextWidth; + final double calendarViewWidth = + _useMobilePlatformUI + ? iconWidth + : _getTextWidgetWidth( + calendarViews[_view]!, + widget.headerHeight, + _minWidth - totalArrowWidth, + context, + style: style, + ).width + + padding + + headerIconTextWidth; double dividerWidth = 0; double todayWidth = 0; /// Today button shown only the date picker enabled. if (widget.showTodayButton) { - todayWidth = _useMobilePlatformUI - ? iconWidth - : _getTextWidgetWidth(_localizations.todayLabel, widget.headerHeight, - _minWidth - totalArrowWidth, context, - style: style) - .width + - padding; + todayWidth = + _useMobilePlatformUI + ? iconWidth + : _getTextWidgetWidth( + _localizations.todayLabel, + widget.headerHeight, + _minWidth - totalArrowWidth, + context, + style: style, + ).width + + padding; /// Divider shown when the view holds calendar views and today button. dividerWidth = _useMobilePlatformUI ? 0 : 5; } - double headerWidth = _minWidth - + double headerWidth = + _minWidth - totalArrowWidth - calendarViewWidth - todayWidth - @@ -8249,34 +9156,39 @@ class _SfCalendarState extends State Alignment popupAlignment; if (_isMobilePlatform) { /// icon width specifies the today button width and calendar view width. - left = _isRTL - ? totalArrowWidth - : headerWidth + todayWidth + iconWidth - width; + left = + _isRTL + ? totalArrowWidth + : headerWidth + todayWidth + iconWidth - width; popupAlignment = _isRTL ? Alignment.topLeft : Alignment.topRight; if (widget.headerStyle.textAlign == TextAlign.right || widget.headerStyle.textAlign == TextAlign.end) { popupAlignment = _isRTL ? Alignment.topRight : Alignment.topLeft; - left = _isRTL - ? headerWidth + iconWidth + todayWidth - width - : totalArrowWidth; + left = + _isRTL + ? headerWidth + iconWidth + todayWidth - width + : totalArrowWidth; } else if (widget.headerStyle.textAlign == TextAlign.center || widget.headerStyle.textAlign == TextAlign.justify) { popupAlignment = _isRTL ? Alignment.topLeft : Alignment.topRight; - left = _isRTL - ? arrowWidth - : headerWidth + arrowWidth + todayWidth + iconWidth - width; + left = + _isRTL + ? arrowWidth + : headerWidth + arrowWidth + todayWidth + iconWidth - width; } } else { - left = _isRTL - ? calendarViewWidth - width - : headerWidth + totalArrowWidth + todayWidth + dividerWidth - 1; + left = + _isRTL + ? calendarViewWidth - width + : headerWidth + totalArrowWidth + todayWidth + dividerWidth - 1; popupAlignment = _isRTL ? Alignment.topLeft : Alignment.topRight; if (widget.headerStyle.textAlign == TextAlign.right || widget.headerStyle.textAlign == TextAlign.end) { popupAlignment = _isRTL ? Alignment.topRight : Alignment.topLeft; - left = _isRTL - ? headerWidth + totalArrowWidth + todayWidth + dividerWidth - 1 - : calendarViewWidth - width; + left = + _isRTL + ? headerWidth + totalArrowWidth + todayWidth + dividerWidth - 1 + : calendarViewWidth - width; } else if (widget.headerStyle.textAlign == TextAlign.center || widget.headerStyle.textAlign == TextAlign.justify) { popupAlignment = _isRTL ? Alignment.topRight : Alignment.topLeft; @@ -8284,20 +9196,22 @@ class _SfCalendarState extends State /// Calculate the left padding by calculate the total icon and header. /// Calculate the menu icon position by adding the left padding, left /// arrow and header label. - final double leftStartPosition = (_minWidth - + final double leftStartPosition = + (_minWidth - totalArrowWidth - calendarViewWidth - dividerWidth - todayWidth - headerWidth) / 2; - left = _isRTL - ? leftStartPosition + calendarViewWidth - width - : leftStartPosition + - totalArrowWidth + - headerWidth + - todayWidth + - dividerWidth; + left = + _isRTL + ? leftStartPosition + calendarViewWidth - width + : leftStartPosition + + totalArrowWidth + + headerWidth + + todayWidth + + dividerWidth; } } @@ -8312,46 +9226,58 @@ class _SfCalendarState extends State scrollPosition = selectedIndex * calendarViewTextHeight; final double maxScrollPosition = allowedViewLength * calendarViewTextHeight; - scrollPosition = (maxScrollPosition - scrollPosition) > height - ? scrollPosition - : maxScrollPosition - height; + scrollPosition = + (maxScrollPosition - scrollPosition) > height + ? scrollPosition + : maxScrollPosition - height; } final bool showScrollbar = totalHeight > height; - final ScrollController calendarViewPopupScrollController = - ScrollController(initialScrollOffset: scrollPosition); + final ScrollController calendarViewPopupScrollController = ScrollController( + initialScrollOffset: scrollPosition, + ); return Positioned( - top: widget.headerHeight, - left: left, - height: height, - width: width, - child: _PopupWidget( - alignment: popupAlignment, - child: Container( + top: widget.headerHeight, + left: left, + height: height, + width: width, + child: _PopupWidget( + alignment: popupAlignment, + child: Container( + padding: EdgeInsets.zero, + decoration: BoxDecoration( + color: + _themeData.brightness == Brightness.dark + ? Colors.grey[850] + : Colors.white, + boxShadow: kElevationToShadow[6], + borderRadius: BorderRadius.circular(2.0), + ), + child: Material( + type: MaterialType.transparency, + child: Scrollbar( + thumbVisibility: showScrollbar, + controller: calendarViewPopupScrollController, + child: ListView( padding: EdgeInsets.zero, - decoration: BoxDecoration( - color: _themeData.brightness == Brightness.dark - ? Colors.grey[850] - : Colors.white, - boxShadow: kElevationToShadow[6], - borderRadius: BorderRadius.circular(2.0), - ), - child: Material( - type: MaterialType.transparency, - child: Scrollbar( - thumbVisibility: showScrollbar, - controller: calendarViewPopupScrollController, - child: ListView( - padding: EdgeInsets.zero, - controller: calendarViewPopupScrollController, - children: children)), - )))); + controller: calendarViewPopupScrollController, + children: children, + ), + ), + ), + ), + ), + ); } /// Adds the resource panel on the left side of the view, if the resource /// collection is not null. - Widget _addResourcePanel(bool isResourceEnabled, double resourceViewSize, - double height, bool isRTL) { + Widget _addResourcePanel( + bool isResourceEnabled, + double resourceViewSize, + double height, + bool isRTL, + ) { if (!isResourceEnabled) { return Positioned( left: 0, @@ -8362,16 +9288,21 @@ class _SfCalendarState extends State ); } - final double viewHeaderHeight = - CalendarViewHelper.getViewHeaderHeight(widget.viewHeaderHeight, _view); + final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( + widget.viewHeaderHeight, + _view, + ); final double timeLabelSize = CalendarViewHelper.getTimeLabelWidth( - widget.timeSlotViewSettings.timeRulerSize, _view); + widget.timeSlotViewSettings.timeRulerSize, + _view, + ); final double top = viewHeaderHeight + timeLabelSize; final double resourceItemHeight = CalendarViewHelper.getResourceItemHeight( - resourceViewSize, - height - top, - widget.resourceViewSettings, - _resourceCollection!.length); + resourceViewSize, + height - top, + widget.resourceViewSettings, + _resourceCollection!.length, + ); final double panelHeight = resourceItemHeight * _resourceCollection!.length; final Widget verticalDivider = VerticalDivider( @@ -8381,105 +9312,152 @@ class _SfCalendarState extends State ); return Positioned( - left: isRTL ? _minWidth - resourceViewSize : 0, - width: resourceViewSize, - top: 0, - bottom: 0, - child: Stack(children: [ + left: isRTL ? _minWidth - resourceViewSize : 0, + width: resourceViewSize, + top: 0, + bottom: 0, + child: Stack( + children: [ Positioned( left: _isRTL ? 0.5 : resourceViewSize - 0.5, width: 0.5, - top: _controller.view == CalendarView.timelineMonth - ? widget.headerHeight - : widget.headerHeight + viewHeaderHeight, - height: _controller.view == CalendarView.timelineMonth - ? viewHeaderHeight - : timeLabelSize, + top: + _controller.view == CalendarView.timelineMonth + ? widget.headerHeight + : widget.headerHeight + viewHeaderHeight, + height: + _controller.view == CalendarView.timelineMonth + ? viewHeaderHeight + : timeLabelSize, child: verticalDivider, ), Positioned( - left: 0, - width: resourceViewSize, - top: widget.headerHeight + top, - bottom: 0, - child: MouseRegion( - onEnter: (PointerEnterEvent event) { - _pointerEnterEvent(event, false, isRTL, null, - top + widget.headerHeight, 0, isResourceEnabled); - }, - onExit: _pointerExitEvent, - onHover: (PointerHoverEvent event) { - _pointerHoverEvent(event, false, isRTL, null, - top + widget.headerHeight, 0, isResourceEnabled); - }, - child: GestureDetector( - child: ScrollConfiguration( - behavior: ScrollConfiguration.of(context) - .copyWith(scrollbars: false), - child: ListView( - padding: EdgeInsets.zero, - physics: const ClampingScrollPhysics(), - controller: _resourcePanelScrollController, - children: [ - ResourceViewWidget( - _resourceCollection, - widget.resourceViewSettings, - resourceItemHeight, - widget.cellBorderColor, - _calendarTheme, - _themeData, - _resourceImageNotifier, - isRTL, - _textScaleFactor, - _resourceHoverNotifier.value, - _imagePainterCollection, - resourceViewSize, - panelHeight, - widget.resourceViewHeaderBuilder), - ]), - ), - onTapUp: (TapUpDetails details) { - _handleOnTapForResourcePanel(details, resourceItemHeight); - }, - onLongPressStart: (LongPressStartDetails details) { - _handleOnLongPressForResourcePanel( - details, resourceItemHeight); - }, - ))) - ])); + left: 0, + width: resourceViewSize, + top: widget.headerHeight + top, + bottom: 0, + child: MouseRegion( + onEnter: (PointerEnterEvent event) { + _pointerEnterEvent( + event, + false, + isRTL, + null, + top + widget.headerHeight, + 0, + isResourceEnabled, + ); + }, + onExit: _pointerExitEvent, + onHover: (PointerHoverEvent event) { + _pointerHoverEvent( + event, + false, + isRTL, + null, + top + widget.headerHeight, + 0, + isResourceEnabled, + ); + }, + child: GestureDetector( + child: ScrollConfiguration( + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), + child: ListView( + padding: EdgeInsets.zero, + physics: const ClampingScrollPhysics(), + controller: _resourcePanelScrollController, + children: [ + ResourceViewWidget( + _resourceCollection, + widget.resourceViewSettings, + resourceItemHeight, + widget.cellBorderColor, + _calendarTheme, + _themeData, + _resourceImageNotifier, + isRTL, + _textScaleFactor, + _resourceHoverNotifier.value, + _imagePainterCollection, + resourceViewSize, + panelHeight, + widget.resourceViewHeaderBuilder, + ), + ], + ), + ), + onTapUp: (TapUpDetails details) { + _handleOnTapForResourcePanel(details, resourceItemHeight); + }, + onLongPressStart: (LongPressStartDetails details) { + _handleOnLongPressForResourcePanel( + details, + resourceItemHeight, + ); + }, + ), + ), + ), + ], + ), + ); } /// Handles and raises the [widget.onLongPress] callback, when the resource /// panel is long pressed in [SfCalendar]. void _handleOnLongPressForResourcePanel( - LongPressStartDetails details, double resourceItemHeight) { + LongPressStartDetails details, + double resourceItemHeight, + ) { if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress)) { + widget.onLongPress, + )) { return; } - final CalendarResource tappedResource = - _getTappedResource(details.localPosition.dy, resourceItemHeight); - final List resourceAppointments = - _getSelectedResourceAppointments(tappedResource); - CalendarViewHelper.raiseCalendarLongPressCallback(widget, null, - resourceAppointments, CalendarElement.resourceHeader, tappedResource); + final CalendarResource tappedResource = _getTappedResource( + details.localPosition.dy, + resourceItemHeight, + ); + final List resourceAppointments = _getSelectedResourceAppointments( + tappedResource, + ); + CalendarViewHelper.raiseCalendarLongPressCallback( + widget, + null, + resourceAppointments, + CalendarElement.resourceHeader, + tappedResource, + ); } /// Handles and raises the [widget.onTap] callback, when the resource panel /// is tapped in [SfCalendar]. void _handleOnTapForResourcePanel( - TapUpDetails details, double resourceItemHeight) { + TapUpDetails details, + double resourceItemHeight, + ) { if (!CalendarViewHelper.shouldRaiseCalendarTapCallback(widget.onTap)) { return; } - final CalendarResource tappedResource = - _getTappedResource(details.localPosition.dy, resourceItemHeight); - final List resourceAppointments = - _getSelectedResourceAppointments(tappedResource); - CalendarViewHelper.raiseCalendarTapCallback(widget, null, - resourceAppointments, CalendarElement.resourceHeader, tappedResource); + final CalendarResource tappedResource = _getTappedResource( + details.localPosition.dy, + resourceItemHeight, + ); + final List resourceAppointments = _getSelectedResourceAppointments( + tappedResource, + ); + CalendarViewHelper.raiseCalendarTapCallback( + widget, + null, + resourceAppointments, + CalendarElement.resourceHeader, + tappedResource, + ); } /// Filter and returns the appointment collection for the given resource from @@ -8496,7 +9474,8 @@ class _SfCalendarState extends State app.resourceIds!.isNotEmpty && app.resourceIds!.contains(resource.id)) { selectedResourceAppointments.add( - CalendarViewHelper.getAppointmentDetail(app, widget.dataSource)); + CalendarViewHelper.getAppointmentDetail(app, widget.dataSource), + ); } } @@ -8505,67 +9484,78 @@ class _SfCalendarState extends State /// Returns the tapped resource details, based on the tapped position. CalendarResource _getTappedResource( - double tappedPosition, double resourceItemHeight) { + double tappedPosition, + double resourceItemHeight, + ) { final int index = (_resourcePanelScrollController!.offset + tappedPosition) ~/ - resourceItemHeight; + resourceItemHeight; return _resourceCollection![index]; } /// Adds the custom scroll view which used to produce the infinity scroll. Widget _addCustomScrollView( - double top, - double resourceViewSize, - bool isRTL, - bool isResourceEnabled, - double width, - double height, - double agendaHeight) { + double top, + double resourceViewSize, + bool isRTL, + bool isResourceEnabled, + double width, + double height, + double agendaHeight, + ) { return Positioned( top: top, left: isResourceEnabled && !isRTL ? resourceViewSize : 0, right: isResourceEnabled && isRTL ? resourceViewSize : 0, height: height - agendaHeight, child: _OpacityWidget( - opacity: _opacity, - child: CustomCalendarScrollView( - widget, - _view, - width - resourceViewSize, - height - agendaHeight, - _agendaSelectedDate, - isRTL, - _locale, - _calendarTheme, - _themeData, - _timeZoneLoaded ? widget.specialRegions : null, - _blackoutDates, - _controller, - _removeDatePicker, - _resourcePanelScrollController, - _resourceCollection, - _textScaleFactor, - _isMobilePlatform, - _fadeInController, - widget.minDate, - widget.maxDate, - _localizations, - _timelineMonthWeekNumberNotifier, - _updateCalendarState, - _getCalendarStateDetails, - key: _customScrollViewKey, - )), + opacity: _opacity, + child: CustomCalendarScrollView( + widget, + _view, + width - resourceViewSize, + height - agendaHeight, + _agendaSelectedDate, + isRTL, + _locale, + _calendarTheme, + _themeData, + _timeZoneLoaded ? widget.specialRegions : null, + _blackoutDates, + _controller, + _removeDatePicker, + _resourcePanelScrollController, + _resourceCollection, + _textScaleFactor, + _isMobilePlatform, + _fadeInController, + widget.minDate, + widget.maxDate, + _localizations, + _timelineMonthWeekNumberNotifier, + _updateCalendarState, + _getCalendarStateDetails, + key: _customScrollViewKey, + ), + ), ); } Widget _addChildren( - double agendaHeight, double height, double width, bool isRTL) { - final bool isResourceEnabled = - CalendarViewHelper.isResourceEnabled(widget.dataSource, _view); + double agendaHeight, + double height, + double width, + bool isRTL, + ) { + final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( + widget.dataSource, + _view, + ); final double resourceViewSize = isResourceEnabled ? widget.resourceViewSettings.size : 0; - final DateTime currentViewDate = _currentViewVisibleDates[ - (_currentViewVisibleDates.length / 2).truncate()]; + final DateTime currentViewDate = + _currentViewVisibleDates[(_currentViewVisibleDates.length / 2) + .truncate()]; final List children = [ Positioned( @@ -8574,63 +9564,82 @@ class _SfCalendarState extends State left: 0, height: widget.headerHeight, child: Container( - color: widget.headerStyle.backgroundColor ?? - _calendarTheme.headerBackgroundColor, - child: _CalendarHeaderView( - _currentViewVisibleDates, - widget.headerStyle, - currentViewDate, - _view, - widget.monthViewSettings.numberOfWeeksInView, - _calendarTheme, - isRTL, - _locale, - widget.showNavigationArrow, - _controller, - widget.maxDate, - widget.minDate, - width, - widget.headerHeight, - widget.timeSlotViewSettings.nonWorkingDays, - widget.monthViewSettings.navigationDirection, - widget.showDatePickerButton, - widget.showTodayButton, - _showHeader, - widget.allowedViews, - widget.allowViewNavigation, - _localizations, - _removeDatePicker, - _headerUpdateNotifier, - _viewChangeNotifier, - _handleOnTapForHeader, - _handleOnLongPressForHeader, - widget.todayHighlightColor, - _textScaleFactor, - _isMobilePlatform, - widget.headerDateFormat, - !_isNeedLoadMore, - widget.todayTextStyle, - widget.showWeekNumber, - widget.weekNumberStyle, - _timelineMonthWeekNumberNotifier, - widget.cellBorderColor, - widget.timeSlotViewSettings.numberOfDaysInView)), + color: + widget.headerStyle.backgroundColor ?? + _calendarTheme.headerBackgroundColor, + child: _CalendarHeaderView( + _currentViewVisibleDates, + widget.headerStyle, + currentViewDate, + _view, + widget.monthViewSettings.numberOfWeeksInView, + _calendarTheme, + isRTL, + _locale, + widget.showNavigationArrow, + _controller, + widget.maxDate, + widget.minDate, + width, + widget.headerHeight, + widget.timeSlotViewSettings.nonWorkingDays, + widget.monthViewSettings.navigationDirection, + widget.showDatePickerButton, + widget.showTodayButton, + _showHeader, + widget.allowedViews, + widget.allowViewNavigation, + _localizations, + _removeDatePicker, + _headerUpdateNotifier, + _viewChangeNotifier, + _handleOnTapForHeader, + _handleOnLongPressForHeader, + widget.todayHighlightColor, + _textScaleFactor, + _isMobilePlatform, + widget.headerDateFormat, + !_isNeedLoadMore, + widget.todayTextStyle, + widget.showWeekNumber, + widget.weekNumberStyle, + _timelineMonthWeekNumberNotifier, + widget.cellBorderColor, + widget.timeSlotViewSettings.numberOfDaysInView, + ), + ), ), _addResourcePanel(isResourceEnabled, resourceViewSize, height, isRTL), - _addCustomScrollView(widget.headerHeight, resourceViewSize, isRTL, - isResourceEnabled, width, height, agendaHeight), - _addAgendaView(agendaHeight, widget.headerHeight + height - agendaHeight, - width, isRTL), + _addCustomScrollView( + widget.headerHeight, + resourceViewSize, + isRTL, + isResourceEnabled, + width, + height, + agendaHeight, + ), + _addAgendaView( + agendaHeight, + widget.headerHeight + height - agendaHeight, + width, + isRTL, + ), _addDatePicker(widget.headerHeight, isRTL), _getCalendarViewPopup(), ]; if (_isNeedLoadMore && widget.loadMoreWidgetBuilder != null) { - children.add(Container( + children.add( + Container( color: Colors.transparent, child: widget.loadMoreWidgetBuilder!(context, () async { - await loadMoreAppointments(_currentViewVisibleDates[0], - _currentViewVisibleDates[_currentViewVisibleDates.length - 1]); - }))); + await loadMoreAppointments( + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + ); + }), + ), + ); } return Stack(children: children); } @@ -8671,7 +9680,10 @@ class _SfCalendarState extends State final Color? todayColor = widget.todayHighlightColor ?? _calendarTheme.todayHighlightColor; final Color? todayTextColor = CalendarViewHelper.getTodayHighlightTextColor( - todayColor, widget.todayTextStyle, _calendarTheme); + todayColor, + widget.todayTextStyle, + _calendarTheme, + ); double left = 0; if (_isMobilePlatform) { pickerWidth = _minWidth; @@ -8696,12 +9708,14 @@ class _SfCalendarState extends State final double totalArrowWidth = 2 * arrowWidth; final double totalWidth = _minWidth - totalArrowWidth; final double totalHeight = _minHeight - widget.headerHeight; - maxHeight = maxHeight < 250 - ? (totalHeight < 250 ? totalHeight - 10 : 250) - : maxHeight; - maxWidth = maxWidth < 250 - ? (totalWidth < 250 ? totalWidth - 10 : 250) - : maxWidth; + maxHeight = + maxHeight < 250 + ? (totalHeight < 250 ? totalHeight - 10 : 250) + : maxHeight; + maxWidth = + maxWidth < 250 + ? (totalWidth < 250 ? totalWidth - 10 : 250) + : maxWidth; double containerSize = maxHeight > maxWidth ? maxWidth : maxHeight; if (containerSize > 300) { containerSize = 300; @@ -8724,147 +9738,158 @@ class _SfCalendarState extends State left = (_minWidth - containerSize) / 2; } else { headerViewWidth = headerViewWidth > 200 ? 200 : headerViewWidth; - final double leftPadding = (_minWidth - + final double leftPadding = + (_minWidth - headerViewWidth - calendarViewWidth - totalArrowWidth) / 2; double headerPadding = (headerViewWidth - containerSize) / 2; headerPadding = headerPadding > 0 ? headerPadding : 0; - left = _isRTL - ? leftPadding + - arrowWidth + - calendarViewWidth + - headerViewWidth - - containerSize - : leftPadding + arrowWidth + headerPadding; + left = + _isRTL + ? leftPadding + + arrowWidth + + calendarViewWidth + + headerViewWidth - + containerSize + : leftPadding + arrowWidth + headerPadding; } } } return Positioned( - top: top, - left: left, - width: pickerWidth, - height: pickerHeight, - child: _PopupWidget( - child: Container( - margin: EdgeInsets.zero, - padding: const EdgeInsets.all(5), - decoration: _isMobilePlatform - ? BoxDecoration( - color: _themeData.brightness == Brightness.dark + top: top, + left: left, + width: pickerWidth, + height: pickerHeight, + child: _PopupWidget( + child: Container( + margin: EdgeInsets.zero, + padding: const EdgeInsets.all(5), + decoration: + _isMobilePlatform + ? BoxDecoration( + color: + _themeData.brightness == Brightness.dark ? Colors.grey[850] : Colors.white, - boxShadow: const [ - BoxShadow( - offset: Offset(0.0, 3.0), - blurRadius: 2.0, - color: Color(0x24000000)), - ], - ) - : BoxDecoration( - color: _themeData.brightness == Brightness.dark + boxShadow: const [ + BoxShadow( + offset: Offset(0.0, 3.0), + blurRadius: 2.0, + color: Color(0x24000000), + ), + ], + ) + : BoxDecoration( + color: + _themeData.brightness == Brightness.dark ? Colors.grey[850] : Colors.white, - boxShadow: kElevationToShadow[6], - borderRadius: BorderRadius.circular(2.0), - ), - child: SfDateRangePicker( - showNavigationArrow: true, - initialSelectedDate: _currentDate, - initialDisplayDate: _currentDate, - todayHighlightColor: todayColor, - minDate: widget.minDate, - maxDate: widget.maxDate, - selectionColor: todayTextColor, - //// For disabling the picker dates based on the calendar non working days. - selectableDayPredicate: _view != CalendarView.workWeek && - _view != CalendarView.timelineWorkWeek - ? null - : (DateTime dateTime) { - for (int i = 0; - i < - widget.timeSlotViewSettings.nonWorkingDays - .length; - i++) { - if (dateTime.weekday == - widget.timeSlotViewSettings.nonWorkingDays[i]) { - return false; - } - } - return true; - }, - headerStyle: DateRangePickerHeaderStyle( - textAlign: - _isMobilePlatform ? TextAlign.center : TextAlign.left, + boxShadow: kElevationToShadow[6], + borderRadius: BorderRadius.circular(2.0), ), - monthViewSettings: DateRangePickerMonthViewSettings( - viewHeaderHeight: pickerHeight / 8, - firstDayOfWeek: widget.firstDayOfWeek, - ), - monthCellStyle: DateRangePickerMonthCellStyle( - textStyle: datePickerStyle, - todayTextStyle: - datePickerStyle.copyWith(color: todayTextColor)), - yearCellStyle: DateRangePickerYearCellStyle( - textStyle: datePickerStyle, - todayTextStyle: - datePickerStyle.copyWith(color: todayTextColor), - leadingDatesTextStyle: _calendarTheme.leadingDatesTextStyle, - ), - view: _view == CalendarView.month || - _view == CalendarView.timelineMonth - ? DateRangePickerView.year - : DateRangePickerView.month, - onViewChanged: (DateRangePickerViewChangedArgs details) { - if ((_view != CalendarView.month && - _view != CalendarView.timelineMonth) || - details.view != DateRangePickerView.month) { - return; - } + child: SfDateRangePicker( + showNavigationArrow: true, + initialSelectedDate: _currentDate, + initialDisplayDate: _currentDate, + todayHighlightColor: todayColor, + minDate: widget.minDate, + maxDate: widget.maxDate, + selectionColor: todayTextColor, + //// For disabling the picker dates based on the calendar non working days. + selectableDayPredicate: + _view != CalendarView.workWeek && + _view != CalendarView.timelineWorkWeek + ? null + : (DateTime dateTime) { + for ( + int i = 0; + i < widget.timeSlotViewSettings.nonWorkingDays.length; + i++ + ) { + if (dateTime.weekday == + widget.timeSlotViewSettings.nonWorkingDays[i]) { + return false; + } + } + return true; + }, + headerStyle: DateRangePickerHeaderStyle( + textAlign: _isMobilePlatform ? TextAlign.center : TextAlign.left, + ), + monthViewSettings: DateRangePickerMonthViewSettings( + viewHeaderHeight: pickerHeight / 8, + firstDayOfWeek: widget.firstDayOfWeek, + ), + monthCellStyle: DateRangePickerMonthCellStyle( + textStyle: datePickerStyle, + todayTextStyle: datePickerStyle.copyWith(color: todayTextColor), + ), + yearCellStyle: DateRangePickerYearCellStyle( + textStyle: datePickerStyle, + todayTextStyle: datePickerStyle.copyWith(color: todayTextColor), + leadingDatesTextStyle: _calendarTheme.leadingDatesTextStyle, + ), + view: + _view == CalendarView.month || + _view == CalendarView.timelineMonth + ? DateRangePickerView.year + : DateRangePickerView.month, + onViewChanged: (DateRangePickerViewChangedArgs details) { + if ((_view != CalendarView.month && + _view != CalendarView.timelineMonth) || + details.view != DateRangePickerView.month) { + return; + } - if (isSameDate(_currentDate, _controller.displayDate) || - isDateWithInDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[ - _currentViewVisibleDates.length - 1], - _controller.displayDate)) { - _removeDatePicker(); - } + if (isSameDate(_currentDate, _controller.displayDate) || + isDateWithInDateRange( + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - + 1], + _controller.displayDate, + )) { + _removeDatePicker(); + } - _showHeader = false; - final DateTime selectedDate = - details.visibleDateRange.startDate!; - _controller.displayDate = DateTime( - selectedDate.year, - selectedDate.month, - selectedDate.day, - _controller.displayDate!.hour, - _controller.displayDate!.minute, - _controller.displayDate!.second); - }, - onSelectionChanged: - (DateRangePickerSelectionChangedArgs details) { - if (isSameDate(_currentDate, _controller.displayDate) || - isDateWithInDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[ - _currentViewVisibleDates.length - 1], - _controller.displayDate)) { - _removeDatePicker(); - } + _showHeader = false; + final DateTime selectedDate = details.visibleDateRange.startDate!; + _controller.displayDate = DateTime( + selectedDate.year, + selectedDate.month, + selectedDate.day, + _controller.displayDate!.hour, + _controller.displayDate!.minute, + _controller.displayDate!.second, + ); + }, + onSelectionChanged: (DateRangePickerSelectionChangedArgs details) { + if (isSameDate(_currentDate, _controller.displayDate) || + isDateWithInDateRange( + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - + 1], + _controller.displayDate, + )) { + _removeDatePicker(); + } - _showHeader = false; - _controller.displayDate = DateTime( - details.value.year, - details.value.month, - details.value.day, - _controller.displayDate!.hour, - _controller.displayDate!.minute, - _controller.displayDate!.second); - }, - )))); + _showHeader = false; + _controller.displayDate = DateTime( + details.value.year, + details.value.month, + details.value.day, + _controller.displayDate!.hour, + _controller.displayDate!.minute, + _controller.displayDate!.second, + ); + }, + ), + ), + ), + ); } void _getCalendarStateDetails(UpdateCalendarStateDetails details) { @@ -8881,7 +9906,8 @@ class _SfCalendarState extends State if (details.currentDate != null && !isSameDate(details.currentDate, _currentDate)) { _currentDate = DateTimeHelper.getDateTimeValue( - getValidDate(widget.minDate, widget.maxDate, details.currentDate)); + getValidDate(widget.minDate, widget.maxDate, details.currentDate), + ); _canScrollTimeSlotView = false; _controller.displayDate = _currentDate; _canScrollTimeSlotView = true; @@ -8896,11 +9922,13 @@ class _SfCalendarState extends State _isNeedLoadMore = widget.loadMoreWidgetBuilder != null; _updateVisibleAppointments(); if (CalendarViewHelper.shouldRaiseViewChangedCallback( - widget.onViewChanged)) { + widget.onViewChanged, + )) { final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - widget.monthViewSettings.numberOfWeeksInView, - widget.monthViewSettings.showTrailingAndLeadingDates); + widget.monthViewSettings.numberOfWeeksInView, + widget.monthViewSettings.showTrailingAndLeadingDates, + ); List visibleDates = _currentViewVisibleDates; if (!showTrailingLeadingDates) { visibleDates = DateTimeHelper.getCurrentMonthDates(visibleDates); @@ -8911,7 +9939,9 @@ class _SfCalendarState extends State } if (!CalendarViewHelper.isSameTimeSlot( - details.selectedDate, _selectedDate)) { + details.selectedDate, + _selectedDate, + )) { _selectedDate = details.selectedDate; _controller.selectedDate = details.selectedDate; } @@ -8926,7 +9956,12 @@ class _SfCalendarState extends State } CalendarViewHelper.raiseCalendarTapCallback( - widget, _getTappedHeaderDate(), null, CalendarElement.header, null); + widget, + _getTappedHeaderDate(), + null, + CalendarElement.header, + null, + ); } //// Handles the on long press callback for header @@ -8934,12 +9969,18 @@ class _SfCalendarState extends State _calendarViewWidth = width; _updateDatePicker(); if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress)) { + widget.onLongPress, + )) { return; } CalendarViewHelper.raiseCalendarLongPressCallback( - widget, _getTappedHeaderDate(), null, CalendarElement.header, null); + widget, + _getTappedHeaderDate(), + null, + CalendarElement.header, + null, + ); } DateTime _getTappedHeaderDate() { @@ -8966,22 +10007,27 @@ class _SfCalendarState extends State return; } - final List selectedAppointments = - _getSelectedAppointments(details.localPosition, selectedDate); + final List selectedAppointments = _getSelectedAppointments( + details.localPosition, + selectedDate, + ); CalendarViewHelper.raiseCalendarTapCallback( - widget, - selectedDate, - selectedAppointments, - selectedAppointments.isNotEmpty - ? CalendarElement.appointment - : CalendarElement.agenda, - null); + widget, + selectedDate, + selectedAppointments, + selectedAppointments.isNotEmpty + ? CalendarElement.appointment + : CalendarElement.agenda, + null, + ); } //// Handles the onLongPress callback for agenda view. void _handleLongPressForAgenda( - LongPressStartDetails details, DateTime? selectedDate) { + LongPressStartDetails details, + DateTime? selectedDate, + ) { _removeDatePicker(); if (widget.allowViewNavigation && ((!_isRTL && details.localPosition.dx < _agendaDateViewWidth) || @@ -8992,25 +10038,31 @@ class _SfCalendarState extends State } if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.onLongPress)) { + widget.onLongPress, + )) { return; } - final List selectedAppointments = - _getSelectedAppointments(details.localPosition, selectedDate); + final List selectedAppointments = _getSelectedAppointments( + details.localPosition, + selectedDate, + ); CalendarViewHelper.raiseCalendarLongPressCallback( - widget, - selectedDate, - selectedAppointments, - selectedAppointments.isNotEmpty - ? CalendarElement.appointment - : CalendarElement.agenda, - null); + widget, + selectedDate, + selectedAppointments, + selectedAppointments.isNotEmpty + ? CalendarElement.appointment + : CalendarElement.agenda, + null, + ); } List _getSelectedAppointments( - Offset localPosition, DateTime? selectedDate) { + Offset localPosition, + DateTime? selectedDate, + ) { /// Return empty collection while tap the agenda view with no selected date. if (selectedDate == null) { return []; @@ -9024,7 +10076,10 @@ class _SfCalendarState extends State List agendaAppointments = AppointmentHelper.getSelectedDateAppointments( - _appointments, widget.timeZone, selectedDate); + _appointments, + widget.timeZone, + selectedDate, + ); /// Return empty collection while tap the agenda view does /// not have appointments. @@ -9033,16 +10088,23 @@ class _SfCalendarState extends State } agendaAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); agendaAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isAllDay, + app2.isAllDay, + ), + ); agendaAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isSpanned, + app2.isSpanned, + ), + ); int index = -1; //// Agenda appointment view top padding as 5. @@ -9052,15 +10114,20 @@ class _SfCalendarState extends State _agendaScrollController!.offset + localPosition.dy; final double actualAppointmentHeight = CalendarViewHelper.getScheduleAppointmentHeight( - widget.monthViewSettings, null); + widget.monthViewSettings, + null, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - widget.monthViewSettings, null); + widget.monthViewSettings, + null, + ); for (int i = 0; i < agendaAppointments.length; i++) { final CalendarAppointment appointment = agendaAppointments[i]; - final double appointmentHeight = _isAllDayAppointmentView(appointment) - ? allDayAppointmentHeight - : actualAppointmentHeight; + final double appointmentHeight = + _isAllDayAppointmentView(appointment) + ? allDayAppointmentHeight + : actualAppointmentHeight; if (tappedYPosition >= xPosition && tappedYPosition < xPosition + appointmentHeight + padding) { index = i; @@ -9080,7 +10147,9 @@ class _SfCalendarState extends State if (widget.dataSource != null && !AppointmentHelper.isCalendarAppointment(widget.dataSource!)) { return CalendarViewHelper.getCustomAppointments( - agendaAppointments, widget.dataSource); + agendaAppointments, + widget.dataSource, + ); } return agendaAppointments; @@ -9088,7 +10157,11 @@ class _SfCalendarState extends State // Returns the agenda view as a child for the calendar. Widget _addAgendaView( - double height, double startPosition, double width, bool isRTL) { + double height, + double startPosition, + double width, + bool isRTL, + ) { if (_view != CalendarView.month || !widget.monthViewSettings.showAgenda) { return Positioned( left: 0, @@ -9103,70 +10176,90 @@ class _SfCalendarState extends State /// disabled or black out date. DateTime? currentSelectedDate; if (_selectedDate != null) { - currentSelectedDate = isDateWithInDateRange( - widget.minDate, widget.maxDate, _selectedDate) && - !CalendarViewHelper.isDateInDateCollection( - _blackoutDates, _selectedDate!) - ? _selectedDate - : null; + currentSelectedDate = + isDateWithInDateRange( + widget.minDate, + widget.maxDate, + _selectedDate, + ) && + !CalendarViewHelper.isDateInDateCollection( + _blackoutDates, + _selectedDate!, + ) + ? _selectedDate + : null; } if (currentSelectedDate == null) { return Positioned( - top: startPosition, - right: 0, - left: 0, - height: height, - child: _OpacityWidget( - opacity: _opacity, - child: Container( - color: widget.monthViewSettings.agendaStyle.backgroundColor ?? - _calendarTheme.agendaBackgroundColor, - child: GestureDetector( - child: AgendaViewLayout( - widget.monthViewSettings, - null, - currentSelectedDate, - null, - isRTL, - _locale, - _localizations, - _calendarTheme, - _themeData, - _agendaViewNotifier, - widget.appointmentTimeTextFormat, - 0, - _textScaleFactor, - _isMobilePlatform, - widget.appointmentBuilder, - width, - height, - widget - .monthViewSettings.agendaStyle.placeholderTextStyle, - widget), - onTapUp: (TapUpDetails details) { - _handleTapForAgenda(details, null); - }, - onLongPressStart: (LongPressStartDetails details) { - _handleLongPressForAgenda(details, null); - }, - )))); + top: startPosition, + right: 0, + left: 0, + height: height, + child: _OpacityWidget( + opacity: _opacity, + child: Container( + color: + widget.monthViewSettings.agendaStyle.backgroundColor ?? + _calendarTheme.agendaBackgroundColor, + child: GestureDetector( + child: AgendaViewLayout( + widget.monthViewSettings, + null, + currentSelectedDate, + null, + isRTL, + _locale, + _localizations, + _calendarTheme, + _themeData, + _agendaViewNotifier, + widget.appointmentTimeTextFormat, + 0, + _textScaleFactor, + _isMobilePlatform, + widget.appointmentBuilder, + width, + height, + widget.monthViewSettings.agendaStyle.placeholderTextStyle, + widget, + ), + onTapUp: (TapUpDetails details) { + _handleTapForAgenda(details, null); + }, + onLongPressStart: (LongPressStartDetails details) { + _handleLongPressForAgenda(details, null); + }, + ), + ), + ), + ); } final List agendaAppointments = AppointmentHelper.getSelectedDateAppointments( - _appointments, widget.timeZone, currentSelectedDate); + _appointments, + widget.timeZone, + currentSelectedDate, + ); agendaAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - app1.actualStartTime.compareTo(app2.actualStartTime)); + (CalendarAppointment app1, CalendarAppointment app2) => + app1.actualStartTime.compareTo(app2.actualStartTime), + ); agendaAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isAllDay, app2.isAllDay)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isAllDay, + app2.isAllDay, + ), + ); agendaAppointments.sort( - (CalendarAppointment app1, CalendarAppointment app2) => - AppointmentHelper.orderAppointmentsAscending( - app1.isSpanned, app2.isSpanned)); + (CalendarAppointment app1, CalendarAppointment app2) => + AppointmentHelper.orderAppointmentsAscending( + app1.isSpanned, + app2.isSpanned, + ), + ); /// Each appointment have top padding and it used to show the space /// between two appointment views @@ -9177,98 +10270,114 @@ class _SfCalendarState extends State const double bottomPadding = 5; final double appointmentHeight = CalendarViewHelper.getScheduleAppointmentHeight( - widget.monthViewSettings, null); + widget.monthViewSettings, + null, + ); final double allDayAppointmentHeight = CalendarViewHelper.getScheduleAllDayAppointmentHeight( - widget.monthViewSettings, null); + widget.monthViewSettings, + null, + ); double painterHeight = height; if (agendaAppointments.isNotEmpty) { final int count = _getAllDayCount(agendaAppointments); - painterHeight = ((count * (allDayAppointmentHeight + topPadding)) + + painterHeight = + ((count * (allDayAppointmentHeight + topPadding)) + ((agendaAppointments.length - count) * (appointmentHeight + topPadding))) + bottomPadding; } return Positioned( - top: startPosition, - right: 0, - left: 0, - height: height, - child: _OpacityWidget( - opacity: _opacity, - child: Container( - color: widget.monthViewSettings.agendaStyle.backgroundColor ?? - _calendarTheme.agendaBackgroundColor, - child: MouseRegion( - onEnter: (PointerEnterEvent event) { - _pointerEnterEvent(event, false, isRTL); - }, - onExit: _pointerExitEvent, - onHover: (PointerHoverEvent event) { - _pointerHoverEvent(event, false, isRTL); - }, - child: GestureDetector( - child: Stack(children: [ - CustomPaint( - painter: _AgendaDateTimePainter( - currentSelectedDate, - widget.monthViewSettings, - null, - widget.todayHighlightColor ?? - _calendarTheme.todayHighlightColor, - widget.todayTextStyle, - _locale, - _calendarTheme, - _themeData, - _agendaDateNotifier, - _minWidth, - isRTL, - _textScaleFactor, - _isMobilePlatform), - size: Size(_agendaDateViewWidth, height), - ), - Positioned( - top: 0, - left: isRTL ? 0 : _agendaDateViewWidth, - right: isRTL ? _agendaDateViewWidth : 0, - bottom: 0, - child: ListView( - padding: EdgeInsets.zero, - controller: _agendaScrollController, - children: [ - AgendaViewLayout( - widget.monthViewSettings, - null, - currentSelectedDate, - agendaAppointments, - isRTL, - _locale, - _localizations, - _calendarTheme, - _themeData, - _agendaViewNotifier, - widget.appointmentTimeTextFormat, - _agendaDateViewWidth, - _textScaleFactor, - _isMobilePlatform, - widget.appointmentBuilder, - width - _agendaDateViewWidth, - painterHeight, - widget.monthViewSettings.agendaStyle - .placeholderTextStyle, - widget), - ], - ), + top: startPosition, + right: 0, + left: 0, + height: height, + child: _OpacityWidget( + opacity: _opacity, + child: Container( + color: + widget.monthViewSettings.agendaStyle.backgroundColor ?? + _calendarTheme.agendaBackgroundColor, + child: MouseRegion( + onEnter: (PointerEnterEvent event) { + _pointerEnterEvent(event, false, isRTL); + }, + onExit: _pointerExitEvent, + onHover: (PointerHoverEvent event) { + _pointerHoverEvent(event, false, isRTL); + }, + child: GestureDetector( + child: Stack( + children: [ + CustomPaint( + painter: _AgendaDateTimePainter( + currentSelectedDate, + widget.monthViewSettings, + null, + widget.todayHighlightColor ?? + _calendarTheme.todayHighlightColor, + widget.todayTextStyle, + _locale, + _calendarTheme, + _themeData, + _agendaDateNotifier, + _minWidth, + isRTL, + _textScaleFactor, + _isMobilePlatform, + ), + size: Size(_agendaDateViewWidth, height), + ), + Positioned( + top: 0, + left: isRTL ? 0 : _agendaDateViewWidth, + right: isRTL ? _agendaDateViewWidth : 0, + bottom: 0, + child: ListView( + padding: EdgeInsets.zero, + controller: _agendaScrollController, + children: [ + AgendaViewLayout( + widget.monthViewSettings, + null, + currentSelectedDate, + agendaAppointments, + isRTL, + _locale, + _localizations, + _calendarTheme, + _themeData, + _agendaViewNotifier, + widget.appointmentTimeTextFormat, + _agendaDateViewWidth, + _textScaleFactor, + _isMobilePlatform, + widget.appointmentBuilder, + width - _agendaDateViewWidth, + painterHeight, + widget + .monthViewSettings + .agendaStyle + .placeholderTextStyle, + widget, ), - ]), - onTapUp: (TapUpDetails details) { - _handleTapForAgenda(details, _selectedDate); - }, - onLongPressStart: (LongPressStartDetails details) { - _handleLongPressForAgenda(details, _selectedDate); - }, - ))))); + ], + ), + ), + ], + ), + onTapUp: (TapUpDetails details) { + _handleTapForAgenda(details, _selectedDate); + }, + onLongPressStart: (LongPressStartDetails details) { + _handleLongPressForAgenda(details, _selectedDate); + }, + ), + ), + ), + ), + ); } } @@ -9319,8 +10428,10 @@ class _OpacityWidgetState extends State<_OpacityWidget> { /// Widget used to show the pop up animation to the child. class _PopupWidget extends StatefulWidget { - const _PopupWidget( - {required this.child, this.alignment = Alignment.topCenter}); + const _PopupWidget({ + required this.child, + this.alignment = Alignment.topCenter, + }); /// Widget that animated like popup. final Widget child; @@ -9343,9 +10454,13 @@ class _PopupWidgetState extends State<_PopupWidget> @override void initState() { _animationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 200)); - _animation = - CurvedAnimation(parent: _animationController, curve: Curves.easeInOut); + vsync: this, + duration: const Duration(milliseconds: 200), + ); + _animation = CurvedAnimation( + parent: _animationController, + curve: Curves.easeInOut, + ); super.initState(); } @@ -9363,53 +10478,55 @@ class _PopupWidgetState extends State<_PopupWidget> /// Start the animation. _animationController.forward(); return ScaleTransition( - alignment: widget.alignment, - scale: _animation, - child: FadeTransition(opacity: _animation, child: widget.child)); + alignment: widget.alignment, + scale: _animation, + child: FadeTransition(opacity: _animation, child: widget.child), + ); } } @immutable class _CalendarHeaderView extends StatefulWidget { const _CalendarHeaderView( - this.visibleDates, - this.headerStyle, - this.currentDate, - this.view, - this.numberOfWeeksInView, - this.calendarTheme, - this.isRTL, - this.locale, - this.showNavigationArrow, - this.controller, - this.maxDate, - this.minDate, - this.width, - this.height, - this.nonWorkingDays, - this.navigationDirection, - this.showDatePickerButton, - this.showTodayButton, - this.isPickerShown, - this.allowedViews, - this.allowViewNavigation, - this.localizations, - this.removePicker, - this.valueChangeNotifier, - this.viewChangeNotifier, - this.headerTapCallback, - this.headerLongPressCallback, - this.todayHighlightColor, - this.textScaleFactor, - this.isMobilePlatform, - this.headerDateFormat, - this.enableInteraction, - this.todayTextStyle, - this.showWeekNumber, - this.weekNumberStyle, - this.timelineMonthWeekNumberNotifier, - this.cellBorderColor, - this.numberOfDaysInView); + this.visibleDates, + this.headerStyle, + this.currentDate, + this.view, + this.numberOfWeeksInView, + this.calendarTheme, + this.isRTL, + this.locale, + this.showNavigationArrow, + this.controller, + this.maxDate, + this.minDate, + this.width, + this.height, + this.nonWorkingDays, + this.navigationDirection, + this.showDatePickerButton, + this.showTodayButton, + this.isPickerShown, + this.allowedViews, + this.allowViewNavigation, + this.localizations, + this.removePicker, + this.valueChangeNotifier, + this.viewChangeNotifier, + this.headerTapCallback, + this.headerLongPressCallback, + this.todayHighlightColor, + this.textScaleFactor, + this.isMobilePlatform, + this.headerDateFormat, + this.enableInteraction, + this.todayTextStyle, + this.showWeekNumber, + this.weekNumberStyle, + this.timelineMonthWeekNumberNotifier, + this.cellBorderColor, + this.numberOfDaysInView, + ); final List visibleDates; final TextStyle? todayTextStyle; @@ -9460,8 +10577,9 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { @override void initState() { widget.valueChangeNotifier.addListener(_updateHeaderChanged); - widget.timelineMonthWeekNumberNotifier - .addListener(_updateWeekNumberChangedForTimelineMonth); + widget.timelineMonthWeekNumberNotifier.addListener( + _updateWeekNumberChangedForTimelineMonth, + ); _calendarViews = _getCalendarViewsText(widget.localizations); super.initState(); } @@ -9475,10 +10593,12 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { if (widget.timelineMonthWeekNumberNotifier != oldWidget.timelineMonthWeekNumberNotifier) { - oldWidget.timelineMonthWeekNumberNotifier - .removeListener(_updateWeekNumberChangedForTimelineMonth); - widget.timelineMonthWeekNumberNotifier - .addListener(_updateWeekNumberChangedForTimelineMonth); + oldWidget.timelineMonthWeekNumberNotifier.removeListener( + _updateWeekNumberChangedForTimelineMonth, + ); + widget.timelineMonthWeekNumberNotifier.addListener( + _updateWeekNumberChangedForTimelineMonth, + ); } _calendarViews = _getCalendarViewsText(widget.localizations); @@ -9488,7 +10608,9 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { @override Widget build(BuildContext context) { final bool useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( - widget.width, widget.isMobilePlatform); + widget.width, + widget.isMobilePlatform, + ); double arrowWidth = 0; double headerWidth = widget.width; @@ -9520,16 +10642,18 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { final List children = []; final Color headerTextColor = widget.calendarTheme.headerTextStyle!.color ?? Colors.black87; - final Color headerBackgroundColor = widget.headerStyle.backgroundColor ?? + final Color headerBackgroundColor = + widget.headerStyle.backgroundColor ?? widget.calendarTheme.headerBackgroundColor!; - final Color arrowColor = - headerTextColor.withValues(alpha: headerTextColor.a * 0.6); + final Color arrowColor = headerTextColor.withValues( + alpha: headerTextColor.a * 0.6, + ); Color prevArrowColor = arrowColor; Color nextArrowColor = arrowColor; final TextStyle style = TextStyle(color: arrowColor); const double defaultCalendarViewTextSize = 12; Widget calendarViewIcon = const SizedBox(width: 0, height: 0); - const double padding = 5; + const double padding = 8; final double headerIconTextWidth = widget.calendarTheme.headerTextStyle!.fontSize ?? 14; final String todayText = widget.localizations.todayLabel; @@ -9543,8 +10667,12 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { if (!useMobilePlatformUI) { /// 5 as padding for around today text view. final Size todayButtonSize = _getTextWidgetWidth( - todayText, widget.height, widget.width - totalArrowWidth, context, - style: const TextStyle(fontSize: defaultCalendarViewTextSize)); + todayText, + widget.height, + widget.width - totalArrowWidth, + context, + style: const TextStyle(fontSize: defaultCalendarViewTextSize), + ); maxHeaderHeight = todayButtonSize.height + allowedViewsPadding; todayIconWidth = todayButtonSize.width + allowedViewsPadding; } @@ -9557,43 +10685,49 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { final Color? weekNumberBackgroundColor = widget.weekNumberStyle.backgroundColor ?? - widget.calendarTheme.weekNumberBackgroundColor; + widget.calendarTheme.weekNumberBackgroundColor; - final bool weekNumberEnabled = widget.showWeekNumber && + final bool weekNumberEnabled = + widget.showWeekNumber && (widget.view == CalendarView.day || isTimelineView); if (!widget.isMobilePlatform || (widget.isMobilePlatform && weekNumberEnabled)) { final Size headerTextSize = _getTextWidgetWidth( - headerString, - widget.height, - widget.width - totalArrowWidth - todayIconWidth - padding, - context, - style: widget.calendarTheme.headerTextStyle); + headerString, + widget.height, + widget.width - totalArrowWidth - todayIconWidth - padding, + context, + style: widget.calendarTheme.headerTextStyle, + ); - headerTextWidth = headerTextSize.width + + headerTextWidth = + headerTextSize.width + padding + (widget.showDatePickerButton ? headerIconTextWidth : 0); - maxHeaderHeight = maxHeaderHeight > headerTextSize.height - ? maxHeaderHeight - : headerTextSize.height; + maxHeaderHeight = + maxHeaderHeight > headerTextSize.height + ? maxHeaderHeight + : headerTextSize.height; } if (weekNumberEnabled) { final Size weekNumberPanelSize = _getTextWidgetWidth( - '${widget.localizations.weeknumberLabel}$weekNumberString ', - widget.height, - widget.width, - context, - style: weekNumberTextStyle); + '${widget.localizations.weeknumberLabel}$weekNumberString ', + widget.height, + widget.width, + context, + style: weekNumberTextStyle, + ); weekNumberTextWidth = weekNumberPanelSize.width + padding; weekNumberPanelWidth = weekNumberTextWidth; weekNumberPanelHeight = weekNumberPanelSize.height; } final Color? highlightColor = CalendarViewHelper.getTodayHighlightTextColor( - widget.todayHighlightColor ?? widget.calendarTheme.todayHighlightColor, - widget.todayTextStyle, - widget.calendarTheme); + widget.todayHighlightColor ?? widget.calendarTheme.todayHighlightColor, + widget.todayTextStyle, + widget.calendarTheme, + ); if (isNeedViewSwitchOption) { calendarViewWidth = iconWidth; @@ -9605,25 +10739,27 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { /// Render allowed views icon on mobile view. calendarViewIcon = _getCalendarViewWidget( - headerBackgroundColor, - useMobilePlatformUI, - false, - calendarViewWidth, - maxHeaderHeight, - style, - arrowColor, - headerTextColor, - widget.view, - // ignore: avoid_bool_literals_in_conditional_expressions - widget.isMobilePlatform ? false : widget.viewChangeNotifier.value, - highlightColor, - defaultCalendarViewTextSize, - semanticLabel: 'CalendarView'); + headerBackgroundColor, + useMobilePlatformUI, + false, + calendarViewWidth, + maxHeaderHeight, + style, + arrowColor, + headerTextColor, + widget.view, + // ignore: avoid_bool_literals_in_conditional_expressions + widget.isMobilePlatform ? false : widget.viewChangeNotifier.value, + highlightColor, + defaultCalendarViewTextSize, + semanticLabel: 'CalendarView', + ); } else { /// Assign divider width when today icon text shown. dividerWidth = widget.showTodayButton ? 10 : 0; - final double totalWidth = widget.width - + final double totalWidth = + widget.width - totalArrowWidth - dividerWidth - todayIconWidth - @@ -9641,8 +10777,12 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { for (int i = 0; i < allowedViewsLength; i++) { final CalendarView currentView = widget.allowedViews![i]; final Size calendarViewSize = _getTextWidgetWidth( - _calendarViews[currentView]!, widget.height, totalWidth, context, - style: const TextStyle(fontSize: defaultCalendarViewTextSize)); + _calendarViews[currentView]!, + widget.height, + totalWidth, + context, + style: const TextStyle(fontSize: defaultCalendarViewTextSize), + ); final double currentViewTextWidth = calendarViewSize.width + allowedViewsPadding; maxCalendarViewHeight = @@ -9657,14 +10797,16 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { /// render the allowed views as children. if (allowedViewsWidth < totalWidth) { calendarViewWidth = allowedViewsWidth; - maxHeaderHeight = maxCalendarViewHeight > maxHeaderHeight - ? maxCalendarViewHeight - : maxHeaderHeight; + maxHeaderHeight = + maxCalendarViewHeight > maxHeaderHeight + ? maxCalendarViewHeight + : maxHeaderHeight; maxHeaderHeight = maxHeaderHeight > widget.height ? widget.height : maxHeaderHeight; for (int i = 0; i < allowedViewsLength; i++) { final CalendarView currentView = widget.allowedViews![i]; - children.add(_getCalendarViewWidget( + children.add( + _getCalendarViewWidget( headerBackgroundColor, useMobilePlatformUI, false, @@ -9676,27 +10818,33 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { currentView, widget.view == currentView, highlightColor, - defaultCalendarViewTextSize)); + defaultCalendarViewTextSize, + ), + ); } } else { /// Render allowed views drop down when header view does not have a /// space to hold the allowed views. final Size calendarViewSize = _getTextWidgetWidth( - _calendarViews[widget.view]!, - widget.height, - widget.width - totalArrowWidth, - context, - style: const TextStyle(fontSize: defaultCalendarViewTextSize)); + _calendarViews[widget.view]!, + widget.height, + widget.width - totalArrowWidth, + context, + style: const TextStyle(fontSize: defaultCalendarViewTextSize), + ); maxCalendarViewHeight = calendarViewSize.height + allowedViewsPadding; - maxHeaderHeight = maxCalendarViewHeight > maxHeaderHeight - ? maxCalendarViewHeight - : maxHeaderHeight; + maxHeaderHeight = + maxCalendarViewHeight > maxHeaderHeight + ? maxCalendarViewHeight + : maxHeaderHeight; maxHeaderHeight = maxHeaderHeight > widget.height ? widget.height : maxHeaderHeight; - calendarViewWidth = calendarViewSize.width + + calendarViewWidth = + calendarViewSize.width + allowedViewsPadding + headerIconTextWidth; - children.add(_getCalendarViewWidget( + children.add( + _getCalendarViewWidget( headerBackgroundColor, useMobilePlatformUI, true, @@ -9709,7 +10857,9 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { widget.viewChangeNotifier.value, highlightColor, defaultCalendarViewTextSize, - semanticLabel: 'CalendarView')); + semanticLabel: 'CalendarView', + ), + ); } } } @@ -9724,7 +10874,8 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { /// because the week number panel occupies the empty space to align the /// today button and calendar view button on right side end. headerWidth = headerTextWidth; - final double remainingWidth = widget.width - + final double remainingWidth = + widget.width - calendarViewWidth - todayIconWidth - dividerWidth - @@ -9746,7 +10897,8 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { /// Assign the header panel width is available space other than /// calendar view button width, today button, arrows width to align the /// today button and calendar view button on right side end. - headerWidth = widget.width - + headerWidth = + widget.width - calendarViewWidth - todayIconWidth - dividerWidth - @@ -9755,22 +10907,24 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { final List dates = widget.visibleDates; if (!DateTimeHelper.canMoveToNextView( - widget.view, - widget.numberOfWeeksInView, - widget.minDate, - widget.maxDate, - dates, - widget.nonWorkingDays)) { + widget.view, + widget.numberOfWeeksInView, + widget.minDate, + widget.maxDate, + dates, + widget.nonWorkingDays, + )) { nextArrowColor = nextArrowColor.withValues(alpha: nextArrowColor.a * 0.5); } if (!DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.numberOfWeeksInView, - widget.minDate, - widget.maxDate, - dates, - widget.nonWorkingDays)) { + widget.view, + widget.numberOfWeeksInView, + widget.minDate, + widget.maxDate, + dates, + widget.nonWorkingDays, + )) { prevArrowColor = prevArrowColor.withValues(alpha: prevArrowColor.a * 0.5); } @@ -9790,7 +10944,8 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { headerHeight == widget.height ? headerHeight * 0.6 : headerHeight * 0.8; arrowSize = arrowSize > 25 ? 25 : arrowSize; arrowSize = arrowSize * widget.textScaleFactor; - final bool isCenterAlignment = !widget.isMobilePlatform && + final bool isCenterAlignment = + !widget.isMobilePlatform && (navigationArrowEnabled || isNeedViewSwitchOption) && (widget.headerStyle.textAlign == TextAlign.center || widget.headerStyle.textAlign == TextAlign.justify); @@ -9812,14 +10967,15 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { ? Colors.transparent : null; final TextStyle headerTextStyle = widget.calendarTheme.headerTextStyle!; - final Widget headerText = widget.isMobilePlatform - ? Container( - alignment: Alignment.center, - color: headerBackgroundColor, - width: isCenterAlignment && headerWidth > 200 ? 200 : headerWidth, - height: headerHeight, - padding: const EdgeInsets.all(2), - child: Material( + final Widget headerText = + widget.isMobilePlatform + ? Container( + alignment: Alignment.center, + color: headerBackgroundColor, + width: isCenterAlignment && headerWidth > 200 ? 200 : headerWidth, + height: headerHeight, + padding: const EdgeInsets.all(2), + child: Material( color: headerBackgroundColor, child: InkWell( //// set splash color as transparent when header does not have @@ -9833,70 +10989,83 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { return; } widget.headerTapCallback( - calendarViewWidth + dividerWidth + todayIconWidth); + calendarViewWidth + dividerWidth + todayIconWidth, + ); }, onLongPress: () { if (!widget.enableInteraction) { return; } widget.headerLongPressCallback( - calendarViewWidth + dividerWidth + todayIconWidth); + calendarViewWidth + dividerWidth + todayIconWidth, + ); }, child: Container( - clipBehavior: Clip.antiAlias, - decoration: const BoxDecoration( - color: Colors.transparent, - ), - width: isCenterAlignment && headerWidth > 200 - ? 200 - : headerWidth, - height: headerHeight, - alignment: Alignment.centerLeft, - padding: const EdgeInsets.symmetric(horizontal: 5), - child: Row( - mainAxisAlignment: getAlignmentFromTextAlign(), - children: widget.showDatePickerButton + clipBehavior: Clip.antiAlias, + decoration: const BoxDecoration(color: Colors.transparent), + width: + isCenterAlignment && headerWidth > 200 + ? 200 + : headerWidth, + height: headerHeight, + alignment: Alignment.centerLeft, + padding: const EdgeInsets.symmetric(horizontal: 5), + child: Row( + mainAxisAlignment: getAlignmentFromTextAlign(), + children: + widget.showDatePickerButton ? [ - Flexible( - child: Text(headerString, - style: headerTextStyle, - maxLines: 1, - semanticsLabel: - // ignore: lines_longer_than_80_chars - '$headerString ${widget.isPickerShown ? 'hide date picker' : 'show date picker'}', - overflow: TextOverflow.clip, - softWrap: false, - textDirection: CalendarViewHelper - .getTextDirectionBasedOnLocale( - widget.locale))), - Icon( - widget.isPickerShown - ? Icons.arrow_drop_up - : Icons.arrow_drop_down, - color: arrowColor, - size: headerTextStyle.fontSize ?? 14, + Flexible( + child: Text( + headerString, + style: headerTextStyle, + maxLines: 1, + semanticsLabel: + // ignore: lines_longer_than_80_chars + '$headerString ${widget.isPickerShown ? 'hide date picker' : 'show date picker'}', + overflow: TextOverflow.clip, + softWrap: false, + textDirection: + CalendarViewHelper.getTextDirectionBasedOnLocale( + widget.locale, + ), ), - ] + ), + Icon( + widget.isPickerShown + ? Icons.arrow_drop_up + : Icons.arrow_drop_down, + color: arrowColor, + size: headerTextStyle.fontSize ?? 14, + ), + ] : [ - Flexible( - child: Text(headerString, - style: headerTextStyle, - maxLines: 1, - overflow: TextOverflow.clip, - softWrap: false, - textDirection: CalendarViewHelper - .getTextDirectionBasedOnLocale( - widget.locale))) - ])), - )), - ) - : Container( - alignment: getHeaderAlignment(), - color: headerBackgroundColor, - width: isCenterAlignment && headerWidth > 200 ? 200 : headerWidth, - height: headerHeight, - padding: const EdgeInsets.all(2), - child: Material( + Flexible( + child: Text( + headerString, + style: headerTextStyle, + maxLines: 1, + overflow: TextOverflow.clip, + softWrap: false, + textDirection: + CalendarViewHelper.getTextDirectionBasedOnLocale( + widget.locale, + ), + ), + ), + ], + ), + ), + ), + ), + ) + : Container( + alignment: getHeaderAlignment(), + color: headerBackgroundColor, + width: isCenterAlignment && headerWidth > 200 ? 200 : headerWidth, + height: headerHeight, + padding: const EdgeInsets.all(2), + child: Material( color: headerBackgroundColor, child: InkWell( //// set splash color as transparent when header does not have @@ -9909,49 +11078,57 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { return; } widget.headerTapCallback( - calendarViewWidth + dividerWidth + todayIconWidth); + calendarViewWidth + dividerWidth + todayIconWidth, + ); }, onLongPress: () { if (!widget.enableInteraction) { return; } widget.headerLongPressCallback( - calendarViewWidth + dividerWidth + todayIconWidth); + calendarViewWidth + dividerWidth + todayIconWidth, + ); }, child: Container( - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration( - color: - widget.showDatePickerButton && widget.isPickerShown - ? Colors.grey.withValues(alpha: 0.3) - : headerBackgroundColor, - ), + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: + widget.showDatePickerButton && widget.isPickerShown + ? Colors.grey.withValues(alpha: 0.3) + : headerBackgroundColor, + ), - /// Padding value is from parent container padding - /// value const EdgeInsets.all(2). - width: (isCenterAlignment && headerTextWidth > 200 - ? 200 - : headerTextWidth) - - padding, - height: headerHeight, - alignment: Alignment.center, - padding: const EdgeInsets.symmetric(horizontal: 5), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: widget.showDatePickerButton - ? [ + /// Padding value is from parent container padding + /// value const EdgeInsets.all(2). + width: + (isCenterAlignment && headerTextWidth > 200 + ? 200 + : headerTextWidth) - + padding, + height: headerHeight, + alignment: Alignment.center, + padding: const EdgeInsets.symmetric(horizontal: 5), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: + widget.showDatePickerButton + ? [ Flexible( - child: Text(headerString, - style: headerTextStyle, - maxLines: 1, - semanticsLabel: - // ignore: lines_longer_than_80_chars - '$headerString ${widget.isPickerShown ? 'hide date picker' : 'show date picker'}', - overflow: TextOverflow.clip, - softWrap: false, - textDirection: CalendarViewHelper - .getTextDirectionBasedOnLocale( - widget.locale))), + child: Text( + headerString, + style: headerTextStyle, + maxLines: 1, + semanticsLabel: + // ignore: lines_longer_than_80_chars + '$headerString ${widget.isPickerShown ? 'hide date picker' : 'show date picker'}', + overflow: TextOverflow.clip, + softWrap: false, + textDirection: + CalendarViewHelper.getTextDirectionBasedOnLocale( + widget.locale, + ), + ), + ), Icon( widget.isPickerShown ? Icons.arrow_drop_up @@ -9960,71 +11137,86 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { size: headerTextStyle.fontSize ?? 14, ), ] - : [ + : [ Flexible( - child: Text(headerString, - style: headerTextStyle, - maxLines: 1, - overflow: TextOverflow.clip, - softWrap: false, - textDirection: CalendarViewHelper - .getTextDirectionBasedOnLocale( - widget.locale))), + child: Text( + headerString, + style: headerTextStyle, + maxLines: 1, + overflow: TextOverflow.clip, + softWrap: false, + textDirection: + CalendarViewHelper.getTextDirectionBasedOnLocale( + widget.locale, + ), + ), + ), ], - )), - )), - ); + ), + ), + ), + ), + ); - final Widget weekNumberWidget = weekNumberEnabled - ? Container( - width: - isCenterAlignment ? weekNumberTextWidth : weekNumberPanelWidth, - height: weekNumberPanelHeight, - alignment: getHeaderAlignment(), - child: Container( + final Widget weekNumberWidget = + weekNumberEnabled + ? Container( + width: + isCenterAlignment + ? weekNumberTextWidth + : weekNumberPanelWidth, + height: weekNumberPanelHeight, + alignment: getHeaderAlignment(), + child: Container( decoration: BoxDecoration( - borderRadius: - const BorderRadius.all(Radius.circular(padding)), - color: weekNumberBackgroundColor), + borderRadius: const BorderRadius.all( + Radius.circular(padding), + ), + color: weekNumberBackgroundColor, + ), alignment: Alignment.center, width: weekNumberTextWidth, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Flexible( - child: Text( - widget.localizations.weeknumberLabel, - textAlign: TextAlign.center, - textScaler: TextScaler.linear(widget.textScaleFactor), - style: weekNumberTextStyle, - overflow: TextOverflow.ellipsis, - maxLines: 1, - )), + child: Text( + widget.localizations.weeknumberLabel, + textAlign: TextAlign.center, + textScaler: TextScaler.linear(widget.textScaleFactor), + style: weekNumberTextStyle, + overflow: TextOverflow.ellipsis, + maxLines: 1, + ), + ), Flexible( - child: Text( - ' $weekNumberString', - textAlign: TextAlign.center, - style: weekNumberTextStyle, - textScaler: TextScaler.linear(widget.textScaleFactor), - maxLines: 1, - )) + child: Text( + ' $weekNumberString', + textAlign: TextAlign.center, + style: weekNumberTextStyle, + textScaler: TextScaler.linear(widget.textScaleFactor), + maxLines: 1, + ), + ), ], - )), - ) - : Container(); + ), + ), + ) + : Container(); final Color? leftArrowSplashColor = prevArrowColor != arrowColor || !widget.enableInteraction ? Colors.transparent : null; - final Container leftArrow = navigationArrowEnabled - ? Container( - alignment: Alignment.center, - color: headerBackgroundColor, - width: arrowWidth, - height: headerHeight, - padding: const EdgeInsets.all(2), - child: Material( + final Container leftArrow = + navigationArrowEnabled + ? Container( + alignment: Alignment.center, + color: headerBackgroundColor, + width: arrowWidth, + height: headerHeight, + padding: const EdgeInsets.all(2), + child: Material( color: headerBackgroundColor, child: InkWell( //// set splash color as transparent when arrow reaches min date(disabled) @@ -10036,37 +11228,41 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { child: Semantics( label: 'Backward', child: Container( - width: arrowWidth, - height: headerHeight, - alignment: Alignment.center, - clipBehavior: Clip.antiAlias, - decoration: - const BoxDecoration(color: Colors.transparent), - child: Icon( - widget.navigationDirection == - MonthNavigationDirection.horizontal - ? Icons.chevron_left - : Icons.keyboard_arrow_up, - color: prevArrowColor, - size: arrowSize, - )), + width: arrowWidth, + height: headerHeight, + alignment: Alignment.center, + clipBehavior: Clip.antiAlias, + decoration: const BoxDecoration( + color: Colors.transparent, + ), + child: Icon( + widget.navigationDirection == + MonthNavigationDirection.horizontal + ? Icons.chevron_left + : Icons.keyboard_arrow_up, + color: prevArrowColor, + size: arrowSize, + ), + ), ), - )), - ) - : Container(); + ), + ), + ) + : Container(); final Color? rightArrowSplashColor = nextArrowColor != arrowColor || !widget.enableInteraction ? Colors.transparent : null; - final Container rightArrow = navigationArrowEnabled - ? Container( - alignment: Alignment.center, - color: headerBackgroundColor, - width: arrowWidth, - height: headerHeight, - padding: const EdgeInsets.all(2), - child: Material( + final Container rightArrow = + navigationArrowEnabled + ? Container( + alignment: Alignment.center, + color: headerBackgroundColor, + width: arrowWidth, + height: headerHeight, + padding: const EdgeInsets.all(2), + child: Material( color: headerBackgroundColor, child: InkWell( //// set splash color as transparent when arrow reaches max date(disabled) @@ -10078,36 +11274,39 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { child: Semantics( label: 'Forward', child: Container( - width: arrowWidth, - height: headerHeight, - alignment: Alignment.center, - clipBehavior: Clip.antiAlias, - decoration: const BoxDecoration( - color: Colors.transparent, - ), - child: Icon( - widget.navigationDirection == - MonthNavigationDirection.horizontal - ? Icons.chevron_right - : Icons.keyboard_arrow_down, - color: nextArrowColor, - size: arrowSize, - )), + width: arrowWidth, + height: headerHeight, + alignment: Alignment.center, + clipBehavior: Clip.antiAlias, + decoration: const BoxDecoration( + color: Colors.transparent, + ), + child: Icon( + widget.navigationDirection == + MonthNavigationDirection.horizontal + ? Icons.chevron_right + : Icons.keyboard_arrow_down, + color: nextArrowColor, + size: arrowSize, + ), + ), ), - )), - ) - : Container(); + ), + ), + ) + : Container(); final Color? todaySplashColor = !widget.enableInteraction ? Colors.transparent : null; - final Widget todayIcon = widget.showTodayButton - ? Container( - alignment: Alignment.center, - color: headerBackgroundColor, - width: todayIconWidth, - height: headerHeight, - padding: EdgeInsets.all(useMobilePlatformUI ? 2 : 4), - child: Material( + final Widget todayIcon = + widget.showTodayButton + ? Container( + alignment: Alignment.center, + color: headerBackgroundColor, + width: todayIconWidth, + height: headerHeight, + padding: EdgeInsets.all(useMobilePlatformUI ? 2 : 4), + child: Material( color: headerBackgroundColor, child: InkWell( splashColor: todaySplashColor, @@ -10124,58 +11323,60 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { }, child: Semantics( label: todayText, - child: useMobilePlatformUI - ? Container( - decoration: const BoxDecoration( - color: Colors.transparent, - ), - clipBehavior: Clip.antiAlias, - width: todayIconWidth, - height: headerHeight, - alignment: Alignment.center, - child: Icon( - Icons.today, - color: style.color, - size: style.fontSize, - )) - : Container( - decoration: BoxDecoration( - border: Border.all( - color: widget.cellBorderColor ?? - widget.calendarTheme.cellBorderColor!), - borderRadius: BorderRadius.circular(5.0), - ), - width: todayIconWidth, - alignment: Alignment.center, - child: Text( - todayText, - style: TextStyle( + child: + useMobilePlatformUI + ? Container( + decoration: const BoxDecoration( + color: Colors.transparent, + ), + clipBehavior: Clip.antiAlias, + width: todayIconWidth, + height: headerHeight, + alignment: Alignment.center, + child: Icon( + Icons.today, + color: style.color, + size: style.fontSize, + ), + ) + : Container( + decoration: BoxDecoration( + border: Border.all( + color: + widget.cellBorderColor ?? + widget.calendarTheme.cellBorderColor!, + ), + borderRadius: BorderRadius.circular(5.0), + ), + width: todayIconWidth, + alignment: Alignment.center, + child: Text( + todayText, + style: TextStyle( color: headerTextColor, - fontSize: defaultCalendarViewTextSize), - maxLines: 1, - textDirection: TextDirection.ltr, - )), + fontSize: defaultCalendarViewTextSize, + ), + maxLines: 1, + textDirection: TextDirection.ltr, + ), + ), ), - )), - ) - : Container(); + ), + ), + ) + : Container(); final Widget dividerWidget = widget.showTodayButton && isNeedViewSwitchOption && !useMobilePlatformUI ? Container( - alignment: Alignment.center, - color: headerBackgroundColor, - width: dividerWidth, - height: headerHeight, - padding: const EdgeInsets.symmetric(vertical: 5), - child: const VerticalDivider( - color: Colors.grey, - thickness: 0.5, - )) - : const SizedBox( - width: 0, - height: 0, - ); + alignment: Alignment.center, + color: headerBackgroundColor, + width: dividerWidth, + height: headerHeight, + padding: const EdgeInsets.symmetric(vertical: 5), + child: const VerticalDivider(color: Colors.grey, thickness: 0.5), + ) + : const SizedBox(width: 0, height: 0); List rowChildren = []; @@ -10205,7 +11406,9 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { } return Row( - mainAxisAlignment: MainAxisAlignment.center, children: rowChildren); + mainAxisAlignment: MainAxisAlignment.center, + children: rowChildren, + ); } else if (widget.headerStyle.textAlign == TextAlign.right || widget.headerStyle.textAlign == TextAlign.end) { if (widget.isMobilePlatform) { @@ -10231,7 +11434,9 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { } return Row( - mainAxisAlignment: MainAxisAlignment.center, children: rowChildren); + mainAxisAlignment: MainAxisAlignment.center, + children: rowChildren, + ); } else { if (widget.isMobilePlatform) { rowChildren = [ @@ -10258,15 +11463,18 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { } return Row( - mainAxisAlignment: MainAxisAlignment.center, children: rowChildren); + mainAxisAlignment: MainAxisAlignment.center, + children: rowChildren, + ); } } @override void dispose() { widget.valueChangeNotifier.removeListener(_updateHeaderChanged); - widget.valueChangeNotifier - .removeListener(_updateWeekNumberChangedForTimelineMonth); + widget.valueChangeNotifier.removeListener( + _updateWeekNumberChangedForTimelineMonth, + ); super.dispose(); } @@ -10302,26 +11510,28 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { } Widget _getCalendarViewWidget( - Color headerBackgroundColor, - bool useMobilePlatformUI, - bool isNeedIcon, - double width, - double height, - TextStyle style, - Color arrowColor, - Color headerTextColor, - CalendarView view, - bool isHighlighted, - Color? highlightColor, - double defaultCalendarViewTextSize, - {String? semanticLabel}) { + Color headerBackgroundColor, + bool useMobilePlatformUI, + bool isNeedIcon, + double width, + double height, + TextStyle style, + Color arrowColor, + Color headerTextColor, + CalendarView view, + bool isHighlighted, + Color? highlightColor, + double defaultCalendarViewTextSize, { + String? semanticLabel, + }) { final String text = _calendarViews[view]!; final Color? calendarViewSplashColor = !widget.enableInteraction ? Colors.transparent : null; - final Color? allowedViewsColor = isHighlighted - ? highlightColor - : widget.cellBorderColor ?? widget.calendarTheme.cellBorderColor; + final Color? allowedViewsColor = + isHighlighted + ? highlightColor + : widget.cellBorderColor ?? widget.calendarTheme.cellBorderColor; return Container( alignment: Alignment.center, color: headerBackgroundColor, @@ -10329,89 +11539,105 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { height: height, padding: EdgeInsets.all(useMobilePlatformUI ? 2 : 4), child: Material( - color: isHighlighted && (isNeedIcon || useMobilePlatformUI) - ? Colors.grey.withValues(alpha: 0.3) - : headerBackgroundColor, + color: + isHighlighted && (isNeedIcon || useMobilePlatformUI) + ? Colors.grey.withValues(alpha: 0.3) + : headerBackgroundColor, child: InkWell( - splashColor: calendarViewSplashColor, - highlightColor: calendarViewSplashColor, - hoverColor: calendarViewSplashColor, - splashFactory: _CustomSplashFactory(), - onTap: () { - if (!widget.enableInteraction) { - return; - } - if (isNeedIcon || useMobilePlatformUI) { - widget.viewChangeNotifier.value = - !widget.viewChangeNotifier.value; - } else { - widget.controller.view = view; - } - }, - child: Semantics( - label: semanticLabel ?? text, - child: useMobilePlatformUI + splashColor: calendarViewSplashColor, + highlightColor: calendarViewSplashColor, + hoverColor: calendarViewSplashColor, + splashFactory: _CustomSplashFactory(), + onTap: () { + if (!widget.enableInteraction) { + return; + } + if (isNeedIcon || useMobilePlatformUI) { + widget.viewChangeNotifier.value = + !widget.viewChangeNotifier.value; + } else { + widget.controller.view = view; + } + }, + child: Semantics( + label: semanticLabel ?? text, + child: + useMobilePlatformUI ? Container( - width: width, - height: height, - alignment: Alignment.center, - clipBehavior: Clip.antiAlias, - decoration: const BoxDecoration( - color: Colors.transparent, - ), - child: Icon( - Icons.more_vert, - color: style.color, - size: style.fontSize, - )) + width: width, + height: height, + alignment: Alignment.center, + clipBehavior: Clip.antiAlias, + decoration: const BoxDecoration( + color: Colors.transparent, + ), + child: Icon( + Icons.more_vert, + color: style.color, + size: style.fontSize, + ), + ) : (isNeedIcon ? Container( - width: width, - height: height, - alignment: Alignment.center, - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration( - border: Border.all(color: highlightColor!), - borderRadius: BorderRadius.circular(5.0)), - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - text, - style: TextStyle( - color: highlightColor, - fontSize: defaultCalendarViewTextSize), - maxLines: 1, - textDirection: TextDirection.ltr, - ), - Icon( - widget.viewChangeNotifier.value - ? Icons.arrow_drop_up - : Icons.arrow_drop_down, - color: arrowColor, - size: widget.calendarTheme.headerTextStyle! - .fontSize ?? - 14, - ) - ], - )) - : Container( - decoration: BoxDecoration( - border: Border.all(color: allowedViewsColor!), - borderRadius: BorderRadius.circular(5.0)), - width: width, - height: height, - alignment: Alignment.center, - child: Text(text, - textAlign: TextAlign.center, + width: width, + height: height, + alignment: Alignment.center, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + border: Border.all(color: highlightColor!), + borderRadius: BorderRadius.circular(5.0), + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + text, style: TextStyle( - color: isHighlighted - ? highlightColor - : headerTextColor, - fontSize: defaultCalendarViewTextSize), + color: highlightColor, + fontSize: defaultCalendarViewTextSize, + ), maxLines: 1, - textDirection: TextDirection.ltr), - )))), + textDirection: TextDirection.ltr, + ), + Icon( + widget.viewChangeNotifier.value + ? Icons.arrow_drop_up + : Icons.arrow_drop_down, + color: arrowColor, + size: + widget + .calendarTheme + .headerTextStyle! + .fontSize ?? + 14, + ), + ], + ), + ) + : Container( + decoration: BoxDecoration( + border: Border.all(color: allowedViewsColor!), + borderRadius: BorderRadius.circular(5.0), + ), + width: width, + height: height, + alignment: Alignment.center, + child: Text( + text, + textAlign: TextAlign.center, + style: TextStyle( + color: + isHighlighted + ? highlightColor + : headerTextColor, + fontSize: defaultCalendarViewTextSize, + ), + maxLines: 1, + textDirection: TextDirection.ltr, + ), + )), + ), + ), ), ); } @@ -10421,8 +11647,9 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { case CalendarView.day: case CalendarView.timelineDay: { - return DateTimeHelper.getWeekNumberOfYear(widget.visibleDates[0]) - .toString(); + return DateTimeHelper.getWeekNumberOfYear( + widget.visibleDates[0], + ).toString(); } case CalendarView.week: case CalendarView.workWeek: @@ -10445,20 +11672,21 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { } else if (widget.nonWorkingDays.contains(DateTime.monday)) { final int midDate = widget.visibleDates.length ~/ 2; return DateTimeHelper.getWeekNumberOfYear( - widget.visibleDates[midDate]) - .toString(); + widget.visibleDates[midDate], + ).toString(); } } break; case CalendarView.timelineMonth: { return DateTimeHelper.getWeekNumberOfYear( - widget.timelineMonthWeekNumberNotifier.value!) - .toString(); + widget.timelineMonthWeekNumberNotifier.value!, + ).toString(); } } - return DateTimeHelper.getWeekNumberOfYear(widget.visibleDates[0]) - .toString(); + return DateTimeHelper.getWeekNumberOfYear( + widget.visibleDates[0], + ).toString(); } String _getHeaderText() { @@ -10467,22 +11695,25 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { widget.headerDateFormat != null && widget.headerDateFormat!.isNotEmpty ? widget.headerDateFormat : null; - final List headerFormatString = headerDateFormat == null - ? [] - : CalendarViewHelper.getListFromString(headerDateFormat); + final List headerFormatString = + headerDateFormat == null + ? [] + : CalendarViewHelper.getListFromString(headerDateFormat); final int visibleDatesCount = DateTimeHelper.getViewDatesCount( - widget.view, - widget.numberOfDaysInView, - widget.numberOfDaysInView, - widget.nonWorkingDays); + widget.view, + widget.numberOfDaysInView, + widget.numberOfDaysInView, + widget.nonWorkingDays, + ); switch (widget.view) { case CalendarView.schedule: { if (headerDateFormat != null) { return CalendarViewHelper.getLocalizedString( - widget.valueChangeNotifier.value!, - headerFormatString, - widget.locale); + widget.valueChangeNotifier.value!, + headerFormatString, + widget.locale, + ); } // ignore: lines_longer_than_80_chars return '${DateFormat(monthFormat, widget.locale).format(widget.valueChangeNotifier.value!)} ${widget.valueChangeNotifier.value!.year}'; @@ -10507,7 +11738,10 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { if (headerDateFormat != null) { // ignore: lines_longer_than_80_chars return CalendarViewHelper.getLocalizedString( - widget.currentDate!, headerFormatString, widget.locale); + widget.currentDate!, + headerFormatString, + widget.locale, + ); } // ignore: lines_longer_than_80_chars return '${DateFormat(monthFormat, widget.locale).format(widget.currentDate!)} ${widget.currentDate!.year}'; @@ -10520,7 +11754,10 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { if (headerDateFormat != null) { // ignore: lines_longer_than_80_chars return CalendarViewHelper.getLocalizedString( - headerDate, headerFormatString, widget.locale); + headerDate, + headerFormatString, + widget.locale, + ); } // ignore: lines_longer_than_80_chars return '${DateFormat(monthFormat, widget.locale).format(headerDate)} ${headerDate.year}'; @@ -10535,8 +11772,11 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { if (visibleDatesCount == 1) { if (headerDateFormat != null) { // ignore: lines_longer_than_80_chars - CalendarViewHelper.getLocalizedString( - startDate, headerFormatString, widget.locale); + return CalendarViewHelper.getLocalizedString( + startDate, + headerFormatString, + widget.locale, + ); } // ignore: lines_longer_than_80_chars return '${DateFormat(monthFormat, widget.locale).format(startDate)} ${startDate.year}'; @@ -10547,8 +11787,10 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { } monthFormat = 'MMM'; - String startText = - DateFormat(monthFormat, widget.locale).format(startDate); + String startText = DateFormat( + monthFormat, + widget.locale, + ).format(startDate); startText = '${startDate.day} $startText - '; final String endText = // ignore: lines_longer_than_80_chars @@ -10563,20 +11805,20 @@ class _CalendarHeaderViewState extends State<_CalendarHeaderView> { /// It is used to generate the week and month label of schedule calendar view. class _ScheduleLabelPainter extends CustomPainter { _ScheduleLabelPainter( - this.startDate, - this.endDate, - this.scheduleViewSettings, - this.isMonthLabel, - this.isRTL, - this.locale, - this.useMobilePlatformUI, - this.agendaViewNotifier, - this.calendarTheme, - this.themeData, - this._localizations, - this.textScaleFactor, - {this.isDisplayDate = false}) - : super(repaint: isDisplayDate ? agendaViewNotifier : null); + this.startDate, + this.endDate, + this.scheduleViewSettings, + this.isMonthLabel, + this.isRTL, + this.locale, + this.useMobilePlatformUI, + this.agendaViewNotifier, + this.calendarTheme, + this.themeData, + this._localizations, + this.textScaleFactor, { + this.isDisplayDate = false, + }) : super(repaint: isDisplayDate ? agendaViewNotifier : null); final DateTime startDate; final DateTime? endDate; @@ -10616,22 +11858,26 @@ class _ScheduleLabelPainter extends CustomPainter { final TextSpan span = TextSpan( text: _localizations.noEventsCalendarLabel, style: themeData.textTheme.bodyMedium!.merge( - scheduleViewSettings.weekHeaderSettings.weekTextStyle ?? - scheduleViewSettings.placeholderTextStyle), + scheduleViewSettings.weekHeaderSettings.weekTextStyle ?? + scheduleViewSettings.placeholderTextStyle, + ), ); double xPosition = 10; _updateTextPainter(span); _textPainter.layout( - maxWidth: size.width - xPosition > 0 ? size.width - xPosition : 0); + maxWidth: size.width - xPosition > 0 ? size.width - xPosition : 0, + ); if (isRTL) { xPosition = size.width - _textPainter.width - xPosition; } /// Draw display date view text _textPainter.paint( - canvas, Offset(xPosition, (size.height - _textPainter.height) / 2)); + canvas, + Offset(xPosition, (size.height - _textPainter.height) / 2), + ); /// Add hovering effect on display date view. if (isDisplayDate && @@ -10640,9 +11886,13 @@ class _ScheduleLabelPainter extends CustomPainter { const double padding = 5; if (useMobilePlatformUI) { final Rect rect = Rect.fromLTWH( - 0, padding, size.width - 2, size.height - (2 * padding)); - _backgroundPainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + 0, + padding, + size.width - 2, + size.height - (2 * padding), + ); + _backgroundPainter.color = calendarTheme.selectionBorderColor! + .withValues(alpha: 0.4); _backgroundPainter.style = PaintingStyle.stroke; _backgroundPainter.strokeWidth = 2; canvas.drawRect(rect, _backgroundPainter); @@ -10650,14 +11900,16 @@ class _ScheduleLabelPainter extends CustomPainter { } else { const double viewPadding = 2; final Rect rect = Rect.fromLTWH( - 0, - padding + viewPadding, - size.width - (isRTL ? viewPadding : padding), - size.height - (2 * (viewPadding + padding))); + 0, + padding + viewPadding, + size.width - (isRTL ? viewPadding : padding), + size.height - (2 * (viewPadding + padding)), + ); _backgroundPainter.color = Colors.grey.withValues(alpha: 0.1); canvas.drawRRect( - RRect.fromRectAndRadius(rect, const Radius.circular(4)), - _backgroundPainter); + RRect.fromRectAndRadius(rect, const Radius.circular(4)), + _backgroundPainter, + ); } } } @@ -10679,9 +11931,15 @@ class _ScheduleLabelPainter extends CustomPainter { final List endDateStringFormats = CalendarViewHelper.getListFromString(endDateFormat); final String firstDate = CalendarViewHelper.getLocalizedString( - startDate, startDateStringFormats, locale); + startDate, + startDateStringFormats, + locale, + ); final String lastDate = CalendarViewHelper.getLocalizedString( - endDate!, endDateStringFormats, locale); + endDate!, + endDateStringFormats, + locale, + ); final TextSpan span = TextSpan( text: '$firstDate - $lastDate', style: themeData.textTheme.bodyMedium! @@ -10693,9 +11951,14 @@ class _ScheduleLabelPainter extends CustomPainter { /// Draw week label background. canvas.drawRect( - Rect.fromLTWH(0, yPosition, size.width, - scheduleViewSettings.weekHeaderSettings.height), - _backgroundPainter); + Rect.fromLTWH( + 0, + yPosition, + size.width, + scheduleViewSettings.weekHeaderSettings.height, + ), + _backgroundPainter, + ); _updateTextPainter(span); _textPainter.layout(maxWidth: size.width - 10 > 0 ? size.width - 10 : 0); @@ -10721,12 +11984,14 @@ class _ScheduleLabelPainter extends CustomPainter { /// Draw week label text _textPainter.paint( - canvas, - Offset( - xPosition, - yPosition + - (scheduleViewSettings.weekHeaderSettings.height / 2 - - _textPainter.height / 2))); + canvas, + Offset( + xPosition, + yPosition + + (scheduleViewSettings.weekHeaderSettings.height / 2 - + _textPainter.height / 2), + ), + ); } void _addMonthLabel(Canvas canvas, Size size) { @@ -10737,19 +12002,29 @@ class _ScheduleLabelPainter extends CustomPainter { final List monthStringFormats = CalendarViewHelper.getListFromString(monthFormat); final String dateString = CalendarViewHelper.getLocalizedString( - startDate, monthStringFormats, locale); + startDate, + monthStringFormats, + locale, + ); final TextSpan span = TextSpan( text: dateString, style: themeData.textTheme.bodyLarge! .copyWith( - color: Colors.white, fontSize: 20, fontWeight: FontWeight.w400) + color: Colors.white, + fontSize: 20, + fontWeight: FontWeight.w400, + ) .merge(scheduleViewSettings.monthHeaderSettings.monthTextStyle), ); _backgroundPainter.shader = null; _backgroundPainter.color = scheduleViewSettings.monthHeaderSettings.backgroundColor; - final Rect rect = Rect.fromLTWH(0, yPosition, size.width, - scheduleViewSettings.monthHeaderSettings.height); + final Rect rect = Rect.fromLTWH( + 0, + yPosition, + size.width, + scheduleViewSettings.monthHeaderSettings.height, + ); /// Draw month label background. canvas.drawRect(rect, _backgroundPainter); @@ -10819,13 +12094,15 @@ class _ScheduleLabelPainter extends CustomPainter { accessibilityText = DateFormat('MMMM yyyy', locale).format(startDate); } - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, size.width, cellHeight), - properties: SemanticsProperties( - label: accessibilityText, - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, size.width, cellHeight), + properties: SemanticsProperties( + label: accessibilityText, + textDirection: TextDirection.ltr, + ), ), - )); + ); return semanticsBuilder; } @@ -10856,13 +12133,13 @@ class _ScheduleAppointmentView extends Stack { AlignmentDirectional? alignment, Key? key, }) : super( - key: key, - children: [ - RepaintBoundary(child: content), - RepaintBoundary(child: header) - ], - alignment: alignment ?? AlignmentDirectional.topStart, - ); + key: key, + children: [ + RepaintBoundary(child: content), + RepaintBoundary(child: header), + ], + alignment: alignment ?? AlignmentDirectional.topStart, + ); @override RenderStack createRenderObject(BuildContext context) => @@ -10891,12 +12168,8 @@ class _AppointmentViewHeaderRenderObject extends RenderStack { AlignmentGeometry alignment = AlignmentDirectional.topStart, TextDirection? textDirection, StackFit fit = StackFit.loose, - }) : _scrollableState = scrollableState, - super( - alignment: alignment, - textDirection: textDirection, - fit: fit, - ); + }) : _scrollableState = scrollableState, + super(alignment: alignment, textDirection: textDirection, fit: fit); /// Used to update the child position when it scroll changed. ScrollableState? _scrollableState; @@ -10961,13 +12234,18 @@ class _AppointmentViewHeaderRenderObject extends RenderStack { final StackParentData headerParentData = // ignore: avoid_as headerView.parentData! as StackParentData; - final double headerYOffset = - _getHeaderOffset(contentSize, offset, headerSize); + final double headerYOffset = _getHeaderOffset( + contentSize, + offset, + headerSize, + ); /// Update the header start y position. if (headerYOffset != headerParentData.offset.dy) { - headerParentData.offset = - Offset(headerParentData.offset.dx, headerYOffset); + headerParentData.offset = Offset( + headerParentData.offset.dx, + headerYOffset, + ); } } @@ -11065,34 +12343,46 @@ class _CustomSplash extends InteractiveInkFeature { RectCallback? rectCallback, BorderRadius? borderRadius, VoidCallback? onRemoved, - }) : _position = position, - _borderRadius = borderRadius ?? BorderRadius.zero, - _targetRadius = _getTargetRadius( - referenceBox, containedInkWell, rectCallback, position), - _clipCallback = - _getClipCallback(referenceBox, containedInkWell, rectCallback), - _repositionToReferenceBox = !containedInkWell, - super( - controller: controller, - referenceBox: referenceBox, - color: color, - onRemoved: onRemoved) { - _radiusController = AnimationController( - duration: _kUnconfirmedRippleSplashDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..forward(); - _radius = _radiusController.drive(Tween( - begin: 0.0, - end: _targetRadius, - )); - _alphaController = AnimationController( - duration: _kSplashFadeDuration, vsync: controller.vsync) - ..addListener(controller.markNeedsPaint) - ..addStatusListener(_handleAlphaStatusChanged); - _alpha = _alphaController!.drive(IntTween( - begin: (color.a * 255).toInt(), - end: 0, - )); + }) : _position = position, + _borderRadius = borderRadius ?? BorderRadius.zero, + _targetRadius = _getTargetRadius( + referenceBox, + containedInkWell, + rectCallback, + position, + ), + _clipCallback = _getClipCallback( + referenceBox, + containedInkWell, + rectCallback, + ), + _repositionToReferenceBox = !containedInkWell, + super( + controller: controller, + referenceBox: referenceBox, + color: color, + onRemoved: onRemoved, + ) { + _radiusController = + AnimationController( + duration: _kUnconfirmedRippleSplashDuration, + vsync: controller.vsync, + ) + ..addListener(controller.markNeedsPaint) + ..forward(); + _radius = _radiusController.drive( + Tween(begin: 0.0, end: _targetRadius), + ); + _alphaController = + AnimationController( + duration: _kSplashFadeDuration, + vsync: controller.vsync, + ) + ..addListener(controller.markNeedsPaint) + ..addStatusListener(_handleAlphaStatusChanged); + _alpha = _alphaController!.drive( + IntTween(begin: (color.a * 255).toInt(), end: 0), + ); controller.addInkFeature(this); } @@ -11131,9 +12421,10 @@ class _CustomSplash extends InteractiveInkFeature { /// Calculate the ripple animation duration from its radius value and start /// the animation. Duration duration = Duration(milliseconds: (_targetRadius * 10).floor()); - duration = duration > _kUnconfirmedRippleSplashDuration - ? _kUnconfirmedRippleSplashDuration - : duration; + duration = + duration > _kUnconfirmedRippleSplashDuration + ? _kUnconfirmedRippleSplashDuration + : duration; _radiusController ..duration = duration ..forward(); @@ -11169,8 +12460,11 @@ class _CustomSplash extends InteractiveInkFeature { /// If the reference box needs to reposition then its 'rectCallback' value /// is null, so calculate the position based on reference box. if (_repositionToReferenceBox) { - center = Offset.lerp(center, referenceBox.size.center(Offset.zero), - _radiusController.value); + center = Offset.lerp( + center, + referenceBox.size.center(Offset.zero), + _radiusController.value, + ); } /// Get the offset needs to translate, if it not specified then it @@ -11212,20 +12506,20 @@ class _CustomSplash extends InteractiveInkFeature { class _AgendaDateTimePainter extends CustomPainter { _AgendaDateTimePainter( - this.selectedDate, - this.monthViewSettings, - this.scheduleViewSettings, - this.todayHighlightColor, - this.todayTextStyle, - this.locale, - this.calendarTheme, - this.themeData, - this.agendaDateNotifier, - this.viewWidth, - this.isRTL, - this.textScaleFactor, - this.isMobilePlatform) - : super(repaint: agendaDateNotifier); + this.selectedDate, + this.monthViewSettings, + this.scheduleViewSettings, + this.todayHighlightColor, + this.todayTextStyle, + this.locale, + this.calendarTheme, + this.themeData, + this.agendaDateNotifier, + this.viewWidth, + this.isRTL, + this.textScaleFactor, + this.isMobilePlatform, + ) : super(repaint: agendaDateNotifier); final DateTime? selectedDate; final MonthViewSettings? monthViewSettings; @@ -11252,25 +12546,24 @@ class _AgendaDateTimePainter extends CustomPainter { return; } - final bool useMobilePlatformUI = - CalendarViewHelper.isMobileLayoutUI(viewWidth, isMobilePlatform); + final bool useMobilePlatformUI = CalendarViewHelper.isMobileLayoutUI( + viewWidth, + isMobilePlatform, + ); final bool isToday = isSameDate(selectedDate, DateTime.now()); TextStyle? dateTextStyle, dayTextStyle; /// Holds the default agenda day text style from framework text theme. - final TextStyle agendaDayThemeTextStyle = - themeData.textTheme.bodySmall!.copyWith( - color: themeData.colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: 10, - fontWeight: FontWeight.w500, - ); + final TextStyle agendaDayThemeTextStyle = themeData.textTheme.bodySmall! + .copyWith( + color: themeData.colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: 10, + fontWeight: FontWeight.w500, + ); /// Holds the default agenda date text style from framework text theme. - final TextStyle agendaDateThemeTextStyle = - themeData.textTheme.bodyMedium!.copyWith( - color: themeData.colorScheme.onSurface, - fontSize: 18, - ); + final TextStyle agendaDateThemeTextStyle = themeData.textTheme.bodyMedium! + .copyWith(color: themeData.colorScheme.onSurface, fontSize: 18); if (monthViewSettings != null) { dayTextStyle = agendaDayThemeTextStyle .merge(calendarTheme.agendaDayTextStyle) @@ -11288,17 +12581,21 @@ class _AgendaDateTimePainter extends CustomPainter { .merge(scheduleViewSettings!.dayHeaderSettings.dateTextStyle); } else { dayTextStyle = agendaDayThemeTextStyle.merge( - scheduleViewSettings!.dayHeaderSettings.dayTextStyle ?? - TextStyle( - color: calendarTheme.agendaDayTextStyle?.color, - fontSize: 9, - fontWeight: FontWeight.w500)); + scheduleViewSettings!.dayHeaderSettings.dayTextStyle ?? + TextStyle( + color: calendarTheme.agendaDayTextStyle?.color, + fontSize: 9, + fontWeight: FontWeight.w500, + ), + ); dateTextStyle = agendaDateThemeTextStyle.merge( - scheduleViewSettings!.dayHeaderSettings.dateTextStyle ?? - TextStyle( - color: calendarTheme.agendaDateTextStyle?.color, - fontSize: 18, - fontWeight: FontWeight.normal)); + scheduleViewSettings!.dayHeaderSettings.dateTextStyle ?? + TextStyle( + color: calendarTheme.agendaDateTextStyle?.color, + fontSize: 18, + fontWeight: FontWeight.normal, + ), + ); } } @@ -11306,24 +12603,46 @@ class _AgendaDateTimePainter extends CustomPainter { final Color? todayTextStyleColor = calendarTheme.todayTextStyle!.color; final Color? todayTextColor = CalendarViewHelper.getTodayHighlightTextColor( - todayHighlightColor, todayTextStyle, calendarTheme); - dayTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle! - .copyWith(fontSize: dayTextStyle.fontSize, color: todayTextColor) - : dayTextStyle.copyWith(color: todayTextColor); - dateTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle!.copyWith( - fontSize: dateTextStyle.fontSize, color: todayTextStyleColor) - : dateTextStyle.copyWith(color: todayTextStyleColor); + todayHighlightColor, + todayTextStyle, + calendarTheme, + ); + dayTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: dayTextStyle.fontSize, + color: todayTextColor, + ) + : dayTextStyle.copyWith(color: todayTextColor); + dateTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: dateTextStyle.fontSize, + color: todayTextStyleColor, + ) + : dateTextStyle.copyWith(color: todayTextStyleColor); } /// Draw day label other than web schedule view. if (scheduleViewSettings == null || useMobilePlatformUI) { - _addDayLabelForMobile(canvas, size, padding, dayTextStyle, dateTextStyle, - isToday, isMobilePlatform); + _addDayLabelForMobile( + canvas, + size, + padding, + dayTextStyle, + dateTextStyle, + isToday, + isMobilePlatform, + ); } else { _addDayLabelForWeb( - canvas, size, padding, dayTextStyle, dateTextStyle, isToday); + canvas, + size, + padding, + dayTextStyle, + dateTextStyle, + isToday, + ); } } @@ -11337,30 +12656,34 @@ class _AgendaDateTimePainter extends CustomPainter { } void _addDayLabelForMobile( - Canvas canvas, - Size size, - double padding, - TextStyle dayTextStyle, - TextStyle dateTextStyle, - bool isToday, - bool isMobile) { + Canvas canvas, + Size size, + double padding, + TextStyle dayTextStyle, + TextStyle dateTextStyle, + bool isToday, + bool isMobile, + ) { //// Draw Weekday - final String dayTextFormat = scheduleViewSettings != null - ? scheduleViewSettings!.dayHeaderSettings.dayFormat - : 'EEE'; + final String dayTextFormat = + scheduleViewSettings != null + ? scheduleViewSettings!.dayHeaderSettings.dayFormat + : 'EEE'; TextSpan span = TextSpan( - text: DateFormat(dayTextFormat, locale) - .format(selectedDate!) - .toUpperCase(), - style: dayTextStyle); + text: + DateFormat(dayTextFormat, locale).format(selectedDate!).toUpperCase(), + style: dayTextStyle, + ); _updateTextPainter(span); _textPainter.layout(maxWidth: size.width); _textPainter.paint( - canvas, - Offset( - padding + ((size.width - (2 * padding) - _textPainter.width) / 2), - padding)); + canvas, + Offset( + padding + ((size.width - (2 * padding) - _textPainter.width) / 2), + padding, + ), + ); final double weekDayHeight = padding + _textPainter.height; //// Draw Date @@ -11393,12 +12716,13 @@ class _AgendaDateTimePainter extends CustomPainter { yPosition < agendaDateNotifier.value!.hoveringOffset.dy && yPosition + _textPainter.height > agendaDateNotifier.value!.hoveringOffset.dy) { - _linePainter.color = isToday - ? Colors.black.withValues(alpha: 0.1) - : (themeData.brightness == Brightness.dark - ? Colors.white - : Colors.black87) - .withValues(alpha: 0.04); + _linePainter.color = + isToday + ? Colors.black.withValues(alpha: 0.1) + : (themeData.brightness == Brightness.dark + ? Colors.white + : Colors.black87) + .withValues(alpha: 0.04); _drawTodayCircle(canvas, xPosition, yPosition, padding); } } @@ -11406,20 +12730,26 @@ class _AgendaDateTimePainter extends CustomPainter { _textPainter.paint(canvas, Offset(xPosition, yPosition)); } - void _addDayLabelForWeb(Canvas canvas, Size size, double padding, - TextStyle dayTextStyle, TextStyle dateTextStyle, bool isToday) { + void _addDayLabelForWeb( + Canvas canvas, + Size size, + double padding, + TextStyle dayTextStyle, + TextStyle dateTextStyle, + bool isToday, + ) { /// Draw day label on web schedule view. final String dateText = selectedDate!.day.toString(); /// Calculate the date text maximum width value. const String maxWidthDateText = '30'; - final String dayText = DateFormat( - isRTL - ? '${scheduleViewSettings!.dayHeaderSettings.dayFormat}, MMM' - : 'MMM, ${scheduleViewSettings!.dayHeaderSettings.dayFormat}', - locale) - .format(selectedDate!) - .toUpperCase(); + final String dayText = + DateFormat( + isRTL + ? '${scheduleViewSettings!.dayHeaderSettings.dayFormat}, MMM' + : 'MMM, ${scheduleViewSettings!.dayHeaderSettings.dayFormat}', + locale, + ).format(selectedDate!).toUpperCase(); //// Draw Weekday TextSpan span = TextSpan(text: maxWidthDateText, style: dateTextStyle); @@ -11459,12 +12789,13 @@ class _AgendaDateTimePainter extends CustomPainter { yPosition < agendaDateNotifier.value!.hoveringOffset.dy && (yPosition + _textPainter.height) > agendaDateNotifier.value!.hoveringOffset.dy) { - _linePainter.color = isToday - ? Colors.black.withValues(alpha: 0.1) - : (themeData.brightness == Brightness.dark - ? Colors.white - : Colors.black87) - .withValues(alpha: 0.04); + _linePainter.color = + isToday + ? Colors.black.withValues(alpha: 0.1) + : (themeData.brightness == Brightness.dark + ? Colors.white + : Colors.black87) + .withValues(alpha: 0.04); _drawTodayCircle(canvas, dateTextStartPosition, yPosition, padding); } } @@ -11478,8 +12809,10 @@ class _AgendaDateTimePainter extends CustomPainter { _textPainter.layout(maxWidth: startXPosition); startXPosition -= _textPainter.width + (3 * padding); if (startXPosition > 0) { - _textPainter.paint(canvas, - Offset(startXPosition, (dateHeight - _textPainter.height) / 2)); + _textPainter.paint( + canvas, + Offset(startXPosition, (dateHeight - _textPainter.height) / 2), + ); } } else { startXPosition += painterWidth + (3 * padding); @@ -11487,20 +12820,29 @@ class _AgendaDateTimePainter extends CustomPainter { return; } _textPainter.layout(maxWidth: size.width - startXPosition); - _textPainter.paint(canvas, - Offset(startXPosition, (dateHeight - _textPainter.height) / 2)); + _textPainter.paint( + canvas, + Offset(startXPosition, (dateHeight - _textPainter.height) / 2), + ); } } void _drawTodayCircle( - Canvas canvas, double xPosition, double yPosition, double padding) { + Canvas canvas, + double xPosition, + double yPosition, + double padding, + ) { canvas.drawCircle( - Offset(xPosition + (_textPainter.width / 2), - yPosition + (_textPainter.height / 2)), - _textPainter.width > _textPainter.height - ? (_textPainter.width / 2) + padding - : (_textPainter.height / 2) + padding, - _linePainter); + Offset( + xPosition + (_textPainter.width / 2), + yPosition + (_textPainter.height / 2), + ), + _textPainter.width > _textPainter.height + ? (_textPainter.width / 2) + padding + : (_textPainter.height / 2) + padding, + _linePainter, + ); } @override @@ -11530,14 +12872,17 @@ class _AgendaDateTimePainter extends CustomPainter { if (selectedDate == null) { return semanticsBuilder; } else if (selectedDate != null) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Offset.zero & size, - properties: SemanticsProperties( - label: DateFormat('EEEEE').format(selectedDate!) + - DateFormat('dd MMMM yyyy').format(selectedDate!), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Offset.zero & size, + properties: SemanticsProperties( + label: + DateFormat('EEEEE').format(selectedDate!) + + DateFormat('dd MMMM yyyy').format(selectedDate!), + textDirection: TextDirection.ltr, + ), ), - )); + ); } return semanticsBuilder; @@ -11552,8 +12897,12 @@ class _ScheduleViewDetails { } /// Returns the maximum radius value calculated based on input touch position. -double _getTargetRadius(RenderBox referenceBox, bool containedInkWell, - RectCallback? rectCallback, Offset position) { +double _getTargetRadius( + RenderBox referenceBox, + bool containedInkWell, + RectCallback? rectCallback, + Offset position, +) { /// If `containedInkWell` is false, then `rectCallback` should be null. if (!containedInkWell) { return Material.defaultSplashRadius; @@ -11570,7 +12919,10 @@ double _getTargetRadius(RenderBox referenceBox, bool containedInkWell, /// Return the rect callback value based on its argument value. RectCallback? _getClipCallback( - RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback) { + RenderBox referenceBox, + bool containedInkWell, + RectCallback? rectCallback, +) { if (rectCallback != null) { /// If `containedInkWell` is false, then `rectCallback` should be null. assert(containedInkWell); @@ -11583,8 +12935,12 @@ RectCallback? _getClipCallback( } Size _getTextWidgetWidth( - String text, double height, double width, BuildContext context, - {TextStyle? style}) { + String text, + double height, + double width, + BuildContext context, { + TextStyle? style, +}) { /// Create new text with it style. final Widget richTextWidget = Text( text, @@ -11602,16 +12958,19 @@ Size _getTextWidgetWidth( /// Create and layout the render object based on allocated width and height. renderObject = richTextWidget.createRenderObject(context); } - renderObject!.layout(BoxConstraints( - minWidth: width, - maxWidth: width, - minHeight: height, - maxHeight: height, - )); + renderObject!.layout( + BoxConstraints( + minWidth: width, + maxWidth: width, + minHeight: height, + maxHeight: height, + ), + ); /// Get the size of text by using render object. final List textBox = renderObject.getBoxesForSelection( - TextSelection(baseOffset: 0, extentOffset: text.length)); + TextSelection(baseOffset: 0, extentOffset: text.length), + ); double textWidth = 0; double textHeight = 0; for (final TextBox box in textBox) { @@ -11644,7 +13003,9 @@ Map _getCalendarViewsText(SfLocalizations localizations) { /// Return day label width based on schedule view setting. double _getAgendaViewDayLabelWidth( - ScheduleViewSettings scheduleViewSettings, bool useMobilePlatformUI) { + ScheduleViewSettings scheduleViewSettings, + bool useMobilePlatformUI, +) { if (scheduleViewSettings.dayHeaderSettings.width == -1) { return useMobilePlatformUI ? 50 : 150; } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/theme.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/theme.dart index ed944c354..92928fbdb 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/theme.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/theme.dart @@ -9,9 +9,7 @@ import 'package:syncfusion_flutter_core/theme.dart'; class SfCalendarThemeColors extends SfCalendarThemeData { /// This a constructor that takes a [BuildContext] as a parameter.This context /// is used for obtaining the color scheme of the current theme. - SfCalendarThemeColors( - this.context, - ); + SfCalendarThemeColors(this.context); /// Property that stores the provided [BuildContext] /// context is later used to obtain the color scheme. @@ -24,11 +22,12 @@ class SfCalendarThemeColors extends SfCalendarThemeData { Color? get backgroundColor => Colors.transparent; @override - Color? get headerBackgroundColor => Theme.of(context).useMaterial3 - ? (Theme.of(context).brightness == Brightness.light - ? const Color.fromRGBO(247, 242, 251, 1) - : const Color.fromRGBO(37, 35, 42, 1)) - : Colors.transparent; + Color? get headerBackgroundColor => + Theme.of(context).useMaterial3 + ? (Theme.of(context).brightness == Brightness.light + ? const Color.fromRGBO(247, 242, 251, 1) + : const Color.fromRGBO(37, 35, 42, 1)) + : Colors.transparent; @override Color? get agendaBackgroundColor => Colors.transparent; diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/calendar_view.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/calendar_view.dart index 76c21e15c..78eccbe1b 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/calendar_view.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/calendar_view.dart @@ -34,32 +34,32 @@ class CustomCalendarScrollView extends StatefulWidget { /// view(time slot, month, timeline and appointment views) widgets of /// calendar widget. const CustomCalendarScrollView( - this.calendar, - this.view, - this.width, - this.height, - this.agendaSelectedDate, - this.isRTL, - this.locale, - this.calendarTheme, - this.themeData, - this.specialRegions, - this.blackoutDates, - this.controller, - this.removePicker, - this.resourcePanelScrollController, - this.resourceCollection, - this.textScaleFactor, - this.isMobilePlatform, - this.fadeInController, - this.minDate, - this.maxDate, - this.localizations, - this.timelineMonthWeekNumberNotifier, - this.updateCalendarState, - this.getCalendarState, - {Key? key}) - : super(key: key); + this.calendar, + this.view, + this.width, + this.height, + this.agendaSelectedDate, + this.isRTL, + this.locale, + this.calendarTheme, + this.themeData, + this.specialRegions, + this.blackoutDates, + this.controller, + this.removePicker, + this.resourcePanelScrollController, + this.resourceCollection, + this.textScaleFactor, + this.isMobilePlatform, + this.fadeInController, + this.minDate, + this.maxDate, + this.localizations, + this.timelineMonthWeekNumberNotifier, + this.updateCalendarState, + this.getCalendarState, { + Key? key, + }) : super(key: key); /// Holds the calendar instance used to get the calendar properties. final SfCalendar calendar; @@ -274,23 +274,26 @@ class _CustomCalendarScrollViewState extends State @override void initState() { _dragDetails = ValueNotifier<_DragPaintDetails>( - _DragPaintDetails(position: ValueNotifier(null))); - widget.controller.forward = widget.isRTL - ? _moveToPreviousViewWithAnimation - : _moveToNextViewWithAnimation; - widget.controller.backward = widget.isRTL - ? _moveToNextViewWithAnimation - : _moveToPreviousViewWithAnimation; + _DragPaintDetails(position: ValueNotifier(null)), + ); + widget.controller.forward = + widget.isRTL + ? _moveToPreviousViewWithAnimation + : _moveToNextViewWithAnimation; + widget.controller.backward = + widget.isRTL + ? _moveToNextViewWithAnimation + : _moveToPreviousViewWithAnimation; _currentChildIndex = 1; _updateVisibleDates(); _animationController = AnimationController( - duration: const Duration(milliseconds: 250), vsync: this); - _animation = _tween.animate(CurvedAnimation( - parent: _animationController, - curve: Curves.ease, - )) - ..addListener(animationListener); + duration: const Duration(milliseconds: 250), + vsync: this, + ); + _animation = _tween.animate( + CurvedAnimation(parent: _animationController, curve: Curves.ease), + )..addListener(animationListener); _timeRegions = CalendarViewHelper.cloneList(widget.specialRegions); @@ -300,18 +303,23 @@ class _CustomCalendarScrollViewState extends State @override void didUpdateWidget(CustomCalendarScrollView oldWidget) { if (oldWidget.controller != widget.controller) { - widget.controller.forward = widget.isRTL - ? _moveToPreviousViewWithAnimation - : _moveToNextViewWithAnimation; - widget.controller.backward = widget.isRTL - ? _moveToNextViewWithAnimation - : _moveToPreviousViewWithAnimation; - - if (!CalendarViewHelper.isSameTimeSlot(oldWidget.controller.selectedDate, - widget.controller.selectedDate) || + widget.controller.forward = + widget.isRTL + ? _moveToPreviousViewWithAnimation + : _moveToNextViewWithAnimation; + widget.controller.backward = + widget.isRTL + ? _moveToNextViewWithAnimation + : _moveToPreviousViewWithAnimation; + + if (!CalendarViewHelper.isSameTimeSlot( + oldWidget.controller.selectedDate, + widget.controller.selectedDate, + ) || !CalendarViewHelper.isSameTimeSlot( - _updateCalendarStateDetails.selectedDate, - widget.controller.selectedDate)) { + _updateCalendarStateDetails.selectedDate, + widget.controller.selectedDate, + )) { _selectResourceProgrammatically(); } } @@ -364,7 +372,9 @@ class _CustomCalendarScrollViewState extends State /// Check and re renders the views if the resource collection changed. if (CalendarViewHelper.isTimelineView(widget.view) && !CalendarViewHelper.isCollectionEqual( - oldWidget.resourceCollection, widget.resourceCollection)) { + oldWidget.resourceCollection, + widget.resourceCollection, + )) { _updateSelectedResourceIndex(); _position = 0; _children.clear(); @@ -397,19 +407,24 @@ class _CustomCalendarScrollViewState extends State oldWidget.calendar.selectionDecoration != widget.calendar.selectionDecoration || oldWidget.calendar.weekNumberStyle != widget.calendar.weekNumberStyle) { - final bool isTimelineView = - CalendarViewHelper.isTimelineView(widget.view); + final bool isTimelineView = CalendarViewHelper.isTimelineView( + widget.view, + ); if (widget.view != CalendarView.month && (oldWidget.calendar.timeSlotViewSettings.timeInterval != widget.calendar.timeSlotViewSettings.timeInterval || (!isTimelineView && oldWidget.calendar.timeSlotViewSettings.timeIntervalHeight != widget - .calendar.timeSlotViewSettings.timeIntervalHeight) || + .calendar + .timeSlotViewSettings + .timeIntervalHeight) || (isTimelineView && oldWidget.calendar.timeSlotViewSettings.timeIntervalWidth != widget - .calendar.timeSlotViewSettings.timeIntervalWidth))) { + .calendar + .timeSlotViewSettings + .timeIntervalWidth))) { if (_currentChildIndex == 0) { _previousViewKey.currentState!._retainScrolledDateTime(); } else if (_currentChildIndex == 1) { @@ -428,11 +443,14 @@ class _CustomCalendarScrollViewState extends State widget.calendar.firstDayOfWeek != oldWidget.calendar.firstDayOfWeek || (widget.view != CalendarView.month && (!CalendarViewHelper.isCollectionEqual( - widget.calendar.timeSlotViewSettings.nonWorkingDays, - oldWidget.calendar.timeSlotViewSettings.nonWorkingDays) || + widget.calendar.timeSlotViewSettings.nonWorkingDays, + oldWidget.calendar.timeSlotViewSettings.nonWorkingDays, + ) || widget.calendar.timeSlotViewSettings.numberOfDaysInView != oldWidget - .calendar.timeSlotViewSettings.numberOfDaysInView)) || + .calendar + .timeSlotViewSettings + .numberOfDaysInView)) || widget.isRTL != oldWidget.isRTL) { _updateVisibleDates(); _position = 0; @@ -460,8 +478,10 @@ class _CustomCalendarScrollViewState extends State if (widget.controller == oldWidget.controller) { if (oldWidget.controller.displayDate != widget.controller.displayDate || - !isSameDate(_updateCalendarStateDetails.currentDate, - widget.controller.displayDate)) { + !isSameDate( + _updateCalendarStateDetails.currentDate, + widget.controller.displayDate, + )) { widget.getCalendarState(_updateCalendarStateDetails); _updateCalendarStateDetails.currentDate = widget.controller.displayDate; widget.updateCalendarState(_updateCalendarStateDetails); @@ -476,11 +496,14 @@ class _CustomCalendarScrollViewState extends State _position = 0; } - if (!CalendarViewHelper.isSameTimeSlot(oldWidget.controller.selectedDate, - widget.controller.selectedDate) || + if (!CalendarViewHelper.isSameTimeSlot( + oldWidget.controller.selectedDate, + widget.controller.selectedDate, + ) || !CalendarViewHelper.isSameTimeSlot( - _updateCalendarStateDetails.selectedDate, - widget.controller.selectedDate)) { + _updateCalendarStateDetails.selectedDate, + widget.controller.selectedDate, + )) { widget.getCalendarState(_updateCalendarStateDetails); _updateCalendarStateDetails.selectedDate = widget.controller.selectedDate; @@ -508,8 +531,8 @@ class _CustomCalendarScrollViewState extends State bottomPosition = 0; final bool isHorizontalNavigation = widget.calendar.monthViewSettings.navigationDirection == - MonthNavigationDirection.horizontal || - widget.view != CalendarView.month; + MonthNavigationDirection.horizontal || + widget.view != CalendarView.month; if (isHorizontalNavigation) { leftPosition = -widget.width; rightPosition = -widget.width; @@ -519,40 +542,53 @@ class _CustomCalendarScrollViewState extends State } final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); final bool isTimelineView = CalendarViewHelper.isTimelineView(widget.view); - final bool isNeedDragAndDrop = widget.calendar.allowDragAndDrop && + final bool isNeedDragAndDrop = + widget.calendar.allowDragAndDrop && widget.view != CalendarView.schedule && (!widget.isMobilePlatform || (widget.view != CalendarView.month && widget.view != CalendarView.timelineMonth)); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); - final double resourceItemHeight = isResourceEnabled - ? CalendarViewHelper.getResourceItemHeight( - widget.calendar.resourceViewSettings.size, - widget.height - viewHeaderHeight - timeLabelWidth, - widget.calendar.resourceViewSettings, - widget.calendar.dataSource!.resources!.length) - : 0; + widget.calendar.dataSource, + widget.view, + ); + final double resourceItemHeight = + isResourceEnabled + ? CalendarViewHelper.getResourceItemHeight( + widget.calendar.resourceViewSettings.size, + widget.height - viewHeaderHeight - timeLabelWidth, + widget.calendar.resourceViewSettings, + widget.calendar.dataSource!.resources!.length, + ) + : 0; final double resourceViewSize = isResourceEnabled ? widget.calendar.resourceViewSettings.size : 0; - final bool isMonthView = widget.view == CalendarView.month || + final bool isMonthView = + widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth; final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); final Widget customScrollWidget = GestureDetector( onTapDown: (TapDownDetails details) { @@ -560,21 +596,24 @@ class _CustomCalendarScrollViewState extends State _focusNode.requestFocus(); } }, - onHorizontalDragStart: isTimelineView - ? null - : (DragStartDetails dragStartDetails) { - _onHorizontalStart( + onHorizontalDragStart: + isTimelineView + ? null + : (DragStartDetails dragStartDetails) { + _onHorizontalStart( dragStartDetails, isResourceEnabled, isTimelineView, viewHeaderHeight, timeLabelWidth, - isNeedDragAndDrop); - }, - onHorizontalDragUpdate: isTimelineView - ? null - : (DragUpdateDetails dragUpdateDetails) { - _onHorizontalUpdate( + isNeedDragAndDrop, + ); + }, + onHorizontalDragUpdate: + isTimelineView + ? null + : (DragUpdateDetails dragUpdateDetails) { + _onHorizontalUpdate( dragUpdateDetails, isResourceEnabled, isMonthView, @@ -583,12 +622,14 @@ class _CustomCalendarScrollViewState extends State timeLabelWidth, resourceItemHeight, weekNumberPanelWidth, - isNeedDragAndDrop); - }, - onHorizontalDragEnd: isTimelineView - ? null - : (DragEndDetails dragEndDetails) { - _onHorizontalEnd( + isNeedDragAndDrop, + ); + }, + onHorizontalDragEnd: + isTimelineView + ? null + : (DragEndDetails dragEndDetails) { + _onHorizontalEnd( dragEndDetails, isResourceEnabled, isTimelineView, @@ -596,23 +637,27 @@ class _CustomCalendarScrollViewState extends State viewHeaderHeight, timeLabelWidth, weekNumberPanelWidth, - isNeedDragAndDrop); - }, - onVerticalDragStart: isHorizontalNavigation - ? null - : (DragStartDetails dragStartDetails) { - _onVerticalStart( + isNeedDragAndDrop, + ); + }, + onVerticalDragStart: + isHorizontalNavigation + ? null + : (DragStartDetails dragStartDetails) { + _onVerticalStart( dragStartDetails, isResourceEnabled, isTimelineView, viewHeaderHeight, timeLabelWidth, - isNeedDragAndDrop); - }, - onVerticalDragUpdate: isHorizontalNavigation - ? null - : (DragUpdateDetails dragUpdateDetails) { - _onVerticalUpdate( + isNeedDragAndDrop, + ); + }, + onVerticalDragUpdate: + isHorizontalNavigation + ? null + : (DragUpdateDetails dragUpdateDetails) { + _onVerticalUpdate( dragUpdateDetails, isResourceEnabled, isMonthView, @@ -621,12 +666,14 @@ class _CustomCalendarScrollViewState extends State timeLabelWidth, resourceItemHeight, weekNumberPanelWidth, - isNeedDragAndDrop); - }, - onVerticalDragEnd: isHorizontalNavigation - ? null - : (DragEndDetails dragEndDetails) { - _onVerticalEnd( + isNeedDragAndDrop, + ); + }, + onVerticalDragEnd: + isHorizontalNavigation + ? null + : (DragEndDetails dragEndDetails) { + _onVerticalEnd( dragEndDetails, isResourceEnabled, isTimelineView, @@ -634,25 +681,34 @@ class _CustomCalendarScrollViewState extends State viewHeaderHeight, timeLabelWidth, weekNumberPanelWidth, - isNeedDragAndDrop); - }, + isNeedDragAndDrop, + ); + }, child: CustomScrollViewerLayout( - _addViews(), - isHorizontalNavigation - ? CustomScrollDirection.horizontal - : CustomScrollDirection.vertical, - _position, - _currentChildIndex), + _addViews(), + isHorizontalNavigation + ? CustomScrollDirection.horizontal + : CustomScrollDirection.vertical, + _position, + _currentChildIndex, + ), ); return GestureDetector( onLongPressStart: (LongPressStartDetails details) { - _handleLongPressStart(details, isNeedDragAndDrop, isTimelineView, - isResourceEnabled, viewHeaderHeight, timeLabelWidth); + _handleLongPressStart( + details, + isNeedDragAndDrop, + isTimelineView, + isResourceEnabled, + viewHeaderHeight, + timeLabelWidth, + ); }, - onLongPressMoveUpdate: isNeedDragAndDrop - ? (LongPressMoveUpdateDetails details) { - _handleLongPressMove( + onLongPressMoveUpdate: + isNeedDragAndDrop + ? (LongPressMoveUpdateDetails details) { + _handleLongPressMove( details.localPosition, isTimelineView, isResourceEnabled, @@ -660,112 +716,128 @@ class _CustomCalendarScrollViewState extends State viewHeaderHeight, timeLabelWidth, resourceItemHeight, - weekNumberPanelWidth); - } - : null, - onLongPressEnd: isNeedDragAndDrop - ? (LongPressEndDetails details) { - _handleLongPressEnd( + weekNumberPanelWidth, + ); + } + : null, + onLongPressEnd: + isNeedDragAndDrop + ? (LongPressEndDetails details) { + _handleLongPressEnd( details.localPosition, isTimelineView, isResourceEnabled, isMonthView, viewHeaderHeight, timeLabelWidth, - weekNumberPanelWidth); - } - : null, + weekNumberPanelWidth, + ); + } + : null, child: Stack( children: [ Positioned( - left: leftPosition, - right: rightPosition, - bottom: bottomPosition, - top: topPosition, - child: FocusScope( - node: _focusNode, - onKeyEvent: _onKeyDown, - child: isTimelineView - ? Listener( + left: leftPosition, + right: rightPosition, + bottom: bottomPosition, + top: topPosition, + child: FocusScope( + node: _focusNode, + onKeyEvent: _onKeyDown, + child: + isTimelineView + ? Listener( onPointerSignal: _handlePointerSignal, child: RawGestureDetector( - gestures: { - HorizontalDragGestureRecognizer: - GestureRecognizerFactoryWithHandlers< - HorizontalDragGestureRecognizer>( - () => HorizontalDragGestureRecognizer(), - (HorizontalDragGestureRecognizer instance) { - instance.onUpdate = - (DragUpdateDetails details) { + gestures: { + HorizontalDragGestureRecognizer: + GestureRecognizerFactoryWithHandlers< + HorizontalDragGestureRecognizer + >(() => HorizontalDragGestureRecognizer(), ( + HorizontalDragGestureRecognizer instance, + ) { + instance.onUpdate = ( + DragUpdateDetails details, + ) { _handleDragUpdate( - details, - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - resourceItemHeight, - weekNumberPanelWidth, - isNeedDragAndDrop, - resourceViewSize); + details, + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + resourceItemHeight, + weekNumberPanelWidth, + isNeedDragAndDrop, + resourceViewSize, + ); }; - instance.onStart = - (DragStartDetails details) { + instance.onStart = ( + DragStartDetails details, + ) { _handleDragStart( - details, - isNeedDragAndDrop, - isTimelineView, - isResourceEnabled, - viewHeaderHeight, - timeLabelWidth, - resourceViewSize); + details, + isNeedDragAndDrop, + isTimelineView, + isResourceEnabled, + viewHeaderHeight, + timeLabelWidth, + resourceViewSize, + ); }; instance.onEnd = (DragEndDetails details) { _handleDragEnd( - details, - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - weekNumberPanelWidth, - isNeedDragAndDrop); + details, + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + weekNumberPanelWidth, + isNeedDragAndDrop, + ); }; instance.onCancel = _handleDragCancel; - }, - ) - }, - behavior: HitTestBehavior.opaque, - child: customScrollWidget), + }), + }, + behavior: HitTestBehavior.opaque, + child: customScrollWidget, + ), ) - : customScrollWidget, - )), + : customScrollWidget, + ), + ), Positioned( - left: 0, - right: 0, - bottom: 0, - top: 0, - child: IgnorePointer( - child: RepaintBoundary( - child: _DraggingAppointmentWidget( - _dragDetails, - widget.isRTL, - widget.textScaleFactor, - widget.isMobilePlatform, - AppointmentHelper.getAppointmentTextStyle( - widget.calendar.appointmentTextStyle, - widget.view, - widget.themeData), - widget.calendar.dragAndDropSettings, - widget.view, - _updateCalendarStateDetails.allDayPanelHeight, - viewHeaderHeight, - timeLabelWidth, - resourceItemHeight, - widget.calendarTheme, - widget.calendar, - widget.width, - widget.height)))) + left: 0, + right: 0, + bottom: 0, + top: 0, + child: IgnorePointer( + child: RepaintBoundary( + child: _DraggingAppointmentWidget( + _dragDetails, + widget.isRTL, + widget.textScaleFactor, + widget.isMobilePlatform, + AppointmentHelper.getAppointmentTextStyle( + widget.calendar.appointmentTextStyle, + widget.view, + widget.themeData, + ), + widget.calendar.dragAndDropSettings, + widget.view, + _updateCalendarStateDetails.allDayPanelHeight, + viewHeaderHeight, + timeLabelWidth, + resourceItemHeight, + widget.calendarTheme, + widget.calendar, + widget.width, + widget.height, + ), + ), + ), + ), ], ), ); @@ -780,44 +852,51 @@ class _CustomCalendarScrollViewState extends State } void _handleAppointmentDragStart( - AppointmentView appointmentView, - bool isTimelineView, - Offset details, - bool isResourceEnabled, - double viewHeaderHeight, - double timeLabelWidth) { + AppointmentView appointmentView, + bool isTimelineView, + Offset details, + bool isResourceEnabled, + double viewHeaderHeight, + double timeLabelWidth, + ) { final _CalendarViewState currentState = _getCurrentViewByVisibleDates()!; currentState._updateDraggingMouseCursor(true); _dragDetails.value.timeIntervalHeight = currentState._getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - currentState.widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + currentState.widget.visibleDates.length, + widget.isMobilePlatform, + ); _dragDetails.value.appointmentView = appointmentView; _dragDifferenceOffset = null; final Offset appointmentPosition = Offset( - widget.isRTL - ? appointmentView.appointmentRect!.right - : appointmentView.appointmentRect!.left, - appointmentView.appointmentRect!.top); + widget.isRTL + ? appointmentView.appointmentRect!.right + : appointmentView.appointmentRect!.left, + appointmentView.appointmentRect!.top, + ); double xPosition; double yPosition; if (isTimelineView) { - xPosition = (appointmentPosition.dx - + xPosition = + (appointmentPosition.dx - currentState._scrollController!.position.pixels) - details.dx; if (widget.isRTL) { - xPosition = currentState._scrollController!.offset + + xPosition = + currentState._scrollController!.offset + currentState._scrollController!.position.viewportDimension; - xPosition = xPosition - + xPosition = + xPosition - ((currentState._scrollController!.position.viewportDimension + currentState._scrollController!.position.maxScrollExtent) - appointmentPosition.dx); xPosition -= details.dx; } - yPosition = appointmentPosition.dy + + yPosition = + appointmentPosition.dy + viewHeaderHeight + timeLabelWidth - details.dy; @@ -831,11 +910,13 @@ class _CustomCalendarScrollViewState extends State yPosition = yPosition - details.dy; _dragDifferenceOffset = Offset(xPosition, yPosition); } else { - final double allDayHeight = currentState._isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : currentState._allDayHeight; + final double allDayHeight = + currentState._isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : currentState._allDayHeight; xPosition = appointmentPosition.dx - details.dx; - yPosition = appointmentPosition.dy + + yPosition = + appointmentPosition.dy + viewHeaderHeight + allDayHeight - currentState._scrollController!.position.pixels; @@ -854,7 +935,10 @@ class _CustomCalendarScrollViewState extends State yPosition = details.dy - viewHeaderHeight - timeLabelWidth; yPosition += currentState._timelineViewVerticalScrollController!.offset; selectedResourceIndex = currentState._getSelectedResourceIndex( - yPosition, viewHeaderHeight, timeLabelWidth); + yPosition, + viewHeaderHeight, + timeLabelWidth, + ); selectedResource = widget.calendar.dataSource!.resources![selectedResourceIndex]; } @@ -864,23 +948,29 @@ class _CustomCalendarScrollViewState extends State ? null : _dragDetails.value.appointmentView!.appointment!.actualStartTime; final dynamic dragStartAppointment = _getCalendarAppointmentToObject( - appointmentView.appointment, widget.calendar); + appointmentView.appointment, + widget.calendar, + ); if (widget.calendar.onDragStart != null) { widget.calendar.onDragStart!( - AppointmentDragStartDetails(dragStartAppointment, selectedResource)); + AppointmentDragStartDetails(dragStartAppointment, selectedResource), + ); } } void _handleLongPressStart( - LongPressStartDetails details, - bool isNeedDragAndDrop, - bool isTimelineView, - bool isResourceEnabled, - double viewHeaderHeight, - double timeLabelWidth) { + LongPressStartDetails details, + bool isNeedDragAndDrop, + bool isTimelineView, + bool isResourceEnabled, + double viewHeaderHeight, + double timeLabelWidth, + ) { final _CalendarViewState currentState = _getCurrentViewByVisibleDates()!; - AppointmentView? appointmentView = - _getDragAppointment(details, currentState); + AppointmentView? appointmentView = _getDragAppointment( + details, + currentState, + ); if (!isNeedDragAndDrop || appointmentView == null) { _dragDetails.value.position.value = null; return; @@ -888,16 +978,19 @@ class _CustomCalendarScrollViewState extends State currentState._removeAllWidgetHovering(); appointmentView = appointmentView.clone(); _handleAppointmentDragStart( - appointmentView, - isTimelineView, - details.localPosition, - isResourceEnabled, - viewHeaderHeight, - timeLabelWidth); + appointmentView, + isTimelineView, + details.localPosition, + isResourceEnabled, + viewHeaderHeight, + timeLabelWidth, + ); } AppointmentView? _getDragAppointment( - LongPressStartDetails details, _CalendarViewState currentState) { + LongPressStartDetails details, + _CalendarViewState currentState, + ) { if (CalendarViewHelper.isTimelineView(widget.view)) { return currentState._handleTouchOnTimeline(null, details); } else if (widget.view == CalendarView.month) { @@ -909,97 +1002,105 @@ class _CustomCalendarScrollViewState extends State } void _handleLongPressMove( - Offset details, - bool isTimelineView, - bool isResourceEnabled, - bool isMonthView, - double viewHeaderHeight, - double timeLabelWidth, - double resourceItemHeight, - double weekNumberPanelWidth) { + Offset details, + bool isTimelineView, + bool isResourceEnabled, + bool isMonthView, + double viewHeaderHeight, + double timeLabelWidth, + double resourceItemHeight, + double weekNumberPanelWidth, + ) { if (_dragDetails.value.appointmentView == null) { return; } final Offset appointmentPosition = details + _dragDifferenceOffset!; final _CalendarViewState currentState = _getCurrentViewByVisibleDates()!; - final double allDayHeight = currentState._isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : currentState._allDayHeight; + final double allDayHeight = + currentState._isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : currentState._allDayHeight; final double timeIntervalHeight = currentState._getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - currentState.widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + currentState.widget.visibleDates.length, + widget.isMobilePlatform, + ); if (isTimelineView) { _updateAutoScrollDragTimelineView( - currentState, - appointmentPosition, - viewHeaderHeight, - timeIntervalHeight, - resourceItemHeight, - isResourceEnabled, - details, - isMonthView, - allDayHeight, - isTimelineView, - timeLabelWidth, - weekNumberPanelWidth); + currentState, + appointmentPosition, + viewHeaderHeight, + timeIntervalHeight, + resourceItemHeight, + isResourceEnabled, + details, + isMonthView, + allDayHeight, + isTimelineView, + timeLabelWidth, + weekNumberPanelWidth, + ); } else { _updateNavigationDayView( - currentState, - appointmentPosition, - viewHeaderHeight, - allDayHeight, - timeIntervalHeight, - timeLabelWidth, - isResourceEnabled, - isTimelineView, - isMonthView, - details, - weekNumberPanelWidth); - } - - _dragDetails.value.position.value = appointmentPosition; - _updateAppointmentDragUpdateCallback( - isTimelineView, + currentState, + appointmentPosition, viewHeaderHeight, - timeLabelWidth, allDayHeight, - appointmentPosition, - isMonthView, timeIntervalHeight, - currentState, - details, + timeLabelWidth, isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + isMonthView, + details, + weekNumberPanelWidth, + ); + } + + _dragDetails.value.position.value = appointmentPosition; + _updateAppointmentDragUpdateCallback( + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); } Future _updateNavigationDayView( - _CalendarViewState currentState, - Offset appointmentPosition, - double viewHeaderHeight, - double allDayHeight, - double timeIntervalHeight, - double timeLabelWidth, - bool isResourceEnabled, - bool isTimelineView, - bool isMonthView, - Offset details, - double weekNumberPanelWidth) async { + _CalendarViewState currentState, + Offset appointmentPosition, + double viewHeaderHeight, + double allDayHeight, + double timeIntervalHeight, + double timeLabelWidth, + bool isResourceEnabled, + bool isTimelineView, + bool isMonthView, + Offset details, + double weekNumberPanelWidth, + ) async { if (_dragDetails.value.appointmentView == null) { return; } double navigationThresholdValue = 0; final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); if (isDayView) { navigationThresholdValue = _dragDetails.value.appointmentView!.appointmentRect!.width * 0.1; @@ -1012,8 +1113,8 @@ class _CustomCalendarScrollViewState extends State final bool isHorizontalNavigation = widget.calendar.monthViewSettings.navigationDirection == - MonthNavigationDirection.horizontal || - widget.view != CalendarView.month; + MonthNavigationDirection.horizontal || + widget.view != CalendarView.month; if (widget.calendar.dragAndDropSettings.allowScroll && widget.view != CalendarView.month && @@ -1030,7 +1131,7 @@ class _CustomCalendarScrollViewState extends State Future updateScrollPosition() async { double scrollPosition = currentState._scrollController!.position.pixels - - timeIntervalHeight; + timeIntervalHeight; if (scrollPosition < 0) { scrollPosition = 0; } @@ -1041,17 +1142,18 @@ class _CustomCalendarScrollViewState extends State ); _updateAppointmentDragUpdateCallback( - isTimelineView, - viewHeaderHeight, - timeLabelWidth, - allDayHeight, - appointmentPosition, - isMonthView, - timeIntervalHeight, - currentState, - details, - isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dy <= @@ -1084,14 +1186,17 @@ class _CustomCalendarScrollViewState extends State if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dy + _dragDetails - .value.appointmentView!.appointmentRect!.height >= + .value + .appointmentView! + .appointmentRect! + .height >= widget.height && currentState._scrollController!.position.pixels != currentState._scrollController!.position.maxScrollExtent) { Future updateScrollPosition() async { double scrollPosition = currentState._scrollController!.position.pixels + - timeIntervalHeight; + timeIntervalHeight; if (scrollPosition > currentState._scrollController!.position.maxScrollExtent) { scrollPosition = @@ -1105,22 +1210,26 @@ class _CustomCalendarScrollViewState extends State ); _updateAppointmentDragUpdateCallback( - isTimelineView, - viewHeaderHeight, - timeLabelWidth, - allDayHeight, - appointmentPosition, - isMonthView, - timeIntervalHeight, - currentState, - details, - isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dy + _dragDetails - .value.appointmentView!.appointmentRect!.height >= + .value + .appointmentView! + .appointmentRect! + .height >= widget.height && currentState._scrollController!.position.pixels != currentState._scrollController!.position.maxScrollExtent) { @@ -1140,41 +1249,53 @@ class _CustomCalendarScrollViewState extends State } else if (widget.calendar.dragAndDropSettings.allowNavigation && ((isHorizontalNavigation && (appointmentPosition.dx + - _dragDetails.value.appointmentView!.appointmentRect! + _dragDetails + .value + .appointmentView! + .appointmentRect! .width) - rtlValue >= widget.width) || (!isHorizontalNavigation && (appointmentPosition.dy + _dragDetails - .value.appointmentView!.appointmentRect!.height >= + .value + .appointmentView! + .appointmentRect! + .height >= widget.height)))) { if (_timer != null) { return; } - _timer = - Timer.periodic(widget.calendar.dragAndDropSettings.autoNavigateDelay, - (Timer timer) async { - if (_dragDetails.value.position.value != null && - ((isHorizontalNavigation && - (_dragDetails.value.position.value!.dx + - _dragDetails.value.appointmentView! - .appointmentRect!.width) - - rtlValue >= - widget.width + navigationThresholdValue) || - (!isHorizontalNavigation && - _dragDetails.value.position.value!.dy + - _dragDetails.value.appointmentView!.appointmentRect! - .height >= - widget.height))) { - if (widget.isRTL) { - _moveToPreviousViewWithAnimation(); - } else { - _moveToNextViewWithAnimation(); - } - currentState = _getCurrentViewByVisibleDates()!; - currentState._updateDraggingMouseCursor(true); - _updateAppointmentDragUpdateCallback( + _timer = Timer.periodic( + widget.calendar.dragAndDropSettings.autoNavigateDelay, + (Timer timer) async { + if (_dragDetails.value.position.value != null && + ((isHorizontalNavigation && + (_dragDetails.value.position.value!.dx + + _dragDetails + .value + .appointmentView! + .appointmentRect! + .width) - + rtlValue >= + widget.width + navigationThresholdValue) || + (!isHorizontalNavigation && + _dragDetails.value.position.value!.dy + + _dragDetails + .value + .appointmentView! + .appointmentRect! + .height >= + widget.height))) { + if (widget.isRTL) { + _moveToPreviousViewWithAnimation(); + } else { + _moveToNextViewWithAnimation(); + } + currentState = _getCurrentViewByVisibleDates()!; + currentState._updateDraggingMouseCursor(true); + _updateAppointmentDragUpdateCallback( isTimelineView, viewHeaderHeight, timeLabelWidth, @@ -1185,12 +1306,14 @@ class _CustomCalendarScrollViewState extends State currentState, details, isResourceEnabled, - weekNumberPanelWidth); - } else if (_timer != null) { - _timer!.cancel(); - _timer = null; - } - }); + weekNumberPanelWidth, + ); + } else if (_timer != null) { + _timer!.cancel(); + _timer = null; + } + }, + ); } else if (widget.calendar.dragAndDropSettings.allowNavigation && ((isHorizontalNavigation && (appointmentPosition.dx + navigationThresholdValue) - @@ -1219,17 +1342,18 @@ class _CustomCalendarScrollViewState extends State currentState = _getCurrentViewByVisibleDates()!; currentState._updateDraggingMouseCursor(true); _updateAppointmentDragUpdateCallback( - isTimelineView, - viewHeaderHeight, - timeLabelWidth, - allDayHeight, - appointmentPosition, - isMonthView, - timeIntervalHeight, - currentState, - details, - isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); } else if (_timer != null) { _timer!.cancel(); _timer = null; @@ -1239,18 +1363,19 @@ class _CustomCalendarScrollViewState extends State } Future _updateAutoScrollDragTimelineView( - _CalendarViewState currentState, - Offset appointmentPosition, - double viewHeaderHeight, - double timeIntervalHeight, - double resourceItemHeight, - bool isResourceEnabled, - Offset details, - bool isMonthView, - double allDayHeight, - bool isTimelineView, - double timeLabelWidth, - double weekNumberPanelWidth) async { + _CalendarViewState currentState, + Offset appointmentPosition, + double viewHeaderHeight, + double timeIntervalHeight, + double resourceItemHeight, + bool isResourceEnabled, + Offset details, + bool isMonthView, + double allDayHeight, + bool isTimelineView, + double timeLabelWidth, + double weekNumberPanelWidth, + ) async { if (_dragDetails.value.appointmentView == null) { return; } @@ -1275,15 +1400,18 @@ class _CustomCalendarScrollViewState extends State ((widget.isRTL && currentState._scrollController!.position.pixels != currentState - ._scrollController!.position.maxScrollExtent) || + ._scrollController! + .position + .maxScrollExtent) || (!widget.isRTL && currentState._scrollController!.position.pixels != 0))) { Future updateScrollPosition() async { double scrollPosition = currentState._scrollController!.position.pixels - - timeIntervalHeight; + timeIntervalHeight; if (widget.isRTL) { - scrollPosition = currentState._scrollController!.position.pixels + + scrollPosition = + currentState._scrollController!.position.pixels + timeIntervalHeight; } if (!widget.isRTL && scrollPosition < 0) { @@ -1301,24 +1429,27 @@ class _CustomCalendarScrollViewState extends State ); _updateAppointmentDragUpdateCallback( - isTimelineView, - viewHeaderHeight, - timeLabelWidth, - allDayHeight, - appointmentPosition, - isMonthView, - timeIntervalHeight, - currentState, - details, - isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dx - rtlValue <= 0 && ((widget.isRTL && currentState._scrollController!.position.pixels != currentState - ._scrollController!.position.maxScrollExtent) || + ._scrollController! + .position + .maxScrollExtent) || (!widget.isRTL && currentState._scrollController!.position.pixels != 0))) { @@ -1327,19 +1458,20 @@ class _CustomCalendarScrollViewState extends State _timer!.cancel(); _timer = null; _updateAutoViewNavigationTimelineView( - currentState, - appointmentPosition, - viewHeaderHeight, - timeIntervalHeight, - resourceItemHeight, - isResourceEnabled, - details, - isMonthView, - allDayHeight, - isTimelineView, - timeLabelWidth, - weekNumberPanelWidth, - rtlValue); + currentState, + appointmentPosition, + viewHeaderHeight, + timeIntervalHeight, + resourceItemHeight, + isResourceEnabled, + details, + isMonthView, + allDayHeight, + isTimelineView, + timeLabelWidth, + weekNumberPanelWidth, + rtlValue, + ); } } @@ -1348,25 +1480,29 @@ class _CustomCalendarScrollViewState extends State _timer!.cancel(); _timer = null; _updateAutoViewNavigationTimelineView( - currentState, - appointmentPosition, - viewHeaderHeight, - timeIntervalHeight, - resourceItemHeight, - isResourceEnabled, - details, - isMonthView, - allDayHeight, - isTimelineView, - timeLabelWidth, - weekNumberPanelWidth, - rtlValue); + currentState, + appointmentPosition, + viewHeaderHeight, + timeIntervalHeight, + resourceItemHeight, + isResourceEnabled, + details, + isMonthView, + allDayHeight, + isTimelineView, + timeLabelWidth, + weekNumberPanelWidth, + rtlValue, + ); } }); } else if (widget.calendar.dragAndDropSettings.allowScroll && (appointmentPosition.dx + _dragDetails - .value.appointmentView!.appointmentRect!.width) - + .value + .appointmentView! + .appointmentRect! + .width) - rtlValue >= widget.width && ((widget.isRTL && @@ -1374,7 +1510,9 @@ class _CustomCalendarScrollViewState extends State (!widget.isRTL && currentState._scrollController!.position.pixels != currentState - ._scrollController!.position.maxScrollExtent))) { + ._scrollController! + .position + .maxScrollExtent))) { if (_timer != null) { return; } @@ -1382,7 +1520,10 @@ class _CustomCalendarScrollViewState extends State if (_dragDetails.value.position.value != null && (_dragDetails.value.position.value!.dx + _dragDetails - .value.appointmentView!.appointmentRect!.width) - + .value + .appointmentView! + .appointmentRect! + .width) - rtlValue >= widget.width && ((widget.isRTL && @@ -1390,13 +1531,16 @@ class _CustomCalendarScrollViewState extends State (!widget.isRTL && currentState._scrollController!.position.pixels != currentState - ._scrollController!.position.maxScrollExtent))) { + ._scrollController! + .position + .maxScrollExtent))) { Future updateScrollPosition() async { double scrollPosition = currentState._scrollController!.position.pixels + - timeIntervalHeight; + timeIntervalHeight; if (widget.isRTL) { - scrollPosition = currentState._scrollController!.position.pixels - + scrollPosition = + currentState._scrollController!.position.pixels - timeIntervalHeight; } if (!widget.isRTL && @@ -1415,21 +1559,25 @@ class _CustomCalendarScrollViewState extends State ); _updateAppointmentDragUpdateCallback( - isTimelineView, - viewHeaderHeight, - timeLabelWidth, - allDayHeight, - appointmentPosition, - isMonthView, - timeIntervalHeight, - currentState, - details, - isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); if (_dragDetails.value.position.value != null && (_dragDetails.value.position.value!.dx + - _dragDetails.value.appointmentView!.appointmentRect! + _dragDetails + .value + .appointmentView! + .appointmentRect! .width) - rtlValue >= widget.width && @@ -1437,26 +1585,29 @@ class _CustomCalendarScrollViewState extends State currentState._scrollController!.position.pixels != 0) || (!widget.isRTL && currentState._scrollController!.position.pixels != - currentState._scrollController!.position + currentState + ._scrollController! + .position .maxScrollExtent))) { updateScrollPosition(); } else if (_timer != null) { _timer!.cancel(); _timer = null; _updateAutoViewNavigationTimelineView( - currentState, - appointmentPosition, - viewHeaderHeight, - timeIntervalHeight, - resourceItemHeight, - isResourceEnabled, - details, - isMonthView, - allDayHeight, - isTimelineView, - timeLabelWidth, - weekNumberPanelWidth, - rtlValue); + currentState, + appointmentPosition, + viewHeaderHeight, + timeIntervalHeight, + resourceItemHeight, + isResourceEnabled, + details, + isMonthView, + allDayHeight, + isTimelineView, + timeLabelWidth, + weekNumberPanelWidth, + rtlValue, + ); } } @@ -1465,37 +1616,39 @@ class _CustomCalendarScrollViewState extends State _timer!.cancel(); _timer = null; _updateAutoViewNavigationTimelineView( - currentState, - appointmentPosition, - viewHeaderHeight, - timeIntervalHeight, - resourceItemHeight, - isResourceEnabled, - details, - isMonthView, - allDayHeight, - isTimelineView, - timeLabelWidth, - weekNumberPanelWidth, - rtlValue); + currentState, + appointmentPosition, + viewHeaderHeight, + timeIntervalHeight, + resourceItemHeight, + isResourceEnabled, + details, + isMonthView, + allDayHeight, + isTimelineView, + timeLabelWidth, + weekNumberPanelWidth, + rtlValue, + ); } }); } _updateAutoViewNavigationTimelineView( - currentState, - appointmentPosition, - viewHeaderHeight, - timeIntervalHeight, - resourceItemHeight, - isResourceEnabled, - details, - isMonthView, - allDayHeight, - isTimelineView, - timeLabelWidth, - weekNumberPanelWidth, - rtlValue); + currentState, + appointmentPosition, + viewHeaderHeight, + timeIntervalHeight, + resourceItemHeight, + isResourceEnabled, + details, + isMonthView, + allDayHeight, + isTimelineView, + timeLabelWidth, + weekNumberPanelWidth, + rtlValue, + ); if (_dragDetails.value.appointmentView == null) { return; @@ -1516,28 +1669,35 @@ class _CustomCalendarScrollViewState extends State timeIntervalHeight <= 0 && currentState - ._timelineViewVerticalScrollController!.position.pixels != + ._timelineViewVerticalScrollController! + .position + .pixels != 0) { Future updateScrollPosition() async { - double scrollPosition = currentState - ._timelineViewVerticalScrollController!.position.pixels - + double scrollPosition = + currentState + ._timelineViewVerticalScrollController! + .position + .pixels - resourceItemHeight; if (scrollPosition < 0) { scrollPosition = 0; } await currentState._timelineViewVerticalScrollController!.position .moveTo( - scrollPosition, - duration: const Duration(milliseconds: 100), - curve: Curves.easeInOut, - ); + scrollPosition, + duration: const Duration(milliseconds: 100), + curve: Curves.easeInOut, + ); if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dy - viewHeaderHeight - timeIntervalHeight <= 0 && - currentState._timelineViewVerticalScrollController!.position + currentState + ._timelineViewVerticalScrollController! + .position .pixels != 0) { updateScrollPosition(); @@ -1558,7 +1718,9 @@ class _CustomCalendarScrollViewState extends State _dragDetails.value.appointmentView!.appointmentRect!.height >= widget.height && currentState._timelineViewVerticalScrollController!.position.pixels != - currentState._timelineViewVerticalScrollController!.position + currentState + ._timelineViewVerticalScrollController! + .position .maxScrollExtent) { if (_timer != null) { return; @@ -1567,41 +1729,61 @@ class _CustomCalendarScrollViewState extends State if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dy + _dragDetails - .value.appointmentView!.appointmentRect!.height >= + .value + .appointmentView! + .appointmentRect! + .height >= widget.height && currentState - ._timelineViewVerticalScrollController!.position.pixels != - currentState._timelineViewVerticalScrollController!.position + ._timelineViewVerticalScrollController! + .position + .pixels != + currentState + ._timelineViewVerticalScrollController! + .position .maxScrollExtent) { Future updateScrollPosition() async { - double scrollPosition = currentState - ._timelineViewVerticalScrollController!.position.pixels + + double scrollPosition = + currentState + ._timelineViewVerticalScrollController! + .position + .pixels + resourceItemHeight; if (scrollPosition > - currentState._timelineViewVerticalScrollController!.position + currentState + ._timelineViewVerticalScrollController! + .position .maxScrollExtent) { - scrollPosition = currentState - ._timelineViewVerticalScrollController! - .position - .maxScrollExtent; + scrollPosition = + currentState + ._timelineViewVerticalScrollController! + .position + .maxScrollExtent; } await currentState._timelineViewVerticalScrollController!.position .moveTo( - scrollPosition, - duration: const Duration(milliseconds: 100), - curve: Curves.easeInOut, - ); + scrollPosition, + duration: const Duration(milliseconds: 100), + curve: Curves.easeInOut, + ); if (_dragDetails.value.position.value != null && _dragDetails.value.position.value!.dy + _dragDetails - .value.appointmentView!.appointmentRect!.height >= + .value + .appointmentView! + .appointmentRect! + .height >= widget.height && - currentState._timelineViewVerticalScrollController!.position + currentState + ._timelineViewVerticalScrollController! + .position .pixels != - currentState._timelineViewVerticalScrollController! - .position.maxScrollExtent) { + currentState + ._timelineViewVerticalScrollController! + .position + .maxScrollExtent) { updateScrollPosition(); } else if (_timer != null) { _timer!.cancel(); @@ -1620,23 +1802,27 @@ class _CustomCalendarScrollViewState extends State } void _updateAutoViewNavigationTimelineView( - _CalendarViewState currentState, - Offset appointmentPosition, - double viewHeaderHeight, - double timeIntervalHeight, - double resourceItemHeight, - bool isResourceEnabled, - dynamic details, - bool isMonthView, - double allDayHeight, - bool isTimelineView, - double timeLabelWidth, - double weekNumberPanelWidth, - double rtlValue) { + _CalendarViewState currentState, + Offset appointmentPosition, + double viewHeaderHeight, + double timeIntervalHeight, + double resourceItemHeight, + bool isResourceEnabled, + dynamic details, + bool isMonthView, + double allDayHeight, + bool isTimelineView, + double timeLabelWidth, + double weekNumberPanelWidth, + double rtlValue, + ) { if (widget.calendar.dragAndDropSettings.allowNavigation && (appointmentPosition.dx + _dragDetails - .value.appointmentView!.appointmentRect!.width) - + .value + .appointmentView! + .appointmentRect! + .width) - rtlValue >= widget.width && ((!widget.isRTL && @@ -1646,29 +1832,34 @@ class _CustomCalendarScrollViewState extends State if (_timer != null) { return; } - _timer = - Timer.periodic(widget.calendar.dragAndDropSettings.autoNavigateDelay, - (Timer timer) async { - if (_dragDetails.value.position.value != null && - (_dragDetails.value.position.value!.dx + - _dragDetails - .value.appointmentView!.appointmentRect!.width) - - rtlValue >= - widget.width && - ((!widget.isRTL && - currentState._scrollController!.offset == - currentState - ._scrollController!.position.maxScrollExtent) || - (widget.isRTL && - currentState._scrollController!.offset == 0))) { - if (widget.isRTL) { - _moveToPreviousViewWithAnimation(isScrollToEnd: true); - } else { - _moveToNextViewWithAnimation(); - } - currentState = _getCurrentViewByVisibleDates()!; - currentState._updateDraggingMouseCursor(true); - _updateAppointmentDragUpdateCallback( + _timer = Timer.periodic( + widget.calendar.dragAndDropSettings.autoNavigateDelay, + (Timer timer) async { + if (_dragDetails.value.position.value != null && + (_dragDetails.value.position.value!.dx + + _dragDetails + .value + .appointmentView! + .appointmentRect! + .width) - + rtlValue >= + widget.width && + ((!widget.isRTL && + currentState._scrollController!.offset == + currentState + ._scrollController! + .position + .maxScrollExtent) || + (widget.isRTL && + currentState._scrollController!.offset == 0))) { + if (widget.isRTL) { + _moveToPreviousViewWithAnimation(isScrollToEnd: true); + } else { + _moveToNextViewWithAnimation(); + } + currentState = _getCurrentViewByVisibleDates()!; + currentState._updateDraggingMouseCursor(true); + _updateAppointmentDragUpdateCallback( isTimelineView, viewHeaderHeight, timeLabelWidth, @@ -1679,12 +1870,14 @@ class _CustomCalendarScrollViewState extends State currentState, details, isResourceEnabled, - weekNumberPanelWidth); - } else if (_timer != null) { - _timer!.cancel(); - _timer = null; - } - }); + weekNumberPanelWidth, + ); + } else if (_timer != null) { + _timer!.cancel(); + _timer = null; + } + }, + ); } else if (widget.calendar.dragAndDropSettings.allowNavigation && ((appointmentPosition.dx) - rtlValue).truncate() <= 0 && ((widget.isRTL && @@ -1701,7 +1894,9 @@ class _CustomCalendarScrollViewState extends State ((widget.isRTL && currentState._scrollController!.position.pixels == currentState - ._scrollController!.position.maxScrollExtent) || + ._scrollController! + .position + .maxScrollExtent) || (!widget.isRTL && currentState._scrollController!.offset == 0))) { if (widget.isRTL) { @@ -1712,17 +1907,18 @@ class _CustomCalendarScrollViewState extends State currentState = _getCurrentViewByVisibleDates()!; currentState._updateDraggingMouseCursor(true); _updateAppointmentDragUpdateCallback( - isTimelineView, - viewHeaderHeight, - timeLabelWidth, - allDayHeight, - appointmentPosition, - isMonthView, - timeIntervalHeight, - currentState, - details, - isResourceEnabled, - weekNumberPanelWidth); + isTimelineView, + viewHeaderHeight, + timeLabelWidth, + allDayHeight, + appointmentPosition, + isMonthView, + timeIntervalHeight, + currentState, + details, + isResourceEnabled, + weekNumberPanelWidth, + ); } else if (_timer != null) { _timer!.cancel(); _timer = null; @@ -1732,17 +1928,18 @@ class _CustomCalendarScrollViewState extends State } void _updateAppointmentDragUpdateCallback( - bool isTimelineView, - double viewHeaderHeight, - double timeLabelWidth, - double allDayHeight, - Offset appointmentPosition, - bool isMonthView, - double timeIntervalHeight, - _CalendarViewState currentState, - Offset details, - bool isResourceEnabled, - double weekNumberPanelWidth) { + bool isTimelineView, + double viewHeaderHeight, + double timeLabelWidth, + double allDayHeight, + Offset appointmentPosition, + bool isMonthView, + double timeIntervalHeight, + _CalendarViewState currentState, + Offset details, + bool isResourceEnabled, + double weekNumberPanelWidth, + ) { if (_dragDetails.value.appointmentView == null) { return; } @@ -1792,21 +1989,24 @@ class _CustomCalendarScrollViewState extends State xPosition = widget.width - 1; } - final double overAllWidth = isTimelineView - ? currentState._timeIntervalHeight * - (currentState._horizontalLinesCount! * - currentState.widget.visibleDates.length) - : widget.width; - final double overAllHeight = isTimelineView || isMonthView - ? widget.height - : currentState._timeIntervalHeight * - currentState._horizontalLinesCount!; + final double overAllWidth = + isTimelineView + ? currentState._timeIntervalHeight * + (currentState._horizontalLinesCount! * + currentState.widget.visibleDates.length) + : widget.width; + final double overAllHeight = + isTimelineView || isMonthView + ? widget.height + : currentState._timeIntervalHeight * + currentState._horizontalLinesCount!; if (isTimelineView && overAllWidth < widget.width && xPosition + _dragDetails.value.appointmentView!.appointmentRect!.width > overAllWidth) { - xPosition = overAllWidth - + xPosition = + overAllWidth - _dragDetails.value.appointmentView!.appointmentRect!.width; } else if (!isTimelineView && !isMonthView && @@ -1814,63 +2014,85 @@ class _CustomCalendarScrollViewState extends State yPosition + _dragDetails.value.appointmentView!.appointmentRect!.height > overAllHeight) { - yPosition = overAllHeight - + yPosition = + overAllHeight - _dragDetails.value.appointmentView!.appointmentRect!.height; } - draggingTime = currentState._getDateFromPosition( - xPosition, yPosition, timeLabelWidth)!; + draggingTime = + currentState._getDateFromPosition( + xPosition, + yPosition, + timeLabelWidth, + )!; if (!isMonthView) { if (isTimelineView) { - final DateTime time = _timeFromPosition( - draggingTime, - widget.calendar.timeSlotViewSettings, - xPosition, - currentState, - timeIntervalHeight, - isTimelineView)!; - - draggingTime = DateTime(draggingTime.year, draggingTime.month, - draggingTime.day, time.hour, time.minute); - } else { - if (yPosition < 0) { - draggingTime = - DateTime(draggingTime.year, draggingTime.month, draggingTime.day); - } else { - draggingTime = _timeFromPosition( + final DateTime time = + _timeFromPosition( draggingTime, widget.calendar.timeSlotViewSettings, - yPosition, + xPosition, currentState, timeIntervalHeight, - isTimelineView)!; + isTimelineView, + )!; + + draggingTime = DateTime( + draggingTime.year, + draggingTime.month, + draggingTime.day, + time.hour, + time.minute, + ); + } else { + if (yPosition < 0) { + draggingTime = DateTime( + draggingTime.year, + draggingTime.month, + draggingTime.day, + ); + } else { + draggingTime = + _timeFromPosition( + draggingTime, + widget.calendar.timeSlotViewSettings, + yPosition, + currentState, + timeIntervalHeight, + isTimelineView, + )!; } } } _dragDetails.value.position.value = Offset( - _dragDetails.value.position.value!.dx, - _dragDetails.value.position.value!.dy - 0.1); + _dragDetails.value.position.value!.dx, + _dragDetails.value.position.value!.dy - 0.1, + ); _dragDetails.value.draggingTime = yPosition <= 0 && widget.view != CalendarView.month && !isTimelineView ? null : draggingTime; _dragDetails.value.position.value = Offset( - _dragDetails.value.position.value!.dx, - _dragDetails.value.position.value!.dy + 0.1); + _dragDetails.value.position.value!.dx, + _dragDetails.value.position.value!.dy + 0.1, + ); final dynamic draggingAppointment = _getCalendarAppointmentToObject( - _dragDetails.value.appointmentView!.appointment, widget.calendar); + _dragDetails.value.appointmentView!.appointment, + widget.calendar, + ); CalendarResource? selectedResource, previousResource; int targetResourceIndex = -1; int sourceSelectedResourceIndex = -1; if (isResourceEnabled) { targetResourceIndex = currentState._getSelectedResourceIndex( - appointmentPosition.dy + - currentState._timelineViewVerticalScrollController!.offset, - viewHeaderHeight, - timeLabelWidth); + appointmentPosition.dy + + currentState._timelineViewVerticalScrollController!.offset, + viewHeaderHeight, + timeLabelWidth, + ); if (targetResourceIndex > widget.calendar.dataSource!.resources!.length - 1) { targetResourceIndex = widget.calendar.dataSource!.resources!.length - 1; @@ -1878,48 +2100,57 @@ class _CustomCalendarScrollViewState extends State selectedResource = widget.calendar.dataSource!.resources![targetResourceIndex]; sourceSelectedResourceIndex = currentState._getSelectedResourceIndex( - _dragDetails.value.appointmentView!.appointmentRect!.top, - viewHeaderHeight, - timeLabelWidth); + _dragDetails.value.appointmentView!.appointmentRect!.top, + viewHeaderHeight, + timeLabelWidth, + ); previousResource = widget.calendar.dataSource!.resources![sourceSelectedResourceIndex]; } - final int currentMonth = currentState.widget - .visibleDates[currentState.widget.visibleDates.length ~/ 2].month; + final int currentMonth = + currentState + .widget + .visibleDates[currentState.widget.visibleDates.length ~/ 2] + .month; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); final DateTime updateStartTime = draggingTime; - final Duration appointmentDuration = _dragDetails - .value.appointmentView!.appointment!.isAllDay && - widget.view != CalendarView.month && - !isTimelineView - ? const Duration(hours: 1) - : _dragDetails.value.appointmentView!.appointment!.endTime.difference( - _dragDetails.value.appointmentView!.appointment!.startTime); + final Duration appointmentDuration = + _dragDetails.value.appointmentView!.appointment!.isAllDay && + widget.view != CalendarView.month && + !isTimelineView + ? const Duration(hours: 1) + : _dragDetails.value.appointmentView!.appointment!.endTime + .difference( + _dragDetails.value.appointmentView!.appointment!.startTime, + ); final DateTime updatedEndTime = updateStartTime.add(appointmentDuration); if (CalendarViewHelper.isDraggingAppointmentHasDisabledCell( - _getTimeRegions(), - _getBlackoutDates(), - updateStartTime, - updatedEndTime, - isTimelineView, - isMonthView, - widget.calendar.minDate, - widget.calendar.maxDate, - timeInterval, - targetResourceIndex, - widget.resourceCollection) || + _getTimeRegions(), + _getBlackoutDates(), + updateStartTime, + updatedEndTime, + isTimelineView, + isMonthView, + widget.calendar.minDate, + widget.calendar.maxDate, + timeInterval, + targetResourceIndex, + widget.resourceCollection, + ) || (widget.view == CalendarView.month && !CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - draggingTime))) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + draggingTime, + ))) { currentState._updateDisabledCellMouseCursor(true); } else { currentState._updateDisabledCellMouseCursor(false); @@ -1930,23 +2161,27 @@ class _CustomCalendarScrollViewState extends State } if (widget.calendar.onDragUpdate != null) { - widget.calendar.onDragUpdate!(AppointmentDragUpdateDetails( + widget.calendar.onDragUpdate!( + AppointmentDragUpdateDetails( draggingAppointment, previousResource, selectedResource, appointmentPosition, - _dragDetails.value.draggingTime)); + _dragDetails.value.draggingTime, + ), + ); } } void _handleLongPressEnd( - Offset details, - bool isTimelineView, - bool isResourceEnabled, - bool isMonthView, - double viewHeaderHeight, - double timeLabelWidth, - double weekNumberPanelWidth) { + Offset details, + bool isTimelineView, + bool isResourceEnabled, + bool isMonthView, + double viewHeaderHeight, + double timeLabelWidth, + double weekNumberPanelWidth, + ) { if (_dragDetails.value.appointmentView == null) { return; } @@ -1958,16 +2193,18 @@ class _CustomCalendarScrollViewState extends State final Offset appointmentPosition = details + _dragDifferenceOffset!; final _CalendarViewState currentState = _getCurrentViewByVisibleDates()!; - final double allDayHeight = currentState._isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : currentState._allDayHeight; + final double allDayHeight = + currentState._isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : currentState._allDayHeight; final double timeIntervalHeight = currentState._getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - currentState.widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + currentState.widget.visibleDates.length, + widget.isMobilePlatform, + ); double xPosition = details.dx; double yPosition = appointmentPosition.dy; if (isTimelineView) { @@ -2006,21 +2243,24 @@ class _CustomCalendarScrollViewState extends State xPosition = widget.width - 1; } - final double overAllWidth = isTimelineView - ? currentState._timeIntervalHeight * - (currentState._horizontalLinesCount! * - currentState.widget.visibleDates.length) - : widget.width; - final double overAllHeight = isTimelineView || isMonthView - ? widget.height - : currentState._timeIntervalHeight * - currentState._horizontalLinesCount!; + final double overAllWidth = + isTimelineView + ? currentState._timeIntervalHeight * + (currentState._horizontalLinesCount! * + currentState.widget.visibleDates.length) + : widget.width; + final double overAllHeight = + isTimelineView || isMonthView + ? widget.height + : currentState._timeIntervalHeight * + currentState._horizontalLinesCount!; if (isTimelineView && overAllWidth < widget.width && xPosition + _dragDetails.value.appointmentView!.appointmentRect!.width > overAllWidth) { - xPosition = overAllWidth - + xPosition = + overAllWidth - _dragDetails.value.appointmentView!.appointmentRect!.width; } else if (!isTimelineView && !isMonthView && @@ -2028,33 +2268,45 @@ class _CustomCalendarScrollViewState extends State yPosition + _dragDetails.value.appointmentView!.appointmentRect!.height > overAllHeight) { - yPosition = overAllHeight - + yPosition = + overAllHeight - _dragDetails.value.appointmentView!.appointmentRect!.height; } final CalendarAppointment? appointment = _dragDetails.value.appointmentView!.appointment; - DateTime? dropTime = - currentState._getDateFromPosition(xPosition, yPosition, timeLabelWidth); + DateTime? dropTime = currentState._getDateFromPosition( + xPosition, + yPosition, + timeLabelWidth, + ); if (!isMonthView) { if (isTimelineView) { - final DateTime time = _timeFromPosition( - dropTime!, - widget.calendar.timeSlotViewSettings, - xPosition, - currentState, - timeIntervalHeight, - isTimelineView)!; - dropTime = DateTime(dropTime.year, dropTime.month, dropTime.day, - time.hour, time.minute); + final DateTime time = + _timeFromPosition( + dropTime!, + widget.calendar.timeSlotViewSettings, + xPosition, + currentState, + timeIntervalHeight, + isTimelineView, + )!; + dropTime = DateTime( + dropTime.year, + dropTime.month, + dropTime.day, + time.hour, + time.minute, + ); } else { dropTime = _timeFromPosition( - dropTime!, - widget.calendar.timeSlotViewSettings, - yPosition, - currentState, - timeIntervalHeight, - isTimelineView); + dropTime!, + widget.calendar.timeSlotViewSettings, + yPosition, + currentState, + timeIntervalHeight, + isTimelineView, + ); } } @@ -2063,10 +2315,11 @@ class _CustomCalendarScrollViewState extends State int sourceSelectedResourceIndex = -1; if (isResourceEnabled) { targetResourceIndex = currentState._getSelectedResourceIndex( - (details.dy - viewHeaderHeight - timeLabelWidth) + - currentState._timelineViewVerticalScrollController!.offset, - viewHeaderHeight, - timeLabelWidth); + (details.dy - viewHeaderHeight - timeLabelWidth) + + currentState._timelineViewVerticalScrollController!.offset, + viewHeaderHeight, + timeLabelWidth, + ); if (targetResourceIndex > widget.calendar.dataSource!.resources!.length - 1) { targetResourceIndex = widget.calendar.dataSource!.resources!.length - 1; @@ -2074,15 +2327,19 @@ class _CustomCalendarScrollViewState extends State selectedResource = widget.calendar.dataSource!.resources![targetResourceIndex]; sourceSelectedResourceIndex = currentState._getSelectedResourceIndex( - _dragDetails.value.appointmentView!.appointmentRect!.top, - viewHeaderHeight, - timeLabelWidth); + _dragDetails.value.appointmentView!.appointmentRect!.top, + viewHeaderHeight, + timeLabelWidth, + ); previousResource = widget.calendar.dataSource!.resources![sourceSelectedResourceIndex]; } - final int currentMonth = currentState.widget - .visibleDates[currentState.widget.visibleDates.length ~/ 2].month; + final int currentMonth = + currentState + .widget + .visibleDates[currentState.widget.visibleDates.length ~/ 2] + .month; bool isAllDay = appointment!.isAllDay; if (!isTimelineView && widget.view != CalendarView.month) { @@ -2095,51 +2352,65 @@ class _CustomCalendarScrollViewState extends State isAllDay = appointment.isAllDay; } - DateTime updateStartTime = isAllDay - ? DateTime(dropTime!.year, dropTime.month, dropTime.day) - : dropTime!; + DateTime updateStartTime = + isAllDay + ? DateTime(dropTime!.year, dropTime.month, dropTime.day) + : dropTime!; - final Duration appointmentDuration = appointment.isAllDay && - widget.view != CalendarView.month && - !isTimelineView - ? const Duration(hours: 1) - : appointment.endTime.difference(appointment.startTime); + final Duration appointmentDuration = + appointment.isAllDay && + widget.view != CalendarView.month && + !isTimelineView + ? const Duration(hours: 1) + : appointment.endTime.difference(appointment.startTime); DateTime updatedEndTime = isAllDay ? updateStartTime : updateStartTime.add(appointmentDuration); final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); final DateTime callbackStartDate = updateStartTime; updateStartTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - updateStartTime, widget.calendar.timeZone, appointment.startTimeZone); + updateStartTime, + widget.calendar.timeZone, + appointment.startTimeZone, + ); updatedEndTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - updatedEndTime, widget.calendar.timeZone, appointment.endTimeZone); + updatedEndTime, + widget.calendar.timeZone, + appointment.endTimeZone, + ); if (CalendarViewHelper.isDraggingAppointmentHasDisabledCell( - _getTimeRegions(), - _getBlackoutDates(), - updateStartTime, - updatedEndTime, - isTimelineView, - isMonthView, - widget.calendar.minDate, - widget.calendar.maxDate, - timeInterval, - targetResourceIndex, - widget.resourceCollection) || + _getTimeRegions(), + _getBlackoutDates(), + updateStartTime, + updatedEndTime, + isTimelineView, + isMonthView, + widget.calendar.minDate, + widget.calendar.maxDate, + timeInterval, + targetResourceIndex, + widget.resourceCollection, + ) || (widget.view == CalendarView.month && !CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - dropTime))) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + dropTime, + ))) { if (widget.calendar.onDragEnd != null) { - widget.calendar.onDragEnd!(AppointmentDragEndDetails( + widget.calendar.onDragEnd!( + AppointmentDragEndDetails( _getCalendarAppointmentToObject(appointment, widget.calendar), previousResource, previousResource, - appointment.exactStartTime)); + appointment.exactStartTime, + ), + ); } _resetDraggingDetails(currentState); return; @@ -2149,9 +2420,11 @@ class _CustomCalendarScrollViewState extends State if ((appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty) || appointment.recurrenceId != null) { - for (int i = 0; - i < _updateCalendarStateDetails.appointments.length; - i++) { + for ( + int i = 0; + i < _updateCalendarStateDetails.appointments.length; + i++ + ) { final CalendarAppointment app = _updateCalendarStateDetails.appointments[i]; if (app.id == appointment.id || app.id == appointment.recurrenceId) { @@ -2162,49 +2435,66 @@ class _CustomCalendarScrollViewState extends State final List recurrenceDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - parentAppointment!.recurrenceRule ?? '', + parentAppointment!.recurrenceRule ?? '', + parentAppointment.exactStartTime, + recurrenceDuration: AppointmentHelper.getDifference( parentAppointment.exactStartTime, - recurrenceDuration: AppointmentHelper.getDifference( - parentAppointment.exactStartTime, - parentAppointment.exactEndTime), - specificStartDate: currentState.widget.visibleDates[0], - specificEndDate: currentState.widget - .visibleDates[currentState.widget.visibleDates.length - 1]); - - for (int i = 0; - i < _updateCalendarStateDetails.appointments.length; - i++) { + parentAppointment.exactEndTime, + ), + specificStartDate: currentState.widget.visibleDates[0], + specificEndDate: + currentState + .widget + .visibleDates[currentState.widget.visibleDates.length - 1], + ); + + for ( + int i = 0; + i < _updateCalendarStateDetails.appointments.length; + i++ + ) { final CalendarAppointment calendarApp = _updateCalendarStateDetails.appointments[i]; if (calendarApp.recurrenceId != null && calendarApp.recurrenceId == parentAppointment.id) { recurrenceDates.add( - AppointmentHelper.convertTimeToAppointmentTimeZone( - calendarApp.startTime, - calendarApp.startTimeZone, - widget.calendar.timeZone)); + AppointmentHelper.convertTimeToAppointmentTimeZone( + calendarApp.startTime, + calendarApp.startTimeZone, + widget.calendar.timeZone, + ), + ); } } if (parentAppointment.recurrenceExceptionDates != null) { - for (int i = 0; - i < parentAppointment.recurrenceExceptionDates!.length; - i++) { + for ( + int i = 0; + i < parentAppointment.recurrenceExceptionDates!.length; + i++ + ) { recurrenceDates.remove( - AppointmentHelper.convertTimeToAppointmentTimeZone( - parentAppointment.recurrenceExceptionDates![i], - '', - widget.calendar.timeZone)); + AppointmentHelper.convertTimeToAppointmentTimeZone( + parentAppointment.recurrenceExceptionDates![i], + '', + widget.calendar.timeZone, + ), + ); } } recurrenceDates.sort(); - bool canAddRecurrence = - isSameDate(appointment.exactStartTime, callbackStartDate); + bool canAddRecurrence = isSameDate( + appointment.exactStartTime, + callbackStartDate, + ); if (!CalendarViewHelper.isDateInDateCollection( - recurrenceDates, callbackStartDate)) { - final int currentRecurrenceIndex = - recurrenceDates.indexOf(appointment.exactStartTime); + recurrenceDates, + callbackStartDate, + )) { + final int currentRecurrenceIndex = recurrenceDates.indexOf( + appointment.exactStartTime, + ); if (currentRecurrenceIndex == 0 || currentRecurrenceIndex == recurrenceDates.length - 1) { canAddRecurrence = true; @@ -2215,8 +2505,12 @@ class _CustomCalendarScrollViewState extends State recurrenceDates[currentRecurrenceIndex - 1]; final DateTime nextRecurrence = recurrenceDates[currentRecurrenceIndex + 1]; - canAddRecurrence = (isDateWithInDateRange( - previousRecurrence, nextRecurrence, callbackStartDate) && + canAddRecurrence = + (isDateWithInDateRange( + previousRecurrence, + nextRecurrence, + callbackStartDate, + ) && !isSameDate(previousRecurrence, callbackStartDate) && !isSameDate(nextRecurrence, callbackStartDate)) || canAddRecurrence; @@ -2225,11 +2519,14 @@ class _CustomCalendarScrollViewState extends State if (!canAddRecurrence) { if (widget.calendar.onDragEnd != null) { - widget.calendar.onDragEnd!(AppointmentDragEndDetails( + widget.calendar.onDragEnd!( + AppointmentDragEndDetails( _getCalendarAppointmentToObject(appointment, widget.calendar), previousResource, previousResource, - appointment.exactStartTime)); + appointment.exactStartTime, + ), + ); } _resetDraggingDetails(currentState); return; @@ -2240,36 +2537,50 @@ class _CustomCalendarScrollViewState extends State appointment.recurrenceRule!.isEmpty)) { widget.calendar.dataSource!.appointments!.remove(appointment.data); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [appointment.data]); + CalendarDataSourceAction.remove, + [appointment.data], + ); } else { - widget.calendar.dataSource!.appointments! - .remove(parentAppointment.data); + widget.calendar.dataSource!.appointments!.remove( + parentAppointment.data, + ); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [parentAppointment.data]); + CalendarDataSourceAction.remove, + [parentAppointment.data], + ); final DateTime exceptionDate = AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.exactStartTime, widget.calendar.timeZone, ''); + appointment.exactStartTime, + widget.calendar.timeZone, + '', + ); parentAppointment.recurrenceExceptionDates != null ? parentAppointment.recurrenceExceptionDates!.add(exceptionDate) : parentAppointment.recurrenceExceptionDates = [ - exceptionDate - ]; + exceptionDate, + ]; appointment.id = appointment.recurrenceId != null ? appointment.id : null; appointment.recurrenceId = appointment.recurrenceId ?? parentAppointment.id; appointment.recurrenceRule = null; - final dynamic newParentAppointment = - _getCalendarAppointmentToObject(parentAppointment, widget.calendar); + final dynamic newParentAppointment = _getCalendarAppointmentToObject( + parentAppointment, + widget.calendar, + ); widget.calendar.dataSource!.appointments!.add(newParentAppointment); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.add, [newParentAppointment]); + CalendarDataSourceAction.add, + [newParentAppointment], + ); } } else { widget.calendar.dataSource!.appointments!.remove(appointment.data); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [appointment.data]); + CalendarDataSourceAction.remove, + [appointment.data], + ); } appointment.startTime = updateStartTime; @@ -2288,17 +2599,27 @@ class _CustomCalendarScrollViewState extends State } } - final dynamic newAppointment = - _getCalendarAppointmentToObject(appointment, widget.calendar); + final dynamic newAppointment = _getCalendarAppointmentToObject( + appointment, + widget.calendar, + ); widget.calendar.dataSource!.appointments!.add(newAppointment); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.add, [newAppointment]); + CalendarDataSourceAction.add, + [newAppointment], + ); _resetDraggingDetails(currentState); if (widget.calendar.onDragEnd != null) { - widget.calendar.onDragEnd!(AppointmentDragEndDetails(newAppointment, - previousResource, selectedResource, callbackStartDate)); + widget.calendar.onDragEnd!( + AppointmentDragEndDetails( + newAppointment, + previousResource, + selectedResource, + callbackStartDate, + ), + ); } } @@ -2371,13 +2692,14 @@ class _CustomCalendarScrollViewState extends State /// move the previous view to end of the scroll or move the next view to /// start of the scroll and set the drag as timeline scroll controller drag. void _handleDragStart( - DragStartDetails details, - bool isNeedDragAndDrop, - bool isTimelineView, - bool isResourceEnabled, - double viewHeaderHeight, - double timeLabelWidth, - double resourceViewSize) { + DragStartDetails details, + bool isNeedDragAndDrop, + bool isTimelineView, + bool isResourceEnabled, + double viewHeaderHeight, + double timeLabelWidth, + double resourceViewSize, + ) { if (!CalendarViewHelper.isTimelineView(widget.view)) { return; } @@ -2386,13 +2708,16 @@ class _CustomCalendarScrollViewState extends State !widget.isMobilePlatform && isNeedDragAndDrop) { _handleAppointmentDragStart( - viewKey._hoveringAppointmentView!.clone(), - isTimelineView, - Offset(details.localPosition.dx - widget.width, - details.localPosition.dy), - isResourceEnabled, - viewHeaderHeight, - timeLabelWidth); + viewKey._hoveringAppointmentView!.clone(), + isTimelineView, + Offset( + details.localPosition.dx - widget.width, + details.localPosition.dy, + ), + isResourceEnabled, + viewHeaderHeight, + timeLabelWidth, + ); return; } _timelineScrollStartPosition = viewKey._scrollController!.position.pixels; @@ -2422,16 +2747,17 @@ class _CustomCalendarScrollViewState extends State /// then pass the touch to custom scroll view and set the timeline view /// drag as null; void _handleDragUpdate( - DragUpdateDetails details, - bool isTimelineView, - bool isResourceEnabled, - bool isMonthView, - double viewHeaderHeight, - double timeLabelWidth, - double resourceItemHeight, - double weekNumberPanelWidth, - bool isNeedDragAndDrop, - double resourceViewSize) { + DragUpdateDetails details, + bool isTimelineView, + bool isResourceEnabled, + bool isMonthView, + double viewHeaderHeight, + double timeLabelWidth, + double resourceItemHeight, + double weekNumberPanelWidth, + bool isNeedDragAndDrop, + double resourceViewSize, + ) { if (!CalendarViewHelper.isTimelineView(widget.view)) { return; } @@ -2441,15 +2767,18 @@ class _CustomCalendarScrollViewState extends State !widget.isMobilePlatform && isNeedDragAndDrop) { _handleLongPressMove( - Offset(details.localPosition.dx - widget.width, - details.localPosition.dy), - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - resourceItemHeight, - weekNumberPanelWidth); + Offset( + details.localPosition.dx - widget.width, + details.localPosition.dy, + ), + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + resourceItemHeight, + weekNumberPanelWidth, + ); return; } @@ -2503,25 +2832,27 @@ class _CustomCalendarScrollViewState extends State /// Handle the scroll end to update the timeline view scroll or custom scroll /// view scroll based on [_isNeedTimelineScrollEnd] value void _handleDragEnd( - DragEndDetails details, - bool isTimelineView, - bool isResourceEnabled, - bool isMonthView, - double viewHeaderHeight, - double timeLabelWidth, - double weekNumberPanelWidth, - bool isNeedDragAndDrop) { + DragEndDetails details, + bool isTimelineView, + bool isResourceEnabled, + bool isMonthView, + double viewHeaderHeight, + double timeLabelWidth, + double weekNumberPanelWidth, + bool isNeedDragAndDrop, + ) { if (_dragDetails.value.appointmentView != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleLongPressEnd( - _dragDetails.value.position.value! - _dragDifferenceOffset!, - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - weekNumberPanelWidth); + _dragDetails.value.position.value! - _dragDifferenceOffset!, + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + weekNumberPanelWidth, + ); return; } @@ -2559,7 +2890,9 @@ class _CustomCalendarScrollViewState extends State /// Horizontal direction. if (widget.height <= _viewPortHeight! && event.scrollDelta.dy.abs() > event.scrollDelta.dx.abs() && - viewKey._timelineViewVerticalScrollController!.position + viewKey + ._timelineViewVerticalScrollController! + .position .maxScrollExtent == 0) { scrolledPosition = @@ -2567,10 +2900,12 @@ class _CustomCalendarScrollViewState extends State } final double targetScrollOffset = math.min( - math.max( - viewKey._scrollController!.position.pixels + scrolledPosition, - viewKey._scrollController!.position.minScrollExtent), - viewKey._scrollController!.position.maxScrollExtent); + math.max( + viewKey._scrollController!.position.pixels + scrolledPosition, + viewKey._scrollController!.position.minScrollExtent, + ), + viewKey._scrollController!.position.maxScrollExtent, + ); if (targetScrollOffset != viewKey._scrollController!.position.pixels) { viewKey._scrollController!.position.jumpTo(targetScrollOffset); } @@ -2579,51 +2914,67 @@ class _CustomCalendarScrollViewState extends State void _updateVisibleDates() { widget.getCalendarState(_updateCalendarStateDetails); - final List? nonWorkingDays = (widget.view == CalendarView.workWeek || - widget.view == CalendarView.timelineWorkWeek) - ? widget.calendar.timeSlotViewSettings.nonWorkingDays - : null; + final List? nonWorkingDays = + (widget.view == CalendarView.workWeek || + widget.view == CalendarView.timelineWorkWeek) + ? widget.calendar.timeSlotViewSettings.nonWorkingDays + : null; final int visibleDatesCount = DateTimeHelper.getViewDatesCount( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + nonWorkingDays, + ); final DateTime currentDate = DateTime( - _updateCalendarStateDetails.currentDate!.year, - _updateCalendarStateDetails.currentDate!.month, - _updateCalendarStateDetails.currentDate!.day); + _updateCalendarStateDetails.currentDate!.year, + _updateCalendarStateDetails.currentDate!.month, + _updateCalendarStateDetails.currentDate!.day, + ); final DateTime prevDate = DateTimeHelper.getPreviousViewStartDate( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - currentDate, - visibleDatesCount, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + currentDate, + visibleDatesCount, + nonWorkingDays, + ); final DateTime nextDate = DateTimeHelper.getNextViewStartDate( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - currentDate, - visibleDatesCount, - nonWorkingDays); - - _visibleDates = getVisibleDates(currentDate, nonWorkingDays, - widget.calendar.firstDayOfWeek, visibleDatesCount) - .cast(); - _previousViewVisibleDates = getVisibleDates( - widget.isRTL ? nextDate : prevDate, - nonWorkingDays, - widget.calendar.firstDayOfWeek, - visibleDatesCount) - .cast(); - _nextViewVisibleDates = getVisibleDates(widget.isRTL ? prevDate : nextDate, - nonWorkingDays, widget.calendar.firstDayOfWeek, visibleDatesCount) - .cast(); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + currentDate, + visibleDatesCount, + nonWorkingDays, + ); + + _visibleDates = + getVisibleDates( + currentDate, + nonWorkingDays, + widget.calendar.firstDayOfWeek, + visibleDatesCount, + ).cast(); + _previousViewVisibleDates = + getVisibleDates( + widget.isRTL ? nextDate : prevDate, + nonWorkingDays, + widget.calendar.firstDayOfWeek, + visibleDatesCount, + ).cast(); + _nextViewVisibleDates = + getVisibleDates( + widget.isRTL ? prevDate : nextDate, + nonWorkingDays, + widget.calendar.firstDayOfWeek, + visibleDatesCount, + ).cast(); if (widget.view == CalendarView.timelineMonth) { _visibleDates = DateTimeHelper.getCurrentMonthDates(_visibleDates); - _previousViewVisibleDates = - DateTimeHelper.getCurrentMonthDates(_previousViewVisibleDates); - _nextViewVisibleDates = - DateTimeHelper.getCurrentMonthDates(_nextViewVisibleDates); + _previousViewVisibleDates = DateTimeHelper.getCurrentMonthDates( + _previousViewVisibleDates, + ); + _nextViewVisibleDates = DateTimeHelper.getCurrentMonthDates( + _nextViewVisibleDates, + ); } _currentViewVisibleDates = _visibleDates; @@ -2646,41 +2997,50 @@ class _CustomCalendarScrollViewState extends State void _updateNextViewVisibleDates() { DateTime currentViewDate = _currentViewVisibleDates[0]; - final List? nonWorkingDays = (widget.view == CalendarView.workWeek || - widget.view == CalendarView.timelineWorkWeek) - ? widget.calendar.timeSlotViewSettings.nonWorkingDays - : null; + final List? nonWorkingDays = + (widget.view == CalendarView.workWeek || + widget.view == CalendarView.timelineWorkWeek) + ? widget.calendar.timeSlotViewSettings.nonWorkingDays + : null; final int visibleDatesCount = DateTimeHelper.getViewDatesCount( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + nonWorkingDays, + ); if (widget.view == CalendarView.month && widget.calendar.monthViewSettings.numberOfWeeksInView == 6) { - currentViewDate = _currentViewVisibleDates[ - (_currentViewVisibleDates.length / 2).truncate()]; + currentViewDate = + _currentViewVisibleDates[(_currentViewVisibleDates.length / 2) + .truncate()]; } if (widget.isRTL) { currentViewDate = DateTimeHelper.getPreviousViewStartDate( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - currentViewDate, - visibleDatesCount, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + currentViewDate, + visibleDatesCount, + nonWorkingDays, + ); } else { currentViewDate = DateTimeHelper.getNextViewStartDate( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - currentViewDate, - visibleDatesCount, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + currentViewDate, + visibleDatesCount, + nonWorkingDays, + ); } - List dates = getVisibleDates(currentViewDate, nonWorkingDays, - widget.calendar.firstDayOfWeek, visibleDatesCount) - .cast(); + List dates = + getVisibleDates( + currentViewDate, + nonWorkingDays, + widget.calendar.firstDayOfWeek, + visibleDatesCount, + ).cast(); if (widget.view == CalendarView.timelineMonth) { dates = DateTimeHelper.getCurrentMonthDates(dates); @@ -2697,41 +3057,50 @@ class _CustomCalendarScrollViewState extends State void _updatePreviousViewVisibleDates() { DateTime currentViewDate = _currentViewVisibleDates[0]; - final List? nonWorkingDays = (widget.view == CalendarView.workWeek || - widget.view == CalendarView.timelineWorkWeek) - ? widget.calendar.timeSlotViewSettings.nonWorkingDays - : null; + final List? nonWorkingDays = + (widget.view == CalendarView.workWeek || + widget.view == CalendarView.timelineWorkWeek) + ? widget.calendar.timeSlotViewSettings.nonWorkingDays + : null; final int visibleDatesCount = DateTimeHelper.getViewDatesCount( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + nonWorkingDays, + ); if (widget.view == CalendarView.month && widget.calendar.monthViewSettings.numberOfWeeksInView == 6) { - currentViewDate = _currentViewVisibleDates[ - (_currentViewVisibleDates.length / 2).truncate()]; + currentViewDate = + _currentViewVisibleDates[(_currentViewVisibleDates.length / 2) + .truncate()]; } if (widget.isRTL) { currentViewDate = DateTimeHelper.getNextViewStartDate( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - currentViewDate, - visibleDatesCount, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + currentViewDate, + visibleDatesCount, + nonWorkingDays, + ); } else { currentViewDate = DateTimeHelper.getPreviousViewStartDate( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - currentViewDate, - visibleDatesCount, - nonWorkingDays); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + currentViewDate, + visibleDatesCount, + nonWorkingDays, + ); } - List dates = getVisibleDates(currentViewDate, nonWorkingDays, - widget.calendar.firstDayOfWeek, visibleDatesCount) - .cast(); + List dates = + getVisibleDates( + currentViewDate, + nonWorkingDays, + widget.calendar.firstDayOfWeek, + visibleDatesCount, + ).cast(); if (widget.view == CalendarView.timelineMonth) { dates = DateTimeHelper.getCurrentMonthDates(dates); @@ -2790,31 +3159,48 @@ class _CustomCalendarScrollViewState extends State return regionCollection; } - final DateTime startDate = - AppointmentHelper.convertToStartTime(visibleStartDate); + final DateTime startDate = AppointmentHelper.convertToStartTime( + visibleStartDate, + ); final DateTime endDate = AppointmentHelper.convertToEndTime(visibleEndDate); for (int j = 0; j < _timeRegions!.length; j++) { final TimeRegion timeRegion = _timeRegions![j]; - final CalendarTimeRegion region = - _getCalendarTimeRegionFromTimeRegion(timeRegion); - region.actualStartTime = - AppointmentHelper.convertTimeToAppointmentTimeZone( - region.startTime, region.timeZone, widget.calendar.timeZone); + final CalendarTimeRegion region = _getCalendarTimeRegionFromTimeRegion( + timeRegion, + ); + region + .actualStartTime = AppointmentHelper.convertTimeToAppointmentTimeZone( + region.startTime, + region.timeZone, + widget.calendar.timeZone, + ); region.actualEndTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - region.endTime, region.timeZone, widget.calendar.timeZone); + region.endTime, + region.timeZone, + widget.calendar.timeZone, + ); region.data = timeRegion; if (region.recurrenceRule == null || region.recurrenceRule == '') { if (AppointmentHelper.isDateRangeWithinVisibleDateRange( - region.actualStartTime, region.actualEndTime, startDate, endDate)) { + region.actualStartTime, + region.actualEndTime, + startDate, + endDate, + )) { regionCollection.add(region); } continue; } - getRecurrenceRegions(region, regionCollection, startDate, endDate, - widget.calendar.timeZone); + getRecurrenceRegions( + region, + regionCollection, + startDate, + endDate, + widget.calendar.timeZone, + ); } return regionCollection; @@ -2822,11 +3208,12 @@ class _CustomCalendarScrollViewState extends State /// Get the recurrence time regions in between the visible date range. void getRecurrenceRegions( - CalendarTimeRegion region, - List regions, - DateTime visibleStartDate, - DateTime visibleEndDate, - String? calendarTimeZone) { + CalendarTimeRegion region, + List regions, + DateTime visibleStartDate, + DateTime visibleEndDate, + String? calendarTimeZone, + ) { final DateTime regionStartDate = region.actualStartTime; if (regionStartDate.isAfter(visibleEndDate)) { return; @@ -2841,11 +3228,15 @@ class _CustomCalendarScrollViewState extends State final List recursiveDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - rule, region.actualStartTime, - recurrenceDuration: AppointmentHelper.getDifference( - region.actualStartTime, region.actualEndTime), - specificStartDate: visibleStartDate, - specificEndDate: visibleEndDate); + rule, + region.actualStartTime, + recurrenceDuration: AppointmentHelper.getDifference( + region.actualStartTime, + region.actualEndTime, + ), + specificStartDate: visibleStartDate, + specificEndDate: visibleEndDate, + ); for (int j = 0; j < recursiveDates.length; j++) { final DateTime recursiveDate = recursiveDates[j]; @@ -2854,7 +3245,10 @@ class _CustomCalendarScrollViewState extends State for (int i = 0; i < region.recurrenceExceptionDates!.length; i++) { final DateTime date = AppointmentHelper.convertTimeToAppointmentTimeZone( - region.recurrenceExceptionDates![i], '', calendarTimeZone); + region.recurrenceExceptionDates![i], + '', + calendarTimeZone, + ); if (isSameDate(date, recursiveDate)) { isDateContains = true; break; @@ -2865,29 +3259,46 @@ class _CustomCalendarScrollViewState extends State } } - final CalendarTimeRegion occurrenceRegion = - cloneRecurrenceRegion(region, recursiveDate, calendarTimeZone); + final CalendarTimeRegion occurrenceRegion = cloneRecurrenceRegion( + region, + recursiveDate, + calendarTimeZone, + ); regions.add(occurrenceRegion); } } /// Used to clone the time region with new values. - CalendarTimeRegion cloneRecurrenceRegion(CalendarTimeRegion region, - DateTime recursiveDate, String? calendarTimeZone) { - final int minutes = AppointmentHelper.getDifference( - region.actualStartTime, region.actualEndTime) - .inMinutes; + CalendarTimeRegion cloneRecurrenceRegion( + CalendarTimeRegion region, + DateTime recursiveDate, + String? calendarTimeZone, + ) { + final int minutes = + AppointmentHelper.getDifference( + region.actualStartTime, + region.actualEndTime, + ).inMinutes; final DateTime actualEndTime = DateTimeHelper.getDateTimeValue( - addDuration(recursiveDate, Duration(minutes: minutes))); + addDuration(recursiveDate, Duration(minutes: minutes)), + ); final DateTime startDate = AppointmentHelper.convertTimeToAppointmentTimeZone( - recursiveDate, calendarTimeZone, region.timeZone); + recursiveDate, + calendarTimeZone, + region.timeZone, + ); final DateTime endDate = AppointmentHelper.convertTimeToAppointmentTimeZone( - actualEndTime, calendarTimeZone, region.timeZone); + actualEndTime, + calendarTimeZone, + region.timeZone, + ); - final TimeRegion occurrenceTimeRegion = - region.data.copyWith(startTime: startDate, endTime: endDate); + final TimeRegion occurrenceTimeRegion = region.data.copyWith( + startTime: startDate, + endTime: endDate, + ); final CalendarTimeRegion occurrenceRegion = _getCalendarTimeRegionFromTimeRegion(occurrenceTimeRegion); occurrenceRegion.actualStartTime = recursiveDate; @@ -2898,7 +3309,9 @@ class _CustomCalendarScrollViewState extends State /// Return date collection which falls between the visible date range. List _getDatesWithInVisibleDateRange( - List? dates, List visibleDates) { + List? dates, + List visibleDates, + ) { final List visibleMonthDates = []; if (dates == null) { return visibleMonthDates; @@ -2911,17 +3324,22 @@ class _CustomCalendarScrollViewState extends State for (int i = 0; i < datesCount; i++) { final DateTime currentDate = dates[i]; if (!isDateWithInDateRange( - visibleStartDate, visibleEndDate, currentDate)) { + visibleStartDate, + visibleEndDate, + currentDate, + )) { continue; } if (dateCollection.keys.contains( - currentDate.day.toString() + currentDate.month.toString())) { + currentDate.day.toString() + currentDate.month.toString(), + )) { continue; } dateCollection[currentDate.day.toString() + - currentDate.month.toString()] = currentDate; + currentDate.month.toString()] = + currentDate; visibleMonthDates.add(currentDate); } @@ -2942,7 +3360,9 @@ class _CustomCalendarScrollViewState extends State widget.themeData, _getRegions(_previousViewVisibleDates), _getDatesWithInVisibleDateRange( - widget.blackoutDates, _previousViewVisibleDates), + widget.blackoutDates, + _previousViewVisibleDates, + ), _focusNode, widget.removePicker, widget.calendar.allowViewNavigation, @@ -3009,7 +3429,9 @@ class _CustomCalendarScrollViewState extends State widget.themeData, _getRegions(_nextViewVisibleDates), _getDatesWithInVisibleDateRange( - widget.blackoutDates, _nextViewVisibleDates), + widget.blackoutDates, + _nextViewVisibleDates, + ), _focusNode, widget.removePicker, widget.calendar.allowViewNavigation, @@ -3040,11 +3462,20 @@ class _CustomCalendarScrollViewState extends State widget.getCalendarState(_updateCalendarStateDetails); final _CalendarView previousView = _updateViews( - _previousView, _previousViewKey, _previousViewVisibleDates); - final _CalendarView currentView = - _updateViews(_currentView, _currentViewKey, _visibleDates); - final _CalendarView nextView = - _updateViews(_nextView, _nextViewKey, _nextViewVisibleDates); + _previousView, + _previousViewKey, + _previousViewVisibleDates, + ); + final _CalendarView currentView = _updateViews( + _currentView, + _currentViewKey, + _visibleDates, + ); + final _CalendarView nextView = _updateViews( + _nextView, + _nextViewKey, + _nextViewVisibleDates, + ); //// Update views while the all day view height differ from original height, //// else repaint the appointment painter while current child visible appointment not equals calendar visible appointment @@ -3062,8 +3493,11 @@ class _CustomCalendarScrollViewState extends State } // method to check and update the views and appointments on the swiping end - _CalendarView _updateViews(_CalendarView view, - GlobalKey<_CalendarViewState> viewKey, List visibleDates) { + _CalendarView _updateViews( + _CalendarView view, + GlobalKey<_CalendarViewState> viewKey, + List visibleDates, + ) { final int index = _children.indexOf(view); final AppointmentLayout appointmentLayout = @@ -3108,8 +3542,9 @@ class _CustomCalendarScrollViewState extends State } // check and update the visible appointments in the view else if (!CalendarViewHelper.isCollectionEqual( - appointmentLayout.visibleAppointments.value, - _updateCalendarStateDetails.visibleAppointments)) { + appointmentLayout.visibleAppointments.value, + _updateCalendarStateDetails.visibleAppointments, + )) { if (widget.view != CalendarView.month && !CalendarViewHelper.isTimelineView(widget.view)) { view = _CalendarView( @@ -3189,11 +3624,13 @@ class _CustomCalendarScrollViewState extends State /// appointment removed. if (viewKey.currentState!._selectionPainter != null && viewKey.currentState!._selectionPainter!.appointmentView != null && - (!_updateCalendarStateDetails.visibleAppointments.contains(viewKey - .currentState! - ._selectionPainter! - .appointmentView! - .appointment))) { + (!_updateCalendarStateDetails.visibleAppointments.contains( + viewKey + .currentState! + ._selectionPainter! + .appointmentView! + .appointment, + ))) { viewKey.currentState!._selectionPainter!.appointmentView = null; viewKey.currentState!._selectionPainter!.repaintNotifier.value = !viewKey.currentState!._selectionPainter!.repaintNotifier.value; @@ -3298,7 +3735,9 @@ class _CustomCalendarScrollViewState extends State /// Check both the region collection as equal or not. bool _isTimeRegionsEquals( - List? regions1, List? regions2) { + List? regions1, + List? regions2, + ) { /// Check both instance as equal /// eg., if both are null then its equal. if (regions1 == regions2) { @@ -3334,7 +3773,9 @@ class _CustomCalendarScrollViewState extends State // ignore: avoid_as _children[i].key! as GlobalKey<_CalendarViewState>; if (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { viewKey.currentState!._selectedResourceIndex = 0; viewKey.currentState!._selectionPainter!.selectedResourceIndex = 0; } else { @@ -3358,7 +3799,9 @@ class _CustomCalendarScrollViewState extends State final Object selectedResourceId = widget.resourceCollection![selectedResourceIndex].id; final int newIndex = CalendarViewHelper.getResourceIndex( - widget.calendar.dataSource?.resources, selectedResourceId); + widget.calendar.dataSource?.resources, + selectedResourceId, + ); viewKey.currentState!._selectedResourceIndex = newIndex; } } @@ -3443,8 +3886,10 @@ class _CustomCalendarScrollViewState extends State widget.calendar.monthViewSettings.numberOfWeeksInView == 6) { final DateTime currentMonthDate = _currentViewVisibleDates[_currentViewVisibleDates.length ~/ 2]; - _updateCalendarStateDetails.currentDate = - DateTime(currentMonthDate.year, currentMonthDate.month); + _updateCalendarStateDetails.currentDate = DateTime( + currentMonthDate.year, + currentMonthDate.month, + ); } else { _updateCalendarStateDetails.currentDate = _currentViewVisibleDates[0]; } @@ -3533,13 +3978,14 @@ class _CustomCalendarScrollViewState extends State } if (!DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { return; } @@ -3570,9 +4016,9 @@ class _CustomCalendarScrollViewState extends State } _animationController.duration = const Duration(milliseconds: 250); - _animationController - .forward() - .then((dynamic value) => _updateNextView()); + _animationController.forward().then( + (dynamic value) => _updateNextView(), + ); /// updates the current view visible dates when the view swiped _updateCurrentViewVisibleDates(isNextView: true); @@ -3585,13 +4031,14 @@ class _CustomCalendarScrollViewState extends State } if (!DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { return; } @@ -3622,9 +4069,9 @@ class _CustomCalendarScrollViewState extends State } _animationController.duration = const Duration(milliseconds: 250); - _animationController - .forward() - .then((dynamic value) => _updatePreviousView()); + _animationController.forward().then( + (dynamic value) => _updatePreviousView(), + ); /// updates the current view visible dates when the view swiped. _updateCurrentViewVisibleDates(); @@ -3632,13 +4079,14 @@ class _CustomCalendarScrollViewState extends State void _moveToPreviousWebViewWithAnimation({bool isScrollToEnd = false}) { if (!DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { return; } @@ -3685,13 +4133,14 @@ class _CustomCalendarScrollViewState extends State void _moveToNextWebViewWithAnimation() { if (!DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { return; } @@ -3771,16 +4220,23 @@ class _CustomCalendarScrollViewState extends State if (_previousViewKey.currentState!._scrollController!.offset != scrolledPosition && _previousViewKey - .currentState!._scrollController!.position.maxScrollExtent >= + .currentState! + ._scrollController! + .position + .maxScrollExtent >= scrolledPosition) { - _previousViewKey.currentState!._scrollController! - .jumpTo(scrolledPosition); + _previousViewKey.currentState!._scrollController!.jumpTo( + scrolledPosition, + ); } if (_currentViewKey.currentState!._scrollController!.offset != scrolledPosition && _currentViewKey - .currentState!._scrollController!.position.maxScrollExtent >= + .currentState! + ._scrollController! + .position + .maxScrollExtent >= scrolledPosition) { _currentViewKey.currentState!._scrollController!.jumpTo(scrolledPosition); } @@ -3788,7 +4244,10 @@ class _CustomCalendarScrollViewState extends State if (_nextViewKey.currentState!._scrollController!.offset != scrolledPosition && _nextViewKey - .currentState!._scrollController!.position.maxScrollExtent >= + .currentState! + ._scrollController! + .position + .maxScrollExtent >= scrolledPosition) { _nextViewKey.currentState!._scrollController!.jumpTo(scrolledPosition); } @@ -3817,67 +4276,95 @@ class _CustomCalendarScrollViewState extends State return -1; } - DateTime _updateSelectedDateForRightArrow(_CalendarView currentView, - _CalendarViewState currentViewState, DateTime? selectedDate) { + DateTime _updateSelectedDateForRightArrow( + _CalendarView currentView, + _CalendarViewState currentViewState, + DateTime? selectedDate, + ) { /// Condition added to move the view to next view when the selection reaches /// the last horizontal cell of the view in day, week, workweek, month and /// timeline month. if (!CalendarViewHelper.isTimelineView(widget.view)) { final int visibleDatesCount = currentView.visibleDates.length; if (isSameDate( - currentView.visibleDates[visibleDatesCount - 1], selectedDate)) { + currentView.visibleDates[visibleDatesCount - 1], + selectedDate, + )) { _moveToNextViewWithAnimation(); } - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate!, 1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate!, + 1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); /// Move to next view when the new selected date as next month date. if (widget.view == CalendarView.month && !CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentView.visibleDates[visibleDatesCount ~/ 2].month, - selectedDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentView.visibleDates[visibleDatesCount ~/ 2].month, + selectedDate, + )) { _moveToNextViewWithAnimation(); } else if (widget.view == CalendarView.workWeek) { - for (int i = 0; - i < - DateTime.daysPerWeek - - widget.calendar.timeSlotViewSettings.nonWorkingDays.length; - i++) { - if (widget.calendar.timeSlotViewSettings.nonWorkingDays - .contains(selectedDate!.weekday)) { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate, 1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + for ( + int i = 0; + i < + DateTime.daysPerWeek - + widget.calendar.timeSlotViewSettings.nonWorkingDays.length; + i++ + ) { + if (widget.calendar.timeSlotViewSettings.nonWorkingDays.contains( + selectedDate!.weekday, + )) { + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate, + 1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } else { break; } } } } else { - final double xPosition = widget.view == CalendarView.timelineMonth - ? 0 - : AppointmentHelper.timeToPosition(widget.calendar, selectedDate!, - currentViewState._timeIntervalHeight); - final int rowIndex = - _getRowOfDate(currentView.visibleDates, selectedDate!); - final double singleChildWidth = - _getSingleViewWidthForTimeLineView(currentViewState); + final double xPosition = + widget.view == CalendarView.timelineMonth + ? 0 + : AppointmentHelper.timeToPosition( + widget.calendar, + selectedDate!, + currentViewState._timeIntervalHeight, + ); + final int rowIndex = _getRowOfDate( + currentView.visibleDates, + selectedDate!, + ); + final double singleChildWidth = _getSingleViewWidthForTimeLineView( + currentViewState, + ); if ((rowIndex * singleChildWidth) + xPosition + currentViewState._timeIntervalHeight >= currentViewState._scrollController!.offset + widget.width) { currentViewState._scrollController!.jumpTo( - currentViewState._scrollController!.offset + - currentViewState._timeIntervalHeight); + currentViewState._scrollController!.offset + + currentViewState._timeIntervalHeight, + ); } if (widget.view == CalendarView.timelineDay && selectedDate .add(widget.calendar.timeSlotViewSettings.timeInterval) .day != currentView - .visibleDates[currentView.visibleDates.length - 1].day) { + .visibleDates[currentView.visibleDates.length - 1] + .day) { _moveToNextViewWithAnimation(); } @@ -3897,22 +4384,36 @@ class _CustomCalendarScrollViewState extends State /// hence to update the selected date for timeline month we must add a day /// and for other timeline views we must add the given time interval. if (widget.view == CalendarView.timelineMonth) { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate, 1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate, + 1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } else { - selectedDate = - selectedDate.add(widget.calendar.timeSlotViewSettings.timeInterval); + selectedDate = selectedDate.add( + widget.calendar.timeSlotViewSettings.timeInterval, + ); } if (widget.view == CalendarView.timelineWorkWeek) { - for (int i = 0; - i < - DateTime.daysPerWeek - - widget.calendar.timeSlotViewSettings.nonWorkingDays.length; - i++) { - if (widget.calendar.timeSlotViewSettings.nonWorkingDays - .contains(selectedDate!.weekday)) { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate, 1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + for ( + int i = 0; + i < + DateTime.daysPerWeek - + widget.calendar.timeSlotViewSettings.nonWorkingDays.length; + i++ + ) { + if (widget.calendar.timeSlotViewSettings.nonWorkingDays.contains( + selectedDate!.weekday, + )) { + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate, + 1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } else { break; } @@ -3923,49 +4424,74 @@ class _CustomCalendarScrollViewState extends State return selectedDate!; } - DateTime _updateSelectedDateForLeftArrow(_CalendarView currentView, - _CalendarViewState currentViewState, DateTime? selectedDate) { + DateTime _updateSelectedDateForLeftArrow( + _CalendarView currentView, + _CalendarViewState currentViewState, + DateTime? selectedDate, + ) { if (!CalendarViewHelper.isTimelineView(widget.view)) { if (isSameDate(currentViewState.widget.visibleDates[0], selectedDate)) { _moveToPreviousViewWithAnimation(); } - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate!, -1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate!, + -1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); /// Move to previous view when the selected date as previous month date. if (widget.view == CalendarView.month && !CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentView - .visibleDates[currentView.visibleDates.length ~/ 2].month, - selectedDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentView + .visibleDates[currentView.visibleDates.length ~/ 2] + .month, + selectedDate, + )) { _moveToPreviousViewWithAnimation(); } else if (widget.view == CalendarView.workWeek) { - for (int i = 0; - i < - DateTime.daysPerWeek - - widget.calendar.timeSlotViewSettings.nonWorkingDays.length; - i++) { - if (widget.calendar.timeSlotViewSettings.nonWorkingDays - .contains(selectedDate!.weekday)) { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate, -1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + for ( + int i = 0; + i < + DateTime.daysPerWeek - + widget.calendar.timeSlotViewSettings.nonWorkingDays.length; + i++ + ) { + if (widget.calendar.timeSlotViewSettings.nonWorkingDays.contains( + selectedDate!.weekday, + )) { + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate, + -1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } else { break; } } } } else { - final double xPosition = widget.view == CalendarView.timelineMonth - ? 0 - : AppointmentHelper.timeToPosition(widget.calendar, selectedDate!, - currentViewState._timeIntervalHeight); - final int rowIndex = - _getRowOfDate(currentView.visibleDates, selectedDate!); - final double singleChildWidth = - _getSingleViewWidthForTimeLineView(currentViewState); + final double xPosition = + widget.view == CalendarView.timelineMonth + ? 0 + : AppointmentHelper.timeToPosition( + widget.calendar, + selectedDate!, + currentViewState._timeIntervalHeight, + ); + final int rowIndex = _getRowOfDate( + currentView.visibleDates, + selectedDate!, + ); + final double singleChildWidth = _getSingleViewWidthForTimeLineView( + currentViewState, + ); if ((rowIndex * singleChildWidth) + xPosition == 0) { _moveToPreviousViewWithAnimation(isScrollToEnd: true); @@ -3977,8 +4503,9 @@ class _CustomCalendarScrollViewState extends State if ((rowIndex * singleChildWidth) + xPosition <= currentViewState._scrollController!.offset) { currentViewState._scrollController!.jumpTo( - currentViewState._scrollController!.offset - - currentViewState._timeIntervalHeight); + currentViewState._scrollController!.offset - + currentViewState._timeIntervalHeight, + ); } /// For timeline month view each column represents a single day, and for @@ -3987,22 +4514,36 @@ class _CustomCalendarScrollViewState extends State /// a day and for other timeline views we must subtract the given time /// interval. if (widget.view == CalendarView.timelineMonth) { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate, -1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate, + -1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } else { - selectedDate = selectedDate - .subtract(widget.calendar.timeSlotViewSettings.timeInterval); + selectedDate = selectedDate.subtract( + widget.calendar.timeSlotViewSettings.timeInterval, + ); } if (widget.view == CalendarView.timelineWorkWeek) { - for (int i = 0; - i < - DateTime.daysPerWeek - - widget.calendar.timeSlotViewSettings.nonWorkingDays.length; - i++) { - if (widget.calendar.timeSlotViewSettings.nonWorkingDays - .contains(selectedDate!.weekday)) { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate, -1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + for ( + int i = 0; + i < + DateTime.daysPerWeek - + widget.calendar.timeSlotViewSettings.nonWorkingDays.length; + i++ + ) { + if (widget.calendar.timeSlotViewSettings.nonWorkingDays.contains( + selectedDate!.weekday, + )) { + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate, + -1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } else { break; } @@ -4014,65 +4555,88 @@ class _CustomCalendarScrollViewState extends State } DateTime? _updateSelectedDateForUpArrow( - _CalendarView currentView, - _CalendarViewState currentViewState, - DateTime? selectedDate, - DateTime? appointmentSelectedDate) { + _CalendarView currentView, + _CalendarViewState currentViewState, + DateTime? selectedDate, + DateTime? appointmentSelectedDate, + ) { if (widget.view == CalendarView.month) { - final int rowIndex = - _getRowOfDate(currentView.visibleDates, selectedDate!); + final int rowIndex = _getRowOfDate( + currentView.visibleDates, + selectedDate!, + ); if (rowIndex == 0) { return selectedDate; } selectedDate = AppointmentHelper.addDaysWithTime( - selectedDate, - -DateTime.daysPerWeek, - selectedDate.hour, - selectedDate.minute, - selectedDate.second); + selectedDate, + -DateTime.daysPerWeek, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); /// Move to month start date when the new selected date as /// previous month date. if (!CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentView.visibleDates[currentView.visibleDates.length ~/ 2].month, - selectedDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentView.visibleDates[currentView.visibleDates.length ~/ 2].month, + selectedDate, + )) { selectedDate = AppointmentHelper.getMonthStartDate( - currentViewState._selectionPainter!.selectedDate ?? - appointmentSelectedDate!); + currentViewState._selectionPainter!.selectedDate ?? + appointmentSelectedDate!, + ); if (CalendarViewHelper.isDateInDateCollection( - currentView.blackoutDates, selectedDate)) { + currentView.blackoutDates, + selectedDate, + )) { do { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate!, 1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate!, + 1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } while (CalendarViewHelper.isDateInDateCollection( - currentView.blackoutDates, selectedDate)); + currentView.blackoutDates, + selectedDate, + )); } } return selectedDate; } else if (!CalendarViewHelper.isTimelineView(widget.view)) { final double yPosition = AppointmentHelper.timeToPosition( - widget.calendar, selectedDate!, currentViewState._timeIntervalHeight); + widget.calendar, + selectedDate!, + currentViewState._timeIntervalHeight, + ); if (yPosition < 1) { return selectedDate; } if (yPosition - 1 <= currentViewState._scrollController!.offset) { - currentViewState._scrollController! - .jumpTo(yPosition - currentViewState._timeIntervalHeight); + currentViewState._scrollController!.jumpTo( + yPosition - currentViewState._timeIntervalHeight, + ); } - return selectedDate - .subtract(widget.calendar.timeSlotViewSettings.timeInterval); + return selectedDate.subtract( + widget.calendar.timeSlotViewSettings.timeInterval, + ); } else if (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { final double resourceItemHeight = CalendarViewHelper.getResourceItemHeight( - widget.calendar.resourceViewSettings.size, - widget.height, - widget.calendar.resourceViewSettings, - widget.calendar.dataSource!.resources!.length); + widget.calendar.resourceViewSettings.size, + widget.height, + widget.calendar.resourceViewSettings, + widget.calendar.dataSource!.resources!.length, + ); currentViewState._selectedResourceIndex -= 1; @@ -4085,10 +4649,11 @@ class _CustomCalendarScrollViewState extends State currentViewState._timelineViewVerticalScrollController!.offset) { double scrollPosition = currentViewState._timelineViewVerticalScrollController!.offset - - resourceItemHeight; + resourceItemHeight; scrollPosition = scrollPosition > 0 ? scrollPosition : 0; - currentViewState._timelineViewVerticalScrollController! - .jumpTo(scrollPosition); + currentViewState._timelineViewVerticalScrollController!.jumpTo( + scrollPosition, + ); } return selectedDate; @@ -4098,50 +4663,70 @@ class _CustomCalendarScrollViewState extends State } DateTime? _updateSelectedDateForDownArrow( - _CalendarView currentView, - _CalendarViewState currentViewState, - DateTime? selectedDate, - DateTime? selectedAppointmentDate) { + _CalendarView currentView, + _CalendarViewState currentViewState, + DateTime? selectedDate, + DateTime? selectedAppointmentDate, + ) { if (widget.view == CalendarView.month) { - final int rowIndex = - _getRowOfDate(currentView.visibleDates, selectedDate!); + final int rowIndex = _getRowOfDate( + currentView.visibleDates, + selectedDate!, + ); if (rowIndex == widget.calendar.monthViewSettings.numberOfWeeksInView - 1) { return selectedDate; } selectedDate = AppointmentHelper.addDaysWithTime( - selectedDate, - DateTime.daysPerWeek, - selectedDate.hour, - selectedDate.minute, - selectedDate.second); + selectedDate, + DateTime.daysPerWeek, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); /// Move to month end date when the new selected date as next month date. if (!CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentView.visibleDates[currentView.visibleDates.length ~/ 2].month, - selectedDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentView.visibleDates[currentView.visibleDates.length ~/ 2].month, + selectedDate, + )) { selectedDate = AppointmentHelper.getMonthEndDate( - currentViewState._selectionPainter!.selectedDate ?? - selectedAppointmentDate!); + currentViewState._selectionPainter!.selectedDate ?? + selectedAppointmentDate!, + ); if (CalendarViewHelper.isDateInDateCollection( - currentView.blackoutDates, selectedDate)) { + currentView.blackoutDates, + selectedDate, + )) { do { - selectedDate = AppointmentHelper.addDaysWithTime(selectedDate!, -1, - selectedDate.hour, selectedDate.minute, selectedDate.second); + selectedDate = AppointmentHelper.addDaysWithTime( + selectedDate!, + -1, + selectedDate.hour, + selectedDate.minute, + selectedDate.second, + ); } while (CalendarViewHelper.isDateInDateCollection( - currentView.blackoutDates, selectedDate)); + currentView.blackoutDates, + selectedDate, + )); } } return selectedDate; } else if (!CalendarViewHelper.isTimelineView(widget.view)) { final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); final double yPosition = AppointmentHelper.timeToPosition( - widget.calendar, selectedDate!, currentViewState._timeIntervalHeight); + widget.calendar, + selectedDate!, + currentViewState._timeIntervalHeight, + ); if (selectedDate .add(widget.calendar.timeSlotViewSettings.timeInterval) @@ -4154,7 +4739,9 @@ class _CustomCalendarScrollViewState extends State (widget.height - viewHeaderHeight) < currentViewState._scrollController!.position.viewportDimension + currentViewState - ._scrollController!.position.maxScrollExtent && + ._scrollController! + .position + .maxScrollExtent && yPosition + currentViewState._timeIntervalHeight + widget.calendar.headerHeight + @@ -4162,22 +4749,29 @@ class _CustomCalendarScrollViewState extends State currentViewState._scrollController!.offset + widget.height && currentViewState._scrollController!.offset + currentViewState - ._scrollController!.position.viewportDimension != + ._scrollController! + .position + .viewportDimension != currentViewState._scrollController!.position.maxScrollExtent) { currentViewState._scrollController!.jumpTo( - currentViewState._scrollController!.offset + - currentViewState._timeIntervalHeight); + currentViewState._scrollController!.offset + + currentViewState._timeIntervalHeight, + ); } - return selectedDate - .add(widget.calendar.timeSlotViewSettings.timeInterval); + return selectedDate.add( + widget.calendar.timeSlotViewSettings.timeInterval, + ); } else if (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { final double resourceItemHeight = CalendarViewHelper.getResourceItemHeight( - widget.calendar.resourceViewSettings.size, - widget.height, - widget.calendar.resourceViewSettings, - widget.calendar.dataSource!.resources!.length); + widget.calendar.resourceViewSettings.size, + widget.height, + widget.calendar.resourceViewSettings, + widget.calendar.dataSource!.resources!.length, + ); if (currentViewState._selectedResourceIndex == widget.calendar.dataSource!.resources!.length - 1 || currentViewState._selectedResourceIndex == -1) { @@ -4188,19 +4782,27 @@ class _CustomCalendarScrollViewState extends State if (currentViewState._selectedResourceIndex * resourceItemHeight >= currentViewState._timelineViewVerticalScrollController!.offset + - currentViewState._timelineViewVerticalScrollController!.position + currentViewState + ._timelineViewVerticalScrollController! + .position .viewportDimension) { double scrollPosition = currentViewState._timelineViewVerticalScrollController!.offset + - resourceItemHeight; - scrollPosition = scrollPosition > - currentViewState._timelineViewVerticalScrollController!.position + resourceItemHeight; + scrollPosition = + scrollPosition > + currentViewState + ._timelineViewVerticalScrollController! + .position + .maxScrollExtent + ? currentViewState + ._timelineViewVerticalScrollController! + .position .maxScrollExtent - ? currentViewState - ._timelineViewVerticalScrollController!.position.maxScrollExtent - : scrollPosition; - currentViewState._timelineViewVerticalScrollController! - .jumpTo(scrollPosition); + : scrollPosition; + currentViewState._timelineViewVerticalScrollController!.jumpTo( + scrollPosition, + ); } return selectedDate!; @@ -4220,48 +4822,62 @@ class _CustomCalendarScrollViewState extends State currentViewState = _nextViewKey.currentState!; } - final double scrollPosition = - currentViewState._getScrollPositionForCurrentDate( - currentViewState._selectionPainter!.selectedDate!); + final double scrollPosition = currentViewState + ._getScrollPositionForCurrentDate( + currentViewState._selectionPainter!.selectedDate!, + ); if (scrollPosition == -1 || currentViewState._scrollController!.position.pixels == scrollPosition) { return; } currentViewState._scrollController!.jumpTo( - currentViewState._scrollController!.position.maxScrollExtent > - scrollPosition - ? scrollPosition - : currentViewState._scrollController!.position.maxScrollExtent); + currentViewState._scrollController!.position.maxScrollExtent > + scrollPosition + ? scrollPosition + : currentViewState._scrollController!.position.maxScrollExtent, + ); } DateTime? _updateSelectedDate( - KeyEvent event, - _CalendarViewState currentViewState, - _CalendarView currentView, - int resourceIndex, - DateTime? selectedAppointmentDate, - bool isAllDayAppointment) { - DateTime? selectedDate = currentViewState._selectionPainter!.selectedDate ?? + KeyEvent event, + _CalendarViewState currentViewState, + _CalendarView currentView, + int resourceIndex, + DateTime? selectedAppointmentDate, + bool isAllDayAppointment, + ) { + DateTime? selectedDate = + currentViewState._selectionPainter!.selectedDate ?? selectedAppointmentDate; if (event.logicalKey == LogicalKeyboardKey.arrowRight) { do { selectedDate = _updateSelectedDateForRightArrow( - currentView, currentViewState, selectedDate); + currentView, + currentViewState, + selectedDate, + ); } while (!_isSelectedDateEnabled(selectedDate, resourceIndex, true)); return selectedDate; } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { do { selectedDate = _updateSelectedDateForLeftArrow( - currentView, currentViewState, selectedDate); + currentView, + currentViewState, + selectedDate, + ); } while (!_isSelectedDateEnabled(selectedDate, resourceIndex, true)); return selectedDate; } else if (event.logicalKey == LogicalKeyboardKey.arrowUp) { do { - selectedDate = _updateSelectedDateForUpArrow(currentView, - currentViewState, selectedDate, selectedAppointmentDate); + selectedDate = _updateSelectedDateForUpArrow( + currentView, + currentViewState, + selectedDate, + selectedAppointmentDate, + ); if (resourceIndex != -1 && currentView.regions != null && currentView.regions!.isNotEmpty) { @@ -4270,14 +4886,18 @@ class _CustomCalendarScrollViewState extends State if (widget.controller.view != CalendarView.month && !CalendarViewHelper.isTimelineView(widget.calendar.view)) { - double yPosition = AppointmentHelper.timeToPosition(widget.calendar, - selectedDate!, currentViewState._timeIntervalHeight); + double yPosition = AppointmentHelper.timeToPosition( + widget.calendar, + selectedDate!, + currentViewState._timeIntervalHeight, + ); if (yPosition < 1 && !_isSelectedDateEnabled(selectedDate, resourceIndex, true)) { yPosition = AppointmentHelper.timeToPosition( - widget.calendar, - currentViewState._selectionPainter!.selectedDate!, - currentViewState._timeIntervalHeight); + widget.calendar, + currentViewState._selectionPainter!.selectedDate!, + currentViewState._timeIntervalHeight, + ); currentViewState._scrollController!.jumpTo(yPosition); break; } @@ -4291,8 +4911,12 @@ class _CustomCalendarScrollViewState extends State } do { - selectedDate = _updateSelectedDateForDownArrow(currentView, - currentViewState, selectedDate, selectedAppointmentDate); + selectedDate = _updateSelectedDateForDownArrow( + currentView, + currentViewState, + selectedDate, + selectedAppointmentDate, + ); if (resourceIndex != -1 && currentView.regions != null && currentView.regions!.isNotEmpty) { @@ -4306,9 +4930,10 @@ class _CustomCalendarScrollViewState extends State .day != selectedDate.day) { final double yPosition = AppointmentHelper.timeToPosition( - widget.calendar, - currentViewState._selectionPainter!.selectedDate!, - currentViewState._timeIntervalHeight); + widget.calendar, + currentViewState._selectionPainter!.selectedDate!, + currentViewState._timeIntervalHeight, + ); if (yPosition <= currentViewState._scrollController!.offset) { currentViewState._scrollController!.jumpTo(yPosition); } @@ -4325,21 +4950,30 @@ class _CustomCalendarScrollViewState extends State } /// Checks the selected date is enabled or not. - bool _isSelectedDateEnabled(DateTime date, int resourceIndex, - [bool isMinMaxDate = false]) { - final bool isMonthView = widget.view == CalendarView.month || + bool _isSelectedDateEnabled( + DateTime date, + int resourceIndex, [ + bool isMinMaxDate = false, + ]) { + final bool isMonthView = + widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); if ((isMonthView && !isDateWithInDateRange( - widget.calendar.minDate, widget.calendar.maxDate, date)) || + widget.calendar.minDate, + widget.calendar.maxDate, + date, + )) || (!isMonthView && !CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - date, - timeInterval))) { + widget.calendar.minDate, + widget.calendar.maxDate, + date, + timeInterval, + ))) { return isMinMaxDate; } @@ -4354,7 +4988,9 @@ class _CustomCalendarScrollViewState extends State if (region.enablePointerInteraction || (region.actualStartTime.isAfter(date) && !CalendarViewHelper.isSameTimeSlot( - region.actualStartTime, date)) || + region.actualStartTime, + date, + )) || region.actualEndTime.isBefore(date) || CalendarViewHelper.isSameTimeSlot(region.actualEndTime, date)) { continue; @@ -4365,8 +5001,9 @@ class _CustomCalendarScrollViewState extends State if (resourceIndex != -1 && region.resourceIds != null && region.resourceIds!.isNotEmpty && - !region.resourceIds! - .contains(widget.resourceCollection![resourceIndex].id)) { + !region.resourceIds!.contains( + widget.resourceCollection![resourceIndex].id, + )) { continue; } @@ -4378,8 +5015,11 @@ class _CustomCalendarScrollViewState extends State } /// Method to handle the page up/down key for timeslot views in calendar. - KeyEventResult _updatePageUpAndDown(KeyEvent event, - _CalendarViewState currentViewState, bool isResourceEnabled) { + KeyEventResult _updatePageUpAndDown( + KeyEvent event, + _CalendarViewState currentViewState, + bool isResourceEnabled, + ) { if (widget.controller.view != CalendarView.day && widget.controller.view != CalendarView.week && widget.controller.view != CalendarView.workWeek && @@ -4388,17 +5028,20 @@ class _CustomCalendarScrollViewState extends State } final bool isDayView = CalendarViewHelper.isDayView( - widget.controller.view!, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final ScrollController scrollController = isResourceEnabled - ? widget.resourcePanelScrollController! - : currentViewState._scrollController!; + widget.controller.view!, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final ScrollController scrollController = + isResourceEnabled + ? widget.resourcePanelScrollController! + : currentViewState._scrollController!; final TargetPlatform platform = Theme.of(context).platform; double difference = 0; - final double scrollViewHeight = scrollController.position.maxScrollExtent + + final double scrollViewHeight = + scrollController.position.maxScrollExtent + scrollController.position.viewportDimension; double divideValue = 0.25; if (scrollController.position.pixels > scrollViewHeight / 2) { @@ -4417,25 +5060,30 @@ class _CustomCalendarScrollViewState extends State (platform == TargetPlatform.windows && event.logicalKey.keyId == 0x10700000022)) { double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.controller.view!); + widget.calendar.viewHeaderHeight, + widget.controller.view!, + ); double allDayHeight = 0; if (isDayView) { allDayHeight = _kAllDayLayoutHeight; viewHeaderHeight = 0; } else { - allDayHeight = allDayHeight > _kAllDayLayoutHeight - ? _kAllDayLayoutHeight - : allDayHeight; + allDayHeight = + allDayHeight > _kAllDayLayoutHeight + ? _kAllDayLayoutHeight + : allDayHeight; } final double timeRulerSize = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, - widget.controller.view!); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.controller.view!, + ); - final double viewPortHeight = isResourceEnabled - ? widget.height - viewHeaderHeight - timeRulerSize - : widget.height - allDayHeight - viewHeaderHeight; + final double viewPortHeight = + isResourceEnabled + ? widget.height - viewHeaderHeight - timeRulerSize + : widget.height - allDayHeight - viewHeaderHeight; final double viewPortEndPosition = scrollController.position.pixels + viewPortHeight; @@ -4457,20 +5105,21 @@ class _CustomCalendarScrollViewState extends State /// Updates the appointment selection based on keyboard navigation in calendar KeyEventResult _updateAppointmentSelection( - KeyEvent event, - _CalendarViewState currentVisibleViewState, - bool isResourceEnabled, - AppointmentView? currentSelectedAppointment, - AppointmentView? currentAllDayAppointment) { + KeyEvent event, + _CalendarViewState currentVisibleViewState, + bool isResourceEnabled, + AppointmentView? currentSelectedAppointment, + AppointmentView? currentAllDayAppointment, + ) { if (widget.controller.view == CalendarView.schedule) { return KeyEventResult.ignored; } AppointmentView? selectedAppointment; bool isAllDay = currentAllDayAppointment != null; - final List appointmentCollection = currentVisibleViewState - ._appointmentLayout - .getAppointmentViewCollection(); + final List appointmentCollection = + currentVisibleViewState._appointmentLayout + .getAppointmentViewCollection(); final List allDayAppointmentCollection = _updateCalendarStateDetails.allDayAppointmentViewCollection; final List tempAppColl = @@ -4479,23 +5128,26 @@ class _CustomCalendarScrollViewState extends State if (event.logicalKey == LogicalKeyboardKey.tab) { if (currentAllDayAppointment != null || currentSelectedAppointment != null) { - int index = tempAppColl.indexOf(isAllDay - ? currentAllDayAppointment - : currentSelectedAppointment!); + int index = tempAppColl.indexOf( + isAllDay ? currentAllDayAppointment : currentSelectedAppointment!, + ); index -= 1; if (tempAppColl.length > index && !index.isNegative) { - selectedAppointment = tempAppColl[index].appointment != null - ? tempAppColl[index] - : null; + selectedAppointment = + tempAppColl[index].appointment != null + ? tempAppColl[index] + : null; } } if (currentSelectedAppointment != null && selectedAppointment == null) { isAllDay = allDayAppointmentCollection.isNotEmpty; - selectedAppointment = isAllDay - ? allDayAppointmentCollection[ - allDayAppointmentCollection.length - 1] - : null; + selectedAppointment = + isAllDay + ? allDayAppointmentCollection[allDayAppointmentCollection + .length - + 1] + : null; } else if (currentSelectedAppointment == null && currentAllDayAppointment == null && selectedAppointment == null) { @@ -4503,9 +5155,9 @@ class _CustomCalendarScrollViewState extends State appointmentCollection.isNotEmpty) { for (int i = 0; i < appointmentCollection.length; i++) { if (AppointmentHelper.getDifference( - currentVisibleViewState._selectionPainter!.selectedDate!, - appointmentCollection[i].appointment!.actualStartTime) - .isNegative) { + currentVisibleViewState._selectionPainter!.selectedDate!, + appointmentCollection[i].appointment!.actualStartTime, + ).isNegative) { continue; } @@ -4515,29 +5167,33 @@ class _CustomCalendarScrollViewState extends State break; } } else { - selectedAppointment = appointmentCollection.isNotEmpty - ? appointmentCollection[appointmentCollection.length - 1] - : null; + selectedAppointment = + appointmentCollection.isNotEmpty + ? appointmentCollection[appointmentCollection.length - 1] + : null; } } return _updateAppointmentSelectionOnView( - selectedAppointment, - currentVisibleViewState, - isAllDay, - isResourceEnabled, - !HardwareKeyboard.instance.isShiftPressed); + selectedAppointment, + currentVisibleViewState, + isAllDay, + isResourceEnabled, + !HardwareKeyboard.instance.isShiftPressed, + ); } } else if (event.logicalKey == LogicalKeyboardKey.tab) { if (currentAllDayAppointment != null || currentSelectedAppointment != null) { int index = tempAppColl.indexOf( - isAllDay ? currentAllDayAppointment : currentSelectedAppointment!); + isAllDay ? currentAllDayAppointment : currentSelectedAppointment!, + ); index += 1; if (tempAppColl.length > index) { - selectedAppointment = tempAppColl[index].appointment != null - ? tempAppColl[index] - : null; + selectedAppointment = + tempAppColl[index].appointment != null + ? tempAppColl[index] + : null; } } @@ -4550,9 +5206,9 @@ class _CustomCalendarScrollViewState extends State appointmentCollection.isNotEmpty) { for (int i = 0; i < appointmentCollection.length; i++) { if (AppointmentHelper.getDifference( - currentVisibleViewState._selectionPainter!.selectedDate!, - appointmentCollection[i].appointment!.actualStartTime) - .isNegative) { + currentVisibleViewState._selectionPainter!.selectedDate!, + appointmentCollection[i].appointment!.actualStartTime, + ).isNegative) { continue; } @@ -4561,20 +5217,22 @@ class _CustomCalendarScrollViewState extends State } } else { isAllDay = allDayAppointmentCollection.isNotEmpty; - selectedAppointment = isAllDay - ? allDayAppointmentCollection[0] - : appointmentCollection.isNotEmpty + selectedAppointment = + isAllDay + ? allDayAppointmentCollection[0] + : appointmentCollection.isNotEmpty ? appointmentCollection[0] : null; } } return _updateAppointmentSelectionOnView( - selectedAppointment, - currentVisibleViewState, - isAllDay, - isResourceEnabled, - !HardwareKeyboard.instance.isShiftPressed); + selectedAppointment, + currentVisibleViewState, + isAllDay, + isResourceEnabled, + !HardwareKeyboard.instance.isShiftPressed, + ); } return KeyEventResult.ignored; @@ -4583,22 +5241,27 @@ class _CustomCalendarScrollViewState extends State /// Updates the selection for appointment view based on keyboard navigation /// in Calendar. KeyEventResult _updateAppointmentSelectionOnView( - AppointmentView? selectedAppointment, - _CalendarViewState currentVisibleViewState, - bool isAllDay, - bool isResourceEnabled, - bool isForward) { + AppointmentView? selectedAppointment, + _CalendarViewState currentVisibleViewState, + bool isAllDay, + bool isResourceEnabled, + bool isForward, + ) { final DateTime visibleStartDate = AppointmentHelper.convertToStartTime( - currentVisibleViewState.widget.visibleDates[0]); + currentVisibleViewState.widget.visibleDates[0], + ); final DateTime visibleEndDate = AppointmentHelper.convertToEndTime( - currentVisibleViewState.widget.visibleDates[ - currentVisibleViewState.widget.visibleDates.length - 1]); + currentVisibleViewState + .widget + .visibleDates[currentVisibleViewState.widget.visibleDates.length - 1], + ); final bool isDayView = CalendarViewHelper.isDayView( - widget.controller.view!, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.controller.view!, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); if (isAllDay && selectedAppointment != null) { currentVisibleViewState._updateAllDaySelection(selectedAppointment, null); @@ -4613,9 +5276,10 @@ class _CustomCalendarScrollViewState extends State if (selectedAppointment != null && AppointmentHelper.isAppointmentWithinVisibleDateRange( - selectedAppointment.appointment!, - visibleStartDate, - visibleEndDate)) { + selectedAppointment.appointment!, + visibleStartDate, + visibleEndDate, + )) { currentVisibleViewState._allDaySelectionNotifier.value = null; currentVisibleViewState._selectionPainter!.appointmentView = selectedAppointment; @@ -4626,16 +5290,24 @@ class _CustomCalendarScrollViewState extends State if (widget.controller.view != CalendarView.month) { late double offset; late double viewPortSize; - final double scrollViewHeight = currentVisibleViewState - ._scrollController!.position.maxScrollExtent + + final double scrollViewHeight = + currentVisibleViewState + ._scrollController! + .position + .maxScrollExtent + currentVisibleViewState - ._scrollController!.position.viewportDimension; + ._scrollController! + .position + .viewportDimension; final double resourceViewSize = isResourceEnabled ? widget.calendar.resourceViewSettings.size : 0; - final bool isTimeline = - CalendarViewHelper.isTimelineView(widget.controller.view!); + final bool isTimeline = CalendarViewHelper.isTimelineView( + widget.controller.view!, + ); double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.controller.view!); + widget.calendar.viewHeaderHeight, + widget.controller.view!, + ); if (isTimeline) { viewPortSize = widget.width - resourceViewSize; @@ -4647,33 +5319,37 @@ class _CustomCalendarScrollViewState extends State allDayHeight = _kAllDayLayoutHeight; viewHeaderHeight = 0; } else { - allDayHeight = allDayHeight > _kAllDayLayoutHeight - ? _kAllDayLayoutHeight - : allDayHeight; + allDayHeight = + allDayHeight > _kAllDayLayoutHeight + ? _kAllDayLayoutHeight + : allDayHeight; } viewPortSize = widget.height - allDayHeight - viewHeaderHeight; offset = selectedAppointment.appointmentRect!.top; } _updateScrollViewToAppointment( - offset, - currentVisibleViewState._scrollController!, - viewPortSize, - scrollViewHeight); + offset, + currentVisibleViewState._scrollController!, + viewPortSize, + scrollViewHeight, + ); if (isResourceEnabled) { - final double resourcePanelHeight = widget - .resourcePanelScrollController!.position.viewportDimension + + final double resourcePanelHeight = + widget.resourcePanelScrollController!.position.viewportDimension + widget.resourcePanelScrollController!.position.maxScrollExtent; final double timeRulerSize = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, - widget.controller.view!), + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.controller.view!, + ), viewPortSize = widget.height - viewHeaderHeight - timeRulerSize; _updateScrollViewToAppointment( - selectedAppointment.appointmentRect!.top, - widget.resourcePanelScrollController!, - viewPortSize, - resourcePanelHeight); + selectedAppointment.appointmentRect!.top, + widget.resourcePanelScrollController!, + viewPortSize, + resourcePanelHeight, + ); } } else if (widget.controller.view == CalendarView.month) { widget.agendaSelectedDate.value = null; @@ -4700,10 +5376,11 @@ class _CustomCalendarScrollViewState extends State /// Moves the scroll panel to the selected appointments position, if the /// selected appointment doesn't falls on the view port. void _updateScrollViewToAppointment( - double offset, - ScrollController scrollController, - double viewPortSize, - double panelHeight) { + double offset, + ScrollController scrollController, + double viewPortSize, + double panelHeight, + ) { if (offset < scrollController.position.pixels || offset > (scrollController.position.pixels + viewPortSize)) { if (offset + viewPortSize > panelHeight) { @@ -4724,21 +5401,23 @@ class _CustomCalendarScrollViewState extends State if (HardwareKeyboard.instance.isControlPressed && widget.view != CalendarView.schedule) { final bool canMoveToNextView = DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + ); final bool canMoveToPreviousView = DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL); + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + ); if (event.logicalKey == LogicalKeyboardKey.arrowRight && canMoveToNextView) { widget.isRTL @@ -4756,12 +5435,17 @@ class _CustomCalendarScrollViewState extends State } CalendarViewHelper.handleViewSwitchKeyBoardEvent( - event, widget.controller, widget.calendar.allowedViews); + event, + widget.controller, + widget.calendar.allowedViews, + ); _CalendarViewState currentVisibleViewState; _CalendarView currentVisibleView; final bool isResourcesEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); if (_currentChildIndex == 0) { currentVisibleViewState = _previousViewKey.currentState!; currentVisibleView = _previousView; @@ -4774,7 +5458,10 @@ class _CustomCalendarScrollViewState extends State } result = _updatePageUpAndDown( - event, currentVisibleViewState, isResourcesEnabled); + event, + currentVisibleViewState, + isResourcesEnabled, + ); AppointmentView? currentSelectedAppointment = currentVisibleViewState._selectionPainter!.appointmentView; @@ -4782,11 +5469,12 @@ class _CustomCalendarScrollViewState extends State currentVisibleViewState._allDaySelectionNotifier.value?.appointmentView; result = _updateAppointmentSelection( - event, - currentVisibleViewState, - isResourcesEnabled, - currentSelectedAppointment, - currentAllDayAppointment); + event, + currentVisibleViewState, + isResourcesEnabled, + currentSelectedAppointment, + currentAllDayAppointment, + ); currentSelectedAppointment = currentVisibleViewState._selectionPainter!.appointmentView; @@ -4795,69 +5483,88 @@ class _CustomCalendarScrollViewState extends State if (event.logicalKey == LogicalKeyboardKey.enter && CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.calendar.onTap)) { - final AppointmentView? selectedAppointment = currentVisibleViewState - ._allDaySelectionNotifier.value?.appointmentView ?? + widget.calendar.onTap, + )) { + final AppointmentView? selectedAppointment = + currentVisibleViewState + ._allDaySelectionNotifier + .value + ?.appointmentView ?? currentVisibleViewState._selectionPainter!.appointmentView; final List? selectedAppointments = widget.controller.view == CalendarView.month && selectedAppointment == null ? AppointmentHelper.getSelectedDateAppointments( - _updateCalendarStateDetails.appointments, - widget.calendar.timeZone, - _updateCalendarStateDetails.selectedDate) + _updateCalendarStateDetails.appointments, + widget.calendar.timeZone, + _updateCalendarStateDetails.selectedDate, + ) : selectedAppointment != null - ? [selectedAppointment.appointment!] - : null; + ? [selectedAppointment.appointment!] + : null; final CalendarElement tappedElement = _updateCalendarStateDetails.selectedDate != null ? CalendarElement.calendarCell : CalendarElement.appointment; CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, - tappedElement == CalendarElement.appointment - ? selectedAppointments![0].startTime - : _updateCalendarStateDetails.selectedDate, - CalendarViewHelper.getCustomAppointments( - selectedAppointments, widget.calendar.dataSource), - tappedElement, - isResourcesEnabled - ? widget.calendar.dataSource! - .resources![currentVisibleViewState._selectedResourceIndex] - : null); + widget.calendar, + tappedElement == CalendarElement.appointment + ? selectedAppointments![0].startTime + : _updateCalendarStateDetails.selectedDate, + CalendarViewHelper.getCustomAppointments( + selectedAppointments, + widget.calendar.dataSource, + ), + tappedElement, + isResourcesEnabled + ? widget.calendar.dataSource!.resources![currentVisibleViewState + ._selectedResourceIndex] + : null, + ); } - final int previousResourceIndex = isResourcesEnabled - ? currentVisibleViewState._selectedResourceIndex - : -1; + final int previousResourceIndex = + isResourcesEnabled + ? currentVisibleViewState._selectedResourceIndex + : -1; if ((currentVisibleViewState._selectionPainter!.selectedDate != null && isDateWithInDateRange( - currentVisibleViewState.widget.visibleDates[0], - currentVisibleViewState.widget.visibleDates[ - currentVisibleViewState.widget.visibleDates.length - 1], - currentVisibleViewState._selectionPainter!.selectedDate)) || + currentVisibleViewState.widget.visibleDates[0], + currentVisibleViewState + .widget + .visibleDates[currentVisibleViewState + .widget + .visibleDates + .length - + 1], + currentVisibleViewState._selectionPainter!.selectedDate, + )) || (currentSelectedAppointment != null || currentAllDayAppointment != null)) { - final int resourceIndex = isResourcesEnabled - ? currentVisibleViewState._selectedResourceIndex - : -1; + final int resourceIndex = + isResourcesEnabled + ? currentVisibleViewState._selectedResourceIndex + : -1; - final DateTime? selectedAppointmentDate = currentAllDayAppointment != null - ? AppointmentHelper.convertToStartTime( - currentAllDayAppointment.appointment!.actualStartTime) - : currentSelectedAppointment?.appointment!.actualStartTime; + final DateTime? selectedAppointmentDate = + currentAllDayAppointment != null + ? AppointmentHelper.convertToStartTime( + currentAllDayAppointment.appointment!.actualStartTime, + ) + : currentSelectedAppointment?.appointment!.actualStartTime; final bool isAllDayAppointment = currentAllDayAppointment != null; final DateTime? selectedDate = _updateSelectedDate( - event, - currentVisibleViewState, - currentVisibleView, - resourceIndex, - selectedAppointmentDate, - isAllDayAppointment); + event, + currentVisibleViewState, + currentVisibleView, + resourceIndex, + selectedAppointmentDate, + isAllDayAppointment, + ); if (selectedDate == null) { result = KeyEventResult.ignored; @@ -4876,19 +5583,22 @@ class _CustomCalendarScrollViewState extends State _updateCalendarStateDetails.selectedDate = selectedDate; if (widget.calendar.onSelectionChanged != null && (!CalendarViewHelper.isSameTimeSlot( - currentVisibleViewState._selectionPainter!.selectedDate, - selectedDate) || + currentVisibleViewState._selectionPainter!.selectedDate, + selectedDate, + ) || (isResourcesEnabled && currentVisibleViewState - ._selectionPainter!.selectedResourceIndex != + ._selectionPainter! + .selectedResourceIndex != currentVisibleViewState._selectedResourceIndex))) { CalendarViewHelper.raiseCalendarSelectionChangedCallback( - widget.calendar, - selectedDate, - isResourcesEnabled - ? widget.resourceCollection![ - currentVisibleViewState._selectedResourceIndex] - : null); + widget.calendar, + selectedDate, + isResourcesEnabled + ? widget.resourceCollection![currentVisibleViewState + ._selectedResourceIndex] + : null, + ); } currentVisibleViewState._selectionPainter!.selectedDate = selectedDate; currentVisibleViewState._updateAllDaySelection(null, null); @@ -4911,61 +5621,77 @@ class _CustomCalendarScrollViewState extends State final _CalendarViewState nextViewState = _nextViewKey.currentState!; if (widget.isRTL) { if (_currentChildIndex == 0) { - currentViewState._scrollController!.jumpTo(isScrolledToEnd - ? currentViewState._scrollController!.position.maxScrollExtent - : 0); + currentViewState._scrollController!.jumpTo( + isScrolledToEnd + ? currentViewState._scrollController!.position.maxScrollExtent + : 0, + ); nextViewState._scrollController!.jumpTo(0); } else if (_currentChildIndex == 1) { - nextViewState._scrollController!.jumpTo(isScrolledToEnd - ? nextViewState._scrollController!.position.maxScrollExtent - : 0); + nextViewState._scrollController!.jumpTo( + isScrolledToEnd + ? nextViewState._scrollController!.position.maxScrollExtent + : 0, + ); previousViewState._scrollController!.jumpTo(0); } else if (_currentChildIndex == 2) { - previousViewState._scrollController!.jumpTo(isScrolledToEnd - ? previousViewState._scrollController!.position.maxScrollExtent - : 0); + previousViewState._scrollController!.jumpTo( + isScrolledToEnd + ? previousViewState._scrollController!.position.maxScrollExtent + : 0, + ); currentViewState._scrollController!.jumpTo(0); } } else { if (_currentChildIndex == 0) { - nextViewState._scrollController!.jumpTo(isScrolledToEnd - ? nextViewState._scrollController!.position.maxScrollExtent - : 0); + nextViewState._scrollController!.jumpTo( + isScrolledToEnd + ? nextViewState._scrollController!.position.maxScrollExtent + : 0, + ); currentViewState._scrollController!.jumpTo(0); } else if (_currentChildIndex == 1) { - previousViewState._scrollController!.jumpTo(isScrolledToEnd - ? previousViewState._scrollController!.position.maxScrollExtent - : 0); + previousViewState._scrollController!.jumpTo( + isScrolledToEnd + ? previousViewState._scrollController!.position.maxScrollExtent + : 0, + ); nextViewState._scrollController!.jumpTo(0); } else if (_currentChildIndex == 2) { - currentViewState._scrollController!.jumpTo(isScrolledToEnd - ? currentViewState._scrollController!.position.maxScrollExtent - : 0); + currentViewState._scrollController!.jumpTo( + isScrolledToEnd + ? currentViewState._scrollController!.position.maxScrollExtent + : 0, + ); previousViewState._scrollController!.jumpTo(0); } } } void _onHorizontalStart( - DragStartDetails dragStartDetails, - bool isResourceEnabled, - bool isTimelineView, - double viewHeaderHeight, - double timeLabelWidth, - bool isNeedDragAndDrop) { + DragStartDetails dragStartDetails, + bool isResourceEnabled, + bool isTimelineView, + double viewHeaderHeight, + double timeLabelWidth, + bool isNeedDragAndDrop, + ) { final _CalendarViewState currentState = _getCurrentViewByVisibleDates()!; if (currentState._hoveringAppointmentView != null && currentState._hoveringAppointmentView!.appointment != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleAppointmentDragStart( - currentState._hoveringAppointmentView!.clone(), - isTimelineView, - Offset(dragStartDetails.localPosition.dx - widget.width, - dragStartDetails.localPosition.dy), - isResourceEnabled, - viewHeaderHeight, - timeLabelWidth); + currentState._hoveringAppointmentView!.clone(), + isTimelineView, + Offset( + dragStartDetails.localPosition.dx - widget.width, + dragStartDetails.localPosition.dy, + ), + isResourceEnabled, + viewHeaderHeight, + timeLabelWidth, + ); return; } switch (widget.calendar.viewNavigationMode) { @@ -4987,28 +5713,33 @@ class _CustomCalendarScrollViewState extends State } } - void _onHorizontalUpdate(DragUpdateDetails dragUpdateDetails, - [bool isResourceEnabled = false, - bool isMonthView = false, - bool isTimelineView = false, - double viewHeaderHeight = 0, - double timeLabelWidth = 0, - double resourceItemHeight = 0, - double weekNumberPanelWidth = 0, - bool isNeedDragAndDrop = false]) { + void _onHorizontalUpdate( + DragUpdateDetails dragUpdateDetails, [ + bool isResourceEnabled = false, + bool isMonthView = false, + bool isTimelineView = false, + double viewHeaderHeight = 0, + double timeLabelWidth = 0, + double resourceItemHeight = 0, + double weekNumberPanelWidth = 0, + bool isNeedDragAndDrop = false, + ]) { if (_dragDetails.value.appointmentView != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleLongPressMove( - Offset(dragUpdateDetails.localPosition.dx - widget.width, - dragUpdateDetails.localPosition.dy), - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - resourceItemHeight, - weekNumberPanelWidth); + Offset( + dragUpdateDetails.localPosition.dx - widget.width, + dragUpdateDetails.localPosition.dy, + ), + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + resourceItemHeight, + weekNumberPanelWidth, + ); return; } switch (widget.calendar.viewNavigationMode) { @@ -5023,24 +5754,26 @@ class _CustomCalendarScrollViewState extends State dragUpdateDetails.globalPosition.dx - _scrollStartPosition; if (difference < 0 && !DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { _position = 0; return; } else if (difference > 0 && !DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { _position = 0; return; } @@ -5054,25 +5787,28 @@ class _CustomCalendarScrollViewState extends State } } - void _onHorizontalEnd(DragEndDetails dragEndDetails, - [bool isResourceEnabled = false, - bool isTimelineView = false, - bool isMonthView = false, - double viewHeaderHeight = 0, - double timeLabelWidth = 0, - double weekNumberPanelWidth = 0, - bool isNeedDragAndDrop = false]) { + void _onHorizontalEnd( + DragEndDetails dragEndDetails, [ + bool isResourceEnabled = false, + bool isTimelineView = false, + bool isMonthView = false, + double viewHeaderHeight = 0, + double timeLabelWidth = 0, + double weekNumberPanelWidth = 0, + bool isNeedDragAndDrop = false, + ]) { if (_dragDetails.value.appointmentView != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleLongPressEnd( - _dragDetails.value.position.value! - _dragDifferenceOffset!, - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - weekNumberPanelWidth); + _dragDetails.value.position.value! - _dragDifferenceOffset!, + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + weekNumberPanelWidth, + ); return; } switch (widget.calendar.viewNavigationMode) { @@ -5094,9 +5830,9 @@ class _CustomCalendarScrollViewState extends State _animationController.reset(); } - _animationController - .forward() - .then((dynamic value) => _updateNextView()); + _animationController.forward().then( + (dynamic value) => _updateNextView(), + ); /// updates the current view visible dates when the view swiped in /// right to left direction @@ -5105,13 +5841,14 @@ class _CustomCalendarScrollViewState extends State // fling the view from right to left else if (-dragEndDetails.velocity.pixelsPerSecond.dx > widget.width) { if (!DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position @@ -5131,7 +5868,9 @@ class _CustomCalendarScrollViewState extends State _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updateNextView()); /// updates the current view visible dates when fling the view in @@ -5149,9 +5888,9 @@ class _CustomCalendarScrollViewState extends State _animationController.reset(); } - _animationController - .forward() - .then((dynamic value) => _updatePreviousView()); + _animationController.forward().then( + (dynamic value) => _updatePreviousView(), + ); /// updates the current view visible dates when the view swiped in /// left to right direction @@ -5160,13 +5899,14 @@ class _CustomCalendarScrollViewState extends State // fling the view from left to right else if (dragEndDetails.velocity.pixelsPerSecond.dx > widget.width) { if (!DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.isRTL)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.isRTL, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position @@ -5186,7 +5926,9 @@ class _CustomCalendarScrollViewState extends State _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updatePreviousView()); /// updates the current view visible dates when fling the view in @@ -5211,25 +5953,29 @@ class _CustomCalendarScrollViewState extends State } void _onVerticalStart( - DragStartDetails dragStartDetails, - bool isResourceEnabled, - bool isTimelineView, - double viewHeaderHeight, - double timeLabelWidth, - bool isNeedDragAndDrop) { + DragStartDetails dragStartDetails, + bool isResourceEnabled, + bool isTimelineView, + double viewHeaderHeight, + double timeLabelWidth, + bool isNeedDragAndDrop, + ) { final _CalendarViewState currentState = _getCurrentViewByVisibleDates()!; if (currentState._hoveringAppointmentView != null && currentState._hoveringAppointmentView!.appointment != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleAppointmentDragStart( - currentState._hoveringAppointmentView!.clone(), - isTimelineView, - Offset(dragStartDetails.localPosition.dx, - dragStartDetails.localPosition.dy - widget.height), - isResourceEnabled, - viewHeaderHeight, - timeLabelWidth); + currentState._hoveringAppointmentView!.clone(), + isTimelineView, + Offset( + dragStartDetails.localPosition.dx, + dragStartDetails.localPosition.dy - widget.height, + ), + isResourceEnabled, + viewHeaderHeight, + timeLabelWidth, + ); return; } switch (widget.calendar.viewNavigationMode) { @@ -5245,28 +5991,33 @@ class _CustomCalendarScrollViewState extends State } } - void _onVerticalUpdate(DragUpdateDetails dragUpdateDetails, - [bool isResourceEnabled = false, - bool isMonthView = false, - bool isTimelineView = false, - double viewHeaderHeight = 0, - double timeLabelWidth = 0, - double resourceItemHeight = 0, - double weekNumberPanelWidth = 0, - bool isNeedDragAndDrop = false]) { + void _onVerticalUpdate( + DragUpdateDetails dragUpdateDetails, [ + bool isResourceEnabled = false, + bool isMonthView = false, + bool isTimelineView = false, + double viewHeaderHeight = 0, + double timeLabelWidth = 0, + double resourceItemHeight = 0, + double weekNumberPanelWidth = 0, + bool isNeedDragAndDrop = false, + ]) { if (_dragDetails.value.appointmentView != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleLongPressMove( - Offset(dragUpdateDetails.localPosition.dx, - dragUpdateDetails.localPosition.dy - widget.height), - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - resourceItemHeight, - weekNumberPanelWidth); + Offset( + dragUpdateDetails.localPosition.dx, + dragUpdateDetails.localPosition.dy - widget.height, + ), + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + resourceItemHeight, + weekNumberPanelWidth, + ); return; } switch (widget.calendar.viewNavigationMode) { @@ -5281,22 +6032,24 @@ class _CustomCalendarScrollViewState extends State dragUpdateDetails.globalPosition.dy - _scrollStartPosition; if (difference < 0 && !DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + )) { _position = 0; return; } else if (difference > 0 && !DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + )) { _position = 0; return; } @@ -5309,25 +6062,28 @@ class _CustomCalendarScrollViewState extends State } } - void _onVerticalEnd(DragEndDetails dragEndDetails, - [bool isResourceEnabled = false, - bool isTimelineView = false, - bool isMonthView = false, - double viewHeaderHeight = 0, - double timeLabelWidth = 0, - double weekNumberPanelWidth = 0, - bool isNeedDragAndDrop = false]) { + void _onVerticalEnd( + DragEndDetails dragEndDetails, [ + bool isResourceEnabled = false, + bool isTimelineView = false, + bool isMonthView = false, + double viewHeaderHeight = 0, + double timeLabelWidth = 0, + double weekNumberPanelWidth = 0, + bool isNeedDragAndDrop = false, + ]) { if (_dragDetails.value.appointmentView != null && !widget.isMobilePlatform && isNeedDragAndDrop) { _handleLongPressEnd( - _dragDetails.value.position.value! - _dragDifferenceOffset!, - isTimelineView, - isResourceEnabled, - isMonthView, - viewHeaderHeight, - timeLabelWidth, - weekNumberPanelWidth); + _dragDetails.value.position.value! - _dragDifferenceOffset!, + isTimelineView, + isResourceEnabled, + isMonthView, + viewHeaderHeight, + timeLabelWidth, + weekNumberPanelWidth, + ); return; } switch (widget.calendar.viewNavigationMode) { @@ -5349,9 +6105,9 @@ class _CustomCalendarScrollViewState extends State _animationController.reset(); } - _animationController - .forward() - .then((dynamic value) => _updateNextView()); + _animationController.forward().then( + (dynamic value) => _updateNextView(), + ); /// updates the current view visible dates when the view swiped in /// bottom to top direction @@ -5361,12 +6117,13 @@ class _CustomCalendarScrollViewState extends State else if (-dragEndDetails.velocity.pixelsPerSecond.dy > widget.height) { if (!DateTimeHelper.canMoveToNextView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position in @@ -5386,7 +6143,9 @@ class _CustomCalendarScrollViewState extends State _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updateNextView()); /// updates the current view visible dates when fling the view in @@ -5404,9 +6163,9 @@ class _CustomCalendarScrollViewState extends State _animationController.reset(); } - _animationController - .forward() - .then((dynamic value) => _updatePreviousView()); + _animationController.forward().then( + (dynamic value) => _updatePreviousView(), + ); /// updates the current view visible dates when the view swiped in /// top to bottom direction @@ -5415,12 +6174,13 @@ class _CustomCalendarScrollViewState extends State // fling the view to top to bottom else if (dragEndDetails.velocity.pixelsPerSecond.dy > widget.height) { if (!DateTimeHelper.canMoveToPreviousView( - widget.view, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.minDate, - widget.calendar.maxDate, - _currentViewVisibleDates, - widget.calendar.timeSlotViewSettings.nonWorkingDays)) { + widget.view, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.minDate, + widget.calendar.maxDate, + _currentViewVisibleDates, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position in @@ -5440,7 +6200,9 @@ class _CustomCalendarScrollViewState extends State _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updatePreviousView()); /// updates the current view visible dates when fling the view in @@ -5511,14 +6273,16 @@ class _CustomCalendarScrollViewState extends State if (view.visibleDates == _currentViewVisibleDates) { widget.getCalendarState(_updateCalendarStateDetails); if (!CalendarViewHelper.isCollectionEqual( - viewKey.currentState!._monthView.visibleAppointmentNotifier.value, - _updateCalendarStateDetails.visibleAppointments)) { + viewKey.currentState!._monthView.visibleAppointmentNotifier.value, + _updateCalendarStateDetails.visibleAppointments, + )) { viewKey.currentState!._monthView.visibleAppointmentNotifier.value = _updateCalendarStateDetails.visibleAppointments; } } else { - if (!CalendarViewHelper.isEmptyList(viewKey - .currentState!._monthView.visibleAppointmentNotifier.value)) { + if (!CalendarViewHelper.isEmptyList( + viewKey.currentState!._monthView.visibleAppointmentNotifier.value, + )) { viewKey.currentState!._monthView.visibleAppointmentNotifier.value = null; } @@ -5529,14 +6293,16 @@ class _CustomCalendarScrollViewState extends State if (view.visibleDates == _currentViewVisibleDates) { widget.getCalendarState(_updateCalendarStateDetails); if (!CalendarViewHelper.isCollectionEqual( - appointmentLayout.visibleAppointments.value, - _updateCalendarStateDetails.visibleAppointments)) { + appointmentLayout.visibleAppointments.value, + _updateCalendarStateDetails.visibleAppointments, + )) { appointmentLayout.visibleAppointments.value = _updateCalendarStateDetails.visibleAppointments; } } else { if (!CalendarViewHelper.isEmptyList( - appointmentLayout.visibleAppointments.value)) { + appointmentLayout.visibleAppointments.value, + )) { appointmentLayout.visibleAppointments.value = null; } } @@ -5548,34 +6314,34 @@ class _CustomCalendarScrollViewState extends State @immutable class _CalendarView extends StatefulWidget { const _CalendarView( - this.calendar, - this.view, - this.visibleDates, - this.width, - this.height, - this.agendaSelectedDate, - this.locale, - this.calendarTheme, - this.themeData, - this.regions, - this.blackoutDates, - this.focusNode, - this.removePicker, - this.allowViewNavigation, - this.controller, - this.resourcePanelScrollController, - this.resourceCollection, - this.textScaleFactor, - this.isMobilePlatform, - this.minDate, - this.maxDate, - this.localizations, - this.timelineMonthWeekNumberNotifier, - this.dragDetails, - this.updateCalendarState, - this.getCalendarState, - {Key? key}) - : super(key: key); + this.calendar, + this.view, + this.visibleDates, + this.width, + this.height, + this.agendaSelectedDate, + this.locale, + this.calendarTheme, + this.themeData, + this.regions, + this.blackoutDates, + this.focusNode, + this.removePicker, + this.allowViewNavigation, + this.controller, + this.resourcePanelScrollController, + this.resourceCollection, + this.textScaleFactor, + this.isMobilePlatform, + this.minDate, + this.maxDate, + this.localizations, + this.timelineMonthWeekNumberNotifier, + this.dragDetails, + this.updateCalendarState, + this.getCalendarState, { + Key? key, + }) : super(key: key); final List visibleDates; final List? regions; @@ -5637,8 +6403,9 @@ class _CalendarViewState extends State<_CalendarView> ValueNotifier _allDaySelectionNotifier = ValueNotifier(null); late ValueNotifier _viewHeaderNotifier; - final ValueNotifier _calendarCellNotifier = - ValueNotifier(null), + final ValueNotifier _calendarCellNotifier = ValueNotifier( + null, + ), _allDayNotifier = ValueNotifier(null), _appointmentHoverNotifier = ValueNotifier(null); final ValueNotifier _selectionNotifier = ValueNotifier(false), @@ -5678,58 +6445,69 @@ class _CalendarViewState extends State<_CalendarView> @override void initState() { _resizingDetails = ValueNotifier<_ResizingPaintDetails>( - _ResizingPaintDetails(position: ValueNotifier(null))); + _ResizingPaintDetails(position: ValueNotifier(null)), + ); _viewHeaderNotifier = ValueNotifier(null) ..addListener(_timelineViewHoveringUpdate); if (!CalendarViewHelper.isTimelineView(widget.view) && widget.view != CalendarView.month) { _animationController = AnimationController( - duration: const Duration(milliseconds: 200), vsync: this); - _heightAnimation = - CurveTween(curve: Curves.easeIn).animate(_animationController!) - ..addListener(() { - setState(() { - /* Animates the all day panel height when + duration: const Duration(milliseconds: 200), + vsync: this, + ); + _heightAnimation = CurveTween( + curve: Curves.easeIn, + ).animate(_animationController!)..addListener(() { + setState(() { + /* Animates the all day panel height when expanding or collapsing */ - }); - }); + }); + }); _expanderAnimationController = AnimationController( - duration: const Duration(milliseconds: 100), vsync: this); - _allDayExpanderAnimation = CurveTween(curve: Curves.easeIn) - .animate(_expanderAnimationController!) - ..addListener(() { - setState(() { - /* Animates the all day panel height when + duration: const Duration(milliseconds: 100), + vsync: this, + ); + _allDayExpanderAnimation = CurveTween( + curve: Curves.easeIn, + ).animate(_expanderAnimationController!)..addListener(() { + setState(() { + /* Animates the all day panel height when expanding or collapsing */ - }); }); + }); } _timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); if (widget.view != CalendarView.month) { _horizontalLinesCount = CalendarViewHelper.getHorizontalLinesCount( - widget.calendar.timeSlotViewSettings, widget.view); + widget.calendar.timeSlotViewSettings, + widget.view, + ); _scrollController = ScrollController()..addListener(_scrollListener); if (CalendarViewHelper.isTimelineView(widget.view)) { - _timelineRulerController = ScrollController() - ..addListener(_timeRulerListener); + _timelineRulerController = + ScrollController()..addListener(_timeRulerListener); _timelineViewHeaderScrollController = ScrollController(); _timelineViewAnimationController = AnimationController( - duration: const Duration(milliseconds: 300), vsync: this); - _timelineViewAnimation = _timelineViewTween - .animate(_timelineViewAnimationController!) - ..addListener(_scrollAnimationListener); - _timelineViewVerticalScrollController = ScrollController() - ..addListener(_updateResourceScroll); - widget.resourcePanelScrollController - ?.addListener(_updateResourcePanelScroll); + duration: const Duration(milliseconds: 300), + vsync: this, + ); + _timelineViewAnimation = _timelineViewTween.animate( + _timelineViewAnimationController!, + )..addListener(_scrollAnimationListener); + _timelineViewVerticalScrollController = + ScrollController()..addListener(_updateResourceScroll); + widget.resourcePanelScrollController?.addListener( + _updateResourcePanelScroll, + ); } _scrollToPosition(); @@ -5737,7 +6515,8 @@ class _CalendarViewState extends State<_CalendarView> final DateTime today = DateTime.now(); _currentTimeNotifier = ValueNotifier( - (today.day * 24 * 60) + (today.hour * 60) + today.minute); + (today.day * 24 * 60) + (today.hour * 60) + today.minute, + ); _timer = _createTimer(); super.initState(); } @@ -5787,27 +6566,30 @@ class _CalendarViewState extends State<_CalendarView> /// day to week views to avoid the blank space at the bottom of the view. final bool isCurrentView = _updateCalendarStateDetails.currentViewVisibleDates == - widget.visibleDates; + widget.visibleDates; _updateAllDayHeight(isCurrentView); _timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); /// Clear the all day panel selection when the calendar view changed /// Eg., if select the all day panel and switch to month view and again /// select the same month cell and move to day view then the view show /// calendar cell selection and all day panel selection. if (oldWidget.view != widget.view) { - _allDaySelectionNotifier = - ValueNotifier(null); + _allDaySelectionNotifier = ValueNotifier( + null, + ); final DateTime today = DateTime.now(); _currentTimeNotifier = ValueNotifier( - (today.day * 24 * 60) + (today.hour * 60) + today.minute); + (today.day * 24 * 60) + (today.hour * 60) + today.minute, + ); _timer?.cancel(); _timer = null; } @@ -5830,13 +6612,17 @@ class _CalendarViewState extends State<_CalendarView> if (!CalendarViewHelper.isTimelineView(oldWidget.view) && _updateCalendarStateDetails.selectedDate != null && CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view) && + widget.calendar.dataSource, + widget.view, + ) && _selectedResourceIndex == -1) { _selectedResourceIndex = 0; } if (!CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { _selectedResourceIndex = -1; } @@ -5876,8 +6662,9 @@ class _CalendarViewState extends State<_CalendarView> } if (widget.resourcePanelScrollController != null) { - widget.resourcePanelScrollController! - .removeListener(_updateResourcePanelScroll); + widget.resourcePanelScrollController!.removeListener( + _updateResourcePanelScroll, + ); } if (CalendarViewHelper.isTimelineView(widget.view) && @@ -5921,25 +6708,28 @@ class _CalendarViewState extends State<_CalendarView> widget.view != CalendarView.month && widget.view != CalendarView.timelineMonth ? Timer.periodic(const Duration(seconds: 1), (Timer t) { - final DateTime today = DateTime.now(); - final DateTime viewEndDate = - widget.visibleDates[widget.visibleDates.length - 1]; - - /// Check the today date is in between visible date range and - /// today date hour and minute is 0(12 AM) because in day view - /// current time as Feb 16, 23.59 and changed to Feb 17 then view - /// will update both Feb 16 and 17 views. - if (!isDateWithInDateRange( - widget.visibleDates[0], viewEndDate, today) && - !(today.hour == 0 && - today.minute == 0 && - isSameDate(addDays(today, -1), viewEndDate))) { - return; - } + final DateTime today = DateTime.now(); + final DateTime viewEndDate = + widget.visibleDates[widget.visibleDates.length - 1]; + + /// Check the today date is in between visible date range and + /// today date hour and minute is 0(12 AM) because in day view + /// current time as Feb 16, 23.59 and changed to Feb 17 then view + /// will update both Feb 16 and 17 views. + if (!isDateWithInDateRange( + widget.visibleDates[0], + viewEndDate, + today, + ) && + !(today.hour == 0 && + today.minute == 0 && + isSameDate(addDays(today, -1), viewEndDate))) { + return; + } - _currentTimeNotifier.value = - (today.day * 24 * 60) + (today.hour * 60) + today.minute; - }) + _currentTimeNotifier.value = + (today.day * 24 * 60) + (today.hour * 60) + today.minute; + }) : null; } @@ -5953,7 +6743,9 @@ class _CalendarViewState extends State<_CalendarView> if (widget.resourcePanelScrollController == null || !CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { return; } @@ -5961,8 +6753,9 @@ class _CalendarViewState extends State<_CalendarView> _timelineViewVerticalScrollController!.hasClients && widget.resourcePanelScrollController!.offset != _timelineViewVerticalScrollController!.offset) { - _timelineViewVerticalScrollController! - .jumpTo(widget.resourcePanelScrollController!.offset); + _timelineViewVerticalScrollController!.jumpTo( + widget.resourcePanelScrollController!.offset, + ); } } @@ -5976,14 +6769,17 @@ class _CalendarViewState extends State<_CalendarView> if (widget.resourcePanelScrollController == null || !CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { return; } if (widget.resourcePanelScrollController!.offset != _timelineViewVerticalScrollController!.offset) { - widget.resourcePanelScrollController! - .jumpTo(_timelineViewVerticalScrollController!.offset); + widget.resourcePanelScrollController!.jumpTo( + _timelineViewVerticalScrollController!.offset, + ); } } @@ -5993,54 +6789,61 @@ class _CalendarViewState extends State<_CalendarView> _mouseCursor == SystemMouseCursors.resizeDown ? SystemMouseCursors.resizeUpDown : _mouseCursor == SystemMouseCursors.resizeRight || - _mouseCursor == SystemMouseCursors.resizeLeft - ? SystemMouseCursors.resizeLeftRight - : _mouseCursor; + _mouseCursor == SystemMouseCursors.resizeLeft + ? SystemMouseCursors.resizeLeftRight + : _mouseCursor; return MouseRegion( cursor: currentCursor, onEnter: _pointerEnterEvent, onExit: _pointerExitEvent, onHover: _pointerHoverEvent, - child: Stack(children: [ - GestureDetector( - onTapUp: _handleOnTapForMonth, - child: SizedBox( + child: Stack( + children: [ + GestureDetector( + onTapUp: _handleOnTapForMonth, + child: SizedBox( width: widget.width, height: widget.height, - child: _addMonthView(_isRTL, widget.locale)), - ), - _getResizeShadowView() - ]), + child: _addMonthView(_isRTL, widget.locale), + ), + ), + _getResizeShadowView(), + ], + ), ); } Widget _getDayView() { final bool isCurrentView = _updateCalendarStateDetails.currentViewVisibleDates == - widget.visibleDates; + widget.visibleDates; // Check and update the time interval height while the all day panel // appointments updated(all day height is default value) for current view. if (isCurrentView && _updateCalendarStateDetails.allDayPanelHeight != 0) { final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); // Default all day height is 0 on week and work week view // Default all day height is view header height on day view. final double defaultAllDayHeight = isDayView ? viewHeaderHeight : 0; if (_allDayHeight == defaultAllDayHeight) { _timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); } } @@ -6051,9 +6854,9 @@ class _CalendarViewState extends State<_CalendarView> _mouseCursor == SystemMouseCursors.resizeDown ? SystemMouseCursors.resizeUpDown : _mouseCursor == SystemMouseCursors.resizeRight || - _mouseCursor == SystemMouseCursors.resizeLeft - ? SystemMouseCursors.resizeLeftRight - : _mouseCursor; + _mouseCursor == SystemMouseCursors.resizeLeft + ? SystemMouseCursors.resizeLeftRight + : _mouseCursor; return MouseRegion( cursor: currentCursor, @@ -6065,16 +6868,18 @@ class _CalendarViewState extends State<_CalendarView> GestureDetector( onTapUp: _handleOnTapForDay, child: SizedBox( - height: widget.height, - width: widget.width, - child: _addDayView( - widget.width, - _timeIntervalHeight * _horizontalLinesCount!, - _isRTL, - widget.locale, - isCurrentView)), + height: widget.height, + width: widget.width, + child: _addDayView( + widget.width, + _timeIntervalHeight * _horizontalLinesCount!, + _isRTL, + widget.locale, + isCurrentView, + ), + ), ), - _getResizeShadowView() + _getResizeShadowView(), ], ), ); @@ -6091,21 +6896,26 @@ class _CalendarViewState extends State<_CalendarView> _allDayHeight = 0; final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); if (isDayView) { final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); if (isCurrentView) { - _allDayHeight = _kAllDayLayoutHeight > viewHeaderHeight && - _updateCalendarStateDetails.allDayPanelHeight > viewHeaderHeight - ? _updateCalendarStateDetails.allDayPanelHeight > - _kAllDayLayoutHeight - ? _kAllDayLayoutHeight - : _updateCalendarStateDetails.allDayPanelHeight - : viewHeaderHeight; + _allDayHeight = + _kAllDayLayoutHeight > viewHeaderHeight && + _updateCalendarStateDetails.allDayPanelHeight > + viewHeaderHeight + ? _updateCalendarStateDetails.allDayPanelHeight > + _kAllDayLayoutHeight + ? _kAllDayLayoutHeight + : _updateCalendarStateDetails.allDayPanelHeight + : viewHeaderHeight; if (_allDayHeight < _updateCalendarStateDetails.allDayPanelHeight) { _allDayHeight += kAllDayAppointmentHeight; } @@ -6127,29 +6937,33 @@ class _CalendarViewState extends State<_CalendarView> _mouseCursor == SystemMouseCursors.resizeDown ? SystemMouseCursors.resizeUpDown : _mouseCursor == SystemMouseCursors.resizeRight || - _mouseCursor == SystemMouseCursors.resizeLeft - ? SystemMouseCursors.resizeLeftRight - : _mouseCursor; + _mouseCursor == SystemMouseCursors.resizeLeft + ? SystemMouseCursors.resizeLeftRight + : _mouseCursor; return MouseRegion( - cursor: currentCursor, - onEnter: _pointerEnterEvent, - onHover: _pointerHoverEvent, - onExit: _pointerExitEvent, - child: Stack(children: [ + cursor: currentCursor, + onEnter: _pointerEnterEvent, + onHover: _pointerHoverEvent, + onExit: _pointerExitEvent, + child: Stack( + children: [ GestureDetector( onTapUp: _handleOnTapForTimeline, child: SizedBox( width: widget.width, height: widget.height, child: _addTimelineView( - _timeIntervalHeight * - (_horizontalLinesCount! * widget.visibleDates.length), - widget.height, - widget.locale), + _timeIntervalHeight * + (_horizontalLinesCount! * widget.visibleDates.length), + widget.height, + widget.locale, + ), ), ), - _getResizeShadowView() - ])); + _getResizeShadowView(), + ], + ), + ); } void _timelineViewHoveringUpdate() { @@ -6173,7 +6987,8 @@ class _CalendarViewState extends State<_CalendarView> widget.getCalendarState(_updateCalendarStateDetails); final double scrollPosition = _getScrollPositionForCurrentDate( - _updateCalendarStateDetails.currentDate!); + _updateCalendarStateDetails.currentDate!, + ); if (scrollPosition == -1 || (_scrollController != null && _scrollController!.position.pixels == scrollPosition)) { @@ -6181,24 +6996,31 @@ class _CalendarViewState extends State<_CalendarView> } if (_scrollController != null) { _scrollController!.jumpTo( - _scrollController!.position.maxScrollExtent > scrollPosition - ? scrollPosition - : _scrollController!.position.maxScrollExtent); + _scrollController!.position.maxScrollExtent > scrollPosition + ? scrollPosition + : _scrollController!.position.maxScrollExtent, + ); } }); } double _getScrollPositionForCurrentDate(DateTime date) { final int visibleDatesCount = widget.visibleDates.length; - if (!isDateWithInDateRange(widget.visibleDates[0], - widget.visibleDates[visibleDatesCount - 1], date)) { + if (!isDateWithInDateRange( + widget.visibleDates[0], + widget.visibleDates[visibleDatesCount - 1], + date, + )) { return -1; } double timeToPosition = 0; if (!CalendarViewHelper.isTimelineView(widget.view)) { timeToPosition = AppointmentHelper.timeToPosition( - widget.calendar, date, _timeIntervalHeight); + widget.calendar, + date, + _timeIntervalHeight, + ); } else { for (int i = 0; i < visibleDatesCount; i++) { if (!isSameDate(date, widget.visibleDates[i])) { @@ -6208,9 +7030,13 @@ class _CalendarViewState extends State<_CalendarView> if (widget.view == CalendarView.timelineMonth) { timeToPosition = _timeIntervalHeight * i; } else { - timeToPosition = (_getSingleViewWidthForTimeLineView(this) * i) + + timeToPosition = + (_getSingleViewWidthForTimeLineView(this) * i) + AppointmentHelper.timeToPosition( - widget.calendar, date, _timeIntervalHeight); + widget.calendar, + date, + _timeIntervalHeight, + ); } break; @@ -6240,8 +7066,9 @@ class _CalendarViewState extends State<_CalendarView> final double singleViewWidth = _getSingleViewWidthForTimeLineView(this); /// Calculate the scrolled position date. - scrolledDate = widget - .visibleDates[_scrollController!.position.pixels ~/ singleViewWidth]; + scrolledDate = + widget.visibleDates[_scrollController!.position.pixels ~/ + singleViewWidth]; /// Calculate the scrolled hour position without visible date position. scrolledPosition = _scrollController!.position.pixels % singleViewWidth; @@ -6254,15 +7081,22 @@ class _CalendarViewState extends State<_CalendarView> final double columnIndex = scrolledPosition / _timeIntervalHeight; /// Calculate the time based on calculated horizontal position. - final double time = ((CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings) / + final double time = + ((CalendarViewHelper.getTimeInterval( + widget.calendar.timeSlotViewSettings, + ) / 60) * columnIndex) + widget.calendar.timeSlotViewSettings.startHour; final int hour = time.toInt(); final int minute = ((time - hour) * 60).round(); scrolledDate = DateTime( - scrolledDate.year, scrolledDate.month, scrolledDate.day, hour, minute); + scrolledDate.year, + scrolledDate.month, + scrolledDate.day, + hour, + minute, + ); /// Update the scrolled position after the widget generated. SchedulerBinding.instance.addPostFrameCallback((_) { @@ -6274,17 +7108,21 @@ class _CalendarViewState extends State<_CalendarView> double _getPositionFromDate(DateTime date) { final int visibleDatesCount = widget.visibleDates.length; _timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - visibleDatesCount, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + visibleDatesCount, + widget.isMobilePlatform, + ); double timeToPosition = 0; final bool isTimelineView = CalendarViewHelper.isTimelineView(widget.view); if (!isTimelineView) { timeToPosition = AppointmentHelper.timeToPosition( - widget.calendar, date, _timeIntervalHeight); + widget.calendar, + date, + _timeIntervalHeight, + ); } else { for (int i = 0; i < visibleDatesCount; i++) { if (!isSameDate(date, widget.visibleDates[i])) { @@ -6294,9 +7132,13 @@ class _CalendarViewState extends State<_CalendarView> if (widget.view == CalendarView.timelineMonth) { timeToPosition = _timeIntervalHeight * i; } else { - timeToPosition = (_getSingleViewWidthForTimeLineView(this) * i) + + timeToPosition = + (_getSingleViewWidthForTimeLineView(this) * i) + AppointmentHelper.timeToPosition( - widget.calendar, date, _timeIntervalHeight); + widget.calendar, + date, + _timeIntervalHeight, + ); } break; @@ -6305,21 +7147,28 @@ class _CalendarViewState extends State<_CalendarView> double maxScrollPosition = 0; if (!isTimelineView) { - final double scrollViewHeight = widget.height - + final double scrollViewHeight = + widget.height - _allDayHeight - CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); final double scrollViewContentHeight = CalendarViewHelper.getHorizontalLinesCount( - widget.calendar.timeSlotViewSettings, widget.view) * - _timeIntervalHeight; + widget.calendar.timeSlotViewSettings, + widget.view, + ) * + _timeIntervalHeight; maxScrollPosition = scrollViewContentHeight - scrollViewHeight; } else { final double scrollViewContentWidth = CalendarViewHelper.getHorizontalLinesCount( - widget.calendar.timeSlotViewSettings, widget.view) * - _timeIntervalHeight * - visibleDatesCount; + widget.calendar.timeSlotViewSettings, + widget.view, + ) * + _timeIntervalHeight * + visibleDatesCount; maxScrollPosition = scrollViewContentWidth - widget.width; } @@ -6368,9 +7217,14 @@ class _CalendarViewState extends State<_CalendarView> if (widget.view == CalendarView.timelineMonth && widget.calendar.showWeekNumber) { final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); - final DateTime? date = - _getDateFromPosition(_scrollController!.offset, 0, timeLabelWidth); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); + final DateTime? date = _getDateFromPosition( + _scrollController!.offset, + 0, + timeLabelWidth, + ); if (date != null) { widget.timelineMonthWeekNumberNotifier.value = date; } @@ -6382,32 +7236,37 @@ class _CalendarViewState extends State<_CalendarView> void _updateTimeSlotView(_CalendarView oldWidget) { _animationController ??= AnimationController( - duration: const Duration(milliseconds: 200), vsync: this); - _heightAnimation ??= - CurveTween(curve: Curves.easeIn).animate(_animationController!) - ..addListener(() { - setState(() { - /*Animates the all day panel when it's expanding or + duration: const Duration(milliseconds: 200), + vsync: this, + ); + _heightAnimation ??= CurveTween( + curve: Curves.easeIn, + ).animate(_animationController!)..addListener(() { + setState(() { + /*Animates the all day panel when it's expanding or collapsing*/ - }); - }); + }); + }); _expanderAnimationController ??= AnimationController( - duration: const Duration(milliseconds: 100), vsync: this); - _allDayExpanderAnimation ??= - CurveTween(curve: Curves.easeIn).animate(_expanderAnimationController!) - ..addListener(() { - setState(() { - /*Animates the all day panel when it's expanding or + duration: const Duration(milliseconds: 100), + vsync: this, + ); + _allDayExpanderAnimation ??= CurveTween( + curve: Curves.easeIn, + ).animate(_expanderAnimationController!)..addListener(() { + setState(() { + /*Animates the all day panel when it's expanding or collapsing*/ - }); - }); + }); + }); if (!CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView) && + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ) && _allDayHeight == 0) { if (_animationController!.status == AnimationStatus.completed) { _animationController!.reset(); @@ -6423,38 +7282,48 @@ class _CalendarViewState extends State<_CalendarView> widget.calendar.timeSlotViewSettings.endHour != oldWidget.calendar.timeSlotViewSettings.endHour || CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings) != + widget.calendar.timeSlotViewSettings, + ) != CalendarViewHelper.getTimeInterval( - oldWidget.calendar.timeSlotViewSettings) || + oldWidget.calendar.timeSlotViewSettings, + ) || oldWidget.view == CalendarView.month || oldWidget.view == CalendarView.timelineMonth || oldWidget.view != CalendarView.timelineMonth && widget.view == CalendarView.timelineMonth) { _horizontalLinesCount = CalendarViewHelper.getHorizontalLinesCount( - widget.calendar.timeSlotViewSettings, widget.view); + widget.calendar.timeSlotViewSettings, + widget.view, + ); } else { - _horizontalLinesCount = _horizontalLinesCount ?? + _horizontalLinesCount = + _horizontalLinesCount ?? CalendarViewHelper.getHorizontalLinesCount( - widget.calendar.timeSlotViewSettings, widget.view); + widget.calendar.timeSlotViewSettings, + widget.view, + ); } } void _updateTimelineViews(_CalendarView oldWidget) { - _timelineRulerController ??= ScrollController() - ..addListener(_timeRulerListener); + _timelineRulerController ??= + ScrollController()..addListener(_timeRulerListener); _timelineViewAnimationController ??= AnimationController( - duration: const Duration(milliseconds: 300), vsync: this); + duration: const Duration(milliseconds: 300), + vsync: this, + ); - _timelineViewAnimation ??= _timelineViewTween - .animate(_timelineViewAnimationController!) - ..addListener(_scrollAnimationListener); + _timelineViewAnimation ??= _timelineViewTween.animate( + _timelineViewAnimationController!, + )..addListener(_scrollAnimationListener); _timelineViewHeaderScrollController ??= ScrollController(); _timelineViewVerticalScrollController = ScrollController(); _timelineViewVerticalScrollController!.addListener(_updateResourceScroll); - widget.resourcePanelScrollController - ?.addListener(_updateResourcePanelScroll); + widget.resourcePanelScrollController?.addListener( + _updateResourcePanelScroll, + ); } void _getPainterProperties(UpdateCalendarStateDetails details) { @@ -6469,12 +7338,15 @@ class _CalendarViewState extends State<_CalendarView> } Widget _addAllDayAppointmentPanel( - SfCalendarThemeData calendarTheme, bool isCurrentView) { + SfCalendarThemeData calendarTheme, + bool isCurrentView, + ) { final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); final Color borderColor = widget.calendar.cellBorderColor ?? calendarTheme.cellBorderColor!; final Widget shadowView = Divider( @@ -6484,9 +7356,13 @@ class _CalendarViewState extends State<_CalendarView> ); final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); double topPosition = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); if (isDayView) { topPosition = _allDayHeight; } @@ -6496,7 +7372,12 @@ class _CalendarViewState extends State<_CalendarView> widget.visibleDates != _updateCalendarStateDetails.currentViewVisibleDates)) { return Positioned( - left: 0, right: 0, top: topPosition, height: 1, child: shadowView); + left: 0, + right: 0, + top: topPosition, + height: 1, + child: shadowView, + ); } if (isDayView) { @@ -6505,9 +7386,10 @@ class _CalendarViewState extends State<_CalendarView> topPosition = 0; } - double panelHeight = isCurrentView - ? _updateCalendarStateDetails.allDayPanelHeight - _allDayHeight - : 0; + double panelHeight = + isCurrentView + ? _updateCalendarStateDetails.allDayPanelHeight - _allDayHeight + : 0; if (panelHeight < 0) { panelHeight = 0; } @@ -6517,7 +7399,8 @@ class _CalendarViewState extends State<_CalendarView> if (_allDaySelectionNotifier.value != null && _allDaySelectionNotifier.value!.appointmentView != null && (!_updateCalendarStateDetails.visibleAppointments.contains( - _allDaySelectionNotifier.value!.appointmentView!.appointment))) { + _allDaySelectionNotifier.value!.appointmentView!.appointment, + ))) { _allDaySelectionNotifier.value = null; } @@ -6539,58 +7422,68 @@ class _CalendarViewState extends State<_CalendarView> physics: const NeverScrollableScrollPhysics(), padding: EdgeInsets.zero, children: [ - _getAllDayLayout(timeLabelWidth, panelHeight, - allDayExpanderHeight, isCurrentView) + _getAllDayLayout( + timeLabelWidth, + panelHeight, + allDayExpanderHeight, + isCurrentView, + ), ], ), ), Positioned( - left: 0, - top: allDayExpanderHeight - 1, - right: 0, - height: 1, - child: shadowView), + left: 0, + top: allDayExpanderHeight - 1, + right: 0, + height: 1, + child: shadowView, + ), ], ), ); } - Widget _getAllDayLayout(double timeLabelWidth, double panelHeight, - double allDayExpanderHeight, bool isCurrentView) { + Widget _getAllDayLayout( + double timeLabelWidth, + double panelHeight, + double allDayExpanderHeight, + bool isCurrentView, + ) { final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); final Widget allDayLayout = AllDayAppointmentLayout( - widget.calendar, - widget.view, - widget.visibleDates, - widget.visibleDates == - _updateCalendarStateDetails.currentViewVisibleDates - ? _updateCalendarStateDetails.visibleAppointments - : null, - timeLabelWidth, - allDayExpanderHeight, - panelHeight > 0 && (_heightAnimation!.value == 1 || isDayView), - _allDayExpanderAnimation!.value != 0.0 && - _allDayExpanderAnimation!.value != 1, - _isRTL, - widget.calendarTheme, - widget.themeData, - _allDaySelectionNotifier, - _allDayNotifier, - widget.textScaleFactor, - widget.isMobilePlatform, - widget.width, - (isDayView && - _updateCalendarStateDetails.allDayPanelHeight < - _allDayHeight) || - !isCurrentView - ? _allDayHeight - : _updateCalendarStateDetails.allDayPanelHeight, - widget.localizations, - _getPainterProperties); + widget.calendar, + widget.view, + widget.visibleDates, + widget.visibleDates == _updateCalendarStateDetails.currentViewVisibleDates + ? _updateCalendarStateDetails.visibleAppointments + : null, + timeLabelWidth, + allDayExpanderHeight, + panelHeight > 0 && (_heightAnimation!.value == 1 || isDayView), + _allDayExpanderAnimation!.value != 0.0 && + _allDayExpanderAnimation!.value != 1, + _isRTL, + widget.calendarTheme, + widget.themeData, + _allDaySelectionNotifier, + _allDayNotifier, + widget.textScaleFactor, + widget.isMobilePlatform, + widget.width, + (isDayView && + _updateCalendarStateDetails.allDayPanelHeight < + _allDayHeight) || + !isCurrentView + ? _allDayHeight + : _updateCalendarStateDetails.allDayPanelHeight, + widget.localizations, + _getPainterProperties, + ); if ((_mouseCursor == SystemMouseCursors.basic || _mouseCursor == SystemMouseCursors.move) || @@ -6606,8 +7499,11 @@ class _CalendarViewState extends State<_CalendarView> } } - Widget _addAppointmentPainter(double width, double height, - [double? resourceItemHeight]) { + Widget _addAppointmentPainter( + double width, + double height, [ + double? resourceItemHeight, + ]) { final List? visibleAppointments = widget.visibleDates == _updateCalendarStateDetails.currentViewVisibleDates @@ -6641,31 +7537,39 @@ class _CalendarViewState extends State<_CalendarView> final double xPosition = details.localPosition.dx; double yPosition = details.localPosition.dy; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); AppointmentView? appointmentView; const double padding = 10; final bool isForwardResize = _mouseCursor == SystemMouseCursors.resizeDown; final bool isBackwardResize = _mouseCursor == SystemMouseCursors.resizeUp; final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); if (!CalendarViewHelper.isTimelineView(widget.view) && widget.view != CalendarView.month) { if (xPosition < timeLabelWidth) { return; } - final double allDayPanelHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; + final double allDayPanelHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; - yPosition = yPosition - + yPosition = + yPosition - viewHeaderHeight - allDayPanelHeight + _scrollController!.offset; @@ -6675,14 +7579,17 @@ class _CalendarViewState extends State<_CalendarView> } else if (isForwardResize) { yPosition -= padding; } - appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); + appointmentView = _appointmentLayout.getAppointmentViewOnPoint( + xPosition, + yPosition, + ); if (appointmentView == null) { return; } _resizingDetails.value.isAllDayPanel = false; - yPosition = details.localPosition.dy - + yPosition = + details.localPosition.dy - viewHeaderHeight - allDayPanelHeight + _scrollController!.offset; @@ -6695,27 +7602,47 @@ class _CalendarViewState extends State<_CalendarView> return; } - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - appointmentView, allDayPanelHeight, viewHeaderHeight); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + appointmentView, + allDayPanelHeight, + viewHeaderHeight, + ); _resizingDetails.value.position.value = Offset( - appointmentView.appointmentRect!.left, details.localPosition.dy); + appointmentView.appointmentRect!.left, + details.localPosition.dy, + ); } - _resizingDetails.value.resizingTime = isBackwardResize - ? _resizingDetails.value.appointmentView!.appointment!.actualStartTime - : _resizingDetails.value.appointmentView!.appointment!.actualEndTime; + _resizingDetails.value.resizingTime = + isBackwardResize + ? _resizingDetails + .value + .appointmentView! + .appointment! + .actualStartTime + : _resizingDetails + .value + .appointmentView! + .appointment! + .actualEndTime; _resizingDetails.value.scrollPosition = null; if (widget.calendar.appointmentBuilder == null) { _resizingDetails.value.appointmentColor = appointmentView!.appointment!.color; } if (CalendarViewHelper.shouldRaiseAppointmentResizeStartCallback( - widget.calendar.onAppointmentResizeStart)) { + widget.calendar.onAppointmentResizeStart, + )) { CalendarViewHelper.raiseAppointmentResizeStartCallback( + widget.calendar, + _getCalendarAppointmentToObject( + appointmentView!.appointment, widget.calendar, - _getCalendarAppointmentToObject( - appointmentView!.appointment, widget.calendar), - null); + ), + null, + ); } } @@ -6725,43 +7652,61 @@ class _CalendarViewState extends State<_CalendarView> } final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); double yPosition = details.localPosition.dy; final bool isForwardResize = _mouseCursor == SystemMouseCursors.resizeDown; final bool isBackwardResize = _mouseCursor == SystemMouseCursors.resizeUp; - final double allDayPanelHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; + final double allDayPanelHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; if (!CalendarViewHelper.isTimelineView(widget.view) && widget.view != CalendarView.month) { _updateMaximumResizingPosition( - isForwardResize, - isBackwardResize, - _resizingDetails.value.appointmentView!, - allDayPanelHeight, - viewHeaderHeight); + isForwardResize, + isBackwardResize, + _resizingDetails.value.appointmentView!, + allDayPanelHeight, + viewHeaderHeight, + ); if ((isForwardResize && yPosition < _maximumResizingPosition!) || (isBackwardResize && yPosition > _maximumResizingPosition!)) { yPosition = _maximumResizingPosition!; } - _updateAutoScrollDay(details, viewHeaderHeight, allDayPanelHeight, - isForwardResize, isBackwardResize, yPosition); + _updateAutoScrollDay( + details, + viewHeaderHeight, + allDayPanelHeight, + isForwardResize, + isBackwardResize, + yPosition, + ); } _resizingDetails.value.scrollPosition = null; _resizingDetails.value.position.value = Offset( - _resizingDetails.value.appointmentView!.appointmentRect!.left, - yPosition); - _updateAppointmentResizingUpdateCallback(isForwardResize, isBackwardResize, - yPosition, viewHeaderHeight, allDayPanelHeight); + _resizingDetails.value.appointmentView!.appointmentRect!.left, + yPosition, + ); + _updateAppointmentResizingUpdateCallback( + isForwardResize, + isBackwardResize, + yPosition, + viewHeaderHeight, + allDayPanelHeight, + ); } void _onVerticalEnd(DragEndDetails details) { @@ -6776,24 +7721,30 @@ class _CalendarViewState extends State<_CalendarView> } final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); - final double allDayPanelHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; + final double allDayPanelHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; final double currentYPosition = _resizingDetails.value.position.value!.dy > widget.height - 1 ? widget.height - 1 : _resizingDetails.value.position.value!.dy; - double yPosition = currentYPosition - + double yPosition = + currentYPosition - viewHeaderHeight - allDayPanelHeight + _scrollController!.offset; @@ -6801,34 +7752,41 @@ class _CalendarViewState extends State<_CalendarView> final CalendarAppointment appointment = _resizingDetails.value.appointmentView!.appointment!; final double timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); final double overAllHeight = _timeIntervalHeight * _horizontalLinesCount!; if (overAllHeight < widget.height && yPosition > overAllHeight) { yPosition = overAllHeight; } - final DateTime resizingTime = _timeFromPosition( - appointment.actualStartTime, - widget.calendar.timeSlotViewSettings, - yPosition, - null, - timeIntervalHeight, - false)!; + final DateTime resizingTime = + _timeFromPosition( + appointment.actualStartTime, + widget.calendar.timeSlotViewSettings, + yPosition, + null, + timeIntervalHeight, + false, + )!; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); DateTime updatedStartTime = appointment.actualStartTime, updatedEndTime = appointment.actualEndTime; if (AppointmentHelper.canAddSpanIcon( - widget.visibleDates, appointment, widget.view)) { + widget.visibleDates, + appointment, + widget.view, + )) { updatedStartTime = appointment.exactStartTime; updatedEndTime = appointment.exactEndTime; } @@ -6842,30 +7800,39 @@ class _CalendarViewState extends State<_CalendarView> final DateTime callbackStartDate = updatedStartTime; final DateTime callbackEndDate = updatedEndTime; updatedStartTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - updatedStartTime, widget.calendar.timeZone, appointment.startTimeZone); + updatedStartTime, + widget.calendar.timeZone, + appointment.startTimeZone, + ); updatedEndTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - updatedEndTime, widget.calendar.timeZone, appointment.endTimeZone); + updatedEndTime, + widget.calendar.timeZone, + appointment.endTimeZone, + ); if (CalendarViewHelper.isDraggingAppointmentHasDisabledCell( - widget.regions!, - widget.blackoutDates!, - updatedStartTime, - updatedEndTime, - false, - false, - widget.calendar.minDate, - widget.calendar.maxDate, - timeInterval, - -1, - widget.resourceCollection)) { + widget.regions!, + widget.blackoutDates!, + updatedStartTime, + updatedEndTime, + false, + false, + widget.calendar.minDate, + widget.calendar.maxDate, + timeInterval, + -1, + widget.resourceCollection, + )) { if (CalendarViewHelper.shouldRaiseAppointmentResizeEndCallback( - widget.calendar.onAppointmentResizeEnd)) { + widget.calendar.onAppointmentResizeEnd, + )) { CalendarViewHelper.raiseAppointmentResizeEndCallback( - widget.calendar, - appointment.data, - null, - appointment.exactStartTime, - appointment.exactEndTime); + widget.calendar, + appointment.data, + null, + appointment.exactStartTime, + appointment.exactEndTime, + ); } _resetResizingPainter(); @@ -6875,9 +7842,11 @@ class _CalendarViewState extends State<_CalendarView> CalendarAppointment? parentAppointment; if (appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty) { - for (int i = 0; - i < _updateCalendarStateDetails.appointments.length; - i++) { + for ( + int i = 0; + i < _updateCalendarStateDetails.appointments.length; + i++ + ) { final CalendarAppointment app = _updateCalendarStateDetails.appointments[i]; if (app.id == appointment.id) { @@ -6888,46 +7857,68 @@ class _CalendarViewState extends State<_CalendarView> widget.calendar.dataSource!.appointments!.remove(parentAppointment!.data); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [parentAppointment.data]); + CalendarDataSourceAction.remove, + [parentAppointment.data], + ); final DateTime exceptionDate = AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.exactStartTime, widget.calendar.timeZone, ''); + appointment.exactStartTime, + widget.calendar.timeZone, + '', + ); parentAppointment.recurrenceExceptionDates != null ? parentAppointment.recurrenceExceptionDates!.add(exceptionDate) : parentAppointment.recurrenceExceptionDates = [ - exceptionDate - ]; + exceptionDate, + ]; - final dynamic newParentAppointment = - _getCalendarAppointmentToObject(parentAppointment, widget.calendar); + final dynamic newParentAppointment = _getCalendarAppointmentToObject( + parentAppointment, + widget.calendar, + ); widget.calendar.dataSource!.appointments!.add(newParentAppointment); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.add, [newParentAppointment]); + CalendarDataSourceAction.add, + [newParentAppointment], + ); } else { widget.calendar.dataSource!.appointments!.remove(appointment.data); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [appointment.data]); + CalendarDataSourceAction.remove, + [appointment.data], + ); } appointment.startTime = updatedStartTime; appointment.endTime = updatedEndTime; - appointment.recurrenceId = parentAppointment != null - ? parentAppointment.id - : appointment.recurrenceId; + appointment.recurrenceId = + parentAppointment != null + ? parentAppointment.id + : appointment.recurrenceId; appointment.recurrenceRule = appointment.recurrenceId != null ? null : appointment.recurrenceRule; appointment.id = parentAppointment != null ? null : appointment.id; - final dynamic newAppointment = - _getCalendarAppointmentToObject(appointment, widget.calendar); + final dynamic newAppointment = _getCalendarAppointmentToObject( + appointment, + widget.calendar, + ); widget.calendar.dataSource!.appointments!.add(newAppointment); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.add, [newAppointment]); + CalendarDataSourceAction.add, + [newAppointment], + ); if (CalendarViewHelper.shouldRaiseAppointmentResizeEndCallback( - widget.calendar.onAppointmentResizeEnd)) { - CalendarViewHelper.raiseAppointmentResizeEndCallback(widget.calendar, - newAppointment, null, callbackStartDate, callbackEndDate); + widget.calendar.onAppointmentResizeEnd, + )) { + CalendarViewHelper.raiseAppointmentResizeEndCallback( + widget.calendar, + newAppointment, + null, + callbackStartDate, + callbackEndDate, + ); } _resetResizingPainter(); @@ -6935,19 +7926,25 @@ class _CalendarViewState extends State<_CalendarView> void _onHorizontalStart(DragStartDetails details) { final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); double xPosition = details.localPosition.dx; CalendarResource? resource; double yPosition = details.localPosition.dy; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final bool isTimelineView = CalendarViewHelper.isTimelineView(widget.view); AppointmentView? appointmentView; const double padding = 10; @@ -6966,9 +7963,10 @@ class _CalendarViewState extends State<_CalendarView> } appointmentView = _getAllDayAppointmentOnPoint( - _updateCalendarStateDetails.allDayAppointmentViewCollection, - xPosition, - yPosition); + _updateCalendarStateDetails.allDayAppointmentViewCollection, + xPosition, + yPosition, + ); if (appointmentView == null) { return; } @@ -6976,16 +7974,23 @@ class _CalendarViewState extends State<_CalendarView> xPosition = details.localPosition.dx; yPosition = appointmentView.appointmentRect!.top + viewHeaderHeight; _resizingDetails.value.isAllDayPanel = true; - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - appointmentView, null, viewHeaderHeight); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + appointmentView, + null, + viewHeaderHeight, + ); } else if (isTimelineView) { yPosition -= viewHeaderHeight + timeLabelWidth; xPosition = _scrollController!.offset + details.localPosition.dx; if (_isRTL) { - xPosition = _scrollController!.offset + + xPosition = + _scrollController!.offset + (_scrollController!.position.viewportDimension - details.localPosition.dx); - xPosition = (_scrollController!.position.viewportDimension + + xPosition = + (_scrollController!.position.viewportDimension + _scrollController!.position.maxScrollExtent) - xPosition; } @@ -6997,32 +8002,45 @@ class _CalendarViewState extends State<_CalendarView> } final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); if (isResourceEnabled) { yPosition += _timelineViewVerticalScrollController!.offset; } - appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); + appointmentView = _appointmentLayout.getAppointmentViewOnPoint( + xPosition, + yPosition, + ); _resizingDetails.value.isAllDayPanel = false; if (appointmentView == null) { return; } if (isResourceEnabled) { - resource = widget.calendar.dataSource!.resources![ - _getSelectedResourceIndex(appointmentView.appointmentRect!.top, - viewHeaderHeight, timeLabelWidth)]; + resource = + widget.calendar.dataSource!.resources![_getSelectedResourceIndex( + appointmentView.appointmentRect!.top, + viewHeaderHeight, + timeLabelWidth, + )]; } - yPosition = appointmentView.appointmentRect!.top + + yPosition = + appointmentView.appointmentRect!.top + viewHeaderHeight + timeLabelWidth; if (isResourceEnabled) { yPosition -= _timelineViewVerticalScrollController!.offset; } - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - appointmentView, null, viewHeaderHeight); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + appointmentView, + null, + viewHeaderHeight, + ); } else if (widget.view == CalendarView.month) { _resizingDetails.value.monthRowCount = 0; yPosition -= viewHeaderHeight; @@ -7033,8 +8051,10 @@ class _CalendarViewState extends State<_CalendarView> xPosition -= padding; } - appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); + appointmentView = _appointmentLayout.getAppointmentViewOnPoint( + xPosition, + yPosition, + ); _resizingDetails.value.isAllDayPanel = false; if (appointmentView == null) { return; @@ -7043,8 +8063,13 @@ class _CalendarViewState extends State<_CalendarView> xPosition = details.localPosition.dx; yPosition = appointmentView.appointmentRect!.top + viewHeaderHeight; - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - appointmentView, null, viewHeaderHeight); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + appointmentView, + null, + viewHeaderHeight, + ); } if (_mouseCursor != SystemMouseCursors.basic && @@ -7061,23 +8086,47 @@ class _CalendarViewState extends State<_CalendarView> appointmentView.appointment!.color; } if (isTimelineView && _isRTL) { - _resizingDetails.value.resizingTime = isForwardResize - ? _resizingDetails.value.appointmentView!.appointment!.actualStartTime - : _resizingDetails.value.appointmentView!.appointment!.actualEndTime; + _resizingDetails.value.resizingTime = + isForwardResize + ? _resizingDetails + .value + .appointmentView! + .appointment! + .actualStartTime + : _resizingDetails + .value + .appointmentView! + .appointment! + .actualEndTime; } else { - _resizingDetails.value.resizingTime = isBackwardResize - ? _resizingDetails.value.appointmentView!.appointment!.actualStartTime - : _resizingDetails.value.appointmentView!.appointment!.actualEndTime; + _resizingDetails.value.resizingTime = + isBackwardResize + ? _resizingDetails + .value + .appointmentView! + .appointment! + .actualStartTime + : _resizingDetails + .value + .appointmentView! + .appointment! + .actualEndTime; } - _resizingDetails.value.position.value = - Offset(details.localPosition.dx, yPosition); + _resizingDetails.value.position.value = Offset( + details.localPosition.dx, + yPosition, + ); if (CalendarViewHelper.shouldRaiseAppointmentResizeStartCallback( - widget.calendar.onAppointmentResizeStart)) { + widget.calendar.onAppointmentResizeStart, + )) { CalendarViewHelper.raiseAppointmentResizeStartCallback( + widget.calendar, + _getCalendarAppointmentToObject( + appointmentView.appointment, widget.calendar, - _getCalendarAppointmentToObject( - appointmentView.appointment, widget.calendar), - resource); + ), + resource, + ); } } @@ -7087,43 +8136,56 @@ class _CalendarViewState extends State<_CalendarView> } final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); final bool isForwardResize = _mouseCursor == SystemMouseCursors.resizeRight; final bool isBackwardResize = _mouseCursor == SystemMouseCursors.resizeLeft; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final bool isTimelineView = CalendarViewHelper.isTimelineView(widget.view); double xPosition = details.localPosition.dx; double yPosition = _resizingDetails.value.position.value!.dy; late DateTime resizingTime; final double timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); if (isTimelineView) { - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - _resizingDetails.value.appointmentView!, null, null); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + _resizingDetails.value.appointmentView!, + null, + null, + ); if ((isForwardResize && xPosition < _maximumResizingPosition!) || (isBackwardResize && xPosition > _maximumResizingPosition!)) { xPosition = _maximumResizingPosition!; } _updateAutoScrollTimeline( - details, - timeIntervalHeight, - isForwardResize, - isBackwardResize, - xPosition, - yPosition, - timeLabelWidth, - isResourceEnabled); + details, + timeIntervalHeight, + isForwardResize, + isBackwardResize, + xPosition, + yPosition, + timeLabelWidth, + isResourceEnabled, + ); } else if (widget.view == CalendarView.month) { final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); double resizingPosition = details.localPosition.dy - viewHeaderHeight; if (resizingPosition < 0) { resizingPosition = 0; @@ -7131,7 +8193,8 @@ class _CalendarViewState extends State<_CalendarView> resizingPosition = widget.height - viewHeaderHeight - 1; } - final double cellHeight = (widget.height - viewHeaderHeight) / + final double cellHeight = + (widget.height - viewHeaderHeight) / widget.calendar.monthViewSettings.numberOfWeeksInView; final int appointmentRowIndex = (_resizingDetails.value.appointmentView!.appointmentRect!.top / @@ -7140,9 +8203,10 @@ class _CalendarViewState extends State<_CalendarView> int resizingRowIndex = (resizingPosition / cellHeight).truncate(); final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if (!_isRTL) { if (xPosition < weekNumberPanelWidth) { xPosition = weekNumberPanelWidth; @@ -7164,11 +8228,13 @@ class _CalendarViewState extends State<_CalendarView> final DateTime currentMonthDate = widget.visibleDates[widget.visibleDates.length ~/ 2]; final int startIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, - AppointmentHelper.getMonthStartDate(currentMonthDate)); + widget.visibleDates, + AppointmentHelper.getMonthStartDate(currentMonthDate), + ); final int endIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, - AppointmentHelper.getMonthEndDate(currentMonthDate)); + widget.visibleDates, + AppointmentHelper.getMonthEndDate(currentMonthDate), + ); final int startRowCount = startIndex ~/ DateTime.daysPerWeek; final int startColumnCount = startIndex % DateTime.daysPerWeek; final int endRowCount = endIndex ~/ DateTime.daysPerWeek; @@ -7255,11 +8321,12 @@ class _CalendarViewState extends State<_CalendarView> resizingTime = _getDateFromPosition(xPosition, resizingPosition, timeLabelWidth)!; - final int rowDifference = isBackwardResize - ? _isRTL - ? (appointmentRowIndex - resizingRowIndex).abs() - : appointmentRowIndex - resizingRowIndex - : _isRTL + final int rowDifference = + isBackwardResize + ? _isRTL + ? (appointmentRowIndex - resizingRowIndex).abs() + : appointmentRowIndex - resizingRowIndex + : _isRTL ? appointmentRowIndex - resizingRowIndex : (appointmentRowIndex - resizingRowIndex).abs(); if (((!_isRTL && @@ -7311,7 +8378,7 @@ class _CalendarViewState extends State<_CalendarView> _resizingDetails.value.monthCellHeight = cellHeight; yPosition = _resizingDetails.value.appointmentView!.appointmentRect!.top + - viewHeaderHeight; + viewHeaderHeight; } } else { if ((isForwardResize && xPosition < _maximumResizingPosition!) || @@ -7341,32 +8408,43 @@ class _CalendarViewState extends State<_CalendarView> if (_resizingDetails.value.isAllDayPanel || widget.view == CalendarView.month) { - resizingTime = - DateTime(resizingTime.year, resizingTime.month, resizingTime.day); + resizingTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + ); } _resizingDetails.value.position.value = Offset(xPosition, yPosition); if (isTimelineView) { _updateAppointmentResizingUpdateCallback( - isForwardResize, isBackwardResize, yPosition, null, null, - xPosition: xPosition, - timeLabelWidth: timeLabelWidth, - isResourceEnabled: isResourceEnabled, - details: details); + isForwardResize, + isBackwardResize, + yPosition, + null, + null, + xPosition: xPosition, + timeLabelWidth: timeLabelWidth, + isResourceEnabled: isResourceEnabled, + details: details, + ); return; } if (CalendarViewHelper.shouldRaiseAppointmentResizeUpdateCallback( - widget.calendar.onAppointmentResizeUpdate)) { + widget.calendar.onAppointmentResizeUpdate, + )) { CalendarViewHelper.raiseAppointmentResizeUpdateCallback( + widget.calendar, + _getCalendarAppointmentToObject( + _resizingDetails.value.appointmentView!.appointment, widget.calendar, - _getCalendarAppointmentToObject( - _resizingDetails.value.appointmentView!.appointment, - widget.calendar), - null, - resizingTime, - _resizingDetails.value.position.value!); + ), + null, + resizingTime, + _resizingDetails.value.position.value!, + ); } } @@ -7382,14 +8460,18 @@ class _CalendarViewState extends State<_CalendarView> } final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); final bool isTimelineView = CalendarViewHelper.isTimelineView(widget.view); @@ -7397,20 +8479,25 @@ class _CalendarViewState extends State<_CalendarView> double yPosition = _resizingDetails.value.position.value!.dy; final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); final CalendarAppointment appointment = _resizingDetails.value.appointmentView!.appointment!; final double timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); if (!isTimelineView && widget.view != CalendarView.month) { if (_isRTL) { if (xPosition > widget.width - timeLabelWidth - 1) { @@ -7430,9 +8517,10 @@ class _CalendarViewState extends State<_CalendarView> } else if (widget.view == CalendarView.month) { final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); _resizingDetails.value.monthRowCount = 0; if (!_isRTL) { if (xPosition < weekNumberPanelWidth) { @@ -7451,7 +8539,8 @@ class _CalendarViewState extends State<_CalendarView> xPosition = widget.width - 1; } - final double overAllWidth = _timeIntervalHeight * + final double overAllWidth = + _timeIntervalHeight * (_horizontalLinesCount! * widget.visibleDates.length); if (overAllWidth < widget.width && xPosition > overAllWidth) { @@ -7464,52 +8553,76 @@ class _CalendarViewState extends State<_CalendarView> if (_resizingDetails.value.isAllDayPanel || widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth) { - resizingTime = - DateTime(resizingTime.year, resizingTime.month, resizingTime.day); + resizingTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + ); } else if (isTimelineView) { - final DateTime time = _timeFromPosition( - resizingTime, - widget.calendar.timeSlotViewSettings, - xPosition, - this, - timeIntervalHeight, - isTimelineView)!; - - resizingTime = DateTime(resizingTime.year, resizingTime.month, - resizingTime.day, time.hour, time.minute, time.second); + final DateTime time = + _timeFromPosition( + resizingTime, + widget.calendar.timeSlotViewSettings, + xPosition, + this, + timeIntervalHeight, + isTimelineView, + )!; + + resizingTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + time.hour, + time.minute, + time.second, + ); } CalendarResource? resource; int selectedResourceIndex = -1; if (isResourceEnabled) { selectedResourceIndex = _getSelectedResourceIndex( - _resizingDetails.value.appointmentView!.appointmentRect!.top, - viewHeaderHeight, - timeLabelWidth); + _resizingDetails.value.appointmentView!.appointmentRect!.top, + viewHeaderHeight, + timeLabelWidth, + ); resource = widget.calendar.dataSource!.resources![selectedResourceIndex]; } - final bool isMonthView = widget.view == CalendarView.timelineMonth || + final bool isMonthView = + widget.view == CalendarView.timelineMonth || widget.view == CalendarView.month; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); DateTime updatedStartTime = appointment.actualStartTime, updatedEndTime = appointment.actualEndTime; if ((_isRTL && _mouseCursor == SystemMouseCursors.resizeLeft) || (!_isRTL && _mouseCursor == SystemMouseCursors.resizeRight)) { if (isMonthView) { - updatedEndTime = DateTime(resizingTime.year, resizingTime.month, - resizingTime.day, updatedEndTime.hour, updatedEndTime.minute); + updatedEndTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + updatedEndTime.hour, + updatedEndTime.minute, + ); } else { updatedEndTime = resizingTime; } } else if ((_isRTL && _mouseCursor == SystemMouseCursors.resizeRight) || (!_isRTL && _mouseCursor == SystemMouseCursors.resizeLeft)) { if (isMonthView) { - updatedStartTime = DateTime(resizingTime.year, resizingTime.month, - resizingTime.day, updatedStartTime.hour, updatedStartTime.minute); + updatedStartTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + updatedStartTime.hour, + updatedStartTime.minute, + ); } else { updatedStartTime = resizingTime; } @@ -7518,29 +8631,38 @@ class _CalendarViewState extends State<_CalendarView> final DateTime callbackStartDate = updatedStartTime; final DateTime callbackEndDate = updatedEndTime; updatedStartTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - updatedStartTime, widget.calendar.timeZone, appointment.startTimeZone); + updatedStartTime, + widget.calendar.timeZone, + appointment.startTimeZone, + ); updatedEndTime = AppointmentHelper.convertTimeToAppointmentTimeZone( - updatedEndTime, widget.calendar.timeZone, appointment.endTimeZone); + updatedEndTime, + widget.calendar.timeZone, + appointment.endTimeZone, + ); if (CalendarViewHelper.isDraggingAppointmentHasDisabledCell( - widget.regions!, - widget.blackoutDates!, - updatedStartTime, - updatedEndTime, - isTimelineView, - isMonthView, - widget.calendar.minDate, - widget.calendar.maxDate, - timeInterval, - selectedResourceIndex, - widget.resourceCollection)) { + widget.regions!, + widget.blackoutDates!, + updatedStartTime, + updatedEndTime, + isTimelineView, + isMonthView, + widget.calendar.minDate, + widget.calendar.maxDate, + timeInterval, + selectedResourceIndex, + widget.resourceCollection, + )) { if (CalendarViewHelper.shouldRaiseAppointmentResizeEndCallback( - widget.calendar.onAppointmentResizeEnd)) { + widget.calendar.onAppointmentResizeEnd, + )) { CalendarViewHelper.raiseAppointmentResizeEndCallback( - widget.calendar, - appointment.data, - resource, - appointment.exactStartTime, - appointment.exactEndTime); + widget.calendar, + appointment.data, + resource, + appointment.exactStartTime, + appointment.exactEndTime, + ); } _resetResizingPainter(); @@ -7552,9 +8674,11 @@ class _CalendarViewState extends State<_CalendarView> if ((appointment.recurrenceRule != null && appointment.recurrenceRule!.isNotEmpty) || appointment.recurrenceId != null) { - for (int i = 0; - i < _updateCalendarStateDetails.appointments.length; - i++) { + for ( + int i = 0; + i < _updateCalendarStateDetails.appointments.length; + i++ + ) { final CalendarAppointment app = _updateCalendarStateDetails.appointments[i]; if (app.id == appointment.id || app.id == appointment.recurrenceId) { @@ -7565,49 +8689,61 @@ class _CalendarViewState extends State<_CalendarView> final List recurrenceDates = RecurrenceHelper.getRecurrenceDateTimeCollection( - parentAppointment!.recurrenceRule ?? '', + parentAppointment!.recurrenceRule ?? '', + parentAppointment.exactStartTime, + recurrenceDuration: AppointmentHelper.getDifference( parentAppointment.exactStartTime, - recurrenceDuration: AppointmentHelper.getDifference( - parentAppointment.exactStartTime, - parentAppointment.exactEndTime), - specificStartDate: widget.visibleDates[0], - specificEndDate: - widget.visibleDates[widget.visibleDates.length - 1]); - - for (int i = 0; - i < _updateCalendarStateDetails.appointments.length; - i++) { + parentAppointment.exactEndTime, + ), + specificStartDate: widget.visibleDates[0], + specificEndDate: + widget.visibleDates[widget.visibleDates.length - 1], + ); + + for ( + int i = 0; + i < _updateCalendarStateDetails.appointments.length; + i++ + ) { final CalendarAppointment calendarApp = _updateCalendarStateDetails.appointments[i]; if (calendarApp.recurrenceId != null && calendarApp.recurrenceId == parentAppointment.id) { recurrenceDates.add( - AppointmentHelper.convertTimeToAppointmentTimeZone( - calendarApp.startTime, - calendarApp.startTimeZone, - widget.calendar.timeZone)); + AppointmentHelper.convertTimeToAppointmentTimeZone( + calendarApp.startTime, + calendarApp.startTimeZone, + widget.calendar.timeZone, + ), + ); } } if (parentAppointment.recurrenceExceptionDates != null) { - for (int i = 0; - i < parentAppointment.recurrenceExceptionDates!.length; - i++) { + for ( + int i = 0; + i < parentAppointment.recurrenceExceptionDates!.length; + i++ + ) { recurrenceDates.remove( - AppointmentHelper.convertTimeToAppointmentTimeZone( - parentAppointment.recurrenceExceptionDates![i], - '', - widget.calendar.timeZone)); + AppointmentHelper.convertTimeToAppointmentTimeZone( + parentAppointment.recurrenceExceptionDates![i], + '', + widget.calendar.timeZone, + ), + ); } } recurrenceDates.sort(); - final int currentRecurrenceIndex = - recurrenceDates.indexOf(appointment.exactStartTime); + final int currentRecurrenceIndex = recurrenceDates.indexOf( + appointment.exactStartTime, + ); if (currentRecurrenceIndex != -1) { - final DateTime? previousRecurrence = currentRecurrenceIndex <= 0 - ? null - : recurrenceDates[currentRecurrenceIndex - 1]; + final DateTime? previousRecurrence = + currentRecurrenceIndex <= 0 + ? null + : recurrenceDates[currentRecurrenceIndex - 1]; final DateTime? nextRecurrence = currentRecurrenceIndex >= recurrenceDates.length - 1 ? null @@ -7625,13 +8761,15 @@ class _CalendarViewState extends State<_CalendarView> !isSameDate(nextRecurrence, resizingTime)) && !isSameDate(appointment.exactStartTime, resizingTime)) { if (CalendarViewHelper.shouldRaiseAppointmentResizeEndCallback( - widget.calendar.onAppointmentResizeEnd)) { + widget.calendar.onAppointmentResizeEnd, + )) { CalendarViewHelper.raiseAppointmentResizeEndCallback( - widget.calendar, - appointment.data, - resource, - appointment.exactStartTime, - appointment.exactEndTime); + widget.calendar, + appointment.data, + resource, + appointment.exactStartTime, + appointment.exactEndTime, + ); } _resetResizingPainter(); @@ -7644,76 +8782,103 @@ class _CalendarViewState extends State<_CalendarView> appointment.recurrenceRule!.isEmpty)) { widget.calendar.dataSource!.appointments!.remove(appointment.data); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [appointment.data]); + CalendarDataSourceAction.remove, + [appointment.data], + ); } else { - widget.calendar.dataSource!.appointments! - .remove(parentAppointment.data); + widget.calendar.dataSource!.appointments!.remove( + parentAppointment.data, + ); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [parentAppointment.data]); + CalendarDataSourceAction.remove, + [parentAppointment.data], + ); final DateTime exceptionDate = AppointmentHelper.convertTimeToAppointmentTimeZone( - appointment.exactStartTime, widget.calendar.timeZone, ''); + appointment.exactStartTime, + widget.calendar.timeZone, + '', + ); parentAppointment.recurrenceExceptionDates != null ? parentAppointment.recurrenceExceptionDates!.add(exceptionDate) : parentAppointment.recurrenceExceptionDates = [ - exceptionDate - ]; + exceptionDate, + ]; - final dynamic newParentAppointment = - _getCalendarAppointmentToObject(parentAppointment, widget.calendar); + final dynamic newParentAppointment = _getCalendarAppointmentToObject( + parentAppointment, + widget.calendar, + ); widget.calendar.dataSource!.appointments!.add(newParentAppointment); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.add, [newParentAppointment]); + CalendarDataSourceAction.add, + [newParentAppointment], + ); } } else { widget.calendar.dataSource!.appointments!.remove(appointment.data); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.remove, [appointment.data]); + CalendarDataSourceAction.remove, + [appointment.data], + ); } appointment.startTime = updatedStartTime; appointment.endTime = updatedEndTime; - appointment.recurrenceId = parentAppointment != null - ? parentAppointment.id - : appointment.recurrenceId; + appointment.recurrenceId = + parentAppointment != null + ? parentAppointment.id + : appointment.recurrenceId; appointment.recurrenceRule = appointment.recurrenceId != null ? null : appointment.recurrenceRule; appointment.id = parentAppointment != null ? null : appointment.id; - final dynamic newAppointment = - _getCalendarAppointmentToObject(appointment, widget.calendar); + final dynamic newAppointment = _getCalendarAppointmentToObject( + appointment, + widget.calendar, + ); widget.calendar.dataSource!.appointments!.add(newAppointment); widget.calendar.dataSource!.notifyListeners( - CalendarDataSourceAction.add, [newAppointment]); + CalendarDataSourceAction.add, + [newAppointment], + ); if (CalendarViewHelper.shouldRaiseAppointmentResizeEndCallback( - widget.calendar.onAppointmentResizeEnd)) { - CalendarViewHelper.raiseAppointmentResizeEndCallback(widget.calendar, - newAppointment, resource, callbackStartDate, callbackEndDate); + widget.calendar.onAppointmentResizeEnd, + )) { + CalendarViewHelper.raiseAppointmentResizeEndCallback( + widget.calendar, + newAppointment, + resource, + callbackStartDate, + callbackEndDate, + ); } _resetResizingPainter(); } Future _updateAutoScrollDay( - DragUpdateDetails details, - double viewHeaderHeight, - double allDayPanelHeight, - bool isForwardResize, - bool isBackwardResize, - double? yPosition) async { + DragUpdateDetails details, + double viewHeaderHeight, + double allDayPanelHeight, + bool isForwardResize, + bool isBackwardResize, + double? yPosition, + ) async { if (_resizingDetails.value.appointmentView == null) { return; } final double timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); if (yPosition! <= viewHeaderHeight + allDayPanelHeight && _scrollController!.position.pixels != 0) { @@ -7735,8 +8900,9 @@ class _CalendarViewState extends State<_CalendarView> _resizingDetails.value.scrollPosition = scrollPosition; _resizingDetails.value.position.value = Offset( - _resizingDetails.value.appointmentView!.appointmentRect!.left, - yPosition! - 0.1); + _resizingDetails.value.appointmentView!.appointmentRect!.left, + yPosition! - 0.1, + ); await _scrollController!.position.animateTo( scrollPosition, @@ -7754,25 +8920,28 @@ class _CalendarViewState extends State<_CalendarView> yPosition = _resizingDetails.value.position.value?.dy; _updateMaximumResizingPosition( - isForwardResize, - isBackwardResize, - _resizingDetails.value.appointmentView!, - allDayPanelHeight, - viewHeaderHeight); + isForwardResize, + isBackwardResize, + _resizingDetails.value.appointmentView!, + allDayPanelHeight, + viewHeaderHeight, + ); if ((isForwardResize && yPosition! < _maximumResizingPosition!) || (isBackwardResize && yPosition! > _maximumResizingPosition!)) { yPosition = _maximumResizingPosition; } _updateAppointmentResizingUpdateCallback( - isForwardResize, - isBackwardResize, - yPosition!, - viewHeaderHeight, - allDayPanelHeight); + isForwardResize, + isBackwardResize, + yPosition!, + viewHeaderHeight, + allDayPanelHeight, + ); _resizingDetails.value.position.value = Offset( - _resizingDetails.value.appointmentView!.appointmentRect!.left, - yPosition!); + _resizingDetails.value.appointmentView!.appointmentRect!.left, + yPosition!, + ); if (yPosition != null && yPosition! <= viewHeaderHeight + allDayPanelHeight && @@ -7812,8 +8981,9 @@ class _CalendarViewState extends State<_CalendarView> _resizingDetails.value.scrollPosition = scrollPosition; _resizingDetails.value.position.value = Offset( - _resizingDetails.value.appointmentView!.appointmentRect!.left, - yPosition! - 0.1); + _resizingDetails.value.appointmentView!.appointmentRect!.left, + yPosition! - 0.1, + ); await _scrollController!.position.moveTo( scrollPosition, @@ -7832,25 +9002,28 @@ class _CalendarViewState extends State<_CalendarView> yPosition = _resizingDetails.value.position.value?.dy; _updateMaximumResizingPosition( - isForwardResize, - isBackwardResize, - _resizingDetails.value.appointmentView!, - allDayPanelHeight, - viewHeaderHeight); + isForwardResize, + isBackwardResize, + _resizingDetails.value.appointmentView!, + allDayPanelHeight, + viewHeaderHeight, + ); if ((isForwardResize && yPosition! < _maximumResizingPosition!) || (isBackwardResize && yPosition! > _maximumResizingPosition!)) { yPosition = _maximumResizingPosition; } _updateAppointmentResizingUpdateCallback( - isForwardResize, - isBackwardResize, - yPosition!, - viewHeaderHeight, - allDayPanelHeight); + isForwardResize, + isBackwardResize, + yPosition!, + viewHeaderHeight, + allDayPanelHeight, + ); _resizingDetails.value.position.value = Offset( - _resizingDetails.value.appointmentView!.appointmentRect!.left, - yPosition!); + _resizingDetails.value.appointmentView!.appointmentRect!.left, + yPosition!, + ); if (yPosition != null && yPosition! >= widget.height && @@ -7873,14 +9046,15 @@ class _CalendarViewState extends State<_CalendarView> } Future _updateAutoScrollTimeline( - DragUpdateDetails details, - double timeIntervalHeight, - bool isForwardResize, - bool isBackwardResize, - double? xPosition, - double yPosition, - double timeLabelWidth, - bool isResourceEnabled) async { + DragUpdateDetails details, + double timeIntervalHeight, + bool isForwardResize, + bool isBackwardResize, + double? xPosition, + double yPosition, + double timeLabelWidth, + bool isResourceEnabled, + ) async { if (_resizingDetails.value.appointmentView == null) { return; } @@ -7920,7 +9094,9 @@ class _CalendarViewState extends State<_CalendarView> _resizingDetails.value.scrollPosition = scrollPosition; _resizingDetails.value.position.value = Offset( - xPosition! - 0.1, _resizingDetails.value.position.value!.dy); + xPosition! - 0.1, + _resizingDetails.value.position.value!.dy, + ); await _scrollController!.position.animateTo( scrollPosition, @@ -7937,22 +9113,34 @@ class _CalendarViewState extends State<_CalendarView> } xPosition = _resizingDetails.value.position.value?.dx; - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - _resizingDetails.value.appointmentView!, null, null); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + _resizingDetails.value.appointmentView!, + null, + null, + ); if ((isForwardResize && xPosition! < _maximumResizingPosition!) || (isBackwardResize && xPosition! > _maximumResizingPosition!)) { xPosition = _maximumResizingPosition; } _updateAppointmentResizingUpdateCallback( - isForwardResize, isBackwardResize, yPosition, null, null, - xPosition: xPosition, - timeLabelWidth: timeLabelWidth, - isResourceEnabled: isResourceEnabled, - details: details); + isForwardResize, + isBackwardResize, + yPosition, + null, + null, + xPosition: xPosition, + timeLabelWidth: timeLabelWidth, + isResourceEnabled: isResourceEnabled, + details: details, + ); - _resizingDetails.value.position.value = - Offset(xPosition!, _resizingDetails.value.position.value!.dy); + _resizingDetails.value.position.value = Offset( + xPosition!, + _resizingDetails.value.position.value!.dy, + ); if (xPosition != null && xPosition! <= 0 && @@ -8006,7 +9194,9 @@ class _CalendarViewState extends State<_CalendarView> _resizingDetails.value.scrollPosition = scrollPosition; _resizingDetails.value.position.value = Offset( - xPosition! + 0.1, _resizingDetails.value.position.value!.dy); + xPosition! + 0.1, + _resizingDetails.value.position.value!.dy, + ); await _scrollController!.position.moveTo( scrollPosition, @@ -8023,22 +9213,34 @@ class _CalendarViewState extends State<_CalendarView> } xPosition = _resizingDetails.value.position.value?.dx; - _updateMaximumResizingPosition(isForwardResize, isBackwardResize, - _resizingDetails.value.appointmentView!, null, null); + _updateMaximumResizingPosition( + isForwardResize, + isBackwardResize, + _resizingDetails.value.appointmentView!, + null, + null, + ); if ((isForwardResize && xPosition! < _maximumResizingPosition!) || (isBackwardResize && xPosition! > _maximumResizingPosition!)) { xPosition = _maximumResizingPosition; } _updateAppointmentResizingUpdateCallback( - isForwardResize, isBackwardResize, yPosition, null, null, - xPosition: xPosition, - timeLabelWidth: timeLabelWidth, - isResourceEnabled: isResourceEnabled, - details: details); + isForwardResize, + isBackwardResize, + yPosition, + null, + null, + xPosition: xPosition, + timeLabelWidth: timeLabelWidth, + isResourceEnabled: isResourceEnabled, + details: details, + ); - _resizingDetails.value.position.value = - Offset(xPosition!, _resizingDetails.value.position.value!.dy); + _resizingDetails.value.position.value = Offset( + xPosition!, + _resizingDetails.value.position.value!.dy, + ); if (xPosition != null && xPosition! + padding >= widget.width && @@ -8063,11 +9265,12 @@ class _CalendarViewState extends State<_CalendarView> } void _updateMaximumResizingPosition( - bool isForwardResize, - bool isBackwardResize, - AppointmentView appointmentView, - double? allDayPanelHeight, - double? viewHeaderHeight) { + bool isForwardResize, + bool isBackwardResize, + AppointmentView appointmentView, + double? allDayPanelHeight, + double? viewHeaderHeight, + ) { switch (widget.view) { case CalendarView.schedule: break; @@ -8077,38 +9280,42 @@ class _CalendarViewState extends State<_CalendarView> { if (_resizingDetails.value.isAllDayPanel) { final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, - widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final double minimumCellWidth = ((widget.width - timeLabelWidth) / widget.visibleDates.length) / - 2; + 2; if (isForwardResize) { - _maximumResizingPosition = appointmentView.appointmentRect!.left + + _maximumResizingPosition = + appointmentView.appointmentRect!.left + (appointmentView.appointmentRect!.width > minimumCellWidth ? minimumCellWidth : appointmentView.appointmentRect!.width); } else if (isBackwardResize) { _maximumResizingPosition = appointmentView.appointmentRect!.right - - (appointmentView.appointmentRect!.width > minimumCellWidth - ? minimumCellWidth - : appointmentView.appointmentRect!.width); + (appointmentView.appointmentRect!.width > minimumCellWidth + ? minimumCellWidth + : appointmentView.appointmentRect!.width); } } else { final double timeIntervalSize = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); double minimumTimeIntervalSize = timeIntervalSize / 4; if (minimumTimeIntervalSize < 20) { minimumTimeIntervalSize = 20; } if (isForwardResize) { - _maximumResizingPosition = (appointmentView.appointmentRect!.top - + _maximumResizingPosition = + (appointmentView.appointmentRect!.top - _scrollController!.offset + allDayPanelHeight! + viewHeaderHeight!) + @@ -8119,13 +9326,13 @@ class _CalendarViewState extends State<_CalendarView> } else if (isBackwardResize) { _maximumResizingPosition = (appointmentView.appointmentRect!.bottom - - _scrollController!.offset + - allDayPanelHeight! + - viewHeaderHeight!) - - (appointmentView.appointmentRect!.height / 2 > - minimumTimeIntervalSize - ? minimumTimeIntervalSize - : appointmentView.appointmentRect!.height / 2); + _scrollController!.offset + + allDayPanelHeight! + + viewHeaderHeight!) - + (appointmentView.appointmentRect!.height / 2 > + minimumTimeIntervalSize + ? minimumTimeIntervalSize + : appointmentView.appointmentRect!.height / 2); } } } @@ -8136,39 +9343,47 @@ class _CalendarViewState extends State<_CalendarView> case CalendarView.timelineMonth: { final double timeIntervalSize = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); - double minimumTimeIntervalSize = timeIntervalSize / + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); + double minimumTimeIntervalSize = + timeIntervalSize / (widget.view == CalendarView.timelineMonth ? 2 : 4); if (minimumTimeIntervalSize < 20) { minimumTimeIntervalSize = 20; } if (isForwardResize) { - _maximumResizingPosition = appointmentView.appointmentRect!.left - + _maximumResizingPosition = + appointmentView.appointmentRect!.left - _scrollController!.offset; if (_isRTL) { - _maximumResizingPosition = _scrollController!.offset - + _maximumResizingPosition = + _scrollController!.offset - _scrollController!.position.maxScrollExtent + appointmentView.appointmentRect!.left; } - _maximumResizingPosition = _maximumResizingPosition! + + _maximumResizingPosition = + _maximumResizingPosition! + (appointmentView.appointmentRect!.width / 2 > minimumTimeIntervalSize ? minimumTimeIntervalSize : appointmentView.appointmentRect!.width / 2); } else if (isBackwardResize) { - _maximumResizingPosition = appointmentView.appointmentRect!.right - + _maximumResizingPosition = + appointmentView.appointmentRect!.right - _scrollController!.offset; if (_isRTL) { - _maximumResizingPosition = _scrollController!.offset - + _maximumResizingPosition = + _scrollController!.offset - _scrollController!.position.maxScrollExtent + appointmentView.appointmentRect!.right; } - _maximumResizingPosition = _maximumResizingPosition! - + _maximumResizingPosition = + _maximumResizingPosition! - (appointmentView.appointmentRect!.width / 2 > minimumTimeIntervalSize ? minimumTimeIntervalSize @@ -8180,19 +9395,22 @@ class _CalendarViewState extends State<_CalendarView> { final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); final double minimumCellWidth = ((widget.width - weekNumberPanelWidth) / DateTime.daysPerWeek) / - 2; + 2; if (isForwardResize) { - _maximumResizingPosition = appointmentView.appointmentRect!.left + + _maximumResizingPosition = + appointmentView.appointmentRect!.left + (appointmentView.appointmentRect!.width / 2 > minimumCellWidth ? minimumCellWidth : appointmentView.appointmentRect!.width / 2); } else if (isBackwardResize) { - _maximumResizingPosition = appointmentView.appointmentRect!.right - + _maximumResizingPosition = + appointmentView.appointmentRect!.right - (appointmentView.appointmentRect!.width / 2 > minimumCellWidth ? minimumCellWidth : appointmentView.appointmentRect!.width / 2); @@ -8202,44 +9420,52 @@ class _CalendarViewState extends State<_CalendarView> } void _updateAppointmentResizingUpdateCallback( - bool isForwardResize, - bool isBackwardResize, - double yPosition, - double? viewHeaderHeight, - double? allDayPanelHeight, - {bool isResourceEnabled = false, - double? timeLabelWidth, - double? xPosition, - DragUpdateDetails? details}) { + bool isForwardResize, + bool isBackwardResize, + double yPosition, + double? viewHeaderHeight, + double? allDayPanelHeight, { + bool isResourceEnabled = false, + double? timeLabelWidth, + double? xPosition, + DragUpdateDetails? details, + }) { final double timeIntervalHeight = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); late DateTime resizingTime; CalendarResource? resource; int selectedResourceIndex = -1; if (isResourceEnabled) { final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); selectedResourceIndex = _getSelectedResourceIndex( - _resizingDetails.value.appointmentView!.appointmentRect!.top, - viewHeaderHeight, - timeLabelWidth!); + _resizingDetails.value.appointmentView!.appointmentRect!.top, + viewHeaderHeight, + timeLabelWidth!, + ); resource = widget.calendar.dataSource!.resources![selectedResourceIndex]; } if (CalendarViewHelper.isTimelineView(widget.view)) { - final double overAllWidth = _timeIntervalHeight * + final double overAllWidth = + _timeIntervalHeight * (_horizontalLinesCount! * widget.visibleDates.length); double updatedXPosition = details!.localPosition.dx; if (updatedXPosition > widget.width - 1) { @@ -8251,24 +9477,39 @@ class _CalendarViewState extends State<_CalendarView> updatedXPosition = overAllWidth; } - resizingTime = _getDateFromPosition( - updatedXPosition, details.localPosition.dy, timeLabelWidth!)!; - final DateTime time = _timeFromPosition( - resizingTime, - widget.calendar.timeSlotViewSettings, - xPosition! > widget.width - 1 - ? widget.width - 1 - : (xPosition < 0 ? 0 : xPosition), - this, - timeIntervalHeight, - true)!; + resizingTime = + _getDateFromPosition( + updatedXPosition, + details.localPosition.dy, + timeLabelWidth!, + )!; + final DateTime time = + _timeFromPosition( + resizingTime, + widget.calendar.timeSlotViewSettings, + xPosition! > widget.width - 1 + ? widget.width - 1 + : (xPosition < 0 ? 0 : xPosition), + this, + timeIntervalHeight, + true, + )!; if (widget.view == CalendarView.timelineMonth) { - resizingTime = - DateTime(resizingTime.year, resizingTime.month, resizingTime.day); + resizingTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + ); } else { - resizingTime = DateTime(resizingTime.year, resizingTime.month, - resizingTime.day, time.hour, time.minute, time.second); + resizingTime = DateTime( + resizingTime.year, + resizingTime.month, + resizingTime.day, + time.hour, + time.minute, + time.second, + ); } } else { final double overAllHeight = _timeIntervalHeight * _horizontalLinesCount!; @@ -8279,26 +9520,35 @@ class _CalendarViewState extends State<_CalendarView> } final double currentYPosition = updatedYPosition - viewHeaderHeight! - allDayPanelHeight!; - resizingTime = _timeFromPosition( - _resizingDetails.value.appointmentView!.appointment!.actualStartTime, - widget.calendar.timeSlotViewSettings, - currentYPosition > 0 ? currentYPosition : 0, - this, - timeIntervalHeight, - false)!; + resizingTime = + _timeFromPosition( + _resizingDetails + .value + .appointmentView! + .appointment! + .actualStartTime, + widget.calendar.timeSlotViewSettings, + currentYPosition > 0 ? currentYPosition : 0, + this, + timeIntervalHeight, + false, + )!; } _resizingDetails.value.resizingTime = resizingTime; if (CalendarViewHelper.shouldRaiseAppointmentResizeUpdateCallback( - widget.calendar.onAppointmentResizeUpdate)) { + widget.calendar.onAppointmentResizeUpdate, + )) { CalendarViewHelper.raiseAppointmentResizeUpdateCallback( + widget.calendar, + _getCalendarAppointmentToObject( + _resizingDetails.value.appointmentView!.appointment, widget.calendar, - _getCalendarAppointmentToObject( - _resizingDetails.value.appointmentView!.appointment, - widget.calendar), - resource, - resizingTime, - _resizingDetails.value.position.value!); + ), + resource, + resizingTime, + _resizingDetails.value.position.value!, + ); } } @@ -8317,7 +9567,9 @@ class _CalendarViewState extends State<_CalendarView> // Returns the month view as a child for the calendar view. Widget _addMonthView(bool isRTL, String locale) { final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); final double height = widget.height - viewHeaderHeight; return Stack( children: [ @@ -8327,37 +9579,42 @@ class _CalendarViewState extends State<_CalendarView> right: 0, height: viewHeaderHeight, child: Container( - color: widget.calendar.viewHeaderStyle.backgroundColor ?? + color: + widget.calendar.viewHeaderStyle.backgroundColor ?? widget.calendarTheme.viewHeaderBackgroundColor, child: RepaintBoundary( child: CustomPaint( painter: _ViewHeaderViewPainter( - widget.visibleDates, + widget.visibleDates, + widget.view, + widget.calendar.viewHeaderStyle, + widget.calendar.timeSlotViewSettings, + CalendarViewHelper.getTimeLabelWidth( + widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view, - widget.calendar.viewHeaderStyle, - widget.calendar.timeSlotViewSettings, - CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, - widget.view), - CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view), - widget.calendar.monthViewSettings, - isRTL, - widget.locale, - widget.calendarTheme, - widget.themeData, - widget.calendar.todayHighlightColor ?? - widget.calendarTheme.todayHighlightColor, - widget.calendar.todayTextStyle, - widget.calendar.cellBorderColor, - widget.calendar.minDate, - widget.calendar.maxDate, - _viewHeaderNotifier, - widget.textScaleFactor, - widget.calendar.showWeekNumber, - widget.isMobilePlatform, - widget.calendar.weekNumberStyle, - widget.localizations), + ), + CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ), + widget.calendar.monthViewSettings, + isRTL, + widget.locale, + widget.calendarTheme, + widget.themeData, + widget.calendar.todayHighlightColor ?? + widget.calendarTheme.todayHighlightColor, + widget.calendar.todayTextStyle, + widget.calendar.cellBorderColor, + widget.calendar.minDate, + widget.calendar.maxDate, + _viewHeaderNotifier, + widget.textScaleFactor, + widget.calendar.showWeekNumber, + widget.isMobilePlatform, + widget.calendar.weekNumberStyle, + widget.localizations, + ), ), ), ), @@ -8368,15 +9625,18 @@ class _CalendarViewState extends State<_CalendarView> right: 0, bottom: 0, child: RepaintBoundary( - child: _CalendarMultiChildContainer( - width: widget.width, - height: height, - children: [ - RepaintBoundary(child: _getMonthWidget(isRTL, height)), - RepaintBoundary( - child: _addAppointmentPainter(widget.width, height)), - ], - )), + child: _CalendarMultiChildContainer( + width: widget.width, + height: height, + builder: widget.calendar.monthCellBuilder, + children: [ + RepaintBoundary(child: _getMonthWidget(isRTL, height)), + RepaintBoundary( + child: _addAppointmentPainter(widget.width, height), + ), + ], + ), + ), ), Positioned( left: 0, @@ -8401,30 +9661,31 @@ class _CalendarViewState extends State<_CalendarView> ? _updateCalendarStateDetails.visibleAppointments : null; _monthView = MonthViewWidget( - widget.visibleDates, - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.monthCellStyle, - isRTL, - widget.calendar.todayHighlightColor ?? - widget.calendarTheme.todayHighlightColor, - widget.calendar.todayTextStyle, - widget.calendar.cellBorderColor, - widget.calendarTheme, - widget.themeData, - _calendarCellNotifier, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - widget.calendar.minDate, - widget.calendar.maxDate, - widget.calendar, - widget.blackoutDates, - widget.calendar.blackoutDatesTextStyle, - widget.textScaleFactor, - widget.calendar.monthCellBuilder, - widget.width, - height, - widget.calendar.weekNumberStyle, - widget.isMobilePlatform, - ValueNotifier?>(visibleAppointments)); + widget.visibleDates, + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.monthCellStyle, + isRTL, + widget.calendar.todayHighlightColor ?? + widget.calendarTheme.todayHighlightColor, + widget.calendar.todayTextStyle, + widget.calendar.cellBorderColor, + widget.calendarTheme, + widget.themeData, + _calendarCellNotifier, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + widget.calendar.minDate, + widget.calendar.maxDate, + widget.calendar, + widget.blackoutDates, + widget.calendar.blackoutDatesTextStyle, + widget.textScaleFactor, + widget.calendar.monthCellBuilder, + widget.width, + height, + widget.calendar.weekNumberStyle, + widget.isMobilePlatform, + ValueNotifier?>(visibleAppointments), + ); return _monthView; } @@ -8434,34 +9695,45 @@ class _CalendarViewState extends State<_CalendarView> } final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); - final double allDayPanelHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; - final bool isVerticalResize = _mouseCursor == SystemMouseCursors.resizeUp || + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); + final double allDayPanelHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; + final bool isVerticalResize = + _mouseCursor == SystemMouseCursors.resizeUp || _mouseCursor == SystemMouseCursors.resizeDown; final bool isTimelineView = CalendarViewHelper.isTimelineView(widget.view); - final bool isAllDayPanel = !isVerticalResize && + final bool isAllDayPanel = + !isVerticalResize && (!isTimelineView && widget.view != CalendarView.month); final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); - final double overAllWidth = isTimelineView - ? _timeIntervalHeight * - (_horizontalLinesCount! * widget.visibleDates.length) - : widget.width; + final double overAllWidth = + isTimelineView + ? _timeIntervalHeight * + (_horizontalLinesCount! * widget.visibleDates.length) + : widget.width; final double overAllHeight = isTimelineView || widget.view == CalendarView.month ? widget.height @@ -8470,70 +9742,87 @@ class _CalendarViewState extends State<_CalendarView> (_timeIntervalHeight * _horizontalLinesCount!); return Positioned( - left: 0, - width: overAllWidth, - height: overAllHeight, - top: 0, - child: GestureDetector( - onVerticalDragStart: isVerticalResize ? _onVerticalStart : null, - onVerticalDragUpdate: isVerticalResize ? _onVerticalUpdate : null, - onVerticalDragEnd: isVerticalResize ? _onVerticalEnd : null, - onHorizontalDragStart: isVerticalResize ? null : _onHorizontalStart, - onHorizontalDragUpdate: isVerticalResize ? null : _onHorizontalUpdate, - onHorizontalDragEnd: isVerticalResize ? null : _onHorizontalEnd, - child: IgnorePointer( - ignoring: _mouseCursor == SystemMouseCursors.basic || - _mouseCursor == SystemMouseCursors.move || - isAllDayPanel, - child: RepaintBoundary( - child: CustomPaint( - painter: _ResizingAppointmentPainter( - _resizingDetails, - _isRTL, - widget.textScaleFactor, - widget.isMobilePlatform, - AppointmentHelper.getAppointmentTextStyle( - widget.calendar.appointmentTextStyle, - widget.view, - widget.themeData), - allDayPanelHeight, - viewHeaderHeight, - timeLabelWidth, - _timeIntervalHeight, - _scrollController, - widget.calendar.dragAndDropSettings, - widget.view, - _mouseCursor, - weekNumberPanelWidth, - widget.calendarTheme), - ))), - )); + left: 0, + width: overAllWidth, + height: overAllHeight, + top: 0, + child: GestureDetector( + onVerticalDragStart: isVerticalResize ? _onVerticalStart : null, + onVerticalDragUpdate: isVerticalResize ? _onVerticalUpdate : null, + onVerticalDragEnd: isVerticalResize ? _onVerticalEnd : null, + onHorizontalDragStart: isVerticalResize ? null : _onHorizontalStart, + onHorizontalDragUpdate: isVerticalResize ? null : _onHorizontalUpdate, + onHorizontalDragEnd: isVerticalResize ? null : _onHorizontalEnd, + child: IgnorePointer( + ignoring: + _mouseCursor == SystemMouseCursors.basic || + _mouseCursor == SystemMouseCursors.move || + isAllDayPanel, + child: RepaintBoundary( + child: CustomPaint( + painter: _ResizingAppointmentPainter( + _resizingDetails, + _isRTL, + widget.textScaleFactor, + widget.isMobilePlatform, + AppointmentHelper.getAppointmentTextStyle( + widget.calendar.appointmentTextStyle, + widget.view, + widget.themeData, + ), + allDayPanelHeight, + viewHeaderHeight, + timeLabelWidth, + _timeIntervalHeight, + _scrollController, + widget.calendar.dragAndDropSettings, + widget.view, + _mouseCursor, + weekNumberPanelWidth, + widget.calendarTheme, + ), + ), + ), + ), + ), + ); } // Returns the day view as a child for the calendar view. - Widget _addDayView(double width, double height, bool isRTL, String locale, - bool isCurrentView) { + Widget _addDayView( + double width, + double height, + bool isRTL, + String locale, + bool isCurrentView, + ) { double viewHeaderWidth = widget.width; final double actualViewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); double viewHeaderHeight = actualViewHeaderHeight; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); if (isDayView) { viewHeaderWidth = timeLabelWidth < 50 ? 50 : timeLabelWidth; viewHeaderHeight = _allDayHeight > viewHeaderHeight ? _allDayHeight : viewHeaderHeight; } - double panelHeight = isCurrentView - ? _updateCalendarStateDetails.allDayPanelHeight - _allDayHeight - : 0; + double panelHeight = + isCurrentView + ? _updateCalendarStateDetails.allDayPanelHeight - _allDayHeight + : 0; if (panelHeight < 0) { panelHeight = 0; } @@ -8549,123 +9838,142 @@ class _CalendarViewState extends State<_CalendarView> right: isRTL ? 0 : widget.width - viewHeaderWidth, height: actualViewHeaderHeight, child: Container( - color: widget.calendar.viewHeaderStyle.backgroundColor ?? + color: + widget.calendar.viewHeaderStyle.backgroundColor ?? widget.calendarTheme.viewHeaderBackgroundColor, child: RepaintBoundary( child: CustomPaint( painter: _ViewHeaderViewPainter( - widget.visibleDates, + widget.visibleDates, + widget.view, + widget.calendar.viewHeaderStyle, + widget.calendar.timeSlotViewSettings, + CalendarViewHelper.getTimeLabelWidth( + widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view, - widget.calendar.viewHeaderStyle, - widget.calendar.timeSlotViewSettings, - CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, - widget.view), - actualViewHeaderHeight, - widget.calendar.monthViewSettings, - isRTL, - widget.locale, - widget.calendarTheme, - widget.themeData, - widget.calendar.todayHighlightColor ?? - widget.calendarTheme.todayHighlightColor, - widget.calendar.todayTextStyle, - widget.calendar.cellBorderColor, - widget.calendar.minDate, - widget.calendar.maxDate, - _viewHeaderNotifier, - widget.textScaleFactor, - widget.calendar.showWeekNumber, - widget.isMobilePlatform, - widget.calendar.weekNumberStyle, - widget.localizations), + ), + actualViewHeaderHeight, + widget.calendar.monthViewSettings, + isRTL, + widget.locale, + widget.calendarTheme, + widget.themeData, + widget.calendar.todayHighlightColor ?? + widget.calendarTheme.todayHighlightColor, + widget.calendar.todayTextStyle, + widget.calendar.cellBorderColor, + widget.calendar.minDate, + widget.calendar.maxDate, + _viewHeaderNotifier, + widget.textScaleFactor, + widget.calendar.showWeekNumber, + widget.isMobilePlatform, + widget.calendar.weekNumberStyle, + widget.localizations, + ), ), ), ), ), Positioned( - top: isDayView - ? viewHeaderHeight + allDayExpanderHeight - : viewHeaderHeight + _allDayHeight + allDayExpanderHeight, - left: 0, - right: 0, - bottom: 0, - child: Scrollbar( + top: + isDayView + ? viewHeaderHeight + allDayExpanderHeight + : viewHeaderHeight + _allDayHeight + allDayExpanderHeight, + left: 0, + right: 0, + bottom: 0, + child: Scrollbar( + controller: _scrollController, + thumbVisibility: !widget.isMobilePlatform, + child: ListView( + padding: EdgeInsets.zero, controller: _scrollController, - thumbVisibility: !widget.isMobilePlatform, - child: ListView( - padding: EdgeInsets.zero, - controller: _scrollController, - physics: const ClampingScrollPhysics(), + physics: const ClampingScrollPhysics(), + children: [ + Stack( children: [ - Stack(children: [ - RepaintBoundary( - child: _CalendarMultiChildContainer( - width: width, - height: height, - children: [ - RepaintBoundary( - child: TimeSlotWidget( - widget.visibleDates, - _horizontalLinesCount!, - _timeIntervalHeight, - timeLabelWidth, - widget.calendar.cellBorderColor, - widget.calendarTheme, - widget.themeData, - widget.calendar.timeSlotViewSettings, - isRTL, - widget.regions, - _calendarCellNotifier, - widget.textScaleFactor, - widget.calendar.timeRegionBuilder, - width, - height, - widget.calendar.minDate, - widget.calendar.maxDate), - ), - RepaintBoundary( - child: _addAppointmentPainter(width, height)), - ])), - RepaintBoundary( - child: CustomPaint( - painter: _TimeRulerView( + RepaintBoundary( + child: _CalendarMultiChildContainer( + width: width, + height: height, + builder: widget.calendar.monthCellBuilder, + children: [ + RepaintBoundary( + child: TimeSlotWidget( + widget.visibleDates, _horizontalLinesCount!, _timeIntervalHeight, + timeLabelWidth, + widget.calendar.cellBorderColor, + widget.calendarTheme, + widget.themeData, widget.calendar.timeSlotViewSettings, - widget.calendar.cellBorderColor, isRTL, - widget.locale, - widget.calendarTheme, - CalendarViewHelper.isTimelineView(widget.view), - widget.visibleDates, - widget.textScaleFactor), - size: Size(timeLabelWidth, height), - ), + widget.regions, + _calendarCellNotifier, + widget.textScaleFactor, + widget.calendar.timeRegionBuilder, + width, + height, + widget.calendar.minDate, + widget.calendar.maxDate, + ), + ), + RepaintBoundary( + child: _addAppointmentPainter(width, height), + ), + ], ), - RepaintBoundary( - child: CustomPaint( - painter: _addSelectionView(), - size: Size(width, height), + ), + RepaintBoundary( + child: CustomPaint( + painter: _TimeRulerView( + _horizontalLinesCount!, + _timeIntervalHeight, + widget.calendar.timeSlotViewSettings, + widget.calendar.cellBorderColor, + isRTL, + widget.locale, + widget.calendarTheme, + CalendarViewHelper.isTimelineView(widget.view), + widget.visibleDates, + widget.textScaleFactor, ), + size: Size(timeLabelWidth, height), + ), + ), + RepaintBoundary( + child: CustomPaint( + painter: _addSelectionView(), + size: Size(width, height), ), - _getCurrentTimeIndicator( - timeLabelWidth, width, height, false), - ]) - ]), - )), + ), + _getCurrentTimeIndicator( + timeLabelWidth, + width, + height, + false, + ), + ], + ), + ], + ), + ), + ), ], ); } Widget _getCurrentTimeIndicator( - double timeLabelSize, double width, double height, bool isTimelineView) { + double timeLabelSize, + double width, + double height, + bool isTimelineView, + ) { if (!widget.calendar.showCurrentTimeIndicator || widget.view == CalendarView.timelineMonth) { - return const SizedBox( - width: 0, - height: 0, - ); + return const SizedBox(width: 0, height: 0); } return RepaintBoundary( @@ -8695,12 +10003,15 @@ class _CalendarViewState extends State<_CalendarView> _selectedResourceIndex == -1) { final bool isTimelineMonth = widget.view == CalendarView.timelineMonth; if ((isTimelineMonth && - (isSameDate(_updateCalendarStateDetails.selectedDate, - widget.calendar.initialSelectedDate))) || + (isSameDate( + _updateCalendarStateDetails.selectedDate, + widget.calendar.initialSelectedDate, + ))) || (!isTimelineMonth && (CalendarViewHelper.isSameTimeSlot( - _updateCalendarStateDetails.selectedDate, - widget.calendar.initialSelectedDate)))) { + _updateCalendarStateDetails.selectedDate, + widget.calendar.initialSelectedDate, + )))) { _selectedResourceIndex = 0; } } @@ -8709,36 +10020,49 @@ class _CalendarViewState extends State<_CalendarView> // Returns the timeline view as a child for the calendar view. Widget _addTimelineView(double width, double height, String locale) { final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); final double timeLabelSize = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); double resourceItemHeight = 0; height -= viewHeaderHeight + timeLabelSize; if (isResourceEnabled) { _updateProgrammaticSelectedResourceIndex(); final double resourceViewSize = widget.calendar.resourceViewSettings.size; resourceItemHeight = CalendarViewHelper.getResourceItemHeight( - resourceViewSize, - widget.height - viewHeaderHeight - timeLabelSize, - widget.calendar.resourceViewSettings, - widget.calendar.dataSource!.resources!.length); + resourceViewSize, + widget.height - viewHeaderHeight - timeLabelSize, + widget.calendar.resourceViewSettings, + widget.calendar.dataSource!.resources!.length, + ); height = resourceItemHeight * widget.resourceCollection!.length; } - return Stack(children: [ - Positioned( - top: 0, - left: 0, - right: 0, - height: viewHeaderHeight, - child: Container( - color: widget.calendar.viewHeaderStyle.backgroundColor ?? - widget.calendarTheme.viewHeaderBackgroundColor, - child: _getTimelineViewHeader(width, viewHeaderHeight, widget.locale), + return Stack( + children: [ + Positioned( + top: 0, + left: 0, + right: 0, + height: viewHeaderHeight, + child: Container( + color: + widget.calendar.viewHeaderStyle.backgroundColor ?? + widget.calendarTheme.viewHeaderBackgroundColor, + child: _getTimelineViewHeader( + width, + viewHeaderHeight, + widget.locale, + ), + ), ), - ), - Positioned( + Positioned( top: viewHeaderHeight, left: 0, right: 0, @@ -8747,13 +10071,14 @@ class _CalendarViewState extends State<_CalendarView> padding: EdgeInsets.zero, controller: _timelineRulerController, scrollDirection: Axis.horizontal, - physics: widget.isMobilePlatform - ? const _CustomNeverScrollableScrollPhysics() - : const ClampingScrollPhysics(), + physics: + widget.isMobilePlatform + ? const _CustomNeverScrollableScrollPhysics() + : const ClampingScrollPhysics(), children: [ RepaintBoundary( - child: CustomPaint( - painter: _TimeRulerView( + child: CustomPaint( + painter: _TimeRulerView( _horizontalLinesCount!, _timeIntervalHeight, widget.calendar.timeSlotViewSettings, @@ -8763,12 +10088,15 @@ class _CalendarViewState extends State<_CalendarView> widget.calendarTheme, CalendarViewHelper.isTimelineView(widget.view), widget.visibleDates, - widget.textScaleFactor), - size: Size(width, timeLabelSize), - )), + widget.textScaleFactor, + ), + size: Size(width, timeLabelSize), + ), + ), ], - )), - Positioned( + ), + ), + Positioned( top: viewHeaderHeight + timeLabelSize, left: 0, right: 0, @@ -8777,78 +10105,100 @@ class _CalendarViewState extends State<_CalendarView> controller: _scrollController, thumbVisibility: !widget.isMobilePlatform, child: ListView( - padding: EdgeInsets.zero, - controller: _scrollController, - scrollDirection: Axis.horizontal, - physics: widget.isMobilePlatform - ? const _CustomNeverScrollableScrollPhysics() - : const ClampingScrollPhysics(), - children: [ - SizedBox( - width: width, - child: Stack(children: [ - Scrollbar( - controller: _timelineViewVerticalScrollController, - thumbVisibility: !widget.isMobilePlatform, - child: ListView( - padding: EdgeInsets.zero, - controller: - _timelineViewVerticalScrollController, - physics: isResourceEnabled - ? const ClampingScrollPhysics() - : const NeverScrollableScrollPhysics(), - children: [ - Stack(children: [ - RepaintBoundary( - child: _CalendarMultiChildContainer( - width: width, - height: height, - children: [ - RepaintBoundary( - child: TimelineWidget( - _horizontalLinesCount!, - widget.visibleDates, - widget.calendar - .timeSlotViewSettings, - _timeIntervalHeight, - widget.calendar.cellBorderColor, - _isRTL, - widget.calendarTheme, - widget.themeData, - _calendarCellNotifier, - _scrollController!, - widget.regions, - resourceItemHeight, - widget.resourceCollection, - widget.textScaleFactor, - widget.isMobilePlatform, - widget - .calendar.timeRegionBuilder, - width, - height, - widget.minDate, - widget.maxDate, - widget.blackoutDates)), - RepaintBoundary( - child: _addAppointmentPainter(width, - height, resourceItemHeight)), - ], - )), - RepaintBoundary( - child: CustomPaint( - painter: _addSelectionView( - resourceItemHeight), - size: Size(width, height), + padding: EdgeInsets.zero, + controller: _scrollController, + scrollDirection: Axis.horizontal, + physics: + widget.isMobilePlatform + ? const _CustomNeverScrollableScrollPhysics() + : const ClampingScrollPhysics(), + children: [ + SizedBox( + width: width, + child: Stack( + children: [ + Scrollbar( + controller: _timelineViewVerticalScrollController, + thumbVisibility: !widget.isMobilePlatform, + child: ListView( + padding: EdgeInsets.zero, + controller: _timelineViewVerticalScrollController, + physics: + isResourceEnabled + ? const ClampingScrollPhysics() + : const NeverScrollableScrollPhysics(), + children: [ + Stack( + children: [ + RepaintBoundary( + child: _CalendarMultiChildContainer( + width: width, + height: height, + builder: widget.calendar.monthCellBuilder, + children: [ + RepaintBoundary( + child: TimelineWidget( + _horizontalLinesCount!, + widget.visibleDates, + widget.calendar.timeSlotViewSettings, + _timeIntervalHeight, + widget.calendar.cellBorderColor, + _isRTL, + widget.calendarTheme, + widget.themeData, + _calendarCellNotifier, + _scrollController!, + widget.regions, + resourceItemHeight, + widget.resourceCollection, + widget.textScaleFactor, + widget.isMobilePlatform, + widget.calendar.timeRegionBuilder, + width, + height, + widget.minDate, + widget.maxDate, + widget.blackoutDates, + ), + ), + RepaintBoundary( + child: _addAppointmentPainter( + width, + height, + resourceItemHeight, + ), ), + ], + ), + ), + RepaintBoundary( + child: CustomPaint( + painter: _addSelectionView( + resourceItemHeight, ), - _getCurrentTimeIndicator( - timeLabelSize, width, height, true), - ]), - ])), - ])), - ]), - )), - ]); + size: Size(width, height), + ), + ), + _getCurrentTimeIndicator( + timeLabelSize, + width, + height, + true, + ), + ], + ), + ], + ), + ), + ], + ), + ), + ], + ), + ), + ), + ], + ); } //// Get the calendar details for all calendar views. @@ -8876,9 +10226,10 @@ class _CalendarViewState extends State<_CalendarView> double yPosition = position.dy; final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if ((!_isRTL && xPosition < weekNumberPanelWidth) || (_isRTL && xPosition > widget.width - weekNumberPanelWidth)) { /// Return null while the [getCalendarDetailsAtOffset] position placed on @@ -8887,16 +10238,19 @@ class _CalendarViewState extends State<_CalendarView> } final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); if (yPosition < viewHeaderHeight) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on view header in month view. return CalendarDetails( - null, - _getTappedViewHeaderDate(position, widget.width), - CalendarElement.viewHeader, - null); + null, + _getTappedViewHeaderDate(position, widget.width), + CalendarElement.viewHeader, + null, + ); } yPosition = yPosition - viewHeaderHeight; @@ -8904,9 +10258,12 @@ class _CalendarViewState extends State<_CalendarView> bool isMoreTapped = false; if (widget.calendar.monthViewSettings.appointmentDisplayMode == MonthAppointmentDisplayMode.appointment) { - appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); - isMoreTapped = appointmentView != null && + appointmentView = _appointmentLayout.getAppointmentViewOnPoint( + xPosition, + yPosition, + ); + isMoreTapped = + appointmentView != null && appointmentView.startIndex == -1 && appointmentView.endIndex == -1 && appointmentView.position == -1 && @@ -8922,10 +10279,11 @@ class _CalendarViewState extends State<_CalendarView> /// Check the position of date as trailing or leading date when /// [SfCalendar] month not shown leading and trailing dates. if (!CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - getDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + getDate, + )) { /// Return null while the [getCalendarDetailsAtOffset] position placed /// on not shown leading and trailing dates. return null; @@ -8936,19 +10294,26 @@ class _CalendarViewState extends State<_CalendarView> appointmentView == null || isMoreTapped ? _getSelectedAppointments(getDate) : [ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ]; - final CalendarElement selectedElement = appointmentView == null - ? CalendarElement.calendarCell - : isMoreTapped + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ]; + final CalendarElement selectedElement = + appointmentView == null + ? CalendarElement.calendarCell + : isMoreTapped ? CalendarElement.moreAppointmentRegion : CalendarElement.appointment; /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on month cells in month view. return CalendarDetails( - selectedAppointments, getDate, selectedElement, null); + selectedAppointments, + getDate, + selectedElement, + null, + ); } //// Handles the onTap callback for month cells, and view header of month @@ -8958,7 +10323,9 @@ class _CalendarViewState extends State<_CalendarView> /// Handles the tap and long press related functions for month view. AppointmentView? _handleTouchOnMonthView( - TapUpDetails? tapDetails, LongPressStartDetails? longPressDetails) { + TapUpDetails? tapDetails, + LongPressStartDetails? longPressDetails, + ) { widget.removePicker(); final DateTime? previousSelectedDate = _selectionPainter!.selectedDate; double xDetails = 0, yDetails = 0; @@ -8973,12 +10340,15 @@ class _CalendarViewState extends State<_CalendarView> } final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if ((!_isRTL && xDetails < weekNumberPanelWidth) || (_isRTL && xDetails > widget.width - weekNumberPanelWidth)) { return null; @@ -9000,8 +10370,11 @@ class _CalendarViewState extends State<_CalendarView> widget.calendar.monthViewSettings.appointmentDisplayMode == MonthAppointmentDisplayMode.appointment) { appointmentView = _appointmentLayout.getAppointmentViewOnPoint( - xDetails, yDetails - viewHeaderHeight); - isMoreTapped = appointmentView != null && + xDetails, + yDetails - viewHeaderHeight, + ); + isMoreTapped = + appointmentView != null && appointmentView.startIndex == -1 && appointmentView.endIndex == -1 && appointmentView.position == -1 && @@ -9022,10 +10395,15 @@ class _CalendarViewState extends State<_CalendarView> final DateTime selectedDate = _getDateFromPosition(xDetails, yDetails - viewHeaderHeight, 0)!; if (appointmentView == null) { - if (!isDateWithInDateRange(widget.calendar.minDate, - widget.calendar.maxDate, selectedDate) || + if (!isDateWithInDateRange( + widget.calendar.minDate, + widget.calendar.maxDate, + selectedDate, + ) || CalendarViewHelper.isDateInDateCollection( - widget.blackoutDates, selectedDate)) { + widget.blackoutDates, + selectedDate, + )) { return null; } @@ -9035,10 +10413,11 @@ class _CalendarViewState extends State<_CalendarView> /// Check the selected cell date as trailing or leading date when /// [SfCalendar] month not shown leading and trailing dates. if (!CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - selectedDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + selectedDate, + )) { return null; } @@ -9047,39 +10426,57 @@ class _CalendarViewState extends State<_CalendarView> final bool canRaiseTap = CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.calendar.onTap) && - isTapCallback; + widget.calendar.onTap, + ) && + isTapCallback; final bool canRaiseLongPress = CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.calendar.onLongPress) && - !isTapCallback; + widget.calendar.onLongPress, + ) && + !isTapCallback; final bool canRaiseSelectionChanged = CalendarViewHelper.shouldRaiseCalendarSelectionChangedCallback( - widget.calendar.onSelectionChanged); + widget.calendar.onSelectionChanged, + ); if (canRaiseLongPress || canRaiseTap || canRaiseSelectionChanged) { - final List selectedAppointments = appointmentView == null || - isMoreTapped - ? _getSelectedAppointments(selectedDate) - : [ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ]; - final CalendarElement selectedElement = appointmentView == null - ? CalendarElement.calendarCell - : isMoreTapped + final List selectedAppointments = + appointmentView == null || isMoreTapped + ? _getSelectedAppointments(selectedDate) + : [ + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ]; + final CalendarElement selectedElement = + appointmentView == null + ? CalendarElement.calendarCell + : isMoreTapped ? CalendarElement.moreAppointmentRegion : CalendarElement.appointment; if (canRaiseTap) { - CalendarViewHelper.raiseCalendarTapCallback(widget.calendar, - selectedDate, selectedAppointments, selectedElement, null); + CalendarViewHelper.raiseCalendarTapCallback( + widget.calendar, + selectedDate, + selectedAppointments, + selectedElement, + null, + ); } else if (canRaiseLongPress) { - CalendarViewHelper.raiseCalendarLongPressCallback(widget.calendar, - selectedDate, selectedAppointments, selectedElement, null); + CalendarViewHelper.raiseCalendarLongPressCallback( + widget.calendar, + selectedDate, + selectedAppointments, + selectedElement, + null, + ); } _updatedSelectionChangedCallback( - canRaiseSelectionChanged, previousSelectedDate); + canRaiseSelectionChanged, + previousSelectedDate, + ); } return appointmentView; } @@ -9088,24 +10485,36 @@ class _CalendarViewState extends State<_CalendarView> /// Raise selection changed callback based on the arguments passed. void _updatedSelectionChangedCallback( - bool canRaiseSelectionChanged, DateTime? previousSelectedDate, - [CalendarResource? selectedResource, - int? previousSelectedResourceIndex]) { - final bool isMonthView = widget.view == CalendarView.month || + bool canRaiseSelectionChanged, + DateTime? previousSelectedDate, [ + CalendarResource? selectedResource, + int? previousSelectedResourceIndex, + ]) { + final bool isMonthView = + widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth; if (canRaiseSelectionChanged && ((isMonthView && !isSameDate( - previousSelectedDate, _selectionPainter!.selectedDate)) || + previousSelectedDate, + _selectionPainter!.selectedDate, + )) || (!isMonthView && !CalendarViewHelper.isSameTimeSlot( - previousSelectedDate, _selectionPainter!.selectedDate)) || + previousSelectedDate, + _selectionPainter!.selectedDate, + )) || (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view) && + widget.calendar.dataSource, + widget.view, + ) && _selectionPainter!.selectedResourceIndex != previousSelectedResourceIndex))) { CalendarViewHelper.raiseCalendarSelectionChangedCallback( - widget.calendar, _selectionPainter!.selectedDate, selectedResource); + widget.calendar, + _selectionPainter!.selectedDate, + selectedResource, + ); } } @@ -9128,16 +10537,21 @@ class _CalendarViewState extends State<_CalendarView> /// Returns the index of resource value associated with the selected calendar /// cell in timeline views. int _getSelectedResourceIndex( - double yPosition, double viewHeaderHeight, double timeLabelSize) { - final int resourceCount = widget.calendar.dataSource != null && - widget.calendar.dataSource!.resources != null - ? widget.calendar.dataSource!.resources!.length - : 0; + double yPosition, + double viewHeaderHeight, + double timeLabelSize, + ) { + final int resourceCount = + widget.calendar.dataSource != null && + widget.calendar.dataSource!.resources != null + ? widget.calendar.dataSource!.resources!.length + : 0; final double resourceItemHeight = CalendarViewHelper.getResourceItemHeight( - widget.calendar.resourceViewSettings.size, - widget.height - viewHeaderHeight - timeLabelSize, - widget.calendar.resourceViewSettings, - resourceCount); + widget.calendar.resourceViewSettings.size, + widget.height - viewHeaderHeight - timeLabelSize, + widget.calendar.resourceViewSettings, + resourceCount, + ); return (yPosition / resourceItemHeight).truncate(); } @@ -9147,23 +10561,28 @@ class _CalendarViewState extends State<_CalendarView> final double yDetails = position.dy; final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); if (yDetails < viewHeaderHeight) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on view header in timeline views. return CalendarDetails( - null, - _getTappedViewHeaderDate(position, widget.width), - CalendarElement.viewHeader, - null); + null, + _getTappedViewHeaderDate(position, widget.width), + CalendarElement.viewHeader, + null, + ); } double xPosition = _scrollController!.offset + xDetails; double yPosition = yDetails - viewHeaderHeight; final double timeLabelHeight = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); if (yPosition < timeLabelHeight) { /// Return null while the [getCalendarDetailsAtOffset] position placed on @@ -9176,24 +10595,31 @@ class _CalendarViewState extends State<_CalendarView> CalendarResource? calendarResource; if (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { yPosition += _timelineViewVerticalScrollController!.offset; _selectedResourceIndex = _getSelectedResourceIndex( - yPosition, viewHeaderHeight, timeLabelHeight); + yPosition, + viewHeaderHeight, + timeLabelHeight, + ); calendarResource = widget.calendar.dataSource!.resources![_selectedResourceIndex]; } if (_isRTL) { - xPosition = _scrollController!.offset + + xPosition = + _scrollController!.offset + (_scrollController!.position.viewportDimension - xDetails); - xPosition = (_scrollController!.position.viewportDimension + + xPosition = + (_scrollController!.position.viewportDimension + _scrollController!.position.maxScrollExtent) - xPosition; } - final AppointmentView? appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); + final AppointmentView? appointmentView = _appointmentLayout + .getAppointmentViewOnPoint(xPosition, yPosition); final DateTime getDate = _getDateFromPosition(xDetails, yDetails - viewHeaderHeight, 0)!; @@ -9202,20 +10628,33 @@ class _CalendarViewState extends State<_CalendarView> /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on calendar cell in timeline views. return CalendarDetails( - null, getDate, CalendarElement.calendarCell, calendarResource); + null, + getDate, + CalendarElement.calendarCell, + calendarResource, + ); } else { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on appointment in timeline views. - return CalendarDetails([ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ], getDate, CalendarElement.appointment, calendarResource); + return CalendarDetails( + [ + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ], + getDate, + CalendarElement.appointment, + calendarResource, + ); } } /// Handles the tap and long press related functions for timeline view. AppointmentView? _handleTouchOnTimeline( - TapUpDetails? tapDetails, LongPressStartDetails? longPressDetails) { + TapUpDetails? tapDetails, + LongPressStartDetails? longPressDetails, + ) { widget.removePicker(); final DateTime? previousSelectedDate = _selectionPainter!.selectedDate; double xDetails = 0, yDetails = 0; @@ -9230,7 +10669,9 @@ class _CalendarViewState extends State<_CalendarView> } final double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); if (yDetails < viewHeaderHeight) { if (isTapCallback) { @@ -9249,7 +10690,9 @@ class _CalendarViewState extends State<_CalendarView> double xPosition = _scrollController!.offset + xDetails; double yPosition = yDetails - viewHeaderHeight; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); if (yPosition < timeLabelWidth) { return null; @@ -9260,10 +10703,15 @@ class _CalendarViewState extends State<_CalendarView> CalendarResource? selectedResource; if (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { yPosition += _timelineViewVerticalScrollController!.offset; _selectedResourceIndex = _getSelectedResourceIndex( - yPosition, viewHeaderHeight, timeLabelWidth); + yPosition, + viewHeaderHeight, + timeLabelWidth, + ); selectedResource = widget.calendar.dataSource!.resources![_selectedResourceIndex]; } @@ -9273,15 +10721,17 @@ class _CalendarViewState extends State<_CalendarView> _selectionPainter!.selectedResourceIndex = _selectedResourceIndex; if (_isRTL) { - xPosition = _scrollController!.offset + + xPosition = + _scrollController!.offset + (_scrollController!.position.viewportDimension - xDetails); - xPosition = (_scrollController!.position.viewportDimension + + xPosition = + (_scrollController!.position.viewportDimension + _scrollController!.position.maxScrollExtent) - xPosition; } - final AppointmentView? appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); + final AppointmentView? appointmentView = _appointmentLayout + .getAppointmentViewOnPoint(xPosition, yPosition); if (appointmentView == null) { _drawSelection(xDetails, yPosition, timeLabelWidth); selectedDate = _selectionPainter!.selectedDate; @@ -9299,19 +10749,25 @@ class _CalendarViewState extends State<_CalendarView> widget.updateCalendarState(_updateCalendarStateDetails); final bool canRaiseTap = CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.calendar.onTap) && - isTapCallback; + widget.calendar.onTap, + ) && + isTapCallback; final bool canRaiseLongPress = CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.calendar.onLongPress) && - !isTapCallback; + widget.calendar.onLongPress, + ) && + !isTapCallback; final bool canRaiseSelectionChanged = CalendarViewHelper.shouldRaiseCalendarSelectionChangedCallback( - widget.calendar.onSelectionChanged); + widget.calendar.onSelectionChanged, + ); if (canRaiseLongPress || canRaiseTap || canRaiseSelectionChanged) { - final DateTime? selectedDate = - _getDateFromPosition(xDetails, yDetails - viewHeaderHeight, 0); + final DateTime? selectedDate = _getDateFromPosition( + xDetails, + yDetails - viewHeaderHeight, + 0, + ); /// Restrict the tap/long press callback while interact after /// the timeslots. @@ -9320,73 +10776,90 @@ class _CalendarViewState extends State<_CalendarView> } final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); if (appointmentView == null) { if (!CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - selectedDate, - timeInterval) || + widget.calendar.minDate, + widget.calendar.maxDate, + selectedDate, + timeInterval, + ) || (widget.view == CalendarView.timelineMonth && CalendarViewHelper.isDateInDateCollection( - widget.calendar.blackoutDates, selectedDate))) { + widget.calendar.blackoutDates, + selectedDate, + ))) { return null; } /// Restrict the callback, while selected region as disabled /// [TimeRegion]. if (!_isEnabledRegion( - xDetails, selectedDate, _selectedResourceIndex)) { + xDetails, + selectedDate, + _selectedResourceIndex, + )) { return null; } if (canRaiseTap) { CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, - selectedDate, - null, - CalendarElement.calendarCell, - selectedResource); + widget.calendar, + selectedDate, + null, + CalendarElement.calendarCell, + selectedResource, + ); } else if (canRaiseLongPress) { CalendarViewHelper.raiseCalendarLongPressCallback( - widget.calendar, - selectedDate, - null, - CalendarElement.calendarCell, - selectedResource); + widget.calendar, + selectedDate, + null, + CalendarElement.calendarCell, + selectedResource, + ); } _updatedSelectionChangedCallback( - canRaiseSelectionChanged, - previousSelectedDate, - selectedResource, - previousSelectedResourceIndex); + canRaiseSelectionChanged, + previousSelectedDate, + selectedResource, + previousSelectedResourceIndex, + ); } else { if (canRaiseTap) { CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, - selectedDate, - [ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ], - CalendarElement.appointment, - selectedResource); + widget.calendar, + selectedDate, + [ + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ], + CalendarElement.appointment, + selectedResource, + ); } else if (canRaiseLongPress) { CalendarViewHelper.raiseCalendarLongPressCallback( - widget.calendar, - selectedDate, - [ - CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) - ], - CalendarElement.appointment, - selectedResource); + widget.calendar, + selectedDate, + [ + CalendarViewHelper.getAppointmentDetail( + appointmentView.appointment!, + widget.calendar.dataSource, + ), + ], + CalendarElement.appointment, + selectedResource, + ); } _updatedSelectionChangedCallback( - canRaiseSelectionChanged, - previousSelectedDate, - selectedResource, - previousSelectedResourceIndex); + canRaiseSelectionChanged, + previousSelectedDate, + selectedResource, + previousSelectedResourceIndex, + ); } } @@ -9417,20 +10890,27 @@ class _CalendarViewState extends State<_CalendarView> final double yDetails = position.dy; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); - - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); - final double allDayHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); + + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); + final double allDayHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; // time ruler position on time slot scroll view. if (!_isRTL && xDetails <= timeLabelWidth && @@ -9462,10 +10942,11 @@ class _CalendarViewState extends State<_CalendarView> /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on view header in week and work week view. return CalendarDetails( - null, - _getTappedViewHeaderDate(position, widget.width), - CalendarElement.viewHeader, - null); + null, + _getTappedViewHeaderDate(position, widget.width), + CalendarElement.viewHeader, + null, + ); } else if (yDetails < viewHeaderHeight + allDayHeight) { /// Check the position in view header when [CalendarView] is day /// If RTL, view header placed at right side, @@ -9475,14 +10956,17 @@ class _CalendarViewState extends State<_CalendarView> (_isRTL && widget.width - xDetails <= timeLabelWidth)) && yDetails < CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view)) { + widget.calendar.viewHeaderHeight, + widget.view, + )) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on view header in day view. return CalendarDetails( - null, - _getTappedViewHeaderDate(position, widget.width), - CalendarElement.viewHeader, - null); + null, + _getTappedViewHeaderDate(position, widget.width), + CalendarElement.viewHeader, + null, + ); } else if ((!_isRTL && timeLabelWidth >= xDetails) || (_isRTL && xDetails > widget.width - timeLabelWidth)) { /// Return null while the [getCalendarDetailsAtOffset] position placed @@ -9492,12 +10976,14 @@ class _CalendarViewState extends State<_CalendarView> final double yPosition = yDetails - viewHeaderHeight; final AppointmentView? appointmentView = _getAllDayAppointmentOnPoint( - _updateCalendarStateDetails.allDayAppointmentViewCollection, - xDetails, - yPosition); + _updateCalendarStateDetails.allDayAppointmentViewCollection, + xDetails, + yPosition, + ); /// Check the count position tapped or not - bool isTappedOnCount = appointmentView != null && + bool isTappedOnCount = + appointmentView != null && _updateCalendarStateDetails.allDayPanelHeight > allDayHeight && yPosition > allDayHeight - kAllDayAppointmentHeight; DateTime? selectedDate; @@ -9511,14 +10997,19 @@ class _CalendarViewState extends State<_CalendarView> // boolean property sets true. if (isTappedOnCount && selectedDate != null) { final int currentSelectedIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, selectedDate); + widget.visibleDates, + selectedDate, + ); if (currentSelectedIndex != -1) { moreRegionAppointments = []; - for (int i = 0; - i < - _updateCalendarStateDetails - .allDayAppointmentViewCollection.length; - i++) { + for ( + int i = 0; + i < + _updateCalendarStateDetails + .allDayAppointmentViewCollection + .length; + i++ + ) { final AppointmentView currentView = _updateCalendarStateDetails.allDayAppointmentViewCollection[i]; if (currentView.appointment == null) { @@ -9548,16 +11039,21 @@ class _CalendarViewState extends State<_CalendarView> _updateCalendarStateDetails.allDayPanelHeight > allDayHeight && yPosition > allDayHeight - kAllDayAppointmentHeight) { final int currentSelectedIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, selectedDate); + widget.visibleDates, + selectedDate, + ); if (currentSelectedIndex != -1) { moreRegionAppointments = []; final List selectedIndexAppointment = []; - for (int i = 0; - i < - _updateCalendarStateDetails - .allDayAppointmentViewCollection.length; - i++) { + for ( + int i = 0; + i < + _updateCalendarStateDetails + .allDayAppointmentViewCollection + .length; + i++ + ) { final AppointmentView currentView = _updateCalendarStateDetails.allDayAppointmentViewCollection[i]; if (currentView.appointment == null) { @@ -9573,13 +11069,18 @@ class _CalendarViewState extends State<_CalendarView> int maxPosition = 0; if (selectedIndexAppointment.isNotEmpty) { - maxPosition = selectedIndexAppointment - .reduce((AppointmentView currentAppView, - AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + maxPosition = + selectedIndexAppointment + .reduce( + ( + AppointmentView currentAppView, + AppointmentView nextAppView, + ) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; } final int endAppointmentPosition = allDayHeight ~/ kAllDayAppointmentHeight; @@ -9595,32 +11096,46 @@ class _CalendarViewState extends State<_CalendarView> appointmentView.position + 1 >= appointmentView.maxPositions)) { final List appointmentDetails = [ CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) + appointmentView.appointment!, + widget.calendar.dataSource, + ), ]; /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on appointments in day, week and workweek view. return CalendarDetails( - appointmentDetails, null, CalendarElement.appointment, null); + appointmentDetails, + null, + CalendarElement.appointment, + null, + ); } else if (isTappedOnCount) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on more appointment region in day, week and workweek /// view. return CalendarDetails( - widget.calendar.dataSource != null && - !AppointmentHelper.isCalendarAppointment( - widget.calendar.dataSource!) - ? CalendarViewHelper.getCustomAppointments( - moreRegionAppointments, widget.calendar.dataSource) - : moreRegionAppointments, - selectedDate, - CalendarElement.moreAppointmentRegion, - null); + widget.calendar.dataSource != null && + !AppointmentHelper.isCalendarAppointment( + widget.calendar.dataSource!, + ) + ? CalendarViewHelper.getCustomAppointments( + moreRegionAppointments, + widget.calendar.dataSource, + ) + : moreRegionAppointments, + selectedDate, + CalendarElement.moreAppointmentRegion, + null, + ); } else if (appointmentView == null) { /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on all day panel in day, week and work week view. return CalendarDetails( - null, selectedDate, CalendarElement.allDayPanel, null); + null, + selectedDate, + CalendarElement.allDayPanel, + null, + ); } return null; @@ -9628,50 +11143,65 @@ class _CalendarViewState extends State<_CalendarView> double yPosition = yDetails - viewHeaderHeight - allDayHeight + _scrollController!.offset; - final AppointmentView? appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xDetails, yPosition); + final AppointmentView? appointmentView = _appointmentLayout + .getAppointmentViewOnPoint(xDetails, yPosition); if (appointmentView == null) { /// Remove the scroll position for internally handles the scroll position /// in _getDateFromPosition method yPosition = yPosition - _scrollController!.offset; final DateTime? selectedDate = _getDateFromPosition( - !_isRTL ? xDetails - timeLabelWidth : xDetails, - yPosition, - timeLabelWidth); + !_isRTL ? xDetails - timeLabelWidth : xDetails, + yPosition, + timeLabelWidth, + ); /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on calendar cell in day, week and work week view. return CalendarDetails( - null, selectedDate, CalendarElement.calendarCell, null); + null, + selectedDate, + CalendarElement.calendarCell, + null, + ); } else { final List appointmentDetails = [ CalendarViewHelper.getAppointmentDetail( - appointmentView.appointment!, widget.calendar.dataSource) + appointmentView.appointment!, + widget.calendar.dataSource, + ), ]; /// Return calendar details while the [getCalendarDetailsAtOffset] /// position placed on appointments in day, week and work week view. return CalendarDetails( - appointmentDetails, null, CalendarElement.appointment, null); + appointmentDetails, + null, + CalendarElement.appointment, + null, + ); } } /// Handles the tap and long press related functions for day, week /// work week views. AppointmentView? _handleTouchOnDayView( - TapUpDetails? tapDetails, LongPressStartDetails? longPressDetails) { + TapUpDetails? tapDetails, + LongPressStartDetails? longPressDetails, + ) { widget.removePicker(); final DateTime? previousSelectedDate = _selectionPainter!.selectedDate; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); double xDetails = 0, yDetails = 0; bool isTappedCallback = false; final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); if (tapDetails != null) { isTappedCallback = true; xDetails = tapDetails.localPosition.dx; @@ -9691,15 +11221,21 @@ class _CalendarViewState extends State<_CalendarView> CalendarElement targetElement = CalendarElement.viewHeader; DateTime? selectedDate = _updateCalendarStateDetails.selectedDate; final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); - - final double viewHeaderHeight = isDayView - ? 0 - : CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); - final double allDayHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); + + final double viewHeaderHeight = + isDayView + ? 0 + : CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ); + final double allDayHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; if (!_isRTL && xDetails <= timeLabelWidth && yDetails > viewHeaderHeight + allDayHeight) { @@ -9737,7 +11273,9 @@ class _CalendarViewState extends State<_CalendarView> (_isRTL && widget.width - xDetails <= timeLabelWidth)) && yDetails < CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view)) { + widget.calendar.viewHeaderHeight, + widget.view, + )) { if (isTappedCallback) { _handleOnTapForViewHeader(tapDetails!, widget.width); } else if (!isTappedCallback) { @@ -9755,23 +11293,29 @@ class _CalendarViewState extends State<_CalendarView> final double yPosition = yDetails - viewHeaderHeight; final AppointmentView? appointmentView = _getAllDayAppointmentOnPoint( - _updateCalendarStateDetails.allDayAppointmentViewCollection, - xDetails, - yPosition); + _updateCalendarStateDetails.allDayAppointmentViewCollection, + xDetails, + yPosition, + ); if (appointmentView == null) { targetElement = CalendarElement.allDayPanel; if (isTappedCallback) { - selectedDate = - _getTappedViewHeaderDate(tapDetails!.localPosition, widget.width); + selectedDate = _getTappedViewHeaderDate( + tapDetails!.localPosition, + widget.width, + ); } else { selectedDate = _getTappedViewHeaderDate( - longPressDetails!.localPosition, widget.width); + longPressDetails!.localPosition, + widget.width, + ); } } /// Check the count position tapped or not - bool isTappedOnCount = appointmentView != null && + bool isTappedOnCount = + appointmentView != null && _updateCalendarStateDetails.allDayPanelHeight > allDayHeight && yPosition > allDayHeight - kAllDayAppointmentHeight; @@ -9790,15 +11334,20 @@ class _CalendarViewState extends State<_CalendarView> _updateCalendarStateDetails.allDayPanelHeight > allDayHeight && yPosition > allDayHeight - kAllDayAppointmentHeight) { final int currentSelectedIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, selectedDate); + widget.visibleDates, + selectedDate, + ); if (currentSelectedIndex != -1) { final List selectedIndexAppointment = []; - for (int i = 0; - i < - _updateCalendarStateDetails - .allDayAppointmentViewCollection.length; - i++) { + for ( + int i = 0; + i < + _updateCalendarStateDetails + .allDayAppointmentViewCollection + .length; + i++ + ) { final AppointmentView currentView = _updateCalendarStateDetails.allDayAppointmentViewCollection[i]; if (currentView.appointment == null) { @@ -9812,13 +11361,18 @@ class _CalendarViewState extends State<_CalendarView> int maxPosition = 0; if (selectedIndexAppointment.isNotEmpty) { - maxPosition = selectedIndexAppointment - .reduce((AppointmentView currentAppView, - AppointmentView nextAppView) => - currentAppView.maxPositions > nextAppView.maxPositions - ? currentAppView - : nextAppView) - .maxPositions; + maxPosition = + selectedIndexAppointment + .reduce( + ( + AppointmentView currentAppView, + AppointmentView nextAppView, + ) => + currentAppView.maxPositions > nextAppView.maxPositions + ? currentAppView + : nextAppView, + ) + .maxPositions; } final int endAppointmentPosition = allDayHeight ~/ kAllDayAppointmentHeight; @@ -9833,15 +11387,17 @@ class _CalendarViewState extends State<_CalendarView> _updateCalendarStateDetails.allDayPanelHeight <= allDayHeight || appointmentView.position + 1 >= appointmentView.maxPositions)) { if ((!CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - appointmentView.appointment!.actualStartTime, - timeInterval) || + widget.calendar.minDate, + widget.calendar.maxDate, + appointmentView.appointment!.actualStartTime, + timeInterval, + ) || !CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - appointmentView.appointment!.actualEndTime, - timeInterval)) && + widget.calendar.minDate, + widget.calendar.maxDate, + appointmentView.appointment!.actualEndTime, + timeInterval, + )) && !appointmentView.appointment!.isSpanned) { return null; } @@ -9870,20 +11426,27 @@ class _CalendarViewState extends State<_CalendarView> selectedAppointmentView = appointmentView; } else { - final double yPosition = yDetails - + final double yPosition = + yDetails - viewHeaderHeight - allDayHeight + _scrollController!.offset; - final AppointmentView? appointmentView = - _appointmentLayout.getAppointmentViewOnPoint(xDetails, yPosition); + final AppointmentView? appointmentView = _appointmentLayout + .getAppointmentViewOnPoint(xDetails, yPosition); _allDaySelectionNotifier.value = null; if (appointmentView == null) { if (_isRTL) { - _drawSelection(xDetails, yDetails - viewHeaderHeight - allDayHeight, - timeLabelWidth); + _drawSelection( + xDetails, + yDetails - viewHeaderHeight - allDayHeight, + timeLabelWidth, + ); } else { - _drawSelection(xDetails - timeLabelWidth, - yDetails - viewHeaderHeight - allDayHeight, timeLabelWidth); + _drawSelection( + xDetails - timeLabelWidth, + yDetails - viewHeaderHeight - allDayHeight, + timeLabelWidth, + ); } targetElement = CalendarElement.calendarCell; } else { @@ -9902,16 +11465,20 @@ class _CalendarViewState extends State<_CalendarView> } widget.updateCalendarState(_updateCalendarStateDetails); - final bool canRaiseTap = CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.calendar.onTap) && + final bool canRaiseTap = + CalendarViewHelper.shouldRaiseCalendarTapCallback( + widget.calendar.onTap, + ) && isTappedCallback; final bool canRaiseLongPress = CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.calendar.onLongPress) && - !isTappedCallback; + widget.calendar.onLongPress, + ) && + !isTappedCallback; final bool canRaiseSelectionChanged = CalendarViewHelper.shouldRaiseCalendarSelectionChangedCallback( - widget.calendar.onSelectionChanged); + widget.calendar.onSelectionChanged, + ); if (canRaiseLongPress || canRaiseTap || canRaiseSelectionChanged) { final double yPosition = yDetails - viewHeaderHeight - allDayHeight; if (_selectionPainter!.selectedDate != null && @@ -9921,9 +11488,10 @@ class _CalendarViewState extends State<_CalendarView> /// In LTR, remove the time ruler width value from the /// touch x position while calculate the selected date value. selectedDate = _getDateFromPosition( - !_isRTL ? xDetails - timeLabelWidth : xDetails, - yPosition, - timeLabelWidth); + !_isRTL ? xDetails - timeLabelWidth : xDetails, + yPosition, + timeLabelWidth, + ); /// Restrict the tap/long press callback while interact after /// the timeslots. @@ -9932,10 +11500,11 @@ class _CalendarViewState extends State<_CalendarView> } if (!CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - selectedDate, - timeInterval)) { + widget.calendar.minDate, + widget.calendar.maxDate, + selectedDate, + timeInterval, + )) { return null; } @@ -9943,68 +11512,94 @@ class _CalendarViewState extends State<_CalendarView> /// [TimeRegion]. if (targetElement == CalendarElement.calendarCell && !_isEnabledRegion( - yPosition, selectedDate, _selectedResourceIndex)) { + yPosition, + selectedDate, + _selectedResourceIndex, + )) { return null; } if (canRaiseTap) { CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, - _selectionPainter!.selectedDate, - selectedAppointments, - targetElement, - null); + widget.calendar, + _selectionPainter!.selectedDate, + selectedAppointments, + targetElement, + null, + ); } else if (canRaiseLongPress) { CalendarViewHelper.raiseCalendarLongPressCallback( - widget.calendar, - _selectionPainter!.selectedDate, - selectedAppointments, - targetElement, - null); + widget.calendar, + _selectionPainter!.selectedDate, + selectedAppointments, + targetElement, + null, + ); } _updatedSelectionChangedCallback( - canRaiseSelectionChanged, previousSelectedDate); + canRaiseSelectionChanged, + previousSelectedDate, + ); } else if (selectedAppointment != null) { selectedAppointments = [ CalendarViewHelper.getAppointmentDetail( - selectedAppointment, widget.calendar.dataSource) + selectedAppointment, + widget.calendar.dataSource, + ), ]; /// In LTR, remove the time ruler width value from the /// touch x position while calculate the selected date value. selectedDate = _getDateFromPosition( - !_isRTL ? xDetails - timeLabelWidth : xDetails, - yPosition, - timeLabelWidth); + !_isRTL ? xDetails - timeLabelWidth : xDetails, + yPosition, + timeLabelWidth, + ); if (canRaiseTap) { CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, - selectedDate, - selectedAppointments, - CalendarElement.appointment, - null); + widget.calendar, + selectedDate, + selectedAppointments, + CalendarElement.appointment, + null, + ); } else if (canRaiseLongPress) { CalendarViewHelper.raiseCalendarLongPressCallback( - widget.calendar, - selectedDate, - selectedAppointments, - CalendarElement.appointment, - null); + widget.calendar, + selectedDate, + selectedAppointments, + CalendarElement.appointment, + null, + ); } _updatedSelectionChangedCallback( - canRaiseSelectionChanged, previousSelectedDate); + canRaiseSelectionChanged, + previousSelectedDate, + ); } else if (selectedDate != null && targetElement == CalendarElement.allDayPanel) { if (canRaiseTap) { CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, selectedDate, null, targetElement, null); + widget.calendar, + selectedDate, + null, + targetElement, + null, + ); } else if (canRaiseLongPress) { CalendarViewHelper.raiseCalendarLongPressCallback( - widget.calendar, selectedDate, null, targetElement, null); + widget.calendar, + selectedDate, + null, + targetElement, + null, + ); } _updatedSelectionChangedCallback( - canRaiseSelectionChanged, previousSelectedDate); + canRaiseSelectionChanged, + previousSelectedDate, + ); } } @@ -10022,27 +11617,33 @@ class _CalendarViewState extends State<_CalendarView> } final double timeIntervalSize = _getTimeIntervalHeight( - widget.calendar, - widget.view, - widget.width, - widget.height, - widget.visibleDates.length, - widget.isMobilePlatform); + widget.calendar, + widget.view, + widget.width, + widget.height, + widget.visibleDates.length, + widget.isMobilePlatform, + ); - final double minuteHeight = timeIntervalSize / + final double minuteHeight = + timeIntervalSize / CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); final Duration startDuration = Duration( - hours: widget.calendar.timeSlotViewSettings.startHour.toInt(), - minutes: ((widget.calendar.timeSlotViewSettings.startHour - - widget.calendar.timeSlotViewSettings.startHour.toInt()) * - 60) - .toInt()); + hours: widget.calendar.timeSlotViewSettings.startHour.toInt(), + minutes: + ((widget.calendar.timeSlotViewSettings.startHour - + widget.calendar.timeSlotViewSettings.startHour.toInt()) * + 60) + .toInt(), + ); int minutes; if (CalendarViewHelper.isTimelineView(widget.view)) { final double viewWidth = _timeIntervalHeight * _horizontalLinesCount!; if (_isRTL) { - minutes = ((_scrollController!.offset + + minutes = + ((_scrollController!.offset + (_scrollController!.position.viewportDimension - y)) % viewWidth) ~/ minuteHeight; @@ -10053,11 +11654,18 @@ class _CalendarViewState extends State<_CalendarView> minutes = (_scrollController!.offset + y) ~/ minuteHeight; } - final DateTime date = DateTime(selectedDate.year, selectedDate.month, - selectedDate.day, 0, minutes + startDuration.inMinutes); + final DateTime date = DateTime( + selectedDate.year, + selectedDate.month, + selectedDate.day, + 0, + minutes + startDuration.inMinutes, + ); bool isValidRegion = true; final bool isResourcesEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); for (int i = 0; i < widget.regions!.length; i++) { final CalendarTimeRegion region = widget.regions![i]; if (region.actualStartTime.isAfter(date) || @@ -10071,8 +11679,9 @@ class _CalendarViewState extends State<_CalendarView> resourceIndex != -1 && region.resourceIds != null && region.resourceIds!.isNotEmpty && - !region.resourceIds! - .contains(widget.resourceCollection![resourceIndex].id)) { + !region.resourceIds!.contains( + widget.resourceCollection![resourceIndex].id, + )) { continue; } @@ -10091,8 +11700,12 @@ class _CalendarViewState extends State<_CalendarView> } /// Returns the default time interval width for timeline views. - double _getTimeIntervalWidth(double timeIntervalHeight, CalendarView view, - double width, bool isMobilePlatform) { + double _getTimeIntervalWidth( + double timeIntervalHeight, + CalendarView view, + double width, + bool isMobilePlatform, + ) { if (timeIntervalHeight >= 0) { return timeIntervalHeight; } @@ -10108,44 +11721,55 @@ class _CalendarViewState extends State<_CalendarView> /// Returns the time interval width based on property value, also arrange the /// time slots into the view port size. double _getTimeIntervalHeight( - SfCalendar calendar, - CalendarView view, - double width, - double height, - int visibleDatesCount, - bool isMobilePlatform) { + SfCalendar calendar, + CalendarView view, + double width, + double height, + int visibleDatesCount, + bool isMobilePlatform, + ) { final bool isTimelineView = CalendarViewHelper.isTimelineView(view); final bool isDayView = CalendarViewHelper.isDayView( - view, - calendar.timeSlotViewSettings.numberOfDaysInView, - calendar.timeSlotViewSettings.nonWorkingDays, - calendar.monthViewSettings.numberOfWeeksInView); - double timeIntervalHeight = isTimelineView - ? _getTimeIntervalWidth(calendar.timeSlotViewSettings.timeIntervalWidth, - view, width, isMobilePlatform) - : calendar.timeSlotViewSettings.timeIntervalHeight; + view, + calendar.timeSlotViewSettings.numberOfDaysInView, + calendar.timeSlotViewSettings.nonWorkingDays, + calendar.monthViewSettings.numberOfWeeksInView, + ); + double timeIntervalHeight = + isTimelineView + ? _getTimeIntervalWidth( + calendar.timeSlotViewSettings.timeIntervalWidth, + view, + width, + isMobilePlatform, + ) + : calendar.timeSlotViewSettings.timeIntervalHeight; if (!_isAutoTimeIntervalHeight(calendar, isTimelineView)) { return timeIntervalHeight; } - double viewHeaderHeight = - CalendarViewHelper.getViewHeaderHeight(calendar.viewHeaderHeight, view); + double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( + calendar.viewHeaderHeight, + view, + ); double allDayViewHeight = 0; final bool isCurrentView = _updateCalendarStateDetails.currentViewVisibleDates == - widget.visibleDates; + widget.visibleDates; if (isDayView) { if (isCurrentView) { - allDayViewHeight = _kAllDayLayoutHeight > viewHeaderHeight && - _updateCalendarStateDetails.allDayPanelHeight > viewHeaderHeight - ? _updateCalendarStateDetails.allDayPanelHeight > - _kAllDayLayoutHeight - ? _kAllDayLayoutHeight - : _updateCalendarStateDetails.allDayPanelHeight - : viewHeaderHeight; + allDayViewHeight = + _kAllDayLayoutHeight > viewHeaderHeight && + _updateCalendarStateDetails.allDayPanelHeight > + viewHeaderHeight + ? _updateCalendarStateDetails.allDayPanelHeight > + _kAllDayLayoutHeight + ? _kAllDayLayoutHeight + : _updateCalendarStateDetails.allDayPanelHeight + : viewHeaderHeight; if (allDayViewHeight < _updateCalendarStateDetails.allDayPanelHeight) { allDayViewHeight += kAllDayAppointmentHeight; } @@ -10165,9 +11789,12 @@ class _CalendarViewState extends State<_CalendarView> case CalendarView.day: case CalendarView.week: case CalendarView.workWeek: - timeIntervalHeight = (height - allDayViewHeight - viewHeaderHeight) / + timeIntervalHeight = + (height - allDayViewHeight - viewHeaderHeight) / CalendarViewHelper.getHorizontalLinesCount( - calendar.timeSlotViewSettings, view); + calendar.timeSlotViewSettings, + view, + ); break; case CalendarView.timelineDay: case CalendarView.timelineWeek: @@ -10176,11 +11803,17 @@ class _CalendarViewState extends State<_CalendarView> { final double horizontalLinesCount = CalendarViewHelper.getHorizontalLinesCount( - calendar.timeSlotViewSettings, view); + calendar.timeSlotViewSettings, + view, + ); timeIntervalHeight = width / (horizontalLinesCount * visibleDatesCount); if (!_isValidWidth( - width, calendar, visibleDatesCount, horizontalLinesCount)) { + width, + calendar, + visibleDatesCount, + horizontalLinesCount, + )) { /// we have used 40 as a default time interval height for timeline /// view when the time interval height set for auto time /// interval height. @@ -10198,8 +11831,12 @@ class _CalendarViewState extends State<_CalendarView> /// checks whether the width can afford the line count or else creates a /// scrollable width - bool _isValidWidth(double screenWidth, SfCalendar calendar, - int visibleDatesCount, double horizontalLinesCount) { + bool _isValidWidth( + double screenWidth, + SfCalendar calendar, + int visibleDatesCount, + double horizontalLinesCount, + ) { const int offSetValue = 10; final double tempWidth = visibleDatesCount * offSetValue * horizontalLinesCount; @@ -10217,27 +11854,41 @@ class _CalendarViewState extends State<_CalendarView> _getTappedViewHeaderDate(details.localPosition, width)!; _handleViewHeaderTapNavigation(tappedDate); if (!CalendarViewHelper.shouldRaiseCalendarTapCallback( - widget.calendar.onTap)) { + widget.calendar.onTap, + )) { return; } CalendarViewHelper.raiseCalendarTapCallback( - widget.calendar, tappedDate, null, CalendarElement.viewHeader, null); + widget.calendar, + tappedDate, + null, + CalendarElement.viewHeader, + null, + ); } //// Handles the on long press callback for view header void _handleOnLongPressForViewHeader( - LongPressStartDetails details, double width) { + LongPressStartDetails details, + double width, + ) { final DateTime tappedDate = _getTappedViewHeaderDate(details.localPosition, width)!; _handleViewHeaderTapNavigation(tappedDate); if (!CalendarViewHelper.shouldRaiseCalendarLongPressCallback( - widget.calendar.onLongPress)) { + widget.calendar.onLongPress, + )) { return; } CalendarViewHelper.raiseCalendarLongPressCallback( - widget.calendar, tappedDate, null, CalendarElement.viewHeader, null); + widget.calendar, + tappedDate, + null, + CalendarElement.viewHeader, + null, + ); } void _handleViewHeaderTapNavigation(DateTime date) { @@ -10249,10 +11900,15 @@ class _CalendarViewState extends State<_CalendarView> } if (!isDateWithInDateRange( - widget.calendar.minDate, widget.calendar.maxDate, date) || + widget.calendar.minDate, + widget.calendar.maxDate, + date, + ) || (widget.controller.view == CalendarView.timelineMonth && CalendarViewHelper.isDateInDateCollection( - widget.blackoutDates, date))) { + widget.blackoutDates, + date, + ))) { return; } @@ -10269,13 +11925,16 @@ class _CalendarViewState extends State<_CalendarView> DateTime? _getTappedViewHeaderDate(Offset localPosition, double width) { int index = 0; final double timeLabelViewWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); final int visibleDatesLength = widget.visibleDates.length; final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); if (!CalendarViewHelper.isTimelineView(widget.view)) { double cellWidth = 0; if (widget.view != CalendarView.month) { @@ -10286,9 +11945,10 @@ class _CalendarViewState extends State<_CalendarView> if (isDayView) { index = 0; } else { - index = ((localPosition.dx - (_isRTL ? 0 : timeLabelViewWidth)) / - cellWidth) - .truncate(); + index = + ((localPosition.dx - (_isRTL ? 0 : timeLabelViewWidth)) / + cellWidth) + .truncate(); } } else { cellWidth = width / DateTime.daysPerWeek; @@ -10309,13 +11969,14 @@ class _CalendarViewState extends State<_CalendarView> return widget.visibleDates[index]; } else { - index = ((_scrollController!.offset + - (_isRTL - ? _scrollController!.position.viewportDimension - - localPosition.dx - : localPosition.dx)) / - _getSingleViewWidthForTimeLineView(this)) - .truncate(); + index = + ((_scrollController!.offset + + (_isRTL + ? _scrollController!.position.viewportDimension - + localPosition.dx + : localPosition.dx)) / + _getSingleViewWidthForTimeLineView(this)) + .truncate(); if (index < 0 || index >= visibleDatesLength) { return null; @@ -10424,14 +12085,18 @@ class _CalendarViewState extends State<_CalendarView> } } - void _updateHoveringForViewHeader(Offset localPosition, double xPosition, - double yPosition, double viewHeaderHeight) { + void _updateHoveringForViewHeader( + Offset localPosition, + double xPosition, + double yPosition, + double viewHeaderHeight, + ) { if (widget.calendar.onTap == null && widget.calendar.onLongPress == null) { final bool isViewNavigationEnabled = widget.calendar.allowViewNavigation && - widget.view != CalendarView.month && - widget.view != CalendarView.day && - widget.view != CalendarView.timelineDay; + widget.view != CalendarView.month && + widget.view != CalendarView.day && + widget.view != CalendarView.timelineDay; if (!isViewNavigationEnabled) { _removeAllWidgetHovering(); return; @@ -10473,12 +12138,14 @@ class _CalendarViewState extends State<_CalendarView> } final DateTime? hoverDate = _getTappedViewHeaderDate( - Offset( - CalendarViewHelper.isTimelineView(widget.view) - ? localPosition.dx - : xPosition, - yPosition), - widget.width); + Offset( + CalendarViewHelper.isTimelineView(widget.view) + ? localPosition.dx + : xPosition, + yPosition, + ), + widget.width, + ); // Remove the hovering when the position not in cell regions. if (hoverDate == null) { @@ -10488,7 +12155,10 @@ class _CalendarViewState extends State<_CalendarView> } if (!isDateWithInDateRange( - widget.calendar.minDate, widget.calendar.maxDate, hoverDate)) { + widget.calendar.minDate, + widget.calendar.maxDate, + hoverDate, + )) { _removeViewHeaderHovering(); return; @@ -10496,7 +12166,9 @@ class _CalendarViewState extends State<_CalendarView> if (widget.view == CalendarView.timelineMonth && CalendarViewHelper.isDateInDateCollection( - widget.blackoutDates, hoverDate)) { + widget.blackoutDates, + hoverDate, + )) { _removeViewHeaderHovering(); return; @@ -10555,9 +12227,13 @@ class _CalendarViewState extends State<_CalendarView> } } - void _updateMouseCursorForAppointment(AppointmentView? appointmentView, - double xPosition, double yPosition, bool isTimelineViews, - {bool isAllDayPanel = false}) { + void _updateMouseCursorForAppointment( + AppointmentView? appointmentView, + double xPosition, + double yPosition, + bool isTimelineViews, { + bool isAllDayPanel = false, + }) { _hoveringAppointmentView = appointmentView; if (!widget.calendar.allowAppointmentResize || (widget.view == CalendarView.month && @@ -10580,56 +12256,74 @@ class _CalendarViewState extends State<_CalendarView> if (isAllDayPanel || (widget.view == CalendarView.month || isTimelineViews)) { - final bool isMonthView = widget.view == CalendarView.month || + final bool isMonthView = + widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth; - final DateTime viewStartDate = - AppointmentHelper.convertToStartTime(widget.visibleDates[0]); + final DateTime viewStartDate = AppointmentHelper.convertToStartTime( + widget.visibleDates[0], + ); final DateTime viewEndDate = AppointmentHelper.convertToEndTime( - widget.visibleDates[widget.visibleDates.length - 1]); + widget.visibleDates[widget.visibleDates.length - 1], + ); final DateTime appStartTime = appointmentView.appointment!.exactStartTime; final DateTime appEndTime = appointmentView.appointment!.exactEndTime; final bool canAddForwardSpanIcon = AppointmentHelper.canAddForwardSpanIcon( - appStartTime, appEndTime, viewStartDate, viewEndDate); + appStartTime, + appEndTime, + viewStartDate, + viewEndDate, + ); final bool canAddBackwardSpanIcon = AppointmentHelper.canAddBackwardSpanIcon( - appStartTime, appEndTime, viewStartDate, viewEndDate); + appStartTime, + appEndTime, + viewStartDate, + viewEndDate, + ); final DateTime appointmentStartTime = appointmentView.appointment!.isAllDay ? AppointmentHelper.convertToStartTime( - appointmentView.appointment!.actualStartTime) + appointmentView.appointment!.actualStartTime, + ) : appointmentView.appointment!.actualStartTime; - final DateTime appointmentEndTime = appointmentView.appointment!.isAllDay - ? AppointmentHelper.convertToEndTime( - appointmentView.appointment!.actualEndTime) - : appointmentView.appointment!.actualEndTime; + final DateTime appointmentEndTime = + appointmentView.appointment!.isAllDay + ? AppointmentHelper.convertToEndTime( + appointmentView.appointment!.actualEndTime, + ) + : appointmentView.appointment!.actualEndTime; final DateTime appointmentExactStartTime = appointmentView.appointment!.isAllDay ? AppointmentHelper.convertToStartTime( - appointmentView.appointment!.exactStartTime) + appointmentView.appointment!.exactStartTime, + ) : appointmentView.appointment!.exactStartTime; final DateTime appointmentExactEndTime = appointmentView.appointment!.isAllDay ? AppointmentHelper.convertToEndTime( - appointmentView.appointment!.exactEndTime) + appointmentView.appointment!.exactEndTime, + ) : appointmentView.appointment!.exactEndTime; if (xPosition >= appointmentView.appointmentRect!.left && xPosition <= appointmentView.appointmentRect!.left + padding && ((isMonthView && isSameDate( - _isRTL ? appointmentEndTime : appointmentStartTime, - _isRTL - ? appointmentExactEndTime - : appointmentExactStartTime)) || + _isRTL ? appointmentEndTime : appointmentStartTime, + _isRTL + ? appointmentExactEndTime + : appointmentExactStartTime, + )) || (!isMonthView && CalendarViewHelper.isSameTimeSlot( - _isRTL ? appointmentEndTime : appointmentStartTime, - _isRTL - ? appointmentExactEndTime - : appointmentExactStartTime))) && + _isRTL ? appointmentEndTime : appointmentStartTime, + _isRTL + ? appointmentExactEndTime + : appointmentExactStartTime, + ))) && ((_isRTL && !canAddForwardSpanIcon) || (!_isRTL && !canAddBackwardSpanIcon))) { setState(() { @@ -10639,16 +12333,18 @@ class _CalendarViewState extends State<_CalendarView> xPosition >= appointmentView.appointmentRect!.right - padding && ((isMonthView && isSameDate( - _isRTL ? appointmentStartTime : appointmentEndTime, - _isRTL - ? appointmentExactStartTime - : appointmentExactEndTime)) || + _isRTL ? appointmentStartTime : appointmentEndTime, + _isRTL + ? appointmentExactStartTime + : appointmentExactEndTime, + )) || (!isMonthView && CalendarViewHelper.isSameTimeSlot( - _isRTL ? appointmentStartTime : appointmentEndTime, - _isRTL - ? appointmentExactStartTime - : appointmentExactEndTime))) && + _isRTL ? appointmentStartTime : appointmentEndTime, + _isRTL + ? appointmentExactStartTime + : appointmentExactEndTime, + ))) && ((_isRTL && !canAddBackwardSpanIcon) || (!_isRTL && !canAddForwardSpanIcon))) { setState(() { @@ -10663,16 +12359,18 @@ class _CalendarViewState extends State<_CalendarView> if (yPosition >= appointmentView.appointmentRect!.top && yPosition <= appointmentView.appointmentRect!.top + padding && CalendarViewHelper.isSameTimeSlot( - appointmentView.appointment!.actualStartTime, - appointmentView.appointment!.exactStartTime)) { + appointmentView.appointment!.actualStartTime, + appointmentView.appointment!.exactStartTime, + )) { setState(() { _mouseCursor = SystemMouseCursors.resizeUp; }); } else if (yPosition <= appointmentView.appointmentRect!.bottom && yPosition >= appointmentView.appointmentRect!.bottom - padding && CalendarViewHelper.isSameTimeSlot( - appointmentView.appointment!.actualEndTime, - appointmentView.appointment!.exactEndTime)) { + appointmentView.appointment!.actualEndTime, + appointmentView.appointment!.exactEndTime, + )) { setState(() { _mouseCursor = SystemMouseCursors.resizeDown; }); @@ -10696,17 +12394,23 @@ class _CalendarViewState extends State<_CalendarView> final RenderBox box = context.findRenderObject()! as RenderBox; final Offset localPosition = box.globalToLocal(globalPosition); double viewHeaderHeight = CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view); + widget.calendar.viewHeaderHeight, + widget.view, + ); final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - widget.calendar.timeSlotViewSettings.timeRulerSize, widget.view); - double allDayHeight = _isExpanded - ? _updateCalendarStateDetails.allDayPanelHeight - : _allDayHeight; + widget.calendar.timeSlotViewSettings.timeRulerSize, + widget.view, + ); + double allDayHeight = + _isExpanded + ? _updateCalendarStateDetails.allDayPanelHeight + : _allDayHeight; final bool isDayView = CalendarViewHelper.isDayView( - widget.view, - widget.calendar.timeSlotViewSettings.numberOfDaysInView, - widget.calendar.timeSlotViewSettings.nonWorkingDays, - widget.calendar.monthViewSettings.numberOfWeeksInView); + widget.view, + widget.calendar.timeSlotViewSettings.numberOfDaysInView, + widget.calendar.timeSlotViewSettings.nonWorkingDays, + widget.calendar.monthViewSettings.numberOfWeeksInView, + ); /// All day panel and view header are arranged horizontally, /// so get the maximum value from all day height and view header height and @@ -10735,25 +12439,35 @@ class _CalendarViewState extends State<_CalendarView> _updateHoveringForAllDayPanel(localPosition.dx, localPosition.dy); final AppointmentView? appointment = _getAllDayAppointmentOnPoint( - _updateCalendarStateDetails.allDayAppointmentViewCollection, - localPosition.dx, - localPosition.dy); - _updateMouseCursorForAppointment(appointment, localPosition.dx, - localPosition.dy, isTimelineViews, - isAllDayPanel: true); + _updateCalendarStateDetails.allDayAppointmentViewCollection, + localPosition.dx, + localPosition.dy, + ); + _updateMouseCursorForAppointment( + appointment, + localPosition.dx, + localPosition.dy, + isTimelineViews, + isAllDayPanel: true, + ); return; } _updateHoveringForViewHeader( - localPosition, - _isRTL ? widget.width - localPosition.dx : localPosition.dx, - localPosition.dy, - viewHeaderHeight); + localPosition, + _isRTL ? widget.width - localPosition.dx : localPosition.dx, + localPosition.dy, + viewHeaderHeight, + ); return; } - _updateHoveringForViewHeader(localPosition, localPosition.dx, - localPosition.dy, viewHeaderHeight); + _updateHoveringForViewHeader( + localPosition, + localPosition.dx, + localPosition.dy, + viewHeaderHeight, + ); return; } @@ -10765,22 +12479,30 @@ class _CalendarViewState extends State<_CalendarView> final double allDayExpanderHeight = panelHeight * _allDayExpanderAnimation!.value; - final double allDayBottom = isDayView - ? viewHeaderHeight - : viewHeaderHeight + _allDayHeight + allDayExpanderHeight; + final double allDayBottom = + isDayView + ? viewHeaderHeight + : viewHeaderHeight + _allDayHeight + allDayExpanderHeight; if (localPosition.dy > viewHeaderHeight && localPosition.dy < allDayBottom) { if ((_isRTL && localPosition.dx < widget.width - timeLabelWidth) || (!_isRTL && localPosition.dx > timeLabelWidth)) { _updateHoveringForAllDayPanel( - localPosition.dx, localPosition.dy - viewHeaderHeight); + localPosition.dx, + localPosition.dy - viewHeaderHeight, + ); final AppointmentView? appointment = _getAllDayAppointmentOnPoint( - _updateCalendarStateDetails.allDayAppointmentViewCollection, - localPosition.dx, - localPosition.dy - viewHeaderHeight); - _updateMouseCursorForAppointment(appointment, localPosition.dx, - localPosition.dy - viewHeaderHeight, isTimelineViews, - isAllDayPanel: true); + _updateCalendarStateDetails.allDayAppointmentViewCollection, + localPosition.dx, + localPosition.dy - viewHeaderHeight, + ); + _updateMouseCursorForAppointment( + appointment, + localPosition.dx, + localPosition.dy - viewHeaderHeight, + isTimelineViews, + isAllDayPanel: true, + ); } else { _removeAllWidgetHovering(); } @@ -10790,15 +12512,23 @@ class _CalendarViewState extends State<_CalendarView> yPosition = localPosition.dy - (viewHeaderHeight + allDayHeight); - final AppointmentView? appointment = - _appointmentLayout.getAppointmentViewOnPoint( - localPosition.dx, yPosition + _scrollController!.offset); + final AppointmentView? appointment = _appointmentLayout + .getAppointmentViewOnPoint( + localPosition.dx, + yPosition + _scrollController!.offset, + ); _hoveringAppointmentView = appointment; if (appointment != null) { _updateHoveringForAppointment( - localPosition.dx, yPosition + _scrollController!.offset); - _updateMouseCursorForAppointment(appointment, localPosition.dx, - yPosition + _scrollController!.offset, isTimelineViews); + localPosition.dx, + yPosition + _scrollController!.offset, + ); + _updateMouseCursorForAppointment( + appointment, + localPosition.dx, + yPosition + _scrollController!.offset, + isTimelineViews, + ); _hoveringDate = null; return; } @@ -10809,9 +12539,10 @@ class _CalendarViewState extends State<_CalendarView> if (widget.calendar.showWeekNumber && widget.view == CalendarView.month) { final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if ((!_isRTL && xPosition < weekNumberPanelWidth) || (_isRTL && xPosition > widget.width - weekNumberPanelWidth)) { _hoveringDate = null; @@ -10835,7 +12566,8 @@ class _CalendarViewState extends State<_CalendarView> /// on all the calendar views. if (isTimelineViews) { if (_isRTL) { - xPosition = (_getSingleViewWidthForTimeLineView(this) * + xPosition = + (_getSingleViewWidthForTimeLineView(this) * widget.visibleDates.length) - (_scrollController!.offset + (_scrollController!.position.viewportDimension - @@ -10847,23 +12579,33 @@ class _CalendarViewState extends State<_CalendarView> if (localPosition.dy < viewHeaderHeight) { _updateHoveringForViewHeader( - localPosition, xPosition, localPosition.dy, viewHeaderHeight); + localPosition, + xPosition, + localPosition.dy, + viewHeaderHeight, + ); return; } yPosition = localPosition.dy - viewHeaderHeight - timeLabelWidth; if (CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view)) { + widget.calendar.dataSource, + widget.view, + )) { yPosition += _timelineViewVerticalScrollController!.offset; } - final AppointmentView? appointment = - _appointmentLayout.getAppointmentViewOnPoint(xPosition, yPosition); + final AppointmentView? appointment = _appointmentLayout + .getAppointmentViewOnPoint(xPosition, yPosition); _hoveringAppointmentView = appointment; if (appointment != null) { _updateHoveringForAppointment(xPosition, yPosition); _updateMouseCursorForAppointment( - appointment, xPosition, yPosition, isTimelineViews); + appointment, + xPosition, + yPosition, + isTimelineViews, + ); _hoveringDate = null; return; } @@ -10883,26 +12625,33 @@ class _CalendarViewState extends State<_CalendarView> } final DateTime? hoverDate = _getDateFromPosition( - isTimelineViews ? localPosition.dx : xPosition, - yPosition, - timeLabelWidth); + isTimelineViews ? localPosition.dx : xPosition, + yPosition, + timeLabelWidth, + ); /// Remove the hovering when the position not in cell regions or non active /// cell regions. - final bool isMonthView = widget.view == CalendarView.month || + final bool isMonthView = + widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); if (hoverDate == null || (isMonthView && !isDateWithInDateRange( - widget.calendar.minDate, widget.calendar.maxDate, hoverDate)) || + widget.calendar.minDate, + widget.calendar.maxDate, + hoverDate, + )) || (!isMonthView && !CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - hoverDate, - timeInterval))) { + widget.calendar.minDate, + widget.calendar.maxDate, + hoverDate, + timeInterval, + ))) { if (_hoveringDate != null) { _hoveringDate = null; } @@ -10917,7 +12666,9 @@ class _CalendarViewState extends State<_CalendarView> /// Check the hovering month cell date is blackout date. if (isMonthView && CalendarViewHelper.isDateInDateCollection( - widget.blackoutDates, hoverDate)) { + widget.blackoutDates, + hoverDate, + )) { if (_hoveringDate != null) { _hoveringDate = null; } @@ -10941,8 +12692,11 @@ class _CalendarViewState extends State<_CalendarView> return; } - final int hoveringResourceIndex = - _getSelectedResourceIndex(yPosition, viewHeaderHeight, timeLabelWidth); + final int hoveringResourceIndex = _getSelectedResourceIndex( + yPosition, + viewHeaderHeight, + timeLabelWidth, + ); /// Restrict the hovering, while selected region as disabled [TimeRegion]. if (((widget.view == CalendarView.day || @@ -10951,7 +12705,10 @@ class _CalendarViewState extends State<_CalendarView> !_isEnabledRegion(yPosition, hoverDate, hoveringResourceIndex)) || (isTimelineViews && !_isEnabledRegion( - localPosition.dx, hoverDate, hoveringResourceIndex))) { + localPosition.dx, + hoverDate, + hoveringResourceIndex, + ))) { if (_hoveringDate != null) { _hoveringDate = null; } @@ -10969,10 +12726,11 @@ class _CalendarViewState extends State<_CalendarView> /// [SfCalendar] month not shown leading and trailing dates. if (isMonthView && !CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - hoverDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + hoverDate, + )) { if (_hoveringDate != null) { _hoveringDate = null; } @@ -10997,7 +12755,9 @@ class _CalendarViewState extends State<_CalendarView> } final bool isResourceEnabled = CalendarViewHelper.isResourceEnabled( - widget.calendar.dataSource, widget.view); + widget.calendar.dataSource, + widget.view, + ); /// If resource enabled the selected date or time slot can be same but the /// resource value differs hence to handle this scenario we are excluding @@ -11021,7 +12781,9 @@ class _CalendarViewState extends State<_CalendarView> return; } else if (widget.view != CalendarView.month && CalendarViewHelper.isSameTimeSlot( - _selectionPainter!.selectedDate, _hoveringDate) && + _selectionPainter!.selectedDate, + _hoveringDate, + ) && hoveringResourceIndex == _selectedResourceIndex) { _calendarCellNotifier.value = null; return; @@ -11082,7 +12844,10 @@ class _CalendarViewState extends State<_CalendarView> } AppointmentView? _getAllDayAppointmentOnPoint( - List? appointmentCollection, double x, double y) { + List? appointmentCollection, + double x, + double y, + ) { if (appointmentCollection == null) { return null; } @@ -11107,26 +12872,35 @@ class _CalendarViewState extends State<_CalendarView> List _getSelectedAppointments(DateTime selectedDate) { return (widget.calendar.dataSource != null && !AppointmentHelper.isCalendarAppointment( - widget.calendar.dataSource!)) + widget.calendar.dataSource!, + )) ? CalendarViewHelper.getCustomAppointments( - AppointmentHelper.getSelectedDateAppointments( - _updateCalendarStateDetails.appointments, - widget.calendar.timeZone, - selectedDate), - widget.calendar.dataSource) - : (AppointmentHelper.getSelectedDateAppointments( + AppointmentHelper.getSelectedDateAppointments( _updateCalendarStateDetails.appointments, widget.calendar.timeZone, - selectedDate)); + selectedDate, + ), + widget.calendar.dataSource, + ) + : (AppointmentHelper.getSelectedDateAppointments( + _updateCalendarStateDetails.appointments, + widget.calendar.timeZone, + selectedDate, + )); } DateTime? _getDateFromPositionForMonth( - double cellWidth, double cellHeight, double x, double y) { + double cellWidth, + double cellHeight, + double x, + double y, + ) { final int rowIndex = (x / cellWidth).truncate(); final int columnIndex = (y / cellHeight).truncate(); int index = 0; if (_isRTL) { - index = (columnIndex * DateTime.daysPerWeek) + + index = + (columnIndex * DateTime.daysPerWeek) + (DateTime.daysPerWeek - rowIndex) - 1; } else { @@ -11141,16 +12915,22 @@ class _CalendarViewState extends State<_CalendarView> } DateTime? _getDateFromPositionForWeek( - double cellWidth, double cellHeight, double x, double y) { + double cellWidth, + double cellHeight, + double x, + double y, + ) { final int columnIndex = ((_scrollController!.offset + y) / cellHeight).truncate(); - final double time = columnIndex == -1 - ? 0 - : ((CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings) / - 60) * - columnIndex) + - widget.calendar.timeSlotViewSettings.startHour; + final double time = + columnIndex == -1 + ? 0 + : ((CalendarViewHelper.getTimeInterval( + widget.calendar.timeSlotViewSettings, + ) / + 60) * + columnIndex) + + widget.calendar.timeSlotViewSettings.startHour; final int hour = time.toInt(); final int minute = ((time - hour) * 60).round(); int rowIndex = (x / cellWidth).truncate(); @@ -11168,20 +12948,26 @@ class _CalendarViewState extends State<_CalendarView> } DateTime? _getDateFromPositionForTimeline( - double cellWidth, double cellHeight, double x, double y) { + double cellWidth, + double cellHeight, + double x, + double y, + ) { int rowIndex, columnIndex; if (_isRTL) { - rowIndex = (((_scrollController!.offset % - _getSingleViewWidthForTimeLineView(this)) + - (_scrollController!.position.viewportDimension - x)) / - cellWidth) - .truncate(); + rowIndex = + (((_scrollController!.offset % + _getSingleViewWidthForTimeLineView(this)) + + (_scrollController!.position.viewportDimension - x)) / + cellWidth) + .truncate(); } else { - rowIndex = (((_scrollController!.offset % - _getSingleViewWidthForTimeLineView(this)) + - x) / - cellWidth) - .truncate(); + rowIndex = + (((_scrollController!.offset % + _getSingleViewWidthForTimeLineView(this)) + + x) / + cellWidth) + .truncate(); } columnIndex = (_scrollController!.offset / _getSingleViewWidthForTimeLineView(this)) @@ -11190,8 +12976,10 @@ class _CalendarViewState extends State<_CalendarView> columnIndex += rowIndex ~/ _horizontalLinesCount!; rowIndex = (rowIndex % _horizontalLinesCount!).toInt(); } - final double time = ((CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings) / + final double time = + ((CalendarViewHelper.getTimeInterval( + widget.calendar.timeSlotViewSettings, + ) / 60) * rowIndex) + widget.calendar.timeSlotViewSettings.startHour; @@ -11224,9 +13012,10 @@ class _CalendarViewState extends State<_CalendarView> /// Remove the selection when the position is to week number panel. final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if (x > widget.width || (!_isRTL && x < weekNumberPanelWidth) || (_isRTL && x > widget.width - weekNumberPanelWidth)) { @@ -11241,9 +13030,12 @@ class _CalendarViewState extends State<_CalendarView> cellWidth = (widget.width - weekNumberPanelWidth) / DateTime.daysPerWeek; - cellHeight = (widget.height - + cellHeight = + (widget.height - CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view)) / + widget.calendar.viewHeaderHeight, + widget.view, + )) / widget.calendar.monthViewSettings.numberOfWeeksInView; return _getDateFromPositionForMonth(cellWidth, cellHeight, x, y); } @@ -11265,7 +13057,8 @@ class _CalendarViewState extends State<_CalendarView> case CalendarView.timelineWorkWeek: case CalendarView.timelineMonth: { - final double viewWidth = _timeIntervalHeight * + final double viewWidth = + _timeIntervalHeight * (_horizontalLinesCount! * widget.visibleDates.length); if ((!_isRTL && x >= viewWidth) || (_isRTL && x < (widget.width - viewWidth))) { @@ -11280,20 +13073,26 @@ class _CalendarViewState extends State<_CalendarView> void _drawSelection(double x, double y, double timeLabelWidth) { final DateTime? selectedDate = _getDateFromPosition(x, y, timeLabelWidth); - final bool isMonthView = widget.view == CalendarView.month || + final bool isMonthView = + widget.view == CalendarView.month || widget.view == CalendarView.timelineMonth; final int timeInterval = CalendarViewHelper.getTimeInterval( - widget.calendar.timeSlotViewSettings); + widget.calendar.timeSlotViewSettings, + ); if (selectedDate == null || (isMonthView && - !isDateWithInDateRange(widget.calendar.minDate, - widget.calendar.maxDate, selectedDate)) || + !isDateWithInDateRange( + widget.calendar.minDate, + widget.calendar.maxDate, + selectedDate, + )) || (!isMonthView && !CalendarViewHelper.isDateTimeWithInDateTimeRange( - widget.calendar.minDate, - widget.calendar.maxDate, - selectedDate, - timeInterval))) { + widget.calendar.minDate, + widget.calendar.maxDate, + selectedDate, + timeInterval, + ))) { return; } @@ -11310,7 +13109,9 @@ class _CalendarViewState extends State<_CalendarView> if (isMonthView && CalendarViewHelper.isDateInDateCollection( - widget.blackoutDates, selectedDate)) { + widget.blackoutDates, + selectedDate, + )) { return; } @@ -11321,10 +13122,11 @@ class _CalendarViewState extends State<_CalendarView> /// Check the selected cell date as trailing or leading date when /// [SfCalendar] month not shown leading and trailing dates. if (!CalendarViewHelper.isCurrentMonthDate( - widget.calendar.monthViewSettings.numberOfWeeksInView, - widget.calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - selectedDate)) { + widget.calendar.monthViewSettings.numberOfWeeksInView, + widget.calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + selectedDate, + )) { return; } @@ -11363,8 +13165,9 @@ class _CalendarViewState extends State<_CalendarView> ); if (appointmentView != null && - _updateCalendarStateDetails.visibleAppointments - .contains(appointmentView.appointment)) { + _updateCalendarStateDetails.visibleAppointments.contains( + appointmentView.appointment, + )) { _selectionPainter!.appointmentView = appointmentView; } @@ -11373,66 +13176,67 @@ class _CalendarViewState extends State<_CalendarView> Widget _getTimelineViewHeader(double width, double height, String locale) { _timelineViewHeader = TimelineViewHeaderView( - widget.visibleDates, - _timelineViewHeaderScrollController!, - _timelineViewHeaderNotifier, - widget.calendar.viewHeaderStyle, - widget.calendar.timeSlotViewSettings, - CalendarViewHelper.getViewHeaderHeight( - widget.calendar.viewHeaderHeight, widget.view), - _isRTL, - widget.calendar.todayHighlightColor ?? - widget.calendarTheme.todayHighlightColor, - widget.calendar.todayTextStyle, - widget.locale, - widget.calendarTheme, - widget.themeData, - widget.calendar.minDate, - widget.calendar.maxDate, - _viewHeaderNotifier, - widget.calendar.cellBorderColor, - widget.blackoutDates, - widget.calendar.blackoutDatesTextStyle, - widget.textScaleFactor); + widget.visibleDates, + _timelineViewHeaderScrollController!, + _timelineViewHeaderNotifier, + widget.calendar.viewHeaderStyle, + widget.calendar.timeSlotViewSettings, + CalendarViewHelper.getViewHeaderHeight( + widget.calendar.viewHeaderHeight, + widget.view, + ), + _isRTL, + widget.calendar.todayHighlightColor ?? + widget.calendarTheme.todayHighlightColor, + widget.calendar.todayTextStyle, + widget.locale, + widget.calendarTheme, + widget.themeData, + widget.calendar.minDate, + widget.calendar.maxDate, + _viewHeaderNotifier, + widget.calendar.cellBorderColor, + widget.blackoutDates, + widget.calendar.blackoutDatesTextStyle, + widget.textScaleFactor, + ); return ListView( - padding: EdgeInsets.zero, - controller: _timelineViewHeaderScrollController, - scrollDirection: Axis.horizontal, - physics: const NeverScrollableScrollPhysics(), - children: [ - CustomPaint( - painter: _timelineViewHeader, - size: Size(width, height), - ) - ]); + padding: EdgeInsets.zero, + controller: _timelineViewHeaderScrollController, + scrollDirection: Axis.horizontal, + physics: const NeverScrollableScrollPhysics(), + children: [ + CustomPaint(painter: _timelineViewHeader, size: Size(width, height)), + ], + ); } } class _ViewHeaderViewPainter extends CustomPainter { _ViewHeaderViewPainter( - this.visibleDates, - this.view, - this.viewHeaderStyle, - this.timeSlotViewSettings, - this.timeLabelWidth, - this.viewHeaderHeight, - this.monthViewSettings, - this.isRTL, - this.locale, - this.calendarTheme, - this.themeData, - this.todayHighlightColor, - this.todayTextStyle, - this.cellBorderColor, - this.minDate, - this.maxDate, - this.viewHeaderNotifier, - this.textScaleFactor, - this.showWeekNumber, - this.isMobilePlatform, - this.weekNumberStyle, - this.localizations) - : super(repaint: viewHeaderNotifier); + this.visibleDates, + this.view, + this.viewHeaderStyle, + this.timeSlotViewSettings, + this.timeLabelWidth, + this.viewHeaderHeight, + this.monthViewSettings, + this.isRTL, + this.locale, + this.calendarTheme, + this.themeData, + this.todayHighlightColor, + this.todayTextStyle, + this.cellBorderColor, + this.minDate, + this.maxDate, + this.viewHeaderNotifier, + this.textScaleFactor, + this.showWeekNumber, + this.isMobilePlatform, + this.weekNumberStyle, + this.localizations, + ) : super(repaint: viewHeaderNotifier); final CalendarView view; final ViewHeaderStyle viewHeaderStyle; @@ -11465,10 +13269,14 @@ class _ViewHeaderViewPainter extends CustomPainter { canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height)); final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - showWeekNumber, size.width, isMobilePlatform); - double width = view == CalendarView.month - ? size.width - weekNumberPanelWidth - : size.width; + showWeekNumber, + size.width, + isMobilePlatform, + ); + double width = + view == CalendarView.month + ? size.width - weekNumberPanelWidth + : size.width; width = _getViewHeaderWidth(width); /// Initializes the default text style for the texts in view header of @@ -11480,51 +13288,77 @@ class _ViewHeaderViewPainter extends CustomPainter { final DateTime today = DateTime.now(); if (view != CalendarView.month) { _addViewHeaderForTimeSlotViews( - canvas, size, viewHeaderDayStyle, viewHeaderDateStyle, width, today); + canvas, + size, + viewHeaderDayStyle, + viewHeaderDateStyle, + width, + today, + ); } else { _addViewHeaderForMonthView( - canvas, size, viewHeaderDayStyle, width, today, weekNumberPanelWidth); + canvas, + size, + viewHeaderDayStyle, + width, + today, + weekNumberPanelWidth, + ); } } void _addViewHeaderForMonthView( - Canvas canvas, - Size size, - TextStyle viewHeaderDayStyle, - double width, - DateTime today, - double weekNumberPanelWidth) { + Canvas canvas, + Size size, + TextStyle viewHeaderDayStyle, + double width, + DateTime today, + double weekNumberPanelWidth, + ) { TextStyle dayTextStyle = viewHeaderDayStyle; - double xPosition = isRTL - ? size.width - width - weekNumberPanelWidth - : weekNumberPanelWidth; + double xPosition = + isRTL + ? size.width - width - weekNumberPanelWidth + : weekNumberPanelWidth; double yPosition = 0; final int visibleDatesLength = visibleDates.length; - bool hasToday = monthViewSettings.numberOfWeeksInView > 0 && + bool hasToday = + monthViewSettings.numberOfWeeksInView > 0 && monthViewSettings.numberOfWeeksInView < 6 || visibleDates[visibleDatesLength ~/ 2].month == today.month; if (hasToday) { hasToday = isDateWithInDateRange( - visibleDates[0], visibleDates[visibleDatesLength - 1], today); + visibleDates[0], + visibleDates[visibleDatesLength - 1], + today, + ); } for (int i = 0; i < DateTime.daysPerWeek; i++) { final DateTime currentDate = visibleDates[i]; - String dayText = DateFormat(monthViewSettings.dayFormat, locale) - .format(currentDate) - .toUpperCase(); + String dayText = + DateFormat( + monthViewSettings.dayFormat, + locale, + ).format(currentDate).toUpperCase(); dayText = _updateViewHeaderFormat(monthViewSettings.dayFormat, dayText); if (hasToday && currentDate.weekday == today.weekday) { final Color? todayTextColor = CalendarViewHelper.getTodayHighlightTextColor( - todayHighlightColor, todayTextStyle, calendarTheme); + todayHighlightColor, + todayTextStyle, + calendarTheme, + ); - dayTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle!.copyWith( - fontSize: viewHeaderDayStyle.fontSize, color: todayTextColor) - : viewHeaderDayStyle.copyWith(color: todayTextColor); + dayTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: viewHeaderDayStyle.fontSize, + color: todayTextColor, + ) + : viewHeaderDayStyle.copyWith(color: todayTextColor); } else { dayTextStyle = viewHeaderDayStyle; } @@ -11540,9 +13374,9 @@ class _ViewHeaderViewPainter extends CustomPainter { } _dayTextPainter.paint( - canvas, - Offset( - xPosition + (width / 2 - _dayTextPainter.width / 2), yPosition)); + canvas, + Offset(xPosition + (width / 2 - _dayTextPainter.width / 2), yPosition), + ); if (isRTL) { xPosition -= width; @@ -11555,8 +13389,11 @@ class _ViewHeaderViewPainter extends CustomPainter { final TextStyle weekNumberTextStyle = calendarTheme.weekNumberTextStyle!; final double xPosition = isRTL ? (size.width - weekNumberPanelWidth) : 0; - _updateDayTextPainter(weekNumberTextStyle, weekNumberPanelWidth, - localizations.weeknumberLabel); + _updateDayTextPainter( + weekNumberTextStyle, + weekNumberPanelWidth, + localizations.weeknumberLabel, + ); /// Condition added to remove the ellipsis, when the width is too small /// the ellipsis alone displayed, hence to resolve this removed ecclipsis @@ -11570,27 +13407,30 @@ class _ViewHeaderViewPainter extends CustomPainter { } _dayTextPainter.paint( - canvas, - Offset( - xPosition + - (weekNumberPanelWidth / 2 - _dayTextPainter.width / 2), - yPosition)); + canvas, + Offset( + xPosition + (weekNumberPanelWidth / 2 - _dayTextPainter.width / 2), + yPosition, + ), + ); } } void _addViewHeaderForTimeSlotViews( - Canvas canvas, - Size size, - TextStyle viewHeaderDayStyle, - TextStyle viewHeaderDateStyle, - double width, - DateTime today) { + Canvas canvas, + Size size, + TextStyle viewHeaderDayStyle, + TextStyle viewHeaderDateStyle, + double width, + DateTime today, + ) { double xPosition, yPosition; final bool isDayView = CalendarViewHelper.isDayView( - view, - timeSlotViewSettings.numberOfDaysInView, - timeSlotViewSettings.nonWorkingDays, - monthViewSettings.numberOfWeeksInView); + view, + timeSlotViewSettings.numberOfDaysInView, + timeSlotViewSettings.nonWorkingDays, + monthViewSettings.numberOfWeeksInView, + ); final double labelWidth = isDayView && timeLabelWidth < 50 ? 50 : timeLabelWidth; TextStyle dayTextStyle = viewHeaderDayStyle; @@ -11611,29 +13451,42 @@ class _ViewHeaderViewPainter extends CustomPainter { for (int i = 0; i < visibleDatesLength; i++) { final DateTime currentDate = visibleDates[i]; - String dayText = DateFormat(timeSlotViewSettings.dayFormat, locale) - .format(currentDate) - .toUpperCase(); + String dayText = + DateFormat( + timeSlotViewSettings.dayFormat, + locale, + ).format(currentDate).toUpperCase(); - dayText = - _updateViewHeaderFormat(timeSlotViewSettings.dayFormat, dayText); + dayText = _updateViewHeaderFormat( + timeSlotViewSettings.dayFormat, + dayText, + ); - final String dateText = - DateFormat(timeSlotViewSettings.dateFormat).format(currentDate); + final String dateText = DateFormat( + timeSlotViewSettings.dateFormat, + ).format(currentDate); final bool isToday = isSameDate(currentDate, today); if (isToday) { final Color? todayTextStyleColor = calendarTheme.todayTextStyle!.color; final Color? todayTextColor = CalendarViewHelper.getTodayHighlightTextColor( - todayHighlightColor, todayTextStyle, calendarTheme); - dayTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle!.copyWith( - fontSize: viewHeaderDayStyle.fontSize, color: todayTextColor) - : viewHeaderDayStyle.copyWith(color: todayTextColor); - dateTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle! - .copyWith(fontSize: viewHeaderDateStyle.fontSize) - : viewHeaderDateStyle.copyWith(color: todayTextStyleColor); + todayHighlightColor, + todayTextStyle, + calendarTheme, + ); + dayTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: viewHeaderDayStyle.fontSize, + color: todayTextColor, + ) + : viewHeaderDayStyle.copyWith(color: todayTextColor); + dateTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: viewHeaderDateStyle.fontSize, + ) + : viewHeaderDateStyle.copyWith(color: todayTextStyleColor); } else { dayTextStyle = viewHeaderDayStyle; dateTextStyle = viewHeaderDateStyle; @@ -11641,17 +13494,21 @@ class _ViewHeaderViewPainter extends CustomPainter { if (!isDateWithInDateRange(minDate, maxDate, currentDate)) { dayTextStyle = dayTextStyle.copyWith( - color: dayTextStyle.color != null - ? dayTextStyle.color!.withValues(alpha: 0.38) - : themeData.brightness == Brightness.light - ? Colors.black26 - : Colors.white38); + color: + dayTextStyle.color != null + ? dayTextStyle.color!.withValues(alpha: 0.38) + : themeData.brightness == Brightness.light + ? Colors.black26 + : Colors.white38, + ); dateTextStyle = dateTextStyle.copyWith( - color: dateTextStyle.color != null - ? dateTextStyle.color!.withValues(alpha: 0.38) - : themeData.brightness == Brightness.light - ? Colors.black26 - : Colors.white38); + color: + dateTextStyle.color != null + ? dateTextStyle.color!.withValues(alpha: 0.38) + : themeData.brightness == Brightness.light + ? Colors.black26 + : Colors.white38, + ); } _updateDayTextPainter(dayTextStyle, width, dayText); @@ -11676,7 +13533,8 @@ class _ViewHeaderViewPainter extends CustomPainter { final double dateXPosition = (cellWidth - _dateTextPainter.width) / 2; const int inBetweenPadding = 2; - yPosition = size.height / 2 - + yPosition = + size.height / 2 - (_dayTextPainter.height + topPadding + _dateTextPainter.height + @@ -11684,35 +13542,46 @@ class _ViewHeaderViewPainter extends CustomPainter { 2; _dayTextPainter.paint( - canvas, Offset(xPosition + dayXPosition, yPosition)); + canvas, + Offset(xPosition + dayXPosition, yPosition), + ); if (isToday) { _drawTodayCircle( - canvas, - xPosition + dateXPosition, - yPosition + topPadding + _dayTextPainter.height + inBetweenPadding, - _dateTextPainter); + canvas, + xPosition + dateXPosition, + yPosition + topPadding + _dayTextPainter.height + inBetweenPadding, + _dateTextPainter, + ); } if (viewHeaderNotifier.value != null) { - _addMouseHoverForTimeSlotView(canvas, size, xPosition, yPosition, - dateXPosition, topPadding, isToday, inBetweenPadding); + _addMouseHoverForTimeSlotView( + canvas, + size, + xPosition, + yPosition, + dateXPosition, + topPadding, + isToday, + inBetweenPadding, + ); } _dateTextPainter.paint( - canvas, - Offset( - xPosition + dateXPosition, - yPosition + - topPadding + - _dayTextPainter.height + - inBetweenPadding)); + canvas, + Offset( + xPosition + dateXPosition, + yPosition + topPadding + _dayTextPainter.height + inBetweenPadding, + ), + ); if (!isDayView && showWeekNumber && ((currentDate.weekday == DateTime.monday) || (view == CalendarView.workWeek && - timeSlotViewSettings.nonWorkingDays - .contains(DateTime.monday) && + timeSlotViewSettings.nonWorkingDays.contains( + DateTime.monday, + ) && i == visibleDatesLength ~/ 2))) { final String weekNumber = DateTimeHelper.getWeekNumberOfYear(currentDate).toString(); @@ -11728,11 +13597,13 @@ class _ViewHeaderViewPainter extends CustomPainter { _dateTextPainter.textWidthBasis = TextWidthBasis.longestLine; _dateTextPainter.textScaler = TextScaler.linear(textScaleFactor); _dateTextPainter.layout(maxWidth: timeLabelWidth); - final double weekNumberPosition = isRTL - ? (size.width - timeLabelWidth) + - ((timeLabelWidth - _dateTextPainter.width) / 2) - : (timeLabelWidth - _dateTextPainter.width) / 2; - final double weekNumberYPosition = size.height / 2 - + final double weekNumberPosition = + isRTL + ? (size.width - timeLabelWidth) + + ((timeLabelWidth - _dateTextPainter.width) / 2) + : (timeLabelWidth - _dateTextPainter.width) / 2; + final double weekNumberYPosition = + size.height / 2 - (_dayTextPainter.height + topPadding + _dateTextPainter.height + @@ -11743,25 +13614,37 @@ class _ViewHeaderViewPainter extends CustomPainter { inBetweenPadding; const double padding = 10; final Rect rect = Rect.fromLTRB( - weekNumberPosition - padding, - weekNumberYPosition - (padding / 2), - weekNumberPosition + _dateTextPainter.width + padding, - weekNumberYPosition + _dateTextPainter.height + (padding / 2)); + weekNumberPosition - padding, + weekNumberYPosition - (padding / 2), + weekNumberPosition + _dateTextPainter.width + padding, + weekNumberYPosition + _dateTextPainter.height + (padding / 2), + ); linePainter.style = PaintingStyle.fill; - linePainter.color = weekNumberStyle.backgroundColor ?? + linePainter.color = + weekNumberStyle.backgroundColor ?? calendarTheme.weekNumberBackgroundColor!; - final RRect roundedRect = - RRect.fromRectAndRadius(rect, const Radius.circular(padding / 2)); + final RRect roundedRect = RRect.fromRectAndRadius( + rect, + const Radius.circular(padding / 2), + ); canvas.drawRRect(roundedRect, linePainter); _dateTextPainter.paint( - canvas, Offset(weekNumberPosition, weekNumberYPosition)); + canvas, + Offset(weekNumberPosition, weekNumberYPosition), + ); final double xPosition = isRTL ? (size.width - timeLabelWidth) : 0; _updateDayTextPainter( - weekNumberTextStyle, timeLabelWidth, localizations.weeknumberLabel); + weekNumberTextStyle, + timeLabelWidth, + localizations.weeknumberLabel, + ); _dayTextPainter.paint( - canvas, - Offset(xPosition + (timeLabelWidth / 2 - _dayTextPainter.width / 2), - yPosition)); + canvas, + Offset( + xPosition + (timeLabelWidth / 2 - _dayTextPainter.width / 2), + yPosition, + ), + ); } if (isRTL) { @@ -11772,8 +13655,13 @@ class _ViewHeaderViewPainter extends CustomPainter { } } - void _addMouseHoverForMonth(Canvas canvas, Size size, double xPosition, - double yPosition, double width) { + void _addMouseHoverForMonth( + Canvas canvas, + Size size, + double xPosition, + double yPosition, + double width, + ) { if (xPosition + (width / 2 - _dayTextPainter.width / 2) <= viewHeaderNotifier.value!.dx && xPosition + @@ -11783,41 +13671,45 @@ class _ViewHeaderViewPainter extends CustomPainter { yPosition - 5 <= viewHeaderNotifier.value!.dy && (yPosition + size.height) - 5 >= viewHeaderNotifier.value!.dy) { _drawTodayCircle( - canvas, - xPosition + (width / 2 - _dayTextPainter.width / 2), - yPosition, - _dayTextPainter, - hoveringColor: (themeData.brightness == Brightness.dark - ? Colors.white - : Colors.black87) - .withValues(alpha: 0.04)); + canvas, + xPosition + (width / 2 - _dayTextPainter.width / 2), + yPosition, + _dayTextPainter, + hoveringColor: (themeData.brightness == Brightness.dark + ? Colors.white + : Colors.black87) + .withValues(alpha: 0.04), + ); } } void _addMouseHoverForTimeSlotView( - Canvas canvas, - Size size, - double xPosition, - double yPosition, - double dateXPosition, - double topPadding, - bool isToday, - int padding) { + Canvas canvas, + Size size, + double xPosition, + double yPosition, + double dateXPosition, + double topPadding, + bool isToday, + int padding, + ) { if (xPosition + dateXPosition <= viewHeaderNotifier.value!.dx && xPosition + dateXPosition + _dateTextPainter.width >= viewHeaderNotifier.value!.dx) { - final Color hoveringColor = isToday - ? Colors.black.withValues(alpha: 0.12) - : (themeData.brightness == Brightness.dark - ? Colors.white - : Colors.black87) - .withValues(alpha: 0.04); + final Color hoveringColor = + isToday + ? Colors.black.withValues(alpha: 0.12) + : (themeData.brightness == Brightness.dark + ? Colors.white + : Colors.black87) + .withValues(alpha: 0.04); _drawTodayCircle( - canvas, - xPosition + dateXPosition, - yPosition + topPadding + _dayTextPainter.height + padding, - _dateTextPainter, - hoveringColor: hoveringColor); + canvas, + xPosition + dateXPosition, + yPosition + topPadding + _dayTextPainter.height + padding, + _dateTextPainter, + hoveringColor: hoveringColor, + ); } } @@ -11828,10 +13720,11 @@ class _ViewHeaderViewPainter extends CustomPainter { case CalendarView.workWeek: { if (!CalendarViewHelper.isDayView( - view, - timeSlotViewSettings.numberOfDaysInView, - timeSlotViewSettings.nonWorkingDays, - monthViewSettings.numberOfWeeksInView) && + view, + timeSlotViewSettings.numberOfDaysInView, + timeSlotViewSettings.nonWorkingDays, + monthViewSettings.numberOfWeeksInView, + ) && (dayFormat == 'EE' && (locale.contains('en')))) { return dayText[0]; } @@ -11856,11 +13749,11 @@ class _ViewHeaderViewPainter extends CustomPainter { } void _updateDayTextPainter( - TextStyle dayTextStyle, double width, String dayText) { - final TextSpan dayTextSpan = TextSpan( - text: dayText, - style: dayTextStyle, - ); + TextStyle dayTextStyle, + double width, + String dayText, + ) { + final TextSpan dayTextSpan = TextSpan(text: dayText, style: dayTextStyle); _dayTextPainter.text = dayTextSpan; _dayTextPainter.textDirection = TextDirection.ltr; @@ -11888,10 +13781,11 @@ class _ViewHeaderViewPainter extends CustomPainter { case CalendarView.workWeek: { if (CalendarViewHelper.isDayView( - view, - timeSlotViewSettings.numberOfDaysInView, - timeSlotViewSettings.nonWorkingDays, - monthViewSettings.numberOfWeeksInView)) { + view, + timeSlotViewSettings.numberOfDaysInView, + timeSlotViewSettings.nonWorkingDays, + monthViewSettings.numberOfWeeksInView, + )) { return timeLabelWidth; } return width - timeLabelWidth; @@ -11920,16 +13814,23 @@ class _ViewHeaderViewPainter extends CustomPainter { //// draw today highlight circle in view header. void _drawTodayCircle( - Canvas canvas, double x, double y, TextPainter dateTextPainter, - {Color? hoveringColor}) { + Canvas canvas, + double x, + double y, + TextPainter dateTextPainter, { + Color? hoveringColor, + }) { _circlePainter.color = (hoveringColor ?? todayHighlightColor)!; const double circlePadding = 5; final double painterWidth = dateTextPainter.width / 2; final double painterHeight = dateTextPainter.height / 2; final double radius = painterHeight > painterWidth ? painterHeight : painterWidth; - canvas.drawCircle(Offset(x + painterWidth, y + painterHeight), - radius + circlePadding, _circlePainter); + canvas.drawCircle( + Offset(x + painterWidth, y + painterHeight), + radius + circlePadding, + _circlePainter, + ); } /// overrides this property to build the semantics information which uses to @@ -11966,13 +13867,15 @@ class _ViewHeaderViewPainter extends CustomPainter { double left = isRTL ? size.width - cellWidth : 0; const double top = 0; for (int i = 0; i < DateTime.daysPerWeek; i++) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, cellWidth, size.height), - properties: SemanticsProperties( - label: DateFormat('EEEEE').format(visibleDates[i]).toUpperCase(), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, cellWidth, size.height), + properties: SemanticsProperties( + label: DateFormat('EEEEE').format(visibleDates[i]).toUpperCase(), + textDirection: TextDirection.ltr, + ), ), - )); + ); if (isRTL) { left -= cellWidth; } else { @@ -11989,17 +13892,20 @@ class _ViewHeaderViewPainter extends CustomPainter { const double top = 0; double left; final bool isDayView = CalendarViewHelper.isDayView( - view, - timeSlotViewSettings.numberOfDaysInView, - timeSlotViewSettings.nonWorkingDays, - monthViewSettings.numberOfWeeksInView); - final double cellWidth = isDayView - ? size.width - : (size.width - timeLabelWidth) / visibleDates.length; + view, + timeSlotViewSettings.numberOfDaysInView, + timeSlotViewSettings.nonWorkingDays, + monthViewSettings.numberOfWeeksInView, + ); + final double cellWidth = + isDayView + ? size.width + : (size.width - timeLabelWidth) / visibleDates.length; if (isRTL) { - left = isDayView - ? size.width - timeLabelWidth - : (size.width - timeLabelWidth) - cellWidth; + left = + isDayView + ? size.width - timeLabelWidth + : (size.width - timeLabelWidth) - cellWidth; } else { left = isDayView ? 0 : timeLabelWidth; } @@ -12008,25 +13914,35 @@ class _ViewHeaderViewPainter extends CustomPainter { if (showWeekNumber && ((visibleDate.weekday == DateTime.monday && !isDayView) || (view == CalendarView.workWeek && - timeSlotViewSettings.nonWorkingDays - .contains(DateTime.monday) && + timeSlotViewSettings.nonWorkingDays.contains( + DateTime.monday, + ) && i == visibleDates.length ~/ 2))) { final int weekNumber = DateTimeHelper.getWeekNumberOfYear(visibleDate); - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(isRTL ? (size.width - timeLabelWidth) : 0, 0, - isRTL ? size.width : timeLabelWidth, viewHeaderHeight), + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + isRTL ? (size.width - timeLabelWidth) : 0, + 0, + isRTL ? size.width : timeLabelWidth, + viewHeaderHeight, + ), properties: SemanticsProperties( label: 'week$weekNumber', textDirection: TextDirection.ltr, - ))); + ), + ), + ); } - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, cellWidth, size.height), - properties: SemanticsProperties( - label: _getAccessibilityText(visibleDates[i]), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, cellWidth, size.height), + properties: SemanticsProperties( + label: _getAccessibilityText(visibleDates[i]), + textDirection: TextDirection.ltr, + ), ), - )); + ); if (isRTL) { left -= cellWidth; } else { @@ -12057,21 +13973,21 @@ class _ViewHeaderViewPainter extends CustomPainter { class _SelectionPainter extends CustomPainter { _SelectionPainter( - this.calendar, - this.view, - this.visibleDates, - this.selectedDate, - this.selectionDecoration, - this.timeIntervalHeight, - this.calendarTheme, - this.repaintNotifier, - this.isRTL, - this.selectedResourceIndex, - this.resourceItemHeight, - this.showWeekNumber, - this.isMobilePlatform, - this.getCalendarState) - : super(repaint: repaintNotifier); + this.calendar, + this.view, + this.visibleDates, + this.selectedDate, + this.selectionDecoration, + this.timeIntervalHeight, + this.calendarTheme, + this.repaintNotifier, + this.isRTL, + this.selectedResourceIndex, + this.resourceItemHeight, + this.showWeekNumber, + this.isMobilePlatform, + this.getCalendarState, + ) : super(repaint: repaintNotifier); final SfCalendar calendar; final CalendarView view; @@ -12105,36 +14021,45 @@ class _SelectionPainter extends CustomPainter { getCalendarState(_updateCalendarStateDetails); selectedDate = _updateCalendarStateDetails.selectedDate; final bool isDayView = CalendarViewHelper.isDayView( - view, - calendar.timeSlotViewSettings.numberOfDaysInView, - calendar.timeSlotViewSettings.nonWorkingDays, - calendar.monthViewSettings.numberOfWeeksInView); + view, + calendar.timeSlotViewSettings.numberOfDaysInView, + calendar.timeSlotViewSettings.nonWorkingDays, + calendar.monthViewSettings.numberOfWeeksInView, + ); final bool isMonthView = view == CalendarView.month || view == CalendarView.timelineMonth; - final int timeInterval = - CalendarViewHelper.getTimeInterval(calendar.timeSlotViewSettings); + final int timeInterval = CalendarViewHelper.getTimeInterval( + calendar.timeSlotViewSettings, + ); if (selectedDate != null && ((isMonthView && !isDateWithInDateRange( - calendar.minDate, calendar.maxDate, selectedDate)) || + calendar.minDate, + calendar.maxDate, + selectedDate, + )) || (!isMonthView && !CalendarViewHelper.isDateTimeWithInDateTimeRange( - calendar.minDate, - calendar.maxDate, - selectedDate!, - timeInterval)))) { + calendar.minDate, + calendar.maxDate, + selectedDate!, + timeInterval, + )))) { return; } canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height)); final double timeLabelWidth = CalendarViewHelper.getTimeLabelWidth( - calendar.timeSlotViewSettings.timeRulerSize, view); + calendar.timeSlotViewSettings.timeRulerSize, + view, + ); double width = size.width; final bool isTimeline = CalendarViewHelper.isTimelineView(view); if (view != CalendarView.month && !isTimeline) { width -= timeLabelWidth; } - final bool isResourceEnabled = isTimeline && + final bool isResourceEnabled = + isTimeline && CalendarViewHelper.isResourceEnabled(calendar.dataSource, view); if ((selectedDate == null && appointmentView == null) || visibleDates != _updateCalendarStateDetails.currentViewVisibleDates || @@ -12215,7 +14140,10 @@ class _SelectionPainter extends CustomPainter { void _drawMonthSelection(Canvas canvas, Size size, double width) { final int visibleDatesLength = visibleDates.length; if (!isDateWithInDateRange( - visibleDates[0], visibleDates[visibleDatesLength - 1], selectedDate)) { + visibleDates[0], + visibleDates[visibleDatesLength - 1], + selectedDate, + )) { return; } @@ -12224,15 +14152,18 @@ class _SelectionPainter extends CustomPainter { /// Check the selected cell date as trailing or leading date when /// [SfCalendar] month not shown leading and trailing dates. if (!CalendarViewHelper.isCurrentMonthDate( - calendar.monthViewSettings.numberOfWeeksInView, - calendar.monthViewSettings.showTrailingAndLeadingDates, - currentMonth, - selectedDate!)) { + calendar.monthViewSettings.numberOfWeeksInView, + calendar.monthViewSettings.showTrailingAndLeadingDates, + currentMonth, + selectedDate!, + )) { return; } if (CalendarViewHelper.isDateInDateCollection( - calendar.blackoutDates, selectedDate!)) { + calendar.blackoutDates, + selectedDate!, + )) { return; } @@ -12240,7 +14171,10 @@ class _SelectionPainter extends CustomPainter { if (isSameDate(visibleDates[i], selectedDate)) { final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - showWeekNumber, width, isMobilePlatform); + showWeekNumber, + width, + isMobilePlatform, + ); _cellWidth = (size.width - weekNumberPanelWidth) / DateTime.daysPerWeek; final int columnIndex = (i / DateTime.daysPerWeek).truncate(); _yPosition = columnIndex * _cellHeight; @@ -12257,7 +14191,11 @@ class _SelectionPainter extends CustomPainter { } void _drawDaySelection( - Canvas canvas, Size size, double width, double timeLabelWidth) { + Canvas canvas, + Size size, + double width, + double timeLabelWidth, + ) { if (isSameDate(visibleDates[0], selectedDate)) { if (isRTL) { _xPosition = 0; @@ -12268,7 +14206,10 @@ class _SelectionPainter extends CustomPainter { selectedDate = _updateSelectedDate(); _yPosition = AppointmentHelper.timeToPosition( - calendar, selectedDate!, timeIntervalHeight); + calendar, + selectedDate!, + timeIntervalHeight, + ); _drawSlotSelection(width + timeLabelWidth, size.height, canvas); } } @@ -12282,13 +14223,16 @@ class _SelectionPainter extends CustomPainter { /// modified the selected date to 1 PM so that the selection will render the /// exact time slot. DateTime _updateSelectedDate() { - final int timeInterval = - CalendarViewHelper.getTimeInterval(calendar.timeSlotViewSettings); + final int timeInterval = CalendarViewHelper.getTimeInterval( + calendar.timeSlotViewSettings, + ); final int startHour = calendar.timeSlotViewSettings.startHour.toInt(); - final double startMinute = (calendar.timeSlotViewSettings.startHour - + final double startMinute = + (calendar.timeSlotViewSettings.startHour - calendar.timeSlotViewSettings.startHour.toInt()) * 60; - final int selectedMinutes = ((selectedDate!.hour - startHour) * 60) + + final int selectedMinutes = + ((selectedDate!.hour - startHour) * 60) + (selectedDate!.minute - startMinute.toInt()); if (selectedMinutes % timeInterval != 0) { final int diff = selectedMinutes % timeInterval; @@ -12303,10 +14247,17 @@ class _SelectionPainter extends CustomPainter { } void _drawWeekSelection( - Canvas canvas, Size size, double timeLabelWidth, double width) { + Canvas canvas, + Size size, + double timeLabelWidth, + double width, + ) { final int visibleDatesLength = visibleDates.length; if (isDateWithInDateRange( - visibleDates[0], visibleDates[visibleDatesLength - 1], selectedDate)) { + visibleDates[0], + visibleDates[visibleDatesLength - 1], + selectedDate, + )) { for (int i = 0; i < visibleDatesLength; i++) { if (isSameDate(selectedDate, visibleDates[i])) { final int rowIndex = i; @@ -12318,7 +14269,10 @@ class _SelectionPainter extends CustomPainter { selectedDate = _updateSelectedDate(); _yPosition = AppointmentHelper.timeToPosition( - calendar, selectedDate!, timeIntervalHeight); + calendar, + selectedDate!, + timeIntervalHeight, + ); _drawSlotSelection(width + timeLabelWidth, size.height, canvas); break; } @@ -12338,12 +14292,17 @@ class _SelectionPainter extends CustomPainter { void _drawTimelineMonthSelection(Canvas canvas, Size size, double width) { if (!isDateWithInDateRange( - visibleDates[0], visibleDates[visibleDates.length - 1], selectedDate)) { + visibleDates[0], + visibleDates[visibleDates.length - 1], + selectedDate, + )) { return; } if (CalendarViewHelper.isDateInDateCollection( - calendar.blackoutDates, selectedDate!)) { + calendar.blackoutDates, + selectedDate!, + )) { return; } @@ -12352,9 +14311,10 @@ class _SelectionPainter extends CustomPainter { _yPosition = _getTimelineYPosition(); _xPosition = isRTL ? size.width - ((i + 1) * _cellWidth) : i * _cellWidth; - final double height = selectedResourceIndex == -1 - ? size.height - : _yPosition + resourceItemHeight!; + final double height = + selectedResourceIndex == -1 + ? size.height + : _yPosition + resourceItemHeight!; _drawSlotSelection(width, height, canvas); break; } @@ -12363,21 +14323,29 @@ class _SelectionPainter extends CustomPainter { void _drawTimelineWeekSelection(Canvas canvas, Size size, double width) { if (isDateWithInDateRange( - visibleDates[0], visibleDates[visibleDates.length - 1], selectedDate)) { + visibleDates[0], + visibleDates[visibleDates.length - 1], + selectedDate, + )) { selectedDate = _updateSelectedDate(); for (int i = 0; i < visibleDates.length; i++) { if (isSameDate(selectedDate, visibleDates[i])) { final double singleViewWidth = width / visibleDates.length; - _xPosition = (i * singleViewWidth) + + _xPosition = + (i * singleViewWidth) + AppointmentHelper.timeToPosition( - calendar, selectedDate!, timeIntervalHeight); + calendar, + selectedDate!, + timeIntervalHeight, + ); if (isRTL) { _xPosition = size.width - _xPosition - _cellWidth; } _yPosition = _getTimelineYPosition(); - final double height = selectedResourceIndex == -1 - ? size.height - : _yPosition + resourceItemHeight!; + final double height = + selectedResourceIndex == -1 + ? size.height + : _yPosition + resourceItemHeight!; _drawSlotSelection(width, height, canvas); break; } @@ -12388,10 +14356,14 @@ class _SelectionPainter extends CustomPainter { void _drawAppointmentSelection(Canvas canvas) { Rect rect = appointmentView!.appointmentRect!.outerRect; rect = Rect.fromLTRB(rect.left, rect.top, rect.right, rect.bottom); - _boxPainter = selectionDecoration! - .createBoxPainter(_updateSelectionDecorationPainter); - _boxPainter.paint(canvas, Offset(rect.left, rect.top), - ImageConfiguration(size: rect.size)); + _boxPainter = selectionDecoration!.createBoxPainter( + _updateSelectionDecorationPainter, + ); + _boxPainter.paint( + canvas, + Offset(rect.left, rect.top), + ImageConfiguration(size: rect.size), + ); } /// Used to pass the argument of create box painter and it is called when @@ -12404,19 +14376,24 @@ class _SelectionPainter extends CustomPainter { //// padding used to avoid first, last row and column selection clipping. const double padding = 0.5; final Rect rect = Rect.fromLTRB( - _xPosition == 0 ? _xPosition + padding : _xPosition, - _yPosition == 0 ? _yPosition + padding : _yPosition, - _xPosition + _cellWidth == width - ? _xPosition + _cellWidth - padding - : _xPosition + _cellWidth, - _yPosition + _cellHeight == height - ? _yPosition + _cellHeight - padding - : _yPosition + _cellHeight); + _xPosition == 0 ? _xPosition + padding : _xPosition, + _yPosition == 0 ? _yPosition + padding : _yPosition, + _xPosition + _cellWidth == width + ? _xPosition + _cellWidth - padding + : _xPosition + _cellWidth, + _yPosition + _cellHeight == height + ? _yPosition + _cellHeight - padding + : _yPosition + _cellHeight, + ); - _boxPainter = selectionDecoration! - .createBoxPainter(_updateSelectionDecorationPainter); - _boxPainter.paint(canvas, Offset(rect.left, rect.top), - ImageConfiguration(size: rect.size, textDirection: TextDirection.ltr)); + _boxPainter = selectionDecoration!.createBoxPainter( + _updateSelectionDecorationPainter, + ); + _boxPainter.paint( + canvas, + Offset(rect.left, rect.top), + ImageConfiguration(size: rect.size, textDirection: TextDirection.ltr), + ); } @override @@ -12433,16 +14410,17 @@ class _SelectionPainter extends CustomPainter { class _TimeRulerView extends CustomPainter { _TimeRulerView( - this.horizontalLinesCount, - this.timeIntervalHeight, - this.timeSlotViewSettings, - this.cellBorderColor, - this.isRTL, - this.locale, - this.calendarTheme, - this.isTimelineView, - this.visibleDates, - this.textScaleFactor); + this.horizontalLinesCount, + this.timeIntervalHeight, + this.timeSlotViewSettings, + this.cellBorderColor, + this.isRTL, + this.locale, + this.calendarTheme, + this.isTimelineView, + this.visibleDates, + this.textScaleFactor, + ); final double horizontalLinesCount; final double timeIntervalHeight; @@ -12472,8 +14450,11 @@ class _TimeRulerView extends CustomPainter { if (!isTimelineView) { final double lineXPosition = isRTL ? offset : size.width - offset; // Draw vertical time label line - canvas.drawLine(Offset(lineXPosition, 0), - Offset(lineXPosition, size.height), _linePainter); + canvas.drawLine( + Offset(lineXPosition, 0), + Offset(lineXPosition, size.height), + _linePainter, + ); } _textPainter.textDirection = @@ -12483,7 +14464,8 @@ class _TimeRulerView extends CustomPainter { final TextStyle timeTextStyle = calendarTheme.timeTextStyle!; - final double hour = (timeSlotViewSettings.startHour - + final double hour = + (timeSlotViewSettings.startHour - timeSlotViewSettings.startHour.toInt()) * 60; if (isTimelineView) { @@ -12493,7 +14475,14 @@ class _TimeRulerView extends CustomPainter { for (int i = 0; i < visibleDates.length; i++) { date = visibleDates[i]; _drawTimeLabels( - canvas, size, date, hour, xPosition, yPosition, timeTextStyle); + canvas, + size, + date, + hour, + xPosition, + yPosition, + timeTextStyle, + ); if (isRTL) { xPosition -= timelineViewWidth; } else { @@ -12502,47 +14491,74 @@ class _TimeRulerView extends CustomPainter { } } else { _drawTimeLabels( - canvas, size, date, hour, xPosition, yPosition, timeTextStyle); + canvas, + size, + date, + hour, + xPosition, + yPosition, + timeTextStyle, + ); } } /// Draws the time labels in the time label view for timeslot views in /// calendar. - void _drawTimeLabels(Canvas canvas, Size size, DateTime date, double hour, - double xPosition, double yPosition, TextStyle timeTextStyle) { + void _drawTimeLabels( + Canvas canvas, + Size size, + DateTime date, + double hour, + double xPosition, + double yPosition, + TextStyle timeTextStyle, + ) { const int padding = 5; - final int timeInterval = - CalendarViewHelper.getTimeInterval(timeSlotViewSettings); + final int timeInterval = CalendarViewHelper.getTimeInterval( + timeSlotViewSettings, + ); - final List timeFormatStrings = - CalendarViewHelper.getListFromString(timeSlotViewSettings.timeFormat); + final List timeFormatStrings = CalendarViewHelper.getListFromString( + timeSlotViewSettings.timeFormat, + ); /// For timeline view we will draw 24 lines where as in day, week and work /// week view we will draw 23 lines excluding the 12 AM, hence to rectify /// this the i value handled accordingly. - for (int i = isTimelineView ? 0 : 1; - i <= (isTimelineView ? horizontalLinesCount - 1 : horizontalLinesCount); - i++) { + for ( + int i = isTimelineView ? 0 : 1; + i <= (isTimelineView ? horizontalLinesCount - 1 : horizontalLinesCount); + i++ + ) { if (isTimelineView) { canvas.save(); canvas.clipRect( - Rect.fromLTWH(xPosition, 0, timeIntervalHeight, size.height)); + Rect.fromLTWH(xPosition, 0, timeIntervalHeight, size.height), + ); canvas.restore(); canvas.drawLine( - Offset(xPosition, 0), Offset(xPosition, size.height), _linePainter); + Offset(xPosition, 0), + Offset(xPosition, size.height), + _linePainter, + ); } final double minute = (i * timeInterval) + hour; - date = DateTime(date.year, date.month, date.day, - timeSlotViewSettings.startHour.toInt(), minute.toInt()); + date = DateTime( + date.year, + date.month, + date.day, + timeSlotViewSettings.startHour.toInt(), + minute.toInt(), + ); final String time = CalendarViewHelper.getLocalizedString( - date, timeFormatStrings, locale); - - final TextSpan span = TextSpan( - text: time, - style: timeTextStyle, + date, + timeFormatStrings, + locale, ); + final TextSpan span = TextSpan(text: time, style: timeTextStyle); + final double cellWidth = isTimelineView ? timeIntervalHeight : size.width; _textPainter.text = span; @@ -12571,10 +14587,14 @@ class _TimeRulerView extends CustomPainter { _textPainter.paint(canvas, Offset(startXPosition, startYPosition)); if (!isTimelineView) { - final Offset start = - Offset(isRTL ? 0 : size.width - (startXPosition / 2), yPosition); - final Offset end = - Offset(isRTL ? startXPosition / 2 : size.width, yPosition); + final Offset start = Offset( + isRTL ? 0 : size.width - (startXPosition / 2), + yPosition, + ); + final Offset end = Offset( + isRTL ? startXPosition / 2 : size.width, + yPosition, + ); canvas.drawLine(start, end, _linePainter); yPosition += timeIntervalHeight; if (yPosition.round() == size.height.round()) { @@ -12605,23 +14625,30 @@ class _TimeRulerView extends CustomPainter { } class _CalendarMultiChildContainer extends Stack { - const _CalendarMultiChildContainer( - // ignore: unused_element_parameter - {this.painter, - List children = const [], - required this.width, - required this.height}) - : super(children: children); + const _CalendarMultiChildContainer({ + // ignore: unused_element_parameter + this.painter, + List children = const [], + required this.width, + required this.height, + required this.builder, + }) : super(children: children); final CustomPainter? painter; final double width; final double height; + final MonthCellBuilder? builder; @override RenderStack createRenderObject(BuildContext context) { final Directionality? widget = context.dependOnInheritedWidgetOfExactType(); - return _MultiChildContainerRenderObject(width, height, - painter: painter, direction: widget?.textDirection); + return _MultiChildContainerRenderObject( + width, + height, + builder, + painter: painter, + direction: widget?.textDirection, + ); } @override @@ -12640,10 +14667,16 @@ class _CalendarMultiChildContainer extends Stack { } class _MultiChildContainerRenderObject extends RenderStack { - _MultiChildContainerRenderObject(this._width, this._height, - {CustomPainter? painter, TextDirection? direction}) - : _painter = painter, - super(textDirection: direction); + _MultiChildContainerRenderObject( + this._width, + this._height, + this.builder, { + CustomPainter? painter, + TextDirection? direction, + }) : _painter = painter, + super(textDirection: direction); + + final MonthCellBuilder? builder; CustomPainter? get painter => _painter; CustomPainter? _painter; @@ -12717,24 +14750,27 @@ class _MultiChildContainerRenderObject extends RenderStack { @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { - RenderBox? child = firstChild; - - while (child != null) { - final StackParentData childParentData = - child.parentData! as StackParentData; - final bool isHit = result.addWithPaintOffset( - offset: childParentData.offset, - position: position, - hitTest: (BoxHitTestResult result, Offset transformed) { - return child!.hitTest(result, position: transformed); - }, - ); - if (isHit) { - return true; + if (builder != null) { + RenderBox? child = lastChild; + bool isChildHit = false; + while (child != null) { + final StackParentData childParentData = + child.parentData! as StackParentData; + final bool isHit = result.addWithPaintOffset( + offset: childParentData.offset, + position: position, + hitTest: (BoxHitTestResult result, Offset transformed) { + return child!.hitTest(result, position: transformed); + }, + ); + if (isHit) { + isChildHit = true; + } + child = childParentData.previousSibling; } - child = childParentData.nextSibling; + return isChildHit; } - return false; + return super.hitTestChildren(result, position: position); } @override @@ -12752,8 +14788,10 @@ class _MultiChildContainerRenderObject extends RenderStack { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); for (dynamic child = firstChild; child != null; child = childAfter(child)) { child.layout(constraints); } @@ -12785,9 +14823,10 @@ class _MultiChildContainerRenderObject extends RenderStack { final List semanticsNodes = []; for (int i = 0; i < semantics.length; i++) { final CustomPainterSemantics currentSemantics = semantics[i]; - final SemanticsNode newChild = _cacheNodes!.isNotEmpty - ? _cacheNodes!.removeAt(0) - : SemanticsNode(key: currentSemantics.key); + final SemanticsNode newChild = + _cacheNodes!.isNotEmpty + ? _cacheNodes!.removeAt(0) + : SemanticsNode(key: currentSemantics.key); final SemanticsProperties properties = currentSemantics.properties; final SemanticsConfiguration config = SemanticsConfiguration(); @@ -12831,10 +14870,12 @@ class _MultiChildContainerRenderObject extends RenderStack { semantics.addAll(painter!.semanticsBuilder!(size)); } // ignore: avoid_as - for (RenderRepaintBoundary? child = firstChild! as RenderRepaintBoundary; - child != null; - // ignore: avoid_as - child = childAfter(child) as RenderRepaintBoundary?) { + for ( + RenderRepaintBoundary? child = firstChild! as RenderRepaintBoundary; + child != null; + // ignore: avoid_as + child = childAfter(child) as RenderRepaintBoundary? + ) { if (child.child is! CustomCalendarRenderObject) { continue; } @@ -12854,7 +14895,7 @@ class _MultiChildContainerRenderObject extends RenderStack { class _CustomNeverScrollableScrollPhysics extends NeverScrollableScrollPhysics { /// Creates scroll physics that does not let the user scroll. const _CustomNeverScrollableScrollPhysics({ScrollPhysics? parent}) - : super(parent: parent); + : super(parent: parent); @override _CustomNeverScrollableScrollPhysics applyTo(ScrollPhysics? ancestor) { @@ -12862,8 +14903,10 @@ class _CustomNeverScrollableScrollPhysics extends NeverScrollableScrollPhysics { /// physics, because flutter framework set different parent physics /// based on platform(iOS, Android, etc.,) return _CustomNeverScrollableScrollPhysics( - parent: buildParent(const ClampingScrollPhysics( - parent: RangeMaintainingScrollPhysics()))); + parent: buildParent( + const ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics()), + ), + ); } } @@ -12918,7 +14961,8 @@ class _CurrentTimeIndicator extends CustomPainter { return; } - final double minuteHeight = timeIntervalSize / + final double minuteHeight = + timeIntervalSize / CalendarViewHelper.getTimeInterval(timeSlotViewSettings); if (timeZoneLoaded && timeZone != '') { @@ -12928,16 +14972,19 @@ class _CurrentTimeIndicator extends CustomPainter { } final double currentTimePosition = CalendarViewHelper.getTimeToPosition( - Duration( - hours: getLocationDateTime.hour, - minutes: getLocationDateTime.minute), - timeSlotViewSettings, - minuteHeight); - final Paint painter = Paint() - ..color = todayHighlightColor! - ..strokeWidth = 1 - ..isAntiAlias = true - ..style = PaintingStyle.fill; + Duration( + hours: getLocationDateTime.hour, + minutes: getLocationDateTime.minute, + ), + timeSlotViewSettings, + minuteHeight, + ); + final Paint painter = + Paint() + ..color = todayHighlightColor! + ..strokeWidth = 1 + ..isAntiAlias = true + ..style = PaintingStyle.fill; if (isTimelineView) { final double viewSize = size.width / visibleDates.length; double startXPosition = (index * viewSize) + currentTimePosition; @@ -12945,8 +14992,11 @@ class _CurrentTimeIndicator extends CustomPainter { startXPosition = size.width - startXPosition; } canvas.drawCircle(Offset(startXPosition, 5), 5, painter); - canvas.drawLine(Offset(startXPosition, 0), - Offset(startXPosition, size.height), painter); + canvas.drawLine( + Offset(startXPosition, 0), + Offset(startXPosition, size.height), + painter, + ); } else { final double viewSize = (size.width - timeRulerSize) / visibleDates.length; @@ -12960,8 +15010,11 @@ class _CurrentTimeIndicator extends CustomPainter { startXPosition = size.width - startXPosition; } canvas.drawCircle(Offset(startXPosition, startYPosition), 5, painter); - canvas.drawLine(Offset(viewStartPosition, startYPosition), - Offset(viewEndPosition, startYPosition), painter); + canvas.drawLine( + Offset(viewStartPosition, startYPosition), + Offset(viewEndPosition, startYPosition), + painter, + ); } } @@ -12978,28 +15031,31 @@ class _CurrentTimeIndicator extends CustomPainter { /// Returns the date time value from the position. DateTime? _timeFromPosition( - DateTime date, - TimeSlotViewSettings timeSlotViewSettings, - double positionY, - _CalendarViewState? currentState, - double timeIntervalHeight, - bool isTimelineView) { + DateTime date, + TimeSlotViewSettings timeSlotViewSettings, + double positionY, + _CalendarViewState? currentState, + double timeIntervalHeight, + bool isTimelineView, +) { final double topPosition = currentState == null ? 0 : currentState._scrollController!.offset; final double singleIntervalHeightForAnHour = (60 / CalendarViewHelper.getTimeInterval(timeSlotViewSettings)) * - timeIntervalHeight; + timeIntervalHeight; final double startHour = timeSlotViewSettings.startHour; final double endHour = timeSlotViewSettings.endHour; if (isTimelineView) { if (currentState!._isRTL) { - positionY = (currentState._scrollController!.offset % + positionY = + (currentState._scrollController!.offset % _getSingleViewWidthForTimeLineView(currentState)) + (currentState._scrollController!.position.viewportDimension - positionY); } else { - positionY += currentState._scrollController!.offset % + positionY += + currentState._scrollController!.offset % _getSingleViewWidthForTimeLineView(currentState); } } else { @@ -13029,22 +15085,23 @@ double _getSingleViewWidthForTimeLineView(_CalendarViewState viewState) { } class _ResizingPaintDetails { - _ResizingPaintDetails( - // ignore: unused_element_parameter - {this.appointmentView, - required this.position, - // ignore: unused_element_parameter - this.isAllDayPanel = false, - // ignore: unused_element_parameter - this.scrollPosition, - // ignore: unused_element_parameter - this.monthRowCount = 0, - // ignore: unused_element_parameter - this.monthCellHeight, - // ignore: unused_element_parameter - this.appointmentColor = Colors.transparent, - // ignore: unused_element_parameter - this.resizingTime}); + _ResizingPaintDetails({ + // ignore: unused_element_parameter + this.appointmentView, + required this.position, + // ignore: unused_element_parameter + this.isAllDayPanel = false, + // ignore: unused_element_parameter + this.scrollPosition, + // ignore: unused_element_parameter + this.monthRowCount = 0, + // ignore: unused_element_parameter + this.monthCellHeight, + // ignore: unused_element_parameter + this.appointmentColor = Colors.transparent, + // ignore: unused_element_parameter + this.resizingTime, + }); AppointmentView? appointmentView; final ValueNotifier position; @@ -13058,22 +15115,22 @@ class _ResizingPaintDetails { class _ResizingAppointmentPainter extends CustomPainter { _ResizingAppointmentPainter( - this.resizingDetails, - this.isRTL, - this.textScaleFactor, - this.isMobilePlatform, - this.appointmentTextStyle, - this.allDayHeight, - this.viewHeaderHeight, - this.timeLabelWidth, - this.timeIntervalHeight, - this.scrollController, - this.dragAndDropSettings, - this.view, - this.mouseCursor, - this.weekNumberPanelWidth, - this.calendarTheme) - : super(repaint: resizingDetails.value.position); + this.resizingDetails, + this.isRTL, + this.textScaleFactor, + this.isMobilePlatform, + this.appointmentTextStyle, + this.allDayHeight, + this.viewHeaderHeight, + this.timeLabelWidth, + this.timeIntervalHeight, + this.scrollController, + this.dragAndDropSettings, + this.view, + this.mouseCursor, + this.weekNumberPanelWidth, + this.calendarTheme, + ) : super(repaint: resizingDetails.value.position); final ValueNotifier<_ResizingPaintDetails> resizingDetails; @@ -13121,9 +15178,11 @@ class _ResizingAppointmentPainter extends CustomPainter { ? 0 : resizingDetails.value.scrollPosition ?? scrollController!.offset; - final bool isForwardResize = mouseCursor == SystemMouseCursors.resizeDown || + final bool isForwardResize = + mouseCursor == SystemMouseCursors.resizeDown || mouseCursor == SystemMouseCursors.resizeRight; - final bool isBackwardResize = mouseCursor == SystemMouseCursors.resizeUp || + final bool isBackwardResize = + mouseCursor == SystemMouseCursors.resizeUp || mouseCursor == SystemMouseCursors.resizeLeft; const int textStartPadding = 3; @@ -13133,7 +15192,8 @@ class _ResizingAppointmentPainter extends CustomPainter { _shadowPainter.color = resizingDetails.value.appointmentColor; final bool isTimelineView = CalendarViewHelper.isTimelineView(view); - final bool isHorizontalResize = resizingDetails.value.isAllDayPanel || + final bool isHorizontalResize = + resizingDetails.value.isAllDayPanel || isTimelineView || view == CalendarView.month; double left = resizingDetails.value.position.value!.dx, @@ -13206,19 +15266,28 @@ class _ResizingAppointmentPainter extends CustomPainter { right = isRTL ? size.width : size.width - weekNumberPanelWidth; } - bottom = top + + bottom = + top + resizingDetails.value.appointmentView!.appointmentRect!.height; rect = Rect.fromLTRB(left, top, right, bottom); canvas.drawRect(rect, _shadowPainter); - paintBorder(canvas, rect, - left: BorderSide( - color: calendarTheme.selectionBorderColor!, width: 2), - right: BorderSide( - color: calendarTheme.selectionBorderColor!, width: 2), - bottom: BorderSide( - color: calendarTheme.selectionBorderColor!, width: 2), - top: BorderSide( - color: calendarTheme.selectionBorderColor!, width: 2)); + paintBorder( + canvas, + rect, + left: BorderSide( + color: calendarTheme.selectionBorderColor!, + width: 2, + ), + right: BorderSide( + color: calendarTheme.selectionBorderColor!, + width: 2, + ), + bottom: BorderSide( + color: calendarTheme.selectionBorderColor!, + width: 2, + ), + top: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), + ); } } else { if (isForwardResize) { @@ -13229,23 +15298,29 @@ class _ResizingAppointmentPainter extends CustomPainter { } else if (isTimelineView) { left = resizingDetails.value.appointmentView!.appointmentRect!.left - - scrollOffset; + scrollOffset; if (isRTL) { left = scrollOffset + scrollController!.position.viewportDimension; - left = left - + left = + left - ((scrollController!.position.viewportDimension + scrollController!.position.maxScrollExtent) - resizingDetails - .value.appointmentView!.appointmentRect!.left); + .value + .appointmentView! + .appointmentRect! + .left); } } right = resizingDetails.value.position.value!.dx; top = resizingDetails.value.position.value!.dy; - bottom = top + + bottom = + top + resizingDetails.value.appointmentView!.appointmentRect!.height; } else { - top = resizingDetails.value.appointmentView!.appointmentRect!.top - + top = + resizingDetails.value.appointmentView!.appointmentRect!.top - scrollOffset + allDayHeight + viewHeaderHeight; @@ -13267,29 +15342,34 @@ class _ResizingAppointmentPainter extends CustomPainter { } else if (isTimelineView) { right = resizingDetails.value.appointmentView!.appointmentRect!.right - - scrollOffset; + scrollOffset; if (isRTL) { right = scrollOffset + scrollController!.position.viewportDimension; - right = right - + right = + right - ((scrollController!.position.viewportDimension + scrollController!.position.maxScrollExtent) - resizingDetails - .value.appointmentView!.appointmentRect!.right); + .value + .appointmentView! + .appointmentRect! + .right); } } left = resizingDetails.value.position.value!.dx; top = resizingDetails.value.position.value!.dy; - bottom = top + + bottom = + top + resizingDetails.value.appointmentView!.appointmentRect!.height; } else { top = resizingDetails.value.position.value!.dy; bottom = resizingDetails.value.appointmentView!.appointmentRect!.bottom - - scrollOffset + - allDayHeight + - viewHeaderHeight; + scrollOffset + + allDayHeight + + viewHeaderHeight; if (top < viewHeaderHeight + allDayHeight) { top = viewHeaderHeight + allDayHeight; } @@ -13325,39 +15405,56 @@ class _ResizingAppointmentPainter extends CustomPainter { final bool isRecurrenceAppointment = resizingDetails.value.appointmentView!.appointment!.recurrenceRule != - null && - resizingDetails - .value.appointmentView!.appointment!.recurrenceRule!.isNotEmpty; + null && + resizingDetails + .value + .appointmentView! + .appointment! + .recurrenceRule! + .isNotEmpty; _updateTextPainter(span); if (view != CalendarView.month) { - _addSubjectTextForTimeslotViews(canvas, textStartPadding, xPosition, - yPosition, isRecurrenceAppointment, rect); + _addSubjectTextForTimeslotViews( + canvas, + textStartPadding, + xPosition, + yPosition, + isRecurrenceAppointment, + rect, + ); } else { _addSubjectTextForMonthView( - canvas, - resizingDetails.value.appointmentView!.appointmentRect!, - appointmentTextStyle, - span, - isRecurrenceAppointment, - xPosition, - rect, - yPosition); + canvas, + resizingDetails.value.appointmentView!.appointmentRect!, + appointmentTextStyle, + span, + isRecurrenceAppointment, + xPosition, + rect, + yPosition, + ); } - paintBorder(canvas, rect, - left: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), - right: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), - bottom: - BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), - top: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2)); + paintBorder( + canvas, + rect, + left: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), + right: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), + bottom: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), + top: BorderSide(color: calendarTheme.selectionBorderColor!, width: 2), + ); } /// Draw the time indicator when resizing the appointment on all calendar /// views except month and timelineMonth views. void _drawTimeIndicator( - Canvas canvas, bool isTimelineView, Size size, bool isBackwardResize) { + Canvas canvas, + bool isTimelineView, + Size size, + bool isBackwardResize, + ) { if (view == CalendarView.month || view == CalendarView.timelineMonth) { return; } @@ -13369,13 +15466,15 @@ class _ResizingAppointmentPainter extends CustomPainter { } final TextSpan span = TextSpan( - text: DateFormat(dragAndDropSettings.indicatorTimeFormat) - .format(resizingDetails.value.resizingTime!), + text: DateFormat( + dragAndDropSettings.indicatorTimeFormat, + ).format(resizingDetails.value.resizingTime!), style: calendarTheme.timeIndicatorTextStyle, ); _updateTextPainter(span); _textPainter.layout( - maxWidth: isTimelineView ? timeIntervalHeight : timeLabelWidth); + maxWidth: isTimelineView ? timeIntervalHeight : timeLabelWidth, + ); double xPosition; double yPosition; if (isTimelineView) { @@ -13406,29 +15505,33 @@ class _ResizingAppointmentPainter extends CustomPainter { } void _addSubjectTextForTimeslotViews( - Canvas canvas, - int textStartPadding, - double xPosition, - double yPosition, - bool isRecurrenceAppointment, - Rect rect) { + Canvas canvas, + int textStartPadding, + double xPosition, + double yPosition, + bool isRecurrenceAppointment, + Rect rect, + ) { final double totalHeight = resizingDetails.value.appointmentView!.appointmentRect!.height - - textStartPadding; + textStartPadding; _updatePainterMaxLines(totalHeight); double maxTextWidth = resizingDetails.value.appointmentView!.appointmentRect!.width - - textStartPadding; + textStartPadding; maxTextWidth = maxTextWidth > 0 ? maxTextWidth : 0; _textPainter.layout(maxWidth: maxTextWidth); if (isRTL) { xPosition -= textStartPadding + _textPainter.width; } _textPainter.paint( - canvas, - Offset(xPosition + (isRTL ? 0 : textStartPadding), - yPosition + textStartPadding)); + canvas, + Offset( + xPosition + (isRTL ? 0 : textStartPadding), + yPosition + textStartPadding, + ), + ); if (isRecurrenceAppointment || resizingDetails.value.appointmentView!.appointment!.recurrenceId != null) { @@ -13437,19 +15540,25 @@ class _ResizingAppointmentPainter extends CustomPainter { textSize = rect.width > rect.height ? rect.height : rect.width; } _addRecurrenceIcon( - rect, canvas, textStartPadding, isRecurrenceAppointment, textSize); + rect, + canvas, + textStartPadding, + isRecurrenceAppointment, + textSize, + ); } } void _addSubjectTextForMonthView( - Canvas canvas, - RRect appointmentRect, - TextStyle style, - TextSpan span, - bool isRecurrenceAppointment, - double xPosition, - Rect rect, - double yPosition) { + Canvas canvas, + RRect appointmentRect, + TextStyle style, + TextSpan span, + bool isRecurrenceAppointment, + double xPosition, + Rect rect, + double yPosition, + ) { double textSize = -1; if (textSize == -1) { //// left and right side padding value 2 subtracted in appointment width @@ -13460,8 +15569,9 @@ class _ResizingAppointmentPainter extends CustomPainter { if (_textPainter.height >= appointmentRect.height) { style = style.copyWith(fontSize: j); span = TextSpan( - text: resizingDetails.value.appointmentView!.appointment!.subject, - style: style); + text: resizingDetails.value.appointmentView!.appointment!.subject, + style: style, + ); _updateTextPainter(span); } else { textSize = j + 1; @@ -13470,8 +15580,9 @@ class _ResizingAppointmentPainter extends CustomPainter { } } else { span = TextSpan( - text: resizingDetails.value.appointmentView!.appointment!.subject, - style: style.copyWith(fontSize: textSize)); + text: resizingDetails.value.appointmentView!.appointment!.subject, + style: style.copyWith(fontSize: textSize), + ); _updateTextPainter(span); } final double textWidth = @@ -13500,13 +15611,21 @@ class _ResizingAppointmentPainter extends CustomPainter { _textPainter.textScaler = TextScaler.linear(textScaleFactor); } - void _addRecurrenceIcon(Rect rect, Canvas canvas, int? textPadding, - bool isRecurrenceAppointment, double textSize) { + void _addRecurrenceIcon( + Rect rect, + Canvas canvas, + int? textPadding, + bool isRecurrenceAppointment, + double textSize, + ) { const double xPadding = 2; const double bottomPadding = 2; final TextSpan icon = AppointmentHelper.getRecurrenceIcon( - appointmentTextStyle.color!, textSize, isRecurrenceAppointment); + appointmentTextStyle.color!, + textSize, + isRecurrenceAppointment, + ); _textPainter.text = icon; if (view == CalendarView.month) { @@ -13514,39 +15633,51 @@ class _ResizingAppointmentPainter extends CustomPainter { final double yPosition = rect.top + ((rect.height - _textPainter.height) / 2); const double rightPadding = 0; - final double recurrenceStartPosition = isRTL - ? rect.left + rightPadding - : rect.right - _textPainter.width - rightPadding; + final double recurrenceStartPosition = + isRTL + ? rect.left + rightPadding + : rect.right - _textPainter.width - rightPadding; canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(recurrenceStartPosition, yPosition, - recurrenceStartPosition + _textPainter.width, rect.bottom), - resizingDetails.value.appointmentView!.appointmentRect!.tlRadius), - _shadowPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + recurrenceStartPosition, + yPosition, + recurrenceStartPosition + _textPainter.width, + rect.bottom, + ), + resizingDetails.value.appointmentView!.appointmentRect!.tlRadius, + ), + _shadowPainter, + ); _textPainter.paint(canvas, Offset(recurrenceStartPosition, yPosition)); } else { double maxTextWidth = resizingDetails.value.appointmentView!.appointmentRect!.width - - textPadding! - - 2; + textPadding! - + 2; maxTextWidth = maxTextWidth > 0 ? maxTextWidth : 0; _textPainter.layout(maxWidth: maxTextWidth); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - isRTL - ? rect.left + textSize + xPadding - : rect.right - textSize - xPadding, - rect.bottom - bottomPadding - textSize, - isRTL ? rect.left : rect.right, - rect.bottom), - resizingDetails.value.appointmentView!.appointmentRect!.tlRadius), - _shadowPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + isRTL + ? rect.left + textSize + xPadding + : rect.right - textSize - xPadding, + rect.bottom - bottomPadding - textSize, + isRTL ? rect.left : rect.right, + rect.bottom, + ), + resizingDetails.value.appointmentView!.appointmentRect!.tlRadius, + ), + _shadowPainter, + ); _textPainter.paint( - canvas, - Offset( - isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, - rect.bottom - bottomPadding - textSize)); + canvas, + Offset( + isRTL ? rect.left + xPadding : rect.right - textSize - xPadding, + rect.bottom - bottomPadding - textSize, + ), + ); } } @@ -13564,7 +15695,9 @@ class _ResizingAppointmentPainter extends CustomPainter { } dynamic _getCalendarAppointmentToObject( - CalendarAppointment? calendarAppointment, SfCalendar calendar) { + CalendarAppointment? calendarAppointment, + SfCalendar calendar, +) { if (calendarAppointment == null) { return null; } @@ -13575,22 +15708,27 @@ dynamic _getCalendarAppointmentToObject( if (calendarAppointment.data is Appointment) { return appointment; } - final dynamic customObject = calendar.dataSource! - .convertAppointmentToObject(calendarAppointment.data, appointment); - assert(customObject != null, - 'Implement convertToCalendarAppointment method from CalendarDataSource'); + final dynamic customObject = calendar.dataSource!.convertAppointmentToObject( + calendarAppointment.data, + appointment, + ); + assert( + customObject != null, + 'Implement convertToCalendarAppointment method from CalendarDataSource', + ); return customObject; } class _DragPaintDetails { - _DragPaintDetails( - // ignore: unused_element_parameter - {this.appointmentView, - required this.position, - // ignore: unused_element_parameter - this.draggingTime, - // ignore: unused_element_parameter - this.timeIntervalHeight}); + _DragPaintDetails({ + // ignore: unused_element_parameter + this.appointmentView, + required this.position, + // ignore: unused_element_parameter + this.draggingTime, + // ignore: unused_element_parameter + this.timeIntervalHeight, + }); AppointmentView? appointmentView; final ValueNotifier position; @@ -13601,21 +15739,22 @@ class _DragPaintDetails { @immutable class _DraggingAppointmentWidget extends StatefulWidget { const _DraggingAppointmentWidget( - this.dragDetails, - this.isRTL, - this.textScaleFactor, - this.isMobilePlatform, - this.appointmentTextStyle, - this.dragAndDropSettings, - this.calendarView, - this.allDayPanelHeight, - this.viewHeaderHeight, - this.timeLabelWidth, - this.resourceItemHeight, - this.calendarTheme, - this.calendar, - this.width, - this.height); + this.dragDetails, + this.isRTL, + this.textScaleFactor, + this.isMobilePlatform, + this.appointmentTextStyle, + this.dragAndDropSettings, + this.calendarView, + this.allDayPanelHeight, + this.viewHeaderHeight, + this.timeLabelWidth, + this.resourceItemHeight, + this.calendarTheme, + this.calendar, + this.width, + this.height, + ); final ValueNotifier<_DragPaintDetails> dragDetails; @@ -13663,8 +15802,9 @@ class _DraggingAppointmentState extends State<_DraggingAppointmentWidget> { @override void dispose() { - widget.dragDetails.value.position - .removeListener(_updateDraggingAppointment); + widget.dragDetails.value.position.removeListener( + _updateDraggingAppointment, + ); super.dispose(); } @@ -13681,26 +15821,31 @@ class _DraggingAppointmentState extends State<_DraggingAppointmentWidget> { if (widget.dragDetails.value.appointmentView != null && widget.calendar.appointmentBuilder != null) { final DateTime date = DateTime( - _draggingAppointmentView!.appointment!.actualStartTime.year, - _draggingAppointmentView!.appointment!.actualStartTime.month, - _draggingAppointmentView!.appointment!.actualStartTime.day); + _draggingAppointmentView!.appointment!.actualStartTime.year, + _draggingAppointmentView!.appointment!.actualStartTime.month, + _draggingAppointmentView!.appointment!.actualStartTime.day, + ); child = widget.calendar.appointmentBuilder!( - context, - CalendarAppointmentDetails( - date, - List.unmodifiable([ - CalendarViewHelper.getAppointmentDetail( - _draggingAppointmentView!.appointment!, - widget.calendar.dataSource) - ]), - Rect.fromLTWH( - widget.dragDetails.value.position.value!.dx, - widget.dragDetails.value.position.value!.dy, - widget.isRTL - ? -_draggingAppointmentView!.appointmentRect!.width - : _draggingAppointmentView!.appointmentRect!.width, - _draggingAppointmentView!.appointmentRect!.height))); + context, + CalendarAppointmentDetails( + date, + List.unmodifiable([ + CalendarViewHelper.getAppointmentDetail( + _draggingAppointmentView!.appointment!, + widget.calendar.dataSource, + ), + ]), + Rect.fromLTWH( + widget.dragDetails.value.position.value!.dx, + widget.dragDetails.value.position.value!.dy, + widget.isRTL + ? -_draggingAppointmentView!.appointmentRect!.width + : _draggingAppointmentView!.appointmentRect!.width, + _draggingAppointmentView!.appointmentRect!.height, + ), + ), + ); } return _DraggingAppointmentRenderObjectWidget( @@ -13727,22 +15872,22 @@ class _DraggingAppointmentState extends State<_DraggingAppointmentWidget> { class _DraggingAppointmentRenderObjectWidget extends SingleChildRenderObjectWidget { const _DraggingAppointmentRenderObjectWidget( - this.dragDetails, - this.isRTL, - this.textScaleFactor, - this.isMobilePlatform, - this.appointmentTextStyle, - this.dragAndDropSettings, - this.calendarView, - this.allDayPanelHeight, - this.viewHeaderHeight, - this.timeLabelWidth, - this.resourceItemHeight, - this.calendarTheme, - this.width, - this.height, - {Widget? child}) - : super(child: child); + this.dragDetails, + this.isRTL, + this.textScaleFactor, + this.isMobilePlatform, + this.appointmentTextStyle, + this.dragAndDropSettings, + this.calendarView, + this.allDayPanelHeight, + this.viewHeaderHeight, + this.timeLabelWidth, + this.resourceItemHeight, + this.calendarTheme, + this.width, + this.height, { + Widget? child, + }) : super(child: child); final _DragPaintDetails dragDetails; final bool isRTL; @@ -13774,25 +15919,28 @@ class _DraggingAppointmentRenderObjectWidget @override RenderObject createRenderObject(BuildContext context) { return _DraggingAppointmentRenderObject( - dragDetails, - isRTL, - textScaleFactor, - isMobilePlatform, - appointmentTextStyle, - dragAndDropSettings, - calendarView, - allDayPanelHeight, - viewHeaderHeight, - timeLabelWidth, - resourceItemHeight, - calendarTheme, - width, - height); + dragDetails, + isRTL, + textScaleFactor, + isMobilePlatform, + appointmentTextStyle, + dragAndDropSettings, + calendarView, + allDayPanelHeight, + viewHeaderHeight, + timeLabelWidth, + resourceItemHeight, + calendarTheme, + width, + height, + ); } @override void updateRenderObject( - BuildContext context, _DraggingAppointmentRenderObject renderObject) { + BuildContext context, + _DraggingAppointmentRenderObject renderObject, + ) { renderObject ..dragDetails = dragDetails ..isRTL = isRTL @@ -13814,20 +15962,21 @@ class _DraggingAppointmentRenderObjectWidget class _DraggingAppointmentRenderObject extends RenderBox with RenderObjectWithChildMixin { _DraggingAppointmentRenderObject( - this._dragDetails, - this._isRTL, - this._textScaleFactor, - this._isMobilePlatform, - this._appointmentTextStyle, - this._dragAndDropSettings, - this._calendarView, - this._allDayPanelHeight, - this._viewHeaderHeight, - this._timeLabelWidth, - this._resourceItemHeight, - this._calendarTheme, - this._width, - this._height); + this._dragDetails, + this._isRTL, + this._textScaleFactor, + this._isMobilePlatform, + this._appointmentTextStyle, + this._dragAndDropSettings, + this._calendarView, + this._allDayPanelHeight, + this._viewHeaderHeight, + this._timeLabelWidth, + this._resourceItemHeight, + this._calendarTheme, + this._width, + this._height, + ); double _width; @@ -14084,14 +16233,19 @@ class _DraggingAppointmentRenderObject extends RenderBox @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); - child?.layout(constraints.copyWith( + child?.layout( + constraints.copyWith( minWidth: dragDetails.appointmentView!.appointmentRect!.width, minHeight: dragDetails.appointmentView!.appointmentRect!.height, maxWidth: dragDetails.appointmentView!.appointmentRect!.width, - maxHeight: dragDetails.appointmentView!.appointmentRect!.height)); + maxHeight: dragDetails.appointmentView!.appointmentRect!.height, + ), + ); } @override @@ -14101,13 +16255,15 @@ class _DraggingAppointmentRenderObject extends RenderBox _drawDefaultUI(context.canvas, isTimelineView); } else { context.paintChild( - child!, - Offset( - isRTL - ? dragDetails.position.value!.dx - - dragDetails.appointmentView!.appointmentRect!.width - : dragDetails.position.value!.dx, - dragDetails.position.value!.dy)); + child!, + Offset( + isRTL + ? dragDetails.position.value!.dx - + dragDetails.appointmentView!.appointmentRect!.width + : dragDetails.position.value!.dx, + dragDetails.position.value!.dy, + ), + ); if (dragAndDropSettings.showTimeIndicator && dragDetails.draggingTime != null) { _drawTimeIndicator(context.canvas, isTimelineView, size); @@ -14126,18 +16282,20 @@ class _DraggingAppointmentRenderObject extends RenderBox double yPosition; xPosition = dragDetails.position.value!.dx; yPosition = dragDetails.position.value!.dy; - _shadowPainter.color = - dragDetails.appointmentView!.appointment!.color.withValues(alpha: 0.5); + _shadowPainter.color = dragDetails.appointmentView!.appointment!.color + .withValues(alpha: 0.5); final RRect rect = RRect.fromRectAndRadius( - Rect.fromLTWH( - dragDetails.position.value!.dx, - dragDetails.position.value!.dy, - isRTL - ? -dragDetails.appointmentView!.appointmentRect!.width - : dragDetails.appointmentView!.appointmentRect!.width, - dragDetails.appointmentView!.appointmentRect!.height), - dragDetails.appointmentView!.appointmentRect!.tlRadius); + Rect.fromLTWH( + dragDetails.position.value!.dx, + dragDetails.position.value!.dy, + isRTL + ? -dragDetails.appointmentView!.appointmentRect!.width + : dragDetails.appointmentView!.appointmentRect!.width, + dragDetails.appointmentView!.appointmentRect!.height, + ), + dragDetails.appointmentView!.appointmentRect!.tlRadius, + ); final Path path = Path(); path.addRRect(rect); canvas.drawPath(path, _shadowPainter); @@ -14172,12 +16330,17 @@ class _DraggingAppointmentRenderObject extends RenderBox _textPainter.layout(maxWidth: maxTextWidth); _textPainter.paint( - canvas, - isTimelineView - ? Offset(xPosition + (isRTL ? 0 : textStartPadding), - yPosition + textStartPadding) - : Offset(xPosition + (isRTL ? 0 : textStartPadding), - yPosition + textStartPadding)); + canvas, + isTimelineView + ? Offset( + xPosition + (isRTL ? 0 : textStartPadding), + yPosition + textStartPadding, + ) + : Offset( + xPosition + (isRTL ? 0 : textStartPadding), + yPosition + textStartPadding, + ), + ); if (dragAndDropSettings.showTimeIndicator && dragDetails.draggingTime != null) { _drawTimeIndicator(canvas, isTimelineView, size); @@ -14191,8 +16354,9 @@ class _DraggingAppointmentRenderObject extends RenderBox } final TextSpan span = TextSpan( - text: DateFormat(dragAndDropSettings.indicatorTimeFormat) - .format(dragDetails.draggingTime!), + text: DateFormat( + dragAndDropSettings.indicatorTimeFormat, + ).format(dragDetails.draggingTime!), style: calendarTheme.timeIndicatorTextStyle, ); _textPainter.text = span; diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/day_view.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/day_view.dart index 8effe13d2..8faa3739b 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/day_view.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/day_view.dart @@ -15,24 +15,25 @@ class TimeSlotWidget extends StatefulWidget { /// Constructor to create the time slot widget to holds time slots view for /// day, week, workweek views. const TimeSlotWidget( - this.visibleDates, - this.horizontalLinesCount, - this.timeIntervalHeight, - this.timeLabelWidth, - this.cellBorderColor, - this.calendarTheme, - this.themeData, - this.timeSlotViewSettings, - this.isRTL, - this.specialRegion, - this.calendarCellNotifier, - this.textScaleFactor, - this.timeRegionBuilder, - this.width, - this.height, - this.minDate, - this.maxDate, - {super.key}); + this.visibleDates, + this.horizontalLinesCount, + this.timeIntervalHeight, + this.timeLabelWidth, + this.cellBorderColor, + this.calendarTheme, + this.themeData, + this.timeSlotViewSettings, + this.isRTL, + this.specialRegion, + this.calendarCellNotifier, + this.textScaleFactor, + this.timeRegionBuilder, + this.width, + this.height, + this.minDate, + this.maxDate, { + super.key, + }); /// Holds the visible dates collection for current time slot view. final List visibleDates; @@ -112,7 +113,9 @@ class _TimeSlotWidgetState extends State { widget.height != oldWidget.height || widget.timeRegionBuilder != oldWidget.timeRegionBuilder || !CalendarViewHelper.isCollectionEqual( - widget.specialRegion, oldWidget.specialRegion)) { + widget.specialRegion, + oldWidget.specialRegion, + )) { _updateSpecialRegionDetails(); _children.clear(); } @@ -129,9 +132,13 @@ class _TimeSlotWidgetState extends State { for (int i = 0; i < count; i++) { final TimeRegionView view = _specialRegionViews[i]; final Widget child = widget.timeRegionBuilder!( - context, - TimeRegionDetails(view.region.data, - widget.visibleDates[view.visibleIndex], view.bound)); + context, + TimeRegionDetails( + view.region.data, + widget.visibleDates[view.visibleIndex], + view.bound, + ), + ); _children.add(RepaintBoundary(child: child)); } @@ -165,13 +172,16 @@ class _TimeSlotWidgetState extends State { return; } - final double minuteHeight = widget.timeIntervalHeight / + final double minuteHeight = + widget.timeIntervalHeight / CalendarViewHelper.getTimeInterval(widget.timeSlotViewSettings); - final DateTime startDate = - AppointmentHelper.convertToStartTime(widget.visibleDates[0]); + final DateTime startDate = AppointmentHelper.convertToStartTime( + widget.visibleDates[0], + ); final int visibleDatesLength = widget.visibleDates.length; final DateTime endDate = AppointmentHelper.convertToEndTime( - widget.visibleDates[visibleDatesLength - 1]); + widget.visibleDates[visibleDatesLength - 1], + ); final double width = widget.width - widget.timeLabelWidth; final double cellWidth = width / visibleDatesLength; for (int i = 0; i < widget.specialRegion!.length; i++) { @@ -195,15 +205,19 @@ class _TimeSlotWidgetState extends State { } int startIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, regionStartTime); + widget.visibleDates, + regionStartTime, + ); int endIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, regionEndTime); + widget.visibleDates, + regionEndTime, + ); double startYPosition = CalendarViewHelper.getTimeToPosition( - Duration( - hours: regionStartTime.hour, minutes: regionStartTime.minute), - widget.timeSlotViewSettings, - minuteHeight); + Duration(hours: regionStartTime.hour, minutes: regionStartTime.minute), + widget.timeSlotViewSettings, + minuteHeight, + ); if (startIndex == -1) { if (startDate.isAfter(regionStartTime)) { // Set index as 0 when the region start date before the visible @@ -232,9 +246,10 @@ class _TimeSlotWidgetState extends State { } double endYPosition = CalendarViewHelper.getTimeToPosition( - Duration(hours: regionEndTime.hour, minutes: regionEndTime.minute), - widget.timeSlotViewSettings, - minuteHeight); + Duration(hours: regionEndTime.hour, minutes: regionEndTime.minute), + widget.timeSlotViewSettings, + minuteHeight, + ); if (endIndex == -1) { /// Find the previous index when the end date as non working date. if (endDate.isAfter(regionEndTime)) { @@ -279,8 +294,12 @@ class _TimeSlotWidgetState extends State { startXPosition = widget.width - (startXPosition + cellWidth); } - final Rect rect = Rect.fromLTRB(startXPosition, startPosition, - startXPosition + cellWidth, endPosition); + final Rect rect = Rect.fromLTRB( + startXPosition, + startPosition, + startXPosition + cellWidth, + endPosition, + ); _specialRegionViews.add(TimeRegionView(j, region, rect)); } } @@ -289,25 +308,25 @@ class _TimeSlotWidgetState extends State { class _TimeSlotRenderWidget extends MultiChildRenderObjectWidget { const _TimeSlotRenderWidget( - this.visibleDates, - this.horizontalLinesCount, - this.timeIntervalHeight, - this.timeLabelWidth, - this.cellBorderColor, - this.calendarTheme, - this.themeData, - this.timeSlotViewSettings, - this.isRTL, - this.specialRegion, - this.calendarCellNotifier, - this.textScaleFactor, - this.width, - this.height, - this.specialRegionBounds, - this.minDate, - this.maxDate, - {List widgets = const []}) - : super(children: widgets); + this.visibleDates, + this.horizontalLinesCount, + this.timeIntervalHeight, + this.timeLabelWidth, + this.cellBorderColor, + this.calendarTheme, + this.themeData, + this.timeSlotViewSettings, + this.isRTL, + this.specialRegion, + this.calendarCellNotifier, + this.textScaleFactor, + this.width, + this.height, + this.specialRegionBounds, + this.minDate, + this.maxDate, { + List widgets = const [], + }) : super(children: widgets); final List visibleDates; final double horizontalLinesCount; @@ -330,28 +349,31 @@ class _TimeSlotRenderWidget extends MultiChildRenderObjectWidget { @override _TimeSlotRenderObject createRenderObject(BuildContext context) { return _TimeSlotRenderObject( - visibleDates, - horizontalLinesCount, - timeIntervalHeight, - timeLabelWidth, - cellBorderColor, - calendarTheme, - themeData, - timeSlotViewSettings, - isRTL, - specialRegion, - calendarCellNotifier, - textScaleFactor, - width, - height, - specialRegionBounds, - minDate, - maxDate); + visibleDates, + horizontalLinesCount, + timeIntervalHeight, + timeLabelWidth, + cellBorderColor, + calendarTheme, + themeData, + timeSlotViewSettings, + isRTL, + specialRegion, + calendarCellNotifier, + textScaleFactor, + width, + height, + specialRegionBounds, + minDate, + maxDate, + ); } @override void updateRenderObject( - BuildContext context, _TimeSlotRenderObject renderObject) { + BuildContext context, + _TimeSlotRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..horizontalLinesCount = horizontalLinesCount @@ -375,23 +397,24 @@ class _TimeSlotRenderWidget extends MultiChildRenderObjectWidget { class _TimeSlotRenderObject extends CustomCalendarRenderObject { _TimeSlotRenderObject( - this._visibleDates, - this._horizontalLinesCount, - this._timeIntervalHeight, - this._timeLabelWidth, - this._cellBorderColor, - this._calendarTheme, - this._themeData, - this._timeSlotViewSettings, - this._isRTL, - this._specialRegion, - this._calendarCellNotifier, - this._textScaleFactor, - this._width, - this._height, - this.specialRegionBounds, - this._minDate, - this._maxDate); + this._visibleDates, + this._horizontalLinesCount, + this._timeIntervalHeight, + this._timeLabelWidth, + this._cellBorderColor, + this._calendarTheme, + this._themeData, + this._timeSlotViewSettings, + this._isRTL, + this._specialRegion, + this._calendarCellNotifier, + this._textScaleFactor, + this._width, + this._height, + this.specialRegionBounds, + this._minDate, + this._maxDate, + ); List _visibleDates; @@ -648,8 +671,10 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; if (specialRegion == null || specialRegion!.isEmpty) { return; @@ -662,11 +687,14 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { continue; } final Rect rect = view.bound; - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: rect.height, maxHeight: rect.height, minWidth: rect.width, - maxWidth: rect.width)); + maxWidth: rect.width, + ), + ); child = childAfter(child); } } @@ -700,12 +728,17 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { _drawTimeSlots(context.canvas, visibleDatesCount); } - void _minMaxExceeds(DateTime minDate, DateTime maxDate, Canvas canvas, - int visibleDatesCount) { + void _minMaxExceeds( + DateTime minDate, + DateTime maxDate, + Canvas canvas, + int visibleDatesCount, + ) { final DateTime visibleStartDate = visibleDates[0]; final DateTime visibleEndDate = visibleDates[visibleDatesCount - 1]; - final DateTime maxEndDate = - AppointmentHelper.convertToEndTime(visibleDates[visibleDatesCount - 1]); + final DateTime maxEndDate = AppointmentHelper.convertToEndTime( + visibleDates[visibleDatesCount - 1], + ); if (isDateWithInDateRange(visibleStartDate, visibleEndDate, minDate)) { _drawDisabledDate(visibleStartDate, minDate, canvas, visibleDatesCount); } @@ -714,26 +747,39 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { } } - void _drawDisabledDate(DateTime disabledStartDate, DateTime disabledEndDate, - Canvas canvas, int visibleDatesCount) { - final double minuteHeight = timeIntervalHeight / + void _drawDisabledDate( + DateTime disabledStartDate, + DateTime disabledEndDate, + Canvas canvas, + int visibleDatesCount, + ) { + final double minuteHeight = + timeIntervalHeight / CalendarViewHelper.getTimeInterval(timeSlotViewSettings); final double viewWidth = width - timeLabelWidth; final double cellWidth = viewWidth / visibleDatesCount; - final int startIndex = - DateTimeHelper.getVisibleDateIndex(visibleDates, disabledStartDate); - final int endIndex = - DateTimeHelper.getVisibleDateIndex(visibleDates, disabledEndDate); + final int startIndex = DateTimeHelper.getVisibleDateIndex( + visibleDates, + disabledStartDate, + ); + final int endIndex = DateTimeHelper.getVisibleDateIndex( + visibleDates, + disabledEndDate, + ); final double startYPosition = CalendarViewHelper.getTimeToPosition( - Duration( - hours: disabledStartDate.hour, minutes: disabledStartDate.minute), - timeSlotViewSettings, - minuteHeight); + Duration( + hours: disabledStartDate.hour, + minutes: disabledStartDate.minute, + ), + timeSlotViewSettings, + minuteHeight, + ); final double endYPosition = CalendarViewHelper.getTimeToPosition( - Duration(hours: disabledEndDate.hour, minutes: disabledEndDate.minute), - timeSlotViewSettings, - minuteHeight); + Duration(hours: disabledEndDate.hour, minutes: disabledEndDate.minute), + timeSlotViewSettings, + minuteHeight, + ); for (int i = startIndex; i <= endIndex; i++) { final double topPosition = i == startIndex ? startYPosition : 0; final double bottomPosition = i == endIndex ? endYPosition : height; @@ -752,7 +798,11 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { rightPosition = width - rightPosition; } rect = Rect.fromLTRB( - leftPosition, topPosition, rightPosition, bottomPosition); + leftPosition, + topPosition, + rightPosition, + bottomPosition, + ); _linePainter.style = PaintingStyle.fill; _linePainter.color = Colors.grey.withValues(alpha: 0.2); canvas.drawRect(rect, _linePainter); @@ -771,7 +821,10 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { isRTL ? size.width - timeLabelWidth : size.width; for (int i = 1; i <= horizontalLinesCount; i++) { canvas.drawLine( - Offset(startXPosition, y), Offset(endXPosition, y), _linePainter); + Offset(startXPosition, y), + Offset(endXPosition, y), + _linePainter, + ); y += timeIntervalHeight; if (y == size.height) { @@ -794,12 +847,14 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { const double strokeWidth = 2; const double padding = strokeWidth / 2; double left = (calendarCellNotifier.value!.dx ~/ _cellWidth) * _cellWidth; - double top = (calendarCellNotifier.value!.dy ~/ timeIntervalHeight) * + double top = + (calendarCellNotifier.value!.dy ~/ timeIntervalHeight) * timeIntervalHeight; _linePainter.style = PaintingStyle.stroke; _linePainter.strokeWidth = strokeWidth; - _linePainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + _linePainter.color = calendarTheme.selectionBorderColor!.withValues( + alpha: 0.4, + ); left += isRTL ? 0 : timeLabelWidth; double height = timeIntervalHeight; if (top == 0) { @@ -808,12 +863,14 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { } canvas.drawRect( - Rect.fromLTWH( - left, - top, - left + _cellWidth == size.width ? _cellWidth - padding : _cellWidth, - top + height == size.height ? height - padding : height), - _linePainter); + Rect.fromLTWH( + left, + top, + left + _cellWidth == size.width ? _cellWidth - padding : _cellWidth, + top + height == size.height ? height - padding : height, + ), + _linePainter, + ); } void _addSpecialRegions(Canvas canvas) { @@ -822,18 +879,21 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { } final TextPainter painter = TextPainter( - textDirection: TextDirection.ltr, - maxLines: 1, - textAlign: isRTL ? TextAlign.right : TextAlign.left, - textScaler: TextScaler.linear(textScaleFactor), - textWidthBasis: TextWidthBasis.longestLine); + textDirection: TextDirection.ltr, + maxLines: 1, + textAlign: isRTL ? TextAlign.right : TextAlign.left, + textScaler: TextScaler.linear(textScaleFactor), + textWidthBasis: TextWidthBasis.longestLine, + ); _linePainter.style = PaintingStyle.fill; final int count = specialRegionBounds.length; final TextStyle defaultTextStyle = TextStyle( - color: themeData.brightness == Brightness.dark - ? Colors.white54 - : Colors.black45); + color: + themeData.brightness == Brightness.dark + ? Colors.white54 + : Colors.black45, + ); for (int i = 0; i < count; i++) { final TimeRegionView view = specialRegionBounds[i]; final CalendarTimeRegion region = view.region; @@ -854,8 +914,9 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { painter.ellipsis = '..'; } else { painter.text = TextSpan( - text: String.fromCharCode(region.iconData!.codePoint), - style: textStyle.copyWith(fontFamily: region.iconData!.fontFamily)); + text: String.fromCharCode(region.iconData!.codePoint), + style: textStyle.copyWith(fontFamily: region.iconData!.fontFamily), + ); } painter.layout(maxWidth: rect.width - 4); @@ -879,20 +940,23 @@ class _TimeSlotRenderObject extends CustomCalendarRenderObject { final int startHour = timeSlotViewSettings.startHour.toInt(); final int hour = ((timeSlotViewSettings.startHour - startHour) * 60).toInt(); - final int timeInterval = - CalendarViewHelper.getTimeInterval(timeSlotViewSettings); + final int timeInterval = CalendarViewHelper.getTimeInterval( + timeSlotViewSettings, + ); for (int j = 0; j < visibleDates.length; j++) { DateTime date = visibleDates[j]; for (int i = 0; i < horizontalLinesCount; i++) { final int minute = (i * timeInterval) + hour; date = DateTime(date.year, date.month, date.day, startHour, minute); - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, cellWidth, cellHeight), - properties: SemanticsProperties( - label: DateFormat('h a, dd MMMM yyyy').format(date), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, cellWidth, cellHeight), + properties: SemanticsProperties( + label: DateFormat('h a, dd MMMM yyyy').format(date), + textDirection: TextDirection.ltr, + ), ), - )); + ); top += cellHeight; } diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/month_view.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/month_view.dart index 310724cd2..8f9879f2f 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/month_view.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/month_view.dart @@ -17,30 +17,31 @@ class MonthViewWidget extends StatefulWidget { /// Constructor to create the month view widget to holds month cells for /// calendar month view. const MonthViewWidget( - this.visibleDates, - this.rowCount, - this.monthCellStyle, - this.isRTL, - this.todayHighlightColor, - this.todayTextStyle, - this.cellBorderColor, - this.calendarTheme, - this.themeData, - this.calendarCellNotifier, - this.showTrailingAndLeadingDates, - this.minDate, - this.maxDate, - this.calendar, - this.blackoutDates, - this.blackoutDatesTextStyle, - this.textScaleFactor, - this.builder, - this.width, - this.height, - this.weekNumberStyle, - this.isMobilePlatform, - this.visibleAppointmentNotifier, - {super.key}); + this.visibleDates, + this.rowCount, + this.monthCellStyle, + this.isRTL, + this.todayHighlightColor, + this.todayTextStyle, + this.cellBorderColor, + this.calendarTheme, + this.themeData, + this.calendarCellNotifier, + this.showTrailingAndLeadingDates, + this.minDate, + this.maxDate, + this.calendar, + this.blackoutDates, + this.blackoutDatesTextStyle, + this.textScaleFactor, + this.builder, + this.width, + this.height, + this.weekNumberStyle, + this.isMobilePlatform, + this.visibleAppointmentNotifier, { + super.key, + }); /// Defines the row count for the month view. final int rowCount; @@ -146,9 +147,10 @@ class _MonthViewWidgetState extends State { final List children = []; final double weekNumberPanelWidth = CalendarViewHelper.getWeekNumberPanelWidth( - widget.calendar.showWeekNumber, - widget.width, - widget.isMobilePlatform); + widget.calendar.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if (widget.builder != null) { final int visibleDatesCount = widget.visibleDates.length; final double cellWidth = @@ -159,7 +161,9 @@ class _MonthViewWidgetState extends State { widget.visibleDates[visibleDatesCount ~/ 2].month; final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - widget.rowCount, widget.showTrailingAndLeadingDates); + widget.rowCount, + widget.showTrailingAndLeadingDates, + ); for (int i = 0; i < visibleDatesCount; i++) { final DateTime currentVisibleDate = widget.visibleDates[i]; if (!showTrailingLeadingDates && @@ -175,28 +179,34 @@ class _MonthViewWidgetState extends State { final List appointments = AppointmentHelper.getSpecificDateVisibleAppointment( - currentVisibleDate, widget.visibleAppointmentNotifier.value); + currentVisibleDate, + widget.visibleAppointmentNotifier.value, + ); List monthCellAppointment = appointments; if (widget.calendar.dataSource != null && !AppointmentHelper.isCalendarAppointment( - widget.calendar.dataSource!)) { + widget.calendar.dataSource!, + )) { monthCellAppointment = CalendarViewHelper.getCustomAppointments( - appointments, widget.calendar.dataSource); + appointments, + widget.calendar.dataSource, + ); } final Widget child = widget.builder!( - context, - MonthCellDetails( - currentVisibleDate, - List.unmodifiable(monthCellAppointment), - List.unmodifiable(widget.visibleDates), - Rect.fromLTWH( - widget.isRTL - ? widget.width - xPosition - cellWidth - : xPosition, - yPosition, - cellWidth, - cellHeight))); + context, + MonthCellDetails( + currentVisibleDate, + List.unmodifiable(monthCellAppointment), + List.unmodifiable(widget.visibleDates), + Rect.fromLTWH( + widget.isRTL ? widget.width - xPosition - cellWidth : xPosition, + yPosition, + cellWidth, + cellHeight, + ), + ), + ); children.add(RepaintBoundary(child: child)); xPosition += cellWidth; @@ -244,31 +254,31 @@ class _MonthViewWidgetState extends State { class _MonthViewRenderObjectWidget extends MultiChildRenderObjectWidget { const _MonthViewRenderObjectWidget( - this.visibleDates, - this.visibleAppointments, - this.rowCount, - this.monthCellStyle, - this.isRTL, - this.todayHighlightColor, - this.todayTextStyle, - this.cellBorderColor, - this.calendarTheme, - this.themeData, - this.calendarCellNotifier, - this.minDate, - this.maxDate, - this.blackoutDates, - this.blackoutDatesTextStyle, - this.showTrailingAndLeadingDates, - this.textScaleFactor, - this.width, - this.height, - this.weekNumberStyle, - this.weekNumberPanelWidth, - this.isMobilePlatform, - this.builder, - {List children = const []}) - : super(children: children); + this.visibleDates, + this.visibleAppointments, + this.rowCount, + this.monthCellStyle, + this.isRTL, + this.todayHighlightColor, + this.todayTextStyle, + this.cellBorderColor, + this.calendarTheme, + this.themeData, + this.calendarCellNotifier, + this.minDate, + this.maxDate, + this.blackoutDates, + this.blackoutDatesTextStyle, + this.showTrailingAndLeadingDates, + this.textScaleFactor, + this.width, + this.height, + this.weekNumberStyle, + this.weekNumberPanelWidth, + this.isMobilePlatform, + this.builder, { + List children = const [], + }) : super(children: children); final int rowCount; final MonthCellStyle monthCellStyle; @@ -297,34 +307,37 @@ class _MonthViewRenderObjectWidget extends MultiChildRenderObjectWidget { @override _MonthViewRenderObject createRenderObject(BuildContext context) { return _MonthViewRenderObject( - visibleDates, - visibleAppointments, - rowCount, - monthCellStyle, - isRTL, - todayHighlightColor, - todayTextStyle, - cellBorderColor, - calendarTheme, - themeData, - calendarCellNotifier, - minDate, - maxDate, - blackoutDates, - blackoutDatesTextStyle, - showTrailingAndLeadingDates, - textScaleFactor, - width, - height, - weekNumberStyle, - weekNumberPanelWidth, - isMobilePlatform, - builder); + visibleDates, + visibleAppointments, + rowCount, + monthCellStyle, + isRTL, + todayHighlightColor, + todayTextStyle, + cellBorderColor, + calendarTheme, + themeData, + calendarCellNotifier, + minDate, + maxDate, + blackoutDates, + blackoutDatesTextStyle, + showTrailingAndLeadingDates, + textScaleFactor, + width, + height, + weekNumberStyle, + weekNumberPanelWidth, + isMobilePlatform, + builder, + ); } @override void updateRenderObject( - BuildContext context, _MonthViewRenderObject renderObject) { + BuildContext context, + _MonthViewRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..visibleAppointments = visibleAppointments @@ -768,17 +781,22 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); final double cellWidth = (size.width - weekNumberPanelWidth) / DateTime.daysPerWeek; final double cellHeight = size.height / rowCount; for (dynamic child = firstChild; child != null; child = childAfter(child)) { - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minWidth: cellWidth, minHeight: cellHeight, maxWidth: cellWidth, - maxHeight: cellHeight)); + maxHeight: cellHeight, + ), + ); } } @@ -801,7 +819,9 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final int currentMonth = visibleDates[visibleDatesCount ~/ 2].month; final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - rowCount, showTrailingAndLeadingDates); + rowCount, + showTrailingAndLeadingDates, + ); _drawWeekNumberPanel(context.canvas, cellHeight); for (int i = 0; i < visibleDatesCount; i++) { final DateTime currentVisibleDate = visibleDates[i]; @@ -815,9 +835,12 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { visibleDates[(i ~/ DateTime.daysPerWeek) * DateTime.daysPerWeek]; /// Calculate the row end date based on visible dates index. - final DateTime endDate = addDuration( - startDate, const Duration(days: DateTime.daysPerWeek - 1)) - as DateTime; + final DateTime endDate = + addDuration( + startDate, + const Duration(days: DateTime.daysPerWeek - 1), + ) + as DateTime; /// Used to check the start and end date is current month date or not. final bool isCurrentMonthWeek = @@ -826,8 +849,13 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { if (weekNumberPanelWidth != 0 && (showTrailingLeadingDates || (!showTrailingLeadingDates && isCurrentMonthWeek))) { - _drawWeekNumber(context.canvas, size, currentVisibleDate, - cellHeight, yPosition); + _drawWeekNumber( + context.canvas, + size, + currentVisibleDate, + cellHeight, + yPosition, + ); } } @@ -842,21 +870,31 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { } context.paintChild( - child!, - Offset(isRTL ? size.width - xPosition - cellWidth : xPosition, - yPosition)); + child!, + Offset( + isRTL ? size.width - xPosition - cellWidth : xPosition, + yPosition, + ), + ); if (child.parentData != null) { (child.parentData! as CalendarParentData).offset = Offset( - isRTL ? size.width - xPosition - cellWidth : xPosition, - yPosition); + isRTL ? size.width - xPosition - cellWidth : xPosition, + yPosition, + ); } child = childAfter(child); if (calendarCellNotifier.value != null && !_blackoutDatesIndex.contains(i)) { - _addMouseHovering(context.canvas, size, cellWidth, cellHeight, - isRTL ? xPosition - weekNumberPanelWidth : xPosition, yPosition); + _addMouseHovering( + context.canvas, + size, + cellWidth, + cellHeight, + isRTL ? xPosition - weekNumberPanelWidth : xPosition, + yPosition, + ); } xPosition += cellWidth; @@ -878,8 +916,10 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final int count = blackoutDates == null ? 0 : blackoutDates!.length; for (int i = 0; i < count; i++) { final DateTime blackoutDate = blackoutDates![i]; - final int blackoutDateIndex = - DateTimeHelper.getVisibleDateIndex(visibleDates, blackoutDate); + final int blackoutDateIndex = DateTimeHelper.getVisibleDateIndex( + visibleDates, + blackoutDate, + ); if (blackoutDateIndex == -1) { continue; } @@ -888,14 +928,21 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { } } - void _drawWeekNumber(Canvas canvas, Size size, DateTime date, - double cellHeight, double yPosition) { + void _drawWeekNumber( + Canvas canvas, + Size size, + DateTime date, + double cellHeight, + double yPosition, + ) { final String weekNumber = DateTimeHelper.getWeekNumberOfYear(date).toString(); double xPosition = isRTL ? size.width - weekNumberPanelWidth : 0; final TextStyle weekNumberTextStyle = calendarTheme.weekNumberTextStyle!; - final TextSpan textSpan = - TextSpan(text: weekNumber, style: weekNumberTextStyle); + final TextSpan textSpan = TextSpan( + text: weekNumber, + style: weekNumberTextStyle, + ); _textPainter.text = textSpan; _textPainter.textDirection = TextDirection.ltr; @@ -917,13 +964,20 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final double padding = isMobilePlatform ? 5 : 0; final double left = xPosition + padding; final double right = (xPosition + weekNumberPanelWidth) - padding; - final Rect rect = - Rect.fromLTRB(left, padding, right, size.height - padding); + final Rect rect = Rect.fromLTRB( + left, + padding, + right, + size.height - padding, + ); _linePainter.style = PaintingStyle.fill; - _linePainter.color = weekNumberStyle.backgroundColor ?? + _linePainter.color = + weekNumberStyle.backgroundColor ?? calendarTheme.weekNumberBackgroundColor!; - final RRect roundedRect = - RRect.fromRectAndRadius(rect, Radius.circular(padding)); + final RRect roundedRect = RRect.fromRectAndRadius( + rect, + Radius.circular(padding), + ); canvas.drawRRect(roundedRect, _linePainter); if (isMobilePlatform) { @@ -932,7 +986,10 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { _linePainter.color = cellBorderColor ?? calendarTheme.cellBorderColor!; for (int i = 0; i < rowCount - 1; i++) { canvas.drawLine( - Offset(left, yPosition), Offset(right, yPosition), _linePainter); + Offset(left, yPosition), + Offset(right, yPosition), + _linePainter, + ); yPosition += cellHeight; } } @@ -944,9 +1001,10 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final double cellWidth = (size.width - weekNumberPanelWidth) / DateTime.daysPerWeek; final double cellHeight = size.height / rowCount; - double xPosition = isRTL - ? size.width - cellWidth - weekNumberPanelWidth - : weekNumberPanelWidth; + double xPosition = + isRTL + ? size.width - cellWidth - weekNumberPanelWidth + : weekNumberPanelWidth; double yPosition = viewPadding; _textPainter.textDirection = TextDirection.ltr; _textPainter.textWidthBasis = TextWidthBasis.longestLine; @@ -954,11 +1012,13 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final int visibleDatesCount = visibleDates.length; final DateTime currentMonthDate = visibleDates[visibleDatesCount ~/ 2]; final int nextMonth = - DateTimeHelper.getDateTimeValue(getNextMonthDate(currentMonthDate)) - .month; + DateTimeHelper.getDateTimeValue( + getNextMonthDate(currentMonthDate), + ).month; final int previousMonth = - DateTimeHelper.getDateTimeValue(getPreviousMonthDate(currentMonthDate)) - .month; + DateTimeHelper.getDateTimeValue( + getPreviousMonthDate(currentMonthDate), + ).month; final DateTime today = DateTime.now(); bool isCurrentDate; @@ -970,25 +1030,31 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final TextStyle nextMonthTextStyle = calendarTheme.leadingDatesTextStyle!; final TextStyle? blackoutDatesStyle = calendarTheme.blackoutDatesTextStyle; final TextStyle disabledTextStyle = currentMonthTextStyle.copyWith( - color: currentMonthTextStyle.color != null - ? currentMonthTextStyle.color!.withValues(alpha: 0.38) - : themeData.brightness == Brightness.light - ? Colors.black26 - : Colors.white38); + color: + currentMonthTextStyle.color != null + ? currentMonthTextStyle.color!.withValues(alpha: 0.38) + : themeData.brightness == Brightness.light + ? Colors.black26 + : Colors.white38, + ); final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - rowCount, showTrailingAndLeadingDates); + rowCount, + showTrailingAndLeadingDates, + ); - final Color currentMonthBackgroundColor = monthCellStyle.backgroundColor ?? + final Color currentMonthBackgroundColor = + monthCellStyle.backgroundColor ?? calendarTheme.activeDatesBackgroundColor!; final Color nextMonthBackgroundColor = monthCellStyle.leadingDatesBackgroundColor ?? - calendarTheme.leadingDatesBackgroundColor!; + calendarTheme.leadingDatesBackgroundColor!; final Color previousMonthBackgroundColor = monthCellStyle.trailingDatesBackgroundColor ?? - calendarTheme.trailingDatesBackgroundColor!; - final Color todayBackgroundColor = monthCellStyle.todayBackgroundColor ?? + calendarTheme.trailingDatesBackgroundColor!; + final Color todayBackgroundColor = + monthCellStyle.todayBackgroundColor ?? calendarTheme.todayBackgroundColor!; TextStyle textStyle = currentMonthTextStyle; @@ -1006,20 +1072,28 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { visibleDates[(i ~/ DateTime.daysPerWeek) * DateTime.daysPerWeek]; /// Calculate the row end date based on visible dates index. - final DateTime endDate = addDuration( - startDate, const Duration(days: DateTime.daysPerWeek - 1)) - as DateTime; + final DateTime endDate = + addDuration( + startDate, + const Duration(days: DateTime.daysPerWeek - 1), + ) + as DateTime; /// Used to check the start and end date is current month date or not. final bool isCurrentMonthWeek = startDate.month == currentMonthDate.month || - endDate.month == currentMonthDate.month; + endDate.month == currentMonthDate.month; if (weekNumberPanelWidth != 0 && (showTrailingLeadingDates || (!showTrailingLeadingDates && isCurrentMonthWeek))) { _drawWeekNumber( - canvas, size, currentVisibleDate, cellHeight, yPosition); + canvas, + size, + currentVisibleDate, + cellHeight, + yPosition, + ); } } @@ -1090,8 +1164,9 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { if (blackoutDatesStyle != null) { textStyle = textStyle.merge(blackoutDatesStyle); } else { - textStyle = - textStyle.copyWith(decoration: TextDecoration.lineThrough); + textStyle = textStyle.copyWith( + decoration: TextDecoration.lineThrough, + ); } } @@ -1111,13 +1186,24 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { //// the style s fill. _linePainter.style = PaintingStyle.fill; canvas.drawRect( - Rect.fromLTWH( - xPosition, yPosition - viewPadding, cellWidth, cellHeight), - _linePainter); + Rect.fromLTWH( + xPosition, + yPosition - viewPadding, + cellWidth, + cellHeight, + ), + _linePainter, + ); if (calendarCellNotifier.value != null && !isBlackoutDate) { - _addMouseHovering(canvas, size, cellWidth, cellHeight, xPosition, - yPosition - viewPadding); + _addMouseHovering( + canvas, + size, + cellWidth, + cellHeight, + xPosition, + yPosition - viewPadding, + ); } if (isCurrentDate) { @@ -1127,16 +1213,22 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final double textHeight = _textPainter.height / 2; canvas.drawCircle( - Offset(xPosition + cellWidth / 2, - yPosition + circlePadding + textHeight), - textHeight + viewPadding, - _linePainter); + Offset( + xPosition + cellWidth / 2, + yPosition + circlePadding + textHeight, + ), + textHeight + viewPadding, + _linePainter, + ); } _textPainter.paint( - canvas, - Offset(xPosition + (cellWidth / 2 - _textPainter.width / 2), - yPosition + circlePadding)); + canvas, + Offset( + xPosition + (cellWidth / 2 - _textPainter.width / 2), + yPosition + circlePadding, + ), + ); if (isRTL) { if (xPosition - 1 < 0) { @@ -1155,80 +1247,117 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { } _drawVerticalAndHorizontalLines( - canvas, size, yPosition, xPosition, cellHeight, cellWidth); + canvas, + size, + yPosition, + xPosition, + cellHeight, + cellWidth, + ); } - void _addMouseHovering(Canvas canvas, Size size, double cellWidth, - double cellHeight, double xPosition, double yPosition) { + void _addMouseHovering( + Canvas canvas, + Size size, + double cellWidth, + double cellHeight, + double xPosition, + double yPosition, + ) { if (xPosition <= calendarCellNotifier.value!.dx && xPosition + cellWidth >= calendarCellNotifier.value!.dx && yPosition <= calendarCellNotifier.value!.dy && yPosition + cellHeight >= calendarCellNotifier.value!.dy) { _linePainter.style = PaintingStyle.stroke; _linePainter.strokeWidth = 2; - _linePainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + _linePainter.color = calendarTheme.selectionBorderColor!.withValues( + alpha: 0.4, + ); canvas.drawRect( - Rect.fromLTWH( - xPosition == 0 ? xPosition + linePadding : xPosition, - yPosition, - (xPosition + cellWidth).round() >= size.width - ? cellWidth - linePadding - 1 - : cellWidth - 1, - (yPosition + cellHeight).round() >= size.height.round() - ? cellHeight - 1 - linePadding - : cellHeight - 1), - _linePainter); + Rect.fromLTWH( + xPosition == 0 ? xPosition + linePadding : xPosition, + yPosition, + (xPosition + cellWidth).round() >= size.width + ? cellWidth - linePadding - 1 + : cellWidth - 1, + (yPosition + cellHeight).round() >= size.height.round() + ? cellHeight - 1 - linePadding + : cellHeight - 1, + ), + _linePainter, + ); } } - void _drawVerticalAndHorizontalLines(Canvas canvas, Size size, - double yPosition, double xPosition, double cellHeight, double cellWidth) { + void _drawVerticalAndHorizontalLines( + Canvas canvas, + Size size, + double yPosition, + double xPosition, + double cellHeight, + double cellWidth, + ) { yPosition = cellHeight; _linePainter.strokeWidth = linePadding; _linePainter.color = cellBorderColor ?? calendarTheme.cellBorderColor!; xPosition = isRTL ? 0 : weekNumberPanelWidth; final double finalXPosition = isRTL ? size.width - weekNumberPanelWidth : size.width; - canvas.drawLine(Offset(xPosition, linePadding), - Offset(finalXPosition, linePadding), _linePainter); + canvas.drawLine( + Offset(xPosition, linePadding), + Offset(finalXPosition, linePadding), + _linePainter, + ); for (int i = 0; i < rowCount - 1; i++) { canvas.drawLine( - Offset( - isMobilePlatform - ? isRTL - ? 0 - : weekNumberPanelWidth - : 0, - yPosition), - Offset( - isMobilePlatform - ? isRTL - ? size.width - weekNumberPanelWidth - : size.width - : size.width, - yPosition), - _linePainter); + Offset( + isMobilePlatform + ? isRTL + ? 0 + : weekNumberPanelWidth + : 0, + yPosition, + ), + Offset( + isMobilePlatform + ? isRTL + ? size.width - weekNumberPanelWidth + : size.width + : size.width, + yPosition, + ), + _linePainter, + ); yPosition += cellHeight; } - canvas.drawLine(Offset(0, size.height - linePadding), - Offset(size.width, size.height - linePadding), _linePainter); + canvas.drawLine( + Offset(0, size.height - linePadding), + Offset(size.width, size.height - linePadding), + _linePainter, + ); xPosition = weekNumberPanelWidth != 0 && !isRTL ? weekNumberPanelWidth : cellWidth; - canvas.drawLine(const Offset(linePadding, 0), - Offset(linePadding, size.height), _linePainter); + canvas.drawLine( + const Offset(linePadding, 0), + Offset(linePadding, size.height), + _linePainter, + ); final int count = weekNumberPanelWidth == 0 ? 6 : 7; for (int i = 0; i < count; i++) { canvas.drawLine( - Offset(xPosition, 0), Offset(xPosition, size.height), _linePainter); + Offset(xPosition, 0), + Offset(xPosition, size.height), + _linePainter, + ); xPosition += cellWidth; } } String _getAccessibilityText(DateTime date, int index) { - final String accessibilityText = - DateFormat('EEE, dd MMMM yyyy').format(date); + final String accessibilityText = DateFormat( + 'EEE, dd MMMM yyyy', + ).format(date); if (_blackoutDatesIndex.contains(index)) { return '$accessibilityText, Blackout date'; } @@ -1251,14 +1380,17 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { final double cellWidth = (size.width - weekNumberPanelWidth) / DateTime.daysPerWeek; - double left = isRTL - ? size.width - cellWidth - weekNumberPanelWidth - : weekNumberPanelWidth, + double left = + isRTL + ? size.width - cellWidth - weekNumberPanelWidth + : weekNumberPanelWidth, top = 0; final double cellHeight = size.height / rowCount; final bool showTrailingLeadingDates = CalendarViewHelper.isLeadingAndTrailingDatesVisible( - rowCount, showTrailingAndLeadingDates); + rowCount, + showTrailingAndLeadingDates, + ); final int currentMonth = visibleDates[visibleDates.length ~/ 2].month; for (int i = 0; i < visibleDates.length; i++) { final DateTime currentVisibleDate = visibleDates[i]; @@ -1272,9 +1404,12 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { visibleDates[(i ~/ DateTime.daysPerWeek) * DateTime.daysPerWeek]; /// Calculate the row end date based on visible dates index. - final DateTime endDate = addDuration( - startDate, const Duration(days: DateTime.daysPerWeek - 1)) - as DateTime; + final DateTime endDate = + addDuration( + startDate, + const Duration(days: DateTime.daysPerWeek - 1), + ) + as DateTime; /// Used to check the start and end date is current month date or not. final bool isCurrentMonthWeek = @@ -1283,27 +1418,41 @@ class _MonthViewRenderObject extends CustomCalendarRenderObject { if (weekNumberPanelWidth != 0 && (showTrailingLeadingDates || (!showTrailingLeadingDates && isCurrentMonthWeek))) { - final int weekNumber = - DateTimeHelper.getWeekNumberOfYear(currentVisibleDate); - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(isRTL ? (size.width - left - cellWidth) : 0, - top, weekNumberPanelWidth, cellHeight), + final int weekNumber = DateTimeHelper.getWeekNumberOfYear( + currentVisibleDate, + ); + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + isRTL ? (size.width - left - cellWidth) : 0, + top, + weekNumberPanelWidth, + cellHeight, + ), properties: SemanticsProperties( label: 'week$weekNumber', textDirection: TextDirection.ltr, - ))); + ), + ), + ); } } if (showTrailingLeadingDates || currentMonth == currentVisibleDate.month) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(isRTL ? size.width - left - cellWidth : left, top, - cellWidth, cellHeight), - properties: SemanticsProperties( - label: _getAccessibilityText(currentVisibleDate, i), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + isRTL ? size.width - left - cellWidth : left, + top, + cellWidth, + cellHeight, + ), + properties: SemanticsProperties( + label: _getAccessibilityText(currentVisibleDate, i), + textDirection: TextDirection.ltr, + ), ), - )); + ); } left += cellWidth; diff --git a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/timeline_view.dart b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/timeline_view.dart index 0c644f6ae..c6b6084aa 100644 --- a/packages/syncfusion_flutter_calendar/lib/src/calendar/views/timeline_view.dart +++ b/packages/syncfusion_flutter_calendar/lib/src/calendar/views/timeline_view.dart @@ -19,28 +19,29 @@ class TimelineWidget extends StatefulWidget { /// Constructor to create the timeline widget to holds time slots view for /// timeline views. const TimelineWidget( - this.horizontalLinesCountPerView, - this.visibleDates, - this.timeSlotViewSettings, - this.timeIntervalWidth, - this.cellBorderColor, - this.isRTL, - this.calendarTheme, - this.themeData, - this.calendarCellNotifier, - this.scrollController, - this.specialRegion, - this.resourceItemHeight, - this.resourceCollection, - this.textScaleFactor, - this.isMobilePlatform, - this.timeRegionBuilder, - this.width, - this.height, - this.minDate, - this.maxDate, - this.blackoutDates, - {super.key}); + this.horizontalLinesCountPerView, + this.visibleDates, + this.timeSlotViewSettings, + this.timeIntervalWidth, + this.cellBorderColor, + this.isRTL, + this.calendarTheme, + this.themeData, + this.calendarCellNotifier, + this.scrollController, + this.specialRegion, + this.resourceItemHeight, + this.resourceCollection, + this.textScaleFactor, + this.isMobilePlatform, + this.timeRegionBuilder, + this.width, + this.height, + this.minDate, + this.maxDate, + this.blackoutDates, { + super.key, + }); /// Defines the total number of time slots needed in the view. final double horizontalLinesCountPerView; @@ -133,7 +134,9 @@ class _TimelineWidgetState extends State { widget.height != oldWidget.height || widget.timeRegionBuilder != oldWidget.timeRegionBuilder || !CalendarViewHelper.isCollectionEqual( - widget.specialRegion, oldWidget.specialRegion)) { + widget.specialRegion, + oldWidget.specialRegion, + )) { _updateSpecialRegionDetails(); _children.clear(); } @@ -150,9 +153,13 @@ class _TimelineWidgetState extends State { for (int i = 0; i < count; i++) { final TimeRegionView view = _specialRegionViews[i]; final Widget child = widget.timeRegionBuilder!( - context, - TimeRegionDetails(view.region.data, - widget.visibleDates[view.visibleIndex], view.bound)); + context, + TimeRegionDetails( + view.region.data, + widget.visibleDates[view.visibleIndex], + view.bound, + ), + ); _children.add(RepaintBoundary(child: child)); } @@ -193,14 +200,18 @@ class _TimelineWidgetState extends State { return; } - final double minuteHeight = widget.timeIntervalWidth / + final double minuteHeight = + widget.timeIntervalWidth / CalendarViewHelper.getTimeInterval(widget.timeSlotViewSettings); - final DateTime startDate = - AppointmentHelper.convertToStartTime(widget.visibleDates[0]); + final DateTime startDate = AppointmentHelper.convertToStartTime( + widget.visibleDates[0], + ); final DateTime endDate = AppointmentHelper.convertToEndTime( - widget.visibleDates[visibleDatesCount - 1]); + widget.visibleDates[visibleDatesCount - 1], + ); final double viewWidth = widget.width / visibleDatesCount; - final bool isResourceEnabled = widget.resourceCollection != null && + final bool isResourceEnabled = + widget.resourceCollection != null && widget.resourceCollection!.isNotEmpty; for (int i = 0; i < widget.specialRegion!.length; i++) { final CalendarTimeRegion region = widget.specialRegion![i]; @@ -223,15 +234,19 @@ class _TimelineWidgetState extends State { } int startIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, regionStartTime); + widget.visibleDates, + regionStartTime, + ); int endIndex = DateTimeHelper.getVisibleDateIndex( - widget.visibleDates, regionEndTime); + widget.visibleDates, + regionEndTime, + ); double startXPosition = CalendarViewHelper.getTimeToPosition( - Duration( - hours: regionStartTime.hour, minutes: regionStartTime.minute), - widget.timeSlotViewSettings, - minuteHeight); + Duration(hours: regionStartTime.hour, minutes: regionStartTime.minute), + widget.timeSlotViewSettings, + minuteHeight, + ); if (startIndex == -1) { if (startDate.isAfter(regionStartTime)) { /// Set index as 0 when the region start date before the visible @@ -260,9 +275,10 @@ class _TimelineWidgetState extends State { } double endXPosition = CalendarViewHelper.getTimeToPosition( - Duration(hours: regionEndTime.hour, minutes: regionEndTime.minute), - widget.timeSlotViewSettings, - minuteHeight); + Duration(hours: regionEndTime.hour, minutes: regionEndTime.minute), + widget.timeSlotViewSettings, + minuteHeight, + ); if (endIndex == -1) { /// Find the previous index when the end date as non working date. if (endDate.isAfter(regionEndTime)) { @@ -313,33 +329,56 @@ class _TimelineWidgetState extends State { region.resourceIds!.isNotEmpty) { for (int i = 0; i < region.resourceIds!.length; i++) { final int index = CalendarViewHelper.getResourceIndex( - widget.resourceCollection, region.resourceIds![i]); + widget.resourceCollection, + region.resourceIds![i], + ); topPosition = index * widget.resourceItemHeight; bottomPosition = topPosition + widget.resourceItemHeight; - _updateSpecialRegionRect(region, startPosition, endPosition, - topPosition, bottomPosition, startIndex); + _updateSpecialRegionRect( + region, + startPosition, + endPosition, + topPosition, + bottomPosition, + startIndex, + ); } } else { - _updateSpecialRegionRect(region, startPosition, endPosition, - topPosition, bottomPosition, startIndex); + _updateSpecialRegionRect( + region, + startPosition, + endPosition, + topPosition, + bottomPosition, + startIndex, + ); } } } void _updateSpecialRegionRect( - CalendarTimeRegion region, - double startPosition, - double endPosition, - double topPosition, - double bottomPosition, - int index) { + CalendarTimeRegion region, + double startPosition, + double endPosition, + double topPosition, + double bottomPosition, + int index, + ) { Rect rect; if (widget.isRTL) { rect = Rect.fromLTRB( - endPosition, topPosition, startPosition, bottomPosition); + endPosition, + topPosition, + startPosition, + bottomPosition, + ); } else { rect = Rect.fromLTRB( - startPosition, topPosition, endPosition, bottomPosition); + startPosition, + topPosition, + endPosition, + bottomPosition, + ); } _specialRegionViews.add(TimeRegionView(index, region, rect)); @@ -348,29 +387,29 @@ class _TimelineWidgetState extends State { class _TimelineRenderWidget extends MultiChildRenderObjectWidget { const _TimelineRenderWidget( - this.horizontalLinesCountPerView, - this.visibleDates, - this.timeSlotViewSettings, - this.timeIntervalWidth, - this.cellBorderColor, - this.isRTL, - this.calendarTheme, - this.themeData, - this.calendarCellNotifier, - this.scrollController, - this.specialRegion, - this.resourceItemHeight, - this.resourceCollection, - this.textScaleFactor, - this.isMobilePlatform, - this.width, - this.height, - this.specialRegionBounds, - this.minDate, - this.maxDate, - this.blackoutDates, - {List widgets = const []}) - : super(children: widgets); + this.horizontalLinesCountPerView, + this.visibleDates, + this.timeSlotViewSettings, + this.timeIntervalWidth, + this.cellBorderColor, + this.isRTL, + this.calendarTheme, + this.themeData, + this.calendarCellNotifier, + this.scrollController, + this.specialRegion, + this.resourceItemHeight, + this.resourceCollection, + this.textScaleFactor, + this.isMobilePlatform, + this.width, + this.height, + this.specialRegionBounds, + this.minDate, + this.maxDate, + this.blackoutDates, { + List widgets = const [], + }) : super(children: widgets); final double horizontalLinesCountPerView; final List visibleDates; @@ -397,32 +436,35 @@ class _TimelineRenderWidget extends MultiChildRenderObjectWidget { @override _TimelineRenderObject createRenderObject(BuildContext context) { return _TimelineRenderObject( - horizontalLinesCountPerView, - visibleDates, - timeSlotViewSettings, - timeIntervalWidth, - cellBorderColor, - isRTL, - calendarTheme, - themeData, - calendarCellNotifier, - scrollController, - specialRegion, - resourceItemHeight, - resourceCollection, - textScaleFactor, - isMobilePlatform, - width, - height, - specialRegionBounds, - minDate, - maxDate, - blackoutDates); + horizontalLinesCountPerView, + visibleDates, + timeSlotViewSettings, + timeIntervalWidth, + cellBorderColor, + isRTL, + calendarTheme, + themeData, + calendarCellNotifier, + scrollController, + specialRegion, + resourceItemHeight, + resourceCollection, + textScaleFactor, + isMobilePlatform, + width, + height, + specialRegionBounds, + minDate, + maxDate, + blackoutDates, + ); } @override void updateRenderObject( - BuildContext context, _TimelineRenderObject renderObject) { + BuildContext context, + _TimelineRenderObject renderObject, + ) { renderObject ..horizontalLinesCountPerView = horizontalLinesCountPerView ..visibleDates = visibleDates @@ -450,27 +492,28 @@ class _TimelineRenderWidget extends MultiChildRenderObjectWidget { class _TimelineRenderObject extends CustomCalendarRenderObject { _TimelineRenderObject( - this._horizontalLinesCountPerView, - this._visibleDates, - this._timeSlotViewSettings, - this._timeIntervalWidth, - this._cellBorderColor, - this._isRTL, - this._calendarTheme, - this._themeData, - this._calendarCellNotifier, - this.scrollController, - this._specialRegion, - this._resourceItemHeight, - this.resourceCollection, - this._textScaleFactor, - this.isMobilePlatform, - this._width, - this._height, - this.specialRegionBounds, - this._minDate, - this._maxDate, - this._blackoutDates); + this._horizontalLinesCountPerView, + this._visibleDates, + this._timeSlotViewSettings, + this._timeIntervalWidth, + this._cellBorderColor, + this._isRTL, + this._calendarTheme, + this._themeData, + this._calendarCellNotifier, + this.scrollController, + this._specialRegion, + this._resourceItemHeight, + this.resourceCollection, + this._textScaleFactor, + this.isMobilePlatform, + this._width, + this._height, + this.specialRegionBounds, + this._minDate, + this._maxDate, + this._blackoutDates, + ); double _horizontalLinesCountPerView; @@ -745,8 +788,10 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; if (specialRegion == null || specialRegion!.isEmpty) { return; @@ -759,11 +804,14 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { continue; } final Rect rect = view.bound; - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: rect.height, maxHeight: rect.height, minWidth: rect.width, - maxWidth: rect.width)); + maxWidth: rect.width, + ), + ); child = childAfter(child); } } @@ -776,8 +824,14 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { resourceCollection != null && resourceCollection!.isNotEmpty; final int visibleDatesCount = visibleDates.length; final bool isTimelineMonth = visibleDatesCount > DateTime.daysPerWeek; - _minMaxExceeds(visibleDatesCount, isTimelineMonth, minDate, maxDate, - blackoutDates, context.canvas); + _minMaxExceeds( + visibleDatesCount, + isTimelineMonth, + minDate, + maxDate, + blackoutDates, + context.canvas, + ); if (isNeedDefaultPaint) { _addSpecialRegion(context.canvas, isResourceEnabled, isTimelineMonth); } else { @@ -801,24 +855,40 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { } void _minMaxExceeds( - int visibleDatesCount, - bool isTimelineMonth, - DateTime minDate, - DateTime maxDate, - List? blackoutDates, - Canvas canvas) { + int visibleDatesCount, + bool isTimelineMonth, + DateTime minDate, + DateTime maxDate, + List? blackoutDates, + Canvas canvas, + ) { final DateTime visibleStartDate = visibleDates[0]; final DateTime visibleEndDate = visibleDates[visibleDatesCount - 1]; - final int timeInterval = - CalendarViewHelper.getTimeInterval(timeSlotViewSettings); + final int timeInterval = CalendarViewHelper.getTimeInterval( + timeSlotViewSettings, + ); if (isDateWithInDateRange(visibleStartDate, visibleEndDate, minDate)) { - _drawDisabledDate(minDate, false, false, canvas, isTimelineMonth, - timeInterval, visibleDatesCount); + _drawDisabledDate( + minDate, + false, + false, + canvas, + isTimelineMonth, + timeInterval, + visibleDatesCount, + ); } if (isDateWithInDateRange(visibleStartDate, visibleEndDate, maxDate)) { - _drawDisabledDate(maxDate, true, false, canvas, isTimelineMonth, - timeInterval, visibleDatesCount); + _drawDisabledDate( + maxDate, + true, + false, + canvas, + isTimelineMonth, + timeInterval, + visibleDatesCount, + ); } if (blackoutDates == null || !isTimelineMonth) { @@ -829,34 +899,49 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { for (int i = 0; i < count; i++) { final DateTime blackoutDate = blackoutDates[i]; if (isDateWithInDateRange( - visibleStartDate, visibleEndDate, blackoutDate)) { - _drawDisabledDate(blackoutDate, false, true, canvas, isTimelineMonth, - timeInterval, visibleDatesCount); + visibleStartDate, + visibleEndDate, + blackoutDate, + )) { + _drawDisabledDate( + blackoutDate, + false, + true, + canvas, + isTimelineMonth, + timeInterval, + visibleDatesCount, + ); } } } void _drawDisabledDate( - DateTime disabledDate, - bool isMaxDate, - bool isBlackOutDate, - Canvas canvas, - bool isTimelineMonth, - int timeInterval, - int visibleDatesCount) { + DateTime disabledDate, + bool isMaxDate, + bool isBlackOutDate, + Canvas canvas, + bool isTimelineMonth, + int timeInterval, + int visibleDatesCount, + ) { final double minuteHeight = timeIntervalWidth / timeInterval; final double viewWidth = width / visibleDatesCount; - final int dateIndex = - DateTimeHelper.getVisibleDateIndex(visibleDates, disabledDate); + final int dateIndex = DateTimeHelper.getVisibleDateIndex( + visibleDates, + disabledDate, + ); double leftPosition = 0; const double topPosition = 0; - final double xPosition = isTimelineMonth - ? 0 - : CalendarViewHelper.getTimeToPosition( - Duration(hours: disabledDate.hour, minutes: disabledDate.minute), - timeSlotViewSettings, - minuteHeight); + final double xPosition = + isTimelineMonth + ? 0 + : CalendarViewHelper.getTimeToPosition( + Duration(hours: disabledDate.hour, minutes: disabledDate.minute), + timeSlotViewSettings, + minuteHeight, + ); double rightPosition = (dateIndex * viewWidth) + xPosition; if (isMaxDate == true) { leftPosition = @@ -873,15 +958,22 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { leftPosition = width - leftPosition; rightPosition = width - rightPosition; } - rect = - Rect.fromLTRB(leftPosition, topPosition, rightPosition, bottomPosition); + rect = Rect.fromLTRB( + leftPosition, + topPosition, + rightPosition, + bottomPosition, + ); _linePainter.style = PaintingStyle.fill; _linePainter.color = Colors.grey.withValues(alpha: 0.2); canvas.drawRect(rect, _linePainter); } void _drawTimeline( - Canvas canvas, bool isResourceEnabled, int visibleDatesCount) { + Canvas canvas, + bool isResourceEnabled, + int visibleDatesCount, + ) { _linePainter.strokeWidth = 0.5; _linePainter.strokeCap = StrokeCap.round; _linePainter.color = cellBorderColor ?? calendarTheme.cellBorderColor!; @@ -909,8 +1001,11 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { points.add(Offset(startXPosition, startYPosition)); points.add(Offset(endXPosition, endYPosition)); } else { - canvas.drawLine(Offset(startXPosition, startYPosition), - Offset(endXPosition, endYPosition), _linePainter); + canvas.drawLine( + Offset(startXPosition, startYPosition), + Offset(endXPosition, endYPosition), + _linePainter, + ); } if (isRTL) { @@ -932,8 +1027,11 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { endXPosition = size.width; startYPosition = resourceItemHeight; for (int i = 0; i < resourceCollection!.length; i++) { - canvas.drawLine(Offset(startXPosition, startYPosition), - Offset(endXPosition, startYPosition), _linePainter); + canvas.drawLine( + Offset(startXPosition, startYPosition), + Offset(endXPosition, startYPosition), + _linePainter, + ); startYPosition += resourceItemHeight; } } @@ -944,7 +1042,8 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { } void _addMouseHovering(Canvas canvas, Size size, bool isResourceEnabled) { - double left = (calendarCellNotifier.value!.dx ~/ timeIntervalWidth) * + double left = + (calendarCellNotifier.value!.dx ~/ timeIntervalWidth) * timeIntervalWidth; double top = 0; double height = size.height; @@ -956,11 +1055,12 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { } const double padding = 0.5; top = top == 0 ? padding : top; - height = height == size.height - ? top == padding - ? height - (padding * 2) - : height - padding - : height; + height = + height == size.height + ? top == padding + ? height - (padding * 2) + : height - padding + : height; double width = timeIntervalWidth; double difference = 0; if (isRTL && @@ -977,8 +1077,9 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { _linePainter.style = PaintingStyle.stroke; _linePainter.strokeWidth = 2; - _linePainter.color = - calendarTheme.selectionBorderColor!.withValues(alpha: 0.4); + _linePainter.color = calendarTheme.selectionBorderColor!.withValues( + alpha: 0.4, + ); left = left == 0 ? left - difference + padding : left - difference; canvas.drawRect(Rect.fromLTWH(left, top, width, height), _linePainter); } @@ -986,7 +1087,10 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { /// Calculate the position for special regions and draw the special regions /// in the timeline views . void _addSpecialRegion( - Canvas canvas, bool isResourceEnabled, bool isTimelineMonth) { + Canvas canvas, + bool isResourceEnabled, + bool isTimelineMonth, + ) { /// Condition added to check and add the special region for timeline day, /// timeline week and timeline work week view only, since the special region /// support not applicable for timeline month view. @@ -995,18 +1099,21 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { } final TextPainter painter = TextPainter( - textDirection: TextDirection.ltr, - maxLines: 1, - textScaler: TextScaler.linear(textScaleFactor), - textAlign: isRTL ? TextAlign.right : TextAlign.left, - textWidthBasis: TextWidthBasis.longestLine); + textDirection: TextDirection.ltr, + maxLines: 1, + textScaler: TextScaler.linear(textScaleFactor), + textAlign: isRTL ? TextAlign.right : TextAlign.left, + textWidthBasis: TextWidthBasis.longestLine, + ); _linePainter.style = PaintingStyle.fill; final int count = specialRegionBounds.length; final TextStyle defaultTextStyle = TextStyle( - color: themeData.brightness == Brightness.dark - ? Colors.white54 - : Colors.black45); + color: + themeData.brightness == Brightness.dark + ? Colors.white54 + : Colors.black45, + ); for (int i = 0; i < count; i++) { final TimeRegionView view = specialRegionBounds[i]; final CalendarTimeRegion region = view.region; @@ -1026,8 +1133,9 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { painter.ellipsis = '..'; } else { painter.text = TextSpan( - text: String.fromCharCode(region.iconData!.codePoint), - style: textStyle.copyWith(fontFamily: region.iconData!.fontFamily)); + text: String.fromCharCode(region.iconData!.codePoint), + style: textStyle.copyWith(fontFamily: region.iconData!.fontFamily), + ); } painter.layout(maxWidth: rect.width - 4); @@ -1048,39 +1156,55 @@ class _TimelineRenderObject extends CustomCalendarRenderObject { if (isResourceEnabled) { for (int i = 0; i < resourceCollection!.length; i++) { semanticsBuilder = _getAccessibilityDates( - size, top, height, semanticsBuilder, resourceCollection![i]); + size, + top, + height, + semanticsBuilder, + resourceCollection![i], + ); top += height; } } else { - semanticsBuilder = - _getAccessibilityDates(size, top, height, semanticsBuilder); + semanticsBuilder = _getAccessibilityDates( + size, + top, + height, + semanticsBuilder, + ); } return semanticsBuilder; } /// Returns the custom painter semantics for visible dates collection. - List _getAccessibilityDates(Size size, double top, - double height, List semanticsBuilder, - [CalendarResource? resource]) { + List _getAccessibilityDates( + Size size, + double top, + double height, + List semanticsBuilder, [ + CalendarResource? resource, + ]) { double left = isRTL ? size.width - timeIntervalWidth : 0; final int startHour = timeSlotViewSettings.startHour.toInt(); final int startHourMinutes = ((timeSlotViewSettings.startHour - startHour) * 60).toInt(); - final int timeInterval = - CalendarViewHelper.getTimeInterval(timeSlotViewSettings); + final int timeInterval = CalendarViewHelper.getTimeInterval( + timeSlotViewSettings, + ); for (int j = 0; j < visibleDates.length; j++) { DateTime date = visibleDates[j]; for (int i = 0; i < horizontalLinesCountPerView; i++) { final int minute = (i * timeInterval) + startHourMinutes; date = DateTime(date.year, date.month, date.day, startHour, minute); - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, timeIntervalWidth, height), - properties: SemanticsProperties( - label: _getAccessibilityText(date, resource), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, timeIntervalWidth, height), + properties: SemanticsProperties( + label: _getAccessibilityText(date, resource), + textDirection: TextDirection.ltr, + ), ), - )); + ); if (isRTL) { left -= timeIntervalWidth; } else { @@ -1112,26 +1236,26 @@ class TimelineViewHeaderView extends CustomPainter { /// Constructor to create the view header view to holds header cell for /// timeline views. TimelineViewHeaderView( - this.visibleDates, - this.timelineViewHeaderScrollController, - this.repaintNotifier, - this.viewHeaderStyle, - this.timeSlotViewSettings, - this.viewHeaderHeight, - this.isRTL, - this.todayHighlightColor, - this.todayTextStyle, - this.locale, - this.calendarTheme, - this.themeData, - this.minDate, - this.maxDate, - this.viewHeaderNotifier, - this.cellBorderColor, - this.blackoutDates, - this.blackoutDatesTextStyle, - this.textScaleFactor) - : super(repaint: repaintNotifier); + this.visibleDates, + this.timelineViewHeaderScrollController, + this.repaintNotifier, + this.viewHeaderStyle, + this.timeSlotViewSettings, + this.viewHeaderHeight, + this.isRTL, + this.todayHighlightColor, + this.todayTextStyle, + this.locale, + this.calendarTheme, + this.themeData, + this.minDate, + this.maxDate, + this.viewHeaderNotifier, + this.cellBorderColor, + this.blackoutDates, + this.blackoutDatesTextStyle, + this.textScaleFactor, + ) : super(repaint: repaintNotifier); /// Holds the visible dates collection for current timeline view. final List visibleDates; @@ -1206,38 +1330,46 @@ class TimelineViewHeaderView extends CustomPainter { final bool isTimelineMonth = visibleDatesLength > DateTime.daysPerWeek; final DateTime today = DateTime.now(); final double childWidth = size.width / visibleDatesLength; - final int index = isTimelineMonth - ? 0 - : timelineViewHeaderScrollController.offset ~/ childWidth; - _xPosition = !isTimelineMonth - ? timelineViewHeaderScrollController.offset - : isRTL + final int index = + isTimelineMonth + ? 0 + : timelineViewHeaderScrollController.offset ~/ childWidth; + _xPosition = + !isTimelineMonth + ? timelineViewHeaderScrollController.offset + : isRTL ? size.width - childWidth : 0; - final TextStyle defaultThemeViewHeaderDayTextStyle = - themeData.textTheme.bodySmall!.copyWith( - color: themeData.colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 11, - ); - final TextStyle defaultThemeViewHeaderDateTextStyle = - themeData.textTheme.bodyMedium!.copyWith( - color: themeData.colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 15, - ); + final TextStyle defaultThemeViewHeaderDayTextStyle = themeData + .textTheme + .bodySmall! + .copyWith( + color: themeData.colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 11, + ); + final TextStyle defaultThemeViewHeaderDateTextStyle = themeData + .textTheme + .bodyMedium! + .copyWith( + color: themeData.colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 15, + ); TextStyle viewHeaderDateStyle = calendarTheme.viewHeaderDateTextStyle!; TextStyle viewHeaderDayStyle = calendarTheme.viewHeaderDayTextStyle!; if (viewHeaderDateStyle == defaultThemeViewHeaderDateTextStyle && isTimelineMonth) { - viewHeaderDateStyle = - viewHeaderDateStyle.copyWith(fontSize: viewHeaderDayStyle.fontSize); + viewHeaderDateStyle = viewHeaderDateStyle.copyWith( + fontSize: viewHeaderDayStyle.fontSize, + ); } if (viewHeaderDayStyle == defaultThemeViewHeaderDayTextStyle && !isTimelineMonth) { - viewHeaderDayStyle = - viewHeaderDayStyle.copyWith(fontSize: viewHeaderDateStyle.fontSize); + viewHeaderDayStyle = viewHeaderDayStyle.copyWith( + fontSize: viewHeaderDateStyle.fontSize, + ); } final TextStyle? blackoutDatesStyle = calendarTheme.blackoutDatesTextStyle; @@ -1246,7 +1378,10 @@ class TimelineViewHeaderView extends CustomPainter { TextStyle dateTextStyle = viewHeaderDateStyle; final Color? todayTextColor = CalendarViewHelper.getTodayHighlightTextColor( - todayHighlightColor, todayTextStyle, calendarTheme); + todayHighlightColor, + todayTextStyle, + calendarTheme, + ); if (isTimelineMonth) { _hoverPainter.strokeWidth = 0.5; @@ -1268,21 +1403,30 @@ class TimelineViewHeaderView extends CustomPainter { : timeSlotViewSettings.dayFormat; final String dayText = DateFormat(dayFormat, locale).format(currentDate); - final String dateText = - DateFormat(timeSlotViewSettings.dateFormat).format(currentDate); + final String dateText = DateFormat( + timeSlotViewSettings.dateFormat, + ).format(currentDate); - final bool isBlackoutDate = - CalendarViewHelper.isDateInDateCollection(blackoutDates, currentDate); + final bool isBlackoutDate = CalendarViewHelper.isDateInDateCollection( + blackoutDates, + currentDate, + ); if (isSameDate(currentDate, today)) { - dayTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle!.copyWith( - fontSize: viewHeaderDayStyle.fontSize, color: todayTextColor) - : viewHeaderDayStyle.copyWith(color: todayTextColor); - dateTextStyle = todayTextStyle != null - ? calendarTheme.todayTextStyle!.copyWith( - fontSize: viewHeaderDateStyle.fontSize, color: todayTextColor) - : viewHeaderDateStyle.copyWith(color: todayTextColor); + dayTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: viewHeaderDayStyle.fontSize, + color: todayTextColor, + ) + : viewHeaderDayStyle.copyWith(color: todayTextColor); + dateTextStyle = + todayTextStyle != null + ? calendarTheme.todayTextStyle!.copyWith( + fontSize: viewHeaderDateStyle.fontSize, + color: todayTextColor, + ) + : viewHeaderDateStyle.copyWith(color: todayTextColor); } else { dateTextStyle = viewHeaderDateStyle; dayTextStyle = viewHeaderDayStyle; @@ -1293,26 +1437,32 @@ class TimelineViewHeaderView extends CustomPainter { dateTextStyle = dateTextStyle.merge(blackoutDatesStyle); dayTextStyle = dayTextStyle.merge(blackoutDatesStyle); } else { - dateTextStyle = - dateTextStyle.copyWith(decoration: TextDecoration.lineThrough); - dayTextStyle = - dayTextStyle.copyWith(decoration: TextDecoration.lineThrough); + dateTextStyle = dateTextStyle.copyWith( + decoration: TextDecoration.lineThrough, + ); + dayTextStyle = dayTextStyle.copyWith( + decoration: TextDecoration.lineThrough, + ); } } if (!isDateWithInDateRange(minDate, maxDate, currentDate)) { dayTextStyle = dayTextStyle.copyWith( - color: dayTextStyle.color != null - ? dayTextStyle.color!.withValues(alpha: 0.38) - : themeData.brightness == Brightness.light - ? Colors.black26 - : Colors.white38); + color: + dayTextStyle.color != null + ? dayTextStyle.color!.withValues(alpha: 0.38) + : themeData.brightness == Brightness.light + ? Colors.black26 + : Colors.white38, + ); dateTextStyle = dateTextStyle.copyWith( - color: dateTextStyle.color != null - ? dateTextStyle.color!.withValues(alpha: 0.38) - : themeData.brightness == Brightness.light - ? Colors.black26 - : Colors.white38); + color: + dateTextStyle.color != null + ? dateTextStyle.color!.withValues(alpha: 0.38) + : themeData.brightness == Brightness.light + ? Colors.black26 + : Colors.white38, + ); } final TextSpan dayTextSpan = TextSpan(text: dayText, style: dayTextStyle); @@ -1323,8 +1473,10 @@ class TimelineViewHeaderView extends CustomPainter { _dayTextPainter.textWidthBasis = TextWidthBasis.longestLine; _dayTextPainter.textScaler = TextScaler.linear(textScaleFactor); - final TextSpan dateTextSpan = - TextSpan(text: dateText, style: dateTextStyle); + final TextSpan dateTextSpan = TextSpan( + text: dateText, + style: dateTextStyle, + ); _dateTextPainter.text = dateTextSpan; _dateTextPainter.textDirection = TextDirection.ltr; @@ -1344,13 +1496,19 @@ class TimelineViewHeaderView extends CustomPainter { } void _drawTimelineTimeSlotsViewHeader( - Canvas canvas, Size size, double childWidth, int index, int i) { + Canvas canvas, + Size size, + double childWidth, + int index, + int i, + ) { if (_dateTextPainter.width + _xPosition + (_padding * 2) + _dayTextPainter.width > (i + 1) * childWidth) { - _xPosition = ((i + 1) * childWidth) - + _xPosition = + ((i + 1) * childWidth) - (_dateTextPainter.width + (_padding * 2) + _dayTextPainter.width); } @@ -1360,27 +1518,38 @@ class TimelineViewHeaderView extends CustomPainter { if (isRTL) { _dateTextPainter.paint( - canvas, - Offset(size.width - _xPosition - _padding - _dateTextPainter.width, - viewHeaderHeight / 2 - _dateTextPainter.height / 2)); + canvas, + Offset( + size.width - _xPosition - _padding - _dateTextPainter.width, + viewHeaderHeight / 2 - _dateTextPainter.height / 2, + ), + ); _dayTextPainter.paint( - canvas, - Offset( - size.width - - _xPosition - - (_padding * 2) - - _dayTextPainter.width - - _dateTextPainter.width, - viewHeaderHeight / 2 - _dayTextPainter.height / 2)); + canvas, + Offset( + size.width - + _xPosition - + (_padding * 2) - + _dayTextPainter.width - + _dateTextPainter.width, + viewHeaderHeight / 2 - _dayTextPainter.height / 2, + ), + ); } else { _dateTextPainter.paint( - canvas, - Offset(_padding + _xPosition, - viewHeaderHeight / 2 - _dateTextPainter.height / 2)); + canvas, + Offset( + _padding + _xPosition, + viewHeaderHeight / 2 - _dateTextPainter.height / 2, + ), + ); _dayTextPainter.paint( - canvas, - Offset(_dateTextPainter.width + _xPosition + (_padding * 2), - viewHeaderHeight / 2 - _dayTextPainter.height / 2)); + canvas, + Offset( + _dateTextPainter.width + _xPosition + (_padding * 2), + viewHeaderHeight / 2 - _dayTextPainter.height / 2, + ), + ); } if (index == i) { @@ -1391,16 +1560,22 @@ class TimelineViewHeaderView extends CustomPainter { } void _drawTimelineMonthViewHeader( - Canvas canvas, double childWidth, Size size, bool isBlackoutDate) { + Canvas canvas, + double childWidth, + Size size, + bool isBlackoutDate, + ) { canvas.clipRect(Rect.fromLTWH(_xPosition, 0, childWidth, size.height)); const double leftPadding = 2; - final double startXPosition = _xPosition + + final double startXPosition = + _xPosition + (childWidth - (_dateTextPainter.width + leftPadding + _dayTextPainter.width)) / 2; - final double startYPosition = (size.height - + final double startYPosition = + (size.height - (_dayTextPainter.height > _dateTextPainter.height ? _dayTextPainter.height : _dateTextPainter.height)) / @@ -1411,15 +1586,21 @@ class TimelineViewHeaderView extends CustomPainter { if (!isRTL) { _dateTextPainter.paint(canvas, Offset(startXPosition, startYPosition)); _dayTextPainter.paint( - canvas, - Offset(startXPosition + _dateTextPainter.width + leftPadding, - startYPosition)); + canvas, + Offset( + startXPosition + _dateTextPainter.width + leftPadding, + startYPosition, + ), + ); } else { _dayTextPainter.paint(canvas, Offset(startXPosition, startYPosition)); _dateTextPainter.paint( - canvas, - Offset(startXPosition + _dayTextPainter.width + leftPadding, - startYPosition)); + canvas, + Offset( + startXPosition + _dayTextPainter.width + leftPadding, + startYPosition, + ), + ); } if (isRTL) { @@ -1431,7 +1612,10 @@ class TimelineViewHeaderView extends CustomPainter { _hoverPainter.color = cellBorderColor ?? calendarTheme.cellBorderColor!; canvas.restore(); canvas.drawLine( - Offset(_xPosition, 0), Offset(_xPosition, size.height), _hoverPainter); + Offset(_xPosition, 0), + Offset(_xPosition, size.height), + _hoverPainter, + ); } void _addMouseHovering(Canvas canvas, Size size, [double? cellWidth]) { @@ -1441,19 +1625,21 @@ class TimelineViewHeaderView extends CustomPainter { timelineViewHeaderScrollController.position.viewportDimension) { difference = timelineViewHeaderScrollController.position.viewportDimension - - size.width; - } - final double leftPosition = isRTL && cellWidth == null - ? size.width - - _xPosition - - (_padding * 2) - - _dayTextPainter.width - - _dateTextPainter.width - - _padding - : _xPosition; - final double rightPosition = isRTL && cellWidth == null - ? size.width - _xPosition - : cellWidth != null + size.width; + } + final double leftPosition = + isRTL && cellWidth == null + ? size.width - + _xPosition - + (_padding * 2) - + _dayTextPainter.width - + _dateTextPainter.width - + _padding + : _xPosition; + final double rightPosition = + isRTL && cellWidth == null + ? size.width - _xPosition + : cellWidth != null ? _xPosition + cellWidth - _padding : _xPosition + _dayTextPainter.width + @@ -1467,8 +1653,9 @@ class TimelineViewHeaderView extends CustomPainter { : Colors.black87) .withValues(alpha: 0.04); canvas.drawRect( - Rect.fromLTRB(leftPosition, 0, rightPosition + _padding, size.height), - _hoverPainter); + Rect.fromLTRB(leftPosition, 0, rightPosition + _padding, size.height), + _hoverPainter, + ); } } @@ -1490,7 +1677,9 @@ class TimelineViewHeaderView extends CustomPainter { (isTimelineMonth && (oldWidget.blackoutDatesTextStyle != blackoutDatesTextStyle || !CalendarViewHelper.isDateCollectionEqual( - oldWidget.blackoutDates, blackoutDates))); + oldWidget.blackoutDates, + blackoutDates, + ))); } List _getSemanticsBuilder(Size size) { @@ -1501,13 +1690,15 @@ class TimelineViewHeaderView extends CustomPainter { double left = isRTL ? size.width - cellWidth : 0; const double top = 0; for (int i = 0; i < visibleDatesLength; i++) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, cellWidth, size.height), - properties: SemanticsProperties( - label: _getAccessibilityText(visibleDates[i]), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, cellWidth, size.height), + properties: SemanticsProperties( + label: _getAccessibilityText(visibleDates[i]), + textDirection: TextDirection.ltr, + ), ), - )); + ); if (isRTL) { left -= cellWidth; } else { @@ -1519,7 +1710,8 @@ class TimelineViewHeaderView extends CustomPainter { } String _getAccessibilityText(DateTime date) { - final String textString = DateFormat('EEEEE').format(date) + + final String textString = + DateFormat('EEEEE').format(date) + DateFormat('dd/MMMM/yyyy').format(date); if (!isDateWithInDateRange(minDate, maxDate, date)) { return '$textString, Disabled date'; diff --git a/packages/syncfusion_flutter_calendar/pubspec.yaml b/packages/syncfusion_flutter_calendar/pubspec.yaml index 2cfd55199..4456e39ea 100644 --- a/packages/syncfusion_flutter_calendar/pubspec.yaml +++ b/packages/syncfusion_flutter_calendar/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_calendar description: The Flutter Calendar widget has nine built-in configurable views that provide basic functionalities for scheduling and representing appointments/events efficiently. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_calendar screenshots: @@ -12,26 +12,29 @@ screenshots: path: screenshots/flutter-calendar-load-more.gif environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: sdk: flutter - timezone: 0.10.0 + timezone: ^0.10.0 syncfusion_flutter_core: - path: ../syncfusion_flutter_core - - + path: ../syncfusion_flutter_core syncfusion_flutter_datepicker: path: ../syncfusion_flutter_datepicker + syncfusion_localizations: + path: ../syncfusion_localizations - intl: '>=0.18.1 <0.21.0' + flutter_localizations: + sdk: flutter flutter: assets: - packages/timezone/data/latest_all.tzf + - assets/fonts/Roboto-Medium.ttf + - assets/images/ \ No newline at end of file diff --git a/packages/syncfusion_flutter_charts/CHANGELOG.md b/packages/syncfusion_flutter_charts/CHANGELOG.md index c02d77900..362fbd1a3 100644 --- a/packages/syncfusion_flutter_charts/CHANGELOG.md +++ b/packages/syncfusion_flutter_charts/CHANGELOG.md @@ -1,10 +1,46 @@ -## [28.2.10] - 11/03/2025 +## [30.1.1] - 10/06/2025 + +**General** + +* The compatible version of our Flutter charts widget has been updated to Flutter SDK 3.32.0. + +### Features + +* Enhanced chart legend customization by introducing chart-specific legend item classes (CartesianLegendItem, CircularLegendItem, FunnelLegendItem, and PyramidLegendItem), enabling direct access to series, seriesIndex, and pointIndex. +* \#FR57680 - Added directional zooming to Cartesian charts for intuitive zoom control based on finger gestures. + +## [29.2.4] - 14/05/2025 + +**Bugs** + +* \#BD718806 - The legend now toggles properly even when the [offset](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/Legend/offset.html) property is set and chart behaviors are enabled. + +## [29.1.40] - 29/04/2025 + +**Bugs** + +* \#GH2334 - Now, the [HistogramSeries](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/HistogramSeries-class.html) will render properly when a single data point is set to the [dataSource](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeries/dataSource.html). +* \#GH2335 - The [onPointDoubleTap](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeries/onPointDoubleTap.html) callback is now correctly invoked on double-tap in the chart series. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.37+1] - 09/04/2025 + +**Bugs** + +* \#FB65781 - - Now, the [`labelsExtent`](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/labelsExtent.html) properly specifies the space between the axis line and the axis title. + +## [29.1.35] - 01/04/2025 **Bugs** -* \#FB65781 - The [labelsExtent](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartAxis/labelsExtent.html) property now applies padding for each axis in the Cartesian axis. +* \#BD702563 - Now, the [updateDataSource](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/ChartSeriesController/updateDataSource.html) method properly clears data points when using removedDataIndexes in charts. -## Unreleased +## [29.1.33] - 25/03/2025 **General** @@ -13,7 +49,7 @@ * The Syncfusion® Flutter charts example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. -## [28.2.8] - 04/03/2025 +## [28.2.9] - 04/03/2025 **Bugs** diff --git a/packages/syncfusion_flutter_charts/assets/fonts/Roboto-Medium.ttf b/packages/syncfusion_flutter_charts/assets/fonts/Roboto-Medium.ttf new file mode 100644 index 000000000..f714a514d Binary files /dev/null and b/packages/syncfusion_flutter_charts/assets/fonts/Roboto-Medium.ttf differ diff --git a/packages/syncfusion_flutter_charts/assets/fonts/Times-New-Roman.ttf b/packages/syncfusion_flutter_charts/assets/fonts/Times-New-Roman.ttf new file mode 100644 index 000000000..5cdac9ca5 Binary files /dev/null and b/packages/syncfusion_flutter_charts/assets/fonts/Times-New-Roman.ttf differ diff --git a/packages/syncfusion_flutter_charts/example/lib/main.dart b/packages/syncfusion_flutter_charts/example/lib/main.dart index b95646a2b..5e903190b 100644 --- a/packages/syncfusion_flutter_charts/example/lib/main.dart +++ b/packages/syncfusion_flutter_charts/example/lib/main.dart @@ -30,33 +30,34 @@ class _MyHomePageState extends State<_MyHomePage> { _SalesData('Feb', 28), _SalesData('Mar', 34), _SalesData('Apr', 32), - _SalesData('May', 40) + _SalesData('May', 40), ]; @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Flutter chart'), - ), - body: Column(children: [ + appBar: AppBar(title: const Text('Syncfusion Flutter chart')), + body: Column( + children: [ //Initialize the chart widget SfCartesianChart( - primaryXAxis: CategoryAxis(), - // Chart title - title: ChartTitle(text: 'Half yearly sales analysis'), - // Enable legend - legend: Legend(isVisible: true), - // Enable tooltip - tooltipBehavior: TooltipBehavior(enable: true), - series: >[ - LineSeries<_SalesData, String>( - dataSource: data, - xValueMapper: (_SalesData sales, _) => sales.year, - yValueMapper: (_SalesData sales, _) => sales.sales, - name: 'Sales', - // Enable data label - dataLabelSettings: DataLabelSettings(isVisible: true)) - ]), + primaryXAxis: CategoryAxis(), + // Chart title + title: ChartTitle(text: 'Half yearly sales analysis'), + // Enable legend + legend: Legend(isVisible: true), + // Enable tooltip + tooltipBehavior: TooltipBehavior(enable: true), + series: >[ + LineSeries<_SalesData, String>( + dataSource: data, + xValueMapper: (_SalesData sales, _) => sales.year, + yValueMapper: (_SalesData sales, _) => sales.sales, + name: 'Sales', + // Enable data label + dataLabelSettings: DataLabelSettings(isVisible: true), + ), + ], + ), Expanded( child: Padding( padding: const EdgeInsets.all(8.0), @@ -64,10 +65,12 @@ class _MyHomePageState extends State<_MyHomePage> { child: SfSparkLineChart.custom( //Enable the trackball trackball: SparkChartTrackball( - activationMode: SparkChartActivationMode.tap), + activationMode: SparkChartActivationMode.tap, + ), //Enable marker marker: SparkChartMarker( - displayMode: SparkChartMarkerDisplayMode.all), + displayMode: SparkChartMarkerDisplayMode.all, + ), //Enable data label labelDisplayMode: SparkChartLabelDisplayMode.all, xValueMapper: (int index) => data[index].year, @@ -75,8 +78,10 @@ class _MyHomePageState extends State<_MyHomePage> { dataCount: 5, ), ), - ) - ])); + ), + ], + ), + ); } } diff --git a/packages/syncfusion_flutter_charts/example/pubspec.yaml b/packages/syncfusion_flutter_charts/example/pubspec.yaml index 8644532b0..180874960 100644 --- a/packages/syncfusion_flutter_charts/example/pubspec.yaml +++ b/packages/syncfusion_flutter_charts/example/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0+1 publish_to: 'none' environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_charts/images/Document.png b/packages/syncfusion_flutter_charts/images/Document.png new file mode 100644 index 000000000..b4e89b92d Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/Document.png differ diff --git a/packages/syncfusion_flutter_charts/images/People_Circle12.png b/packages/syncfusion_flutter_charts/images/People_Circle12.png new file mode 100644 index 000000000..bafa37946 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/People_Circle12.png differ diff --git a/packages/syncfusion_flutter_charts/images/People_Circle14.png b/packages/syncfusion_flutter_charts/images/People_Circle14.png new file mode 100644 index 000000000..0ed7efe76 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/People_Circle14.png differ diff --git a/packages/syncfusion_flutter_charts/images/People_Circle16.png b/packages/syncfusion_flutter_charts/images/People_Circle16.png new file mode 100644 index 000000000..37d86ad47 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/People_Circle16.png differ diff --git a/packages/syncfusion_flutter_charts/images/People_Circle3.png b/packages/syncfusion_flutter_charts/images/People_Circle3.png new file mode 100644 index 000000000..34d3c6109 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/People_Circle3.png differ diff --git a/packages/syncfusion_flutter_charts/images/SB.png b/packages/syncfusion_flutter_charts/images/SB.png new file mode 100644 index 000000000..ac042e938 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/SB.png differ diff --git a/packages/syncfusion_flutter_charts/images/apple.png b/packages/syncfusion_flutter_charts/images/apple.png new file mode 100644 index 000000000..7c67b1985 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/apple.png differ diff --git a/packages/syncfusion_flutter_charts/images/axes.png b/packages/syncfusion_flutter_charts/images/axes.png new file mode 100644 index 000000000..2b98ca55f Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/axes.png differ diff --git a/packages/syncfusion_flutter_charts/images/axisfeatures.png b/packages/syncfusion_flutter_charts/images/axisfeatures.png new file mode 100644 index 000000000..98d877c67 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/axisfeatures.png differ diff --git a/packages/syncfusion_flutter_charts/images/bike.png b/packages/syncfusion_flutter_charts/images/bike.png new file mode 100644 index 000000000..2165945de Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/bike.png differ diff --git a/packages/syncfusion_flutter_charts/images/bike_legend.png b/packages/syncfusion_flutter_charts/images/bike_legend.png new file mode 100644 index 000000000..75befc73e Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/bike_legend.png differ diff --git a/packages/syncfusion_flutter_charts/images/book.png b/packages/syncfusion_flutter_charts/images/book.png new file mode 100644 index 000000000..a92ccc0a5 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/book.png differ diff --git a/packages/syncfusion_flutter_charts/images/bus.png b/packages/syncfusion_flutter_charts/images/bus.png new file mode 100644 index 000000000..a7796d619 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/bus.png differ diff --git a/packages/syncfusion_flutter_charts/images/car.png b/packages/syncfusion_flutter_charts/images/car.png new file mode 100644 index 000000000..f0f3fd420 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/car.png differ diff --git a/packages/syncfusion_flutter_charts/images/car_legend.png b/packages/syncfusion_flutter_charts/images/car_legend.png new file mode 100644 index 000000000..eab6cafa6 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/car_legend.png differ diff --git a/packages/syncfusion_flutter_charts/images/cartesian.png b/packages/syncfusion_flutter_charts/images/cartesian.png new file mode 100644 index 000000000..7de6f7627 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/cartesian.png differ diff --git a/packages/syncfusion_flutter_charts/images/cloudy.png b/packages/syncfusion_flutter_charts/images/cloudy.png new file mode 100644 index 000000000..5e033713b Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/cloudy.png differ diff --git a/packages/syncfusion_flutter_charts/images/code.png b/packages/syncfusion_flutter_charts/images/code.png new file mode 100644 index 000000000..b9a3169a8 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/code.png differ diff --git a/packages/syncfusion_flutter_charts/images/code1.png b/packages/syncfusion_flutter_charts/images/code1.png new file mode 100644 index 000000000..bb6185050 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/code1.png differ diff --git a/packages/syncfusion_flutter_charts/images/code2.png b/packages/syncfusion_flutter_charts/images/code2.png new file mode 100644 index 000000000..186d333b9 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/code2.png differ diff --git a/packages/syncfusion_flutter_charts/images/cycle.webp b/packages/syncfusion_flutter_charts/images/cycle.webp new file mode 100644 index 000000000..209b3f344 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/cycle.webp differ diff --git a/packages/syncfusion_flutter_charts/images/cycle_legend.png b/packages/syncfusion_flutter_charts/images/cycle_legend.png new file mode 100644 index 000000000..eccde60ca Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/cycle_legend.png differ diff --git a/packages/syncfusion_flutter_charts/images/dashline.png b/packages/syncfusion_flutter_charts/images/dashline.png new file mode 100644 index 000000000..b654fee33 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/dashline.png differ diff --git a/packages/syncfusion_flutter_charts/images/documentation.png b/packages/syncfusion_flutter_charts/images/documentation.png new file mode 100644 index 000000000..eedf97f1e Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/documentation.png differ diff --git a/packages/syncfusion_flutter_charts/images/flight.png b/packages/syncfusion_flutter_charts/images/flight.png new file mode 100644 index 000000000..e7b244710 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/flight.png differ diff --git a/packages/syncfusion_flutter_charts/images/funnel.png b/packages/syncfusion_flutter_charts/images/funnel.png new file mode 100644 index 000000000..c6d87f26a Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/funnel.png differ diff --git a/packages/syncfusion_flutter_charts/images/grouping_dark.png b/packages/syncfusion_flutter_charts/images/grouping_dark.png new file mode 100644 index 000000000..fbffec0e8 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/grouping_dark.png differ diff --git a/packages/syncfusion_flutter_charts/images/home.png b/packages/syncfusion_flutter_charts/images/home.png new file mode 100644 index 000000000..3aebd8a31 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/home.png differ diff --git a/packages/syncfusion_flutter_charts/images/information.png b/packages/syncfusion_flutter_charts/images/information.png new file mode 100644 index 000000000..b26c04679 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/information.png differ diff --git a/packages/syncfusion_flutter_charts/images/livechart.png b/packages/syncfusion_flutter_charts/images/livechart.png new file mode 100644 index 000000000..9ff4a01f3 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/livechart.png differ diff --git a/packages/syncfusion_flutter_charts/images/maps_facebook.png b/packages/syncfusion_flutter_charts/images/maps_facebook.png new file mode 100644 index 000000000..86d2e724b Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/maps_facebook.png differ diff --git a/packages/syncfusion_flutter_charts/images/maps_instagram.png b/packages/syncfusion_flutter_charts/images/maps_instagram.png new file mode 100644 index 000000000..af4bdf3d3 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/maps_instagram.png differ diff --git a/packages/syncfusion_flutter_charts/images/maps_snapchat.png b/packages/syncfusion_flutter_charts/images/maps_snapchat.png new file mode 100644 index 000000000..1c65cc662 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/maps_snapchat.png differ diff --git a/packages/syncfusion_flutter_charts/images/maps_twitter.png b/packages/syncfusion_flutter_charts/images/maps_twitter.png new file mode 100644 index 000000000..032a520af Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/maps_twitter.png differ diff --git a/packages/syncfusion_flutter_charts/images/orange.png b/packages/syncfusion_flutter_charts/images/orange.png new file mode 100644 index 000000000..624c5aafb Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/orange.png differ diff --git a/packages/syncfusion_flutter_charts/images/other_fruits.png b/packages/syncfusion_flutter_charts/images/other_fruits.png new file mode 100644 index 000000000..909f56516 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/other_fruits.png differ diff --git a/packages/syncfusion_flutter_charts/images/pears.png b/packages/syncfusion_flutter_charts/images/pears.png new file mode 100644 index 000000000..10ac13bb2 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/pears.png differ diff --git a/packages/syncfusion_flutter_charts/images/person.png b/packages/syncfusion_flutter_charts/images/person.png new file mode 100644 index 000000000..b4dc1fb70 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/person.png differ diff --git a/packages/syncfusion_flutter_charts/images/personal_loan.png b/packages/syncfusion_flutter_charts/images/personal_loan.png new file mode 100644 index 000000000..592e7ab47 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/personal_loan.png differ diff --git a/packages/syncfusion_flutter_charts/images/productpage.png b/packages/syncfusion_flutter_charts/images/productpage.png new file mode 100644 index 000000000..ee93ba9c9 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/productpage.png differ diff --git a/packages/syncfusion_flutter_charts/images/pyramid.png b/packages/syncfusion_flutter_charts/images/pyramid.png new file mode 100644 index 000000000..90c1be377 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/pyramid.png differ diff --git a/packages/syncfusion_flutter_charts/images/rainy.png b/packages/syncfusion_flutter_charts/images/rainy.png new file mode 100644 index 000000000..da1c79053 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/rainy.png differ diff --git a/packages/syncfusion_flutter_charts/images/seriesfeatures.png b/packages/syncfusion_flutter_charts/images/seriesfeatures.png new file mode 100644 index 000000000..61736c544 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/seriesfeatures.png differ diff --git a/packages/syncfusion_flutter_charts/images/setting.png b/packages/syncfusion_flutter_charts/images/setting.png new file mode 100644 index 000000000..0b5a7c3e9 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/setting.png differ diff --git a/packages/syncfusion_flutter_charts/images/sunny_image.png b/packages/syncfusion_flutter_charts/images/sunny_image.png new file mode 100644 index 000000000..05a83177d Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/sunny_image.png differ diff --git a/packages/syncfusion_flutter_charts/images/syncfusion.png b/packages/syncfusion_flutter_charts/images/syncfusion.png new file mode 100644 index 000000000..b832e00d2 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/syncfusion.png differ diff --git a/packages/syncfusion_flutter_charts/images/syncfusion1.png b/packages/syncfusion_flutter_charts/images/syncfusion1.png new file mode 100644 index 000000000..18ab9100c Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/syncfusion1.png differ diff --git a/packages/syncfusion_flutter_charts/images/train.png b/packages/syncfusion_flutter_charts/images/train.png new file mode 100644 index 000000000..c53585329 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/train.png differ diff --git a/packages/syncfusion_flutter_charts/images/truck_legend.png b/packages/syncfusion_flutter_charts/images/truck_legend.png new file mode 100644 index 000000000..f95a05446 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/truck_legend.png differ diff --git a/packages/syncfusion_flutter_charts/images/userinteraction.png b/packages/syncfusion_flutter_charts/images/userinteraction.png new file mode 100644 index 000000000..12a0aa32d Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/userinteraction.png differ diff --git a/packages/syncfusion_flutter_charts/images/youtube.png b/packages/syncfusion_flutter_charts/images/youtube.png new file mode 100644 index 000000000..a84d09e23 Binary files /dev/null and b/packages/syncfusion_flutter_charts/images/youtube.png differ diff --git a/packages/syncfusion_flutter_charts/lib/charts.dart b/packages/syncfusion_flutter_charts/lib/charts.dart index 992bca38d..55de2dd31 100644 --- a/packages/syncfusion_flutter_charts/lib/charts.dart +++ b/packages/syncfusion_flutter_charts/lib/charts.dart @@ -52,7 +52,7 @@ export './src/charts/common/connector_line.dart'; export './src/charts/common/data_label.dart' show DataLabelSettings; export './src/charts/common/empty_points.dart'; export './src/charts/common/interactive_tooltip.dart'; -export './src/charts/common/legend.dart' hide ChartLegendItem; +export './src/charts/common/legend.dart'; export './src/charts/common/marker.dart' hide MarkerContainer, ChartMarker; export './src/charts/funnel_chart.dart'; export './src/charts/indicators/accumulation_distribution_indicator.dart' diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/axis.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/axis.dart index de6a6ff74..8773f4e50 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/axis.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/axis.dart @@ -884,16 +884,32 @@ abstract class ChartAxis extends LeafRenderObjectWidget { final double? maximumLabelWidth; /// Specifies the fixed width for the axis labels. This width represents the - /// space between axis line and axis title. + /// space between axis line and axis title, if value exceeds the maximum size + /// of the axis label. /// - /// If an axis label exceeds the specified value, as like [maximumLabelWidth] - /// feature, axis label will get trimmed and ellipse(...) will be added at - /// the end of the trimmed text. + /// If the `labelsExtent` value is greater than the axis label width, and no + /// [maximumLabelWidth] is specified, the additional space defined by + /// `labelsExtent` will be applied between the axis line and the axis title. + /// If [maximumLabelWidth] is specified, extra space is applied only if + /// `labelsExtent` exceeds the [maximumLabelWidth]. /// - /// Additionally, if an axis label width is within the specified value, white - /// space will be added at the beginning for remaining width. This is done to - /// maintain uniform bounds and to eliminate axis label flickering - /// on zooming/panning. + /// When multi-level labels are enabled, [labelsExtent] does not account for + /// their size; it only considers the axis label width. However, if the + /// `labelsExtent` value exceeds the axis label width, the extra space will + /// be applied between the axis title and the multi-level label. + /// + /// If the [labelPosition] is set to 'ChartDataLabelPosition.inside', and if + /// [labelsExtent] value exceeds the axis label width or [maximumLabelWidth], + /// additional space will be added between the axis line and the axis title. + /// + /// The [labelsExtent] property is especially useful when arranging the + /// multiple charts in a column layout, as it ensures that the Y-axis bounds + /// appear evenly aligned across all charts for better visual consistency. + /// + /// Additionally, if an axis label width or [maximumLabelWidth] is within the + /// specified value, white space will be added at the beginning for remaining + /// width.This is done to maintain uniform bounds and to eliminate axis label + /// flickering on zooming/panning. /// /// Complete label text will be shown in a tooltip when tapping/clicking over /// the trimmed axis labels. @@ -1605,8 +1621,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { double? _plotOffset; set plotOffset(double? value) { if (_plotOffset != value) { - assert(value == null || value >= 0, - 'PlotOffset must be greater than or equal to 0'); + assert( + value == null || value >= 0, + 'PlotOffset must be greater than or equal to 0', + ); _plotOffset = value; _updateEffectivePlotOffset(); } @@ -1616,8 +1634,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { double? _plotOffsetStart; set plotOffsetStart(double? value) { if (_plotOffsetStart != value) { - assert(value == null || value >= 0, - 'PlotOffsetStart must be greater than or equal to 0'); + assert( + value == null || value >= 0, + 'PlotOffsetStart must be greater than or equal to 0', + ); _plotOffsetStart = value; _updateEffectivePlotOffset(); } @@ -1627,8 +1647,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { double? _plotOffsetEnd; set plotOffsetEnd(double? value) { if (_plotOffsetEnd != value) { - assert(value == null || value >= 0, - 'PlotOffsetEnd must be greater than or equal to 0'); + assert( + value == null || value >= 0, + 'PlotOffsetEnd must be greater than or equal to 0', + ); _plotOffsetEnd = value; _updateEffectivePlotOffset(); } @@ -1639,8 +1661,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { set initialZoomFactor(double value) { if (_initialZoomFactor != value) { _initialZoomFactor = value; - assert(initialZoomFactor >= 0 && initialZoomFactor <= 1, - 'The initialZoomFactor of the axis should be between 0 and 1'); + assert( + initialZoomFactor >= 0 && initialZoomFactor <= 1, + 'The initialZoomFactor of the axis should be between 0 and 1', + ); controller.zoomFactor = clampDouble(value, 0.0, 1.0); markNeedsRangeUpdate(); } @@ -1652,8 +1676,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (_initialZoomPosition != value) { _initialZoomPosition = value; _needsRangeUpdate = true; - assert(initialZoomPosition >= 0 && initialZoomPosition <= 1, - 'The initialZoomPosition of the axis should be between 0 and 1'); + assert( + initialZoomPosition >= 0 && initialZoomPosition <= 1, + 'The initialZoomPosition of the axis should be between 0 and 1', + ); controller.zoomPosition = clampDouble(value, 0.0, 1.0); markNeedsRangeUpdate(); } @@ -1727,8 +1753,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { set maximumLabelWidth(double? value) { if (_maximumLabelWidth != value) { _maximumLabelWidth = value; - assert(maximumLabelWidth == null || maximumLabelWidth! >= 0, - 'maximumLabelWidth must not be negative'); + assert( + maximumLabelWidth == null || maximumLabelWidth! >= 0, + 'maximumLabelWidth must not be negative', + ); markNeedsLayout(); } } @@ -1738,8 +1766,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { set labelsExtent(double? value) { if (_labelsExtent != value) { _labelsExtent = value; - assert(labelsExtent == null || labelsExtent! >= 0, - 'labelsExtent must not be negative'); + assert( + labelsExtent == null || labelsExtent! >= 0, + 'labelsExtent must not be negative', + ); markNeedsLayout(); } } @@ -1908,8 +1938,9 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { ); _animationController!.addStatusListener(_onAnimationStatusChanged); _animation!.addListener(markNeedsRangeUpdate); - controller - ._addZoomFactorAndPositionListener(_onZoomFactorAndPositionChanged); + controller._addZoomFactorAndPositionListener( + _onZoomFactorAndPositionChanged, + ); super.attach(owner); } @@ -1922,8 +1953,9 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { void detach() { _animationController?.removeStatusListener(_onAnimationStatusChanged); _animation?.removeListener(markNeedsRangeUpdate); - controller - ._removeZoomFactorAndPositionListener(_onZoomFactorAndPositionChanged); + controller._removeZoomFactorAndPositionListener( + _onZoomFactorAndPositionChanged, + ); super.detach(); } @@ -1964,13 +1996,16 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { assert(_renderer != null); newSize = _renderer!._preferredSize(availableSize); } else { - newSize = isVertical - ? Size(0, availableSize.height) - : Size(availableSize.width, 0); + newSize = + isVertical + ? Size(0, availableSize.height) + : Size(availableSize.width, 0); } final Size constraintsSize = constraints.biggest; - size = Size(min(newSize.width, constraintsSize.width), - min(newSize.height, constraintsSize.height)); + size = Size( + min(newSize.width, constraintsSize.width), + min(newSize.height, constraintsSize.height), + ); if (isVertical) { _renderSize = Size(size.width, size.height - _effectivePlotOffset); @@ -2016,22 +2051,33 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (_effectivePlotOffset > 0) { if (isVertical) { availableSize = Size( - availableSize.width, availableSize.height - _effectivePlotOffset); + availableSize.width, + availableSize.height - _effectivePlotOffset, + ); } else { availableSize = Size( - availableSize.width - _effectivePlotOffset, availableSize.height); + availableSize.width - _effectivePlotOffset, + availableSize.height, + ); } } DoubleRange newActualRange = calculateActualRange(); - final num newActualInterval = - calculateActualInterval(newActualRange, availableSize); - newActualRange = - applyRangePadding(newActualRange, newActualInterval, availableSize); + final num newActualInterval = calculateActualInterval( + newActualRange, + availableSize, + ); + newActualRange = applyRangePadding( + newActualRange, + newActualInterval, + availableSize, + ); late DoubleRange newVisibleRange; // TODO(VijayakumarM): Need to handle anchorRangeToVisiblePoints in series? if (!anchorRangeToVisiblePoints && isXAxis && - parent!.behaviorArea?.zoomPanBehavior?.zoomMode == ZoomMode.x) { + parent != null && + parent!.behaviorArea != null && + parent!.behaviorArea!.effectiveZoomMode == ZoomMode.x) { newVisibleRange = newActualRange; } else { newVisibleRange = calculateVisibleRange(newActualRange); @@ -2039,7 +2085,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { autoScrollingDelta! > 0 && !zoomingInProgress) { final DoubleRange autoScrollRange = updateAutoScrollingDelta( - autoScrollingDelta!, newActualRange, newVisibleRange); + autoScrollingDelta!, + newActualRange, + newVisibleRange, + ); if ((autoScrollingMode == AutoScrollingMode.end && newActualRange.minimum < autoScrollRange.minimum) || (autoScrollingMode == AutoScrollingMode.start && @@ -2051,8 +2100,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (newVisibleRange != _visibleRange) { _effectiveVisibleRange = newVisibleRange; - _visibleRangeTween = - DoubleRangeTween(begin: _visibleRange, end: newVisibleRange); + _visibleRangeTween = DoubleRangeTween( + begin: _visibleRange, + end: newVisibleRange, + ); _animationController?.forward(from: 0.0); } } @@ -2061,19 +2112,28 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (_effectivePlotOffset > 0) { if (isVertical) { availableSize = Size( - availableSize.width, availableSize.height - _effectivePlotOffset); + availableSize.width, + availableSize.height - _effectivePlotOffset, + ); } else { availableSize = Size( - availableSize.width - _effectivePlotOffset, availableSize.height); + availableSize.width - _effectivePlotOffset, + availableSize.height, + ); } } DoubleRange newActualRange = calculateActualRange(); - final num newActualInterval = - calculateActualInterval(newActualRange, availableSize); + final num newActualInterval = calculateActualInterval( + newActualRange, + availableSize, + ); _actualInterval = newActualInterval; - newActualRange = - applyRangePadding(newActualRange, newActualInterval, availableSize); + newActualRange = applyRangePadding( + newActualRange, + newActualInterval, + availableSize, + ); controller._updateActualRange(newActualRange); late DoubleRange newVisibleRange; num newVisibleInterval = _actualInterval; @@ -2081,7 +2141,9 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { final bool canKeepActualRange = !anchorRangeToVisiblePoints; if (canKeepActualRange && !isXAxis && - parent?.behaviorArea?.zoomPanBehavior?.zoomMode == ZoomMode.x) { + parent != null && + parent!.behaviorArea != null && + parent!.behaviorArea!.effectiveZoomMode == ZoomMode.x) { newVisibleRange = newActualRange.copyWith(); } else { newVisibleRange = calculateVisibleRange(newActualRange.copyWith()); @@ -2089,7 +2151,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { autoScrollingDelta! > 0 && !zoomingInProgress) { final DoubleRange autoScrollRange = updateAutoScrollingDelta( - autoScrollingDelta!, newActualRange, newVisibleRange); + autoScrollingDelta!, + newActualRange, + newVisibleRange, + ); if ((autoScrollingMode == AutoScrollingMode.end && newActualRange.minimum < autoScrollRange.minimum) || (autoScrollingMode == AutoScrollingMode.start && @@ -2097,19 +2162,25 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { newVisibleRange = autoScrollRange; } } - newVisibleInterval = - calculateVisibleInterval(newVisibleRange, availableSize); + newVisibleInterval = calculateVisibleInterval( + newVisibleRange, + availableSize, + ); } } else { final bool canKeepActualRange = !anchorRangeToVisiblePoints; if (canKeepActualRange && !isXAxis && - parent?.behaviorArea?.zoomPanBehavior?.zoomMode == ZoomMode.x) { + parent != null && + parent!.behaviorArea != null && + parent!.behaviorArea!.effectiveZoomMode == ZoomMode.x) { newVisibleRange = newActualRange.copyWith(); } else { newVisibleRange = _visibleRangeTween!.evaluate(_animation!)!; - newVisibleInterval = - calculateVisibleInterval(newVisibleRange, availableSize); + newVisibleInterval = calculateVisibleInterval( + newVisibleRange, + availableSize, + ); } } @@ -2142,7 +2213,7 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { controller.zoomFactor = newVisibleRange.delta / actualRangeDelta; controller.zoomPosition = (newVisibleRange.minimum - newActualRange.minimum) / - actualRangeDelta; + actualRangeDelta; } newVisibleInterval = args.visibleInterval; } @@ -2163,18 +2234,25 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { @protected DoubleRange updateAutoScrollingDelta( - int scrollingDelta, DoubleRange actualRange, DoubleRange visibleRange) { + int scrollingDelta, + DoubleRange actualRange, + DoubleRange visibleRange, + ) { switch (autoScrollingMode) { case AutoScrollingMode.start: final DoubleRange autoScrollRange = DoubleRange( - actualRange.minimum, actualRange.minimum + scrollingDelta); + actualRange.minimum, + actualRange.minimum + scrollingDelta, + ); controller.zoomFactor = autoScrollRange.delta / actualRange.delta; controller.zoomPosition = 0; return autoScrollRange; case AutoScrollingMode.end: final DoubleRange autoScrollRange = DoubleRange( - actualRange.maximum - scrollingDelta, actualRange.maximum); + actualRange.maximum - scrollingDelta, + actualRange.maximum, + ); controller.zoomFactor = autoScrollRange.delta / actualRange.delta; controller.zoomPosition = 1 - controller.zoomFactor; return autoScrollRange; @@ -2237,7 +2315,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { @protected DoubleRange applyRangePadding( - DoubleRange range, num interval, Size availableSize) { + DoubleRange range, + num interval, + Size availableSize, + ) { final ChartRangePadding padding = effectiveRangePadding(); if (padding == ChartRangePadding.additional || padding == ChartRangePadding.additionalStart || @@ -2259,17 +2340,19 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { ChartRangePadding padding = ChartRangePadding.auto; if (rangePadding == ChartRangePadding.auto) { if (isVertical) { - padding = !isTransposed - ? (_dependentIsStacked100 - ? ChartRangePadding.round - : ChartRangePadding.normal) - : ChartRangePadding.none; + padding = + !isTransposed + ? (_dependentIsStacked100 + ? ChartRangePadding.round + : ChartRangePadding.normal) + : ChartRangePadding.none; } else { - padding = isTransposed - ? (_dependentIsStacked100 - ? ChartRangePadding.round - : ChartRangePadding.normal) - : ChartRangePadding.none; + padding = + isTransposed + ? (_dependentIsStacked100 + ? ChartRangePadding.round + : ChartRangePadding.normal) + : ChartRangePadding.none; } } else { padding = rangePadding; @@ -2324,24 +2407,27 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { minimum = (minimum - interval) - _remainder(minimum, interval); } } else { - minimum = range.minimum < ((5.0 / 6.0) * range.maximum) - ? 0 - : (range.minimum - (range.maximum - range.minimum) / 2); + minimum = + range.minimum < ((5.0 / 6.0) * range.maximum) + ? 0 + : (range.minimum - (range.maximum - range.minimum) / 2); if (minimum % interval > 0) { minimum -= minimum % interval; } } - num maximum = (range.maximum > 0) - ? (range.maximum + (range.maximum - start) / 20) - : (range.maximum - (range.maximum - start) / 20); + num maximum = + (range.maximum > 0) + ? (range.maximum + (range.maximum - start) / 20) + : (range.maximum - (range.maximum - start) / 20); remaining = interval - (maximum % interval); if ((0.365 * interval) >= remaining) { maximum += interval; } if (maximum % interval > 0) { - maximum = range.maximum > 0 - ? (maximum + interval) - (maximum % interval) - : (maximum + interval) + (maximum % interval); + maximum = + range.maximum > 0 + ? (maximum + interval) - (maximum % interval) + : (maximum + interval) + (maximum % interval); } range.minimum = minimum; range.maximum = maximum; @@ -2454,13 +2540,19 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (borderWidth > 0 && labelBorderColor != Colors.transparent) { switch (labelPlacement) { case LabelPlacement.onTicks: - calculateTickPositions(LabelPlacement.betweenTicks, - source: borderPositions, canCalculateMajorTick: false); + calculateTickPositions( + LabelPlacement.betweenTicks, + source: borderPositions, + canCalculateMajorTick: false, + ); break; case LabelPlacement.betweenTicks: - calculateTickPositions(LabelPlacement.onTicks, - source: borderPositions, canCalculateMajorTick: false); + calculateTickPositions( + LabelPlacement.onTicks, + source: borderPositions, + canCalculateMajorTick: false, + ); break; } } @@ -2517,15 +2609,27 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (effectiveLabelIntersectAction != AxisLabelIntersectAction.none) { _hasCollidingLabels = _isCollidingLabels( - length, startLabelAlign, betweenLabelsAlign, endLabelAlign); + length, + startLabelAlign, + betweenLabelsAlign, + endLabelAlign, + ); if (_hasCollidingLabels) { _arrangeLabels( - length, startLabelAlign, betweenLabelsAlign, endLabelAlign); + length, + startLabelAlign, + betweenLabelsAlign, + endLabelAlign, + ); } } else { _hasCollidingLabels = false; _arrangeLabels( - length, startLabelAlign, betweenLabelsAlign, endLabelAlign); + length, + startLabelAlign, + betweenLabelsAlign, + endLabelAlign, + ); } } @@ -2537,8 +2641,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { ) { if (labelsLength == 1) { final AxisLabel current = visibleLabels[0]; - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); return false; } @@ -2572,8 +2678,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { bool hasCollidingLabels = false; for (int i = startIndex; i < endIndex; i++) { current = visibleLabels[i]; - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); hasCollidingLabels = _isIntersect(current, source); if (hasCollidingLabels) { return true; @@ -2590,8 +2698,10 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { visibleLabels[labelsLength - 1].isVisible = false; // Need to find the endIndex [length - 2] position. Because, the for loop // only run till the previous index of endIndex. - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); } else { // Need to find the endIndex [length - 1] position. Because, the for loop // only run till the previous index of endIndex. @@ -2608,17 +2718,23 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { ) { if (length == 1) { final AxisLabel current = visibleLabels[0]; - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); return; } else if (length <= 2) { // Handles 2 visible labels when set [EdgeLabelPlacement] as hide. AxisLabel current = visibleLabels[0]; - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); current = visibleLabels[1]; - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); return; } late int startIndex; @@ -2629,7 +2745,7 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { AxisLabel source; AxisLabel current = visibleLabels[0]; final AxisLabel Function(AxisLabel, AxisLabel, double, _AlignLabel, {int i}) - applyLabelIntersectAction = _applyLabelIntersectAction(); + applyLabelIntersectAction = _applyLabelIntersectAction(); if (edgeLabelPlacement == EdgeLabelPlacement.hide) { // Start edge label [0] visibility is collapsed. @@ -2643,13 +2759,19 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { // [1] index will overlaps with the [2] label. So taken the [2] as source. source = visibleLabels[startIndex]; source.position = betweenLabelsAlign(pointToPixel(source.value), source); - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); if (effectiveLabelIntersectAction != AxisLabelIntersectAction.hide && effectiveLabelIntersectAction != AxisLabelIntersectAction.multipleRows) { source = applyLabelIntersectAction( - current, source, extent, betweenLabelsAlign); + current, + source, + extent, + betweenLabelsAlign, + ); } else { source = current; } @@ -2665,7 +2787,11 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { effectiveLabelIntersectAction != AxisLabelIntersectAction.multipleRows) { source = applyLabelIntersectAction( - current, source, edgeLabelsExtent, startLabelAlign); + current, + source, + edgeLabelsExtent, + startLabelAlign, + ); } else { source = current; } @@ -2673,32 +2799,51 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { for (int i = startIndex; i < endIndex; i++) { current = visibleLabels[i]; - current.position = - betweenLabelsAlign(pointToPixel(current.value), current); + current.position = betweenLabelsAlign( + pointToPixel(current.value), + current, + ); source = applyLabelIntersectAction( - current, source, extent, betweenLabelsAlign, - i: i); + current, + source, + extent, + betweenLabelsAlign, + i: i, + ); } if (edgeLabelPlacement == EdgeLabelPlacement.hide) { current = visibleLabels[endIndex]; current.position = endLabelAlign(pointToPixel(current.value), current); applyLabelIntersectAction( - current, source, edgeLabelsExtent, endLabelAlign, - i: endIndex); + current, + source, + edgeLabelsExtent, + endLabelAlign, + i: endIndex, + ); visibleLabels[length - 1].isVisible = false; } else { current = visibleLabels[endIndex]; current.position = endLabelAlign(pointToPixel(current.value), current); applyLabelIntersectAction( - current, source, edgeLabelsExtent, endLabelAlign, - i: endIndex); + current, + source, + edgeLabelsExtent, + endLabelAlign, + i: endIndex, + ); } } AxisLabel Function( - AxisLabel source, AxisLabel target, double extent, _AlignLabel align, - {int i}) _applyLabelIntersectAction() { + AxisLabel source, + AxisLabel target, + double extent, + _AlignLabel align, { + int i, + }) + _applyLabelIntersectAction() { switch (effectiveLabelIntersectAction) { case AxisLabelIntersectAction.none: return _applyNoneIntersectAction; @@ -2724,21 +2869,33 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { } AxisLabel _applyNoneIntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { return current; } AxisLabel _applyHideIntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { current.isVisible = !_isIntersect(current, source); return current.isVisible ? current : source; } AxisLabel _applyWrapIntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { final List words = current.renderText.split(RegExp(r'\s+')); final int wrapLength = words.length; final TextStyle textStyle = current.labelStyle; @@ -2774,12 +2931,20 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { } AxisLabel _applyTrimIntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { final TextStyle textStyle = current.labelStyle; if (current.labelSize.width > extent) { - current.renderText = - trimmedText(current.renderText, textStyle, extent, labelRotation); + current.renderText = trimmedText( + current.renderText, + textStyle, + extent, + labelRotation, + ); if (current.renderText != current.text) { current.trimmedText = current.renderText; hasTrimmedAxisLabel = true; @@ -2792,12 +2957,19 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { } AxisLabel _applyMultipleRowsIntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { if (_isIntersect(current, source)) { current - ..labelSize = - measureText(current.renderText, current.labelStyle, labelRotation) + ..labelSize = measureText( + current.renderText, + current.labelStyle, + labelRotation, + ) ..position = align(pointToPixel(current.value), current); _computeRowIndexForMultiRows(i, current); return source; @@ -2813,33 +2985,49 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { final AxisLabel source = visibleLabels[i]; if (_isIntersect(current, source)) { labelIndex.add(source._rowIndex); - current._rowIndex = current._rowIndex > source._rowIndex - ? current._rowIndex - : source._rowIndex + 1; + current._rowIndex = + current._rowIndex > source._rowIndex + ? current._rowIndex + : source._rowIndex + 1; } else { - current._rowIndex = labelIndex.contains(source._rowIndex) - ? current._rowIndex - : source._rowIndex; + current._rowIndex = + labelIndex.contains(source._rowIndex) + ? current._rowIndex + : source._rowIndex; } } } AxisLabel _applyRotate90IntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { current - ..labelSize = - measureText(current.renderText, current.labelStyle, angle90Degree) + ..labelSize = measureText( + current.renderText, + current.labelStyle, + angle90Degree, + ) ..position = align(pointToPixel(current.value), current); return current; } AxisLabel _applyRotate45IntersectAction( - AxisLabel current, AxisLabel source, double extent, _AlignLabel align, - {int i = 0}) { + AxisLabel current, + AxisLabel source, + double extent, + _AlignLabel align, { + int i = 0, + }) { current - ..labelSize = - measureText(current.renderText, current.labelStyle, angle45Degree) + ..labelSize = measureText( + current.renderText, + current.labelStyle, + angle45Degree, + ) ..position = align(pointToPixel(current.value), current); return current; } @@ -3015,12 +3203,14 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { for (int i = 0; i < length; i++) { final PlotBand plotBand = plotBands[i]; if (plotBand.isVisible) { - final num min = plotBand.start != null - ? actualValue(plotBand.start) - : visibleRange!.minimum; - num max = plotBand.end != null - ? actualValue(plotBand.end) - : visibleRange!.maximum; + final num min = + plotBand.start != null + ? actualValue(plotBand.start) + : visibleRange!.minimum; + num max = + plotBand.end != null + ? actualValue(plotBand.end) + : visibleRange!.maximum; num extent; if (plotBand.isRepeatable) { @@ -3040,8 +3230,13 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { num current = min; if (plotBand.isRepeatable) { while (current < max) { - current = - formPlotBandFrame(plotBand, current, extent, max, bounds); + current = formPlotBandFrame( + plotBand, + current, + extent, + max, + bounds, + ); } } else { formPlotBandFrame(plotBand, current, extent, max, bounds); @@ -3051,10 +3246,18 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { } } - num formPlotBandFrame(PlotBand plotBand, num current, num extent, num max, - Rect Function(PlotBand plotBand, num start, num end) bounds) { - num end = plotBandExtent(plotBand, current, - plotBand.isRepeatable ? plotBand.size ?? extent : extent); + num formPlotBandFrame( + PlotBand plotBand, + num current, + num extent, + num max, + Rect Function(PlotBand plotBand, num start, num end) bounds, + ) { + num end = plotBandExtent( + plotBand, + current, + plotBand.isRepeatable ? plotBand.size ?? extent : extent, + ); if (end > max) { end = max; } @@ -3062,17 +3265,22 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { final Rect frame = bounds(plotBand, current, end); addPlotBand(frame, plotBand); } - current = plotBand.size != null - ? plotBandExtent(plotBand, current, - plotBand.isRepeatable ? plotBand.repeatEvery : end) - : end; + current = + plotBand.size != null + ? plotBandExtent( + plotBand, + current, + plotBand.isRepeatable ? plotBand.repeatEvery : end, + ) + : end; return current; } @nonVirtual void addPlotBand(Rect frame, PlotBand plotBand) { - final TextStyle textStyle = - chartThemeData!.plotBandLabelTextStyle!.merge(plotBand.textStyle); + final TextStyle textStyle = chartThemeData!.plotBandLabelTextStyle!.merge( + plotBand.textStyle, + ); final Rect bounds = parent!.paintBounds; final AxisPlotBand plotBandDetails = AxisPlotBand( bounds: frame, @@ -3108,63 +3316,84 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (plotBand.associatedAxisStart != null) { if (associatedAxis is RenderDateTimeCategoryAxis) { final dynamic associateStart = plotBand.associatedAxisStart; - top = associatedAxis!.pointToPixel(associatedAxis!.actualValue( + top = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( associateStart is num ? (associatedAxis! as RenderDateTimeCategoryAxis) .indexToDateTime(associateStart as int) - : associateStart)); + : associateStart, + ), + ); } else if (associatedAxis is RenderCategoryAxis) { final dynamic associateStart = plotBand.associatedAxisStart; - top = associatedAxis!.pointToPixel(associatedAxis!.actualValue( + top = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( associateStart is String - ? (associatedAxis! as RenderCategoryAxis) - .labels - .indexOf(associateStart) - : associateStart)); + ? (associatedAxis! as RenderCategoryAxis).labels.indexOf( + associateStart, + ) + : associateStart, + ), + ); } else { top = associatedAxis!.pointToPixel( - associatedAxis!.actualValue(plotBand.associatedAxisStart!)); + associatedAxis!.actualValue(plotBand.associatedAxisStart!), + ); } } else { if (associatedAxis is RenderLogarithmicAxis) { top = associatedAxis!.pointToPixel( - (associatedAxis! as RenderLogarithmicAxis) - .toPow(associatedAxis!.visibleRange!.minimum)); + (associatedAxis! as RenderLogarithmicAxis).toPow( + associatedAxis!.visibleRange!.minimum, + ), + ); } else { - top = - associatedAxis!.pointToPixel(associatedAxis!.visibleRange!.minimum); + top = associatedAxis!.pointToPixel( + associatedAxis!.visibleRange!.minimum, + ); } } if (plotBand.associatedAxisEnd != null) { if (associatedAxis is RenderDateTimeCategoryAxis) { final dynamic associateEnd = plotBand.associatedAxisEnd; - bottom = associatedAxis!.pointToPixel(associatedAxis!.actualValue( + bottom = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( associateEnd is num ? (associatedAxis! as RenderDateTimeCategoryAxis) .indexToDateTime(associateEnd as int) - : associateEnd)); + : associateEnd, + ), + ); } else if (associatedAxis is RenderCategoryAxis) { final dynamic associateEnd = plotBand.associatedAxisEnd; - final num index = associateEnd is String - ? (associatedAxis! as RenderCategoryAxis) - .labels - .indexOf(associateEnd) - : associateEnd; - bottom = associatedAxis!.pointToPixel(associatedAxis!.actualValue( - index != -1 ? index : associatedAxis!.actualRange!.maximum)); + final num index = + associateEnd is String + ? (associatedAxis! as RenderCategoryAxis).labels.indexOf( + associateEnd, + ) + : associateEnd; + bottom = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( + index != -1 ? index : associatedAxis!.actualRange!.maximum, + ), + ); } else { bottom = associatedAxis!.pointToPixel( - associatedAxis!.actualValue(plotBand.associatedAxisEnd!)); + associatedAxis!.actualValue(plotBand.associatedAxisEnd!), + ); } } else { if (associatedAxis is RenderLogarithmicAxis) { bottom = associatedAxis!.pointToPixel( - (associatedAxis! as RenderLogarithmicAxis) - .toPow(associatedAxis!.visibleRange!.maximum)); + (associatedAxis! as RenderLogarithmicAxis).toPow( + associatedAxis!.visibleRange!.maximum, + ), + ); } else { - bottom = - associatedAxis!.pointToPixel(associatedAxis!.visibleRange!.maximum); + bottom = associatedAxis!.pointToPixel( + associatedAxis!.visibleRange!.maximum, + ); } } @@ -3180,63 +3409,84 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { if (plotBand.associatedAxisStart != null) { if (associatedAxis is RenderDateTimeCategoryAxis) { final dynamic associateStart = plotBand.associatedAxisStart; - left = associatedAxis!.pointToPixel(associatedAxis!.actualValue( + left = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( associateStart is num ? (associatedAxis! as RenderDateTimeCategoryAxis) .indexToDateTime(associateStart as int) - : associateStart)); + : associateStart, + ), + ); } else if (associatedAxis is RenderCategoryAxis) { final dynamic associateStart = plotBand.associatedAxisStart; - left = associatedAxis!.pointToPixel(associatedAxis!.actualValue( + left = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( associateStart is String - ? (associatedAxis! as RenderCategoryAxis) - .labels - .indexOf(associateStart) - : associateStart)); + ? (associatedAxis! as RenderCategoryAxis).labels.indexOf( + associateStart, + ) + : associateStart, + ), + ); } else { left = associatedAxis!.pointToPixel( - associatedAxis!.actualValue(plotBand.associatedAxisStart!)); + associatedAxis!.actualValue(plotBand.associatedAxisStart!), + ); } } else { if (associatedAxis is RenderLogarithmicAxis) { left = associatedAxis!.pointToPixel( - (associatedAxis! as RenderLogarithmicAxis) - .toPow(associatedAxis!.visibleRange!.minimum)); + (associatedAxis! as RenderLogarithmicAxis).toPow( + associatedAxis!.visibleRange!.minimum, + ), + ); } else { - left = - associatedAxis!.pointToPixel(associatedAxis!.visibleRange!.minimum); + left = associatedAxis!.pointToPixel( + associatedAxis!.visibleRange!.minimum, + ); } } if (plotBand.associatedAxisEnd != null) { if (associatedAxis is RenderDateTimeCategoryAxis) { final dynamic associateEnd = plotBand.associatedAxisEnd; - right = associatedAxis!.pointToPixel(associatedAxis!.actualValue( + right = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( associateEnd is num ? (associatedAxis! as RenderDateTimeCategoryAxis) .indexToDateTime(associateEnd as int) - : associateEnd)); + : associateEnd, + ), + ); } else if (associatedAxis is RenderCategoryAxis) { final dynamic associateEnd = plotBand.associatedAxisEnd; - final num index = associateEnd is String - ? (associatedAxis! as RenderCategoryAxis) - .labels - .indexOf(associateEnd) - : associateEnd; - right = associatedAxis!.pointToPixel(associatedAxis!.actualValue( - index != -1 ? index : associatedAxis!.actualRange!.maximum)); + final num index = + associateEnd is String + ? (associatedAxis! as RenderCategoryAxis).labels.indexOf( + associateEnd, + ) + : associateEnd; + right = associatedAxis!.pointToPixel( + associatedAxis!.actualValue( + index != -1 ? index : associatedAxis!.actualRange!.maximum, + ), + ); } else { right = associatedAxis!.pointToPixel( - associatedAxis!.actualValue(plotBand.associatedAxisEnd!)); + associatedAxis!.actualValue(plotBand.associatedAxisEnd!), + ); } } else { if (associatedAxis is RenderLogarithmicAxis) { right = associatedAxis!.pointToPixel( - (associatedAxis! as RenderLogarithmicAxis) - .toPow(associatedAxis!.visibleRange!.maximum)); + (associatedAxis! as RenderLogarithmicAxis).toPow( + associatedAxis!.visibleRange!.maximum, + ), + ); } else { - right = - associatedAxis!.pointToPixel(associatedAxis!.visibleRange!.maximum); + right = associatedAxis!.pointToPixel( + associatedAxis!.visibleRange!.maximum, + ); } } @@ -3320,24 +3570,27 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { for (final AxisLabel label in visibleLabels) { if (label.region != null && label.region!.contains(localPosition)) { if (parent!.onAxisLabelTapped != null) { - final AxisLabelTapArgs args = AxisLabelTapArgs(widget, name) - ..text = label.text - ..value = label.value; + final AxisLabelTapArgs args = + AxisLabelTapArgs(widget, name) + ..text = label.text + ..value = label.value; parent!.onAxisLabelTapped!(args); } if (hasTrimmedAxisLabel && label.trimmedText != null) { final BoxParentData parentData = parent!.parentData! as BoxParentData; final Rect parentBounds = parentData.offset & parent!.size; - parent!.behaviorArea!.showTooltip(TooltipInfo( - primaryPosition: localToGlobal(label.region!.topCenter), - secondaryPosition: localToGlobal(label.region!.bottomCenter), - text: label.text, - surfaceBounds: Rect.fromPoints( - parent!.localToGlobal(parentBounds.topLeft), - parent!.localToGlobal(parentBounds.bottomRight), + parent!.behaviorArea!.showTooltip( + TooltipInfo( + primaryPosition: localToGlobal(label.region!.topCenter), + secondaryPosition: localToGlobal(label.region!.bottomCenter), + text: label.text, + surfaceBounds: Rect.fromPoints( + parent!.localToGlobal(parentBounds.topLeft), + parent!.localToGlobal(parentBounds.bottomRight), + ), ), - )); + ); } break; } @@ -3357,15 +3610,17 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { label.region!.contains(localPosition)) { final BoxParentData parentData = parent!.parentData! as BoxParentData; final Rect parentBounds = parentData.offset & parent!.size; - parent!.behaviorArea!.showTooltip(TooltipInfo( - primaryPosition: localToGlobal(label.region!.topCenter), - secondaryPosition: localToGlobal(label.region!.bottomCenter), - text: label.text, - surfaceBounds: Rect.fromPoints( - parent!.localToGlobal(parentBounds.topLeft), - parent!.localToGlobal(parentBounds.bottomRight), + parent!.behaviorArea!.showTooltip( + TooltipInfo( + primaryPosition: localToGlobal(label.region!.topCenter), + secondaryPosition: localToGlobal(label.region!.bottomCenter), + text: label.text, + surfaceBounds: Rect.fromPoints( + parent!.localToGlobal(parentBounds.topLeft), + parent!.localToGlobal(parentBounds.bottomRight), + ), ), - )); + ); break; } } @@ -3429,10 +3684,7 @@ abstract class RenderChartAxis extends RenderBox with ChartAreaUpdateMixin { } class DoubleRangeTween extends Tween { - DoubleRangeTween({ - super.begin, - super.end, - }); + DoubleRangeTween({super.begin, super.end}); @override DoubleRange? transform(double t) { @@ -3488,7 +3740,9 @@ class DoubleRange { DoubleRange operator +(DoubleRange other) { return DoubleRange( - min(_minimum, other.minimum), max(_maximum, other.maximum)); + min(_minimum, other.minimum), + max(_maximum, other.maximum), + ); } DoubleRange copyWith({num? minimum, num? maximum}) { @@ -3643,8 +3897,9 @@ abstract class _GridLineRenderer { @nonVirtual void onPaint(PaintingContext context, Offset offset) { - final Offset plotAreaGlobalOffset = - axis.parent!.localToGlobal(axis.parent!.plotAreaOffset); + final Offset plotAreaGlobalOffset = axis.parent!.localToGlobal( + axis.parent!.plotAreaOffset, + ); final Offset plotAreaOffset = axis.globalToLocal(plotAreaGlobalOffset); context.canvas.save(); context.canvas.clipRect(axis.parent!.plotAreaBounds); @@ -3668,8 +3923,14 @@ class _HorizontalGridLineRenderer extends _GridLineRenderer { final MajorGridLines majorGridLines = axis.majorGridLines; final Color color = (majorGridLines.color ?? axis.chartThemeData!.majorGridLineColor)!; - _drawGridLines(context, offset, axis.majorTickPositions, color, - majorGridLines.width, majorGridLines.dashArray); + _drawGridLines( + context, + offset, + axis.majorTickPositions, + color, + majorGridLines.width, + majorGridLines.dashArray, + ); } @override @@ -3677,8 +3938,14 @@ class _HorizontalGridLineRenderer extends _GridLineRenderer { final MinorGridLines minorGridLines = axis.minorGridLines; final Color color = (minorGridLines.color ?? axis.chartThemeData!.minorGridLineColor)!; - _drawGridLines(context, offset, axis.minorTickPositions, color, - minorGridLines.width, minorGridLines.dashArray); + _drawGridLines( + context, + offset, + axis.minorTickPositions, + color, + minorGridLines.width, + minorGridLines.dashArray, + ); } void _drawGridLines( @@ -3692,11 +3959,12 @@ class _HorizontalGridLineRenderer extends _GridLineRenderer { if (axis.associatedAxis != null && color != Colors.transparent && width > 0) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = color - ..strokeWidth = width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = color + ..strokeWidth = width + ..style = PaintingStyle.stroke; final RenderChartAxis associatedAxis = axis.associatedAxis!; num minimum = associatedAxis.visibleRange!.minimum; @@ -3735,8 +4003,14 @@ class _VerticalGridLineRenderer extends _GridLineRenderer { final MajorGridLines majorGridLines = axis.majorGridLines; final Color color = (majorGridLines.color ?? axis.chartThemeData!.majorGridLineColor)!; - _drawGridLines(context, offset, axis.majorTickPositions, color, - majorGridLines.width, majorGridLines.dashArray); + _drawGridLines( + context, + offset, + axis.majorTickPositions, + color, + majorGridLines.width, + majorGridLines.dashArray, + ); } @override @@ -3744,8 +4018,14 @@ class _VerticalGridLineRenderer extends _GridLineRenderer { final MinorGridLines minorGridLines = axis.minorGridLines; final Color color = (minorGridLines.color ?? axis.chartThemeData!.minorGridLineColor)!; - _drawGridLines(context, offset, axis.minorTickPositions, color, - minorGridLines.width, minorGridLines.dashArray); + _drawGridLines( + context, + offset, + axis.minorTickPositions, + color, + minorGridLines.width, + minorGridLines.dashArray, + ); } void _drawGridLines( @@ -3759,11 +4039,12 @@ class _VerticalGridLineRenderer extends _GridLineRenderer { if (axis.associatedAxis != null && color != Colors.transparent && width > 0) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = color - ..strokeWidth = width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = color + ..strokeWidth = width + ..style = PaintingStyle.stroke; final RenderChartAxis associatedAxis = axis.associatedAxis!; num minimum = associatedAxis.visibleRange!.minimum; @@ -3846,14 +4127,18 @@ abstract class _PlotBandRenderer { _drawPlotBand(context, offset); } - void _drawPlotBand(PaintingContext context, Offset offset, - {bool shouldRenderAboveSeries = false}) { + void _drawPlotBand( + PaintingContext context, + Offset offset, { + bool shouldRenderAboveSeries = false, + }) { if (axis.visiblePlotBands == null || axis.visiblePlotBands!.isEmpty) { return; } - final Offset plotAreaGlobalOffset = - axis.parent!.localToGlobal(axis.parent!.plotAreaOffset); + final Offset plotAreaGlobalOffset = axis.parent!.localToGlobal( + axis.parent!.plotAreaOffset, + ); final Offset plotAreaOffset = axis.globalToLocal(plotAreaGlobalOffset); offset += plotAreaOffset; context.canvas.save(); @@ -3879,17 +4164,19 @@ abstract class _PlotBandRenderer { if (plotBand.borderWidth > 0 && plotBand.borderColor != Colors.transparent) { paint - ..color = plotBand.opacity < 1.0 - ? plotBand.borderColor.withValues(alpha: plotBand.opacity) - : plotBand.borderColor + ..color = + plotBand.opacity < 1.0 + ? plotBand.borderColor.withValues(alpha: plotBand.opacity) + : plotBand.borderColor ..strokeWidth = plotBand.borderWidth ..style = PaintingStyle.stroke; - final Path path = Path() - ..moveTo(bounds.left, bounds.top) - ..lineTo(bounds.left + bounds.width, bounds.top) - ..lineTo(bounds.left + bounds.width, bounds.top + bounds.height) - ..lineTo(bounds.left, bounds.top + bounds.height) - ..close(); + final Path path = + Path() + ..moveTo(bounds.left, bounds.top) + ..lineTo(bounds.left + bounds.width, bounds.top) + ..lineTo(bounds.left + bounds.width, bounds.top + bounds.height) + ..lineTo(bounds.left, bounds.top + bounds.height) + ..close(); drawDashes(context.canvas, plotBand.dashArray, paint, path: path); } _drawText(context, bounds, plotBand); @@ -3918,8 +4205,12 @@ abstract class _PlotBandRenderer { if (bounds.top > bounds.bottom) { // Top value is always greater than the bottom value. So vertical // alignment is working oppositely, hence swapped the value. - bounds = - Rect.fromLTRB(bounds.left, bounds.bottom, bounds.right, bounds.top); + bounds = Rect.fromLTRB( + bounds.left, + bounds.bottom, + bounds.right, + bounds.top, + ); } switch (plotBand.yAlign) { @@ -3947,7 +4238,8 @@ class _HorizontalPlotBandRenderer extends _PlotBandRenderer { TextStyle style = plotBand.textStyle; if (plotBand.opacity < 1.0) { style = style.copyWith( - color: style.color?.withValues(alpha: plotBand.opacity)); + color: style.color?.withValues(alpha: plotBand.opacity), + ); } final TextSpan span = TextSpan(text: plotBand.text, style: style); _textPainter @@ -3955,8 +4247,11 @@ class _HorizontalPlotBandRenderer extends _PlotBandRenderer { ..textAlign = TextAlign.center ..textDirection = TextDirection.ltr ..layout(); - final Offset position = - _textPosition(plotBand, bounds, _textPainter.size); + final Offset position = _textPosition( + plotBand, + bounds, + _textPainter.size, + ); if (plotBand.textAngle == 0) { _textPainter.paint(context.canvas, position); } else { @@ -3982,7 +4277,8 @@ class _VerticalPlotBandRenderer extends _PlotBandRenderer { TextStyle style = plotBand.textStyle; if (plotBand.opacity < 1.0) { style = style.copyWith( - color: style.color?.withValues(alpha: plotBand.opacity)); + color: style.color?.withValues(alpha: plotBand.opacity), + ); } final TextSpan span = TextSpan(text: plotBand.text, style: style); _textPainter @@ -3990,8 +4286,11 @@ class _VerticalPlotBandRenderer extends _PlotBandRenderer { ..textAlign = TextAlign.center ..textDirection = TextDirection.ltr ..layout(); - final Offset position = - _textPosition(plotBand, bounds, _textPainter.size); + final Offset position = _textPosition( + plotBand, + bounds, + _textPainter.size, + ); if (plotBand.textAngle == 0) { _textPainter.paint(context.canvas, position); } else { @@ -4076,8 +4375,8 @@ abstract class _AxisRenderer { borderSize = axis.borderWidth / 2; titleSize = 0.0; if (axis.title.text != null && axis.title.text!.isNotEmpty) { - final TextStyle textStyle = - axis.chartThemeData!.axisTitleTextStyle!.merge(axis.title.textStyle); + final TextStyle textStyle = axis.chartThemeData!.axisTitleTextStyle! + .merge(axis.title.textStyle); titleSize = measureText(axis.title.text!, textStyle).height; } @@ -4166,6 +4465,14 @@ abstract class _AxisRenderer { double multilevelLabelPadding = 0.0; double titlePadding = 0.0; + // The `labelsExtent` defines the space between the axis line and the title, + // if its value exceeds the maximum size of the label. + final double labelsExtent = axis.labelsExtent ?? 0.0; + double labelsExtentPadding = 0.0; + if (maxLabelSize < labelsExtent) { + labelsExtentPadding = labelsExtent - maxLabelSize; + } + double outerSize = 0.0; // Normal order @@ -4179,25 +4486,31 @@ abstract class _AxisRenderer { majorTickPadding = 0.0; minorTickPadding = 0.0; labelPadding = outerTickSize + outerLabelGap; - multilevelLabelPadding = labelPadding + + multilevelLabelPadding = + labelPadding + outerLabelSize + outerBorderGap + effectiveBorderSize + outerMultilevelLabelGap + effectiveMultilevelBorderSize; - titlePadding = multilevelLabelPadding + + titlePadding = + multilevelLabelPadding + outerMultilevelLabelSize + effectiveMultilevelBorderSize + + labelsExtentPadding + titleGap; _axisBorderSize = multilevelLabelPadding - outerMultilevelLabelGap; outerSize = titlePadding + titleSize; } else { titlePadding = 0.0; multilevelLabelPadding = - titleSize + titleGap + effectiveMultilevelBorderSize; - borderPadding = multilevelLabelPadding + + titleSize + + titleGap + + labelsExtentPadding + + effectiveMultilevelBorderSize; + borderPadding = + multilevelLabelPadding + outerMultilevelLabelSize + - // effectiveMultilevelBorderSize + outerMultilevelLabelGap + effectiveBorderSize; labelPadding = borderPadding + outerBorderGap; @@ -4207,7 +4520,8 @@ abstract class _AxisRenderer { labelPadding + outerLabelSize + outerLabelGap + majorTickAdj; axisLinePadding = labelPadding + outerLabelSize + outerLabelGap + outerTickSize; - _axisBorderSize = effectiveBorderSize + + _axisBorderSize = + effectiveBorderSize + effectiveMultilevelBorderSize + outerBorderGap + outerLabelSize + @@ -4240,7 +4554,8 @@ abstract class _AxisRenderer { } else { labelPadding = outerSize + innerTickSize + innerLabelGap; borderPadding = outerSize; - multilevelLabelPadding = labelPadding + + multilevelLabelPadding = + labelPadding + innerLabelSize + innerBorderGap + innerMultilevelLabelGap; @@ -4312,11 +4627,13 @@ abstract class _AxisRenderer { if (axis.parentData == null) { return; } - final Rect clipRect = axis.tickPosition == TickPosition.inside - ? axis.parent!.plotAreaBounds - : (axis.parentData! as CartesianAxesParentData).offset & axis.size; - final Rect extendedClipRect = clipRect - .inflate(max(axis.majorTickLines.size, axis.minorTickLines.size) / 2); + final Rect clipRect = + axis.tickPosition == TickPosition.inside + ? axis.parent!.plotAreaBounds + : (axis.parentData! as CartesianAxesParentData).offset & axis.size; + final Rect extendedClipRect = clipRect.inflate( + max(axis.majorTickLines.size, axis.minorTickLines.size) / 2, + ); // HACK: If the ouput renders in html web renderer, y axis labels, ticks // and axis line hide. To avoid this y axis hide, we called canvas save // two times. @@ -4444,11 +4761,12 @@ class _HorizontalAxisRenderer extends _AxisRenderer { @override void _drawAxisLine(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (axis.axisLine.color ?? axis.chartThemeData!.axisLineColor)! - ..strokeWidth = axis.axisLine.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = (axis.axisLine.color ?? axis.chartThemeData!.axisLineColor)! + ..strokeWidth = axis.axisLine.width + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { drawDashes( context.canvas, @@ -4462,12 +4780,14 @@ class _HorizontalAxisRenderer extends _AxisRenderer { @override void _drawMajorTicks(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (axis.majorTickLines.color ?? - axis.chartThemeData!.majorTickLineColor)! - ..strokeWidth = axis.majorTickLines.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = + (axis.majorTickLines.color ?? + axis.chartThemeData!.majorTickLineColor)! + ..strokeWidth = axis.majorTickLines.width + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { for (final double position in axis.majorTickPositions) { final Offset start = offset.translate(position, 0.0); @@ -4479,12 +4799,14 @@ class _HorizontalAxisRenderer extends _AxisRenderer { @override void _drawMinorTicks(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (axis.minorTickLines.color ?? - axis.chartThemeData!.minorTickLineColor)! - ..strokeWidth = axis.minorTickLines.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = + (axis.minorTickLines.color ?? + axis.chartThemeData!.minorTickLineColor)! + ..strokeWidth = axis.minorTickLines.width + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { for (final double position in axis.minorTickPositions) { final Offset start = offset.translate(position, 0.0); @@ -4512,7 +4834,8 @@ class _HorizontalAxisRenderer extends _AxisRenderer { final bool isMultipleRows = action == AxisLabelIntersectAction.multipleRows; final bool isOutSide = axis.labelPosition == ChartDataLabelPosition.outside; - final bool normalOrder = (!axis.invertElementsOrder && isOutSide) || + final bool normalOrder = + (!axis.invertElementsOrder && isOutSide) || (axis.invertElementsOrder && !isOutSide); final List axisLabels = axis.visibleLabels; for (final AxisLabel label in axisLabels) { @@ -4533,17 +4856,27 @@ class _HorizontalAxisRenderer extends _AxisRenderer { } Offset position = Offset(labelOffset.dx + label.position!, dy); - label.region = Rect.fromLTWH(position.dx, position.dy, - label.labelSize.width, label.labelSize.height); + label.region = Rect.fromLTWH( + position.dx, + position.dy, + label.labelSize.width, + label.labelSize.height, + ); position += offset; _drawLabel(context, position, label, rotationAngle); } } - void _drawLabel(PaintingContext context, Offset position, AxisLabel label, - int rotationAngle) { - final TextSpan span = - TextSpan(text: label.renderText, style: label.labelStyle); + void _drawLabel( + PaintingContext context, + Offset position, + AxisLabel label, + int rotationAngle, + ) { + final TextSpan span = TextSpan( + text: label.renderText, + style: label.labelStyle, + ); _textPainter ..text = span ..textAlign = TextAlign.center @@ -4554,11 +4887,15 @@ class _HorizontalAxisRenderer extends _AxisRenderer { } else { context.canvas ..save() - ..translate(position.dx + label.labelSize.width / 2, - position.dy + label.labelSize.height / 2) + ..translate( + position.dx + label.labelSize.width / 2, + position.dy + label.labelSize.height / 2, + ) ..rotate(degreeToRadian(rotationAngle)); - _textPainter.paint(context.canvas, - Offset(-_textPainter.size.width / 2, -_textPainter.size.height / 2)); + _textPainter.paint( + context.canvas, + Offset(-_textPainter.size.width / 2, -_textPainter.size.height / 2), + ); context.canvas.restore(); } } @@ -4574,11 +4911,12 @@ class _HorizontalAxisRenderer extends _AxisRenderer { if (effectiveBorderColor != Colors.transparent && axis.borderWidth > 0 && axis.borderPositions.isNotEmpty) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = effectiveBorderColor - ..strokeWidth = axis.borderWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = effectiveBorderColor + ..strokeWidth = axis.borderWidth + ..style = PaintingStyle.stroke; final double axisLeft = axis.paintBounds.left; final double axisRight = axis.paintBounds.right; final List positions = axis.borderPositions; @@ -4609,13 +4947,16 @@ class _HorizontalAxisRenderer extends _AxisRenderer { if (length > 0) { final MultiLevelBorderType borderType = axis.multiLevelLabelStyle.borderType; - final Paint paint = Paint() - ..color = (axis.multiLevelLabelStyle.borderColor ?? - axis.chartThemeData!.axisLineColor)! - ..strokeWidth = axis.multiLevelLabelStyle.borderWidth != 0 - ? axis.multiLevelLabelStyle.borderWidth - : axis.axisLine.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = + (axis.multiLevelLabelStyle.borderColor ?? + axis.chartThemeData!.axisLineColor)! + ..strokeWidth = + axis.multiLevelLabelStyle.borderWidth != 0 + ? axis.multiLevelLabelStyle.borderWidth + : axis.axisLine.width + ..style = PaintingStyle.stroke; double top = offset.dy; int level = _multilevelLabelSizes.keys.first; @@ -4628,31 +4969,40 @@ class _HorizontalAxisRenderer extends _AxisRenderer { } final TextSpan span = TextSpan( - text: label.trimmedText, - style: label.style.copyWith( - color: - label.style.color ?? axis.chartThemeData!.axisLabelColor)); + text: label.trimmedText, + style: label.style.copyWith( + color: label.style.color ?? axis.chartThemeData!.axisLabelColor, + ), + ); _textPainter ..text = span ..textAlign = TextAlign.center ..textDirection = TextDirection.ltr ..layout(); - final Rect bounds = Rect.fromLTWH(offset.dx + label.region.left, - top + label.region.top, label.region.width, height); + final Rect bounds = Rect.fromLTWH( + offset.dx + label.region.left, + top + label.region.top, + label.region.width, + height, + ); _multilevelLabelBorderShape.onPaint( - context, borderType, bounds, _textPainter, paint, axis); + context, + borderType, + bounds, + _textPainter, + paint, + axis, + ); } } } @override void _drawTitle(PaintingContext context, Offset offset) { - final TextStyle textStyle = - axis.chartThemeData!.axisTitleTextStyle!.merge(axis.title.textStyle); - final TextSpan span = TextSpan( - text: axis.title.text, - style: textStyle, + final TextStyle textStyle = axis.chartThemeData!.axisTitleTextStyle!.merge( + axis.title.textStyle, ); + final TextSpan span = TextSpan(text: axis.title.text, style: textStyle); _textPainter ..text = span ..textAlign = TextAlign.center @@ -4729,11 +5079,12 @@ class _VerticalAxisRenderer extends _AxisRenderer { @override void _drawAxisLine(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (axis.axisLine.color ?? axis.chartThemeData!.axisLineColor)! - ..strokeWidth = axis.axisLine.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = (axis.axisLine.color ?? axis.chartThemeData!.axisLineColor)! + ..strokeWidth = axis.axisLine.width + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { drawDashes( context.canvas, @@ -4747,12 +5098,14 @@ class _VerticalAxisRenderer extends _AxisRenderer { @override void _drawMajorTicks(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (axis.majorTickLines.color ?? - axis.chartThemeData!.majorTickLineColor)! - ..strokeWidth = axis.majorTickLines.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = + (axis.majorTickLines.color ?? + axis.chartThemeData!.majorTickLineColor)! + ..strokeWidth = axis.majorTickLines.width + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { for (final double position in axis.majorTickPositions) { final Offset start = offset.translate(0.0, position); @@ -4764,12 +5117,14 @@ class _VerticalAxisRenderer extends _AxisRenderer { @override void _drawMinorTicks(PaintingContext context, Offset offset) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (axis.minorTickLines.color ?? - axis.chartThemeData!.minorTickLineColor)! - ..strokeWidth = axis.minorTickLines.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = + (axis.minorTickLines.color ?? + axis.chartThemeData!.minorTickLineColor)! + ..strokeWidth = axis.minorTickLines.width + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { for (final double position in axis.minorTickPositions) { final Offset start = offset.translate(0.0, position); @@ -4809,17 +5164,27 @@ class _VerticalAxisRenderer extends _AxisRenderer { } Offset position = Offset(dx, labelOffset.dy + label.position!); - label.region = Rect.fromLTWH(position.dx, position.dy, - label.labelSize.width, label.labelSize.height); + label.region = Rect.fromLTWH( + position.dx, + position.dy, + label.labelSize.width, + label.labelSize.height, + ); position += offset; _drawLabel(context, position, label, rotationAngle); } } - void _drawLabel(PaintingContext context, Offset position, AxisLabel label, - int rotationAngle) { - final TextSpan span = - TextSpan(text: label.renderText, style: label.labelStyle); + void _drawLabel( + PaintingContext context, + Offset position, + AxisLabel label, + int rotationAngle, + ) { + final TextSpan span = TextSpan( + text: label.renderText, + style: label.labelStyle, + ); _textPainter ..text = span ..textAlign = TextAlign.center @@ -4830,11 +5195,15 @@ class _VerticalAxisRenderer extends _AxisRenderer { } else { context.canvas ..save() - ..translate(position.dx + label.labelSize.width / 2, - position.dy + label.labelSize.height / 2) + ..translate( + position.dx + label.labelSize.width / 2, + position.dy + label.labelSize.height / 2, + ) ..rotate(degreeToRadian(rotationAngle)); - _textPainter.paint(context.canvas, - Offset(-_textPainter.size.width / 2, -_textPainter.size.height / 2)); + _textPainter.paint( + context.canvas, + Offset(-_textPainter.size.width / 2, -_textPainter.size.height / 2), + ); context.canvas.restore(); } } @@ -4850,11 +5219,12 @@ class _VerticalAxisRenderer extends _AxisRenderer { if (effectiveBorderColor != Colors.transparent && axis.borderWidth > 0 && axis.borderPositions.isNotEmpty) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = effectiveBorderColor - ..strokeWidth = axis.borderWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = effectiveBorderColor + ..strokeWidth = axis.borderWidth + ..style = PaintingStyle.stroke; final double axisTop = axis.paintBounds.top; final double axisBottom = axis.paintBounds.bottom; final List positions = axis.borderPositions; @@ -4885,13 +5255,16 @@ class _VerticalAxisRenderer extends _AxisRenderer { if (length > 0) { final MultiLevelBorderType borderType = axis.multiLevelLabelStyle.borderType; - final Paint paint = Paint() - ..color = (axis.multiLevelLabelStyle.borderColor ?? - axis.chartThemeData!.axisLineColor)! - ..strokeWidth = axis.multiLevelLabelStyle.borderWidth != 0 - ? axis.multiLevelLabelStyle.borderWidth - : axis.axisLine.width - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = + (axis.multiLevelLabelStyle.borderColor ?? + axis.chartThemeData!.axisLineColor)! + ..strokeWidth = + axis.multiLevelLabelStyle.borderWidth != 0 + ? axis.multiLevelLabelStyle.borderWidth + : axis.axisLine.width + ..style = PaintingStyle.stroke; double left = offset.dx; int level = _multilevelLabelSizes.keys.first; @@ -4904,19 +5277,30 @@ class _VerticalAxisRenderer extends _AxisRenderer { } final TextSpan span = TextSpan( - text: label.trimmedText, - style: label.style.copyWith( - color: - label.style.color ?? axis.chartThemeData!.axisLabelColor)); + text: label.trimmedText, + style: label.style.copyWith( + color: label.style.color ?? axis.chartThemeData!.axisLabelColor, + ), + ); _textPainter ..text = span ..textAlign = TextAlign.center ..textDirection = TextDirection.ltr ..layout(); - final Rect bounds = Rect.fromLTWH(left + label.region.left, - offset.dy + label.region.top, width, label.region.height); + final Rect bounds = Rect.fromLTWH( + left + label.region.left, + offset.dy + label.region.top, + width, + label.region.height, + ); _multilevelLabelBorderShape.onPaint( - context, borderType, bounds, _textPainter, paint, axis); + context, + borderType, + bounds, + _textPainter, + paint, + axis, + ); } } } @@ -4924,8 +5308,9 @@ class _VerticalAxisRenderer extends _AxisRenderer { @override void _drawTitle(PaintingContext context, Offset offset) { final int rotationAngle = axis.invertElementsOrder ? 270 : 90; - final TextStyle textStyle = - axis.chartThemeData!.axisTitleTextStyle!.merge(axis.title.textStyle); + final TextStyle textStyle = axis.chartThemeData!.axisTitleTextStyle!.merge( + axis.title.textStyle, + ); final TextSpan span = TextSpan(text: axis.title.text, style: textStyle); _textPainter ..text = span @@ -4947,7 +5332,8 @@ class _VerticalAxisRenderer extends _AxisRenderer { } break; case ChartAlignment.center: - y = offset.dy + + y = + offset.dy + axis.size.height / 2 + (_textPainter.width / 2 * (axis.invertElementsOrder ? 1 : -1)); break; @@ -4994,9 +5380,10 @@ abstract class _MultilevelLabelBorderShape { if (axis.parentData == null) { return; } - final Rect clipRect = axis.labelPosition == ChartDataLabelPosition.inside - ? axis.parent!.plotAreaBounds - : (axis.parentData! as CartesianAxesParentData).offset & axis.size; + final Rect clipRect = + axis.labelPosition == ChartDataLabelPosition.inside + ? axis.parent!.plotAreaBounds + : (axis.parentData! as CartesianAxesParentData).offset & axis.size; final Rect extendedClipRect = clipRect.inflate(borderPaint.strokeWidth / 2); context.canvas.save(); context.canvas.clipRect(extendedClipRect); @@ -5010,52 +5397,94 @@ abstract class _MultilevelLabelBorderShape { break; case MultiLevelBorderType.withoutTopAndBottom: _drawBorderWithoutTopAndBottom( - context, bounds, labelPainter, borderPaint); + context, + bounds, + labelPainter, + borderPaint, + ); break; case MultiLevelBorderType.squareBrace: _drawSquareBraceBorder( - context, bounds, labelPainter, borderPaint, invertElementsOrder); + context, + bounds, + labelPainter, + borderPaint, + invertElementsOrder, + ); break; case MultiLevelBorderType.curlyBrace: _drawCurlyBraceBorder( - context, bounds, labelPainter, borderPaint, invertElementsOrder); + context, + bounds, + labelPainter, + borderPaint, + invertElementsOrder, + ); break; } context.canvas.restore(); } - void _drawRectangleBorder(PaintingContext context, Rect bounds, - TextPainter labelPainter, Paint paint) { + void _drawRectangleBorder( + PaintingContext context, + Rect bounds, + TextPainter labelPainter, + Paint paint, + ) { context.canvas.drawRect(bounds, paint); _drawLabelAtRectangleBorderCenter(context, labelPainter, bounds); } void _drawLabelAtRectangleBorderCenter( - PaintingContext context, TextPainter labelPainter, Rect bounds) { + PaintingContext context, + TextPainter labelPainter, + Rect bounds, + ) { labelPainter.paint( - context.canvas, - bounds.center.translate( - -labelPainter.size.width / 2, -labelPainter.size.height / 2)); + context.canvas, + bounds.center.translate( + -labelPainter.size.width / 2, + -labelPainter.size.height / 2, + ), + ); } @protected - void _drawBorderWithoutTopAndBottom(PaintingContext context, Rect bounds, - TextPainter labelPainter, Paint paint); + void _drawBorderWithoutTopAndBottom( + PaintingContext context, + Rect bounds, + TextPainter labelPainter, + Paint paint, + ); @protected - void _drawSquareBraceBorder(PaintingContext context, Rect bounds, - TextPainter labelPainter, Paint paint, bool isOpposed); + void _drawSquareBraceBorder( + PaintingContext context, + Rect bounds, + TextPainter labelPainter, + Paint paint, + bool isOpposed, + ); @protected - void _drawCurlyBraceBorder(PaintingContext context, Rect bounds, - TextPainter labelPainter, Paint paint, bool isOpposed); + void _drawCurlyBraceBorder( + PaintingContext context, + Rect bounds, + TextPainter labelPainter, + Paint paint, + bool isOpposed, + ); } class _HorizontalMultilevelLabelBorderShape extends _MultilevelLabelBorderShape { @override - void _drawBorderWithoutTopAndBottom(PaintingContext context, Rect bounds, - TextPainter labelPainter, Paint paint) { + void _drawBorderWithoutTopAndBottom( + PaintingContext context, + Rect bounds, + TextPainter labelPainter, + Paint paint, + ) { context.canvas ..drawLine(bounds.topLeft, bounds.bottomLeft, paint) ..drawLine(bounds.topRight, bounds.bottomRight, paint); @@ -5070,10 +5499,14 @@ class _HorizontalMultilevelLabelBorderShape Paint paint, bool isOpposed, ) { - final Offset labelOffset = bounds.center - .translate(-labelPainter.size.width / 2, -labelPainter.size.height / 2); - Offset labelStart = - labelOffset.translate(0.0, labelPainter.size.height / 2); + final Offset labelOffset = bounds.center.translate( + -labelPainter.size.width / 2, + -labelPainter.size.height / 2, + ); + Offset labelStart = labelOffset.translate( + 0.0, + labelPainter.size.height / 2, + ); Offset labelEnd = labelStart.translate(labelPainter.size.width, 0.0); Offset topLeft = bounds.topLeft; @@ -5115,8 +5548,12 @@ class _HorizontalMultilevelLabelBorderShape } } - void _drawNormalCurlyBraceBorder(Rect bounds, PaintingContext context, - TextPainter labelPainter, Paint paint) { + void _drawNormalCurlyBraceBorder( + Rect bounds, + PaintingContext context, + TextPainter labelPainter, + Paint paint, + ) { final Path path = Path(); double left = bounds.left; double right = bounds.right; @@ -5127,54 +5564,78 @@ class _HorizontalMultilevelLabelBorderShape } final Rect startCurveRegion = Rect.fromLTWH( - left, bounds.top, _curveBraceCurveSize, _curveBraceCurveSize); + left, + bounds.top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); final Rect centerStartCurveRegion = Rect.fromLTWH( - bounds.center.dx - _curveBraceCurveSize, - startCurveRegion.bottom, - _curveBraceCurveSize, - _curveBraceCurveSize); + bounds.center.dx - _curveBraceCurveSize, + startCurveRegion.bottom, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..moveTo(startCurveRegion.left, startCurveRegion.top) ..quadraticBezierTo( - startCurveRegion.bottomLeft.dx, - startCurveRegion.bottomLeft.dy, - startCurveRegion.bottomRight.dx, - startCurveRegion.bottomRight.dy) + startCurveRegion.bottomLeft.dx, + startCurveRegion.bottomLeft.dy, + startCurveRegion.bottomRight.dx, + startCurveRegion.bottomRight.dy, + ) ..lineTo(centerStartCurveRegion.left, centerStartCurveRegion.top) ..quadraticBezierTo( - centerStartCurveRegion.topRight.dx, - centerStartCurveRegion.topRight.dy, - centerStartCurveRegion.bottomRight.dx, - centerStartCurveRegion.bottomRight.dy); + centerStartCurveRegion.topRight.dx, + centerStartCurveRegion.topRight.dy, + centerStartCurveRegion.bottomRight.dx, + centerStartCurveRegion.bottomRight.dy, + ); - final Rect centerEndCurveRegion = Rect.fromLTWH(bounds.center.dx, - centerStartCurveRegion.top, _curveBraceCurveSize, _curveBraceCurveSize); - final Rect endCurveRegion = Rect.fromLTWH(right - _curveBraceCurveSize, - startCurveRegion.top, _curveBraceCurveSize, _curveBraceCurveSize); + final Rect centerEndCurveRegion = Rect.fromLTWH( + bounds.center.dx, + centerStartCurveRegion.top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); + final Rect endCurveRegion = Rect.fromLTWH( + right - _curveBraceCurveSize, + startCurveRegion.top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..quadraticBezierTo( - centerEndCurveRegion.topLeft.dx, - centerEndCurveRegion.topLeft.dy, - centerEndCurveRegion.topRight.dx, - centerEndCurveRegion.topRight.dy) + centerEndCurveRegion.topLeft.dx, + centerEndCurveRegion.topLeft.dy, + centerEndCurveRegion.topRight.dx, + centerEndCurveRegion.topRight.dy, + ) ..lineTo(endCurveRegion.left, endCurveRegion.bottom) ..quadraticBezierTo( - endCurveRegion.bottomRight.dx, - endCurveRegion.bottomRight.dy, - endCurveRegion.topRight.dx, - endCurveRegion.topRight.dy); + endCurveRegion.bottomRight.dx, + endCurveRegion.bottomRight.dy, + endCurveRegion.topRight.dx, + endCurveRegion.topRight.dy, + ); context.canvas.drawPath(path, paint); // TODO(VijayakumarM): Add label padding. labelPainter.paint( - context.canvas, - Offset(bounds.center.dx - labelPainter.size.width / 2, - bounds.top + 2 * _curveBraceCurveSize)); + context.canvas, + Offset( + bounds.center.dx - labelPainter.size.width / 2, + bounds.top + 2 * _curveBraceCurveSize, + ), + ); } - void _drawOpposedCurlyBraceBorder(Rect bounds, PaintingContext context, - TextPainter labelPainter, Paint paint) { + void _drawOpposedCurlyBraceBorder( + Rect bounds, + PaintingContext context, + TextPainter labelPainter, + Paint paint, + ) { final Path path = Path(); double left = bounds.left; double right = bounds.right; @@ -5185,58 +5646,78 @@ class _HorizontalMultilevelLabelBorderShape } final Rect startCurveRegion = Rect.fromLTWH( - left, - bounds.bottom - _curveBraceCurveSize, - _curveBraceCurveSize, - _curveBraceCurveSize); + left, + bounds.bottom - _curveBraceCurveSize, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); final Rect centerStartCurveRegion = Rect.fromLTWH( - bounds.center.dx - _curveBraceCurveSize, - startCurveRegion.top - _curveBraceCurveSize, - _curveBraceCurveSize, - _curveBraceCurveSize); + bounds.center.dx - _curveBraceCurveSize, + startCurveRegion.top - _curveBraceCurveSize, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..moveTo(startCurveRegion.left, startCurveRegion.bottom) ..quadraticBezierTo( - startCurveRegion.topLeft.dx, - startCurveRegion.topLeft.dy, - startCurveRegion.topRight.dx, - startCurveRegion.topRight.dy) + startCurveRegion.topLeft.dx, + startCurveRegion.topLeft.dy, + startCurveRegion.topRight.dx, + startCurveRegion.topRight.dy, + ) ..lineTo(centerStartCurveRegion.left, centerStartCurveRegion.bottom) ..quadraticBezierTo( - centerStartCurveRegion.bottomRight.dx, - centerStartCurveRegion.bottomRight.dy, - centerStartCurveRegion.topRight.dx, - centerStartCurveRegion.topRight.dy); + centerStartCurveRegion.bottomRight.dx, + centerStartCurveRegion.bottomRight.dy, + centerStartCurveRegion.topRight.dx, + centerStartCurveRegion.topRight.dy, + ); - final Rect centerEndCurveRegion = Rect.fromLTWH(bounds.center.dx, - centerStartCurveRegion.top, _curveBraceCurveSize, _curveBraceCurveSize); - final Rect endCurveRegion = Rect.fromLTWH(right - _curveBraceCurveSize, - startCurveRegion.top, _curveBraceCurveSize, _curveBraceCurveSize); + final Rect centerEndCurveRegion = Rect.fromLTWH( + bounds.center.dx, + centerStartCurveRegion.top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); + final Rect endCurveRegion = Rect.fromLTWH( + right - _curveBraceCurveSize, + startCurveRegion.top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..quadraticBezierTo( - centerEndCurveRegion.bottomLeft.dx, - centerEndCurveRegion.bottomLeft.dy, - centerEndCurveRegion.bottomRight.dx, - centerEndCurveRegion.bottomRight.dy) + centerEndCurveRegion.bottomLeft.dx, + centerEndCurveRegion.bottomLeft.dy, + centerEndCurveRegion.bottomRight.dx, + centerEndCurveRegion.bottomRight.dy, + ) ..lineTo(endCurveRegion.left, endCurveRegion.top) ..quadraticBezierTo( - endCurveRegion.topRight.dx, - endCurveRegion.topRight.dy, - endCurveRegion.bottomRight.dx, - endCurveRegion.bottomRight.dy); + endCurveRegion.topRight.dx, + endCurveRegion.topRight.dy, + endCurveRegion.bottomRight.dx, + endCurveRegion.bottomRight.dy, + ); context.canvas.drawPath(path, paint); // TODO(VijayakumarM): Add label padding. - labelPainter.paint(context.canvas, - Offset(bounds.center.dx - labelPainter.size.width / 2, bounds.top)); + labelPainter.paint( + context.canvas, + Offset(bounds.center.dx - labelPainter.size.width / 2, bounds.top), + ); } } class _VerticalMultilevelLabelBorderShape extends _MultilevelLabelBorderShape { @override - void _drawBorderWithoutTopAndBottom(PaintingContext context, Rect bounds, - TextPainter labelPainter, Paint paint) { + void _drawBorderWithoutTopAndBottom( + PaintingContext context, + Rect bounds, + TextPainter labelPainter, + Paint paint, + ) { context.canvas ..drawLine(bounds.topLeft, bounds.topRight, paint) ..drawLine(bounds.bottomLeft, bounds.bottomRight, paint); @@ -5254,11 +5735,15 @@ class _VerticalMultilevelLabelBorderShape extends _MultilevelLabelBorderShape { Offset topLeft = bounds.topLeft; Offset bottomLeft = bounds.bottomLeft; - final Offset labelOffset = bounds.center - .translate(-labelPainter.size.width / 2, -labelPainter.size.height / 2); + final Offset labelOffset = bounds.center.translate( + -labelPainter.size.width / 2, + -labelPainter.size.height / 2, + ); final double halfLabelWidth = labelPainter.size.width / 2; - Offset labelStart = - labelOffset.translate(halfLabelWidth, labelPainter.size.height); + Offset labelStart = labelOffset.translate( + halfLabelWidth, + labelPainter.size.height, + ); Offset labelEnd = labelOffset.translate(halfLabelWidth, 0.0); // Handling axis inversed. @@ -5298,8 +5783,12 @@ class _VerticalMultilevelLabelBorderShape extends _MultilevelLabelBorderShape { } } - void _drawNormalCurlyBraceBorder(Rect bounds, PaintingContext context, - TextPainter labelPainter, Paint paint) { + void _drawNormalCurlyBraceBorder( + Rect bounds, + PaintingContext context, + TextPainter labelPainter, + Paint paint, + ) { final Path path = Path(); double top = bounds.top; double bottom = bounds.bottom; @@ -5311,57 +5800,78 @@ class _VerticalMultilevelLabelBorderShape extends _MultilevelLabelBorderShape { } final Rect startCurveRegion = Rect.fromLTWH( - bounds.left, top, _curveBraceCurveSize, _curveBraceCurveSize); + bounds.left, + top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); final Rect centerStartCurveRegion = Rect.fromLTWH( - startCurveRegion.left + _curveBraceCurveSize, - bounds.center.dy - _curveBraceCurveSize, - _curveBraceCurveSize, - _curveBraceCurveSize); + startCurveRegion.left + _curveBraceCurveSize, + bounds.center.dy - _curveBraceCurveSize, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..moveTo(startCurveRegion.left, startCurveRegion.top) ..quadraticBezierTo( - startCurveRegion.topRight.dx, - startCurveRegion.topRight.dy, - startCurveRegion.bottomRight.dx, - startCurveRegion.bottomRight.dy) + startCurveRegion.topRight.dx, + startCurveRegion.topRight.dy, + startCurveRegion.bottomRight.dx, + startCurveRegion.bottomRight.dy, + ) ..lineTo(centerStartCurveRegion.left, centerStartCurveRegion.top) ..quadraticBezierTo( - centerStartCurveRegion.bottomLeft.dx, - centerStartCurveRegion.bottomLeft.dy, - centerStartCurveRegion.bottomRight.dx, - centerStartCurveRegion.bottomRight.dy); + centerStartCurveRegion.bottomLeft.dx, + centerStartCurveRegion.bottomLeft.dy, + centerStartCurveRegion.bottomRight.dx, + centerStartCurveRegion.bottomRight.dy, + ); - final Rect centerEndCurveRegion = Rect.fromLTWH(centerStartCurveRegion.left, - bounds.center.dy, _curveBraceCurveSize, _curveBraceCurveSize); + final Rect centerEndCurveRegion = Rect.fromLTWH( + centerStartCurveRegion.left, + bounds.center.dy, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); final Rect endCurveRegion = Rect.fromLTWH( - startCurveRegion.left, - bottom - _curveBraceCurveSize, - _curveBraceCurveSize, - _curveBraceCurveSize); + startCurveRegion.left, + bottom - _curveBraceCurveSize, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..quadraticBezierTo( - centerEndCurveRegion.topLeft.dx, - centerEndCurveRegion.topLeft.dy, - centerEndCurveRegion.bottomLeft.dx, - centerEndCurveRegion.bottomLeft.dy) + centerEndCurveRegion.topLeft.dx, + centerEndCurveRegion.topLeft.dy, + centerEndCurveRegion.bottomLeft.dx, + centerEndCurveRegion.bottomLeft.dy, + ) ..lineTo(endCurveRegion.right, endCurveRegion.top) ..quadraticBezierTo( - endCurveRegion.bottomRight.dx, - endCurveRegion.bottomRight.dy, - endCurveRegion.bottomLeft.dx, - endCurveRegion.bottomLeft.dy); + endCurveRegion.bottomRight.dx, + endCurveRegion.bottomRight.dy, + endCurveRegion.bottomLeft.dx, + endCurveRegion.bottomLeft.dy, + ); context.canvas.drawPath(path, paint); // TODO(VijayakumarM): Add label padding. labelPainter.paint( - context.canvas, - Offset(bounds.left + 2 * _curveBraceCurveSize, - bounds.center.dy - labelPainter.size.height / 2)); + context.canvas, + Offset( + bounds.left + 2 * _curveBraceCurveSize, + bounds.center.dy - labelPainter.size.height / 2, + ), + ); } - void _drawOpposedCurlyBraceBorder(Rect bounds, PaintingContext context, - TextPainter labelPainter, Paint paint) { + void _drawOpposedCurlyBraceBorder( + Rect bounds, + PaintingContext context, + TextPainter labelPainter, + Paint paint, + ) { final Path path = Path(); double top = bounds.top; double bottom = bounds.bottom; @@ -5373,54 +5883,67 @@ class _VerticalMultilevelLabelBorderShape extends _MultilevelLabelBorderShape { } final Rect startCurveRegion = Rect.fromLTWH( - bounds.right - _curveBraceCurveSize, - top, - _curveBraceCurveSize, - _curveBraceCurveSize); + bounds.right - _curveBraceCurveSize, + top, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); final Rect centerStartCurveRegion = Rect.fromLTWH( - startCurveRegion.left - _curveBraceCurveSize, - bounds.center.dy - _curveBraceCurveSize, - _curveBraceCurveSize, - _curveBraceCurveSize); + startCurveRegion.left - _curveBraceCurveSize, + bounds.center.dy - _curveBraceCurveSize, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..moveTo(startCurveRegion.right, startCurveRegion.top) ..quadraticBezierTo( - startCurveRegion.topLeft.dx, - startCurveRegion.topLeft.dy, - startCurveRegion.bottomLeft.dx, - startCurveRegion.bottomLeft.dy) + startCurveRegion.topLeft.dx, + startCurveRegion.topLeft.dy, + startCurveRegion.bottomLeft.dx, + startCurveRegion.bottomLeft.dy, + ) ..lineTo(centerStartCurveRegion.right, centerStartCurveRegion.top) ..quadraticBezierTo( - centerStartCurveRegion.bottomRight.dx, - centerStartCurveRegion.bottomRight.dy, - centerStartCurveRegion.bottomLeft.dx, - centerStartCurveRegion.bottomLeft.dy); + centerStartCurveRegion.bottomRight.dx, + centerStartCurveRegion.bottomRight.dy, + centerStartCurveRegion.bottomLeft.dx, + centerStartCurveRegion.bottomLeft.dy, + ); - final Rect centerEndCurveRegion = Rect.fromLTWH(centerStartCurveRegion.left, - bounds.center.dy, _curveBraceCurveSize, _curveBraceCurveSize); + final Rect centerEndCurveRegion = Rect.fromLTWH( + centerStartCurveRegion.left, + bounds.center.dy, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); final Rect endCurveRegion = Rect.fromLTWH( - startCurveRegion.left, - bottom - _curveBraceCurveSize, - _curveBraceCurveSize, - _curveBraceCurveSize); + startCurveRegion.left, + bottom - _curveBraceCurveSize, + _curveBraceCurveSize, + _curveBraceCurveSize, + ); path ..quadraticBezierTo( - centerEndCurveRegion.topRight.dx, - centerEndCurveRegion.topRight.dy, - centerEndCurveRegion.bottomRight.dx, - centerEndCurveRegion.bottomRight.dy) + centerEndCurveRegion.topRight.dx, + centerEndCurveRegion.topRight.dy, + centerEndCurveRegion.bottomRight.dx, + centerEndCurveRegion.bottomRight.dy, + ) ..lineTo(endCurveRegion.left, endCurveRegion.top) ..quadraticBezierTo( - endCurveRegion.bottomLeft.dx, - endCurveRegion.bottomLeft.dy, - endCurveRegion.bottomRight.dx, - endCurveRegion.bottomRight.dy); + endCurveRegion.bottomLeft.dx, + endCurveRegion.bottomLeft.dy, + endCurveRegion.bottomRight.dx, + endCurveRegion.bottomRight.dy, + ); context.canvas.drawPath(path, paint); // TODO(VijayakumarM): Add label padding. - labelPainter.paint(context.canvas, - Offset(bounds.left, bounds.center.dy - labelPainter.size.height / 2)); + labelPainter.paint( + context.canvas, + Offset(bounds.left, bounds.center.dy - labelPainter.size.height / 2), + ); } } @@ -5519,11 +6042,7 @@ class AxisLabel { /// the appearance. class MajorTickLines { /// Creating an argument constructor of [MajorTickLines] class. - const MajorTickLines({ - this.size = 5, - this.width = 1, - this.color, - }); + const MajorTickLines({this.size = 5, this.width = 1, this.color}); /// Size of the major tick lines. /// @@ -5594,11 +6113,7 @@ class MajorTickLines { @immutable class MinorTickLines { /// Creating an argument constructor of MinorTickLines class. - const MinorTickLines({ - this.size = 3, - this.width = 0.7, - this.color, - }); + const MinorTickLines({this.size = 3, this.width = 0.7, this.color}); /// Height of the minor tick lines. /// @@ -5696,11 +6211,7 @@ class MinorTickLines { @immutable class MajorGridLines { /// Creating an argument constructor of MajorGridLines class. - const MajorGridLines({ - this.width = 0.7, - this.color, - this.dashArray, - }); + const MajorGridLines({this.width = 0.7, this.color, this.dashArray}); /// Any number of values can be provided in the list. Odd value is considered /// as rendering size and even value is considered as a gap. @@ -5790,11 +6301,7 @@ class MajorGridLines { /// to customize the appearance. class MinorGridLines { /// Creating an argument constructor of MinorGridLines class. - const MinorGridLines({ - this.width = 0.5, - this.color, - this.dashArray, - }); + const MinorGridLines({this.width = 0.5, this.color, this.dashArray}); /// Any number of values can be provided in the list. Odd value is considered /// as rendering size and even value is considered as a gap. @@ -5867,11 +6374,7 @@ class MinorGridLines { /// appearance of the axis line. class AxisLine { /// Creating an argument constructor of AxisLine class. - const AxisLine({ - this.color, - this.dashArray, - this.width = 1, - }); + const AxisLine({this.color, this.dashArray, this.width = 1}); /// Width of the axis line. /// @@ -6037,9 +6540,10 @@ abstract class ChartAxisController { double get previousZoomPosition => _previousZoomPosition; double _previousZoomPosition = 0.0; - double get zoomFactor => _zoomFactorTween != null && axis._animation != null - ? _zoomFactorTween!.evaluate(axis._animation!) - : _zoomFactor; + double get zoomFactor => + _zoomFactorTween != null && axis._animation != null + ? _zoomFactorTween!.evaluate(axis._animation!) + : _zoomFactor; double _zoomFactor = 1.0; set zoomFactor(double value) { _zoomFactor = value; @@ -6306,7 +6810,8 @@ class DateTimeAxisController extends ChartAxisController { return _visibleMinimum; } return DateTime.fromMillisecondsSinceEpoch( - axis.visibleRange!.minimum.toInt()); + axis.visibleRange!.minimum.toInt(), + ); } DateTime? _visibleMax() { @@ -6314,7 +6819,8 @@ class DateTimeAxisController extends ChartAxisController { return _visibleMaximum; } return DateTime.fromMillisecondsSinceEpoch( - axis.visibleRange!.maximum.toInt()); + axis.visibleRange!.maximum.toInt(), + ); } } @@ -6341,7 +6847,9 @@ class DateTimeCategoryAxisController extends ChartAxisController { _updateMinMaxIfNeeded(); _isVisibleMinChanged = true; _updateZoomFactorAndPosition( - _visibleMinimumIndex, _visibleMaximumIndex); + _visibleMinimumIndex, + _visibleMaximumIndex, + ); } } } @@ -6355,7 +6863,9 @@ class DateTimeCategoryAxisController extends ChartAxisController { _updateMinMaxIfNeeded(); _isVisibleMaxChanged = true; _updateZoomFactorAndPosition( - _visibleMinimumIndex, _visibleMaximumIndex); + _visibleMinimumIndex, + _visibleMaximumIndex, + ); } } } @@ -6370,8 +6880,10 @@ class DateTimeCategoryAxisController extends ChartAxisController { _visibleMaximumIndex == null && _dateAxis.labels.isNotEmpty) { _visibleMinimumIndex = _dateAxis.effectiveValue(_visibleMinimum); - _visibleMaximumIndex = - _dateAxis.effectiveValue(_visibleMaximum, needMin: false); + _visibleMaximumIndex = _dateAxis.effectiveValue( + _visibleMaximum, + needMin: false, + ); if (axis.labelPlacement == LabelPlacement.betweenTicks) { if (_visibleMinimumIndex != null) { _visibleMinimumIndex = _visibleMinimumIndex! - 0.5; @@ -6383,7 +6895,9 @@ class DateTimeCategoryAxisController extends ChartAxisController { _updateMinMaxIfNeeded(); if (_visibleMaximumIndex != null && _visibleMinimumIndex != null) { _updateZoomFactorAndPosition( - _visibleMinimumIndex, _visibleMaximumIndex); + _visibleMinimumIndex, + _visibleMaximumIndex, + ); } } _onUpdateInitialZoomFactorAndPosition?.call(); @@ -6400,8 +6914,10 @@ class DateTimeCategoryAxisController extends ChartAxisController { _visibleMaximumIndex = null; if (_visibleMaximum != null) { - _visibleMaximumIndex = - _dateAxis.effectiveValue(_visibleMaximum, needMin: false); + _visibleMaximumIndex = _dateAxis.effectiveValue( + _visibleMaximum, + needMin: false, + ); if (axis.labelPlacement == LabelPlacement.betweenTicks) { _visibleMaximumIndex = _visibleMaximumIndex! + 0.5; } @@ -6433,7 +6949,8 @@ class DateTimeCategoryAxisController extends ChartAxisController { return _visibleMinimum; } return DateTime.fromMillisecondsSinceEpoch( - axis.visibleRange!.minimum.toInt()); + axis.visibleRange!.minimum.toInt(), + ); } DateTime? _visibleMax() { @@ -6441,7 +6958,8 @@ class DateTimeCategoryAxisController extends ChartAxisController { return _visibleMaximum; } return DateTime.fromMillisecondsSinceEpoch( - axis.visibleRange!.maximum.toInt()); + axis.visibleRange!.maximum.toInt(), + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/category_axis.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/category_axis.dart index 8e5eb9d0c..7b099177b 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/category_axis.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/category_axis.dart @@ -75,9 +75,10 @@ class CategoryAxis extends ChartAxis { super.axisLabelFormatter, this.onRendererCreated, }) : assert( - (initialVisibleMaximum == null && initialVisibleMinimum == null) || - autoScrollingDelta == null, - 'Both properties have the same behavior to display the visible data points, use any one of the properties'); + (initialVisibleMaximum == null && initialVisibleMinimum == null) || + autoScrollingDelta == null, + 'Both properties have the same behavior to display the visible data points, use any one of the properties', + ); /// Position of the category axis labels. /// @@ -321,7 +322,9 @@ class CategoryAxis extends ChartAxis { @override void updateRenderObject( - BuildContext context, RenderCategoryAxis renderObject) { + BuildContext context, + RenderCategoryAxis renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..labelPlacement = labelPlacement @@ -462,8 +465,9 @@ class RenderCategoryAxis extends RenderChartAxis { @override num actualValue(Object value) { if (value is String) { - return super - .actualValue(_toIndex(value, defaultIndex: visibleRange!.minimum)); + return super.actualValue( + _toIndex(value, defaultIndex: visibleRange!.minimum), + ); } return super.actualValue(value); @@ -492,12 +496,18 @@ class RenderCategoryAxis extends RenderChartAxis { @override DoubleRange updateAutoScrollingDelta( - int scrollingDelta, DoubleRange actualRange, DoubleRange visibleRange) { + int scrollingDelta, + DoubleRange actualRange, + DoubleRange visibleRange, + ) { if (initialVisibleMaximum != null || initialVisibleMinimum != null) { return visibleRange; } - return super - .updateAutoScrollingDelta(scrollingDelta, actualRange, visibleRange); + return super.updateAutoScrollingDelta( + scrollingDelta, + actualRange, + visibleRange, + ); } @override @@ -512,7 +522,10 @@ class RenderCategoryAxis extends RenderChartAxis { @override DoubleRange applyRangePadding( - DoubleRange range, num interval, Size availableSize) { + DoubleRange range, + num interval, + Size availableSize, + ) { if (labelPlacement == LabelPlacement.betweenTicks) { range.minimum -= 0.5; range.maximum += 0.5; @@ -626,18 +639,28 @@ class RenderCategoryAxis extends RenderChartAxis { } String callbackText = text; - TextStyle callbackTextStyle = - chartThemeData!.axisLabelTextStyle!.merge(labelStyle); + TextStyle callbackTextStyle = chartThemeData!.axisLabelTextStyle!.merge( + labelStyle, + ); if (axisLabelFormatter != null) { final AxisLabelRenderDetails details = AxisLabelRenderDetails( - current, callbackText, callbackTextStyle, this, null, null); + current, + callbackText, + callbackTextStyle, + this, + null, + null, + ); final ChartAxisLabel label = axisLabelFormatter!(details); callbackText = label.text; callbackTextStyle = callbackTextStyle.merge(label.textStyle); } - Size textSize = - measureText(callbackText, callbackTextStyle, labelRotation); + Size textSize = measureText( + callbackText, + callbackTextStyle, + labelRotation, + ); String textAfterTrimming = callbackText; if (extent.isFinite && textSize.width > extent) { textAfterTrimming = trimmedText( @@ -649,8 +672,11 @@ class RenderCategoryAxis extends RenderChartAxis { ); } - textSize = - measureText(textAfterTrimming, callbackTextStyle, labelRotation); + textSize = measureText( + textAfterTrimming, + callbackTextStyle, + labelRotation, + ); final bool isTextTrimmed = callbackText != textAfterTrimming; final AxisLabel label = AxisLabel( callbackTextStyle, @@ -722,22 +748,30 @@ class RenderCategoryAxis extends RenderChartAxis { if (plotBand.isVisible) { final dynamic actualStart = plotBand.start; final dynamic actualEnd = plotBand.end; - final num min = actualStart != null - ? actualValue( - _toIndex(actualStart, defaultIndex: visibleRange!.minimum)) - : visibleRange!.minimum; - num max = actualEnd != null - ? actualValue( - _toIndex(actualEnd, defaultIndex: visibleRange!.maximum)) - : visibleRange!.maximum; + final num min = + actualStart != null + ? actualValue( + _toIndex(actualStart, defaultIndex: visibleRange!.minimum), + ) + : visibleRange!.minimum; + num max = + actualEnd != null + ? actualValue( + _toIndex(actualEnd, defaultIndex: visibleRange!.maximum), + ) + : visibleRange!.maximum; num extent; if (plotBand.isRepeatable) { extent = plotBand.repeatEvery; final dynamic actualRepeatUntil = plotBand.repeatUntil; if (actualRepeatUntil != null) { - max = actualValue(_toIndex(actualRepeatUntil, - defaultIndex: visibleRange!.maximum)); + max = actualValue( + _toIndex( + actualRepeatUntil, + defaultIndex: visibleRange!.maximum, + ), + ); if (max > actualRange!.maximum) { max = actualRange!.maximum; } @@ -751,8 +785,13 @@ class RenderCategoryAxis extends RenderChartAxis { num current = min; if (plotBand.isRepeatable) { while (current < max) { - current = - formPlotBandFrame(plotBand, current, extent, max, bounds); + current = formPlotBandFrame( + plotBand, + current, + extent, + max, + bounds, + ); } } else { formPlotBandFrame(plotBand, current, extent, max, bounds); @@ -784,17 +823,26 @@ class RenderCategoryAxis extends RenderChartAxis { for (int i = 0; i < length; i++) { final CategoricalMultiLevelLabel label = multiLevelLabels![i]; - _multilevelLabels.add(AxisMultilevelLabel(label.text, label.level, - labels.indexOf(label.start), labels.indexOf(label.end))); + _multilevelLabels.add( + AxisMultilevelLabel( + label.text, + label.level, + labels.indexOf(label.start), + labels.indexOf(label.end), + ), + ); } - _multilevelLabels.sort((AxisMultilevelLabel a, AxisMultilevelLabel b) => - a.level.compareTo(b.level)); + _multilevelLabels.sort( + (AxisMultilevelLabel a, AxisMultilevelLabel b) => + a.level.compareTo(b.level), + ); - final void Function(AxisMultilevelLabel label) add = invertElementsOrder - ? (AxisMultilevelLabel label) => - visibleMultilevelLabels.insert(0, label) - : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); + final void Function(AxisMultilevelLabel label) add = + invertElementsOrder + ? (AxisMultilevelLabel label) => + visibleMultilevelLabels.insert(0, label) + : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); final int labelsLength = _multilevelLabels.length; final TextStyle textStyle = chartThemeData!.axisMultiLevelLabelTextStyle! @@ -807,7 +855,12 @@ class RenderCategoryAxis extends RenderChartAxis { if (multiLevelLabelFormatter != null) { final MultiLevelLabelRenderDetails details = MultiLevelLabelRenderDetails( - current.level, desiredText, desiredTextStyle, i, name); + current.level, + desiredText, + desiredTextStyle, + i, + name, + ); final ChartAxisLabel label = multiLevelLabelFormatter!(details); desiredText = label.text; desiredTextStyle = textStyle.merge(label.textStyle); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_axis.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_axis.dart index d0f25e51b..e013012de 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_axis.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_axis.dart @@ -81,9 +81,10 @@ class DateTimeAxis extends ChartAxis { super.axisLabelFormatter, this.onRendererCreated, }) : assert( - (initialVisibleMaximum == null && initialVisibleMinimum == null) || - autoScrollingDelta == null, - 'Both properties have the same behavior to display the visible data points, use any one of the properties'); + (initialVisibleMaximum == null && initialVisibleMinimum == null) || + autoScrollingDelta == null, + 'Both properties have the same behavior to display the visible data points, use any one of the properties', + ); /// Formats the date-time axis labels. The default data-time axis label can be /// formatted with various built-in date formats. @@ -354,7 +355,9 @@ class DateTimeAxis extends ChartAxis { @override void updateRenderObject( - BuildContext context, RenderDateTimeAxis renderObject) { + BuildContext context, + RenderDateTimeAxis renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..dateFormat = dateFormat @@ -517,11 +520,13 @@ class RenderDateTimeAxis extends RenderChartAxis { dynamic end = rangeController!.end; if (rangeController!.start is! DateTime) { start = DateTime.fromMillisecondsSinceEpoch( - (rangeController!.start as num).toInt()); + (rangeController!.start as num).toInt(), + ); } if (rangeController!.end is! DateTime) { end = DateTime.fromMillisecondsSinceEpoch( - (rangeController!.end as num).toInt()); + (rangeController!.end as num).toInt(), + ); } _updateVisibleMinMax(min: start, max: end); } @@ -537,10 +542,12 @@ class RenderDateTimeAxis extends RenderChartAxis { @override void updateRangeControllerValues(DoubleRange newVisibleRange) { - final DateTime start = - DateTime.fromMillisecondsSinceEpoch(newVisibleRange.minimum.toInt()); - final DateTime end = - DateTime.fromMillisecondsSinceEpoch(newVisibleRange.maximum.toInt()); + final DateTime start = DateTime.fromMillisecondsSinceEpoch( + newVisibleRange.minimum.toInt(), + ); + final DateTime end = DateTime.fromMillisecondsSinceEpoch( + newVisibleRange.maximum.toInt(), + ); if (rangeController!.start != start) { rangeController!.start = start; } @@ -553,11 +560,15 @@ class RenderDateTimeAxis extends RenderChartAxis { DoubleRange calculateActualRange() { if (minimum != null && maximum != null) { if (minimum == maximum) { - return DoubleRange(minimum!.millisecondsSinceEpoch - defaultTimeStamp, - maximum!.millisecondsSinceEpoch + defaultTimeStamp); + return DoubleRange( + minimum!.millisecondsSinceEpoch - defaultTimeStamp, + maximum!.millisecondsSinceEpoch + defaultTimeStamp, + ); } return DoubleRange( - minimum!.millisecondsSinceEpoch, maximum!.millisecondsSinceEpoch); + minimum!.millisecondsSinceEpoch, + maximum!.millisecondsSinceEpoch, + ); } final DoubleRange range = super.calculateActualRange(); @@ -577,9 +588,9 @@ class RenderDateTimeAxis extends RenderChartAxis { @override DoubleRange defaultRange() => DoubleRange( - DateTime(1970, 2).millisecondsSinceEpoch, - DateTime(1970, 6).millisecondsSinceEpoch, - ); + DateTime(1970, 2).millisecondsSinceEpoch, + DateTime(1970, 6).millisecondsSinceEpoch, + ); @override num calculateActualInterval(DoubleRange range, Size availableSize) { @@ -589,8 +600,10 @@ class RenderDateTimeAxis extends RenderChartAxis { @override num calculateNiceInterval(num delta, Size availableSize) { if (intervalType == DateTimeIntervalType.auto) { - final num typeBasedInterval = - _calculateIntervalAndType(delta, availableSize); + final num typeBasedInterval = _calculateIntervalAndType( + delta, + availableSize, + ); return interval ?? typeBasedInterval; } @@ -638,8 +651,10 @@ class RenderDateTimeAxis extends RenderChartAxis { final num totalDays = (delta / perDay).abs(); // For years. - num niceInterval = - super.calculateNiceInterval(totalDays / 365, availableSize); + num niceInterval = super.calculateNiceInterval( + totalDays / 365, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.years; return niceInterval.floor(); @@ -660,16 +675,20 @@ class RenderDateTimeAxis extends RenderChartAxis { } // For hours. - niceInterval = - super.calculateNiceInterval(totalDays * hours, availableSize); + niceInterval = super.calculateNiceInterval( + totalDays * hours, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.hours; return niceInterval.floor(); } // For minutes. - niceInterval = - super.calculateNiceInterval(totalDays * hours * minutes, availableSize); + niceInterval = super.calculateNiceInterval( + totalDays * hours * minutes, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.minutes; return niceInterval.floor(); @@ -677,7 +696,9 @@ class RenderDateTimeAxis extends RenderChartAxis { // For seconds. niceInterval = super.calculateNiceInterval( - totalDays * hours * minutes * seconds, availableSize); + totalDays * hours * minutes * seconds, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.seconds; return niceInterval.floor(); @@ -685,7 +706,9 @@ class RenderDateTimeAxis extends RenderChartAxis { // For milliseconds. niceInterval = super.calculateNiceInterval( - totalDays * hours * minutes * seconds * milliseconds, availableSize); + totalDays * hours * minutes * seconds * milliseconds, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.milliseconds; return niceInterval.floor(); @@ -696,7 +719,10 @@ class RenderDateTimeAxis extends RenderChartAxis { @override DoubleRange updateAutoScrollingDelta( - int scrollingDelta, DoubleRange actualRange, DoubleRange visibleRange) { + int scrollingDelta, + DoubleRange actualRange, + DoubleRange visibleRange, + ) { if (initialVisibleMaximum != null || initialVisibleMinimum != null) { return visibleRange; } @@ -704,32 +730,35 @@ class RenderDateTimeAxis extends RenderChartAxis { autoScrollingDeltaType == DateTimeIntervalType.auto ? _visibleIntervalType : autoScrollingDeltaType; - DateTime dateTime = - DateTime.fromMillisecondsSinceEpoch(visibleRange.maximum.toInt()); + DateTime dateTime = DateTime.fromMillisecondsSinceEpoch( + visibleRange.maximum.toInt(), + ); switch (intervalType) { case DateTimeIntervalType.years: dateTime = DateTime( - dateTime.year - autoScrollingDelta!, - dateTime.month, - dateTime.day, - dateTime.hour, - dateTime.minute, - dateTime.second, - dateTime.millisecond, - dateTime.microsecond); + dateTime.year - autoScrollingDelta!, + dateTime.month, + dateTime.day, + dateTime.hour, + dateTime.minute, + dateTime.second, + dateTime.millisecond, + dateTime.microsecond, + ); scrollingDelta = visibleRange.maximum.toInt() - dateTime.millisecondsSinceEpoch; break; case DateTimeIntervalType.months: dateTime = DateTime( - dateTime.year, - dateTime.month - autoScrollingDelta!, - dateTime.day, - dateTime.hour, - dateTime.minute, - dateTime.second, - dateTime.millisecond, - dateTime.microsecond); + dateTime.year, + dateTime.month - autoScrollingDelta!, + dateTime.day, + dateTime.hour, + dateTime.minute, + dateTime.second, + dateTime.millisecond, + dateTime.microsecond, + ); scrollingDelta = visibleRange.maximum.toInt() - dateTime.millisecondsSinceEpoch; break; @@ -753,13 +782,19 @@ class RenderDateTimeAxis extends RenderChartAxis { scrollingDelta = autoScrollingDelta!; break; } - return super - .updateAutoScrollingDelta(scrollingDelta, actualRange, visibleRange); + return super.updateAutoScrollingDelta( + scrollingDelta, + actualRange, + visibleRange, + ); } @override DoubleRange applyRangePadding( - DoubleRange range, num interval, Size availableSize) { + DoubleRange range, + num interval, + Size availableSize, + ) { if (minimum == null && maximum == null) { final ChartRangePadding padding = effectiveRangePadding(); if (padding == ChartRangePadding.additional || @@ -812,10 +847,12 @@ class RenderDateTimeAxis extends RenderChartAxis { } void _addAdditionalYear(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startYear = startDate.year; final int endYear = endDate.year; if (rangePadding == ChartRangePadding.additional || @@ -829,142 +866,199 @@ class RenderDateTimeAxis extends RenderChartAxis { } void _addAdditionalMonth(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startMonth = startDate.month; final int endMonth = endDate.month; if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalStart) { - range.minimum = DateTime(startDate.year, startMonth - interval) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startMonth - interval, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalEnd) { range.maximum = // TODO(Natrayan): Revisit the end month calculation. - DateTime(endDate.year, endMonth + interval, endMonth == 2 ? 28 : 30) - .millisecondsSinceEpoch; + DateTime( + endDate.year, + endMonth + interval, + endMonth == 2 ? 28 : 30, + ).millisecondsSinceEpoch; } } void _addAdditionalDays(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startDay = startDate.day; final int endDay = endDate.day; if (rangePadding == ChartRangePadding.additionalStart || rangePadding == ChartRangePadding.additional) { range.minimum = - DateTime(startDate.year, startDate.month, startDay - interval) - .millisecondsSinceEpoch; + DateTime( + startDate.year, + startDate.month, + startDay - interval, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalEnd) { - range.maximum = DateTime(endDate.year, endDate.month, endDay + interval) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDay + interval, + ).millisecondsSinceEpoch; } } void _addAdditionalHours(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startHour = ((startDate.hour / interval) * interval).toInt(); final int endHour = endDate.hour + (startDate.hour - startHour); if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalStart) { - range.minimum = DateTime(startDate.year, startDate.month, startDate.day, - startHour - interval) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startHour - interval, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalEnd) { range.maximum = - DateTime(endDate.year, endDate.month, endDate.day, endHour + interval) - .millisecondsSinceEpoch; + DateTime( + endDate.year, + endDate.month, + endDate.day, + endHour + interval, + ).millisecondsSinceEpoch; } } void _addAdditionalMinutes(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startMinute = ((startDate.minute / interval) * interval).toInt(); final int endMinute = endDate.minute + (startDate.minute - startMinute); if (rangePadding == ChartRangePadding.additionalStart || rangePadding == ChartRangePadding.additional) { - range.minimum = DateTime(startDate.year, startDate.month, startDate.day, - startDate.hour, startMinute - interval) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startMinute - interval, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalEnd) { - range.maximum = DateTime(endDate.year, endDate.month, endDate.day, - endDate.hour, endMinute + interval) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDate.day, + endDate.hour, + endMinute + interval, + ).millisecondsSinceEpoch; } } void _addAdditionalSeconds(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startSecond = ((startDate.second / interval) * interval).toInt(); final int endSecond = endDate.second + (startDate.second - startSecond); if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalStart) { - range.minimum = DateTime(startDate.year, startDate.month, startDate.day, - startDate.hour, startDate.minute, startSecond - interval) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startDate.minute, + startSecond - interval, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalEnd) { - range.maximum = DateTime(endDate.year, endDate.month, endDate.day, - endDate.hour, endDate.minute, endSecond + interval) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDate.day, + endDate.hour, + endDate.minute, + endSecond + interval, + ).millisecondsSinceEpoch; } } void _addAdditionalMilliseconds(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startMilliSecond = ((startDate.millisecond / interval) * interval).toInt(); final int endMilliSecond = endDate.millisecond + (startDate.millisecond - startMilliSecond); if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalStart) { - range.minimum = DateTime( - startDate.year, - startDate.month, - startDate.day, - startDate.hour, - startDate.minute, - startDate.second, - startMilliSecond - interval) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startDate.minute, + startDate.second, + startMilliSecond - interval, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.additional || rangePadding == ChartRangePadding.additionalEnd) { - range.maximum = DateTime( - endDate.year, - endDate.month, - endDate.day, - endDate.hour, - endDate.minute, - endDate.second, - endMilliSecond + interval) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDate.day, + endDate.hour, + endDate.minute, + endDate.second, + endMilliSecond + interval, + ).millisecondsSinceEpoch; } } @@ -1004,10 +1098,12 @@ class RenderDateTimeAxis extends RenderChartAxis { } void _roundYears(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startYear = startDate.year; final int endYear = endDate.year; if (rangePadding == ChartRangePadding.round || @@ -1022,10 +1118,12 @@ class RenderDateTimeAxis extends RenderChartAxis { } void _roundMonths(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startMonth = startDate.month; final int endMonth = endDate.month; if (rangePadding == ChartRangePadding.round || @@ -1035,119 +1133,187 @@ class RenderDateTimeAxis extends RenderChartAxis { } if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundEnd) { - range.maximum = DateTime(endDate.year, endMonth, - DateTime(endDate.year, endDate.month, 0).day, 23, 59, 59) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endMonth, + DateTime(endDate.year, endDate.month, 0).day, + 23, + 59, + 59, + ).millisecondsSinceEpoch; } } void _roundDays(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startDay = startDate.day; final int endDay = endDate.day; if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundStart) { - range.minimum = DateTime(startDate.year, startDate.month, startDay) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDay, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundEnd) { - range.maximum = DateTime(endDate.year, endDate.month, endDay, 23, 59, 59) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDay, + 23, + 59, + 59, + ).millisecondsSinceEpoch; } } void _roundHours(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startHour = ((startDate.hour / interval) * interval).toInt(); if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundStart) { range.minimum = - DateTime(startDate.year, startDate.month, startDate.day, startHour) - .millisecondsSinceEpoch; + DateTime( + startDate.year, + startDate.month, + startDate.day, + startHour, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundEnd) { range.maximum = - DateTime(endDate.year, endDate.month, endDate.day, startHour, 59, 59) - .millisecondsSinceEpoch; + DateTime( + endDate.year, + endDate.month, + endDate.day, + startHour, + 59, + 59, + ).millisecondsSinceEpoch; } } void _roundMinutes(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startMinute = ((startDate.minute / interval) * interval).toInt(); final int endMinute = endDate.minute + (startDate.minute - startMinute); if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundStart) { - range.minimum = DateTime(startDate.year, startDate.month, startDate.day, - startDate.hour, startMinute) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startMinute, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundEnd) { - range.maximum = DateTime(endDate.year, endDate.month, endDate.day, - endDate.hour, endMinute, 59) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDate.day, + endDate.hour, + endMinute, + 59, + ).millisecondsSinceEpoch; } } void _roundSeconds(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startSecond = ((startDate.second / interval) * interval).toInt(); final int endSecond = endDate.second + (startDate.second - startSecond); if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundStart) { - range.minimum = DateTime(startDate.year, startDate.month, startDate.day, - startDate.hour, startDate.minute, startSecond) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startDate.minute, + startSecond, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundEnd) { - range.maximum = DateTime(startDate.year, startDate.month, startDate.day, - startDate.hour, startDate.minute, endSecond) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startDate.minute, + endSecond, + ).millisecondsSinceEpoch; } } void _roundMilliseconds(DoubleRange range, int interval) { - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(range.minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(range.maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + range.minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + range.maximum.toInt(), + ); final int startMilliSecond = ((startDate.millisecond / interval) * interval).toInt(); final int endMilliSecond = endDate.millisecond + (startDate.millisecond - startMilliSecond); if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundStart) { - range.minimum = DateTime( - startDate.year, - startDate.month, - startDate.day, - startDate.hour, - startDate.minute, - startDate.second, - startMilliSecond) - .millisecondsSinceEpoch; + range.minimum = + DateTime( + startDate.year, + startDate.month, + startDate.day, + startDate.hour, + startDate.minute, + startDate.second, + startMilliSecond, + ).millisecondsSinceEpoch; } if (rangePadding == ChartRangePadding.round || rangePadding == ChartRangePadding.roundEnd) { - range.maximum = DateTime(endDate.year, endDate.month, endDate.day, - endDate.hour, endDate.minute, endDate.second, endMilliSecond) - .millisecondsSinceEpoch; + range.maximum = + DateTime( + endDate.year, + endDate.month, + endDate.day, + endDate.hour, + endDate.minute, + endDate.second, + endMilliSecond, + ).millisecondsSinceEpoch; } } @@ -1168,25 +1334,38 @@ class RenderDateTimeAxis extends RenderChartAxis { while (current <= visibleMaximum) { if (current < visibleMinimum || !effectiveVisibleRange!.contains(current)) { - current = _nextDate(current, visibleInterval, visibleIntervalType) - .millisecondsSinceEpoch; + current = + _nextDate( + current, + visibleInterval, + visibleIntervalType, + ).millisecondsSinceEpoch; continue; } - final DateFormat niceDateFormat = dateFormat ?? + final DateFormat niceDateFormat = + dateFormat ?? dateTimeAxisLabelFormat(this, current, previous.toInt()); - String text = niceDateFormat - .format(DateTime.fromMillisecondsSinceEpoch(current.toInt())); + String text = niceDateFormat.format( + DateTime.fromMillisecondsSinceEpoch(current.toInt()), + ); if (labelFormat != null && labelFormat != '') { text = labelFormat!.replaceAll(RegExp('{value}'), text); } String callbackText = text; - TextStyle callbackTextStyle = - chartThemeData!.axisLabelTextStyle!.merge(labelStyle); + TextStyle callbackTextStyle = chartThemeData!.axisLabelTextStyle!.merge( + labelStyle, + ); if (axisLabelFormatter != null) { - final AxisLabelRenderDetails details = AxisLabelRenderDetails(current, - callbackText, callbackTextStyle, this, visibleIntervalType, text); + final AxisLabelRenderDetails details = AxisLabelRenderDetails( + current, + callbackText, + callbackTextStyle, + this, + visibleIntervalType, + text, + ); final ChartAxisLabel label = axisLabelFormatter!(details); callbackText = label.text; callbackTextStyle = callbackTextStyle.merge(label.textStyle); @@ -1204,8 +1383,11 @@ class RenderDateTimeAxis extends RenderChartAxis { ); } - textSize = - measureText(textAfterTrimming, callbackTextStyle, labelRotation); + textSize = measureText( + textAfterTrimming, + callbackTextStyle, + labelRotation, + ); final bool isTextTrimmed = callbackText != textAfterTrimming; final AxisLabel label = AxisLabel( callbackTextStyle, @@ -1220,8 +1402,12 @@ class RenderDateTimeAxis extends RenderChartAxis { if (isTextTrimmed) { hasTrimmedAxisLabel = true; } - current = _nextDate(current, visibleInterval, visibleIntervalType) - .millisecondsSinceEpoch; + current = + _nextDate( + current, + visibleInterval, + visibleIntervalType, + ).millisecondsSinceEpoch; if (previous == current) { return; } @@ -1267,15 +1453,28 @@ class RenderDateTimeAxis extends RenderChartAxis { final int second = ((date.second / visibleInterval).floor() * visibleInterval).floor(); date = DateTime( - date.year, date.month, date.day, date.hour, date.minute, second); + date.year, + date.month, + date.day, + date.hour, + date.minute, + second, + ); break; case DateTimeIntervalType.milliseconds: final int millisecond = ((date.millisecond / visibleInterval).floor() * visibleInterval) .floor(); - date = DateTime(date.year, date.month, date.day, date.hour, date.minute, - date.second, millisecond); + date = DateTime( + date.year, + date.month, + date.day, + date.hour, + date.minute, + date.second, + millisecond, + ); break; case DateTimeIntervalType.auto: @@ -1286,19 +1485,34 @@ class RenderDateTimeAxis extends RenderChartAxis { } DateTime _nextDate( - num current, num interval, DateTimeIntervalType intervalType) { + num current, + num interval, + DateTimeIntervalType intervalType, + ) { DateTime date = DateTime.fromMillisecondsSinceEpoch(current.toInt()); final bool hasDecimalInterval = interval % 1 == 0; if (hasDecimalInterval) { final int effectiveInterval = interval.floor(); switch (intervalType) { case DateTimeIntervalType.years: - return date = DateTime(date.year + effectiveInterval, date.month, - date.day, date.hour, date.minute, date.second); + return date = DateTime( + date.year + effectiveInterval, + date.month, + date.day, + date.hour, + date.minute, + date.second, + ); case DateTimeIntervalType.months: - return date = DateTime(date.year, date.month + effectiveInterval, - date.day, date.hour, date.minute, date.second); + return date = DateTime( + date.year, + date.month + effectiveInterval, + date.day, + date.hour, + date.minute, + date.second, + ); case DateTimeIntervalType.days: return date.add(Duration(days: effectiveInterval)); @@ -1322,12 +1536,13 @@ class RenderDateTimeAxis extends RenderChartAxis { switch (intervalType) { case DateTimeIntervalType.years: return date = DateTime( - date.year, - date.month + (interval * 12).floor(), - date.day, - date.hour, - date.minute, - date.second); + date.year, + date.month + (interval * 12).floor(), + date.day, + date.hour, + date.minute, + date.second, + ); case DateTimeIntervalType.months: return date.add(Duration(days: (interval * 30).floor())); @@ -1420,22 +1635,29 @@ class RenderDateTimeAxis extends RenderChartAxis { for (int i = 0; i < length; i++) { final DateTimeMultiLevelLabel label = multiLevelLabels![i]; - assert(label.start.millisecondsSinceEpoch <= - label.end.millisecondsSinceEpoch); - _multilevelLabels.add(AxisMultilevelLabel( + assert( + label.start.millisecondsSinceEpoch <= label.end.millisecondsSinceEpoch, + ); + _multilevelLabels.add( + AxisMultilevelLabel( label.text, label.level, label.start.millisecondsSinceEpoch, - label.end.millisecondsSinceEpoch)); + label.end.millisecondsSinceEpoch, + ), + ); } - _multilevelLabels.sort((AxisMultilevelLabel a, AxisMultilevelLabel b) => - a.level.compareTo(b.level)); + _multilevelLabels.sort( + (AxisMultilevelLabel a, AxisMultilevelLabel b) => + a.level.compareTo(b.level), + ); - final void Function(AxisMultilevelLabel label) add = invertElementsOrder - ? (AxisMultilevelLabel label) => - visibleMultilevelLabels.insert(0, label) - : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); + final void Function(AxisMultilevelLabel label) add = + invertElementsOrder + ? (AxisMultilevelLabel label) => + visibleMultilevelLabels.insert(0, label) + : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); final int labelsLength = _multilevelLabels.length; final TextStyle textStyle = chartThemeData!.axisMultiLevelLabelTextStyle! @@ -1448,7 +1670,12 @@ class RenderDateTimeAxis extends RenderChartAxis { if (multiLevelLabelFormatter != null) { final MultiLevelLabelRenderDetails details = MultiLevelLabelRenderDetails( - current.level, desiredText, desiredTextStyle, i, name); + current.level, + desiredText, + desiredTextStyle, + i, + name, + ); final ChartAxisLabel label = multiLevelLabelFormatter!(details); desiredText = label.text; desiredTextStyle = textStyle.merge(label.textStyle); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_category_axis.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_category_axis.dart index b5d054b5e..ec00cdda2 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_category_axis.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/datetime_category_axis.dart @@ -84,9 +84,10 @@ class DateTimeCategoryAxis extends ChartAxis { super.axisLabelFormatter, this.onRendererCreated, }) : assert( - (initialVisibleMaximum == null && initialVisibleMinimum == null) || - autoScrollingDelta == null, - 'Both properties have the same behavior to display the visible data points, use any one of the properties'); + (initialVisibleMaximum == null && initialVisibleMinimum == null) || + autoScrollingDelta == null, + 'Both properties have the same behavior to display the visible data points, use any one of the properties', + ); /// Formats the date-time category axis labels. /// @@ -376,7 +377,9 @@ class DateTimeCategoryAxis extends ChartAxis { @override void updateRenderObject( - BuildContext context, RenderDateTimeCategoryAxis renderObject) { + BuildContext context, + RenderDateTimeCategoryAxis renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..labelPlacement = labelPlacement @@ -539,11 +542,13 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { dynamic end = rangeController!.end; if (rangeController!.start is! DateTime) { start = DateTime.fromMillisecondsSinceEpoch( - labels[(rangeController!.start as num).toInt()]); + labels[(rangeController!.start as num).toInt()], + ); } if (rangeController!.end is! DateTime) { end = DateTime.fromMillisecondsSinceEpoch( - labels[(rangeController!.end as num).toInt()]); + labels[(rangeController!.end as num).toInt()], + ); } _updateVisibleMinMax(min: start, max: end); } @@ -561,7 +566,9 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { DoubleRange calculateActualRange() { if (minimum != null && maximum != null) { return DoubleRange( - effectiveValue(minimum)!, effectiveValue(maximum, needMin: false)!); + effectiveValue(minimum)!, + effectiveValue(maximum, needMin: false)!, + ); } final DoubleRange range = super.calculateActualRange(); @@ -581,12 +588,18 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { @override DoubleRange updateAutoScrollingDelta( - int scrollingDelta, DoubleRange actualRange, DoubleRange visibleRange) { + int scrollingDelta, + DoubleRange actualRange, + DoubleRange visibleRange, + ) { if (initialVisibleMaximum != null || initialVisibleMinimum != null) { return visibleRange; } - return super - .updateAutoScrollingDelta(scrollingDelta, actualRange, visibleRange); + return super.updateAutoScrollingDelta( + scrollingDelta, + actualRange, + visibleRange, + ); } @override @@ -618,18 +631,22 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { num _calculateIntervalAndType(num minimum, num maximum, Size availableSize) { const int perDay = 24 * 60 * 60 * 1000; const num hours = 24, minutes = 60, seconds = 60, milliseconds = 1000; - final DateTime startDate = - DateTime.fromMillisecondsSinceEpoch(minimum.toInt()); - final DateTime endDate = - DateTime.fromMillisecondsSinceEpoch(maximum.toInt()); + final DateTime startDate = DateTime.fromMillisecondsSinceEpoch( + minimum.toInt(), + ); + final DateTime endDate = DateTime.fromMillisecondsSinceEpoch( + maximum.toInt(), + ); final num totalDays = ((endDate.millisecondsSinceEpoch - startDate.millisecondsSinceEpoch) / perDay) .abs(); // For years. - num niceInterval = - super.calculateNiceInterval(totalDays / 365, availableSize); + num niceInterval = super.calculateNiceInterval( + totalDays / 365, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.years; return niceInterval.floor(); @@ -650,16 +667,20 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { } // For hours. - niceInterval = - super.calculateNiceInterval(totalDays * hours, availableSize); + niceInterval = super.calculateNiceInterval( + totalDays * hours, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.hours; return niceInterval.floor(); } // For minutes. - niceInterval = - super.calculateNiceInterval(totalDays * hours * minutes, availableSize); + niceInterval = super.calculateNiceInterval( + totalDays * hours * minutes, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.minutes; return niceInterval.floor(); @@ -667,7 +688,9 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { // For seconds. niceInterval = super.calculateNiceInterval( - totalDays * hours * minutes * seconds, availableSize); + totalDays * hours * minutes * seconds, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.seconds; return niceInterval.floor(); @@ -675,7 +698,9 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { // For milliseconds. niceInterval = super.calculateNiceInterval( - totalDays * hours * minutes * seconds * milliseconds, availableSize); + totalDays * hours * minutes * seconds * milliseconds, + availableSize, + ); if (niceInterval >= 1) { _visibleIntervalType = DateTimeIntervalType.milliseconds; return niceInterval.floor(); @@ -686,7 +711,10 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { @override DoubleRange applyRangePadding( - DoubleRange range, num interval, Size availableSize) { + DoubleRange range, + num interval, + Size availableSize, + ) { if (labelPlacement == LabelPlacement.betweenTicks) { range.minimum -= 0.5; range.maximum += 0.5; @@ -754,16 +782,18 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { final bool isRtl = textDirection == TextDirection.rtl; num niceInterval = visibleInterval; final List split = niceInterval.toString().split('.'); - niceInterval = split.length >= 2 - ? split[1].length == 1 && split[1] == '0' - ? niceInterval.floor() - : niceInterval.ceil() - : niceInterval; + niceInterval = + split.length >= 2 + ? split[1].length == 1 && split[1] == '0' + ? niceInterval.floor() + : niceInterval.ceil() + : niceInterval; final num visibleMinimum = visibleRange!.minimum; final num visibleMaximum = visibleRange!.maximum; num current = visibleMinimum.ceil(); num previous = current; - final DateFormat niceDateTimeFormat = dateFormat ?? + final DateFormat niceDateTimeFormat = + dateFormat ?? dateTimeCategoryAxisLabelFormat(this, current, previous.toInt()); while (current <= visibleMaximum) { if (current < visibleMinimum || @@ -779,27 +809,38 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { current += niceInterval; continue; } else if (labels.isNotEmpty) { - text = niceDateTimeFormat - .format(DateTime.fromMillisecondsSinceEpoch(labels[currentValue])); + text = niceDateTimeFormat.format( + DateTime.fromMillisecondsSinceEpoch(labels[currentValue]), + ); } else { current += niceInterval; continue; } String callbackText = text; - TextStyle callbackTextStyle = - chartThemeData!.axisLabelTextStyle!.merge(labelStyle); + TextStyle callbackTextStyle = chartThemeData!.axisLabelTextStyle!.merge( + labelStyle, + ); if (axisLabelFormatter != null) { - final AxisLabelRenderDetails details = AxisLabelRenderDetails(current, - callbackText, callbackTextStyle, this, visibleIntervalType, text); + final AxisLabelRenderDetails details = AxisLabelRenderDetails( + current, + callbackText, + callbackTextStyle, + this, + visibleIntervalType, + text, + ); final ChartAxisLabel label = axisLabelFormatter!(details); callbackText = label.text; callbackTextStyle = callbackTextStyle.merge(label.textStyle); } String textAfterTrimming = callbackText; - Size textSize = - measureText(callbackText, callbackTextStyle, labelRotation); + Size textSize = measureText( + callbackText, + callbackTextStyle, + labelRotation, + ); if (extent.isFinite && textSize.width > extent) { textAfterTrimming = trimmedText( callbackText, @@ -810,8 +851,11 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { ); } - textSize = - measureText(textAfterTrimming, callbackTextStyle, labelRotation); + textSize = measureText( + textAfterTrimming, + callbackTextStyle, + labelRotation, + ); final bool isTextTrimmed = callbackText != textAfterTrimming; final AxisLabel label = AxisLabel( callbackTextStyle, @@ -884,12 +928,14 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { if (plotBand.isVisible) { final dynamic actualStart = plotBand.start; final dynamic actualEnd = plotBand.end; - final num min = actualStart != null - ? _handleValueType(actualStart) - : visibleRange!.minimum; - num max = actualEnd != null - ? _handleValueType(actualEnd) - : visibleRange!.maximum; + final num min = + actualStart != null + ? _handleValueType(actualStart) + : visibleRange!.minimum; + num max = + actualEnd != null + ? _handleValueType(actualEnd) + : visibleRange!.maximum; num extent; if (plotBand.isRepeatable) { @@ -910,8 +956,13 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { num current = min; if (plotBand.isRepeatable) { while (current < max) { - current = - formPlotBandFrame(plotBand, current, extent, max, bounds); + current = formPlotBandFrame( + plotBand, + current, + extent, + max, + bounds, + ); } } else { formPlotBandFrame(plotBand, current, extent, max, bounds); @@ -958,20 +1009,26 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { for (int index = 0; index < length; index++) { final DateTimeCategoricalMultiLevelLabel label = multiLevelLabels![index]; - _multilevelLabels.add(AxisMultilevelLabel( + _multilevelLabels.add( + AxisMultilevelLabel( label.text, label.level, effectiveValue(label.start)!, - effectiveValue(label.end, needMin: false)!)); + effectiveValue(label.end, needMin: false)!, + ), + ); } - _multilevelLabels.sort((AxisMultilevelLabel a, AxisMultilevelLabel b) => - a.level.compareTo(b.level)); + _multilevelLabels.sort( + (AxisMultilevelLabel a, AxisMultilevelLabel b) => + a.level.compareTo(b.level), + ); - final void Function(AxisMultilevelLabel label) add = invertElementsOrder - ? (AxisMultilevelLabel label) => - visibleMultilevelLabels.insert(0, label) - : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); + final void Function(AxisMultilevelLabel label) add = + invertElementsOrder + ? (AxisMultilevelLabel label) => + visibleMultilevelLabels.insert(0, label) + : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); final int labelsLength = _multilevelLabels.length; final TextStyle textStyle = chartThemeData!.axisMultiLevelLabelTextStyle! @@ -984,7 +1041,12 @@ class RenderDateTimeCategoryAxis extends RenderChartAxis { if (multiLevelLabelFormatter != null) { final MultiLevelLabelRenderDetails details = MultiLevelLabelRenderDetails( - current.level, desiredText, desiredTextStyle, i, name); + current.level, + desiredText, + desiredTextStyle, + i, + name, + ); final ChartAxisLabel label = multiLevelLabelFormatter!(details); desiredText = label.text; desiredTextStyle = textStyle.merge(label.textStyle); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/logarithmic_axis.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/logarithmic_axis.dart index 3d8822cf4..6fe19ec21 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/logarithmic_axis.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/logarithmic_axis.dart @@ -79,9 +79,10 @@ class LogarithmicAxis extends ChartAxis { super.axisLabelFormatter, this.onRendererCreated, }) : assert( - (initialVisibleMaximum == null && initialVisibleMinimum == null) || - autoScrollingDelta == null, - 'Both properties have the same behavior to display the visible data points, use any one of the properties'); + (initialVisibleMaximum == null && initialVisibleMinimum == null) || + autoScrollingDelta == null, + 'Both properties have the same behavior to display the visible data points, use any one of the properties', + ); /// Formats the numeric axis labels. /// @@ -343,7 +344,9 @@ class LogarithmicAxis extends ChartAxis { @override void updateRenderObject( - BuildContext context, RenderLogarithmicAxis renderObject) { + BuildContext context, + RenderLogarithmicAxis renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..labelFormat = labelFormat @@ -361,8 +364,9 @@ class RenderLogarithmicAxis extends RenderChartAxis { @override LogarithmicAxisController get controller => _controller; - late final LogarithmicAxisController _controller = - LogarithmicAxisController(this); + late final LogarithmicAxisController _controller = LogarithmicAxisController( + this, + ); @override @nonVirtual @@ -513,7 +517,10 @@ class RenderLogarithmicAxis extends RenderChartAxis { @override DoubleRange applyRangePadding( - DoubleRange range, num interval, Size availableSize) { + DoubleRange range, + num interval, + Size availableSize, + ) { return range; } @@ -573,12 +580,18 @@ class RenderLogarithmicAxis extends RenderChartAxis { @override DoubleRange updateAutoScrollingDelta( - int scrollingDelta, DoubleRange actualRange, DoubleRange visibleRange) { + int scrollingDelta, + DoubleRange actualRange, + DoubleRange visibleRange, + ) { if (initialVisibleMaximum != null || initialVisibleMinimum != null) { return visibleRange; } - return super - .updateAutoScrollingDelta(scrollingDelta, actualRange, visibleRange); + return super.updateAutoScrollingDelta( + scrollingDelta, + actualRange, + visibleRange, + ); } @override @@ -626,9 +639,10 @@ class RenderLogarithmicAxis extends RenderChartAxis { } final num currentValue = toPow(current); - String text = currentValue < 1 - ? currentValue.toString() - : currentValue.floor().toString(); + String text = + currentValue < 1 + ? currentValue.toString() + : currentValue.floor().toString(); if (numberFormat != null) { text = numberFormat!.format(toPow(current)); } @@ -641,11 +655,18 @@ class RenderLogarithmicAxis extends RenderChartAxis { text = '$text%'; } String callbackText = text; - TextStyle callbackTextStyle = - chartThemeData!.axisLabelTextStyle!.merge(labelStyle); + TextStyle callbackTextStyle = chartThemeData!.axisLabelTextStyle!.merge( + labelStyle, + ); if (axisLabelFormatter != null) { final AxisLabelRenderDetails details = AxisLabelRenderDetails( - current, callbackText, callbackTextStyle, this, null, null); + current, + callbackText, + callbackTextStyle, + this, + null, + null, + ); final ChartAxisLabel label = axisLabelFormatter!(details); callbackText = label.text; callbackTextStyle = callbackTextStyle.merge(label.textStyle); @@ -663,8 +684,11 @@ class RenderLogarithmicAxis extends RenderChartAxis { ); } - textSize = - measureText(textAfterTrimming, callbackTextStyle, labelRotation); + textSize = measureText( + textAfterTrimming, + callbackTextStyle, + labelRotation, + ); final bool isTextTrimmed = callbackText != textAfterTrimming; final AxisLabel label = AxisLabel( callbackTextStyle, @@ -706,7 +730,8 @@ class RenderLogarithmicAxis extends RenderChartAxis { if (i < lastIndex) { current = toLog(visibleLabels[i].value) - tickBetweenLabel; } else { - current = (toLog(visibleLabels[i - 1].value) + visibleInterval) - + current = + (toLog(visibleLabels[i - 1].value) + visibleInterval) - tickBetweenLabel; } } else { @@ -743,12 +768,14 @@ class RenderLogarithmicAxis extends RenderChartAxis { for (int i = 0; i < length; i++) { final PlotBand plotBand = plotBands[i]; if (plotBand.isVisible) { - final num min = plotBand.start != null - ? actualValue(plotBand.start) - : toPow(visibleRange!.minimum); - num max = plotBand.end != null - ? actualValue(plotBand.end) - : toPow(visibleRange!.maximum); + final num min = + plotBand.start != null + ? actualValue(plotBand.start) + : toPow(visibleRange!.minimum); + num max = + plotBand.end != null + ? actualValue(plotBand.end) + : toPow(visibleRange!.maximum); num extent; if (plotBand.isRepeatable) { @@ -769,8 +796,13 @@ class RenderLogarithmicAxis extends RenderChartAxis { num current = min; if (plotBand.isRepeatable) { while (current < max) { - current = - formPlotBandFrame(plotBand, current, extent, max, bounds); + current = formPlotBandFrame( + plotBand, + current, + extent, + max, + bounds, + ); } } else { formPlotBandFrame(plotBand, current, extent, max, bounds); @@ -781,23 +813,37 @@ class RenderLogarithmicAxis extends RenderChartAxis { } @override - num formPlotBandFrame(PlotBand plotBand, num current, num extent, num max, - Rect Function(PlotBand plotBand, num start, num end) bounds) { + num formPlotBandFrame( + PlotBand plotBand, + num current, + num extent, + num max, + Rect Function(PlotBand plotBand, num start, num end) bounds, + ) { num end = plotBandExtent( - plotBand, current, plotBand.isRepeatable ? plotBand.size : extent); + plotBand, + current, + plotBand.isRepeatable ? plotBand.size : extent, + ); if (end > max) { end = max; } final DoubleRange logRange = visibleRange!.copyWith(); - final DoubleRange powRange = - DoubleRange(toPow(logRange.minimum), toPow(logRange.maximum)); + final DoubleRange powRange = DoubleRange( + toPow(logRange.minimum), + toPow(logRange.maximum), + ); if (powRange.lies(current, end)) { final Rect frame = bounds(plotBand, current, end); addPlotBand(frame, plotBand); - current = plotBand.size != null - ? plotBandExtent(plotBand, current, - plotBand.isRepeatable ? plotBand.repeatEvery : end) - : end; + current = + plotBand.size != null + ? plotBandExtent( + plotBand, + current, + plotBand.isRepeatable ? plotBand.repeatEvery : end, + ) + : end; } return current; } @@ -815,17 +861,26 @@ class RenderLogarithmicAxis extends RenderChartAxis { for (int i = 0; i < length; i++) { final LogarithmicMultiLevelLabel label = multiLevelLabels![i]; assert(label.start <= label.end); - _multilevelLabels.add(AxisMultilevelLabel( - label.text, label.level, toLog(label.start), toLog(label.end))); + _multilevelLabels.add( + AxisMultilevelLabel( + label.text, + label.level, + toLog(label.start), + toLog(label.end), + ), + ); } - _multilevelLabels.sort((AxisMultilevelLabel a, AxisMultilevelLabel b) => - a.level.compareTo(b.level)); + _multilevelLabels.sort( + (AxisMultilevelLabel a, AxisMultilevelLabel b) => + a.level.compareTo(b.level), + ); - final void Function(AxisMultilevelLabel label) add = invertElementsOrder - ? (AxisMultilevelLabel label) => - visibleMultilevelLabels.insert(0, label) - : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); + final void Function(AxisMultilevelLabel label) add = + invertElementsOrder + ? (AxisMultilevelLabel label) => + visibleMultilevelLabels.insert(0, label) + : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); final int labelsLength = _multilevelLabels.length; final TextStyle textStyle = chartThemeData!.axisMultiLevelLabelTextStyle! @@ -838,7 +893,12 @@ class RenderLogarithmicAxis extends RenderChartAxis { if (multiLevelLabelFormatter != null) { final MultiLevelLabelRenderDetails details = MultiLevelLabelRenderDetails( - current.level, desiredText, desiredTextStyle, i, name); + current.level, + desiredText, + desiredTextStyle, + i, + name, + ); final ChartAxisLabel label = multiLevelLabelFormatter!(details); desiredText = label.text; desiredTextStyle = textStyle.merge(label.textStyle); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/multi_level_labels.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/multi_level_labels.dart index 20072f54e..7df9d3be9 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/multi_level_labels.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/multi_level_labels.dart @@ -403,12 +403,7 @@ class MultiLevelLabelStyle { /// Holds the multi-level axis label information. class AxisMultilevelLabel { /// Argument constructor of [AxisMultilevelLabel] class. - AxisMultilevelLabel( - this.text, - this.level, - this.start, - this.end, - ); + AxisMultilevelLabel(this.text, this.level, this.start, this.end); /// Contains the text of the label. String text; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/numeric_axis.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/numeric_axis.dart index a18567dd1..5dc7087f5 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/numeric_axis.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/numeric_axis.dart @@ -77,9 +77,10 @@ class NumericAxis extends ChartAxis { super.axisLabelFormatter, this.onRendererCreated, }) : assert( - (initialVisibleMaximum == null && initialVisibleMinimum == null) || - autoScrollingDelta == null, - 'Both properties have the same behavior to display the visible data points, use any one of the properties'); + (initialVisibleMaximum == null && initialVisibleMinimum == null) || + autoScrollingDelta == null, + 'Both properties have the same behavior to display the visible data points, use any one of the properties', + ); /// Formats the numeric axis labels. /// @@ -339,7 +340,9 @@ class NumericAxis extends ChartAxis { @override void updateRenderObject( - BuildContext context, RenderNumericAxis renderObject) { + BuildContext context, + RenderNumericAxis renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..labelFormat = labelFormat @@ -506,12 +509,18 @@ class RenderNumericAxis extends RenderChartAxis { @override DoubleRange updateAutoScrollingDelta( - int scrollingDelta, DoubleRange actualRange, DoubleRange visibleRange) { + int scrollingDelta, + DoubleRange actualRange, + DoubleRange visibleRange, + ) { if (initialVisibleMaximum != null || initialVisibleMinimum != null) { return visibleRange; } - return super - .updateAutoScrollingDelta(scrollingDelta, actualRange, visibleRange); + return super.updateAutoScrollingDelta( + scrollingDelta, + actualRange, + visibleRange, + ); } @override @@ -542,7 +551,10 @@ class RenderNumericAxis extends RenderChartAxis { @override DoubleRange applyRangePadding( - DoubleRange range, num interval, Size availableSize) { + DoubleRange range, + num interval, + Size availableSize, + ) { if (minimum != null && maximum != null) { return range; } @@ -581,20 +593,28 @@ class RenderNumericAxis extends RenderChartAxis { final int piecesLength = pieces.length; int digits = piecesLength >= 2 ? pieces[1].length : 0; digits = digits > 20 ? 20 : digits; - currentValue = currentText.contains('e') - ? currentValue - : num.tryParse(currentValue.toStringAsFixed(digits))!; + currentValue = + currentText.contains('e') + ? currentValue + : num.tryParse(currentValue.toStringAsFixed(digits))!; String text = numericAxisLabel(this, currentValue, decimalPlaces); if (_dependentIsStacked) { text = '$text%'; } String callbackText = text; - TextStyle callbackTextStyle = - chartThemeData!.axisLabelTextStyle!.merge(labelStyle); + TextStyle callbackTextStyle = chartThemeData!.axisLabelTextStyle!.merge( + labelStyle, + ); if (axisLabelFormatter != null) { final AxisLabelRenderDetails details = AxisLabelRenderDetails( - current, callbackText, callbackTextStyle, this, null, null); + current, + callbackText, + callbackTextStyle, + this, + null, + null, + ); final ChartAxisLabel label = axisLabelFormatter!(details); callbackText = label.text; callbackTextStyle = callbackTextStyle.merge(label.textStyle); @@ -612,8 +632,11 @@ class RenderNumericAxis extends RenderChartAxis { ); } - textSize = - measureText(textAfterTrimming, callbackTextStyle, labelRotation); + textSize = measureText( + textAfterTrimming, + callbackTextStyle, + labelRotation, + ); final bool isTextTrimmed = callbackText != textAfterTrimming; final AxisLabel label = AxisLabel( callbackTextStyle, @@ -648,15 +671,19 @@ class RenderNumericAxis extends RenderChartAxis { final NumericMultiLevelLabel label = multiLevelLabels![i]; assert(label.start <= label.end); _multilevelLabels.add( - AxisMultilevelLabel(label.text, label.level, label.start, label.end)); + AxisMultilevelLabel(label.text, label.level, label.start, label.end), + ); } - _multilevelLabels.sort((AxisMultilevelLabel a, AxisMultilevelLabel b) => - a.level.compareTo(b.level)); - final void Function(AxisMultilevelLabel label) add = invertElementsOrder - ? (AxisMultilevelLabel label) => - visibleMultilevelLabels.insert(0, label) - : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); + _multilevelLabels.sort( + (AxisMultilevelLabel a, AxisMultilevelLabel b) => + a.level.compareTo(b.level), + ); + final void Function(AxisMultilevelLabel label) add = + invertElementsOrder + ? (AxisMultilevelLabel label) => + visibleMultilevelLabels.insert(0, label) + : (AxisMultilevelLabel label) => visibleMultilevelLabels.add(label); final int labelsLength = _multilevelLabels.length; final TextStyle textStyle = chartThemeData!.axisMultiLevelLabelTextStyle! @@ -669,7 +696,12 @@ class RenderNumericAxis extends RenderChartAxis { if (multiLevelLabelFormatter != null) { final MultiLevelLabelRenderDetails details = MultiLevelLabelRenderDetails( - current.level, desiredText, desiredTextStyle, i, name); + current.level, + desiredText, + desiredTextStyle, + i, + name, + ); final ChartAxisLabel label = multiLevelLabelFormatter!(details); desiredText = label.text; desiredTextStyle = textStyle.merge(label.textStyle); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/axis/plot_band.dart b/packages/syncfusion_flutter_charts/lib/src/charts/axis/plot_band.dart index 5d9a0e737..bcb60468e 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/axis/plot_band.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/axis/plot_band.dart @@ -654,7 +654,7 @@ class PlotBand { associatedAxisEnd, verticalTextAlignment, horizontalTextAlignment, - gradient + gradient, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/base.dart b/packages/syncfusion_flutter_charts/lib/src/charts/base.dart index b1caf67bd..ba75180e6 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/base.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/base.dart @@ -192,37 +192,42 @@ mixin ChartAreaUpdateMixin on RenderBox { class RenderChartArea extends RenderBox with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin - implements - MouseTrackerAnnotation { + RenderBoxContainerDefaultsMixin< + ChartAreaUpdateMixin, + ChartAreaParentData + > + implements MouseTrackerAnnotation { RenderChartArea() { final GestureArenaTeam team = GestureArenaTeam(); - _tapGestureRecognizer = TapGestureRecognizer() - ..team = team - ..onTapDown = _handleTapDown - ..onTapUp = _handleTapUp - ..gestureSettings = gestureSettings; - - _doubleTapGestureRecognizer = DoubleTapGestureRecognizer() - ..onDoubleTapDown = _handleDoubleTapDown - ..onDoubleTap = _handleDoubleTap - ..onDoubleTapCancel = _handleDoubleTapCancel - ..gestureSettings = gestureSettings; - - _longPressGestureRecognizer = LongPressGestureRecognizer() - ..team = team - ..onLongPressStart = _handleLongPressStart - ..onLongPressMoveUpdate = _handleLongPressMoveUpdate - ..onLongPressEnd = _handleLongPressEnd - ..gestureSettings = gestureSettings; - - _scaleGestureRecognizer = ScaleGestureRecognizer() - ..onStart = _handleScaleStart - ..onUpdate = _handleScaleUpdate - ..onEnd = _handleScaleEnd - ..gestureSettings = gestureSettings; + _tapGestureRecognizer = + TapGestureRecognizer() + ..team = team + ..onTapDown = _handleTapDown + ..onTapUp = _handleTapUp + ..gestureSettings = gestureSettings; + + _doubleTapGestureRecognizer = + DoubleTapGestureRecognizer() + ..onDoubleTapDown = _handleDoubleTapDown + ..onDoubleTap = _handleDoubleTap + ..onDoubleTapCancel = _handleDoubleTapCancel + ..gestureSettings = gestureSettings; + + _longPressGestureRecognizer = + LongPressGestureRecognizer() + ..team = team + ..onLongPressStart = _handleLongPressStart + ..onLongPressMoveUpdate = _handleLongPressMoveUpdate + ..onLongPressEnd = _handleLongPressEnd + ..gestureSettings = gestureSettings; + + _scaleGestureRecognizer = + ScaleGestureRecognizer() + ..onStart = _handleScaleStart + ..onUpdate = _handleScaleUpdate + ..onEnd = _handleScaleEnd + ..gestureSettings = gestureSettings; } void _initializeDragGestureRecognizers() { @@ -252,8 +257,9 @@ class RenderChartArea extends RenderBox if (!canHandleXYDrag || !canHandleXDrag || !canHandleYDrag) { if (zoomPanBehavior != null && + _behaviorArea != null && (zoomPanBehavior!.enablePinching || zoomPanBehavior!.enablePanning)) { - final ZoomMode zoomMode = zoomPanBehavior!.zoomMode; + final ZoomMode zoomMode = _behaviorArea!.effectiveZoomMode; canHandleXYDrag = zoomMode == ZoomMode.xy; canHandleXDrag = zoomMode == ZoomMode.x; canHandleYDrag = zoomMode == ZoomMode.y; @@ -263,19 +269,23 @@ class RenderChartArea extends RenderBox final GestureArenaTeam team = GestureArenaTeam(); final bool canHandleHorizontalDrag = canHandleXYDrag || canHandleXDrag; final bool canHandleVerticalDrag = canHandleXYDrag || canHandleYDrag; - _horizontalDragGestureRecognizer = HorizontalDragGestureRecognizer() - ..team = team - ..onStart = canHandleHorizontalDrag ? _handleHorizontalDragStart : null - ..onUpdate = canHandleHorizontalDrag ? _handleHorizontalDragUpdate : null - ..onEnd = canHandleHorizontalDrag ? _handleHorizontalDragEnd : null - ..gestureSettings = gestureSettings; - - _verticalDragGestureRecognizer = VerticalDragGestureRecognizer() - ..team = team - ..onStart = canHandleVerticalDrag ? _handleVerticalDragStart : null - ..onUpdate = canHandleVerticalDrag ? _handleVerticalDragUpdate : null - ..onEnd = canHandleVerticalDrag ? _handleVerticalDragEnd : null - ..gestureSettings = gestureSettings; + _horizontalDragGestureRecognizer = + HorizontalDragGestureRecognizer() + ..team = team + ..onStart = + canHandleHorizontalDrag ? _handleHorizontalDragStart : null + ..onUpdate = + canHandleHorizontalDrag ? _handleHorizontalDragUpdate : null + ..onEnd = canHandleHorizontalDrag ? _handleHorizontalDragEnd : null + ..gestureSettings = gestureSettings; + + _verticalDragGestureRecognizer = + VerticalDragGestureRecognizer() + ..team = team + ..onStart = canHandleVerticalDrag ? _handleVerticalDragStart : null + ..onUpdate = canHandleVerticalDrag ? _handleVerticalDragUpdate : null + ..onEnd = canHandleVerticalDrag ? _handleVerticalDragEnd : null + ..gestureSettings = gestureSettings; } GlobalKey? legendKey; @@ -433,7 +443,8 @@ class RenderChartArea extends RenderBox child = childParentData.previousSibling; } - isHit = isHit || + isHit = + isHit || onChartTouchInteractionDown != null || onChartTouchInteractionMove != null || onChartTouchInteractionUp != null; @@ -449,20 +460,38 @@ class RenderChartArea extends RenderBox bool _isDoubleTapGesture() { if (_plotArea != null) { final TooltipBehavior? tooltipBehavior = _plotArea!.tooltipBehavior; - final bool isSelection = + final bool hasSelection = _plotArea!.selectionGesture == ActivationMode.doubleTap; - final bool isTooltip = tooltipBehavior != null && + final bool hasTooltip = + tooltipBehavior != null && tooltipBehavior.enable && tooltipBehavior.activationMode == ActivationMode.doubleTap; - final bool isTrackball = trackballBehavior != null && + final bool hasTrackball = + trackballBehavior != null && trackballBehavior!.enable && trackballBehavior!.activationMode == ActivationMode.doubleTap; - final bool isCrosshair = crosshairBehavior != null && + final bool hasCrosshair = + crosshairBehavior != null && crosshairBehavior!.enable && crosshairBehavior!.activationMode == ActivationMode.doubleTap; - final bool isZoom = + final bool hasZooming = zoomPanBehavior != null && zoomPanBehavior!.enableDoubleTapZooming; - return isSelection || isTooltip || isTrackball || isCrosshair || isZoom; + + bool hasPointDoubleTap = false; + _plotArea!.visitChildren((RenderObject child) { + if (child is ChartSeriesRenderer && + child.isVisible() && + child.onPointDoubleTap != null) { + hasPointDoubleTap = true; + return; + } + }); + return hasSelection || + hasTooltip || + hasTrackball || + hasCrosshair || + hasZooming || + hasPointDoubleTap; } return false; } @@ -544,8 +573,9 @@ class RenderChartArea extends RenderBox if (!attached) { return; } - onChartTouchInteractionDown?.call(ChartTouchInteractionArgs() - ..position = globalToLocal(details.position)); + onChartTouchInteractionDown?.call( + ChartTouchInteractionArgs()..position = globalToLocal(details.position), + ); if (_isPlotAreaHit(details.position)) { _plotArea?.visitChildren((RenderObject child) { if (child is ChartSeriesRenderer) { @@ -560,8 +590,9 @@ class RenderChartArea extends RenderBox if (!attached) { return; } - onChartTouchInteractionMove?.call(ChartTouchInteractionArgs() - ..position = globalToLocal(details.position)); + onChartTouchInteractionMove?.call( + ChartTouchInteractionArgs()..position = globalToLocal(details.position), + ); } @protected @@ -595,8 +626,9 @@ class RenderChartArea extends RenderBox if (!attached) { return; } - onChartTouchInteractionUp?.call(ChartTouchInteractionArgs() - ..position = globalToLocal(details.position)); + onChartTouchInteractionUp?.call( + ChartTouchInteractionArgs()..position = globalToLocal(details.position), + ); if (_isPlotAreaHit(details.position)) { _plotArea?.visitChildren((RenderObject child) { if (child is ChartSeriesRenderer) { @@ -903,7 +935,9 @@ class CartesianChartArea extends ChartArea { @override void updateRenderObject( - BuildContext context, RenderCartesianChartArea renderObject) { + BuildContext context, + RenderCartesianChartArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isTransposed = isTransposed @@ -1108,8 +1142,10 @@ class RenderCartesianChartArea extends RenderChartArea { if (_cartesianAxes != null) { _cartesianAxes!._isGridLinePaint = true; - context.paintChild(_cartesianAxes!, - (_cartesianAxes!.parentData! as BoxParentData).offset + offset); + context.paintChild( + _cartesianAxes!, + (_cartesianAxes!.parentData! as BoxParentData).offset + offset, + ); } defaultPaint(context, offset); @@ -1202,7 +1238,9 @@ class ChartPlotArea extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderChartPlotArea renderObject) { + BuildContext context, + RenderChartPlotArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..backgroundColor = backgroundColor @@ -1228,9 +1266,7 @@ class ChartPlotArea extends MultiChildRenderObjectWidget { } class RenderChartPlotArea extends RenderStack with ChartAreaUpdateMixin { - RenderChartPlotArea({ - super.textDirection = TextDirection.ltr, - }); + RenderChartPlotArea({super.textDirection = TextDirection.ltr}); GlobalKey? legendKey; Legend? legend; @@ -1245,8 +1281,9 @@ class RenderChartPlotArea extends RenderStack with ChartAreaUpdateMixin { DataLabelTapCallback? onDataLabelTapped; ChartSelectionCallback? onSelectionChanged; - late final SelectionController selectionController = - SelectionController(this); + late final SelectionController selectionController = SelectionController( + this, + ); RenderBehaviorArea? behaviorArea; SfLocalizations? localizations; @@ -1426,8 +1463,12 @@ class RenderChartPlotArea extends RenderStack with ChartAreaUpdateMixin { @override void paint(PaintingContext context, Offset offset) { - final Rect bounds = - Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height); + final Rect bounds = Rect.fromLTWH( + offset.dx, + offset.dy, + size.width, + size.height, + ); if (backgroundColor != null) { context.canvas.drawRect( bounds, @@ -1524,7 +1565,9 @@ class CartesianChartPlotArea extends ChartPlotArea { @override void updateRenderObject( - BuildContext context, RenderCartesianChartPlotArea renderObject) { + BuildContext context, + RenderCartesianChartPlotArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isTransposed = isTransposed @@ -1659,17 +1702,20 @@ class RenderCartesianChartPlotArea extends RenderChartPlotArea { final StackingSeriesMixin stacked = yDependent as StackingSeriesMixin; final String groupName = stacked.groupName; - final int size = sbsDetails!.isNotEmpty && - groupingKeys.isNotEmpty && - groupingKeys.containsKey(groupName) - ? sbsDetails![groupingKeys[groupName]]!.length - : 0; + final int size = + sbsDetails!.isNotEmpty && + groupingKeys.isNotEmpty && + groupingKeys.containsKey(groupName) + ? sbsDetails![groupingKeys[groupName]]!.length + : 0; bool isSameType = false; StackingSeriesMixin? previous; if (size > 0) { - previous = sbsDetails![groupingKeys[groupName]]![size - 1] - as StackingSeriesMixin?; - isSameType = previous != null && + previous = + sbsDetails![groupingKeys[groupName]]![size - 1] + as StackingSeriesMixin?; + isSameType = + previous != null && previous.yAxis!.dependents.contains(yDependent) && previous.runtimeType == yDependent.runtimeType; } @@ -1809,10 +1855,12 @@ class RenderCartesianChartPlotArea extends RenderChartPlotArea { } final double space = (sbsMaxWidth - width) / seriesCount; - double start = startPosition + + double start = + startPosition + ((space * _primaryAxisAdjacentDataPointsMinDiff) / 2); - end = start + + end = + start + ((width / seriesCount) * _primaryAxisAdjacentDataPointsMinDiff); final double delta = end - start; final double spacing = sbs.spacing * delta; @@ -1958,11 +2006,11 @@ class CartesianAxes extends MultiChildRenderObjectWidget { @override RenderCartesianAxes createRenderObject(BuildContext context) { return RenderCartesianAxes( - vsync: vsync, - enableAxisAnimation: enableAxisAnimation, - isTransposed: isTransposed, - chartThemeData: chartThemeData, - ) + vsync: vsync, + enableAxisAnimation: enableAxisAnimation, + isTransposed: isTransposed, + chartThemeData: chartThemeData, + ) ..onAxisLabelTapped = onAxisLabelTapped ..indicators = indicators ..onActualRangeChanged = onActualRangeChanged; @@ -1970,7 +2018,9 @@ class CartesianAxes extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderCartesianAxes renderObject) { + BuildContext context, + RenderCartesianAxes renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..vsync = vsync @@ -1986,18 +2036,20 @@ class CartesianAxes extends MultiChildRenderObjectWidget { class RenderCartesianAxes extends RenderBox with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin, + RenderBoxContainerDefaultsMixin< + RenderChartAxis, + CartesianAxesParentData + >, ChartAreaUpdateMixin { RenderCartesianAxes({ required TickerProvider vsync, required bool enableAxisAnimation, required bool isTransposed, required SfChartThemeData chartThemeData, - }) : _vsync = vsync, - _enableAxisAnimation = enableAxisAnimation, - _isTransposed = isTransposed, - _chartThemeData = chartThemeData; + }) : _vsync = vsync, + _enableAxisAnimation = enableAxisAnimation, + _isTransposed = isTransposed, + _chartThemeData = chartThemeData; RenderBehaviorArea? behaviorArea; BoxConstraints? _plotAreaConstraints; Offset plotAreaOffset = Offset.zero; @@ -2218,7 +2270,6 @@ class RenderCartesianAxes extends RenderBox topAxesHeight = 0; bottomAxesHeight = 0; for (final RenderChartAxis axis in horizontalAxes) { - final double extent = axis.labelsExtent ?? spaceBetweenMultipleAxes; final CartesianAxesParentData childParentData = axis.parentData! as CartesianAxesParentData; childParentData.isResized = hasSize && size != constraints.biggest; @@ -2228,16 +2279,14 @@ class RenderCartesianAxes extends RenderBox if (axis.opposedPosition) { topAxesHeight += axisHeight; // Apply the padding(gap) between the multiple axes. - if (axis.isVisible && - (topAxesHeight > axisHeight || axis.labelsExtent != null)) { - topAxesHeight += extent; + if (axis.isVisible && topAxesHeight > axisHeight) { + topAxesHeight += spaceBetweenMultipleAxes; } } else { bottomAxesHeight += axisHeight; // Apply the padding(gap) between the multiple axes. - if (axis.isVisible && - (bottomAxesHeight > axisHeight || axis.labelsExtent != null)) { - bottomAxesHeight += extent; + if (axis.isVisible && bottomAxesHeight > axisHeight) { + bottomAxesHeight += spaceBetweenMultipleAxes; } } } @@ -2249,7 +2298,6 @@ class RenderCartesianAxes extends RenderBox leftAxesWidth = 0; rightAxesWidth = 0; for (final RenderChartAxis axis in verticalAxes) { - final double extent = axis.labelsExtent ?? spaceBetweenMultipleAxes; final CartesianAxesParentData childParentData = axis.parentData! as CartesianAxesParentData; childParentData.isResized = hasSize && size != constraints.biggest; @@ -2259,16 +2307,14 @@ class RenderCartesianAxes extends RenderBox if (axis.opposedPosition) { rightAxesWidth += axisWidth; // Apply the padding(gap) between the multiple axes. - if (axis.isVisible && - (rightAxesWidth > axisWidth || axis.labelsExtent != null)) { - rightAxesWidth += extent; + if (axis.isVisible && rightAxesWidth > axisWidth) { + rightAxesWidth += spaceBetweenMultipleAxes; } } else { leftAxesWidth += axisWidth; // Apply the padding(gap) between the multiple axes. - if (axis.isVisible && - (leftAxesWidth > axisWidth || axis.labelsExtent != null)) { - leftAxesWidth += extent; + if (axis.isVisible && leftAxesWidth > axisWidth) { + leftAxesWidth += spaceBetweenMultipleAxes; } } } @@ -2324,33 +2370,37 @@ class RenderCartesianAxes extends RenderBox } void _arrangeVerticalAxes( - Rect plotAreaBounds, List verticalAxes) { + Rect plotAreaBounds, + List verticalAxes, + ) { Offset leftAxisPosition = plotAreaBounds.topLeft; Offset rightAxisPosition = plotAreaBounds.topRight; for (final RenderChartAxis axis in verticalAxes) { final double? crossing = _crossValue(axis); final CartesianAxesParentData childParentData = axis.parentData! as CartesianAxesParentData; - final double extent = axis.labelsExtent ?? spaceBetweenMultipleAxes; if (axis.opposedPosition) { axis.invertElementsOrder = false; if (crossing != null) { if (crossing + axis.size.width > plotAreaBounds.right) { axis.invertElementsOrder = true; - childParentData.offset = - Offset(crossing - axis.size.width, plotAreaBounds.top); + childParentData.offset = Offset( + crossing - axis.size.width, + plotAreaBounds.top, + ); } else { childParentData.offset = Offset(crossing, plotAreaBounds.top); } } else { - childParentData.offset = rightAxisPosition; - rightAxisPosition = rightAxisPosition.translate(axis.size.width, 0); // Move the axis with padding value for multiple axes. - if (axis.isVisible && - (rightAxisPosition != plotAreaBounds.topRight || - axis.labelsExtent != null)) { - rightAxisPosition = rightAxisPosition.translate(extent, 0); + if (axis.isVisible && rightAxisPosition != plotAreaBounds.topRight) { + rightAxisPosition = rightAxisPosition.translate( + spaceBetweenMultipleAxes, + 0, + ); } + childParentData.offset = rightAxisPosition; + rightAxisPosition = rightAxisPosition.translate(axis.size.width, 0); } } else { axis.invertElementsOrder = true; @@ -2363,29 +2413,33 @@ class RenderCartesianAxes extends RenderBox childParentData.offset = Offset(y, plotAreaBounds.top); } } else { - childParentData.offset = - leftAxisPosition.translate(-axis.size.width, 0); - leftAxisPosition = childParentData.offset; // Move the axis with padding value for multiple axes. - if (axis.isVisible && - (leftAxisPosition != plotAreaBounds.topLeft || - axis.labelsExtent != null)) { - leftAxisPosition = leftAxisPosition.translate(-extent, 0); + if (axis.isVisible && leftAxisPosition != plotAreaBounds.topLeft) { + leftAxisPosition = leftAxisPosition.translate( + -spaceBetweenMultipleAxes, + 0, + ); } + childParentData.offset = leftAxisPosition.translate( + -axis.size.width, + 0, + ); + leftAxisPosition = childParentData.offset; } } } } void _arrangeHorizontalAxes( - Rect plotAreaBounds, List horizontalAxes) { + Rect plotAreaBounds, + List horizontalAxes, + ) { Offset topAxisPosition = plotAreaBounds.topLeft; Offset bottomAxisPosition = plotAreaBounds.bottomLeft; for (final RenderChartAxis axis in horizontalAxes) { final double? crossing = _crossValue(axis); final CartesianAxesParentData childParentData = axis.parentData! as CartesianAxesParentData; - final double extent = axis.labelsExtent ?? spaceBetweenMultipleAxes; if (axis.opposedPosition) { axis.invertElementsOrder = true; if (crossing != null) { @@ -2397,36 +2451,45 @@ class RenderCartesianAxes extends RenderBox childParentData.offset = Offset(plotAreaBounds.left, y); } } else { - childParentData.offset = - topAxisPosition.translate(0, -axis.size.height); - topAxisPosition = childParentData.offset; // Move the axis with padding value for multiple axes. - if (axis.isVisible && - (topAxisPosition != plotAreaBounds.topLeft || - axis.labelsExtent != null)) { - topAxisPosition = topAxisPosition.translate(0, -extent); + if (axis.isVisible && topAxisPosition != plotAreaBounds.topLeft) { + topAxisPosition = topAxisPosition.translate( + 0, + -spaceBetweenMultipleAxes, + ); } + childParentData.offset = topAxisPosition.translate( + 0, + -axis.size.height, + ); + topAxisPosition = childParentData.offset; } } else { axis.invertElementsOrder = false; if (crossing != null) { if (crossing + axis.size.height > plotAreaBounds.bottom) { axis.invertElementsOrder = true; - childParentData.offset = - Offset(plotAreaBounds.left, crossing - axis.size.height); + childParentData.offset = Offset( + plotAreaBounds.left, + crossing - axis.size.height, + ); } else { childParentData.offset = Offset(plotAreaBounds.left, crossing); } } else { - childParentData.offset = bottomAxisPosition; - bottomAxisPosition = - bottomAxisPosition.translate(0, axis.size.height); // Move the axis with padding value for multiple axes. if (axis.isVisible && - (bottomAxisPosition != plotAreaBounds.bottomLeft || - axis.labelsExtent != null)) { - bottomAxisPosition = bottomAxisPosition.translate(0, extent); + bottomAxisPosition != plotAreaBounds.bottomLeft) { + bottomAxisPosition = bottomAxisPosition.translate( + 0, + spaceBetweenMultipleAxes, + ); } + childParentData.offset = bottomAxisPosition; + bottomAxisPosition = bottomAxisPosition.translate( + 0, + axis.size.height, + ); } } } @@ -2436,8 +2499,9 @@ class RenderCartesianAxes extends RenderBox if (axis.placeLabelsNearAxisLine && axis.crossesAt != null && axis.associatedAxis != null) { - return axis.associatedAxis! - .pointToPixel(axis.associatedAxis!.actualValue(axis.crossesAt)); + return axis.associatedAxis!.pointToPixel( + axis.associatedAxis!.actualValue(axis.crossesAt), + ); } return null; @@ -2463,7 +2527,9 @@ class RenderCartesianAxes extends RenderBox while (child != null) { child.renderType = AxisRender.gridLines; context.paintChild( - child, (child.parentData! as BoxParentData).offset + offset); + child, + (child.parentData! as BoxParentData).offset + offset, + ); child = childAfter(child); } @@ -2481,14 +2547,19 @@ class RenderCartesianAxes extends RenderBox _isGridLinePaint = false; } - void _paintPlotBands(PaintingContext context, Offset offset, - {bool onSeries = false}) { + void _paintPlotBands( + PaintingContext context, + Offset offset, { + bool onSeries = false, + }) { RenderChartAxis? child = firstChild; while (child != null) { child.renderType = onSeries ? AxisRender.overPlotBand : AxisRender.underPlotBand; context.paintChild( - child, (child.parentData! as BoxParentData).offset + offset); + child, + (child.parentData! as BoxParentData).offset + offset, + ); child = childAfter(child); } } @@ -2562,7 +2633,9 @@ class CircularChartPlotArea extends ChartPlotArea { @override void updateRenderObject( - BuildContext context, RenderCircularChartPlotArea renderObject) { + BuildContext context, + RenderCircularChartPlotArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..centerX = centerX @@ -2810,7 +2883,9 @@ class IndicatorArea extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderIndicatorArea renderObject) { + BuildContext context, + RenderIndicatorArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..indicators = indicators @@ -2908,7 +2983,9 @@ class AnnotationArea extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderAnnotationArea renderObject) { + BuildContext context, + RenderAnnotationArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..annotations = annotations @@ -2998,13 +3075,21 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { child.layout(constraints, parentUsesSize: true); final Size childSize = child.size; final double x = _horizontalAlignment( - annotation.horizontalAlignment, offset.dx, childSize); + annotation.horizontalAlignment, + offset.dx, + childSize, + ); final double y = _verticalAlignment( - annotation.verticalAlignment, offset.dy, childSize); + annotation.verticalAlignment, + offset.dy, + childSize, + ); if (childParentData != null) { childParentData.offset = Offset(x, y); childParentData.isVisible = _isVisible( - annotation, _isBeyondRegion(annotation, x, y, childSize)); + annotation, + _isBeyondRegion(annotation, x, y, childSize), + ); child = childParentData.nextSibling; } @@ -3017,9 +3102,16 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { final RenderChartAxis? yAxis = _yAxis(annotation); if (xAxis != null && yAxis != null) { final Offset position = rawValueToPixelPoint( - annotation.x, annotation.y, xAxis, yAxis, isTransposed); + annotation.x, + annotation.y, + xAxis, + yAxis, + isTransposed, + ); return Offset( - position.dx + _plotAreaOffset.dx, position.dy + _plotAreaOffset.dy); + position.dx + _plotAreaOffset.dx, + position.dy + _plotAreaOffset.dy, + ); } return Offset.zero; } @@ -3103,7 +3195,10 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { } double _horizontalAlignment( - ChartAlignment horizontalAlignment, double xPosition, Size childSize) { + ChartAlignment horizontalAlignment, + double xPosition, + Size childSize, + ) { final double size = childSize.width; switch (horizontalAlignment) { case ChartAlignment.near: @@ -3116,7 +3211,10 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { } double _verticalAlignment( - ChartAlignment verticalAlignment, double yPosition, Size childSize) { + ChartAlignment verticalAlignment, + double yPosition, + Size childSize, + ) { final double size = childSize.height; switch (verticalAlignment) { case ChartAlignment.near: @@ -3129,7 +3227,11 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { } bool _isBeyondRegion( - CartesianChartAnnotation annotation, double x, double y, Size size) { + CartesianChartAnnotation annotation, + double x, + double y, + Size size, + ) { final Rect childBounds = Rect.fromLTWH(x, y, size.width, size.height); switch (annotation.region) { case AnnotationRegion.chart: @@ -3162,9 +3264,11 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { context.canvas.save(); final CartesianChartAnnotation annotation = _annotations![index]; if (annotation.clip == ChartClipBehavior.clip) { - context.canvas.clipRect(annotation.region == AnnotationRegion.chart - ? paintBounds - : _plotAreaBounds); + context.canvas.clipRect( + annotation.region == AnnotationRegion.chart + ? paintBounds + : _plotAreaBounds, + ); } final AnnotationParentData childParentData = @@ -3181,11 +3285,7 @@ class RenderAnnotationArea extends RenderStack with ChartAreaUpdateMixin { } class CircularAnnotationArea extends MultiChildRenderObjectWidget { - const CircularAnnotationArea({ - super.key, - this.annotations, - super.children, - }); + const CircularAnnotationArea({super.key, this.annotations, super.children}); final List? annotations; @@ -3196,7 +3296,9 @@ class CircularAnnotationArea extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderCircularAnnotationArea renderObject) { + BuildContext context, + RenderCircularAnnotationArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.annotations = annotations; } @@ -3232,8 +3334,11 @@ class RenderCircularAnnotationArea extends RenderStack final CircularChartAnnotation annotation = _annotations![index]; final double radius = percentToValue(annotation.radius, minSize)!; - final Offset angle = calculateOffset(annotation.angle.toDouble(), radius, - Offset(size.width / 2, size.height / 2)); + final Offset angle = calculateOffset( + annotation.angle.toDouble(), + radius, + Offset(size.width / 2, size.height / 2), + ); final Offset offset = Offset(angle.dx, angle.dy); final double width = percentToValue(annotations![index].width, minSize)!; final double height = @@ -3241,10 +3346,11 @@ class RenderCircularAnnotationArea extends RenderStack if (height > 0 && width > 0) { final BoxConstraints childConstraints = BoxConstraints( - minHeight: height, - minWidth: width, - maxHeight: height, - maxWidth: width); + minHeight: height, + minWidth: width, + maxHeight: height, + maxWidth: width, + ); child.layout(childConstraints, parentUsesSize: true); } else { child.layout(constraints, parentUsesSize: true); @@ -3252,9 +3358,15 @@ class RenderCircularAnnotationArea extends RenderStack final Size childSize = child.size; final double x = _horizontalAlignment( - annotation.horizontalAlignment, offset.dx, childSize); + annotation.horizontalAlignment, + offset.dx, + childSize, + ); final double y = _verticalAlignment( - annotation.verticalAlignment, offset.dy, childSize); + annotation.verticalAlignment, + offset.dy, + childSize, + ); if (childParentData != null) { childParentData.offset = Offset(x, y); child = childParentData.nextSibling; @@ -3264,7 +3376,10 @@ class RenderCircularAnnotationArea extends RenderStack } double _horizontalAlignment( - ChartAlignment horizontalAlignment, double xPosition, Size childSize) { + ChartAlignment horizontalAlignment, + double xPosition, + Size childSize, + ) { final double size = childSize.width; switch (horizontalAlignment) { case ChartAlignment.near: @@ -3277,7 +3392,10 @@ class RenderCircularAnnotationArea extends RenderStack } double _verticalAlignment( - ChartAlignment verticalAlignment, double yPosition, Size childSize) { + ChartAlignment verticalAlignment, + double yPosition, + Size childSize, + ) { final double size = childSize.height; switch (verticalAlignment) { case ChartAlignment.near: @@ -3324,7 +3442,9 @@ class LoadingIndicator extends CustomConstrainedLayoutBuilder { @override void updateRenderObject( - BuildContext context, RenderLoadingIndicator renderObject) { + BuildContext context, + RenderLoadingIndicator renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isTransposed = isTransposed @@ -3406,9 +3526,10 @@ class RenderLoadingIndicator extends RenderProxyBox void _handlePlotAreaSwipe(Velocity swipeVelocity) { final double minsSwipeVelocity = _isDesktop ? 0.0 : 240.0; - final double velocity = isTransposed - ? swipeVelocity.pixelsPerSecond.dy - : swipeVelocity.pixelsPerSecond.dx; + final double velocity = + isTransposed + ? swipeVelocity.pixelsPerSecond.dy + : swipeVelocity.pixelsPerSecond.dx; if (velocity.abs() < minsSwipeVelocity) { _startPosition = Offset.zero; _endPosition = Offset.zero; @@ -3417,32 +3538,35 @@ class RenderLoadingIndicator extends RenderProxyBox ChartSwipeDirection direction; if (isTransposed) { - direction = _isDesktop - ? _endPosition.dy > _startPosition.dy - ? ChartSwipeDirection.end - : ChartSwipeDirection.start - : velocity > 0 + direction = + _isDesktop + ? _endPosition.dy > _startPosition.dy + ? ChartSwipeDirection.end + : ChartSwipeDirection.start + : velocity > 0 ? ChartSwipeDirection.start : ChartSwipeDirection.end; } else { - direction = _isDesktop - ? _endPosition.dx > _startPosition.dx - ? ChartSwipeDirection.start - : ChartSwipeDirection.end - : velocity > 0 + direction = + _isDesktop + ? _endPosition.dx > _startPosition.dx + ? ChartSwipeDirection.start + : ChartSwipeDirection.end + : velocity > 0 ? ChartSwipeDirection.start : ChartSwipeDirection.end; } if (isInversed) { - direction = direction == ChartSwipeDirection.start - ? ChartSwipeDirection.end - : ChartSwipeDirection.start; + direction = + direction == ChartSwipeDirection.start + ? ChartSwipeDirection.end + : ChartSwipeDirection.start; } final bool verticallyDragging = (_endPosition.dy - _startPosition.dy).abs() > - (_endPosition.dx - _startPosition.dx).abs(); + (_endPosition.dx - _startPosition.dx).abs(); if ((verticallyDragging && !isTransposed) || (!verticallyDragging && isTransposed)) { @@ -3563,8 +3687,12 @@ class ChartBehavior { /// Called to customize each behaviors with given context at the given offset. @protected - void onPaint(PaintingContext context, Offset offset, - SfChartThemeData chartThemeData, ThemeData themeData) {} + void onPaint( + PaintingContext context, + Offset offset, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) {} } typedef SelectionCallback = void Function(int seriesIndex, int pointIndex); @@ -3596,8 +3724,10 @@ class SelectionController { void resetSelection() { _hasSelectedIndexes = false; - selectedDataPoints - .forEach((int previousSelectedSeriesIndex, List values) { + selectedDataPoints.forEach(( + int previousSelectedSeriesIndex, + List values, + ) { final int length = values.length; for (int i = 0; i < length; i++) { _notifyDeselectionListeners(previousSelectedSeriesIndex, values[i]); @@ -3637,7 +3767,7 @@ class SelectionController { if (forceSelection) { final bool existingSelected = selectedDataPoints[seriesIndex]?.contains(segmentPointIndex) ?? - false; + false; if (existingSelected) { return; } @@ -3682,8 +3812,10 @@ class SelectionController { selectedPointIndex = segmentPointIndex; } } else { - selectedDataPoints - .forEach((int previousSelectedSeriesIndex, List values) { + selectedDataPoints.forEach(( + int previousSelectedSeriesIndex, + List values, + ) { if (values.isNotEmpty) { deselectedSeriesIndex = previousSelectedSeriesIndex; deselectedPointIndex = values[0]; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/crosshair.dart b/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/crosshair.dart index 995360750..4135e1a68 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/crosshair.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/crosshair.dart @@ -285,7 +285,7 @@ class CrosshairBehavior extends ChartBehavior { lineColor, lineWidth, shouldAlwaysShow, - hideDelay + hideDelay, ]; return Object.hashAll(values); } @@ -308,16 +308,26 @@ class CrosshairBehavior extends ChartBehavior { assert(!y.isNaN); if (coordinateUnit == 'point') { _position = rawValueToPixelPoint( - x, y, parent.xAxis, parent.yAxis, parent.isTransposed); + x, + y, + parent.xAxis, + parent.yAxis, + parent.isTransposed, + ); } else if (coordinateUnit == 'pixel') { if (x is num) { _position = Offset(x.toDouble(), y); } else { _position = Offset( - rawValueToPixelPoint( - x, y, parent.xAxis, parent.yAxis, parent.isTransposed) - .dx, - y); + rawValueToPixelPoint( + x, + y, + parent.xAxis, + parent.yAxis, + parent.isTransposed, + ).dx, + y, + ); } } @@ -467,11 +477,13 @@ class CrosshairBehavior extends ChartBehavior { final int hideDelayDuration = hideDelay > 0 ? hideDelay.toInt() : doubleTapHideDelay; _crosshairHideTimer?.cancel(); - _crosshairHideTimer = - Timer(Duration(milliseconds: hideDelayDuration), () { - _crosshairHideTimer = null; - hide(); - }); + _crosshairHideTimer = Timer( + Duration(milliseconds: hideDelayDuration), + () { + _crosshairHideTimer = null; + hide(); + }, + ); } } @@ -495,7 +507,9 @@ class CrosshairBehavior extends ChartBehavior { } void _calculateTooltipLabelAndPositions( - RenderBehaviorArea parent, RenderCartesianAxes cartesianAxes) { + RenderBehaviorArea parent, + RenderCartesianAxes cartesianAxes, + ) { final Rect plotAreaBounds = parent.paintBounds; if (plotAreaBounds.contains(_position!)) { _resetCrosshairHolders(); @@ -514,7 +528,9 @@ class CrosshairBehavior extends ChartBehavior { final Offset parentDataOffset = (child.parentData! as BoxParentData).offset; final Offset axisOffset = parentDataOffset.translate( - -plotAreaOffset.dx, -plotAreaOffset.dy); + -plotAreaOffset.dx, + -plotAreaOffset.dy, + ); final Rect axisBounds = axisOffset & child.size; if (child.isVertical) { @@ -566,20 +582,34 @@ class CrosshairBehavior extends ChartBehavior { final String tooltipPosition = axis.opposedPosition ? 'Top' : 'Bottom'; final Rect tooltipRect = _calculateTooltipRect( - tooltipPosition, position, labelSize, axisBounds, arrowLength); + tooltipPosition, + position, + labelSize, + axisBounds, + arrowLength, + ); final Rect validatedRect = _validateRectBounds(tooltipRect, axisBounds); _validateRectXPosition(validatedRect, plotAreaBounds); - final RRect tooltipRRect = - RRect.fromRectAndRadius(validatedRect, Radius.circular(borderRadius)); - - final Path tooltipAndArrowPath = Path() - ..addRRect(tooltipRRect) - ..addPath( - _tooltipArrowHeadPath( - tooltipPosition, tooltipRRect, position, arrowLength, arrowWidth), - Offset.zero); + final RRect tooltipRRect = RRect.fromRectAndRadius( + validatedRect, + Radius.circular(borderRadius), + ); + + final Path tooltipAndArrowPath = + Path() + ..addRRect(tooltipRRect) + ..addPath( + _tooltipArrowHeadPath( + tooltipPosition, + tooltipRRect, + position, + arrowLength, + arrowWidth, + ), + Offset.zero, + ); _horizontalPaths.add(tooltipAndArrowPath); _horizontalLabels.add(label); @@ -603,20 +633,34 @@ class CrosshairBehavior extends ChartBehavior { final String tooltipPosition = axis.opposedPosition ? 'Right' : 'Left'; final Rect tooltipRect = _calculateTooltipRect( - tooltipPosition, position, labelSize, axisBounds, arrowLength); + tooltipPosition, + position, + labelSize, + axisBounds, + arrowLength, + ); final Rect validatedRect = _validateRectBounds(tooltipRect, axisBounds); _validateRectYPosition(validatedRect, plotAreaBounds); - final RRect tooltipRRect = - RRect.fromRectAndRadius(validatedRect, Radius.circular(borderRadius)); - - final Path tooltipAndArrowPath = Path() - ..addRRect(tooltipRRect) - ..addPath( - _tooltipArrowHeadPath( - tooltipPosition, tooltipRRect, position, arrowLength, arrowWidth), - Offset.zero); + final RRect tooltipRRect = RRect.fromRectAndRadius( + validatedRect, + Radius.circular(borderRadius), + ); + + final Path tooltipAndArrowPath = + Path() + ..addRRect(tooltipRRect) + ..addPath( + _tooltipArrowHeadPath( + tooltipPosition, + tooltipRRect, + position, + arrowLength, + arrowWidth, + ), + Offset.zero, + ); _verticalPaths.add(tooltipAndArrowPath); _verticalLabels.add(label); @@ -624,9 +668,15 @@ class CrosshairBehavior extends ChartBehavior { } num _actualXValue( - RenderChartAxis axis, Offset position, Rect plotAreaBounds) { - return axis.pixelToPoint(axis.paintBounds, - position.dx - plotAreaBounds.left, position.dy - plotAreaBounds.top); + RenderChartAxis axis, + Offset position, + Rect plotAreaBounds, + ) { + return axis.pixelToPoint( + axis.paintBounds, + position.dx - plotAreaBounds.left, + position.dy - plotAreaBounds.top, + ); } num _actualYValue(RenderChartAxis axis, Offset position) { @@ -634,7 +684,10 @@ class CrosshairBehavior extends ChartBehavior { } String _triggerCrosshairCallback( - RenderChartAxis axis, String label, num value) { + RenderChartAxis axis, + String label, + num value, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (parent != null && parent.onCrosshairPositionChanging != null && @@ -680,16 +733,18 @@ class CrosshairBehavior extends ChartBehavior { Rect _validateRectXPosition(Rect labelRect, Rect axisClipRect) { if (labelRect.right >= axisClipRect.right) { return Rect.fromLTRB( - labelRect.left - (labelRect.right - axisClipRect.right), - labelRect.top, - axisClipRect.right, - labelRect.bottom); + labelRect.left - (labelRect.right - axisClipRect.right), + labelRect.top, + axisClipRect.right, + labelRect.bottom, + ); } else if (labelRect.left <= axisClipRect.left) { return Rect.fromLTRB( - axisClipRect.left, - labelRect.top, - labelRect.right + (axisClipRect.left - labelRect.left), - labelRect.bottom); + axisClipRect.left, + labelRect.top, + labelRect.right + (axisClipRect.left - labelRect.left), + labelRect.bottom, + ); } return labelRect; } @@ -697,55 +752,74 @@ class CrosshairBehavior extends ChartBehavior { Rect _validateRectYPosition(Rect labelRect, Rect axisClipRect) { if (labelRect.bottom >= axisClipRect.bottom) { return Rect.fromLTRB( - labelRect.left, - labelRect.top - (labelRect.bottom - axisClipRect.bottom), - labelRect.right, - axisClipRect.bottom); + labelRect.left, + labelRect.top - (labelRect.bottom - axisClipRect.bottom), + labelRect.right, + axisClipRect.bottom, + ); } else if (labelRect.top <= axisClipRect.top) { - return Rect.fromLTRB(labelRect.left, axisClipRect.top, labelRect.right, - labelRect.bottom + (axisClipRect.top - labelRect.top)); + return Rect.fromLTRB( + labelRect.left, + axisClipRect.top, + labelRect.right, + labelRect.bottom + (axisClipRect.top - labelRect.top), + ); } return labelRect; } - Rect _calculateTooltipRect(String axis, Offset position, Size labelSize, - Rect axisBounds, double arrowLength) { + Rect _calculateTooltipRect( + String axis, + Offset position, + Size labelSize, + Rect axisBounds, + double arrowLength, + ) { final double labelWidthWithPadding = labelSize.width + crosshairPadding; final double labelHeightWithPadding = labelSize.height + crosshairPadding; switch (axis) { case 'Left': return Rect.fromLTWH( - axisBounds.right - labelWidthWithPadding - arrowLength, - position.dy - (labelHeightWithPadding / 2), - labelWidthWithPadding, - labelHeightWithPadding); + axisBounds.right - labelWidthWithPadding - arrowLength, + position.dy - (labelHeightWithPadding / 2), + labelWidthWithPadding, + labelHeightWithPadding, + ); case 'Right': return Rect.fromLTWH( - axisBounds.left + arrowLength, - position.dy - (labelHeightWithPadding / 2), - labelSize.width + crosshairPadding, - labelHeightWithPadding); + axisBounds.left + arrowLength, + position.dy - (labelHeightWithPadding / 2), + labelSize.width + crosshairPadding, + labelHeightWithPadding, + ); case 'Top': return Rect.fromLTWH( - position.dx - (labelWidthWithPadding / 2), - axisBounds.bottom - labelHeightWithPadding - arrowLength, - labelWidthWithPadding, - labelHeightWithPadding); + position.dx - (labelWidthWithPadding / 2), + axisBounds.bottom - labelHeightWithPadding - arrowLength, + labelWidthWithPadding, + labelHeightWithPadding, + ); case 'Bottom': return Rect.fromLTWH( - position.dx - (labelWidthWithPadding / 2), - axisBounds.top + arrowLength, - labelWidthWithPadding, - labelSize.height + crosshairPadding); + position.dx - (labelWidthWithPadding / 2), + axisBounds.top + arrowLength, + labelWidthWithPadding, + labelSize.height + crosshairPadding, + ); } return Rect.zero; } - Path _tooltipArrowHeadPath(String axis, RRect tooltipRect, Offset position, - double arrowLength, double arrowWidth) { + Path _tooltipArrowHeadPath( + String axis, + RRect tooltipRect, + Offset position, + double arrowLength, + double arrowWidth, + ) { final Path arrowPath = Path(); final double tooltipLeft = tooltipRect.left; final double tooltipRight = tooltipRect.right; @@ -756,9 +830,13 @@ class CrosshairBehavior extends ChartBehavior { switch (axis) { case 'Left': arrowPath.moveTo( - tooltipRight, tooltipTop + rectHalfHeight - arrowWidth); + tooltipRight, + tooltipTop + rectHalfHeight - arrowWidth, + ); arrowPath.lineTo( - tooltipRight, tooltipBottom - rectHalfHeight + arrowWidth); + tooltipRight, + tooltipBottom - rectHalfHeight + arrowWidth, + ); arrowPath.lineTo(tooltipRight + arrowLength, position.dy); arrowPath.close(); return arrowPath; @@ -766,7 +844,9 @@ class CrosshairBehavior extends ChartBehavior { case 'Right': arrowPath.moveTo(tooltipLeft, tooltipTop + rectHalfHeight - arrowWidth); arrowPath.lineTo( - tooltipLeft, tooltipBottom - rectHalfHeight + arrowWidth); + tooltipLeft, + tooltipBottom - rectHalfHeight + arrowWidth, + ); arrowPath.lineTo(tooltipLeft - arrowLength, position.dy); arrowPath.close(); return arrowPath; @@ -774,18 +854,26 @@ class CrosshairBehavior extends ChartBehavior { case 'Top': arrowPath.moveTo(position.dx, tooltipBottom + arrowLength); arrowPath.lineTo( - (tooltipRight - rectHalfWidth) + arrowWidth, tooltipBottom); + (tooltipRight - rectHalfWidth) + arrowWidth, + tooltipBottom, + ); arrowPath.lineTo( - (tooltipLeft + rectHalfWidth) - arrowWidth, tooltipBottom); + (tooltipLeft + rectHalfWidth) - arrowWidth, + tooltipBottom, + ); arrowPath.close(); return arrowPath; case 'Bottom': arrowPath.moveTo(position.dx, tooltipTop - arrowLength); arrowPath.lineTo( - (tooltipRight - rectHalfWidth) + arrowWidth, tooltipTop); + (tooltipRight - rectHalfWidth) + arrowWidth, + tooltipTop, + ); arrowPath.lineTo( - (tooltipLeft + rectHalfWidth) - arrowWidth, tooltipTop); + (tooltipLeft + rectHalfWidth) - arrowWidth, + tooltipTop, + ); arrowPath.close(); return arrowPath; } @@ -794,15 +882,18 @@ class CrosshairBehavior extends ChartBehavior { Offset _textPosition(RRect tooltipRect, Size labelSize) { return Offset( - (tooltipRect.left + tooltipRect.width / 2) - labelSize.width / 2, - (tooltipRect.top + tooltipRect.height / 2) - labelSize.height / 2); + (tooltipRect.left + tooltipRect.width / 2) - labelSize.width / 2, + (tooltipRect.top + tooltipRect.height / 2) - labelSize.height / 2, + ); } String _resultantString(RenderChartAxis axis, num actualValue) { final String resultantString = _interactiveTooltipLabel(actualValue, axis); if (axis.interactiveTooltip.format != null) { - return axis.interactiveTooltip.format! - .replaceAll('{value}', resultantString); + return axis.interactiveTooltip.format!.replaceAll( + '{value}', + resultantString, + ); } else { return resultantString; } @@ -825,35 +916,55 @@ class CrosshairBehavior extends ChartBehavior { final num index = value < 0 ? 0 : value; final List labels = axis.labels; final int labelsLength = labels.length; - final int milliseconds = labels[(index.round() >= labelsLength - ? (index.round() > labelsLength ? labelsLength - 1 : index - 1) - : index) - .round()]; + final int milliseconds = + labels[(index.round() >= labelsLength + ? (index.round() > labelsLength + ? labelsLength - 1 + : index - 1) + : index) + .round()]; final num interval = axis.visibleRange!.minimum.ceil(); final num previousInterval = labels.isNotEmpty ? labels[labelsLength - 1] : interval; - final DateFormat dateFormat = axis.dateFormat ?? + final DateFormat dateFormat = + axis.dateFormat ?? dateTimeCategoryAxisLabelFormat( - axis, interval.toInt(), previousInterval.toInt()); - return dateFormat - .format(DateTime.fromMillisecondsSinceEpoch(milliseconds)); + axis, + interval.toInt(), + previousInterval.toInt(), + ); + return dateFormat.format( + DateTime.fromMillisecondsSinceEpoch(milliseconds), + ); } else if (axis is RenderDateTimeAxis) { final num interval = axis.visibleRange!.minimum.ceil(); final List visibleLabels = axis.visibleLabels; - final num previousInterval = visibleLabels.isNotEmpty - ? visibleLabels[visibleLabels.length - 1].value - : interval; - final DateFormat dateFormat = axis.dateFormat ?? + final num previousInterval = + visibleLabels.isNotEmpty + ? visibleLabels[visibleLabels.length - 1].value + : interval; + final DateFormat dateFormat = + axis.dateFormat ?? dateTimeAxisLabelFormat( - axis, interval.toInt(), previousInterval.toInt()); - return dateFormat - .format(DateTime.fromMillisecondsSinceEpoch(value.toInt())); + axis, + interval.toInt(), + previousInterval.toInt(), + ); + return dateFormat.format( + DateTime.fromMillisecondsSinceEpoch(value.toInt()), + ); } else if (axis is RenderLogarithmicAxis) { return logAxisLabel( - axis, axis.toPow(value), axis.interactiveTooltip.decimalPlaces); + axis, + axis.toPow(value), + axis.interactiveTooltip.decimalPlaces, + ); } else if (axis is RenderNumericAxis) { return numericAxisLabel( - axis, value, axis.interactiveTooltip.decimalPlaces); + axis, + value, + axis.interactiveTooltip.decimalPlaces, + ); } else { return ''; } @@ -864,10 +975,13 @@ class CrosshairBehavior extends ChartBehavior { if (axis is RenderCategoryAxis) { final num index = value < 0 ? 0 : value; final int labelsLength = axis.labels.length; - final String? label = axis.labels[(index.round() >= labelsLength - ? (index.round() > labelsLength ? labelsLength - 1 : index - 1) - : index) - .round()]; + final String? label = + axis.labels[(index.round() >= labelsLength + ? (index.round() > labelsLength + ? labelsLength - 1 + : index - 1) + : index) + .round()]; return axis.labels.indexOf(label); } else if (axis is RenderDateTimeCategoryAxis) { final num index = value < 0 ? 0 : value; @@ -883,8 +997,12 @@ class CrosshairBehavior extends ChartBehavior { /// Override this method to customize the crosshair tooltips & line rendering. @override - void onPaint(PaintingContext context, Offset offset, - SfChartThemeData chartThemeData, ThemeData themeData) { + void onPaint( + PaintingContext context, + Offset offset, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (_position == null || parent == null) { return; @@ -896,8 +1014,12 @@ class CrosshairBehavior extends ChartBehavior { } } - void _drawCrosshairLines(PaintingContext context, Offset offset, - RenderBehaviorArea parent, SfChartThemeData chartThemeData) { + void _drawCrosshairLines( + PaintingContext context, + Offset offset, + RenderBehaviorArea parent, + SfChartThemeData chartThemeData, + ) { Color crosshairLineColor = (lineColor ?? chartThemeData.crosshairLineColor)!; if (parent.onCrosshairPositionChanging != null && @@ -909,11 +1031,12 @@ class CrosshairBehavior extends ChartBehavior { crosshairLineColor = crosshairEventArgs.lineColor; } - final Paint paint = Paint() - ..isAntiAlias = true - ..color = crosshairLineColor - ..strokeWidth = lineWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = crosshairLineColor + ..strokeWidth = lineWidth + ..style = PaintingStyle.stroke; switch (lineType) { case CrosshairLineType.both: @@ -936,8 +1059,12 @@ class CrosshairBehavior extends ChartBehavior { /// Override this method to customize the horizontal line drawing and styling. @protected - void drawHorizontalAxisLine(PaintingContext context, Offset offset, - List? dashArray, Paint paint) { + void drawHorizontalAxisLine( + PaintingContext context, + Offset offset, + List? dashArray, + Paint paint, + ) { if (parentBox == null) { return; } @@ -950,8 +1077,12 @@ class CrosshairBehavior extends ChartBehavior { /// Override this method to customize the vertical line drawing and styling. @protected - void drawVerticalAxisLine(PaintingContext context, Offset offset, - List? dashArray, Paint paint) { + void drawVerticalAxisLine( + PaintingContext context, + Offset offset, + List? dashArray, + Paint paint, + ) { if (parentBox == null) { return; } @@ -963,7 +1094,9 @@ class CrosshairBehavior extends ChartBehavior { } void _drawCrosshairTooltip( - PaintingContext context, RenderBehaviorArea parent) { + PaintingContext context, + RenderBehaviorArea parent, + ) { final RenderCartesianAxes? cartesianAxes = parent.cartesianAxes; if (cartesianAxes == null) { return; @@ -975,17 +1108,22 @@ class CrosshairBehavior extends ChartBehavior { _drawVerticalAxisTooltip(context, cartesianAxes, themeBackgroundColor); } - void _drawHorizontalAxisTooltip(PaintingContext context, - RenderCartesianAxes cartesianAxes, Color themeBackgroundColor) { + void _drawHorizontalAxisTooltip( + PaintingContext context, + RenderCartesianAxes cartesianAxes, + Color themeBackgroundColor, + ) { if (_horizontalPaths.isNotEmpty && _horizontalLabels.isNotEmpty && _horizontalLabelPositions.isNotEmpty) { - final Paint fillPaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint fillPaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; RenderChartAxis? child = cartesianAxes.firstChild; int index = 0; @@ -1003,13 +1141,14 @@ class CrosshairBehavior extends ChartBehavior { ..strokeWidth = interactiveTooltip.borderWidth; drawHorizontalAxisTooltip( - context, - _horizontalLabelPositions[index], - _horizontalLabels[index], - textStyle, - _horizontalPaths[index], - fillPaint, - strokePaint); + context, + _horizontalLabelPositions[index], + _horizontalLabels[index], + textStyle, + _horizontalPaths[index], + fillPaint, + strokePaint, + ); index++; } @@ -1021,17 +1160,22 @@ class CrosshairBehavior extends ChartBehavior { } } - void _drawVerticalAxisTooltip(PaintingContext context, - RenderCartesianAxes cartesianAxes, Color themeBackgroundColor) { + void _drawVerticalAxisTooltip( + PaintingContext context, + RenderCartesianAxes cartesianAxes, + Color themeBackgroundColor, + ) { if (_verticalPaths.isNotEmpty && _verticalLabels.isNotEmpty && _verticalLabelPositions.isNotEmpty) { - final Paint fillPaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint fillPaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; RenderChartAxis? child = cartesianAxes.firstChild; int index = 0; @@ -1049,13 +1193,14 @@ class CrosshairBehavior extends ChartBehavior { ..strokeWidth = interactiveTooltip.borderWidth; drawVerticalAxisTooltip( - context, - _verticalLabelPositions[index], - _verticalLabels[index], - textStyle, - _verticalPaths[index], - fillPaint, - strokePaint); + context, + _verticalLabelPositions[index], + _verticalLabels[index], + textStyle, + _verticalPaths[index], + fillPaint, + strokePaint, + ); index++; } @@ -1071,25 +1216,57 @@ class CrosshairBehavior extends ChartBehavior { /// and it's position. @protected void drawHorizontalAxisTooltip( - PaintingContext context, Offset position, String text, TextStyle style, - [Path? path, Paint? fillPaint, Paint? strokePaint]) { + PaintingContext context, + Offset position, + String text, + TextStyle style, [ + Path? path, + Paint? fillPaint, + Paint? strokePaint, + ]) { _drawTooltipAndLabel( - context, position, text, style, path, fillPaint, strokePaint); + context, + position, + text, + style, + path, + fillPaint, + strokePaint, + ); } /// Override this method to customize the vertical axis tooltip with styling /// and it's position. @protected void drawVerticalAxisTooltip( - PaintingContext context, Offset position, String text, TextStyle style, - [Path? path, Paint? fillPaint, Paint? strokePaint]) { + PaintingContext context, + Offset position, + String text, + TextStyle style, [ + Path? path, + Paint? fillPaint, + Paint? strokePaint, + ]) { _drawTooltipAndLabel( - context, position, text, style, path, fillPaint, strokePaint); + context, + position, + text, + style, + path, + fillPaint, + strokePaint, + ); } void _drawTooltipAndLabel( - PaintingContext context, Offset position, String text, TextStyle style, - [Path? path, Paint? fillPaint, Paint? strokePaint]) { + PaintingContext context, + Offset position, + String text, + TextStyle style, [ + Path? path, + Paint? fillPaint, + Paint? strokePaint, + ]) { if (text.isEmpty) { return; } @@ -1102,10 +1279,11 @@ class CrosshairBehavior extends ChartBehavior { // Draw label. final TextPainter textPainter = TextPainter( - text: TextSpan(text: text, style: style), - textAlign: TextAlign.center, - maxLines: getMaxLinesContent(text), - textDirection: TextDirection.ltr); + text: TextSpan(text: text, style: style), + textAlign: TextAlign.center, + maxLines: getMaxLinesContent(text), + textDirection: TextDirection.ltr, + ); textPainter ..layout() ..paint(context.canvas, position); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/trackball.dart b/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/trackball.dart index 514a79be0..398e6bb36 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/trackball.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/trackball.dart @@ -423,7 +423,7 @@ class TrackballBehavior extends ChartBehavior { lineWidth, shouldAlwaysShow, builder, - hideDelay + hideDelay, ]; return Object.hashAll(values); } @@ -459,16 +459,26 @@ class TrackballBehavior extends ChartBehavior { assert(!y.isNaN); if (coordinateUnit == 'point') { _position = rawValueToPixelPoint( - x, y, parent.xAxis, parent.yAxis, parent.isTransposed); + x, + y, + parent.xAxis, + parent.yAxis, + parent.isTransposed, + ); } else if (coordinateUnit == 'pixel') { if (x is num) { _position = Offset(x.toDouble(), y); } else { _position = Offset( - rawValueToPixelPoint( - x, y, parent.xAxis, parent.yAxis, parent.isTransposed) - .dx, - y); + rawValueToPixelPoint( + x, + y, + parent.xAxis, + parent.yAxis, + parent.isTransposed, + ).dx, + y, + ); } } @@ -619,11 +629,13 @@ class TrackballBehavior extends ChartBehavior { final int hideDelayDuration = hideDelay > 0 ? hideDelay.toInt() : doubleTapHideDelay; _trackballHideTimer?.cancel(); - _trackballHideTimer = - Timer(Duration(milliseconds: hideDelayDuration), () { - _trackballHideTimer = null; - hide(); - }); + _trackballHideTimer = Timer( + Duration(milliseconds: hideDelayDuration), + () { + _trackballHideTimer = null; + hide(); + }, + ); } } @@ -670,8 +682,12 @@ class TrackballBehavior extends ChartBehavior { } final TrackballGroupingModeInfo groupingModeInfo = - TrackballGroupingModeInfo(chartPoints, currentPointIndices, - visibleSeriesIndices, visibleSeriesList); + TrackballGroupingModeInfo( + chartPoints, + currentPointIndices, + visibleSeriesIndices, + visibleSeriesList, + ); details.add(TrackballDetails(null, null, null, null, groupingModeInfo)); } else { for (int i = 0; i < length; i++) { @@ -681,8 +697,14 @@ class TrackballBehavior extends ChartBehavior { pointInfo.series is CartesianSeriesRenderer; if (isIndicator || (isCartesianSeries && pointInfo.series.enableTrackball)) { - details.add(TrackballDetails(pointInfo.chartPoint, pointInfo.series, - pointInfo.dataPointIndex, pointInfo.seriesIndex)); + details.add( + TrackballDetails( + pointInfo.chartPoint, + pointInfo.series, + pointInfo.dataPointIndex, + pointInfo.seriesIndex, + ), + ); } } } @@ -733,12 +755,16 @@ class TrackballBehavior extends ChartBehavior { child.dataSource!.isNotEmpty && child.animationController != null && !child.animationController!.isAnimating) { - final List nearestPointIndexes = - _findNearestChartPointIndexes(child, position); + final List nearestPointIndexes = _findNearestChartPointIndexes( + child, + position, + ); for (final int nearestPointIndex in nearestPointIndexes) { final ChartSegment segment = child.segmentAt(nearestPointIndex); - final TrackballInfo? trackballInfo = - segment.trackballInfo(position, nearestPointIndex); + final TrackballInfo? trackballInfo = segment.trackballInfo( + position, + nearestPointIndex, + ); if (trackballInfo != null) { final ChartTrackballInfo trackInfo = @@ -753,8 +779,9 @@ class TrackballBehavior extends ChartBehavior { leastX = xPos; } - final Rect rect = _plotAreaBounds - .intersect(Rect.fromLTWH(xPos - 1, yPos - 1, 2, 2)); + final Rect rect = _plotAreaBounds.intersect( + Rect.fromLTWH(xPos - 1, yPos - 1, 2, 2), + ); if (_plotAreaBounds.contains(trackPosition) || _plotAreaBounds.overlaps(rect)) { _visiblePoints.add(Offset(xPos, yPos)); @@ -783,8 +810,9 @@ class TrackballBehavior extends ChartBehavior { if (parent.indicatorArea != null) { parent.indicatorArea!.visitChildren((RenderObject child) { if (child is IndicatorRenderer && child.effectiveIsVisible) { - final List? trackballInfo = - child.trackballInfo(position); + final List? trackballInfo = child.trackballInfo( + position, + ); if (trackballInfo != null && trackballInfo.isNotEmpty && child.animationFactor == 1) { @@ -793,7 +821,7 @@ class TrackballBehavior extends ChartBehavior { final CartesianChartPoint chartPoint = info.point; final bool pointIsNaN = (chartPoint.xValue != null && chartPoint.xValue!.isNaN) || - (chartPoint.y != null && chartPoint.y!.isNaN); + (chartPoint.y != null && chartPoint.y!.isNaN); if (trackInfo.pointIndex >= 0 && !pointIsNaN) { final Offset indicatorPosition = info.position!; double xPos = indicatorPosition.dx; @@ -808,8 +836,9 @@ class TrackballBehavior extends ChartBehavior { leastX = yPos; } - final Rect rect = _plotAreaBounds - .intersect(Rect.fromLTWH(xPos - 1, yPos - 1, 2, 2)); + final Rect rect = _plotAreaBounds.intersect( + Rect.fromLTWH(xPos - 1, yPos - 1, 2, 2), + ); if (_plotAreaBounds.contains(indicatorPosition) || _plotAreaBounds.overlaps(rect)) { _visiblePoints.add(Offset(xPos, yPos)); @@ -834,7 +863,12 @@ class TrackballBehavior extends ChartBehavior { _sortTrackballPoints(_isTransposed); _triggerTrackballRenderCallback(parent); _applyTooltipDisplayMode( - _chartThemeData!, _themeData!, leastX, position, isRtl); + _chartThemeData!, + _themeData!, + leastX, + position, + isRtl, + ); } void _sortTrackballPoints(bool isTranposed) { @@ -846,13 +880,19 @@ class TrackballBehavior extends ChartBehavior { if (chartPointInfo.isNotEmpty) { if (tooltipDisplayMode != TrackballDisplayMode.groupAllPoints) { isTranposed - ? chartPointInfo.sort((ChartPointInfo a, ChartPointInfo b) => - a.xPosition!.compareTo(b.xPosition!)) + ? chartPointInfo.sort( + (ChartPointInfo a, ChartPointInfo b) => + a.xPosition!.compareTo(b.xPosition!), + ) : tooltipDisplayMode == TrackballDisplayMode.floatAllPoints - ? chartPointInfo.sort((ChartPointInfo a, ChartPointInfo b) => - a.yPosition!.compareTo(b.yPosition!)) - : chartPointInfo.sort((ChartPointInfo a, ChartPointInfo b) => - b.yPosition!.compareTo(a.yPosition!)); + ? chartPointInfo.sort( + (ChartPointInfo a, ChartPointInfo b) => + a.yPosition!.compareTo(b.yPosition!), + ) + : chartPointInfo.sort( + (ChartPointInfo a, ChartPointInfo b) => + b.yPosition!.compareTo(a.yPosition!), + ); } } } @@ -877,7 +917,9 @@ class TrackballBehavior extends ChartBehavior { } List _findNearestChartPointIndexes( - CartesianSeriesRenderer series, Offset position) { + CartesianSeriesRenderer series, + Offset position, + ) { final List indexes = []; final int dataCount = series.dataCount; final RenderChartAxis xAxis = series.xAxis!; @@ -907,8 +949,12 @@ class TrackballBehavior extends ChartBehavior { } if (series.canFindLinearVisibleIndexes) { - final int binaryIndex = - binarySearch(series.xValues, xValue.toDouble(), 0, dataCount - 1); + final int binaryIndex = binarySearch( + series.xValues, + xValue.toDouble(), + 0, + dataCount - 1, + ); if (binaryIndex >= 0) { indexes.add(binaryIndex); } @@ -941,7 +987,10 @@ class TrackballBehavior extends ChartBehavior { } void _addChartPointInfo( - ChartTrackballInfo trackballInfo, double xPos, double yPos) { + ChartTrackballInfo trackballInfo, + double xPos, + double yPos, + ) { final ChartPointInfo pointInfo = ChartPointInfo( label: trackballInfo.text, header: trackballInfo.header, @@ -1032,13 +1081,14 @@ class TrackballBehavior extends ChartBehavior { final ChartPointInfo nextPoint = chartPointInfo[i]; final double nextX = nextPoint.xPosition!; final double nextY = nextPoint.yPosition!; - final bool isXYPositioned = !_isTransposed - ? (((pointInfo!.yPosition! - touchYPos).abs() > - (nextY - touchYPos).abs()) && - pointInfo.xPosition! == nextX) - : (((pointInfo!.xPosition! - touchXPos).abs() > - (nextX - touchXPos).abs()) && - pointInfo.yPosition! == nextY); + final bool isXYPositioned = + !_isTransposed + ? (((pointInfo!.yPosition! - touchYPos).abs() > + (nextY - touchYPos).abs()) && + pointInfo.xPosition! == nextX) + : (((pointInfo!.xPosition! - touchXPos).abs() > + (nextX - touchXPos).abs()) && + pointInfo.yPosition! == nextY); if (isXYPositioned) { pointInfo = chartPointInfo[i]; } @@ -1069,28 +1119,44 @@ class TrackballBehavior extends ChartBehavior { } if (builder == null) { - final bool markerIsVisible = markerSettings != null && + final bool markerIsVisible = + markerSettings != null && markerSettings!.markerVisibility == TrackballVisibilityMode.visible; - final bool markerAutoVisibility = markerSettings != null && + final bool markerAutoVisibility = + markerSettings != null && markerSettings!.markerVisibility == TrackballVisibilityMode.auto; if (tooltipSettings.enable) { final TextStyle labelStyle = _createLabelStyle( - FontWeight.normal, _chartThemeData!.trackballTextStyle!); + FontWeight.normal, + _chartThemeData!.trackballTextStyle!, + ); switch (tooltipDisplayMode) { case TrackballDisplayMode.nearestPoint: _applyNearestPointDisplayMode( - labelStyle, markerIsVisible, markerAutoVisibility, isRtl); + labelStyle, + markerIsVisible, + markerAutoVisibility, + isRtl, + ); break; case TrackballDisplayMode.floatAllPoints: _applyFloatAllPointsDisplayMode( - labelStyle, markerIsVisible, markerAutoVisibility, isRtl); + labelStyle, + markerIsVisible, + markerAutoVisibility, + isRtl, + ); break; case TrackballDisplayMode.groupAllPoints: _applyGroupAllPointDisplayMode( - labelStyle, markerIsVisible, markerAutoVisibility, isRtl); + labelStyle, + markerIsVisible, + markerAutoVisibility, + isRtl, + ); break; case TrackballDisplayMode.none: @@ -1101,7 +1167,11 @@ class TrackballBehavior extends ChartBehavior { if (markerSettings != null && markerSettings!.markerVisibility != TrackballVisibilityMode.hidden) { _computeLineMarkers( - themeData, _lineMarkers, markerIsVisible, markerAutoVisibility); + themeData, + _lineMarkers, + markerIsVisible, + markerAutoVisibility, + ); } } } @@ -1124,15 +1194,25 @@ class TrackballBehavior extends ChartBehavior { borderRadius = borderRadius > 5 ? 5 : borderRadius; } borderRadius = borderRadius > 15 ? 15 : borderRadius; - final double padding = (markerAutoVisibility - ? series is IndicatorRenderer || - (series != null && series.markerSettings.isVisible) - : markerIsVisible) - ? (markerSettings!.width / 2) + defaultTrackballPadding - : defaultTrackballPadding; - - _computeNearestTooltip(pointInfo, labelStyle, width, labelSize.height, - padding, arrowWidth, arrowLength, borderRadius, isRtl); + final double padding = + (markerAutoVisibility + ? series is IndicatorRenderer || + (series != null && series.markerSettings.isVisible) + : markerIsVisible) + ? (markerSettings!.width / 2) + defaultTrackballPadding + : defaultTrackballPadding; + + _computeNearestTooltip( + pointInfo, + labelStyle, + width, + labelSize.height, + padding, + arrowWidth, + arrowLength, + borderRadius, + isRtl, + ); } } @@ -1153,36 +1233,58 @@ class TrackballBehavior extends ChartBehavior { final double labelRectWidth = tooltipRect.width; final double labelRectHeight = tooltipRect.height; final Offset alignPosition = _alignPosition( - xPosition, - yPosition, - labelRectWidth, - labelRectHeight, - arrowLength, - arrowWidth, - padding, - isRtl); + xPosition, + yPosition, + labelRectWidth, + labelRectHeight, + arrowLength, + arrowWidth, + padding, + isRtl, + ); final RRect tooltipRRect = RRect.fromRectAndRadius( Rect.fromLTWH( - alignPosition.dx, alignPosition.dy, labelRectWidth, labelRectHeight), + alignPosition.dx, + alignPosition.dy, + labelRectWidth, + labelRectHeight, + ), Radius.circular(borderRadius), ); - final Path nosePath = _nosePath(_tooltipDirection(), tooltipRRect, - Offset(xPosition, yPosition), arrowLength, arrowWidth); - final Path nearestTooltipPath = Path() - ..addRRect(tooltipRRect) - ..addPath(nosePath, Offset.zero); + final Path nosePath = _nosePath( + _tooltipDirection(), + tooltipRRect, + Offset(xPosition, yPosition), + arrowLength, + arrowWidth, + ); + final Path nearestTooltipPath = + Path() + ..addRRect(tooltipRRect) + ..addPath(nosePath, Offset.zero); _tooltipPaths.add(nearestTooltipPath); if (tooltipSettings.canShowMarker) { final Offset markerPosition = _markerPosition( - tooltipRRect, width, height, defaultTrackballPadding, isRtl); + tooltipRRect, + width, + height, + defaultTrackballPadding, + isRtl, + ); _computeTooltipMarkers(pointInfo, markerPosition); } if (pointInfo.label != null) { _computeTooltipLabels( - pointInfo.label!, width, height, labelStyle, tooltipRRect, isRtl); + pointInfo.label!, + width, + height, + labelStyle, + tooltipRRect, + isRtl, + ); } } @@ -1209,12 +1311,13 @@ class TrackballBehavior extends ChartBehavior { borderRadius = borderRadius > 5 ? 5 : borderRadius; } borderRadius = borderRadius > 15 ? 15 : borderRadius; - final double padding = (markerAutoVisibility - ? series is IndicatorRenderer || - (series != null && series.markerSettings.isVisible) - : markerIsVisible) - ? (markerSettings!.width / 2) + defaultTrackballPadding - : defaultTrackballPadding; + final double padding = + (markerAutoVisibility + ? series is IndicatorRenderer || + (series != null && series.markerSettings.isVisible) + : markerIsVisible) + ? (markerSettings!.width / 2) + defaultTrackballPadding + : defaultTrackballPadding; final num tooltipTop = floatTooltipPosition.tooltipTop[i]; final num tooltipBottom = floatTooltipPosition.tooltipBottom[i]; @@ -1224,17 +1327,18 @@ class TrackballBehavior extends ChartBehavior { : tooltipTop >= _plotAreaBounds.top && tooltipBottom <= _plotAreaBounds.bottom) { _computeFloatAllPointTooltip( - i, - pointInfo, - width, - labelSize.height, - padding, - arrowWidth, - arrowLength, - borderRadius, - labelStyle, - floatTooltipPosition, - isRtl); + i, + pointInfo, + width, + labelSize.height, + padding, + arrowWidth, + arrowLength, + borderRadius, + labelStyle, + floatTooltipPosition, + isRtl, + ); } } } @@ -1258,45 +1362,67 @@ class TrackballBehavior extends ChartBehavior { final double labelRectWidth = tooltipRect.width; final double labelRectHeight = tooltipRect.height; final Offset alignPosition = _alignPosition( - xPosition, - yPosition, - labelRectWidth, - labelRectHeight, - arrowLength, - arrowWidth, - padding, - isRtl); + xPosition, + yPosition, + labelRectWidth, + labelRectHeight, + arrowLength, + arrowWidth, + padding, + isRtl, + ); final double topValue = tooltipPosition.tooltipTop[index].toDouble(); final RRect tooltipRRect = RRect.fromRectAndRadius( - Rect.fromLTWH( - _isTransposed ? topValue : alignPosition.dx, - _isTransposed ? alignPosition.dy : topValue, - labelRectWidth, - labelRectHeight), - Radius.circular(borderRadius)); - - final Path nosePath = _nosePath(_tooltipDirection(), tooltipRRect, - Offset(xPosition, yPosition), arrowLength, arrowWidth); - final Path nearestTooltipPath = Path() - ..addRRect(tooltipRRect) - ..addPath(nosePath, Offset.zero); + Rect.fromLTWH( + _isTransposed ? topValue : alignPosition.dx, + _isTransposed ? alignPosition.dy : topValue, + labelRectWidth, + labelRectHeight, + ), + Radius.circular(borderRadius), + ); + + final Path nosePath = _nosePath( + _tooltipDirection(), + tooltipRRect, + Offset(xPosition, yPosition), + arrowLength, + arrowWidth, + ); + final Path nearestTooltipPath = + Path() + ..addRRect(tooltipRRect) + ..addPath(nosePath, Offset.zero); _tooltipPaths.add(nearestTooltipPath); if (tooltipSettings.canShowMarker) { final Offset markerPosition = _markerPosition( - tooltipRRect, width, height, defaultTrackballPadding, isRtl); + tooltipRRect, + width, + height, + defaultTrackballPadding, + isRtl, + ); _computeTooltipMarkers(pointInfo, markerPosition); } if (pointInfo.label != null) { _computeTooltipLabels( - pointInfo.label!, width, height, labelStyle, tooltipRRect, isRtl); + pointInfo.label!, + width, + height, + labelStyle, + tooltipRRect, + isRtl, + ); } } _TooltipPositions _computeTooltipPositionForFloatAllPoints( - TextStyle labelStyle, double borderRadius) { + TextStyle labelStyle, + double borderRadius, + ) { final List tooltipTop = []; final List tooltipBottom = []; final List xAxesInfo = []; @@ -1318,13 +1444,19 @@ class TrackballBehavior extends ChartBehavior { final Offset visiblePoint = _visiblePoints[i]; final double closeX = visiblePoint.dx; final double closeY = visiblePoint.dy; - tooltipTop.add(_isTransposed - ? closeX - tooltipPaddingForFloatPoint - (width / 2) - : closeY - tooltipPaddingForFloatPoint - height / 2); - tooltipBottom.add(_isTransposed - ? (closeX + tooltipPaddingForFloatPoint + (width / 2)) + - (tooltipSettings.canShowMarker ? trackballTooltipMarkerSize : 0) - : closeY + tooltipPaddingForFloatPoint + height / 2); + tooltipTop.add( + _isTransposed + ? closeX - tooltipPaddingForFloatPoint - (width / 2) + : closeY - tooltipPaddingForFloatPoint - height / 2, + ); + tooltipBottom.add( + _isTransposed + ? (closeX + tooltipPaddingForFloatPoint + (width / 2)) + + (tooltipSettings.canShowMarker + ? trackballTooltipMarkerSize + : 0) + : closeY + tooltipPaddingForFloatPoint + height / 2, + ); if (series != null && series.xAxis != null) { xAxesInfo.add(series.xAxis!); } @@ -1335,20 +1467,27 @@ class TrackballBehavior extends ChartBehavior { } if (tooltipTop.isNotEmpty && tooltipBottom.isNotEmpty) { - return _smartTooltipPositions(tooltipTop, tooltipBottom, xAxesInfo, - yAxesInfo, chartPointInfo, tooltipPaddingForFloatPoint); + return _smartTooltipPositions( + tooltipTop, + tooltipBottom, + xAxesInfo, + yAxesInfo, + chartPointInfo, + tooltipPaddingForFloatPoint, + ); } return _TooltipPositions(tooltipTop, tooltipBottom); } /// Method to place the collided tooltips properly _TooltipPositions _smartTooltipPositions( - List tooltipTop, - List tooltipBottom, - List xAxesInfo, - List yAxesInfo, - List chartPointInfo, - [num tooltipPaddingForFloatPoint = 0]) { + List tooltipTop, + List tooltipBottom, + List xAxesInfo, + List yAxesInfo, + List chartPointInfo, [ + num tooltipPaddingForFloatPoint = 0, + ]) { final List visibleLocation = []; num totalHeight = 0; final int length = chartPointInfo.length; @@ -1362,15 +1501,20 @@ class TrackballBehavior extends ChartBehavior { } _TooltipPositions smartTooltipPosition = _continuousOverlappingPoints( - tooltipTop, - tooltipBottom, - visibleLocation, - tooltipPaddingForFloatPoint); + tooltipTop, + tooltipBottom, + visibleLocation, + tooltipPaddingForFloatPoint, + ); if (!_isTransposed ? totalHeight < (_plotAreaBounds.bottom - _plotAreaBounds.top) : totalHeight < (_plotAreaBounds.right - _plotAreaBounds.left)) { - smartTooltipPosition = _verticalArrangements(smartTooltipPosition, - xAxesInfo, yAxesInfo, tooltipPaddingForFloatPoint); + smartTooltipPosition = _verticalArrangements( + smartTooltipPosition, + xAxesInfo, + yAxesInfo, + tooltipPaddingForFloatPoint, + ); } return smartTooltipPosition; } @@ -1465,7 +1609,7 @@ class TrackballBehavior extends ChartBehavior { tooltipPosition.tooltipBottom[j - 1] < chartHeight!)) { tooltipPosition.tooltipTop[j] = tooltipPosition.tooltipBottom[j - 1] + - tooltipPaddingForFloatPoint; + tooltipPaddingForFloatPoint; tooltipPosition.tooltipBottom[j] = tooltipPosition.tooltipTop[j] + secWidth; } @@ -1477,8 +1621,12 @@ class TrackballBehavior extends ChartBehavior { // Method to identify the colliding trackball tooltips and // return the new tooltip positions - _TooltipPositions _continuousOverlappingPoints(List tooltipTop, - List tooltipBottom, List visibleLocation, num tooltipPadding) { + _TooltipPositions _continuousOverlappingPoints( + List tooltipTop, + List tooltipBottom, + List visibleLocation, + num tooltipPadding, + ) { num temp; num count = 0; num start = 0; @@ -1568,8 +1716,12 @@ class TrackballBehavior extends ChartBehavior { return _TooltipPositions(tooltipTop, tooltipBottom); } - void _applyGroupAllPointDisplayMode(TextStyle labelStyle, - bool markerIsVisible, bool markerAutoVisibility, bool isRtl) { + void _applyGroupAllPointDisplayMode( + TextStyle labelStyle, + bool markerIsVisible, + bool markerAutoVisibility, + bool isRtl, + ) { double borderRadius = tooltipSettings.borderRadius; final ChartPointInfo pointInfo = chartPointInfo[0]; final double xPosition = pointInfo.xPosition!; @@ -1583,12 +1735,13 @@ class TrackballBehavior extends ChartBehavior { borderRadius = borderRadius > 5 ? 5 : borderRadius; } borderRadius = borderRadius > 15 ? 15 : borderRadius; - final double padding = (markerAutoVisibility - ? series is IndicatorRenderer || - (series != null && series.markerSettings.isVisible) - : markerIsVisible) - ? (markerSettings!.width / 2) + defaultTrackballPadding - : defaultTrackballPadding; + final double padding = + (markerAutoVisibility + ? series is IndicatorRenderer || + (series != null && series.markerSettings.isVisible) + : markerIsVisible) + ? (markerSettings!.width / 2) + defaultTrackballPadding + : defaultTrackballPadding; final Rect tooltipRect = _tooltipRect(xPosition, yPosition, width, height); final double labelRectWidth = tooltipRect.width; @@ -1608,7 +1761,11 @@ class TrackballBehavior extends ChartBehavior { final RRect tooltipRRect = _validateRect( Rect.fromLTWH( - alignPosition.dx, alignPosition.dy, labelRectWidth, labelRectHeight), + alignPosition.dx, + alignPosition.dy, + labelRectWidth, + labelRectHeight, + ), _plotAreaBounds, borderRadius, ); @@ -1616,12 +1773,22 @@ class TrackballBehavior extends ChartBehavior { if (tooltipRRect != RRect.zero) { _tooltipPaths.add(Path()..addRRect(tooltipRRect)); _computeGroupTooltipLabels( - alignPosition, tooltipRRect, totalLabelSize, labelStyle, isRtl); + alignPosition, + tooltipRRect, + totalLabelSize, + labelStyle, + isRtl, + ); } } - void _computeGroupTooltipLabels(Offset alignPosition, RRect tooltipRRect, - Size totalLabelSize, TextStyle textStyle, bool isRtl) { + void _computeGroupTooltipLabels( + Offset alignPosition, + RRect tooltipRRect, + Size totalLabelSize, + TextStyle textStyle, + bool isRtl, + ) { bool hasIndicator = false; final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (parent != null && parent.indicatorArea != null) { @@ -1645,19 +1812,26 @@ class TrackballBehavior extends ChartBehavior { totalLabelHeight += headerHeight; eachTextHeight += headerHeight; - _tooltipLabels.add(_TooltipLabels( - header, - boldStyle, - Offset(tooltipRRect.left + tooltipRRect.width / 2, - tooltipRRect.top + headerHeight / 2 + headerPadding / 2) - .translate(-headerSize.width / 2, -headerSize.height / 2), - )); + _tooltipLabels.add( + _TooltipLabels( + header, + boldStyle, + Offset( + tooltipRRect.left + tooltipRRect.width / 2, + tooltipRRect.top + headerHeight / 2 + headerPadding / 2, + ).translate(-headerSize.width / 2, -headerSize.height / 2), + ), + ); // Divider offset calculation. - _dividerStartOffset = Offset(tooltipRRect.left + headerPadding, - tooltipRRect.top + headerHeight + headerPadding); - _dividerEndOffset = Offset(tooltipRRect.right - headerPadding, - tooltipRRect.top + headerHeight + headerPadding); + _dividerStartOffset = Offset( + tooltipRRect.left + headerPadding, + tooltipRRect.top + headerHeight + headerPadding, + ); + _dividerEndOffset = Offset( + tooltipRRect.right - headerPadding, + tooltipRRect.top + headerHeight + headerPadding, + ); } // Empty text size consideration between the header and series text. @@ -1680,12 +1854,14 @@ class TrackballBehavior extends ChartBehavior { final double rectLeftWithPadding = tooltipRRect.left + padding; final double rectRightWithPadding = tooltipRRect.right - padding; - final double markerX = isRtl - ? rectRightWithPadding - halfMarkerSize - : rectLeftWithPadding + halfMarkerSize; - final double x = isRtl - ? rectRightWithPadding - markerSize - : rectLeftWithPadding + markerSize; + final double markerX = + isRtl + ? rectRightWithPadding - halfMarkerSize + : rectLeftWithPadding + halfMarkerSize; + final double x = + isRtl + ? rectRightWithPadding - markerSize + : rectLeftWithPadding + markerSize; final double y = tooltipRRect.top + defaultTrackballPadding; final int length = chartPointInfo.length; for (int i = 0; i < length; i++) { @@ -1703,11 +1879,15 @@ class TrackballBehavior extends ChartBehavior { if (canShowMarker) { Offset markerPosition; if (text.contains('\n') && hasIndicator) { - markerPosition = Offset(markerX, - totalLabelHeight - actualLabelHeight + defaultTrackballPadding); + markerPosition = Offset( + markerX, + totalLabelHeight - actualLabelHeight + defaultTrackballPadding, + ); } else { - markerPosition = - Offset(markerX, totalLabelHeight - actualLabelHeight / 2); + markerPosition = Offset( + markerX, + totalLabelHeight - actualLabelHeight / 2, + ); } _computeTooltipMarkers(pointInfo, markerPosition); @@ -1823,8 +2003,13 @@ class TrackballBehavior extends ChartBehavior { return Offset(xPos, yPos); } - Offset _markerPosition(RRect tooltipRRect, double labelWidth, - double labelHeight, double markerPadding, bool isRtl) { + Offset _markerPosition( + RRect tooltipRRect, + double labelWidth, + double labelHeight, + double markerPadding, + bool isRtl, + ) { final double padding = labelWidth / 2 + markerPadding; return Offset( (tooltipRRect.left + tooltipRRect.width / 2) + @@ -1836,26 +2021,32 @@ class TrackballBehavior extends ChartBehavior { Rect _tooltipRect(double x, double y, double width, double height) { if (tooltipSettings.canShowMarker) { return Rect.fromLTWH( - x, - y, - width + (trackballTooltipMarkerSize + trackballTooltipPadding), - height + defaultTooltipWidth); + x, + y, + width + (trackballTooltipMarkerSize + trackballTooltipPadding), + height + defaultTooltipWidth, + ); } else { - return Rect.fromLTWH(x, y, width + trackballTooltipMarkerSize, - height + defaultTooltipWidth); + return Rect.fromLTWH( + x, + y, + width + trackballTooltipMarkerSize, + height + defaultTooltipWidth, + ); } } Offset _alignPosition( - double xPosition, - double yPosition, - double rectWidth, - double rectHeight, - double arrowLength, - double arrowWidth, - double padding, - bool isRtl, - [bool isGroupMode = false]) { + double xPosition, + double yPosition, + double rectWidth, + double rectHeight, + double arrowLength, + double arrowWidth, + double padding, + bool isRtl, [ + bool isGroupMode = false, + ]) { double xPos = xPosition; double yPos = yPosition; if (yPosition > arrowLength + rectHeight) { @@ -1881,25 +2072,29 @@ class TrackballBehavior extends ChartBehavior { if (!isRtl) { if (xPos + rectWidth + padding + arrowLength > _plotAreaBounds.right) { - xPos = isGroupMode - ? xPos - rectWidth - groupAllPadding - : xPos - rectWidth - padding - arrowLength; + xPos = + isGroupMode + ? xPos - rectWidth - groupAllPadding + : xPos - rectWidth - padding - arrowLength; _isLeft = true; } else { - xPos = isGroupMode - ? xPosition + groupAllPadding - : xPosition + padding + arrowLength; + xPos = + isGroupMode + ? xPosition + groupAllPadding + : xPosition + padding + arrowLength; _isLeft = false; _isRight = true; } } else { - xPos = isGroupMode - ? xPos - rectWidth - groupAllPadding - : xPos - rectWidth - padding - arrowLength; + xPos = + isGroupMode + ? xPos - rectWidth - groupAllPadding + : xPos - rectWidth - padding - arrowLength; if (xPos < _plotAreaBounds.left) { - xPos = isGroupMode - ? xPosition + groupAllPadding - : xPosition + padding + arrowLength; + xPos = + isGroupMode + ? xPosition + groupAllPadding + : xPosition + padding + arrowLength; _isRight = true; } else { _isLeft = true; @@ -1935,27 +2130,31 @@ class TrackballBehavior extends ChartBehavior { ? (xPos + (rectWidth / 2) + groupAllPadding) : xPos + rectWidth + padding + arrowLength) > _plotAreaBounds.right) { - xPos = isGroupMode - ? (xPos - (rectWidth / 2) - groupAllPadding) - : xPos - rectWidth - padding - arrowLength; + xPos = + isGroupMode + ? (xPos - (rectWidth / 2) - groupAllPadding) + : xPos - rectWidth - padding - arrowLength; _isLeft = true; } else { - xPos = isGroupMode - ? xPosition + groupAllPadding - : xPosition + padding + arrowLength; + xPos = + isGroupMode + ? xPosition + groupAllPadding + : xPosition + padding + arrowLength; _isRight = true; } } else { if (xPosition - rectWidth - padding - arrowLength > _plotAreaBounds.left) { - xPos = isGroupMode - ? (xPos - (rectWidth / 2) - groupAllPadding) - : xPos - rectWidth - padding - arrowLength; + xPos = + isGroupMode + ? (xPos - (rectWidth / 2) - groupAllPadding) + : xPos - rectWidth - padding - arrowLength; _isLeft = true; } else { - xPos = isGroupMode - ? xPosition + groupAllPadding - : xPosition + padding + arrowLength; + xPos = + isGroupMode + ? xPosition + groupAllPadding + : xPosition + padding + arrowLength; _isRight = true; } } @@ -1976,7 +2175,10 @@ class TrackballBehavior extends ChartBehavior { } RRect _validateRect( - Rect tooltipRRect, Rect plotAreaBounds, double borderRadius) { + Rect tooltipRRect, + Rect plotAreaBounds, + double borderRadius, + ) { if (tooltipRRect == Rect.zero || tooltipRRect.width >= plotAreaBounds.width || tooltipRRect.height >= plotAreaBounds.height) { @@ -2007,8 +2209,13 @@ class TrackballBehavior extends ChartBehavior { return alignedRect; } - Path _nosePath(String tooltipPosition, RRect tooltipRect, Offset position, - double arrowLength, double arrowWidth) { + Path _nosePath( + String tooltipPosition, + RRect tooltipRect, + Offset position, + double arrowLength, + double arrowWidth, + ) { final Path nosePath = Path(); final double tooltipLeft = tooltipRect.left; final double tooltipRight = tooltipRect.right; @@ -2020,7 +2227,9 @@ class TrackballBehavior extends ChartBehavior { case 'Left': nosePath.moveTo(tooltipRight, tooltipTop + rectHalfHeight - arrowWidth); nosePath.lineTo( - tooltipRight, tooltipBottom - rectHalfHeight + arrowWidth); + tooltipRight, + tooltipBottom - rectHalfHeight + arrowWidth, + ); nosePath.lineTo(tooltipRight + arrowLength, position.dy); nosePath.close(); return nosePath; @@ -2028,7 +2237,9 @@ class TrackballBehavior extends ChartBehavior { case 'Right': nosePath.moveTo(tooltipLeft, tooltipTop + rectHalfHeight - arrowWidth); nosePath.lineTo( - tooltipLeft, tooltipBottom - rectHalfHeight + arrowWidth); + tooltipLeft, + tooltipBottom - rectHalfHeight + arrowWidth, + ); nosePath.lineTo(tooltipLeft - arrowLength, position.dy); nosePath.close(); return nosePath; @@ -2036,16 +2247,22 @@ class TrackballBehavior extends ChartBehavior { case 'Top': nosePath.moveTo(position.dx, tooltipBottom + arrowLength); nosePath.lineTo( - (tooltipRight - rectHalfWidth) + arrowWidth, tooltipBottom); + (tooltipRight - rectHalfWidth) + arrowWidth, + tooltipBottom, + ); nosePath.lineTo( - (tooltipLeft + rectHalfWidth) - arrowWidth, tooltipBottom); + (tooltipLeft + rectHalfWidth) - arrowWidth, + tooltipBottom, + ); nosePath.close(); return nosePath; case 'Bottom': nosePath.moveTo(position.dx, tooltipTop - arrowLength); nosePath.lineTo( - (tooltipRight - rectHalfWidth) + arrowWidth, tooltipTop); + (tooltipRight - rectHalfWidth) + arrowWidth, + tooltipTop, + ); nosePath.lineTo((tooltipLeft + rectHalfWidth) - arrowWidth, tooltipTop); nosePath.close(); return nosePath; @@ -2067,41 +2284,43 @@ class TrackballBehavior extends ChartBehavior { TextStyle _createLabelStyle(FontWeight fontWeight, TextStyle labelStyle) { return TextStyle( - fontWeight: fontWeight, - color: labelStyle.color, - fontSize: labelStyle.fontSize, - fontFamily: labelStyle.fontFamily, - fontStyle: labelStyle.fontStyle, - inherit: labelStyle.inherit, - backgroundColor: labelStyle.backgroundColor, - letterSpacing: labelStyle.letterSpacing, - wordSpacing: labelStyle.wordSpacing, - textBaseline: labelStyle.textBaseline, - height: labelStyle.height, - locale: labelStyle.locale, - foreground: labelStyle.foreground, - background: labelStyle.background, - shadows: labelStyle.shadows, - fontFeatures: labelStyle.fontFeatures, - decoration: labelStyle.decoration, - decorationColor: labelStyle.decorationColor, - decorationStyle: labelStyle.decorationStyle, - decorationThickness: labelStyle.decorationThickness, - debugLabel: labelStyle.debugLabel, - fontFamilyFallback: labelStyle.fontFamilyFallback); + fontWeight: fontWeight, + color: labelStyle.color, + fontSize: labelStyle.fontSize, + fontFamily: labelStyle.fontFamily, + fontStyle: labelStyle.fontStyle, + inherit: labelStyle.inherit, + backgroundColor: labelStyle.backgroundColor, + letterSpacing: labelStyle.letterSpacing, + wordSpacing: labelStyle.wordSpacing, + textBaseline: labelStyle.textBaseline, + height: labelStyle.height, + locale: labelStyle.locale, + foreground: labelStyle.foreground, + background: labelStyle.background, + shadows: labelStyle.shadows, + fontFeatures: labelStyle.fontFeatures, + decoration: labelStyle.decoration, + decorationColor: labelStyle.decorationColor, + decorationStyle: labelStyle.decorationStyle, + decorationThickness: labelStyle.decorationThickness, + debugLabel: labelStyle.debugLabel, + fontFamilyFallback: labelStyle.fontFamilyFallback, + ); } void _computeTooltipMarkers(ChartPointInfo pointInfo, Offset markerPosition) { final Color color = pointInfo.color!; - final ChartMarker marker = ChartMarker() - ..x = markerPosition.dx - ..y = markerPosition.dy - ..index = pointInfo.dataPointIndex! - ..height = tooltipMarkerSize - ..width = tooltipMarkerSize - ..borderColor = color - ..borderWidth = 1 - ..color = color; + final ChartMarker marker = + ChartMarker() + ..x = markerPosition.dx + ..y = markerPosition.dy + ..index = pointInfo.dataPointIndex! + ..height = tooltipMarkerSize + ..width = tooltipMarkerSize + ..borderColor = color + ..borderWidth = 1 + ..color = color; if (markerSettings != null) { marker.merge( borderColor: markerSettings!.borderColor ?? color, @@ -2110,10 +2329,14 @@ class TrackballBehavior extends ChartBehavior { type: markerSettings!.shape, ); } - marker.position = - Offset(marker.x - marker.width / 2, marker.y - marker.height / 2); + marker.position = Offset( + marker.x - marker.width / 2, + marker.y - marker.height / 2, + ); marker.shader = _markerShader( - pointInfo, marker.position & Size(marker.height, marker.width)); + pointInfo, + marker.position & Size(marker.height, marker.width), + ); _tooltipMarkers.add(marker); } @@ -2139,18 +2362,20 @@ class TrackballBehavior extends ChartBehavior { final Color themeFillColor = themeData.colorScheme.surface; for (final ChartPointInfo pointInfo in chartPointInfo) { final dynamic series = pointInfo.series; - final bool isVisible = markerAutoVisibility - ? series is IndicatorRenderer || - (series != null && series.markerSettings.isVisible) - : markerIsVisible; + final bool isVisible = + markerAutoVisibility + ? series is IndicatorRenderer || + (series != null && series.markerSettings.isVisible) + : markerIsVisible; if (isVisible) { final Color color = pointInfo.color!; - final ChartMarker marker = ChartMarker() - ..x = pointInfo.markerXPos! - ..y = pointInfo.markerYPos! - ..index = pointInfo.dataPointIndex! - ..borderColor = color - ..color = themeFillColor; + final ChartMarker marker = + ChartMarker() + ..x = pointInfo.markerXPos! + ..y = pointInfo.markerYPos! + ..index = pointInfo.dataPointIndex! + ..borderColor = color + ..color = themeFillColor; if (markerSettings != null) { marker.merge( borderColor: markerSettings!.borderColor ?? color, @@ -2162,8 +2387,10 @@ class TrackballBehavior extends ChartBehavior { type: markerSettings!.shape, ); } - marker.position = - Offset(marker.x - marker.width / 2, marker.y - marker.height / 2); + marker.position = Offset( + marker.x - marker.width / 2, + marker.y - marker.height / 2, + ); source.add(marker); } } @@ -2181,9 +2408,10 @@ class TrackballBehavior extends ChartBehavior { final double markerSize = canShowMarker ? trackballTooltipMarkerSize : 0; final double padding = canShowMarker ? 0 : defaultTrackballPadding; final double markerSizeWithPadding = defaultTrackballPadding + markerSize; - final double x = isRtl - ? tooltipRRect.right - markerSizeWithPadding - padding - : tooltipRRect.left + markerSizeWithPadding + padding; + final double x = + isRtl + ? tooltipRRect.right - markerSizeWithPadding - padding + : tooltipRRect.left + markerSizeWithPadding + padding; final double y = tooltipRRect.top + defaultTrackballPadding; if (tooltipSettings.format != null) { _computeFormatTooltipLabels(x, y, text, textStyle, isRtl); @@ -2193,17 +2421,26 @@ class TrackballBehavior extends ChartBehavior { _computeDefaultTooltipLabels(x, y, text, textStyle, isRtl); } else { // It represents for xYDataSeries. - final TextStyle boldStyle = - _createLabelStyle(FontWeight.bold, textStyle); - final Offset offset = - Offset(isRtl ? x - measureText(text, boldStyle).width : x, y); + final TextStyle boldStyle = _createLabelStyle( + FontWeight.bold, + textStyle, + ); + final Offset offset = Offset( + isRtl ? x - measureText(text, boldStyle).width : x, + y, + ); _tooltipLabels.add(_TooltipLabels(text, boldStyle, offset)); } } } void _computeDefaultTooltipLabels( - double x, double y, String text, TextStyle textStyle, bool isRtl) { + double x, + double y, + String text, + TextStyle textStyle, + bool isRtl, + ) { final TextStyle boldStyle = _createLabelStyle(FontWeight.bold, textStyle); double eachTextHeight = 0; final List labels = text.split('\n'); @@ -2222,17 +2459,21 @@ class TrackballBehavior extends ChartBehavior { eachTextHeight += isRtl ? rightSize.height : leftSize.height; if (isRtl) { dx -= rightSize.width; - _tooltipLabels - .add(_TooltipLabels(rightText, textStyle, Offset(dx, dy))); + _tooltipLabels.add( + _TooltipLabels(rightText, textStyle, Offset(dx, dy)), + ); dx -= leftSize.width; - _tooltipLabels - .add(_TooltipLabels(leftText, boldStyle, Offset(dx, dy))); + _tooltipLabels.add( + _TooltipLabels(leftText, boldStyle, Offset(dx, dy)), + ); } else { - _tooltipLabels - .add(_TooltipLabels(leftText, textStyle, Offset(dx, dy))); + _tooltipLabels.add( + _TooltipLabels(leftText, textStyle, Offset(dx, dy)), + ); dx += leftSize.width; - _tooltipLabels - .add(_TooltipLabels(rightText, boldStyle, Offset(dx, dy))); + _tooltipLabels.add( + _TooltipLabels(rightText, boldStyle, Offset(dx, dy)), + ); } } } else { @@ -2247,7 +2488,12 @@ class TrackballBehavior extends ChartBehavior { } void _computeFormatTooltipLabels( - double x, double y, String text, TextStyle textStyle, bool isRtl) { + double x, + double y, + String text, + TextStyle textStyle, + bool isRtl, + ) { if (text.contains('\n')) { _multiLineLabelFormat(x, y, text, textStyle, isRtl); } else { @@ -2264,7 +2510,12 @@ class TrackballBehavior extends ChartBehavior { } void _multiLineLabelFormat( - double x, double y, String label, TextStyle textStyle, bool isRtl) { + double x, + double y, + String label, + TextStyle textStyle, + bool isRtl, + ) { double dy = y; final List multiLines = label.split('\n'); for (final String text in multiLines) { @@ -2283,7 +2534,12 @@ class TrackballBehavior extends ChartBehavior { } void _singleLineLabelFormat( - double x, double y, String label, TextStyle textStyle, bool isRtl) { + double x, + double y, + String label, + TextStyle textStyle, + bool isRtl, + ) { final TextStyle boldStyle = _createLabelStyle(FontWeight.bold, textStyle); double dx = x; if (label.contains('') && label.contains('')) { @@ -2311,8 +2567,9 @@ class TrackballBehavior extends ChartBehavior { j == partsStart ? boldStyle : textStyle; final Size textSize = measureText(part, currentStyle); dx -= textSize.width; - _tooltipLabels - .add(_TooltipLabels(part, currentStyle, Offset(dx, y))); + _tooltipLabels.add( + _TooltipLabels(part, currentStyle, Offset(dx, y)), + ); } } else { dx -= measureText(text, textStyle).width; @@ -2339,8 +2596,9 @@ class TrackballBehavior extends ChartBehavior { final TextStyle currentStyle = j == 0 ? boldStyle : textStyle; final Size textSize = measureText(part, currentStyle); - _tooltipLabels - .add(_TooltipLabels(part, currentStyle, Offset(dx, y))); + _tooltipLabels.add( + _TooltipLabels(part, currentStyle, Offset(dx, y)), + ); dx += textSize.width; } } else { @@ -2360,25 +2618,40 @@ class TrackballBehavior extends ChartBehavior { /// Override this method to customize the trackball tooltip labels /// and it's positions and line rendering. @override - void onPaint(PaintingContext context, Offset offset, - SfChartThemeData chartThemeData, ThemeData themeData) { + void onPaint( + PaintingContext context, + Offset offset, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) { _drawTrackballLine(context, offset, chartThemeData, themeData); // Draw line marker. _drawMarkers(context, chartThemeData, _lineMarkers); _drawLabel(context, offset, chartThemeData, themeData); } - void _drawTrackballLine(PaintingContext context, Offset offset, - SfChartThemeData chartThemeData, ThemeData themeData) { + void _drawTrackballLine( + PaintingContext context, + Offset offset, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) { if (chartPointInfo.isNotEmpty && lineType != TrackballLineType.none) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = (lineColor ?? chartThemeData.crosshairLineColor)! - ..strokeWidth = lineWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = (lineColor ?? chartThemeData.crosshairLineColor)! + ..strokeWidth = lineWidth + ..style = PaintingStyle.stroke; _drawLine( - context, offset, chartThemeData, themeData, lineDashArray, paint); + context, + offset, + chartThemeData, + themeData, + lineDashArray, + paint, + ); } } @@ -2410,8 +2683,12 @@ class TrackballBehavior extends ChartBehavior { drawDashes(context.canvas, dashArray, paint, path: path); } - void _drawLabel(PaintingContext context, Offset offset, - SfChartThemeData chartThemeData, ThemeData themeData) { + void _drawLabel( + PaintingContext context, + Offset offset, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (parent == null) { return; @@ -2423,16 +2700,18 @@ class TrackballBehavior extends ChartBehavior { if (_tooltipPaths.isNotEmpty) { final Color themeBackgroundColor = chartThemeData.crosshairBackgroundColor!; - final Paint fillPaint = Paint() - ..color = tooltipSettings.color ?? themeBackgroundColor - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..color = tooltipSettings.borderColor ?? themeBackgroundColor - ..strokeWidth = tooltipSettings.borderWidth - ..strokeCap = StrokeCap.butt - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint fillPaint = + Paint() + ..color = tooltipSettings.color ?? themeBackgroundColor + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint strokePaint = + Paint() + ..color = tooltipSettings.borderColor ?? themeBackgroundColor + ..strokeWidth = tooltipSettings.borderWidth + ..strokeCap = StrokeCap.butt + ..isAntiAlias = true + ..style = PaintingStyle.stroke; final int length = _tooltipPaths.length; for (int i = 0; i < length; i++) { final Path path = _tooltipPaths[i]; @@ -2465,21 +2744,31 @@ class TrackballBehavior extends ChartBehavior { for (int i = 0; i < length; i++) { final _TooltipLabels label = _tooltipLabels[i]; _drawText( - context.canvas, label.text, label.position, label.style, isRtl); + context.canvas, + label.text, + label.position, + label.style, + isRtl, + ); } } } } - void _drawMarkers(PaintingContext context, SfChartThemeData chartThemeData, - List markers) { + void _drawMarkers( + PaintingContext context, + SfChartThemeData chartThemeData, + List markers, + ) { if (markers.isNotEmpty) { - final Paint fillPaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint fillPaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; for (final ChartMarker marker in markers) { fillPaint ..color = marker.color! @@ -2499,8 +2788,14 @@ class TrackballBehavior extends ChartBehavior { } } - void _drawMarker(Canvas canvas, Offset position, Size size, - DataMarkerType type, Paint fillPaint, Paint strokePaint) { + void _drawMarker( + Canvas canvas, + Offset position, + Size size, + DataMarkerType type, + Paint fillPaint, + Paint strokePaint, + ) { if (position.isNaN) { return; } @@ -2508,7 +2803,10 @@ class TrackballBehavior extends ChartBehavior { if (type == DataMarkerType.image) { if (_trackballImage != null) { paintImage( - canvas: canvas, rect: position & size, image: _trackballImage!); + canvas: canvas, + rect: position & size, + image: _trackballImage!, + ); } } else if (type != DataMarkerType.none) { paint( @@ -2521,8 +2819,13 @@ class TrackballBehavior extends ChartBehavior { } } - void _drawText(Canvas canvas, String text, Offset position, TextStyle style, - bool isRtl) { + void _drawText( + Canvas canvas, + String text, + Offset position, + TextStyle style, + bool isRtl, + ) { final TextPainter textPainter = TextPainter( text: TextSpan(text: text, style: style), textAlign: isRtl ? TextAlign.right : TextAlign.left, @@ -2560,16 +2863,16 @@ class TrackballOpacityRenderBox extends RenderOpacity { } class TrackballBuilderRenderObjectWidget extends SingleChildRenderObjectWidget { - const TrackballBuilderRenderObjectWidget( - {Key? key, - this.index, - required this.xPos, - required this.yPos, - required this.builder, - required this.chartPointInfo, - required this.trackballBehavior, - required Widget child}) - : super(key: key, child: child); + const TrackballBuilderRenderObjectWidget({ + Key? key, + this.index, + required this.xPos, + required this.yPos, + required this.builder, + required this.chartPointInfo, + required this.trackballBehavior, + required Widget child, + }) : super(key: key, child: child); final int? index; final double xPos; @@ -2592,7 +2895,9 @@ class TrackballBuilderRenderObjectWidget extends SingleChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, covariant TrackballBuilderRenderBox renderObject) { + BuildContext context, + covariant TrackballBuilderRenderBox renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..index = index @@ -2607,10 +2912,15 @@ class TrackballBuilderRenderObjectWidget extends SingleChildRenderObjectWidget { /// Render the annotation widget in the respective position. class TrackballBuilderRenderBox extends RenderShiftedBox { /// Creates an instance of trackball template render box. - TrackballBuilderRenderBox(this.index, this.xPos, this.yPos, this._builder, - this.chartPointInfo, this.trackballBehavior, - [RenderBox? child]) - : super(child); + TrackballBuilderRenderBox( + this.index, + this.xPos, + this.yPos, + this._builder, + this.chartPointInfo, + this.trackballBehavior, [ + RenderBox? child, + ]) : super(child); /// Holds the value of x and y position. double xPos, yPos; @@ -2688,7 +2998,8 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { @override void performLayout() { size = constraints.biggest; - isTransposed = chartPointInfo != null && + isTransposed = + chartPointInfo != null && chartPointInfo!.isNotEmpty && chartPointInfo![0].series!.isTransposed; final TrackballDisplayMode tooltipDisplayMode = @@ -2730,8 +3041,8 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { if (isGroupAllPoints) { final ChartAlignment tooltipAlignment = trackballBehavior.tooltipAlignment; - final Offset tooltipPosition = - trackballBehavior._defaultGroupPosition(xPos, yPos); + final Offset tooltipPosition = trackballBehavior + ._defaultGroupPosition(xPos, yPos); xPos = tooltipPosition.dx; yPos = tooltipPosition.dy; if (isTransposed) { @@ -2758,42 +3069,51 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { final Offset visiblePoint = visiblePoints[i]; final double closestPointX = visiblePoint.dx; final double closestPointY = visiblePoint.dy; - tooltipTop.add(isTransposed - ? closestPointX - templateHalfWidth - : closestPointY - templateHalfHeight); - tooltipBottom.add(isTransposed - ? closestPointX + templateHalfWidth - : closestPointY + templateHalfHeight); + tooltipTop.add( + isTransposed + ? closestPointX - templateHalfWidth + : closestPointY - templateHalfHeight, + ); + tooltipBottom.add( + isTransposed + ? closestPointX + templateHalfWidth + : closestPointY + templateHalfHeight, + ); xAxesInfo.add(series.xAxis!); yAxesInfo.add(series.yAxis!); } if (tooltipTop.isNotEmpty) { _tooltipPosition = trackballBehavior._smartTooltipPositions( - tooltipTop, - tooltipBottom, - xAxesInfo, - yAxesInfo, - chartPointInfo!, - isTransposed ? 8 : 5); + tooltipTop, + tooltipBottom, + xAxesInfo, + yAxesInfo, + chartPointInfo!, + isTransposed ? 8 : 5, + ); } if (isNearestPoint) { - left = isTransposed - ? xPos + templateHalfWidth - : xPos + padding + markerHalfWidth; - top = isTransposed - ? yPos + padding + markerHalfWidth - : yPos - templateHalfHeight; + left = + isTransposed + ? xPos + templateHalfWidth + : xPos + padding + markerHalfWidth; + top = + isTransposed + ? yPos + padding + markerHalfWidth + : yPos - templateHalfHeight; } else { - left = (isTransposed - ? _tooltipPosition!.tooltipTop[index!] - : xPos + padding + markerHalfWidth) - .toDouble(); - top = (isTransposed - ? yPos + pointerLength + markerHalfWidth - : _tooltipPosition!.tooltipTop[index!]) - .toDouble(); + left = + (isTransposed + ? _tooltipPosition!.tooltipTop[index!] + : xPos + padding + markerHalfWidth) + .toDouble(); + top = + (isTransposed + ? yPos + pointerLength + markerHalfWidth + : _tooltipPosition!.tooltipTop[index!]) + .toDouble(); } if (!isTransposed) { @@ -2812,8 +3132,12 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { } } - trackballTemplateRect = - Rect.fromLTWH(left, top, templateFullWidth, templateFullHeight); + trackballTemplateRect = Rect.fromLTWH( + left, + top, + templateFullWidth, + templateFullHeight, + ); double xPlotOffset = visiblePoints.first.dx - trackballTemplateRect!.width / 2; final double rightTemplateEnd = @@ -2832,7 +3156,8 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { xPlotOffset = xPlotOffset + (boundaryLeft - xPlotOffset); if (xPlotOffset + trackballTemplateRect!.width > boundaryRight) { - xPlotOffset = xPlotOffset - + xPlotOffset = + xPlotOffset - (totalWidth + trackballTemplateRect!.width - boundaryRight); @@ -2844,7 +3169,8 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { } else if (leftTemplateEnd < boundaryLeft) { xPlotOffset = xPlotOffset + (boundaryLeft - leftTemplateEnd); if (xPlotOffset + trackballTemplateRect!.width > boundaryRight) { - xPlotOffset = xPlotOffset - + xPlotOffset = + xPlotOffset - (totalWidth + trackballTemplateRect!.width - boundaryRight); if (xPlotOffset < boundaryLeft) { xPlotOffset = xPlotOffset + (boundaryLeft - xPlotOffset); @@ -2876,8 +3202,10 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { } childParentData.offset = Offset(xPlotOffset, yPlotOffset); } else { - child!.layout(constraints.copyWith(maxWidth: 0), - parentUsesSize: true); + child!.layout( + constraints.copyWith(maxWidth: 0), + parentUsesSize: true, + ); isTemplateInBounds = false; } } else { @@ -2907,7 +3235,11 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { } trackballTemplateRect = Rect.fromLTWH( - xPos, yPos, templateFullWidth, templateFullHeight); + xPos, + yPos, + templateFullWidth, + templateFullHeight, + ); double xPlotOffset = visiblePoints.first.dx - trackballTemplateRect!.width / 2; final double rightTemplateEnd = @@ -2915,7 +3247,9 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { final double leftTemplateEnd = xPlotOffset; if (_isTemplateWithinBounds( - plotAreaBounds, trackballTemplateRect!)) { + plotAreaBounds, + trackballTemplateRect!, + )) { isTemplateInBounds = true; childParentData.offset = Offset(xPos, yPos); } else if (plotAreaBounds.width > trackballTemplateRect!.width && @@ -2927,7 +3261,8 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { xPlotOffset = xPlotOffset + (boundaryLeft - xPlotOffset); if (xPlotOffset + trackballTemplateRect!.width > boundaryRight) { - xPlotOffset = xPlotOffset - + xPlotOffset = + xPlotOffset - (totalWidth + trackballTemplateRect!.width - boundaryRight); @@ -2941,7 +3276,8 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { xPlotOffset = xPlotOffset + (boundaryLeft - leftTemplateEnd); if (xPlotOffset + trackballTemplateRect!.width > boundaryRight) { - xPlotOffset = xPlotOffset - + xPlotOffset = + xPlotOffset - (xPlotOffset + trackballTemplateRect!.width - boundaryRight); @@ -2957,8 +3293,10 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { childParentData.offset = Offset(xPlotOffset, yPos); } else { - child!.layout(constraints.copyWith(maxWidth: 0), - parentUsesSize: true); + child!.layout( + constraints.copyWith(maxWidth: 0), + parentUsesSize: true, + ); isTemplateInBounds = false; } } @@ -2977,23 +3315,28 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { bool _isTemplateWithinBounds(Rect plotAreaBounds, Rect templateRect) { final double triplePadding = (3 * padding).toDouble(); final Rect rect = Rect.fromLTWH( - padding + templateRect.left, - triplePadding + templateRect.top, - templateRect.width, - templateRect.height); + padding + templateRect.left, + triplePadding + templateRect.top, + templateRect.width, + templateRect.height, + ); final Rect axisBounds = Rect.fromLTWH( - padding + plotAreaBounds.left, - triplePadding + plotAreaBounds.top, - plotAreaBounds.width, - plotAreaBounds.height); + padding + plotAreaBounds.left, + triplePadding + plotAreaBounds.top, + plotAreaBounds.width, + plotAreaBounds.height, + ); return rect.left >= axisBounds.left && rect.left + rect.width <= axisBounds.left + axisBounds.width && rect.top >= axisBounds.top && rect.bottom <= axisBounds.top + axisBounds.height; } - void _calculateMarkerPositions(PaintingContext context, - SfChartThemeData chartThemeData, ThemeData themeData) { + void _calculateMarkerPositions( + PaintingContext context, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) { final TrackballMarkerSettings? markerSettings = trackballBehavior.markerSettings; if ((chartPointInfo != null && chartPointInfo!.isEmpty) || @@ -3031,31 +3374,36 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { final Color chartThemeBackgroundColor = chartThemeData.crosshairBackgroundColor!; final ChartPointInfo pointInfo = chartPointInfo![index!]; - final Color color = pointInfo.series is IndicatorRenderer - ? pointInfo.color - : (pointInfo.series!.color) ?? chartThemeBackgroundColor; + final Color color = + pointInfo.series is IndicatorRenderer + ? pointInfo.color + : (pointInfo.series!.color) ?? chartThemeBackgroundColor; final InteractiveTooltip tooltipSettings = trackballBehavior.tooltipSettings; - final Paint fillPaint = Paint() - ..color = tooltipSettings.color ?? color - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..color = tooltipSettings.borderColor ?? color - ..strokeWidth = tooltipSettings.borderWidth - ..strokeCap = StrokeCap.butt - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint fillPaint = + Paint() + ..color = tooltipSettings.color ?? color + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint strokePaint = + Paint() + ..color = tooltipSettings.borderColor ?? color + ..strokeWidth = tooltipSettings.borderWidth + ..strokeCap = StrokeCap.butt + ..isAntiAlias = true + ..style = PaintingStyle.stroke; if (trackballTemplateRect!.left > plotAreaBounds.left && trackballTemplateRect!.right < plotAreaBounds.right) { final RRect templateRRect = RRect.fromRectAndRadius( - Rect.fromLTWH( - offset.dx + trackballTemplateRect!.left, - offset.dy + trackballTemplateRect!.top, - trackballTemplateRect!.width, - trackballTemplateRect!.height), - Radius.zero); + Rect.fromLTWH( + offset.dx + trackballTemplateRect!.left, + offset.dy + trackballTemplateRect!.top, + trackballTemplateRect!.width, + trackballTemplateRect!.height, + ), + Radius.zero, + ); String nosePosition = ''; if (!isTransposed) { @@ -3073,8 +3421,13 @@ class TrackballBuilderRenderBox extends RenderShiftedBox { } } - final Path nosePath = trackballBehavior._nosePath(nosePosition, - templateRRect, Offset(xPos, yPos), pointerLength, pointerWidth); + final Path nosePath = trackballBehavior._nosePath( + nosePosition, + templateRRect, + Offset(xPos, yPos), + pointerLength, + pointerWidth, + ); if (isTemplateInBounds) { context.canvas.drawPath(nosePath, fillPaint); @@ -3176,18 +3529,14 @@ class TrackballMarkerSettings extends MarkerSettings { shape, borderWidth, borderColor, - image + image, ]; return Object.hashAll(values); } } class TrackballInfo { - TrackballInfo({ - required this.position, - this.name, - this.color, - }); + TrackballInfo({required this.position, this.name, this.color}); /// Local position of the tooltip. final Offset? position; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/zooming.dart b/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/zooming.dart index 7ff23b09f..9221d906e 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/zooming.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/behaviors/zooming.dart @@ -38,6 +38,7 @@ class ZoomPanBehavior extends ChartBehavior { this.enablePanning = false, this.enableSelectionZooming = false, this.enableMouseWheelZooming = false, + this.enableDirectionalZooming = false, this.zoomMode = ZoomMode.xy, this.maximumZoomLevel = 0.01, this.selectionRectBorderWidth = 1, @@ -169,6 +170,41 @@ class ZoomPanBehavior extends ChartBehavior { /// ``` final bool enableMouseWheelZooming; + /// Enables or disables directional zooming + /// + /// Enables directional zooming behavior in the chart. When it set to true, + /// users can zoom in a specific direction (horizontal, vertical, or diagonal) based on + /// the angle of their pinch or drag gesture. This provides precise control over zooming, + /// especially in scenarios with dense or complex data. + /// + /// Directional zooming is effective only when both [enableDirectionalZooming] and + /// [enablePinching] are set to true. + /// + /// Directional zooming is designed specifically for finger interactions (touch gestures). + /// It is not effective for mouse or trackpad-based interactions. + /// + /// Defaults to `false`. + /// + /// ```dart + /// late ZoomPanBehavior zoomPanBehavior; + /// + /// void initState() { + /// zoomPanBehavior = ZoomPanBehavior( + /// enableDirectionalZooming: true, + /// zoomMode: ZoomMode.xy + /// enablePinching: true, + /// ); + /// super.initState(); + /// } + /// + /// Widget build(BuildContext context) { + /// return SfCartesianChart( + /// zoomPanBehavior: zoomPanBehavior, + /// ); + /// } + /// ``` + final bool enableDirectionalZooming; + /// By default, both the x and y-axes in the chart can be zoomed. /// /// It can be changed by setting value to this property. @@ -312,6 +348,37 @@ class ZoomPanBehavior extends ChartBehavior { // Holds the path of the zooming rect. Path? _rectPath; + // Determines zoom direction (horizontal, vertical or both) based on scale changes and angle. + ZoomMode _computeDirectionalZoomMode(ScaleUpdateDetails details) { + final double scale = details.scale; + final double horizontalScale = details.horizontalScale; + final double verticalScale = details.verticalScale; + final double dx = (scale - horizontalScale).abs(); + final double dy = (scale - verticalScale).abs(); + final double angle = ((180 / pi) * atan2(dx, dy)).abs(); + + final bool isXDirection = + (angle >= 340 && angle <= 360) || + (angle >= 0 && angle <= 20) || + (angle >= 160 && angle <= 200); + final bool isYDirection = + (angle >= 70 && angle <= 110) || (angle >= 250 && angle <= 290); + final bool isBothDirection = + (angle > 20 && angle < 70) || + (angle > 110 && angle < 160) || + (angle > 200 && angle < 250) || + (angle > 290 && angle < 340); + + if (isBothDirection) { + return ZoomMode.xy; + } else if (isXDirection) { + return ZoomMode.x; + } else if (isYDirection) { + return ZoomMode.y; + } + return ZoomMode.xy; + } + @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { @@ -328,6 +395,7 @@ class ZoomPanBehavior extends ChartBehavior { other.enablePanning == enablePanning && other.enableSelectionZooming == enableSelectionZooming && other.enableMouseWheelZooming == enableMouseWheelZooming && + other.enableDirectionalZooming == enableDirectionalZooming && other.zoomMode == zoomMode && other.maximumZoomLevel == maximumZoomLevel && other.selectionRectBorderWidth == selectionRectBorderWidth && @@ -344,11 +412,12 @@ class ZoomPanBehavior extends ChartBehavior { enablePanning, enableSelectionZooming, enableMouseWheelZooming, + enableDirectionalZooming, zoomMode, maximumZoomLevel, selectionRectBorderWidth, selectionRectBorderColor, - selectionRectColor + selectionRectColor, ]; return Object.hashAll(values); } @@ -397,6 +466,14 @@ class ZoomPanBehavior extends ChartBehavior { if (axes == null) { return; } + + // Directional zooming works only if both [enableDirectionalZooming] and + // [enablePinching] are true. + parent.directionalZoomMode = + enableDirectionalZooming && zoomMode == ZoomMode.xy + ? _computeDirectionalZoomMode(details) + : zoomMode; + if (details.pointerCount == 2) { parent.hideInteractiveTooltip(); _pinchZoom(axes, parent, details, details.localFocalPoint); @@ -501,26 +578,34 @@ class ZoomPanBehavior extends ChartBehavior { // Method to perform pan zooming. void _pan( - RenderCartesianAxes axes, RenderBehaviorArea parent, Offset position) { + RenderCartesianAxes axes, + RenderBehaviorArea parent, + Offset position, + ) { + final ZoomMode effectiveZoomMode = parent.effectiveZoomMode; double currentZoomPosition; double calcZoomPosition; if (_previousMovedPosition != null) { final Offset translatePosition = _previousMovedPosition! - position; axes.visitChildren((RenderObject child) { if (child is RenderChartAxis && child.controller.zoomFactor != 1) { - if (_canZoom(child)) { + if (_canZoom(child, effectiveZoomMode)) { child.zoomingInProgress = true; _previousScale ??= _toScaleValue(child.controller.zoomFactor); currentZoomPosition = child.controller.zoomPosition; calcZoomPosition = _toPanValue( - child.paintBounds, - translatePosition, - child.controller.zoomPosition, - _previousScale!, - child.isVertical, - child.isInversed); - currentZoomPosition = - _minMax(calcZoomPosition, 0, 1 - child.controller.zoomFactor); + child.paintBounds, + translatePosition, + child.controller.zoomPosition, + _previousScale!, + child.isVertical, + child.isInversed, + ); + currentZoomPosition = _minMax( + calcZoomPosition, + 0, + 1 - child.controller.zoomFactor, + ); if (currentZoomPosition != child.controller.zoomPosition) { child.controller.zoomPosition = currentZoomPosition; } @@ -535,18 +620,27 @@ class ZoomPanBehavior extends ChartBehavior { } // Method to perform pinch zooming - void _pinchZoom(RenderCartesianAxes axes, RenderBehaviorArea parent, - ScaleUpdateDetails details, Offset location) { + void _pinchZoom( + RenderCartesianAxes axes, + RenderBehaviorArea parent, + ScaleUpdateDetails details, + Offset location, + ) { + final ZoomMode effectiveZoomMode = parent.effectiveZoomMode; axes.visitChildren((RenderObject child) { if (child is RenderChartAxis) { - if (_canZoom(child)) { + if (_canZoom(child, effectiveZoomMode)) { child.zoomingInProgress = true; final double maxZoomLevel = _toScaleValue(maximumZoomLevel); - final double origin = - _calculateOrigin(child, child.paintBounds, location); - final double currentScale = zoomMode == ZoomMode.xy - ? details.scale - : child.isVertical + final double origin = _calculateOrigin( + child, + child.paintBounds, + location, + ); + final double currentScale = + effectiveZoomMode == ZoomMode.xy + ? details.scale + : child.isVertical ? details.verticalScale : details.horizontalScale; _previousScale ??= _toScaleValue(child.controller.zoomFactor); @@ -582,9 +676,16 @@ class ZoomPanBehavior extends ChartBehavior { return max(1 / _minMax(zoomFactor, 0, 1), 1); } - double _toPanValue(Rect bounds, Offset position, double zoomPosition, - double scale, bool isVertical, bool isInversed) { - double value = (isVertical + double _toPanValue( + Rect bounds, + Offset position, + double zoomPosition, + double scale, + bool isVertical, + bool isInversed, + ) { + double value = + (isVertical ? position.dy / bounds.height : position.dx / bounds.width) / scale; @@ -597,11 +698,11 @@ class ZoomPanBehavior extends ChartBehavior { } // Method to find the chart needs zooming or not. - bool _canZoom(RenderChartAxis axis) { - final bool canDirectionalZoom = zoomMode == ZoomMode.xy; + bool _canZoom(RenderChartAxis axis, ZoomMode effectiveZoomMode) { + final bool canDirectionalZoom = effectiveZoomMode == ZoomMode.xy; - if ((axis.isVertical && zoomMode == ZoomMode.y) || - (!axis.isVertical && zoomMode == ZoomMode.x) || + if ((axis.isVertical && effectiveZoomMode == ZoomMode.y) || + (!axis.isVertical && effectiveZoomMode == ZoomMode.x) || canDirectionalZoom) { return true; } @@ -611,7 +712,10 @@ class ZoomPanBehavior extends ChartBehavior { // Method to find the origin value based on touch position. double _calculateOrigin( - RenderChartAxis axis, Rect bounds, Offset? manipulation) { + RenderChartAxis axis, + Rect bounds, + Offset? manipulation, + ) { if (manipulation == null) { return 0.5; } @@ -627,21 +731,27 @@ class ZoomPanBehavior extends ChartBehavior { } if (axis.isVertical) { - origin = axis.isInversed - ? ((manipulation.dy - plotOffsetEnd) / bounds.height) - : 1 - ((manipulation.dy - plotOffsetStart) / bounds.height); + origin = + axis.isInversed + ? ((manipulation.dy - plotOffsetEnd) / bounds.height) + : 1 - ((manipulation.dy - plotOffsetStart) / bounds.height); } else { - origin = axis.isInversed - ? 1.0 - ((manipulation.dx - plotOffsetStart) / bounds.width) - : (manipulation.dx - plotOffsetEnd) / bounds.width; + origin = + axis.isInversed + ? 1.0 - ((manipulation.dx - plotOffsetStart) / bounds.width) + : (manipulation.dx - plotOffsetEnd) / bounds.width; } return origin; } // Method to update the zoom values. - void _zoom(RenderBehaviorArea parent, RenderChartAxis axis, - double originPoint, double cumulativeZoomLevel) { + void _zoom( + RenderBehaviorArea parent, + RenderChartAxis axis, + double originPoint, + double cumulativeZoomLevel, + ) { double currentZoomPosition; double currentZoomFactor; if (cumulativeZoomLevel == 1) { @@ -649,7 +759,8 @@ class ZoomPanBehavior extends ChartBehavior { currentZoomPosition = 0; } else { currentZoomFactor = _minMax(1 / cumulativeZoomLevel, 0, 1); - currentZoomPosition = axis.controller.zoomPosition + + currentZoomPosition = + axis.controller.zoomPosition + ((axis.controller.zoomFactor - currentZoomFactor) * originPoint); } @@ -657,8 +768,11 @@ class ZoomPanBehavior extends ChartBehavior { axis.controller.zoomFactor = currentZoomFactor; } if (axis.controller.zoomPosition != currentZoomPosition) { - axis.controller.zoomPosition = - _minMax(currentZoomPosition, 0, 1 - axis.controller.zoomFactor); + axis.controller.zoomPosition = _minMax( + currentZoomPosition, + 0, + 1 - axis.controller.zoomFactor, + ); } } @@ -731,9 +845,10 @@ class ZoomPanBehavior extends ChartBehavior { } final Rect clipRect = parent.paintBounds; + final ZoomMode effectiveZoomMode = parent.effectiveZoomMode; cartesianAxes.visitChildren((RenderObject child) { if (child is RenderChartAxis) { - if (_canZoom(child)) { + if (_canZoom(child, effectiveZoomMode)) { final double originPoint = _calculateOrigin(child, clipRect, origin); child.zoomingInProgress = true; if (parent.onZoomStart != null) { @@ -781,9 +896,10 @@ class ZoomPanBehavior extends ChartBehavior { if (cartesianAxes == null) { return; } + final ZoomMode effectiveZoomMode = parent.effectiveZoomMode; cartesianAxes.visitChildren((RenderObject child) { if (child is RenderChartAxis) { - if (_canZoom(child)) { + if (_canZoom(child, effectiveZoomMode)) { child.controller.zoomFactor = max(zoomFactor, maximumZoomLevel); if (parent.onZooming != null) { _bindZoomEvent(child, parent.onZooming!); @@ -806,16 +922,20 @@ class ZoomPanBehavior extends ChartBehavior { /// Here, you need to pass axis, zoom factor, zoom position of the zoom level /// that needs to be modified. void zoomToSingleAxis( - ChartAxis axis, double zoomPosition, double zoomFactor) { + ChartAxis axis, + double zoomPosition, + double zoomFactor, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (parent == null) { return; } parent.hideInteractiveTooltip(); - final RenderChartAxis? axisDetails = axis.name != null - ? parent.axisFromName(axis.name) - : parent.axisFromObject(axis); + final RenderChartAxis? axisDetails = + axis.name != null + ? parent.axisFromName(axis.name) + : parent.axisFromObject(axis); if (axisDetails != null) { axisDetails.controller.zoomFactor = max(zoomFactor, maximumZoomLevel); @@ -848,12 +968,18 @@ class ZoomPanBehavior extends ChartBehavior { child.controller.zoomPosition + (child.isInversed ? 0.1 : -0.1); if ((child.isVertical && direction == 'bottom') || (!child.isVertical && direction == 'left')) { - child.controller.zoomPosition = - _minMax(decreaseZoomPosition, 0, 1 - currentZoomFactor); + child.controller.zoomPosition = _minMax( + decreaseZoomPosition, + 0, + 1 - currentZoomFactor, + ); } else if ((child.isVertical && direction == 'top') || (!child.isVertical && direction == 'right')) { - child.controller.zoomPosition = - _minMax(increaseZoomPosition, 0, 1 - currentZoomFactor); + child.controller.zoomPosition = _minMax( + increaseZoomPosition, + 0, + 1 - currentZoomFactor, + ); } if (parent.onZooming != null) { _bindZoomEvent(child, parent.onZooming!); @@ -888,12 +1014,15 @@ class ZoomPanBehavior extends ChartBehavior { } ZoomPanArgs _bindZoomEvent( - RenderChartAxis axis, ChartZoomingCallback zoomEventType) { + RenderChartAxis axis, + ChartZoomingCallback zoomEventType, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; final ZoomPanArgs zoomPanArgs = ZoomPanArgs( - axis, - axis.controller.previousZoomPosition, - axis.controller.previousZoomFactor); + axis, + axis.controller.previousZoomPosition, + axis.controller.previousZoomFactor, + ); zoomPanArgs.currentZoomFactor = axis.controller.zoomFactor; zoomPanArgs.currentZoomPosition = axis.controller.zoomPosition; if (parent == null) { @@ -902,15 +1031,18 @@ class ZoomPanBehavior extends ChartBehavior { zoomEventType == parent.onZoomStart ? parent.onZoomStart!(zoomPanArgs) : zoomEventType == parent.onZoomEnd - ? parent.onZoomEnd!(zoomPanArgs) - : zoomEventType == parent.onZooming - ? parent.onZooming!(zoomPanArgs) - : parent.onZoomReset!(zoomPanArgs); + ? parent.onZoomEnd!(zoomPanArgs) + : zoomEventType == parent.onZooming + ? parent.onZooming!(zoomPanArgs) + : parent.onZoomReset!(zoomPanArgs); return zoomPanArgs; } void _doSelectionZooming( - LongPressMoveUpdateDetails details, double currentX, double currentY) { + LongPressMoveUpdateDetails details, + double currentX, + double currentY, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (parent == null) { return; @@ -923,19 +1055,26 @@ class ZoomPanBehavior extends ChartBehavior { ); Offset currentMousePosition = startPosition + details.localOffsetFromOrigin; - final double currentX = - _minMax(currentMousePosition.dx, clipRect.left, clipRect.right); - final double currentY = - _minMax(currentMousePosition.dy, clipRect.top, clipRect.bottom); + final double currentX = _minMax( + currentMousePosition.dx, + clipRect.left, + clipRect.right, + ); + final double currentY = _minMax( + currentMousePosition.dy, + clipRect.top, + clipRect.bottom, + ); currentMousePosition = Offset(currentX, currentY); _rectPath = Path(); - if (zoomMode == ZoomMode.x) { + final ZoomMode effectiveZoomMode = parent.effectiveZoomMode; + if (effectiveZoomMode == ZoomMode.x) { _rectPath!.moveTo(startPosition.dx, clipRect.top); _rectPath!.lineTo(startPosition.dx, clipRect.bottom); _rectPath!.lineTo(currentMousePosition.dx, clipRect.bottom); _rectPath!.lineTo(currentMousePosition.dx, clipRect.top); _rectPath!.close(); - } else if (zoomMode == ZoomMode.y) { + } else if (effectiveZoomMode == ZoomMode.y) { _rectPath!.moveTo(clipRect.left, startPosition.dy); _rectPath!.lineTo(clipRect.left, currentMousePosition.dy); _rectPath!.lineTo(clipRect.right, currentMousePosition.dy); @@ -970,27 +1109,32 @@ class ZoomPanBehavior extends ChartBehavior { _bindZoomEvent(child, parent.onZoomStart!); } final Rect clipRect = child.paintBounds; + final ZoomMode effectiveZoomMode = parent.effectiveZoomMode; if (child.isVertical) { - if (zoomMode != ZoomMode.x) { + if (effectiveZoomMode != ZoomMode.x) { final double zoomRectHeightFromTop = zoomRect.height + (zoomRect.top - clipRect.top); child.controller.zoomPosition += (1 - (zoomRectHeightFromTop / clipRect.height).abs()) * - child.controller.zoomFactor; + child.controller.zoomFactor; child.controller.zoomFactor *= zoomRect.height / clipRect.height; - child.controller.zoomFactor = - max(child.controller.zoomFactor, maximumZoomLevel); + child.controller.zoomFactor = max( + child.controller.zoomFactor, + maximumZoomLevel, + ); } } else { - if (zoomMode != ZoomMode.y) { + if (effectiveZoomMode != ZoomMode.y) { final double zoomRectWidthFromLeft = zoomRect.left - clipRect.left; child.controller.zoomPosition += (zoomRectWidthFromLeft / clipRect.width).abs() * - child.controller.zoomFactor; + child.controller.zoomFactor; child.controller.zoomFactor *= zoomRect.width / child.paintBounds.width; - child.controller.zoomFactor = - max(child.controller.zoomFactor, maximumZoomLevel); + child.controller.zoomFactor = max( + child.controller.zoomFactor, + maximumZoomLevel, + ); } } if (parent.onZoomEnd != null) { @@ -1003,42 +1147,49 @@ class ZoomPanBehavior extends ChartBehavior { } void _drawTooltipConnector( - RenderCartesianAxes axes, - RenderBehaviorArea? parent, - Offset startPosition, - Offset endPosition, - Canvas canvas, - Rect plotAreaBounds, - Offset plotAreaOffset) { + RenderCartesianAxes axes, + RenderBehaviorArea? parent, + Offset startPosition, + Offset endPosition, + Canvas canvas, + Rect plotAreaBounds, + Offset plotAreaOffset, + ) { RRect? startTooltipRect, endTooltipRect; String startValue, endValue; Size startLabelSize, endLabelSize; Rect startLabelRect, endLabelRect; TextStyle textStyle = parent!.chartThemeData!.selectionZoomingTooltipTextStyle!; - final Paint labelFillPaint = Paint() - ..color = axes.chartThemeData.crosshairBackgroundColor! - ..isAntiAlias = true; + final Paint labelFillPaint = + Paint() + ..color = axes.chartThemeData.crosshairBackgroundColor! + ..isAntiAlias = true; - final Paint labelStrokePaint = Paint() - ..color = axes.chartThemeData.crosshairBackgroundColor! - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint labelStrokePaint = + Paint() + ..color = axes.chartThemeData.crosshairBackgroundColor! + ..isAntiAlias = true + ..style = PaintingStyle.stroke; axes.visitChildren((RenderObject child) { if (child is RenderChartAxis) { if (child.interactiveTooltip.enable) { textStyle = textStyle.merge(child.interactiveTooltip.textStyle); - labelFillPaint.color = (child.interactiveTooltip.color ?? - axes.chartThemeData.crosshairBackgroundColor)!; - labelStrokePaint.color = (child.interactiveTooltip.borderColor ?? - axes.chartThemeData.crosshairBackgroundColor)!; + labelFillPaint.color = + (child.interactiveTooltip.color ?? + axes.chartThemeData.crosshairBackgroundColor)!; + labelStrokePaint.color = + (child.interactiveTooltip.borderColor ?? + axes.chartThemeData.crosshairBackgroundColor)!; labelStrokePaint.strokeWidth = child.interactiveTooltip.borderWidth; - final Paint connectorLinePaint = Paint() - ..color = (child.interactiveTooltip.connectorLineColor ?? - axes.chartThemeData.selectionTooltipConnectorLineColor)! - ..strokeWidth = child.interactiveTooltip.connectorLineWidth - ..style = PaintingStyle.stroke; + final Paint connectorLinePaint = + Paint() + ..color = + (child.interactiveTooltip.connectorLineColor ?? + axes.chartThemeData.selectionTooltipConnectorLineColor)! + ..strokeWidth = child.interactiveTooltip.connectorLineWidth + ..style = PaintingStyle.stroke; final Path startLabelPath = Path(); final Path endLabelPath = Path(); @@ -1048,49 +1199,67 @@ class ZoomPanBehavior extends ChartBehavior { if (startValue.isNotEmpty && endValue.isNotEmpty) { startLabelSize = measureText(startValue, textStyle); endLabelSize = measureText(endValue, textStyle); - startLabelRect = - calculateRect(child, startPosition, startLabelSize); + startLabelRect = calculateRect( + child, + startPosition, + startLabelSize, + ); endLabelRect = calculateRect(child, endPosition, endLabelSize); if (child.isVertical && startLabelRect.width != endLabelRect.width) { final String axisPosition = child.opposedPosition ? 'right' : 'left'; (startLabelRect.width > endLabelRect.width) - ? endLabelRect = - validateRect(startLabelRect, endLabelRect, axisPosition) - : startLabelRect = - validateRect(endLabelRect, startLabelRect, axisPosition); + ? endLabelRect = validateRect( + startLabelRect, + endLabelRect, + axisPosition, + ) + : startLabelRect = validateRect( + endLabelRect, + startLabelRect, + axisPosition, + ); } startTooltipRect = calculateTooltipRect( - canvas, - labelFillPaint, - labelStrokePaint, - startLabelPath, - startPosition, - startLabelRect, - startTooltipRect, - startValue, - startLabelSize, - plotAreaBounds, - textStyle, - child, - plotAreaOffset); + canvas, + labelFillPaint, + labelStrokePaint, + startLabelPath, + startPosition, + startLabelRect, + startTooltipRect, + startValue, + startLabelSize, + plotAreaBounds, + textStyle, + child, + plotAreaOffset, + ); endTooltipRect = calculateTooltipRect( - canvas, - labelFillPaint, - labelStrokePaint, - endLabelPath, - endPosition, - endLabelRect, - endTooltipRect, - endValue, - endLabelSize, - plotAreaBounds, - textStyle, - child, - plotAreaOffset); - drawConnector(canvas, connectorLinePaint, startTooltipRect!, - endTooltipRect!, startPosition, endPosition, child); + canvas, + labelFillPaint, + labelStrokePaint, + endLabelPath, + endPosition, + endLabelRect, + endTooltipRect, + endValue, + endLabelSize, + plotAreaBounds, + textStyle, + child, + plotAreaOffset, + ); + drawConnector( + canvas, + connectorLinePaint, + startTooltipRect!, + endTooltipRect!, + startPosition, + endPosition, + child, + ); } } } @@ -1098,8 +1267,12 @@ class ZoomPanBehavior extends ChartBehavior { } @override - void onPaint(PaintingContext context, Offset offset, - SfChartThemeData chartThemeData, ThemeData themeData) { + void onPaint( + PaintingContext context, + Offset offset, + SfChartThemeData chartThemeData, + ThemeData themeData, + ) { final RenderBehaviorArea? parent = parentBox as RenderBehaviorArea?; if (parent == null) { return; @@ -1115,17 +1288,20 @@ class ZoomPanBehavior extends ChartBehavior { fillColor.a == 1) { fillColor = fillColor.withValues(alpha: 0.3); } - final Paint fillPaint = Paint() - ..color = - (fillColor ?? cartesianAxes.chartThemeData.selectionRectColor)! - ..style = PaintingStyle.fill; + final Paint fillPaint = + Paint() + ..color = + (fillColor ?? cartesianAxes.chartThemeData.selectionRectColor)! + ..style = PaintingStyle.fill; context.canvas.drawRect(_zoomingRect, fillPaint); - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..color = (selectionRectBorderColor ?? - cartesianAxes.chartThemeData.selectionRectBorderColor)! - ..strokeWidth = selectionRectBorderWidth - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..color = + (selectionRectBorderColor ?? + cartesianAxes.chartThemeData.selectionRectBorderColor)! + ..strokeWidth = selectionRectBorderWidth + ..style = PaintingStyle.stroke; if (strokePaint.color != Colors.transparent && strokePaint.strokeWidth > 0) { @@ -1137,13 +1313,14 @@ class ZoomPanBehavior extends ChartBehavior { (parent.parentData! as BoxParentData).offset; // Selection zooming tooltip rendering _drawTooltipConnector( - cartesianAxes, - parent, - _zoomingRect.topLeft, - _zoomingRect.bottomRight, - context.canvas, - parent.paintBounds, - plotAreaOffset); + cartesianAxes, + parent, + _zoomingRect.topLeft, + _zoomingRect.bottomRight, + context.canvas, + parent.paintBounds, + plotAreaOffset, + ); } } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/cartesian_chart.dart b/packages/syncfusion_flutter_charts/lib/src/charts/cartesian_chart.dart index 3fa022dfe..07a5062ad 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/cartesian_chart.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/cartesian_chart.dart @@ -1181,125 +1181,170 @@ class SfCartesianChartState extends State Widget? _trackballBuilder; SfChartThemeData _updateThemeData( - BuildContext context, ChartThemeData effectiveChartThemeData) { + BuildContext context, + ChartThemeData effectiveChartThemeData, + ) { SfChartThemeData chartThemeData = SfChartTheme.of(context); chartThemeData = chartThemeData.copyWith( axisLineColor: chartThemeData.axisLineColor ?? effectiveChartThemeData.axisLineColor, - axisLabelColor: chartThemeData.axisLabelColor ?? + axisLabelColor: + chartThemeData.axisLabelColor ?? effectiveChartThemeData.axisLabelColor, - axisTitleColor: chartThemeData.axisTitleColor ?? + axisTitleColor: + chartThemeData.axisTitleColor ?? effectiveChartThemeData.axisTitleColor, - titleTextColor: chartThemeData.titleTextColor ?? + titleTextColor: + chartThemeData.titleTextColor ?? effectiveChartThemeData.titleTextColor, - crosshairBackgroundColor: chartThemeData.crosshairBackgroundColor ?? + crosshairBackgroundColor: + chartThemeData.crosshairBackgroundColor ?? effectiveChartThemeData.crosshairBackgroundColor, - crosshairLabelColor: chartThemeData.crosshairLabelColor ?? + crosshairLabelColor: + chartThemeData.crosshairLabelColor ?? effectiveChartThemeData.crosshairLabelColor, - legendTextColor: chartThemeData.legendTextColor ?? + legendTextColor: + chartThemeData.legendTextColor ?? effectiveChartThemeData.legendTextColor, - legendTitleColor: chartThemeData.legendTitleColor ?? + legendTitleColor: + chartThemeData.legendTitleColor ?? effectiveChartThemeData.legendTitleColor, - majorGridLineColor: chartThemeData.majorGridLineColor ?? + majorGridLineColor: + chartThemeData.majorGridLineColor ?? effectiveChartThemeData.majorGridLineColor, - minorGridLineColor: chartThemeData.minorGridLineColor ?? + minorGridLineColor: + chartThemeData.minorGridLineColor ?? effectiveChartThemeData.minorGridLineColor, - majorTickLineColor: chartThemeData.majorTickLineColor ?? + majorTickLineColor: + chartThemeData.majorTickLineColor ?? effectiveChartThemeData.majorTickLineColor, - minorTickLineColor: chartThemeData.minorTickLineColor ?? + minorTickLineColor: + chartThemeData.minorTickLineColor ?? effectiveChartThemeData.minorTickLineColor, - selectionRectColor: chartThemeData.selectionRectColor ?? + selectionRectColor: + chartThemeData.selectionRectColor ?? effectiveChartThemeData.selectionRectColor, - selectionRectBorderColor: chartThemeData.selectionRectBorderColor ?? + selectionRectBorderColor: + chartThemeData.selectionRectBorderColor ?? effectiveChartThemeData.selectionRectBorderColor, selectionTooltipConnectorLineColor: chartThemeData.selectionTooltipConnectorLineColor ?? - effectiveChartThemeData.selectionTooltipConnectorLineColor, - waterfallConnectorLineColor: chartThemeData.waterfallConnectorLineColor ?? + effectiveChartThemeData.selectionTooltipConnectorLineColor, + waterfallConnectorLineColor: + chartThemeData.waterfallConnectorLineColor ?? effectiveChartThemeData.waterfallConnectorLineColor, - tooltipLabelColor: chartThemeData.tooltipLabelColor ?? + tooltipLabelColor: + chartThemeData.tooltipLabelColor ?? effectiveChartThemeData.tooltipLabelColor, - tooltipSeparatorColor: chartThemeData.tooltipSeparatorColor ?? + tooltipSeparatorColor: + chartThemeData.tooltipSeparatorColor ?? effectiveChartThemeData.tooltipSeparatorColor, - backgroundColor: widget.backgroundColor ?? + backgroundColor: + widget.backgroundColor ?? chartThemeData.backgroundColor ?? effectiveChartThemeData.backgroundColor, - titleBackgroundColor: widget.title.backgroundColor ?? + titleBackgroundColor: + widget.title.backgroundColor ?? chartThemeData.titleBackgroundColor ?? effectiveChartThemeData.titleBackgroundColor, - plotAreaBackgroundColor: widget.plotAreaBackgroundColor ?? + plotAreaBackgroundColor: + widget.plotAreaBackgroundColor ?? chartThemeData.plotAreaBackgroundColor ?? effectiveChartThemeData.plotAreaBackgroundColor, - plotAreaBorderColor: widget.plotAreaBorderColor ?? + plotAreaBorderColor: + widget.plotAreaBorderColor ?? chartThemeData.plotAreaBorderColor ?? effectiveChartThemeData.plotAreaBorderColor, - legendBackgroundColor: widget.legend.backgroundColor ?? + legendBackgroundColor: + widget.legend.backgroundColor ?? chartThemeData.legendBackgroundColor ?? effectiveChartThemeData.legendBackgroundColor, - crosshairLineColor: widget.crosshairBehavior?.lineColor ?? + crosshairLineColor: + widget.crosshairBehavior?.lineColor ?? chartThemeData.crosshairLineColor ?? effectiveChartThemeData.crosshairLineColor, - tooltipColor: widget.tooltipBehavior?.color ?? + tooltipColor: + widget.tooltipBehavior?.color ?? chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, titleTextStyle: effectiveChartThemeData.titleTextStyle! .copyWith( - color: chartThemeData.titleTextColor ?? - effectiveChartThemeData.titleTextColor) + color: + chartThemeData.titleTextColor ?? + effectiveChartThemeData.titleTextColor, + ) .merge(chartThemeData.titleTextStyle) .merge(widget.title.textStyle), axisTitleTextStyle: effectiveChartThemeData.axisTitleTextStyle! .copyWith( - color: chartThemeData.axisTitleColor ?? - effectiveChartThemeData.axisTitleColor) + color: + chartThemeData.axisTitleColor ?? + effectiveChartThemeData.axisTitleColor, + ) .merge(chartThemeData.axisTitleTextStyle), axisLabelTextStyle: effectiveChartThemeData.axisLabelTextStyle! .copyWith( - color: chartThemeData.axisLabelColor ?? - effectiveChartThemeData.axisLabelColor) + color: + chartThemeData.axisLabelColor ?? + effectiveChartThemeData.axisLabelColor, + ) .merge(chartThemeData.axisLabelTextStyle), axisMultiLevelLabelTextStyle: effectiveChartThemeData .axisMultiLevelLabelTextStyle! .copyWith( - color: chartThemeData.axisLabelColor ?? - effectiveChartThemeData.axisLabelColor) + color: + chartThemeData.axisLabelColor ?? + effectiveChartThemeData.axisLabelColor, + ) .merge(chartThemeData.axisMultiLevelLabelTextStyle), plotBandLabelTextStyle: effectiveChartThemeData.plotBandLabelTextStyle! .merge(chartThemeData.plotBandLabelTextStyle), legendTitleTextStyle: effectiveChartThemeData.legendTitleTextStyle! .copyWith( - color: chartThemeData.legendTitleColor ?? - effectiveChartThemeData.legendTitleColor) + color: + chartThemeData.legendTitleColor ?? + effectiveChartThemeData.legendTitleColor, + ) .merge(chartThemeData.legendTitleTextStyle) .merge(widget.legend.title?.textStyle), legendTextStyle: effectiveChartThemeData.legendTextStyle! .copyWith( - color: chartThemeData.legendTextColor ?? - effectiveChartThemeData.legendTextColor) + color: + chartThemeData.legendTextColor ?? + effectiveChartThemeData.legendTextColor, + ) .merge(chartThemeData.legendTextStyle) .merge(widget.legend.textStyle), tooltipTextStyle: effectiveChartThemeData.tooltipTextStyle! .copyWith( - color: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor) + color: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) .merge(chartThemeData.tooltipTextStyle) .merge(widget.tooltipBehavior?.textStyle), trackballTextStyle: effectiveChartThemeData.trackballTextStyle! .copyWith( - color: chartThemeData.crosshairLabelColor ?? - effectiveChartThemeData.crosshairLabelColor) + color: + chartThemeData.crosshairLabelColor ?? + effectiveChartThemeData.crosshairLabelColor, + ) .merge(chartThemeData.trackballTextStyle) .merge(widget.trackballBehavior?.tooltipSettings.textStyle), crosshairTextStyle: effectiveChartThemeData.crosshairTextStyle! .copyWith( - color: chartThemeData.crosshairLabelColor ?? - effectiveChartThemeData.crosshairLabelColor) + color: + chartThemeData.crosshairLabelColor ?? + effectiveChartThemeData.crosshairLabelColor, + ) .merge(chartThemeData.crosshairTextStyle), selectionZoomingTooltipTextStyle: effectiveChartThemeData .selectionZoomingTooltipTextStyle! .copyWith( - color: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor) + color: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) .merge(chartThemeData.selectionZoomingTooltipTextStyle), ); return chartThemeData; @@ -1324,9 +1369,18 @@ class SfCartesianChartState extends State } Widget? _buildTooltipWidget( - BuildContext context, TooltipInfo? info, Size maxSize) { - return buildTooltipWidget(context, info, maxSize, widget.tooltipBehavior, - _chartThemeData, _themeData); + BuildContext context, + TooltipInfo? info, + Size maxSize, + ) { + return buildTooltipWidget( + context, + info, + maxSize, + widget.tooltipBehavior, + _chartThemeData, + _themeData, + ); } void _buildTrackballWidget(List details) { @@ -1339,20 +1393,23 @@ class SfCartesianChartState extends State trackballBehavior.builder != null && chartPointInfo.isNotEmpty) { _trackballBuilder = Stack( - children: List.generate(details.length, (int index) { - final ChartPointInfo info = chartPointInfo[index]; - final Widget builder = - trackballBehavior.builder!.call(context, details[index]); - return TrackballBuilderRenderObjectWidget( - index: index, - xPos: info.xPosition!, - yPos: info.yPosition!, - builder: builder, - chartPointInfo: chartPointInfo, - trackballBehavior: trackballBehavior, - child: builder, - ); - }).toList(), + children: + List.generate(details.length, (int index) { + final ChartPointInfo info = chartPointInfo[index]; + final Widget builder = trackballBehavior.builder!.call( + context, + details[index], + ); + return TrackballBuilderRenderObjectWidget( + index: index, + xPos: info.xPosition!, + yPos: info.yPosition!, + builder: builder, + chartPointInfo: chartPointInfo, + trackballBehavior: trackballBehavior, + child: builder, + ); + }).toList(), ); } final RenderObjectElement? trackballBuilderElement = @@ -1376,7 +1433,9 @@ class SfCartesianChartState extends State } Widget _buildLoadingIndicator( - BuildContext context, BoxConstraints constraints) { + BuildContext context, + BoxConstraints constraints, + ) { if (widget.loadMoreIndicatorBuilder != null && _swipeDirection != null) { return widget.loadMoreIndicatorBuilder!(context, _swipeDirection!); } @@ -1416,28 +1475,36 @@ class SfCartesianChartState extends State isTransposed = !isTransposed; } - final core.LegendPosition legendPosition = - effectiveLegendPosition(widget.legend); - final Axis orientation = - effectiveLegendOrientation(legendPosition, widget.legend); + final core.LegendPosition legendPosition = effectiveLegendPosition( + widget.legend, + ); + final Axis orientation = effectiveLegendOrientation( + legendPosition, + widget.legend, + ); Widget current = core.LegendLayout( key: _legendKey, padding: EdgeInsets.zero, showLegend: widget.legend.isVisible, legendPosition: legendPosition, legendAlignment: effectiveLegendAlignment(widget.legend.alignment), - legendTitleAlignment: - effectiveLegendAlignment(widget.legend.title?.alignment), + legendTitleAlignment: effectiveLegendAlignment( + widget.legend.title?.alignment, + ), itemIconBorderColor: widget.legend.iconBorderColor, itemIconBorderWidth: widget.legend.iconBorderWidth, legendBorderColor: widget.legend.borderColor, legendBackgroundColor: _chartThemeData.legendBackgroundColor, legendBorderWidth: widget.legend.borderWidth, itemOpacity: widget.legend.opacity, - legendWidthFactor: - percentageToWidthFactor(widget.legend.width, legendPosition), - legendHeightFactor: - percentageToHeightFactor(widget.legend.height, legendPosition), + legendWidthFactor: percentageToWidthFactor( + widget.legend.width, + legendPosition, + ), + legendHeightFactor: percentageToHeightFactor( + widget.legend.height, + legendPosition, + ), itemInnerSpacing: widget.legend.padding, itemSpacing: 0.0, itemPadding: widget.legend.itemPadding, @@ -1462,7 +1529,8 @@ class SfCartesianChartState extends State crosshairBehavior: widget.crosshairBehavior, trackballBehavior: widget.trackballBehavior, zoomPanBehavior: widget.zoomPanBehavior, - hasLoadingIndicator: widget.loadMoreIndicatorBuilder != null || + hasLoadingIndicator: + widget.loadMoreIndicatorBuilder != null || widget.onPlotAreaSwipe != null, onChartTouchInteractionDown: widget.onChartTouchInteractionDown, onChartTouchInteractionMove: widget.onChartTouchInteractionMove, @@ -1512,7 +1580,7 @@ class SfCartesianChartState extends State children: [ widget.primaryXAxis, widget.primaryYAxis, - ...widget.axes + ...widget.axes, ], ), if (widget.indicators.isNotEmpty) @@ -1564,8 +1632,10 @@ class SfCartesianChartState extends State opacity: 1.0, child: CustomLayoutBuilder( key: _trackballBuilderKey, - builder: - (BuildContext context, BoxConstraints constraints) { + builder: ( + BuildContext context, + BoxConstraints constraints, + ) { return _trackballBuilder ?? const SizedBox(height: 0); }, ), @@ -1586,8 +1656,9 @@ class SfCartesianChartState extends State opacity: widget.tooltipBehavior!.opacity, borderColor: widget.tooltipBehavior!.borderColor, borderWidth: widget.tooltipBehavior!.borderWidth, - color: (widget.tooltipBehavior!.color ?? - _chartThemeData.tooltipColor)!, + color: + (widget.tooltipBehavior!.color ?? + _chartThemeData.tooltipColor)!, showDuration: widget.tooltipBehavior!.duration.toInt(), shadowColor: widget.tooltipBehavior!.shadowColor, elevation: widget.tooltipBehavior!.elevation, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/circular_chart.dart b/packages/syncfusion_flutter_charts/lib/src/charts/circular_chart.dart index 94b79edb0..0eaac161d 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/circular_chart.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/circular_chart.dart @@ -589,45 +589,60 @@ class SfCircularChartState extends State List? _annotations; SfChartThemeData _updateThemeData( - BuildContext context, ChartThemeData effectiveChartThemeData) { + BuildContext context, + ChartThemeData effectiveChartThemeData, + ) { SfChartThemeData chartThemeData = SfChartTheme.of(context); chartThemeData = chartThemeData.copyWith( - backgroundColor: widget.backgroundColor ?? + backgroundColor: + widget.backgroundColor ?? chartThemeData.backgroundColor ?? effectiveChartThemeData.backgroundColor, - titleBackgroundColor: widget.title.backgroundColor ?? + titleBackgroundColor: + widget.title.backgroundColor ?? chartThemeData.titleBackgroundColor ?? effectiveChartThemeData.titleBackgroundColor, - legendBackgroundColor: widget.legend.backgroundColor ?? + legendBackgroundColor: + widget.legend.backgroundColor ?? chartThemeData.legendBackgroundColor ?? effectiveChartThemeData.legendBackgroundColor, - tooltipColor: widget.tooltipBehavior?.color ?? + tooltipColor: + widget.tooltipBehavior?.color ?? chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - plotAreaBackgroundColor: chartThemeData.plotAreaBackgroundColor ?? + plotAreaBackgroundColor: + chartThemeData.plotAreaBackgroundColor ?? effectiveChartThemeData.plotAreaBackgroundColor, titleTextStyle: effectiveChartThemeData.titleTextStyle! .copyWith( - color: chartThemeData.titleTextColor ?? - effectiveChartThemeData.titleTextColor) + color: + chartThemeData.titleTextColor ?? + effectiveChartThemeData.titleTextColor, + ) .merge(chartThemeData.titleTextStyle) .merge(widget.title.textStyle), legendTitleTextStyle: effectiveChartThemeData.legendTitleTextStyle! .copyWith( - color: chartThemeData.legendTitleColor ?? - effectiveChartThemeData.legendTitleColor) + color: + chartThemeData.legendTitleColor ?? + effectiveChartThemeData.legendTitleColor, + ) .merge(chartThemeData.legendTitleTextStyle) .merge(widget.legend.title?.textStyle), legendTextStyle: effectiveChartThemeData.legendTextStyle! .copyWith( - color: chartThemeData.legendTextColor ?? - effectiveChartThemeData.legendTextColor) + color: + chartThemeData.legendTextColor ?? + effectiveChartThemeData.legendTextColor, + ) .merge(chartThemeData.legendTextStyle) .merge(widget.legend.textStyle), tooltipTextStyle: effectiveChartThemeData.tooltipTextStyle! .copyWith( - color: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor) + color: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) .merge(chartThemeData.tooltipTextStyle) .merge(widget.tooltipBehavior?.textStyle), ); @@ -639,27 +654,39 @@ class SfCircularChartState extends State } Widget? _buildTooltipWidget( - BuildContext context, TooltipInfo? info, Size maxSize) { - return buildTooltipWidget(context, info, maxSize, widget.tooltipBehavior, - _chartThemeData, _themeData); + BuildContext context, + TooltipInfo? info, + Size maxSize, + ) { + return buildTooltipWidget( + context, + info, + maxSize, + widget.tooltipBehavior, + _chartThemeData, + _themeData, + ); } // ignore: unused_element void _handleTouchDown(Offset localPosition) { - widget.onChartTouchInteractionDown - ?.call(ChartTouchInteractionArgs()..position = localPosition); + widget.onChartTouchInteractionDown?.call( + ChartTouchInteractionArgs()..position = localPosition, + ); } // ignore: unused_element void _handleTouchMove(Offset localPosition) { - widget.onChartTouchInteractionMove - ?.call(ChartTouchInteractionArgs()..position = localPosition); + widget.onChartTouchInteractionMove?.call( + ChartTouchInteractionArgs()..position = localPosition, + ); } // ignore: unused_element void _handleTouchUp(Offset localPosition) { - widget.onChartTouchInteractionUp - ?.call(ChartTouchInteractionArgs()..position = localPosition); + widget.onChartTouchInteractionUp?.call( + ChartTouchInteractionArgs()..position = localPosition, + ); } /// Called when this object is inserted into the tree. @@ -761,28 +788,36 @@ class SfCircularChartState extends State _themeData = Theme.of(context); final ChartThemeData effectiveChartThemeData = ChartThemeData(context); _chartThemeData = _updateThemeData(context, effectiveChartThemeData); - final core.LegendPosition legendPosition = - effectiveLegendPosition(widget.legend); - final Axis orientation = - effectiveLegendOrientation(legendPosition, widget.legend); + final core.LegendPosition legendPosition = effectiveLegendPosition( + widget.legend, + ); + final Axis orientation = effectiveLegendOrientation( + legendPosition, + widget.legend, + ); Widget current = core.LegendLayout( key: _legendKey, padding: EdgeInsets.zero, showLegend: widget.legend.isVisible, legendPosition: legendPosition, legendAlignment: effectiveLegendAlignment(widget.legend.alignment), - legendTitleAlignment: - effectiveLegendAlignment(widget.legend.title?.alignment), + legendTitleAlignment: effectiveLegendAlignment( + widget.legend.title?.alignment, + ), itemIconBorderColor: widget.legend.iconBorderColor, itemIconBorderWidth: widget.legend.iconBorderWidth, legendBorderColor: widget.legend.borderColor, legendBackgroundColor: _chartThemeData.legendBackgroundColor, legendBorderWidth: widget.legend.borderWidth, itemOpacity: widget.legend.opacity, - legendWidthFactor: - percentageToWidthFactor(widget.legend.width, legendPosition), - legendHeightFactor: - percentageToHeightFactor(widget.legend.height, legendPosition), + legendWidthFactor: percentageToWidthFactor( + widget.legend.width, + legendPosition, + ), + legendHeightFactor: percentageToHeightFactor( + widget.legend.height, + legendPosition, + ), itemInnerSpacing: widget.legend.padding, itemSpacing: 0.0, itemPadding: widget.legend.itemPadding, @@ -855,8 +890,9 @@ class SfCircularChartState extends State opacity: widget.tooltipBehavior!.opacity, borderColor: widget.tooltipBehavior!.borderColor, borderWidth: widget.tooltipBehavior!.borderWidth, - color: (widget.tooltipBehavior!.color ?? - _chartThemeData.tooltipColor)!, + color: + (widget.tooltipBehavior!.color ?? + _chartThemeData.tooltipColor)!, showDuration: widget.tooltipBehavior!.duration.toInt(), shadowColor: widget.tooltipBehavior!.shadowColor, elevation: widget.tooltipBehavior!.elevation, @@ -875,12 +911,13 @@ class SfCircularChartState extends State return RepaintBoundary( child: Container( decoration: BoxDecoration( - image: widget.backgroundImage != null - ? DecorationImage( - image: widget.backgroundImage!, - fit: BoxFit.fill, - ) - : null, + image: + widget.backgroundImage != null + ? DecorationImage( + image: widget.backgroundImage!, + fit: BoxFit.fill, + ) + : null, color: _chartThemeData.backgroundColor, border: Border.all( color: widget.borderColor, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/annotation.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/annotation.dart index ee3722f1a..f04d5511d 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/annotation.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/annotation.dart @@ -326,7 +326,7 @@ class CartesianChartAnnotation { x, y, xAxisName, - yAxisName + yAxisName, ]; return Object.hashAll(values); } @@ -544,7 +544,7 @@ class CircularChartAnnotation { horizontalAlignment, verticalAlignment, height, - width + width, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/callbacks.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/callbacks.dart index 7030af087..e8d879604 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/callbacks.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/callbacks.dart @@ -171,16 +171,15 @@ class MultiLevelLabelRenderDetails { /// Holds the axis label text and style details. class ChartAxisLabel { /// Creating an argument constructor of ChartAxisLabel class. - ChartAxisLabel( - this.text, - TextStyle? textStyle, - ) : textStyle = textStyle ?? - const TextStyle( - fontFamily: 'Roboto', - fontStyle: FontStyle.normal, - fontWeight: FontWeight.normal, - fontSize: 12, - ); + ChartAxisLabel(this.text, TextStyle? textStyle) + : textStyle = + textStyle ?? + const TextStyle( + fontFamily: 'Roboto', + fontStyle: FontStyle.normal, + fontWeight: FontWeight.normal, + fontSize: 12, + ); ///Text which is to be rendered as an axis label. final String text; @@ -270,10 +269,7 @@ class DataLabelRenderArgs { /// [SfPyramidChart] and [SfFunnelChart]. class LegendRenderArgs { /// Creating an argument constructor of LegendRenderArgs class. - LegendRenderArgs([ - this.seriesIndex, - this.pointIndex, - ]); + LegendRenderArgs([this.seriesIndex, this.pointIndex]); /// Get and set the legend text. String? text; @@ -354,12 +350,7 @@ class TrackballArgs { /// and orientation. class CrosshairRenderArgs { /// Creating an argument constructor of CrosshairRenderArgs class. - CrosshairRenderArgs([ - this.axis, - this.value, - this.axisName, - this.orientation, - ]); + CrosshairRenderArgs([this.axis, this.value, this.axisName, this.orientation]); /// Get the type of chart axis and its properties. final ChartAxis? axis; @@ -399,11 +390,7 @@ class ChartTouchInteractionArgs { /// _Note:_ This is only applicable for [SfCartesianChart]. class ZoomPanArgs { /// Creating an argument constructor of ZoomPanArgs class. - ZoomPanArgs([ - this.axis, - this.previousZoomPosition, - this.previousZoomFactor, - ]); + ZoomPanArgs([this.axis, this.previousZoomPosition, this.previousZoomFactor]); /// Get the chart axis types and properties. final RenderChartAxis? axis; @@ -455,10 +442,7 @@ class ChartPointDetails { /// options to get the axis type, label text, and axis name. class AxisLabelTapArgs { /// Creating an argument constructor of AxisLabelTapArgs class. - AxisLabelTapArgs([ - this.axis, - this.axisName, - ]); + AxisLabelTapArgs([this.axis, this.axisName]); /// Get the type of chart axis and its properties. final ChartAxis? axis; @@ -479,11 +463,7 @@ class AxisLabelTapArgs { /// can get the `series`, [seriesIndex], and [pointIndex]. class LegendTapArgs { /// Creating an argument constructor of LegendTapArgs class. - LegendTapArgs([ - this.series, - this.seriesIndex, - this.pointIndex, - ]); + LegendTapArgs([this.series, this.seriesIndex, this.pointIndex]); /// Get the current series. /// @@ -557,7 +537,6 @@ class SelectionArgs { } @Deprecated('Use IndicatorRenderParams instead.') - /// Holds the onRenderDetailsUpdate event arguments. /// /// Triggers when indicator is rendering. You can customize the @@ -686,11 +665,7 @@ class DataLabelTapDetails { /// (either series or legend). class ChartShaderDetails { /// Creating an argument constructor of ChartShaderDetails class. - ChartShaderDetails( - this.outerRect, - this.innerRect, - this.renderType, - ); + ChartShaderDetails(this.outerRect, this.innerRect, this.renderType); /// Holds the pie, doughnut and radial bar chart's outer rect value. final Rect outerRect; @@ -705,10 +680,7 @@ class ChartShaderDetails { /// Holds the onCreateShader callback arguments. class ShaderDetails { /// Creating an argument constructor of ShaderDetails class. - ShaderDetails( - this.rect, - this.renderType, - ); + ShaderDetails(this.rect, this.renderType); /// Holds the chart area rect. final Rect rect; @@ -781,12 +753,12 @@ class MomentumIndicatorRenderParams extends IndicatorRenderParams { Color signalLineColor, List signalLineDashArray, ) : super( - calculatedDataPoints, - name, - signalLineWidth, - signalLineColor, - signalLineDashArray, - ); + calculatedDataPoints, + name, + signalLineWidth, + signalLineColor, + signalLineDashArray, + ); /// Gets the calculated center line value of the Momentum indicator. final double? centerLineValue; @@ -803,12 +775,12 @@ class RocIndicatorRenderParams extends IndicatorRenderParams { Color signalLineColor, List signalLineDashArray, ) : super( - calculatedDataPoints, - name, - signalLineWidth, - signalLineColor, - signalLineDashArray, - ); + calculatedDataPoints, + name, + signalLineWidth, + signalLineColor, + signalLineDashArray, + ); /// Gets the calculated center line value of the Roc indicator. final double? centerLineValue; @@ -825,12 +797,12 @@ class StochasticIndicatorRenderParams extends IndicatorRenderParams { Color signalLineColor, List signalLineDashArray, ) : super( - calculatedDataPoints, - name, - signalLineWidth, - signalLineColor, - signalLineDashArray, - ); + calculatedDataPoints, + name, + signalLineWidth, + signalLineColor, + signalLineDashArray, + ); /// Gets the calculated period line values of the stochastic indicator. final List? periodLineValues; @@ -848,12 +820,12 @@ class MacdIndicatorRenderParams extends IndicatorRenderParams { Color signalLineColor, List signalLineDashArray, ) : super( - calculatedDataPoints, - name, - signalLineWidth, - signalLineColor, - signalLineDashArray, - ); + calculatedDataPoints, + name, + signalLineWidth, + signalLineColor, + signalLineDashArray, + ); /// Gets the calculated Macd line values of the Macd indicator. final List? macdLineValues; @@ -973,7 +945,7 @@ class TrackballDetails { series, pointIndex, seriesIndex, - groupingModeInfo + groupingModeInfo, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/chart_point.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/chart_point.dart index f38089f68..f0e03487c 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/chart_point.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/chart_point.dart @@ -206,10 +206,7 @@ class ChartPoint with Diagnosticable { class CircularChartPoint extends ChartPoint { /// Creating an argument constructor of [CircularChartPoint] class. - CircularChartPoint({ - super.x, - super.y, - }); + CircularChartPoint({super.x, super.y}); /// Degree of chart point. num? degree; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label.dart index e1bb48fed..bac3876e5 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label.dart @@ -104,13 +104,15 @@ class CircularDataLabelContainer extends StatefulWidget { _CircularDataLabelContainerState(); } -typedef _ChartDataLabelWidgetBuilder = Widget Function( - T data, - ChartPoint point, - ChartSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position); +typedef _ChartDataLabelWidgetBuilder = + Widget Function( + T data, + ChartPoint point, + ChartSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ); class _CircularDataLabelContainerState extends State> @@ -123,22 +125,24 @@ class _CircularDataLabelContainerState super.renderer as CircularSeriesRenderer?; Widget _dataLabelFromBuilder( - T data, - ChartPoint point, - ChartSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position) { + T data, + ChartPoint point, + ChartSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ) { return widget.builder!(data, point, series, pointIndex, seriesIndex); } Widget _dataLabelFromMapper( - T data, - ChartPoint point, - ChartSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position) { + T data, + ChartPoint point, + ChartSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ) { String text = widget.mapper!(data, pointIndex) ?? ''; if (renderer!.groupTo != null) { @@ -167,14 +171,18 @@ class _CircularDataLabelContainerState if (settings.color != null) { return settings.color!.withValues(alpha: settings.opacity); } else if (settings.useSeriesColor) { - return renderer!.segments[dataPointIndex].fillPaint.color - .withValues(alpha: settings.opacity); + return renderer!.segments[dataPointIndex].fillPaint.color.withValues( + alpha: settings.opacity, + ); } return Colors.transparent; } - DataLabelText _buildDataLabelText(String text, int pointIndex, - {bool isYText = false}) { + DataLabelText _buildDataLabelText( + String text, + int pointIndex, { + bool isYText = false, + }) { final RenderChartPlotArea parent = renderer!.parent!; final TextStyle dataLabelTextStyle = parent.themeData!.textTheme.bodySmall! .copyWith(color: Colors.transparent) @@ -206,8 +214,10 @@ class _CircularDataLabelContainerState _textChildren!.add(child); } - void _buildDataLabels(_ChartDataLabelWidgetBuilder callback, - Function(CircularChartDataLabelPositioned) add) { + void _buildDataLabels( + _ChartDataLabelWidgetBuilder callback, + Function(CircularChartDataLabelPositioned) add, + ) { const List positions = ChartDataPointType.values; final int yLength = yLists?.length ?? 0; final int posAdj = _positionIndex(yLength); @@ -222,13 +232,22 @@ class _CircularDataLabelContainerState return; } - final bool hasSortedIndexes = renderer!.sortingOrder != SortingOrder.none && + final bool hasSortedIndexes = + renderer!.sortingOrder != SortingOrder.none && sortedIndexes != null && sortedIndexes!.isNotEmpty; for (int i = 0; i < renderer!.dataCount; i++) { - _obtainLabel(i, actualXValues, yLength, positions, posAdj, callback, add, - hasSortedIndexes); + _obtainLabel( + i, + actualXValues, + yLength, + positions, + posAdj, + callback, + add, + hasSortedIndexes, + ); } } @@ -249,8 +268,9 @@ class _CircularDataLabelContainerState ) { final int pointIndex = hasSortedIndexes ? sortedIndexes![index] : index; final num x = xValues![index]; - final CircularChartPoint point = - CircularChartPoint(x: rawXValues[index] as D?); + final CircularChartPoint point = CircularChartPoint( + x: rawXValues[index] as D?, + ); point.color = _dataPointColor(index); for (int j = 0; j < yLength; j++) { final List yValues = yLists![j]; @@ -265,20 +285,20 @@ class _CircularDataLabelContainerState final ChartDataPointType position = positions[k + posAdj]; final CircularChartDataLabelPositioned child = CircularChartDataLabelPositioned( - x: x, - y: point[position], - dataPointIndex: index, - position: position, - point: point, - child: callback( - widget.dataSource[pointIndex], - point, - widget.series, - pointIndex, - renderer!.index, - position, - ), - ); + x: x, + y: point[position], + dataPointIndex: index, + position: position, + point: point, + child: callback( + widget.dataSource[pointIndex], + point, + widget.series, + pointIndex, + renderer!.index, + position, + ), + ); add(child); } @@ -299,9 +319,10 @@ class _CircularDataLabelContainerState if (widget.builder != null) { callback = _dataLabelFromBuilder; } else { - callback = widget.mapper != null - ? _dataLabelFromMapper - : _defaultDataLabel; + callback = + widget.mapper != null + ? _dataLabelFromMapper + : _defaultDataLabel; } void Function(CircularChartDataLabelPositioned child) add; if (widget.builder != null) { @@ -358,7 +379,9 @@ class CircularDataLabelStack extends ChartElementStack { @override void updateRenderObject( - BuildContext context, RenderCircularDataLabelStack renderObject) { + BuildContext context, + RenderCircularDataLabelStack renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..series = series @@ -435,16 +458,19 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { return; } - final String text = childCount > 0 - ? '' - : (labels!.elementAt(selectedIndex).child as DataLabelText).text; - series!.parent!.onDataLabelTapped!(DataLabelTapDetails( - series!.index, - series!.viewportIndex(selectedIndex), - text, - settings, - selectedIndex, - )); + final String text = + childCount > 0 + ? '' + : (labels!.elementAt(selectedIndex).child as DataLabelText).text; + series!.parent!.onDataLabelTapped!( + DataLabelTapDetails( + series!.index, + series!.viewportIndex(selectedIndex), + text, + settings, + selectedIndex, + ), + ); } else if (hasTrimmedDataLabel) { final int selectedIndex = _findSelectedDataLabelIndex(localPosition); if (selectedIndex == -1) { @@ -476,19 +502,23 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { } void _showTooltipForTrimmedDataLabel( - CircularChartPoint point, int pointIndex) { + CircularChartPoint point, + int pointIndex, + ) { final RenderCircularChartPlotArea plotArea = series!.parent! as RenderCircularChartPlotArea; - plotArea.behaviorArea?.showTooltip(TooltipInfo( - primaryPosition: localToGlobal(point.labelRect.topCenter), - secondaryPosition: localToGlobal(point.labelRect.topCenter), - text: point.text, - surfaceBounds: Rect.fromPoints( - plotArea.localToGlobal(paintBounds.topLeft), - plotArea.localToGlobal(paintBounds.bottomRight), + plotArea.behaviorArea?.showTooltip( + TooltipInfo( + primaryPosition: localToGlobal(point.labelRect.topCenter), + secondaryPosition: localToGlobal(point.labelRect.topCenter), + text: point.text, + surfaceBounds: Rect.fromPoints( + plotArea.localToGlobal(paintBounds.topLeft), + plotArea.localToGlobal(paintBounds.bottomRight), + ), ), - )); + ); } @override @@ -521,14 +551,19 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { final RenderBox? nextSibling = currentChildData.nextSibling; child.layout(constraints, parentUsesSize: true); - currentChildData.offset = - series!.dataLabelPosition(currentChildData, child.size); + currentChildData.offset = series!.dataLabelPosition( + currentChildData, + child.size, + ); // TODO(Lavanya): Need to handle the offset value for the // shift data label. - final Offset offset = - _invokeDataLabelRender(currentChildData.dataPointIndex); - currentChildData.offset = Offset(currentChildData.offset.dx + offset.dx, - currentChildData.offset.dy - offset.dy); + final Offset offset = _invokeDataLabelRender( + currentChildData.dataPointIndex, + ); + currentChildData.offset = Offset( + currentChildData.offset.dx + offset.dx, + currentChildData.offset.dy - offset.dy, + ); child = nextSibling; } @@ -547,14 +582,20 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { ..point = currentLabel.point; final DataLabelText details = currentLabel.child as DataLabelText; - final Offset offset = - _invokeDataLabelRender(currentLabel.dataPointIndex, details); - currentLabel.offset = Offset(currentLabel.offset.dx + offset.dx, - currentLabel.offset.dy - offset.dy); + final Offset offset = _invokeDataLabelRender( + currentLabel.dataPointIndex, + details, + ); + currentLabel.offset = Offset( + currentLabel.offset.dx + offset.dx, + currentLabel.offset.dy - offset.dy, + ); currentLabel.point!.text = details.text; currentLabel.size = measureText(details.text, details.textStyle); - currentLabel.offset += - series!.dataLabelPosition(currentLabelData, currentLabel.size); + currentLabel.offset += series!.dataLabelPosition( + currentLabelData, + currentLabel.size, + ); hasTrimmedDataLabel = currentLabel.point!.trimmedText != null; if (currentLabel.point!.text != details.text) { @@ -565,8 +606,9 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { if (series!.dataLabelSettings.labelIntersectAction == LabelIntersectAction.shift) { shiftCircularDataLabels(series!, labels!); - hasTrimmedDataLabel = - labels!.any((element) => element.point!.trimmedText != null); + hasTrimmedDataLabel = labels!.any( + (element) => element.point!.trimmedText != null, + ); } } } @@ -613,8 +655,11 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { final CircularChartPoint point = childParentData.point!; if (point.isVisible) { if (point.connectorPath != null) { - series!.drawConnectorLine(point.connectorPath!, context.canvas, - childParentData.dataPointIndex); + series!.drawConnectorLine( + point.connectorPath!, + context.canvas, + childParentData.dataPointIndex, + ); } context.paintChild(child, childParentData.offset + offset); } @@ -622,10 +667,11 @@ class RenderCircularDataLabelStack extends RenderChartElementStack { } } else if (labels != null) { final Paint fillPaint = Paint(); - final Paint strokePaint = Paint() - ..color = settings.borderColor - ..strokeWidth = settings.borderWidth - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = settings.borderColor + ..strokeWidth = settings.borderWidth + ..style = PaintingStyle.stroke; for (final CircularChartDataLabelPositioned label in labels!) { final DataLabelText details = label.child as DataLabelText; fillPaint.color = details.color; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label_helper.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label_helper.dart index 9ace43763..b2c3c4180 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label_helper.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/circular_data_label_helper.dart @@ -53,15 +53,16 @@ bool findingCollision(Rect rect, List regions, [Rect? pathRect]) { /// Method to get a text when the text overlap with another segment/slice. String segmentOverflowTrimmedText( - CircularSeriesRenderer seriesRenderer, - String text, - Size size, - CircularChartPoint point, - Rect labelRect, - Offset centerLocation, - Offset labelLocation, - OverflowMode action, - TextStyle dataLabelStyle) { + CircularSeriesRenderer seriesRenderer, + String text, + Size size, + CircularChartPoint point, + Rect labelRect, + Offset centerLocation, + Offset labelLocation, + OverflowMode action, + TextStyle dataLabelStyle, +) { bool isTextWithinRegion; const String ellipse = '...'; const int minCharacterLength = 3; @@ -70,18 +71,20 @@ String segmentOverflowTrimmedText( final double labelPadding = kIsWeb ? 4 : 2; final bool labelLeftEnd = _isInsideSegment( - point.labelRect.centerLeft - Offset(labelPadding, 0), - centerLocation, - point.outerRadius!, - point.startAngle!, - point.endAngle!); + point.labelRect.centerLeft - Offset(labelPadding, 0), + centerLocation, + point.outerRadius!, + point.startAngle!, + point.endAngle!, + ); final bool labelRightEnd = _isInsideSegment( - point.labelRect.centerRight - Offset(labelPadding, 0), - centerLocation, - point.outerRadius!, - point.startAngle!, - point.endAngle!); + point.labelRect.centerRight - Offset(labelPadding, 0), + centerLocation, + point.outerRadius!, + point.startAngle!, + point.endAngle!, + ); if (labelLeftEnd && labelRightEnd) { return text; @@ -104,36 +107,43 @@ String segmentOverflowTrimmedText( } const num labelPadding = 0; final Size trimSize = measureText(text, dataLabelStyle); - Offset trimmedLabelLocation = calculateOffset(point.midAngle!, - (point.innerRadius! + point.outerRadius!) / 2, point.center!); + Offset trimmedLabelLocation = calculateOffset( + point.midAngle!, + (point.innerRadius! + point.outerRadius!) / 2, + point.center!, + ); trimmedLabelLocation = Offset( - (trimmedLabelLocation.dx - trimSize.width - 5) + - (seriesRenderer.dataLabelSettings.angle == 0 - ? 0 - : trimSize.width / 2), - (trimmedLabelLocation.dy - trimSize.height / 2) + - (seriesRenderer.dataLabelSettings.angle == 0 - ? 0 - : trimSize.height / 2)); + (trimmedLabelLocation.dx - trimSize.width - 5) + + (seriesRenderer.dataLabelSettings.angle == 0 + ? 0 + : trimSize.width / 2), + (trimmedLabelLocation.dy - trimSize.height / 2) + + (seriesRenderer.dataLabelSettings.angle == 0 + ? 0 + : trimSize.height / 2), + ); final Rect trimmedLabelRect = Rect.fromLTWH( - trimmedLabelLocation.dx - labelPadding, - trimmedLabelLocation.dy - labelPadding, - trimSize.width + (2 * labelPadding), - trimSize.height + (2 * labelPadding)); + trimmedLabelLocation.dx - labelPadding, + trimmedLabelLocation.dy - labelPadding, + trimSize.width + (2 * labelPadding), + trimSize.height + (2 * labelPadding), + ); final bool trimmedLeftEnd = _isInsideSegment( - trimmedLabelRect.centerLeft, - centerLocation, - point.outerRadius!, - point.startAngle!, - point.endAngle!); + trimmedLabelRect.centerLeft, + centerLocation, + point.outerRadius!, + point.startAngle!, + point.endAngle!, + ); final bool trimmedRightEnd = _isInsideSegment( - trimmedLabelRect.centerRight, - centerLocation, - point.outerRadius!, - point.startAngle!, - point.endAngle!); + trimmedLabelRect.centerRight, + centerLocation, + point.outerRadius!, + point.startAngle!, + point.endAngle!, + ); if (trimmedLeftEnd && trimmedRightEnd) { isTextWithinRegion = true; point.labelRect = trimmedLabelRect; @@ -169,7 +179,12 @@ String addEllipse(String text, int maxLength, String ellipse, {bool? isRtl}) { /// Method to check if a label is inside the point region based /// on the angle for pie and doughnut series. bool _isInsideSegment( - Offset point, Offset center, num radius, num start, num end) { + Offset point, + Offset center, + num radius, + num start, + num end, +) { final Offset labelOffset = point - center; final double labelRadius = labelOffset.distance; @@ -189,8 +204,11 @@ bool _isInsideSegment( } /// Method for setting color to data label. -Color findThemeColor(CircularSeriesRenderer seriesRenderer, - CircularChartPoint point, DataLabelSettings dataLabelSettings) { +Color findThemeColor( + CircularSeriesRenderer seriesRenderer, + CircularChartPoint point, + DataLabelSettings dataLabelSettings, +) { // TODO(Lavanya): Recheck here. final Color dataLabelBackgroundColor = seriesRenderer.parent!.themeData!.colorScheme.surface; @@ -205,13 +223,14 @@ Color findThemeColor(CircularSeriesRenderer seriesRenderer, /// To render outside positioned data labels. void renderOutsideDataLabel( - CircularChartPoint point, - Size textSize, - int pointIndex, - CircularSeriesRenderer seriesRenderer, - int seriesIndex, - TextStyle textStyle, - List renderDataLabelRegions) { + CircularChartPoint point, + Size textSize, + int pointIndex, + CircularSeriesRenderer seriesRenderer, + int seriesIndex, + TextStyle textStyle, + List renderDataLabelRegions, +) { Path connectorPath; Rect? rect; Offset labelLocation; @@ -220,34 +239,46 @@ void renderOutsideDataLabel( final EdgeInsets margin = settings.margin; final ConnectorLineSettings connector = settings.connectorLineSettings; connectorPath = Path(); - final num connectorLength = percentToValue( - connector.length ?? defaultConnectorLineLength, point.outerRadius!)!; + final num connectorLength = + percentToValue( + connector.length ?? defaultConnectorLineLength, + point.outerRadius!, + )!; final Offset startPoint = calculateOffset( - point.midAngle!, point.outerRadius!.toDouble(), point.center!); - final Offset endPoint = calculateOffset(point.midAngle!, - (point.outerRadius! + connectorLength).toDouble(), point.center!); + point.midAngle!, + point.outerRadius!.toDouble(), + point.center!, + ); + final Offset endPoint = calculateOffset( + point.midAngle!, + (point.outerRadius! + connectorLength).toDouble(), + point.center!, + ); connectorPath.moveTo(startPoint.dx, startPoint.dy); if (connector.type == ConnectorType.line) { connectorPath.lineTo(endPoint.dx, endPoint.dy); } rect = getDataLabelRect( - point.dataLabelPosition, - connector.type, - margin, - connectorPath, - endPoint, - textSize, - // To avoid the extra padding added to the exact template size. - settings.builder != null && - settings.labelIntersectAction == LabelIntersectAction.shift - ? seriesRenderer.dataLabelSettings - : null); + point.dataLabelPosition, + connector.type, + margin, + connectorPath, + endPoint, + textSize, + // To avoid the extra padding added to the exact template size. + settings.builder != null && + settings.labelIntersectAction == LabelIntersectAction.shift + ? seriesRenderer.dataLabelSettings + : null, + ); point.connectorPath = connectorPath; point.labelRect = rect!; - labelLocation = Offset(rect.left + margin.left, - rect.top + rect.height / 2 - textSize.height / 2); + labelLocation = Offset( + rect.left + margin.left, + rect.top + rect.height / 2 - textSize.height / 2, + ); point.labelLocation = labelLocation; final Rect containerRect = seriesRenderer.paintBounds; @@ -301,9 +332,15 @@ void renderOutsideDataLabel( } /// To return data label rect calculation method based on position. -Rect? getDataLabelRect(Position position, ConnectorType connectorType, - EdgeInsets margin, Path connectorPath, Offset endPoint, Size textSize, - [DataLabelSettings? dataLabelSettings]) { +Rect? getDataLabelRect( + Position position, + ConnectorType connectorType, + EdgeInsets margin, + Path connectorPath, + Offset endPoint, + Size textSize, [ + DataLabelSettings? dataLabelSettings, +]) { Rect? rect; const int lineLength = 10; switch (position) { @@ -311,40 +348,62 @@ Rect? getDataLabelRect(Position position, ConnectorType connectorType, connectorType == ConnectorType.line ? connectorPath.lineTo(endPoint.dx + lineLength, endPoint.dy) : connectorPath.quadraticBezierTo( - endPoint.dx, endPoint.dy, endPoint.dx + lineLength, endPoint.dy); - rect = dataLabelSettings != null && dataLabelSettings.builder != null - ? Rect.fromLTWH( - endPoint.dx, endPoint.dy, textSize.width, textSize.height) - : Rect.fromLTWH( - endPoint.dx + lineLength, - endPoint.dy - (textSize.height / 2) - margin.top, - textSize.width + margin.left + margin.right, - textSize.height + margin.top + margin.bottom); + endPoint.dx, + endPoint.dy, + endPoint.dx + lineLength, + endPoint.dy, + ); + rect = + dataLabelSettings != null && dataLabelSettings.builder != null + ? Rect.fromLTWH( + endPoint.dx, + endPoint.dy, + textSize.width, + textSize.height, + ) + : Rect.fromLTWH( + endPoint.dx + lineLength, + endPoint.dy - (textSize.height / 2) - margin.top, + textSize.width + margin.left + margin.right, + textSize.height + margin.top + margin.bottom, + ); break; case Position.left: connectorType == ConnectorType.line ? connectorPath.lineTo(endPoint.dx - lineLength, endPoint.dy) : connectorPath.quadraticBezierTo( - endPoint.dx, endPoint.dy, endPoint.dx - lineLength, endPoint.dy); - rect = dataLabelSettings != null && dataLabelSettings.builder != null - ? Rect.fromLTWH( - endPoint.dx, endPoint.dy, textSize.width, textSize.height) - : Rect.fromLTWH( - endPoint.dx - - lineLength - - margin.right - - textSize.width - - margin.left, - endPoint.dy - ((textSize.height / 2) + margin.top), - textSize.width + margin.left + margin.right, - textSize.height + margin.top + margin.bottom); + endPoint.dx, + endPoint.dy, + endPoint.dx - lineLength, + endPoint.dy, + ); + rect = + dataLabelSettings != null && dataLabelSettings.builder != null + ? Rect.fromLTWH( + endPoint.dx, + endPoint.dy, + textSize.width, + textSize.height, + ) + : Rect.fromLTWH( + endPoint.dx - + lineLength - + margin.right - + textSize.width - + margin.left, + endPoint.dy - ((textSize.height / 2) + margin.top), + textSize.width + margin.left + margin.right, + textSize.height + margin.top + margin.bottom, + ); break; } return rect; } -void shiftCircularDataLabels(CircularSeriesRenderer seriesRenderer, - LinkedList labels) { +void shiftCircularDataLabels( + CircularSeriesRenderer seriesRenderer, + LinkedList labels, +) { final List points = []; if (seriesRenderer is RadialBarSeriesRenderer) { @@ -374,8 +433,10 @@ void shiftCircularDataLabels(CircularSeriesRenderer seriesRenderer, } } } - leftPoints.sort((CircularChartPoint a, CircularChartPoint b) => - a.newAngle!.compareTo(b.newAngle!)); + leftPoints.sort( + (CircularChartPoint a, CircularChartPoint b) => + a.newAngle!.compareTo(b.newAngle!), + ); if (leftPoints.isNotEmpty) { _arrangeLeftSidePoints(seriesRenderer); } @@ -386,8 +447,8 @@ void shiftCircularDataLabels(CircularSeriesRenderer seriesRenderer, } for (int pointIndex = 0; pointIndex < labels.length; pointIndex++) { - final CircularChartDataLabelPositioned dataLabelPositioned = - labels.elementAt(pointIndex); + final CircularChartDataLabelPositioned dataLabelPositioned = labels + .elementAt(pointIndex); final CircularChartPoint point = dataLabelPositioned.point!; if (point.isVisible) { final EdgeInsets margin = seriesRenderer.dataLabelSettings.margin; @@ -396,38 +457,48 @@ void shiftCircularDataLabels(CircularSeriesRenderer seriesRenderer, final Size textSize = dataLabelPositioned.size; labelLocation = Offset( - rect.left + - (point.renderPosition == ChartDataLabelPosition.inside - ? labelPadding - : margin.left), - rect.top + rect.height / 2 - textSize.height / 2); + rect.left + + (point.renderPosition == ChartDataLabelPosition.inside + ? labelPadding + : margin.left), + rect.top + rect.height / 2 - textSize.height / 2, + ); const String defaultConnectorLineLength = '10%'; point.trimmedText = point.text; Path shiftedConnectorPath = Path(); - final num connectorLength = percentToValue( - seriesRenderer.dataLabelSettings.connectorLineSettings.length ?? - defaultConnectorLineLength, - point.outerRadius!)!; + final num connectorLength = + percentToValue( + seriesRenderer.dataLabelSettings.connectorLineSettings.length ?? + defaultConnectorLineLength, + point.outerRadius!, + )!; final Offset startPoint = calculateOffset( - (point.startAngle! + point.endAngle!) / 2, - point.outerRadius!.toDouble(), - point.center!); - final Offset endPoint = calculateOffset(point.newAngle!.toDouble(), - (point.outerRadius! + connectorLength).toDouble(), point.center!); + (point.startAngle! + point.endAngle!) / 2, + point.outerRadius!.toDouble(), + point.center!, + ); + final Offset endPoint = calculateOffset( + point.newAngle!.toDouble(), + (point.outerRadius! + connectorLength).toDouble(), + point.center!, + ); shiftedConnectorPath.moveTo(startPoint.dx, startPoint.dy); if (seriesRenderer.dataLabelSettings.connectorLineSettings.type == ConnectorType.line) { shiftedConnectorPath.lineTo(endPoint.dx, endPoint.dy); } getDataLabelRect( - point.dataLabelPosition, - seriesRenderer.dataLabelSettings.connectorLineSettings.type, - margin, - shiftedConnectorPath, - endPoint, - textSize); + point.dataLabelPosition, + seriesRenderer.dataLabelSettings.connectorLineSettings.type, + margin, + shiftedConnectorPath, + endPoint, + textSize, + ); final Offset midAngle = getPerpendicularDistance( - Offset(startPoint.dx, startPoint.dy), point); + Offset(startPoint.dx, startPoint.dy), + point, + ); if (seriesRenderer.dataLabelSettings.connectorLineSettings.type == ConnectorType.curve && (point.isLabelUpdated) == 1) { @@ -435,13 +506,12 @@ void shiftCircularDataLabels(CircularSeriesRenderer seriesRenderer, shiftedConnectorPath = Path(); shiftedConnectorPath.moveTo(startPoint.dx, startPoint.dy); shiftedConnectorPath.quadraticBezierTo( - midAngle.dx, - midAngle.dy, - endPoint.dx - - (point.dataLabelPosition == Position.left - ? spacing - : -spacing), - endPoint.dy); + midAngle.dx, + midAngle.dy, + endPoint.dx - + (point.dataLabelPosition == Position.left ? spacing : -spacing), + endPoint.dy, + ); } // TODO(Lavanya): Recheck connector line here. @@ -453,36 +523,46 @@ void shiftCircularDataLabels(CircularSeriesRenderer seriesRenderer, // TODO(Lavanya): Recheck here. final Rect containerRect = seriesRenderer.paintBounds; if (containerRect.left > rect.left) { - labelLocation = Offset(containerRect.left, - rect.top + rect.height / 2 - textSize.height / 2); + labelLocation = Offset( + containerRect.left, + rect.top + rect.height / 2 - textSize.height / 2, + ); } final DataLabelText details = labels.elementAt(pointIndex).child as DataLabelText; if (point.labelRect.left < containerRect.left && point.renderPosition == ChartDataLabelPosition.outside) { - point.trimmedText = getTrimmedText(point.trimmedText!, - point.labelRect.right - containerRect.left, details.textStyle, - isRtl: false); // TODO(Lavanya): Recheck here. + point.trimmedText = getTrimmedText( + point.trimmedText!, + point.labelRect.right - containerRect.left, + details.textStyle, + isRtl: false, + ); // TODO(Lavanya): Recheck here. } if (point.labelRect.right > containerRect.right && point.renderPosition == ChartDataLabelPosition.outside) { - point.trimmedText = getTrimmedText(point.trimmedText!, - containerRect.right - point.labelRect.left, details.textStyle, - isRtl: false); + point.trimmedText = getTrimmedText( + point.trimmedText!, + containerRect.right - point.labelRect.left, + details.textStyle, + isRtl: false, + ); } if (point.text != point.trimmedText) { details.text = point.trimmedText!; point.dataLabelSize = measureText(details.text, details.textStyle); dataLabelPositioned.size = point.dataLabelSize; - rect = getDataLabelRect( - point.dataLabelPosition, - seriesRenderer.dataLabelSettings.connectorLineSettings.type, - margin, - shiftedConnectorPath, - endPoint, - point.dataLabelSize)!; + rect = + getDataLabelRect( + point.dataLabelPosition, + seriesRenderer.dataLabelSettings.connectorLineSettings.type, + margin, + shiftedConnectorPath, + endPoint, + point.dataLabelSize, + )!; } else { point.trimmedText = null; } @@ -522,7 +602,11 @@ void _arrangeLeftSidePoints(CircularSeriesRenderer seriesRenderer) { if (!isIncreaseAngle) { for (int k = i; k > 0; k--) { _decreaseAngle( - leftPoints[k], leftPoints[k - 1], seriesRenderer, false); + leftPoints[k], + leftPoints[k - 1], + seriesRenderer, + false, + ); for (int index = 1; index < leftPoints.length; index++) { if ((leftPoints[index].isLabelUpdated) != null && leftPoints[index].newAngle! - 10 < 100) { @@ -533,7 +617,11 @@ void _arrangeLeftSidePoints(CircularSeriesRenderer seriesRenderer) { } else { for (int k = i; k < leftPoints.length; k++) { _increaseAngle( - leftPoints[k - 1], leftPoints[k], seriesRenderer, false); + leftPoints[k - 1], + leftPoints[k], + seriesRenderer, + false, + ); } } } else { @@ -588,12 +676,20 @@ void _arrangeRightSidePoints(CircularSeriesRenderer seriesRenderer) { if (!isIncreaseAngle) { for (int k = i + 1; k < rightPoints.length; k++) { _increaseAngle( - rightPoints[k - 1], rightPoints[k], seriesRenderer, true); + rightPoints[k - 1], + rightPoints[k], + seriesRenderer, + true, + ); } } else { for (int k = i + 1; k > 0; k--) { _decreaseAngle( - rightPoints[k], rightPoints[k - 1], seriesRenderer, true); + rightPoints[k], + rightPoints[k - 1], + seriesRenderer, + true, + ); } } } else { @@ -611,10 +707,11 @@ void _arrangeRightSidePoints(CircularSeriesRenderer seriesRenderer) { /// Decrease the angle of the label if it intersects with labels. void _decreaseAngle( - CircularChartPoint currentPoint, - CircularChartPoint previousPoint, - CircularSeriesRenderer seriesRenderer, - bool isRightSide) { + CircularChartPoint currentPoint, + CircularChartPoint previousPoint, + CircularSeriesRenderer seriesRenderer, + bool isRightSide, +) { int count = 1; if (isRightSide) { while (isOverlap(currentPoint.labelRect, previousPoint.labelRect) || @@ -655,7 +752,10 @@ void _decreaseAngle( leftPoints.indexOf(previousPoint) == null && (newAngle - 1 < 90 && newAngle - 1 > 270)) { _changeLabelAngle( - currentPoint, currentPoint.newAngle! + 1, seriesRenderer); + currentPoint, + currentPoint.newAngle! + 1, + seriesRenderer, + ); _arrangeLeftSidePoints(seriesRenderer); break; } @@ -666,10 +766,11 @@ void _decreaseAngle( /// Increase the angle of the label if it intersects labels. void _increaseAngle( - CircularChartPoint currentPoint, - CircularChartPoint nextPoint, - CircularSeriesRenderer seriesRenderer, - bool isRightSide) { + CircularChartPoint currentPoint, + CircularChartPoint nextPoint, + CircularSeriesRenderer seriesRenderer, + bool isRightSide, +) { int count = 1; if (isRightSide) { while (isOverlap(currentPoint.labelRect, nextPoint.labelRect) || @@ -687,7 +788,10 @@ void _increaseAngle( (newAngle + 1 > 90 && newAngle + 1 < 270) && rightPoints.indexOf(nextPoint) == rightPoints.length - 1) { _changeLabelAngle( - currentPoint, currentPoint.newAngle! - 1, seriesRenderer); + currentPoint, + currentPoint.newAngle! - 1, + seriesRenderer, + ); _arrangeRightSidePoints(seriesRenderer); break; } @@ -711,44 +815,57 @@ void _increaseAngle( } /// Change the label angle based on the given new angle. -void _changeLabelAngle(CircularChartPoint currentPoint, num newAngle, - CircularSeriesRenderer seriesRenderer) { -// TODO(Lavanya): Code cleanup for seriesRenderer field. +void _changeLabelAngle( + CircularChartPoint currentPoint, + num newAngle, + CircularSeriesRenderer seriesRenderer, +) { + // TODO(Lavanya): Code cleanup for seriesRenderer field. const String defaultConnectorLineLength = '10%'; final DataLabelSettings dataLabelSettings = seriesRenderer.dataLabelSettings; final RenderChartPlotArea parent = seriesRenderer.parent!; - final TextStyle dataLabelStyle = parent.themeData!.textTheme.bodySmall! - ..merge(parent.chartThemeData!.dataLabelTextStyle) - ..merge(dataLabelSettings.textStyle); + final TextStyle dataLabelStyle = + parent.themeData!.textTheme.bodySmall! + ..merge(parent.chartThemeData!.dataLabelTextStyle) + ..merge(dataLabelSettings.textStyle); // Builder check for change the angle based on the template size. - final Size textSize = dataLabelSettings.builder != null - ? currentPoint.dataLabelSize - : measureText(currentPoint.text!, dataLabelStyle); + final Size textSize = + dataLabelSettings.builder != null + ? currentPoint.dataLabelSize + : measureText(currentPoint.text!, dataLabelStyle); final Path angleChangedConnectorPath = Path(); - final num connectorLength = percentToValue( - dataLabelSettings.connectorLineSettings.length ?? - defaultConnectorLineLength, - currentPoint.outerRadius!)!; - final Offset startPoint = calculateOffset(newAngle.toDouble(), - currentPoint.outerRadius!.toDouble(), currentPoint.center!); + final num connectorLength = + percentToValue( + dataLabelSettings.connectorLineSettings.length ?? + defaultConnectorLineLength, + currentPoint.outerRadius!, + )!; + final Offset startPoint = calculateOffset( + newAngle.toDouble(), + currentPoint.outerRadius!.toDouble(), + currentPoint.center!, + ); final Offset endPoint = calculateOffset( - newAngle.toDouble(), - currentPoint.outerRadius!.toDouble() + connectorLength, - currentPoint.center!); + newAngle.toDouble(), + currentPoint.outerRadius!.toDouble() + connectorLength, + currentPoint.center!, + ); angleChangedConnectorPath.moveTo(startPoint.dx, startPoint.dy); if (dataLabelSettings.connectorLineSettings.type == ConnectorType.line) { angleChangedConnectorPath.lineTo(endPoint.dx, endPoint.dy); } // TODO(Lavanya): Recheck label rect position here. - currentPoint.labelRect = getDataLabelRect( - currentPoint.dataLabelPosition, - seriesRenderer.dataLabelSettings.connectorLineSettings.type, - dataLabelSettings.margin, - angleChangedConnectorPath, - endPoint, - textSize)!; + currentPoint.labelRect = + getDataLabelRect( + currentPoint.dataLabelPosition, + seriesRenderer.dataLabelSettings.connectorLineSettings.type, + dataLabelSettings.margin, + angleChangedConnectorPath, + endPoint, + textSize, + )!; // TODO(Lavanya): Recheck connector line here. currentPoint.connectorPath = angleChangedConnectorPath; @@ -765,8 +882,11 @@ bool isOverlap(Rect currentRect, Rect rect) { } /// To find the current point overlapped with previous points. -bool isOverlapWithPrevious(CircularChartPoint currentPoint, - List points, int currentPointIndex) { +bool isOverlapWithPrevious( + CircularChartPoint currentPoint, + List points, + int currentPointIndex, +) { for (int i = 0; i < currentPointIndex; i++) { if (i != points.indexOf(currentPoint) && points[i].isVisible && @@ -779,7 +899,10 @@ bool isOverlapWithPrevious(CircularChartPoint currentPoint, /// To find the current point overlapped with next points. bool isOverlapWithNext( - CircularChartPoint point, List points, int pointIndex) { + CircularChartPoint point, + List points, + int pointIndex, +) { for (int i = pointIndex; i < points.length; i++) { if (i != points.indexOf(point) && points[i].isVisible && @@ -799,27 +922,35 @@ Offset getPerpendicularDistance(Offset startPoint, CircularChartPoint point) { final num height = add + 10 * sin(point.midAngle! * pi / 360); if (point.midAngle! > 270 && point.midAngle! < 360) { increasedLocation = Offset( - startPoint.dx + height * (cos((360 - point.midAngle!) * pi / 180)), - startPoint.dy - height * (sin((360 - point.midAngle!) * pi / 180))); + startPoint.dx + height * (cos((360 - point.midAngle!) * pi / 180)), + startPoint.dy - height * (sin((360 - point.midAngle!) * pi / 180)), + ); } else if (point.midAngle! > 0 && point.midAngle! < 90) { increasedLocation = Offset( - startPoint.dx + height * (cos(point.midAngle! * pi / 180)), - startPoint.dy + height * (sin(point.midAngle! * pi / 180))); + startPoint.dx + height * (cos(point.midAngle! * pi / 180)), + startPoint.dy + height * (sin(point.midAngle! * pi / 180)), + ); } else if (point.midAngle! > 0 && point.midAngle! < 90) { increasedLocation = Offset( - startPoint.dx - height * (cos((point.midAngle! - 90) * pi / 180)), - startPoint.dy + height * (sin((point.midAngle! - 90) * pi / 180))); + startPoint.dx - height * (cos((point.midAngle! - 90) * pi / 180)), + startPoint.dy + height * (sin((point.midAngle! - 90) * pi / 180)), + ); } else { increasedLocation = Offset( - startPoint.dx - height * (cos((point.midAngle! - 180) * pi / 180)), - startPoint.dy - height * (sin((point.midAngle! - 180) * pi / 180))); + startPoint.dx - height * (cos((point.midAngle! - 180) * pi / 180)), + startPoint.dy - height * (sin((point.midAngle! - 180) * pi / 180)), + ); } return increasedLocation; } /// To trim the text by given width. -String getTrimmedText(String text, num labelsExtent, TextStyle labelStyle, - {bool? isRtl}) { +String getTrimmedText( + String text, + num labelsExtent, + TextStyle labelStyle, { + bool? isRtl, +}) { String label = text; num size = measureText(label, labelStyle).width; @@ -847,8 +978,10 @@ String getTrimmedText(String text, num labelsExtent, TextStyle labelStyle, } /// To shift the data label template in the circular chart. -void shiftCircularDataLabelTemplate(CircularSeriesRenderer seriesRenderer, - List widgets) { +void shiftCircularDataLabelTemplate( + CircularSeriesRenderer seriesRenderer, + List widgets, +) { if (seriesRenderer is RadialBarSeriesRenderer) { return; } @@ -867,22 +1000,32 @@ void shiftCircularDataLabelTemplate(CircularSeriesRenderer seriesRenderer, // For the data label position is inside. if (seriesRenderer.dataLabelSettings.labelPosition == ChartDataLabelPosition.inside) { - Offset labelLocation = calculateOffset(point.midAngle!, - (point.innerRadius! + point.outerRadius!) / 2, point.center!); + Offset labelLocation = calculateOffset( + point.midAngle!, + (point.innerRadius! + point.outerRadius!) / 2, + point.center!, + ); // TODO(Lavanya): Recheck here. // labelLocation = Offset(labelLocation.dx - (rectSize[i].width / 2), // labelLocation.dy - (rectSize[i].height / 2)); - labelLocation = Offset(labelLocation.dx - (point.labelRect.width / 2), - labelLocation.dy - (point.labelRect.height / 2)); + labelLocation = Offset( + labelLocation.dx - (point.labelRect.width / 2), + labelLocation.dy - (point.labelRect.height / 2), + ); final Rect rect = Rect.fromLTWH( - labelLocation.dx - labelPadding, - labelLocation.dy - labelPadding, - point.labelRect.width + (2 * labelPadding), - point.labelRect.height + (2 * labelPadding)); + labelLocation.dx - labelPadding, + labelLocation.dy - labelPadding, + point.labelRect.width + (2 * labelPadding), + point.labelRect.height + (2 * labelPadding), + ); // If collide with label when the position is inside calculate the outside rect value of that perticular label. if (findingCollision(rect, renderDataLabelRegions)) { - _renderOutsideDataLabelTemplate(point, seriesRenderer, - point.labelRect.size, renderDataLabelRegions); + _renderOutsideDataLabelTemplate( + point, + seriesRenderer, + point.labelRect.size, + renderDataLabelRegions, + ); } else { point.renderPosition = ChartDataLabelPosition.inside; point.labelRect = rect; @@ -891,8 +1034,12 @@ void shiftCircularDataLabelTemplate(CircularSeriesRenderer seriesRenderer, } } else if (seriesRenderer.dataLabelSettings.labelPosition == ChartDataLabelPosition.outside) { - _renderOutsideDataLabelTemplate(point, seriesRenderer, - point.labelRect.size, renderDataLabelRegions); + _renderOutsideDataLabelTemplate( + point, + seriesRenderer, + point.labelRect.size, + renderDataLabelRegions, + ); } } } @@ -911,8 +1058,10 @@ void shiftCircularDataLabelTemplate(CircularSeriesRenderer seriesRenderer, } } } - leftPoints.sort((CircularChartPoint a, CircularChartPoint b) => - a.newAngle!.compareTo(b.newAngle!)); + leftPoints.sort( + (CircularChartPoint a, CircularChartPoint b) => + a.newAngle!.compareTo(b.newAngle!), + ); if (leftPoints.isNotEmpty) { _arrangeLeftSidePoints(seriesRenderer); } @@ -933,23 +1082,30 @@ void shiftCircularDataLabelTemplate(CircularSeriesRenderer seriesRenderer, Offset labelLocation = point.labelLocation; final Size templateSize = point.labelRect.size; labelLocation = Offset( - rect.left + - (point.renderPosition == ChartDataLabelPosition.inside - ? labelPadding - : margin.left), - rect.top + margin.top); + rect.left + + (point.renderPosition == ChartDataLabelPosition.inside + ? labelPadding + : margin.left), + rect.top + margin.top, + ); const String defaultConnectorLineLength = '10%'; final Path shiftedConnectorPath = Path(); - final num connectorLength = percentToValue( - seriesRenderer.dataLabelSettings.connectorLineSettings.length ?? - defaultConnectorLineLength, - point.outerRadius!)!; + final num connectorLength = + percentToValue( + seriesRenderer.dataLabelSettings.connectorLineSettings.length ?? + defaultConnectorLineLength, + point.outerRadius!, + )!; final Offset startPoint = calculateOffset( - (point.startAngle! + point.endAngle!) / 2, - point.outerRadius!.toDouble(), - point.center!); - final Offset endPoint = calculateOffset(point.newAngle!.toDouble(), - (point.outerRadius! + connectorLength).toDouble(), point.center!); + (point.startAngle! + point.endAngle!) / 2, + point.outerRadius!.toDouble(), + point.center!, + ); + final Offset endPoint = calculateOffset( + point.newAngle!.toDouble(), + (point.outerRadius! + connectorLength).toDouble(), + point.center!, + ); shiftedConnectorPath.moveTo(startPoint.dx, startPoint.dy); if (seriesRenderer.dataLabelSettings.connectorLineSettings.type == ConnectorType.line) { @@ -957,12 +1113,13 @@ void shiftCircularDataLabelTemplate(CircularSeriesRenderer seriesRenderer, } getDataLabelRect( - point.dataLabelPosition, - seriesRenderer.dataLabelSettings.connectorLineSettings.type, - margin, - shiftedConnectorPath, - endPoint, - templateSize)!; + point.dataLabelPosition, + seriesRenderer.dataLabelSettings.connectorLineSettings.type, + margin, + shiftedConnectorPath, + endPoint, + templateSize, + )!; point.connectorPath = point.renderPosition == ChartDataLabelPosition.outside @@ -996,29 +1153,46 @@ bool isTemplateWithinBounds(Rect bounds, Rect templateRect) => // Calculate the data label rectangle value when the data label template // position is outside and it consider the outer radius. void _renderOutsideDataLabelTemplate( - CircularChartPoint point, - CircularSeriesRenderer seriesRenderer, - Size templateSize, - List renderDataLabelRegion) { + CircularChartPoint point, + CircularSeriesRenderer seriesRenderer, + Size templateSize, + List renderDataLabelRegion, +) { Path connectorPath; const String defaultConnectorLineLength = '10%'; final EdgeInsets margin = seriesRenderer.dataLabelSettings.margin; final ConnectorLineSettings connector = seriesRenderer.dataLabelSettings.connectorLineSettings; connectorPath = Path(); - final num connectorLength = percentToValue( - connector.length ?? defaultConnectorLineLength, point.outerRadius!)!; + final num connectorLength = + percentToValue( + connector.length ?? defaultConnectorLineLength, + point.outerRadius!, + )!; final Offset startPoint = calculateOffset( - point.midAngle!, point.outerRadius!.toDouble(), point.center!); - final Offset endPoint = calculateOffset(point.midAngle!, - (point.outerRadius! + connectorLength).toDouble(), point.center!); + point.midAngle!, + point.outerRadius!.toDouble(), + point.center!, + ); + final Offset endPoint = calculateOffset( + point.midAngle!, + (point.outerRadius! + connectorLength).toDouble(), + point.center!, + ); connectorPath.moveTo(startPoint.dx, startPoint.dy); if (connector.type == ConnectorType.line) { connectorPath.lineTo(endPoint.dx, endPoint.dy); } point.dataLabelSize = templateSize; - final Rect rect = getDataLabelRect(point.dataLabelPosition, connector.type, - margin, connectorPath, endPoint, templateSize)!; + final Rect rect = + getDataLabelRect( + point.dataLabelPosition, + connector.type, + margin, + connectorPath, + endPoint, + templateSize, + )!; point.connectorPath = connectorPath; point.labelRect = rect; point.renderPosition = ChartDataLabelPosition.outside; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/connector_line.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/connector_line.dart index c4718cac7..16499c009 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/connector_line.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/connector_line.dart @@ -12,10 +12,13 @@ import '../utils/enum.dart'; /// class ConnectorLineSettings { /// Creating an argument constructor of ConnectorLineSettings class. - const ConnectorLineSettings( - {this.length, double? width, ConnectorType? type, this.color}) - : width = width ?? 1.0, - type = type ?? ConnectorType.line; + const ConnectorLineSettings({ + this.length, + double? width, + ConnectorType? type, + this.color, + }) : width = width ?? 1.0, + type = type ?? ConnectorType.line; /// Length of the connector line. The value range from 0% to 100%. /// diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/core_legend.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/core_legend.dart index 877a09c70..4999969fe 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/core_legend.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/core_legend.dart @@ -9,6 +9,7 @@ import 'package:flutter/rendering.dart'; import 'package:syncfusion_flutter_core/core.dart' as shape_helper; import 'package:syncfusion_flutter_core/core.dart'; +import '../series/chart_series.dart'; import '../utils/helper.dart'; import 'element_widget.dart'; @@ -19,15 +20,15 @@ typedef LegendItemBuilder = Widget Function(BuildContext context, int index); typedef LegendItemTapCallback = void Function(LegendItem, bool); /// Callback which returns toggled indices and teh current toggled index. -typedef ToggledIndicesChangedCallback = void Function( - List indices, int currentIndex); +typedef ToggledIndicesChangedCallback = + void Function(List indices, int currentIndex); /// Called with the details of single legend item. typedef ItemRenderCallback = void Function(ItemRendererDetails); /// Signature to return a [Widget] for the given value. -typedef LegendPointerBuilder = Widget Function( - BuildContext context, dynamic value); +typedef LegendPointerBuilder = + Widget Function(BuildContext context, dynamic value); /// Positions the legend in the different directions. enum LegendPosition { @@ -69,7 +70,7 @@ enum LegendLabelsPlacement { /// [LegendLabelsPlacement.betweenItems] places labels /// in-between two bars. - betweenItems + betweenItems, } /// Placement of edge labels in the bar legend. @@ -79,7 +80,7 @@ enum LegendEdgeLabelsPlacement { /// Place the edge labels in the center of the starting position of the /// legend bars. - center + center, } /// Behavior of the labels when it overflowed from the shape. @@ -92,7 +93,7 @@ enum LegendLabelOverflow { /// It trims the labels based on the available space in their respective /// legend item. - ellipsis + ellipsis, } /// Applies gradient or solid color for the bar segments. @@ -101,7 +102,7 @@ enum LegendPaintingStyle { solid, /// Applies gradient color for bar segments. - gradient + gradient, } /// Specifies the alignment of legend. @@ -173,13 +174,14 @@ class ItemRendererDetails { } /// Represents the class of items in legends. -class LegendItem { +abstract class LegendItem { /// Creates a [LegendItem]. LegendItem({ required this.text, required this.iconType, required this.iconColor, required this.iconBorderWidth, + required this.seriesIndex, this.iconBorderColor, this.shader, this.imageProvider, @@ -190,6 +192,8 @@ class LegendItem { this.degree, this.endAngle, this.startAngle, + this.series, + this.pointIndex = -1, }); /// Specifies the text of the legend. @@ -236,6 +240,15 @@ class LegendItem { /// Specifies the legend item is tapped. VoidCallback? onToggled; + + /// Specifies the series associated with the legend item. + final ChartSeriesRenderer? series; + + /// Specifies the index of the series associated with the legend item. + final int seriesIndex; + + /// Specifies the index of the data point in the series. + final int pointIndex; } /// The base layout for the legend dependents. @@ -421,7 +434,9 @@ class LegendLayoutState extends State { List? _items; LegendPosition _effectiveLegendPosition( - LegendPosition position, TextDirection direction) { + LegendPosition position, + TextDirection direction, + ) { if (position == LegendPosition.top || position == LegendPosition.bottom) { return position; } @@ -466,14 +481,15 @@ class LegendLayoutState extends State { @override Widget build(BuildContext context) { - final Widget? legend = widget.showLegend - ? CustomLayoutBuilder( - key: _legendKey, - builder: (BuildContext context, BoxConstraints constraints) { - return _buildLegend(); - }, - ) - : null; + final Widget? legend = + widget.showLegend + ? CustomLayoutBuilder( + key: _legendKey, + builder: (BuildContext context, BoxConstraints constraints) { + return _buildLegend(); + }, + ) + : null; return _LegendLayoutHandler( onTouchDown: widget.onTouchDown, @@ -487,7 +503,9 @@ class LegendLayoutState extends State { legendHeightFactor: widget.legendHeightFactor, legendFloatingOffset: widget.legendFloatingOffset, legendPosition: _effectiveLegendPosition( - widget.legendPosition, Directionality.of(context)), + widget.legendPosition, + Directionality.of(context), + ), legendAlignment: widget.legendAlignment, padding: widget.padding, backgroundColor: widget.backgroundColor, @@ -498,10 +516,7 @@ class LegendLayoutState extends State { legendTitle: widget.legendTitle, legend: legend, // TODO(VijayakumarM): Testing needed. - plotArea: KeyedSubtree( - key: _plotAreaKey, - child: widget.child, - ), + plotArea: KeyedSubtree(key: _plotAreaKey, child: widget.child), ); } @@ -601,7 +616,8 @@ class _LegendLayoutHandler backgroundColor: backgroundColor, borderColor: borderColor, borderWidth: borderWidth, - isResponsive: isResponsive) + isResponsive: isResponsive, + ) ..onTouchDown = onTouchDown ..onTouchMove = onTouchMove ..onTouchUp = onTouchUp; @@ -609,7 +625,9 @@ class _LegendLayoutHandler @override void updateRenderObject( - BuildContext context, _RenderLegendLayoutHandler renderObject) { + BuildContext context, + _RenderLegendLayoutHandler renderObject, + ) { renderObject ..backgroundImage = backgroundImage ..legendBackgroundColor = legendBackgroundColor @@ -667,22 +685,22 @@ class _RenderLegendLayoutHandler extends RenderBox required Color? borderColor, required double borderWidth, required bool isResponsive, - }) : _backgroundImage = backgroundImage, - _legendBackgroundColor = legendBackgroundColor, - _legendBorderColor = legendBorderColor, - _legendBorderWidth = legendBorderWidth, - _legendWidthFactor = legendWidthFactor, - _legendHeightFactor = legendHeightFactor, - _legendFloatingOffset = legendFloatingOffset, - _isLegendFloating = legendFloatingOffset != null, - _legendPosition = legendPosition, - _legendAlignment = legendAlignment, - _legendTitleAlignment = legendTitleAlignment, - _padding = padding, - _backgroundColor = backgroundColor, - _borderColor = borderColor, - _borderWidth = borderWidth, - _isResponsive = isResponsive { + }) : _backgroundImage = backgroundImage, + _legendBackgroundColor = legendBackgroundColor, + _legendBorderColor = legendBorderColor, + _legendBorderWidth = legendBorderWidth, + _legendWidthFactor = legendWidthFactor, + _legendHeightFactor = legendHeightFactor, + _legendFloatingOffset = legendFloatingOffset, + _isLegendFloating = legendFloatingOffset != null, + _legendPosition = legendPosition, + _legendAlignment = legendAlignment, + _legendTitleAlignment = legendTitleAlignment, + _padding = padding, + _backgroundColor = backgroundColor, + _borderColor = borderColor, + _borderWidth = borderWidth, + _isResponsive = isResponsive { _fetchImage(); } @@ -863,7 +881,8 @@ class _RenderLegendLayoutHandler extends RenderBox @override bool hitTestChildren(BoxHitTestResult result, {required Offset position}) { - final Iterable<_LegendSlot> slots = _LegendSlot.values.reversed; + final Iterable<_LegendSlot> slots = + _isLegendFloating ? _LegendSlot.values : _LegendSlot.values.reversed; for (final _LegendSlot slot in slots) { final RenderBox? child = childForSlot(slot); if (child != null) { @@ -944,9 +963,10 @@ class _RenderLegendLayoutHandler extends RenderBox ); } - final double gap = _isLegendFloating || legendSize.isEmpty - ? 0 - : _spaceBetweenLegendAndPlotArea; + final double gap = + _isLegendFloating || legendSize.isEmpty + ? 0 + : _spaceBetweenLegendAndPlotArea; late BoxConstraints plotAreaConstraints; if (_isLegendFloating) { plotAreaConstraints = BoxConstraints( @@ -989,16 +1009,25 @@ class _RenderLegendLayoutHandler extends RenderBox plotArea!.layout(plotAreaConstraints, parentUsesSize: true); _alignChildren( - legendSize, legendTitleSize, availableWidth, availableHeight); + legendSize, + legendTitleSize, + availableWidth, + availableHeight, + ); size = Size(desiredWidth, desiredHeight); } - void _alignChildren(Size legendSize, Size legendTitleSize, - double availableWidth, double availableHeight) { - final double gap = _isLegendFloating || legendSize.isEmpty - ? 0 - : _spaceBetweenLegendAndPlotArea; + void _alignChildren( + Size legendSize, + Size legendTitleSize, + double availableWidth, + double availableHeight, + ) { + final double gap = + _isLegendFloating || legendSize.isEmpty + ? 0 + : _spaceBetweenLegendAndPlotArea; final BoxParentData plotAreaParentData = plotArea!.parentData! as BoxParentData; if (_legendNeedsPaint) { @@ -1011,18 +1040,12 @@ class _RenderLegendLayoutHandler extends RenderBox switch (legendPosition) { case LegendPosition.left: case LegendPosition.right: - legendAreaSize = Size( - legendSize.width, - availableHeight, - ); + legendAreaSize = Size(legendSize.width, availableHeight); break; case LegendPosition.top: case LegendPosition.bottom: - legendAreaSize = Size( - availableWidth, - legendSize.height, - ); + legendAreaSize = Size(availableWidth, legendSize.height); break; } @@ -1030,8 +1053,9 @@ class _RenderLegendLayoutHandler extends RenderBox plotAreaParentData.offset = padding.topLeft; final Alignment alignmentForLegend = _effectiveLegendAlignment(); - legendParentData.offset = alignmentForLegend - .alongOffset(legendAreaSize - legendSize as Offset); + legendParentData.offset = alignmentForLegend.alongOffset( + legendAreaSize - legendSize as Offset, + ); switch (legendPosition) { case LegendPosition.left: legendParentData.offset += padding.topLeft; @@ -1043,35 +1067,41 @@ class _RenderLegendLayoutHandler extends RenderBox case LegendPosition.right: legendParentData.offset = Offset( - plotArea!.size.width - legendSize.width - padding.left - gap, - legendParentData.offset.dy + padding.top); + plotArea!.size.width - legendSize.width - padding.left - gap, + legendParentData.offset.dy + padding.top, + ); break; case LegendPosition.bottom: legendParentData.offset = Offset( - legendParentData.offset.dx + padding.left, - plotArea!.size.height - legendSize.height - padding.top); + legendParentData.offset.dx + padding.left, + plotArea!.size.height - legendSize.height - padding.top, + ); break; } legendTitleParentData?.offset = legendParentData.offset; legendParentData.offset = legendParentData.offset.translate( - legendFloatingOffset!.dx, - legendFloatingOffset!.dy + legendTitleSize.height); + legendFloatingOffset!.dx, + legendFloatingOffset!.dy + legendTitleSize.height, + ); //Edge detection for legend. Offset legendOffset = legendParentData.offset; - Offset legendTitleOffset = legendTitleParentData != null - ? legendTitleParentData.offset - : Offset.zero; + Offset legendTitleOffset = + legendTitleParentData != null + ? legendTitleParentData.offset + : Offset.zero; final Offset parentOffset = plotAreaParentData.offset; if (legendOffset.dx < parentOffset.dx) { legendOffset = Offset(parentOffset.dx, legendOffset.dy); legendTitleOffset = Offset(legendOffset.dx, legendTitleOffset.dy); } else if ((legendOffset.dx + (legendSize.width + padding.left + gap)) > plotArea!.size.width) { - legendOffset = - Offset(plotArea!.size.width - legendSize.width, legendOffset.dy); + legendOffset = Offset( + plotArea!.size.width - legendSize.width, + legendOffset.dy, + ); legendTitleOffset = Offset(legendOffset.dx, legendTitleOffset.dy); } @@ -1080,59 +1110,79 @@ class _RenderLegendLayoutHandler extends RenderBox legendTitleOffset = Offset(legendTitleOffset.dx, legendOffset.dy); } else if ((legendOffset.dy + (legendSize.height + padding.top + gap)) > plotArea!.size.height) { - legendOffset = Offset(legendOffset.dx, - plotArea!.size.height - legendSize.height + padding.top); + legendOffset = Offset( + legendOffset.dx, + plotArea!.size.height - legendSize.height + padding.top, + ); legendTitleOffset = Offset(legendTitleOffset.dx, legendOffset.dy); } legendParentData.offset = legendOffset; - legendTitleParentData?.offset = legendTitleOffset + + legendTitleParentData?.offset = + legendTitleOffset + _legendTitleAlignmentOffset( - legendTitleAlignment, legendTitleSize, legendSize) - .translate( - legendPosition == LegendPosition.right - ? 0 - : legendFloatingOffset!.dx, - legendPosition == LegendPosition.bottom - ? 0 - : legendFloatingOffset!.dy); + legendTitleAlignment, + legendTitleSize, + legendSize, + ).translate( + legendPosition == LegendPosition.right + ? 0 + : legendFloatingOffset!.dx, + legendPosition == LegendPosition.bottom + ? 0 + : legendFloatingOffset!.dy, + ); } else { final Alignment alignmentForLegend = _effectiveLegendAlignment(); - legendParentData.offset = alignmentForLegend - .alongOffset(legendAreaSize - legendSize as Offset); + legendParentData.offset = alignmentForLegend.alongOffset( + legendAreaSize - legendSize as Offset, + ); final Size legendPortionFromAvailableSize = _isLegendFloating ? Size.zero : legendSize; switch (legendPosition) { case LegendPosition.left: legendParentData.offset += padding.topLeft; plotAreaParentData.offset = Offset( - padding.left + legendPortionFromAvailableSize.width + gap, - padding.top); + padding.left + legendPortionFromAvailableSize.width + gap, + padding.top, + ); break; case LegendPosition.top: legendParentData.offset += padding.topLeft; - plotAreaParentData.offset = Offset(padding.left, - padding.top + legendPortionFromAvailableSize.height + gap); + plotAreaParentData.offset = Offset( + padding.left, + padding.top + legendPortionFromAvailableSize.height + gap, + ); break; case LegendPosition.right: - legendParentData.offset += - Offset(padding.left + plotArea!.size.width + gap, padding.top); + legendParentData.offset += Offset( + padding.left + plotArea!.size.width + gap, + padding.top, + ); plotAreaParentData.offset = Offset(padding.left, padding.top); break; case LegendPosition.bottom: - legendParentData.offset += - Offset(padding.left, padding.top + plotArea!.size.height + gap); + legendParentData.offset += Offset( + padding.left, + padding.top + plotArea!.size.height + gap, + ); plotAreaParentData.offset = Offset(padding.left, padding.top); break; } - legendTitleParentData?.offset = legendParentData.offset + + legendTitleParentData?.offset = + legendParentData.offset + _legendTitleAlignmentOffset( - legendTitleAlignment, legendTitleSize, legendSize); - legendParentData.offset = - legendParentData.offset.translate(0.0, legendTitleSize.height); + legendTitleAlignment, + legendTitleSize, + legendSize, + ); + legendParentData.offset = legendParentData.offset.translate( + 0.0, + legendTitleSize.height, + ); } } else { plotAreaParentData.offset = padding.topLeft; @@ -1140,7 +1190,10 @@ class _RenderLegendLayoutHandler extends RenderBox } Offset _legendTitleAlignmentOffset( - LegendAlignment alignment, Size titleSize, Size areaSize) { + LegendAlignment alignment, + Size titleSize, + Size areaSize, + ) { switch (alignment) { case LegendAlignment.near: return Offset.zero; @@ -1231,9 +1284,11 @@ class _RenderLegendLayoutHandler extends RenderBox void _drawLegendBackgroundAndBorder(PaintingContext context, Offset offset) { if (legend != null) { - final bool canDrawLegendBackground = legendBackgroundColor != null && + final bool canDrawLegendBackground = + legendBackgroundColor != null && legendBackgroundColor != Colors.transparent; - final bool canDrawLegendBorder = legendBorderColor != null && + final bool canDrawLegendBorder = + legendBorderColor != null && legendBorderColor != Colors.transparent && legendBorderWidth > 0; if (canDrawLegendBackground || canDrawLegendBorder) { @@ -1246,17 +1301,22 @@ class _RenderLegendLayoutHandler extends RenderBox legendTitleOffset = (legendTitle!.parentData! as BoxParentData).offset; legendSize = Size( - legendSize.width, legendTitle!.size.height + legendSize.height); + legendSize.width, + legendTitle!.size.height + legendSize.height, + ); } final Rect bounds = Rect.fromLTWH( - legendBounds.left + offset.dx, - legendTitleOffset.dy + offset.dy, - legendSize.width, - legendSize.height); + legendBounds.left + offset.dx, + legendTitleOffset.dy + offset.dy, + legendSize.width, + legendSize.height, + ); if (canDrawLegendBackground) { - context.canvas - .drawRect(bounds, Paint()..color = legendBackgroundColor!); + context.canvas.drawRect( + bounds, + Paint()..color = legendBackgroundColor!, + ); } if (canDrawLegendBorder) { @@ -1377,27 +1437,29 @@ class _VectorLegendState extends State<_VectorLegend> { final int length = widget.items!.length; for (int i = 0; i < length; i++) { final LegendItem item = widget.items![i]; - legendItems.add(_IconText( - details: item, - index: i, - itemBuilder: widget.itemBuilder, - padding: EdgeInsets.all(widget.itemPadding / 2), - textStyle: widget.textStyle, - iconSize: widget.iconSize, - iconBorderColor: widget.iconBorderColor, - iconBorderWidth: widget.iconBorderWidth, - spacing: widget.spacing, - iconOpacity: widget.itemIconOpacity, - toggleEnabled: widget.enableToggling, - isToggled: item.isToggled, - toggledColor: _effectiveToggledColor(context), - toggledTextOpacity: widget.toggledTextOpacity, - onTap: item.onTap, - overlayMarkerType: item.overlayMarkerType, - degree: item.degree, - startAngle: item.startAngle, - endAngle: item.endAngle, - )); + legendItems.add( + _IconText( + details: item, + index: i, + itemBuilder: widget.itemBuilder, + padding: EdgeInsets.all(widget.itemPadding / 2), + textStyle: widget.textStyle, + iconSize: widget.iconSize, + iconBorderColor: widget.iconBorderColor, + iconBorderWidth: widget.iconBorderWidth, + spacing: widget.spacing, + iconOpacity: widget.itemIconOpacity, + toggleEnabled: widget.enableToggling, + isToggled: item.isToggled, + toggledColor: _effectiveToggledColor(context), + toggledTextOpacity: widget.toggledTextOpacity, + onTap: item.onTap, + overlayMarkerType: item.overlayMarkerType, + degree: item.degree, + startAngle: item.startAngle, + endAngle: item.endAngle, + ), + ); } } @@ -1409,9 +1471,10 @@ class _VectorLegendState extends State<_VectorLegend> { if (widget.enableToggling) { toggledColor = widget.toggledIconColor ?? widget.toggledItemColor; if (toggledColor == null || toggledColor == Colors.transparent) { - toggledColor = Theme.of(context).brightness == Brightness.light - ? const Color.fromRGBO(230, 230, 230, 1) - : const Color.fromRGBO(66, 66, 66, 1); + toggledColor = + Theme.of(context).brightness == Brightness.light + ? const Color.fromRGBO(230, 230, 230, 1) + : const Color.fromRGBO(66, 66, 66, 1); } } @@ -1421,8 +1484,10 @@ class _VectorLegendState extends State<_VectorLegend> { Widget _wrapWithWrap(List items) { final double horizontalPadding = widget.itemPadding / 2; return Padding( - padding: - EdgeInsets.only(left: horizontalPadding, right: horizontalPadding), + padding: EdgeInsets.only( + left: horizontalPadding, + right: horizontalPadding, + ), child: Wrap( direction: widget.direction, spacing: widget.itemSpacing, @@ -1655,7 +1720,9 @@ class _IconTextState extends State<_IconText> bool _isToggled = false; Widget _buildCustomPaint( - ItemRendererDetails details, AsyncSnapshot snapshot) { + ItemRendererDetails details, + AsyncSnapshot snapshot, + ) { Widget current = CustomPaint( size: widget.iconSize, painter: _LegendIconShape( @@ -1685,8 +1752,9 @@ class _IconTextState extends State<_IconText> return ShaderMask( blendMode: BlendMode.srcATop, shaderCallback: (Rect bounds) { - return LinearGradient(colors: [color, color]) - .createShader(bounds); + return LinearGradient( + colors: [color, color], + ).createShader(bounds); }, child: current, ); @@ -1700,8 +1768,9 @@ class _IconTextState extends State<_IconText> _completer = Completer(); _imageStream?.removeListener(imageStreamListener(_completer!)); - _imageStream = - widget.details.imageProvider!.resolve(ImageConfiguration.empty); + _imageStream = widget.details.imageProvider!.resolve( + ImageConfiguration.empty, + ); _imageStream!.addListener(imageStreamListener(_completer!)); _imageInfo?.dispose(); _imageInfo = await _completer!.future; @@ -1736,10 +1805,14 @@ class _IconTextState extends State<_IconText> @override void initState() { _toggleAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); _toggleAnimationController.addListener(rebuild); _toggleAnimation = CurvedAnimation( - parent: _toggleAnimationController, curve: Curves.easeInOut); + parent: _toggleAnimationController, + curve: Curves.easeInOut, + ); final Color begin = widget.details.shader == null && widget.details.imageProvider == null @@ -1750,8 +1823,10 @@ class _IconTextState extends State<_IconText> ? widget.details.iconBorderColor ?? widget.iconBorderColor : Colors.transparent; _iconColorTween = ColorTween(begin: begin, end: widget.toggledColor); - _iconBorderColorTween = - ColorTween(begin: borderColorBegin, end: widget.toggledColor); + _iconBorderColorTween = ColorTween( + begin: borderColorBegin, + end: widget.toggledColor, + ); _shaderMaskColorTween = ColorTween(end: widget.toggledColor); _opacityTween = Tween(begin: 1.0, end: widget.toggledTextOpacity); @@ -1829,10 +1904,11 @@ class _IconTextState extends State<_IconText> current = _buildShaderMask(color, current); } } else { - final Color? effectiveIconColor = - _iconColorTween.evaluate(_toggleAnimation); - final Color? effectiveBorderIconColor = - _iconBorderColorTween.evaluate(_toggleAnimation); + final Color? effectiveIconColor = _iconColorTween.evaluate( + _toggleAnimation, + ); + final Color? effectiveBorderIconColor = _iconBorderColorTween + .evaluate(_toggleAnimation); final ItemRendererDetails details = ItemRendererDetails( item: widget.details, index: widget.index, @@ -1852,8 +1928,9 @@ class _IconTextState extends State<_IconText> if (effectiveBorderIconColor != null && effectiveBorderIconColor != details.iconBorderColor) { _iconBorderColorTween.begin = details.iconBorderColor; - details.iconBorderColor = - _iconBorderColorTween.evaluate(_toggleAnimation); + details.iconBorderColor = _iconBorderColorTween.evaluate( + _toggleAnimation, + ); } current = SingleChildScrollView( physics: const NeverScrollableScrollPhysics(), @@ -1866,21 +1943,20 @@ class _IconTextState extends State<_IconText> Text( details.text, style: widget.textStyle.copyWith( - color: widget.textStyle.foreground == null - ? widget.textStyle.color!.withValues( - alpha: _opacityTween.evaluate(_toggleAnimation)) - : widget.textStyle.foreground!.color, + color: + widget.textStyle.foreground == null + ? widget.textStyle.color!.withValues( + alpha: _opacityTween.evaluate(_toggleAnimation), + ) + : widget.textStyle.foreground!.color, ), - ) + ), ], ), ); } - current = Padding( - padding: widget.padding, - child: current, - ); + current = Padding(padding: widget.padding, child: current); if (widget.toggleEnabled) { current = MouseRegion( diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/core_tooltip.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/core_tooltip.dart index 755d54722..62fe6e746 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/core_tooltip.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/core_tooltip.dart @@ -7,8 +7,8 @@ import 'package:flutter/rendering.dart'; import 'element_widget.dart'; -typedef TooltipWidgetBuilder = Widget? Function( - BuildContext, TooltipInfo?, Size); +typedef TooltipWidgetBuilder = + Widget? Function(BuildContext, TooltipInfo?, Size); /// Holds details of a tooltip is shown. @immutable @@ -135,8 +135,11 @@ class CoreTooltipState extends State Timer? _desktopShowDelayTimer; Timer? _showTimer; - void show(TooltipInfo info, PointerDeviceKind kind, - {bool immediately = false}) { + void show( + TooltipInfo info, + PointerDeviceKind kind, { + bool immediately = false, + }) { if (_isDesktop && kind == PointerDeviceKind.mouse) { _desktopShowDelayTimer?.cancel(); if (immediately) { @@ -188,17 +191,18 @@ class CoreTooltipState extends State } _showTimer = Timer( - // When the [animationDuration] is 3000 and the [showDuration] is 3000, - // the tooltip will start hiding after it completes the scale animation, - // without staying in the visual for 3 seconds. - // So, [widget.animationDuration] has been considered in [_showTimer]. - Duration(milliseconds: widget.animationDuration + widget.showDuration), - () { - if (mounted) { - hide(); - _showTimer = null; - } - }); + // When the [animationDuration] is 3000 and the [showDuration] is 3000, + // the tooltip will start hiding after it completes the scale animation, + // without staying in the visual for 3 seconds. + // So, [widget.animationDuration] has been considered in [_showTimer]. + Duration(milliseconds: widget.animationDuration + widget.showDuration), + () { + if (mounted) { + hide(); + _showTimer = null; + } + }, + ); // } } @@ -231,7 +235,8 @@ class CoreTooltipState extends State @override Widget build(BuildContext context) { final ThemeData chartThemeData = Theme.of(context); - _isDesktop = kIsWeb || + _isDesktop = + kIsWeb || chartThemeData.platform == TargetPlatform.macOS || chartThemeData.platform == TargetPlatform.windows || chartThemeData.platform == TargetPlatform.linux; @@ -321,7 +326,9 @@ class _CoreTooltipRenderObjectWidget extends SingleChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, _CoreTooltipRenderBox renderObject) { + BuildContext context, + _CoreTooltipRenderBox renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..primaryPosition = primaryPosition @@ -348,9 +355,10 @@ class _CoreTooltipRenderBox extends RenderProxyBox { final _RectangularShape _tooltipShape = const _RectangularShape(); final Paint _fillPaint = Paint()..isAntiAlias = true; - final Paint _strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint _strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; Offset? _localPrimaryPosition; Offset? _localSecondaryPosition; @@ -385,8 +393,10 @@ class _CoreTooltipRenderBox extends RenderProxyBox { set edgeBounds(Rect? value) { _edgeBounds = value; if (value != null) { - _localEdgeBounds = Rect.fromPoints(globalToLocal(edgeBounds!.topLeft), - globalToLocal(edgeBounds!.bottomRight)); + _localEdgeBounds = Rect.fromPoints( + globalToLocal(edgeBounds!.topLeft), + globalToLocal(edgeBounds!.bottomRight), + ); } else { _localEdgeBounds = null; } @@ -567,9 +577,10 @@ class _CoreTooltipRenderBox extends RenderProxyBox { final Rect surfaceBounds = _localEdgeBounds ?? paintBounds; child?.layout(constraints, parentUsesSize: true); _effectivePreferTooltipOnTop ??= _canPreferTooltipOnTop(surfaceBounds); - _nosePosition = _effectivePreferTooltipOnTop! - ? _localPrimaryPosition?.translate(0.0, -_noseGap) - : _localSecondaryPosition?.translate(0.0, _noseGap); + _nosePosition = + _effectivePreferTooltipOnTop! + ? _localPrimaryPosition?.translate(0.0, -_noseGap) + : _localSecondaryPosition?.translate(0.0, _noseGap); _validateNosePosition(); _path = _tooltipShape.outerPath( @@ -703,11 +714,14 @@ class _CoreTooltipRenderBox extends RenderProxyBox { final BoxParentData childParentData = child!.parentData! as BoxParentData; // Used [pushTransform] because scrollable widgets are not scaled with // [context.paintChild]. - context.pushTransform(true, Offset(_nosePosition!.dx, _nosePosition!.dy), - Matrix4.diagonal3Values(animationValue, animationValue, 1), - (PaintingContext context, Offset translateOffset) { - context.paintChild(child!, childParentData.offset + offset); - }); + context.pushTransform( + true, + Offset(_nosePosition!.dx, _nosePosition!.dy), + Matrix4.diagonal3Values(animationValue, animationValue, 1), + (PaintingContext context, Offset translateOffset) { + context.paintChild(child!, childParentData.offset + offset); + }, + ); context.canvas.restore(); } @@ -744,30 +758,36 @@ class _RectangularShape { double tooltipTriangleOffsetY = tooltipStartPoint - triangleHeight; final double endGlobal = surfaceBounds.right - innerPadding; - double rightLineWidth = position.dx + halfTooltipWidth > endGlobal - ? endGlobal - position.dx - : halfTooltipWidth; + double rightLineWidth = + position.dx + halfTooltipWidth > endGlobal + ? endGlobal - position.dx + : halfTooltipWidth; final double leftLineWidth = position.dx - halfTooltipWidth < surfaceBounds.left + innerPadding ? position.dx - surfaceBounds.left - innerPadding : tooltipWidth - rightLineWidth; - rightLineWidth = leftLineWidth < halfTooltipWidth - ? halfTooltipWidth - leftLineWidth + rightLineWidth - : rightLineWidth; - - double moveNosePoint = leftLineWidth < tooltipWidth * 0.1 - ? tooltipWidth * 0.1 - leftLineWidth - : 0.0; - moveNosePoint = rightLineWidth < tooltipWidth * 0.1 - ? -(tooltipWidth * 0.1 - rightLineWidth) - : moveNosePoint; - - double shiftText = leftLineWidth > rightLineWidth - ? -(halfTooltipWidth - rightLineWidth) - : 0.0; - shiftText = leftLineWidth < rightLineWidth - ? (halfTooltipWidth - leftLineWidth) - : shiftText; + rightLineWidth = + leftLineWidth < halfTooltipWidth + ? halfTooltipWidth - leftLineWidth + rightLineWidth + : rightLineWidth; + + double moveNosePoint = + leftLineWidth < tooltipWidth * 0.1 + ? tooltipWidth * 0.1 - leftLineWidth + : 0.0; + moveNosePoint = + rightLineWidth < tooltipWidth * 0.1 + ? -(tooltipWidth * 0.1 - rightLineWidth) + : moveNosePoint; + + double shiftText = + leftLineWidth > rightLineWidth + ? -(halfTooltipWidth - rightLineWidth) + : 0.0; + shiftText = + leftLineWidth < rightLineWidth + ? (halfTooltipWidth - leftLineWidth) + : shiftText; rightLineWidth = rightLineWidth + elevation; if (!preferTooltipOnTop) { @@ -782,13 +802,21 @@ class _RectangularShape { tooltipHeight *= -1; borderRadius = BorderRadius.only( topRight: Radius.elliptical( - borderRadius.bottomRight.x, -borderRadius.bottomRight.y), + borderRadius.bottomRight.x, + -borderRadius.bottomRight.y, + ), bottomRight: Radius.elliptical( - borderRadius.topRight.x, -borderRadius.topRight.y), + borderRadius.topRight.x, + -borderRadius.topRight.y, + ), topLeft: Radius.elliptical( - borderRadius.bottomLeft.x, -borderRadius.bottomLeft.y), - bottomLeft: - Radius.elliptical(borderRadius.topLeft.x, -borderRadius.topLeft.y), + borderRadius.bottomLeft.x, + -borderRadius.bottomLeft.y, + ), + bottomLeft: Radius.elliptical( + borderRadius.topLeft.x, + -borderRadius.topLeft.y, + ), ); } @@ -824,7 +852,9 @@ class _RectangularShape { // preferTooltipOnTop is false, // \ path.lineTo( - halfTooltipTriangleWidth + moveNosePoint, tooltipTriangleOffsetY); + halfTooltipTriangleWidth + moveNosePoint, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ___ // / @@ -832,7 +862,9 @@ class _RectangularShape { // preferTooltipOnTop is false, // \___ path.lineTo( - rightLineWidth - borderRadius.bottomRight.x, tooltipTriangleOffsetY); + rightLineWidth - borderRadius.bottomRight.x, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ___| // / @@ -840,10 +872,16 @@ class _RectangularShape { // preferTooltipOnTop is false, // \___ // | - path.quadraticBezierTo(rightLineWidth, tooltipTriangleOffsetY, - rightLineWidth, tooltipTriangleOffsetY - borderRadius.bottomRight.y); - path.lineTo(rightLineWidth, - tooltipTriangleOffsetY - tooltipHeight + borderRadius.topRight.y); + path.quadraticBezierTo( + rightLineWidth, + tooltipTriangleOffsetY, + rightLineWidth, + tooltipTriangleOffsetY - borderRadius.bottomRight.y, + ); + path.lineTo( + rightLineWidth, + tooltipTriangleOffsetY - tooltipHeight + borderRadius.topRight.y, + ); // preferTooltipOnTop is true, // _______ // ___| @@ -853,12 +891,15 @@ class _RectangularShape { // \___ // ________| path.quadraticBezierTo( - rightLineWidth, - tooltipTriangleOffsetY - tooltipHeight, - rightLineWidth - borderRadius.topRight.x, - tooltipTriangleOffsetY - tooltipHeight); - path.lineTo(-leftLineWidth + borderRadius.topLeft.x, - tooltipTriangleOffsetY - tooltipHeight); + rightLineWidth, + tooltipTriangleOffsetY - tooltipHeight, + rightLineWidth - borderRadius.topRight.x, + tooltipTriangleOffsetY - tooltipHeight, + ); + path.lineTo( + -leftLineWidth + borderRadius.topLeft.x, + tooltipTriangleOffsetY - tooltipHeight, + ); // preferTooltipOnTop is true, // _______ // | ___| @@ -868,12 +909,15 @@ class _RectangularShape { // \___ // |________| path.quadraticBezierTo( - -leftLineWidth, - tooltipTriangleOffsetY - tooltipHeight, - -leftLineWidth, - tooltipTriangleOffsetY - tooltipHeight + borderRadius.topLeft.y); + -leftLineWidth, + tooltipTriangleOffsetY - tooltipHeight, + -leftLineWidth, + tooltipTriangleOffsetY - tooltipHeight + borderRadius.topLeft.y, + ); path.lineTo( - -leftLineWidth, tooltipTriangleOffsetY - borderRadius.bottomLeft.y); + -leftLineWidth, + tooltipTriangleOffsetY - borderRadius.bottomLeft.y, + ); // preferTooltipOnTop is true, // ________ // |___ ___| @@ -882,10 +926,16 @@ class _RectangularShape { // preferTooltipOnTop is false, // ___ \___ // |________| - path.quadraticBezierTo(-leftLineWidth, tooltipTriangleOffsetY, - -leftLineWidth + borderRadius.bottomLeft.x, tooltipTriangleOffsetY); + path.quadraticBezierTo( + -leftLineWidth, + tooltipTriangleOffsetY, + -leftLineWidth + borderRadius.bottomLeft.x, + tooltipTriangleOffsetY, + ); path.lineTo( - -halfTooltipTriangleWidth + moveNosePoint, tooltipTriangleOffsetY); + -halfTooltipTriangleWidth + moveNosePoint, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ________ // |___ ___| diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/data_label.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/data_label.dart index 5c37cfde3..8a2039591 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/data_label.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/data_label.dart @@ -572,20 +572,21 @@ class DataLabelSettings { overflowMode, labelIntersectAction, connectorLineSettings, - labelPosition + labelPosition, ]; return Object.hashAll(values); } } -typedef _ChartDataLabelWidgetBuilder = Widget Function( - T data, - int yIndex, - ChartSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position, -); +typedef _ChartDataLabelWidgetBuilder = + Widget Function( + T data, + int yIndex, + ChartSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ); // ignore: must_be_immutable base class CartesianChartDataLabelPositioned @@ -741,9 +742,10 @@ class _CartesianDataLabelContainerState ChartDataPointType position, ) { final DataLabelSettings settings = widget.settings; - final num value = stackedYValues != null && !settings.showCumulativeValues - ? stackedYValues![pointIndex] - : yLists![yIndex][pointIndex]; + final num value = + stackedYValues != null && !settings.showCumulativeValues + ? stackedYValues![pointIndex] + : yLists![yIndex][pointIndex]; final String formattedText = formatNumericValue(value, renderer!.yAxis); return _buildDataLabelText(formattedText, pointIndex); } @@ -753,9 +755,10 @@ class _CartesianDataLabelContainerState if (settings.color != null) { return settings.color!.withValues(alpha: settings.opacity); } else if (settings.useSeriesColor) { - final Color? pointColor = renderer!.pointColors.isNotEmpty - ? renderer!.pointColors[dataPointIndex] - : null; + final Color? pointColor = + renderer!.pointColors.isNotEmpty + ? renderer!.pointColors[dataPointIndex] + : null; return (pointColor ?? renderer!.color ?? renderer!.paletteColor) .withValues(alpha: settings.opacity); } else { @@ -784,8 +787,10 @@ class _CartesianDataLabelContainerState _textChildren!.add(child); } - void _buildLinearDataLabels(_ChartDataLabelWidgetBuilder callback, - Function(CartesianChartDataLabelPositioned) add) { + void _buildLinearDataLabels( + _ChartDataLabelWidgetBuilder callback, + Function(CartesianChartDataLabelPositioned) add, + ) { final int yLength = yLists?.length ?? 0; List? actualXValues; if (xRawValues != null && xRawValues!.isNotEmpty) { @@ -798,11 +803,13 @@ class _CartesianDataLabelContainerState return; } - final bool isEmptyMode = renderer! is! WaterfallSeriesRenderer && + final bool isEmptyMode = + renderer! is! WaterfallSeriesRenderer && (renderer!.emptyPointSettings.mode == EmptyPointMode.drop || renderer!.emptyPointSettings.mode == EmptyPointMode.gap); - final bool hasSortedIndexes = renderer!.sortingOrder != SortingOrder.none && + final bool hasSortedIndexes = + renderer!.sortingOrder != SortingOrder.none && sortedIndexes != null && sortedIndexes!.isNotEmpty; @@ -810,13 +817,22 @@ class _CartesianDataLabelContainerState final int end = renderer!.visibleIndexes[1]; final int xLength = actualXValues.length; for (int i = start; i <= end && i < xLength; i++) { - _obtainLabel(i, actualXValues, yLength, callback, add, isEmptyMode, - hasSortedIndexes); + _obtainLabel( + i, + actualXValues, + yLength, + callback, + add, + isEmptyMode, + hasSortedIndexes, + ); } } - void _buildNonLinearDataLabels(_ChartDataLabelWidgetBuilder callback, - Function(CartesianChartDataLabelPositioned) add) { + void _buildNonLinearDataLabels( + _ChartDataLabelWidgetBuilder callback, + Function(CartesianChartDataLabelPositioned) add, + ) { final int yLength = yLists?.length ?? 0; List? actualXValues; if (xRawValues != null && xRawValues!.isNotEmpty) { @@ -829,19 +845,28 @@ class _CartesianDataLabelContainerState return; } - final bool isEmptyMode = renderer! is! WaterfallSeriesRenderer && + final bool isEmptyMode = + renderer! is! WaterfallSeriesRenderer && (renderer!.emptyPointSettings.mode == EmptyPointMode.drop || renderer!.emptyPointSettings.mode == EmptyPointMode.gap); - final bool hasSortedIndexes = renderer!.sortingOrder != SortingOrder.none && + final bool hasSortedIndexes = + renderer!.sortingOrder != SortingOrder.none && sortedIndexes != null && sortedIndexes!.isNotEmpty; final int xLength = actualXValues.length; for (final int index in renderer!.visibleIndexes) { if (index < xLength) { - _obtainLabel(index, actualXValues, yLength, callback, add, isEmptyMode, - hasSortedIndexes); + _obtainLabel( + index, + actualXValues, + yLength, + callback, + add, + isEmptyMode, + hasSortedIndexes, + ); } } } @@ -871,19 +896,19 @@ class _CartesianDataLabelContainerState } final CartesianChartDataLabelPositioned child = CartesianChartDataLabelPositioned( - x: x, - y: yValues[index], - dataPointIndex: index, - position: position, - child: callback( - widget.dataSource[pointIndex], - k, - widget.series, - index, - renderer!.index, - position, - ), - ); + x: x, + y: yValues[index], + dataPointIndex: index, + position: position, + child: callback( + widget.dataSource[pointIndex], + k, + widget.series, + index, + renderer!.index, + position, + ), + ); add(child); } } @@ -910,9 +935,10 @@ class _CartesianDataLabelContainerState if (widget.builder != null) { callback = _dataLabelFromBuilder; } else { - callback = widget.mapper != null - ? _dataLabelFromMapper - : _defaultDataLabel; + callback = + widget.mapper != null + ? _dataLabelFromMapper + : _defaultDataLabel; } void Function(CartesianChartDataLabelPositioned child) add; if (widget.builder != null) { @@ -969,7 +995,9 @@ class CartesianDataLabelStack extends ChartElementStack { @override void updateRenderObject( - BuildContext context, RenderCartesianDataLabelStack renderObject) { + BuildContext context, + RenderCartesianDataLabelStack renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..series = series @@ -1030,16 +1058,19 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { return; } - final String text = childCount > 0 - ? '' - : (labels!.elementAt(selectedIndex).child as DataLabelText).text; - series!.parent!.onDataLabelTapped!(DataLabelTapDetails( - series!.index, - series!.viewportIndex(selectedIndex), - text, - settings, - selectedIndex, - )); + final String text = + childCount > 0 + ? '' + : (labels!.elementAt(selectedIndex).child as DataLabelText).text; + series!.parent!.onDataLabelTapped!( + DataLabelTapDetails( + series!.index, + series!.viewportIndex(selectedIndex), + text, + settings, + selectedIndex, + ), + ); } } @@ -1088,14 +1119,21 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { nextChildData, child.size, ); - final Offset offset = - _invokeDataLabelRender(currentChildData.dataPointIndex); - currentChildData.offset = Offset(currentChildData.offset.dx + offset.dx, - currentChildData.offset.dy - offset.dy); - currentChildData.bounds = - _calculateBounds(child.size, currentChildData.offset); - currentChildData.rotatedBounds = - calculateRotatedBounds(currentChildData.bounds, settings.angle); + final Offset offset = _invokeDataLabelRender( + currentChildData.dataPointIndex, + ); + currentChildData.offset = Offset( + currentChildData.offset.dx + offset.dx, + currentChildData.offset.dy - offset.dy, + ); + currentChildData.bounds = _calculateBounds( + child.size, + currentChildData.offset, + ); + currentChildData.rotatedBounds = calculateRotatedBounds( + currentChildData.bounds, + settings.angle, + ); child = nextSibling; previousChildData = currentChildData; } @@ -1112,17 +1150,22 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { ..position = currentLabel.position; final CartesianChartDataLabelPositioned? nextLabel = currentLabel.next; if (nextLabel != null) { - nextLabelData = ChartElementParentData() - ..x = nextLabel.x - ..y = nextLabel.y - ..dataPointIndex = nextLabel.dataPointIndex - ..position = nextLabel.position; + nextLabelData = + ChartElementParentData() + ..x = nextLabel.x + ..y = nextLabel.y + ..dataPointIndex = nextLabel.dataPointIndex + ..position = nextLabel.position; } final DataLabelText details = currentLabel.child as DataLabelText; - final Offset offset = - _invokeDataLabelRender(currentLabel.dataPointIndex, details); - currentLabel.offset = Offset(currentLabel.offset.dx + offset.dx, - currentLabel.offset.dy - offset.dy); + final Offset offset = _invokeDataLabelRender( + currentLabel.dataPointIndex, + details, + ); + currentLabel.offset = Offset( + currentLabel.offset.dx + offset.dx, + currentLabel.offset.dy - offset.dy, + ); currentLabel.size = measureText(details.text, details.textStyle); currentLabel.labelAlignment = series!.effectiveDataLabelAlignment( settings.labelAlignment, @@ -1138,10 +1181,14 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { nextLabelData, currentLabel.size, ); - currentLabel.bounds = - _calculateBounds(currentLabel.size, currentLabel.offset); - currentLabel.rotatedBounds = - calculateRotatedBounds(currentLabel.bounds, settings.angle); + currentLabel.bounds = _calculateBounds( + currentLabel.size, + currentLabel.offset, + ); + currentLabel.rotatedBounds = calculateRotatedBounds( + currentLabel.bounds, + settings.angle, + ); previousLabelData = currentLabelData; } } @@ -1200,15 +1247,24 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { yAlignment = settings.alignment; } } - final double x = - _addPlacementAlignment(xAlignment, position.dx, size.width); - final double y = - _addPlacementAlignment(yAlignment, position.dy, size.height); + final double x = _addPlacementAlignment( + xAlignment, + position.dx, + size.width, + ); + final double y = _addPlacementAlignment( + yAlignment, + position.dy, + size.height, + ); return _alignWithInRange(current.x!, current.y!, x, y, paintBounds, size); } double _addPlacementAlignment( - ChartAlignment? alignment, double position, double size) { + ChartAlignment? alignment, + double position, + double size, + ) { if (alignment == null) { return position; } @@ -1223,8 +1279,14 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { } } - Offset _alignWithInRange(num xPoint, num yPoint, double labelX, double labelY, - Rect source, Size size) { + Offset _alignWithInRange( + num xPoint, + num yPoint, + double labelX, + double labelY, + Rect source, + Size size, + ) { final DoubleRange xRange = series!.xAxis!.effectiveVisibleRange!; final DoubleRange yRange = series!.yAxis!.effectiveVisibleRange!; num xValue = xPoint; @@ -1293,8 +1355,9 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { nextChildData = nextSibling.parentData! as ChartElementParentData; if (!currentChildData.rotatedBounds.topLeft.isNaN && !currentChildData.rotatedBounds.bottomRight.isNaN && - currentChildData.rotatedBounds - .overlaps(nextChildData.rotatedBounds)) { + currentChildData.rotatedBounds.overlaps( + nextChildData.rotatedBounds, + )) { nextChildData.isVisible = false; } nextSibling = nextChildData.nextSibling; @@ -1366,8 +1429,9 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { continue; } - nextSeriesDataLabelRenderBox - ?.visitChildren((RenderObject nextSeriesDataLabel) { + nextSeriesDataLabelRenderBox?.visitChildren(( + RenderObject nextSeriesDataLabel, + ) { final RenderCartesianDataLabelStack nextSeriesDataLabelStack = nextSeriesDataLabel as RenderCartesianDataLabelStack; if (nextSeriesDataLabelStack.childCount > 0) { @@ -1382,8 +1446,9 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { if (!currentChildData.rotatedBounds.topLeft.isNaN && !currentChildData.rotatedBounds.bottomRight.isNaN && - currentChildData.rotatedBounds - .overlaps(nextChildData.rotatedBounds)) { + currentChildData.rotatedBounds.overlaps( + nextChildData.rotatedBounds, + )) { nextChildData.isVisible = false; } nextChild = nextChildData.nextSibling; @@ -1412,8 +1477,9 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { continue; } - nextSeriesDataLabelRenderBox - ?.visitChildren((RenderObject nextSeriesDataLabel) { + nextSeriesDataLabelRenderBox?.visitChildren(( + RenderObject nextSeriesDataLabel, + ) { final RenderCartesianDataLabelStack nextSeriesDataLabelStack = nextSeriesDataLabel as RenderCartesianDataLabelStack; final LinkedList? nextLabels = @@ -1427,8 +1493,9 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { if (!currentLabel.rotatedBounds.topLeft.isNaN && !currentLabel.rotatedBounds.bottomRight.isNaN && - currentLabel.rotatedBounds - .overlaps(nextLabel.rotatedBounds)) { + currentLabel.rotatedBounds.overlaps( + nextLabel.rotatedBounds, + )) { nextLabel.isVisible = false; } } @@ -1463,10 +1530,11 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { } } else if (labels != null) { final Paint fillPaint = Paint()..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..color = settings.borderColor - ..strokeWidth = settings.borderWidth - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = settings.borderColor + ..strokeWidth = settings.borderWidth + ..style = PaintingStyle.stroke; for (final CartesianChartDataLabelPositioned label in labels!) { if (label.offset.isNaN || !label.isVisible) { continue; @@ -1476,8 +1544,10 @@ class RenderCartesianDataLabelStack extends RenderChartElementStack { final DataLabelText details = label.child as DataLabelText; surfaceColor = details.color == Colors.transparent ? surfaceColor : details.color; - final TextStyle effectiveTextStyle = - saturatedTextStyle(surfaceColor, details.textStyle); + final TextStyle effectiveTextStyle = saturatedTextStyle( + surfaceColor, + details.textStyle, + ); fillPaint ..color = details.color ..shader = series!.markerShader(label.offset & label.size); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/element_widget.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/element_widget.dart index ba24e628e..8f5ee1429 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/element_widget.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/element_widget.dart @@ -26,11 +26,7 @@ mixin ChartElementParentDataMixin { } class ChartFadeTransition extends FadeTransition { - const ChartFadeTransition({ - super.key, - required super.opacity, - super.child, - }); + const ChartFadeTransition({super.key, required super.opacity, super.child}); @override RenderChartFadeTransition createRenderObject(BuildContext context) { @@ -176,10 +172,7 @@ class ChartElementParentData extends ContainerBoxParentData { } class ChartElementStack extends MultiChildRenderObjectWidget { - const ChartElementStack({ - super.key, - super.children, - }); + const ChartElementStack({super.key, super.children}); @override RenderChartElementStack createRenderObject(BuildContext context) { @@ -188,7 +181,9 @@ class ChartElementStack extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderChartElementStack renderObject) { + BuildContext context, + RenderChartElementStack renderObject, + ) { super.updateRenderObject(context, renderObject); } } @@ -217,14 +212,13 @@ class RenderChartElementStack extends RenderBox } abstract class CustomConstrainedLayoutBuilder< - ConstraintType extends Constraints> extends RenderObjectWidget { - const CustomConstrainedLayoutBuilder({ - super.key, - required this.builder, - }); + ConstraintType extends Constraints +> + extends RenderObjectWidget { + const CustomConstrainedLayoutBuilder({super.key, required this.builder}); final Widget Function(BuildContext context, ConstraintType constraints) - builder; + builder; @override RenderObjectElement createElement() => @@ -232,18 +226,20 @@ abstract class CustomConstrainedLayoutBuilder< @protected bool updateShouldRebuild( - covariant CustomConstrainedLayoutBuilder oldWidget) => - true; + covariant CustomConstrainedLayoutBuilder oldWidget, + ) => true; } class CustomLayoutBuilderElement extends RenderObjectElement { CustomLayoutBuilderElement( - CustomConstrainedLayoutBuilder super.widget); + CustomConstrainedLayoutBuilder super.widget, + ); @override CustomRenderConstrainedLayoutBuilder - get renderObject => super.renderObject + get renderObject => + super.renderObject as CustomRenderConstrainedLayoutBuilder; Element? _child; @@ -308,9 +304,10 @@ class CustomLayoutBuilderElement ErrorDescription('building $widget'), e, stack, - informationCollector: () => [ - if (kDebugMode) DiagnosticsDebugCreator(DebugCreator(this)), - ], + informationCollector: + () => [ + if (kDebugMode) DiagnosticsDebugCreator(DebugCreator(this)), + ], ), ); } @@ -323,9 +320,10 @@ class CustomLayoutBuilderElement ErrorDescription('building $widget'), e, stack, - informationCollector: () => [ - if (kDebugMode) DiagnosticsDebugCreator(DebugCreator(this)), - ], + informationCollector: + () => [ + if (kDebugMode) DiagnosticsDebugCreator(DebugCreator(this)), + ], ), ); _child = updateChild(null, built, slot); @@ -347,22 +345,28 @@ class CustomLayoutBuilderElement @override void moveRenderObjectChild( - RenderObject child, Object? oldSlot, Object? newSlot) { + RenderObject child, + Object? oldSlot, + Object? newSlot, + ) { assert(false); } @override void removeRenderObjectChild(RenderObject child, Object? slot) { final CustomRenderConstrainedLayoutBuilder - renderObject = this.renderObject; + renderObject = this.renderObject; assert(renderObject.child == child); renderObject.child = null; assert(renderObject == this.renderObject); } } -mixin CustomRenderConstrainedLayoutBuilder on RenderObjectWithChildMixin { +mixin CustomRenderConstrainedLayoutBuilder< + ConstraintType extends Constraints, + ChildType extends RenderObject +> + on RenderObjectWithChildMixin { LayoutCallback? _callback; void updateCallback(LayoutCallback? value) { @@ -394,10 +398,7 @@ mixin CustomRenderConstrainedLayoutBuilder { - const CustomLayoutBuilder({ - super.key, - required super.builder, - }); + const CustomLayoutBuilder({super.key, required super.builder}); @override RenderObject createRenderObject(BuildContext context) => @@ -434,11 +435,13 @@ class CustomRenderLayoutBuilder extends RenderBox @override Size computeDryLayout(BoxConstraints constraints) { - assert(debugCannotComputeDryLayout( - reason: - 'Calculating the dry layout would require running the layout callback ' - 'speculatively, which might mutate the live render object tree.', - )); + assert( + debugCannotComputeDryLayout( + reason: + 'Calculating the dry layout would require running the layout callback ' + 'speculatively, which might mutate the live render object tree.', + ), + ); return Size.zero; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/funnel_data_label.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/funnel_data_label.dart index 089653b45..379133bec 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/funnel_data_label.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/funnel_data_label.dart @@ -96,13 +96,15 @@ class FunnelDataLabelContainer extends StatefulWidget { _FunnelDataLabelContainerState(); } -typedef _ChartDataLabelWidgetBuilder = Widget Function( - T data, - ChartPoint point, - FunnelSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position); +typedef _ChartDataLabelWidgetBuilder = + Widget Function( + T data, + ChartPoint point, + FunnelSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ); class _FunnelDataLabelContainerState extends State> @@ -111,22 +113,24 @@ class _FunnelDataLabelContainerState LinkedList? _textChildren; Widget _dataLabelFromBuilder( - T data, - ChartPoint point, - FunnelSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position) { + T data, + ChartPoint point, + FunnelSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ) { return widget.builder!(data, point, series, pointIndex, seriesIndex); } Widget _dataLabelFromMapper( - T data, - ChartPoint point, - FunnelSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position) { + T data, + ChartPoint point, + FunnelSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ) { final String text = widget.mapper!(data, pointIndex) ?? ''; return _buildDataLabelText(text, pointIndex); } @@ -151,7 +155,9 @@ class _FunnelDataLabelContainerState } else if (settings.useSeriesColor) { final int segmentsLastIndex = renderer!.segments.length - 1; return renderer! - .segments[segmentsLastIndex - dataPointIndex].fillPaint.color + .segments[segmentsLastIndex - dataPointIndex] + .fillPaint + .color .withValues(alpha: settings.opacity); } return Colors.transparent; @@ -178,8 +184,10 @@ class _FunnelDataLabelContainerState _textChildren!.add(child); } - void _buildDataLabels(_ChartDataLabelWidgetBuilder callback, - Function(FunnelChartDataLabelPositioned) add) { + void _buildDataLabels( + _ChartDataLabelWidgetBuilder callback, + Function(FunnelChartDataLabelPositioned) add, + ) { const List positions = ChartDataPointType.values; final int yLength = yLists?.length ?? 0; final int posAdj = _positionIndex(yLength); @@ -221,19 +229,19 @@ class _FunnelDataLabelContainerState final ChartDataPointType position = positions[k + posAdj]; final FunnelChartDataLabelPositioned child = FunnelChartDataLabelPositioned( - x: x, - y: yValues[index], - dataPointIndex: index, - position: position, - child: callback( - widget.dataSource[index], - point, - widget.series, - index, - renderer!.index, - position, - ), - ); + x: x, + y: yValues[index], + dataPointIndex: index, + position: position, + child: callback( + widget.dataSource[index], + point, + widget.series, + index, + renderer!.index, + position, + ), + ); add(child); } } @@ -253,9 +261,10 @@ class _FunnelDataLabelContainerState if (widget.builder != null) { callback = _dataLabelFromBuilder; } else { - callback = widget.mapper != null - ? _dataLabelFromMapper - : _defaultDataLabel; + callback = + widget.mapper != null + ? _dataLabelFromMapper + : _defaultDataLabel; } void Function(FunnelChartDataLabelPositioned child) add; if (widget.builder != null) { @@ -308,7 +317,9 @@ class FunnelDataLabelStack extends ChartElementStack { @override void updateRenderObject( - BuildContext context, RenderFunnelDataLabelStack renderObject) { + BuildContext context, + RenderFunnelDataLabelStack renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..series = series @@ -376,16 +387,19 @@ class RenderFunnelDataLabelStack extends RenderChartElementStack { return; } - final String text = childCount > 0 - ? '' - : (labels!.elementAt(selectedIndex).child as DataLabelText).text; - series!.parent!.onDataLabelTapped!(DataLabelTapDetails( - series!.index, - series!.viewportIndex(selectedIndex), - text, - settings, - selectedIndex, - )); + final String text = + childCount > 0 + ? '' + : (labels!.elementAt(selectedIndex).child as DataLabelText).text; + series!.parent!.onDataLabelTapped!( + DataLabelTapDetails( + series!.index, + series!.viewportIndex(selectedIndex), + text, + settings, + selectedIndex, + ), + ); } } @@ -414,35 +428,48 @@ class RenderFunnelDataLabelStack extends RenderChartElementStack { child.parentData! as ChartElementParentData; final RenderBox? nextSibling = currentChildData.nextSibling; child.layout(constraints, parentUsesSize: true); - currentChildData.offset = - series!.dataLabelPosition(currentChildData, child.size); - final Offset offset = - _invokeDataLabelRender(currentChildData.dataPointIndex); - currentChildData.offset = Offset(currentChildData.offset.dx + offset.dx, - currentChildData.offset.dy - offset.dy); + currentChildData.offset = series!.dataLabelPosition( + currentChildData, + child.size, + ); + final Offset offset = _invokeDataLabelRender( + currentChildData.dataPointIndex, + ); + currentChildData.offset = Offset( + currentChildData.offset.dx + offset.dx, + currentChildData.offset.dy - offset.dy, + ); // TODO(Praveen): Builder works only for inner and outer position, // Need to handle for intersection. child = nextSibling; } } else if (labels != null) { for (final FunnelChartDataLabelPositioned currentLabel in labels!) { - final ChartElementParentData currentLabelData = ChartElementParentData() - ..x = currentLabel.x - ..y = currentLabel.y - ..dataPointIndex = currentLabel.dataPointIndex - ..position = currentLabel.position; + final ChartElementParentData currentLabelData = + ChartElementParentData() + ..x = currentLabel.x + ..y = currentLabel.y + ..dataPointIndex = currentLabel.dataPointIndex + ..position = currentLabel.position; final DataLabelText details = currentLabel.child as DataLabelText; - final Offset offset = - _invokeDataLabelRender(currentLabel.dataPointIndex, details); - currentLabel.offset = Offset(currentLabel.offset.dx + offset.dx, - currentLabel.offset.dy - offset.dy); + final Offset offset = _invokeDataLabelRender( + currentLabel.dataPointIndex, + details, + ); + currentLabel.offset = Offset( + currentLabel.offset.dx + offset.dx, + currentLabel.offset.dy - offset.dy, + ); currentLabel.size = measureText(details.text, details.textStyle); - currentLabel.offset += - series!.dataLabelPosition(currentLabelData, currentLabel.size); + currentLabel.offset += series!.dataLabelPosition( + currentLabelData, + currentLabel.size, + ); currentLabel.connectorPath = _calculateConnectorPath( - currentLabel.dataPointIndex, - currentLabel.offset, - currentLabel.size); + currentLabel.dataPointIndex, + currentLabel.offset, + currentLabel.size, + ); } } } @@ -498,10 +525,11 @@ class RenderFunnelDataLabelStack extends RenderChartElementStack { } else if (labels != null) { final List previousRect = []; final Paint fillPaint = Paint(); - final Paint strokePaint = Paint() - ..color = settings.borderColor - ..strokeWidth = settings.borderWidth - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = settings.borderColor + ..strokeWidth = settings.borderWidth + ..style = PaintingStyle.stroke; for (final FunnelChartDataLabelPositioned label in labels!) { final DataLabelText details = label.child as DataLabelText; fillPaint.color = details.color; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/interactive_tooltip.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/interactive_tooltip.dart index ca3fb8066..c5cdfd990 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/interactive_tooltip.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/interactive_tooltip.dart @@ -452,7 +452,7 @@ class InteractiveTooltip { connectorLineDashArray, decimalPlaces, canShowMarker, - textStyle + textStyle, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/layout_handler.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/layout_handler.dart index 389210803..b02a8bfab 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/layout_handler.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/layout_handler.dart @@ -2,10 +2,7 @@ import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; class ChartLayoutHandler extends SingleChildRenderObjectWidget { - const ChartLayoutHandler({ - super.key, - required super.child, - }); + const ChartLayoutHandler({super.key, required super.child}); @override RenderObject createRenderObject(BuildContext context) { diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/legend.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/legend.dart index a2341928b..73c8f4fc0 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/legend.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/legend.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; -import '../series/chart_series.dart'; import '../utils/enum.dart'; import '../utils/typedef.dart'; import 'core_legend.dart' as core; @@ -590,7 +589,7 @@ class Legend { iconBorderColor, iconBorderWidth, itemPadding, - image + image, ]; return Object.hashAll(values); } @@ -701,28 +700,82 @@ class LegendTitle { } } -class ChartLegendItem extends core.LegendItem { - ChartLegendItem({ +/// Represents a cartesian legend item in legends. +class CartesianLegendItem extends core.LegendItem { + CartesianLegendItem({ required super.text, required super.iconType, required super.iconColor, required super.iconBorderWidth, + required super.seriesIndex, super.iconBorderColor, super.shader, super.imageProvider, super.overlayMarkerType, + super.isToggled = false, + super.onTap, + super.onRender, + super.series, + super.pointIndex = -1, + }); +} + +/// Represents a circular legend item in legends. +class CircularLegendItem extends core.LegendItem { + CircularLegendItem({ + required super.text, + required super.iconType, + required super.iconColor, + required super.iconBorderWidth, + required super.seriesIndex, + super.iconBorderColor, + super.shader, + super.imageProvider, super.degree, super.endAngle, super.startAngle, super.isToggled = false, super.onTap, super.onRender, - this.series, - required this.seriesIndex, - this.pointIndex = -1, + super.series, + super.pointIndex = -1, + }); +} + +/// Represents a funnel legend item in legends. +class FunnelLegendItem extends core.LegendItem { + FunnelLegendItem({ + required super.text, + required super.iconType, + required super.iconColor, + required super.iconBorderWidth, + required super.seriesIndex, + super.iconBorderColor, + super.shader, + super.imageProvider, + super.isToggled = false, + super.onTap, + super.onRender, + super.series, + super.pointIndex = -1, }); +} - final ChartSeriesRenderer? series; - final int seriesIndex; - final int pointIndex; +/// Represents a pyramid legend item in legends. +class PyramidLegendItem extends core.LegendItem { + PyramidLegendItem({ + required super.text, + required super.iconType, + required super.iconColor, + required super.iconBorderWidth, + required super.seriesIndex, + super.iconBorderColor, + super.shader, + super.imageProvider, + super.isToggled = false, + super.onTap, + super.onRender, + super.series, + super.pointIndex = -1, + }); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/marker.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/marker.dart index c03e9cd5c..b7c285205 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/marker.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/marker.dart @@ -256,7 +256,7 @@ class MarkerSettings { shape, borderWidth, borderColor, - image + image, ]; return Object.hashAll(values); } @@ -376,8 +376,13 @@ class _MarkerContainerState extends State> } } - void _updateDetails(int index, ChartMarker base, double sbsValue, int yLength, - Color themeFillColor) { + void _updateDetails( + int index, + ChartMarker base, + double sbsValue, + int yLength, + Color themeFillColor, + ) { final num x = xValues![index] + sbsValue; for (int j = 0; j < yLength; j++) { final List yValues = yLists![j]; @@ -393,14 +398,18 @@ class _MarkerContainerState extends State> ..index = index; if (renderer!.parent != null && renderer!.parent!.onMarkerRender != null) { - final MarkerRenderArgs args = MarkerRenderArgs( - renderer!.viewportIndex(index), renderer!.index, index) - ..shape = marker.type - ..color = marker.color - ..borderColor = marker.borderColor - ..borderWidth = marker.borderWidth - ..markerHeight = marker.height - ..markerWidth = marker.width; + final MarkerRenderArgs args = + MarkerRenderArgs( + renderer!.viewportIndex(index), + renderer!.index, + index, + ) + ..shape = marker.type + ..color = marker.color + ..borderColor = marker.borderColor + ..borderWidth = marker.borderWidth + ..markerHeight = marker.height + ..markerWidth = marker.width; renderer!.parent!.onMarkerRender!(args); marker.merge( type: args.shape, @@ -487,7 +496,9 @@ class _MarkerStack extends ChartElementStack { @override void updateRenderObject( - BuildContext context, _RenderMarkerStack renderObject) { + BuildContext context, + _RenderMarkerStack renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..series = series @@ -565,12 +576,14 @@ class _RenderMarkerStack extends RenderChartElementStack { return; } - final Paint fillPaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint fillPaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; for (final ChartMarker marker in markers) { if (marker.position.isNaN) { continue; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/common/pyramid_data_label.dart b/packages/syncfusion_flutter_charts/lib/src/charts/common/pyramid_data_label.dart index 2eab5f308..b7ed7ee6a 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/common/pyramid_data_label.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/common/pyramid_data_label.dart @@ -96,13 +96,15 @@ class PyramidDataLabelContainer extends StatefulWidget { _PyramidDataLabelContainerState(); } -typedef _ChartDataLabelWidgetBuilder = Widget Function( - T data, - ChartPoint point, - PyramidSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position); +typedef _ChartDataLabelWidgetBuilder = + Widget Function( + T data, + ChartPoint point, + PyramidSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ); class _PyramidDataLabelContainerState extends State> @@ -111,22 +113,24 @@ class _PyramidDataLabelContainerState LinkedList? _textChildren; Widget _dataLabelFromBuilder( - T data, - ChartPoint point, - PyramidSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position) { + T data, + ChartPoint point, + PyramidSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ) { return widget.builder!(data, point, series, pointIndex, seriesIndex); } Widget _dataLabelFromMapper( - T data, - ChartPoint point, - PyramidSeries series, - int pointIndex, - int seriesIndex, - ChartDataPointType position) { + T data, + ChartPoint point, + PyramidSeries series, + int pointIndex, + int seriesIndex, + ChartDataPointType position, + ) { final String text = widget.mapper!(data, pointIndex) ?? ''; return _buildDataLabelText(text, pointIndex); } @@ -149,8 +153,9 @@ class _PyramidDataLabelContainerState if (settings.color != null) { return settings.color!.withValues(alpha: settings.opacity); } else if (settings.useSeriesColor) { - return renderer!.segments[dataPointIndex].fillPaint.color - .withValues(alpha: settings.opacity); + return renderer!.segments[dataPointIndex].fillPaint.color.withValues( + alpha: settings.opacity, + ); } return Colors.transparent; } @@ -176,8 +181,10 @@ class _PyramidDataLabelContainerState _textChildren!.add(child); } - void _buildDataLabels(_ChartDataLabelWidgetBuilder callback, - Function(PyramidChartDataLabelPositioned) add) { + void _buildDataLabels( + _ChartDataLabelWidgetBuilder callback, + Function(PyramidChartDataLabelPositioned) add, + ) { const List positions = ChartDataPointType.values; final int yLength = yLists?.length ?? 0; final int posAdj = _positionIndex(yLength); @@ -219,19 +226,19 @@ class _PyramidDataLabelContainerState final ChartDataPointType position = positions[k + posAdj]; final PyramidChartDataLabelPositioned child = PyramidChartDataLabelPositioned( - x: x, - y: yValues[index], - dataPointIndex: index, - position: position, - child: callback( - widget.dataSource[index], - point, - widget.series, - index, - renderer!.index, - position, - ), - ); + x: x, + y: yValues[index], + dataPointIndex: index, + position: position, + child: callback( + widget.dataSource[index], + point, + widget.series, + index, + renderer!.index, + position, + ), + ); add(child); } } @@ -251,9 +258,10 @@ class _PyramidDataLabelContainerState if (widget.builder != null) { callback = _dataLabelFromBuilder; } else { - callback = widget.mapper != null - ? _dataLabelFromMapper - : _defaultDataLabel; + callback = + widget.mapper != null + ? _dataLabelFromMapper + : _defaultDataLabel; } void Function(PyramidChartDataLabelPositioned child) add; if (widget.builder != null) { @@ -306,7 +314,9 @@ class PyramidDataLabelStack extends ChartElementStack { @override void updateRenderObject( - BuildContext context, RenderPyramidDataLabelStack renderObject) { + BuildContext context, + RenderPyramidDataLabelStack renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..series = series @@ -374,16 +384,19 @@ class RenderPyramidDataLabelStack extends RenderChartElementStack { return; } - final String text = childCount > 0 - ? '' - : (labels!.elementAt(selectedIndex).child as DataLabelText).text; - series!.parent!.onDataLabelTapped!(DataLabelTapDetails( - series!.index, - series!.viewportIndex(selectedIndex), - text, - settings, - selectedIndex, - )); + final String text = + childCount > 0 + ? '' + : (labels!.elementAt(selectedIndex).child as DataLabelText).text; + series!.parent!.onDataLabelTapped!( + DataLabelTapDetails( + series!.index, + series!.viewportIndex(selectedIndex), + text, + settings, + selectedIndex, + ), + ); } } @@ -412,35 +425,48 @@ class RenderPyramidDataLabelStack extends RenderChartElementStack { child.parentData! as ChartElementParentData; final RenderBox? nextSibling = currentChildData.nextSibling; child.layout(constraints, parentUsesSize: true); - currentChildData.offset = - series!.dataLabelPosition(currentChildData, child.size); - final Offset offset = - _invokeDataLabelRender(currentChildData.dataPointIndex); - currentChildData.offset = Offset(currentChildData.offset.dx + offset.dx, - currentChildData.offset.dy - offset.dy); + currentChildData.offset = series!.dataLabelPosition( + currentChildData, + child.size, + ); + final Offset offset = _invokeDataLabelRender( + currentChildData.dataPointIndex, + ); + currentChildData.offset = Offset( + currentChildData.offset.dx + offset.dx, + currentChildData.offset.dy - offset.dy, + ); // TODO(Praveen): Builder works only for inner and outer position, // Need to handle for intersection. child = nextSibling; } } else if (labels != null) { for (final PyramidChartDataLabelPositioned currentLabel in labels!) { - final ChartElementParentData currentLabelData = ChartElementParentData() - ..x = currentLabel.x - ..y = currentLabel.y - ..dataPointIndex = currentLabel.dataPointIndex - ..position = currentLabel.position; + final ChartElementParentData currentLabelData = + ChartElementParentData() + ..x = currentLabel.x + ..y = currentLabel.y + ..dataPointIndex = currentLabel.dataPointIndex + ..position = currentLabel.position; final DataLabelText details = currentLabel.child as DataLabelText; - final Offset offset = - _invokeDataLabelRender(currentLabel.dataPointIndex, details); - currentLabel.offset = Offset(currentLabel.offset.dx + offset.dx, - currentLabel.offset.dy - offset.dy); + final Offset offset = _invokeDataLabelRender( + currentLabel.dataPointIndex, + details, + ); + currentLabel.offset = Offset( + currentLabel.offset.dx + offset.dx, + currentLabel.offset.dy - offset.dy, + ); currentLabel.size = measureText(details.text, details.textStyle); - currentLabel.offset += - series!.dataLabelPosition(currentLabelData, currentLabel.size); + currentLabel.offset += series!.dataLabelPosition( + currentLabelData, + currentLabel.size, + ); currentLabel.connectorPath = _drawConnectorPath( - currentLabel.dataPointIndex, - currentLabel.offset, - currentLabel.size); + currentLabel.dataPointIndex, + currentLabel.offset, + currentLabel.size, + ); } } } @@ -494,10 +520,11 @@ class RenderPyramidDataLabelStack extends RenderChartElementStack { } else if (labels != null) { final List previousRect = []; final Paint fillPaint = Paint(); - final Paint strokePaint = Paint() - ..color = settings.borderColor - ..strokeWidth = settings.borderWidth - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = settings.borderColor + ..strokeWidth = settings.borderWidth + ..style = PaintingStyle.stroke; for (final PyramidChartDataLabelPositioned label in labels!) { final DataLabelText details = label.child as DataLabelText; fillPaint.color = details.color; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/funnel_chart.dart b/packages/syncfusion_flutter_charts/lib/src/charts/funnel_chart.dart index ab847f6d1..ca47ace23 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/funnel_chart.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/funnel_chart.dart @@ -408,45 +408,60 @@ class SfFunnelChartState extends State SfLocalizations? _localizations; SfChartThemeData _updateThemeData( - BuildContext context, ChartThemeData effectiveChartThemeData) { + BuildContext context, + ChartThemeData effectiveChartThemeData, + ) { SfChartThemeData chartThemeData = SfChartTheme.of(context); chartThemeData = chartThemeData.copyWith( - backgroundColor: widget.backgroundColor ?? + backgroundColor: + widget.backgroundColor ?? chartThemeData.backgroundColor ?? effectiveChartThemeData.backgroundColor, - titleBackgroundColor: widget.title.backgroundColor ?? + titleBackgroundColor: + widget.title.backgroundColor ?? chartThemeData.titleBackgroundColor ?? effectiveChartThemeData.titleBackgroundColor, - legendBackgroundColor: widget.legend.backgroundColor ?? + legendBackgroundColor: + widget.legend.backgroundColor ?? chartThemeData.legendBackgroundColor ?? effectiveChartThemeData.legendBackgroundColor, - tooltipColor: widget.tooltipBehavior?.color ?? + tooltipColor: + widget.tooltipBehavior?.color ?? chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - plotAreaBackgroundColor: chartThemeData.plotAreaBackgroundColor ?? + plotAreaBackgroundColor: + chartThemeData.plotAreaBackgroundColor ?? effectiveChartThemeData.plotAreaBackgroundColor, titleTextStyle: effectiveChartThemeData.titleTextStyle! .copyWith( - color: chartThemeData.titleTextColor ?? - effectiveChartThemeData.titleTextColor) + color: + chartThemeData.titleTextColor ?? + effectiveChartThemeData.titleTextColor, + ) .merge(chartThemeData.titleTextStyle) .merge(widget.title.textStyle), legendTitleTextStyle: effectiveChartThemeData.legendTitleTextStyle! .copyWith( - color: chartThemeData.legendTitleColor ?? - effectiveChartThemeData.legendTitleColor) + color: + chartThemeData.legendTitleColor ?? + effectiveChartThemeData.legendTitleColor, + ) .merge(chartThemeData.legendTitleTextStyle) .merge(widget.legend.title?.textStyle), legendTextStyle: effectiveChartThemeData.legendTextStyle! .copyWith( - color: chartThemeData.legendTextColor ?? - effectiveChartThemeData.legendTextColor) + color: + chartThemeData.legendTextColor ?? + effectiveChartThemeData.legendTextColor, + ) .merge(chartThemeData.legendTextStyle) .merge(widget.legend.textStyle), tooltipTextStyle: effectiveChartThemeData.tooltipTextStyle! .copyWith( - color: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor) + color: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) .merge(chartThemeData.tooltipTextStyle) .merge(widget.tooltipBehavior?.textStyle), ); @@ -458,9 +473,18 @@ class SfFunnelChartState extends State } Widget? _buildTooltipWidget( - BuildContext context, TooltipInfo? info, Size maxSize) { - return buildTooltipWidget(context, info, maxSize, widget.tooltipBehavior, - _chartThemeData, _themeData); + BuildContext context, + TooltipInfo? info, + Size maxSize, + ) { + return buildTooltipWidget( + context, + info, + maxSize, + widget.tooltipBehavior, + _chartThemeData, + _themeData, + ); } /// Called when this object is inserted into the tree. @@ -517,28 +541,36 @@ class SfFunnelChartState extends State _themeData = Theme.of(context); final ChartThemeData effectiveChartThemeData = ChartThemeData(context); _chartThemeData = _updateThemeData(context, effectiveChartThemeData); - final core.LegendPosition legendPosition = - effectiveLegendPosition(widget.legend); - final Axis orientation = - effectiveLegendOrientation(legendPosition, widget.legend); + final core.LegendPosition legendPosition = effectiveLegendPosition( + widget.legend, + ); + final Axis orientation = effectiveLegendOrientation( + legendPosition, + widget.legend, + ); Widget current = core.LegendLayout( key: _legendKey, padding: EdgeInsets.zero, showLegend: widget.legend.isVisible, legendPosition: legendPosition, legendAlignment: effectiveLegendAlignment(widget.legend.alignment), - legendTitleAlignment: - effectiveLegendAlignment(widget.legend.title?.alignment), + legendTitleAlignment: effectiveLegendAlignment( + widget.legend.title?.alignment, + ), itemIconBorderColor: widget.legend.iconBorderColor, itemIconBorderWidth: widget.legend.iconBorderWidth, legendBorderColor: widget.legend.borderColor, legendBackgroundColor: _chartThemeData.legendBackgroundColor, legendBorderWidth: widget.legend.borderWidth, itemOpacity: widget.legend.opacity, - legendWidthFactor: - percentageToWidthFactor(widget.legend.width, legendPosition), - legendHeightFactor: - percentageToHeightFactor(widget.legend.height, legendPosition), + legendWidthFactor: percentageToWidthFactor( + widget.legend.width, + legendPosition, + ), + legendHeightFactor: percentageToHeightFactor( + widget.legend.height, + legendPosition, + ), itemInnerSpacing: widget.legend.padding, itemSpacing: 0.0, itemPadding: widget.legend.itemPadding, @@ -600,8 +632,9 @@ class SfFunnelChartState extends State opacity: widget.tooltipBehavior!.opacity, borderColor: widget.tooltipBehavior!.borderColor, borderWidth: widget.tooltipBehavior!.borderWidth, - color: (widget.tooltipBehavior!.color ?? - _chartThemeData.tooltipColor)!, + color: + (widget.tooltipBehavior!.color ?? + _chartThemeData.tooltipColor)!, showDuration: widget.tooltipBehavior!.duration.toInt(), shadowColor: widget.tooltipBehavior!.shadowColor, elevation: widget.tooltipBehavior!.elevation, @@ -620,12 +653,13 @@ class SfFunnelChartState extends State return RepaintBoundary( child: Container( decoration: BoxDecoration( - image: widget.backgroundImage != null - ? DecorationImage( - image: widget.backgroundImage!, - fit: BoxFit.fill, - ) - : null, + image: + widget.backgroundImage != null + ? DecorationImage( + image: widget.backgroundImage!, + fit: BoxFit.fill, + ) + : null, color: _chartThemeData.backgroundColor, border: Border.all( color: widget.borderColor, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/accumulation_distribution_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/accumulation_distribution_indicator.dart index 261d772aa..6919cc45c 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/accumulation_distribution_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/accumulation_distribution_indicator.dart @@ -46,22 +46,27 @@ class AccumulationDistributionIndicator extends TechnicalIndicator { super.signalLineWidth, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - volumeValueMapper: volumeValueMapper != null && dataSource != null - ? (int index) => volumeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + volumeValueMapper: + volumeValueMapper != null && dataSource != null + ? (int index) => volumeValueMapper(dataSource[index], index) + : null, + ); @override bool operator ==(Object other) { @@ -115,7 +120,7 @@ class AccumulationDistributionIndicator extends TechnicalIndicator { legendIconType, legendItemText, signalLineColor, - signalLineWidth + signalLineWidth, ]; return Object.hashAll(values); } @@ -158,7 +163,9 @@ class ADIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, ADIndicatorRenderer renderObject) { + BuildContext context, + ADIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final AccumulationDistributionIndicator adi = indicator as AccumulationDistributionIndicator; @@ -387,8 +394,9 @@ class ADIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -405,8 +413,12 @@ class ADIndicatorRenderer extends IndicatorRenderer { void onPaint(PaintingContext context, Offset offset) { if (signalLinePoints.isNotEmpty) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); final int length = signalLinePoints.length - 1; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/atr_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/atr_indicator.dart index c0771b52b..6e3597d97 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/atr_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/atr_indicator.dart @@ -46,19 +46,23 @@ class AtrIndicator extends TechnicalIndicator { this.period = 14, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Period determines the start point for the rendering of /// technical indicators. @@ -130,7 +134,7 @@ class AtrIndicator extends TechnicalIndicator { legendItemText, signalLineColor, signalLineWidth, - period + period, ]; return Object.hashAll(values); } @@ -172,7 +176,9 @@ class AtrIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, AtrIndicatorRenderer renderObject) { + BuildContext context, + AtrIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final AtrIndicator atr = indicator as AtrIndicator; @@ -218,7 +224,7 @@ class AtrIndicatorRenderer extends IndicatorRenderer { ?>[ lowValueMapper, highValueMapper, - closeValueMapper + closeValueMapper, ], >[_lowValues, _highValues, _closeValues], ); @@ -278,7 +284,8 @@ class AtrIndicatorRenderer extends IndicatorRenderer { final num trueRange = max(range, lowClose); sum += trueRange; if (i >= period && period > 0) { - average = (averageOffsetValues[averageOffsetValues.length - 1].dy * + average = + (averageOffsetValues[averageOffsetValues.length - 1].dy * (period - 1) + trueRange) / period; @@ -360,7 +367,7 @@ class AtrIndicatorRenderer extends IndicatorRenderer { text: trackballText(chartPoint, text), color: signalLineColor, segmentIndex: nearestPointIndex, - ) + ), ]; } return null; @@ -423,8 +430,9 @@ class AtrIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -441,8 +449,12 @@ class AtrIndicatorRenderer extends IndicatorRenderer { void onPaint(PaintingContext context, Offset offset) { if (signalLinePoints.isNotEmpty) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); final int length = signalLinePoints.length - 1; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/bollinger_bands_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/bollinger_bands_indicator.dart index 75ff39c2a..1396cd86c 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/bollinger_bands_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/bollinger_bands_indicator.dart @@ -50,13 +50,15 @@ class BollingerBandIndicator extends TechnicalIndicator { this.bandColor = const Color(0x409e9e9e), super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Standard deviation value of the bollinger band. /// @@ -249,7 +251,7 @@ class BollingerBandIndicator extends TechnicalIndicator { upperLineWidth, lowerLineColor, lowerLineWidth, - bandColor + bandColor, ]; return Object.hashAll(values); } @@ -296,7 +298,9 @@ class BollingerIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, BollingerIndicatorRenderer renderObject) { + BuildContext context, + BollingerIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final BollingerBandIndicator bollinger = indicator as BollingerBandIndicator; @@ -485,21 +489,25 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { if (j + 1 == length) { for (int k = 0; k < length - 1; k++) { midBands[k] = smaPoints[j]; - lowBands[k] = lowerBand.isNaN || lowerBand.isInfinite + lowBands[k] = + lowerBand.isNaN || lowerBand.isInfinite + ? smaPoints[j] + : lowerBand; + upperBands[k] = + upperBand.isNaN || upperBand.isInfinite + ? smaPoints[j] + : upperBand; + } + } + midBands[j] = smaPoints[j]; + lowBands[j] = + lowerBand.isNaN || lowerBand.isInfinite ? smaPoints[j] : lowerBand; - upperBands[k] = upperBand.isNaN || upperBand.isInfinite + upperBands[j] = + upperBand.isNaN || upperBand.isInfinite ? smaPoints[j] : upperBand; - } - } - midBands[j] = smaPoints[j]; - lowBands[j] = lowerBand.isNaN || lowerBand.isInfinite - ? smaPoints[j] - : lowerBand; - upperBands[j] = upperBand.isNaN || upperBand.isInfinite - ? smaPoints[j] - : upperBand; } else { if (j < period - 1) { smaPoints[j] = sma; @@ -530,10 +538,12 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { _lowerLineActualValues.add(Offset(x, lower)); _signalLineActualValues.add(Offset(x, middle)); if (enableBand) { - _upperBandActualValues - .add(Offset(x, _upperLineActualValues[++l].dy)); - _lowerBandActualValues - .add(Offset(x, _lowerLineActualValues[++m].dy)); + _upperBandActualValues.add( + Offset(x, _upperLineActualValues[++l].dy), + ); + _lowerBandActualValues.add( + Offset(x, _lowerLineActualValues[++m].dy), + ); } } } @@ -572,8 +582,10 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < dataCount; i++) { final num xValue = xValues[i]; - final CartesianChartPoint point = - CartesianChartPoint(x: xRawValues[i], xValue: xValue); + final CartesianChartPoint point = CartesianChartPoint( + x: xRawValues[i], + xValue: xValue, + ); for (int j = 0; j < yLength; j++) { point[positions[j]] = yLists[j][i]; } @@ -624,10 +636,12 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { final int length = _upperLineActualValues.length; for (int i = 0; i < length; i++) { final Offset upper = _upperLineActualValues[i]; - _upperLinePoints.add(Offset( - pointToPixelX(upper.dx, upper.dy), - pointToPixelY(upper.dx, upper.dy), - )); + _upperLinePoints.add( + Offset( + pointToPixelX(upper.dx, upper.dy), + pointToPixelY(upper.dx, upper.dy), + ), + ); } } @@ -635,10 +649,12 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { final int length = _lowerLineActualValues.length; for (int i = 0; i < length; i++) { final Offset lower = _lowerLineActualValues[i]; - _lowerLinePoints.add(Offset( - pointToPixelX(lower.dx, lower.dy), - pointToPixelY(lower.dx, lower.dy), - )); + _lowerLinePoints.add( + Offset( + pointToPixelX(lower.dx, lower.dy), + pointToPixelY(lower.dx, lower.dy), + ), + ); } } @@ -646,10 +662,12 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { final int length = _signalLineActualValues.length; for (int i = 0; i < length; i++) { final Offset signal = _signalLineActualValues[i]; - signalLinePoints.add(Offset( - pointToPixelX(signal.dx, signal.dy), - pointToPixelY(signal.dx, signal.dy), - )); + signalLinePoints.add( + Offset( + pointToPixelX(signal.dx, signal.dy), + pointToPixelY(signal.dx, signal.dy), + ), + ); } } @@ -688,11 +706,15 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { final List> trackballInfo = >[]; if (signalLineWidth > 0) { - final int nearestPointIndex = - _findNearestPoint(signalLinePoints, position); + final int nearestPointIndex = _findNearestPoint( + signalLinePoints, + position, + ); if (nearestPointIndex != -1) { - final CartesianChartPoint bollingerPoint = - _chartPoint(nearestPointIndex, 'bollinger'); + final CartesianChartPoint bollingerPoint = _chartPoint( + nearestPointIndex, + 'bollinger', + ); final String bollingerText = defaultLegendItemText(); trackballInfo.add( ChartTrackballInfo( @@ -713,8 +735,10 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { if (upperLineWidth > 0) { final int upperPointIndex = _findNearestPoint(_upperLinePoints, position); if (upperPointIndex != -1) { - final CartesianChartPoint upperPoint = - _chartPoint(upperPointIndex, 'upper'); + final CartesianChartPoint upperPoint = _chartPoint( + upperPointIndex, + 'upper', + ); trackballInfo.add( ChartTrackballInfo( position: _upperLinePoints[upperPointIndex], @@ -734,8 +758,10 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { if (lowerLineWidth > 0) { final int lowerPointIndex = _findNearestPoint(_lowerLinePoints, position); if (lowerPointIndex != -1) { - final CartesianChartPoint lowerPoint = - _chartPoint(lowerPointIndex, 'lower'); + final CartesianChartPoint lowerPoint = _chartPoint( + lowerPointIndex, + 'lower', + ); trackballInfo.add( ChartTrackballInfo( position: _lowerLinePoints[lowerPointIndex], @@ -798,9 +824,10 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { return CartesianChartPoint( x: xRawValues[pointIndex + period - 1], xValue: xValues[pointIndex + period - 1], - y: type == 'bollinger' - ? _signalLineActualValues[pointIndex].dy - : type == 'upper' + y: + type == 'bollinger' + ? _signalLineActualValues[pointIndex].dy + : type == 'upper' ? _upperLineActualValues[pointIndex].dy : _lowerLineActualValues[pointIndex].dy, ); @@ -811,16 +838,17 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { if (onRenderDetailsUpdate != null) { final BollingerBandIndicatorRenderParams params = BollingerBandIndicatorRenderParams( - _upperLineChartPoints, - _lowerLineChartPoints, - chartPoints, - legendItemText ?? name ?? defaultLegendItemText(), - signalLineWidth, - signalLineColor, - dashArray, + _upperLineChartPoints, + _lowerLineChartPoints, + chartPoints, + legendItemText ?? name ?? defaultLegendItemText(), + signalLineWidth, + signalLineColor, + dashArray, + ); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -836,8 +864,12 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); if (bandColor != Colors.transparent) { @@ -869,19 +901,22 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { length = _upperLinePoints.length; _upperLinePath.moveTo( - _upperLinePoints.first.dx, _upperLinePoints.first.dy); + _upperLinePoints.first.dx, + _upperLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { final Offset upper = _upperLinePoints[i]; _upperLinePath.lineTo(upper.dx, upper.dy); } drawDashes( - context.canvas, - _dashArray, - strokePaint - ..color = upperLineColor - ..strokeWidth = upperLineWidth, - path: _upperLinePath); + context.canvas, + _dashArray, + strokePaint + ..color = upperLineColor + ..strokeWidth = upperLineWidth, + path: _upperLinePath, + ); } // Draw lower line. @@ -892,19 +927,22 @@ class BollingerIndicatorRenderer extends IndicatorRenderer { length = _lowerLinePoints.length; _lowerLinePath.moveTo( - _lowerLinePoints.first.dx, _lowerLinePoints.first.dy); + _lowerLinePoints.first.dx, + _lowerLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { final Offset lower = _lowerLinePoints[i]; _lowerLinePath.lineTo(lower.dx, lower.dy); } drawDashes( - context.canvas, - _dashArray, - strokePaint - ..color = lowerLineColor - ..strokeWidth = lowerLineWidth, - path: _lowerLinePath); + context.canvas, + _dashArray, + strokePaint + ..color = lowerLineColor + ..strokeWidth = lowerLineWidth, + path: _lowerLinePath, + ); } context.canvas.restore(); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/ema_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/ema_indicator.dart index 3c04eddf7..50a7588a5 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/ema_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/ema_indicator.dart @@ -47,22 +47,27 @@ class EmaIndicator extends TechnicalIndicator { this.valueField = 'close', super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Value field property for EMA indicator. /// @@ -165,7 +170,7 @@ class EmaIndicator extends TechnicalIndicator { signalLineColor, signalLineWidth, valueField, - period + period, ]; return Object.hashAll(values); } @@ -209,7 +214,9 @@ class EmaIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, EmaIndicatorRenderer renderObject) { + BuildContext context, + EmaIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final EmaIndicator ema = indicator as EmaIndicator; @@ -266,17 +273,17 @@ class EmaIndicatorRenderer extends IndicatorRenderer { ]) { if (dataSource != null) { super.populateDataSource( - dataSource, xValueMapper, xValues, ?>[ - highValueMapper, - lowValueMapper, - openValueMapper, - closeValueMapper - ], >[ - _highValues, - _lowValues, - _openValues, - _closeValues - ]); + dataSource, + xValueMapper, + xValues, + ?>[ + highValueMapper, + lowValueMapper, + openValueMapper, + closeValueMapper, + ], + >[_highValues, _lowValues, _openValues, _closeValues], + ); } else { if (seriesName != null) { if (dependent is FinancialSeriesRendererBase) { @@ -328,7 +335,7 @@ class EmaIndicatorRenderer extends IndicatorRenderer { final num previousAverage = _signalLineActualValues[index - period].dy; final num yValue = (_fieldValue(index, valueField) - previousAverage) * value + - previousAverage; + previousAverage; _yValues.add(yValue); final double x = xValues[index].toDouble(); @@ -425,7 +432,7 @@ class EmaIndicatorRenderer extends IndicatorRenderer { header: tooltipHeaderText(chartPoint), text: trackballText(chartPoint, text), color: signalLineColor, - ) + ), ]; } return null; @@ -488,8 +495,9 @@ class EmaIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -506,8 +514,12 @@ class EmaIndicatorRenderer extends IndicatorRenderer { void onPaint(PaintingContext context, Offset offset) { if (signalLinePoints.isNotEmpty) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); final int length = signalLinePoints.length - 1; if (strokePaint.color != Colors.transparent && diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/macd_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/macd_indicator.dart index 563454330..cfebd9868 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/macd_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/macd_indicator.dart @@ -54,13 +54,15 @@ class MacdIndicator extends TechnicalIndicator { this.histogramNegativeColor = Colors.red, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Period determines the start point for the rendering of /// technical indicators. @@ -305,7 +307,7 @@ class MacdIndicator extends TechnicalIndicator { macdLineWidth, macdType, histogramPositiveColor, - histogramNegativeColor + histogramNegativeColor, ]; return Object.hashAll(values); } @@ -352,7 +354,9 @@ class MacdIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, MacdIndicatorRenderer renderObject) { + BuildContext context, + MacdIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final MacdIndicator macd = indicator as MacdIndicator; @@ -615,7 +619,8 @@ class MacdIndicatorRenderer extends IndicatorRenderer { int histogramIndex = 0; while (index < dataCount) { final double x = xValues[index].toDouble(); - final double y = macdPoints[histogramIndex + (period - 1)] - + final double y = + macdPoints[histogramIndex + (period - 1)] - signalEma[histogramIndex].toDouble(); _xMinimum = min(_xMinimum, x); @@ -656,8 +661,10 @@ class MacdIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < dataCount; i++) { final num xValue = xValues[i]; - final CartesianChartPoint point = - CartesianChartPoint(x: xRawValues[i], xValue: xValue); + final CartesianChartPoint point = CartesianChartPoint( + x: xRawValues[i], + xValue: xValue, + ); for (int j = 0; j < yLength; j++) { point[positions[j]] = yLists[j][i]; } @@ -695,8 +702,10 @@ class MacdIndicatorRenderer extends IndicatorRenderer { if (macdType == MacdType.both || macdType == MacdType.line) { final int macdPointIndex = _findNearestPoint(signalLinePoints, position); if (macdPointIndex != -1) { - final CartesianChartPoint macdPoint = - _chartPoint(macdPointIndex, 'macd'); + final CartesianChartPoint macdPoint = _chartPoint( + macdPointIndex, + 'macd', + ); final String text = defaultLegendItemText(); trackballInfo.add( ChartTrackballInfo( @@ -716,8 +725,10 @@ class MacdIndicatorRenderer extends IndicatorRenderer { final int macdLinePointIndex = _findNearestPoint(_macdPoints, position); if (macdLinePointIndex != -1) { - final CartesianChartPoint macdLinePoint = - _chartPoint(macdLinePointIndex, 'macdLine'); + final CartesianChartPoint macdLinePoint = _chartPoint( + macdLinePointIndex, + 'macdLine', + ); trackballInfo.add( ChartTrackballInfo( position: _macdPoints[macdLinePointIndex], @@ -737,16 +748,23 @@ class MacdIndicatorRenderer extends IndicatorRenderer { if (macdType == MacdType.both || macdType == MacdType.histogram) { final int histogramPointIndex = _findNearestPoint( - List.generate( - _bounds.length, (int index) => _bounds[index].center).toList(), - position); + List.generate( + _bounds.length, + (int index) => _bounds[index].center, + ).toList(), + position, + ); if (histogramPointIndex != -1) { - final CartesianChartPoint histogramPoint = - _chartPoint(histogramPointIndex, 'histogram'); + final CartesianChartPoint histogramPoint = _chartPoint( + histogramPointIndex, + 'histogram', + ); final Offset histogramPosition = Offset( - xAxis!.pointToPixel(_histogramActualValues[histogramPointIndex].dx), - yAxis!.pointToPixel( - _histogramActualValues[histogramPointIndex].dy.abs())); + xAxis!.pointToPixel(_histogramActualValues[histogramPointIndex].dx), + yAxis!.pointToPixel( + _histogramActualValues[histogramPointIndex].dy.abs(), + ), + ); trackballInfo.add( ChartTrackballInfo( position: histogramPosition, @@ -758,9 +776,10 @@ class MacdIndicatorRenderer extends IndicatorRenderer { name: trackballHistogramText, header: tooltipHeaderText(histogramPoint), text: trackballText(histogramPoint, trackballHistogramText), - color: histogramPoint.y!.isNegative - ? histogramNegativeColor - : histogramPositiveColor, + color: + histogramPoint.y!.isNegative + ? histogramNegativeColor + : histogramPositiveColor, ), ); } @@ -809,24 +828,27 @@ class MacdIndicatorRenderer extends IndicatorRenderer { CartesianChartPoint _chartPoint(int pointIndex, String type) { return CartesianChartPoint( - x: type == 'macd' - ? xRawValues[ - pointIndex + (signalLinePoints.length - xRawValues.length).abs()] - : type == 'macdLine' - ? xRawValues[ - pointIndex + (_macdPoints.length - xRawValues.length).abs()] + x: + type == 'macd' + ? xRawValues[pointIndex + + (signalLinePoints.length - xRawValues.length).abs()] + : type == 'macdLine' + ? xRawValues[pointIndex + + (_macdPoints.length - xRawValues.length).abs()] : xRawValues[pointIndex + (_histogramActualValues.length - xRawValues.length).abs()], - xValue: type == 'macd' - ? xValues[ - pointIndex + (signalLinePoints.length - xValues.length).abs()] - : type == 'macdLine' - ? xValues[ - pointIndex + (_macdPoints.length - xValues.length).abs()] + xValue: + type == 'macd' + ? xValues[pointIndex + + (signalLinePoints.length - xValues.length).abs()] + : type == 'macdLine' + ? xValues[pointIndex + + (_macdPoints.length - xValues.length).abs()] : _histogramActualValues[pointIndex].dx, - y: type == 'macd' - ? _signalLineActualValues[pointIndex].dy - : type == 'macdLine' + y: + type == 'macd' + ? _signalLineActualValues[pointIndex].dy + : type == 'macdLine' ? _macdLineActualValues[pointIndex].dy : _histogramActualValues[pointIndex].dy, ); @@ -844,8 +866,9 @@ class MacdIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -918,8 +941,12 @@ class MacdIndicatorRenderer extends IndicatorRenderer { @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); int length = signalLinePoints.length - 1; if (strokePaint.color != Colors.transparent && @@ -937,11 +964,12 @@ class MacdIndicatorRenderer extends IndicatorRenderer { if (macdType == MacdType.both || macdType == MacdType.line) { if (_macdPoints.isNotEmpty) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = macdLineColor - ..strokeWidth = macdLineWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = macdLineColor + ..strokeWidth = macdLineWidth + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { _macdPath.reset(); length = _macdPoints.length; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/momentum_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/momentum_indicator.dart index 85a0f3355..8e4404915 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/momentum_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/momentum_indicator.dart @@ -48,22 +48,27 @@ class MomentumIndicator extends TechnicalIndicator { this.centerLineWidth = 2, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Center line color of the momentum indicator. /// @@ -187,7 +192,7 @@ class MomentumIndicator extends TechnicalIndicator { signalLineWidth, period, centerLineColor, - centerLineWidth + centerLineWidth, ]; return Object.hashAll(values); } @@ -233,7 +238,9 @@ class MomentumIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, MomentumIndicatorRenderer renderObject) { + BuildContext context, + MomentumIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final MomentumIndicator momentum = indicator as MomentumIndicator; @@ -304,7 +311,7 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { highValueMapper, lowValueMapper, openValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _openValues, _closeValues], ); @@ -424,11 +431,15 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { List? trackballInfo(Offset position) { final List> trackballInfo = >[]; - final int momentumPointIndex = - _findNearestPoint(signalLinePoints, position); + final int momentumPointIndex = _findNearestPoint( + signalLinePoints, + position, + ); if (momentumPointIndex != -1) { - final CartesianChartPoint momentumPoint = - _chartPoint(momentumPointIndex, 'momentum'); + final CartesianChartPoint momentumPoint = _chartPoint( + momentumPointIndex, + 'momentum', + ); final String text = defaultLegendItemText(); trackballInfo.add( ChartTrackballInfo( @@ -447,20 +458,24 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { } final int centerPointIndex = _findNearestPoint(_centerLinePoints, position); if (centerPointIndex != -1) { - final CartesianChartPoint centerPoint = - _chartPoint(centerPointIndex, 'center'); - trackballInfo.add(ChartTrackballInfo( - position: _centerLinePoints[centerPointIndex], - point: centerPoint, - series: this, - pointIndex: centerPointIndex, - segmentIndex: centerPointIndex, - seriesIndex: index, - name: trackballCenterText, - header: tooltipHeaderText(centerPoint), - text: trackballText(centerPoint, trackballCenterText), - color: _centerLineColor, - )); + final CartesianChartPoint centerPoint = _chartPoint( + centerPointIndex, + 'center', + ); + trackballInfo.add( + ChartTrackballInfo( + position: _centerLinePoints[centerPointIndex], + point: centerPoint, + series: this, + pointIndex: centerPointIndex, + segmentIndex: centerPointIndex, + seriesIndex: index, + name: trackballCenterText, + header: tooltipHeaderText(centerPoint), + text: trackballText(centerPoint, trackballCenterText), + color: _centerLineColor, + ), + ); } return trackballInfo; @@ -507,15 +522,18 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { CartesianChartPoint _chartPoint(int pointIndex, String type) { return CartesianChartPoint( - x: type == 'momentum' - ? xRawValues[pointIndex + period - 1] - : xRawValues[pointIndex], - xValue: type == 'momentum' - ? xValues[pointIndex + period] - : xValues[pointIndex], - y: type == 'momentum' - ? _signalLineActualValues[pointIndex].dy - : _centerLineActualValues[pointIndex].dy, + x: + type == 'momentum' + ? xRawValues[pointIndex + period - 1] + : xRawValues[pointIndex], + xValue: + type == 'momentum' + ? xValues[pointIndex + period] + : xValues[pointIndex], + y: + type == 'momentum' + ? _signalLineActualValues[pointIndex].dy + : _centerLineActualValues[pointIndex].dy, ); } @@ -524,15 +542,16 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { if (onRenderDetailsUpdate != null) { final MomentumIndicatorRenderParams params = MomentumIndicatorRenderParams( - _centerLineActualValues.first.dy, - chartPoints, - legendItemText ?? name ?? defaultLegendItemText(), - signalLineWidth, - signalLineColor, - dashArray, + _centerLineActualValues.first.dy, + chartPoints, + legendItemText ?? name ?? defaultLegendItemText(), + signalLineWidth, + signalLineColor, + dashArray, + ); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -550,8 +569,12 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { int length = signalLinePoints.length - 1; context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); if (strokePaint.color != Colors.transparent && @@ -568,21 +591,26 @@ class MomentumIndicatorRenderer extends IndicatorRenderer { } if (_centerLinePoints.isNotEmpty) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = centerLineColor - ..strokeWidth = centerLineWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = centerLineColor + ..strokeWidth = centerLineWidth + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { _centerLinePath.reset(); length = _centerLinePoints.length; _centerLinePath.moveTo( - _centerLinePoints.first.dx, _centerLinePoints.first.dy); + _centerLinePoints.first.dx, + _centerLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { _centerLinePath.lineTo( - _centerLinePoints[i].dx, _centerLinePoints[i].dy); + _centerLinePoints[i].dx, + _centerLinePoints[i].dy, + ); } drawDashes(context.canvas, _dashArray, paint, path: _centerLinePath); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/roc_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/roc_indicator.dart index 04baf7129..15ed26f5b 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/roc_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/roc_indicator.dart @@ -174,22 +174,27 @@ class RocIndicator extends TechnicalIndicator { this.centerLineWidth = 2, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Center line color of the ROC indicator. /// @@ -313,7 +318,7 @@ class RocIndicator extends TechnicalIndicator { signalLineWidth, period, centerLineColor, - centerLineWidth + centerLineWidth, ]; return Object.hashAll(values); } @@ -358,7 +363,9 @@ class RocIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, RocIndicatorRenderer renderObject) { + BuildContext context, + RocIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final RocIndicator roc = indicator as RocIndicator; renderObject @@ -428,7 +435,7 @@ class RocIndicatorRenderer extends IndicatorRenderer { highValueMapper, lowValueMapper, openValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _openValues, _closeValues], ); @@ -552,35 +559,41 @@ class RocIndicatorRenderer extends IndicatorRenderer { if (rocPointIndex != -1) { final CartesianChartPoint rocPoint = _chartPoint(rocPointIndex, 'roc'); final String text = defaultLegendItemText(); - trackballInfo.add(ChartTrackballInfo( - position: signalLinePoints[rocPointIndex], - point: rocPoint, - series: this, - pointIndex: rocPointIndex, - segmentIndex: rocPointIndex, - seriesIndex: index, - name: text, - header: tooltipHeaderText(rocPoint), - text: trackballText(rocPoint, text), - color: signalLineColor, - )); + trackballInfo.add( + ChartTrackballInfo( + position: signalLinePoints[rocPointIndex], + point: rocPoint, + series: this, + pointIndex: rocPointIndex, + segmentIndex: rocPointIndex, + seriesIndex: index, + name: text, + header: tooltipHeaderText(rocPoint), + text: trackballText(rocPoint, text), + color: signalLineColor, + ), + ); } final int centerPointIndex = _findNearestPoint(_centerLinePoints, position); if (centerPointIndex != -1) { - final CartesianChartPoint centerPoint = - _chartPoint(centerPointIndex, 'center'); - trackballInfo.add(ChartTrackballInfo( - position: _centerLinePoints[centerPointIndex], - point: centerPoint, - series: this, - pointIndex: centerPointIndex, - segmentIndex: centerPointIndex, - seriesIndex: index, - name: trackballCenterText, - header: tooltipHeaderText(centerPoint), - text: trackballText(centerPoint, trackballCenterText), - color: _centerLineColor, - )); + final CartesianChartPoint centerPoint = _chartPoint( + centerPointIndex, + 'center', + ); + trackballInfo.add( + ChartTrackballInfo( + position: _centerLinePoints[centerPointIndex], + point: centerPoint, + series: this, + pointIndex: centerPointIndex, + segmentIndex: centerPointIndex, + seriesIndex: index, + name: trackballCenterText, + header: tooltipHeaderText(centerPoint), + text: trackballText(centerPoint, trackballCenterText), + color: _centerLineColor, + ), + ); } return trackballInfo; @@ -627,14 +640,16 @@ class RocIndicatorRenderer extends IndicatorRenderer { CartesianChartPoint _chartPoint(int pointIndex, String type) { return CartesianChartPoint( - x: type == 'roc' - ? xRawValues[pointIndex + period - 1] - : xRawValues[pointIndex], + x: + type == 'roc' + ? xRawValues[pointIndex + period - 1] + : xRawValues[pointIndex], xValue: type == 'roc' ? xValues[pointIndex + period] : xValues[pointIndex], - y: type == 'roc' - ? _signalLineActualValues[pointIndex].dy - : _centerLineActualValues[pointIndex].dy, + y: + type == 'roc' + ? _signalLineActualValues[pointIndex].dy + : _centerLineActualValues[pointIndex].dy, ); } @@ -649,8 +664,9 @@ class RocIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -666,8 +682,12 @@ class RocIndicatorRenderer extends IndicatorRenderer { @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); int length = signalLinePoints.length - 1; @@ -685,20 +705,25 @@ class RocIndicatorRenderer extends IndicatorRenderer { } if (_centerLinePoints.isNotEmpty) { - final Paint paint = Paint() - ..isAntiAlias = true - ..color = centerLineColor - ..strokeWidth = centerLineWidth - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = centerLineColor + ..strokeWidth = centerLineWidth + ..style = PaintingStyle.stroke; if (paint.color != Colors.transparent && paint.strokeWidth > 0) { _centerLinePath.reset(); length = _centerLinePoints.length; _centerLinePath.moveTo( - _centerLinePoints.first.dx, _centerLinePoints.first.dy); + _centerLinePoints.first.dx, + _centerLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { _centerLinePath.lineTo( - _centerLinePoints[i].dx, _centerLinePoints[i].dy); + _centerLinePoints[i].dx, + _centerLinePoints[i].dy, + ); } drawDashes(context.canvas, _dashArray, paint, path: _centerLinePath); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/rsi_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/rsi_indicator.dart index 7069784fc..1e7758ad7 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/rsi_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/rsi_indicator.dart @@ -56,19 +56,23 @@ class RsiIndicator extends TechnicalIndicator { this.lowerLineWidth = 2, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Show zones boolean value for RSI indicator. /// @@ -315,7 +319,7 @@ class RsiIndicator extends TechnicalIndicator { upperLineColor, upperLineWidth, lowerLineColor, - lowerLineWidth + lowerLineWidth, ]; return Object.hashAll(values); } @@ -365,7 +369,9 @@ class RsiIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, RsiIndicatorRenderer renderObject) { + BuildContext context, + RsiIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final RsiIndicator rsi = indicator as RsiIndicator; @@ -492,7 +498,7 @@ class RsiIndicatorRenderer extends IndicatorRenderer { ?>[ highValueMapper, lowValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _closeValues], ); @@ -648,8 +654,9 @@ class RsiIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < length; i++) { final num x = _upperLineActualValues[i].dx; final num y = _upperLineActualValues[i].dy; - _upperLinePoints - .add(Offset(pointToPixelX(x, y), pointToPixelY(x, y))); + _upperLinePoints.add( + Offset(pointToPixelX(x, y), pointToPixelY(x, y)), + ); } } @@ -658,8 +665,9 @@ class RsiIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < length; i++) { final num x = _lowerLineActualValues[i].dx; final num y = _lowerLineActualValues[i].dy; - _lowerLinePoints - .add(Offset(pointToPixelX(x, y), pointToPixelY(x, y))); + _lowerLinePoints.add( + Offset(pointToPixelX(x, y), pointToPixelY(x, y)), + ); } } } @@ -700,8 +708,10 @@ class RsiIndicatorRenderer extends IndicatorRenderer { if (showZones) { final int upperPointIndex = _findNearestPoint(_upperLinePoints, position); if (upperPointIndex != -1) { - final CartesianChartPoint upperPoint = - _chartPoint(upperPointIndex, 'upper'); + final CartesianChartPoint upperPoint = _chartPoint( + upperPointIndex, + 'upper', + ); trackballInfo.add( ChartTrackballInfo( position: _upperLinePoints[upperPointIndex], @@ -719,8 +729,10 @@ class RsiIndicatorRenderer extends IndicatorRenderer { } final int lowerPointIndex = _findNearestPoint(_lowerLinePoints, position); if (lowerPointIndex != -1) { - final CartesianChartPoint lowerPoint = - _chartPoint(lowerPointIndex, 'lower'); + final CartesianChartPoint lowerPoint = _chartPoint( + lowerPointIndex, + 'lower', + ); trackballInfo.add( ChartTrackballInfo( position: _lowerLinePoints[lowerPointIndex], @@ -781,16 +793,19 @@ class RsiIndicatorRenderer extends IndicatorRenderer { CartesianChartPoint _chartPoint(int pointIndex, String type) { return CartesianChartPoint( - x: type == 'rsi' - ? xRawValues[pointIndex + period] - : xRawValues[pointIndex], - xValue: - type == 'rsi' ? xValues[pointIndex + period] : xValues[pointIndex], - y: type == 'rsi' - ? _signalLineActualValues[pointIndex].dy - : type == 'upper' - ? _upperLineActualValues[pointIndex].dy - : _lowerLineActualValues[pointIndex].dy); + x: + type == 'rsi' + ? xRawValues[pointIndex + period] + : xRawValues[pointIndex], + xValue: + type == 'rsi' ? xValues[pointIndex + period] : xValues[pointIndex], + y: + type == 'rsi' + ? _signalLineActualValues[pointIndex].dy + : type == 'upper' + ? _upperLineActualValues[pointIndex].dy + : _lowerLineActualValues[pointIndex].dy, + ); } @override @@ -803,8 +818,9 @@ class RsiIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -822,8 +838,12 @@ class RsiIndicatorRenderer extends IndicatorRenderer { int length = signalLinePoints.length - 1; context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); strokePaint @@ -850,18 +870,21 @@ class RsiIndicatorRenderer extends IndicatorRenderer { length = _upperLinePoints.length; _upperLinePath.moveTo( - _upperLinePoints.first.dx, _upperLinePoints.first.dy); + _upperLinePoints.first.dx, + _upperLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { _upperLinePath.lineTo(_upperLinePoints[i].dx, _upperLinePoints[i].dy); } drawDashes( - context.canvas, - _dashArray, - strokePaint - ..color = upperLineColor - ..strokeWidth = upperLineWidth, - path: _upperLinePath); + context.canvas, + _dashArray, + strokePaint + ..color = upperLineColor + ..strokeWidth = upperLineWidth, + path: _upperLinePath, + ); } if (showZones && @@ -872,18 +895,21 @@ class RsiIndicatorRenderer extends IndicatorRenderer { length = _lowerLinePoints.length; _lowerLinePath.moveTo( - _lowerLinePoints.first.dx, _lowerLinePoints.first.dy); + _lowerLinePoints.first.dx, + _lowerLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { _lowerLinePath.lineTo(_lowerLinePoints[i].dx, _lowerLinePoints[i].dy); } drawDashes( - context.canvas, - _dashArray, - strokePaint - ..color = lowerLineColor - ..strokeWidth = lowerLineWidth, - path: _lowerLinePath); + context.canvas, + _dashArray, + strokePaint + ..color = lowerLineColor + ..strokeWidth = lowerLineWidth, + path: _lowerLinePath, + ); } context.canvas.restore(); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/sma_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/sma_indicator.dart index e1f2998a0..1c0543255 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/sma_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/sma_indicator.dart @@ -46,22 +46,27 @@ class SmaIndicator extends TechnicalIndicator { this.valueField = 'close', super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Value field value for SMA indicator. /// @@ -163,7 +168,7 @@ class SmaIndicator extends TechnicalIndicator { signalLineColor, signalLineWidth, valueField, - period + period, ]; return Object.hashAll(values); } @@ -208,7 +213,9 @@ class SmaIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, SmaIndicatorRenderer renderObject) { + BuildContext context, + SmaIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final SmaIndicator sma = indicator as SmaIndicator; @@ -267,7 +274,7 @@ class SmaIndicatorRenderer extends IndicatorRenderer { highValueMapper, lowValueMapper, openValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _openValues, _closeValues], ); @@ -414,7 +421,7 @@ class SmaIndicatorRenderer extends IndicatorRenderer { header: tooltipHeaderText(chartPoint), text: trackballText(chartPoint, text), color: signalLineColor, - ) + ), ]; } return null; @@ -477,8 +484,9 @@ class SmaIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -498,8 +506,12 @@ class SmaIndicatorRenderer extends IndicatorRenderer { if (strokePaint.color != Colors.transparent && strokePaint.strokeWidth > 0) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); for (int i = 0; i < length; i++) { diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/stochastic_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/stochastic_indicator.dart index 285c82028..c876c987b 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/stochastic_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/stochastic_indicator.dart @@ -58,22 +58,27 @@ class StochasticIndicator extends TechnicalIndicator { this.dPeriod = 5, super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Show zones boolean value for stochastic indicator. /// @@ -422,7 +427,7 @@ class StochasticIndicator extends TechnicalIndicator { periodLineColor, periodLineWidth, kPeriod, - dPeriod + dPeriod, ]; return Object.hashAll(values); } @@ -476,7 +481,9 @@ class StochasticIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, StochasticIndicatorRenderer renderObject) { + BuildContext context, + StochasticIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final StochasticIndicator stochastic = indicator as StochasticIndicator; @@ -652,7 +659,7 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { highValueMapper, lowValueMapper, openValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _openValues, _closeValues], ); @@ -717,18 +724,27 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { void _calculateStochasticIndicatorValues() { final List source = _calculatePeriodValues(period, kPeriod.toInt()); if (periodLineWidth > 0) { - _periodLineActualValues - .addAll(_calculateStochasticValues(period, kPeriod.toInt(), source)); + _periodLineActualValues.addAll( + _calculateStochasticValues(period, kPeriod.toInt(), source), + ); } if (signalLineWidth > 0) { - _signalLineActualValues.addAll(_calculateStochasticValues( - (period + kPeriod - 1).toInt(), dPeriod.toInt(), source)); + _signalLineActualValues.addAll( + _calculateStochasticValues( + (period + kPeriod - 1).toInt(), + dPeriod.toInt(), + source, + ), + ); } } List _calculateStochasticValues( - int period, int kPeriod, List data) { + int period, + int kPeriod, + List data, + ) { final List points = []; final int dataLength = data.length; if (dataLength >= period + kPeriod && kPeriod > 0) { @@ -842,11 +858,15 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { @override List? trackballInfo(Offset position) { final List trackballInfo = []; - final int stocasticPointIndex = - _findNearestPoint(signalLinePoints, position); + final int stocasticPointIndex = _findNearestPoint( + signalLinePoints, + position, + ); if (stocasticPointIndex != -1) { - final CartesianChartPoint stocasticPoint = - _chartPoint(stocasticPointIndex, 'stocastic'); + final CartesianChartPoint stocasticPoint = _chartPoint( + stocasticPointIndex, + 'stocastic', + ); final String stocasticText = defaultLegendItemText(); trackballInfo.add( ChartTrackballInfo( @@ -865,8 +885,10 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { } final int periodPointIndex = _findNearestPoint(_periodLinePoints, position); if (periodPointIndex != -1) { - final CartesianChartPoint periodPoint = - _chartPoint(periodPointIndex, 'periodLine'); + final CartesianChartPoint periodPoint = _chartPoint( + periodPointIndex, + 'periodLine', + ); trackballInfo.add( ChartTrackballInfo( position: _periodLinePoints[periodPointIndex], @@ -885,8 +907,10 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { if (showZones) { final int upperPointIndex = _findNearestPoint(_upperLinePoints, position); if (upperPointIndex != -1) { - final CartesianChartPoint upperPoint = - _chartPoint(upperPointIndex, 'upperLine'); + final CartesianChartPoint upperPoint = _chartPoint( + upperPointIndex, + 'upperLine', + ); trackballInfo.add( ChartTrackballInfo( position: _upperLinePoints[upperPointIndex], @@ -904,8 +928,10 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { } final int lowerPointIndex = _findNearestPoint(_lowerLinePoints, position); if (lowerPointIndex != -1) { - final CartesianChartPoint lowerPoint = - _chartPoint(lowerPointIndex, 'lowerLine'); + final CartesianChartPoint lowerPoint = _chartPoint( + lowerPointIndex, + 'lowerLine', + ); trackballInfo.add( ChartTrackballInfo( position: _lowerLinePoints[lowerPointIndex], @@ -966,27 +992,31 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { CartesianChartPoint _chartPoint(int pointIndex, String type) { return CartesianChartPoint( - x: type == 'stocastic' - ? xRawValues[pointIndex + - (signalLinePoints.length - xRawValues.length).abs()] - : type == 'periodLine' - ? xRawValues[pointIndex + - (_periodLinePoints.length - xRawValues.length).abs()] - : xRawValues[pointIndex], - xValue: type == 'stocastic' - ? xValues[pointIndex + - (signalLinePoints.length - xRawValues.length).abs()] - : type == 'periodLine' - ? xValues[pointIndex + - (_periodLinePoints.length - xValues.length).abs()] - : xValues[pointIndex], - y: type == 'stocastic' - ? _signalLineActualValues[pointIndex].dy - : type == 'periodLine' - ? _periodLineActualValues[pointIndex].dy - : type == 'upperLine' - ? _upperLineActualValues[pointIndex].dy - : _lowerLineActualValues[pointIndex].dy); + x: + type == 'stocastic' + ? xRawValues[pointIndex + + (signalLinePoints.length - xRawValues.length).abs()] + : type == 'periodLine' + ? xRawValues[pointIndex + + (_periodLinePoints.length - xRawValues.length).abs()] + : xRawValues[pointIndex], + xValue: + type == 'stocastic' + ? xValues[pointIndex + + (signalLinePoints.length - xRawValues.length).abs()] + : type == 'periodLine' + ? xValues[pointIndex + + (_periodLinePoints.length - xValues.length).abs()] + : xValues[pointIndex], + y: + type == 'stocastic' + ? _signalLineActualValues[pointIndex].dy + : type == 'periodLine' + ? _periodLineActualValues[pointIndex].dy + : type == 'upperLine' + ? _upperLineActualValues[pointIndex].dy + : _lowerLineActualValues[pointIndex].dy, + ); } @override @@ -1020,8 +1050,10 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < dataCount; i++) { final num xValue = xValues[i]; - final CartesianChartPoint point = - CartesianChartPoint(x: xRawValues[i], xValue: xValue); + final CartesianChartPoint point = CartesianChartPoint( + x: xRawValues[i], + xValue: xValue, + ); for (int j = 0; j < yLength; j++) { point[positions[j]] = yLists[j][i]; } @@ -1060,8 +1092,9 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < length; i++) { final num x = _upperLineActualValues[i].dx; final num y = _upperLineActualValues[i].dy; - _upperLinePoints - .add(Offset(pointToPixelX(x, y), pointToPixelY(x, y))); + _upperLinePoints.add( + Offset(pointToPixelX(x, y), pointToPixelY(x, y)), + ); } } @@ -1070,8 +1103,9 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { for (int i = 0; i < length; i++) { final num x = _lowerLineActualValues[i].dx; final num y = _lowerLineActualValues[i].dy; - _lowerLinePoints - .add(Offset(pointToPixelX(x, y), pointToPixelY(x, y))); + _lowerLinePoints.add( + Offset(pointToPixelX(x, y), pointToPixelY(x, y)), + ); } } } @@ -1100,15 +1134,16 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { if (onRenderDetailsUpdate != null) { final StochasticIndicatorRenderParams params = StochasticIndicatorRenderParams( - _periodChartPoints, - chartPoints, - legendItemText ?? name ?? defaultLegendItemText(), - signalLineWidth, - signalLineColor, - dashArray, + _periodChartPoints, + chartPoints, + legendItemText ?? name ?? defaultLegendItemText(), + signalLineWidth, + signalLineColor, + dashArray, + ); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -1126,8 +1161,12 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { int length = signalLinePoints.length - 1; context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); strokePaint @@ -1173,18 +1212,21 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { length = _upperLinePoints.length; _upperLinePath.moveTo( - _upperLinePoints.first.dx, _upperLinePoints.first.dy); + _upperLinePoints.first.dx, + _upperLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { _upperLinePath.lineTo(_upperLinePoints[i].dx, _upperLinePoints[i].dy); } drawDashes( - context.canvas, - _dashArray, - strokePaint - ..color = upperLineColor - ..strokeWidth = upperLineWidth, - path: _upperLinePath); + context.canvas, + _dashArray, + strokePaint + ..color = upperLineColor + ..strokeWidth = upperLineWidth, + path: _upperLinePath, + ); } // Draw lower line. @@ -1196,18 +1238,21 @@ class StochasticIndicatorRenderer extends IndicatorRenderer { length = _lowerLinePoints.length; _lowerLinePath.moveTo( - _lowerLinePoints.first.dx, _lowerLinePoints.first.dy); + _lowerLinePoints.first.dx, + _lowerLinePoints.first.dy, + ); for (int i = 1; i < length; i++) { _lowerLinePath.lineTo(_lowerLinePoints[i].dx, _lowerLinePoints[i].dy); } drawDashes( - context.canvas, - _dashArray, - strokePaint - ..color = lowerLineColor - ..strokeWidth = lowerLineWidth, - path: _lowerLinePath); + context.canvas, + _dashArray, + strokePaint + ..color = lowerLineColor + ..strokeWidth = lowerLineWidth, + path: _lowerLinePath, + ); } context.canvas.restore(); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/technical_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/technical_indicator.dart index 12643f184..965602699 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/technical_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/technical_indicator.dart @@ -617,7 +617,9 @@ abstract class IndicatorWidget extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, IndicatorRenderer renderObject) { + BuildContext context, + IndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..vsync = vsync @@ -664,13 +666,15 @@ abstract class IndicatorRenderer extends RenderBox ChartLegendRenderCallback? onLegendItemRender; ChartIndicatorRenderCallback? onRenderDetailsUpdate; - final Paint _fillPaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.fill; - final Paint _strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round; + final Paint _fillPaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.fill; + final Paint _strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; @override bool get isRepaintBoundary => true; @@ -998,8 +1002,10 @@ abstract class IndicatorRenderer extends RenderBox for (int i = 0; i < dataCount; i++) { final num xValue = xValues[i]; - final CartesianChartPoint point = - CartesianChartPoint(x: xRawValues[i], xValue: xValue); + final CartesianChartPoint point = CartesianChartPoint( + x: xRawValues[i], + xValue: xValue, + ); for (int j = 0; j < yLength; j++) { point[positions[j]] = yLists[j][i]; } @@ -1070,7 +1076,7 @@ abstract class IndicatorRenderer extends RenderBox List? buildLegendItems(int index) { if (parent != null && isVisibleInLegend) { return [ - ChartLegendItem( + CartesianLegendItem( text: legendItemText ?? name ?? defaultLegendItemText(), iconType: toLegendShapeMarkerType(legendIconType, this), iconColor: effectiveLegendIconColor(), @@ -1088,9 +1094,11 @@ abstract class IndicatorRenderer extends RenderBox void _handleLegendItemTapped(LegendItem item, bool isToggled) { if (onLegendTapped != null) { - final ChartLegendItem legendItem = item as ChartLegendItem; - final LegendTapArgs args = - LegendTapArgs(legendItem.series, legendItem.seriesIndex); + final CartesianLegendItem legendItem = item as CartesianLegendItem; + final LegendTapArgs args = LegendTapArgs( + legendItem.series, + legendItem.seriesIndex, + ); onLegendTapped!(args); } effectiveIsVisible = !isToggled; @@ -1099,7 +1107,7 @@ abstract class IndicatorRenderer extends RenderBox void _handleLegendItemCreated(ItemRendererDetails details) { if (onLegendItemRender != null) { - final ChartLegendItem item = details.item as ChartLegendItem; + final CartesianLegendItem item = details.item as CartesianLegendItem; final LegendIconType iconType = toLegendIconType(details.iconType); final LegendRenderArgs args = LegendRenderArgs(item.seriesIndex, item.pointIndex) @@ -1109,7 +1117,9 @@ abstract class IndicatorRenderer extends RenderBox onLegendItemRender!(args); if (args.legendIconType != iconType) { details.iconType = toLegendShapeMarkerType( - args.legendIconType ?? LegendIconType.seriesType, this); + args.legendIconType ?? LegendIconType.seriesType, + this, + ); } details diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/tma_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/tma_indicator.dart index c4dc64d58..8fb289059 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/tma_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/tma_indicator.dart @@ -46,22 +46,27 @@ class TmaIndicator extends TechnicalIndicator { this.valueField = 'close', super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// ValueField value for tma indicator. /// @@ -163,7 +168,7 @@ class TmaIndicator extends TechnicalIndicator { signalLineColor, signalLineWidth, valueField, - period + period, ]; return Object.hashAll(values); } @@ -207,7 +212,9 @@ class TmaIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, TmaIndicatorRenderer renderObject) { + BuildContext context, + TmaIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final TmaIndicator tma = indicator as TmaIndicator; @@ -266,7 +273,7 @@ class TmaIndicatorRenderer extends IndicatorRenderer { highValueMapper, lowValueMapper, openValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _openValues, _closeValues], ); @@ -396,7 +403,7 @@ class TmaIndicatorRenderer extends IndicatorRenderer { header: tooltipHeaderText(chartPoint), text: trackballText(chartPoint, text), color: signalLineColor, - ) + ), ]; } return null; @@ -493,8 +500,9 @@ class TmaIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -514,8 +522,12 @@ class TmaIndicatorRenderer extends IndicatorRenderer { if (strokePaint.color != Colors.transparent && strokePaint.strokeWidth > 0) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); for (int i = 0; i < length; i++) { diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/wma_indicator.dart b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/wma_indicator.dart index 1567d6c85..905427f60 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/indicators/wma_indicator.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/indicators/wma_indicator.dart @@ -179,22 +179,27 @@ class WmaIndicator extends TechnicalIndicator { this.valueField = 'close', super.onRenderDetailsUpdate, }) : super( - xValueMapper: xValueMapper != null && dataSource != null - ? (int index) => xValueMapper(dataSource[index], index) - : null, - highValueMapper: highValueMapper != null && dataSource != null - ? (int index) => highValueMapper(dataSource[index], index) - : null, - lowValueMapper: lowValueMapper != null && dataSource != null - ? (int index) => lowValueMapper(dataSource[index], index) - : null, - openValueMapper: openValueMapper != null && dataSource != null - ? (int index) => openValueMapper(dataSource[index], index) - : null, - closeValueMapper: closeValueMapper != null && dataSource != null - ? (int index) => closeValueMapper(dataSource[index], index) - : null, - ); + xValueMapper: + xValueMapper != null && dataSource != null + ? (int index) => xValueMapper(dataSource[index], index) + : null, + highValueMapper: + highValueMapper != null && dataSource != null + ? (int index) => highValueMapper(dataSource[index], index) + : null, + lowValueMapper: + lowValueMapper != null && dataSource != null + ? (int index) => lowValueMapper(dataSource[index], index) + : null, + openValueMapper: + openValueMapper != null && dataSource != null + ? (int index) => openValueMapper(dataSource[index], index) + : null, + closeValueMapper: + closeValueMapper != null && dataSource != null + ? (int index) => closeValueMapper(dataSource[index], index) + : null, + ); /// Value field value for WMA indicator. /// @@ -296,7 +301,7 @@ class WmaIndicator extends TechnicalIndicator { signalLineColor, signalLineWidth, valueField, - period + period, ]; return Object.hashAll(values); } @@ -338,7 +343,9 @@ class WmaIndicatorWidget extends IndicatorWidget { @override void updateRenderObject( - BuildContext context, WmaIndicatorRenderer renderObject) { + BuildContext context, + WmaIndicatorRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); final WmaIndicator wma = indicator as WmaIndicator; renderObject @@ -396,7 +403,7 @@ class WmaIndicatorRenderer extends IndicatorRenderer { highValueMapper, lowValueMapper, openValueMapper, - closeValueMapper + closeValueMapper, ], >[_highValues, _lowValues, _openValues, _closeValues], ); @@ -530,7 +537,7 @@ class WmaIndicatorRenderer extends IndicatorRenderer { header: tooltipHeaderText(chartPoint), text: trackballText(chartPoint, text), color: signalLineColor, - ) + ), ]; } return null; @@ -593,8 +600,9 @@ class WmaIndicatorRenderer extends IndicatorRenderer { signalLineColor, dashArray, ); - final TechnicalIndicatorRenderDetails details = - onRenderDetailsUpdate!(params); + final TechnicalIndicatorRenderDetails details = onRenderDetailsUpdate!( + params, + ); strokePaint ..color = details.signalLineColor ..strokeWidth = details.signalLineWidth; @@ -610,8 +618,12 @@ class WmaIndicatorRenderer extends IndicatorRenderer { @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); if (signalLinePoints.isNotEmpty) { diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/interactions/behavior.dart b/packages/syncfusion_flutter_charts/lib/src/charts/interactions/behavior.dart index 6ef991f8d..be62bd8d7 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/interactions/behavior.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/interactions/behavior.dart @@ -89,7 +89,9 @@ class BehaviorArea extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderBehaviorArea renderObject) { + BuildContext context, + RenderBehaviorArea renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject .._tooltipKey = tooltipKey @@ -203,13 +205,15 @@ class RenderBehaviorArea extends RenderBox value.parentBox = this; } _zoomPanBehavior = value; - _zoomingEnabled = value != null && + _zoomingEnabled = + value != null && (value.enablePinching || value.enablePanning || value.enableMouseWheelZooming || value.enableDoubleTapZooming || value.enableSelectionZooming); - performZoomThroughTouch = value != null && + performZoomThroughTouch = + value != null && (value.enablePinching || value.enableSelectionZooming); } } @@ -240,6 +244,27 @@ class RenderBehaviorArea extends RenderBox markNeedsPaint(); } + ZoomMode get directionalZoomMode => _directionalZoomMode; + ZoomMode _directionalZoomMode = ZoomMode.xy; + set directionalZoomMode(ZoomMode value) { + if (_directionalZoomMode != value) { + _directionalZoomMode = value; + } + } + + ZoomMode get effectiveZoomMode { + ZoomMode zoomMode = ZoomMode.xy; + if (zoomPanBehavior != null) { + zoomMode = + zoomPanBehavior!.enableDirectionalZooming && + zoomPanBehavior!.enablePinching && + zoomPanBehavior!.zoomMode == ZoomMode.xy + ? directionalZoomMode + : zoomPanBehavior!.zoomMode; + } + return zoomMode; + } + RenderChartAxis? get xAxis => cartesianAxes?.axes[primaryXAxisName]; RenderChartAxis? get yAxis => cartesianAxes?.axes[primaryYAxisName]; @@ -479,21 +504,27 @@ class RenderBehaviorArea extends RenderBox _loadingIndicator?.handleDragEnd(details); } - void raiseTooltip(TooltipInfo info, - [PointerDeviceKind kind = PointerDeviceKind.touch]) { + void raiseTooltip( + TooltipInfo info, [ + PointerDeviceKind kind = PointerDeviceKind.touch, + ]) { if (tooltipBehavior != null && tooltipBehavior!.shared && info is! TrendlineTooltipInfo) { final ChartTooltipInfo chartTooltipInfo = info as ChartTooltipInfo; tooltipBehavior!.showByIndex( - chartTooltipInfo.seriesIndex, chartTooltipInfo.pointIndex); + chartTooltipInfo.seriesIndex, + chartTooltipInfo.pointIndex, + ); } else { showTooltip(info, kind); } } - void showTooltip(TooltipInfo info, - [PointerDeviceKind kind = PointerDeviceKind.touch]) { + void showTooltip( + TooltipInfo info, [ + PointerDeviceKind kind = PointerDeviceKind.touch, + ]) { if (tooltipBehavior == null || !tooltipBehavior!.enable) { return; } @@ -507,35 +538,44 @@ class RenderBehaviorArea extends RenderBox if (info is ChartTooltipInfo && onTooltipRender != null && _previousTooltipInfo != info) { - final TooltipArgs tooltipRenderArgs = TooltipArgs( - info.seriesIndex, - info.renderer.chartPoints, - info.renderer.viewportIndex(info.pointIndex), - info.pointIndex) - ..text = info.text - ..header = tooltipBehavior!.header ?? info.header - ..locationX = info.primaryPosition.dx - ..locationY = info.primaryPosition.dy; + final TooltipArgs tooltipRenderArgs = + TooltipArgs( + info.seriesIndex, + info.renderer.chartPoints, + info.renderer.viewportIndex(info.pointIndex), + info.pointIndex, + ) + ..text = info.text + ..header = tooltipBehavior!.header ?? info.header + ..locationX = info.primaryPosition.dx + ..locationY = info.primaryPosition.dy; onTooltipRender!(tooltipRenderArgs); - assert(tooltipRenderArgs.locationX != null && - tooltipRenderArgs.locationY != null); + assert( + tooltipRenderArgs.locationX != null && + tooltipRenderArgs.locationY != null, + ); info = info.copyWith( - primaryPosition: - Offset(tooltipRenderArgs.locationX!, tooltipRenderArgs.locationY!), + primaryPosition: Offset( + tooltipRenderArgs.locationX!, + tooltipRenderArgs.locationY!, + ), text: tooltipRenderArgs.text, name: tooltipRenderArgs.header, ); _previousTooltipInfo = info; } - state.show(info, kind, - immediately: - tooltipBehavior!.tooltipPosition == TooltipPosition.pointer); + state.show( + info, + kind, + immediately: tooltipBehavior!.tooltipPosition == TooltipPosition.pointer, + ); } void hideTooltip({bool immediately = false}) { _previousTooltipInfo = null; - (_tooltipKey?.currentState as CoreTooltipState?) - ?.hide(immediately: immediately); + (_tooltipKey?.currentState as CoreTooltipState?)?.hide( + immediately: immediately, + ); } void hideInteractiveTooltip() { diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/interactions/tooltip.dart b/packages/syncfusion_flutter_charts/lib/src/charts/interactions/tooltip.dart index 348b4d3c1..da34c316f 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/interactions/tooltip.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/interactions/tooltip.dart @@ -542,8 +542,9 @@ class TooltipBehavior extends ChartBehavior { if (child is ChartSeriesRenderer) { final bool isHit = child.hitInsideSegment(primaryLocalPosition); if (isHit) { - final TooltipInfo? info = - child.tooltipInfo(position: primaryLocalPosition); + final TooltipInfo? info = child.tooltipInfo( + position: primaryLocalPosition, + ); if (info != null) { parent.raiseTooltip(info); } @@ -553,10 +554,12 @@ class TooltipBehavior extends ChartBehavior { child = childParentData.previousSibling; } - parent.raiseTooltip(TooltipInfo( - primaryPosition: primaryPosition, - secondaryPosition: primaryPosition, - )); + parent.raiseTooltip( + TooltipInfo( + primaryPosition: primaryPosition, + secondaryPosition: primaryPosition, + ), + ); } /// Displays the tooltip at the specified x and y-values. @@ -575,8 +578,13 @@ class TooltipBehavior extends ChartBehavior { xAxisName != null ? parent.axisFromName(xAxisName) : parent.xAxis; final RenderChartAxis? yAxis = yAxisName != null ? parent.axisFromName(yAxisName) : parent.yAxis; - final Offset position = - rawValueToPixelPoint(x, y, xAxis, yAxis, parent.isTransposed); + final Offset position = rawValueToPixelPoint( + x, + y, + xAxis, + yAxis, + parent.isTransposed, + ); showByPixel(position.dx, position.dy); } } @@ -606,8 +614,9 @@ class TooltipBehavior extends ChartBehavior { if (series is CartesianSeriesRenderer && series.isVisible() && series.enableTooltip) { - final ChartTooltipInfo? info = series - .tooltipInfoFromPointIndex(pointIndex) as ChartTooltipInfo?; + final ChartTooltipInfo? info = + series.tooltipInfoFromPointIndex(pointIndex) + as ChartTooltipInfo?; if (info != null && series.index == seriesIndex) { baseXValue = (info.point as CartesianChartPoint).xValue; break; @@ -624,8 +633,9 @@ class TooltipBehavior extends ChartBehavior { if (child is ChartSeriesRenderer && child.isVisible() && child.enableTooltip) { - final ChartTooltipInfo? info = child - .tooltipInfoFromPointIndex(pointIndex) as ChartTooltipInfo?; + final ChartTooltipInfo? info = + child.tooltipInfoFromPointIndex(pointIndex) + as ChartTooltipInfo?; if (info != null && info.text != null) { if (child.index == seriesIndex) { tooltipInfo ??= info; @@ -641,8 +651,12 @@ class TooltipBehavior extends ChartBehavior { } else { // It specifies for cartesian series renderer. if (child.canFindLinearVisibleIndexes) { - final int binaryIndex = binarySearch(child.xValues, - baseXValue.toDouble(), 0, child.dataCount - 1); + final int binaryIndex = binarySearch( + child.xValues, + baseXValue.toDouble(), + 0, + child.dataCount - 1, + ); if (binaryIndex >= 0) { final ChartTooltipInfo? info = child.tooltipInfoFromPointIndex(binaryIndex) @@ -658,8 +672,9 @@ class TooltipBehavior extends ChartBehavior { } else { final int index = child.xValues.indexOf(baseXValue); if (index >= 0) { - final ChartTooltipInfo? info = child - .tooltipInfoFromPointIndex(index) as ChartTooltipInfo?; + final ChartTooltipInfo? info = + child.tooltipInfoFromPointIndex(index) + as ChartTooltipInfo?; if (info != null && info.text != null) { tooltipInfoList.add(info); } @@ -684,22 +699,24 @@ class TooltipBehavior extends ChartBehavior { } if (tooltipInfo != null && text != null && position != null) { - parent.showTooltip(ChartTooltipInfo( - primaryPosition: position, - secondaryPosition: tooltipInfo.secondaryPosition, - text: text, - data: tooltipInfo.data, - point: tooltipInfo.point, - series: tooltipInfo.series, - renderer: tooltipInfo.renderer, - header: header ?? tooltipInfo.header, - seriesIndex: seriesIndex, - pointIndex: pointIndex, - segmentIndex: tooltipInfo.segmentIndex, - markerColors: markerColors, - markerBorderColor: tooltipInfo.markerBorderColor, - markerType: tooltipInfo.markerType, - )); + parent.showTooltip( + ChartTooltipInfo( + primaryPosition: position, + secondaryPosition: tooltipInfo.secondaryPosition, + text: text, + data: tooltipInfo.data, + point: tooltipInfo.point, + series: tooltipInfo.series, + renderer: tooltipInfo.renderer, + header: header ?? tooltipInfo.header, + seriesIndex: seriesIndex, + pointIndex: pointIndex, + segmentIndex: tooltipInfo.segmentIndex, + markerColors: markerColors, + markerBorderColor: tooltipInfo.markerBorderColor, + markerType: tooltipInfo.markerType, + ), + ); } } else { parent.plotArea?.visitChildren((RenderObject child) { @@ -707,8 +724,9 @@ class TooltipBehavior extends ChartBehavior { child.isVisible() && child.enableTooltip) { if (child.index == seriesIndex) { - final TooltipInfo? info = - child.tooltipInfoFromPointIndex(pointIndex); + final TooltipInfo? info = child.tooltipInfoFromPointIndex( + pointIndex, + ); if (info != null) { parent.showTooltip(info); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/pyramid_chart.dart b/packages/syncfusion_flutter_charts/lib/src/charts/pyramid_chart.dart index 5edda4297..a2db855a8 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/pyramid_chart.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/pyramid_chart.dart @@ -427,45 +427,60 @@ class SfPyramidChartState extends State SfLocalizations? _localizations; SfChartThemeData _updateThemeData( - BuildContext context, ChartThemeData effectiveChartThemeData) { + BuildContext context, + ChartThemeData effectiveChartThemeData, + ) { SfChartThemeData chartThemeData = SfChartTheme.of(context); chartThemeData = chartThemeData.copyWith( - backgroundColor: widget.backgroundColor ?? + backgroundColor: + widget.backgroundColor ?? chartThemeData.backgroundColor ?? effectiveChartThemeData.backgroundColor, - titleBackgroundColor: widget.title.backgroundColor ?? + titleBackgroundColor: + widget.title.backgroundColor ?? chartThemeData.titleBackgroundColor ?? effectiveChartThemeData.titleBackgroundColor, - legendBackgroundColor: widget.legend.backgroundColor ?? + legendBackgroundColor: + widget.legend.backgroundColor ?? chartThemeData.legendBackgroundColor ?? effectiveChartThemeData.legendBackgroundColor, - tooltipColor: widget.tooltipBehavior?.color ?? + tooltipColor: + widget.tooltipBehavior?.color ?? chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - plotAreaBackgroundColor: chartThemeData.plotAreaBackgroundColor ?? + plotAreaBackgroundColor: + chartThemeData.plotAreaBackgroundColor ?? effectiveChartThemeData.plotAreaBackgroundColor, titleTextStyle: effectiveChartThemeData.titleTextStyle! .copyWith( - color: chartThemeData.titleTextColor ?? - effectiveChartThemeData.titleTextColor) + color: + chartThemeData.titleTextColor ?? + effectiveChartThemeData.titleTextColor, + ) .merge(chartThemeData.titleTextStyle) .merge(widget.title.textStyle), legendTitleTextStyle: effectiveChartThemeData.legendTitleTextStyle! .copyWith( - color: chartThemeData.legendTitleColor ?? - effectiveChartThemeData.legendTitleColor) + color: + chartThemeData.legendTitleColor ?? + effectiveChartThemeData.legendTitleColor, + ) .merge(chartThemeData.legendTitleTextStyle) .merge(widget.legend.title?.textStyle), legendTextStyle: effectiveChartThemeData.legendTextStyle! .copyWith( - color: chartThemeData.legendTextColor ?? - effectiveChartThemeData.legendTextColor) + color: + chartThemeData.legendTextColor ?? + effectiveChartThemeData.legendTextColor, + ) .merge(chartThemeData.legendTextStyle) .merge(widget.legend.textStyle), tooltipTextStyle: effectiveChartThemeData.tooltipTextStyle! .copyWith( - color: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor) + color: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) .merge(chartThemeData.tooltipTextStyle) .merge(widget.tooltipBehavior?.textStyle), ); @@ -477,9 +492,18 @@ class SfPyramidChartState extends State } Widget? _buildTooltipWidget( - BuildContext context, TooltipInfo? info, Size maxSize) { - return buildTooltipWidget(context, info, maxSize, widget.tooltipBehavior, - _chartThemeData, _themeData); + BuildContext context, + TooltipInfo? info, + Size maxSize, + ) { + return buildTooltipWidget( + context, + info, + maxSize, + widget.tooltipBehavior, + _chartThemeData, + _themeData, + ); } /// Called when this object is inserted into the tree. @@ -526,28 +550,36 @@ class SfPyramidChartState extends State _themeData = Theme.of(context); final ChartThemeData effectiveChartThemeData = ChartThemeData(context); _chartThemeData = _updateThemeData(context, effectiveChartThemeData); - final core.LegendPosition legendPosition = - effectiveLegendPosition(widget.legend); - final Axis orientation = - effectiveLegendOrientation(legendPosition, widget.legend); + final core.LegendPosition legendPosition = effectiveLegendPosition( + widget.legend, + ); + final Axis orientation = effectiveLegendOrientation( + legendPosition, + widget.legend, + ); Widget current = core.LegendLayout( key: _legendKey, padding: EdgeInsets.zero, showLegend: widget.legend.isVisible, legendPosition: legendPosition, legendAlignment: effectiveLegendAlignment(widget.legend.alignment), - legendTitleAlignment: - effectiveLegendAlignment(widget.legend.title?.alignment), + legendTitleAlignment: effectiveLegendAlignment( + widget.legend.title?.alignment, + ), itemIconBorderColor: widget.legend.iconBorderColor, itemIconBorderWidth: widget.legend.iconBorderWidth, legendBorderColor: widget.legend.borderColor, legendBackgroundColor: _chartThemeData.legendBackgroundColor, legendBorderWidth: widget.legend.borderWidth, itemOpacity: widget.legend.opacity, - legendWidthFactor: - percentageToWidthFactor(widget.legend.width, legendPosition), - legendHeightFactor: - percentageToHeightFactor(widget.legend.height, legendPosition), + legendWidthFactor: percentageToWidthFactor( + widget.legend.width, + legendPosition, + ), + legendHeightFactor: percentageToHeightFactor( + widget.legend.height, + legendPosition, + ), itemInnerSpacing: widget.legend.padding, itemSpacing: 0.0, itemPadding: widget.legend.itemPadding, @@ -609,8 +641,9 @@ class SfPyramidChartState extends State opacity: widget.tooltipBehavior!.opacity, borderColor: widget.tooltipBehavior!.borderColor, borderWidth: widget.tooltipBehavior!.borderWidth, - color: (widget.tooltipBehavior!.color ?? - _chartThemeData.tooltipColor)!, + color: + (widget.tooltipBehavior!.color ?? + _chartThemeData.tooltipColor)!, showDuration: widget.tooltipBehavior!.duration.toInt(), shadowColor: widget.tooltipBehavior!.shadowColor, elevation: widget.tooltipBehavior!.elevation, @@ -629,12 +662,13 @@ class SfPyramidChartState extends State return RepaintBoundary( child: Container( decoration: BoxDecoration( - image: widget.backgroundImage != null - ? DecorationImage( - image: widget.backgroundImage!, - fit: BoxFit.fill, - ) - : null, + image: + widget.backgroundImage != null + ? DecorationImage( + image: widget.backgroundImage!, + fit: BoxFit.fill, + ) + : null, color: _chartThemeData.backgroundColor, border: Border.all( color: widget.borderColor, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/area_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/area_series.dart index 52695488d..cb8e6023b 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/area_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/area_series.dart @@ -108,10 +108,11 @@ class AreaSeries extends XyDataSeries { if (onCreateRenderer != null) { renderer = onCreateRenderer!(this) as AreaSeriesRenderer?; assert( - renderer != null, - 'This onCreateRenderer callback function should return value as ' - 'extends from ChartSeriesRenderer class and should not be return ' - 'value as null'); + renderer != null, + 'This onCreateRenderer callback function should return value as ' + 'extends from ChartSeriesRenderer class and should not be return ' + 'value as null', + ); } return renderer ?? AreaSeriesRenderer(); @@ -129,7 +130,9 @@ class AreaSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, AreaSeriesRenderer renderObject) { + BuildContext context, + AreaSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..borderDrawMode = borderDrawMode @@ -186,17 +189,23 @@ class AreaSeriesRenderer extends XyDataSeriesRenderer void customizeSegment(ChartSegment segment) { final AreaSegment areaSegment = segment as AreaSegment; updateSegmentColor(areaSegment, borderColor, borderWidth); - updateSegmentGradient(areaSegment, - gradientBounds: areaSegment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + areaSegment, + gradientBounds: areaSegment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -230,7 +239,9 @@ class AreaSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -250,26 +261,50 @@ class AreaSegment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + bottom, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + bottom, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + bottom, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -336,19 +371,22 @@ class AreaSegment extends ChartSegment { final int newPointsLength = newPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!, + ); } } @@ -356,7 +394,10 @@ class AreaSegment extends ChartSegment { } Path _createFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -365,7 +406,10 @@ class AreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createFillPath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -424,7 +468,10 @@ class AreaSegment extends ChartSegment { } Path _createExcludeBottomStrokePath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -433,7 +480,10 @@ class AreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createExcludeBottomStrokePath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -446,7 +496,10 @@ class AreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i - 1]; path!.lineTo(lowPoint.dx, lowPoint.dy); _createExcludeBottomStrokePath( - source, highPoints.sublist(i), lowPoints.sublist(i)); + source, + highPoints.sublist(i), + lowPoints.sublist(i), + ); break; } else { path!.lineTo(highPoint.dx, highPoint.dy); @@ -469,8 +522,11 @@ class AreaSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -510,14 +566,17 @@ class AreaSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -592,8 +651,10 @@ class AreaSegment extends ChartSegment { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); _createFillPath(_fillPath, lerpHighPoints, lerpLowPoints); @@ -606,7 +667,10 @@ class AreaSegment extends ChartSegment { break; case BorderDrawMode.excludeBottom: _createExcludeBottomStrokePath( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/bar_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/bar_series.dart index 6039d3171..88bd4616f 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/bar_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/bar_series.dart @@ -232,10 +232,11 @@ class BarSeries extends XyDataSeries { if (onCreateRenderer != null) { renderer = onCreateRenderer!(this) as BarSeriesRenderer?; assert( - renderer != null, - 'This onCreateRenderer callback function should return value as ' - 'extends from ChartSeriesRenderer class and should not be return ' - 'value as null'); + renderer != null, + 'This onCreateRenderer callback function should return value as ' + 'extends from ChartSeriesRenderer class and should not be return ' + 'value as null', + ); } return renderer ?? BarSeriesRenderer(); @@ -260,7 +261,9 @@ class BarSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, BarSeriesRenderer renderObject) { + BuildContext context, + BarSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isTrackVisible = isTrackVisible @@ -367,20 +370,29 @@ class BarSeriesRenderer extends XyDataSeriesRenderer void customizeSegment(ChartSegment segment) { final BarSegment barSegment = segment as BarSegment; updateSegmentTrackerStyle( - barSegment, trackColor, trackBorderColor, trackBorderWidth); + barSegment, + trackColor, + trackBorderColor, + trackBorderWidth, + ); updateSegmentColor(barSegment, borderColor, borderWidth); - updateSegmentGradient(barSegment, - gradientBounds: barSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + barSegment, + gradientBounds: barSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } @override void handleLegendItemTapped(LegendItem item, bool isToggled) { if (parent != null && parent!.onLegendTapped != null) { - final ChartLegendItem legendItem = item as ChartLegendItem; + final CartesianLegendItem legendItem = item as CartesianLegendItem; final LegendTapArgs args = LegendTapArgs( - legendItem.series, legendItem.seriesIndex, legendItem.pointIndex); + legendItem.series, + legendItem.seriesIndex, + legendItem.pointIndex, + ); parent!.onLegendTapped!(args); } parent!.behaviorArea?.hideInteractiveTooltip(); @@ -424,7 +436,9 @@ class BarSegment extends ChartSegment with BarSeriesTrackerMixin { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -498,21 +512,25 @@ class BarSegment extends ChartSegment with BarSeriesTrackerMixin { final TooltipPosition? tooltipPosition = series.parent?.tooltipBehavior?.tooltipPosition; final Offset posFromRect = segmentRect!.outerRect.topCenter; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? posFromRect - : posFromRect; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? posFromRect + : posFromRect; final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -532,8 +550,10 @@ class BarSegment extends ChartSegment with BarSeriesTrackerMixin { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, y), series.pointToPixelY(x, y)), + position: Offset( + series.pointToPixelX(x, y), + series.pointToPixelY(x, y), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -576,7 +596,11 @@ class BarSegment extends ChartSegment with BarSeriesTrackerMixin { _oldSegmentRect != null && series.animationType != AnimationType.loading) { paintRRect = performLegendToggleAnimation( - series, segmentRect!, _oldSegmentRect!, series.borderRadius); + series, + segmentRect!, + _oldSegmentRect!, + series.borderRadius, + ); } else { paintRRect = RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/box_and_whisker_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/box_and_whisker_series.dart index c211de69b..98c1acb8f 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/box_and_whisker_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/box_and_whisker_series.dart @@ -164,13 +164,13 @@ class BoxAndWhiskerSeries extends CartesianSeries { case SeriesSlot.dataLabel: return dataLabelSettings.isVisible ? CartesianDataLabelContainer( - series: this, - dataSource: dataSource!, - mapper: dataLabelMapper, - builder: dataLabelSettings.builder, - settings: dataLabelSettings, - positions: positions, - ) + series: this, + dataSource: dataSource!, + mapper: dataLabelMapper, + builder: dataLabelSettings.builder, + settings: dataLabelSettings, + positions: positions, + ) : null; case SeriesSlot.marker: @@ -190,13 +190,13 @@ class BoxAndWhiskerSeries extends CartesianSeries { @override List get positions => [ - ChartDataPointType.high, - ChartDataPointType.low, - ChartDataPointType.open, - ChartDataPointType.close, - ChartDataPointType.median, - ChartDataPointType.outliers, - ]; + ChartDataPointType.high, + ChartDataPointType.low, + ChartDataPointType.open, + ChartDataPointType.close, + ChartDataPointType.median, + ChartDataPointType.outliers, + ]; /// Create the Box and Whisker series renderer. @override @@ -225,7 +225,9 @@ class BoxAndWhiskerSeries extends CartesianSeries { @override void updateRenderObject( - BuildContext context, BoxAndWhiskerSeriesRenderer renderObject) { + BuildContext context, + BoxAndWhiskerSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..yValueMapper = yValueMapper @@ -254,8 +256,9 @@ class BoxAndWhiskerSeriesRenderer @override set color(Color? value) { - markerSettings = - markerSettings.copyWith(borderColor: value ?? paletteColor); + markerSettings = markerSettings.copyWith( + borderColor: value ?? paletteColor, + ); super.color = value; } @@ -321,7 +324,13 @@ class BoxAndWhiskerSeriesRenderer ]) { _resetDataSourceHolders(); super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); populateChartPoints(); } @@ -337,7 +346,7 @@ class BoxAndWhiskerSeriesRenderer List>? chaoticFLists, List>? fLists, ]) { - outliersValues.clear(); + _resetDataSourceHolders(); super.updateDataPoints( removedIndexes, addedIndexes, @@ -371,8 +380,10 @@ class BoxAndWhiskerSeriesRenderer } for (int i = 0; i < dataCount; i++) { - final CartesianChartPoint point = - CartesianChartPoint(x: xRawValues[i], xValue: xValues[i]); + final CartesianChartPoint point = CartesianChartPoint( + x: xRawValues[i], + xValue: xValues[i], + ); chartPoints.add(point); } } @@ -531,8 +542,11 @@ class BoxAndWhiskerSeriesRenderer : alignment; } - void _findBoxPlotValues(List yValues, BoxPlotMode mode, - BoxPlotQuartileValues boxPlotValues) { + void _findBoxPlotValues( + List yValues, + BoxPlotMode mode, + BoxPlotQuartileValues boxPlotValues, + ) { final int yCount = yValues.length; if (yCount == 0) { return; @@ -541,16 +555,28 @@ class BoxAndWhiskerSeriesRenderer boxPlotValues.average = (yValues.fold(0, (num x, num? y) => (x.toDouble()) + y!)) / yCount; if (mode == BoxPlotMode.exclusive) { - boxPlotValues.lowerQuartile = - _exclusiveQuartileValue(yValues, yCount, 0.25); - boxPlotValues.upperQuartile = - _exclusiveQuartileValue(yValues, yCount, 0.75); + boxPlotValues.lowerQuartile = _exclusiveQuartileValue( + yValues, + yCount, + 0.25, + ); + boxPlotValues.upperQuartile = _exclusiveQuartileValue( + yValues, + yCount, + 0.75, + ); boxPlotValues.median = _exclusiveQuartileValue(yValues, yCount, 0.5); } else if (mode == BoxPlotMode.inclusive) { - boxPlotValues.lowerQuartile = - _inclusiveQuartileValue(yValues, yCount, 0.25); - boxPlotValues.upperQuartile = - _inclusiveQuartileValue(yValues, yCount, 0.75); + boxPlotValues.lowerQuartile = _inclusiveQuartileValue( + yValues, + yCount, + 0.25, + ); + boxPlotValues.upperQuartile = _inclusiveQuartileValue( + yValues, + yCount, + 0.75, + ); boxPlotValues.median = _inclusiveQuartileValue(yValues, yCount, 0.5); } else { boxPlotValues.median = _median(yValues); @@ -574,7 +600,8 @@ class BoxAndWhiskerSeriesRenderer } else if (integerRank > count - 1) { value = yValues[count - 1]; } else { - value = fractionRank * (yValues[integerRank] - yValues[integerRank - 1]) + + value = + fractionRank * (yValues[integerRank] - yValues[integerRank - 1]) + yValues[integerRank - 1]; } return value.toDouble(); @@ -590,7 +617,8 @@ class BoxAndWhiskerSeriesRenderer final num rank = percentile * (count - 1); final int integerRank = rank.abs().floor(); final num fractionRank = rank - integerRank; - value = fractionRank * (yValues[integerRank + 1] - yValues[integerRank]) + + value = + fractionRank * (yValues[integerRank + 1] - yValues[integerRank]) + yValues[integerRank]; return value.toDouble(); } @@ -608,23 +636,32 @@ class BoxAndWhiskerSeriesRenderer .toDouble(); } - void _quartileValues(List yValues, int count, - BoxPlotQuartileValues boxPlotQuartileValues) { + void _quartileValues( + List yValues, + int count, + BoxPlotQuartileValues boxPlotQuartileValues, + ) { if (count == 1) { boxPlotQuartileValues.lowerQuartile = yValues[0].toDouble(); boxPlotQuartileValues.upperQuartile = yValues[0].toDouble(); } final int halfLength = count ~/ 2; final List lowerQuartileArray = yValues.sublist(0, halfLength); - final List upperQuartileArray = - yValues.sublist(count.isEven ? halfLength : halfLength + 1, count); + final List upperQuartileArray = yValues.sublist( + count.isEven ? halfLength : halfLength + 1, + count, + ); boxPlotQuartileValues.lowerQuartile = _median(lowerQuartileArray); boxPlotQuartileValues.upperQuartile = _median(upperQuartileArray); } - void _minMaxOutlier(List yValues, int count, - BoxPlotQuartileValues boxPlotQuartileValues) { - final double interQuartile = boxPlotQuartileValues.upperQuartile! - + void _minMaxOutlier( + List yValues, + int count, + BoxPlotQuartileValues boxPlotQuartileValues, + ) { + final double interQuartile = + boxPlotQuartileValues.upperQuartile! - boxPlotQuartileValues.lowerQuartile!; final num rangeIQR = 1.5 * interQuartile; for (int i = 0; i < count; i++) { @@ -657,10 +694,12 @@ class BoxAndWhiskerSeriesRenderer ? Colors.black : borderColor; updateSegmentColor(boxAndWhiskerSegment, customBorderColor, borderWidth); - updateSegmentGradient(boxAndWhiskerSegment, - gradientBounds: boxAndWhiskerSegment.segmentRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + boxAndWhiskerSegment, + gradientBounds: boxAndWhiskerSegment.segmentRect, + gradient: gradient, + borderGradient: borderGradient, + ); } @override @@ -717,7 +756,9 @@ class BoxAndWhiskerSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -752,8 +793,11 @@ class BoxAndWhiskerSegment extends ChartSegment { } } - _oldSegmentRect = - Rect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = Rect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldPoints.clear(); _oldSegmentRect = segmentRect; @@ -822,10 +866,12 @@ class BoxAndWhiskerSegment extends ChartSegment { _addMinMaxPoints(transformX, transformY, centerX, centerY, left, right); if (!median.isNaN) { - _medianLinePoints - .add(Offset(transformX(left, median), transformY(left, median))); - _medianLinePoints - .add(Offset(transformX(right, median), transformY(right, median))); + _medianLinePoints.add( + Offset(transformX(left, median), transformY(left, median)), + ); + _medianLinePoints.add( + Offset(transformX(right, median), transformY(right, median)), + ); } if (series.showMean && !mean.isNaN) { @@ -834,15 +880,19 @@ class BoxAndWhiskerSegment extends ChartSegment { final double markerHeight = series.markerSettings.height; final double markerWidth = series.markerSettings.width; - _meanLinePoints - .add(Offset(meanX + markerWidth / 2, meanY - markerHeight / 2)); - _meanLinePoints - .add(Offset(meanX - markerWidth / 2, meanY + markerHeight / 2)); - - _meanLinePoints - .add(Offset(meanX + markerWidth / 2, meanY + markerHeight / 2)); - _meanLinePoints - .add(Offset(meanX - markerWidth / 2, meanY - markerHeight / 2)); + _meanLinePoints.add( + Offset(meanX + markerWidth / 2, meanY - markerHeight / 2), + ); + _meanLinePoints.add( + Offset(meanX - markerWidth / 2, meanY + markerHeight / 2), + ); + + _meanLinePoints.add( + Offset(meanX + markerWidth / 2, meanY + markerHeight / 2), + ); + _meanLinePoints.add( + Offset(meanX - markerWidth / 2, meanY - markerHeight / 2), + ); } if (outliers != null && outliers!.isNotEmpty) { @@ -857,52 +907,75 @@ class BoxAndWhiskerSegment extends ChartSegment { } void _addMinMaxPoints( - PointToPixelCallback transformX, - PointToPixelCallback transformY, - double centerX, - double centerY, - num left, - num right) { + PointToPixelCallback transformX, + PointToPixelCallback transformY, + double centerX, + double centerY, + num left, + num right, + ) { if (!minimum.isNaN && !maximum.isNaN) { - final Offset maxStart = - Offset(transformX(left, maximum), transformY(left, maximum)); - final Offset maxEnd = - Offset(transformX(right, maximum), transformY(right, maximum)); + final Offset maxStart = Offset( + transformX(left, maximum), + transformY(left, maximum), + ); + final Offset maxEnd = Offset( + transformX(right, maximum), + transformY(right, maximum), + ); points.add(maxStart); points.add(maxEnd); - final Offset maxConnectorStart = - Offset(transformX(x, upperQuartile), transformY(x, upperQuartile)); - final Offset maxConnectorEnd = - Offset(transformX(x, maximum), transformY(x, maximum)); + final Offset maxConnectorStart = Offset( + transformX(x, upperQuartile), + transformY(x, upperQuartile), + ); + final Offset maxConnectorEnd = Offset( + transformX(x, maximum), + transformY(x, maximum), + ); points.add(maxConnectorStart); points.add(maxConnectorEnd); - final Offset minStart = - Offset(transformX(left, minimum), transformY(left, minimum)); - final Offset minEnd = - Offset(transformX(right, minimum), transformY(right, minimum)); + final Offset minStart = Offset( + transformX(left, minimum), + transformY(left, minimum), + ); + final Offset minEnd = Offset( + transformX(right, minimum), + transformY(right, minimum), + ); points.add(minStart); points.add(minEnd); - final Offset minConnectorStart = - Offset(transformX(x, lowerQuartile), transformY(x, lowerQuartile)); - final Offset minConnectorEnd = - Offset(transformX(x, minimum), transformY(x, minimum)); + final Offset minConnectorStart = Offset( + transformX(x, lowerQuartile), + transformY(x, lowerQuartile), + ); + final Offset minConnectorEnd = Offset( + transformX(x, minimum), + transformY(x, minimum), + ); points.add(minConnectorStart); points.add(minConnectorEnd); if (_oldPoints.isEmpty) { // Max points. - final Offset start = - Offset(transformX(left, centerY), transformY(left, centerY)); - final Offset end = - Offset(transformX(right, centerY), transformY(right, centerY)); + final Offset start = Offset( + transformX(left, centerY), + transformY(left, centerY), + ); + final Offset end = Offset( + transformX(right, centerY), + transformY(right, centerY), + ); _oldPoints.add(start); _oldPoints.add(end); - final Offset center = - Offset(transformX(centerX, centerY), transformY(centerX, centerY)); + final Offset center = Offset( + transformX(centerX, centerY), + transformY(centerX, centerY), + ); _oldPoints.add(center); _oldPoints.add(center); @@ -925,8 +998,11 @@ class BoxAndWhiskerSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = _outlierPoints.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(_outlierPoints[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + _outlierPoints[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -960,9 +1036,10 @@ class BoxAndWhiskerSegment extends ChartSegment { for (int i = 0; i < length; i++) { final ChartMarker marker = series.markerAt(i); final Rect outlierRect = Rect.fromCenter( - center: _outlierPoints[i], - width: marker.width, - height: marker.height); + center: _outlierPoints[i], + width: marker.width, + height: marker.height, + ); if (outlierRect.contains(position)) { outlierBounds = outlierRect; outlierIndex = i; @@ -984,9 +1061,10 @@ class BoxAndWhiskerSegment extends ChartSegment { if (points.isNotEmpty && points.length == 8) { primaryPos = secondaryPos = series.localToGlobal(points[3]); } else { - primaryPos = tooltipPosition == TooltipPosition.pointer - ? series.localToGlobal(position ?? segmentRect!.topCenter) - : series.localToGlobal(segmentRect!.topCenter); + primaryPos = + tooltipPosition == TooltipPosition.pointer + ? series.localToGlobal(position ?? segmentRect!.topCenter) + : series.localToGlobal(segmentRect!.topCenter); secondaryPos = primaryPos; } } @@ -994,9 +1072,10 @@ class BoxAndWhiskerSegment extends ChartSegment { primaryPosition: primaryPos, secondaryPosition: secondaryPos, text: series.tooltipText(chartPoint, outlierIndex), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -1018,8 +1097,10 @@ class BoxAndWhiskerSegment extends ChartSegment { if (points.isNotEmpty && points.length == 8) { primaryPos = points[3]; } else { - primaryPos = Offset(series.pointToPixelX(x, chartPoint.upperQuartile!), - series.pointToPixelY(x, chartPoint.upperQuartile!)); + primaryPos = Offset( + series.pointToPixelX(x, chartPoint.upperQuartile!), + series.pointToPixelY(x, chartPoint.upperQuartile!), + ); } return ChartTrackballInfo( @@ -1058,40 +1139,84 @@ class BoxAndWhiskerSegment extends ChartSegment { points.length == 8 && strokePaint.strokeWidth > 0 && strokePaint.color != Colors.transparent) { - final Offset? maxStart = - Offset.lerp(_oldPoints[0], points[0], animationFactor); - final Offset? maxEnd = - Offset.lerp(_oldPoints[1], points[1], animationFactor); + final Offset? maxStart = Offset.lerp( + _oldPoints[0], + points[0], + animationFactor, + ); + final Offset? maxEnd = Offset.lerp( + _oldPoints[1], + points[1], + animationFactor, + ); if (maxStart != null && maxEnd != null) { - drawDashes(canvas, series.dashArray, strokePaint, - start: maxStart, end: maxEnd); + drawDashes( + canvas, + series.dashArray, + strokePaint, + start: maxStart, + end: maxEnd, + ); } - final Offset? maxConnectorStart = - Offset.lerp(_oldPoints[2], points[2], animationFactor); - final Offset? maxConnectorEnd = - Offset.lerp(_oldPoints[3], points[3], animationFactor); + final Offset? maxConnectorStart = Offset.lerp( + _oldPoints[2], + points[2], + animationFactor, + ); + final Offset? maxConnectorEnd = Offset.lerp( + _oldPoints[3], + points[3], + animationFactor, + ); if (maxConnectorStart != null && maxConnectorEnd != null) { - drawDashes(canvas, series.dashArray, strokePaint, - start: maxConnectorStart, end: maxConnectorEnd); + drawDashes( + canvas, + series.dashArray, + strokePaint, + start: maxConnectorStart, + end: maxConnectorEnd, + ); } - final Offset? minStart = - Offset.lerp(_oldPoints[4], points[4], animationFactor); - final Offset? minEnd = - Offset.lerp(_oldPoints[5], points[5], animationFactor); + final Offset? minStart = Offset.lerp( + _oldPoints[4], + points[4], + animationFactor, + ); + final Offset? minEnd = Offset.lerp( + _oldPoints[5], + points[5], + animationFactor, + ); if (minStart != null && minEnd != null) { - drawDashes(canvas, series.dashArray, strokePaint, - start: minStart, end: minEnd); + drawDashes( + canvas, + series.dashArray, + strokePaint, + start: minStart, + end: minEnd, + ); } - final Offset? minConnectorStart = - Offset.lerp(_oldPoints[6], points[6], animationFactor); - final Offset? minConnectorEnd = - Offset.lerp(_oldPoints[7], points[7], animationFactor); + final Offset? minConnectorStart = Offset.lerp( + _oldPoints[6], + points[6], + animationFactor, + ); + final Offset? minConnectorEnd = Offset.lerp( + _oldPoints[7], + points[7], + animationFactor, + ); if (minConnectorStart != null && minConnectorEnd != null) { - drawDashes(canvas, series.dashArray, strokePaint, - start: minConnectorStart, end: minConnectorEnd); + drawDashes( + canvas, + series.dashArray, + strokePaint, + start: minConnectorStart, + end: minConnectorEnd, + ); } } @@ -1099,8 +1224,11 @@ class BoxAndWhiskerSegment extends ChartSegment { return; } - final Rect? paintRect = - Rect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final Rect? paintRect = Rect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRect == null) { return; } @@ -1113,13 +1241,20 @@ class BoxAndWhiskerSegment extends ChartSegment { final double strokeWidth = strokePaint.strokeWidth; if (strokeWidth > 0 && strokePaint.color != Colors.transparent) { final Path strokePath = strokePathFromRRect( - RRect.fromRectAndRadius(paintRect, Radius.zero), strokeWidth); + RRect.fromRectAndRadius(paintRect, Radius.zero), + strokeWidth, + ); drawDashes(canvas, series.dashArray, strokePaint, path: strokePath); } if (_medianLinePoints.isNotEmpty) { - drawDashes(canvas, series.dashArray, strokePaint, - start: _medianLinePoints[0], end: _medianLinePoints[1]); + drawDashes( + canvas, + series.dashArray, + strokePaint, + start: _medianLinePoints[0], + end: _medianLinePoints[1], + ); } if (animationFactor > 0.75 && _meanLinePoints.isNotEmpty) { @@ -1127,18 +1262,29 @@ class BoxAndWhiskerSegment extends ChartSegment { // only 0.25. So, 0.25 * 4 = 1.0. So, the animation factor is multiplied // by 4 to get the animation factor for mean line. final double opacity = (animationFactor - 0.75) * 4.0; - final Paint meanPaint = Paint() - ..color = strokePaint.color.withValues(alpha: opacity) - ..strokeWidth = strokePaint.strokeWidth - ..shader = strokePaint.shader - ..style = strokePaint.style - ..strokeCap = strokePaint.strokeCap - ..strokeJoin = strokePaint.strokeJoin - ..strokeMiterLimit = strokePaint.strokeMiterLimit; - drawDashes(canvas, series.dashArray, meanPaint, - start: _meanLinePoints[0], end: _meanLinePoints[1]); - drawDashes(canvas, series.dashArray, meanPaint, - start: _meanLinePoints[2], end: _meanLinePoints[3]); + final Paint meanPaint = + Paint() + ..color = strokePaint.color.withValues(alpha: opacity) + ..strokeWidth = strokePaint.strokeWidth + ..shader = strokePaint.shader + ..style = strokePaint.style + ..strokeCap = strokePaint.strokeCap + ..strokeJoin = strokePaint.strokeJoin + ..strokeMiterLimit = strokePaint.strokeMiterLimit; + drawDashes( + canvas, + series.dashArray, + meanPaint, + start: _meanLinePoints[0], + end: _meanLinePoints[1], + ); + drawDashes( + canvas, + series.dashArray, + meanPaint, + start: _meanLinePoints[2], + end: _meanLinePoints[3], + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/bubble_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/bubble_series.dart index 16a1531a1..fe16a9b32 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/bubble_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/bubble_series.dart @@ -166,7 +166,9 @@ class BubbleSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, BubbleSeriesRenderer renderObject) { + BuildContext context, + BubbleSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..maximumRadius = maximumRadius @@ -187,8 +189,10 @@ class BubbleSeriesRenderer extends XyDataSeriesRenderer set maximumRadius(double value) { if (_maximumRadius != value) { _maximumRadius = value; - assert(_maximumRadius >= 0, - 'The maximum radius should be greater than or equal to 0.'); + assert( + _maximumRadius >= 0, + 'The maximum radius should be greater than or equal to 0.', + ); canUpdateOrCreateSegments = true; markNeedsLayout(); } @@ -199,8 +203,10 @@ class BubbleSeriesRenderer extends XyDataSeriesRenderer set minimumRadius(double value) { if (_minimumRadius != value) { _minimumRadius = value; - assert(_minimumRadius >= 0, - 'The minimum radius should be greater than or equal to 0.'); + assert( + _minimumRadius >= 0, + 'The minimum radius should be greater than or equal to 0.', + ); canUpdateOrCreateSegments = true; markNeedsLayout(); } @@ -312,9 +318,7 @@ class BubbleSeriesRenderer extends XyDataSeriesRenderer }) { if (yLists == null) { yLists = >[_sizes]; - positions = [ - ChartDataPointType.bubbleSize, - ]; + positions = [ChartDataPointType.bubbleSize]; } else { yLists.add(_sizes); positions!.add(ChartDataPointType.bubbleSize); @@ -365,10 +369,12 @@ class BubbleSeriesRenderer extends XyDataSeriesRenderer void customizeSegment(ChartSegment segment) { final BubbleSegment bubbleSegment = segment as BubbleSegment; updateSegmentColor(bubbleSegment, borderColor, borderWidth); - updateSegmentGradient(bubbleSegment, - gradientBounds: bubbleSegment.segmentRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + bubbleSegment, + gradientBounds: bubbleSegment.segmentRect, + gradient: gradient, + borderGradient: borderGradient, + ); } @override @@ -423,19 +429,28 @@ class BubbleSeriesRenderer extends XyDataSeriesRenderer translationY = -margin.top - size.height / 2; } return translateTransform( - current.x!, current.y!, translationX, translationY); + current.x!, + current.y!, + translationX, + translationY, + ); case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: final BubbleSegment segment = segments[current.dataPointIndex] as BubbleSegment; translationX = -margin.left; - translationY = -(segment.radius + - dataLabelPadding + - size.height + - margin.vertical); + translationY = + -(segment.radius + + dataLabelPadding + + size.height + + margin.vertical); return translateTransform( - current.x!, current.y!, translationX, translationY); + current.x!, + current.y!, + translationX, + translationY, + ); case ChartDataLabelAlignment.bottom: final BubbleSegment segment = @@ -443,7 +458,11 @@ class BubbleSeriesRenderer extends XyDataSeriesRenderer translationX = -margin.left; translationY = segment.radius + dataLabelPadding; return translateTransform( - current.x!, current.y!, translationX, translationY); + current.x!, + current.y!, + translationX, + translationY, + ); } } @@ -473,7 +492,9 @@ class BubbleSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -481,8 +502,11 @@ class BubbleSegment extends ChartSegment { } if (series.animationDuration > 0) { - _oldSegmentRect = - Rect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = Rect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -529,9 +553,10 @@ class BubbleSegment extends ChartSegment { primaryPosition: series.localToGlobal(segmentRect!.topCenter), secondaryPosition: series.localToGlobal(segmentRect!.bottomCenter), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![currentSegmentIndex], point: chartPoint, series: series.widget, @@ -583,8 +608,11 @@ class BubbleSegment extends ChartSegment { if (segmentRect == null) { return; } - final Rect? paintRect = - Rect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final Rect? paintRect = Rect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRect == null || paintRect.isEmpty) { return; } @@ -597,8 +625,8 @@ class BubbleSegment extends ChartSegment { paint = getStrokePaint(); final double strokeWidth = paint.strokeWidth; if (paint.color != Colors.transparent && strokeWidth > 0) { - final Path strokePath = Path() - ..addOval(paintRect.deflate(strokeWidth / 2)); + final Path strokePath = + Path()..addOval(paintRect.deflate(strokeWidth / 2)); drawDashes(canvas, series.dashArray, paint, path: strokePath); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/candle_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/candle_series.dart index 9b5092865..60f30aa08 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/candle_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/candle_series.dart @@ -103,7 +103,9 @@ class CandleSeries extends FinancialSeriesBase { @override void updateRenderObject( - BuildContext context, CandleSeriesRenderer renderObject) { + BuildContext context, + CandleSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.borderRadius = borderRadius; } @@ -200,21 +202,32 @@ class CandleSeriesRenderer extends FinancialSeriesRendererBase late Color color; if (enableSolidCandles) { color = isHollow ? bullColor : bearColor; - final Color? segmentColor = pointColorMapper != null && - pointColors[segment.currentSegmentIndex] != null - ? null - : color; - updateSegmentColor(segment, segmentColor, borderWidth, - fillColor: segmentColor, isLineType: true); + final Color? segmentColor = + pointColorMapper != null && + pointColors[segment.currentSegmentIndex] != null + ? null + : color; + updateSegmentColor( + segment, + segmentColor, + borderWidth, + fillColor: segmentColor, + isLineType: true, + ); } else { color = isBull ? bullColor : bearColor; - final Color? segmentColor = pointColorMapper != null && - pointColors[segment.currentSegmentIndex] != null - ? null - : color; - updateSegmentColor(segment, segmentColor, borderWidth, - fillColor: isHollow ? Colors.transparent : segmentColor, - isLineType: true); + final Color? segmentColor = + pointColorMapper != null && + pointColors[segment.currentSegmentIndex] != null + ? null + : color; + updateSegmentColor( + segment, + segmentColor, + borderWidth, + fillColor: isHollow ? Colors.transparent : segmentColor, + isLineType: true, + ); } updateSegmentGradient(segment); } @@ -250,7 +263,9 @@ class CandleSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -285,8 +300,11 @@ class CandleSegment extends ChartSegment { } } - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldPoints.clear(); _oldSegmentRect = segmentRect; @@ -354,12 +372,15 @@ class CandleSegment extends ChartSegment { points.add(Offset(transformX(centerX, low), transformY(centerX, low))); points.add( - Offset(transformX(centerX, bottom), transformY(centerX, bottom))); + Offset(transformX(centerX, bottom), transformY(centerX, bottom)), + ); } if (_oldPoints.isEmpty) { - final Offset point = - Offset(transformX(centerX, centerY), transformY(centerX, centerY)); + final Offset point = Offset( + transformX(centerX, centerY), + transformY(centerX, centerY), + ); _oldPoints.add(point); _oldPoints.add(point); _oldPoints.add(point); @@ -405,9 +426,10 @@ class CandleSegment extends ChartSegment { primaryPosition: primaryPos, secondaryPosition: secondaryPos, text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -428,10 +450,14 @@ class CandleSegment extends ChartSegment { Offset preferredPos; if (points.isNotEmpty) { preferredPos = Offset( - series.pointToPixelX(x, high), series.pointToPixelY(x, high)); + series.pointToPixelX(x, high), + series.pointToPixelY(x, high), + ); } else { - preferredPos = - Offset(series.pointToPixelX(x, top), series.pointToPixelX(x, top)); + preferredPos = Offset( + series.pointToPixelX(x, top), + series.pointToPixelX(x, top), + ); } return ChartTrackballInfo( position: preferredPos, @@ -445,9 +471,10 @@ class CandleSegment extends ChartSegment { pointIndex: pointIndex, text: series.trackballText(chartPoint, series.name), header: series.tooltipHeaderText(chartPoint), - color: fillPaint.color == Colors.transparent - ? strokePaint.color - : fillPaint.color, + color: + fillPaint.color == Colors.transparent + ? strokePaint.color + : fillPaint.color, ); } return null; @@ -472,8 +499,11 @@ class CandleSegment extends ChartSegment { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); Paint paint = getFillPaint(); if (paint.color != Colors.transparent && !_isSameValue) { canvas.drawRRect(paintRRect!, paint); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/chart_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/chart_series.dart index ae7281a14..e863cbf11 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/chart_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/chart_series.dart @@ -38,11 +38,7 @@ import '../utils/renderer_helper.dart'; import '../utils/typedef.dart'; import 'waterfall_series.dart'; -enum SeriesSlot { - trendline, - marker, - dataLabel, -} +enum SeriesSlot { trendline, marker, dataLabel } class ChartSeriesParentData extends ContainerBoxParentData {} @@ -748,7 +744,9 @@ abstract class ChartSeries @mustCallSuper @override void updateRenderObject( - BuildContext context, ChartSeriesRenderer renderObject) { + BuildContext context, + ChartSeriesRenderer renderObject, + ) { renderObject ..xValueMapper = xValueMapper ..dataSource = dataSource @@ -779,11 +777,7 @@ abstract class ChartSeries } } -enum AnimationType { - loading, - realtime, - none, -} +enum AnimationType { loading, realtime, none } /// Creates a series renderer for chart series. abstract class ChartSeriesRenderer extends RenderBox @@ -1078,12 +1072,14 @@ abstract class ChartSeriesRenderer extends RenderBox SelectionBehavior? _selectionBehavior; set selectionBehavior(SelectionBehavior? value) { if (_selectionBehavior != value) { - _selectionBehavior?.selectionController - ?.removeListener(_handleSelectionControllerChange); + _selectionBehavior?.selectionController?.removeListener( + _handleSelectionControllerChange, + ); _selectionBehavior = value; _effectiveSelectionBehavior = value; - _selectionBehavior?.selectionController - ?.addListener(_handleSelectionControllerChange); + _selectionBehavior?.selectionController?.addListener( + _handleSelectionControllerChange, + ); if (_selectionEnabled) { _initSelection(); } else { @@ -1220,35 +1216,6 @@ abstract class ChartSeriesRenderer extends RenderBox } } - @override - List? buildLegendItems(int index) { - if (isVisibleInLegend) { - final LegendItem legendItem = ChartLegendItem( - text: legendItemText ?? name, - iconType: toLegendShapeMarkerType(legendIconType, this), - iconColor: legendIconColor(), - iconBorderColor: legendIconBorderColor(), - iconBorderWidth: legendIconBorderWidth(), - series: this, - seriesIndex: index, - pointIndex: 0, - isToggled: _isToggled(), - shader: legendIconShader(), - overlayMarkerType: markerSettings.isVisible - ? toShapeMarkerType(markerSettings.shape) - : null, - imageProvider: legendIconType == LegendIconType.image - ? parent?.legend?.image - : null, - onTap: handleLegendItemTapped, - onRender: _handleLegendItemCreated, - ); - return [legendItem]; - } else { - return null; - } - } - bool _isToggled() { return true; } @@ -1280,9 +1247,11 @@ abstract class ChartSeriesRenderer extends RenderBox @protected void handleLegendItemTapped(LegendItem item, bool isToggled) { if (parent != null && parent!.onLegendTapped != null) { - final ChartLegendItem legendItem = item as ChartLegendItem; final LegendTapArgs args = LegendTapArgs( - legendItem.series, legendItem.seriesIndex, legendItem.pointIndex); + item.series, + item.seriesIndex, + item.pointIndex, + ); parent!.onLegendTapped!(args); } parent!.behaviorArea?.hideInteractiveTooltip(); @@ -1290,7 +1259,7 @@ abstract class ChartSeriesRenderer extends RenderBox void _handleLegendItemCreated(ItemRendererDetails details) { if (parent != null && parent!.onLegendItemRender != null) { - final ChartLegendItem item = details.item as ChartLegendItem; + final LegendItem item = details.item; final LegendIconType iconType = toLegendIconType(details.iconType); final LegendRenderArgs args = LegendRenderArgs(item.seriesIndex, item.pointIndex) @@ -1300,7 +1269,9 @@ abstract class ChartSeriesRenderer extends RenderBox parent!.onLegendItemRender!(args); if (args.legendIconType != iconType) { details.iconType = toLegendShapeMarkerType( - args.legendIconType ?? LegendIconType.seriesType, this); + args.legendIconType ?? LegendIconType.seriesType, + this, + ); } details @@ -1332,8 +1303,9 @@ abstract class ChartSeriesRenderer extends RenderBox ..dispose(); _animation = null; - _selectionBehavior?.selectionController - ?.removeListener(_handleSelectionControllerChange); + _selectionBehavior?.selectionController?.removeListener( + _handleSelectionControllerChange, + ); _markerAnimationController?.dispose(); _markerAnimationController = null; _markerAnimation?.dispose(); @@ -1378,8 +1350,9 @@ abstract class ChartSeriesRenderer extends RenderBox ..addStatusListener(_handleAnimationStatusChange); _animationController!.duration = Duration(milliseconds: duration); _animation ??= CurvedAnimation( - parent: _animationController!, curve: Interval(curveStart, curveEnd)) - ..addListener(_handleAnimationUpdate); + parent: _animationController!, + curve: Interval(curveStart, curveEnd), + )..addListener(_handleAnimationUpdate); final double defaultElementAnimationValue = (animationDuration == 0 || animationType == AnimationType.none) @@ -1398,8 +1371,9 @@ abstract class ChartSeriesRenderer extends RenderBox curveStart = curveEnd; curveEnd = curveStart + dataLabelAnimationDuration; - _dataLabelAnimationController ??= - AnimationController(vsync: parent!.vsync!); + _dataLabelAnimationController ??= AnimationController( + vsync: parent!.vsync!, + ); _dataLabelAnimationController!.duration = Duration(milliseconds: duration); _dataLabelAnimationController!.value = defaultElementAnimationValue; _dataLabelAnimation ??= CurvedAnimation( @@ -1495,7 +1469,9 @@ abstract class ChartSeriesRenderer extends RenderBox } bool _canPopulateDataPoints( - List>? yPaths, List>? yLists) { + List>? yPaths, + List>? yLists, + ) { return dataSource != null && dataSource!.isNotEmpty && xValueMapper != null && @@ -1573,8 +1549,11 @@ abstract class ChartSeriesRenderer extends RenderBox _doSortingIfNeeded(chaoticYLists, yLists, chaoticFLists, fLists); } - void _addPointColorMapper(List>? fPaths, - List>? chaoticFLists, List>? fLists) { + void _addPointColorMapper( + List>? fPaths, + List>? chaoticFLists, + List>? fLists, + ) { if (fPaths != null && pointColorMapper != null) { fPaths.add(pointColorMapper!); if (sortingOrder == SortingOrder.none) { @@ -1587,8 +1566,11 @@ abstract class ChartSeriesRenderer extends RenderBox } } - void _addSortValueMapper(List>? fPaths, - List>? chaoticFLists, List>? fLists) { + void _addSortValueMapper( + List>? fPaths, + List>? chaoticFLists, + List>? fLists, + ) { if (fPaths != null && sortFieldValueMapper != null) { fPaths.add(sortFieldValueMapper!); if (sortingOrder == SortingOrder.none) { @@ -1677,10 +1659,11 @@ abstract class ChartSeriesRenderer extends RenderBox } void _doSortingIfNeeded( - List>? chaoticYLists, - List>? yLists, - List>? chaoticFLists, - List>? fLists) { + List>? chaoticYLists, + List>? yLists, + List>? chaoticFLists, + List>? fLists, + ) { if (sortingOrder != SortingOrder.none && chaoticYLists != null && chaoticYLists.isNotEmpty && @@ -1714,9 +1697,13 @@ abstract class ChartSeriesRenderer extends RenderBox } } - void _sort(List> chaoticYLists, List> yLists, - List>? chaoticFLists, List>? fLists, - {bool ascending = true}) { + void _sort( + List> chaoticYLists, + List> yLists, + List>? chaoticFLists, + List>? fLists, { + bool ascending = true, + }) { _computeSortedIndexes(ascending); if (sortedIndexes.isNotEmpty) { final void Function(int index, num xValue) copyX = @@ -1775,8 +1762,10 @@ abstract class ChartSeriesRenderer extends RenderBox for (int i = 0; i < length - 1; i++) { final int currentIndex = sortedIndexes[i]; final int nextIndex = sortedIndexes[i + 1]; - if (canSwap(_chaoticRawSortValues[nextIndex], - _chaoticRawSortValues[currentIndex])) { + if (canSwap( + _chaoticRawSortValues[nextIndex], + _chaoticRawSortValues[currentIndex], + )) { sortedIndexes[i] = nextIndex; sortedIndexes[i + 1] = currentIndex; swapped = true; @@ -1856,16 +1845,21 @@ abstract class ChartSeriesRenderer extends RenderBox } void updateSegmentColor( - ChartSegment segment, Color? borderColor, double borderWidth, - {Color? fillColor, bool isLineType = false}) { + ChartSegment segment, + Color? borderColor, + double borderWidth, { + Color? fillColor, + bool isLineType = false, + }) { Color color; Color strokeColor; double strokeWidth; final Color effColor = effectiveColor(segment.currentSegmentIndex); if (segment.isEmpty) { - color = (isLineType && emptyPointSettings.mode == EmptyPointMode.zero) - ? fillColor ?? effColor - : emptyPointSettings.color; + color = + (isLineType && emptyPointSettings.mode == EmptyPointMode.zero) + ? fillColor ?? effColor + : emptyPointSettings.color; // The purpose of isLineType is to set a default border color for // both line-type series and financial-type series. strokeColor = isLineType ? color : emptyPointSettings.borderColor; @@ -1966,7 +1960,8 @@ abstract class ChartSeriesRenderer extends RenderBox ); } - final bool hasTouchCallback = onPointLongPress != null || + final bool hasTouchCallback = + onPointLongPress != null || onPointTap != null || onPointDoubleTap != null; bool isSeriesHit = false; @@ -2000,10 +1995,14 @@ abstract class ChartSeriesRenderer extends RenderBox if (onPointTap != null && _interactiveSegment != null && _canInvokePointerUp) { - final int pointIndex = - dataPointIndex(localPosition, _interactiveSegment!); - final int segPointIndex = - segmentPointIndex(localPosition, _interactiveSegment!); + final int pointIndex = dataPointIndex( + localPosition, + _interactiveSegment!, + ); + final int segPointIndex = segmentPointIndex( + localPosition, + _interactiveSegment!, + ); final ChartPointDetails pointDetails = ChartPointDetails( index, viewportIndex(segPointIndex), @@ -2019,10 +2018,15 @@ abstract class ChartSeriesRenderer extends RenderBox final Offset localPosition = globalToLocal(details.position); if (parent != null && _interactiveSegment != null) { const bool hasSelection = false; - final bool hasTooltip = _tooltipEnabled && + final bool hasTooltip = + _tooltipEnabled && parent!.tooltipBehavior!.activationMode == ActivationMode.singleTap; - _handleCurrentInteraction(hasSelection, hasTooltip, localPosition, - kind: details.kind); + _handleCurrentInteraction( + hasSelection, + hasTooltip, + localPosition, + kind: details.kind, + ); } dataLabelContainer?.handlePointerHover(localPosition); trendlineContainer?.handlePointerHover(localPosition); @@ -2032,10 +2036,14 @@ abstract class ChartSeriesRenderer extends RenderBox _canInvokePointerUp = false; final Offset localPosition = globalToLocal(details.globalPosition); if (onPointLongPress != null && _interactiveSegment != null) { - final int pointIndex = - dataPointIndex(localPosition, _interactiveSegment!); - final int segPointIndex = - segmentPointIndex(localPosition, _interactiveSegment!); + final int pointIndex = dataPointIndex( + localPosition, + _interactiveSegment!, + ); + final int segPointIndex = segmentPointIndex( + localPosition, + _interactiveSegment!, + ); final ChartPointDetails pointDetails = ChartPointDetails( index, viewportIndex(segPointIndex), @@ -2046,9 +2054,11 @@ abstract class ChartSeriesRenderer extends RenderBox } if (parent != null && _interactiveSegment != null) { - final bool hasSelection = _selectionEnabled && + final bool hasSelection = + _selectionEnabled && parent!.selectionGesture == ActivationMode.longPress; - final bool hasTooltip = _tooltipEnabled && + final bool hasTooltip = + _tooltipEnabled && parent!.tooltipBehavior!.activationMode == ActivationMode.longPress; _handleCurrentInteraction(hasSelection, hasTooltip, localPosition); } @@ -2058,9 +2068,11 @@ abstract class ChartSeriesRenderer extends RenderBox void handleTapUp(TapUpDetails details) { final Offset localPosition = globalToLocal(details.globalPosition); if (parent != null && _interactiveSegment != null) { - final bool hasSelection = _selectionEnabled && + final bool hasSelection = + _selectionEnabled && parent!.selectionGesture == ActivationMode.singleTap; - final bool hasTooltip = _tooltipEnabled && + final bool hasTooltip = + _tooltipEnabled && parent!.tooltipBehavior!.activationMode == ActivationMode.singleTap; _handleCurrentInteraction(hasSelection, hasTooltip, localPosition); } @@ -2072,10 +2084,14 @@ abstract class ChartSeriesRenderer extends RenderBox void handleDoubleTap(Offset position) { final Offset localPosition = globalToLocal(position); if (onPointDoubleTap != null && _interactiveSegment != null) { - final int pointIndex = - dataPointIndex(localPosition, _interactiveSegment!); - final int segPointIndex = - segmentPointIndex(localPosition, _interactiveSegment!); + final int pointIndex = dataPointIndex( + localPosition, + _interactiveSegment!, + ); + final int segPointIndex = segmentPointIndex( + localPosition, + _interactiveSegment!, + ); final ChartPointDetails pointDetails = ChartPointDetails( index, viewportIndex(segPointIndex), @@ -2086,9 +2102,11 @@ abstract class ChartSeriesRenderer extends RenderBox } if (parent != null && _interactiveSegment != null) { - final bool hasSelection = _selectionEnabled && + final bool hasSelection = + _selectionEnabled && parent!.selectionGesture == ActivationMode.doubleTap; - final bool hasTooltip = _tooltipEnabled && + final bool hasTooltip = + _tooltipEnabled && parent!.tooltipBehavior!.activationMode == ActivationMode.doubleTap; _handleCurrentInteraction(hasSelection, hasTooltip, localPosition); } @@ -2141,8 +2159,11 @@ abstract class ChartSeriesRenderer extends RenderBox } void _handleCurrentInteraction( - bool hasSelection, bool hasTooltip, Offset position, - {PointerDeviceKind kind = PointerDeviceKind.touch}) { + bool hasSelection, + bool hasTooltip, + Offset position, { + PointerDeviceKind kind = PointerDeviceKind.touch, + }) { if (parent != null && _interactiveSegment != null) { if (hasSelection) { _updateSelectionToController( @@ -2197,8 +2218,11 @@ abstract class ChartSeriesRenderer extends RenderBox return null; } - void _updateSelectionToVisual(int seriesIndex, int segmentPointIndex, - {bool elected = false}) { + void _updateSelectionToVisual( + int seriesIndex, + int segmentPointIndex, { + bool elected = false, + }) { if (parent == null || selectionBehavior == null || !selectionBehavior!.enable) { @@ -2232,17 +2256,19 @@ abstract class ChartSeriesRenderer extends RenderBox void _invokeSelectionChangedCallback(int seriesIndex, int segmentPointIndex) { if (parent != null && parent!.onSelectionChanged != null) { - final SelectionArgs selectionArgs = SelectionArgs( - seriesRenderer: this, - seriesIndex: seriesIndex, - pointIndex: segmentPointIndex, - viewportPointIndex: viewportIndex(segmentPointIndex)) - ..selectedColor = selectionBehavior!.selectedColor - ..unselectedColor = selectionBehavior!.unselectedColor - ..selectedBorderColor = selectionBehavior!.selectedBorderColor - ..unselectedBorderColor = selectionBehavior!.unselectedBorderColor - ..selectedBorderWidth = selectionBehavior!.selectedBorderWidth - ..unselectedBorderWidth = selectionBehavior!.unselectedBorderWidth; + final SelectionArgs selectionArgs = + SelectionArgs( + seriesRenderer: this, + seriesIndex: seriesIndex, + pointIndex: segmentPointIndex, + viewportPointIndex: viewportIndex(segmentPointIndex), + ) + ..selectedColor = selectionBehavior!.selectedColor + ..unselectedColor = selectionBehavior!.unselectedColor + ..selectedBorderColor = selectionBehavior!.selectedBorderColor + ..unselectedBorderColor = selectionBehavior!.unselectedBorderColor + ..selectedBorderWidth = selectionBehavior!.selectedBorderWidth + ..unselectedBorderWidth = selectionBehavior!.unselectedBorderWidth; parent!.onSelectionChanged!(selectionArgs); _effectiveSelectionBehavior = selectionBehavior!.copyWith( selectedColor: selectionArgs.selectedColor, @@ -2341,9 +2367,12 @@ abstract class ChartSeriesRenderer extends RenderBox final List? base = parent?.selectionController.selectedDataPoints[index]; if (base != null) { - final List result = base - .where((element) => !effectiveSelectedIndexes.contains(element)) - .toList(); + final List result = + base + .where( + (element) => !effectiveSelectedIndexes.contains(element), + ) + .toList(); final int length = result.length; for (int i = 0; i < length; i++) { _updateSelectionToController( @@ -2472,7 +2501,9 @@ abstract class ChartSeriesRenderer extends RenderBox } void copyOldSegmentValues( - double animationFactor, double segmentAnimationFactor) { + double animationFactor, + double segmentAnimationFactor, + ) { for (int i = 0; i < segments.length; i++) { final ChartSegment segment = segments[i]; segment.copyOldSegmentValues(animationFactor, segmentAnimationFactor); @@ -2593,10 +2624,11 @@ abstract class ChartSegment { final Paint fillPaint = Paint()..isAntiAlias = true; /// Stroke paint of the segment. - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; /// Animation factor value. double animationFactor = 0.0; @@ -2617,7 +2649,9 @@ abstract class ChartSegment { bool isVisible = true; void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) {} + double seriesAnimationFactor, + double segmentAnimationFactor, + ) {} TooltipInfo? tooltipInfo({Offset? position, int? pointIndex}) => null; @@ -2834,10 +2868,16 @@ class ChartSeriesController { seriesRenderer.parent!.parentData! as BoxParentData; final Rect seriesBounds = seriesRenderer.paintBounds; position -= parentData.offset; - double xValue = seriesRenderer.xAxis! - .pixelToPoint(seriesBounds, position.dx, position.dy); - final num yValue = seriesRenderer.yAxis! - .pixelToPoint(seriesBounds, position.dx, position.dy); + double xValue = seriesRenderer.xAxis!.pixelToPoint( + seriesBounds, + position.dx, + position.dy, + ); + final num yValue = seriesRenderer.yAxis!.pixelToPoint( + seriesBounds, + position.dx, + position.dy, + ); if (seriesRenderer.xAxis is RenderCategoryAxis || seriesRenderer.xAxis is RenderDateTimeCategoryAxis) { @@ -3283,20 +3323,23 @@ abstract class CartesianSeries extends ChartSeries { case SeriesSlot.dataLabel: return dataLabelSettings.isVisible ? CartesianDataLabelContainer( - series: this, - dataSource: dataSource!, - mapper: dataLabelMapper, - builder: dataLabelSettings.builder, - settings: dataLabelSettings, - positions: positions, - ) + series: this, + dataSource: dataSource!, + mapper: dataLabelMapper, + builder: dataLabelSettings.builder, + settings: dataLabelSettings, + positions: positions, + ) : null; case SeriesSlot.marker: return markerSettings.isVisible // TODO(VijayakumarM): Check bang operator. ? MarkerContainer( - series: this, dataSource: dataSource!, settings: markerSettings) + series: this, + dataSource: dataSource!, + settings: markerSettings, + ) : null; case SeriesSlot.trendline: @@ -3327,7 +3370,9 @@ abstract class CartesianSeries extends ChartSeries { @override void updateRenderObject( - BuildContext context, CartesianSeriesRenderer renderObject) { + BuildContext context, + CartesianSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..xAxisName = xAxisName @@ -3480,8 +3525,36 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer bool isVisible() => controller.isVisible; @override - List? buildLegendItems(int index) { - final List? items = super.buildLegendItems(index); + List? buildLegendItems(int index) { + List? items = []; + if (isVisibleInLegend) { + final CartesianLegendItem legendItem = CartesianLegendItem( + text: legendItemText ?? name, + iconType: toLegendShapeMarkerType(legendIconType, this), + iconColor: legendIconColor(), + iconBorderColor: legendIconBorderColor(), + iconBorderWidth: legendIconBorderWidth(), + series: this, + seriesIndex: index, + pointIndex: 0, + isToggled: _isToggled(), + shader: legendIconShader(), + overlayMarkerType: + markerSettings.isVisible + ? toShapeMarkerType(markerSettings.shape) + : null, + imageProvider: + legendIconType == LegendIconType.image + ? parent?.legend?.image + : null, + onTap: handleLegendItemTapped, + onRender: _handleLegendItemCreated, + ); + items = [legendItem]; + } else { + items = null; + } + if (trendlineContainer != null && items != null) { items.addAll(trendlineContainer!.buildLegendItems(index, this)!); } @@ -3512,7 +3585,11 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer Shader? legendIconShader() { if (parent != null && parent!.legend != null) { final Rect legendIconBounds = Rect.fromLTWH( - 0.0, 0.0, parent!.legend!.iconWidth, parent!.legend!.iconHeight); + 0.0, + 0.0, + parent!.legend!.iconWidth, + parent!.legend!.iconHeight, + ); if (onCreateShader != null) { final ShaderDetails details = ShaderDetails(legendIconBounds, 'legend'); return onCreateShader?.call(details); @@ -3551,7 +3628,9 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer @override void copyOldSegmentValues( - double animationFactor, double segmentAnimationFactor) { + double animationFactor, + double segmentAnimationFactor, + ) { super.copyOldSegmentValues(animationFactor, segmentAnimationFactor); forceTransformValues = true; markNeedsLayout(); @@ -3731,8 +3810,10 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer for (int i = 0; i < dataCount; i++) { final num xValue = xValues[i]; - final CartesianChartPoint point = - CartesianChartPoint(x: xRawValues[i], xValue: xValue); + final CartesianChartPoint point = CartesianChartPoint( + x: xRawValues[i], + xValue: xValue, + ); for (int j = 0; j < yLength; j++) { point[positions[j]] = yLists[j][i]; } @@ -3747,7 +3828,8 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer axis.anchorRangeToVisiblePoints && plotArea != null && plotArea.zoomPanBehavior != null && - plotArea.zoomPanBehavior!.zoomMode == ZoomMode.x && + plotArea.behaviorArea != null && + plotArea.behaviorArea!.effectiveZoomMode == ZoomMode.x && _yVisibleRange != null) { return _yVisibleRange!.copyWith(); } @@ -3763,8 +3845,10 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer DoubleRange _trendlineRange(DoubleRange actualRange, RenderChartAxis axis) { num minimum = actualRange.minimum; num maximum = actualRange.maximum; - final DoubleRange trendlineRange = - trendlineContainer!.range(axis, actualRange); + final DoubleRange trendlineRange = trendlineContainer!.range( + axis, + actualRange, + ); minimum = min(minimum, trendlineRange.minimum); maximum = max(maximum, trendlineRange.maximum); @@ -3810,7 +3894,9 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer late DoubleRange range; if (xAxis is RenderLogarithmicAxis) { range = DoubleRange( - _valueAsPow(baseRange.minimum), _valueAsPow(baseRange.maximum)); + _valueAsPow(baseRange.minimum), + _valueAsPow(baseRange.maximum), + ); } else { range = baseRange; } @@ -3866,7 +3952,8 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer yAxis!.anchorRangeToVisiblePoints && plotArea != null && plotArea.zoomPanBehavior != null && - plotArea.zoomPanBehavior!.zoomMode == ZoomMode.x) { + plotArea.behaviorArea != null && + plotArea.behaviorArea!.effectiveZoomMode == ZoomMode.x) { final DoubleRange newYVisibleRange = _calculateYRange(); if (_yVisibleRange != newYVisibleRange) { _yVisibleRange = newYVisibleRange; @@ -3991,29 +4078,33 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = y.isNegative - ? -(markerWidthWithPadding + size.width + margin.horizontal) - : markerWidthWithPadding; + translationX = + y.isNegative + ? -(markerWidthWithPadding + size.width + margin.horizontal) + : markerWidthWithPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = y.isNegative - ? markerHeightWithPadding - : -(markerHeightWithPadding + size.height + margin.vertical); + translationY = + y.isNegative + ? markerHeightWithPadding + : -(markerHeightWithPadding + size.height + margin.vertical); } return translateTransform(current.x!, y, translationX, translationY); case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = y.isNegative - ? markerWidthWithPadding - : -(markerWidthWithPadding + size.width + margin.horizontal); + translationX = + y.isNegative + ? markerWidthWithPadding + : -(markerWidthWithPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = y.isNegative - ? -(markerHeightWithPadding + size.height + margin.vertical) - : markerHeightWithPadding; + translationY = + y.isNegative + ? -(markerHeightWithPadding + size.height + margin.vertical) + : markerHeightWithPadding; } return translateTransform(current.x!, y, translationX, translationY); @@ -4027,7 +4118,11 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer translationY = -margin.top - size.height / 2; } return translateTransform( - current.x!, current.y!, translationX, translationY); + current.x!, + current.y!, + translationX, + translationY, + ); } } @@ -4167,7 +4262,8 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer } segment.strokePaint.shader = borderGradient.createShader( - gradientBounds.deflate(segment.strokePaint.strokeWidth / 2)); + gradientBounds.deflate(segment.strokePaint.strokeWidth / 2), + ); } } } @@ -4217,8 +4313,14 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer parent != null && parent!.render == SeriesRender.trendline) { context.canvas.save(); - context.canvas.clipRect(clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed)); + context.canvas.clipRect( + clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ), + ); context.paintChild(trendlineContainer!, offset); context.canvas.restore(); } @@ -4302,21 +4404,29 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer textPainter.height + margin.vertical, ); RRect labelRect = RRect.fromRectAndRadius( - dataLabelRect, Radius.circular(dataLabelSettings.borderRadius)); + dataLabelRect, + Radius.circular(dataLabelSettings.borderRadius), + ); // To check and update the label rect and offset by rotated // label rect height overlaps with plotArea or not. if (angle != 0) { - final Rect rotatedBounds = - calculateRotatedBounds(dataLabelRect, dataLabelSettings.angle); + final Rect rotatedBounds = calculateRotatedBounds( + dataLabelRect, + dataLabelSettings.angle, + ); final double heightFromCenter = rotatedBounds.height / 2; if (paintBounds.bottom < labelRect.center.dy + heightFromCenter) { - labelRect = - _rotatedRRect(labelRect, labelRect.bottom - heightFromCenter); + labelRect = _rotatedRRect( + labelRect, + labelRect.bottom - heightFromCenter, + ); offset = Offset(labelRect.left, labelRect.top); } if (paintBounds.top > labelRect.center.dy - heightFromCenter) { - labelRect = - _rotatedRRect(labelRect, labelRect.top + heightFromCenter); + labelRect = _rotatedRRect( + labelRect, + labelRect.top + heightFromCenter, + ); offset = Offset(labelRect.left, labelRect.top); } } @@ -4350,11 +4460,13 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer RRect _rotatedRRect(RRect labelRect, double labelY) { return RRect.fromRectAndRadius( - Rect.fromCenter( - center: Offset(labelRect.center.dx, labelY), - width: labelRect.width, - height: labelRect.height), - Radius.circular(dataLabelSettings.borderRadius)); + Rect.fromCenter( + center: Offset(labelRect.center.dx, labelY), + width: labelRect.width, + height: labelRect.height, + ), + Radius.circular(dataLabelSettings.borderRadius), + ); } /// To customize each data labels. @@ -4377,10 +4489,14 @@ abstract class CartesianSeriesRenderer extends ChartSeriesRenderer textPainter.layout(); canvas.save(); canvas.translate( - pointX + textPainter.width / 2, pointY + textPainter.height / 2); + pointX + textPainter.width / 2, + pointY + textPainter.height / 2, + ); canvas.rotate(degreeToRadian(angle)); - final Offset labelOffset = - Offset(-textPainter.width / 2, -textPainter.height / 2); + final Offset labelOffset = Offset( + -textPainter.width / 2, + -textPainter.height / 2, + ); textPainter.paint(canvas, labelOffset); canvas.restore(); } @@ -4487,9 +4603,10 @@ mixin ContinuousSeriesMixin on CartesianSeriesRenderer { final int length = segment.points.length; for (int i = 0; i < length; i++) { final Rect bounds = Rect.fromCenter( - center: segment.points[i], - width: tooltipPadding, - height: tooltipPadding); + center: segment.points[i], + width: tooltipPadding, + height: tooltipPadding, + ); if (bounds.contains(position)) { return i; } @@ -4529,7 +4646,11 @@ mixin RealTimeUpdateMixin on ChartSeriesRenderer { List>? chaoticFLists, List>? fLists, ]) { - if (!_canPopulateDataPoints(yPaths, chaoticYLists)) { + if (xValueMapper == null || + yPaths == null || + yPaths.isEmpty || + chaoticYLists == null || + chaoticYLists.isEmpty) { return; } @@ -4542,18 +4663,39 @@ mixin RealTimeUpdateMixin on ChartSeriesRenderer { _addSortValueMapper(fPaths, chaoticFLists, fLists); if (removedIndexes != null) { - _removeDataPoints(removedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _removeDataPoints( + removedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } if (addedIndexes != null) { - _addDataPoints(addedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _addDataPoints( + addedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } if (replacedIndexes != null) { - _replaceDataPoints(replacedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _replaceDataPoints( + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } createOrUpdateSegments(); @@ -4572,7 +4714,11 @@ mixin RealTimeUpdateMixin on ChartSeriesRenderer { ) { final int chaoticYLength = chaoticYLists?.length ?? 0; final int fPathLength = fPaths?.length ?? 0; - for (final int index in indexes) { + // Sort 'indexes' in descending order to remove higher indexes first, + // preventing shifting issues when removing lower ones. + final List sortedIndexes = List.from(indexes) + ..sort((a, b) => b.compareTo(a)); + for (final int index in sortedIndexes) { _removeXValueAt(index); _removeRawSortValueAt(index); for (int i = 0; i < chaoticYLength; i++) { @@ -4597,8 +4743,15 @@ mixin RealTimeUpdateMixin on ChartSeriesRenderer { _dataCount = _chaoticXValues.length; // Collecting previous and next index to update them. final List mutableIndexes = _findMutableIndexes(indexes); - _replaceDataPoints(mutableIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _replaceDataPoints( + mutableIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } void _addDataPoints( @@ -4719,8 +4872,9 @@ mixin RealTimeUpdateMixin on ChartSeriesRenderer { if (_callbacksEnabled) { final List positions = widget.positions; - final ChartPoint point = - ChartPoint(x: _chaoticRawXValues[index]); + final ChartPoint point = ChartPoint( + x: _chaoticRawXValues[index], + ); for (int j = 0; j < yPathLength; j++) { point[positions[j]] = chaoticYLists![j][index]; } @@ -4803,18 +4957,39 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { _addSortValueMapper(fPaths, chaoticFLists, fLists); if (removedIndexes != null) { - _removeDataPoints(removedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _removeDataPoints( + removedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } if (addedIndexes != null) { - _addDataPoints(addedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _addDataPoints( + addedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } if (replacedIndexes != null) { - _replaceDataPoints(replacedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _replaceDataPoints( + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } _applyEmptyPointModeIfNeeded(chaoticYLists); @@ -4822,7 +4997,11 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { final DoubleRange xRange = _findMinMaxXRange(xValues); final DoubleRange yRange = _findMinMaxYRange(chaoticYLists); _updateAxisRange( - xRange.minimum, xRange.maximum, yRange.minimum, yRange.maximum); + xRange.minimum, + xRange.maximum, + yRange.minimum, + yRange.maximum, + ); computeNonEmptyYValues(); _populateTrendlineDataSource(); _updateXValuesForCategoryTypeAxes(); @@ -4855,7 +5034,11 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { // continuous series. final int chaoticYLength = chaoticYLists?.length ?? 0; final int fPathLength = fPaths?.length ?? 0; - for (final int index in indexes) { + // Sort 'indexes' in descending order to remove higher indexes first, + // preventing shifting issues when removing lower ones. + final List sortedIndexes = List.from(indexes) + ..sort((a, b) => b.compareTo(a)); + for (final int index in sortedIndexes) { if (index < 0 || index >= _dataCount) { continue; } @@ -4882,8 +5065,15 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { _dataCount = _chaoticXValues.length; // Collecting previous and next index to update them. final List mutableIndexes = _findMutableIndexes(indexes); - _replaceDataPoints(mutableIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _replaceDataPoints( + mutableIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } void _addDataPoints( @@ -4959,7 +5149,9 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { final List positions = widget.positions; final num xValue = _chaoticXValues[index]; final CartesianChartPoint point = CartesianChartPoint( - x: _chaoticRawXValues[index], xValue: xValue); + x: _chaoticRawXValues[index], + xValue: xValue, + ); for (int j = 0; j < yPathLength; j++) { point[positions[j]] = chaoticYLists![j][index]; } @@ -4977,7 +5169,11 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { } void _updateAxisRange( - num xMinimum, num xMaximum, num yMinimum, num yMaximum) { + num xMinimum, + num xMaximum, + num yMinimum, + num yMaximum, + ) { if ((xMin.isInfinite && xMinimum.isFinite) || xMinimum != xMin) { xMin = xMinimum; _isXRangeChanged = true; @@ -5079,7 +5275,9 @@ mixin CartesianRealTimeUpdateMixin on CartesianSeriesRenderer { final List positions = widget.positions; final num xValue = _chaoticXValues[index]; final CartesianChartPoint point = CartesianChartPoint( - x: _chaoticRawXValues[index], xValue: xValue); + x: _chaoticRawXValues[index], + xValue: xValue, + ); for (int j = 0; j < yPathLength; j++) { point[positions[j]] = chaoticYLists![j][index]; } @@ -5218,8 +5416,10 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { double get spacing => _spacing; double _spacing = 0; set spacing(double value) { - assert(value >= 0 && value <= 1, - 'The spacing of the series should be between 0 and 1'); + assert( + value >= 0 && value <= 1, + 'The spacing of the series should be between 0 and 1', + ); if (value != _spacing) { _spacing = value; } @@ -5228,8 +5428,10 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { double get width => _width; double _width = 0.7; set width(double value) { - assert(value >= 0 && value <= 1, - 'The width of the series should be between 0 and 1'); + assert( + value >= 0 && value <= 1, + 'The width of the series should be between 0 and 1', + ); if (value != _width) { _width = value; } @@ -5262,7 +5464,13 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { List>? fLists, ]) { super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); if (dataCount < 1) { return; @@ -5290,8 +5498,9 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { DateTime? minDate; num? minimumInSeconds; if (xAxis is RenderDateTimeAxis) { - minDate = - DateTime.fromMillisecondsSinceEpoch(_sortedXValues[0]! as int); + minDate = DateTime.fromMillisecondsSinceEpoch( + _sortedXValues[0]! as int, + ); minDate = minDate.subtract(const Duration(days: 1)); minimumInSeconds = minDate.millisecondsSinceEpoch; } @@ -5342,7 +5551,8 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { axis.anchorRangeToVisiblePoints && plotArea != null && plotArea.zoomPanBehavior != null && - plotArea.zoomPanBehavior!.zoomMode == ZoomMode.x && + plotArea.behaviorArea != null && + plotArea.behaviorArea!.effectiveZoomMode == ZoomMode.x && _yVisibleRange != null) { return _yVisibleRange!.copyWith(); } @@ -5356,8 +5566,12 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } @nonVirtual - void updateSegmentTrackerStyle(ChartSegment segment, Color trackColor, - Color trackBorderColor, double trackBorderWidth) { + void updateSegmentTrackerStyle( + ChartSegment segment, + Color trackColor, + Color trackBorderColor, + double trackBorderWidth, + ) { if (segment is BarSeriesTrackerMixin) { segment.trackerFillPaint.color = trackColor; segment.trackerStrokePaint @@ -5410,8 +5624,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { final num x = current.x! + (sbsInfo.maximum + sbsInfo.minimum) / 2; num y = current.y!; switch (current.position) { @@ -5421,8 +5638,13 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } else if (alignment == ChartDataLabelAlignment.middle) { y = (y + _bottom) / 2; } - return _calculateYPosition(x, y, alignment, size, - isNegative: current.y!.isNegative); + return _calculateYPosition( + x, + y, + alignment, + size, + isNegative: current.y!.isNegative, + ); case ChartDataPointType.high: return _calculateHighPosition(x, y, alignment, size); @@ -5453,8 +5675,12 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateYPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size, - {bool isNegative = false}) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, { + bool isNegative = false, + }) { final EdgeInsets margin = dataLabelSettings.margin; double translationX = 0.0; double translationY = 0.0; @@ -5463,29 +5689,33 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.width + margin.horizontal); + translationX = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? -(dataLabelPadding + size.height + margin.vertical) - : dataLabelPadding; + translationY = + isNegative + ? -(dataLabelPadding + size.height + margin.vertical) + : dataLabelPadding; } return translateTransform(x, y, translationX, translationY); @@ -5503,7 +5733,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateHighPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -5517,7 +5751,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateLowPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -5531,7 +5769,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateDataLabelOpenPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -5545,7 +5787,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateDataLabelClosePosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -5559,7 +5805,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateMedianPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -5573,7 +5823,11 @@ mixin SbsSeriesMixin on CartesianSeriesRenderer { } Offset _calculateOutlierPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -5610,9 +5864,10 @@ mixin BarSeriesTrackerMixin on ChartSegment { final Paint trackerFillPaint = Paint()..isAntiAlias = true; /// Stroke paint of the tracker segment. - final Paint trackerStrokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint trackerStrokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; RRect? _trackerRect; @@ -5807,8 +6062,9 @@ abstract class XyDataSeries extends CartesianSeries { final ChartValueMapper? yValueMapper; @override - List get positions => - [ChartDataPointType.y]; + List get positions => [ + ChartDataPointType.y, + ]; @override XyDataSeriesRenderer createRenderObject(BuildContext context) { @@ -5820,7 +6076,9 @@ abstract class XyDataSeries extends CartesianSeries { @override void updateRenderObject( - BuildContext context, XyDataSeriesRenderer renderObject) { + BuildContext context, + XyDataSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.yValueMapper = yValueMapper; } @@ -5872,7 +6130,13 @@ abstract class XyDataSeriesRenderer extends CartesianSeriesRenderer } super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); if (this is! WaterfallSeriesRenderer) { populateChartPoints(); } @@ -5906,8 +6170,17 @@ abstract class XyDataSeriesRenderer extends CartesianSeriesRenderer yLists?.add(yValues); } } - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } @override @@ -5942,8 +6215,10 @@ abstract class XyDataSeriesRenderer extends CartesianSeriesRenderer @override void _populateTrendlineDataSource() { - trendlineContainer?.populateDataSource(xValues, - seriesYValues: nonEmptyYValues); + trendlineContainer?.populateDataSource( + xValues, + seriesYValues: nonEmptyYValues, + ); } @override @@ -6167,7 +6442,9 @@ abstract class StackedSeriesBase extends XyDataSeries { @override void updateRenderObject( - BuildContext context, StackedSeriesRenderer renderObject) { + BuildContext context, + StackedSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..trackColor = trackColor @@ -6259,7 +6536,8 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer final List yValuesCopy = [...yValues]; _stackYValues = yValuesCopy; final String seriesType = series.runtimeType.toString().toLowerCase(); - final bool isStackedBar = seriesType.contains('stackedcolumn') || + final bool isStackedBar = + seriesType.contains('stackedcolumn') || seriesType.contains('stackedbar'); for (int i = 0; i < dataCount; i++) { if (_stackYValues[i].isNaN) { @@ -6318,8 +6596,14 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer negativeValues.add(_StackingInfo(groupName, {})); } - _computeStackedValues(current, currentPositiveStackInfo, positiveValues, - negativeValues, _isStacked100, groupName); + _computeStackedValues( + current, + currentPositiveStackInfo, + positiveValues, + negativeValues, + _isStacked100, + groupName, + ); if (previous != null) { current.prevSeriesYValues = previous.yValues; @@ -6342,7 +6626,8 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer final String seriesType = current.runtimeType.toString().toLowerCase(); final bool isStackedLine = seriesType.contains('stackedline'); final EmptyPointMode emptyPointMode = current.emptyPointSettings.mode; - final bool isDropOrGapMode = emptyPointMode == EmptyPointMode.drop || + final bool isDropOrGapMode = + emptyPointMode == EmptyPointMode.drop || emptyPointMode == EmptyPointMode.gap; final List actualYValues = [...current._stackYValues]; _StackingInfo? currentNegativeStackInfo; @@ -6466,8 +6751,9 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer } final String seriesType = current.runtimeType.toString().toLowerCase(); - final bool isContainsStackedArea100 = - seriesType.contains('stackedarea100'); + final bool isContainsStackedArea100 = seriesType.contains( + 'stackedarea100', + ); final String groupName = isContainsStackedArea100 ? 'stackedareagroup' : current.groupName; @@ -6579,7 +6865,13 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer List>? fLists, ]) { super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); /// Calculate [StackYValues] based on empty point modes with yValues. _applyDropOrGapEmptyPointModes(this); @@ -6629,7 +6921,15 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer dataLabel = formatNumericValue(value, yAxis); } super.drawDataLabelWithBackground( - index, canvas, dataLabel, offset, angle, style, fillPaint, strokePaint); + index, + canvas, + dataLabel, + offset, + angle, + style, + fillPaint, + strokePaint, + ); } @override @@ -6644,8 +6944,17 @@ abstract class StackedSeriesRenderer extends XyDataSeriesRenderer List>? chaoticFLists, List>? fLists, ]) { - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); /// Clear `stackedYLists` alone instead of resetting `YLists`. _resetStackedYLists(); @@ -6813,8 +7122,10 @@ abstract class RangeSeriesBase extends CartesianSeries { final Color borderColor; @override - List get positions => - [ChartDataPointType.high, ChartDataPointType.low]; + List get positions => [ + ChartDataPointType.high, + ChartDataPointType.low, + ]; @override RangeSeriesRendererBase createRenderObject(BuildContext context) { @@ -6827,7 +7138,9 @@ abstract class RangeSeriesBase extends CartesianSeries { @override void updateRenderObject( - BuildContext context, RangeSeriesRendererBase renderObject) { + BuildContext context, + RangeSeriesRendererBase renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.highValueMapper = highValueMapper; renderObject.lowValueMapper = lowValueMapper; @@ -6872,12 +7185,13 @@ abstract class RangeSeriesRendererBase if (highValueMapper != null && lowValueMapper != null) { if (sortingOrder == SortingOrder.none) { super.populateDataSource( - >[highValueMapper!, lowValueMapper!], - >[highValues, lowValues], - >[], - fPaths, - chaoticFLists, - fLists); + >[highValueMapper!, lowValueMapper!], + >[highValues, lowValues], + >[], + fPaths, + chaoticFLists, + fLists, + ); } else { super.populateDataSource( >[highValueMapper!, lowValueMapper!], @@ -6920,27 +7234,29 @@ abstract class RangeSeriesRendererBase if (highValueMapper != null && lowValueMapper != null) { if (sortingOrder == SortingOrder.none) { super.updateDataPoints( - removedIndexes, - addedIndexes, - replacedIndexes, - >[highValueMapper!, lowValueMapper!], - >[highValues, lowValues], - >[], - fPaths, - chaoticFLists, - fLists); + removedIndexes, + addedIndexes, + replacedIndexes, + >[highValueMapper!, lowValueMapper!], + >[highValues, lowValues], + >[], + fPaths, + chaoticFLists, + fLists, + ); } else { _resetYLists(); super.updateDataPoints( - removedIndexes, - addedIndexes, - replacedIndexes, - >[highValueMapper!, lowValueMapper!], - >[_chaoticHighValues, _chaoticLowValues], - >[highValues, lowValues], - fPaths, - chaoticFLists, - fLists); + removedIndexes, + addedIndexes, + replacedIndexes, + >[highValueMapper!, lowValueMapper!], + >[_chaoticHighValues, _chaoticLowValues], + >[highValues, lowValues], + fPaths, + chaoticFLists, + fLists, + ); } } @@ -7020,9 +7336,11 @@ abstract class RangeSeriesRendererBase @override void _populateTrendlineDataSource() { - trendlineContainer?.populateDataSource(xValues, - seriesHighValues: nonEmptyHighValues, - seriesLowValues: nonEmptyLowValues); + trendlineContainer?.populateDataSource( + xValues, + seriesHighValues: nonEmptyHighValues, + seriesLowValues: nonEmptyLowValues, + ); } @override @@ -7037,7 +7355,7 @@ abstract class RangeSeriesRendererBase yLists = >[highValues, lowValues]; positions = [ ChartDataPointType.high, - ChartDataPointType.low + ChartDataPointType.low, ]; } else { yLists.add(highValues); @@ -7081,8 +7399,11 @@ abstract class RangeSeriesRendererBase } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (current.position) { case ChartDataPointType.y: case ChartDataPointType.high: @@ -7091,15 +7412,24 @@ abstract class RangeSeriesRendererBase case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: return super.dataLabelPosition( - current, ChartDataLabelAlignment.outer, size); + current, + ChartDataLabelAlignment.outer, + size, + ); case ChartDataLabelAlignment.bottom: return super.dataLabelPosition( - current, ChartDataLabelAlignment.bottom, size); + current, + ChartDataLabelAlignment.bottom, + size, + ); case ChartDataLabelAlignment.middle: return super.dataLabelPosition( - current, ChartDataLabelAlignment.middle, size); + current, + ChartDataLabelAlignment.middle, + size, + ); } case ChartDataPointType.low: @@ -7108,15 +7438,24 @@ abstract class RangeSeriesRendererBase case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.bottom: return super.dataLabelPosition( - current, ChartDataLabelAlignment.bottom, size); + current, + ChartDataLabelAlignment.bottom, + size, + ); case ChartDataLabelAlignment.top: - return super - .dataLabelPosition(current, ChartDataLabelAlignment.top, size); + return super.dataLabelPosition( + current, + ChartDataLabelAlignment.top, + size, + ); case ChartDataLabelAlignment.middle: return super.dataLabelPosition( - current, ChartDataLabelAlignment.middle, size); + current, + ChartDataLabelAlignment.middle, + size, + ); } case ChartDataPointType.open: @@ -7254,11 +7593,11 @@ abstract class FinancialSeriesBase extends CartesianSeries { @override List get positions => [ - ChartDataPointType.high, - ChartDataPointType.low, - ChartDataPointType.open, - ChartDataPointType.close, - ]; + ChartDataPointType.high, + ChartDataPointType.low, + ChartDataPointType.open, + ChartDataPointType.close, + ]; @override FinancialSeriesRendererBase createRenderObject(BuildContext context) { @@ -7281,7 +7620,9 @@ abstract class FinancialSeriesBase extends CartesianSeries { @override void updateRenderObject( - BuildContext context, FinancialSeriesRendererBase renderObject) { + BuildContext context, + FinancialSeriesRendererBase renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..volumeValueMapper = volumeValueMapper @@ -7441,7 +7782,13 @@ abstract class FinancialSeriesRendererBase if (sortingOrder == SortingOrder.none) { super.populateDataSource( - mappers, finalYLists, >[], fPaths, chaoticFLists, fLists); + mappers, + finalYLists, + >[], + fPaths, + chaoticFLists, + fLists, + ); } else { super.populateDataSource( mappers, @@ -7520,26 +7867,36 @@ abstract class FinancialSeriesRendererBase ]; if (sortingOrder == SortingOrder.none) { - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - mappers, finalYLists, >[], fPaths, chaoticFLists, fLists); + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + mappers, + finalYLists, + >[], + fPaths, + chaoticFLists, + fLists, + ); } else { _resetYLists(); super.updateDataPoints( - removedIndexes, - addedIndexes, - replacedIndexes, - mappers, - >[ - _chaoticHighValues, - _chaoticLowValues, - _chaoticOpenValues, - _chaoticCloseValues, - if (volumeValueMapper != null) _chaoticVolumeValues, - ], - finalYLists, - fPaths, - chaoticFLists, - fLists); + removedIndexes, + addedIndexes, + replacedIndexes, + mappers, + >[ + _chaoticHighValues, + _chaoticLowValues, + _chaoticOpenValues, + _chaoticCloseValues, + if (volumeValueMapper != null) _chaoticVolumeValues, + ], + finalYLists, + fPaths, + chaoticFLists, + fLists, + ); } } @@ -7575,8 +7932,11 @@ abstract class FinancialSeriesRendererBase @override void _populateTrendlineDataSource() { - trendlineContainer?.populateDataSource(xValues, - seriesHighValues: highValues, seriesLowValues: lowValues); + trendlineContainer?.populateDataSource( + xValues, + seriesHighValues: highValues, + seriesLowValues: lowValues, + ); } @override @@ -7637,11 +7997,12 @@ abstract class FinancialSeriesRendererBase @override ChartDataLabelAlignment effectiveDataLabelAlignment( - ChartDataLabelAlignment alignment, - ChartDataPointType position, - ChartElementParentData? previous, - ChartElementParentData current, - ChartElementParentData? next) { + ChartDataLabelAlignment alignment, + ChartDataPointType position, + ChartElementParentData? previous, + ChartElementParentData current, + ChartElementParentData? next, + ) { final int index = current.dataPointIndex; if (position == ChartDataPointType.open) { final num open = openValues[index]; @@ -7664,45 +8025,74 @@ abstract class FinancialSeriesRendererBase @override Offset _calculateDataLabelOpenPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: case ChartDataLabelAlignment.middle: return _calculateOpenAndClosePosition( - x, y, ChartDataLabelAlignment.outer, size, ChartDataPointType.open); + x, + y, + ChartDataLabelAlignment.outer, + size, + ChartDataPointType.open, + ); case ChartDataLabelAlignment.bottom: return _calculateOpenAndClosePosition( - x, y, ChartDataLabelAlignment.top, size, ChartDataPointType.open); + x, + y, + ChartDataLabelAlignment.top, + size, + ChartDataPointType.open, + ); } } @protected Offset _calculateOpenAndClosePosition( - num x, - num y, - ChartDataLabelAlignment alignment, - Size size, - ChartDataPointType position) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ChartDataPointType position, + ) { return _calculateYPosition(x, y, alignment, size); } @override Offset _calculateDataLabelClosePosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: case ChartDataLabelAlignment.middle: - return _calculateOpenAndClosePosition(x, y, - ChartDataLabelAlignment.outer, size, ChartDataPointType.close); + return _calculateOpenAndClosePosition( + x, + y, + ChartDataLabelAlignment.outer, + size, + ChartDataPointType.close, + ); case ChartDataLabelAlignment.bottom: return _calculateOpenAndClosePosition( - x, y, ChartDataLabelAlignment.top, size, ChartDataPointType.close); + x, + y, + ChartDataLabelAlignment.top, + size, + ChartDataPointType.close, + ); } } @@ -8170,11 +8560,12 @@ abstract class CircularSeries extends ChartSeries { case SeriesSlot.dataLabel: return dataLabelSettings.isVisible ? CircularDataLabelContainer( - series: this, - dataSource: dataSource!, - mapper: dataLabelMapper, - builder: dataLabelSettings.builder, - settings: dataLabelSettings) + series: this, + dataSource: dataSource!, + mapper: dataLabelMapper, + builder: dataLabelSettings.builder, + settings: dataLabelSettings, + ) : null; case SeriesSlot.marker: @@ -8212,7 +8603,9 @@ abstract class CircularSeries extends ChartSeries { @override void updateRenderObject( - BuildContext context, CircularSeriesRenderer renderObject) { + BuildContext context, + CircularSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..yValueMapper = yValueMapper @@ -8600,18 +8993,20 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer // TODO(Preethika): Marked as public to access from pie series. ChartShaderDetails createShaderDetails() { - final Rect innerRect = - Rect.fromCircle(center: center, radius: currentInnerRadius); - final Rect outerRect = - Rect.fromCircle(center: center, radius: currentRadius); + final Rect innerRect = Rect.fromCircle( + center: center, + radius: currentInnerRadius, + ); + final Rect outerRect = Rect.fromCircle( + center: center, + radius: currentRadius, + ); return ChartShaderDetails(outerRect, innerRect, 'series'); } @override Iterable get children { - return [ - if (dataLabelContainer != null) dataLabelContainer!, - ]; + return [if (dataLabelContainer != null) dataLabelContainer!]; } @override @@ -8672,14 +9067,23 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer _addDataLabelMapper(fPaths, chaoticFLists, fLists); super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); _calculateGroupingValues(); markNeedsLegendUpdate(); populateChartPoints(); } - void _addPointRadiusMapper(List>? fPaths, - List>? chaoticFLists, List>? fLists) { + void _addPointRadiusMapper( + List>? fPaths, + List>? chaoticFLists, + List>? fLists, + ) { if (fPaths != null && pointRadiusMapper != null) { fPaths.add(pointRadiusMapper!); if (sortingOrder == SortingOrder.none) { @@ -8692,8 +9096,11 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer } } - void _addDataLabelMapper(List>? fPaths, - List>? chaoticFLists, List>? fLists) { + void _addDataLabelMapper( + List>? fPaths, + List>? chaoticFLists, + List>? fLists, + ) { if (fPaths != null && dataLabelMapper != null) { fPaths.add(dataLabelMapper!); if (sortingOrder == SortingOrder.none) { @@ -8760,8 +9167,17 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer _addPointRadiusMapper(fPaths, chaoticFLists, fLists); _addDataLabelMapper(fPaths, chaoticFLists, fLists); - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); _calculateGroupingValues(); } @@ -8863,15 +9279,18 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer final int startDegree = _calculateAngle(startAngle); int endDegree = _calculateAngle(endAngle); endDegree = startDegree == endDegree ? startDegree + 360 : endDegree; - totalAngle = startDegree > endDegree - ? (startDegree - 360).abs() + endDegree - : (startDegree - endDegree).abs(); + totalAngle = + startDegree > endDegree + ? (startDegree - 360).abs() + endDegree + : (startDegree - endDegree).abs(); pointStartAngle = startDegree.toDouble(); currentRadius = percentToValue(radius, (min(size.width, size.height)) / 2)!; currentInnerRadius = percentToValue(innerRadius, currentRadius)!; - center = Offset(percentToValue(centerX, size.width)!, - percentToValue(centerY, size.height)!); + center = Offset( + percentToValue(centerX, size.width)!, + percentToValue(centerY, size.height)!, + ); ringSize = (currentRadius - currentInnerRadius) / length; segmentGap = percentToValue(gap, currentRadius - currentInnerRadius); @@ -8889,12 +9308,12 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer } @override - List? buildLegendItems(int index) { - final List legendItems = []; + List? buildLegendItems(int index) { + final List legendItems = []; final int segmentsCount = segments.length; // TODO(Lavanya): Ignore legend item for gap and drop mode. for (int i = 0; i < dataCount; i++) { - final ChartLegendItem legendItem = ChartLegendItem( + final CircularLegendItem legendItem = CircularLegendItem( text: circularXValues[i].toString(), iconType: toLegendShapeMarkerType(legendIconType, this), iconColor: effectiveColor(i), @@ -8903,9 +9322,10 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer series: this, seriesIndex: index, pointIndex: i, - imageProvider: legendIconType == LegendIconType.image - ? parent?.legend?.image - : null, + imageProvider: + legendIconType == LegendIconType.image + ? parent?.legend?.image + : null, isToggled: i < segmentsCount && !segmentAt(i).isVisible, onTap: handleLegendItemTapped, onRender: _handleLegendItemCreated, @@ -8919,7 +9339,7 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer void handleLegendItemTapped(LegendItem item, bool isToggled) { super.handleLegendItemTapped(item, isToggled); - final ChartLegendItem legendItem = item as ChartLegendItem; + final CircularLegendItem legendItem = item as CircularLegendItem; if (legendItem.pointIndex < segments.length) { segmentAt(legendItem.pointIndex).isVisible = !isToggled; } @@ -8933,13 +9353,24 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer Shader? _legendIconShaders(int pointIndex) { if (parent != null && parent!.legend != null) { final Rect legendIconBounds = Rect.fromLTWH( - 0.0, 0.0, parent!.legend!.iconWidth, parent!.legend!.iconHeight); + 0.0, + 0.0, + parent!.legend!.iconWidth, + parent!.legend!.iconHeight, + ); if (pointShaderMapper != null) { - return pointShaderMapper!(dataSource![pointIndex], pointIndex, - palette[pointIndex % palette.length], legendIconBounds); + return pointShaderMapper!( + dataSource![pointIndex], + pointIndex, + palette[pointIndex % palette.length], + legendIconBounds, + ); } else if (onCreateShader != null) { - final ChartShaderDetails details = - ChartShaderDetails(legendIconBounds, legendIconBounds, 'legend'); + final ChartShaderDetails details = ChartShaderDetails( + legendIconBounds, + legendIconBounds, + 'legend', + ); return onCreateShader?.call(details); } } @@ -8966,17 +9397,20 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer segmentIndex < dataSource!.length) { if (pointShaderMapper != null) { final Shader shader = pointShaderMapper!( - dataSource![segmentIndex], - segmentIndex, - palette[segmentIndex % palette.length], - Rect.fromCircle(center: center, radius: currentRadius)); + dataSource![segmentIndex], + segmentIndex, + palette[segmentIndex % palette.length], + Rect.fromCircle(center: center, radius: currentRadius), + ); segment.fillPaint.shader = shader; } else if (onCreateShader != null) { final ChartShaderDetails details = createShaderDetails(); segment.fillPaint.shader = onCreateShader!(details); } else if (pointRenderMode == PointRenderMode.gradient) { final List colors = List.generate( - segments.length, (int i) => palette[i % palette.length]); + segments.length, + (int i) => palette[i % palette.length], + ); final List stops = []; num initialStops = 0; for (int i = 0; i < segments.length; i++) { @@ -8993,14 +9427,16 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer } } final SweepGradient sweep = SweepGradient( - startAngle: degreeToRadian(startAngle), - endAngle: degreeToRadian(endAngle), - colors: colors, - stops: stops, - transform: GradientRotation(degreeToRadian(-90))); + startAngle: degreeToRadian(startAngle), + endAngle: degreeToRadian(endAngle), + colors: colors, + stops: stops, + transform: GradientRotation(degreeToRadian(-90)), + ); segment.fillPaint.shader = sweep.createShader( - createShaderDetails().outerRect, - textDirection: TextDirection.ltr); + createShaderDetails().outerRect, + textDirection: TextDirection.ltr, + ); } } } @@ -9010,37 +9446,50 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer final int pointIndex = current.dataPointIndex; Offset labelLocation; const int labelPadding = 2; - TextStyle dataLabelStyle = parent!.themeData!.textTheme.bodySmall! - ..merge(chartThemeData!.dataLabelTextStyle) - ..merge(dataLabelSettings.textStyle); + TextStyle dataLabelStyle = + parent!.themeData!.textTheme.bodySmall! + ..merge(chartThemeData!.dataLabelTextStyle) + ..merge(dataLabelSettings.textStyle); final CircularChartPoint point = current.point!; if (point.isExplode) { - point.center = calculateExplodingCenter(point.midAngle!, - point.outerRadius!.toDouble(), point.center!, point.explodeOffset); + point.center = calculateExplodingCenter( + point.midAngle!, + point.outerRadius!.toDouble(), + point.center!, + point.explodeOffset, + ); } if (point.isVisible && (point.y != 0 || dataLabelSettings.showZeroValue)) { dataLabelStyle = dataLabelStyle.copyWith( - color: dataLabelStyle.color ?? - saturatedTextColor( - findThemeColor(this, point, dataLabelSettings))); + color: + dataLabelStyle.color ?? + saturatedTextColor(findThemeColor(this, point, dataLabelSettings)), + ); if (dataLabelSettings.labelPosition == ChartDataLabelPosition.inside) { - labelLocation = calculateOffset(point.midAngle!, - (point.innerRadius! + point.outerRadius!) / 2, point.center!); + labelLocation = calculateOffset( + point.midAngle!, + (point.innerRadius! + point.outerRadius!) / 2, + point.center!, + ); labelLocation = Offset( - labelLocation.dx - - (size.width / 2) + - (angle == 0 ? 0 : size.width / 2), - labelLocation.dy - - (size.height / 2) + - (angle == 0 ? 0 : size.height / 2)); + labelLocation.dx - + (size.width / 2) + + (angle == 0 ? 0 : size.width / 2), + labelLocation.dy - + (size.height / 2) + + (angle == 0 ? 0 : size.height / 2), + ); point.labelRect = Rect.fromLTWH( - labelLocation.dx - labelPadding, - labelLocation.dy - labelPadding, - size.width + (2 * labelPadding), - size.height + (2 * labelPadding)); - bool isDataLabelCollide = - findingCollision(point.labelRect, renderDataLabelRegions); + labelLocation.dx - labelPadding, + labelLocation.dy - labelPadding, + size.width + (2 * labelPadding), + size.height + (2 * labelPadding), + ); + bool isDataLabelCollide = findingCollision( + point.labelRect, + renderDataLabelRegions, + ); if (dataLabelSettings.labelIntersectAction == LabelIntersectAction.hide || dataLabelSettings.overflowMode == OverflowMode.hide) { @@ -9054,15 +9503,16 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer if (dataLabelSettings.overflowMode == OverflowMode.shift) { final String labelText = segmentOverflowTrimmedText( - this, - point.text!, - size, - point, - point.labelRect, - center, - labelLocation, - dataLabelSettings.overflowMode, - dataLabelStyle); + this, + point.text!, + size, + point, + point.labelRect, + center, + labelLocation, + dataLabelSettings.overflowMode, + dataLabelStyle, + ); if (labelText.contains('...') || labelText.isEmpty) { isDataLabelCollide = true; point.renderPosition = ChartDataLabelPosition.outside; @@ -9072,32 +9522,38 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer !point.text!.contains('...')) { if (!isDataLabelCollide) { point.text = segmentOverflowTrimmedText( - this, - point.text!, - size, - point, - point.labelRect, - center, - labelLocation, - dataLabelSettings.overflowMode, - dataLabelStyle); + this, + point.text!, + size, + point, + point.labelRect, + center, + labelLocation, + dataLabelSettings.overflowMode, + dataLabelStyle, + ); label = point.text!; final Size trimmedTextSize = measureText(label, dataLabelStyle); - labelLocation = calculateOffset(point.midAngle!, - (point.innerRadius! + point.outerRadius!) / 2, point.center!); + labelLocation = calculateOffset( + point.midAngle!, + (point.innerRadius! + point.outerRadius!) / 2, + point.center!, + ); labelLocation = Offset( - labelLocation.dx - - (trimmedTextSize.width / 2) + - (angle == 0 ? 0 : trimmedTextSize.width / 2), - labelLocation.dy - - (trimmedTextSize.height / 2) + - (angle == 0 ? 0 : trimmedTextSize.height / 2)); + labelLocation.dx - + (trimmedTextSize.width / 2) + + (angle == 0 ? 0 : trimmedTextSize.width / 2), + labelLocation.dy - + (trimmedTextSize.height / 2) + + (angle == 0 ? 0 : trimmedTextSize.height / 2), + ); point.labelLocation = labelLocation; point.labelRect = Rect.fromLTWH( - labelLocation.dx - labelPadding, - labelLocation.dy - labelPadding, - trimmedTextSize.width + (2 * labelPadding), - trimmedTextSize.height + (2 * labelPadding)); + labelLocation.dx - labelPadding, + labelLocation.dy - labelPadding, + trimmedTextSize.width + (2 * labelPadding), + trimmedTextSize.height + (2 * labelPadding), + ); } else { point.isVisible = false; } @@ -9110,8 +9566,15 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer dataLabelSettings.overflowMode != OverflowMode.trim) { point.saturationRegionOutside = true; point.renderPosition = ChartDataLabelPosition.outside; - renderOutsideDataLabel(point, size, pointIndex, this, index, - dataLabelStyle, renderDataLabelRegions); + renderOutsideDataLabel( + point, + size, + pointIndex, + this, + index, + dataLabelStyle, + renderDataLabelRegions, + ); } else if (((dataLabelSettings.labelIntersectAction == LabelIntersectAction.shift && dataLabelSettings.overflowMode == OverflowMode.none) && @@ -9121,8 +9584,15 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer dataLabelSettings.overflowMode == OverflowMode.shift)) { point.saturationRegionOutside = true; point.renderPosition = ChartDataLabelPosition.outside; - renderOutsideDataLabel(point, size, pointIndex, this, index, - dataLabelStyle, renderDataLabelRegions); + renderOutsideDataLabel( + point, + size, + pointIndex, + this, + index, + dataLabelStyle, + renderDataLabelRegions, + ); } else if (!isDataLabelCollide || (dataLabelSettings.labelIntersectAction == LabelIntersectAction.none && @@ -9144,15 +9614,16 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer if (point.renderPosition == ChartDataLabelPosition.inside && (dataLabelSettings.overflowMode == OverflowMode.hide)) { point.text = segmentOverflowTrimmedText( - this, - point.text!, - size, - point, - point.labelRect, - center, - labelLocation, - dataLabelSettings.overflowMode, - dataLabelStyle); + this, + point.text!, + size, + point, + point.labelRect, + center, + labelLocation, + dataLabelSettings.overflowMode, + dataLabelStyle, + ); // label = point.text!; } @@ -9174,11 +9645,21 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer } else { point.renderPosition = ChartDataLabelPosition.outside; dataLabelStyle = dataLabelStyle.copyWith( - color: dataLabelStyle.color ?? - saturatedTextColor( - findThemeColor(this, point, dataLabelSettings))); - renderOutsideDataLabel(point, size, pointIndex, this, index, - dataLabelStyle, renderDataLabelRegions); + color: + dataLabelStyle.color ?? + saturatedTextColor( + findThemeColor(this, point, dataLabelSettings), + ), + ); + renderOutsideDataLabel( + point, + size, + pointIndex, + this, + index, + dataLabelStyle, + renderDataLabelRegions, + ); } } else { point.labelRect = Rect.zero; @@ -9216,8 +9697,14 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer final SfChartThemeData chartThemeData = parent!.chartThemeData!; final ThemeData themeData = parent!.themeData!; final ChartSegment segment = segments[index]; - Color surfaceColor = dataLabelSurfaceColor(fillPaint.color, index, - dataLabelSettings.labelPosition, chartThemeData, themeData, segment); + Color surfaceColor = dataLabelSurfaceColor( + fillPaint.color, + index, + dataLabelSettings.labelPosition, + chartThemeData, + themeData, + segment, + ); TextStyle effectiveTextStyle = saturatedTextStyle(surfaceColor, style); final CircularChartPoint point = dataLabelPositioned.point!; if (!point.isVisible || !segments[index].isVisible || point.text == '') { @@ -9234,8 +9721,14 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer dataLabelSettings.color == null && !dataLabelSettings.useSeriesColor) { if (style.color == Colors.transparent) { - surfaceColor = dataLabelSurfaceColor(fillPaint.color, index, - ChartDataLabelPosition.outside, chartThemeData, themeData, segment); + surfaceColor = dataLabelSurfaceColor( + fillPaint.color, + index, + ChartDataLabelPosition.outside, + chartThemeData, + themeData, + segment, + ); effectiveTextStyle = saturatedTextStyle(surfaceColor, style); } } @@ -9249,55 +9742,82 @@ abstract class CircularSeriesRenderer extends ChartSeriesRenderer if (dataLabelSettings.borderWidth > 0 && strokePaint.color != Colors.transparent) { _drawLabelRect( - strokePaint, - Rect.fromLTRB( - labelRect.left, labelRect.top, labelRect.right, labelRect.bottom), - dataLabelSettings.borderRadius, - canvas); + strokePaint, + Rect.fromLTRB( + labelRect.left, + labelRect.top, + labelRect.right, + labelRect.bottom, + ), + dataLabelSettings.borderRadius, + canvas, + ); } if (fillPaint.color != Colors.transparent) { _drawLabelRect( - fillPaint, - Rect.fromLTRB( - labelRect.left, labelRect.top, labelRect.right, labelRect.bottom), - dataLabelSettings.borderRadius, - canvas); + fillPaint, + Rect.fromLTRB( + labelRect.left, + labelRect.top, + labelRect.right, + labelRect.bottom, + ), + dataLabelSettings.borderRadius, + canvas, + ); } canvas.restore(); drawDataLabel( - canvas, dataLabel, offset, effectiveTextStyle, dataLabelSettings.angle); + canvas, + dataLabel, + offset, + effectiveTextStyle, + dataLabelSettings.angle, + ); } void drawConnectorLine(Path connectorPath, Canvas canvas, int index) { final ConnectorLineSettings line = dataLabelSettings.connectorLineSettings; canvas.drawPath( - connectorPath, - Paint() - ..color = line.width <= 0 - ? Colors.transparent - : line.color ?? segments[index].fillPaint.color - ..strokeWidth = line.width - ..style = PaintingStyle.stroke); + connectorPath, + Paint() + ..color = + line.width <= 0 + ? Colors.transparent + : line.color ?? segments[index].fillPaint.color + ..strokeWidth = line.width + ..style = PaintingStyle.stroke, + ); } void _drawLabelRect( - Paint paint, Rect labelRect, double borderRadius, Canvas canvas) => - canvas.drawRRect( - RRect.fromRectAndRadius(labelRect, Radius.circular(borderRadius)), - paint); + Paint paint, + Rect labelRect, + double borderRadius, + Canvas canvas, + ) => canvas.drawRRect( + RRect.fromRectAndRadius(labelRect, Radius.circular(borderRadius)), + paint, + ); void drawDataLabel( - Canvas canvas, String text, Offset point, TextStyle style, int angle, - [bool? isRtl]) { + Canvas canvas, + String text, + Offset point, + TextStyle style, + int angle, [ + bool? isRtl, + ]) { final int maxLines = getMaxLinesContent(text); final TextSpan span = TextSpan(text: text, style: style); final TextPainter tp = TextPainter( - text: span, - textDirection: (isRtl ?? false) ? TextDirection.rtl : TextDirection.ltr, - textAlign: TextAlign.center, - maxLines: maxLines); + text: span, + textDirection: (isRtl ?? false) ? TextDirection.rtl : TextDirection.ltr, + textAlign: TextAlign.center, + maxLines: maxLines, + ); tp.layout(); canvas.save(); canvas.translate(point.dx + tp.width / 2, point.dy + tp.height / 2); @@ -9437,10 +9957,11 @@ abstract class BoxAndWhiskerSeriesRendererBase @override void _doSortingIfNeeded( - List>? chaoticYLists, - List>? yLists, - List>? chaoticFLists, - List>? fLists) { + List>? chaoticYLists, + List>? yLists, + List>? chaoticFLists, + List>? fLists, + ) { if (sortingOrder != SortingOrder.none && _chaoticYValues.isNotEmpty) { if (_chaoticRawSortValues.isEmpty) { if (_chaoticRawXValues.isNotEmpty) { @@ -9473,8 +9994,10 @@ abstract class BoxAndWhiskerSeriesRendererBase } void _sortBoxValues( - List>? chaoticFLists, List>? fLists, - {bool ascending = true}) { + List>? chaoticFLists, + List>? fLists, { + bool ascending = true, + }) { _computeSortedIndexes(ascending); if (sortedIndexes.isNotEmpty) { final void Function(int index, num xValue) copyX = @@ -9528,10 +10051,7 @@ abstract class BoxAndWhiskerSeriesRendererBase List>? chaoticFLists, List>? fLists, ]) { - if (dataSource == null || - dataSource!.isEmpty || - xValueMapper == null || - yValueMapper == null) { + if (xValueMapper == null || yValueMapper == null) { return; } @@ -9544,18 +10064,39 @@ abstract class BoxAndWhiskerSeriesRendererBase _addSortValueMapper(fPaths, chaoticFLists, fLists); if (removedIndexes != null) { - _removeDataPoints(removedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _removeDataPoints( + removedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } if (addedIndexes != null) { - _addDataPoints(addedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _addDataPoints( + addedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } if (replacedIndexes != null) { - _replaceDataPoints(replacedIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _replaceDataPoints( + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } // During sorting, the x, y, and feature path values are recalculated. @@ -9572,7 +10113,11 @@ abstract class BoxAndWhiskerSeriesRendererBase final DoubleRange xRange = _findMinMaxXRange(xValues); final DoubleRange yRange = _findMinMaxYRange(_chaoticYValues); _updateAxisRange( - xRange.minimum, xRange.maximum, yRange.minimum, yRange.maximum); + xRange.minimum, + xRange.maximum, + yRange.minimum, + yRange.maximum, + ); computeNonEmptyYValues(); _populateTrendlineDataSource(); _updateXValuesForCategoryTypeAxes(); @@ -9592,7 +10137,11 @@ abstract class BoxAndWhiskerSeriesRendererBase List>? fLists, ) { final int fPathLength = fPaths?.length ?? 0; - for (final int index in indexes) { + // Sort 'indexes' in descending order to remove higher indexes first, + // preventing shifting issues when removing lower ones. + final List sortedIndexes = List.from(indexes) + ..sort((a, b) => b.compareTo(a)); + for (final int index in sortedIndexes) { _removeXValueAt(index); _removeRawSortValueAt(index); _chaoticYValues.removeAt(index); @@ -9609,8 +10158,15 @@ abstract class BoxAndWhiskerSeriesRendererBase _dataCount = _chaoticXValues.length; // Collecting previous and next index to update them. final List mutableIndexes = _findMutableIndexes(indexes); - _replaceDataPoints(mutableIndexes, yPaths, chaoticYLists, yLists, fPaths, - chaoticFLists, fLists); + _replaceDataPoints( + mutableIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } @override @@ -9677,7 +10233,9 @@ abstract class BoxAndWhiskerSeriesRendererBase if (_callbacksEnabled) { final num xValue = _chaoticXValues[index]; final CartesianChartPoint point = CartesianChartPoint( - x: _chaoticRawXValues[index], xValue: xValue); + x: _chaoticRawXValues[index], + xValue: xValue, + ); chartPoints.insert(index, point); } @@ -9749,7 +10307,9 @@ abstract class BoxAndWhiskerSeriesRendererBase if (_callbacksEnabled) { final num xValue = _chaoticXValues[index]; final CartesianChartPoint point = CartesianChartPoint( - x: _chaoticRawXValues[index], xValue: xValue); + x: _chaoticRawXValues[index], + xValue: xValue, + ); chartPoints[index] = point; } @@ -9761,7 +10321,11 @@ abstract class BoxAndWhiskerSeriesRendererBase @override Offset _calculateMedianPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -9778,7 +10342,11 @@ abstract class BoxAndWhiskerSeriesRendererBase @override Offset _calculateDataLabelOpenPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: @@ -9935,7 +10503,9 @@ abstract class HistogramSeriesRendererBase @override bool _canPopulateDataPoints( - List>? yPaths, List>? yLists) { + List>? yPaths, + List>? yLists, + ) { return dataSource != null && dataSource!.isNotEmpty && yPaths != null && @@ -10084,6 +10654,13 @@ abstract class HistogramSeriesRendererBase num sumValue = 0; _mean = 0; final num yLength = _yRawValues.length; + num minValue = _yRawValues.reduce(min); + if (yLength == 1 && binInterval == null) { + _histogramYValues.add(1); + _histogramXValues.add(minValue); + return; + } + for (int i = 0; i < yLength; i++) { final num yValue = _yRawValues[i]; sumOfY += yValue; @@ -10096,13 +10673,18 @@ abstract class HistogramSeriesRendererBase } _deviation = sqrt(sumValue / (yLength - 1)); - num minValue = _yRawValues.reduce(min); binWidth = binInterval ?? (3.5 * _deviation) / pow(yLength, 1 / 3); + if (binWidth <= 0 || binWidth.isNaN) { + _histogramYValues.add(0); + _histogramXValues.add(minValue); + return; + } for (int i = 0; i < yLength;) { - final num count = _yRawValues - .where((num y) => y >= minValue && y < (minValue + binWidth)) - .length; + final num count = + _yRawValues + .where((num y) => y >= minValue && y < (minValue + binWidth)) + .length; if (count >= 0) { _histogramYValues.add(count); final num x = minValue + binWidth / 2; @@ -10150,7 +10732,7 @@ abstract class HistogramSeriesRendererBase final num xValue = minimum + i * delta; final num yValue = exp(-pow(xValue - _mean, 2) / (2 * pow(_deviation, 2))) / - (_deviation * sqrt(2 * pi)); + (_deviation * sqrt(2 * pi)); final num dx = yValue * binWidth * dataCount; final double x = pointToPixelX(xValue, dx); final double y = pointToPixelY(xValue, dx); @@ -10184,17 +10766,26 @@ abstract class HistogramSeriesRendererBase paintSegments(context, offset); if (showNormalDistributionCurve) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, segmentAnimationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + segmentAnimationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); - final Paint strokePaint = Paint() - ..color = curveColor - ..strokeWidth = curveWidth - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = curveColor + ..strokeWidth = curveWidth + ..style = PaintingStyle.stroke; curveDashArray == null ? context.canvas.drawPath(_distributionPath, strokePaint) - : drawDashes(context.canvas, curveDashArray, strokePaint, - path: _distributionPath); + : drawDashes( + context.canvas, + curveDashArray, + strokePaint, + path: _distributionPath, + ); } context.canvas.restore(); paintMarkers(context, offset); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/column_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/column_series.dart index 137305504..a2147cef8 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/column_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/column_series.dart @@ -245,7 +245,9 @@ class ColumnSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, ColumnSeriesRenderer renderObject) { + BuildContext context, + ColumnSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isTrackVisible = isTrackVisible @@ -352,20 +354,29 @@ class ColumnSeriesRenderer extends XyDataSeriesRenderer void customizeSegment(ChartSegment segment) { final ColumnSegment columnSegment = segment as ColumnSegment; updateSegmentTrackerStyle( - columnSegment, trackColor, trackBorderColor, trackBorderWidth); + columnSegment, + trackColor, + trackBorderColor, + trackBorderWidth, + ); updateSegmentColor(columnSegment, borderColor, borderWidth); - updateSegmentGradient(columnSegment, - gradientBounds: columnSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + columnSegment, + gradientBounds: columnSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } @override void handleLegendItemTapped(LegendItem item, bool isToggled) { if (parent != null && parent!.onLegendTapped != null) { - final ChartLegendItem legendItem = item as ChartLegendItem; + final CartesianLegendItem legendItem = item as CartesianLegendItem; final LegendTapArgs args = LegendTapArgs( - legendItem.series, legendItem.seriesIndex, legendItem.pointIndex); + legendItem.series, + legendItem.seriesIndex, + legendItem.pointIndex, + ); parent!.onLegendTapped!(args); } parent!.behaviorArea?.hideInteractiveTooltip(); @@ -410,7 +421,9 @@ class ColumnSegment extends ChartSegment with BarSeriesTrackerMixin { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -484,24 +497,29 @@ class ColumnSegment extends ChartSegment with BarSeriesTrackerMixin { final CartesianChartPoint chartPoint = _chartPoint(); final TooltipPosition? tooltipPosition = series.parent?.tooltipBehavior?.tooltipPosition; - final Offset posFromRect = y.isNegative && bottom == 0 - ? segmentRect!.outerRect.bottomCenter - : segmentRect!.outerRect.topCenter; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? posFromRect - : posFromRect; + final Offset posFromRect = + y.isNegative && bottom == 0 + ? segmentRect!.outerRect.bottomCenter + : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? posFromRect + : posFromRect; final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -521,8 +539,10 @@ class ColumnSegment extends ChartSegment with BarSeriesTrackerMixin { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, y), series.pointToPixelY(x, y)), + position: Offset( + series.pointToPixelX(x, y), + series.pointToPixelY(x, y), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -564,7 +584,11 @@ class ColumnSegment extends ChartSegment with BarSeriesTrackerMixin { _oldSegmentRect != null && series.animationType != AnimationType.loading) { paintRRect = performLegendToggleAnimation( - series, segmentRect!, _oldSegmentRect!, series.borderRadius); + series, + segmentRect!, + _oldSegmentRect!, + series.borderRadius, + ); } else { paintRRect = RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/doughnut_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/doughnut_series.dart index d5630e8ba..7e17542a1 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/doughnut_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/doughnut_series.dart @@ -69,10 +69,7 @@ class DoughnutSeries extends CircularSeries { super.legendIconType, super.cornerStyle = CornerStyle.bothFlat, super.initialSelectedDataIndexes, - }) : super( - borderColor: strokeColor, - borderWidth: strokeWidth, - ); + }) : super(borderColor: strokeColor, borderWidth: strokeWidth); /// Enables or disables the explode of slices on tap. /// @@ -179,8 +176,9 @@ class DoughnutSeries extends CircularSeries { final ActivationMode explodeGesture; @override - List get positions => - [ChartDataPointType.y]; + List get positions => [ + ChartDataPointType.y, + ]; /// Create the circular series renderer. @override @@ -209,7 +207,9 @@ class DoughnutSeries extends CircularSeries { @override void updateRenderObject( - BuildContext context, DoughnutSeriesRenderer renderObject) { + BuildContext context, + DoughnutSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..explode = explode @@ -298,9 +298,13 @@ class DoughnutSeriesRenderer extends CircularSeriesRenderer { final double degree = (yValue.abs() / (sumOfY != 0 ? sumOfY : 1)) * totalAngle; final double pointEndAngle = pointStartAngle + degree; - final double outerRadius = pointRadii.isNotEmpty - ? percentToValue(pointRadii[index], (min(size.width, size.height)) / 2)! - : currentRadius; + final double outerRadius = + pointRadii.isNotEmpty + ? percentToValue( + pointRadii[index], + (min(size.width, size.height)) / 2, + )! + : currentRadius; segment as DoughnutSegment ..series = this @@ -311,7 +315,8 @@ class DoughnutSeriesRenderer extends CircularSeriesRenderer { .._outerRadius = outerRadius .._center = center .._isExploded = explode && (index == explodeIndex || explodeAll) - ..isEmpty = (emptyPointSettings.mode != EmptyPointMode.drop && + ..isEmpty = + (emptyPointSettings.mode != EmptyPointMode.drop && emptyPointSettings.mode != EmptyPointMode.gap) && isEmpty(index); @@ -478,14 +483,20 @@ class DoughnutSegment extends ChartSegment { double degree = _degree * animationFactor; final double angle = calculateAngle( - series.animationFactor == 1, series.startAngle, series.endAngle); - final double startAngle = lerpDouble( - _priorEndAngle.isNaN ? angle : _priorStartAngle, - _startAngle, - animationFactor)!; - final double endAngle = _priorEndAngle.isNaN - ? startAngle + degree - : lerpDouble(_priorEndAngle, _endAngle, animationFactor)!; + series.animationFactor == 1, + series.startAngle, + series.endAngle, + ); + final double startAngle = + lerpDouble( + _priorEndAngle.isNaN ? angle : _priorStartAngle, + _startAngle, + animationFactor, + )!; + final double endAngle = + _priorEndAngle.isNaN + ? startAngle + degree + : lerpDouble(_priorEndAngle, _endAngle, animationFactor)!; degree = _priorEndAngle.isNaN ? degree : endAngle - startAngle; // If the startAngle and endAngle value is same, then degree will be 0. @@ -497,7 +508,11 @@ class DoughnutSegment extends ChartSegment { if (series.explode && _isExploded) { final double midAngle = (_startAngle + _endAngle) / 2; _center = calculateExplodingCenter( - midAngle, _outerRadius, series.center, series.explodeOffset); + midAngle, + _outerRadius, + series.center, + series.explodeOffset, + ); } else { _center = series.center; } @@ -505,22 +520,39 @@ class DoughnutSegment extends ChartSegment { final CornerStyle cornerStyle = series.cornerStyle; if (cornerStyle == CornerStyle.bothFlat) { fillPath = calculateArcPath( - _innerRadius, _outerRadius, _center, startAngle, endAngle, degree, - isAnimate: true); + _innerRadius, + _outerRadius, + _center, + startAngle, + endAngle, + degree, + isAnimate: true, + ); } else { - final num angleDeviation = - findAngleDeviation(_innerRadius, _outerRadius, 360); - final double actualStartAngle = (cornerStyle == CornerStyle.startCurve || - cornerStyle == CornerStyle.bothCurve) - ? (startAngle + angleDeviation) - : startAngle; - final double actualEndAngle = (cornerStyle == CornerStyle.endCurve || - cornerStyle == CornerStyle.bothCurve) - ? (endAngle - angleDeviation) - : endAngle; - - fillPath = calculateRoundedCornerArcPath(cornerStyle, _innerRadius, - _outerRadius, _center, actualStartAngle, actualEndAngle); + final num angleDeviation = findAngleDeviation( + _innerRadius, + _outerRadius, + 360, + ); + final double actualStartAngle = + (cornerStyle == CornerStyle.startCurve || + cornerStyle == CornerStyle.bothCurve) + ? (startAngle + angleDeviation) + : startAngle; + final double actualEndAngle = + (cornerStyle == CornerStyle.endCurve || + cornerStyle == CornerStyle.bothCurve) + ? (endAngle - angleDeviation) + : endAngle; + + fillPath = calculateRoundedCornerArcPath( + cornerStyle, + _innerRadius, + _outerRadius, + _center, + actualStartAngle, + actualEndAngle, + ); } } @@ -541,15 +573,20 @@ class DoughnutSegment extends ChartSegment { @override TooltipInfo? tooltipInfo({Offset? position, int? pointIndex}) { final ChartPoint point = ChartPoint( - x: series.circularXValues[currentSegmentIndex], - y: series.circularYValues[currentSegmentIndex]); - final Offset location = calculateOffset((_startAngle + _endAngle) / 2, - (_innerRadius + _outerRadius) / 2, _center); + x: series.circularXValues[currentSegmentIndex], + y: series.circularYValues[currentSegmentIndex], + ); + final Offset location = calculateOffset( + (_startAngle + _endAngle) / 2, + (_innerRadius + _outerRadius) / 2, + _center, + ); final TooltipPosition? tooltipPosition = series.parent?.tooltipBehavior?.tooltipPosition; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? series.localToGlobal(position ?? location) - : series.localToGlobal(location); + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? series.localToGlobal(position ?? location) + : series.localToGlobal(location); return ChartTooltipInfo( primaryPosition: preferredPos, secondaryPosition: preferredPos, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/error_bar_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/error_bar_series.dart index 03726a5d5..c0cdc0de6 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/error_bar_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/error_bar_series.dart @@ -299,7 +299,9 @@ class ErrorBarSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, ErrorBarSeriesRenderer renderObject) { + BuildContext context, + ErrorBarSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..type = type @@ -458,7 +460,13 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer List>? fLists, ]) { super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); _xMin = xMin; _xMax = xMax; _yMin = yMin; @@ -468,16 +476,28 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer } @override - void updateDataPoints(List? removedIndexes, List? addedIndexes, - List? replacedIndexes, - [List>? yPaths, - List>? chaoticYLists, - List>? yLists, - List>? fPaths, - List>? chaoticFLists, - List>? fLists]) { - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + void updateDataPoints( + List? removedIndexes, + List? addedIndexes, + List? replacedIndexes, [ + List>? yPaths, + List>? chaoticYLists, + List>? yLists, + List>? fPaths, + List>? chaoticFLists, + List>? fLists, + ]) { + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); _xMin = xMin; _xMax = xMax; _yMin = yMin; @@ -504,35 +524,43 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer sumOfX += xValues[i]; } - verticalMean = (mode == RenderingMode.horizontal) - ? verticalMean - : sumOfY / dataCount; - horizontalMean = (mode == RenderingMode.vertical) - ? horizontalMean - : sumOfX / dataCount; + verticalMean = + (mode == RenderingMode.horizontal) + ? verticalMean + : sumOfY / dataCount; + horizontalMean = + (mode == RenderingMode.vertical) + ? horizontalMean + : sumOfX / dataCount; for (int i = 0; i < dataCount; i++) { - sumOfY = (mode == RenderingMode.horizontal) - ? sumOfY - : sumOfY + pow(yValues[i] - verticalMean!, 2); - sumOfX = (mode == RenderingMode.vertical) - ? sumOfX - : sumOfX + pow(xValues[i] - horizontalMean!, 2); + sumOfY = + (mode == RenderingMode.horizontal) + ? sumOfY + : sumOfY + pow(yValues[i] - verticalMean!, 2); + sumOfX = + (mode == RenderingMode.vertical) + ? sumOfX + : sumOfX + pow(xValues[i] - horizontalMean!, 2); } verticalSquareRoot = sqrt(sumOfY / (dataCount - 1)); horizontalSquareRoot = sqrt(sumOfX / (dataCount - 1)); final ErrorBarMean mean = ErrorBarMean( - verticalSquareRoot: verticalSquareRoot, - horizontalSquareRoot: horizontalSquareRoot, - verticalMean: verticalMean, - horizontalMean: horizontalMean); + verticalSquareRoot: verticalSquareRoot, + horizontalSquareRoot: horizontalSquareRoot, + verticalMean: verticalMean, + horizontalMean: horizontalMean, + ); for (int j = 0; j < dataCount; j++) { final num xValue = xValues[j]; final num yValue = yValues[j]; - final ErrorValues errorValues = - _calculateErrorValues(xValue, yValue, mean: mean); + final ErrorValues errorValues = _calculateErrorValues( + xValue, + yValue, + mean: mean, + ); errorBarValues = _calculateErrorBarValues(errorValues, xValue, yValue); _errorBarValues.add(errorBarValues); @@ -542,15 +570,8 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer for (int k = 0; k < dataCount; k++) { final num xValue = xValues[k]; final num yValue = yValues[k]; - final ErrorValues errorValues = _calculateErrorValues( - xValue, - yValue, - ); - errorBarValues = _calculateErrorBarValues( - errorValues, - xValue, - yValue, - ); + final ErrorValues errorValues = _calculateErrorValues(xValue, yValue); + errorBarValues = _calculateErrorBarValues(errorValues, xValue, yValue); _errorBarValues.add(errorBarValues); _findMinMax(errorBarValues, axesRange); } @@ -564,28 +585,39 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer void _findMinMax(ErrorBarValues errorBarValues, AxesRange axesRange) { if (errorBarValues.horizontalNegativeErrorValue != null) { - axesRange.xMinimum = - min(axesRange.xMinimum, errorBarValues.horizontalNegativeErrorValue!); + axesRange.xMinimum = min( + axesRange.xMinimum, + errorBarValues.horizontalNegativeErrorValue!, + ); } if (errorBarValues.horizontalPositiveErrorValue != null) { - axesRange.xMaximum = - max(axesRange.xMaximum, errorBarValues.horizontalPositiveErrorValue!); + axesRange.xMaximum = max( + axesRange.xMaximum, + errorBarValues.horizontalPositiveErrorValue!, + ); } if (errorBarValues.verticalNegativeErrorValue != null) { - axesRange.yMinimum = - min(axesRange.yMinimum, errorBarValues.verticalNegativeErrorValue!); + axesRange.yMinimum = min( + axesRange.yMinimum, + errorBarValues.verticalNegativeErrorValue!, + ); } if (errorBarValues.verticalPositiveErrorValue != null) { - axesRange.yMaximum = - max(axesRange.yMaximum, errorBarValues.verticalPositiveErrorValue!); + axesRange.yMaximum = max( + axesRange.yMaximum, + errorBarValues.verticalPositiveErrorValue!, + ); } } /// Calculating error values based on error bar type. - ErrorValues _calculateErrorValues(num actualXValue, num actualYValue, - {ErrorBarMean? mean}) { + ErrorValues _calculateErrorValues( + num actualXValue, + num actualYValue, { + ErrorBarMean? mean, + }) { num errorX = 0.0; num errorY = 0.0; num customNegativeErrorX = 0.0; @@ -604,39 +636,48 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer } else if (type == ErrorBarType.standardDeviation) { errorValues = _calculateStandardDeviationValues(errorValues, mean!); } else if (type == ErrorBarType.percentage) { - errorY = (mode == RenderingMode.horizontal) - ? errorY - : (errorY / 100) * actualYValue; - errorX = (mode == RenderingMode.vertical) - ? errorX - : (errorX / 100) * actualXValue; + errorY = + (mode == RenderingMode.horizontal) + ? errorY + : (errorY / 100) * actualYValue; + errorX = + (mode == RenderingMode.vertical) + ? errorX + : (errorX / 100) * actualXValue; errorValues = ErrorValues(errorX: errorX, errorY: errorY); } } else if (type == ErrorBarType.custom) { - errorY = (mode == RenderingMode.horizontal) - ? errorY - : verticalPositiveErrorValue!; - customNegativeErrorY = (mode == RenderingMode.horizontal) - ? customNegativeErrorY - : verticalNegativeErrorValue!; - errorX = (mode == RenderingMode.vertical) - ? errorX - : horizontalPositiveErrorValue!; - customNegativeErrorX = (mode == RenderingMode.vertical) - ? customNegativeErrorX - : horizontalNegativeErrorValue!; + errorY = + (mode == RenderingMode.horizontal) + ? errorY + : verticalPositiveErrorValue!; + customNegativeErrorY = + (mode == RenderingMode.horizontal) + ? customNegativeErrorY + : verticalNegativeErrorValue!; + errorX = + (mode == RenderingMode.vertical) + ? errorX + : horizontalPositiveErrorValue!; + customNegativeErrorX = + (mode == RenderingMode.vertical) + ? customNegativeErrorX + : horizontalNegativeErrorValue!; errorValues = ErrorValues( - errorX: errorX, - errorY: errorY, - customNegativeX: customNegativeErrorX, - customNegativeY: customNegativeErrorY); + errorX: errorX, + errorY: errorY, + customNegativeX: customNegativeErrorX, + customNegativeY: customNegativeErrorY, + ); } return errorValues!; } /// Calculate the error values of standard error type error bar. ErrorValues _calculateStandardErrorValues( - ErrorValues errorValues, ErrorBarMean mean) { + ErrorValues errorValues, + ErrorBarMean mean, + ) { final num errorX = (errorValues.errorX! * mean.horizontalSquareRoot!) / sqrt(dataCount); final num errorY = @@ -646,20 +687,27 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer /// Calculate the error values of standard deviation type error bar. ErrorValues _calculateStandardDeviationValues( - ErrorValues errorValues, ErrorBarMean mean) { + ErrorValues errorValues, + ErrorBarMean mean, + ) { num errorY = errorValues.errorY!, errorX = errorValues.errorX!; - errorY = (mode == RenderingMode.horizontal) - ? errorY - : errorY * (mean.verticalSquareRoot! + mean.verticalMean!); - errorX = (mode == RenderingMode.vertical) - ? errorX - : errorX * (mean.horizontalSquareRoot! + mean.horizontalMean!); + errorY = + (mode == RenderingMode.horizontal) + ? errorY + : errorY * (mean.verticalSquareRoot! + mean.verticalMean!); + errorX = + (mode == RenderingMode.vertical) + ? errorX + : errorX * (mean.horizontalSquareRoot! + mean.horizontalMean!); return ErrorValues(errorX: errorX, errorY: errorY); } /// Calculate the error bar values. ErrorBarValues _calculateErrorBarValues( - ErrorValues errorValues, num actualXValue, num actualYValue) { + ErrorValues errorValues, + num actualXValue, + num actualYValue, + ) { final bool isDirectionPlus = direction == Direction.plus; final bool isBothDirection = direction == Direction.both; final bool isDirectionMinus = direction == Direction.minus; @@ -674,7 +722,9 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer if (isDirectionPlus || isBothDirection) { if (xAxis is RenderDateTimeAxis && isCustomFixedType) { horizontalPositiveErrorValue = _updateDateTimeHorizontalErrorValue( - actualXValue, errorValues.errorX!); + actualXValue, + errorValues.errorX!, + ); } else { horizontalPositiveErrorValue = actualXValue + errorValues.errorX! as double; @@ -683,15 +733,18 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer if (isDirectionMinus || isBothDirection) { if (xAxis is RenderDateTimeAxis && isCustomFixedType) { horizontalNegativeErrorValue = _updateDateTimeHorizontalErrorValue( - actualXValue, - (type == ErrorBarType.custom) - ? -errorValues.customNegativeX! - : -errorValues.errorX!); + actualXValue, + (type == ErrorBarType.custom) + ? -errorValues.customNegativeX! + : -errorValues.errorX!, + ); } else { - horizontalNegativeErrorValue = actualXValue - - ((type == ErrorBarType.custom) - ? errorValues.customNegativeX! - : errorValues.errorX!) as double; + horizontalNegativeErrorValue = + actualXValue - + ((type == ErrorBarType.custom) + ? errorValues.customNegativeX! + : errorValues.errorX!) + as double; } } } @@ -702,23 +755,27 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer actualYValue + errorValues.errorY! as double; } if (isDirectionMinus || isBothDirection) { - verticalNegativeErrorValue = actualYValue - - ((type == ErrorBarType.custom) - ? errorValues.customNegativeY! - : errorValues.errorY!) as double; + verticalNegativeErrorValue = + actualYValue - + ((type == ErrorBarType.custom) + ? errorValues.customNegativeY! + : errorValues.errorY!) + as double; } } return ErrorBarValues( - horizontalPositiveErrorValue, - horizontalNegativeErrorValue, - verticalPositiveErrorValue, - verticalNegativeErrorValue); + horizontalPositiveErrorValue, + horizontalNegativeErrorValue, + verticalPositiveErrorValue, + verticalNegativeErrorValue, + ); } /// Calculate the error values for DateTime axis. double _updateDateTimeHorizontalErrorValue(num actualXValue, num errorValue) { - DateTime errorXValue = - DateTime.fromMillisecondsSinceEpoch(actualXValue.toInt()); + DateTime errorXValue = DateTime.fromMillisecondsSinceEpoch( + actualXValue.toInt(), + ); final int errorX = errorValue.toInt(); final RenderDateTimeAxis dateTimeAxis = xAxis! as RenderDateTimeAxis; @@ -726,15 +783,24 @@ class ErrorBarSeriesRenderer extends XyDataSeriesRenderer switch (type) { case DateTimeIntervalType.years: errorXValue = DateTime( - errorXValue.year + errorX, errorXValue.month, errorXValue.day); + errorXValue.year + errorX, + errorXValue.month, + errorXValue.day, + ); break; case DateTimeIntervalType.months: errorXValue = DateTime( - errorXValue.year, errorXValue.month + errorX, errorXValue.day); + errorXValue.year, + errorXValue.month + errorX, + errorXValue.day, + ); break; case DateTimeIntervalType.days: errorXValue = DateTime( - errorXValue.year, errorXValue.month, errorXValue.day + errorX); + errorXValue.year, + errorXValue.month, + errorXValue.day + errorX, + ); break; case DateTimeIntervalType.hours: errorXValue = errorXValue.add(Duration(hours: errorX)); @@ -830,7 +896,9 @@ class ErrorBarSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -903,111 +971,151 @@ class ErrorBarSegment extends ChartSegment { points.add(Offset(_errorBarMidPointX, _errorBarMidPointY)); if (errorBarValues.verticalPositiveErrorValue != null) { - verticalPositiveX = - transformX(xValue, errorBarValues.verticalPositiveErrorValue!); - verticalPositiveY = - transformY(xValue, errorBarValues.verticalPositiveErrorValue!); + verticalPositiveX = transformX( + xValue, + errorBarValues.verticalPositiveErrorValue!, + ); + verticalPositiveY = transformY( + xValue, + errorBarValues.verticalPositiveErrorValue!, + ); points.add(Offset(verticalPositiveX, verticalPositiveY)); } if (errorBarValues.verticalNegativeErrorValue != null) { - verticalNegativeX = - transformX(xValue, errorBarValues.verticalNegativeErrorValue!); - verticalNegativeY = - transformY(xValue, errorBarValues.verticalNegativeErrorValue!); + verticalNegativeX = transformX( + xValue, + errorBarValues.verticalNegativeErrorValue!, + ); + verticalNegativeY = transformY( + xValue, + errorBarValues.verticalNegativeErrorValue!, + ); points.add(Offset(verticalNegativeX, verticalNegativeY)); } if (errorBarValues.horizontalPositiveErrorValue != null) { - horizontalPositiveX = - transformX(errorBarValues.horizontalPositiveErrorValue!, yValue); - horizontalPositiveY = - transformY(errorBarValues.horizontalPositiveErrorValue!, yValue); + horizontalPositiveX = transformX( + errorBarValues.horizontalPositiveErrorValue!, + yValue, + ); + horizontalPositiveY = transformY( + errorBarValues.horizontalPositiveErrorValue!, + yValue, + ); points.add(Offset(horizontalPositiveX, horizontalPositiveY)); } if (errorBarValues.horizontalNegativeErrorValue != null) { - horizontalNegativeX = - transformX(errorBarValues.horizontalNegativeErrorValue!, yValue); - horizontalNegativeY = - transformY(errorBarValues.horizontalNegativeErrorValue!, yValue); + horizontalNegativeX = transformX( + errorBarValues.horizontalNegativeErrorValue!, + yValue, + ); + horizontalNegativeY = transformY( + errorBarValues.horizontalNegativeErrorValue!, + yValue, + ); points.add(Offset(horizontalNegativeX, horizontalNegativeY)); } double animatingPoint; if (verticalPositiveX != null && verticalPositiveY != null) { - animatingPoint = isTransposedChart - ? _errorBarMidPointX + - ((verticalPositiveX - _errorBarMidPointX) * - _effectiveAnimationFactor) - : _errorBarMidPointY - - ((_errorBarMidPointY - verticalPositiveY) * - _effectiveAnimationFactor); - - _capPointValue = animatingPoint - + animatingPoint = + isTransposedChart + ? _errorBarMidPointX + + ((verticalPositiveX - _errorBarMidPointX) * + _effectiveAnimationFactor) + : _errorBarMidPointY - + ((_errorBarMidPointY - verticalPositiveY) * + _effectiveAnimationFactor); + + _capPointValue = + animatingPoint - ((animatingPoint - (isTransposedChart ? verticalPositiveX : verticalPositiveY)) * animationFactor); - _calculateVerticalPath(_capPointValue, animationFactor, - series.capLength!, isTransposedChart); + _calculateVerticalPath( + _capPointValue, + animationFactor, + series.capLength!, + isTransposedChart, + ); } if (verticalNegativeX != null && verticalNegativeY != null) { - animatingPoint = isTransposedChart - ? _errorBarMidPointX + - ((verticalNegativeX - _errorBarMidPointX) * - _effectiveAnimationFactor) - : _errorBarMidPointY + - ((verticalNegativeY - _errorBarMidPointY) * - _effectiveAnimationFactor); - - _capPointValue = animatingPoint + + animatingPoint = + isTransposedChart + ? _errorBarMidPointX + + ((verticalNegativeX - _errorBarMidPointX) * + _effectiveAnimationFactor) + : _errorBarMidPointY + + ((verticalNegativeY - _errorBarMidPointY) * + _effectiveAnimationFactor); + + _capPointValue = + animatingPoint + (((isTransposedChart ? verticalNegativeX : verticalNegativeY) - animatingPoint) * animationFactor); - _calculateVerticalPath(_capPointValue, animationFactor, - series.capLength!, isTransposedChart); + _calculateVerticalPath( + _capPointValue, + animationFactor, + series.capLength!, + isTransposedChart, + ); } if (horizontalPositiveX != null && horizontalPositiveY != null) { - animatingPoint = isTransposedChart - ? _errorBarMidPointY - - ((_errorBarMidPointY - horizontalPositiveY) * - _effectiveAnimationFactor) - : _errorBarMidPointX + - ((horizontalPositiveX - _errorBarMidPointX) * - _effectiveAnimationFactor); - - _capPointValue = animatingPoint + + animatingPoint = + isTransposedChart + ? _errorBarMidPointY - + ((_errorBarMidPointY - horizontalPositiveY) * + _effectiveAnimationFactor) + : _errorBarMidPointX + + ((horizontalPositiveX - _errorBarMidPointX) * + _effectiveAnimationFactor); + + _capPointValue = + animatingPoint + (((isTransposedChart ? horizontalPositiveY : horizontalPositiveX) - animatingPoint) * animationFactor); - _calculateHorizontalPath(_capPointValue, animationFactor, - series.capLength!, isTransposedChart); + _calculateHorizontalPath( + _capPointValue, + animationFactor, + series.capLength!, + isTransposedChart, + ); } if (horizontalNegativeX != null && horizontalNegativeY != null) { - animatingPoint = isTransposedChart - ? _errorBarMidPointY + - ((horizontalNegativeY - _errorBarMidPointY) * - _effectiveAnimationFactor) - : _errorBarMidPointX - - ((_errorBarMidPointX - horizontalNegativeX) * - _effectiveAnimationFactor); - - _capPointValue = animatingPoint - + animatingPoint = + isTransposedChart + ? _errorBarMidPointY + + ((horizontalNegativeY - _errorBarMidPointY) * + _effectiveAnimationFactor) + : _errorBarMidPointX - + ((_errorBarMidPointX - horizontalNegativeX) * + _effectiveAnimationFactor); + + _capPointValue = + animatingPoint - ((animatingPoint - (isTransposedChart ? horizontalNegativeY : horizontalNegativeX)) * animationFactor); - _calculateHorizontalPath(_capPointValue, animationFactor, - series.capLength!, isTransposedChart); + _calculateHorizontalPath( + _capPointValue, + animationFactor, + series.capLength!, + isTransposedChart, + ); } if (points.length > _oldPoints.length) { @@ -1017,36 +1125,56 @@ class ErrorBarSegment extends ChartSegment { } } - void _calculateVerticalPath(double capPointValue, double animationFactor, - double capLength, bool isTransposedChart) { + void _calculateVerticalPath( + double capPointValue, + double animationFactor, + double capLength, + bool isTransposedChart, + ) { if (isTransposedChart) { _verticalPath.moveTo(_errorBarMidPointX, _errorBarMidPointY); _verticalPath.lineTo(capPointValue, _errorBarMidPointY); _verticalCapPath.moveTo( - capPointValue, _errorBarMidPointY - (capLength / 2)); + capPointValue, + _errorBarMidPointY - (capLength / 2), + ); _verticalCapPath.lineTo( - capPointValue, _errorBarMidPointY + (capLength / 2)); + capPointValue, + _errorBarMidPointY + (capLength / 2), + ); } else { _verticalPath.moveTo(_errorBarMidPointX, _errorBarMidPointY); _verticalPath.lineTo(_errorBarMidPointX, capPointValue); _verticalCapPath.moveTo( - _errorBarMidPointX - (capLength / 2), capPointValue); + _errorBarMidPointX - (capLength / 2), + capPointValue, + ); _verticalCapPath.lineTo( - _errorBarMidPointX + (capLength / 2), capPointValue); + _errorBarMidPointX + (capLength / 2), + capPointValue, + ); } _verticalPath.close(); _verticalCapPath.close(); } - void _calculateHorizontalPath(double capPointValue, double animationFactor, - double capLength, bool isTransposedChart) { + void _calculateHorizontalPath( + double capPointValue, + double animationFactor, + double capLength, + bool isTransposedChart, + ) { if (isTransposedChart) { _horizontalPath.moveTo(_errorBarMidPointX, _errorBarMidPointY); _horizontalPath.lineTo(_errorBarMidPointX, capPointValue); _horizontalCapPath.moveTo( - _errorBarMidPointX - (capLength / 2), capPointValue); + _errorBarMidPointX - (capLength / 2), + capPointValue, + ); _horizontalCapPath.lineTo( - _errorBarMidPointX + (capLength / 2), capPointValue); + _errorBarMidPointX + (capLength / 2), + capPointValue, + ); } else { _horizontalPath.moveTo(capPointValue, _errorBarMidPointY); _horizontalPath.lineTo(_errorBarMidPointX, _errorBarMidPointY); @@ -1147,12 +1275,7 @@ class ErrorBarMean { class AxesRange { /// Creates an instance of MinMaxValues. - AxesRange( - this.xMinimum, - this.xMaximum, - this.yMinimum, - this.yMaximum, - ); + AxesRange(this.xMinimum, this.xMaximum, this.yMinimum, this.yMaximum); /// Holds the x axis minimum value. num xMinimum; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/fast_line_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/fast_line_series.dart index 2ba7d38b1..5182822ec 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/fast_line_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/fast_line_series.dart @@ -105,8 +105,10 @@ class FastLineSeriesRenderer extends XyDataSeriesRenderer @override int dataPointIndex(Offset position, ChartSegment segment) { final FastLineSegment fastLineSegment = segment as FastLineSegment; - final int nearestPointIndex = - fastLineSegment._findNearestPoint(fastLineSegment.points, position); + final int nearestPointIndex = fastLineSegment._findNearestPoint( + fastLineSegment.points, + position, + ); final int pointIndex = fastLineSegment._drawIndexes[nearestPointIndex]; if (pointIndex != -1) { return super.actualPointIndex(pointIndex); @@ -123,8 +125,11 @@ class FastLineSeriesRenderer extends XyDataSeriesRenderer void customizeSegment(ChartSegment segment) { final Color fastlineColor = color ?? paletteColor; updateSegmentColor(segment, fastlineColor, borderWidth); - updateSegmentGradient(segment, - gradientBounds: paintBounds, borderGradient: gradient); + updateSegmentGradient( + segment, + gradientBounds: paintBounds, + borderGradient: gradient, + ); } @override @@ -136,8 +141,12 @@ class FastLineSeriesRenderer extends XyDataSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -163,7 +172,9 @@ class FastLineSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -328,8 +339,11 @@ class FastLineSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -369,14 +383,17 @@ class FastLineSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![currentSegmentIndex], point: chartPoint, series: series.widget, @@ -424,12 +441,14 @@ class FastLineSegment extends ChartSegment { int? pointIndex; final int length = points.length; for (int i = 0; i < length; i++) { - nearPointX ??= series.isTransposed - ? series.xAxis!.visibleRange!.minimum - : points[0].dx; - nearPointY ??= series.isTransposed - ? points[0].dy - : series.yAxis!.visibleRange!.minimum; + nearPointX ??= + series.isTransposed + ? series.xAxis!.visibleRange!.minimum + : points[0].dx; + nearPointY ??= + series.isTransposed + ? points[0].dy + : series.yAxis!.visibleRange!.minimum; final num touchXValue = position.dx; final num touchYValue = position.dy; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/funnel_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/funnel_series.dart index c069adeb2..06000c32f 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/funnel_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/funnel_series.dart @@ -65,9 +65,7 @@ class FunnelSeries extends ChartSeries { super.opacity, super.selectionBehavior, super.initialSelectedDataIndexes, - }) : super( - dataLabelMapper: textFieldMapper, - ); + }) : super(dataLabelMapper: textFieldMapper); /// Maps the field name, which will be considered as y-values. /// @@ -321,8 +319,9 @@ class FunnelSeries extends ChartSeries { final FunnelSeriesRendererCreatedCallback? onRendererCreated; @override - List get positions => - [ChartDataPointType.y]; + List get positions => [ + ChartDataPointType.y, + ]; @override Widget? childForSlot(SeriesSlot slot) { @@ -330,11 +329,12 @@ class FunnelSeries extends ChartSeries { case SeriesSlot.dataLabel: return dataLabelSettings.isVisible ? FunnelDataLabelContainer( - series: this, - dataSource: dataSource!, - mapper: dataLabelMapper, - builder: dataLabelSettings.builder, - settings: dataLabelSettings) + series: this, + dataSource: dataSource!, + mapper: dataLabelMapper, + builder: dataLabelSettings.builder, + settings: dataLabelSettings, + ) : null; case SeriesSlot.marker: @@ -371,7 +371,9 @@ class FunnelSeries extends ChartSeries { @override void updateRenderObject( - BuildContext context, FunnelSeriesRenderer renderObject) { + BuildContext context, + FunnelSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..yValueMapper = yValueMapper @@ -399,10 +401,11 @@ class FunnelSeries extends ChartSeries { if (onCreateRenderer != null) { renderer = onCreateRenderer!(this) as FunnelSeriesRenderer?; assert( - renderer != null, - 'This onCreateRenderer callback function should return value as ' - 'extends from ChartSeriesRenderer class and should not be return ' - 'value as null'); + renderer != null, + 'This onCreateRenderer callback function should return value as ' + 'extends from ChartSeriesRenderer class and should not be return ' + 'value as null', + ); } return renderer ?? FunnelSeriesRenderer(); } @@ -469,8 +472,10 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer set gapRatio(double value) { if (_gapRatio != value) { _gapRatio = value; - assert(_gapRatio >= 0 && _gapRatio <= 1, - 'The gap ratio for the funnel chart must be between 0 and 1.'); + assert( + _gapRatio >= 0 && _gapRatio <= 1, + 'The gap ratio for the funnel chart must be between 0 and 1.', + ); _gapRatio = clampDouble(value, 0, 1); markNeedsLayout(); } @@ -533,9 +538,7 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer @override Iterable get children { - return [ - if (dataLabelContainer != null) dataLabelContainer!, - ]; + return [if (dataLabelContainer != null) dataLabelContainer!]; } /// Stores pointer down time to determine whether a long press interaction is handled at pointer up @@ -553,8 +556,9 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer final List points = segments[segmentsLastIndex - current.dataPointIndex].points; final Rect region = _calculateSegmentRect( - segments[segmentsLastIndex - current.dataPointIndex].points, - segmentsLastIndex - current.dataPointIndex); + segments[segmentsLastIndex - current.dataPointIndex].points, + segmentsLastIndex - current.dataPointIndex, + ); final List connectorPoints = segments[0].points; final double connectorLength = _calculateConnectorLength( connectorPoints, @@ -563,22 +567,27 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer final Offset insideLabelOffset = dataLabelSettings.labelPosition == ChartDataLabelPosition.inside - ? Offset(region.left + region.width / 2 - size.width / 2, - region.top + region.height / 2 - size.height / 2) - : Offset((points[0].dx + points[1].dx) / 2 - size.width / 2, - (points[0].dy + points[2].dy) / 2 - size.height / 2); + ? Offset( + region.left + region.width / 2 - size.width / 2, + region.top + region.height / 2 - size.height / 2, + ) + : Offset( + (points[0].dx + points[1].dx) / 2 - size.width / 2, + (points[0].dy + points[2].dy) / 2 - size.height / 2, + ); final double connectorLengthWithXValue = insideLabelOffset.dx + connectorLength + size.width / 2; final Offset outsideLabelOffset = Offset( - (connectorLengthWithXValue + - size.width + - dataLabelSettings.margin.left + - dataLabelSettings.margin.right > - paintBounds.right) - ? connectorLengthWithXValue - - (percentToValue(explodeOffset, paintBounds.width)!) - : connectorLengthWithXValue, - insideLabelOffset.dy); + (connectorLengthWithXValue + + size.width + + dataLabelSettings.margin.left + + dataLabelSettings.margin.right > + paintBounds.right) + ? connectorLengthWithXValue - + (percentToValue(explodeOffset, paintBounds.width)!) + : connectorLengthWithXValue, + insideLabelOffset.dy, + ); final Offset finalOffset = dataLabelSettings.labelPosition == ChartDataLabelPosition.inside ? insideLabelOffset @@ -621,26 +630,33 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer ..lineTo(endPoint, y); } - RRect _calculateRect(Offset offset, int padding, EdgeInsets margin, Size size, - ChartDataLabelPosition labelPosition) { + RRect _calculateRect( + Offset offset, + int padding, + EdgeInsets margin, + Size size, + ChartDataLabelPosition labelPosition, + ) { if (labelPosition == ChartDataLabelPosition.inside) { return RRect.fromRectAndRadius( - Rect.fromLTWH( - offset.dx - padding, - offset.dy - padding, - size.width + (2 * padding), - size.height + (2 * padding), - ), - Radius.circular(dataLabelSettings.borderRadius)); - } - return RRect.fromRectAndRadius( Rect.fromLTWH( - offset.dx, - offset.dy - margin.top, - size.width + margin.top + margin.left, - size.height + margin.bottom + margin.right, + offset.dx - padding, + offset.dy - padding, + size.width + (2 * padding), + size.height + (2 * padding), ), - Radius.circular(dataLabelSettings.borderRadius)); + Radius.circular(dataLabelSettings.borderRadius), + ); + } + return RRect.fromRectAndRadius( + Rect.fromLTWH( + offset.dx, + offset.dy - margin.top, + size.width + margin.top + margin.left, + size.height + margin.bottom + margin.right, + ), + Radius.circular(dataLabelSettings.borderRadius), + ); } Rect _calculateSegmentRect(List points, int index) { @@ -650,22 +666,31 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer final double x = (points[0].dx + points[bottom].dx) / 2; final double right = (points[1].dx + points[bottom - 1].dx) / 2; final Rect region = Rect.fromLTWH( - x, points[0].dy, right - x, points[bottom].dy - points[0].dy); + x, + points[0].dy, + right - x, + points[bottom].dy - points[0].dy, + ); return region; } double _calculateConnectorLength( - List points, DataLabelSettings settings) { - final Path segmentPath = Path() - ..moveTo(points[0].dx, points[0].dy) - ..lineTo(points[1].dx, points[1].dy) - ..lineTo(points[2].dx, points[2].dy) - ..lineTo(points[3].dx, points[3].dy) - ..close(); + List points, + DataLabelSettings settings, + ) { + final Path segmentPath = + Path() + ..moveTo(points[0].dx, points[0].dy) + ..lineTo(points[1].dx, points[1].dy) + ..lineTo(points[2].dx, points[2].dy) + ..lineTo(points[3].dx, points[3].dy) + ..close(); final Rect segmentBounds = segmentPath.getBounds(); - final double connectorLength = percentToValue( - settings.connectorLineSettings.length ?? '0%', - _plotAreaBounds.width / 2)! + + final double connectorLength = + percentToValue( + settings.connectorLineSettings.length ?? '0%', + _plotAreaBounds.width / 2, + )! + (segmentBounds.width / 2); return connectorLength; } @@ -694,8 +719,13 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer return isCollide; } - String _getTrimmedText(String? text, Rect rect, Offset labelLocation, - Rect region, TextStyle style) { + String _getTrimmedText( + String? text, + Rect rect, + Offset labelLocation, + Rect region, + TextStyle style, + ) { const int labelPadding = 2; const String ellipse = '...'; String label = text!; @@ -713,17 +743,22 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer } final Size trimTextSize = measureText(label, style); final Rect trimRect = Rect.fromLTWH( - labelLocation.dx - labelPadding, - labelLocation.dy - labelPadding, - trimTextSize.width + (2 * labelPadding), - trimTextSize.height + (2 * labelPadding)); + labelLocation.dx - labelPadding, + labelLocation.dy - labelPadding, + trimTextSize.width + (2 * labelPadding), + trimTextSize.height + (2 * labelPadding), + ); isCollide = _isLabelsColliding(trimRect, region); } return label == ellipse ? '' : label; } - String _addEllipse(String text, int maxLength, String ellipse, - {bool isRtl = false}) { + String _addEllipse( + String text, + int maxLength, + String ellipse, { + bool isRtl = false, + }) { if (isRtl) { if (text.contains(ellipse)) { text = text.replaceAll(ellipse, ''); @@ -772,8 +807,14 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer final int segmentsLastIndex = segments.length - 1; final int dataPointIndex = segmentsLastIndex - index; final ChartSegment segment = segments[dataPointIndex]; - Color surfaceColor = dataLabelSurfaceColor(fillPaint.color, dataPointIndex, - dataLabelSettings.labelPosition, chartThemeData, themeData, segment); + Color surfaceColor = dataLabelSurfaceColor( + fillPaint.color, + dataPointIndex, + dataLabelSettings.labelPosition, + chartThemeData, + themeData, + segment, + ); TextStyle effectiveTextStyle = saturatedTextStyle(surfaceColor, style); final EdgeInsets margin = dataLabelSettings.margin; final Radius radius = Radius.circular(dataLabelSettings.borderRadius); @@ -790,11 +831,13 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer connectorPoints, dataLabelSettings, ); - final Paint connectorPaint = Paint() - ..color = dataLabelSettings.connectorLineSettings.color ?? - segments[segmentsLastIndex - index].fillPaint.color - ..strokeWidth = dataLabelSettings.connectorLineSettings.width - ..style = PaintingStyle.stroke; + final Paint connectorPaint = + Paint() + ..color = + dataLabelSettings.connectorLineSettings.color ?? + segments[segmentsLastIndex - index].fillPaint.color + ..strokeWidth = dataLabelSettings.connectorLineSettings.width + ..style = PaintingStyle.stroke; if ((yValues[index] == 0 && !dataLabelSettings.showZeroValue) || yValues[index].isNaN || @@ -804,11 +847,14 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer for (int i = segmentsLastIndex; i >= 0; i--) { final Rect region = _calculateSegmentRect(segmentAt(i).points, i); - labels.add(Rect.fromLTWH( + labels.add( + Rect.fromLTWH( region.left + region.width / 2 - (size.width / 2) - labelPadding, region.top + region.height / 2 - (size.height / 2) - labelPadding, size.width + (2 * labelPadding), - size.height + (2 * labelPadding))); + size.height + (2 * labelPadding), + ), + ); } if (!offset.dx.isNaN && !offset.dy.isNaN) { @@ -816,31 +862,47 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer if (fillPaint.color != Colors.transparent || (strokePaint.color != const Color.fromARGB(0, 25, 5, 5) && strokePaint.strokeWidth > 0)) { - RRect labelRect = - _calculateRect(offset, labelPadding, margin, size, labelPosition); + RRect labelRect = _calculateRect( + offset, + labelPadding, + margin, + size, + labelPosition, + ); final Rect region = _calculateSegmentRect( - segments[segmentsLastIndex - index].points, - segmentsLastIndex - index); - final bool isDataLabelCollide = (_findingCollision( - labels[index], previousRect, region)) && + segments[segmentsLastIndex - index].points, + segmentsLastIndex - index, + ); + final bool isDataLabelCollide = + (_findingCollision(labels[index], previousRect, region)) && dataLabelSettings.labelPosition != ChartDataLabelPosition.outside; if (isDataLabelCollide) { switch (dataLabelSettings.overflowMode) { case OverflowMode.trim: - dataLabel = _getTrimmedText(dataLabel, labels[index], - finalOffset, region, effectiveTextStyle); - final Size trimSize = - measureText(dataLabel, effectiveTextStyle); + dataLabel = _getTrimmedText( + dataLabel, + labels[index], + finalOffset, + region, + effectiveTextStyle, + ); + final Size trimSize = measureText( + dataLabel, + effectiveTextStyle, + ); finalOffset = Offset( - finalOffset.dx + size.width / 2 - trimSize.width / 2, - finalOffset.dy + size.height / 2 - trimSize.height / 2); + finalOffset.dx + size.width / 2 - trimSize.width / 2, + finalOffset.dy + size.height / 2 - trimSize.height / 2, + ); labelRect = RRect.fromRectAndRadius( - Rect.fromLTWH( - finalOffset.dx - labelPadding, - finalOffset.dy - labelPadding, - trimSize.width + (2 * labelPadding), - trimSize.height + (2 * labelPadding)), - radius); + Rect.fromLTWH( + finalOffset.dx - labelPadding, + finalOffset.dy - labelPadding, + trimSize.width + (2 * labelPadding), + trimSize.height + (2 * labelPadding), + ), + radius, + ); break; case OverflowMode.hide: dataLabel = ''; @@ -860,12 +922,13 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer !dataLabelSettings.useSeriesColor) { if (style.color == Colors.transparent) { surfaceColor = dataLabelSurfaceColor( - fillPaint.color, - dataPointIndex, - ChartDataLabelPosition.outside, - chartThemeData, - themeData, - segment); + fillPaint.color, + dataPointIndex, + ChartDataLabelPosition.outside, + chartThemeData, + themeData, + segment, + ); effectiveTextStyle = saturatedTextStyle(surfaceColor, style); } } @@ -890,34 +953,49 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer labelPosition = ChartDataLabelPosition.outside; offset = dataLabelSettings.labelPosition == ChartDataLabelPosition.inside - ? Offset((points[0].dx + points[1].dx) / 2 - size.width / 2, - (points[0].dy + points[2].dy) / 2 - size.height / 2) + ? Offset( + (points[0].dx + points[1].dx) / 2 - size.width / 2, + (points[0].dy + points[2].dy) / 2 - size.height / 2, + ) : offset; - finalOffset = dataLabelSettings.labelPosition == - ChartDataLabelPosition.outside - ? offset - : offset + Offset(connectorLength + size.width / 2, 0); + finalOffset = + dataLabelSettings.labelPosition == + ChartDataLabelPosition.outside + ? offset + : offset + Offset(connectorLength + size.width / 2, 0); labelRect = _calculateRect( - finalOffset, labelPadding, margin, size, labelPosition); + finalOffset, + labelPadding, + margin, + size, + labelPosition, + ); connectorPath = _calculateConnectorPath(index, finalOffset, size); if (_plotAreaBounds.right < labelRect.right) { isOverlapRight = true; labelRect = RRect.fromRectAndRadius( - Rect.fromLTRB( - _plotAreaBounds.right - labelRect.width - labelPadding, - labelRect.top, - _plotAreaBounds.right - labelPadding, - labelRect.bottom), - radius); + Rect.fromLTRB( + _plotAreaBounds.right - labelRect.width - labelPadding, + labelRect.top, + _plotAreaBounds.right - labelPadding, + labelRect.bottom, + ), + radius, + ); } - final RRect previous = previousRect.isEmpty - ? labelRect - : previousRect[previousRect.length - 1]; - final bool isIntersectOutside = - _isFunnelLabelIntersectOutside(labelRect, previous); + final RRect previous = + previousRect.isEmpty + ? labelRect + : previousRect[previousRect.length - 1]; + final bool isIntersectOutside = _isFunnelLabelIntersectOutside( + labelRect, + previous, + ); if (!isIntersectOutside && isOverlapRight) { - finalOffset = Offset(labelRect.left, - (labelRect.top + labelRect.height / 2) - size.height / 2); + finalOffset = Offset( + labelRect.left, + (labelRect.top + labelRect.height / 2) - size.height / 2, + ); connectorPath = _calculateConnectorPath(index, finalOffset, size); } if (dataLabelSettings.labelIntersectAction == @@ -928,21 +1006,31 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer dataLabelSettings.labelIntersectAction == LabelIntersectAction.shift) { labelRect = RRect.fromRectAndRadius( - Rect.fromLTWH( + Rect.fromLTWH( + labelRect.left, + previous.top - labelPadding - labelRect.height, + labelRect.width, + labelRect.height, + ), + radius, + ); + + connectorPath = + Path() + ..moveTo(startPoint, finalOffset.dy + size.height / 2) + ..lineTo( + labelRect.left - connectorPadding, + finalOffset.dy + size.height / 2, + ) + ..lineTo( labelRect.left, - previous.top - labelPadding - labelRect.height, - labelRect.width, - labelRect.height), - radius); - - connectorPath = Path() - ..moveTo(startPoint, finalOffset.dy + size.height / 2) - ..lineTo(labelRect.left - connectorPadding, - finalOffset.dy + size.height / 2) - ..lineTo(labelRect.left, labelRect.top + labelRect.height / 2); + labelRect.top + labelRect.height / 2, + ); } - finalOffset = Offset(labelRect.left + margin.left, - (labelRect.top + labelRect.height / 2) - size.height / 2); + finalOffset = Offset( + labelRect.left + margin.left, + (labelRect.top + labelRect.height / 2) - size.height / 2, + ); } previousRect.add(labelRect); if (labelRect.top < dataLabelSettings.margin.top) { @@ -970,15 +1058,21 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer } void drawDataLabel( - Canvas canvas, String text, Offset point, TextStyle style, int angle, - [bool? isRtl]) { + Canvas canvas, + String text, + Offset point, + TextStyle style, + int angle, [ + bool? isRtl, + ]) { final int maxLines = getMaxLinesContent(text); final TextSpan span = TextSpan(text: text, style: style); final TextPainter tp = TextPainter( - text: span, - textDirection: (isRtl ?? false) ? TextDirection.rtl : TextDirection.ltr, - textAlign: TextAlign.center, - maxLines: maxLines); + text: span, + textDirection: (isRtl ?? false) ? TextDirection.rtl : TextDirection.ltr, + textAlign: TextAlign.center, + maxLines: maxLines, + ); tp.layout(); canvas.save(); canvas.translate(point.dx + tp.width / 2, point.dy + tp.height / 2); @@ -1021,7 +1115,13 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer } } super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); markNeedsLegendUpdate(); populateChartPoints(); } @@ -1069,8 +1169,17 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer yLists?.add(yValues); } } - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } @override @@ -1108,10 +1217,14 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer } _plotAreaBounds = Rect.fromLTWH(0, 0, size.width, size.height); - _triangleSize = Size(percentToValue(width, _plotAreaBounds.width)!, - percentToValue(height, _plotAreaBounds.height)!); - _neckSize = Size(percentToValue(neckWidth, _plotAreaBounds.width)!, - percentToValue(neckHeight, _plotAreaBounds.height)!); + _triangleSize = Size( + percentToValue(width, _plotAreaBounds.width)!, + percentToValue(height, _plotAreaBounds.height)!, + ); + _neckSize = Size( + percentToValue(neckWidth, _plotAreaBounds.width)!, + percentToValue(neckHeight, _plotAreaBounds.height)!, + ); _coefficient = 1 / (_sumOfY * (1 + gapRatio / (1 - gapRatio))); _spacing = gapRatio / (dataCount - emptyPointIndexes.length - 1); _y = 0; @@ -1144,7 +1257,8 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer .._neckSize = _neckSize .._plotAreaBounds = _plotAreaBounds ..isExploded = explode && i == explodeIndex - ..isEmpty = (emptyPointSettings.mode != EmptyPointMode.drop && + ..isEmpty = + (emptyPointSettings.mode != EmptyPointMode.drop && emptyPointSettings.mode != EmptyPointMode.gap) && isEmpty(i); @@ -1164,12 +1278,12 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer } @override - List? buildLegendItems(int index) { - final List legendItems = []; + List? buildLegendItems(int index) { + final List legendItems = []; final int segmentsCount = segments.length; for (int i = 0; i < dataCount; i++) { final int legendIndex = dataCount - 1 - i; - final ChartLegendItem legendItem = ChartLegendItem( + final FunnelLegendItem legendItem = FunnelLegendItem( text: xRawValues[legendIndex].toString(), iconType: toLegendShapeMarkerType(legendIconType, this), iconColor: effectiveColor(legendIndex), @@ -1177,9 +1291,10 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer series: this, seriesIndex: index, pointIndex: legendIndex, - imageProvider: legendIconType == LegendIconType.image - ? parent?.legend?.image - : null, + imageProvider: + legendIconType == LegendIconType.image + ? parent?.legend?.image + : null, isToggled: i < segmentsCount && !segmentAt(i).isVisible, onTap: handleLegendItemTapped, onRender: _handleLegendItemCreated, @@ -1191,7 +1306,7 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer void _handleLegendItemCreated(ItemRendererDetails details) { if (parent != null && parent!.onLegendItemRender != null) { - final ChartLegendItem item = details.item as ChartLegendItem; + final FunnelLegendItem item = details.item as FunnelLegendItem; final LegendIconType iconType = toLegendIconType(details.iconType); final LegendRenderArgs args = LegendRenderArgs(item.seriesIndex, item.pointIndex) @@ -1201,7 +1316,9 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer parent!.onLegendItemRender!(args); if (args.legendIconType != iconType) { details.iconType = toLegendShapeMarkerType( - args.legendIconType ?? LegendIconType.seriesType, this); + args.legendIconType ?? LegendIconType.seriesType, + this, + ); } details ..text = args.text ?? '' @@ -1213,7 +1330,7 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer void handleLegendItemTapped(LegendItem item, bool isToggled) { super.handleLegendItemTapped(item, isToggled); - final ChartLegendItem legendItem = item as ChartLegendItem; + final FunnelLegendItem legendItem = item as FunnelLegendItem; final int toggledIndex = legendItem.pointIndex; if (toggledIndex < segments.length) { segmentAt(toggledIndex).isVisible = !isToggled; @@ -1229,8 +1346,11 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = - clipRect(paintBounds, animationFactor, isTransposed: true); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isTransposed: true, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -1325,8 +1445,10 @@ class FunnelSeriesRenderer extends ChartSeriesRenderer @override ChartSegment segmentAt(int segmentPointIndex) { - return segments.firstWhere((ChartSegment segment) => - segment.currentSegmentIndex == segmentPointIndex); + return segments.firstWhere( + (ChartSegment segment) => + segment.currentSegmentIndex == segmentPointIndex, + ); } @override @@ -1364,7 +1486,8 @@ class FunnelSegment extends ChartSegment { final double triangleHeight = _triangleSize.height; final double funnelHeight = triangleHeight - neckSizeHeight; - final double left = (isExploded + final double left = + (isExploded ? percentToValue(series.explodeOffset, _plotAreaBounds.width)! : 0) + (_plotAreaBounds.width - triangleWidth) / 2; @@ -1373,17 +1496,19 @@ class FunnelSegment extends ChartSegment { double topY = y * triangleHeight; double bottomY = topY + _height * triangleHeight; - double funnelWidth = neckSizeWidth + + double funnelWidth = + neckSizeWidth + (triangleWidth - neckSizeWidth) * ((funnelHeight - topY) / funnelHeight); double topX1 = (triangleWidth / 2) - funnelWidth / 2; double topX2 = topX1 + funnelWidth; - funnelWidth = (bottomY > funnelHeight || triangleHeight == neckSizeHeight) - ? neckSizeWidth - : neckSizeWidth + - (triangleWidth - neckSizeWidth) * - ((funnelHeight - bottomY) / funnelHeight); + funnelWidth = + (bottomY > funnelHeight || triangleHeight == neckSizeHeight) + ? neckSizeWidth + : neckSizeWidth + + (triangleWidth - neckSizeWidth) * + ((funnelHeight - bottomY) / funnelHeight); double bottomX1 = triangleWidth / 2 - funnelWidth / 2; double bottomX2 = bottomX1 + funnelWidth; @@ -1456,14 +1581,16 @@ class FunnelSegment extends ChartSegment { @override TooltipInfo? tooltipInfo({Offset? position, int? pointIndex}) { final ChartPoint point = ChartPoint( - x: series.xRawValues[currentSegmentIndex], - y: series.yValues[currentSegmentIndex]); + x: series.xRawValues[currentSegmentIndex], + y: series.yValues[currentSegmentIndex], + ); final Offset location = path.getBounds().center; final TooltipPosition? tooltipPosition = series.parent?.tooltipBehavior?.tooltipPosition; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? series.localToGlobal(position ?? location) - : series.localToGlobal(location); + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? series.localToGlobal(position ?? location) + : series.localToGlobal(location); return ChartTooltipInfo( primaryPosition: preferredPos, secondaryPosition: preferredPos, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_open_close_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_open_close_series.dart index d40feb09b..def82005c 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_open_close_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_open_close_series.dart @@ -87,10 +87,14 @@ class HiloOpenCloseSeries extends FinancialSeriesBase { /// Creates series renderer for hilo open close series. class HiloOpenCloseSeriesRenderer - extends FinancialSeriesRendererBase with SegmentAnimationMixin { + extends FinancialSeriesRendererBase + with SegmentAnimationMixin { @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { if (current.position != ChartDataPointType.open || current.position != ChartDataPointType.close) { return super.dataLabelPosition(current, alignment, size); @@ -107,46 +111,77 @@ class HiloOpenCloseSeriesRenderer } Offset _calculateDataLabelOpenPosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: case ChartDataLabelAlignment.middle: return _calculateOpenAndClosePosition( - x, y, ChartDataLabelAlignment.outer, size, ChartDataPointType.open); + x, + y, + ChartDataLabelAlignment.outer, + size, + ChartDataPointType.open, + ); case ChartDataLabelAlignment.bottom: return _calculateOpenAndClosePosition( - x, y, ChartDataLabelAlignment.top, size, ChartDataPointType.open); + x, + y, + ChartDataLabelAlignment.top, + size, + ChartDataPointType.open, + ); } } Offset _calculateDataLabelClosePosition( - num x, num y, ChartDataLabelAlignment alignment, Size size) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ) { switch (alignment) { case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.top: case ChartDataLabelAlignment.middle: - return _calculateOpenAndClosePosition(x, y, - ChartDataLabelAlignment.outer, size, ChartDataPointType.close); + return _calculateOpenAndClosePosition( + x, + y, + ChartDataLabelAlignment.outer, + size, + ChartDataPointType.close, + ); case ChartDataLabelAlignment.bottom: return _calculateOpenAndClosePosition( - x, y, ChartDataLabelAlignment.top, size, ChartDataPointType.close); + x, + y, + ChartDataLabelAlignment.top, + size, + ChartDataPointType.close, + ); } } Offset _calculateOpenAndClosePosition( - num x, - num y, - ChartDataLabelAlignment alignment, - Size size, - ChartDataPointType position) { + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + ChartDataPointType position, + ) { final EdgeInsets margin = dataLabelSettings.margin; - final double openAndCloseDataLabelPadding = - _openAndCloseDataLabelPadding(position, margin); + final double openAndCloseDataLabelPadding = _openAndCloseDataLabelPadding( + position, + margin, + ); double translationX = 0.0; double translationY = 0.0; @@ -177,7 +212,9 @@ class HiloOpenCloseSeriesRenderer } double _openAndCloseDataLabelPadding( - ChartDataPointType position, EdgeInsets margin) { + ChartDataPointType position, + EdgeInsets margin, + ) { double paddingValue = dataLabelPadding + (2 * margin.left); if (isTransposed) { paddingValue = dataLabelPadding + (2 * margin.top); @@ -223,12 +260,18 @@ class HiloOpenCloseSeriesRenderer final int index = segment.currentSegmentIndex; final bool isBull = closeValues[index] > openValues[index]; final Color color = isBull ? bullColor : bearColor; - final Color? segmentColor = pointColorMapper != null && - pointColors[segment.currentSegmentIndex] != null - ? null - : color; - updateSegmentColor(segment, segmentColor, borderWidth, - fillColor: segmentColor, isLineType: true); + final Color? segmentColor = + pointColorMapper != null && + pointColors[segment.currentSegmentIndex] != null + ? null + : color; + updateSegmentColor( + segment, + segmentColor, + borderWidth, + fillColor: segmentColor, + isLineType: true, + ); updateSegmentGradient(segment); } } @@ -248,7 +291,9 @@ class HiloOpenCloseSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -325,15 +370,19 @@ class HiloOpenCloseSegment extends ChartSegment { } if (_oldPoints.isEmpty) { - final Offset center = - Offset(transformX(centerX, centerY), transformY(centerX, centerY)); + final Offset center = Offset( + transformX(centerX, centerY), + transformY(centerX, centerY), + ); _oldPoints.add(center); _oldPoints.add(center); - _oldPoints - .add(Offset(transformX(left, centerY), transformY(left, centerY))); + _oldPoints.add( + Offset(transformX(left, centerY), transformY(left, centerY)), + ); _oldPoints.add(center); - _oldPoints - .add(Offset(transformX(right, centerY), transformY(right, centerY))); + _oldPoints.add( + Offset(transformX(right, centerY), transformY(right, centerY)), + ); _oldPoints.add(center); } @@ -346,23 +395,35 @@ class HiloOpenCloseSegment extends ChartSegment { bool contains(Offset position) { late Rect segmentRegion; if (series.isTransposed) { - final Offset start = series.yAxis != null && series.yAxis!.isInversed - ? points[0] - : points[1]; - final Offset end = series.yAxis != null && series.yAxis!.isInversed - ? points[1] - : points[0]; + final Offset start = + series.yAxis != null && series.yAxis!.isInversed + ? points[0] + : points[1]; + final Offset end = + series.yAxis != null && series.yAxis!.isInversed + ? points[1] + : points[0]; segmentRegion = Rect.fromLTRB( - start.dx, start.dy - hiloPadding, end.dx, end.dy + hiloPadding); + start.dx, + start.dy - hiloPadding, + end.dx, + end.dy + hiloPadding, + ); } else { - final Offset start = series.yAxis != null && series.yAxis!.isInversed - ? points[1] - : points[0]; - final Offset end = series.yAxis != null && series.yAxis!.isInversed - ? points[0] - : points[1]; + final Offset start = + series.yAxis != null && series.yAxis!.isInversed + ? points[1] + : points[0]; + final Offset end = + series.yAxis != null && series.yAxis!.isInversed + ? points[0] + : points[1]; segmentRegion = Rect.fromLTRB( - start.dx - hiloPadding, start.dy, end.dx + hiloPadding, end.dy); + start.dx - hiloPadding, + start.dy, + end.dx + hiloPadding, + end.dy, + ); } if (segmentRegion.contains(position)) { @@ -395,9 +456,10 @@ class HiloOpenCloseSegment extends ChartSegment { primaryPosition: preferredPos, secondaryPosition: preferredPos, text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -414,8 +476,10 @@ class HiloOpenCloseSegment extends ChartSegment { @override TrackballInfo? trackballInfo(Offset position, int pointIndex) { if (pointIndex != -1 && points.isNotEmpty) { - final Offset preferredPos = - Offset(series.pointToPixelX(x, high), series.pointToPixelY(x, high)); + final Offset preferredPos = Offset( + series.pointToPixelX(x, high), + series.pointToPixelY(x, high), + ); final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( position: preferredPos, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_series.dart index 56ba4ba65..e702a6f36 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/hilo_series.dart @@ -120,7 +120,9 @@ class HiloSeries extends RangeSeriesBase { @override void updateRenderObject( - BuildContext context, HiloSeriesRenderer renderObject) { + BuildContext context, + HiloSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..spacing = spacing @@ -186,7 +188,9 @@ class HiloSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -240,14 +244,18 @@ class HiloSegment extends ChartSegment { if (series.showIndicationForSameValues) { if (series.isTransposed) { points.add( - Offset(transformX(xValue, high) - 2, transformY(xValue, high))); + Offset(transformX(xValue, high) - 2, transformY(xValue, high)), + ); points.add( - Offset(transformX(xValue, low) + 2, transformY(xValue, low))); + Offset(transformX(xValue, low) + 2, transformY(xValue, low)), + ); } else { points.add( - Offset(transformX(xValue, high), transformY(xValue, high) - 2)); + Offset(transformX(xValue, high), transformY(xValue, high) - 2), + ); points.add( - Offset(transformX(xValue, low), transformY(xValue, low) + 2)); + Offset(transformX(xValue, low), transformY(xValue, low) + 2), + ); } } } else { @@ -256,8 +264,10 @@ class HiloSegment extends ChartSegment { } if (_oldPoints.isEmpty) { - final Offset center = - Offset(transformX(xValue, centerY), transformY(xValue, centerY)); + final Offset center = Offset( + transformX(xValue, centerY), + transformY(xValue, centerY), + ); _oldPoints.addAll([center, center]); } @@ -274,23 +284,35 @@ class HiloSegment extends ChartSegment { late Rect segmentBounds; if (series.isTransposed) { - final Offset start = series.yAxis != null && series.yAxis!.isInversed - ? points[0] - : points[1]; - final Offset end = series.yAxis != null && series.yAxis!.isInversed - ? points[1] - : points[0]; + final Offset start = + series.yAxis != null && series.yAxis!.isInversed + ? points[0] + : points[1]; + final Offset end = + series.yAxis != null && series.yAxis!.isInversed + ? points[1] + : points[0]; segmentBounds = Rect.fromLTRB( - start.dx, start.dy - hiloPadding, end.dx, end.dy + hiloPadding); + start.dx, + start.dy - hiloPadding, + end.dx, + end.dy + hiloPadding, + ); } else { - final Offset start = series.yAxis != null && series.yAxis!.isInversed - ? points[1] - : points[0]; - final Offset end = series.yAxis != null && series.yAxis!.isInversed - ? points[0] - : points[1]; + final Offset start = + series.yAxis != null && series.yAxis!.isInversed + ? points[1] + : points[0]; + final Offset end = + series.yAxis != null && series.yAxis!.isInversed + ? points[0] + : points[1]; segmentBounds = Rect.fromLTRB( - start.dx - hiloPadding, start.dy, end.dx + hiloPadding, end.dy); + start.dx - hiloPadding, + start.dy, + end.dx + hiloPadding, + end.dy, + ); } if (segmentBounds.contains(position)) { @@ -322,14 +344,17 @@ class HiloSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = points[0]; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/histogram_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/histogram_series.dart index a992d98a9..001a16542 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/histogram_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/histogram_series.dart @@ -354,7 +354,9 @@ class HistogramSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, HistogramSeriesRenderer renderObject) { + BuildContext context, + HistogramSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..binInterval = binInterval @@ -387,7 +389,13 @@ class HistogramSeriesRenderer extends HistogramSeriesRendererBase { List>? fLists, ]) { super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); populateChartPoints(); } @@ -414,12 +422,18 @@ class HistogramSeriesRenderer extends HistogramSeriesRendererBase { final HistogramSegment histogramSegment = segment as HistogramSegment; updateSegmentTrackerStyle( - histogramSegment, trackColor, trackBorderColor, trackBorderWidth); + histogramSegment, + trackColor, + trackBorderColor, + trackBorderWidth, + ); updateSegmentColor(histogramSegment, borderColor, borderWidth); - updateSegmentGradient(histogramSegment, - gradientBounds: histogramSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + histogramSegment, + gradientBounds: histogramSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } } @@ -436,7 +450,9 @@ class HistogramSegment extends ChartSegment with BarSeriesTrackerMixin { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -445,8 +461,11 @@ class HistogramSegment extends ChartSegment with BarSeriesTrackerMixin { } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -519,20 +538,26 @@ class HistogramSegment extends ChartSegment with BarSeriesTrackerMixin { final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: _tooltipTextFormat(chartPoint, digits), - header: tooltipBehavior.shared - ? _tooltipText(series.tooltipHeaderText(chartPoint), digits) - : series.name, - data: series.dataSource![ - pointIndex >= dataSourceLength ? dataSourceLength - 1 : pointIndex], + header: + tooltipBehavior.shared + ? _tooltipText(series.tooltipHeaderText(chartPoint), digits) + : series.name, + data: + series.dataSource![pointIndex >= dataSourceLength + ? dataSourceLength - 1 + : pointIndex], point: chartPoint, series: series.widget, renderer: series, @@ -551,8 +576,10 @@ class HistogramSegment extends ChartSegment with BarSeriesTrackerMixin { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, y), series.pointToPixelY(x, y)), + position: Offset( + series.pointToPixelX(x, y), + series.pointToPixelY(x, y), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -594,10 +621,16 @@ class HistogramSegment extends ChartSegment with BarSeriesTrackerMixin { final num xValue = series.xValues[currentSegmentIndex]; final num binWidth = _binWidth / 2; - final String x1 = - formatNumericValue(xValue - binWidth, series.xAxis, digits); - final String x2 = - formatNumericValue(xValue + binWidth, series.xAxis, digits); + final String x1 = formatNumericValue( + xValue - binWidth, + series.xAxis, + digits, + ); + final String x2 = formatNumericValue( + xValue + binWidth, + series.xAxis, + digits, + ); if (text.contains(':')) { // Tooltip text. text = '$x1 - $x2 : ${text.split(':')[1]}'; @@ -633,8 +666,11 @@ class HistogramSegment extends ChartSegment with BarSeriesTrackerMixin { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/line_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/line_series.dart index 7f368985c..5d1188cc1 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/line_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/line_series.dart @@ -100,7 +100,11 @@ class LineSeriesRenderer extends XyDataSeriesRenderer num y2 = double.nan; final int nextIndex = nextIndexConsideringEmptyPointMode( - index, emptyPointSettings.mode, yValues, dataCount); + index, + emptyPointSettings.mode, + yValues, + dataCount, + ); if (nextIndex != -1) { x2 = xValues[nextIndex]; y2 = yValues[nextIndex]; @@ -138,8 +142,12 @@ class LineSeriesRenderer extends XyDataSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -171,7 +179,9 @@ class LineSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -233,8 +243,11 @@ class LineSegment extends ChartSegment { bool contains(Offset position) { if (points.isNotEmpty) { final ChartMarker marker = series.markerAt(currentSegmentIndex); - return tooltipTouchBounds(points[0], marker.width, marker.height) - .contains(position); + return tooltipTouchBounds( + points[0], + marker.width, + marker.height, + ).contains(position); } return false; } @@ -258,14 +271,17 @@ class LineSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = points[0]; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/pie_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/pie_series.dart index badf12bdc..f643f6388 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/pie_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/pie_series.dart @@ -67,10 +67,7 @@ class PieSeries extends CircularSeries { super.sortingOrder, super.legendIconType, super.initialSelectedDataIndexes, - }) : super( - borderColor: strokeColor, - borderWidth: strokeWidth, - ); + }) : super(borderColor: strokeColor, borderWidth: strokeWidth); /// Enables or disables the explode of slices on tap. /// @@ -177,8 +174,9 @@ class PieSeries extends CircularSeries { final ActivationMode explodeGesture; @override - List get positions => - [ChartDataPointType.y]; + List get positions => [ + ChartDataPointType.y, + ]; /// Create the pie series renderer. @override @@ -206,7 +204,9 @@ class PieSeries extends CircularSeries { @override void updateRenderObject( - BuildContext context, PieSeriesRenderer renderObject) { + BuildContext context, + PieSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..explode = explode @@ -294,9 +294,13 @@ class PieSeriesRenderer extends CircularSeriesRenderer { final double degree = (yValue.abs() / (sumOfY != 0 ? sumOfY : 1)) * totalAngle; final double pointEndAngle = pointStartAngle + degree; - final double outerRadius = pointRadii.isNotEmpty - ? percentToValue(pointRadii[index], (min(size.width, size.height)) / 2)! - : currentRadius; + final double outerRadius = + pointRadii.isNotEmpty + ? percentToValue( + pointRadii[index], + (min(size.width, size.height)) / 2, + )! + : currentRadius; segment as PieSegment ..series = this @@ -306,7 +310,8 @@ class PieSeriesRenderer extends CircularSeriesRenderer { .._outerRadius = outerRadius .._center = center .._isExploded = explode && (index == explodeIndex || explodeAll) - ..isEmpty = (emptyPointSettings.mode != EmptyPointMode.drop && + ..isEmpty = + (emptyPointSettings.mode != EmptyPointMode.drop && emptyPointSettings.mode != EmptyPointMode.gap) && isEmpty(index); @@ -411,7 +416,10 @@ class PieSeriesRenderer extends CircularSeriesRenderer { @nonVirtual ChartShaderDetails createShaderDetails() { return ChartShaderDetails( - Rect.fromCircle(center: center, radius: currentRadius), null, 'series'); + Rect.fromCircle(center: center, radius: currentRadius), + null, + 'series', + ); } @override @@ -490,14 +498,20 @@ class PieSegment extends ChartSegment { double degree = _degree * animationFactor; final double angle = calculateAngle( - series.animationFactor == 1, series.startAngle, series.endAngle); - final double startAngle = lerpDouble( - _priorEndAngle.isNaN ? angle : _priorStartAngle, - _startAngle, - animationFactor)!; - final double endAngle = _priorEndAngle.isNaN - ? startAngle + degree - : lerpDouble(_priorEndAngle, _endAngle, animationFactor)!; + series.animationFactor == 1, + series.startAngle, + series.endAngle, + ); + final double startAngle = + lerpDouble( + _priorEndAngle.isNaN ? angle : _priorStartAngle, + _startAngle, + animationFactor, + )!; + final double endAngle = + _priorEndAngle.isNaN + ? startAngle + degree + : lerpDouble(_priorEndAngle, _endAngle, animationFactor)!; degree = _priorEndAngle.isNaN ? degree : endAngle - startAngle; // If the startAngle and endAngle value is same, then degree will be 0. @@ -509,14 +523,24 @@ class PieSegment extends ChartSegment { if (series.explode && _isExploded) { final double midAngle = (_startAngle + _endAngle) / 2; _center = calculateExplodingCenter( - midAngle, _outerRadius, series.center, series.explodeOffset); + midAngle, + _outerRadius, + series.center, + series.explodeOffset, + ); } else { _center = series.center; } fillPath = calculateArcPath( - _innerRadius, _outerRadius, _center, startAngle, endAngle, degree, - isAnimate: true); + _innerRadius, + _outerRadius, + _center, + startAngle, + endAngle, + degree, + isAnimate: true, + ); } @override @@ -536,15 +560,20 @@ class PieSegment extends ChartSegment { @override TooltipInfo? tooltipInfo({Offset? position, int? pointIndex}) { final ChartPoint point = ChartPoint( - x: series.circularXValues[currentSegmentIndex], - y: series.circularYValues[currentSegmentIndex]); - final Offset location = calculateOffset((_startAngle + _endAngle) / 2, - (_innerRadius + _outerRadius) / 2, _center); + x: series.circularXValues[currentSegmentIndex], + y: series.circularYValues[currentSegmentIndex], + ); + final Offset location = calculateOffset( + (_startAngle + _endAngle) / 2, + (_innerRadius + _outerRadius) / 2, + _center, + ); final TooltipPosition? tooltipPosition = series.parent?.tooltipBehavior?.tooltipPosition; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? series.localToGlobal(position ?? location) - : series.localToGlobal(location); + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? series.localToGlobal(position ?? location) + : series.localToGlobal(location); return ChartTooltipInfo( primaryPosition: preferredPos, secondaryPosition: preferredPos, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/pyramid_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/pyramid_series.dart index 3c2600d3b..ac9cd17bb 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/pyramid_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/pyramid_series.dart @@ -64,9 +64,7 @@ class PyramidSeries extends ChartSeries { super.opacity, super.selectionBehavior, super.initialSelectedDataIndexes, - }) : super( - dataLabelMapper: textFieldMapper, - ); + }) : super(dataLabelMapper: textFieldMapper); /// Maps the field name, which will be considered as y-values. /// @@ -306,11 +304,12 @@ class PyramidSeries extends ChartSeries { case SeriesSlot.dataLabel: return dataLabelSettings.isVisible ? PyramidDataLabelContainer( - series: this, - dataSource: dataSource!, - mapper: dataLabelMapper, - builder: dataLabelSettings.builder, - settings: dataLabelSettings) + series: this, + dataSource: dataSource!, + mapper: dataLabelMapper, + builder: dataLabelSettings.builder, + settings: dataLabelSettings, + ) : null; case SeriesSlot.marker: @@ -322,8 +321,9 @@ class PyramidSeries extends ChartSeries { } @override - List get positions => - [ChartDataPointType.y]; + List get positions => [ + ChartDataPointType.y, + ]; // Create the pyramid series renderer. @override @@ -332,10 +332,11 @@ class PyramidSeries extends ChartSeries { if (onCreateRenderer != null) { renderer = onCreateRenderer!(this) as PyramidSeriesRenderer?; assert( - renderer != null, - 'This onCreateRenderer callback function should return value as ' - 'extends from ChartSeriesRenderer class and should not be return ' - 'value as null'); + renderer != null, + 'This onCreateRenderer callback function should return value as ' + 'extends from ChartSeriesRenderer class and should not be return ' + 'value as null', + ); } return renderer ?? PyramidSeriesRenderer(); } @@ -365,7 +366,9 @@ class PyramidSeries extends ChartSeries { @override void updateRenderObject( - BuildContext context, PyramidSeriesRenderer renderObject) { + BuildContext context, + PyramidSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..yValueMapper = yValueMapper @@ -429,8 +432,10 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer set gapRatio(double value) { if (_gapRatio != value) { _gapRatio = value; - assert(_gapRatio >= 0 && _gapRatio <= 1, - 'The gap ratio for the funnel chart must be between 0 and 1.'); + assert( + _gapRatio >= 0 && _gapRatio <= 1, + 'The gap ratio for the funnel chart must be between 0 and 1.', + ); _gapRatio = clampDouble(value, 0, 1); markNeedsLayout(); } @@ -502,9 +507,7 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer @override Iterable get children { - return [ - if (dataLabelContainer != null) dataLabelContainer!, - ]; + return [if (dataLabelContainer != null) dataLabelContainer!]; } /// Stores pointer down time to determine whether a long press interaction is handled at pointer up @@ -529,20 +532,22 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer ); final Offset insideLabelOffset = Offset( - (points[0].dx + points[1].dx) / 2 - size.width / 2, - (points[0].dy + points[2].dy) / 2 - size.height / 2); + (points[0].dx + points[1].dx) / 2 - size.width / 2, + (points[0].dy + points[2].dy) / 2 - size.height / 2, + ); final double connectorLengthWithXValue = insideLabelOffset.dx + connectorLength + size.width / 2; final Offset outsideLabelOffset = Offset( - (connectorLengthWithXValue + - size.width + - dataLabelSettings.margin.left + - dataLabelSettings.margin.right > - paintBounds.right) - ? connectorLengthWithXValue - - (percentToValue(explodeOffset, paintBounds.width)!) - : connectorLengthWithXValue, - insideLabelOffset.dy); + (connectorLengthWithXValue + + size.width + + dataLabelSettings.margin.left + + dataLabelSettings.margin.right > + paintBounds.right) + ? connectorLengthWithXValue - + (percentToValue(explodeOffset, paintBounds.width)!) + : connectorLengthWithXValue, + insideLabelOffset.dy, + ); final Offset finalOffset = dataLabelSettings.labelPosition == ChartDataLabelPosition.inside ? insideLabelOffset @@ -584,26 +589,33 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer ..lineTo(endPoint, y); } - RRect _calculateRect(Offset offset, int padding, EdgeInsets margin, Size size, - ChartDataLabelPosition labelPosition) { + RRect _calculateRect( + Offset offset, + int padding, + EdgeInsets margin, + Size size, + ChartDataLabelPosition labelPosition, + ) { if (labelPosition == ChartDataLabelPosition.inside) { return RRect.fromRectAndRadius( - Rect.fromLTWH( - offset.dx - padding, - offset.dy - padding, - size.width + (2 * padding), - size.height + (2 * padding), - ), - Radius.circular(dataLabelSettings.borderRadius)); - } - return RRect.fromRectAndRadius( Rect.fromLTWH( - offset.dx, - offset.dy - margin.top, - size.width + margin.top + margin.left, - size.height + margin.bottom + margin.right, + offset.dx - padding, + offset.dy - padding, + size.width + (2 * padding), + size.height + (2 * padding), ), - Radius.circular(dataLabelSettings.borderRadius)); + Radius.circular(dataLabelSettings.borderRadius), + ); + } + return RRect.fromRectAndRadius( + Rect.fromLTWH( + offset.dx, + offset.dy - margin.top, + size.width + margin.top + margin.left, + size.height + margin.bottom + margin.right, + ), + Radius.circular(dataLabelSettings.borderRadius), + ); } Rect _calculateSegmentRect(List points, int index) { @@ -612,22 +624,31 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer final double x = (points[0].dx + points[bottom].dx) / 2; final double right = (points[1].dx + points[bottom - 1].dx) / 2; final Rect region = Rect.fromLTWH( - x, points[0].dy, right - x, points[bottom].dy - points[0].dy); + x, + points[0].dy, + right - x, + points[bottom].dy - points[0].dy, + ); return region; } double _calculateConnectorLength( - List points, DataLabelSettings settings) { - final Path segmentPath = Path() - ..moveTo(points[0].dx, points[0].dy) - ..lineTo(points[1].dx, points[1].dy) - ..lineTo(points[2].dx, points[2].dy) - ..lineTo(points[3].dx, points[3].dy) - ..close(); + List points, + DataLabelSettings settings, + ) { + final Path segmentPath = + Path() + ..moveTo(points[0].dx, points[0].dy) + ..lineTo(points[1].dx, points[1].dy) + ..lineTo(points[2].dx, points[2].dy) + ..lineTo(points[3].dx, points[3].dy) + ..close(); final Rect segmentBounds = segmentPath.getBounds(); - final double connectorLength = percentToValue( - settings.connectorLineSettings.length ?? '0%', - _plotAreaBounds.width / 2)! + + final double connectorLength = + percentToValue( + settings.connectorLineSettings.length ?? '0%', + _plotAreaBounds.width / 2, + )! + (segmentBounds.width / 2); return connectorLength; } @@ -656,8 +677,13 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer return isCollide; } - String _getTrimmedText(String? text, Rect rect, Offset labelLocation, - Rect region, TextStyle style) { + String _getTrimmedText( + String? text, + Rect rect, + Offset labelLocation, + Rect region, + TextStyle style, + ) { const int labelPadding = 2; const String ellipse = '...'; String label = text!; @@ -675,17 +701,22 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer } final Size trimTextSize = measureText(label, style); final Rect trimRect = Rect.fromLTWH( - labelLocation.dx - labelPadding, - labelLocation.dy - labelPadding, - trimTextSize.width + (2 * labelPadding), - trimTextSize.height + (2 * labelPadding)); + labelLocation.dx - labelPadding, + labelLocation.dy - labelPadding, + trimTextSize.width + (2 * labelPadding), + trimTextSize.height + (2 * labelPadding), + ); isCollide = _isLabelsColliding(trimRect, region); } return label == ellipse ? '' : label; } - String _addEllipse(String text, int maxLength, String ellipse, - {bool isRtl = false}) { + String _addEllipse( + String text, + int maxLength, + String ellipse, { + bool isRtl = false, + }) { if (isRtl) { if (text.contains(ellipse)) { text = text.replaceAll(ellipse, ''); @@ -732,8 +763,14 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer final SfChartThemeData chartThemeData = parent!.chartThemeData!; final ThemeData themeData = parent!.themeData!; final ChartSegment segment = segments[index]; - Color surfaceColor = dataLabelSurfaceColor(fillPaint.color, index, - dataLabelSettings.labelPosition, chartThemeData, themeData, segment); + Color surfaceColor = dataLabelSurfaceColor( + fillPaint.color, + index, + dataLabelSettings.labelPosition, + chartThemeData, + themeData, + segment, + ); TextStyle effectiveTextStyle = saturatedTextStyle(surfaceColor, style); final EdgeInsets margin = dataLabelSettings.margin; final Radius radius = Radius.circular(dataLabelSettings.borderRadius); @@ -750,11 +787,13 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer connectorPoints, dataLabelSettings, ); - final Paint connectorPaint = Paint() - ..color = dataLabelSettings.connectorLineSettings.color ?? - segments[index].fillPaint.color - ..strokeWidth = dataLabelSettings.connectorLineSettings.width - ..style = PaintingStyle.stroke; + final Paint connectorPaint = + Paint() + ..color = + dataLabelSettings.connectorLineSettings.color ?? + segments[index].fillPaint.color + ..strokeWidth = dataLabelSettings.connectorLineSettings.width + ..style = PaintingStyle.stroke; if ((yValues[index] == 0 && !dataLabelSettings.showZeroValue) || yValues[index].isNaN || @@ -765,12 +804,17 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer for (int i = 0; i < segments.length; i++) { final List points = segmentAt(i).points; final Offset point = Offset( - (points[0].dx + points[1].dx) / 2, (points[0].dy + points[2].dy) / 2); - labels.add(Rect.fromLTWH( + (points[0].dx + points[1].dx) / 2, + (points[0].dy + points[2].dy) / 2, + ); + labels.add( + Rect.fromLTWH( point.dx - (size.width / 2) - labelPadding, point.dy - (size.height / 2) - labelPadding, size.width + (2 * labelPadding), - size.height + (2 * labelPadding))); + size.height + (2 * labelPadding), + ), + ); } if (!offset.dx.isNaN && !offset.dy.isNaN) { @@ -778,30 +822,47 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer if (fillPaint.color != Colors.transparent || (strokePaint.color != const Color.fromARGB(0, 25, 5, 5) && strokePaint.strokeWidth > 0)) { - RRect labelRect = - _calculateRect(offset, labelPadding, margin, size, labelPosition); - final Rect region = - _calculateSegmentRect(segments[index].points, index); - final bool isDataLabelCollide = (_findingCollision( - labels[index], previousRect, region)) && + RRect labelRect = _calculateRect( + offset, + labelPadding, + margin, + size, + labelPosition, + ); + final Rect region = _calculateSegmentRect( + segments[index].points, + index, + ); + final bool isDataLabelCollide = + (_findingCollision(labels[index], previousRect, region)) && dataLabelSettings.labelPosition != ChartDataLabelPosition.outside; if (isDataLabelCollide) { switch (dataLabelSettings.overflowMode) { case OverflowMode.trim: - dataLabel = _getTrimmedText(dataLabel, labels[index], - finalOffset, region, effectiveTextStyle); - final Size trimSize = - measureText(dataLabel, effectiveTextStyle); + dataLabel = _getTrimmedText( + dataLabel, + labels[index], + finalOffset, + region, + effectiveTextStyle, + ); + final Size trimSize = measureText( + dataLabel, + effectiveTextStyle, + ); finalOffset = Offset( - finalOffset.dx + size.width / 2 - trimSize.width / 2, - finalOffset.dy + size.height / 2 - trimSize.height / 2); + finalOffset.dx + size.width / 2 - trimSize.width / 2, + finalOffset.dy + size.height / 2 - trimSize.height / 2, + ); labelRect = RRect.fromRectAndRadius( - Rect.fromLTWH( - finalOffset.dx - labelPadding, - finalOffset.dy - labelPadding, - trimSize.width + (2 * labelPadding), - trimSize.height + (2 * labelPadding)), - radius); + Rect.fromLTWH( + finalOffset.dx - labelPadding, + finalOffset.dy - labelPadding, + trimSize.width + (2 * labelPadding), + trimSize.height + (2 * labelPadding), + ), + radius, + ); break; case OverflowMode.hide: dataLabel = ''; @@ -821,12 +882,13 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer !dataLabelSettings.useSeriesColor) { if (style.color == Colors.transparent) { surfaceColor = dataLabelSurfaceColor( - fillPaint.color, - index, - ChartDataLabelPosition.outside, - chartThemeData, - themeData, - segment); + fillPaint.color, + index, + ChartDataLabelPosition.outside, + chartThemeData, + themeData, + segment, + ); effectiveTextStyle = saturatedTextStyle(surfaceColor, style); } } @@ -846,31 +908,44 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer (dataLabelSettings.labelPosition == ChartDataLabelPosition.outside)) { labelPosition = ChartDataLabelPosition.outside; - finalOffset = dataLabelSettings.labelPosition == - ChartDataLabelPosition.outside - ? offset - : offset + Offset(connectorLength + size.width / 2, 0); + finalOffset = + dataLabelSettings.labelPosition == + ChartDataLabelPosition.outside + ? offset + : offset + Offset(connectorLength + size.width / 2, 0); labelRect = _calculateRect( - finalOffset, labelPadding, margin, size, labelPosition); + finalOffset, + labelPadding, + margin, + size, + labelPosition, + ); connectorPath = _drawConnectorPath(index, finalOffset, size); if (_plotAreaBounds.right < labelRect.right) { isOverlapRight = true; labelRect = RRect.fromRectAndRadius( - Rect.fromLTRB( - _plotAreaBounds.right - labelRect.width - labelPadding, - labelRect.top, - _plotAreaBounds.right - labelPadding, - labelRect.bottom), - radius); + Rect.fromLTRB( + _plotAreaBounds.right - labelRect.width - labelPadding, + labelRect.top, + _plotAreaBounds.right - labelPadding, + labelRect.bottom, + ), + radius, + ); } - final RRect previous = previousRect.isEmpty - ? labelRect - : previousRect[previousRect.length - 1]; - final bool isIntersectOutside = - _isDataLabelIntersectOutside(labelRect, previous); + final RRect previous = + previousRect.isEmpty + ? labelRect + : previousRect[previousRect.length - 1]; + final bool isIntersectOutside = _isDataLabelIntersectOutside( + labelRect, + previous, + ); if (!isIntersectOutside && isOverlapRight) { - finalOffset = Offset(labelRect.left, - (labelRect.top + labelRect.height / 2) - size.height / 2); + finalOffset = Offset( + labelRect.left, + (labelRect.top + labelRect.height / 2) - size.height / 2, + ); connectorPath = _drawConnectorPath(index, finalOffset, size); } if (dataLabelSettings.labelIntersectAction == @@ -886,17 +961,30 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer ChartDataLabelPosition.outside && index != 0)) { labelRect = RRect.fromRectAndRadius( - Rect.fromLTWH(labelRect.left, previous.bottom + 2, - labelRect.width, labelRect.height), - radius); - connectorPath = Path() - ..moveTo(startPoint, finalOffset.dy + size.height / 2) - ..lineTo(labelRect.left - connectorPadding, - labelRect.top + labelRect.height / 2) - ..lineTo(labelRect.left, labelRect.top + labelRect.height / 2); + Rect.fromLTWH( + labelRect.left, + previous.bottom + 2, + labelRect.width, + labelRect.height, + ), + radius, + ); + connectorPath = + Path() + ..moveTo(startPoint, finalOffset.dy + size.height / 2) + ..lineTo( + labelRect.left - connectorPadding, + labelRect.top + labelRect.height / 2, + ) + ..lineTo( + labelRect.left, + labelRect.top + labelRect.height / 2, + ); } - finalOffset = Offset(labelRect.left + margin.left, - (labelRect.top + labelRect.height / 2) - size.height / 2); + finalOffset = Offset( + labelRect.left + margin.left, + (labelRect.top + labelRect.height / 2) - size.height / 2, + ); previousRect.add(labelRect); } if (_plotAreaBounds.height < labelRect.bottom + labelPadding) { @@ -924,15 +1012,21 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer } void drawDataLabel( - Canvas canvas, String text, Offset point, TextStyle style, int angle, - [bool? isRtl]) { + Canvas canvas, + String text, + Offset point, + TextStyle style, + int angle, [ + bool? isRtl, + ]) { final int maxLines = getMaxLinesContent(text); final TextSpan span = TextSpan(text: text, style: style); final TextPainter tp = TextPainter( - text: span, - textDirection: (isRtl ?? false) ? TextDirection.rtl : TextDirection.ltr, - textAlign: TextAlign.center, - maxLines: maxLines); + text: span, + textDirection: (isRtl ?? false) ? TextDirection.rtl : TextDirection.ltr, + textAlign: TextAlign.center, + maxLines: maxLines, + ); tp.layout(); canvas.save(); canvas.translate(point.dx + tp.width / 2, point.dy + tp.height / 2); @@ -975,7 +1069,13 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer } } super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); markNeedsLegendUpdate(); populateChartPoints(); } @@ -1023,8 +1123,17 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer yLists?.add(yValues); } } - super.updateDataPoints(removedIndexes, addedIndexes, replacedIndexes, - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + super.updateDataPoints( + removedIndexes, + addedIndexes, + replacedIndexes, + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); } @override @@ -1062,8 +1171,10 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer } _plotAreaBounds = Rect.fromLTWH(0, 0, size.width, size.height); - _triangleSize = Size(percentToValue(width, _plotAreaBounds.width)!, - percentToValue(height, _plotAreaBounds.height)!); + _triangleSize = Size( + percentToValue(width, _plotAreaBounds.width)!, + percentToValue(height, _plotAreaBounds.height)!, + ); _coefficient = 1 / (_sumOfY * (1 + gapRatio / (1 - gapRatio))); _spacing = gapRatio / (dataCount - emptyPointIndexes.length - 1); y = 0; @@ -1126,7 +1237,8 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer .._triangleSize = _triangleSize .._plotAreaBounds = _plotAreaBounds ..isExploded = explode && index == explodeIndex - ..isEmpty = (emptyPointSettings.mode != EmptyPointMode.drop && + ..isEmpty = + (emptyPointSettings.mode != EmptyPointMode.drop && emptyPointSettings.mode != EmptyPointMode.gap) && isEmpty(index); @@ -1141,7 +1253,8 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer .._triangleSize = _triangleSize .._plotAreaBounds = _plotAreaBounds ..isExploded = explode && index == explodeIndex - ..isEmpty = (emptyPointSettings.mode != EmptyPointMode.drop && + ..isEmpty = + (emptyPointSettings.mode != EmptyPointMode.drop && emptyPointSettings.mode != EmptyPointMode.gap) && isEmpty(index); } @@ -1172,11 +1285,11 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer } @override - List? buildLegendItems(int index) { - final List legendItems = []; + List? buildLegendItems(int index) { + final List legendItems = []; final int segmentsCount = segments.length; for (int i = 0; i < dataCount; i++) { - final ChartLegendItem legendItem = ChartLegendItem( + final PyramidLegendItem legendItem = PyramidLegendItem( text: xRawValues[i].toString(), iconType: toLegendShapeMarkerType(legendIconType, this), iconColor: effectiveColor(i), @@ -1184,9 +1297,10 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer series: this, seriesIndex: index, pointIndex: i, - imageProvider: legendIconType == LegendIconType.image - ? parent?.legend?.image - : null, + imageProvider: + legendIconType == LegendIconType.image + ? parent?.legend?.image + : null, isToggled: i < segmentsCount && !segmentAt(i).isVisible, onTap: handleLegendItemTapped, onRender: _handleLegendItemCreated, @@ -1198,7 +1312,7 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer void _handleLegendItemCreated(ItemRendererDetails details) { if (parent != null && parent!.onLegendItemRender != null) { - final ChartLegendItem item = details.item as ChartLegendItem; + final PyramidLegendItem item = details.item as PyramidLegendItem; final LegendIconType iconType = toLegendIconType(details.iconType); final LegendRenderArgs args = LegendRenderArgs(item.seriesIndex, item.pointIndex) @@ -1208,7 +1322,9 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer parent!.onLegendItemRender!(args); if (args.legendIconType != iconType) { details.iconType = toLegendShapeMarkerType( - args.legendIconType ?? LegendIconType.seriesType, this); + args.legendIconType ?? LegendIconType.seriesType, + this, + ); } details ..text = args.text ?? '' @@ -1220,7 +1336,7 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer void handleLegendItemTapped(LegendItem item, bool isToggled) { super.handleLegendItemTapped(item, isToggled); - final ChartLegendItem legendItem = item as ChartLegendItem; + final PyramidLegendItem legendItem = item as PyramidLegendItem; final int toggledIndex = legendItem.pointIndex; segments[toggledIndex].isVisible = !isToggled; @@ -1234,8 +1350,11 @@ class PyramidSeriesRenderer extends ChartSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = - clipRect(paintBounds, animationFactor, isTransposed: true); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isTransposed: true, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -1356,11 +1475,13 @@ class PyramidSegment extends ChartSegment { void transformValues() { points.clear(); - final double marginSpace = (isExploded + final double marginSpace = + (isExploded ? percentToValue(series.explodeOffset, _plotAreaBounds.width)! : 0) + (_plotAreaBounds.width - _triangleSize.width) / 2; - final double pyramidTop = _plotAreaBounds.top + + final double pyramidTop = + _plotAreaBounds.top + (_plotAreaBounds.height - _triangleSize.height) / 2; final double pyramidLeft = marginSpace + _plotAreaBounds.left; final double heightRatio = pyramidTop / _triangleSize.height; @@ -1414,14 +1535,16 @@ class PyramidSegment extends ChartSegment { @override TooltipInfo? tooltipInfo({Offset? position, int? pointIndex}) { final ChartPoint point = ChartPoint( - x: series.xRawValues[currentSegmentIndex], - y: series.yValues[currentSegmentIndex]); + x: series.xRawValues[currentSegmentIndex], + y: series.yValues[currentSegmentIndex], + ); final Offset location = path.getBounds().center; final TooltipPosition? tooltipPosition = series.parent?.tooltipBehavior?.tooltipPosition; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? series.localToGlobal(position ?? location) - : series.localToGlobal(location); + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? series.localToGlobal(position ?? location) + : series.localToGlobal(location); return ChartTooltipInfo( primaryPosition: preferredPos, secondaryPosition: preferredPos, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/radial_bar_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/radial_bar_series.dart index e4e3a8af9..56dedd9e5 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/radial_bar_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/radial_bar_series.dart @@ -69,10 +69,7 @@ class RadialBarSeries extends CircularSeries { super.legendIconType, super.cornerStyle = CornerStyle.bothFlat, super.initialSelectedDataIndexes, - }) : super( - borderColor: strokeColor, - borderWidth: strokeWidth, - ); + }) : super(borderColor: strokeColor, borderWidth: strokeWidth); /// Color of the track. /// @@ -189,8 +186,9 @@ class RadialBarSeries extends CircularSeries { final bool useSeriesColor; @override - List get positions => - [ChartDataPointType.y]; + List get positions => [ + ChartDataPointType.y, + ]; /// Create the Radial bar series renderer. @override @@ -219,7 +217,9 @@ class RadialBarSeries extends CircularSeries { @override void updateRenderObject( - BuildContext context, RadialBarSeriesRenderer renderObject) { + BuildContext context, + RadialBarSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..trackColor = trackColor @@ -298,17 +298,20 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { double degree = yValue / (maximumValue ?? (sumOfY != 0 ? sumOfY : 1)); degree = degree * fullAngle; final double pointEndAngle = pointStartAngle + degree; - final double innerRadius = currentInnerRadius = segment.isVisible - ? (currentInnerRadius + - ((index == firstVisibleIndex) ? 0 : ringSize) - - (trackBorderWidth / 2) / dataCount) - : currentInnerRadius; - final double outerRadius = ringSize < segmentGap! - ? 0 - : innerRadius + - ringSize - - segmentGap! - - (trackBorderWidth / 2) / dataCount; + final double innerRadius = + currentInnerRadius = + segment.isVisible + ? (currentInnerRadius + + ((index == firstVisibleIndex) ? 0 : ringSize) - + (trackBorderWidth / 2) / dataCount) + : currentInnerRadius; + final double outerRadius = + ringSize < segmentGap! + ? 0 + : innerRadius + + ringSize - + segmentGap! - + (trackBorderWidth / 2) / dataCount; segment as RadialBarSegment ..series = this @@ -333,11 +336,13 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { if (trackColor != Colors.transparent) { if (useSeriesColor) { - segment.trackFillPaint.color = - segment.fillPaint.color.withValues(alpha: trackOpacity); + segment.trackFillPaint.color = segment.fillPaint.color.withValues( + alpha: trackOpacity, + ); } else { - segment.trackFillPaint.color = - trackColor.withValues(alpha: trackOpacity); + segment.trackFillPaint.color = trackColor.withValues( + alpha: trackOpacity, + ); } } else { if (useSeriesColor) { @@ -356,21 +361,22 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { } @override - List? buildLegendItems(int index) { + List? buildLegendItems(int index) { if (circularYValues.isEmpty) { return null; } - final num sumOfY = circularYValues - .reduce((num value, num element) => value + element.abs()); + final num sumOfY = circularYValues.reduce( + (num value, num element) => value + element.abs(), + ); const double pointStartAngle = -90; - final List legendItems = []; + final List legendItems = []; final int segmentsCount = segments.length; for (int i = 0; i < dataCount; i++) { double degree = circularYValues[i] / (maximumValue ?? sumOfY); degree = (degree > 1 ? 1 : degree) * fullAngle; final double pointEndAngle = pointStartAngle + degree; - final ChartLegendItem legendItem = ChartLegendItem( + final CircularLegendItem legendItem = CircularLegendItem( text: circularXValues[i].toString(), iconType: toLegendShapeMarkerType(legendIconType, this), iconColor: effectiveColor(i), @@ -383,9 +389,10 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { degree: degree, iconBorderColor: trackColor, iconBorderWidth: legendIconBorderWidth(), - imageProvider: legendIconType == LegendIconType.image - ? parent?.legend?.image - : null, + imageProvider: + legendIconType == LegendIconType.image + ? parent?.legend?.image + : null, isToggled: i < segmentsCount && !segmentAt(i).isVisible, onTap: handleLegendItemTapped, onRender: _handleLegendItemCreated, @@ -399,7 +406,7 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { void handleLegendItemTapped(LegendItem item, bool isToggled) { super.handleLegendItemTapped(item, isToggled); // Resets `_isLegendToggled` to `true` to handle legend inner and outer radius animations. - if (item is ChartLegendItem && item.pointIndex != -1) { + if (item is CircularLegendItem && item.pointIndex != -1) { final RadialBarSegment segment = segmentAt(item.pointIndex) as RadialBarSegment; segment._isLegendToggled = true; @@ -408,7 +415,7 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { void _handleLegendItemCreated(ItemRendererDetails details) { if (parent != null && parent!.onLegendItemRender != null) { - final ChartLegendItem item = details.item as ChartLegendItem; + final CircularLegendItem item = details.item as CircularLegendItem; final LegendIconType iconType = toLegendIconType(details.iconType); final LegendRenderArgs args = LegendRenderArgs(item.seriesIndex, item.pointIndex) @@ -418,7 +425,9 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { parent!.onLegendItemRender!(args); if (args.legendIconType != iconType) { details.iconType = toLegendShapeMarkerType( - args.legendIconType ?? LegendIconType.seriesType, this); + args.legendIconType ?? LegendIconType.seriesType, + this, + ); } details @@ -430,13 +439,24 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { Shader? _legendIconShaders(int pointIndex) { if (parent != null && parent!.legend != null) { final Rect legendIconBounds = Rect.fromLTWH( - 0.0, 0.0, parent!.legend!.iconWidth, parent!.legend!.iconHeight); + 0.0, + 0.0, + parent!.legend!.iconWidth, + parent!.legend!.iconHeight, + ); if (pointShaderMapper != null) { - return pointShaderMapper!(dataSource![pointIndex], pointIndex, - palette[pointIndex % palette.length], legendIconBounds); + return pointShaderMapper!( + dataSource![pointIndex], + pointIndex, + palette[pointIndex % palette.length], + legendIconBounds, + ); } else if (onCreateShader != null) { - final ChartShaderDetails details = - ChartShaderDetails(legendIconBounds, legendIconBounds, 'legend'); + final ChartShaderDetails details = ChartShaderDetails( + legendIconBounds, + legendIconBounds, + 'legend', + ); return onCreateShader?.call(details); } } @@ -462,22 +482,26 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { ..fill = palette[current.dataPointIndex % palette.length]; final CircularChartPoint point = current.point!; - Offset labelLocation = calculateOffset(point.startAngle!, - (point.innerRadius! + point.outerRadius!) / 2, point.center!); + Offset labelLocation = calculateOffset( + point.startAngle!, + (point.innerRadius! + point.outerRadius!) / 2, + point.center!, + ); labelLocation = Offset( - (labelLocation.dx - size.width - 5) + (angle == 0 ? 0 : size.width / 2), - (labelLocation.dy - size.height / 2) + - (angle == 0 ? 0 : size.height / 2)); + (labelLocation.dx - size.width - 5) + (angle == 0 ? 0 : size.width / 2), + (labelLocation.dy - size.height / 2) + (angle == 0 ? 0 : size.height / 2), + ); if (point.isVisible && (point.y == 0 && !dataLabelSettings.showZeroValue)) { point.isVisible = false; return labelLocation; } if (size.width > 0 && size.height > 0) { point.labelRect = Rect.fromLTWH( - labelLocation.dx - labelPadding, - labelLocation.dy - labelPadding, - size.width + (2 * labelPadding), - size.height + (2 * labelPadding)); + labelLocation.dx - labelPadding, + labelLocation.dy - labelPadding, + size.width + (2 * labelPadding), + size.height + (2 * labelPadding), + ); } else { point.labelRect = Rect.zero; } @@ -486,15 +510,16 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { @override void drawDataLabelWithBackground( - CircularChartDataLabelPositioned dataLabelPositioned, - int index, - Canvas canvas, - String dataLabel, - Offset offset, - int angle, - TextStyle style, - Paint fillPaint, - Paint strokePaint) { + CircularChartDataLabelPositioned dataLabelPositioned, + int index, + Canvas canvas, + String dataLabel, + Offset offset, + int angle, + TextStyle style, + Paint fillPaint, + Paint strokePaint, + ) { final TextStyle effectiveTextStyle = parent!.themeData!.textTheme.bodySmall! .copyWith(color: Colors.black) .merge(parent!.chartThemeData!.dataLabelTextStyle) @@ -513,32 +538,51 @@ class RadialBarSeriesRenderer extends CircularSeriesRenderer { if (dataLabelSettings.borderWidth > 0 && strokePaint.color != Colors.transparent) { _drawLabelRect( - strokePaint, - Rect.fromLTRB( - labelRect.left, labelRect.top, labelRect.right, labelRect.bottom), - dataLabelSettings.borderRadius, - canvas); + strokePaint, + Rect.fromLTRB( + labelRect.left, + labelRect.top, + labelRect.right, + labelRect.bottom, + ), + dataLabelSettings.borderRadius, + canvas, + ); } if (fillPaint.color != Colors.transparent) { _drawLabelRect( - fillPaint, - Rect.fromLTRB( - labelRect.left, labelRect.top, labelRect.right, labelRect.bottom), - dataLabelSettings.borderRadius, - canvas); + fillPaint, + Rect.fromLTRB( + labelRect.left, + labelRect.top, + labelRect.right, + labelRect.bottom, + ), + dataLabelSettings.borderRadius, + canvas, + ); } canvas.restore(); drawDataLabel( - canvas, dataLabel, offset, effectiveTextStyle, dataLabelSettings.angle); + canvas, + dataLabel, + offset, + effectiveTextStyle, + dataLabelSettings.angle, + ); } void _drawLabelRect( - Paint paint, Rect labelRect, double borderRadius, Canvas canvas) => - canvas.drawRRect( - RRect.fromRectAndRadius(labelRect, Radius.circular(borderRadius)), - paint); + Paint paint, + Rect labelRect, + double borderRadius, + Canvas canvas, + ) => canvas.drawRRect( + RRect.fromRectAndRadius(labelRect, Radius.circular(borderRadius)), + paint, + ); } class RadialBarSegment extends ChartSegment { @@ -586,9 +630,10 @@ class RadialBarSegment extends ChartSegment { final Paint trackFillPaint = Paint()..isAntiAlias = true; /// Stroke paint of the segment track. - final Paint trackStrokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint trackStrokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; @override void transformValues() { @@ -625,9 +670,11 @@ class RadialBarSegment extends ChartSegment { final double halfRadii = (_priorOuterRadius + _priorInnerRadius) / 2; endAngle = _priorEndAngle; degree = endAngle - startAngle; - innerRadius = _priorInnerRadius + + innerRadius = + _priorInnerRadius + (halfRadii - _priorInnerRadius) * animationFactor; - outerRadius = _priorOuterRadius - + outerRadius = + _priorOuterRadius - (_priorOuterRadius - halfRadii) * animationFactor; _innerRadius = innerRadius; _outerRadius = outerRadius; @@ -640,12 +687,21 @@ class RadialBarSegment extends ChartSegment { } trackPath = calculateArcPath( - innerRadius, outerRadius, _center, 0, fullAngle, fullAngle, - isAnimate: true); + innerRadius, + outerRadius, + _center, + 0, + fullAngle, + fullAngle, + isAnimate: true, + ); if (_outerRadius > 0 && degree > 0) { - final num angleDeviation = - findAngleDeviation(innerRadius, outerRadius, 360); + final num angleDeviation = findAngleDeviation( + innerRadius, + outerRadius, + 360, + ); final CornerStyle cornerStyle = series.cornerStyle; if (cornerStyle == CornerStyle.bothCurve || cornerStyle == CornerStyle.startCurve) { @@ -659,20 +715,34 @@ class RadialBarSegment extends ChartSegment { if (degree > 360) { yValuePath = calculateRoundedCornerArcPath( - cornerStyle, innerRadius, outerRadius, _center, 0, fullAngle); + cornerStyle, + innerRadius, + outerRadius, + _center, + 0, + fullAngle, + ); yValuePath.arcTo( - Rect.fromCircle(center: _center, radius: outerRadius), - degreesToRadians(_startAngle), - degreesToRadians(_endAngle - _startAngle), - true); + Rect.fromCircle(center: _center, radius: outerRadius), + degreesToRadians(_startAngle), + degreesToRadians(_endAngle - _startAngle), + true, + ); yValuePath.arcTo( - Rect.fromCircle(center: _center, radius: innerRadius), - degreesToRadians(_endAngle), - degreesToRadians(_startAngle) - degreesToRadians(_endAngle), - false); + Rect.fromCircle(center: _center, radius: innerRadius), + degreesToRadians(_endAngle), + degreesToRadians(_startAngle) - degreesToRadians(_endAngle), + false, + ); } else { - yValuePath = calculateRoundedCornerArcPath(cornerStyle, innerRadius, - outerRadius, _center, startAngle, endAngle); + yValuePath = calculateRoundedCornerArcPath( + cornerStyle, + innerRadius, + outerRadius, + _center, + startAngle, + endAngle, + ); } if (degree > 360 && endAngle >= startAngle + 180) { @@ -682,20 +752,31 @@ class RadialBarSegment extends ChartSegment { } void _calculateShadowPath( - double endAngle, double degree, double innerRadius, double outerRadius) { + double endAngle, + double degree, + double innerRadius, + double outerRadius, + ) { if (degree > 360) { final double actualRadius = (innerRadius - outerRadius).abs() / 2; - final Offset midPoint = - calculateOffset(endAngle, (innerRadius + outerRadius) / 2, _center); + final Offset midPoint = calculateOffset( + endAngle, + (innerRadius + outerRadius) / 2, + _center, + ); if (actualRadius > 0) { double shadowWidth = actualRadius * 0.2; const double sigmaRadius = 3 * 0.57735 + 0.5; shadowWidth = shadowWidth < 3 ? 3 : (shadowWidth > 5 ? 5 : shadowWidth); - _shadowPaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke - ..strokeWidth = shadowWidth - ..maskFilter = const MaskFilter.blur(BlurStyle.normal, sigmaRadius); + _shadowPaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke + ..strokeWidth = shadowWidth + ..maskFilter = const MaskFilter.blur( + BlurStyle.normal, + sigmaRadius, + ); _overFilledPaint = Paint()..isAntiAlias = true; double newEndAngle = endAngle; if (series.cornerStyle == CornerStyle.endCurve || @@ -705,14 +786,19 @@ class RadialBarSegment extends ChartSegment { shadowPath ..reset() ..addArc( - Rect.fromCircle( - center: midPoint, - radius: actualRadius - (actualRadius * 0.05)), - degreesToRadians(newEndAngle + 22.5), - degreesToRadians(118.125)); - overFilledPath = Path() - ..addArc(Rect.fromCircle(center: midPoint, radius: actualRadius), - degreesToRadians(newEndAngle - 20), degreesToRadians(225)); + Rect.fromCircle( + center: midPoint, + radius: actualRadius - (actualRadius * 0.05), + ), + degreesToRadians(newEndAngle + 22.5), + degreesToRadians(118.125), + ); + overFilledPath = + Path()..addArc( + Rect.fromCircle(center: midPoint, radius: actualRadius), + degreesToRadians(newEndAngle - 20), + degreesToRadians(225), + ); } else if (series.cornerStyle == CornerStyle.bothFlat || series.cornerStyle == CornerStyle.startCurve) { _overFilledPaint! @@ -720,14 +806,26 @@ class RadialBarSegment extends ChartSegment { ..strokeWidth = series.borderWidth; final Offset shadowStartPoint = calculateOffset( - newEndAngle, outerRadius - (outerRadius * 0.025), _center); + newEndAngle, + outerRadius - (outerRadius * 0.025), + _center, + ); final Offset shadowEndPoint = calculateOffset( - newEndAngle, innerRadius + (innerRadius * 0.025), _center); - - final Offset overFilledStartPoint = - calculateOffset(newEndAngle - 2, outerRadius, _center); - final Offset overFilledEndPoint = - calculateOffset(newEndAngle - 2, innerRadius, _center); + newEndAngle, + innerRadius + (innerRadius * 0.025), + _center, + ); + + final Offset overFilledStartPoint = calculateOffset( + newEndAngle - 2, + outerRadius, + _center, + ); + final Offset overFilledEndPoint = calculateOffset( + newEndAngle - 2, + innerRadius, + _center, + ); shadowPath ..reset() @@ -766,12 +864,16 @@ class RadialBarSegment extends ChartSegment { @override TooltipInfo? tooltipInfo({Offset? position, int? pointIndex}) { final ChartPoint point = ChartPoint( - x: series.circularXValues[currentSegmentIndex], - y: series.circularYValues[currentSegmentIndex]); - final Offset preferredPos = series.localToGlobal(calculateOffset( + x: series.circularXValues[currentSegmentIndex], + y: series.circularYValues[currentSegmentIndex], + ); + final Offset preferredPos = series.localToGlobal( + calculateOffset( (_startAngle + _endAngle) / 2, (_innerRadius + _outerRadius) / 2, - _center)); + _center, + ), + ); return ChartTooltipInfo( primaryPosition: preferredPos, secondaryPosition: preferredPos, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/range_area_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/range_area_series.dart index bc8696e4d..580ce4ed9 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/range_area_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/range_area_series.dart @@ -114,7 +114,9 @@ class RangeAreaSeries extends RangeSeriesBase { @override void updateRenderObject( - BuildContext context, RangeAreaSeriesRenderer renderObject) { + BuildContext context, + RangeAreaSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..borderDrawMode = borderDrawMode @@ -170,17 +172,23 @@ class RangeAreaSeriesRenderer extends RangeSeriesRendererBase final RangeAreaSegment rangeAreaSegment = segment as RangeAreaSegment; updateSegmentColor(rangeAreaSegment, borderColor, borderWidth); - updateSegmentGradient(rangeAreaSegment, - gradientBounds: rangeAreaSegment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + rangeAreaSegment, + gradientBounds: rangeAreaSegment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -208,7 +216,9 @@ class RangeAreaSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -228,26 +238,50 @@ class RangeAreaSegment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -282,18 +316,21 @@ class RangeAreaSegment extends ChartSegment { if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } @@ -301,7 +338,10 @@ class RangeAreaSegment extends ChartSegment { } void _calculatePoints( - List xValues, List highValues, List lowValues) { + List xValues, + List highValues, + List lowValues, + ) { final PointToPixelCallback transformX = series.pointToPixelX; final PointToPixelCallback transformY = series.pointToPixelY; @@ -322,8 +362,10 @@ class RangeAreaSegment extends ChartSegment { _drawIndexes.add(i); final Offset highPoint = Offset(transformX(x, topY), transformY(x, topY)); _highPoints.add(highPoint); - final Offset lowPoint = - Offset(transformX(x, bottomY), transformY(x, bottomY)); + final Offset lowPoint = Offset( + transformX(x, bottomY), + transformY(x, bottomY), + ); _lowPoints.add(lowPoint); points.add(lowPoint); points.add(highPoint); @@ -344,8 +386,10 @@ class RangeAreaSegment extends ChartSegment { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); _createFillPath(_fillPath, lerpHighPoints, lerpLowPoints); @@ -355,13 +399,19 @@ class RangeAreaSegment extends ChartSegment { break; case RangeAreaBorderMode.excludeSides: _createStrokePathForExcludeSides( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; } } Path _createFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int lastIndex = highPoints.length - 1; for (int i = 0; i <= lastIndex; i++) { @@ -369,7 +419,10 @@ class RangeAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createFillPath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { @@ -404,7 +457,10 @@ class RangeAreaSegment extends ChartSegment { } Path _createStrokePathForExcludeSides( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? highPath; Path? lowPath; final int lastIndex = highPoints.length - 1; @@ -413,7 +469,10 @@ class RangeAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (highPoint.isNaN) { _createStrokePathForExcludeSides( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { if (i == 0) { @@ -486,14 +545,17 @@ class RangeAreaSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/range_column_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/range_column_series.dart index 7661199c1..55bac3d78 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/range_column_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/range_column_series.dart @@ -250,7 +250,9 @@ class RangeColumnSeries extends RangeSeriesBase { @override void updateRenderObject( - BuildContext context, RangeColumnSeriesRenderer renderObject) { + BuildContext context, + RangeColumnSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..trackColor = trackColor @@ -383,12 +385,18 @@ class RangeColumnSeriesRenderer extends RangeSeriesRendererBase final RangeColumnSegment rangeColumnSegment = segment as RangeColumnSegment; updateSegmentTrackerStyle( - rangeColumnSegment, trackColor, trackBorderColor, trackBorderWidth); + rangeColumnSegment, + trackColor, + trackBorderColor, + trackBorderWidth, + ); updateSegmentColor(rangeColumnSegment, borderColor, borderWidth); - updateSegmentGradient(rangeColumnSegment, - gradientBounds: rangeColumnSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + rangeColumnSegment, + gradientBounds: rangeColumnSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } } @@ -404,7 +412,9 @@ class RangeColumnSegment extends ChartSegment with BarSeriesTrackerMixin { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -413,8 +423,11 @@ class RangeColumnSegment extends ChartSegment with BarSeriesTrackerMixin { } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -487,18 +500,22 @@ class RangeColumnSegment extends ChartSegment with BarSeriesTrackerMixin { final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -518,8 +535,10 @@ class RangeColumnSegment extends ChartSegment with BarSeriesTrackerMixin { TrackballInfo? trackballInfo(Offset position, int pointIndex) { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); - final Offset preferredPos = - Offset(series.pointToPixelX(x, top), series.pointToPixelY(x, top)); + final Offset preferredPos = Offset( + series.pointToPixelX(x, top), + series.pointToPixelY(x, top), + ); return ChartTrackballInfo( position: preferredPos, highXPos: preferredPos.dx, @@ -561,8 +580,11 @@ class RangeColumnSegment extends ChartSegment with BarSeriesTrackerMixin { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/scatter_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/scatter_series.dart index f04db2747..ddc93f062 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/scatter_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/scatter_series.dart @@ -84,7 +84,9 @@ class ScatterSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, ScatterSeriesRenderer renderObject) { + BuildContext context, + ScatterSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.borderColor = borderColor; } @@ -131,10 +133,12 @@ class ScatterSeriesRenderer extends XyDataSeriesRenderer void customizeSegment(ChartSegment segment) { final ScatterSegment scatterSegment = segment as ScatterSegment; updateSegmentColor(scatterSegment, borderColor, borderWidth); - updateSegmentGradient(scatterSegment, - gradientBounds: scatterSegment.segmentRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + scatterSegment, + gradientBounds: scatterSegment.segmentRect, + gradient: gradient, + borderGradient: borderGradient, + ); } @override @@ -174,7 +178,9 @@ class ScatterSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -183,8 +189,11 @@ class ScatterSegment extends ChartSegment { } if (series.animationDuration > 0) { - _oldSegmentRect = - Rect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = Rect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -229,9 +238,10 @@ class ScatterSegment extends ChartSegment { primaryPosition: series.localToGlobal(segmentRect!.topCenter), secondaryPosition: series.localToGlobal(segmentRect!.bottomCenter), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -287,8 +297,11 @@ class ScatterSegment extends ChartSegment { return; } - final Rect? paintRect = - Rect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final Rect? paintRect = Rect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRect == null || paintRect.isEmpty) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/spline_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/spline_series.dart index 8e3dbdaee..67cc6a97d 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/spline_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/spline_series.dart @@ -44,7 +44,11 @@ mixin _SplineControlPointMixin on CartesianSeriesRenderer { } void _computeMonotonicSpline( - List yValues, List yCoefficient, List dx, int length) { + List yValues, + List yCoefficient, + List dx, + int length, + ) { final List slope = List.filled(length - 1, null); final int dxLength = dx.length; final int slopeLength = slope.length; @@ -76,7 +80,8 @@ mixin _SplineControlPointMixin on CartesianSeriesRenderer { final num firstPoint = dx[i]!; final num nextPoint = dx[i + 1]!; final num interPoint = firstPoint + nextPoint; - yCoefficient[++index] = 3 * + yCoefficient[++index] = + 3 * interPoint / (((interPoint + nextPoint) / m) + ((interPoint + firstPoint) / next)); @@ -91,7 +96,9 @@ mixin _SplineControlPointMixin on CartesianSeriesRenderer { } void _computeCardinalSpline( - List yCoefficient, double cardinalSplineTension) { + List yCoefficient, + double cardinalSplineTension, + ) { if (dataCount <= 2) { for (int i = 0; i < dataCount; i++) { yCoefficient[i] = 0; @@ -122,7 +129,10 @@ mixin _SplineControlPointMixin on CartesianSeriesRenderer { } void _computeNaturalSpline( - List yValues, List yCoefficient, SplineType splineType) { + List yValues, + List yCoefficient, + SplineType splineType, + ) { const double a = 6; num d1, d2, d3, dy1, dy2, p; @@ -267,10 +277,12 @@ mixin _SplineControlPointMixin on CartesianSeriesRenderer { final num dy2 = y1 + (2 * y2); controlX1 = dx1 * oneThird; - controlY1 = oneThird * + controlY1 = + oneThird * (dy1 - (oneThird * deltaXSquared * (yCoef1 + (0.5 * yCoef2)))); controlX2 = dx2 * oneThird; - controlY2 = oneThird * + controlY2 = + oneThird * (dy2 - (oneThird * deltaXSquared * ((0.5 * yCoef1) + yCoef2))); _yMax = max(_yMax, max(controlY1, max(controlY2, max(y1, y2)))); break; @@ -446,7 +458,9 @@ class SplineSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, SplineSeriesRenderer renderObject) { + BuildContext context, + SplineSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..splineType = splineType @@ -508,10 +522,12 @@ class SplineSeriesRenderer extends XyDataSeriesRenderer final num dy2 = y1 + (2 * y2); controlX1 = dx1 * oneThird; - controlY1 = oneThird * + controlY1 = + oneThird * (dy1 - (oneThird * deltaXSquared * (yCoef1 + (0.5 * yCoef2)))); controlX2 = dx2 * oneThird; - controlY2 = oneThird * + controlY2 = + oneThird * (dy2 - (oneThird * deltaXSquared * ((0.5 * yCoef1) + yCoef2))); _yMax = max(_yMax, max(controlY1, max(controlY2, max(y1, y2)))); break; @@ -561,7 +577,11 @@ class SplineSeriesRenderer extends XyDataSeriesRenderer x1 = xValues[index]; y1 = yValues[index]; nextIndex = nextIndexConsideringEmptyPointMode( - index, emptyPointSettings.mode, yValues, dataCount); + index, + emptyPointSettings.mode, + yValues, + dataCount, + ); if (nextIndex != -1) { x2 = xValues[nextIndex]; y2 = yValues[nextIndex]; @@ -605,8 +625,12 @@ class SplineSeriesRenderer extends XyDataSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.save(); context.canvas.clipRect(clip); paintSegments(context, offset); @@ -649,7 +673,9 @@ class SplineSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldStartControlX = null; @@ -687,14 +713,26 @@ class SplineSegment extends ChartSegment { } } - _oldStartControlX = - lerpDouble(_oldStartControlX, startControlX, segmentAnimationFactor); - _oldStartControlY = - lerpDouble(_oldStartControlY, startControlY, segmentAnimationFactor); - _oldEndControlX = - lerpDouble(_oldEndControlX, endControlX, segmentAnimationFactor); - _oldEndControlY = - lerpDouble(_oldEndControlY, endControlY, segmentAnimationFactor); + _oldStartControlX = lerpDouble( + _oldStartControlX, + startControlX, + segmentAnimationFactor, + ); + _oldStartControlY = lerpDouble( + _oldStartControlY, + startControlY, + segmentAnimationFactor, + ); + _oldEndControlX = lerpDouble( + _oldEndControlX, + endControlX, + segmentAnimationFactor, + ); + _oldEndControlY = lerpDouble( + _oldEndControlY, + endControlY, + segmentAnimationFactor, + ); } else { _oldPoints.clear(); } @@ -733,8 +771,11 @@ class SplineSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -768,9 +809,10 @@ class SplineSegment extends ChartSegment { final int nearestPointIndex = position == null ? 0 : _nearestPointIndex(points, position); if (nearestPointIndex != -1) { - pointIndex ??= (position == null || nearestPointIndex == 0 - ? currentSegmentIndex - : currentSegmentIndex + 1); + pointIndex ??= + (position == null || nearestPointIndex == 0 + ? currentSegmentIndex + : currentSegmentIndex + 1); CartesianChartPoint chartPoint = _chartPoint(pointIndex); List markerColors = [fillPaint.color]; if (chartPoint.y != null && chartPoint.y!.isNaN) { @@ -783,14 +825,17 @@ class SplineSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = points[nearestPointIndex]; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -846,8 +891,11 @@ class SplineSegment extends ChartSegment { return; } - final Offset? start = - Offset.lerp(_oldPoints[0], points[0], animationFactor); + final Offset? start = Offset.lerp( + _oldPoints[0], + points[0], + animationFactor, + ); final Offset? end = Offset.lerp(_oldPoints[1], points[1], animationFactor); final double controlX1 = lerpDouble(_oldStartControlX, startControlX, animationFactor)!; @@ -859,9 +907,17 @@ class SplineSegment extends ChartSegment { lerpDouble(_oldEndControlY, endControlY, animationFactor)!; if (start != null && end != null) { - final Path path = Path() - ..moveTo(start.dx, start.dy) - ..cubicTo(controlX1, controlY1, controlX2, controlY2, end.dx, end.dy); + final Path path = + Path() + ..moveTo(start.dx, start.dy) + ..cubicTo( + controlX1, + controlY1, + controlX2, + controlY2, + end.dx, + end.dy, + ); final Paint paint = getStrokePaint(); if (paint.color != Colors.transparent && paint.strokeWidth > 0) { drawDashes(canvas, series.dashArray, paint, path: path); @@ -1013,8 +1069,10 @@ class SplineAreaSeries extends XyDataSeries { } @override - void updateRenderObject(BuildContext context, - covariant SplineAreaSeriesRenderer renderObject) { + void updateRenderObject( + BuildContext context, + covariant SplineAreaSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..borderDrawMode = borderDrawMode @@ -1135,16 +1193,22 @@ class SplineAreaSeriesRenderer extends XyDataSeriesRenderer final SplineAreaSegment splineAreaSegment = segment as SplineAreaSegment; updateSegmentColor(splineAreaSegment, borderColor, borderWidth); - updateSegmentGradient(splineAreaSegment, - gradientBounds: splineAreaSegment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + splineAreaSegment, + gradientBounds: splineAreaSegment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override void onPaint(PaintingContext context, Offset offset) { - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); super.onPaint(context, offset); } @@ -1191,7 +1255,9 @@ class SplineAreaSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -1215,26 +1281,50 @@ class SplineAreaSegment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + bottom, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + bottom, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + bottom, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -1244,33 +1334,63 @@ class SplineAreaSegment extends ChartSegment { final int newControlPointsLength = _startControlHighPoints.length; if (oldControlPointsLength == newControlPointsLength) { for (int i = 0; i < oldControlPointsLength; i++) { - _oldStartControlHighPoints[i] = _oldStartControlHighPoints[i].lerp( - _startControlHighPoints[i], segmentAnimationFactor, bottom)!; - _oldEndControlHighPoints[i] = _oldEndControlHighPoints[i] - .lerp(_endControlHighPoints[i], segmentAnimationFactor, bottom)!; + _oldStartControlHighPoints[i] = + _oldStartControlHighPoints[i].lerp( + _startControlHighPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldEndControlHighPoints[i] = + _oldEndControlHighPoints[i].lerp( + _endControlHighPoints[i], + segmentAnimationFactor, + bottom, + )!; } } else if (oldControlPointsLength < newControlPointsLength) { for (int i = 0; i < oldControlPointsLength; i++) { - _oldStartControlHighPoints[i] = _oldStartControlHighPoints[i].lerp( - _startControlHighPoints[i], segmentAnimationFactor, bottom)!; - _oldEndControlHighPoints[i] = _oldEndControlHighPoints[i] - .lerp(_endControlHighPoints[i], segmentAnimationFactor, bottom)!; + _oldStartControlHighPoints[i] = + _oldStartControlHighPoints[i].lerp( + _startControlHighPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldEndControlHighPoints[i] = + _oldEndControlHighPoints[i].lerp( + _endControlHighPoints[i], + segmentAnimationFactor, + bottom, + )!; } - _oldStartControlHighPoints - .addAll(_startControlHighPoints.sublist(oldControlPointsLength)); - _oldEndControlHighPoints - .addAll(_endControlHighPoints.sublist(oldControlPointsLength)); + _oldStartControlHighPoints.addAll( + _startControlHighPoints.sublist(oldControlPointsLength), + ); + _oldEndControlHighPoints.addAll( + _endControlHighPoints.sublist(oldControlPointsLength), + ); } else { for (int i = 0; i < newControlPointsLength; i++) { - _oldStartControlHighPoints[i] = _oldStartControlHighPoints[i].lerp( - _startControlHighPoints[i], segmentAnimationFactor, bottom)!; - _oldEndControlHighPoints[i] = _oldEndControlHighPoints[i] - .lerp(_endControlHighPoints[i], segmentAnimationFactor, bottom)!; + _oldStartControlHighPoints[i] = + _oldStartControlHighPoints[i].lerp( + _startControlHighPoints[i], + segmentAnimationFactor, + bottom, + )!; + _oldEndControlHighPoints[i] = + _oldEndControlHighPoints[i].lerp( + _endControlHighPoints[i], + segmentAnimationFactor, + bottom, + )!; } _oldStartControlHighPoints.removeRange( - newControlPointsLength, oldControlPointsLength); + newControlPointsLength, + oldControlPointsLength, + ); _oldEndControlHighPoints.removeRange( - newControlPointsLength, oldControlPointsLength); + newControlPointsLength, + oldControlPointsLength, + ); } } else { _oldHighPoints.clear(); @@ -1296,8 +1416,13 @@ class SplineAreaSegment extends ChartSegment { } _calculatePoints(_xValues, _yValues); - _createFillPath(_fillPath, _highPoints, _lowPoints, _startControlHighPoints, - _endControlHighPoints); + _createFillPath( + _fillPath, + _highPoints, + _lowPoints, + _startControlHighPoints, + _endControlHighPoints, + ); } void _calculatePoints(List xValues, List yValues) { @@ -1327,14 +1452,17 @@ class SplineAreaSegment extends ChartSegment { final num startHighX = _startControlHighXValues[i]; final num startHighY = _startControlHighYValues[i]; final Offset startControlHighPoint = Offset( - transformX(startHighX, startHighY), - transformY(startHighX, startHighY)); + transformX(startHighX, startHighY), + transformY(startHighX, startHighY), + ); _startControlHighPoints.add(startControlHighPoint); final num endHighX = _endControlHighXValues[i]; final num endHighY = _endControlHighYValues[i]; final Offset endControlHighPoint = Offset( - transformX(endHighX, endHighY), transformY(endHighX, endHighY)); + transformX(endHighX, endHighY), + transformY(endHighX, endHighY), + ); _endControlHighPoints.add(endControlHighPoint); } } @@ -1347,8 +1475,9 @@ class SplineAreaSegment extends ChartSegment { length = _oldStartControlHighPoints.length; if (_startControlHighPoints.length > length) { - _oldStartControlHighPoints - .addAll(_startControlHighPoints.sublist(length)); + _oldStartControlHighPoints.addAll( + _startControlHighPoints.sublist(length), + ); _oldEndControlHighPoints.addAll(_endControlHighPoints.sublist(length)); } } @@ -1361,15 +1490,26 @@ class SplineAreaSegment extends ChartSegment { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); - final List lerpStartControlHighPoints = - _lerpPoints(_oldStartControlHighPoints, _startControlHighPoints); - final List lerpEndControlHighPoints = - _lerpPoints(_oldEndControlHighPoints, _endControlHighPoints); - _createFillPath(_fillPath, lerpHighPoints, lerpLowPoints, - lerpStartControlHighPoints, lerpEndControlHighPoints); + final List lerpStartControlHighPoints = _lerpPoints( + _oldStartControlHighPoints, + _startControlHighPoints, + ); + final List lerpEndControlHighPoints = _lerpPoints( + _oldEndControlHighPoints, + _endControlHighPoints, + ); + _createFillPath( + _fillPath, + lerpHighPoints, + lerpLowPoints, + lerpStartControlHighPoints, + lerpEndControlHighPoints, + ); switch (series.borderDrawMode) { case BorderDrawMode.all: @@ -1401,19 +1541,22 @@ class SplineAreaSegment extends ChartSegment { final int newPointsLength = newPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, bottom)!, + ); } } @@ -1474,8 +1617,14 @@ class SplineAreaSegment extends ChartSegment { } else { final Offset startControlHigh = startControlHighPoints[i - 1]; final Offset endControlHigh = endControlHighPoints[i - 1]; - path!.cubicTo(startControlHigh.dx, startControlHigh.dy, - endControlHigh.dx, endControlHigh.dy, highPoint.dx, highPoint.dy); + path!.cubicTo( + startControlHigh.dx, + startControlHigh.dy, + endControlHigh.dx, + endControlHigh.dy, + highPoint.dx, + highPoint.dy, + ); if (i == lastIndex) { for (int j = i; j >= 0; j--) { final Offset lowPoint = lowPoints[j]; @@ -1521,8 +1670,14 @@ class SplineAreaSegment extends ChartSegment { } else { final Offset startControlHigh = startControlHighPoints[i - 1]; final Offset endControlHigh = endControlHighPoints[i - 1]; - path!.cubicTo(startControlHigh.dx, startControlHigh.dy, - endControlHigh.dx, endControlHigh.dy, highPoint.dx, highPoint.dy); + path!.cubicTo( + startControlHigh.dx, + startControlHigh.dy, + endControlHigh.dx, + endControlHigh.dy, + highPoint.dx, + highPoint.dy, + ); } } } @@ -1585,8 +1740,14 @@ class SplineAreaSegment extends ChartSegment { } else { final Offset startControlHigh = startControlHighPoints[i - 1]; final Offset endControlHigh = endControlHighPoints[i - 1]; - path!.cubicTo(startControlHigh.dx, startControlHigh.dy, - endControlHigh.dx, endControlHigh.dy, highPoint.dx, highPoint.dy); + path!.cubicTo( + startControlHigh.dx, + startControlHigh.dy, + endControlHigh.dx, + endControlHigh.dy, + highPoint.dx, + highPoint.dy, + ); if (i == lastIndex) { final Offset lowPoint = lowPoints[i]; path.lineTo(lowPoint.dx, lowPoint.dy); @@ -1605,8 +1766,11 @@ class SplineAreaSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -1646,14 +1810,17 @@ class SplineAreaSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -1896,8 +2063,9 @@ class SplineRangeAreaSeries extends RangeSeriesBase { @override SplineRangeAreaSeriesRenderer createRenderObject(BuildContext context) { - final SplineRangeAreaSeriesRenderer renderer = super - .createRenderObject(context) as SplineRangeAreaSeriesRenderer; + final SplineRangeAreaSeriesRenderer renderer = + super.createRenderObject(context) + as SplineRangeAreaSeriesRenderer; renderer ..borderDrawMode = borderDrawMode ..splineType = splineType @@ -1908,7 +2076,9 @@ class SplineRangeAreaSeries extends RangeSeriesBase { @override void updateRenderObject( - BuildContext context, SplineRangeAreaSeriesRenderer renderObject) { + BuildContext context, + SplineRangeAreaSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..borderDrawMode = borderDrawMode @@ -1977,9 +2147,10 @@ class SplineRangeAreaSeriesRenderer extends RangeSeriesRendererBase final int nextIndex = index + 1; if (nextIndex < dataCount) { x2 = xValues[nextIndex]; - y2 = _isHigh - ? nonEmptyHighValues[nextIndex] - : nonEmptyLowValues[nextIndex]; + y2 = + _isHigh + ? nonEmptyHighValues[nextIndex] + : nonEmptyLowValues[nextIndex]; } _buildSplineAreaSegment( @@ -2030,17 +2201,23 @@ class SplineRangeAreaSeriesRenderer extends RangeSeriesRendererBase final SplineRangeAreaSegment splineRangeAreaSegment = segment as SplineRangeAreaSegment; updateSegmentColor(splineRangeAreaSegment, borderColor, borderWidth); - updateSegmentGradient(splineRangeAreaSegment, - gradientBounds: splineRangeAreaSegment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + splineRangeAreaSegment, + gradientBounds: splineRangeAreaSegment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -2098,7 +2275,9 @@ class SplineRangeAreaSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -2126,26 +2305,50 @@ class SplineRangeAreaSegment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -2155,79 +2358,115 @@ class SplineRangeAreaSegment extends ChartSegment { final int newControlPointsLength = _startControlHighPoints.length; if (oldControlPointsLength == newControlPointsLength) { for (int i = 0; i < oldControlPointsLength; i++) { - _oldStartControlHighPoints[i] = _oldStartControlHighPoints[i].lerp( - _startControlHighPoints[i], - segmentAnimationFactor, - _startControlHighPoints[i].dy)!; - _oldEndControlHighPoints[i] = _oldEndControlHighPoints[i].lerp( - _endControlHighPoints[i], - segmentAnimationFactor, - _oldEndControlHighPoints[i].dy)!; - - _oldStartControlLowPoints[i] = _oldStartControlLowPoints[i].lerp( - _startControlLowPoints[i], - segmentAnimationFactor, - _startControlLowPoints[i].dy)!; - _oldEndControlLowPoints[i] = _oldEndControlLowPoints[i].lerp( - _endControlLowPoints[i], - segmentAnimationFactor, - _oldEndControlLowPoints[i].dy)!; + _oldStartControlHighPoints[i] = + _oldStartControlHighPoints[i].lerp( + _startControlHighPoints[i], + segmentAnimationFactor, + _startControlHighPoints[i].dy, + )!; + _oldEndControlHighPoints[i] = + _oldEndControlHighPoints[i].lerp( + _endControlHighPoints[i], + segmentAnimationFactor, + _oldEndControlHighPoints[i].dy, + )!; + + _oldStartControlLowPoints[i] = + _oldStartControlLowPoints[i].lerp( + _startControlLowPoints[i], + segmentAnimationFactor, + _startControlLowPoints[i].dy, + )!; + _oldEndControlLowPoints[i] = + _oldEndControlLowPoints[i].lerp( + _endControlLowPoints[i], + segmentAnimationFactor, + _oldEndControlLowPoints[i].dy, + )!; } } else if (oldControlPointsLength < newControlPointsLength) { for (int i = 0; i < oldControlPointsLength; i++) { - _oldStartControlHighPoints[i] = _oldStartControlHighPoints[i].lerp( - _startControlHighPoints[i], - segmentAnimationFactor, - _startControlHighPoints[i].dy)!; - _oldEndControlHighPoints[i] = _oldEndControlHighPoints[i].lerp( - _endControlHighPoints[i], - segmentAnimationFactor, - _oldEndControlHighPoints[i].dy)!; - _oldStartControlLowPoints[i] = _oldStartControlLowPoints[i].lerp( - _startControlLowPoints[i], - segmentAnimationFactor, - _startControlLowPoints[i].dy)!; - _oldEndControlLowPoints[i] = _oldEndControlLowPoints[i].lerp( - _endControlLowPoints[i], - segmentAnimationFactor, - _oldEndControlLowPoints[i].dy)!; + _oldStartControlHighPoints[i] = + _oldStartControlHighPoints[i].lerp( + _startControlHighPoints[i], + segmentAnimationFactor, + _startControlHighPoints[i].dy, + )!; + _oldEndControlHighPoints[i] = + _oldEndControlHighPoints[i].lerp( + _endControlHighPoints[i], + segmentAnimationFactor, + _oldEndControlHighPoints[i].dy, + )!; + _oldStartControlLowPoints[i] = + _oldStartControlLowPoints[i].lerp( + _startControlLowPoints[i], + segmentAnimationFactor, + _startControlLowPoints[i].dy, + )!; + _oldEndControlLowPoints[i] = + _oldEndControlLowPoints[i].lerp( + _endControlLowPoints[i], + segmentAnimationFactor, + _oldEndControlLowPoints[i].dy, + )!; } - _oldStartControlHighPoints - .addAll(_startControlHighPoints.sublist(oldControlPointsLength)); - _oldEndControlHighPoints - .addAll(_endControlHighPoints.sublist(oldControlPointsLength)); - _oldStartControlLowPoints - .addAll(_startControlLowPoints.sublist(oldControlPointsLength)); - _oldEndControlLowPoints - .addAll(_endControlLowPoints.sublist(oldControlPointsLength)); + _oldStartControlHighPoints.addAll( + _startControlHighPoints.sublist(oldControlPointsLength), + ); + _oldEndControlHighPoints.addAll( + _endControlHighPoints.sublist(oldControlPointsLength), + ); + _oldStartControlLowPoints.addAll( + _startControlLowPoints.sublist(oldControlPointsLength), + ); + _oldEndControlLowPoints.addAll( + _endControlLowPoints.sublist(oldControlPointsLength), + ); } else { for (int i = 0; i < newControlPointsLength; i++) { - _oldStartControlHighPoints[i] = _oldStartControlHighPoints[i].lerp( - _startControlHighPoints[i], - segmentAnimationFactor, - _startControlHighPoints[i].dy)!; - _oldEndControlHighPoints[i] = _oldEndControlHighPoints[i].lerp( - _endControlHighPoints[i], - segmentAnimationFactor, - _oldEndControlHighPoints[i].dy)!; - - _oldStartControlLowPoints[i] = _oldStartControlLowPoints[i].lerp( - _startControlLowPoints[i], - segmentAnimationFactor, - _startControlLowPoints[i].dy)!; - _oldEndControlLowPoints[i] = _oldEndControlLowPoints[i].lerp( - _endControlLowPoints[i], - segmentAnimationFactor, - _oldEndControlLowPoints[i].dy)!; + _oldStartControlHighPoints[i] = + _oldStartControlHighPoints[i].lerp( + _startControlHighPoints[i], + segmentAnimationFactor, + _startControlHighPoints[i].dy, + )!; + _oldEndControlHighPoints[i] = + _oldEndControlHighPoints[i].lerp( + _endControlHighPoints[i], + segmentAnimationFactor, + _oldEndControlHighPoints[i].dy, + )!; + + _oldStartControlLowPoints[i] = + _oldStartControlLowPoints[i].lerp( + _startControlLowPoints[i], + segmentAnimationFactor, + _startControlLowPoints[i].dy, + )!; + _oldEndControlLowPoints[i] = + _oldEndControlLowPoints[i].lerp( + _endControlLowPoints[i], + segmentAnimationFactor, + _oldEndControlLowPoints[i].dy, + )!; } _oldStartControlHighPoints.removeRange( - newControlPointsLength, oldControlPointsLength); + newControlPointsLength, + oldControlPointsLength, + ); _oldEndControlHighPoints.removeRange( - newControlPointsLength, oldControlPointsLength); + newControlPointsLength, + oldControlPointsLength, + ); _oldStartControlLowPoints.removeRange( - newControlPointsLength, oldControlPointsLength); + newControlPointsLength, + oldControlPointsLength, + ); _oldEndControlLowPoints.removeRange( - newControlPointsLength, oldControlPointsLength); + newControlPointsLength, + oldControlPointsLength, + ); } } else { _oldHighPoints.clear(); @@ -2287,8 +2526,10 @@ class SplineRangeAreaSegment extends ChartSegment { } _drawIndexes.add(i); - final Offset highPoint = - Offset(transformX(x, highY), transformY(x, highY)); + final Offset highPoint = Offset( + transformX(x, highY), + transformY(x, highY), + ); _highPoints.add(highPoint); final Offset lowPoint = Offset(transformX(x, lowY), transformY(x, lowY)); _lowPoints.add(lowPoint); @@ -2298,8 +2539,10 @@ class SplineRangeAreaSegment extends ChartSegment { if (i < controlPointsLength) { num xValue = _startControlHighXValues[i]; num yValue = _startControlHighYValues[i]; - Offset point = - Offset(transformX(xValue, yValue), transformY(xValue, yValue)); + Offset point = Offset( + transformX(xValue, yValue), + transformY(xValue, yValue), + ); _startControlHighPoints.add(point); xValue = _endControlHighXValues[i]; @@ -2327,11 +2570,13 @@ class SplineRangeAreaSegment extends ChartSegment { oldLength = _oldStartControlHighPoints.length; if (_startControlHighPoints.length > oldLength) { - _oldStartControlHighPoints - .addAll(_startControlHighPoints.sublist(oldLength)); + _oldStartControlHighPoints.addAll( + _startControlHighPoints.sublist(oldLength), + ); _oldEndControlHighPoints.addAll(_endControlHighPoints.sublist(oldLength)); - _oldStartControlLowPoints - .addAll(_startControlLowPoints.sublist(oldLength)); + _oldStartControlLowPoints.addAll( + _startControlLowPoints.sublist(oldLength), + ); _oldEndControlLowPoints.addAll(_endControlLowPoints.sublist(oldLength)); } } @@ -2344,17 +2589,27 @@ class SplineRangeAreaSegment extends ChartSegment { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); - final List lerpStartControlHighPoints = - _lerpPoints(_oldStartControlHighPoints, _startControlHighPoints); - final List lerpEndControlHighPoints = - _lerpPoints(_oldEndControlHighPoints, _endControlHighPoints); - final List lerpStartControlLowPoints = - _lerpPoints(_oldStartControlLowPoints, _startControlLowPoints); - final List lerpEndControlLowPoints = - _lerpPoints(_oldEndControlLowPoints, _endControlLowPoints); + final List lerpStartControlHighPoints = _lerpPoints( + _oldStartControlHighPoints, + _startControlHighPoints, + ); + final List lerpEndControlHighPoints = _lerpPoints( + _oldEndControlHighPoints, + _endControlHighPoints, + ); + final List lerpStartControlLowPoints = _lerpPoints( + _oldStartControlLowPoints, + _startControlLowPoints, + ); + final List lerpEndControlLowPoints = _lerpPoints( + _oldEndControlLowPoints, + _endControlLowPoints, + ); _createFillPath( _fillPath, lerpHighPoints, @@ -2390,18 +2645,21 @@ class SplineRangeAreaSegment extends ChartSegment { if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } @@ -2458,8 +2716,14 @@ class SplineRangeAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[j]; final Offset startLow = startControlLowPoints[j]; final Offset endLow = endControlLowPoints[j]; - path!.cubicTo(endLow.dx, endLow.dy, startLow.dx, startLow.dy, - lowPoint.dx, lowPoint.dy); + path!.cubicTo( + endLow.dx, + endLow.dy, + startLow.dx, + startLow.dy, + lowPoint.dx, + lowPoint.dy, + ); } final int controlPointsLength = startControlHighPoints.length; if (i < length && i < controlPointsLength) { @@ -2477,8 +2741,14 @@ class SplineRangeAreaSegment extends ChartSegment { } else { final Offset startHigh = startControlHighPoints[i - 1]; final Offset endHigh = endControlHighPoints[i - 1]; - path!.cubicTo(startHigh.dx, startHigh.dy, endHigh.dx, endHigh.dy, - highPoint.dx, highPoint.dy); + path!.cubicTo( + startHigh.dx, + startHigh.dy, + endHigh.dx, + endHigh.dy, + highPoint.dx, + highPoint.dy, + ); if (i == lastIndex) { for (int j = i; j >= 0; j--) { if (j == i) { @@ -2490,8 +2760,14 @@ class SplineRangeAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[j]; final Offset startLow = startControlLowPoints[j]; final Offset endLow = endControlLowPoints[j]; - path.cubicTo(endLow.dx, endLow.dy, startLow.dx, startLow.dy, - lowPoint.dx, lowPoint.dy); + path.cubicTo( + endLow.dx, + endLow.dy, + startLow.dx, + startLow.dy, + lowPoint.dx, + lowPoint.dy, + ); } } } @@ -2542,13 +2818,25 @@ class SplineRangeAreaSegment extends ChartSegment { } else { final Offset startHigh = startControlHighPoints[i - 1]; final Offset endHigh = endControlHighPoints[i - 1]; - highPath!.cubicTo(startHigh.dx, startHigh.dy, endHigh.dx, endHigh.dy, - highPoint.dx, highPoint.dy); + highPath!.cubicTo( + startHigh.dx, + startHigh.dy, + endHigh.dx, + endHigh.dy, + highPoint.dx, + highPoint.dy, + ); final Offset startLow = startControlLowPoints[i - 1]; final Offset endLow = endControlLowPoints[i - 1]; - lowPath!.cubicTo(startLow.dx, startLow.dy, endLow.dx, endLow.dy, - lowPoint.dx, lowPoint.dy); + lowPath!.cubicTo( + startLow.dx, + startLow.dy, + endLow.dx, + endLow.dy, + lowPoint.dx, + lowPoint.dy, + ); } } } @@ -2611,14 +2899,17 @@ class SplineRangeAreaSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area100_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area100_series.dart index c1ba3672b..e14de03a2 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area100_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area100_series.dart @@ -121,7 +121,9 @@ class StackedArea100Series extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedArea100SeriesRenderer renderObject) { + BuildContext context, + StackedArea100SeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..borderDrawMode = borderDrawMode @@ -178,17 +180,23 @@ class StackedArea100SeriesRenderer extends StackedSeriesRenderer final StackedArea100Segment stackedArea100Segment = segment as StackedArea100Segment; updateSegmentColor(stackedArea100Segment, borderColor, borderWidth); - updateSegmentGradient(stackedArea100Segment, - gradientBounds: stackedArea100Segment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stackedArea100Segment, + gradientBounds: stackedArea100Segment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -218,7 +226,9 @@ class StackedArea100Segment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -238,26 +248,50 @@ class StackedArea100Segment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -300,8 +334,11 @@ class StackedArea100Segment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -309,7 +346,10 @@ class StackedArea100Segment extends ChartSegment { } void _calculatePoints( - List xValues, List topValues, List bottomValues) { + List xValues, + List topValues, + List bottomValues, + ) { final PointToPixelCallback transformX = series.pointToPixelX; final PointToPixelCallback transformY = series.pointToPixelY; @@ -330,8 +370,10 @@ class StackedArea100Segment extends ChartSegment { final Offset highPoint = Offset(transformX(x, topY), transformY(x, topY)); _highPoints.add(highPoint); - final Offset lowPoint = - Offset(transformX(x, bottomY), transformY(x, bottomY)); + final Offset lowPoint = Offset( + transformX(x, bottomY), + transformY(x, bottomY), + ); _lowPoints.add(lowPoint); points.add(highPoint); @@ -345,7 +387,10 @@ class StackedArea100Segment extends ChartSegment { } void _calculateDropPoints( - List xValues, List topValues, List bottomValues) { + List xValues, + List topValues, + List bottomValues, + ) { final PointToPixelCallback transformX = series.pointToPixelX; final PointToPixelCallback transformY = series.pointToPixelY; @@ -377,8 +422,10 @@ class StackedArea100Segment extends ChartSegment { continue; } - final Offset lowPoint = - Offset(transformX(x, bottomY), transformY(x, bottomY)); + final Offset lowPoint = Offset( + transformX(x, bottomY), + transformY(x, bottomY), + ); _lowPoints.add(lowPoint); } @@ -397,8 +444,10 @@ class StackedArea100Segment extends ChartSegment { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); switch (series.emptyPointSettings.mode) { @@ -428,12 +477,18 @@ class StackedArea100Segment extends ChartSegment { case EmptyPointMode.zero: case EmptyPointMode.average: _createExcludeBottomStrokePath( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; case EmptyPointMode.drop: _createExcludeBottomStrokePathForDrop( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; } break; @@ -447,18 +502,21 @@ class StackedArea100Segment extends ChartSegment { if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } @@ -466,7 +524,10 @@ class StackedArea100Segment extends ChartSegment { } Path _createFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -475,7 +536,10 @@ class StackedArea100Segment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createFillPath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -509,7 +573,10 @@ class StackedArea100Segment extends ChartSegment { } Path _createDropFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; int length = highPoints.length; for (int i = 0; i < length; i++) { @@ -560,7 +627,10 @@ class StackedArea100Segment extends ChartSegment { } Path _createExcludeBottomStrokePath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -569,7 +639,10 @@ class StackedArea100Segment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createExcludeBottomStrokePath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -582,7 +655,10 @@ class StackedArea100Segment extends ChartSegment { final Offset lowPoint = lowPoints[i - 1]; path!.lineTo(lowPoint.dx, lowPoint.dy); _createExcludeBottomStrokePath( - source, highPoints.sublist(i), lowPoints.sublist(i)); + source, + highPoints.sublist(i), + lowPoints.sublist(i), + ); break; } else { path!.lineTo(highPoint.dx, highPoint.dy); @@ -601,7 +677,10 @@ class StackedArea100Segment extends ChartSegment { } Path _createExcludeBottomStrokePathForDrop( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; for (int i = 0; i < length; i++) { @@ -659,14 +738,17 @@ class StackedArea100Segment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area_series.dart index 33ec6fe55..adc914554 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_area_series.dart @@ -120,7 +120,9 @@ class StackedAreaSeries extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedAreaSeriesRenderer renderObject) { + BuildContext context, + StackedAreaSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..groupName = groupName @@ -177,17 +179,23 @@ class StackedAreaSeriesRenderer extends StackedSeriesRenderer final StackedAreaSegment stackedAreaSegment = segment as StackedAreaSegment; updateSegmentColor(stackedAreaSegment, borderColor, borderWidth); - updateSegmentGradient(stackedAreaSegment, - gradientBounds: stackedAreaSegment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stackedAreaSegment, + gradientBounds: stackedAreaSegment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -217,7 +225,9 @@ class StackedAreaSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -237,26 +247,50 @@ class StackedAreaSegment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _highPoints[i].dy)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _lowPoints[i].dy)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _highPoints[i].dy, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _lowPoints[i].dy, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -295,7 +329,10 @@ class StackedAreaSegment extends ChartSegment { } void _calculatePoints( - List xValues, List topValues, List bottomValues) { + List xValues, + List topValues, + List bottomValues, + ) { final PointToPixelCallback transformX = series.pointToPixelX; final PointToPixelCallback transformY = series.pointToPixelY; @@ -316,8 +353,10 @@ class StackedAreaSegment extends ChartSegment { final Offset highPoint = Offset(transformX(x, topY), transformY(x, topY)); _highPoints.add(highPoint); - final Offset lowPoint = - Offset(transformX(x, bottomY), transformY(x, bottomY)); + final Offset lowPoint = Offset( + transformX(x, bottomY), + transformY(x, bottomY), + ); _lowPoints.add(lowPoint); points.add(highPoint); @@ -331,7 +370,10 @@ class StackedAreaSegment extends ChartSegment { } void _calculateDropPoints( - List xValues, List topValues, List bottomValues) { + List xValues, + List topValues, + List bottomValues, + ) { final PointToPixelCallback transformX = series.pointToPixelX; final PointToPixelCallback transformY = series.pointToPixelY; @@ -363,8 +405,10 @@ class StackedAreaSegment extends ChartSegment { continue; } - final Offset lowPoint = - Offset(transformX(x, bottomY), transformY(x, bottomY)); + final Offset lowPoint = Offset( + transformX(x, bottomY), + transformY(x, bottomY), + ); _lowPoints.add(lowPoint); } @@ -383,8 +427,10 @@ class StackedAreaSegment extends ChartSegment { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); switch (series.emptyPointSettings.mode) { @@ -414,12 +460,18 @@ class StackedAreaSegment extends ChartSegment { case EmptyPointMode.zero: case EmptyPointMode.average: _createExcludeBottomStrokePath( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; case EmptyPointMode.drop: _createExcludeBottomStrokePathForDrop( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; } break; @@ -433,18 +485,21 @@ class StackedAreaSegment extends ChartSegment { if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { lerpPoints.add( - oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!); + oldPoints[i].lerp(newPoints[i], animationFactor, newPoints[i].dy)!, + ); } } @@ -452,7 +507,10 @@ class StackedAreaSegment extends ChartSegment { } Path _createFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -461,7 +519,10 @@ class StackedAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createFillPath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -495,7 +556,10 @@ class StackedAreaSegment extends ChartSegment { } Path _createDropFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; int length = highPoints.length; for (int i = 0; i < length; i++) { @@ -546,7 +610,10 @@ class StackedAreaSegment extends ChartSegment { } Path _createExcludeBottomStrokePath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -555,7 +622,10 @@ class StackedAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i]; if (lowPoint.isNaN) { _createExcludeBottomStrokePath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -568,7 +638,10 @@ class StackedAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i - 1]; path!.lineTo(lowPoint.dx, lowPoint.dy); _createExcludeBottomStrokePath( - source, highPoints.sublist(i), lowPoints.sublist(i)); + source, + highPoints.sublist(i), + lowPoints.sublist(i), + ); break; } else { path!.lineTo(highPoint.dx, highPoint.dy); @@ -587,7 +660,10 @@ class StackedAreaSegment extends ChartSegment { } Path _createExcludeBottomStrokePathForDrop( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; for (int i = 0; i < length; i++) { @@ -616,8 +692,11 @@ class StackedAreaSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -658,14 +737,17 @@ class StackedAreaSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar100_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar100_series.dart index 7c49d4694..87cdb22dc 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar100_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar100_series.dart @@ -136,7 +136,9 @@ class StackedBar100Series extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedBar100SeriesRenderer renderObject) { + BuildContext context, + StackedBar100SeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..spacing = spacing @@ -173,8 +175,11 @@ class StackedBar100SeriesRenderer extends StackedSeriesRenderer } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { final num x = current.x! + (sbsInfo.maximum + sbsInfo.minimum) / 2; final double bottomValue = bottomValues[current.dataPointIndex].toDouble(); double y = current.y!.toDouble(); @@ -184,11 +189,21 @@ class StackedBar100SeriesRenderer extends StackedSeriesRenderer y = (y + bottomValue) / 2; } return _calculateDataLabelPosition( - x, y, alignment, size, current.y!.isNegative); + x, + y, + alignment, + size, + current.y!.isNegative, + ); } - Offset _calculateDataLabelPosition(num x, num y, - ChartDataLabelAlignment alignment, Size size, bool isNegative) { + Offset _calculateDataLabelPosition( + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + bool isNegative, + ) { final EdgeInsets margin = dataLabelSettings.margin; double translationX = 0.0; double translationY = 0.0; @@ -197,29 +212,33 @@ class StackedBar100SeriesRenderer extends StackedSeriesRenderer case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.width + margin.horizontal); + translationX = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? -(dataLabelPadding + size.height + margin.vertical) - : dataLabelPadding; + translationY = + isNegative + ? -(dataLabelPadding + size.height + margin.vertical) + : dataLabelPadding; } return translateTransform(x, y, translationX, translationY); @@ -262,10 +281,12 @@ class StackedBar100SeriesRenderer extends StackedSeriesRenderer final StackedBar100Segment stackedBar100Segment = segment as StackedBar100Segment; updateSegmentColor(stackedBar100Segment, borderColor, borderWidth); - updateSegmentGradient(stackedBar100Segment, - gradientBounds: stackedBar100Segment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stackedBar100Segment, + gradientBounds: stackedBar100Segment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } } @@ -283,7 +304,9 @@ class StackedBar100Segment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -292,8 +315,11 @@ class StackedBar100Segment extends ChartSegment { } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -354,18 +380,22 @@ class StackedBar100Segment extends ChartSegment { final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -385,8 +415,10 @@ class StackedBar100Segment extends ChartSegment { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, top), series.pointToPixelY(x, top)), + position: Offset( + series.pointToPixelX(x, top), + series.pointToPixelY(x, top), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -419,8 +451,11 @@ class StackedBar100Segment extends ChartSegment { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar_series.dart index c992016bc..505d72460 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_bar_series.dart @@ -137,7 +137,9 @@ class StackedBarSeries extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedBarSeriesRenderer renderObject) { + BuildContext context, + StackedBarSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..spacing = spacing @@ -171,11 +173,12 @@ class StackedBarSeriesRenderer extends StackedSeriesRenderer @override ChartDataLabelAlignment effectiveDataLabelAlignment( - ChartDataLabelAlignment alignment, - ChartDataPointType position, - ChartElementParentData? previous, - ChartElementParentData current, - ChartElementParentData? next) { + ChartDataLabelAlignment alignment, + ChartDataPointType position, + ChartElementParentData? previous, + ChartElementParentData current, + ChartElementParentData? next, + ) { return alignment == ChartDataLabelAlignment.auto || alignment == ChartDataLabelAlignment.outer ? ChartDataLabelAlignment.top @@ -183,8 +186,11 @@ class StackedBarSeriesRenderer extends StackedSeriesRenderer } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { final num x = current.x! + (sbsInfo.maximum + sbsInfo.minimum) / 2; final num stackValue = yValues[current.dataPointIndex]; double y = current.y!.toDouble(); @@ -194,11 +200,21 @@ class StackedBarSeriesRenderer extends StackedSeriesRenderer y = (y + (y - stackValue)) / 2; } return _calculateDataLabelPosition( - x, y, alignment, size, current.y!.isNegative); + x, + y, + alignment, + size, + current.y!.isNegative, + ); } - Offset _calculateDataLabelPosition(num x, num y, - ChartDataLabelAlignment alignment, Size size, bool isNegative) { + Offset _calculateDataLabelPosition( + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + bool isNegative, + ) { final EdgeInsets margin = dataLabelSettings.margin; double translationX = 0.0; double translationY = 0.0; @@ -207,29 +223,33 @@ class StackedBarSeriesRenderer extends StackedSeriesRenderer case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.width + margin.horizontal); + translationX = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? -(dataLabelPadding + size.height + margin.vertical) - : dataLabelPadding; + translationY = + isNegative + ? -(dataLabelPadding + size.height + margin.vertical) + : dataLabelPadding; } return translateTransform(x, y, translationX, translationY); @@ -268,12 +288,18 @@ class StackedBarSeriesRenderer extends StackedSeriesRenderer final StackedBarSegment stackedBarSegment = segment as StackedBarSegment; updateSegmentTrackerStyle( - stackedBarSegment, trackColor, trackBorderColor, trackBorderWidth); + stackedBarSegment, + trackColor, + trackBorderColor, + trackBorderWidth, + ); updateSegmentColor(stackedBarSegment, borderColor, borderWidth); - updateSegmentGradient(stackedBarSegment, - gradientBounds: stackedBarSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stackedBarSegment, + gradientBounds: stackedBarSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } @override @@ -294,7 +320,9 @@ class StackedBarSegment extends ChartSegment with BarSeriesTrackerMixin { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -303,8 +331,11 @@ class StackedBarSegment extends ChartSegment with BarSeriesTrackerMixin { } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -341,8 +372,14 @@ class StackedBarSegment extends ChartSegment with BarSeriesTrackerMixin { ); if (series.isTrackVisible) { - calculateTrackerBounds(left, right, borderRadius, series.trackPadding, - series.trackBorderWidth, series); + calculateTrackerBounds( + left, + right, + borderRadius, + series.trackPadding, + series.trackBorderWidth, + series, + ); } } @@ -370,18 +407,22 @@ class StackedBarSegment extends ChartSegment with BarSeriesTrackerMixin { final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -401,8 +442,10 @@ class StackedBarSegment extends ChartSegment with BarSeriesTrackerMixin { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, top), series.pointToPixelY(x, top)), + position: Offset( + series.pointToPixelX(x, top), + series.pointToPixelY(x, top), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -440,8 +483,11 @@ class StackedBarSegment extends ChartSegment with BarSeriesTrackerMixin { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column100_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column100_series.dart index e22a478d9..7db82166f 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column100_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column100_series.dart @@ -120,9 +120,11 @@ class StackedColumn100Series extends StackedSeriesBase { @override StackedColumn100SeriesRenderer createRenderObject( - BuildContext context) { - final StackedColumn100SeriesRenderer renderer = super - .createRenderObject(context) as StackedColumn100SeriesRenderer; + BuildContext context, + ) { + final StackedColumn100SeriesRenderer renderer = + super.createRenderObject(context) + as StackedColumn100SeriesRenderer; renderer ..spacing = spacing ..width = width @@ -134,7 +136,9 @@ class StackedColumn100Series extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedColumn100SeriesRenderer renderObject) { + BuildContext context, + StackedColumn100SeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..spacing = spacing @@ -171,8 +175,11 @@ class StackedColumn100SeriesRenderer extends StackedSeriesRenderer } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { final num x = current.x! + (sbsInfo.maximum + sbsInfo.minimum) / 2; final double bottomValue = bottomValues[current.dataPointIndex].toDouble(); double y = current.y!.toDouble(); @@ -182,11 +189,21 @@ class StackedColumn100SeriesRenderer extends StackedSeriesRenderer y = (y + bottomValue) / 2; } return _calculateDataLabelPosition( - x, y, alignment, size, current.y!.isNegative); + x, + y, + alignment, + size, + current.y!.isNegative, + ); } - Offset _calculateDataLabelPosition(num x, num y, - ChartDataLabelAlignment alignment, Size size, bool isNegative) { + Offset _calculateDataLabelPosition( + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + bool isNegative, + ) { final EdgeInsets margin = dataLabelSettings.margin; double translationX = 0.0; double translationY = 0.0; @@ -195,29 +212,33 @@ class StackedColumn100SeriesRenderer extends StackedSeriesRenderer case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.width + margin.horizontal); + translationX = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? -(dataLabelPadding + size.height + margin.vertical) - : dataLabelPadding; + translationY = + isNegative + ? -(dataLabelPadding + size.height + margin.vertical) + : dataLabelPadding; } return translateTransform(x, y, translationX, translationY); @@ -261,10 +282,12 @@ class StackedColumn100SeriesRenderer extends StackedSeriesRenderer final StackedColumn100Segment stackedColumn100Segment = segment as StackedColumn100Segment; updateSegmentColor(stackedColumn100Segment, borderColor, borderWidth); - updateSegmentGradient(stackedColumn100Segment, - gradientBounds: stackedColumn100Segment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stackedColumn100Segment, + gradientBounds: stackedColumn100Segment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } } @@ -282,7 +305,9 @@ class StackedColumn100Segment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -291,8 +316,11 @@ class StackedColumn100Segment extends ChartSegment { } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -353,18 +381,22 @@ class StackedColumn100Segment extends ChartSegment { final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -384,8 +416,10 @@ class StackedColumn100Segment extends ChartSegment { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, top), series.pointToPixelY(x, top)), + position: Offset( + series.pointToPixelX(x, top), + series.pointToPixelY(x, top), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -418,8 +452,11 @@ class StackedColumn100Segment extends ChartSegment { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column_series.dart index a3dc61816..a745e18f0 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_column_series.dart @@ -136,7 +136,9 @@ class StackedColumnSeries extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedColumnSeriesRenderer renderObject) { + BuildContext context, + StackedColumnSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..spacing = spacing @@ -170,11 +172,12 @@ class StackedColumnSeriesRenderer extends StackedSeriesRenderer @override ChartDataLabelAlignment effectiveDataLabelAlignment( - ChartDataLabelAlignment alignment, - ChartDataPointType position, - ChartElementParentData? previous, - ChartElementParentData current, - ChartElementParentData? next) { + ChartDataLabelAlignment alignment, + ChartDataPointType position, + ChartElementParentData? previous, + ChartElementParentData current, + ChartElementParentData? next, + ) { return alignment == ChartDataLabelAlignment.auto || alignment == ChartDataLabelAlignment.outer ? ChartDataLabelAlignment.top @@ -182,8 +185,11 @@ class StackedColumnSeriesRenderer extends StackedSeriesRenderer } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { final num x = current.x! + (sbsInfo.maximum + sbsInfo.minimum) / 2; final num stackValue = yValues[current.dataPointIndex]; double y = current.y!.toDouble(); @@ -193,11 +199,21 @@ class StackedColumnSeriesRenderer extends StackedSeriesRenderer y = (y + (y - stackValue)) / 2; } return _calculateDataLabelPosition( - x, y, alignment, size, current.y!.isNegative); + x, + y, + alignment, + size, + current.y!.isNegative, + ); } - Offset _calculateDataLabelPosition(num x, num y, - ChartDataLabelAlignment alignment, Size size, bool isNegative) { + Offset _calculateDataLabelPosition( + num x, + num y, + ChartDataLabelAlignment alignment, + Size size, + bool isNegative, + ) { final EdgeInsets margin = dataLabelSettings.margin; double translationX = 0.0; double translationY = 0.0; @@ -206,29 +222,33 @@ class StackedColumnSeriesRenderer extends StackedSeriesRenderer case ChartDataLabelAlignment.outer: case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.width + margin.horizontal); + translationX = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? -(dataLabelPadding + size.height + margin.vertical) - : dataLabelPadding; + translationY = + isNegative + ? -(dataLabelPadding + size.height + margin.vertical) + : dataLabelPadding; } return translateTransform(x, y, translationX, translationY); @@ -271,12 +291,18 @@ class StackedColumnSeriesRenderer extends StackedSeriesRenderer final StackedColumnSegment stackedColumnSegment = segment as StackedColumnSegment; updateSegmentTrackerStyle( - stackedColumnSegment, trackColor, trackBorderColor, trackBorderWidth); + stackedColumnSegment, + trackColor, + trackBorderColor, + trackBorderWidth, + ); updateSegmentColor(stackedColumnSegment, borderColor, borderWidth); - updateSegmentGradient(stackedColumnSegment, - gradientBounds: stackedColumnSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stackedColumnSegment, + gradientBounds: stackedColumnSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); } } @@ -295,7 +321,9 @@ class StackedColumnSegment extends ChartSegment @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -304,8 +332,11 @@ class StackedColumnSegment extends ChartSegment } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -342,8 +373,14 @@ class StackedColumnSegment extends ChartSegment ); if (series.isTrackVisible) { - calculateTrackerBounds(left, right, borderRadius, series.trackPadding, - series.trackBorderWidth, series); + calculateTrackerBounds( + left, + right, + borderRadius, + series.trackPadding, + series.trackBorderWidth, + series, + ); } } @@ -371,18 +408,22 @@ class StackedColumnSegment extends ChartSegment final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -402,8 +443,10 @@ class StackedColumnSegment extends ChartSegment if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, top), series.pointToPixelY(x, top)), + position: Offset( + series.pointToPixelX(x, top), + series.pointToPixelY(x, top), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -441,8 +484,11 @@ class StackedColumnSegment extends ChartSegment return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line100_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line100_series.dart index 7bb0d5b81..8c893abf2 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line100_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line100_series.dart @@ -92,7 +92,9 @@ class StackedLine100Series extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedLine100SeriesRenderer renderObject) { + BuildContext context, + StackedLine100SeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.groupName = groupName; } @@ -116,7 +118,11 @@ class StackedLine100SeriesRenderer extends StackedSeriesRenderer num y2 = double.nan; final int nextIndex = nextIndexConsideringEmptyPointMode( - index, emptyPointSettings.mode, topValues, dataCount); + index, + emptyPointSettings.mode, + topValues, + dataCount, + ); if (nextIndex != -1) { x2 = xValues[nextIndex]; y2 = topValues[nextIndex]; @@ -151,8 +157,12 @@ class StackedLine100SeriesRenderer extends StackedSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -171,7 +181,9 @@ class StackedLine100Segment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -232,8 +244,11 @@ class StackedLine100Segment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -268,9 +283,10 @@ class StackedLine100Segment extends ChartSegment { final int nearestPointIndex = position == null ? 0 : _nearestPointIndex(points, position); if (nearestPointIndex != -1) { - pointIndex ??= (position == null || nearestPointIndex == 0 - ? currentSegmentIndex - : currentSegmentIndex + 1); + pointIndex ??= + (position == null || nearestPointIndex == 0 + ? currentSegmentIndex + : currentSegmentIndex + 1); CartesianChartPoint chartPoint = _chartPoint(pointIndex); List markerColors = [fillPaint.color]; if (chartPoint.y != null && chartPoint.y!.isNaN) { @@ -283,14 +299,17 @@ class StackedLine100Segment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = points[nearestPointIndex]; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -348,8 +367,13 @@ class StackedLine100Segment extends ChartSegment { final Paint paint = getStrokePaint(); if (paint.color != Colors.transparent && paint.strokeWidth > 0) { - drawDashes(canvas, series.dashArray, paint, - start: points[0], end: points[1]); + drawDashes( + canvas, + series.dashArray, + paint, + start: points[0], + end: points[1], + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line_series.dart index f7ea16585..3f9cbd406 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stacked_line_series.dart @@ -93,7 +93,9 @@ class StackedLineSeries extends StackedSeriesBase { @override void updateRenderObject( - BuildContext context, StackedLineSeriesRenderer renderObject) { + BuildContext context, + StackedLineSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject.groupName = groupName; } @@ -117,7 +119,11 @@ class StackedLineSeriesRenderer extends StackedSeriesRenderer num y2 = double.nan; final int nextIndex = nextIndexConsideringEmptyPointMode( - index, emptyPointSettings.mode, topValues, dataCount); + index, + emptyPointSettings.mode, + topValues, + dataCount, + ); if (nextIndex != -1) { x2 = xValues[nextIndex]; y2 = topValues[nextIndex]; @@ -152,8 +158,12 @@ class StackedLineSeriesRenderer extends StackedSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -172,7 +182,9 @@ class StackedLineSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -234,8 +246,11 @@ class StackedLineSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -270,9 +285,10 @@ class StackedLineSegment extends ChartSegment { final int nearestPointIndex = position == null ? 0 : _nearestPointIndex(points, position); if (nearestPointIndex != -1) { - pointIndex ??= (position == null || nearestPointIndex == 0 - ? currentSegmentIndex - : currentSegmentIndex + 1); + pointIndex ??= + (position == null || nearestPointIndex == 0 + ? currentSegmentIndex + : currentSegmentIndex + 1); CartesianChartPoint chartPoint = _chartPoint(pointIndex); List markerColors = [fillPaint.color]; if (chartPoint.y != null && chartPoint.y!.isNaN) { @@ -285,14 +301,17 @@ class StackedLineSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = points[nearestPointIndex]; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -350,8 +369,13 @@ class StackedLineSegment extends ChartSegment { final Paint paint = getStrokePaint(); if (paint.color != Colors.transparent && paint.strokeWidth > 0) { - drawDashes(canvas, series.dashArray, paint, - start: points[0], end: points[1]); + drawDashes( + canvas, + series.dashArray, + paint, + start: points[0], + end: points[1], + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/step_area_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/step_area_series.dart index d0e09ac2e..5f4a51da5 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/step_area_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/step_area_series.dart @@ -119,7 +119,9 @@ class StepAreaSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, StepAreaSeriesRenderer renderObject) { + BuildContext context, + StepAreaSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..borderDrawMode = borderDrawMode @@ -170,10 +172,12 @@ class StepAreaSeriesRenderer extends XyDataSeriesRenderer final StepAreaSegment stepAreaSegment = segment as StepAreaSegment; updateSegmentColor(stepAreaSegment, borderColor, borderWidth); - updateSegmentGradient(stepAreaSegment, - gradientBounds: stepAreaSegment._fillPath.getBounds(), - gradient: gradient, - borderGradient: borderGradient); + updateSegmentGradient( + stepAreaSegment, + gradientBounds: stepAreaSegment._fillPath.getBounds(), + gradient: gradient, + borderGradient: borderGradient, + ); } @override @@ -182,8 +186,12 @@ class StepAreaSeriesRenderer extends XyDataSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -211,7 +219,9 @@ class StepAreaSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _drawIndexes.clear(); @@ -231,26 +241,50 @@ class StepAreaSegment extends ChartSegment { final int newPointsLength = _highPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _bottom, + )!; } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _bottom, + )!; } _oldHighPoints.addAll(_highPoints.sublist(oldPointsLength)); _oldLowPoints.addAll(_lowPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - _oldHighPoints[i] = _oldHighPoints[i] - .lerp(_highPoints[i], segmentAnimationFactor, _bottom)!; - _oldLowPoints[i] = _oldLowPoints[i] - .lerp(_lowPoints[i], segmentAnimationFactor, _bottom)!; + _oldHighPoints[i] = + _oldHighPoints[i].lerp( + _highPoints[i], + segmentAnimationFactor, + _bottom, + )!; + _oldLowPoints[i] = + _oldLowPoints[i].lerp( + _lowPoints[i], + segmentAnimationFactor, + _bottom, + )!; } _oldHighPoints.removeRange(newPointsLength, oldPointsLength); _oldLowPoints.removeRange(newPointsLength, oldPointsLength); @@ -316,8 +350,10 @@ class StepAreaSegment extends ChartSegment { if (_highPoints.isEmpty) { return; } - final List lerpHighPoints = - _lerpPoints(_oldHighPoints, _highPoints); + final List lerpHighPoints = _lerpPoints( + _oldHighPoints, + _highPoints, + ); final List lerpLowPoints = _lerpPoints(_oldLowPoints, _lowPoints); _createFillPath(_fillPath, lerpHighPoints, lerpLowPoints); @@ -330,7 +366,10 @@ class StepAreaSegment extends ChartSegment { break; case BorderDrawMode.excludeBottom: _createExcludeBottomStrokePath( - _strokePath, lerpHighPoints, lerpLowPoints); + _strokePath, + lerpHighPoints, + lerpLowPoints, + ); break; } } @@ -341,19 +380,22 @@ class StepAreaSegment extends ChartSegment { final int newPointsLength = newPoints.length; if (oldPointsLength == newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, _bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, _bottom)!, + ); } } else if (oldPointsLength < newPointsLength) { for (int i = 0; i < oldPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, _bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, _bottom)!, + ); } lerpPoints.addAll(newPoints.sublist(oldPointsLength)); } else { for (int i = 0; i < newPointsLength; i++) { - lerpPoints - .add(oldPoints[i].lerp(newPoints[i], animationFactor, _bottom)!); + lerpPoints.add( + oldPoints[i].lerp(newPoints[i], animationFactor, _bottom)!, + ); } } @@ -361,7 +403,10 @@ class StepAreaSegment extends ChartSegment { } Path _createFillPath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -371,7 +416,10 @@ class StepAreaSegment extends ChartSegment { if (i == 0) { if (lowPoint.isNaN) { _createFillPath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -431,7 +479,10 @@ class StepAreaSegment extends ChartSegment { } Path _createExcludeBottomStrokePath( - Path source, List highPoints, List lowPoints) { + Path source, + List highPoints, + List lowPoints, + ) { Path? path; final int length = highPoints.length; final int lastIndex = length - 1; @@ -441,7 +492,10 @@ class StepAreaSegment extends ChartSegment { if (i == 0) { if (lowPoint.isNaN) { _createExcludeBottomStrokePath( - source, highPoints.sublist(i + 1), lowPoints.sublist(i + 1)); + source, + highPoints.sublist(i + 1), + lowPoints.sublist(i + 1), + ); break; } else { path = Path(); @@ -453,7 +507,10 @@ class StepAreaSegment extends ChartSegment { final Offset lowPoint = lowPoints[i - 1]; path!.lineTo(lowPoint.dx, lowPoint.dy); _createExcludeBottomStrokePath( - source, highPoints.sublist(i), lowPoints.sublist(i)); + source, + highPoints.sublist(i), + lowPoints.sublist(i), + ); break; } else { path!.lineTo(highPoint.dx, highPoints[i - 1].dy); @@ -477,8 +534,11 @@ class StepAreaSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -518,14 +578,17 @@ class StepAreaSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = Offset(dx, dy); return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/stepline_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/stepline_series.dart index 97534fea0..37f85389b 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/stepline_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/stepline_series.dart @@ -91,7 +91,11 @@ class StepLineSeriesRenderer extends XyDataSeriesRenderer num y2 = double.nan; final int nextIndex = nextIndexConsideringEmptyPointMode( - index, emptyPointSettings.mode, yValues, dataCount); + index, + emptyPointSettings.mode, + yValues, + dataCount, + ); if (nextIndex != -1) { x2 = xValues[nextIndex]; y2 = yValues[nextIndex]; @@ -131,8 +135,12 @@ class StepLineSeriesRenderer extends XyDataSeriesRenderer @override void onPaint(PaintingContext context, Offset offset) { context.canvas.save(); - final Rect clip = clipRect(paintBounds, animationFactor, - isInversed: xAxis!.isInversed, isTransposed: isTransposed); + final Rect clip = clipRect( + paintBounds, + animationFactor, + isInversed: xAxis!.isInversed, + isTransposed: isTransposed, + ); context.canvas.clipRect(clip); paintSegments(context, offset); context.canvas.restore(); @@ -159,7 +167,9 @@ class StepLineSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldPoints.clear(); @@ -226,8 +236,11 @@ class StepLineSegment extends ChartSegment { final MarkerSettings marker = series.markerSettings; final int length = points.length; for (int i = 0; i < length; i++) { - if (tooltipTouchBounds(points[i], marker.width, marker.height) - .contains(position)) { + if (tooltipTouchBounds( + points[i], + marker.width, + marker.height, + ).contains(position)) { return true; } } @@ -262,9 +275,10 @@ class StepLineSegment extends ChartSegment { final int nearestPointIndex = position == null ? 0 : _nearestPointIndex(linePoints, position); if (nearestPointIndex != -1) { - pointIndex ??= (position == null || nearestPointIndex == 0 - ? currentSegmentIndex - : currentSegmentIndex + 1); + pointIndex ??= + (position == null || nearestPointIndex == 0 + ? currentSegmentIndex + : currentSegmentIndex + 1); CartesianChartPoint chartPoint = _chartPoint(pointIndex); List markerColors = [fillPaint.color]; if (chartPoint.y != null && chartPoint.y!.isNaN) { @@ -277,14 +291,17 @@ class StepLineSegment extends ChartSegment { series.markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = linePoints[nearestPointIndex]; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/series/waterfall_series.dart b/packages/syncfusion_flutter_charts/lib/src/charts/series/waterfall_series.dart index f6d6ba59a..2abee1b9a 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/series/waterfall_series.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/series/waterfall_series.dart @@ -321,7 +321,9 @@ class WaterfallSeries extends XyDataSeries { @override void updateRenderObject( - BuildContext context, WaterfallSeriesRenderer renderObject) { + BuildContext context, + WaterfallSeriesRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..negativePointsColor = negativePointsColor @@ -482,7 +484,13 @@ class WaterfallSeriesRenderer extends XyDataSeriesRenderer List>? fLists, ]) { super.populateDataSource( - yPaths, chaoticYLists, yLists, fPaths, chaoticFLists, fLists); + yPaths, + chaoticYLists, + yLists, + fPaths, + chaoticFLists, + fLists, + ); _calculateWaterfallValues(); populateChartPoints(); } @@ -552,9 +560,10 @@ class WaterfallSeriesRenderer extends XyDataSeriesRenderer intermediateSumPredicate != null ? _intermediateSumPredicateMapper : _defaultSumPredicate; - final bool? Function(T data, int index) totalSum = totalSumPredicate != null - ? _totalSumPredicateMapper - : _defaultSumPredicate; + final bool? Function(T data, int index) totalSum = + totalSumPredicate != null + ? _totalSumPredicateMapper + : _defaultSumPredicate; for (int i = 0; i < dataCount; i++) { final T current = dataSource![i]; @@ -652,22 +661,32 @@ class WaterfallSeriesRenderer extends XyDataSeriesRenderer color = negativePointsColor; } - updateSegmentColor(waterfallSegment, borderColor, borderWidth, - fillColor: color); - updateSegmentGradient(waterfallSegment, - gradientBounds: waterfallSegment.segmentRect?.outerRect, - gradient: gradient, - borderGradient: borderGradient); + updateSegmentColor( + waterfallSegment, + borderColor, + borderWidth, + fillColor: color, + ); + updateSegmentGradient( + waterfallSegment, + gradientBounds: waterfallSegment.segmentRect?.outerRect, + gradient: gradient, + borderGradient: borderGradient, + ); segment.connectorLineStrokePaint - ..color = (connectorLineSettings.color ?? - chartThemeData!.waterfallConnectorLineColor)! + ..color = + (connectorLineSettings.color ?? + chartThemeData!.waterfallConnectorLineColor)! ..strokeWidth = connectorLineSettings.width; } @override - Offset dataLabelPosition(ChartElementParentData current, - ChartDataLabelAlignment alignment, Size size) { + Offset dataLabelPosition( + ChartElementParentData current, + ChartDataLabelAlignment alignment, + Size size, + ) { final num x = current.x! + (sbsInfo.maximum + sbsInfo.minimum) / 2; num y = current.y!; final int dataPointIndex = current.dataPointIndex; @@ -686,43 +705,49 @@ class WaterfallSeriesRenderer extends XyDataSeriesRenderer case ChartDataLabelAlignment.auto: case ChartDataLabelAlignment.outer: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? 0 - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? 0 + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.bottom: if (isTransposed) { - translationX = isNegative - ? -(dataLabelPadding + size.width + margin.horizontal) - : dataLabelPadding; + translationX = + isNegative + ? -(dataLabelPadding + size.width + margin.horizontal) + : dataLabelPadding; translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? dataLabelPadding - : -(dataLabelPadding + size.height + margin.vertical); + translationY = + isNegative + ? dataLabelPadding + : -(dataLabelPadding + size.height + margin.vertical); } return translateTransform(x, y, translationX, translationY); case ChartDataLabelAlignment.top: if (isTransposed) { - translationX = isNegative - ? 0 - : -(dataLabelPadding + size.width + margin.horizontal); + translationX = + isNegative + ? 0 + : -(dataLabelPadding + size.width + margin.horizontal); translationY = -margin.top; } else { translationX = -margin.left; - translationY = isNegative - ? -(dataLabelPadding + size.height + margin.vertical) - : dataLabelPadding; + translationY = + isNegative + ? -(dataLabelPadding + size.height + margin.vertical) + : dataLabelPadding; } return translateTransform(x, y, translationX, translationY); @@ -756,10 +781,11 @@ class WaterfallSeriesRenderer extends XyDataSeriesRenderer /// Gets the path and color from the `series`. class WaterfallSegment extends ChartSegment { late WaterfallSeriesRenderer series; - final Paint connectorLineStrokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke - ..strokeCap = StrokeCap.round; + final Paint connectorLineStrokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round; late num x; late num top; @@ -773,7 +799,9 @@ class WaterfallSegment extends ChartSegment { @override void copyOldSegmentValues( - double seriesAnimationFactor, double segmentAnimationFactor) { + double seriesAnimationFactor, + double segmentAnimationFactor, + ) { if (series.animationType == AnimationType.loading) { points.clear(); _oldSegmentRect = null; @@ -782,8 +810,11 @@ class WaterfallSegment extends ChartSegment { } if (series.animationDuration > 0) { - _oldSegmentRect = - RRect.lerp(_oldSegmentRect, segmentRect, segmentAnimationFactor); + _oldSegmentRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + segmentAnimationFactor, + ); } else { _oldSegmentRect = segmentRect; } @@ -826,10 +857,12 @@ class WaterfallSegment extends ChartSegment { series.segments[currentSegmentIndex - 1] as WaterfallSegment; final num oldSegmentRight = oldSegment.x + sbsMaximum; final num oldSegmentTop = oldSegment.top; - points.add(Offset( - transformX(oldSegmentRight, oldSegmentTop), - transformY(oldSegmentRight, oldSegmentTop), - )); + points.add( + Offset( + transformX(oldSegmentRight, oldSegmentTop), + transformY(oldSegmentRight, oldSegmentTop), + ), + ); if (isTotalSum || isIntermediateSum) { points.add(Offset(x1, y1)); @@ -864,18 +897,22 @@ class WaterfallSegment extends ChartSegment { final ChartMarker marker = series.markerAt(pointIndex); final double markerHeight = series.markerSettings.isVisible ? marker.height / 2 : 0; - final Offset preferredPos = tooltipPosition == TooltipPosition.pointer - ? position ?? segmentRect!.outerRect.topCenter - : segmentRect!.outerRect.topCenter; + final Offset preferredPos = + tooltipPosition == TooltipPosition.pointer + ? position ?? segmentRect!.outerRect.topCenter + : segmentRect!.outerRect.topCenter; return ChartTooltipInfo( - primaryPosition: - series.localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - series.localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: series.localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: series.localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series.tooltipText(chartPoint), - header: series.parent!.tooltipBehavior!.shared - ? series.tooltipHeaderText(chartPoint) - : series.name, + header: + series.parent!.tooltipBehavior!.shared + ? series.tooltipHeaderText(chartPoint) + : series.name, data: series.dataSource![pointIndex], point: chartPoint, series: series.widget, @@ -895,8 +932,10 @@ class WaterfallSegment extends ChartSegment { if (pointIndex != -1 && segmentRect != null) { final CartesianChartPoint chartPoint = _chartPoint(); return ChartTrackballInfo( - position: - Offset(series.pointToPixelX(x, top), series.pointToPixelY(x, top)), + position: Offset( + series.pointToPixelX(x, top), + series.pointToPixelY(x, top), + ), point: chartPoint, series: series, seriesIndex: series.index, @@ -931,8 +970,11 @@ class WaterfallSegment extends ChartSegment { return; } - final RRect? paintRRect = - RRect.lerp(_oldSegmentRect, segmentRect, animationFactor); + final RRect? paintRRect = RRect.lerp( + _oldSegmentRect, + segmentRect, + animationFactor, + ); if (paintRRect == null) { return; } diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/trendline/trendline.dart b/packages/syncfusion_flutter_charts/lib/src/charts/trendline/trendline.dart index 9235b1762..b7f0e51ee 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/trendline/trendline.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/trendline/trendline.dart @@ -499,17 +499,14 @@ class Trendline { legendIconType, markerSettings, polynomialOrder, - period + period, ]; return Object.hashAll(values); } } class TrendlineContainer extends StatefulWidget { - const TrendlineContainer({ - super.key, - required this.trendlines, - }); + const TrendlineContainer({super.key, required this.trendlines}); final List trendlines; @@ -521,33 +518,30 @@ class _TrendlineContainerState extends State { @override Widget build(BuildContext context) { return TrendlineStack( - children: List.generate( - widget.trendlines.length, - (int index) { - final Trendline trendline = widget.trendlines[index]; - return TrendlineWidget( - index: index, - isVisible: trendline.isVisible, - enableTooltip: trendline.enableTooltip, - name: trendline.name, - color: trendline.color, - dashArray: trendline.dashArray, - opacity: trendline.opacity, - width: trendline.width, - type: trendline.type, - valueField: trendline.valueField, - period: trendline.period, - intercept: trendline.intercept, - polynomialOrder: trendline.polynomialOrder, - backwardForecast: trendline.backwardForecast, - forwardForecast: trendline.forwardForecast, - isVisibleInLegend: trendline.isVisibleInLegend, - legendIconType: trendline.legendIconType, - markerSettings: trendline.markerSettings, - onRenderDetailsUpdate: trendline.onRenderDetailsUpdate, - ); - }, - ), + children: List.generate(widget.trendlines.length, (int index) { + final Trendline trendline = widget.trendlines[index]; + return TrendlineWidget( + index: index, + isVisible: trendline.isVisible, + enableTooltip: trendline.enableTooltip, + name: trendline.name, + color: trendline.color, + dashArray: trendline.dashArray, + opacity: trendline.opacity, + width: trendline.width, + type: trendline.type, + valueField: trendline.valueField, + period: trendline.period, + intercept: trendline.intercept, + polynomialOrder: trendline.polynomialOrder, + backwardForecast: trendline.backwardForecast, + forwardForecast: trendline.forwardForecast, + isVisibleInLegend: trendline.isVisibleInLegend, + legendIconType: trendline.legendIconType, + markerSettings: trendline.markerSettings, + onRenderDetailsUpdate: trendline.onRenderDetailsUpdate, + ); + }), ); } } @@ -566,8 +560,10 @@ class TrendlineParentData extends ContainerBoxParentData {} class RenderTrendlineStack extends RenderBox with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin { + RenderBoxContainerDefaultsMixin< + TrendlineRenderer, + TrendlineParentData + > { CartesianSeriesRenderer? renderer; bool get _isTooltipEnabled => @@ -600,7 +596,8 @@ class RenderTrendlineStack extends RenderBox void handlePointerHover(Offset localPosition) { TrendlineRenderer? child = lastChild; while (child != null) { - final bool hasTooltip = _isTooltipEnabled && + final bool hasTooltip = + _isTooltipEnabled && renderer!.parent!.tooltipBehavior!.activationMode == ActivationMode.singleTap; if (child.enableTooltip && hasTooltip) { @@ -613,7 +610,8 @@ class RenderTrendlineStack extends RenderBox void handleDoubleTap(Offset localPosition) { TrendlineRenderer? child = lastChild; while (child != null) { - final bool hasTooltip = _isTooltipEnabled && + final bool hasTooltip = + _isTooltipEnabled && renderer!.parent!.tooltipBehavior!.activationMode == ActivationMode.doubleTap; if (child.enableTooltip && hasTooltip) { @@ -626,7 +624,8 @@ class RenderTrendlineStack extends RenderBox void handleLongPress(Offset localPosition) { TrendlineRenderer? child = lastChild; while (child != null) { - final bool hasTooltip = _isTooltipEnabled && + final bool hasTooltip = + _isTooltipEnabled && renderer!.parent!.tooltipBehavior!.activationMode == ActivationMode.longPress; if (child.enableTooltip && hasTooltip) { @@ -683,14 +682,18 @@ class RenderTrendlineStack extends RenderBox return DoubleRange(minimum, maximum); } - List? buildLegendItems( - int seriesIndex, LegendItemProviderMixin provider) { - final List legendItems = []; + List? buildLegendItems( + int seriesIndex, + LegendItemProviderMixin provider, + ) { + final List legendItems = []; const int trendlineIndex = 0; TrendlineRenderer? child = firstChild; while (child != null) { - final List? items = - child.buildLegendItems(trendlineIndex, provider); + final List? items = child.buildLegendItems( + trendlineIndex, + provider, + ); if (items != null) { legendItems.addAll(items); } @@ -823,7 +826,9 @@ class TrendlineWidget extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, TrendlineRenderer renderObject) { + BuildContext context, + TrendlineRenderer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isVisible = isVisible @@ -852,7 +857,7 @@ class TrendlineWidget extends LeafRenderObjectWidget { class TrendlineRenderer extends RenderBox { TrendlineRenderer(); - ChartLegendItem? _legendItem; + CartesianLegendItem? _legendItem; int get index => _index; int _index = -1; @@ -1095,8 +1100,10 @@ class TrendlineRenderer extends RenderBox { for (final int segmentIndex in trendSegmentIndexes) { final ChartMarker marker = series!.markerAt(segmentIndex); if (tooltipTouchBounds( - _points[segmentIndex], marker.width, marker.height) - .contains(position)) { + _points[segmentIndex], + marker.width, + marker.height, + ).contains(position)) { return segmentIndex; } } @@ -1114,14 +1121,17 @@ class TrendlineRenderer extends RenderBox { markerSettings.isVisible ? marker.height / 2 : 0; final Offset preferredPos = _points[pointIndex]; return TrendlineTooltipInfo( - primaryPosition: - localToGlobal(preferredPos.translate(0, -markerHeight)), - secondaryPosition: - localToGlobal(preferredPos.translate(0, markerHeight)), + primaryPosition: localToGlobal( + preferredPos.translate(0, -markerHeight), + ), + secondaryPosition: localToGlobal( + preferredPos.translate(0, markerHeight), + ), text: series!.tooltipText(chartPoint), - header: series!.parent!.tooltipBehavior!.shared - ? series!.tooltipHeaderText(chartPoint) - : series!.name, + header: + series!.parent!.tooltipBehavior!.shared + ? series!.tooltipHeaderText(chartPoint) + : series!.name, data: series!.dataSource![pointIndex], point: chartPoint, series: series!.widget, @@ -1187,13 +1197,19 @@ class TrendlineRenderer extends RenderBox { } slopeIntercept = _computeSlopeInterceptValues( - seriesXValues, linearYValues, length, slopeIntercept); + seriesXValues, + linearYValues, + length, + slopeIntercept, + ); if (!slopeIntercept.slope!.isNaN && !slopeIntercept.intercept!.isNaN) { final double intercept = slopeIntercept.intercept!; final double slope = slopeIntercept.slope!; final double x1 = forecastValue(sortedXValues[0], -backwardForecast); - final double x2 = - forecastValue(sortedXValues[length - 1], forwardForecast); + final double x2 = forecastValue( + sortedXValues[length - 1], + forwardForecast, + ); final double y1 = slope * x1 + intercept; final double y2 = slope * x2 + intercept; @@ -1228,7 +1244,11 @@ class TrendlineRenderer extends RenderBox { } slopeIntercept = _computeSlopeInterceptValues( - sortedXValues, exponentialYValues, length, slopeIntercept); + sortedXValues, + exponentialYValues, + length, + slopeIntercept, + ); if (!slopeIntercept.slope!.isNaN && !slopeIntercept.intercept!.isNaN) { final double intercept = slopeIntercept.intercept!; @@ -1237,8 +1257,10 @@ class TrendlineRenderer extends RenderBox { final double x1 = forecastValue(sortedXValues[0], -backwardForecast); final double x2 = sortedXValues[midPoint - 1].toDouble(); - final double x3 = - forecastValue(sortedXValues[length - 1], forwardForecast); + final double x3 = forecastValue( + sortedXValues[length - 1], + forwardForecast, + ); double y1 = intercept * exp(slope * x1); double y2 = intercept * exp(slope * x2); double y3 = intercept * exp(slope * x3); @@ -1287,7 +1309,11 @@ class TrendlineRenderer extends RenderBox { } slopeIntercept = _computeSlopeInterceptValues( - powerXValues, powerYValues, length, slopeIntercept); + powerXValues, + powerYValues, + length, + slopeIntercept, + ); if (!slopeIntercept.slope!.isNaN && !slopeIntercept.intercept!.isNaN) { final double intercept = slopeIntercept.intercept!; final double slope = slopeIntercept.slope!; @@ -1298,8 +1324,10 @@ class TrendlineRenderer extends RenderBox { x1 = x1 > -1 ? x1 : 0; } final double x2 = sortedXValues[midPoint - 1].toDouble(); - final double x3 = - forecastValue(sortedXValues[length - 1], forwardForecast); + final double x3 = forecastValue( + sortedXValues[length - 1], + forwardForecast, + ); double y1 = x1 == 0 ? 0 : intercept * pow(x1, slope); double y2 = intercept * pow(x2, slope); double y3 = intercept * pow(x3, slope); @@ -1349,7 +1377,11 @@ class TrendlineRenderer extends RenderBox { } slopeIntercept = _computeSlopeInterceptValues( - logXValues, logYValues, length, slopeIntercept); + logXValues, + logYValues, + length, + slopeIntercept, + ); if (!slopeIntercept.slope!.isNaN && !slopeIntercept.intercept!.isNaN) { final double intercept = slopeIntercept.intercept!; final double slope = slopeIntercept.slope!; @@ -1357,8 +1389,10 @@ class TrendlineRenderer extends RenderBox { final double x1 = forecastValue(sortedXValues[0], -backwardForecast); final double x2 = sortedXValues[midPoint - 1].toDouble(); - final double x3 = - forecastValue(sortedXValues[length - 1], forwardForecast); + final double x3 = forecastValue( + sortedXValues[length - 1], + forwardForecast, + ); final double y1 = intercept + (slope * (log(x1).isFinite ? log(x1) : x1)); final double y2 = intercept + (slope * (log(x2).isFinite ? log(x2) : x2)); final double y3 = intercept + (slope * (log(x3).isFinite ? log(x3) : x3)); @@ -1379,7 +1413,9 @@ class TrendlineRenderer extends RenderBox { } void _calculateMovingAveragePoints( - List sortedXValues, List seriesYValues) { + List sortedXValues, + List seriesYValues, + ) { final int xLength = sortedXValues.length; final int yLength = seriesYValues.length; final int trendPeriod = period; @@ -1432,16 +1468,23 @@ class TrendlineRenderer extends RenderBox { } } - final List> matrix = - _computeMatrix(sortedXValues, trendPolynomialOrder); + final List> matrix = _computeMatrix( + sortedXValues, + trendPolynomialOrder, + ); // The trendline will not be generated if there is just one data point or // if the x and y values are the same. For example (1,1), (1,1). // So, the line was commented and now marker alone will be rendered // in this case. // _polynomialSlopes = null; _gaussJordanElimination(matrix, polynomialSlopes); - _computePoints(sortedXValues, seriesYValues, length, polynomialSlopes, - polynomialForeCastValue); + _computePoints( + sortedXValues, + seriesYValues, + length, + polynomialSlopes, + polynomialForeCastValue, + ); List? polynomialSlopeValues; if (onRenderDetailsUpdate != null) { @@ -1459,8 +1502,10 @@ class TrendlineRenderer extends RenderBox { slopeValues.add(slopeValue(k, sortedXValues[k])); } - final List> matrix = - _computeMatrix(slopeValues, trendPolynomialOrder); + final List> matrix = _computeMatrix( + slopeValues, + trendPolynomialOrder, + ); // To find the prompt polynomial slopes for the trendline equation, // gaussJordanElimination method is used here. _gaussJordanElimination(matrix, polynomialSlopeValues); @@ -1471,11 +1516,14 @@ class TrendlineRenderer extends RenderBox { List> _computeMatrix(List xValues, int polynomialOrder) { final int length = xValues.length; - final List numArray = - List.filled(2 * polynomialOrder + 1, 0); + final List numArray = List.filled( + 2 * polynomialOrder + 1, + 0, + ); final List> matrix = List>.generate( - polynomialOrder + 1, - (int _) => List.filled(polynomialOrder + 1, 0)); + polynomialOrder + 1, + (int _) => List.filled(polynomialOrder + 1, 0), + ); for (int i = 0; i <= polynomialOrder; i++) { matrix[i] = List.filled(polynomialOrder + 1, 0); } @@ -1507,10 +1555,14 @@ class TrendlineRenderer extends RenderBox { ) { final List polynomialSlopesList = polynomialSlopes!; final int polynomialSlopesLength = polynomialSlopesList.length; - final double trendBackwardForecast = - polynomialForeCastValue(backwardForecast, false); - final double trendForwardForecast = - polynomialForeCastValue(forwardForecast, true); + final double trendBackwardForecast = polynomialForeCastValue( + backwardForecast, + false, + ); + final double trendForwardForecast = polynomialForeCastValue( + forwardForecast, + true, + ); num xMin = double.infinity; num xMax = double.negativeInfinity; @@ -1555,7 +1607,9 @@ class TrendlineRenderer extends RenderBox { } bool _gaussJordanElimination( - List> matrix, List polynomialSlopes) { + List> matrix, + List polynomialSlopes, + ) { final int length = matrix.length; final List list1 = List.filled(length, 0); final List list2 = List.filled(length, 0); @@ -1683,7 +1737,8 @@ class TrendlineRenderer extends RenderBox { break; } } else { - slope = ((length * xyAvg) - (xAvg * yAvg)) / + slope = + ((length * xyAvg) - (xAvg * yAvg)) / ((length * xxAvg) - (xAvg * xAvg)); trendIntercept = @@ -1715,14 +1770,24 @@ class TrendlineRenderer extends RenderBox { final DateTimeIntervalType visibleIntervalType = _visibleIntervalType(); switch (visibleIntervalType) { case DateTimeIntervalType.years: - return DateTime(date.year + effectiveInterval, date.month, date.day, - date.hour, date.minute, date.second) - .millisecondsSinceEpoch; + return DateTime( + date.year + effectiveInterval, + date.month, + date.day, + date.hour, + date.minute, + date.second, + ).millisecondsSinceEpoch; case DateTimeIntervalType.months: - return DateTime(date.year, date.month + effectiveInterval, date.day, - date.hour, date.minute, date.second) - .millisecondsSinceEpoch; + return DateTime( + date.year, + date.month + effectiveInterval, + date.day, + date.hour, + date.minute, + date.second, + ).millisecondsSinceEpoch; case DateTimeIntervalType.days: return date @@ -1890,13 +1955,29 @@ class TrendlineRenderer extends RenderBox { final int length = xValues.length; List yCoefficient = List.filled(length, 0); yCoefficient = _computeNaturalSpline( - xValues, yValues, yCoefficient, xValues.length, SplineType.natural); - return _controlPoints(xValues, yValues, yCoefficient[index]!.toDouble(), - yCoefficient[index + 1]!.toDouble(), index, controlPoints); + xValues, + yValues, + yCoefficient, + xValues.length, + SplineType.natural, + ); + return _controlPoints( + xValues, + yValues, + yCoefficient[index]!.toDouble(), + yCoefficient[index + 1]!.toDouble(), + index, + controlPoints, + ); } - List _computeNaturalSpline(List xValues, List yValues, - List yCoefficient, int length, SplineType splineType) { + List _computeNaturalSpline( + List xValues, + List yValues, + List yCoefficient, + int length, + SplineType splineType, + ) { const double a = 6; num d1, d2, d3, dy1, dy2, p; @@ -1991,10 +2072,12 @@ class TrendlineRenderer extends RenderBox { final num dx2 = x + (2 * nextX); final num dy1 = (2 * y) + nextY; final num dy2 = y + (2 * nextY); - final double y1 = oneThird * + final double y1 = + oneThird * (dy1 - (oneThird * deltaX2 * (yCoefficient + (0.5 * nextYCoefficient)))); - final double y2 = oneThird * + final double y2 = + oneThird * (dy2 - (oneThird * deltaX2 * ((0.5 * yCoefficient) + nextYCoefficient))); values[0] = dx1 * oneThird; @@ -2034,29 +2117,37 @@ class TrendlineRenderer extends RenderBox { switch (type) { case TrendlineType.linear: for (int k = 0; k < yLength; k++) { - sumOfSquareDueToRegression += - pow(((slope![0] * xValue[k]) + intercept!) - yMean, power); + sumOfSquareDueToRegression += pow( + ((slope![0] * xValue[k]) + intercept!) - yMean, + power, + ); } break; case TrendlineType.exponential: for (int k = 0; k < yLength; k++) { - sumOfSquareDueToRegression += - pow((intercept! * exp(slope![0] * xValue[k])) - yMean, power); + sumOfSquareDueToRegression += pow( + (intercept! * exp(slope![0] * xValue[k])) - yMean, + power, + ); } break; case TrendlineType.power: for (int k = 0; k < yLength; k++) { - sumOfSquareDueToRegression += - pow((intercept! * pow(xValue[k], slope![0])) - yMean, power); + sumOfSquareDueToRegression += pow( + (intercept! * pow(xValue[k], slope![0])) - yMean, + power, + ); } break; case TrendlineType.logarithmic: for (int k = 0; k < yLength; k++) { - sumOfSquareDueToRegression += - pow(((slope![0] * log(xValue[k])) + intercept!) - yMean, power); + sumOfSquareDueToRegression += pow( + ((slope![0] * log(xValue[k])) + intercept!) - yMean, + power, + ); } break; @@ -2091,14 +2182,16 @@ class TrendlineRenderer extends RenderBox { } num _slopeDateTimeXValue(int index, num value) { - final DateTime dateTime = - DateTime.fromMillisecondsSinceEpoch(value.toInt()); + final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch( + value.toInt(), + ); return dateTime.difference(DateTime(1900)).inDays; } double _forecastDateTimeValue(num value, double forecast) { - final DateTime dateTime = - DateTime.fromMillisecondsSinceEpoch(value.toInt()); + final DateTime dateTime = DateTime.fromMillisecondsSinceEpoch( + value.toInt(), + ); return _computeDateTimeForeCast(dateTime, forecast).toDouble(); } @@ -2106,8 +2199,10 @@ class TrendlineRenderer extends RenderBox { return forecast; } - double _polynomialForeCastDateTimeAxisValue(num forecast, - [bool? isForeCast]) { + double _polynomialForeCastDateTimeAxisValue( + num forecast, [ + bool? isForeCast, + ]) { return _computeDateTimeDuration(isForeCast!).toDouble(); } @@ -2128,7 +2223,8 @@ class TrendlineRenderer extends RenderBox { } void populateDataSource(List seriesXValues, List seriesYValues) { - final bool trendIsVisible = !isToggled && + final bool trendIsVisible = + !isToggled && (type == TrendlineType.polynomial ? (polynomialOrder >= 2 && polynomialOrder <= 6) : !(type == TrendlineType.movingAverage) || @@ -2183,59 +2279,68 @@ class TrendlineRenderer extends RenderBox { switch (type) { case TrendlineType.linear: _calculateLinearPoints( - seriesXValues, - seriesYValues, - sortedXValues, - _slopeIntercept, - slopeInterceptData, - slopeValue, - forecastValue, - slopeInterceptXValues, - yValues); + seriesXValues, + seriesYValues, + sortedXValues, + _slopeIntercept, + slopeInterceptData, + slopeValue, + forecastValue, + slopeInterceptXValues, + yValues, + ); break; case TrendlineType.exponential: _calculateExponentialPoints( - seriesXValues, - seriesYValues, - sortedXValues, - _slopeIntercept, - slopeInterceptData, - slopeValue, - forecastValue, - slopeInterceptXValues, - yValues); + seriesXValues, + seriesYValues, + sortedXValues, + _slopeIntercept, + slopeInterceptData, + slopeValue, + forecastValue, + slopeInterceptXValues, + yValues, + ); break; case TrendlineType.power: _calculatePowerPoints( - seriesXValues, - seriesYValues, - sortedXValues, - _slopeIntercept, - slopeInterceptData, - slopeValue, - forecastValue, - slopeInterceptXValues, - yValues); + seriesXValues, + seriesYValues, + sortedXValues, + _slopeIntercept, + slopeInterceptData, + slopeValue, + forecastValue, + slopeInterceptXValues, + yValues, + ); break; case TrendlineType.logarithmic: _calculateLogarithmicPoints( - seriesXValues, - seriesYValues, - sortedXValues, - _slopeIntercept, - slopeInterceptData, - slopeValue, - forecastValue, - slopeInterceptXValues, - yValues); + seriesXValues, + seriesYValues, + sortedXValues, + _slopeIntercept, + slopeInterceptData, + slopeValue, + forecastValue, + slopeInterceptXValues, + yValues, + ); break; case TrendlineType.polynomial: - _slope = _calculatePolynomialPoints(sortedXValues, seriesYValues, - polynomialSlopes, slopeValue, polynomialForeCastValue); + _slope = _calculatePolynomialPoints( + sortedXValues, + seriesYValues, + polynomialSlopes, + slopeValue, + polynomialForeCastValue, + ); break; case TrendlineType.movingAverage: @@ -2247,14 +2352,23 @@ class TrendlineRenderer extends RenderBox { // Calculate slope and intercept values after calculated trendline points. if (!(type == TrendlineType.movingAverage || type == TrendlineType.polynomial)) { - slopeInterceptData = _computeSlopeInterceptValues(slopeInterceptXValues, - yValues, seriesXValues.length, _slopeIntercept); + slopeInterceptData = _computeSlopeInterceptValues( + slopeInterceptXValues, + yValues, + seriesXValues.length, + _slopeIntercept, + ); _slope = [slopeInterceptData.slope!]; } if (onRenderDetailsUpdate != null) { - _rSquaredValue = _computeRSquaredValue(seriesXValues, seriesYValues, - _slope, _slopeIntercept.intercept, slopeValue); + _rSquaredValue = _computeRSquaredValue( + seriesXValues, + seriesYValues, + _slope, + _slopeIntercept.intercept, + slopeValue, + ); } // Calculate segment index based on the trendXValues. @@ -2265,13 +2379,17 @@ class TrendlineRenderer extends RenderBox { } } - List? buildLegendItems( - int index, LegendItemProviderMixin provider) { + List? buildLegendItems( + int index, + LegendItemProviderMixin provider, + ) { if (isVisibleInLegend) { - _legendItem = ChartLegendItem( + _legendItem = CartesianLegendItem( text: name ?? _defaultTrendlineName(), - iconType: - _toShapeMarkerType(legendIconType, legendItemProvider: provider), + iconType: _toShapeMarkerType( + legendIconType, + legendItemProvider: provider, + ), iconColor: color!, iconBorderWidth: 2, series: series, @@ -2281,7 +2399,7 @@ class TrendlineRenderer extends RenderBox { onTap: _handleLegendItemTapped, onRender: _handleLegendItemCreated, ); - return [_legendItem!]; + return [_legendItem!]; } else { _legendItem = null; return null; @@ -2299,8 +2417,10 @@ class TrendlineRenderer extends RenderBox { void _handleLegendItemTapped(LegendItem item, bool wasToggled) { if (_legendItem != null && series != null && series!.controller.isVisible) { if (series!.parent != null && series!.parent!.onLegendTapped != null) { - final LegendTapArgs args = - LegendTapArgs(_legendItem!.series, _legendItem!.seriesIndex); + final LegendTapArgs args = LegendTapArgs( + _legendItem!.series, + _legendItem!.seriesIndex, + ); series!.parent!.onLegendTapped!(args); } isToggled = wasToggled; @@ -2312,7 +2432,7 @@ class TrendlineRenderer extends RenderBox { if (series != null && series!.parent != null && series!.parent!.onLegendItemRender != null) { - final ChartLegendItem item = details.item as ChartLegendItem; + final CartesianLegendItem item = details.item as CartesianLegendItem; final LegendIconType iconType = toLegendIconType(details.iconType); final LegendRenderArgs args = LegendRenderArgs(item.seriesIndex, item.pointIndex) @@ -2322,7 +2442,8 @@ class TrendlineRenderer extends RenderBox { series!.parent!.onLegendItemRender!(args); if (args.legendIconType != iconType) { details.iconType = _toShapeMarkerType( - args.legendIconType ?? LegendIconType.seriesType); + args.legendIconType ?? LegendIconType.seriesType, + ); } details @@ -2331,8 +2452,10 @@ class TrendlineRenderer extends RenderBox { } } - ShapeMarkerType _toShapeMarkerType(LegendIconType iconType, - {LegendItemProviderMixin? legendItemProvider}) { + ShapeMarkerType _toShapeMarkerType( + LegendIconType iconType, { + LegendItemProviderMixin? legendItemProvider, + }) { switch (iconType) { case LegendIconType.seriesType: if (legendItemProvider != null) { @@ -2465,10 +2588,11 @@ class TrendlineRenderer extends RenderBox { final Color themeFillColor = series!.parent!.themeData!.colorScheme.surface; final int length = trendlineXValues.length; for (int i = 0; i < length; i++) { - final ChartMarker marker = ChartMarker() - ..x = trendlineXValues[i] - ..y = trendlineYValues[i] - ..index = i; + final ChartMarker marker = + ChartMarker() + ..x = trendlineXValues[i] + ..y = trendlineYValues[i] + ..index = i; marker.merge( borderColor: markerSettings.borderColor ?? color, borderWidth: markerSettings.borderWidth, @@ -2493,10 +2617,11 @@ class TrendlineRenderer extends RenderBox { return; } - final Paint trendlinePaint = Paint() - ..color = color!.withValues(alpha: opacity) - ..strokeWidth = width - ..style = PaintingStyle.stroke; + final Paint trendlinePaint = + Paint() + ..color = color!.withValues(alpha: opacity) + ..strokeWidth = width + ..style = PaintingStyle.stroke; if (trendlinePaint.color != Colors.transparent && trendlinePaint.strokeWidth > 0) { @@ -2505,9 +2630,10 @@ class TrendlineRenderer extends RenderBox { if (_markers.isNotEmpty) { final Paint fillPaint = Paint()..isAntiAlias = true; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; for (final ChartMarker marker in _markers) { fillPaint.color = marker.color!; strokePaint diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/utils/constants.dart b/packages/syncfusion_flutter_charts/lib/src/charts/utils/constants.dart index eb58b46ac..9d3dde344 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/utils/constants.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/utils/constants.dart @@ -42,8 +42,9 @@ const double tooltipMarkerSize = 10.0; /// Specifies the tooltip marker padding. const EdgeInsets tooltipMarkerPadding = EdgeInsets.all(2.0); -const EdgeInsetsDirectional tooltipItemSpacing = - EdgeInsetsDirectional.only(end: 3.0); +const EdgeInsetsDirectional tooltipItemSpacing = EdgeInsetsDirectional.only( + end: 3.0, +); const EdgeInsets tooltipInnerPadding = EdgeInsets.all(6.0); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/utils/enum.dart b/packages/syncfusion_flutter_charts/lib/src/charts/utils/enum.dart index 67d0478c3..765908086 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/utils/enum.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/utils/enum.dart @@ -15,7 +15,7 @@ enum LegendPosition { right, /// - `LegendPosition.top`, places the legend at the top of the plot area. - top + top, } /// Alignment of various elements in chart. @@ -27,7 +27,7 @@ enum ChartAlignment { center, /// - `ChartAlignment.far` aligns to the far position. - far + far, } /// Mode to handle the legend items overflow. @@ -42,7 +42,7 @@ enum LegendItemOverflowMode { /// - `LegendItemOverflowMode.none`, will simply hides the remaining /// legend items. - none + none, } /// Orientation of legend items. @@ -56,7 +56,7 @@ enum LegendItemOrientation { horizontal, /// - `LegendItemOrientation.vertical`, will align the legend item vertically. - vertical + vertical, } /// It used to change the legend icons in different type of series and @@ -91,7 +91,7 @@ enum LegendIconType { ///`LegendIconType.invertedTriangle`, icon is changed by invertedTriangle // shape. - invertedTriangle + invertedTriangle, } /// Position of data labels in Cartesian chart.The position of data labels @@ -117,7 +117,7 @@ enum ChartDataLabelAlignment { /// - ChartDataLabelAlignment.middle places the data label at the /// center position of a point. - middle + middle, } /// Position of data labels in Circular chart. @@ -126,7 +126,7 @@ enum CircularLabelPosition { inside, /// - CircularLabelPosition.line places the data label outside the point. - outside + outside, } /// PyramidMode for pyramid charts. @@ -137,7 +137,7 @@ enum PyramidMode { linear, /// - PyramidMode.surface, Surface pyramid will be displayed - surface + surface, } /// Orientation of an axis. @@ -148,7 +148,7 @@ enum AxisOrientation { vertical, /// - AxisOrientation.horizontal, renders the axis horizontally. - horizontal + horizontal, } /// Padding for axis ranges. @@ -197,7 +197,7 @@ enum LabelPlacement { betweenTicks, /// - LabelPlacement.onTicks, places the axis label on the ticks. - onTicks + onTicks, } /// Action while the axis label intersects. Axis label placements can be @@ -226,7 +226,7 @@ enum AxisLabelIntersectAction { rotate45, /// - AxisLabelIntersectAction.rotate90, rotates all the axis labels to 90°. - rotate90 + rotate90, } /// Interval type of the DateTime and DateTimeCategory axis. @@ -265,7 +265,7 @@ enum ChartDataLabelPosition { /// - ChartDataLabelPosition.outside places the axis label outside the /// plot area. - outside + outside, } /// Renders a variety of splines @@ -284,7 +284,7 @@ enum SplineType { cardinal, ///- SplineType.clamped, will rendering clamped type spline. - clamped + clamped, } /// Placement of edge labels in the axis. @@ -297,7 +297,7 @@ enum EdgeLabelPlacement { /// - EdgeLabelPlacement.shift, shift the edge labels inside the /// plot area bounds. - shift + shift, } /// Mode of empty data points. @@ -316,7 +316,7 @@ enum EmptyPointMode { /// - EmptyPointMode.average, will consider the average value of its previous /// and next data points. - average + average, } /// Sorting order of data points. @@ -330,7 +330,7 @@ enum SortingOrder { descending, /// - SortingOrder.none renders the points without sorting. - none + none, } /// Position of the ticks in the axis. @@ -339,7 +339,7 @@ enum TickPosition { inside, /// - TickPosition.outside, places the ticks outside the plot area. - outside + outside, } /// Trendline type @@ -362,7 +362,7 @@ enum TrendlineType { polynomial, /// - TrendlineType.movingAverage, displays movingAverage trendline type. - movingAverage + movingAverage, } /// Mode to activate a specific interactive user feature. @@ -380,7 +380,7 @@ enum ActivationMode { longPress, /// - ActivationMode.none, does not activate any feature. - none + none, } /// Trackball tooltip's display mode. @@ -400,7 +400,7 @@ enum TrackballDisplayMode { /// - TrackballDisplayMode.nearestPoint, displays the tooltip of /// nearest point. - nearestPoint + nearestPoint, } /// Crosshair line type. @@ -415,7 +415,7 @@ enum CrosshairLineType { vertical, /// - CrosshairLineType.none, will not display crosshair line. - none + none, } /// Trackball line type. @@ -424,7 +424,7 @@ enum TrackballLineType { vertical, /// - TrackballLineType.none, will not display trackball line. - none + none, } /// Zooming mode in [SfCartesianChart] @@ -436,7 +436,7 @@ enum ZoomMode { y, /// - `ZoomMode.xy`, zooms in both horizontal and vertical direction. - xy + xy, } /// Data point selection type. @@ -448,7 +448,7 @@ enum SelectionType { series, /// - SelectionType.cluster, selects the cluster of data points. - cluster + cluster, } /// Coordinate unit for placing annotations. @@ -462,7 +462,7 @@ enum CoordinateUnit { /// - CoordinateUnit.percentage, places the annotation concerning to the /// percentage value. - percentage + percentage, } /// Annotation is a note by way of explanation or comment added to the chart. @@ -475,7 +475,7 @@ enum AnnotationRegion { /// - AnnotationRegion.plotArea, places the annotation anywhere in the /// plot area. - plotArea + plotArea, } enum ChartClipBehavior { @@ -497,7 +497,7 @@ enum BorderDrawMode { top, /// - BorderDrawMode.excludeBottom, renders border except bottom side. - excludeBottom + excludeBottom, } /// Border mode of range area series. @@ -507,7 +507,7 @@ enum RangeAreaBorderMode { /// - RangeAreaBorderMode.excludeSides, renders border except /// left and right side. - excludeSides + excludeSides, } /// Types of text rendering positions. @@ -519,7 +519,7 @@ enum TextAnchor { middle, /// - TextAnchor.end, anchors the text at the end position. - end + end, } /// Tooltip positioning. @@ -529,7 +529,7 @@ enum TooltipPosition { /// - TooltipPosition.pointer, position of the tooltip will be at the /// pointer position. - pointer + pointer, } /// Macd indicator type. @@ -541,7 +541,7 @@ enum MacdType { line, /// - MacdType.histogram, the indicator will have a histogram line only. - histogram + histogram, } /// Box plot series rendering mode. @@ -564,7 +564,7 @@ enum BoxPlotMode { /// The quartile values are calculated using the formula /// (N+1) * P (N count, P percentile), and their index value starts from 1 /// in the list. - exclusive + exclusive, } /// Used to align the Cartesian data label positions. @@ -580,7 +580,7 @@ enum LabelAlignment { /// `LabelAlignment.center`, data label alignment is center of the /// series line. - center + center, } /// Whether marker should be visible or not when trackball is enabled. @@ -597,7 +597,7 @@ enum TrackballVisibilityMode { /// * TrackballVisibilityMode.hidden - Hides the trackball marker for all /// the series. - hidden + hidden, } /// The direction of swiping on the chart. @@ -610,7 +610,7 @@ enum ChartSwipeDirection { /// If the swipe happens from right to left direction, the /// direction is `ChartSwipeDirection.end`. - end + end, } /// Determines whether the axis should be scrolled from the start position or @@ -629,7 +629,7 @@ enum AutoScrollingMode { /// `AutoScrollingMode.end`, if the chart is scrolled from right to /// left direction. - end + end, } /// Determines the type of the Error Bar. @@ -652,7 +652,7 @@ enum ErrorBarType { /// `ErrorBarType.custom` - It determines the positive and negative error /// values in both horizontal and vertical direction. - custom + custom, } /// Determines the error bar direction. @@ -665,7 +665,7 @@ enum Direction { /// `Direction.both` - Determines the error bar direction in both positive /// and negative sides. - both + both, } /// Determines mode of the error bar. @@ -679,7 +679,7 @@ enum RenderingMode { /// `RenderingMode.both` - Determines both the vertical and horizontal sides /// of the error bar. - both + both, } /// Border type of the chart axis label. @@ -722,7 +722,7 @@ enum CircularChartGroupMode { point, /// - CircularChartGroupMode.value, groups the points based on the y value. - value + value, } /// Data label position of range bar series. @@ -731,7 +731,7 @@ enum Position { left, /// - Position.right, places the data label to the right side. - right + right, } /// Data labels intersect action. @@ -747,7 +747,7 @@ enum LabelIntersectAction { /// labels smartly. If the labels are moved out of the chart area, then the /// labels will be trimmed and the eclipse will be shown for the /// trimmed labels. - shift + shift, } /// Type of connector line. @@ -757,7 +757,7 @@ enum ConnectorType { /// - ConnectorType.line, will render the data label connector line /// straightly. - line + line, } /// Corner style of range bar series. @@ -772,7 +772,7 @@ enum CornerStyle { startCurve, /// - CornerStyle.endCurve, will render ending corner curly. - endCurve + endCurve, } /// Point Render Mode for circular charts diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/utils/helper.dart b/packages/syncfusion_flutter_charts/lib/src/charts/utils/helper.dart index 659fb85d9..ecf8bd71e 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/utils/helper.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/utils/helper.dart @@ -62,9 +62,10 @@ Widget buildChartWithTitle( decoration: BoxDecoration( color: chartThemeData.titleBackgroundColor, border: Border.all( - color: title.borderWidth == 0 - ? Colors.transparent - : title.borderColor, + color: + title.borderWidth == 0 + ? Colors.transparent + : title.borderColor, width: title.borderWidth, ), ), @@ -126,16 +127,22 @@ Offset _rotatePoint(Offset point, Offset center, double radius) { double factorFromValue(String? value) { if (value != null && value.isNotEmpty) { - final double? factor = value.contains('%') - ? double.tryParse(value.replaceAll(RegExp('%'), ''))! / 100.0 - : double.tryParse(value); + final double? factor = + value.contains('%') + ? double.tryParse(value.replaceAll(RegExp('%'), ''))! / 100.0 + : double.tryParse(value); return factor != null ? clampDouble(factor, 0.0, 1.0) : 0.0; } return 0.0; } -Offset rawValueToPixelPoint(dynamic x, num y, RenderChartAxis? xAxis, - RenderChartAxis? yAxis, bool isTransposed) { +Offset rawValueToPixelPoint( + dynamic x, + num y, + RenderChartAxis? xAxis, + RenderChartAxis? yAxis, + bool isTransposed, +) { if (xAxis == null || yAxis == null) { return Offset.zero; } @@ -165,13 +172,23 @@ Offset rawValueToPixelPoint(dynamic x, num y, RenderChartAxis? xAxis, ); } -double _pointToPixelX(num x, num y, RenderChartAxis xAxis, - RenderChartAxis yAxis, bool isTransposed) { +double _pointToPixelX( + num x, + num y, + RenderChartAxis xAxis, + RenderChartAxis yAxis, + bool isTransposed, +) { return isTransposed ? yAxis.pointToPixel(y) : xAxis.pointToPixel(x); } -double _pointToPixelY(num x, num y, RenderChartAxis xAxis, - RenderChartAxis yAxis, bool isTransposed) { +double _pointToPixelY( + num x, + num y, + RenderChartAxis xAxis, + RenderChartAxis yAxis, + bool isTransposed, +) { return isTransposed ? xAxis.pointToPixel(x) : yAxis.pointToPixel(y); } @@ -236,7 +253,11 @@ Path createPath(List points) { } void drawDashesFromPoints( - Canvas canvas, List points, List? dashArray, Paint paint) { + Canvas canvas, + List points, + List? dashArray, + Paint paint, +) { if (points.isEmpty) { return; } @@ -245,8 +266,14 @@ void drawDashesFromPoints( drawDashes(canvas, dashArray, paint, path: path); } -void drawDashes(Canvas canvas, List? dashArray, Paint paint, - {Path? path, Offset? start, Offset? end}) { +void drawDashes( + Canvas canvas, + List? dashArray, + Paint paint, { + Path? path, + Offset? start, + Offset? end, +}) { if (path == null && (start == null || start.isNaN || end == null || end.isNaN)) { return; @@ -270,9 +297,10 @@ void drawDashes(Canvas canvas, List? dashArray, Paint paint, } } else { if (path == null && start != null && end != null) { - path = Path() - ..moveTo(start.dx, start.dy) - ..lineTo(end.dx, end.dy); + path = + Path() + ..moveTo(start.dx, start.dy) + ..lineTo(end.dx, end.dy); } if (path == null) { @@ -281,15 +309,14 @@ void drawDashes(Canvas canvas, List? dashArray, Paint paint, paint.isAntiAlias = false; canvas.drawPath( - _dashPath(path, dashArray: _IntervalList(dashArray!))!, paint); + _dashPath(path, dashArray: _IntervalList(dashArray!))!, + paint, + ); } } /// To calculate dash array path for series. -Path? _dashPath( - Path? source, { - required _IntervalList dashArray, -}) { +Path? _dashPath(Path? source, {required _IntervalList dashArray}) { if (source == null) { return null; } @@ -302,7 +329,9 @@ Path? _dashPath( final double length = dashArray.next; if (canDraw) { path.addPath( - matric.extractPath(distance, distance + length), Offset.zero); + matric.extractPath(distance, distance + length), + Offset.zero, + ); } distance += length; canDraw = !canDraw; @@ -312,12 +341,13 @@ Path? _dashPath( } Color dataLabelSurfaceColor( - Color labelColor, - int dataPointIndex, - ChartDataLabelPosition labelPosition, - SfChartThemeData chartThemeData, - ThemeData themeData, - ChartSegment segment) { + Color labelColor, + int dataPointIndex, + ChartDataLabelPosition labelPosition, + SfChartThemeData chartThemeData, + ThemeData themeData, + ChartSegment segment, +) { switch (labelPosition) { case ChartDataLabelPosition.inside: return labelColor != Colors.transparent @@ -374,7 +404,9 @@ double? percentToValue(String? value, num size) { Offset calculateOffset(double degree, double radius, Offset center) { final double radian = degreesToRadians(degree); return Offset( - center.dx + cos(radian) * radius, center.dy + sin(radian) * radius); + center.dx + cos(radian) * radius, + center.dy + sin(radian) * radius, + ); } double degreesToRadians(double deg) => deg * (pi / 180); @@ -387,8 +419,12 @@ bool isLies(num start, num end, DoubleRange range) { } String trimmedText( - String text, TextStyle labelStyle, num labelsExtent, int labelRotation, - {bool? isRtl}) { + String text, + TextStyle labelStyle, + num labelsExtent, + int labelRotation, { + bool? isRtl, +}) { String current = text; num width = measureText(text, labelStyle, labelRotation).width; if (width > labelsExtent) { @@ -427,8 +463,12 @@ double paddingFromSize(String? padding, double size) { return 0; } -Rect clipRect(Rect bounds, double animationFactor, - {bool isInversed = false, bool isTransposed = false}) { +Rect clipRect( + Rect bounds, + double animationFactor, { + bool isInversed = false, + bool isTransposed = false, +}) { double left = bounds.left; double top = bounds.top; double width = bounds.width; @@ -474,7 +514,9 @@ ShapeMarkerType toShapeMarkerType(DataMarkerType type) { } ShapeMarkerType toLegendShapeMarkerType( - LegendIconType iconType, core.LegendItemProviderMixin provider) { + LegendIconType iconType, + core.LegendItemProviderMixin provider, +) { switch (iconType) { case LegendIconType.seriesType: return provider.effectiveLegendIconType(); @@ -530,15 +572,16 @@ String decimalLabelValue(num? value, [int? showDigits]) { final String str = value.toString(); final List list = str.split('.'); value = double.parse(value.toStringAsFixed(showDigits ?? 3)); - value = (list[1] == '0' || - list[1] == '00' || - list[1] == '000' || - list[1] == '0000' || - list[1] == '00000' || - list[1] == '000000' || - list[1] == '0000000') - ? value.round() - : value; + value = + (list[1] == '0' || + list[1] == '00' || + list[1] == '000' || + list[1] == '0000' || + list[1] == '00000' || + list[1] == '000000' || + list[1] == '0000000') + ? value.round() + : value; } return value == null ? '' : value.toString(); @@ -596,9 +639,10 @@ String formatRTLText(String tooltipText) { String string = ''; for (int i = secondStringCollection.length - 1; i >= 0; i--) { secondStringCollection[i] = secondStringCollection[i].trim(); - string += (i == secondStringCollection.length - 1 - ? secondStringCollection[i] - : ' : ${secondStringCollection[i]}'); + string += + (i == secondStringCollection.length - 1 + ? secondStringCollection[i] + : ' : ${secondStringCollection[i]}'); } resultantString += (resultantString.isEmpty ? '' : '\n') + string; } else { @@ -630,13 +674,15 @@ Widget? buildTooltipWidget( ); if (tooltip == null) { - final bool hasMarker = tooltipBehavior.canShowMarker && + final bool hasMarker = + tooltipBehavior.canShowMarker && info.markerColors.isNotEmpty && info.markerColors.any((Color? color) => color != null); final TextStyle textStyle = chartThemeData.tooltipTextStyle!; - final TextStyle headerStyle = - textStyle.copyWith(fontWeight: FontWeight.bold); + final TextStyle headerStyle = textStyle.copyWith( + fontWeight: FontWeight.bold, + ); final String header = tooltipBehavior.header ?? info.header; final Size headerSize = measureText(header, headerStyle); final Size textSize = measureText(info.text!, textStyle); @@ -647,9 +693,10 @@ Widget? buildTooltipWidget( headerAlignedSize = maxSize.width - tooltipInnerPadding.horizontal; dividerWidth = headerAlignedSize; } else { - dividerWidth += tooltipBehavior.canShowMarker - ? tooltipMarkerSize + tooltipMarkerPadding.horizontal - : 0.0; + dividerWidth += + tooltipBehavior.canShowMarker + ? tooltipMarkerSize + tooltipMarkerPadding.horizontal + : 0.0; } final bool isLtr = Directionality.of(context) == TextDirection.ltr; @@ -671,7 +718,8 @@ Widget? buildTooltipWidget( child: Divider( height: 10.0, thickness: 0.5, - color: tooltipBehavior.textStyle?.color ?? + color: + tooltipBehavior.textStyle?.color ?? chartThemeData.tooltipSeparatorColor, ), ), @@ -715,10 +763,7 @@ Widget? buildTooltipWidget( ], ); - tooltip = Padding( - padding: tooltipInnerPadding, - child: tooltip, - ); + tooltip = Padding(padding: tooltipInnerPadding, child: tooltip); } } } else if (info != null && info.text != null && info.text!.isNotEmpty) { @@ -763,7 +808,9 @@ class TooltipMarkerShapeRenderObject extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderTooltipMarkerShape renderObject) { + BuildContext context, + RenderTooltipMarkerShape renderObject, + ) { renderObject ..index = index ..colors = colors @@ -853,13 +900,15 @@ class RenderTooltipMarkerShape extends RenderBox { size = const Size(tooltipMarkerSize, tooltipMarkerSize); } - final Paint strokePaint = Paint() - ..style = PaintingStyle.stroke - ..isAntiAlias = true - ..strokeWidth = 1.0; - final Paint fillPaint = Paint() - ..style = PaintingStyle.fill - ..isAntiAlias = true; + final Paint strokePaint = + Paint() + ..style = PaintingStyle.stroke + ..isAntiAlias = true + ..strokeWidth = 1.0; + final Paint fillPaint = + Paint() + ..style = PaintingStyle.fill + ..isAntiAlias = true; @override void paint(PaintingContext context, Offset offset) { @@ -876,9 +925,10 @@ class RenderTooltipMarkerShape extends RenderBox { if (markerType == DataMarkerType.image) { if (_markerImage != null) { paintImage( - canvas: context.canvas, - rect: offset & size, - image: _markerImage!); + canvas: context.canvas, + rect: offset & size, + image: _markerImage!, + ); } } else { _drawTooltipMarker( @@ -929,9 +979,11 @@ Future fetchImage(ImageProvider? imageProvider) async { final Completer completer = Completer(); imageProvider .resolve(ImageConfiguration.empty) - .addListener(ImageStreamListener((ImageInfo info, bool _) { - completer.complete(info); - })); + .addListener( + ImageStreamListener((ImageInfo info, bool _) { + completer.complete(info); + }), + ); final ImageInfo imageInfo = await completer.future; return imageInfo.image; } @@ -965,9 +1017,15 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } String _replace( - String tooltipText, String replacingText, num value, int digits) { + String tooltipText, + String replacingText, + num value, + int digits, + ) { return tooltipText.replaceAll( - replacingText, formatNumericValue(value, yAxis, digits)); + replacingText, + formatNumericValue(value, yAxis, digits), + ); } String _formatTrackballLabel(num value, int digits, String text, bool isLtr) { @@ -1013,63 +1071,104 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } if (point.close != null) { - tooltipText = - _replace(tooltipText, 'point.close', point.close!, digits); + tooltipText = _replace( + tooltipText, + 'point.close', + point.close!, + digits, + ); } if (outlierIndex != -1) { if (point.outliers != null && point.outliers!.isNotEmpty) { - tooltipText = _replace(tooltipText, 'point.outliers', - point.outliers![outlierIndex], digits); + tooltipText = _replace( + tooltipText, + 'point.outliers', + point.outliers![outlierIndex], + digits, + ); } } else { if (point.minimum != null) { - tooltipText = - _replace(tooltipText, 'point.minimum', point.minimum!, digits); + tooltipText = _replace( + tooltipText, + 'point.minimum', + point.minimum!, + digits, + ); } if (point.maximum != null) { - tooltipText = - _replace(tooltipText, 'point.maximum', point.maximum!, digits); + tooltipText = _replace( + tooltipText, + 'point.maximum', + point.maximum!, + digits, + ); } if (point.lowerQuartile != null) { tooltipText = _replace( - tooltipText, 'point.lowerQuartile', point.lowerQuartile!, digits); + tooltipText, + 'point.lowerQuartile', + point.lowerQuartile!, + digits, + ); } if (point.upperQuartile != null) { tooltipText = _replace( - tooltipText, 'point.upperQuartile', point.upperQuartile!, digits); + tooltipText, + 'point.upperQuartile', + point.upperQuartile!, + digits, + ); } if (point.mean != null) { - tooltipText = - _replace(tooltipText, 'point.mean', point.mean!, digits); + tooltipText = _replace( + tooltipText, + 'point.mean', + point.mean!, + digits, + ); } if (point.median != null) { - tooltipText = - _replace(tooltipText, 'point.median', point.median!, digits); + tooltipText = _replace( + tooltipText, + 'point.median', + point.median!, + digits, + ); } } if (point.cumulative != null) { tooltipText = _replace( - tooltipText, 'point.cumulative', point.cumulative!, digits); + tooltipText, + 'point.cumulative', + point.cumulative!, + digits, + ); } if (point.bubbleSize != null) { - tooltipText = - _replace(tooltipText, 'point.size', point.bubbleSize!, digits); + tooltipText = _replace( + tooltipText, + 'point.size', + point.bubbleSize!, + digits, + ); } tooltipText = tooltipText.replaceAll('series.name', name); text = isLtr ? tooltipText : formatRTLText(tooltipText); } else { - text = parent!.tooltipBehavior!.shared - ? name - : tooltipHeaderText(point, digits); + text = + parent!.tooltipBehavior!.shared + ? name + : tooltipHeaderText(point, digits); if (point.y != null) { text = _formatTooltipLabel(point.y!, digits, text, isLtr); @@ -1111,7 +1210,11 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } text += _formatTooltipLabel( - point.outliers![outlierIndex], digits, 'Outliers', isLtr); + point.outliers![outlierIndex], + digits, + 'Outliers', + isLtr, + ); } } else { if (point.minimum != null) { @@ -1151,8 +1254,12 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { text += '\n'; } - text += - _formatTooltipLabel(point.lowerQuartile!, digits, 'LQ', isLtr); + text += _formatTooltipLabel( + point.lowerQuartile!, + digits, + 'LQ', + isLtr, + ); } if (point.upperQuartile != null) { @@ -1160,8 +1267,12 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { text += '\n'; } - text += - _formatTooltipLabel(point.upperQuartile!, digits, 'HQ', isLtr); + text += _formatTooltipLabel( + point.upperQuartile!, + digits, + 'HQ', + isLtr, + ); } } } @@ -1169,8 +1280,11 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { return text; } - String trackballText(CartesianChartPoint point, String seriesName, - {int outlierIndex = -1}) { + String trackballText( + CartesianChartPoint point, + String seriesName, { + int outlierIndex = -1, + }) { if (parent == null || parent!.trackballBehavior == null || xAxis == null || @@ -1209,55 +1323,95 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } if (point.close != null) { - tooltipText = - _replace(tooltipText, 'point.close', point.close!, digits); + tooltipText = _replace( + tooltipText, + 'point.close', + point.close!, + digits, + ); } if (outlierIndex != -1) { if (point.outliers != null && point.outliers!.isNotEmpty) { - tooltipText = _replace(tooltipText, 'point.outliers', - point.outliers![outlierIndex], digits); + tooltipText = _replace( + tooltipText, + 'point.outliers', + point.outliers![outlierIndex], + digits, + ); } } else { if (point.minimum != null) { - tooltipText = - _replace(tooltipText, 'point.minimum', point.minimum!, digits); + tooltipText = _replace( + tooltipText, + 'point.minimum', + point.minimum!, + digits, + ); } if (point.maximum != null) { - tooltipText = - _replace(tooltipText, 'point.maximum', point.maximum!, digits); + tooltipText = _replace( + tooltipText, + 'point.maximum', + point.maximum!, + digits, + ); } if (point.lowerQuartile != null) { tooltipText = _replace( - tooltipText, 'point.lowerQuartile', point.lowerQuartile!, digits); + tooltipText, + 'point.lowerQuartile', + point.lowerQuartile!, + digits, + ); } if (point.upperQuartile != null) { tooltipText = _replace( - tooltipText, 'point.upperQuartile', point.upperQuartile!, digits); + tooltipText, + 'point.upperQuartile', + point.upperQuartile!, + digits, + ); } if (point.mean != null) { - tooltipText = - _replace(tooltipText, 'point.mean', point.mean!, digits); + tooltipText = _replace( + tooltipText, + 'point.mean', + point.mean!, + digits, + ); } if (point.median != null) { - tooltipText = - _replace(tooltipText, 'point.median', point.median!, digits); + tooltipText = _replace( + tooltipText, + 'point.median', + point.median!, + digits, + ); } } if (point.cumulative != null) { tooltipText = _replace( - tooltipText, 'point.cumulative', point.cumulative!, digits); + tooltipText, + 'point.cumulative', + point.cumulative!, + digits, + ); } if (point.bubbleSize != null) { - tooltipText = - _replace(tooltipText, 'point.size', point.bubbleSize!, digits); + tooltipText = _replace( + tooltipText, + 'point.size', + point.bubbleSize!, + digits, + ); } tooltipText = tooltipText.replaceAll('series.name', seriesName); @@ -1303,7 +1457,11 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } text += _formatTrackballLabel( - point.outliers![outlierIndex], digits, 'Outliers', isLtr); + point.outliers![outlierIndex], + digits, + 'Outliers', + isLtr, + ); } } else { if (point.minimum != null) { @@ -1311,8 +1469,12 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { text += '\n'; } - text += - _formatTrackballLabel(point.minimum!, digits, 'Minimum', isLtr); + text += _formatTrackballLabel( + point.minimum!, + digits, + 'Minimum', + isLtr, + ); } if (point.maximum != null) { @@ -1320,8 +1482,12 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { text += '\n'; } - text += - _formatTrackballLabel(point.maximum!, digits, 'Maximum', isLtr); + text += _formatTrackballLabel( + point.maximum!, + digits, + 'Maximum', + isLtr, + ); } if (point.median != null) { @@ -1346,7 +1512,11 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } text += _formatTrackballLabel( - point.lowerQuartile!, digits, 'LowerQuartile', isLtr); + point.lowerQuartile!, + digits, + 'LowerQuartile', + isLtr, + ); } if (point.upperQuartile != null) { @@ -1355,7 +1525,11 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { } text += _formatTrackballLabel( - point.upperQuartile!, digits, 'UpperQuartile', isLtr); + point.upperQuartile!, + digits, + 'UpperQuartile', + isLtr, + ); } } } @@ -1385,12 +1559,15 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { return text; } - DateFormat _dateTimeLabelFormat(RenderChartAxis axis, - [int? interval, int? prevInterval]) { + DateFormat _dateTimeLabelFormat( + RenderChartAxis axis, [ + int? interval, + int? prevInterval, + ]) { DateFormat? format; final bool notDoubleInterval = (axis.interval != null && axis.interval! % 1 == 0) || - axis.interval == null; + axis.interval == null; DateTimeIntervalType? actualIntervalType; num? minimum; minimum = axis.visibleRange!.minimum; @@ -1405,15 +1582,17 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { format = notDoubleInterval ? DateFormat.y() : DateFormat.MMMd(); break; case DateTimeIntervalType.months: - format = (minimum == interval || interval == prevInterval) - ? _firstLabelFormat(actualIntervalType) - : _dateTimeFormat(actualIntervalType, interval, prevInterval); + format = + (minimum == interval || interval == prevInterval) + ? _firstLabelFormat(actualIntervalType) + : _dateTimeFormat(actualIntervalType, interval, prevInterval); break; case DateTimeIntervalType.days: - format = (minimum == interval || interval == prevInterval) - ? _firstLabelFormat(actualIntervalType) - : _dateTimeFormat(actualIntervalType, interval, prevInterval); + format = + (minimum == interval || interval == prevInterval) + ? _firstLabelFormat(actualIntervalType) + : _dateTimeFormat(actualIntervalType, interval, prevInterval); break; case DateTimeIntervalType.hours: format = DateFormat.j(); @@ -1435,20 +1614,25 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { return format!; } - DateFormat? _dateTimeFormat(DateTimeIntervalType? actualIntervalType, - int? interval, int? prevInterval) { + DateFormat? _dateTimeFormat( + DateTimeIntervalType? actualIntervalType, + int? interval, + int? prevInterval, + ) { final DateTime minimum = DateTime.fromMillisecondsSinceEpoch(interval!); final DateTime maximum = DateTime.fromMillisecondsSinceEpoch(prevInterval!); DateFormat? format; final bool isIntervalDecimal = interval % 1 == 0; if (actualIntervalType == DateTimeIntervalType.months) { - format = minimum.year == maximum.year - ? (isIntervalDecimal ? DateFormat.MMM() : DateFormat.MMMd()) - : DateFormat('yyy MMM'); + format = + minimum.year == maximum.year + ? (isIntervalDecimal ? DateFormat.MMM() : DateFormat.MMMd()) + : DateFormat('yyy MMM'); } else if (actualIntervalType == DateTimeIntervalType.days) { - format = minimum.month != maximum.month - ? (isIntervalDecimal ? DateFormat.MMMd() : DateFormat.MEd()) - : DateFormat.d(); + format = + minimum.month != maximum.month + ? (isIntervalDecimal ? DateFormat.MMMd() : DateFormat.MEd()) + : DateFormat.d(); } return format; @@ -1468,8 +1652,12 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { return format; } - Offset translateTransform(num x, num y, - [double translationX = 0, double translationY = 0]) { + Offset translateTransform( + num x, + num y, [ + double translationX = 0, + double translationY = 0, + ]) { final double posX = pointToPixelX(x, y); final double posY = pointToPixelY(x, y); return Offset(posX + translationX, posY + translationY); @@ -1495,9 +1683,15 @@ extension CartesianSeriesExtension on CartesianSeriesRenderer { extension IndicatorExtension on IndicatorRenderer { String _replace( - String tooltipText, String replacingText, num value, int digits) { + String tooltipText, + String replacingText, + num value, + int digits, + ) { return tooltipText.replaceAll( - replacingText, formatNumericValue(value, yAxis, digits)); + replacingText, + formatNumericValue(value, yAxis, digits), + ); } String _formatTrackballLabel(num value, int digits, String text, bool isLtr) { @@ -1509,8 +1703,11 @@ extension IndicatorExtension on IndicatorRenderer { : '${formatNumericValue(value, yAxis, digits)} :$text'; } - String trackballText(CartesianChartPoint point, String seriesName, - {int outlierIndex = -1}) { + String trackballText( + CartesianChartPoint point, + String seriesName, { + int outlierIndex = -1, + }) { if (parent == null || parent!.trackballBehavior == null || xAxis == null || @@ -1526,13 +1723,14 @@ extension IndicatorExtension on IndicatorRenderer { } return _behaviorText( - parent!.trackballBehavior!.tooltipSettings.format, - text, - point, - digits, - outlierIndex, - seriesName, - parent!.textDirection == TextDirection.ltr); + parent!.trackballBehavior!.tooltipSettings.format, + text, + point, + digits, + outlierIndex, + seriesName, + parent!.textDirection == TextDirection.ltr, + ); } String _behaviorText( @@ -1565,55 +1763,95 @@ extension IndicatorExtension on IndicatorRenderer { } if (point.close != null) { - tooltipText = - _replace(tooltipText, 'point.close', point.close!, digits); + tooltipText = _replace( + tooltipText, + 'point.close', + point.close!, + digits, + ); } if (outlierIndex != -1) { if (point.outliers != null && point.outliers!.isNotEmpty) { - tooltipText = _replace(tooltipText, 'point.outliers', - point.outliers![outlierIndex], digits); + tooltipText = _replace( + tooltipText, + 'point.outliers', + point.outliers![outlierIndex], + digits, + ); } } else { if (point.minimum != null) { - tooltipText = - _replace(tooltipText, 'point.minimum', point.minimum!, digits); + tooltipText = _replace( + tooltipText, + 'point.minimum', + point.minimum!, + digits, + ); } if (point.maximum != null) { - tooltipText = - _replace(tooltipText, 'point.maximum', point.maximum!, digits); + tooltipText = _replace( + tooltipText, + 'point.maximum', + point.maximum!, + digits, + ); } if (point.lowerQuartile != null) { tooltipText = _replace( - tooltipText, 'point.lowerQuartile', point.lowerQuartile!, digits); + tooltipText, + 'point.lowerQuartile', + point.lowerQuartile!, + digits, + ); } if (point.upperQuartile != null) { tooltipText = _replace( - tooltipText, 'point.upperQuartile', point.upperQuartile!, digits); + tooltipText, + 'point.upperQuartile', + point.upperQuartile!, + digits, + ); } if (point.mean != null) { - tooltipText = - _replace(tooltipText, 'point.mean', point.mean!, digits); + tooltipText = _replace( + tooltipText, + 'point.mean', + point.mean!, + digits, + ); } if (point.median != null) { - tooltipText = - _replace(tooltipText, 'point.median', point.median!, digits); + tooltipText = _replace( + tooltipText, + 'point.median', + point.median!, + digits, + ); } } if (point.cumulative != null) { tooltipText = _replace( - tooltipText, 'point.cumulative', point.cumulative!, digits); + tooltipText, + 'point.cumulative', + point.cumulative!, + digits, + ); } if (point.bubbleSize != null) { - tooltipText = - _replace(tooltipText, 'point.size', point.bubbleSize!, digits); + tooltipText = _replace( + tooltipText, + 'point.size', + point.bubbleSize!, + digits, + ); } tooltipText = tooltipText.replaceAll('series.name', seriesName); @@ -1659,7 +1897,11 @@ extension IndicatorExtension on IndicatorRenderer { } text += _formatTrackballLabel( - point.outliers![outlierIndex], digits, 'Outliers', isLtr); + point.outliers![outlierIndex], + digits, + 'Outliers', + isLtr, + ); } } else { if (point.minimum != null) { @@ -1667,8 +1909,12 @@ extension IndicatorExtension on IndicatorRenderer { text += '\n'; } - text += - _formatTrackballLabel(point.minimum!, digits, 'Minimum', isLtr); + text += _formatTrackballLabel( + point.minimum!, + digits, + 'Minimum', + isLtr, + ); } if (point.maximum != null) { @@ -1676,8 +1922,12 @@ extension IndicatorExtension on IndicatorRenderer { text += '\n'; } - text += - _formatTrackballLabel(point.maximum!, digits, 'Maximum', isLtr); + text += _formatTrackballLabel( + point.maximum!, + digits, + 'Maximum', + isLtr, + ); } if (point.median != null) { @@ -1702,7 +1952,11 @@ extension IndicatorExtension on IndicatorRenderer { } text += _formatTrackballLabel( - point.lowerQuartile!, digits, 'LowerQuartile', isLtr); + point.lowerQuartile!, + digits, + 'LowerQuartile', + isLtr, + ); } if (point.upperQuartile != null) { @@ -1711,7 +1965,11 @@ extension IndicatorExtension on IndicatorRenderer { } text += _formatTrackballLabel( - point.upperQuartile!, digits, 'UpperQuartile', isLtr); + point.upperQuartile!, + digits, + 'UpperQuartile', + isLtr, + ); } } } @@ -1740,12 +1998,15 @@ extension IndicatorExtension on IndicatorRenderer { return text; } - DateFormat _dateTimeLabelFormat(RenderChartAxis axis, - [int? interval, int? prevInterval]) { + DateFormat _dateTimeLabelFormat( + RenderChartAxis axis, [ + int? interval, + int? prevInterval, + ]) { DateFormat? format; final bool notDoubleInterval = (axis.interval != null && axis.interval! % 1 == 0) || - axis.interval == null; + axis.interval == null; DateTimeIntervalType? actualIntervalType; num? minimum; minimum = axis.visibleRange!.minimum; @@ -1760,15 +2021,17 @@ extension IndicatorExtension on IndicatorRenderer { format = notDoubleInterval ? DateFormat.y() : DateFormat.MMMd(); break; case DateTimeIntervalType.months: - format = (minimum == interval || interval == prevInterval) - ? _firstLabelFormat(actualIntervalType) - : _dateTimeFormat(actualIntervalType, interval, prevInterval); + format = + (minimum == interval || interval == prevInterval) + ? _firstLabelFormat(actualIntervalType) + : _dateTimeFormat(actualIntervalType, interval, prevInterval); break; case DateTimeIntervalType.days: - format = (minimum == interval || interval == prevInterval) - ? _firstLabelFormat(actualIntervalType) - : _dateTimeFormat(actualIntervalType, interval, prevInterval); + format = + (minimum == interval || interval == prevInterval) + ? _firstLabelFormat(actualIntervalType) + : _dateTimeFormat(actualIntervalType, interval, prevInterval); break; case DateTimeIntervalType.hours: format = DateFormat.j(); @@ -1790,20 +2053,25 @@ extension IndicatorExtension on IndicatorRenderer { return format!; } - DateFormat? _dateTimeFormat(DateTimeIntervalType? actualIntervalType, - int? interval, int? prevInterval) { + DateFormat? _dateTimeFormat( + DateTimeIntervalType? actualIntervalType, + int? interval, + int? prevInterval, + ) { final DateTime minimum = DateTime.fromMillisecondsSinceEpoch(interval!); final DateTime maximum = DateTime.fromMillisecondsSinceEpoch(prevInterval!); DateFormat? format; final bool isIntervalDecimal = interval % 1 == 0; if (actualIntervalType == DateTimeIntervalType.months) { - format = minimum.year == maximum.year - ? (isIntervalDecimal ? DateFormat.MMM() : DateFormat.MMMd()) - : DateFormat('yyy MMM'); + format = + minimum.year == maximum.year + ? (isIntervalDecimal ? DateFormat.MMM() : DateFormat.MMMd()) + : DateFormat('yyy MMM'); } else if (actualIntervalType == DateTimeIntervalType.days) { - format = minimum.month != maximum.month - ? (isIntervalDecimal ? DateFormat.MMMd() : DateFormat.MEd()) - : DateFormat.d(); + format = + minimum.month != maximum.month + ? (isIntervalDecimal ? DateFormat.MMMd() : DateFormat.MEd()) + : DateFormat.d(); } return format; @@ -1825,7 +2093,11 @@ extension IndicatorExtension on IndicatorRenderer { } int nextIndexConsideringEmptyPointMode( - int index, EmptyPointMode mode, List yValues, int dataCount) { + int index, + EmptyPointMode mode, + List yValues, + int dataCount, +) { return mode == EmptyPointMode.drop ? _nextValidIndex(index, dataCount, yValues) : _nextIndex(index, dataCount); @@ -1856,8 +2128,13 @@ int _nextValidIndex(int index, int dataCount, List yValues) { return -1; } -RRect toRRect(double left, double top, double right, double bottom, - BorderRadius borderRadius) { +RRect toRRect( + double left, + double top, + double right, + double bottom, + BorderRadius borderRadius, +) { if (top > bottom) { final double temp = top; top = bottom; @@ -1887,8 +2164,10 @@ extension OffsetExtension on Offset { Offset? lerp(Offset b, double t, num visibleMin) { final Offset a = this; - return Offset(_lerpDouble(a.dx, b.dx, t, visibleMin), - _lerpDouble(a.dy, b.dy, t, visibleMin)); + return Offset( + _lerpDouble(a.dx, b.dx, t, visibleMin), + _lerpDouble(a.dy, b.dy, t, visibleMin), + ); } } @@ -1990,40 +2269,47 @@ Widget? buildLegendTitle(SfChartThemeData? chartThemeData, Legend legend) { legend.title!.text!.isNotEmpty) { return Padding( padding: const EdgeInsets.all(5.0), - child: Text(legend.title!.text!, - style: chartThemeData!.legendTitleTextStyle), + child: Text( + legend.title!.text!, + style: chartThemeData!.legendTitleTextStyle, + ), ); } return null; } Widget buildLegendItem( - BuildContext context, core.LegendItem legendItem, Legend legend) { - final ChartLegendItem item = legendItem as ChartLegendItem; + BuildContext context, + core.LegendItem legendItem, + Legend legend, +) { ChartPoint point; - if (item.series != null) { - final int length = item.series!.chartPoints.length; - final int pointIndex = item.pointIndex; + if (legendItem.series != null) { + final int length = legendItem.series!.chartPoints.length; + final int pointIndex = legendItem.pointIndex; if (length > 0 && pointIndex > -1 && pointIndex < length) { - point = item.series!.chartPoints[item.pointIndex]; + point = legendItem.series!.chartPoints[legendItem.pointIndex]; } else { - point = ChartPoint(x: item.text); + point = ChartPoint(x: legendItem.text); } } else { - point = ChartPoint(x: item.text); + point = ChartPoint(x: legendItem.text); } - if (item.series is! CartesianSeriesRenderer && - item.series!.segments.isNotEmpty && - item.pointIndex < item.series!.segments.length) { - point.isVisible = item.series!.segmentAt(item.pointIndex).isVisible; + if (legendItem.series is! CartesianSeriesRenderer && + legendItem.series!.segments.isNotEmpty && + legendItem.pointIndex < legendItem.series!.segments.length) { + point.isVisible = + legendItem.series!.segmentAt(legendItem.pointIndex).isVisible; } return legend.legendItemBuilder!( - item.text, - item.series?.widget, + legendItem.text, + legendItem.series?.widget, point, - item.series is CartesianSeriesRenderer ? item.seriesIndex : item.pointIndex, + legendItem.series is CartesianSeriesRenderer + ? legendItem.seriesIndex + : legendItem.pointIndex, ); } @@ -2047,19 +2333,43 @@ bool isValueLinear(int index, num value, List values) { } DateFormat dateTimeAxisLabelFormat( - RenderDateTimeAxis axis, num current, int previous) { - return _niceDateFormat(current, previous, axis.visibleRange!.minimum, - axis.interval, axis.visibleInterval, axis.visibleIntervalType); + RenderDateTimeAxis axis, + num current, + int previous, +) { + return _niceDateFormat( + current, + previous, + axis.visibleRange!.minimum, + axis.interval, + axis.visibleInterval, + axis.visibleIntervalType, + ); } DateFormat dateTimeCategoryAxisLabelFormat( - RenderDateTimeCategoryAxis axis, num current, int previous) { - return _niceDateFormat(current, previous, axis.visibleRange!.minimum, - axis.interval, axis.visibleInterval, axis.visibleIntervalType); + RenderDateTimeCategoryAxis axis, + num current, + int previous, +) { + return _niceDateFormat( + current, + previous, + axis.visibleRange!.minimum, + axis.interval, + axis.visibleInterval, + axis.visibleIntervalType, + ); } -DateFormat _niceDateFormat(num current, int previous, num minimum, - double? interval, num visibleInterval, DateTimeIntervalType intervalType) { +DateFormat _niceDateFormat( + num current, + int previous, + num minimum, + double? interval, + num visibleInterval, + DateTimeIntervalType intervalType, +) { final bool notDoubleInterval = (interval != null && interval % 1 == 0) || interval == null; switch (intervalType) { @@ -2105,8 +2415,12 @@ DateFormat _firstLabelFormat(DateTimeIntervalType visibleIntervalType) { } } -DateFormat _normalDateFormat(DateTimeIntervalType visibleIntervalType, - num visibleInterval, num current, int previousLabel) { +DateFormat _normalDateFormat( + DateTimeIntervalType visibleIntervalType, + num visibleInterval, + num current, + int previousLabel, +) { final DateTime minimum = DateTime.fromMillisecondsSinceEpoch(current.toInt()); final DateTime maximum = DateTime.fromMillisecondsSinceEpoch(previousLabel); final bool isIntervalDecimal = visibleInterval % 1 == 0; @@ -2131,13 +2445,18 @@ String logAxisLabel(RenderLogarithmicAxis axis, num value, int showDigits) { return _labelValue(value, showDigits, axis.numberFormat, axis.labelFormat); } -String _labelValue(num value, int showDigits, NumberFormat? numberFormat, - String? labelFormat) { +String _labelValue( + num value, + int showDigits, + NumberFormat? numberFormat, + String? labelFormat, +) { final List pieces = value.toString().split('.'); if (pieces.length > 1) { value = double.parse(value.toStringAsFixed(showDigits)); final String decimals = pieces[1]; - final bool isDecimalContainsZero = decimals == '0' || + final bool isDecimalContainsZero = + decimals == '0' || decimals == '00' || decimals == '000' || decimals == '0000' || @@ -2166,8 +2485,14 @@ RRect performLegendToggleAnimation( final bool oldSeriesVisible = series.visibilityBeforeTogglingLegend; if (series.parent!.isTransposed) { - return performTransposedLegendToggleAnimation(series, segmentRect, - oldSegmentRect, oldSeriesVisible, animationFactor, borderRadius); + return performTransposedLegendToggleAnimation( + series, + segmentRect, + oldSegmentRect, + oldSeriesVisible, + animationFactor, + borderRadius, + ); } final RenderCartesianChartPlotArea plotArea = series.parent!; @@ -2190,12 +2515,14 @@ RRect performLegendToggleAnimation( final double newRight = segmentRect.right; final double newLeft = segmentRect.left; - right = oldRight > newRight - ? oldRight + (animationFactor * (newRight - oldRight)) - : oldRight - (animationFactor * (oldRight - newRight)); - left = oldLeft > newLeft - ? oldLeft - (animationFactor * (oldLeft - newLeft)) - : oldLeft + (animationFactor * (newLeft - oldLeft)); + right = + oldRight > newRight + ? oldRight + (animationFactor * (newRight - oldRight)) + : oldRight - (animationFactor * (oldRight - newRight)); + left = + oldLeft > newLeft + ? oldLeft - (animationFactor * (oldLeft - newLeft)) + : oldLeft + (animationFactor * (newLeft - oldLeft)); width = right - left; } else { final bool isInversed = series.xAxis!.isInversed; @@ -2263,12 +2590,14 @@ RRect performTransposedLegendToggleAnimation( final double newBottom = segmentRect.bottom; final double newTop = segmentRect.top; - bottom = oldBottom > newBottom - ? oldBottom + (animationFactor * (newBottom - oldBottom)) - : oldBottom - (animationFactor * (oldBottom - newBottom)); - top = oldTop > newTop - ? oldTop - (animationFactor * (oldTop - newTop)) - : oldTop + (animationFactor * (newTop - oldTop)); + bottom = + oldBottom > newBottom + ? oldBottom + (animationFactor * (newBottom - oldBottom)) + : oldBottom - (animationFactor * (oldBottom - newBottom)); + top = + oldTop > newTop + ? oldTop - (animationFactor * (oldTop - newTop)) + : oldTop + (animationFactor * (newTop - oldTop)); height = bottom - top; } else { final bool isInversed = series.xAxis!.isInversed; diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/utils/renderer_helper.dart b/packages/syncfusion_flutter_charts/lib/src/charts/utils/renderer_helper.dart index 07644c464..eb5107509 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/utils/renderer_helper.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/utils/renderer_helper.dart @@ -4,8 +4,12 @@ import 'dart:ui'; import 'enum.dart'; import 'helper.dart'; -Offset calculateExplodingCenter(double midAngle, double currentRadius, - Offset center, String explodeOffset) { +Offset calculateExplodingCenter( + double midAngle, + double currentRadius, + Offset center, + String explodeOffset, +) { final double explodeCenter = percentToValue(explodeOffset, currentRadius)!; return calculateOffset(midAngle, explodeCenter, center); } @@ -20,9 +24,15 @@ num findAngleDeviation(num innerRadius, num outerRadius, num totalAngle) { } /// Calculate arc path for circular series segment. -Path calculateArcPath(double innerRadius, double radius, Offset center, - double startAngle, double endAngle, double degree, - {bool isAnimate = false}) { +Path calculateArcPath( + double innerRadius, + double radius, + Offset center, + double startAngle, + double endAngle, + double degree, { + bool isAnimate = false, +}) { final Path path = Path(); final double startRadian = degreesToRadians(startAngle); final double endRadian = degreesToRadians(endAngle); @@ -30,45 +40,74 @@ Path calculateArcPath(double innerRadius, double radius, Offset center, if (isAnimate) { final Offset innerRadiusStartPoint = Offset( - innerRadius * cos(startRadian) + center.dx, - innerRadius * sin(startRadian) + center.dy); + innerRadius * cos(startRadian) + center.dx, + innerRadius * sin(startRadian) + center.dy, + ); path.moveTo(innerRadiusStartPoint.dx, innerRadiusStartPoint.dy); } - final Offset radiusStartPoint = Offset(radius * cos(startRadian) + center.dx, - radius * sin(startRadian) + center.dy); + final Offset radiusStartPoint = Offset( + radius * cos(startRadian) + center.dx, + radius * sin(startRadian) + center.dy, + ); // Check if the angle between startAngle and endAngle is equal to // a full circle (2 * pi radians) by rounding both values to 5 decimal // places and comparing them to avoid precision errors. - final bool isFullCircle = (endRadian - startRadian).toStringAsFixed(5) == + final bool isFullCircle = + (endRadian - startRadian).toStringAsFixed(5) == (2 * pi).toStringAsFixed(5); final double midAngle = (endRadian + startRadian) / 2; if (isFullCircle) { - path.arcTo(Rect.fromCircle(center: center, radius: radius), startRadian, - midAngle - startRadian, true); - path.arcTo(Rect.fromCircle(center: center, radius: radius), midAngle, - endRadian - midAngle, true); + path.arcTo( + Rect.fromCircle(center: center, radius: radius), + startRadian, + midAngle - startRadian, + true, + ); + path.arcTo( + Rect.fromCircle(center: center, radius: radius), + midAngle, + endRadian - midAngle, + true, + ); } else { path.lineTo(radiusStartPoint.dx, radiusStartPoint.dy); - path.arcTo(Rect.fromCircle(center: center, radius: radius), startRadian, - sweepRadian, true); + path.arcTo( + Rect.fromCircle(center: center, radius: radius), + startRadian, + sweepRadian, + true, + ); } if (isFullCircle) { - path.arcTo(Rect.fromCircle(center: center, radius: innerRadius), endRadian, - midAngle - endRadian, true); - path.arcTo(Rect.fromCircle(center: center, radius: innerRadius), midAngle, - startRadian - midAngle, true); + path.arcTo( + Rect.fromCircle(center: center, radius: innerRadius), + endRadian, + midAngle - endRadian, + true, + ); + path.arcTo( + Rect.fromCircle(center: center, radius: innerRadius), + midAngle, + startRadian - midAngle, + true, + ); } else { final Offset innerRadiusEndPoint = Offset( - innerRadius * cos(endRadian) + center.dx, - innerRadius * sin(endRadian) + center.dy); + innerRadius * cos(endRadian) + center.dx, + innerRadius * sin(endRadian) + center.dy, + ); path.lineTo(innerRadiusEndPoint.dx, innerRadiusEndPoint.dy); - path.arcTo(Rect.fromCircle(center: center, radius: innerRadius), endRadian, - startRadian - endRadian, true); + path.arcTo( + Rect.fromCircle(center: center, radius: innerRadius), + endRadian, + startRadian - endRadian, + true, + ); path.lineTo(radiusStartPoint.dx, radiusStartPoint.dy); } @@ -88,8 +127,14 @@ double calculateAngle(bool isRealTimeAnimation, int startAngle, int endAngle) { } /// Calculate rounded corners arc path. -Path calculateRoundedCornerArcPath(CornerStyle cornerStyle, double innerRadius, - double outerRadius, Offset center, double startAngle, double endAngle) { +Path calculateRoundedCornerArcPath( + CornerStyle cornerStyle, + double innerRadius, + double outerRadius, + Offset center, + double startAngle, + double endAngle, +) { final Path path = Path(); if (cornerStyle == CornerStyle.startCurve || @@ -98,25 +143,33 @@ Path calculateRoundedCornerArcPath(CornerStyle cornerStyle, double innerRadius, final Offset endPoint = calculateOffset(startAngle, outerRadius, center); path.moveTo(startPoint.dx, startPoint.dy); - path.arcToPoint(endPoint, - radius: Radius.circular((innerRadius - outerRadius).abs() / 2)); + path.arcToPoint( + endPoint, + radius: Radius.circular((innerRadius - outerRadius).abs() / 2), + ); } - path.addArc(Rect.fromCircle(center: center, radius: outerRadius), - degreesToRadians(startAngle), degreesToRadians(endAngle - startAngle)); + path.addArc( + Rect.fromCircle(center: center, radius: outerRadius), + degreesToRadians(startAngle), + degreesToRadians(endAngle - startAngle), + ); if (cornerStyle == CornerStyle.endCurve || cornerStyle == CornerStyle.bothCurve) { final Offset endPoint = calculateOffset(endAngle, innerRadius, center); - path.arcToPoint(endPoint, - radius: Radius.circular((innerRadius - outerRadius).abs() / 2)); + path.arcToPoint( + endPoint, + radius: Radius.circular((innerRadius - outerRadius).abs() / 2), + ); } path.arcTo( - Rect.fromCircle(center: center, radius: innerRadius), - degreesToRadians(endAngle), - degreesToRadians(startAngle) - degreesToRadians(endAngle), - false); + Rect.fromCircle(center: center, radius: innerRadius), + degreesToRadians(endAngle), + degreesToRadians(startAngle) - degreesToRadians(endAngle), + false, + ); if (cornerStyle == CornerStyle.endCurve) { path.close(); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/utils/typedef.dart b/packages/syncfusion_flutter_charts/lib/src/charts/utils/typedef.dart index d72e76b30..7347c4ee1 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/utils/typedef.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/utils/typedef.dart @@ -11,48 +11,50 @@ import '../utils/enum.dart'; typedef ChartTooltipCallback = void Function(TooltipArgs tooltipArgs); /// Returns the ActualRangeChangedArgs. -typedef ChartActualRangeChangedCallback = void Function( - ActualRangeChangedArgs rangeChangedArgs); +typedef ChartActualRangeChangedCallback = + void Function(ActualRangeChangedArgs rangeChangedArgs); /// Signature for the [axisLabelFormatter] callback that returns /// [ChartAxisLabel] class value to customize the axis label text and style. -typedef ChartLabelFormatterCallback = ChartAxisLabel Function( - AxisLabelRenderDetails axisLabelRenderArgs); +typedef ChartLabelFormatterCallback = + ChartAxisLabel Function(AxisLabelRenderDetails axisLabelRenderArgs); /// Signature for the [multiLevelLabelFormatter] callback that returns /// [ChartAxisLabel]. -typedef MultiLevelLabelFormatterCallback = ChartAxisLabel Function( - MultiLevelLabelRenderDetails multiLevelLabelRenderArgs); +typedef MultiLevelLabelFormatterCallback = + ChartAxisLabel Function( + MultiLevelLabelRenderDetails multiLevelLabelRenderArgs, + ); /// Returns the DataLabelRenderArgs. -typedef ChartDataLabelRenderCallback = void Function( - DataLabelRenderArgs dataLabelArgs); +typedef ChartDataLabelRenderCallback = + void Function(DataLabelRenderArgs dataLabelArgs); /// Returns the LegendRenderArgs. -typedef ChartLegendRenderCallback = void Function( - LegendRenderArgs legendRenderArgs); +typedef ChartLegendRenderCallback = + void Function(LegendRenderArgs legendRenderArgs); /// Returns the Trendline args -typedef ChartTrendlineRenderCallback = void Function( - TrendlineRenderParams trendlineRenderParams); +typedef ChartTrendlineRenderCallback = + void Function(TrendlineRenderParams trendlineRenderParams); ///Returns the TrackballArgs. typedef ChartTrackballCallback = void Function(TrackballArgs trackballArgs); /// Returns the CrosshairRenderArgs -typedef ChartCrosshairCallback = void Function( - CrosshairRenderArgs crosshairArgs); +typedef ChartCrosshairCallback = + void Function(CrosshairRenderArgs crosshairArgs); /// Returns the ZoomPanArgs. typedef ChartZoomingCallback = void Function(ZoomPanArgs zoomingArgs); /// Returns the ChartPointDetails. -typedef ChartPointInteractionCallback = void Function( - ChartPointDetails pointInteractionDetails); +typedef ChartPointInteractionCallback = + void Function(ChartPointDetails pointInteractionDetails); /// Returns the AxisLabelTapArgs. -typedef ChartAxisLabelTapCallback = void Function( - AxisLabelTapArgs axisLabelTapArgs); +typedef ChartAxisLabelTapCallback = + void Function(AxisLabelTapArgs axisLabelTapArgs); /// Returns the LegendTapArgs. typedef ChartLegendTapCallback = void Function(LegendTapArgs legendTapArgs); @@ -61,33 +63,40 @@ typedef ChartLegendTapCallback = void Function(LegendTapArgs legendTapArgs); typedef ChartSelectionCallback = void Function(SelectionArgs selectionArgs); /// Returns the offset. -typedef ChartTouchInteractionCallback = void Function( - ChartTouchInteractionArgs tapArgs); +typedef ChartTouchInteractionCallback = + void Function(ChartTouchInteractionArgs tapArgs); /// Returns the IndicatorRenderArgs. -typedef ChartIndicatorRenderCallback = TechnicalIndicatorRenderDetails Function( - IndicatorRenderParams indicatorRenderParams); +typedef ChartIndicatorRenderCallback = + TechnicalIndicatorRenderDetails Function( + IndicatorRenderParams indicatorRenderParams, + ); /// Returns the MarkerRenderArgs. typedef ChartMarkerRenderCallback = void Function(MarkerRenderArgs markerArgs); /// Returns a widget which can be used to load more data to chart. /// called on dragging and when the visible range reaches the end. -typedef LoadMoreViewBuilderCallback = Widget Function( - BuildContext context, ChartSwipeDirection direction); +typedef LoadMoreViewBuilderCallback = + Widget Function(BuildContext context, ChartSwipeDirection direction); /// A callback which gets called on swiping over plot area. -typedef ChartPlotAreaSwipeCallback = void Function( - ChartSwipeDirection direction); +typedef ChartPlotAreaSwipeCallback = + void Function(ChartSwipeDirection direction); /// Called when the series renderer is created. -typedef SeriesRendererCreatedCallback = void Function( - ChartSeriesController controller); +typedef SeriesRendererCreatedCallback = + void Function(ChartSeriesController controller); /// Returns the widget. -typedef ChartDataLabelTemplateBuilder = Widget Function( - T data, CartesianChartPoint point, int pointIndex, - {int seriesIndex, CartesianSeries series}); +typedef ChartDataLabelTemplateBuilder = + Widget Function( + T data, + CartesianChartPoint point, + int pointIndex, { + int seriesIndex, + CartesianSeries series, + }); /// typedef common for all the chart types /// @@ -100,12 +109,13 @@ typedef DataLabelTapCallback = void Function(DataLabelTapDetails onTapArgs); /// /// Customize the appearance of legend items with your template by /// using legendItemBuilder property of legend. -typedef LegendItemBuilder = Widget Function( - String legendText, - ChartSeries? series, - ChartPoint point, - int seriesIndex, -); +typedef LegendItemBuilder = + Widget Function( + String legendText, + ChartSeries? series, + ChartPoint point, + int seriesIndex, + ); /// Maps the index value. typedef ChartIndexedValueMapper = R? Function(int index); @@ -123,49 +133,55 @@ typedef ChartValueMapper = R? Function(T datum, int index); /// rect - Rect value of the current data point slice /// /// color - Color of the current data point -typedef ChartShaderMapper = Shader Function( - T datum, int index, Color color, Rect rect); +typedef ChartShaderMapper = + Shader Function(T datum, int index, Color color, Rect rect); /// Returns the widget. -typedef ChartWidgetBuilder = Widget Function(T data, ChartPoint point, - ChartSeries series, int pointIndex, int seriesIndex); +typedef ChartWidgetBuilder = + Widget Function( + T data, + ChartPoint point, + ChartSeries series, + int pointIndex, + int seriesIndex, + ); /// Returns the widget as a template of trackball -typedef ChartTrackballBuilder = Widget Function( - BuildContext context, TrackballDetails trackballDetails); +typedef ChartTrackballBuilder = + Widget Function(BuildContext context, TrackballDetails trackballDetails); /// Custom renderer for series -typedef ChartSeriesRendererFactory = ChartSeriesRenderer Function( - ChartSeries series); +typedef ChartSeriesRendererFactory = + ChartSeriesRenderer Function(ChartSeries series); /// typedef belongs SfCircularChart /// Returns the LegendRenderArgs. -typedef CircularLegendRenderCallback = void Function( - LegendRenderArgs legendRenderArgs); +typedef CircularLegendRenderCallback = + void Function(LegendRenderArgs legendRenderArgs); /// Returns the TooltipArgs. typedef CircularTooltipCallback = void Function(TooltipArgs tooltipArgs); /// Returns the DataLabelRenderArgs. -typedef CircularDataLabelRenderCallback = void Function( - DataLabelRenderArgs dataLabelArgs); +typedef CircularDataLabelRenderCallback = + void Function(DataLabelRenderArgs dataLabelArgs); /// Returns the SelectionArgs. typedef CircularSelectionCallback = void Function(SelectionArgs selectionArgs); /// Returns the offset. -typedef CircularTouchInteractionCallback = void Function( - ChartTouchInteractionArgs tapArgs); +typedef CircularTouchInteractionCallback = + void Function(ChartTouchInteractionArgs tapArgs); /// Signature for the callback that returns the shader value to override the /// fill color of the data points. -typedef CircularShaderCallback = Shader Function( - ChartShaderDetails chartShaderDetails); +typedef CircularShaderCallback = + Shader Function(ChartShaderDetails chartShaderDetails); /// Return the controller for circular series. -typedef CircularSeriesRendererCreatedCallback = void Function( - CircularSeriesController controller); +typedef CircularSeriesRendererCreatedCallback = + void Function(CircularSeriesController controller); // typedef belongs to SfFunnelChart @@ -176,19 +192,19 @@ typedef FunnelLegendRenderCallback = void Function(LegendRenderArgs args); typedef FunnelTooltipCallback = void Function(TooltipArgs tooltipArgs); /// Returns the DataLabelRenderArgs. -typedef FunnelDataLabelRenderCallback = void Function( - DataLabelRenderArgs dataLabelArgs); +typedef FunnelDataLabelRenderCallback = + void Function(DataLabelRenderArgs dataLabelArgs); /// Returns the SelectionArgs. typedef FunnelSelectionCallback = void Function(SelectionArgs selectionArgs); /// Returns the offset. -typedef FunnelTouchInteractionCallback = void Function( - ChartTouchInteractionArgs tapArgs); +typedef FunnelTouchInteractionCallback = + void Function(ChartTouchInteractionArgs tapArgs); /// Called when the renderer for the funnel series is created. -typedef FunnelSeriesRendererCreatedCallback = void Function( - FunnelSeriesController controller); +typedef FunnelSeriesRendererCreatedCallback = + void Function(FunnelSeriesController controller); // typedef belongs to SfPyramidChart @@ -199,23 +215,23 @@ typedef PyramidLegendRenderCallback = void Function(LegendRenderArgs args); typedef PyramidTooltipCallback = void Function(TooltipArgs tooltipArgs); /// Returns the DataLabelRenderArgs. -typedef PyramidDataLabelRenderCallback = void Function( - DataLabelRenderArgs dataLabelArgs); +typedef PyramidDataLabelRenderCallback = + void Function(DataLabelRenderArgs dataLabelArgs); /// Returns the SelectionArgs. typedef PyramidSelectionCallback = void Function(SelectionArgs selectionArgs); /// Returns the Offset. -typedef PyramidTouchInteractionCallback = void Function( - ChartTouchInteractionArgs tapArgs); +typedef PyramidTouchInteractionCallback = + void Function(ChartTouchInteractionArgs tapArgs); /// Called when the pyramid series is created. -typedef PyramidSeriesRendererCreatedCallback = void Function( - PyramidSeriesController controller); +typedef PyramidSeriesRendererCreatedCallback = + void Function(PyramidSeriesController controller); /// Callback definition for error bar event. -typedef ChartErrorBarRenderCallback = void Function( - ErrorBarRenderDetails errorBarRenderDetails); +typedef ChartErrorBarRenderCallback = + void Function(ErrorBarRenderDetails errorBarRenderDetails); //// Callback definition for cartesian shader events. typedef CartesianShaderCallback = Shader Function(ShaderDetails shaderDetails); diff --git a/packages/syncfusion_flutter_charts/lib/src/charts/utils/zooming_helper.dart b/packages/syncfusion_flutter_charts/lib/src/charts/utils/zooming_helper.dart index 3d3d006dd..98ae57756 100644 --- a/packages/syncfusion_flutter_charts/lib/src/charts/utils/zooming_helper.dart +++ b/packages/syncfusion_flutter_charts/lib/src/charts/utils/zooming_helper.dart @@ -13,16 +13,25 @@ import 'helper.dart'; /// Returns the tooltip label on zooming. String tooltipValue( - Offset position, RenderChartAxis axis, Rect plotAreaBounds) { - final num value = axis.isVertical - ? axis.pixelToPoint(axis.paintBounds, position.dx, position.dy) - : axis.pixelToPoint(axis.paintBounds, position.dx - plotAreaBounds.left, - position.dy - plotAreaBounds.top); + Offset position, + RenderChartAxis axis, + Rect plotAreaBounds, +) { + final num value = + axis.isVertical + ? axis.pixelToPoint(axis.paintBounds, position.dx, position.dy) + : axis.pixelToPoint( + axis.paintBounds, + position.dx - plotAreaBounds.left, + position.dy - plotAreaBounds.top, + ); dynamic result = interactiveTooltipLabel(value, axis); if (axis.interactiveTooltip.format != null) { - final String stringValue = - axis.interactiveTooltip.format!.replaceAll('{value}', result); + final String stringValue = axis.interactiveTooltip.format!.replaceAll( + '{value}', + result, + ); result = stringValue; } return result.toString(); @@ -43,31 +52,45 @@ dynamic interactiveTooltipLabel(dynamic value, RenderChartAxis axis) { final num index = value < 0 ? 0 : value; final List labels = axis.labels; final int labelsLength = labels.length; - final int milliseconds = labels[(index.round() >= labelsLength - ? (index.round() > labelsLength ? labelsLength - 1 : index - 1) - : index) - .round()]; + final int milliseconds = + labels[(index.round() >= labelsLength + ? (index.round() > labelsLength ? labelsLength - 1 : index - 1) + : index) + .round()]; final num interval = axis.visibleRange!.minimum.ceil(); final num previousInterval = labels.isNotEmpty ? labels[labelsLength - 1] : interval; - final DateFormat dateFormat = axis.dateFormat ?? + final DateFormat dateFormat = + axis.dateFormat ?? dateTimeCategoryAxisLabelFormat( - axis, interval.toInt(), previousInterval.toInt()); + axis, + interval.toInt(), + previousInterval.toInt(), + ); return dateFormat.format(DateTime.fromMillisecondsSinceEpoch(milliseconds)); } else if (axis is RenderDateTimeAxis) { final num interval = axis.visibleRange!.minimum.ceil(); final List visibleLabels = axis.visibleLabels; - final num previousInterval = visibleLabels.isNotEmpty - ? visibleLabels[visibleLabels.length - 1].value - : interval; - final DateFormat dateFormat = axis.dateFormat ?? + final num previousInterval = + visibleLabels.isNotEmpty + ? visibleLabels[visibleLabels.length - 1].value + : interval; + final DateFormat dateFormat = + axis.dateFormat ?? dateTimeAxisLabelFormat( - axis, interval.toInt(), previousInterval.toInt()); - return dateFormat - .format(DateTime.fromMillisecondsSinceEpoch(value.toInt())); + axis, + interval.toInt(), + previousInterval.toInt(), + ); + return dateFormat.format( + DateTime.fromMillisecondsSinceEpoch(value.toInt()), + ); } else if (axis is RenderLogarithmicAxis) { return logAxisLabel( - axis, axis.toPow(value), axis.interactiveTooltip.decimalPlaces); + axis, + axis.toPow(value), + axis.interactiveTooltip.decimalPlaces, + ); } else if (axis is RenderNumericAxis) { return numericAxisLabel(axis, value, axis.interactiveTooltip.decimalPlaces); } else { @@ -76,17 +99,17 @@ dynamic interactiveTooltipLabel(dynamic value, RenderChartAxis axis) { } /// Validate the rect by comparing small and large rect. -Rect validateRect( - Rect largeRect, Rect smallRect, String axisPosition) => +Rect validateRect(Rect largeRect, Rect smallRect, String axisPosition) => Rect.fromLTRB( - axisPosition == 'left' - ? (smallRect.left - (largeRect.width - smallRect.width)) - : smallRect.left, - smallRect.top, - axisPosition == 'right' - ? (smallRect.right + (largeRect.width - smallRect.width)) - : smallRect.right, - smallRect.bottom); + axisPosition == 'left' + ? (smallRect.left - (largeRect.width - smallRect.width)) + : smallRect.left, + smallRect.top, + axisPosition == 'right' + ? (smallRect.right + (largeRect.width - smallRect.width)) + : smallRect.right, + smallRect.bottom, + ); /// Calculate the interactive tooltip rect, based on the zoomed axis position. Rect calculateRect(RenderChartAxis axis, Offset position, Size labelSize) { @@ -117,81 +140,125 @@ Rect calculateRect(RenderChartAxis axis, Offset position, Size labelSize) { /// To draw connectors. void drawConnector( - Canvas canvas, - Paint connectorLinePaint, - RRect startTooltipRect, - RRect endTooltipRect, - Offset startPosition, - Offset endPosition, - RenderChartAxis axis) { + Canvas canvas, + Paint connectorLinePaint, + RRect startTooltipRect, + RRect endTooltipRect, + Offset startPosition, + Offset endPosition, + RenderChartAxis axis, +) { final InteractiveTooltip tooltip = axis.interactiveTooltip; if (!axis.isVertical && !axis.opposedPosition) { - startPosition = - Offset(startPosition.dx, startTooltipRect.top - tooltip.arrowLength); - endPosition = - Offset(endPosition.dx, endTooltipRect.top - tooltip.arrowLength); + startPosition = Offset( + startPosition.dx, + startTooltipRect.top - tooltip.arrowLength, + ); + endPosition = Offset( + endPosition.dx, + endTooltipRect.top - tooltip.arrowLength, + ); } else if (!axis.isVertical && axis.opposedPosition) { - startPosition = - Offset(startPosition.dx, startTooltipRect.bottom + tooltip.arrowLength); - endPosition = - Offset(endPosition.dx, endTooltipRect.bottom + tooltip.arrowLength); + startPosition = Offset( + startPosition.dx, + startTooltipRect.bottom + tooltip.arrowLength, + ); + endPosition = Offset( + endPosition.dx, + endTooltipRect.bottom + tooltip.arrowLength, + ); } else if (axis.isVertical && !axis.opposedPosition) { - startPosition = - Offset(startTooltipRect.right + tooltip.arrowLength, startPosition.dy); - endPosition = - Offset(endTooltipRect.right + tooltip.arrowLength, endPosition.dy); + startPosition = Offset( + startTooltipRect.right + tooltip.arrowLength, + startPosition.dy, + ); + endPosition = Offset( + endTooltipRect.right + tooltip.arrowLength, + endPosition.dy, + ); } else { - startPosition = - Offset(startTooltipRect.left - tooltip.arrowLength, startPosition.dy); - endPosition = - Offset(endTooltipRect.left - tooltip.arrowLength, endPosition.dy); + startPosition = Offset( + startTooltipRect.left - tooltip.arrowLength, + startPosition.dy, + ); + endPosition = Offset( + endTooltipRect.left - tooltip.arrowLength, + endPosition.dy, + ); } - drawDashedPath(canvas, connectorLinePaint, startPosition, endPosition, - tooltip.connectorLineDashArray); + drawDashedPath( + canvas, + connectorLinePaint, + startPosition, + endPosition, + tooltip.connectorLineDashArray, + ); } /// To draw tooltip. RRect calculateTooltipRect( - Canvas canvas, - Paint fillPaint, - Paint strokePaint, - Path path, - Offset position, - Rect labelRect, - RRect? rect, - String value, - Size labelSize, - Rect plotAreaBound, - TextStyle textStyle, - RenderChartAxis axis, - Offset plotAreaOffset) { + Canvas canvas, + Paint fillPaint, + Paint strokePaint, + Path path, + Offset position, + Rect labelRect, + RRect? rect, + String value, + Size labelSize, + Rect plotAreaBound, + TextStyle textStyle, + RenderChartAxis axis, + Offset plotAreaOffset, +) { final Offset parentDataOffset = (axis.parentData! as BoxParentData).offset; - final Offset axisOffset = - parentDataOffset.translate(-plotAreaOffset.dx, -plotAreaOffset.dy); + final Offset axisOffset = parentDataOffset.translate( + -plotAreaOffset.dx, + -plotAreaOffset.dy, + ); final Rect axisRect = axisOffset & axis.size; labelRect = validateRectBounds(labelRect, axisRect); - labelRect = axis.isVertical - ? validateRectYPosition(labelRect, plotAreaBound) - : validateRectXPosition(labelRect, plotAreaBound); + labelRect = + axis.isVertical + ? validateRectYPosition(labelRect, plotAreaBound) + : validateRectXPosition(labelRect, plotAreaBound); path.reset(); rect = RRect.fromRectAndRadius( - labelRect, Radius.circular(axis.interactiveTooltip.borderRadius)); + labelRect, + Radius.circular(axis.interactiveTooltip.borderRadius), + ); path.addRRect(rect); calculateNeckPositions( - canvas, fillPaint, strokePaint, path, position, rect, axis); + canvas, + fillPaint, + strokePaint, + path, + position, + rect, + axis, + ); drawText( canvas, value, - Offset((rect.left + rect.width / 2) - labelSize.width / 2, - (rect.top + rect.height / 2) - labelSize.height / 2), + Offset( + (rect.left + rect.width / 2) - labelSize.width / 2, + (rect.top + rect.height / 2) - labelSize.height / 2, + ), textStyle, ); return rect; } /// To calculate tooltip neck positions. -void calculateNeckPositions(Canvas canvas, Paint fillPaint, Paint strokePaint, - Path path, Offset position, RRect rect, RenderChartAxis axis) { +void calculateNeckPositions( + Canvas canvas, + Paint fillPaint, + Paint strokePaint, + Path path, + Offset position, + RRect rect, + RenderChartAxis axis, +) { final InteractiveTooltip tooltip = axis.interactiveTooltip; double x1, x2, x3, x4, y1, y2, y3, y4; if (!axis.isVertical && !axis.opposedPosition) { @@ -232,7 +299,19 @@ void calculateNeckPositions(Canvas canvas, Paint fillPaint, Paint strokePaint, y4 = position.dy; } drawTooltipArrowhead( - canvas, path, fillPaint, strokePaint, x1, y1, x2, y2, x3, y3, x4, y4); + canvas, + path, + fillPaint, + strokePaint, + x1, + y1, + x2, + y2, + x3, + y3, + x4, + y4, + ); } /// This method will validate whether the tooltip exceeds the screen or not. @@ -269,13 +348,18 @@ Rect validateRectYPosition(Rect labelRect, Rect axisClipRect) { Rect validatedRect = labelRect; if (labelRect.bottom >= axisClipRect.bottom) { validatedRect = Rect.fromLTRB( - labelRect.left, - labelRect.top - (labelRect.bottom - axisClipRect.bottom), - labelRect.right, - axisClipRect.bottom); + labelRect.left, + labelRect.top - (labelRect.bottom - axisClipRect.bottom), + labelRect.right, + axisClipRect.bottom, + ); } else if (labelRect.top <= axisClipRect.top) { - validatedRect = Rect.fromLTRB(labelRect.left, axisClipRect.top, - labelRect.right, labelRect.bottom + (axisClipRect.top - labelRect.top)); + validatedRect = Rect.fromLTRB( + labelRect.left, + axisClipRect.top, + labelRect.right, + labelRect.bottom + (axisClipRect.top - labelRect.top), + ); } return validatedRect; } @@ -285,34 +369,37 @@ Rect validateRectXPosition(Rect labelRect, Rect axisClipRect) { Rect validatedRect = labelRect; if (labelRect.right >= axisClipRect.right) { validatedRect = Rect.fromLTRB( - labelRect.left - (labelRect.right - axisClipRect.right), - labelRect.top, - axisClipRect.right, - labelRect.bottom); + labelRect.left - (labelRect.right - axisClipRect.right), + labelRect.top, + axisClipRect.right, + labelRect.bottom, + ); } else if (labelRect.left <= axisClipRect.left) { validatedRect = Rect.fromLTRB( - axisClipRect.left, - labelRect.top, - labelRect.right + (axisClipRect.left - labelRect.left), - labelRect.bottom); + axisClipRect.left, + labelRect.top, + labelRect.right + (axisClipRect.left - labelRect.left), + labelRect.bottom, + ); } return validatedRect; } /// Draw tooltip arrow head. void drawTooltipArrowhead( - Canvas canvas, - Path backgroundPath, - Paint fillPaint, - Paint strokePaint, - double x1, - double y1, - double x2, - double y2, - double x3, - double y3, - double x4, - double y4) { + Canvas canvas, + Path backgroundPath, + Paint fillPaint, + Paint strokePaint, + double x1, + double y1, + double x2, + double y2, + double x3, + double y3, + double x4, + double y4, +) { backgroundPath.moveTo(x1, y1); backgroundPath.lineTo(x2, y2); backgroundPath.lineTo(x3, y3); diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/marker.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/marker.dart index 5b7acfc9f..780f64217 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/marker.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/marker.dart @@ -29,13 +29,14 @@ class SparkChartMarker { /// ); /// } /// ``` - const SparkChartMarker( - {this.displayMode = SparkChartMarkerDisplayMode.none, - this.borderColor, - this.borderWidth = 2, - this.color, - this.size = 5, - this.shape = SparkChartMarkerShape.circle}); + const SparkChartMarker({ + this.displayMode = SparkChartMarkerDisplayMode.none, + this.borderColor, + this.borderWidth = 2, + this.color, + this.size = 5, + this.shape = SparkChartMarkerShape.circle, + }); /// Enables the markers in different modes. /// diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/plot_band.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/plot_band.dart index f3204306a..1781530ed 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/plot_band.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/plot_band.dart @@ -30,12 +30,13 @@ class SparkChartPlotBand { /// ); /// } /// ``` - const SparkChartPlotBand( - {this.color = const Color.fromRGBO(191, 212, 252, 0.5), - this.start, - this.end, - this.borderColor, - this.borderWidth = 0}); + const SparkChartPlotBand({ + this.color = const Color.fromRGBO(191, 212, 252, 0.5), + this.start, + this.end, + this.borderColor, + this.borderWidth = 0, + }); /// Customizes the color of the plot band. Since the plot band is rendered /// above the axis line, you can customize the color of the plot band for a diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/renderer_base.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/renderer_base.dart index c06d0d6c8..f45bf297e 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/renderer_base.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/renderer_base.dart @@ -10,29 +10,29 @@ import '../utils/helper.dart'; @immutable abstract class SfSparkChartRenderObjectWidget extends LeafRenderObjectWidget { /// Creates the render object for spark chart. - const SfSparkChartRenderObjectWidget( - {Key? key, - this.data, - this.dataCount, - this.xValueMapper, - this.yValueMapper, - this.isInversed, - this.axisCrossesAt, - this.axisLineColor, - this.axisLineWidth, - this.axisLineDashArray, - this.firstPointColor, - this.lowPointColor, - this.highPointColor, - this.lastPointColor, - this.negativePointColor, - this.color, - this.plotBand, - this.sparkChartDataDetails, - this.themeData, - this.dataPoints, - this.coordinatePoints}) - : super(key: key); + const SfSparkChartRenderObjectWidget({ + Key? key, + this.data, + this.dataCount, + this.xValueMapper, + this.yValueMapper, + this.isInversed, + this.axisCrossesAt, + this.axisLineColor, + this.axisLineWidth, + this.axisLineDashArray, + this.firstPointColor, + this.lowPointColor, + this.highPointColor, + this.lastPointColor, + this.negativePointColor, + this.color, + this.plotBand, + this.sparkChartDataDetails, + this.themeData, + this.dataPoints, + this.coordinatePoints, + }) : super(key: key); /// Specifies the data source for the series. final List? data; @@ -98,50 +98,49 @@ abstract class SfSparkChartRenderObjectWidget extends LeafRenderObjectWidget { /// Represents the RenderSparkChart class. abstract class RenderSparkChart extends RenderBox { /// Creates the render object widget. - RenderSparkChart( - { - //ignore: avoid_unused_constructor_parameters - Widget? child, - List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - double? axisLineWidth, - Color? axisLineColor, - List? axisLineDashArray, - Color? color, - Color? firstPointColor, - Color? lastPointColor, - Color? highPointColor, - Color? lowPointColor, - Color? negativePointColor, - SparkChartPlotBand? plotBand, - SparkChartDataDetails? sparkChartDataDetails, - SfSparkChartThemeData? themeData, - List? coordinatePoints, - List? dataPoints}) - : _data = data, - _dataCount = dataCount, - _xValueMapper = xValueMapper, - _yValueMapper = yValueMapper, - _isInversed = isInversed, - _axisCrossesAt = axisCrossesAt, - _axisLineWidth = axisLineWidth, - _axisLineDashArray = axisLineDashArray, - _axisLineColor = axisLineColor, - _color = color, - _firstPointColor = firstPointColor, - _lastPointColor = lastPointColor, - _highPointColor = highPointColor, - _lowPointColor = lowPointColor, - _negativePointColor = negativePointColor, - _plotBand = plotBand, - _sparkChartDataDetails = sparkChartDataDetails, - _themeData = themeData, - _dataPoints = dataPoints, - _coordinatePoints = coordinatePoints { + RenderSparkChart({ + //ignore: avoid_unused_constructor_parameters + Widget? child, + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + double? axisLineWidth, + Color? axisLineColor, + List? axisLineDashArray, + Color? color, + Color? firstPointColor, + Color? lastPointColor, + Color? highPointColor, + Color? lowPointColor, + Color? negativePointColor, + SparkChartPlotBand? plotBand, + SparkChartDataDetails? sparkChartDataDetails, + SfSparkChartThemeData? themeData, + List? coordinatePoints, + List? dataPoints, + }) : _data = data, + _dataCount = dataCount, + _xValueMapper = xValueMapper, + _yValueMapper = yValueMapper, + _isInversed = isInversed, + _axisCrossesAt = axisCrossesAt, + _axisLineWidth = axisLineWidth, + _axisLineDashArray = axisLineDashArray, + _axisLineColor = axisLineColor, + _color = color, + _firstPointColor = firstPointColor, + _lastPointColor = lastPointColor, + _highPointColor = highPointColor, + _lowPointColor = lowPointColor, + _negativePointColor = negativePointColor, + _plotBand = plotBand, + _sparkChartDataDetails = sparkChartDataDetails, + _themeData = themeData, + _dataPoints = dataPoints, + _coordinatePoints = coordinatePoints { processDataSource(); if (isInversed ?? false) { inverseDataPoints(); @@ -523,8 +522,9 @@ abstract class RenderSparkChart extends RenderBox { xValue = i.toDouble(); } else if (xValue is DateTime) { xValue = xValue.millisecondsSinceEpoch; - labelX = DateFormat.yMd() - .format(DateTime.fromMillisecondsSinceEpoch(xValue)); + labelX = DateFormat.yMd().format( + DateTime.fromMillisecondsSinceEpoch(xValue), + ); } else if (xValue is num) { labelX = _getDataLabel(xValue); } @@ -565,16 +565,18 @@ abstract class RenderSparkChart extends RenderBox { final double value = axisCrossesAt!; final double areaHeight = areaSize!.height; double? axisLineHeight = areaHeight - ((areaHeight / diffY!) * (-minY!)); - axisLineHeight = minY! < value && maxY! <= value - ? 0 - : (minY! < value && maxY! > value) + axisLineHeight = + minY! < value && maxY! <= value + ? 0 + : (minY! < value && maxY! > value) ? axisHeight : areaHeight; if (value >= minY! && value <= maxY!) { - axisLineHeight = (minY! == maxY!) - ? 0 - : areaHeight - - (areaHeight * ((value - minY!) / diffY!)).roundToDouble(); + axisLineHeight = + (minY! == maxY!) + ? 0 + : areaHeight - + (areaHeight * ((value - minY!) / diffY!)).roundToDouble(); } return axisLineHeight; } @@ -617,8 +619,18 @@ abstract class RenderSparkChart extends RenderBox { for (int i = 0; i < dataPoints!.length; i++) { x = dataPoints![i].x.toDouble(); y = dataPoints![i].y.toDouble(); - visiblePoint = transformToCoordinatePoint(minX!, maxX!, minY!, maxY!, - diffX!, diffY!, areaSize!, x, y, dataPoints!.length); + visiblePoint = transformToCoordinatePoint( + minX!, + maxX!, + minY!, + maxY!, + diffX!, + diffY!, + areaSize!, + x, + y, + dataPoints!.length, + ); coordinatePoints!.add(visiblePoint); } coordinatePoints = sortScreenCoordinatePoints(coordinatePoints!); @@ -635,14 +647,16 @@ abstract class RenderSparkChart extends RenderBox { } final double height = areaSize!.height; - final double? start = plotBand == null - ? 0 - : (plotBand!.start ?? minY!) < minY! + final double? start = + plotBand == null + ? 0 + : (plotBand!.start ?? minY!) < minY! ? minY : (plotBand!.start ?? minY); - final double? end = plotBand == null - ? 0 - : (plotBand!.end ?? maxY!) > maxY! + final double? end = + plotBand == null + ? 0 + : (plotBand!.end ?? maxY!) > maxY! ? maxY : (plotBand!.end ?? maxY); plotBandStartHeight = height - ((height / diffY!) * (start! - minY!)); @@ -657,10 +671,11 @@ abstract class RenderSparkChart extends RenderBox { final double x2 = offset.dx + areaSize!.width; final Offset point1 = Offset(x1, y1); final Offset point2 = Offset(x2, y1); - final Paint paint = Paint() - ..strokeWidth = axisLineWidth! - ..style = PaintingStyle.stroke - ..color = axisLineColor!; + final Paint paint = + Paint() + ..strokeWidth = axisLineWidth! + ..style = PaintingStyle.stroke + ..color = axisLineColor!; if (axisLineDashArray != null && axisLineDashArray!.isNotEmpty) { drawDashedPath(canvas, paint, point1, point2, axisLineDashArray); } else { @@ -680,30 +695,35 @@ abstract class RenderSparkChart extends RenderBox { if (plotBandStartHeight != plotBandEndHeight) { final Paint paint = Paint()..color = plotBand!.color; final Rect plotBandRect = Rect.fromLTRB( - offset.dx, - offset.dy + plotBandStartHeight!, - offset.dx + areaSize!.width, - offset.dy + plotBandEndHeight!); + offset.dx, + offset.dy + plotBandStartHeight!, + offset.dx + areaSize!.width, + offset.dy + plotBandEndHeight!, + ); if (plotBandRect.top >= sparkChartAreaRect!.top && plotBandRect.bottom <= sparkChartAreaRect!.bottom) { canvas.drawRect(plotBandRect, paint); if (plotBand!.borderColor != Colors.transparent && plotBand!.borderWidth > 0) { - final Paint borderPaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = plotBand!.borderWidth - ..color = plotBand!.borderColor!; + final Paint borderPaint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = plotBand!.borderWidth + ..color = plotBand!.borderColor!; canvas.drawRect(plotBandRect, borderPaint); } } } else { - final Paint paint = Paint() - ..color = plotBand!.color - ..style = PaintingStyle.stroke - ..strokeWidth = 3; + final Paint paint = + Paint() + ..color = plotBand!.color + ..style = PaintingStyle.stroke + ..strokeWidth = 3; final Offset point1 = Offset(offset.dx, offset.dy + plotBandStartHeight!); - final Offset point2 = - Offset(offset.dx + areaSize!.width, offset.dy + plotBandStartHeight!); + final Offset point2 = Offset( + offset.dx + areaSize!.width, + offset.dy + plotBandStartHeight!, + ); canvas.drawLine(point1, point2, paint); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_area_renderer.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_area_renderer.dart index efe98f075..3d7545848 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_area_renderer.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_area_renderer.dart @@ -38,27 +38,28 @@ class SfSparkAreaChartRenderObjectWidget List? coordinatePoints, List? dataPoints, }) : super( - key: key, - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lowPointColor: lowPointColor, - highPointColor: highPointColor, - lastPointColor: lastPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - dataPoints: dataPoints, - coordinatePoints: coordinatePoints); + key: key, + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lowPointColor: lowPointColor, + highPointColor: highPointColor, + lastPointColor: lastPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + dataPoints: dataPoints, + coordinatePoints: coordinatePoints, + ); /// Specifies the area chart border width. final double? borderWidth; @@ -78,38 +79,40 @@ class SfSparkAreaChartRenderObjectWidget @override RenderObject createRenderObject(BuildContext context) { return _RenderSparkAreaChart( - dataCount: dataCount, - data: data, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - borderColor: borderColor, - borderWidth: borderWidth, - marker: marker, - labelDisplayMode: labelDisplayMode, - labelStyle: labelStyle, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - dataPoints: dataPoints, - coordinatePoints: coordinatePoints); + dataCount: dataCount, + data: data, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + borderColor: borderColor, + borderWidth: borderWidth, + marker: marker, + labelDisplayMode: labelDisplayMode, + labelStyle: labelStyle, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + dataPoints: dataPoints, + coordinatePoints: coordinatePoints, + ); } @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderSparkAreaChart renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderSparkAreaChart renderObject, + ) { renderObject ..dataCount = dataCount ..data = data @@ -141,58 +144,59 @@ class SfSparkAreaChartRenderObjectWidget /// Represents the render spark area chart class. class _RenderSparkAreaChart extends RenderSparkChart { /// Creates the render object widget. - _RenderSparkAreaChart( - {List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - double? axisLineWidth, - Color? axisLineColor, - List? axisLineDashArray, - Color? color, - Color? firstPointColor, - Color? lastPointColor, - Color? highPointColor, - Color? lowPointColor, - Color? negativePointColor, - SparkChartPlotBand? plotBand, - double? borderWidth, - Color? borderColor, - SparkChartMarker? marker, - SparkChartLabelDisplayMode? labelDisplayMode, - TextStyle? labelStyle, - SparkChartDataDetails? sparkChartDataDetails, - SfSparkChartThemeData? themeData, - List? coordinatePoints, - List? dataPoints}) - : _borderWidth = borderWidth, - _borderColor = borderColor, - _marker = marker, - _labelDisplayMode = labelDisplayMode, - _labelStyle = labelStyle, - super( - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineWidth: axisLineWidth, - axisLineColor: axisLineColor, - axisLineDashArray: axisLineDashArray, - color: color, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + _RenderSparkAreaChart({ + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + double? axisLineWidth, + Color? axisLineColor, + List? axisLineDashArray, + Color? color, + Color? firstPointColor, + Color? lastPointColor, + Color? highPointColor, + Color? lowPointColor, + Color? negativePointColor, + SparkChartPlotBand? plotBand, + double? borderWidth, + Color? borderColor, + SparkChartMarker? marker, + SparkChartLabelDisplayMode? labelDisplayMode, + TextStyle? labelStyle, + SparkChartDataDetails? sparkChartDataDetails, + SfSparkChartThemeData? themeData, + List? coordinatePoints, + List? dataPoints, + }) : _borderWidth = borderWidth, + _borderColor = borderColor, + _marker = marker, + _labelDisplayMode = labelDisplayMode, + _labelStyle = labelStyle, + super( + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineWidth: axisLineWidth, + axisLineColor: axisLineColor, + axisLineDashArray: axisLineDashArray, + color: color, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Defines the border width. double? _borderWidth; @@ -274,8 +278,9 @@ class _RenderSparkAreaChart extends RenderSparkChart { void processDataSource() { super.processDataSource(); if (dataPoints != null && dataPoints!.isNotEmpty) { - final List temp = - List.from(dataPoints!); + final List temp = List.from( + dataPoints!, + ); final List tempDataLabels = List.from(dataLabels!); dataLabels!.clear(); dataPoints!.clear(); @@ -284,8 +289,10 @@ class _RenderSparkAreaChart extends RenderSparkChart { point1.labelY = temp[0].labelY; dataPoints!.add(point1); dataPoints!.addAll(temp); - final SparkChartPoint point2 = - SparkChartPoint(x: temp[temp.length - 1].x, y: minY!); + final SparkChartPoint point2 = SparkChartPoint( + x: temp[temp.length - 1].x, + y: minY!, + ); point2.labelX = temp[temp.length - 1].labelX; point2.labelY = temp[temp.length - 1].labelY; dataPoints!.add(point2); @@ -297,9 +304,10 @@ class _RenderSparkAreaChart extends RenderSparkChart { /// Render area series. void _renderAreaSeries(Canvas canvas, Offset offset) { - final Paint paint = Paint() - ..color = color! - ..style = PaintingStyle.fill; + final Paint paint = + Paint() + ..color = color! + ..style = PaintingStyle.fill; final Path path = Path(); Size size; _highPoint = coordinatePoints![0].dy; @@ -315,13 +323,17 @@ class _RenderSparkAreaChart extends RenderSparkChart { } if (i == 0) { - path.moveTo(offset.dx + coordinatePoints![i].dx, - offset.dy + coordinatePoints![i].dy); + path.moveTo( + offset.dx + coordinatePoints![i].dx, + offset.dy + coordinatePoints![i].dy, + ); } if (i < coordinatePoints!.length - 1) { - path.lineTo(offset.dx + coordinatePoints![i + 1].dx, - offset.dy + coordinatePoints![i + 1].dy); + path.lineTo( + offset.dx + coordinatePoints![i + 1].dx, + offset.dy + coordinatePoints![i + 1].dy, + ); } if (i >= 1 && @@ -330,50 +342,54 @@ class _RenderSparkAreaChart extends RenderSparkChart { labelStyle != null) { size = getTextSize(dataLabels![i], labelStyle!); dataPoints![i].dataLabelOffset = Offset( - (offset.dx + coordinatePoints![i].dx) - size.width / 2, - offset.dy + - (marker != null && - marker!.displayMode != SparkChartMarkerDisplayMode.none - ? (dataPoints![i].y > 0 - ? (coordinatePoints![i].dy - - size.height - - marker!.size / 2) - : (coordinatePoints![i].dy + marker!.size / 2)) - : dataPoints![i].y > 0 - ? (coordinatePoints![i].dy - size.height) - : (coordinatePoints![i].dy + size.height))); + (offset.dx + coordinatePoints![i].dx) - size.width / 2, + offset.dy + + (marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? (dataPoints![i].y > 0 + ? (coordinatePoints![i].dy - + size.height - + marker!.size / 2) + : (coordinatePoints![i].dy + marker!.size / 2)) + : dataPoints![i].y > 0 + ? (coordinatePoints![i].dy - size.height) + : (coordinatePoints![i].dy + size.height)), + ); if (dataPoints![i].dataLabelOffset!.dx <= offset.dx) { - dataPoints![i].dataLabelOffset = - Offset(offset.dx, dataPoints![i].dataLabelOffset!.dy); + dataPoints![i].dataLabelOffset = Offset( + offset.dx, + dataPoints![i].dataLabelOffset!.dy, + ); } if (dataPoints![i].dataLabelOffset!.dx >= offset.dx + areaSize!.width) { dataPoints![i].dataLabelOffset = Offset( - (offset.dx + areaSize!.width) - size.width, - dataPoints![i].dataLabelOffset!.dy); + (offset.dx + areaSize!.width) - size.width, + dataPoints![i].dataLabelOffset!.dy, + ); } if (dataPoints![i].dataLabelOffset!.dy <= offset.dy) { dataPoints![i].dataLabelOffset = Offset( - dataPoints![i].dataLabelOffset!.dx, - offset.dy + - (marker != null && - marker!.displayMode != - SparkChartMarkerDisplayMode.none - ? marker!.size / 2 + size.height - : size.height)); + dataPoints![i].dataLabelOffset!.dx, + offset.dy + + (marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? marker!.size / 2 + size.height + : size.height), + ); } if (dataPoints![i].dataLabelOffset!.dy >= offset.dy + areaSize!.height) { dataPoints![i].dataLabelOffset = Offset( - dataPoints![i].dataLabelOffset!.dx, - (offset.dy + areaSize!.height) - - (marker != null && - marker!.displayMode != - SparkChartMarkerDisplayMode.none - ? marker!.size / 2 + size.height - : size.height)); + dataPoints![i].dataLabelOffset!.dx, + (offset.dy + areaSize!.height) - + (marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? marker!.size / 2 + size.height + : size.height), + ); } } } @@ -389,21 +405,26 @@ class _RenderSparkAreaChart extends RenderSparkChart { /// Method to render the area series border. void _renderAreaSeriesBorder(Canvas canvas, Offset offset) { - final Paint strokePaint = Paint() - ..color = borderColor! - ..strokeWidth = borderWidth! - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = borderColor! + ..strokeWidth = borderWidth! + ..style = PaintingStyle.stroke; final Path strokePath = Path(); for (int i = 1; i < coordinatePoints!.length - 1; i++) { if (i == 1) { - strokePath.moveTo(offset.dx + coordinatePoints![i].dx, - offset.dy + coordinatePoints![i].dy); + strokePath.moveTo( + offset.dx + coordinatePoints![i].dx, + offset.dy + coordinatePoints![i].dy, + ); } if (i < coordinatePoints!.length - 2) { - strokePath.lineTo(offset.dx + coordinatePoints![i + 1].dx, - offset.dy + coordinatePoints![i + 1].dy); + strokePath.lineTo( + offset.dx + coordinatePoints![i + 1].dx, + offset.dy + coordinatePoints![i + 1].dy, + ); } } @@ -422,38 +443,40 @@ class _RenderSparkAreaChart extends RenderSparkChart { marker!.displayMode != SparkChartMarkerDisplayMode.none && marker!.borderWidth > 0) { renderMarker( - context.canvas, - offset, - marker!, - coordinatePoints!, - dataPoints!, - color!, - 'Area', - _highPoint!, - _lowPoint!, - axisCrossesAt!, - themeData!, - lowPointColor, - highPointColor, - negativePointColor, - firstPointColor, - lastPointColor); + context.canvas, + offset, + marker!, + coordinatePoints!, + dataPoints!, + color!, + 'Area', + _highPoint!, + _lowPoint!, + axisCrossesAt!, + themeData!, + lowPointColor, + highPointColor, + negativePointColor, + firstPointColor, + lastPointColor, + ); } if (labelDisplayMode != null && labelDisplayMode != SparkChartLabelDisplayMode.none) { renderDataLabel( - context.canvas, - dataLabels!, - dataPoints!, - coordinatePoints!, - labelStyle!, - labelDisplayMode!, - 'Area', - themeData!, - offset, - color!, - _highPoint!, - _lowPoint!); + context.canvas, + dataLabels!, + dataPoints!, + coordinatePoints!, + labelStyle!, + labelDisplayMode!, + 'Area', + themeData!, + offset, + color!, + _highPoint!, + _lowPoint!, + ); } } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_bar_renderer.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_bar_renderer.dart index 4147c0b32..cba5048c7 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_bar_renderer.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_bar_renderer.dart @@ -8,54 +8,55 @@ import 'renderer_base.dart'; /// Represents the render object for spark chart. class SfSparkBarChartRenderObjectWidget extends SfSparkChartRenderObjectWidget { /// Creates the render object for spark chart. - const SfSparkBarChartRenderObjectWidget( - {Key? key, - this.borderWidth, - this.borderColor, - List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - Color? axisLineColor, - double? axisLineWidth, - List? axisLineDashArray, - Color? firstPointColor, - Color? lowPointColor, - Color? highPointColor, - Color? lastPointColor, - Color? negativePointColor, - Color? color, - SparkChartPlotBand? plotBand, - this.labelDisplayMode, - this.labelStyle, - SfSparkChartThemeData? themeData, - SparkChartDataDetails? sparkChartDataDetails, - List? coordinatePoints, - List? dataPoints}) - : super( - key: key, - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lowPointColor: lowPointColor, - highPointColor: highPointColor, - lastPointColor: lastPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + const SfSparkBarChartRenderObjectWidget({ + Key? key, + this.borderWidth, + this.borderColor, + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + Color? axisLineColor, + double? axisLineWidth, + List? axisLineDashArray, + Color? firstPointColor, + Color? lowPointColor, + Color? highPointColor, + Color? lastPointColor, + Color? negativePointColor, + Color? color, + SparkChartPlotBand? plotBand, + this.labelDisplayMode, + this.labelStyle, + SfSparkChartThemeData? themeData, + SparkChartDataDetails? sparkChartDataDetails, + List? coordinatePoints, + List? dataPoints, + }) : super( + key: key, + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lowPointColor: lowPointColor, + highPointColor: highPointColor, + lastPointColor: lastPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Specifies the bar chart border width. final double? borderWidth; @@ -72,37 +73,39 @@ class SfSparkBarChartRenderObjectWidget extends SfSparkChartRenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return _RenderSparkBarChart( - dataCount: dataCount, - data: data, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - borderColor: borderColor, - borderWidth: borderWidth, - labelDisplayMode: labelDisplayMode, - labelStyle: labelStyle, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + dataCount: dataCount, + data: data, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + borderColor: borderColor, + borderWidth: borderWidth, + labelDisplayMode: labelDisplayMode, + labelStyle: labelStyle, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); } @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderSparkBarChart renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderSparkBarChart renderObject, + ) { renderObject ..isInversed = isInversed ..axisCrossesAt = axisCrossesAt @@ -133,57 +136,58 @@ class SfSparkBarChartRenderObjectWidget extends SfSparkChartRenderObjectWidget { /// Represents the render spark bar chart class. class _RenderSparkBarChart extends RenderSparkChart { /// Creates the render object widget. - _RenderSparkBarChart( - {List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - double? axisLineWidth, - Color? axisLineColor, - List? axisLineDashArray, - Color? color, - Color? firstPointColor, - Color? lastPointColor, - Color? highPointColor, - Color? lowPointColor, - Color? negativePointColor, - SparkChartPlotBand? plotBand, - double? borderWidth, - Color? borderColor, - SparkChartLabelDisplayMode? labelDisplayMode, - TextStyle? labelStyle, - SparkChartDataDetails? sparkChartDataDetails, - SfSparkChartThemeData? themeData, - List? coordinatePoints, - List? dataPoints}) - : _borderWidth = borderWidth, - _borderColor = borderColor, - _labelDisplayMode = labelDisplayMode, - _labelStyle = labelStyle, - _axisCrossesAt = axisCrossesAt, - super( - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineWidth: axisLineWidth, - axisLineColor: axisLineColor, - axisLineDashArray: axisLineDashArray, - color: color, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + _RenderSparkBarChart({ + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + double? axisLineWidth, + Color? axisLineColor, + List? axisLineDashArray, + Color? color, + Color? firstPointColor, + Color? lastPointColor, + Color? highPointColor, + Color? lowPointColor, + Color? negativePointColor, + SparkChartPlotBand? plotBand, + double? borderWidth, + Color? borderColor, + SparkChartLabelDisplayMode? labelDisplayMode, + TextStyle? labelStyle, + SparkChartDataDetails? sparkChartDataDetails, + SfSparkChartThemeData? themeData, + List? coordinatePoints, + List? dataPoints, + }) : _borderWidth = borderWidth, + _borderColor = borderColor, + _labelDisplayMode = labelDisplayMode, + _labelStyle = labelStyle, + _axisCrossesAt = axisCrossesAt, + super( + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineWidth: axisLineWidth, + axisLineColor: axisLineColor, + axisLineDashArray: axisLineDashArray, + color: color, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Defines the border width. double? _borderWidth; @@ -283,9 +287,10 @@ class _RenderSparkBarChart extends RenderSparkChart { diffX = diffX == 0 ? 1 : diffX; _segments = []; - final double xInterval = dataPoints!.length > 1 - ? dataPoints![1].x.toDouble() - dataPoints![0].x.toDouble() - : dataPoints!.length.toDouble(); + final double xInterval = + dataPoints!.length > 1 + ? dataPoints![1].x.toDouble() - dataPoints![0].x.toDouble() + : dataPoints!.length.toDouble(); const double columnSpace = 0.5; // Default space for column and winloss const double space = columnSpace * 2; final double? axisBaseValue = minY! < 0 ? minY : 0; @@ -307,12 +312,13 @@ class _RenderSparkBarChart extends RenderSparkChart { visibleXPoint = (((x - minX!) / xInterval) * (columnWidth + space)) + (space / 2); columnHeight = (areaSize!.height / diffY!) * (y - axisBaseValue); - currentColumnHeight = (y == axisBaseValue && y > axisCrossesAt) - ? ((dataPoints!.length != 1 && diffY != 1) - ? (areaSize!.height / diffY!) * axisBaseValue - : (columnHeight.toInt() | 1)) - .toDouble() - : (y == maxY && + currentColumnHeight = + (y == axisBaseValue && y > axisCrossesAt) + ? ((dataPoints!.length != 1 && diffY != 1) + ? (areaSize!.height / diffY!) * axisBaseValue + : (columnHeight.toInt() | 1)) + .toDouble() + : (y == maxY && y < axisCrossesAt && dataPoints!.length != 1 && diffY != 1) @@ -320,8 +326,12 @@ class _RenderSparkBarChart extends RenderSparkChart { : columnHeight; y2 = (areaSize!.height - currentColumnHeight).abs(); top = (y2 > axisHeight!) ? axisHeight! : y2; - rect = Rect.fromLTRB(visibleXPoint, top, visibleXPoint + columnWidth, - top + (y2 - axisHeight!).abs()); + rect = Rect.fromLTRB( + visibleXPoint, + top, + visibleXPoint + columnWidth, + top + (y2 - axisHeight!).abs(), + ); _segments!.add(rect); yPoint = y >= axisCrossesAt ? rect.top : rect.bottom; coordinatePoints!.add(Offset(visibleXPoint + columnWidth / 2, yPoint)); @@ -335,13 +345,15 @@ class _RenderSparkBarChart extends RenderSparkChart { final double minimumColumnValue = minY! < 0 ? minY! : 0; double? axisLineHeight = areaSize!.height - ((areaSize!.height / diffY!) * (-minY!)); - axisLineHeight = (minY! < 0 && maxY! <= 0) - ? 0 - : (minY! < 0 && maxY! > 0) + axisLineHeight = + (minY! < 0 && maxY! <= 0) + ? 0 + : (minY! < 0 && maxY! > 0) ? axisHeight : areaSize!.height; if (value >= minimumColumnValue && value <= maxY!) { - axisLineHeight = areaSize!.height - + axisLineHeight = + areaSize!.height - (areaSize!.height * ((value - minimumColumnValue) / diffY!)) .roundToDouble(); } @@ -373,14 +385,16 @@ class _RenderSparkBarChart extends RenderSparkChart { void _renderBarSeries(Canvas canvas, Offset offset) { Color currentColor; Paint paint; - final Paint strokePaint = Paint() - ..color = borderColor ?? Colors.transparent - ..strokeWidth = borderWidth ?? 0 - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = borderColor ?? Colors.transparent + ..strokeWidth = borderWidth ?? 0 + ..style = PaintingStyle.stroke; Size size; double yPosition; - final bool canDrawBorder = borderColor != null && + final bool canDrawBorder = + borderColor != null && borderColor != Colors.transparent && borderWidth != null && borderWidth! > 0; @@ -396,10 +410,11 @@ class _RenderSparkBarChart extends RenderSparkChart { _lowPoint = coordinatePoints![i].dy; } rect = Rect.fromLTRB( - _segments![i].left + offset.dx, - _segments![i].top + offset.dy, - _segments![i].right + offset.dx, - _segments![i].bottom + offset.dy); + _segments![i].left + offset.dx, + _segments![i].top + offset.dy, + _segments![i].right + offset.dx, + _segments![i].bottom + offset.dy, + ); if (dataPoints![i].y == maxY && highPointColor != null) { currentColor = highPointColor!; } else if (dataPoints![i].y == minY && lowPointColor != null) { @@ -424,22 +439,27 @@ class _RenderSparkBarChart extends RenderSparkChart { if (labelDisplayMode != SparkChartLabelDisplayMode.none && labelStyle != null) { size = getTextSize(dataLabels![i], labelStyle!); - yPosition = dataPoints![i].y > 0 - ? ((_segments![i].topCenter.dy + offset.dy) - size.height) - : (_segments![i].bottomCenter.dy + offset.dy); + yPosition = + dataPoints![i].y > 0 + ? ((_segments![i].topCenter.dy + offset.dy) - size.height) + : (_segments![i].bottomCenter.dy + offset.dy); dataPoints![i].dataLabelOffset = Offset( - (offset.dx + _segments![i].topCenter.dx) - size.width / 2, - yPosition); + (offset.dx + _segments![i].topCenter.dx) - size.width / 2, + yPosition, + ); if (dataPoints![i].dataLabelOffset!.dy <= offset.dy) { dataPoints![i].dataLabelOffset = Offset( - dataPoints![i].dataLabelOffset!.dx, offset.dy + size.height); + dataPoints![i].dataLabelOffset!.dx, + offset.dy + size.height, + ); } if (dataPoints![i].dataLabelOffset!.dy >= offset.dy + areaSize!.height) { dataPoints![i].dataLabelOffset = Offset( - dataPoints![i].dataLabelOffset!.dx, - (offset.dy + areaSize!.height) - size.height); + dataPoints![i].dataLabelOffset!.dx, + (offset.dy + areaSize!.height) - size.height, + ); } } } @@ -456,19 +476,20 @@ class _RenderSparkBarChart extends RenderSparkChart { if (labelDisplayMode != null && labelDisplayMode != SparkChartLabelDisplayMode.none) { renderDataLabel( - context.canvas, - dataLabels!, - dataPoints!, - coordinatePoints!, - labelStyle!, - labelDisplayMode!, - 'Bar', - themeData!, - offset, - color!, - _highPoint, - _lowPoint, - _segments); + context.canvas, + dataLabels!, + dataPoints!, + coordinatePoints!, + labelStyle!, + labelDisplayMode!, + 'Bar', + themeData!, + offset, + color!, + _highPoint, + _lowPoint, + _segments, + ); } } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_line_renderer.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_line_renderer.dart index c42e9bdd2..979b00cc1 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_line_renderer.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_line_renderer.dart @@ -10,55 +10,56 @@ import 'renderer_base.dart'; class SfSparkLineChartRenderObjectWidget extends SfSparkChartRenderObjectWidget { /// Creates the render object for spark chart. - const SfSparkLineChartRenderObjectWidget( - {Key? key, - this.width, - this.dashArray, - List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - Color? axisLineColor, - double? axisLineWidth, - List? axisLineDashArray, - Color? firstPointColor, - Color? lowPointColor, - Color? highPointColor, - Color? lastPointColor, - Color? negativePointColor, - Color? color, - SparkChartPlotBand? plotBand, - this.marker, - this.labelDisplayMode, - this.labelStyle, - SfSparkChartThemeData? themeData, - SparkChartDataDetails? sparkChartDataDetails, - List? coordinatePoints, - List? dataPoints}) - : super( - key: key, - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lowPointColor: lowPointColor, - highPointColor: highPointColor, - lastPointColor: lastPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + const SfSparkLineChartRenderObjectWidget({ + Key? key, + this.width, + this.dashArray, + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + Color? axisLineColor, + double? axisLineWidth, + List? axisLineDashArray, + Color? firstPointColor, + Color? lowPointColor, + Color? highPointColor, + Color? lastPointColor, + Color? negativePointColor, + Color? color, + SparkChartPlotBand? plotBand, + this.marker, + this.labelDisplayMode, + this.labelStyle, + SfSparkChartThemeData? themeData, + SparkChartDataDetails? sparkChartDataDetails, + List? coordinatePoints, + List? dataPoints, + }) : super( + key: key, + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lowPointColor: lowPointColor, + highPointColor: highPointColor, + lastPointColor: lastPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Specifies the line width. final double? width; @@ -78,38 +79,40 @@ class SfSparkLineChartRenderObjectWidget @override RenderObject createRenderObject(BuildContext context) { return _RenderSparkLineChart( - dataCount: dataCount, - data: data, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - width: width, - dashArray: dashArray, - marker: marker, - labelDisplayMode: labelDisplayMode, - labelStyle: labelStyle, - themeData: themeData, - sparkChartDataDetails: sparkChartDataDetails, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + dataCount: dataCount, + data: data, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + width: width, + dashArray: dashArray, + marker: marker, + labelDisplayMode: labelDisplayMode, + labelStyle: labelStyle, + themeData: themeData, + sparkChartDataDetails: sparkChartDataDetails, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); } @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderSparkLineChart renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderSparkLineChart renderObject, + ) { renderObject ..isInversed = isInversed ..axisCrossesAt = axisCrossesAt @@ -141,58 +144,59 @@ class SfSparkLineChartRenderObjectWidget /// Represents the render spark line class. class _RenderSparkLineChart extends RenderSparkChart { /// Creates the render object widget. - _RenderSparkLineChart( - {List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - double? axisLineWidth, - Color? axisLineColor, - List? axisLineDashArray, - Color? color, - Color? firstPointColor, - Color? lastPointColor, - Color? highPointColor, - Color? lowPointColor, - Color? negativePointColor, - SparkChartPlotBand? plotBand, - double? width, - List? dashArray, - SparkChartMarker? marker, - SparkChartLabelDisplayMode? labelDisplayMode, - TextStyle? labelStyle, - SparkChartDataDetails? sparkChartDataDetails, - SfSparkChartThemeData? themeData, - List? coordinatePoints, - List? dataPoints}) - : _width = width, - _dashArray = dashArray, - _marker = marker, - _labelDisplayMode = labelDisplayMode, - _labelStyle = labelStyle, - super( - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineWidth: axisLineWidth, - axisLineColor: axisLineColor, - axisLineDashArray: axisLineDashArray, - color: color, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - plotBand: plotBand, - themeData: themeData, - sparkChartDataDetails: sparkChartDataDetails, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + _RenderSparkLineChart({ + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + double? axisLineWidth, + Color? axisLineColor, + List? axisLineDashArray, + Color? color, + Color? firstPointColor, + Color? lastPointColor, + Color? highPointColor, + Color? lowPointColor, + Color? negativePointColor, + SparkChartPlotBand? plotBand, + double? width, + List? dashArray, + SparkChartMarker? marker, + SparkChartLabelDisplayMode? labelDisplayMode, + TextStyle? labelStyle, + SparkChartDataDetails? sparkChartDataDetails, + SfSparkChartThemeData? themeData, + List? coordinatePoints, + List? dataPoints, + }) : _width = width, + _dashArray = dashArray, + _marker = marker, + _labelDisplayMode = labelDisplayMode, + _labelStyle = labelStyle, + super( + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineWidth: axisLineWidth, + axisLineColor: axisLineColor, + axisLineDashArray: axisLineDashArray, + color: color, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + plotBand: plotBand, + themeData: themeData, + sparkChartDataDetails: sparkChartDataDetails, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Defines the line width. double? _width; @@ -273,10 +277,11 @@ class _RenderSparkLineChart extends RenderSparkChart { /// Render line series. void _renderLineSeries(Canvas canvas, Offset offset) { if (width != null && width! > 0) { - final Paint paint = Paint() - ..strokeWidth = width! - ..style = PaintingStyle.stroke - ..color = color!; + final Paint paint = + Paint() + ..strokeWidth = width! + ..style = PaintingStyle.stroke + ..color = color!; Size size; double yPosition; @@ -294,26 +299,34 @@ class _RenderSparkLineChart extends RenderSparkChart { } if (i < coordinatePoints!.length - 1) { - point1 = Offset(offset.dx + coordinatePoints![i].dx, - offset.dy + coordinatePoints![i].dy); - point2 = Offset(offset.dx + coordinatePoints![i + 1].dx, - offset.dy + coordinatePoints![i + 1].dy); + point1 = Offset( + offset.dx + coordinatePoints![i].dx, + offset.dy + coordinatePoints![i].dy, + ); + point2 = Offset( + offset.dx + coordinatePoints![i + 1].dx, + offset.dy + coordinatePoints![i + 1].dy, + ); drawDashedPath(canvas, paint, point1, point2, dashArray); } if (labelDisplayMode != SparkChartLabelDisplayMode.none && labelStyle != null) { size = getTextSize(dataLabels![i], labelStyle!); - yPosition = marker != null && - marker!.displayMode != SparkChartMarkerDisplayMode.none - ? (dataPoints![i].y > 0 - ? (coordinatePoints![i].dy - size.height - marker!.size / 2) - : (coordinatePoints![i].dy + marker!.size / 2)) - : dataPoints![i].y > 0 + yPosition = + marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? (dataPoints![i].y > 0 + ? (coordinatePoints![i].dy - + size.height - + marker!.size / 2) + : (coordinatePoints![i].dy + marker!.size / 2)) + : dataPoints![i].y > 0 ? (coordinatePoints![i].dy - size.height) : (coordinatePoints![i].dy); dataPoints![i].dataLabelOffset = Offset( - (offset.dx + coordinatePoints![i].dx) - size.width / 2, - offset.dy + yPosition); + (offset.dx + coordinatePoints![i].dx) - size.width / 2, + offset.dy + yPosition, + ); _positionDataLabels(dataPoints![i], size, offset); } } @@ -329,29 +342,37 @@ class _RenderSparkLineChart extends RenderSparkChart { } if (i == 0) { - path.moveTo(offset.dx + coordinatePoints![i].dx, - offset.dy + coordinatePoints![i].dy); + path.moveTo( + offset.dx + coordinatePoints![i].dx, + offset.dy + coordinatePoints![i].dy, + ); } if (i < coordinatePoints!.length - 1) { - path.lineTo(offset.dx + coordinatePoints![i + 1].dx, - offset.dy + coordinatePoints![i + 1].dy); + path.lineTo( + offset.dx + coordinatePoints![i + 1].dx, + offset.dy + coordinatePoints![i + 1].dy, + ); } if (labelDisplayMode != SparkChartLabelDisplayMode.none && labelStyle != null) { size = getTextSize(dataLabels![i], labelStyle!); - yPosition = marker != null && - marker!.displayMode != SparkChartMarkerDisplayMode.none - ? (dataPoints![i].y > 0 - ? (coordinatePoints![i].dy - size.height - marker!.size / 2) - : (coordinatePoints![i].dy + marker!.size / 2)) - : dataPoints![i].y > 0 + yPosition = + marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? (dataPoints![i].y > 0 + ? (coordinatePoints![i].dy - + size.height - + marker!.size / 2) + : (coordinatePoints![i].dy + marker!.size / 2)) + : dataPoints![i].y > 0 ? (coordinatePoints![i].dy - size.height) : (coordinatePoints![i].dy); dataPoints![i].dataLabelOffset = Offset( - (offset.dx + coordinatePoints![i].dx) - size.width / 2, - offset.dy + yPosition); + (offset.dx + coordinatePoints![i].dx) - size.width / 2, + offset.dy + yPosition, + ); _positionDataLabels(dataPoints![i], size, offset); } } @@ -362,35 +383,43 @@ class _RenderSparkLineChart extends RenderSparkChart { } void _positionDataLabels( - SparkChartPoint dataPoint, Size size, Offset offset) { + SparkChartPoint dataPoint, + Size size, + Offset offset, + ) { if (dataPoint.dataLabelOffset!.dx <= offset.dx) { - dataPoint.dataLabelOffset = - Offset(offset.dx, dataPoint.dataLabelOffset!.dy); + dataPoint.dataLabelOffset = Offset( + offset.dx, + dataPoint.dataLabelOffset!.dy, + ); } if (dataPoint.dataLabelOffset!.dx >= offset.dx + areaSize!.width) { dataPoint.dataLabelOffset = Offset( - (offset.dx + areaSize!.width) - size.width, - dataPoint.dataLabelOffset!.dy); + (offset.dx + areaSize!.width) - size.width, + dataPoint.dataLabelOffset!.dy, + ); } if (dataPoint.dataLabelOffset!.dy <= offset.dy) { dataPoint.dataLabelOffset = Offset( - dataPoint.dataLabelOffset!.dx, - offset.dy + - (marker != null && - marker!.displayMode != SparkChartMarkerDisplayMode.none - ? marker!.size / 2 + size.height - : size.height)); + dataPoint.dataLabelOffset!.dx, + offset.dy + + (marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? marker!.size / 2 + size.height + : size.height), + ); } if (dataPoint.dataLabelOffset!.dy >= offset.dy + areaSize!.height) { dataPoint.dataLabelOffset = Offset( - dataPoint.dataLabelOffset!.dx, - (offset.dy + areaSize!.height) - - (marker != null && - marker!.displayMode != SparkChartMarkerDisplayMode.none - ? marker!.size / 2 + size.height - : size.height)); + dataPoint.dataLabelOffset!.dx, + (offset.dy + areaSize!.height) - + (marker != null && + marker!.displayMode != SparkChartMarkerDisplayMode.none + ? marker!.size / 2 + size.height + : size.height), + ); } } @@ -407,38 +436,40 @@ class _RenderSparkLineChart extends RenderSparkChart { marker!.displayMode != SparkChartMarkerDisplayMode.none && marker!.borderWidth > 0) { renderMarker( - context.canvas, - offset, - marker!, - coordinatePoints!, - dataPoints!, - color!, - 'Line', - _highPoint, - _lowPoint, - axisCrossesAt!, - themeData!, - lowPointColor, - highPointColor, - negativePointColor, - firstPointColor, - lastPointColor); + context.canvas, + offset, + marker!, + coordinatePoints!, + dataPoints!, + color!, + 'Line', + _highPoint, + _lowPoint, + axisCrossesAt!, + themeData!, + lowPointColor, + highPointColor, + negativePointColor, + firstPointColor, + lastPointColor, + ); } if (labelDisplayMode != null && labelDisplayMode != SparkChartLabelDisplayMode.none) { renderDataLabel( - context.canvas, - dataLabels!, - dataPoints!, - coordinatePoints!, - labelStyle!, - labelDisplayMode!, - 'Line', - themeData!, - offset, - color!, - _highPoint, - _lowPoint); + context.canvas, + dataLabels!, + dataPoints!, + coordinatePoints!, + labelStyle!, + labelDisplayMode!, + 'Line', + themeData!, + offset, + color!, + _highPoint, + _lowPoint, + ); } } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_win_loss_renderer.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_win_loss_renderer.dart index 914366086..7f7c9bcb8 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_win_loss_renderer.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/renderers/spark_win_loss_renderer.dart @@ -9,53 +9,54 @@ import 'renderer_base.dart'; class SfSparkWinLossChartRenderObjectWidget extends SfSparkChartRenderObjectWidget { /// Creates the render object for spark chart. - const SfSparkWinLossChartRenderObjectWidget( - {Key? key, - List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - Color? color, - SparkChartPlotBand? plotBand, - this.borderWidth, - this.borderColor, - this.tiePointColor, - bool? isInversed, - double? axisCrossesAt, - Color? axisLineColor, - double? axisLineWidth, - List? axisLineDashArray, - Color? firstPointColor, - Color? lowPointColor, - Color? highPointColor, - Color? lastPointColor, - Color? negativePointColor, - SparkChartDataDetails? sparkChartDataDetails, - SfSparkChartThemeData? themeData, - List? coordinatePoints, - List? dataPoints}) - : super( - key: key, - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lowPointColor: lowPointColor, - highPointColor: highPointColor, - lastPointColor: lastPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + const SfSparkWinLossChartRenderObjectWidget({ + Key? key, + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + Color? color, + SparkChartPlotBand? plotBand, + this.borderWidth, + this.borderColor, + this.tiePointColor, + bool? isInversed, + double? axisCrossesAt, + Color? axisLineColor, + double? axisLineWidth, + List? axisLineDashArray, + Color? firstPointColor, + Color? lowPointColor, + Color? highPointColor, + Color? lastPointColor, + Color? negativePointColor, + SparkChartDataDetails? sparkChartDataDetails, + SfSparkChartThemeData? themeData, + List? coordinatePoints, + List? dataPoints, + }) : super( + key: key, + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lowPointColor: lowPointColor, + highPointColor: highPointColor, + lastPointColor: lastPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Specifies the area chart border width. final double? borderWidth; @@ -69,36 +70,38 @@ class SfSparkWinLossChartRenderObjectWidget @override RenderObject createRenderObject(BuildContext context) { return _RenderSparkWinLossChart( - dataCount: dataCount, - data: data, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineColor: axisLineColor, - axisLineWidth: axisLineWidth, - axisLineDashArray: axisLineDashArray, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - color: color, - plotBand: plotBand, - tiePointColor: tiePointColor, - borderColor: borderColor, - borderWidth: borderWidth, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + dataCount: dataCount, + data: data, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineColor: axisLineColor, + axisLineWidth: axisLineWidth, + axisLineDashArray: axisLineDashArray, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + color: color, + plotBand: plotBand, + tiePointColor: tiePointColor, + borderColor: borderColor, + borderWidth: borderWidth, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); } @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderSparkWinLossChart renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderSparkWinLossChart renderObject, + ) { renderObject ..isInversed = isInversed ..axisCrossesAt = axisCrossesAt @@ -128,54 +131,55 @@ class SfSparkWinLossChartRenderObjectWidget /// Represents the render spark win loss chart class. class _RenderSparkWinLossChart extends RenderSparkChart { /// Creates the render object widget. - _RenderSparkWinLossChart( - {List? data, - int? dataCount, - SparkChartIndexedValueMapper? xValueMapper, - SparkChartIndexedValueMapper? yValueMapper, - bool? isInversed, - double? axisCrossesAt, - double? axisLineWidth, - Color? axisLineColor, - List? axisLineDashArray, - Color? color, - Color? firstPointColor, - Color? lastPointColor, - Color? highPointColor, - Color? lowPointColor, - Color? negativePointColor, - SparkChartPlotBand? plotBand, - Color? tiePointColor, - double? borderWidth, - Color? borderColor, - SfSparkChartThemeData? themeData, - SparkChartDataDetails? sparkChartDataDetails, - List? coordinatePoints, - List? dataPoints}) - : _tiePointColor = tiePointColor, - _borderWidth = borderWidth, - _borderColor = borderColor, - super( - data: data, - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper, - isInversed: isInversed, - axisCrossesAt: axisCrossesAt, - axisLineWidth: axisLineWidth, - axisLineColor: axisLineColor, - axisLineDashArray: axisLineDashArray, - color: color, - firstPointColor: firstPointColor, - lastPointColor: lastPointColor, - highPointColor: highPointColor, - lowPointColor: lowPointColor, - negativePointColor: negativePointColor, - plotBand: plotBand, - sparkChartDataDetails: sparkChartDataDetails, - themeData: themeData, - coordinatePoints: coordinatePoints, - dataPoints: dataPoints); + _RenderSparkWinLossChart({ + List? data, + int? dataCount, + SparkChartIndexedValueMapper? xValueMapper, + SparkChartIndexedValueMapper? yValueMapper, + bool? isInversed, + double? axisCrossesAt, + double? axisLineWidth, + Color? axisLineColor, + List? axisLineDashArray, + Color? color, + Color? firstPointColor, + Color? lastPointColor, + Color? highPointColor, + Color? lowPointColor, + Color? negativePointColor, + SparkChartPlotBand? plotBand, + Color? tiePointColor, + double? borderWidth, + Color? borderColor, + SfSparkChartThemeData? themeData, + SparkChartDataDetails? sparkChartDataDetails, + List? coordinatePoints, + List? dataPoints, + }) : _tiePointColor = tiePointColor, + _borderWidth = borderWidth, + _borderColor = borderColor, + super( + data: data, + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + isInversed: isInversed, + axisCrossesAt: axisCrossesAt, + axisLineWidth: axisLineWidth, + axisLineColor: axisLineColor, + axisLineDashArray: axisLineDashArray, + color: color, + firstPointColor: firstPointColor, + lastPointColor: lastPointColor, + highPointColor: highPointColor, + lowPointColor: lowPointColor, + negativePointColor: negativePointColor, + plotBand: plotBand, + sparkChartDataDetails: sparkChartDataDetails, + themeData: themeData, + coordinatePoints: coordinatePoints, + dataPoints: dataPoints, + ); /// Defines the border width. double? _borderWidth; @@ -239,9 +243,10 @@ class _RenderSparkWinLossChart extends RenderSparkChart { diffY = diffY == 0 ? 1 : diffY; _segments = []; - final double xInterval = dataPoints!.length > 1 - ? dataPoints![1].x.toDouble() - dataPoints![0].x.toDouble() - : dataPoints!.length.toDouble(); + final double xInterval = + dataPoints!.length > 1 + ? dataPoints![1].x.toDouble() - dataPoints![0].x.toDouble() + : dataPoints!.length.toDouble(); const double columnSpace = 0.5; // Default space for column and winloss const double space = columnSpace * 2; const double winLossFactor = 0.5; @@ -264,17 +269,22 @@ class _RenderSparkWinLossChart extends RenderSparkChart { visibleXPoint = (((x - minX!) / xInterval) * (columnWidth + space)) + (space / 2); - y2 = (y > axisCrossesAt!) - ? (areaSize!.height / 2) - : (y < axisCrossesAt!) + y2 = + (y > axisCrossesAt!) + ? (areaSize!.height / 2) + : (y < axisCrossesAt!) ? areaSize!.height * winLossFactor : ((areaSize!.height * winLossFactor) - (areaSize!.height / heightFactor)); rectHeight = (y != axisCrossesAt) ? (areaSize!.height / 2) : areaSize!.height / 20; bottom = y > axisCrossesAt! ? rectHeight - y2 : rectHeight + y2; - rect = - Rect.fromLTRB(visibleXPoint, y2, visibleXPoint + columnWidth, bottom); + rect = Rect.fromLTRB( + visibleXPoint, + y2, + visibleXPoint + columnWidth, + bottom, + ); _segments.add(rect); coordinatePoints!.add(Offset(visibleXPoint + columnWidth / 2, y2)); } @@ -282,17 +292,19 @@ class _RenderSparkWinLossChart extends RenderSparkChart { /// Method to render win loss series. void _renderWinLossSeries(Canvas canvas, Offset offset) { - final Paint tiePointPaint = Paint() - ..color = tiePointColor ?? Colors.deepPurple; - final Paint negativePointPaint = Paint() - ..color = negativePointColor ?? Colors.red; + final Paint tiePointPaint = + Paint()..color = tiePointColor ?? Colors.deepPurple; + final Paint negativePointPaint = + Paint()..color = negativePointColor ?? Colors.red; final Paint paint = Paint()..color = color!; - final Paint strokePaint = Paint() - ..color = borderColor ?? Colors.transparent - ..strokeWidth = borderWidth ?? 0 - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = borderColor ?? Colors.transparent + ..strokeWidth = borderWidth ?? 0 + ..style = PaintingStyle.stroke; - final bool canDrawBorder = borderColor != null && + final bool canDrawBorder = + borderColor != null && borderColor != Colors.transparent && borderWidth != null && borderWidth! > 0; @@ -300,10 +312,11 @@ class _RenderSparkWinLossChart extends RenderSparkChart { for (int i = 0; i < dataPoints!.length; i++) { rect = Rect.fromLTRB( - _segments[i].left + offset.dx, - _segments[i].top + offset.dy, - _segments[i].right + offset.dx, - _segments[i].bottom + offset.dy); + _segments[i].left + offset.dx, + _segments[i].top + offset.dy, + _segments[i].right + offset.dx, + _segments[i].bottom + offset.dy, + ); if (dataPoints![i].y < axisCrossesAt!) { canvas.drawRect(rect, negativePointPaint); } else if (dataPoints![i].y == axisCrossesAt) { diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_area_base.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_area_base.dart index 058882380..79f45e510 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_area_base.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_area_base.dart @@ -39,29 +39,29 @@ class SfSparkAreaChart extends StatefulWidget { /// ); /// } /// ``` - SfSparkAreaChart( - {Key? key, - List? data, - this.plotBand, - this.borderWidth = 0, - this.borderColor, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.marker, - this.labelDisplayMode, - this.labelStyle, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails(data: data), - super(key: key); + SfSparkAreaChart({ + Key? key, + List? data, + this.plotBand, + this.borderWidth = 0, + this.borderColor, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.marker, + this.labelDisplayMode, + this.labelStyle, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails(data: data), + super(key: key); /// Creates the spark area chart for the provided set of data with its default view. /// @@ -115,40 +115,41 @@ class SfSparkAreaChart extends StatefulWidget { /// } /// ``` - SfSparkAreaChart.custom( - {Key? key, - - /// Data count for the spark charts. - int? dataCount, - - /// Specifies the x-value mapping field. - SparkChartIndexedValueMapper? xValueMapper, - - /// Specifies the y-value mapping field. - SparkChartIndexedValueMapper? yValueMapper, - this.plotBand, - this.borderWidth = 2, - this.borderColor, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.marker, - this.labelDisplayMode, - this.labelStyle, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails( - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper), - super(key: key); + SfSparkAreaChart.custom({ + Key? key, + + /// Data count for the spark charts. + int? dataCount, + + /// Specifies the x-value mapping field. + SparkChartIndexedValueMapper? xValueMapper, + + /// Specifies the y-value mapping field. + SparkChartIndexedValueMapper? yValueMapper, + this.plotBand, + this.borderWidth = 2, + this.borderColor, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.marker, + this.labelDisplayMode, + this.labelStyle, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails( + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + ), + super(key: key); /// Inverts the axis from right to left. /// @@ -582,37 +583,44 @@ class _SfSparkAreaChartState extends State { SfSparkChartThemeData _updateThemeData(BuildContext context) { SfSparkChartThemeData chartThemeData = SfSparkChartTheme.of(context); final ThemeData theme = Theme.of(context); - final SfSparkChartThemeData effectiveChartThemeData = - SparkChartThemeData(context); + final SfSparkChartThemeData effectiveChartThemeData = SparkChartThemeData( + context, + ); chartThemeData = chartThemeData.copyWith( - color: widget.color ?? - chartThemeData.color ?? - effectiveChartThemeData.color, - axisLineColor: widget.axisLineColor ?? - chartThemeData.axisLineColor ?? - effectiveChartThemeData.axisLineColor, - markerFillColor: chartThemeData.markerFillColor ?? - effectiveChartThemeData.markerFillColor, - dataLabelBackgroundColor: chartThemeData.dataLabelBackgroundColor ?? - effectiveChartThemeData.dataLabelBackgroundColor, - tooltipColor: - chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - trackballLineColor: chartThemeData.trackballLineColor ?? - effectiveChartThemeData.trackballLineColor, - tooltipLabelColor: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - dataLabelTextStyle: theme.textTheme.bodySmall! - .copyWith(color: Colors.transparent) - .merge(chartThemeData.dataLabelTextStyle) - .merge(widget.labelStyle), - trackballTextStyle: theme.textTheme.bodySmall - ?.copyWith( - color: widget.trackball?.color ?? - chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - ) - .merge(chartThemeData.trackballTextStyle) - .merge(widget.trackball?.labelStyle)); + color: + widget.color ?? chartThemeData.color ?? effectiveChartThemeData.color, + axisLineColor: + widget.axisLineColor ?? + chartThemeData.axisLineColor ?? + effectiveChartThemeData.axisLineColor, + markerFillColor: + chartThemeData.markerFillColor ?? + effectiveChartThemeData.markerFillColor, + dataLabelBackgroundColor: + chartThemeData.dataLabelBackgroundColor ?? + effectiveChartThemeData.dataLabelBackgroundColor, + tooltipColor: + chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, + trackballLineColor: + chartThemeData.trackballLineColor ?? + effectiveChartThemeData.trackballLineColor, + tooltipLabelColor: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + dataLabelTextStyle: theme.textTheme.bodySmall! + .copyWith(color: Colors.transparent) + .merge(chartThemeData.dataLabelTextStyle) + .merge(widget.labelStyle), + trackballTextStyle: theme.textTheme.bodySmall + ?.copyWith( + color: + widget.trackball?.color ?? + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) + .merge(chartThemeData.trackballTextStyle) + .merge(widget.trackball?.labelStyle), + ); return chartThemeData; } @@ -676,8 +684,11 @@ class _SfSparkAreaChartState extends State { widget.marker!.displayMode != SparkChartMarkerDisplayMode.none) { final double padding = widget.marker!.size / 2; return RepaintBoundary( - child: Padding( - padding: EdgeInsets.all(padding), child: _getSparkAreaChart())); + child: Padding( + padding: EdgeInsets.all(padding), + child: _getSparkAreaChart(), + ), + ); } else { return RepaintBoundary(child: _getSparkAreaChart()); } @@ -686,39 +697,44 @@ class _SfSparkAreaChartState extends State { /// Method to return the spark area chart widget. Widget _getSparkAreaChart() { return SparkChartContainer( - child: Stack(children: [ - SfSparkAreaChartRenderObjectWidget( - data: widget._sparkChartDataDetails.data, - dataCount: widget._sparkChartDataDetails.dataCount, - xValueMapper: widget._sparkChartDataDetails.xValueMapper, - yValueMapper: widget._sparkChartDataDetails.yValueMapper, - isInversed: widget.isInversed, - axisCrossesAt: widget.axisCrossesAt, - axisLineColor: _chartThemeData.axisLineColor, - axisLineWidth: widget.axisLineWidth, - axisLineDashArray: widget.axisLineDashArray, - highPointColor: widget.highPointColor, - lowPointColor: widget.lowPointColor, - firstPointColor: widget.firstPointColor, - lastPointColor: widget.lastPointColor, - negativePointColor: widget.negativePointColor, - color: _chartThemeData.color, - borderColor: widget.borderColor, - borderWidth: widget.borderWidth, - plotBand: widget.plotBand, - marker: widget.marker, - labelDisplayMode: widget.labelDisplayMode, - labelStyle: _chartThemeData.dataLabelTextStyle, - themeData: _chartThemeData, - sparkChartDataDetails: widget._sparkChartDataDetails, - dataPoints: _dataPoints, - coordinatePoints: _coordinatePoints), - SparkChartTrackballRenderer( - trackball: widget.trackball, - coordinatePoints: _coordinatePoints, - dataPoints: _dataPoints, - themeData: _chartThemeData, - sparkChart: widget) - ])); + child: Stack( + children: [ + SfSparkAreaChartRenderObjectWidget( + data: widget._sparkChartDataDetails.data, + dataCount: widget._sparkChartDataDetails.dataCount, + xValueMapper: widget._sparkChartDataDetails.xValueMapper, + yValueMapper: widget._sparkChartDataDetails.yValueMapper, + isInversed: widget.isInversed, + axisCrossesAt: widget.axisCrossesAt, + axisLineColor: _chartThemeData.axisLineColor, + axisLineWidth: widget.axisLineWidth, + axisLineDashArray: widget.axisLineDashArray, + highPointColor: widget.highPointColor, + lowPointColor: widget.lowPointColor, + firstPointColor: widget.firstPointColor, + lastPointColor: widget.lastPointColor, + negativePointColor: widget.negativePointColor, + color: _chartThemeData.color, + borderColor: widget.borderColor, + borderWidth: widget.borderWidth, + plotBand: widget.plotBand, + marker: widget.marker, + labelDisplayMode: widget.labelDisplayMode, + labelStyle: _chartThemeData.dataLabelTextStyle, + themeData: _chartThemeData, + sparkChartDataDetails: widget._sparkChartDataDetails, + dataPoints: _dataPoints, + coordinatePoints: _coordinatePoints, + ), + SparkChartTrackballRenderer( + trackball: widget.trackball, + coordinatePoints: _coordinatePoints, + dataPoints: _dataPoints, + themeData: _chartThemeData, + sparkChart: widget, + ), + ], + ), + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_bar_base.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_bar_base.dart index df79fe485..67e8df7e0 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_bar_base.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_bar_base.dart @@ -37,28 +37,28 @@ class SfSparkBarChart extends StatefulWidget { /// ); /// } /// ``` - SfSparkBarChart( - {Key? key, - List? data, - this.plotBand, - this.borderWidth = 0, - this.borderColor, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.labelDisplayMode, - this.labelStyle, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails(data: data), - super(key: key); + SfSparkBarChart({ + Key? key, + List? data, + this.plotBand, + this.borderWidth = 0, + this.borderColor, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.labelDisplayMode, + this.labelStyle, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails(data: data), + super(key: key); /// Creates the spark bar chart for the provided set of data with its default view. /// @@ -111,39 +111,40 @@ class SfSparkBarChart extends StatefulWidget { /// ); /// } /// ``` - SfSparkBarChart.custom( - {Key? key, - - /// Data count for the spark charts. - int? dataCount, - - /// Specifies the x-value mapping field. - SparkChartIndexedValueMapper? xValueMapper, - - /// Specifies the y-value maping field. - SparkChartIndexedValueMapper? yValueMapper, - this.plotBand, - this.borderWidth = 2, - this.borderColor, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.labelDisplayMode, - this.labelStyle, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails( - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper), - super(key: key); + SfSparkBarChart.custom({ + Key? key, + + /// Data count for the spark charts. + int? dataCount, + + /// Specifies the x-value mapping field. + SparkChartIndexedValueMapper? xValueMapper, + + /// Specifies the y-value maping field. + SparkChartIndexedValueMapper? yValueMapper, + this.plotBand, + this.borderWidth = 2, + this.borderColor, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.labelDisplayMode, + this.labelStyle, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails( + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + ), + super(key: key); /// Inverts the axis from right to left. /// @@ -540,37 +541,44 @@ class _SfSparkBarChartState extends State { SfSparkChartThemeData _updateThemeData(BuildContext context) { SfSparkChartThemeData chartThemeData = SfSparkChartTheme.of(context); final ThemeData theme = Theme.of(context); - final SfSparkChartThemeData effectiveChartThemeData = - SparkChartThemeData(context); + final SfSparkChartThemeData effectiveChartThemeData = SparkChartThemeData( + context, + ); chartThemeData = chartThemeData.copyWith( - color: widget.color ?? - chartThemeData.color ?? - effectiveChartThemeData.color, - axisLineColor: widget.axisLineColor ?? - chartThemeData.axisLineColor ?? - effectiveChartThemeData.axisLineColor, - markerFillColor: chartThemeData.markerFillColor ?? - effectiveChartThemeData.markerFillColor, - dataLabelBackgroundColor: chartThemeData.dataLabelBackgroundColor ?? - effectiveChartThemeData.dataLabelBackgroundColor, - tooltipColor: - chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - trackballLineColor: chartThemeData.trackballLineColor ?? - effectiveChartThemeData.trackballLineColor, - tooltipLabelColor: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - dataLabelTextStyle: theme.textTheme.bodySmall! - .copyWith(color: Colors.transparent) - .merge(chartThemeData.dataLabelTextStyle) - .merge(widget.labelStyle), - trackballTextStyle: theme.textTheme.bodySmall - ?.copyWith( - color: widget.trackball?.color ?? - chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - ) - .merge(chartThemeData.trackballTextStyle) - .merge(widget.trackball?.labelStyle)); + color: + widget.color ?? chartThemeData.color ?? effectiveChartThemeData.color, + axisLineColor: + widget.axisLineColor ?? + chartThemeData.axisLineColor ?? + effectiveChartThemeData.axisLineColor, + markerFillColor: + chartThemeData.markerFillColor ?? + effectiveChartThemeData.markerFillColor, + dataLabelBackgroundColor: + chartThemeData.dataLabelBackgroundColor ?? + effectiveChartThemeData.dataLabelBackgroundColor, + tooltipColor: + chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, + trackballLineColor: + chartThemeData.trackballLineColor ?? + effectiveChartThemeData.trackballLineColor, + tooltipLabelColor: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + dataLabelTextStyle: theme.textTheme.bodySmall! + .copyWith(color: Colors.transparent) + .merge(chartThemeData.dataLabelTextStyle) + .merge(widget.labelStyle), + trackballTextStyle: theme.textTheme.bodySmall + ?.copyWith( + color: + widget.trackball?.color ?? + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) + .merge(chartThemeData.trackballTextStyle) + .merge(widget.trackball?.labelStyle), + ); return chartThemeData; } @@ -631,40 +639,45 @@ class _SfSparkBarChartState extends State { Widget build(BuildContext context) { _chartThemeData = _updateThemeData(context); return RepaintBoundary( - child: SparkChartContainer( - child: Stack(children: [ - SfSparkBarChartRenderObjectWidget( - data: widget._sparkChartDataDetails.data, - dataCount: widget._sparkChartDataDetails.dataCount, - xValueMapper: widget._sparkChartDataDetails.xValueMapper, - yValueMapper: widget._sparkChartDataDetails.yValueMapper, - isInversed: widget.isInversed, - axisCrossesAt: widget.axisCrossesAt, - axisLineColor: _chartThemeData.axisLineColor, - axisLineWidth: widget.axisLineWidth, - axisLineDashArray: widget.axisLineDashArray, - highPointColor: widget.highPointColor, - lowPointColor: widget.lowPointColor, - firstPointColor: widget.firstPointColor, - lastPointColor: widget.lastPointColor, - negativePointColor: widget.negativePointColor, - color: _chartThemeData.color, - borderColor: widget.borderColor, - borderWidth: widget.borderWidth, - plotBand: widget.plotBand, - labelDisplayMode: widget.labelDisplayMode, - labelStyle: _chartThemeData.dataLabelTextStyle, - themeData: _chartThemeData, - sparkChartDataDetails: widget._sparkChartDataDetails, - dataPoints: _dataPoints, - coordinatePoints: _coordinatePoints), - SparkChartTrackballRenderer( - trackball: widget.trackball, - coordinatePoints: _coordinatePoints, - dataPoints: _dataPoints, - themeData: _chartThemeData, - sparkChart: widget, - ) - ]))); + child: SparkChartContainer( + child: Stack( + children: [ + SfSparkBarChartRenderObjectWidget( + data: widget._sparkChartDataDetails.data, + dataCount: widget._sparkChartDataDetails.dataCount, + xValueMapper: widget._sparkChartDataDetails.xValueMapper, + yValueMapper: widget._sparkChartDataDetails.yValueMapper, + isInversed: widget.isInversed, + axisCrossesAt: widget.axisCrossesAt, + axisLineColor: _chartThemeData.axisLineColor, + axisLineWidth: widget.axisLineWidth, + axisLineDashArray: widget.axisLineDashArray, + highPointColor: widget.highPointColor, + lowPointColor: widget.lowPointColor, + firstPointColor: widget.firstPointColor, + lastPointColor: widget.lastPointColor, + negativePointColor: widget.negativePointColor, + color: _chartThemeData.color, + borderColor: widget.borderColor, + borderWidth: widget.borderWidth, + plotBand: widget.plotBand, + labelDisplayMode: widget.labelDisplayMode, + labelStyle: _chartThemeData.dataLabelTextStyle, + themeData: _chartThemeData, + sparkChartDataDetails: widget._sparkChartDataDetails, + dataPoints: _dataPoints, + coordinatePoints: _coordinatePoints, + ), + SparkChartTrackballRenderer( + trackball: widget.trackball, + coordinatePoints: _coordinatePoints, + dataPoints: _dataPoints, + themeData: _chartThemeData, + sparkChart: widget, + ), + ], + ), + ), + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_line_base.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_line_base.dart index f5b4680ba..09e8793e4 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_line_base.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_line_base.dart @@ -38,29 +38,29 @@ class SfSparkLineChart extends StatefulWidget { /// ); /// } /// ``` - SfSparkLineChart( - {Key? key, - List? data, - this.plotBand, - this.width = 2, - this.dashArray, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.marker, - this.labelDisplayMode, - this.labelStyle, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails(data: data), - super(key: key); + SfSparkLineChart({ + Key? key, + List? data, + this.plotBand, + this.width = 2, + this.dashArray, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.marker, + this.labelDisplayMode, + this.labelStyle, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails(data: data), + super(key: key); /// Creates the sparkline chart for the provided set of data with its default view. /// @@ -114,40 +114,41 @@ class SfSparkLineChart extends StatefulWidget { /// } /// ``` - SfSparkLineChart.custom( - {Key? key, - - /// Data count for the spark charts. - int? dataCount, - - /// Specifies the x-value mapping field. - SparkChartIndexedValueMapper? xValueMapper, - - /// Specifies the y-value maping field. - SparkChartIndexedValueMapper? yValueMapper, - this.plotBand, - this.width = 2, - this.dashArray, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.trackball, - this.marker, - this.labelDisplayMode, - this.labelStyle}) - : _sparkChartDataDetails = SparkChartDataDetails( - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper), - super(key: key); + SfSparkLineChart.custom({ + Key? key, + + /// Data count for the spark charts. + int? dataCount, + + /// Specifies the x-value mapping field. + SparkChartIndexedValueMapper? xValueMapper, + + /// Specifies the y-value maping field. + SparkChartIndexedValueMapper? yValueMapper, + this.plotBand, + this.width = 2, + this.dashArray, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.trackball, + this.marker, + this.labelDisplayMode, + this.labelStyle, + }) : _sparkChartDataDetails = SparkChartDataDetails( + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + ), + super(key: key); /// Inverts the axis from right to left. /// @@ -576,37 +577,44 @@ class _SfSparkLineChartState extends State { SfSparkChartThemeData _updateThemeData(BuildContext context) { SfSparkChartThemeData chartThemeData = SfSparkChartTheme.of(context); final ThemeData theme = Theme.of(context); - final SfSparkChartThemeData effectiveChartThemeData = - SparkChartThemeData(context); + final SfSparkChartThemeData effectiveChartThemeData = SparkChartThemeData( + context, + ); chartThemeData = chartThemeData.copyWith( - color: widget.color ?? - chartThemeData.color ?? - effectiveChartThemeData.color, - axisLineColor: widget.axisLineColor ?? - chartThemeData.axisLineColor ?? - effectiveChartThemeData.axisLineColor, - markerFillColor: chartThemeData.markerFillColor ?? - effectiveChartThemeData.markerFillColor, - dataLabelBackgroundColor: chartThemeData.dataLabelBackgroundColor ?? - effectiveChartThemeData.dataLabelBackgroundColor, - tooltipColor: - chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - trackballLineColor: chartThemeData.trackballLineColor ?? - effectiveChartThemeData.trackballLineColor, - tooltipLabelColor: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - dataLabelTextStyle: theme.textTheme.bodySmall! - .copyWith(color: Colors.transparent) - .merge(chartThemeData.dataLabelTextStyle) - .merge(widget.labelStyle), - trackballTextStyle: theme.textTheme.bodySmall - ?.copyWith( - color: widget.trackball?.color ?? - chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - ) - .merge(chartThemeData.trackballTextStyle) - .merge(widget.trackball?.labelStyle)); + color: + widget.color ?? chartThemeData.color ?? effectiveChartThemeData.color, + axisLineColor: + widget.axisLineColor ?? + chartThemeData.axisLineColor ?? + effectiveChartThemeData.axisLineColor, + markerFillColor: + chartThemeData.markerFillColor ?? + effectiveChartThemeData.markerFillColor, + dataLabelBackgroundColor: + chartThemeData.dataLabelBackgroundColor ?? + effectiveChartThemeData.dataLabelBackgroundColor, + tooltipColor: + chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, + trackballLineColor: + chartThemeData.trackballLineColor ?? + effectiveChartThemeData.trackballLineColor, + tooltipLabelColor: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + dataLabelTextStyle: theme.textTheme.bodySmall! + .copyWith(color: Colors.transparent) + .merge(chartThemeData.dataLabelTextStyle) + .merge(widget.labelStyle), + trackballTextStyle: theme.textTheme.bodySmall + ?.copyWith( + color: + widget.trackball?.color ?? + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) + .merge(chartThemeData.trackballTextStyle) + .merge(widget.trackball?.labelStyle), + ); return chartThemeData; } @@ -669,8 +677,11 @@ class _SfSparkLineChartState extends State { widget.marker!.displayMode != SparkChartMarkerDisplayMode.none) { final double padding = widget.marker!.size / 2; return RepaintBoundary( - child: Padding( - padding: EdgeInsets.all(padding), child: _getSparkLineChart())); + child: Padding( + padding: EdgeInsets.all(padding), + child: _getSparkLineChart(), + ), + ); } else { return RepaintBoundary(child: _getSparkLineChart()); } @@ -680,39 +691,43 @@ class _SfSparkLineChartState extends State { Widget _getSparkLineChart() { _chartThemeData = _updateThemeData(context); return SparkChartContainer( - child: Stack(children: [ - SfSparkLineChartRenderObjectWidget( - data: widget._sparkChartDataDetails.data, - dataCount: widget._sparkChartDataDetails.dataCount, - xValueMapper: widget._sparkChartDataDetails.xValueMapper, - yValueMapper: widget._sparkChartDataDetails.yValueMapper, - width: widget.width, - dashArray: widget.dashArray, - isInversed: widget.isInversed, - axisCrossesAt: widget.axisCrossesAt, - axisLineColor: _chartThemeData.axisLineColor, - axisLineWidth: widget.axisLineWidth, - axisLineDashArray: widget.axisLineDashArray, - highPointColor: widget.highPointColor, - lowPointColor: widget.lowPointColor, - firstPointColor: widget.firstPointColor, - lastPointColor: widget.lastPointColor, - negativePointColor: widget.negativePointColor, - color: _chartThemeData.color, - plotBand: widget.plotBand, - marker: widget.marker, - labelDisplayMode: widget.labelDisplayMode, - labelStyle: _chartThemeData.dataLabelTextStyle, - themeData: _chartThemeData, - sparkChartDataDetails: widget._sparkChartDataDetails, - dataPoints: _dataPoints, - coordinatePoints: _coordinatePoints), - SparkChartTrackballRenderer( - trackball: widget.trackball, - coordinatePoints: _coordinatePoints, - dataPoints: _dataPoints, - themeData: _chartThemeData, - ) - ])); + child: Stack( + children: [ + SfSparkLineChartRenderObjectWidget( + data: widget._sparkChartDataDetails.data, + dataCount: widget._sparkChartDataDetails.dataCount, + xValueMapper: widget._sparkChartDataDetails.xValueMapper, + yValueMapper: widget._sparkChartDataDetails.yValueMapper, + width: widget.width, + dashArray: widget.dashArray, + isInversed: widget.isInversed, + axisCrossesAt: widget.axisCrossesAt, + axisLineColor: _chartThemeData.axisLineColor, + axisLineWidth: widget.axisLineWidth, + axisLineDashArray: widget.axisLineDashArray, + highPointColor: widget.highPointColor, + lowPointColor: widget.lowPointColor, + firstPointColor: widget.firstPointColor, + lastPointColor: widget.lastPointColor, + negativePointColor: widget.negativePointColor, + color: _chartThemeData.color, + plotBand: widget.plotBand, + marker: widget.marker, + labelDisplayMode: widget.labelDisplayMode, + labelStyle: _chartThemeData.dataLabelTextStyle, + themeData: _chartThemeData, + sparkChartDataDetails: widget._sparkChartDataDetails, + dataPoints: _dataPoints, + coordinatePoints: _coordinatePoints, + ), + SparkChartTrackballRenderer( + trackball: widget.trackball, + coordinatePoints: _coordinatePoints, + dataPoints: _dataPoints, + themeData: _chartThemeData, + ), + ], + ), + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_win_loss_base.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_win_loss_base.dart index 112599aa7..822673d53 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_win_loss_base.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/series/spark_win_loss_base.dart @@ -39,27 +39,27 @@ class SfSparkWinLossChart extends StatefulWidget { /// ); /// } /// ``` - SfSparkWinLossChart( - {Key? key, - List? data, - this.plotBand, - this.borderWidth = 0, - this.borderColor, - this.tiePointColor, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails(data: data), - super(key: key); + SfSparkWinLossChart({ + Key? key, + List? data, + this.plotBand, + this.borderWidth = 0, + this.borderColor, + this.tiePointColor, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails(data: data), + super(key: key); /// Creates the spark win loss chart for the provided set of data with its /// default view. @@ -113,38 +113,39 @@ class SfSparkWinLossChart extends StatefulWidget { /// ); /// } /// ``` - SfSparkWinLossChart.custom( - {Key? key, - - /// Data count for the spark charts. - int? dataCount, - - /// Specifies the x-value mapping field. - SparkChartIndexedValueMapper? xValueMapper, - - /// Specifies the y-value maping field. - SparkChartIndexedValueMapper? yValueMapper, - this.plotBand, - this.borderWidth = 2, - this.borderColor, - this.tiePointColor, - this.color, - this.isInversed = false, - this.axisCrossesAt = 0, - this.axisLineColor, - this.axisLineWidth = 2, - this.axisLineDashArray, - this.highPointColor, - this.lowPointColor, - this.negativePointColor, - this.firstPointColor, - this.lastPointColor, - this.trackball}) - : _sparkChartDataDetails = SparkChartDataDetails( - dataCount: dataCount, - xValueMapper: xValueMapper, - yValueMapper: yValueMapper), - super(key: key); + SfSparkWinLossChart.custom({ + Key? key, + + /// Data count for the spark charts. + int? dataCount, + + /// Specifies the x-value mapping field. + SparkChartIndexedValueMapper? xValueMapper, + + /// Specifies the y-value maping field. + SparkChartIndexedValueMapper? yValueMapper, + this.plotBand, + this.borderWidth = 2, + this.borderColor, + this.tiePointColor, + this.color, + this.isInversed = false, + this.axisCrossesAt = 0, + this.axisLineColor, + this.axisLineWidth = 2, + this.axisLineDashArray, + this.highPointColor, + this.lowPointColor, + this.negativePointColor, + this.firstPointColor, + this.lastPointColor, + this.trackball, + }) : _sparkChartDataDetails = SparkChartDataDetails( + dataCount: dataCount, + xValueMapper: xValueMapper, + yValueMapper: yValueMapper, + ), + super(key: key); /// Inverts the axis from right to left. /// @@ -511,33 +512,40 @@ class _SfSparkWinLossChartState extends State { SfSparkChartThemeData _updateThemeData(BuildContext context) { SfSparkChartThemeData chartThemeData = SfSparkChartTheme.of(context); final ThemeData theme = Theme.of(context); - final SfSparkChartThemeData effectiveChartThemeData = - SparkChartThemeData(context); + final SfSparkChartThemeData effectiveChartThemeData = SparkChartThemeData( + context, + ); chartThemeData = chartThemeData.copyWith( - color: widget.color ?? - chartThemeData.color ?? - effectiveChartThemeData.color, - axisLineColor: widget.axisLineColor ?? - chartThemeData.axisLineColor ?? - effectiveChartThemeData.axisLineColor, - markerFillColor: chartThemeData.markerFillColor ?? - effectiveChartThemeData.markerFillColor, - dataLabelBackgroundColor: chartThemeData.dataLabelBackgroundColor ?? - effectiveChartThemeData.dataLabelBackgroundColor, - tooltipColor: - chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, - trackballLineColor: chartThemeData.trackballLineColor ?? - effectiveChartThemeData.trackballLineColor, - tooltipLabelColor: chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - trackballTextStyle: theme.textTheme.bodySmall - ?.copyWith( - color: widget.trackball?.color ?? - chartThemeData.tooltipLabelColor ?? - effectiveChartThemeData.tooltipLabelColor, - ) - .merge(chartThemeData.trackballTextStyle) - .merge(widget.trackball?.labelStyle)); + color: + widget.color ?? chartThemeData.color ?? effectiveChartThemeData.color, + axisLineColor: + widget.axisLineColor ?? + chartThemeData.axisLineColor ?? + effectiveChartThemeData.axisLineColor, + markerFillColor: + chartThemeData.markerFillColor ?? + effectiveChartThemeData.markerFillColor, + dataLabelBackgroundColor: + chartThemeData.dataLabelBackgroundColor ?? + effectiveChartThemeData.dataLabelBackgroundColor, + tooltipColor: + chartThemeData.tooltipColor ?? effectiveChartThemeData.tooltipColor, + trackballLineColor: + chartThemeData.trackballLineColor ?? + effectiveChartThemeData.trackballLineColor, + tooltipLabelColor: + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + trackballTextStyle: theme.textTheme.bodySmall + ?.copyWith( + color: + widget.trackball?.color ?? + chartThemeData.tooltipLabelColor ?? + effectiveChartThemeData.tooltipLabelColor, + ) + .merge(chartThemeData.trackballTextStyle) + .merge(widget.trackball?.labelStyle), + ); return chartThemeData; } @@ -598,38 +606,43 @@ class _SfSparkWinLossChartState extends State { Widget build(BuildContext context) { _chartThemeData = _updateThemeData(context); return RepaintBoundary( - child: SparkChartContainer( - child: Stack(children: [ - SfSparkWinLossChartRenderObjectWidget( - data: widget._sparkChartDataDetails.data, - dataCount: widget._sparkChartDataDetails.dataCount, - xValueMapper: widget._sparkChartDataDetails.xValueMapper, - yValueMapper: widget._sparkChartDataDetails.yValueMapper, - isInversed: widget.isInversed, - axisCrossesAt: widget.axisCrossesAt, - axisLineColor: _chartThemeData.axisLineColor, - axisLineWidth: widget.axisLineWidth, - axisLineDashArray: widget.axisLineDashArray, - highPointColor: widget.highPointColor, - lowPointColor: widget.lowPointColor, - firstPointColor: widget.firstPointColor, - lastPointColor: widget.lastPointColor, - negativePointColor: widget.negativePointColor, - color: _chartThemeData.color, - tiePointColor: widget.tiePointColor, - borderColor: widget.borderColor, - borderWidth: widget.borderWidth, - plotBand: widget.plotBand, - themeData: _chartThemeData, - sparkChartDataDetails: widget._sparkChartDataDetails, - dataPoints: _dataPoints, - coordinatePoints: _coordinatePoints), - SparkChartTrackballRenderer( - trackball: widget.trackball, - coordinatePoints: _coordinatePoints, - dataPoints: _dataPoints, - themeData: _chartThemeData, - ) - ]))); + child: SparkChartContainer( + child: Stack( + children: [ + SfSparkWinLossChartRenderObjectWidget( + data: widget._sparkChartDataDetails.data, + dataCount: widget._sparkChartDataDetails.dataCount, + xValueMapper: widget._sparkChartDataDetails.xValueMapper, + yValueMapper: widget._sparkChartDataDetails.yValueMapper, + isInversed: widget.isInversed, + axisCrossesAt: widget.axisCrossesAt, + axisLineColor: _chartThemeData.axisLineColor, + axisLineWidth: widget.axisLineWidth, + axisLineDashArray: widget.axisLineDashArray, + highPointColor: widget.highPointColor, + lowPointColor: widget.lowPointColor, + firstPointColor: widget.firstPointColor, + lastPointColor: widget.lastPointColor, + negativePointColor: widget.negativePointColor, + color: _chartThemeData.color, + tiePointColor: widget.tiePointColor, + borderColor: widget.borderColor, + borderWidth: widget.borderWidth, + plotBand: widget.plotBand, + themeData: _chartThemeData, + sparkChartDataDetails: widget._sparkChartDataDetails, + dataPoints: _dataPoints, + coordinatePoints: _coordinatePoints, + ), + SparkChartTrackballRenderer( + trackball: widget.trackball, + coordinatePoints: _coordinatePoints, + dataPoints: _dataPoints, + themeData: _chartThemeData, + ), + ], + ), + ), + ); } } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/theme.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/theme.dart index f50b98a6d..f57e5b454 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/theme.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/theme.dart @@ -14,18 +14,20 @@ class SparkChartThemeData extends SfSparkChartThemeData { late final SfColorScheme colorScheme = SfTheme.colorScheme(context); @override - Color? get color => colorScheme.useMaterial3 - ? colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(150, 60, 112, 1) - : const Color.fromRGBO(77, 170, 255, 1) - : Colors.blue; + Color? get color => + colorScheme.useMaterial3 + ? colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(150, 60, 112, 1) + : const Color.fromRGBO(77, 170, 255, 1) + : Colors.blue; @override - Color? get axisLineColor => colorScheme.useMaterial3 - ? colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(73, 69, 79, 1) - : const Color.fromRGBO(202, 196, 208, 1) - : Colors.black; + Color? get axisLineColor => + colorScheme.useMaterial3 + ? colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(73, 69, 79, 1) + : const Color.fromRGBO(202, 196, 208, 1) + : Colors.black; @override Color? get markerFillColor => colorScheme.surface[150]; diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/spark_chart_trackball.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/spark_chart_trackball.dart index 9ff630c45..2ce4ac823 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/spark_chart_trackball.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/spark_chart_trackball.dart @@ -30,19 +30,20 @@ class SparkChartTrackball { /// ); /// } /// ``` - const SparkChartTrackball( - {this.width = 2, - this.color, - this.dashArray, - this.activationMode = SparkChartActivationMode.tap, - this.labelStyle, - this.tooltipFormatter, - this.backgroundColor, - this.shouldAlwaysShow = false, - this.hideDelay = 0, - this.borderColor, - this.borderWidth = 0, - this.borderRadius = const BorderRadius.all(Radius.circular(5))}); + const SparkChartTrackball({ + this.width = 2, + this.color, + this.dashArray, + this.activationMode = SparkChartActivationMode.tap, + this.labelStyle, + this.tooltipFormatter, + this.backgroundColor, + this.shouldAlwaysShow = false, + this.hideDelay = 0, + this.borderColor, + this.borderWidth = 0, + this.borderRadius = const BorderRadius.all(Radius.circular(5)), + }); /// Customizes the width of the trackball line. /// @@ -346,7 +347,7 @@ class SparkChartTrackball { shouldAlwaysShow, hideDelay, borderRadius, - tooltipFormatter! + tooltipFormatter!, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/trackball_renderer.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/trackball_renderer.dart index c2af33035..3add1e0cb 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/trackball_renderer.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/trackball/trackball_renderer.dart @@ -13,14 +13,14 @@ import 'spark_chart_trackball.dart'; @immutable class SparkChartTrackballRenderer extends StatefulWidget { /// Creates the trackball renderer. - const SparkChartTrackballRenderer( - {Key? key, - this.trackball, - this.coordinatePoints, - this.dataPoints, - this.themeData, - this.sparkChart}) - : super(key: key); + const SparkChartTrackballRenderer({ + Key? key, + this.trackball, + this.coordinatePoints, + this.dataPoints, + this.themeData, + this.sparkChart, + }) : super(key: key); /// Specifies the spark chart trackball. final SparkChartTrackball? trackball; @@ -113,46 +113,83 @@ class _SparkChartTrackballRendererState @override Widget build(BuildContext context) { return MouseRegion( - // Using the _enableMouseHover property, prevented mouse hover function in mobile platforms. The mouse hover event should not be triggered for mobile platforms and logged an issue regarding this to the Flutter team. - // Issue: https://github.com/flutter/flutter/issues/68690 - onHover: (PointerHoverEvent event) => _enableMouseHover - ? _enableAndUpdateTrackball(context, event.position) - : null, - onExit: (PointerExitEvent event) => _hide(), - child: Listener( - onPointerUp: (PointerUpEvent event) => _hide(), - child: GestureDetector( - onVerticalDragStart: (widget.trackball != null && widget.trackball!.activationMode != SparkChartActivationMode.doubleTap) + // Using the _enableMouseHover property, prevented mouse hover function in mobile platforms. The mouse hover event should not be triggered for mobile platforms and logged an issue regarding this to the Flutter team. + // Issue: https://github.com/flutter/flutter/issues/68690 + onHover: + (PointerHoverEvent event) => + _enableMouseHover + ? _enableAndUpdateTrackball(context, event.position) + : null, + onExit: (PointerExitEvent event) => _hide(), + child: Listener( + onPointerUp: (PointerUpEvent event) => _hide(), + child: GestureDetector( + onVerticalDragStart: + (widget.trackball != null && + widget.trackball!.activationMode != + SparkChartActivationMode.doubleTap) + ? (DragStartDetails details) => + _updateDragValue(context, details.globalPosition) + : null, + onVerticalDragUpdate: + (widget.trackball != null && + widget.trackball!.activationMode != + SparkChartActivationMode.doubleTap) + ? (DragUpdateDetails details) => + _updateDragValue(context, details.globalPosition) + : null, + onHorizontalDragStart: + (widget.trackball != null && + widget.trackball!.activationMode != + SparkChartActivationMode.doubleTap) ? (DragStartDetails details) => _updateDragValue(context, details.globalPosition) : null, - onVerticalDragUpdate: (widget.trackball != null && widget.trackball!.activationMode != SparkChartActivationMode.doubleTap) + onHorizontalDragUpdate: + (widget.trackball != null && + widget.trackball!.activationMode != + SparkChartActivationMode.doubleTap) ? (DragUpdateDetails details) => _updateDragValue(context, details.globalPosition) : null, - onHorizontalDragStart: - (widget.trackball != null && widget.trackball!.activationMode != SparkChartActivationMode.doubleTap) - ? (DragStartDetails details) => - _updateDragValue(context, details.globalPosition) - : null, - onHorizontalDragUpdate: - (widget.trackball != null && widget.trackball!.activationMode != SparkChartActivationMode.doubleTap) - ? (DragUpdateDetails details) => - _updateDragValue(context, details.globalPosition) - : null, - onTapDown: (widget.trackball != null && widget.trackball!.activationMode == SparkChartActivationMode.tap) + onTapDown: + (widget.trackball != null && + widget.trackball!.activationMode == + SparkChartActivationMode.tap) ? (TapDownDetails details) => _enableAndUpdateTrackball(context, details.globalPosition) : null, - onLongPressStart: (widget.trackball != null && widget.trackball!.activationMode == SparkChartActivationMode.longPress) + onLongPressStart: + (widget.trackball != null && + widget.trackball!.activationMode == + SparkChartActivationMode.longPress) ? (LongPressStartDetails details) => _enableAndUpdateTrackball(context, details.globalPosition) : null, - onLongPressMoveUpdate: (widget.trackball != null && widget.trackball!.activationMode == SparkChartActivationMode.longPress) ? (LongPressMoveUpdateDetails details) => _updateDragValue(context, details.globalPosition) : null, - onDoubleTapDown: (widget.trackball != null && widget.trackball!.activationMode == SparkChartActivationMode.doubleTap) ? (TapDownDetails details) => _enableAndUpdateTrackball(context, details.globalPosition) : null, - onDoubleTap: (widget.trackball != null && widget.trackball!.activationMode == SparkChartActivationMode.doubleTap) ? () => _updateDragValue(context, _globalPosition!) : null, - child: _addTrackballPainter()), - )); + onLongPressMoveUpdate: + (widget.trackball != null && + widget.trackball!.activationMode == + SparkChartActivationMode.longPress) + ? (LongPressMoveUpdateDetails details) => + _updateDragValue(context, details.globalPosition) + : null, + onDoubleTapDown: + (widget.trackball != null && + widget.trackball!.activationMode == + SparkChartActivationMode.doubleTap) + ? (TapDownDetails details) => + _enableAndUpdateTrackball(context, details.globalPosition) + : null, + onDoubleTap: + (widget.trackball != null && + widget.trackball!.activationMode == + SparkChartActivationMode.doubleTap) + ? () => _updateDragValue(context, _globalPosition!) + : null, + child: _addTrackballPainter(), + ), + ), + ); } /// Method to hide the trackball. @@ -164,10 +201,12 @@ class _SparkChartTrackballRendererState _trackballRepaintNotifier!.value++; _timer = Timer( - Duration(milliseconds: widget.trackball!.hideDelay.toInt()), () { - _trackballRepaintNotifier!.value++; - _endTrackballDragging(); - }); + Duration(milliseconds: widget.trackball!.hideDelay.toInt()), + () { + _trackballRepaintNotifier!.value++; + _endTrackballDragging(); + }, + ); } } @@ -179,9 +218,14 @@ class _SparkChartTrackballRendererState return Container( child: RepaintBoundary( child: CustomPaint( - painter: TrackballPainter(_trackballRepaintNotifier!, - _isTrackballEnabled, widget.trackball, this), - size: Size(constraints.maxWidth, constraints.maxHeight)), + painter: TrackballPainter( + _trackballRepaintNotifier!, + _isTrackballEnabled, + widget.trackball, + this, + ), + size: Size(constraints.maxWidth, constraints.maxHeight), + ), ), ); }, @@ -193,10 +237,18 @@ class _SparkChartTrackballRendererState final RenderBox renderBox = context.findRenderObject()! as RenderBox; final Size renderBoxSize = renderBox.size; final Offset renderBoxOffset = renderBox.localToGlobal(Offset.zero); - _areaBounds = Rect.fromLTWH(renderBoxOffset.dx, renderBoxOffset.dy, - renderBoxSize.width, renderBoxSize.height); - _localBounds = - Rect.fromLTWH(0, 0, renderBoxSize.width, renderBoxSize.height); + _areaBounds = Rect.fromLTWH( + renderBoxOffset.dx, + renderBoxOffset.dy, + renderBoxSize.width, + renderBoxSize.height, + ); + _localBounds = Rect.fromLTWH( + 0, + 0, + renderBoxSize.width, + renderBoxSize.height, + ); _globalPosition = globalPosition; _touchPosition = renderBox.globalToLocal(globalPosition); if (_localBounds!.contains(_touchPosition!)) { @@ -264,12 +316,12 @@ class _SparkChartTrackballRendererState class TrackballPainter extends CustomPainter { /// Creates the painter to render the trackball. TrackballPainter( - ValueNotifier notifier, - this._isRepaint, - this._trackball, - // ignore: library_private_types_in_public_api - this._rendererState) - : super(repaint: notifier); + ValueNotifier notifier, + this._isRepaint, + this._trackball, + // ignore: library_private_types_in_public_api + this._rendererState, + ) : super(repaint: notifier); /// Specifies whether to repaint the series. final bool _isRepaint; @@ -292,7 +344,11 @@ class TrackballPainter extends CustomPainter { /// Method to render the trackball tooltip. void _renderTrackballTooltip( - Canvas canvas, Offset? screenPoint, num index, Size size) { + Canvas canvas, + Offset? screenPoint, + num index, + Size size, + ) { Offset labelOffset = screenPoint!; final String dataLabel = _getTrackballLabel(); final TextStyle labelStyle = _rendererState._themeData!.trackballTextStyle!; @@ -307,8 +363,12 @@ class TrackballPainter extends CustomPainter { final double textWidth = textSize.height / 2; borderRadius = _getBorderRadius(borderRadius, textWidth); - Rect labelRect = Rect.fromLTWH(screenPoint.dx, screenPoint.dy, - textSize.width + 15, textSize.height + 10); + Rect labelRect = Rect.fromLTWH( + screenPoint.dx, + screenPoint.dy, + textSize.width + 15, + textSize.height + 10, + ); const double tooltipPadding = 5; const double pointerWidth = 5; const double pointerLength = 7; @@ -325,7 +385,8 @@ class TrackballPainter extends CustomPainter { xPosition = screenPoint.dx + pointerLength + tooltipPadding; yPosition = screenPoint.dy - labelRect.height / 2; if ((xPosition + labelRect.width) > totalWidth) { - xPosition = (xPosition - labelRect.width - 2 * tooltipPadding) - + xPosition = + (xPosition - labelRect.width - 2 * tooltipPadding) - 2 * pointerLength; isRight = true; } else if (xPosition >= totalWidth) { @@ -349,29 +410,46 @@ class TrackballPainter extends CustomPainter { screenPoint.dy - labelRect.height - padding - pointerLength; } else { isBottom = true; - yPosition = (screenPoint.dy > 0 ? screenPoint.dy : 0) + + yPosition = + (screenPoint.dy > 0 ? screenPoint.dy : 0) + pointerLength + padding; if ((yPosition + labelRect.height) > size.height) { final double y = size.height - (yPosition + labelRect.height); screenPoint = Offset(screenPoint.dx, y); - yPosition = (screenPoint.dy > 0 ? screenPoint.dy : 0) + + yPosition = + (screenPoint.dy > 0 ? screenPoint.dy : 0) + pointerLength + padding; } } - xPosition = xPosition < 0 - ? 0 - : (tooltipRight > totalWidth - ? totalWidth - labelRect.width - : xPosition); + xPosition = + xPosition < 0 + ? 0 + : (tooltipRight > totalWidth + ? totalWidth - labelRect.width + : xPosition); } labelRect = Rect.fromLTWH( - xPosition, yPosition, labelRect.width, labelRect.height); - _drawTrackballRect(canvas, textSize, labelRect, isRight, borderRadius, - pointerWidth, pointerLength, screenPoint, isTop, isBottom); + xPosition, + yPosition, + labelRect.width, + labelRect.height, + ); + _drawTrackballRect( + canvas, + textSize, + labelRect, + isRight, + borderRadius, + pointerWidth, + pointerLength, + screenPoint, + isTop, + isBottom, + ); final double labelOffsetX = (labelRect.left + labelRect.width / 2) - textSize.width / 2; @@ -391,7 +469,10 @@ class TrackballPainter extends CustomPainter { if (_trackball!.tooltipFormatter != null) { final TooltipFormatterDetails tooltipFormatterDetails = TooltipFormatterDetails( - x: currentPoint.actualX, y: currentPoint.y, label: dataLabel); + x: currentPoint.actualX, + y: currentPoint.y, + label: dataLabel, + ); dataLabel = _trackball.tooltipFormatter!(tooltipFormatterDetails); } @@ -401,35 +482,41 @@ class TrackballPainter extends CustomPainter { /// Method to get the border radius. BorderRadius _getBorderRadius(BorderRadius borderRadius, double value) { return BorderRadius.only( - topLeft: borderRadius.topLeft.x > value - ? BorderRadius.circular(value).topLeft - : borderRadius.topLeft, - topRight: borderRadius.topRight.x > value - ? BorderRadius.circular(value).topRight - : borderRadius.topRight, - bottomLeft: borderRadius.bottomLeft.x > value - ? BorderRadius.circular(value).bottomLeft - : borderRadius.bottomLeft, - bottomRight: borderRadius.bottomRight.x > value - ? BorderRadius.circular(value).bottomRight - : borderRadius.bottomRight); + topLeft: + borderRadius.topLeft.x > value + ? BorderRadius.circular(value).topLeft + : borderRadius.topLeft, + topRight: + borderRadius.topRight.x > value + ? BorderRadius.circular(value).topRight + : borderRadius.topRight, + bottomLeft: + borderRadius.bottomLeft.x > value + ? BorderRadius.circular(value).bottomLeft + : borderRadius.bottomLeft, + bottomRight: + borderRadius.bottomRight.x > value + ? BorderRadius.circular(value).bottomRight + : borderRadius.bottomRight, + ); } /// Method to draw the trackball rect. void _drawTrackballRect( - Canvas canvas, - Size textSize, - Rect rect, - bool isRight, - BorderRadius borderRadius, - double pointerWidth, - double pointerLength, - Offset screenPoint, - bool isTop, - bool isBottom) { + Canvas canvas, + Size textSize, + Rect rect, + bool isRight, + BorderRadius borderRadius, + double pointerWidth, + double pointerLength, + Offset screenPoint, + bool isTop, + bool isBottom, + ) { final Color backgroundColor = _rendererState._themeData!.tooltipColor!; - final Paint paint = Paint() - ..color = _trackball!.backgroundColor ?? backgroundColor; + final Paint paint = + Paint()..color = _trackball!.backgroundColor ?? backgroundColor; final Path path = Path(); if (!isTop) { if (isRight) { @@ -449,7 +536,9 @@ class TrackballPainter extends CustomPainter { path.moveTo(rect.left + rect.width / 2 - pointerWidth, yValue); path.lineTo(rect.left + rect.width / 2 + pointerWidth, yValue); path.lineTo( - screenPoint.dx, yValue + (isBottom ? -pointerLength : pointerLength)); + screenPoint.dx, + yValue + (isBottom ? -pointerLength : pointerLength), + ); path.lineTo(rect.left + rect.width / 2 - pointerWidth, yValue); } @@ -467,22 +556,29 @@ class TrackballPainter extends CustomPainter { if (_trackball.borderColor != null && _trackball.borderColor != Colors.transparent && _trackball.borderWidth > 0) { - final Paint borderPaint = Paint() - ..color = _trackball.borderColor! - ..strokeWidth = _trackball.borderWidth - ..style = PaintingStyle.stroke; + final Paint borderPaint = + Paint() + ..color = _trackball.borderColor! + ..strokeWidth = _trackball.borderWidth + ..style = PaintingStyle.stroke; canvas.drawPath(path, borderPaint); } } /// Method to render the trackball line. void _drawTrackLine( - Canvas canvas, Rect areaBounds, Offset screenPoint, Size size) { - final Paint paint = Paint() - ..color = - (_trackball!.color ?? _rendererState._themeData!.trackballLineColor)! - ..strokeWidth = _trackball.width - ..style = PaintingStyle.stroke; + Canvas canvas, + Rect areaBounds, + Offset screenPoint, + Size size, + ) { + final Paint paint = + Paint() + ..color = + (_trackball!.color ?? + _rendererState._themeData!.trackballLineColor)! + ..strokeWidth = _trackball.width + ..style = PaintingStyle.stroke; final Offset point1 = Offset(screenPoint.dx, 0); final Offset point2 = Offset(screenPoint.dx, size.height); if (_trackball.dashArray != null && _trackball.dashArray!.isNotEmpty) { diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/enum.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/enum.dart index fee04141f..08e89e343 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/enum.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/enum.dart @@ -6,8 +6,8 @@ typedef SparkChartIndexedValueMapper = R Function(int index); /// Signature for the callback that returns the string value to override the /// default text format of trackball tooltip label. /// -typedef SparkChartTooltipCallback = String Function( - TooltipFormatterDetails details); +typedef SparkChartTooltipCallback = + String Function(TooltipFormatterDetails details); /// Displays the marker on the spark chart widget in different modes. enum SparkChartMarkerDisplayMode { @@ -33,7 +33,7 @@ enum SparkChartMarkerDisplayMode { /// SparkChartMarkerDisplayMode.last allows displaying marker only on the last data /// points in the spark chart widget. - last + last, } /// Displays the marker in different types of shape. @@ -52,7 +52,7 @@ enum SparkChartMarkerShape { /// SparkChartMarkerShape.invertedTriangle displays the marker in an inverted /// triangle shape - invertedTriangle + invertedTriangle, } /// Activates the trackball in different gestures. @@ -93,7 +93,7 @@ enum SparkChartLabelDisplayMode { /// SparkChartLabelDisplayMode.first allows displaying data label only on the /// last data points in the spark chart widget. - last + last, } /// Passes as the argument in the `tooltipFormatter` callback of trackball. diff --git a/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/helper.dart b/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/helper.dart index ccd19c124..c8bb9a389 100644 --- a/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/helper.dart +++ b/packages/syncfusion_flutter_charts/lib/src/sparkline/utils/helper.dart @@ -27,13 +27,15 @@ Size getTextSize(String textValue, TextStyle textStyle) { textAlign: TextAlign.center, textDirection: TextDirection.ltr, text: TextSpan( - text: textValue, - style: TextStyle( - color: textStyle.color, - fontSize: textStyle.fontSize, - fontFamily: textStyle.fontFamily, - fontStyle: textStyle.fontStyle, - fontWeight: textStyle.fontWeight)), + text: textValue, + style: TextStyle( + color: textStyle.color, + fontSize: textStyle.fontSize, + fontFamily: textStyle.fontFamily, + fontStyle: textStyle.fontStyle, + fontWeight: textStyle.fontWeight, + ), + ), ); textPainter.layout(); size = Size(textPainter.width, textPainter.height); @@ -45,10 +47,11 @@ void drawText(Canvas canvas, String dataLabel, Offset point, TextStyle style) { final num maxLines = getMaxLinesContent(dataLabel); final TextSpan span = TextSpan(text: dataLabel, style: style); final TextPainter tp = TextPainter( - text: span, - textDirection: TextDirection.ltr, - textAlign: TextAlign.center, - maxLines: maxLines.toInt()); + text: span, + textDirection: TextDirection.ltr, + textAlign: TextAlign.center, + maxLines: maxLines.toInt(), + ); tp.layout(); canvas.save(); canvas.translate(point.dx, point.dy); @@ -59,8 +62,12 @@ void drawText(Canvas canvas, String dataLabel, Offset point, TextStyle style) { /// Draw the dashed line. void drawDashedPath( - Canvas canvas, Paint paint, Offset moveToPoint, Offset lineToPoint, - [List? dashArray]) { + Canvas canvas, + Paint paint, + Offset moveToPoint, + Offset lineToPoint, [ + List? dashArray, +]) { bool even = false; final Path path = Path(); path.moveTo(moveToPoint.dx, moveToPoint.dy); @@ -74,11 +81,9 @@ void drawDashedPath( } if (even == false) { canvas.drawPath( - _dashPath( - path, - dashArray: DashArrayIntervalList(dashArray), - )!, - paint); + _dashPath(path, dashArray: DashArrayIntervalList(dashArray))!, + paint, + ); } } else { canvas.drawPath(path, paint); @@ -104,7 +109,9 @@ Path? _dashPath( length = dashArray!.next; if (draw) { path.addPath( - measurePath.extractPath(distance, distance + length), Offset.zero); + measurePath.extractPath(distance, distance + length), + Offset.zero, + ); } distance += length; draw = !draw; @@ -116,16 +123,18 @@ Path? _dashPath( /// Returns the Rectangle marker type. Path drawRectangle(Path path, double x, double y, double size) { path.addRect( - Rect.fromLTRB(x - size / 2, y - size / 2, x + size / 2, y + size / 2)); + Rect.fromLTRB(x - size / 2, y - size / 2, x + size / 2, y + size / 2), + ); return path; } /// Returns the circle marker type. Path drawCircle(Path path, double x, double y, double size) { path.addArc( - Rect.fromLTRB(x - size / 2, y - size / 2, x + size / 2, y + size / 2), - 0.0, - 2 * math.pi); + Rect.fromLTRB(x - size / 2, y - size / 2, x + size / 2, y + size / 2), + 0.0, + 2 * math.pi, + ); return path; } @@ -163,8 +172,9 @@ Path drawTriangle(Path path, double x, double y, double size) { /// Method to find the sorted spark chart points. List sortSparkChartPoints(List dataPoints) { - final List sortedPoints = - List.from(dataPoints); + final List sortedPoints = List.from( + dataPoints, + ); sortedPoints.sort((SparkChartPoint firstPoint, SparkChartPoint secondPoint) { firstPoint.x.compareTo(secondPoint.x); if (firstPoint.x < secondPoint.x == true) { @@ -197,22 +207,25 @@ List sortScreenCoordinatePoints(List coordinatePoints) { /// Converts the provided data point to visible point for rendering. Offset transformToCoordinatePoint( - double minX, - double maxX, - double minY, - double maxY, - double diffX, - double diffY, - Size size, - double x, - double y, - int dataLength) { - final double visibleYPoint = (minY != maxY && dataLength != 1) - ? (size.height * (1 - ((y - minY) / diffY))).roundToDouble() - : 0; - final double visibleXPoint = (minX != maxX) - ? (size.width * ((x - minX) / diffX)).roundToDouble() - : size.width / 2; + double minX, + double maxX, + double minY, + double maxY, + double diffX, + double diffY, + Size size, + double x, + double y, + int dataLength, +) { + final double visibleYPoint = + (minY != maxY && dataLength != 1) + ? (size.height * (1 - ((y - minY) / diffY))).roundToDouble() + : 0; + final double visibleXPoint = + (minX != maxX) + ? (size.width * ((x - minX) / diffX)).roundToDouble() + : size.width / 2; return Offset(visibleXPoint, visibleYPoint); } @@ -292,8 +305,12 @@ class SparkChartPoint { /// Represents the spark chart data details. class SparkChartDataDetails { /// Creates the spark chart container box. - SparkChartDataDetails( - {this.data, this.dataCount, this.xValueMapper, this.yValueMapper}); + SparkChartDataDetails({ + this.data, + this.dataCount, + this.xValueMapper, + this.yValueMapper, + }); /// Specifies the list of spark chart data. final List? data; @@ -330,10 +347,7 @@ class _SparKChartContainerBox extends RenderShiftedBox { size = getLayoutSize(constraints, context); child!.layout( - BoxConstraints( - maxHeight: size.height, - maxWidth: size.width, - ), + BoxConstraints(maxHeight: size.height, maxWidth: size.width), ); // True- Parent widget recomputes again respect to // every build of child widget, // False- Parent widget not rebuild respect to child widget build @@ -348,7 +362,10 @@ class _SparKChartContainerBox extends RenderShiftedBox { /// To draw the respective shapes for marker. Path getMarkerShapes( - SparkChartMarkerShape markerShape, Offset position, double size) { + SparkChartMarkerShape markerShape, + Offset position, + double size, +) { final Path path = Path(); switch (markerShape) { case SparkChartMarkerShape.circle: @@ -385,54 +402,59 @@ Path getMarkerShapes( /// To render the marker for line and area series. void renderMarker( - Canvas canvas, - Offset offset, - SparkChartMarker marker, - List coordinatePoints, - List dataPoints, - Color color, - String type, - num highPoint, - num lowPoint, - double axisCrossesAt, - SfSparkChartThemeData themeData, - Color? lowPointColor, - Color? highPointColor, - Color? negativePointColor, - Color? firstPointColor, - Color? lastPointColor) { + Canvas canvas, + Offset offset, + SparkChartMarker marker, + List coordinatePoints, + List dataPoints, + Color color, + String type, + num highPoint, + num lowPoint, + double axisCrossesAt, + SfSparkChartThemeData themeData, + Color? lowPointColor, + Color? highPointColor, + Color? negativePointColor, + Color? firstPointColor, + Color? lastPointColor, +) { final Paint fillPaint = Paint()..style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..color = marker.borderColor ?? color - ..style = PaintingStyle.stroke - ..strokeWidth = marker.borderWidth; + final Paint strokePaint = + Paint() + ..color = marker.borderColor ?? color + ..style = PaintingStyle.stroke + ..strokeWidth = marker.borderWidth; final SparkChartMarkerShape markerShape = marker.shape; final double markerSize = marker.size; final SparkChartMarkerDisplayMode markerDisplayMode = marker.displayMode; final Color themeBasedColor = themeData.markerFillColor!; Path markerPath; final Offset lastMarkerOffset = Offset( - offset.dx + - coordinatePoints[type == 'Line' - ? coordinatePoints.length - 1 - : coordinatePoints.length - 2] - .dx, - offset.dy + - coordinatePoints[type == 'Line' - ? coordinatePoints.length - 1 - : coordinatePoints.length - 2] - .dy); + offset.dx + + coordinatePoints[type == 'Line' + ? coordinatePoints.length - 1 + : coordinatePoints.length - 2] + .dx, + offset.dy + + coordinatePoints[type == 'Line' + ? coordinatePoints.length - 1 + : coordinatePoints.length - 2] + .dy, + ); final Offset firstMarkerOffset = Offset( - offset.dx + coordinatePoints[type == 'Line' ? 0 : 1].dx, - offset.dy + coordinatePoints[type == 'Line' ? 0 : 1].dy); + offset.dx + coordinatePoints[type == 'Line' ? 0 : 1].dx, + offset.dy + coordinatePoints[type == 'Line' ? 0 : 1].dy, + ); switch (markerDisplayMode) { case SparkChartMarkerDisplayMode.all: { - final int length = type == 'Line' - ? coordinatePoints.length - : coordinatePoints.length - 1; + final int length = + type == 'Line' + ? coordinatePoints.length + : coordinatePoints.length - 1; int i = type == 'Line' ? 0 : 1; for (i = i; i < length; i++) { fillPaint.color = marker.color ?? themeBasedColor; @@ -461,10 +483,13 @@ void renderMarker( } markerPath = getMarkerShapes( - markerShape, - Offset(offset.dx + coordinatePoints[i].dx, - offset.dy + coordinatePoints[i].dy), - markerSize); + markerShape, + Offset( + offset.dx + coordinatePoints[i].dx, + offset.dy + coordinatePoints[i].dy, + ), + markerSize, + ); canvas.drawPath(markerPath, fillPaint); canvas.drawPath(markerPath, strokePaint); } @@ -480,8 +505,11 @@ void renderMarker( dataPoints[type == 'Line' ? 0 : 1].y < 0) { fillPaint.color = negativePointColor; } - markerPath = - getMarkerShapes(markerShape, firstMarkerOffset, markerSize); + markerPath = getMarkerShapes( + markerShape, + firstMarkerOffset, + markerSize, + ); canvas.drawPath(markerPath, fillPaint); canvas.drawPath(markerPath, strokePaint); } @@ -514,9 +542,10 @@ void renderMarker( ? fillPaint.color = lowPointColor : fillPaint.color = fillPaint.color; - final int length = type == 'Line' - ? coordinatePoints.length - : coordinatePoints.length - 1; + final int length = + type == 'Line' + ? coordinatePoints.length + : coordinatePoints.length - 1; final int index = type == 'Line' ? 0 : 1; for (int j = index; j < length; j++) { @@ -527,10 +556,13 @@ void renderMarker( } if (highPoint == coordinatePoints[j].dy) { markerPath = getMarkerShapes( - markerShape, - Offset(offset.dx + coordinatePoints[j].dx, - offset.dy + coordinatePoints[j].dy), - markerSize); + markerShape, + Offset( + offset.dx + coordinatePoints[j].dx, + offset.dy + coordinatePoints[j].dy, + ), + markerSize, + ); canvas.drawPath(markerPath, fillPaint); canvas.drawPath(markerPath, strokePaint); } @@ -545,9 +577,10 @@ void renderMarker( ? fillPaint.color = highPointColor : fillPaint.color = fillPaint.color; - final int length = type == 'Line' - ? coordinatePoints.length - : coordinatePoints.length - 1; + final int length = + type == 'Line' + ? coordinatePoints.length + : coordinatePoints.length - 1; final int index = type == 'Line' ? 0 : 1; for (int j = index; j < length; j++) { if (negativePointColor != null && @@ -557,10 +590,13 @@ void renderMarker( } if (lowPoint == coordinatePoints[j].dy) { markerPath = getMarkerShapes( - markerShape, - Offset(offset.dx + coordinatePoints[j].dx, - offset.dy + coordinatePoints[j].dy), - markerSize); + markerShape, + Offset( + offset.dx + coordinatePoints[j].dx, + offset.dy + coordinatePoints[j].dy, + ), + markerSize, + ); canvas.drawPath(markerPath, fillPaint); canvas.drawPath(markerPath, strokePaint); } @@ -574,14 +610,15 @@ void renderMarker( } Color _getDataLabelSaturationColor( - Offset dataLabelOffset, - Offset coordinateOffset, - SfSparkChartThemeData theme, - Offset offset, - Color seriesColor, - String type, - [Rect? segment, - num? yValue]) { + Offset dataLabelOffset, + Offset coordinateOffset, + SfSparkChartThemeData theme, + Offset offset, + Color seriesColor, + String type, [ + Rect? segment, + num? yValue, +]) { Color color; if (type == 'Area') { @@ -596,8 +633,8 @@ Color _getDataLabelSaturationColor( ? color = seriesColor : color = theme.dataLabelBackgroundColor! : dataLabelOffset.dy < (segment!.top + offset.dy) - ? color = seriesColor - : color = theme.dataLabelBackgroundColor!; + ? color = seriesColor + : color = theme.dataLabelBackgroundColor!; } color = getSaturationColor(color); @@ -606,83 +643,102 @@ Color _getDataLabelSaturationColor( } TextStyle _getTextStyle( - TextStyle labelStyle, - Offset dataLabelOffset, - Offset coordinateOffset, - Offset offset, - SfSparkChartThemeData theme, - Color seriesColor, - String type, - [Rect? segment, - num? yValue]) { + TextStyle labelStyle, + Offset dataLabelOffset, + Offset coordinateOffset, + Offset offset, + SfSparkChartThemeData theme, + Color seriesColor, + String type, [ + Rect? segment, + num? yValue, +]) { final TextStyle font = labelStyle; - final Color fontColor = font.color != Colors.transparent - ? font.color! - : _getDataLabelSaturationColor(dataLabelOffset, coordinateOffset, theme, - offset, seriesColor, type, segment, yValue); + final Color fontColor = + font.color != Colors.transparent + ? font.color! + : _getDataLabelSaturationColor( + dataLabelOffset, + coordinateOffset, + theme, + offset, + seriesColor, + type, + segment, + yValue, + ); final TextStyle textStyle = TextStyle( - color: fontColor, - fontFamily: font.fontFamily, - fontSize: font.fontSize, - fontStyle: font.fontStyle, - fontWeight: font.fontWeight, - inherit: font.inherit, - backgroundColor: font.backgroundColor, - letterSpacing: font.letterSpacing, - wordSpacing: font.wordSpacing, - textBaseline: font.textBaseline, - height: font.height, - locale: font.locale, - foreground: font.foreground, - background: font.background, - shadows: font.shadows, - fontFeatures: font.fontFeatures, - decoration: font.decoration, - decorationColor: font.decorationColor, - decorationStyle: font.decorationStyle, - decorationThickness: font.decorationThickness, - debugLabel: font.debugLabel, - fontFamilyFallback: font.fontFamilyFallback); + color: fontColor, + fontFamily: font.fontFamily, + fontSize: font.fontSize, + fontStyle: font.fontStyle, + fontWeight: font.fontWeight, + inherit: font.inherit, + backgroundColor: font.backgroundColor, + letterSpacing: font.letterSpacing, + wordSpacing: font.wordSpacing, + textBaseline: font.textBaseline, + height: font.height, + locale: font.locale, + foreground: font.foreground, + background: font.background, + shadows: font.shadows, + fontFeatures: font.fontFeatures, + decoration: font.decoration, + decorationColor: font.decorationColor, + decorationStyle: font.decorationStyle, + decorationThickness: font.decorationThickness, + debugLabel: font.debugLabel, + fontFamilyFallback: font.fontFamilyFallback, + ); return textStyle; } /// To render the data label. void renderDataLabel( - Canvas canvas, - List dataLabels, - List dataPoints, - List coordinatePoints, - TextStyle labelStyle, - SparkChartLabelDisplayMode labelDisplayMode, - String type, - SfSparkChartThemeData theme, - Offset offset, - Color seriesColor, - num highPoint, - num lowPoint, - [List? segments]) { + Canvas canvas, + List dataLabels, + List dataPoints, + List coordinatePoints, + TextStyle labelStyle, + SparkChartLabelDisplayMode labelDisplayMode, + String type, + SfSparkChartThemeData theme, + Offset offset, + Color seriesColor, + num highPoint, + num lowPoint, [ + List? segments, +]) { TextStyle textStyle; switch (labelDisplayMode) { case SparkChartLabelDisplayMode.all: { - for (int i = type == 'Area' ? 1 : 0; - type == 'Area' ? i < dataPoints.length - 1 : i < dataPoints.length; - i++) { + for ( + int i = type == 'Area' ? 1 : 0; + type == 'Area' ? i < dataPoints.length - 1 : i < dataPoints.length; + i++ + ) { textStyle = _getTextStyle( - labelStyle, - dataPoints[i].dataLabelOffset!, - coordinatePoints[i], - offset, - theme, - type == 'Bar' ? dataPoints[i].color! : seriesColor, - type, - type == 'Bar' ? segments![i] : null, - dataPoints[i].y); + labelStyle, + dataPoints[i].dataLabelOffset!, + coordinatePoints[i], + offset, + theme, + type == 'Bar' ? dataPoints[i].color! : seriesColor, + type, + type == 'Bar' ? segments![i] : null, + dataPoints[i].y, + ); drawText( - canvas, dataLabels[i], dataPoints[i].dataLabelOffset!, textStyle); + canvas, + dataLabels[i], + dataPoints[i].dataLabelOffset!, + textStyle, + ); } } @@ -691,72 +747,87 @@ void renderDataLabel( case SparkChartLabelDisplayMode.first: { textStyle = _getTextStyle( - labelStyle, - dataPoints[type == 'Area' ? 1 : 0].dataLabelOffset!, - coordinatePoints[type == 'Area' ? 1 : 0], - offset, - theme, - type == 'Bar' ? dataPoints[0].color! : seriesColor, - type, - type == 'Bar' ? segments![0] : null, - dataPoints[0].y); - drawText(canvas, dataLabels[type == 'Area' ? 1 : 0], - dataPoints[type == 'Area' ? 1 : 0].dataLabelOffset!, textStyle); + labelStyle, + dataPoints[type == 'Area' ? 1 : 0].dataLabelOffset!, + coordinatePoints[type == 'Area' ? 1 : 0], + offset, + theme, + type == 'Bar' ? dataPoints[0].color! : seriesColor, + type, + type == 'Bar' ? segments![0] : null, + dataPoints[0].y, + ); + drawText( + canvas, + dataLabels[type == 'Area' ? 1 : 0], + dataPoints[type == 'Area' ? 1 : 0].dataLabelOffset!, + textStyle, + ); } break; case SparkChartLabelDisplayMode.last: { textStyle = _getTextStyle( - labelStyle, - dataPoints[type == 'Area' - ? dataPoints.length - 2 - : dataPoints.length - 1] - .dataLabelOffset!, - coordinatePoints[ - type == 'Area' ? dataPoints.length - 2 : dataPoints.length - 1], - offset, - theme, - type == 'Bar' - ? dataPoints[dataPoints.length - 1].color! - : seriesColor, - type, - type == 'Bar' ? segments![dataPoints.length - 1] : null, - dataPoints[dataPoints.length - 1].y); + labelStyle, + dataPoints[type == 'Area' + ? dataPoints.length - 2 + : dataPoints.length - 1] + .dataLabelOffset!, + coordinatePoints[type == 'Area' + ? dataPoints.length - 2 + : dataPoints.length - 1], + offset, + theme, + type == 'Bar' + ? dataPoints[dataPoints.length - 1].color! + : seriesColor, + type, + type == 'Bar' ? segments![dataPoints.length - 1] : null, + dataPoints[dataPoints.length - 1].y, + ); drawText( - canvas, - dataLabels[ - type == 'Area' ? dataPoints.length - 2 : dataPoints.length - 1], - dataPoints[type == 'Area' - ? dataPoints.length - 2 - : dataPoints.length - 1] - .dataLabelOffset!, - textStyle); + canvas, + dataLabels[type == 'Area' + ? dataPoints.length - 2 + : dataPoints.length - 1], + dataPoints[type == 'Area' + ? dataPoints.length - 2 + : dataPoints.length - 1] + .dataLabelOffset!, + textStyle, + ); } break; case SparkChartLabelDisplayMode.low: { - final int length = type == 'Area' - ? coordinatePoints.length - 1 - : coordinatePoints.length; + final int length = + type == 'Area' + ? coordinatePoints.length - 1 + : coordinatePoints.length; final int index = type == 'Area' ? 1 : 0; for (int j = index; j < length; j++) { if (highPoint == coordinatePoints[j].dy) { textStyle = _getTextStyle( - labelStyle, - dataPoints[j].dataLabelOffset!, - coordinatePoints[j], - offset, - theme, - type == 'Bar' ? dataPoints[j].color! : seriesColor, - type, - type == 'Bar' ? segments![j] : null, - dataPoints[j].y); - drawText(canvas, dataLabels[j], dataPoints[j].dataLabelOffset!, - textStyle); + labelStyle, + dataPoints[j].dataLabelOffset!, + coordinatePoints[j], + offset, + theme, + type == 'Bar' ? dataPoints[j].color! : seriesColor, + type, + type == 'Bar' ? segments![j] : null, + dataPoints[j].y, + ); + drawText( + canvas, + dataLabels[j], + dataPoints[j].dataLabelOffset!, + textStyle, + ); } } } @@ -765,25 +836,31 @@ void renderDataLabel( case SparkChartLabelDisplayMode.high: { - final int length = type == 'Area' - ? coordinatePoints.length - 1 - : coordinatePoints.length; + final int length = + type == 'Area' + ? coordinatePoints.length - 1 + : coordinatePoints.length; final int index = type == 'Area' ? 1 : 0; for (int j = index; j < length; j++) { if (lowPoint == coordinatePoints[j].dy) { textStyle = _getTextStyle( - labelStyle, - dataPoints[j].dataLabelOffset!, - coordinatePoints[j], - offset, - theme, - type == 'Bar' ? dataPoints[j].color! : seriesColor, - type, - type == 'Bar' ? segments![j] : null, - dataPoints[j].y); - drawText(canvas, dataLabels[j], dataPoints[j].dataLabelOffset!, - textStyle); + labelStyle, + dataPoints[j].dataLabelOffset!, + coordinatePoints[j], + offset, + theme, + type == 'Bar' ? dataPoints[j].color! : seriesColor, + type, + type == 'Bar' ? segments![j] : null, + dataPoints[j].y, + ); + drawText( + canvas, + dataLabels[j], + dataPoints[j].dataLabelOffset!, + textStyle, + ); } } } diff --git a/packages/syncfusion_flutter_charts/pubspec.yaml b/packages/syncfusion_flutter_charts/pubspec.yaml index d27cc4e8a..34297920b 100644 --- a/packages/syncfusion_flutter_charts/pubspec.yaml +++ b/packages/syncfusion_flutter_charts/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_charts description: A Flutter Charts library which includes data visualization widgets such as cartesian and circular charts, to create real-time, interactive, high-performance, animated charts. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_charts screenshots: @@ -18,7 +18,7 @@ screenshots: path: screenshots/flutter-SparkChart.png environment: - sdk: ">=3.4.0 <4.0.0" + sdk: ^3.7.0 dependencies: flutter: @@ -28,8 +28,11 @@ dependencies: syncfusion_flutter_core: path: ../syncfusion_flutter_core - flutter: + assets: + - images/ + - assets/fonts/Roboto-Medium.ttf + - assets/fonts/Times-New-Roman.ttf diff --git a/packages/syncfusion_flutter_chat/CHANGELOG.md b/packages/syncfusion_flutter_chat/CHANGELOG.md index 657b61df2..59f244028 100644 --- a/packages/syncfusion_flutter_chat/CHANGELOG.md +++ b/packages/syncfusion_flutter_chat/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of our Flutter chat and AI assistView widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter chat and AI assistView widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter chat and AI assistView example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter chat and AI assistView example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_chat/assets/Roboto-Medium.ttf b/packages/syncfusion_flutter_chat/assets/Roboto-Medium.ttf new file mode 100644 index 000000000..d629e9848 Binary files /dev/null and b/packages/syncfusion_flutter_chat/assets/Roboto-Medium.ttf differ diff --git a/packages/syncfusion_flutter_chat/assets/images/AI_in_Avatar.png b/packages/syncfusion_flutter_chat/assets/images/AI_in_Avatar.png new file mode 100644 index 000000000..067e11db2 Binary files /dev/null and b/packages/syncfusion_flutter_chat/assets/images/AI_in_Avatar.png differ diff --git a/packages/syncfusion_flutter_chat/assets/images/People_Circle23.png b/packages/syncfusion_flutter_chat/assets/images/People_Circle23.png new file mode 100644 index 000000000..d7a12ee96 Binary files /dev/null and b/packages/syncfusion_flutter_chat/assets/images/People_Circle23.png differ diff --git a/packages/syncfusion_flutter_chat/assets/images/People_Circle5.png b/packages/syncfusion_flutter_chat/assets/images/People_Circle5.png new file mode 100644 index 000000000..9a1f4b34a Binary files /dev/null and b/packages/syncfusion_flutter_chat/assets/images/People_Circle5.png differ diff --git a/packages/syncfusion_flutter_chat/example/lib/main.dart b/packages/syncfusion_flutter_chat/example/lib/main.dart index 781e19458..ac63954ca 100644 --- a/packages/syncfusion_flutter_chat/example/lib/main.dart +++ b/packages/syncfusion_flutter_chat/example/lib/main.dart @@ -3,10 +3,7 @@ import 'package:syncfusion_flutter_chat/chat.dart'; import 'package:syncfusion_flutter_chat/assist_view.dart'; void main() { - runApp(const MaterialApp( - debugShowCheckedModeBanner: false, - home: MainApp(), - )); + runApp(const MaterialApp(debugShowCheckedModeBanner: false, home: MainApp())); } class MainApp extends StatelessWidget { @@ -15,9 +12,7 @@ class MainApp extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Conversational UI Sample'), - ), + appBar: AppBar(title: const Text('Syncfusion Conversational UI Sample')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -91,30 +86,28 @@ class ChatSampleState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Flutter Chat'), - ), + appBar: AppBar(title: const Text('Syncfusion Flutter Chat')), body: Padding( padding: const EdgeInsets.all(10.0), child: SfChat( messages: _messages, outgoingUser: '8ob3-b720-g9s6-25s8', composer: const ChatComposer( - decoration: InputDecoration( - hintText: 'Type a message', - ), + decoration: InputDecoration(hintText: 'Type a message'), ), actionButton: ChatActionButton( onPressed: (String newMessage) { setState(() { - _messages.add(ChatMessage( - text: newMessage, - time: DateTime.now(), - author: const ChatAuthor( - id: '8ob3-b720-g9s6-25s8', - name: 'Outgoing user name', + _messages.add( + ChatMessage( + text: newMessage, + time: DateTime.now(), + author: const ChatAuthor( + id: '8ob3-b720-g9s6-25s8', + name: 'Outgoing user name', + ), ), - )); + ); }); }, ), @@ -163,17 +156,13 @@ class AssistViewSampleState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Flutter AI AssistView'), - ), + appBar: AppBar(title: const Text('Syncfusion Flutter AI AssistView')), body: Padding( padding: const EdgeInsets.all(10.0), child: SfAIAssistView( messages: _messages, composer: const AssistComposer( - decoration: InputDecoration( - hintText: 'Type a message', - ), + decoration: InputDecoration(hintText: 'Type a message'), ), actionButton: AssistActionButton( onPressed: (String data) { diff --git a/packages/syncfusion_flutter_chat/example/pubspec.yaml b/packages/syncfusion_flutter_chat/example/pubspec.yaml index f46a2b9ad..c898c3c2c 100644 --- a/packages/syncfusion_flutter_chat/example/pubspec.yaml +++ b/packages/syncfusion_flutter_chat/example/pubspec.yaml @@ -4,7 +4,7 @@ version: 1.0.0 publish_to: 'none' environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_chat/lib/src/assist_view/assist_view.dart b/packages/syncfusion_flutter_chat/lib/src/assist_view/assist_view.dart index 7ed9e76d7..a30ad0c6c 100644 --- a/packages/syncfusion_flutter_chat/lib/src/assist_view/assist_view.dart +++ b/packages/syncfusion_flutter_chat/lib/src/assist_view/assist_view.dart @@ -593,18 +593,18 @@ class SfAIAssistView extends StatefulWidget { class _SfAIAssistViewState extends State { final AssistMessageSettings _requestMessageSettings = const AssistMessageSettings( - avatarPadding: EdgeInsetsDirectional.only(start: 16.0), - padding: EdgeInsets.all(8.0), - margin: EdgeInsetsDirectional.only(top: 24.0), - showAuthorAvatar: true, - ); + avatarPadding: EdgeInsetsDirectional.only(start: 16.0), + padding: EdgeInsets.all(8.0), + margin: EdgeInsetsDirectional.only(top: 24.0), + showAuthorAvatar: true, + ); final AssistMessageSettings _responseMessageSettings = const AssistMessageSettings( - avatarPadding: EdgeInsetsDirectional.only(end: 16.0), - padding: EdgeInsetsDirectional.symmetric(vertical: 8.0), - margin: EdgeInsetsDirectional.only(top: 24.0), - showAuthorAvatar: true, - ); + avatarPadding: EdgeInsetsDirectional.only(end: 16.0), + padding: EdgeInsetsDirectional.symmetric(vertical: 8.0), + margin: EdgeInsetsDirectional.only(top: 24.0), + showAuthorAvatar: true, + ); final InputBorder _defaultInputDecorBorder = const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(42.0)), ); @@ -621,69 +621,83 @@ class _SfAIAssistViewState extends State { void _updateThemeData(BuildContext context) { _themeData = Theme.of(context); - _defaultThemeData = _themeData.useMaterial3 - ? AIAssistViewM3ThemeData(context) - : AIAssistViewM2ThemeData(context); + _defaultThemeData = + _themeData.useMaterial3 + ? AIAssistViewM3ThemeData(context) + : AIAssistViewM2ThemeData(context); _userDefinedThemeData = SfAIAssistViewTheme.of(context); final TextStyle contentBaseTextStyle = _themeData.textTheme.bodyMedium! .copyWith(color: _themeData.colorScheme.onSurface); final TextStyle primaryHeaderBaseTextStyle = _themeData - .textTheme.labelMedium! + .textTheme + .labelMedium! .copyWith(color: _themeData.colorScheme.primary); final TextStyle secondaryHeaderBaseTextStyle = _themeData - .textTheme.labelSmall! + .textTheme + .labelSmall! .copyWith(color: _themeData.colorScheme.onSurfaceVariant); _effectiveAssistThemeData = _userDefinedThemeData.copyWith( - actionButtonForegroundColor: widget.actionButton?.foregroundColor ?? + actionButtonForegroundColor: + widget.actionButton?.foregroundColor ?? _userDefinedThemeData.actionButtonForegroundColor ?? _defaultThemeData.actionButtonForegroundColor, - actionButtonBackgroundColor: widget.actionButton?.backgroundColor ?? + actionButtonBackgroundColor: + widget.actionButton?.backgroundColor ?? _userDefinedThemeData.actionButtonBackgroundColor ?? _defaultThemeData.actionButtonBackgroundColor, actionButtonDisabledForegroundColor: _userDefinedThemeData.actionButtonDisabledForegroundColor ?? - _defaultThemeData.actionButtonDisabledForegroundColor, + _defaultThemeData.actionButtonDisabledForegroundColor, actionButtonDisabledBackgroundColor: _userDefinedThemeData.actionButtonDisabledBackgroundColor ?? - _defaultThemeData.actionButtonDisabledBackgroundColor, - actionButtonFocusColor: widget.actionButton?.focusColor ?? + _defaultThemeData.actionButtonDisabledBackgroundColor, + actionButtonFocusColor: + widget.actionButton?.focusColor ?? _userDefinedThemeData.actionButtonFocusColor ?? _defaultThemeData.actionButtonFocusColor, - actionButtonHoverColor: widget.actionButton?.hoverColor ?? + actionButtonHoverColor: + widget.actionButton?.hoverColor ?? _userDefinedThemeData.actionButtonHoverColor ?? _defaultThemeData.actionButtonHoverColor, - actionButtonSplashColor: widget.actionButton?.splashColor ?? + actionButtonSplashColor: + widget.actionButton?.splashColor ?? _userDefinedThemeData.actionButtonSplashColor ?? _defaultThemeData.actionButtonSplashColor, - actionButtonElevation: widget.actionButton?.elevation ?? + actionButtonElevation: + widget.actionButton?.elevation ?? _userDefinedThemeData.actionButtonElevation, - actionButtonFocusElevation: widget.actionButton?.focusElevation ?? + actionButtonFocusElevation: + widget.actionButton?.focusElevation ?? _userDefinedThemeData.actionButtonFocusElevation, - actionButtonHoverElevation: widget.actionButton?.hoverElevation ?? + actionButtonHoverElevation: + widget.actionButton?.hoverElevation ?? _userDefinedThemeData.actionButtonHoverElevation, - actionButtonHighlightElevation: widget.actionButton?.highlightElevation ?? + actionButtonHighlightElevation: + widget.actionButton?.highlightElevation ?? _userDefinedThemeData.actionButtonHighlightElevation, - actionButtonMouseCursor: widget.actionButton?.mouseCursor ?? + actionButtonMouseCursor: + widget.actionButton?.mouseCursor ?? _userDefinedThemeData.actionButtonMouseCursor ?? _defaultThemeData.actionButtonMouseCursor, - actionButtonShape: widget.actionButton?.shape ?? + actionButtonShape: + widget.actionButton?.shape ?? _userDefinedThemeData.actionButtonShape ?? _defaultThemeData.actionButtonShape, requestAvatarBackgroundColor: _userDefinedThemeData.requestAvatarBackgroundColor ?? - _defaultThemeData.requestAvatarBackgroundColor, + _defaultThemeData.requestAvatarBackgroundColor, responseAvatarBackgroundColor: _userDefinedThemeData.responseAvatarBackgroundColor ?? - _defaultThemeData.responseAvatarBackgroundColor, + _defaultThemeData.responseAvatarBackgroundColor, requestMessageBackgroundColor: widget.requestMessageSettings.backgroundColor ?? - _userDefinedThemeData.requestMessageBackgroundColor ?? - _defaultThemeData.requestMessageBackgroundColor, + _userDefinedThemeData.requestMessageBackgroundColor ?? + _defaultThemeData.requestMessageBackgroundColor, responseMessageBackgroundColor: widget.responseMessageSettings.backgroundColor ?? - _userDefinedThemeData.responseMessageBackgroundColor ?? - _defaultThemeData.responseMessageBackgroundColor, + _userDefinedThemeData.responseMessageBackgroundColor ?? + _defaultThemeData.responseMessageBackgroundColor, editorTextStyle: contentBaseTextStyle .merge(_userDefinedThemeData.editorTextStyle) .merge(widget.composer?.textStyle), @@ -705,35 +719,40 @@ class _SfAIAssistViewState extends State { responseSecondaryHeaderTextStyle: secondaryHeaderBaseTextStyle .merge(_userDefinedThemeData.responseSecondaryHeaderTextStyle) .merge(widget.responseMessageSettings.headerTextStyle), - requestMessageShape: widget.requestMessageSettings.shape ?? + requestMessageShape: + widget.requestMessageSettings.shape ?? _userDefinedThemeData.requestMessageShape ?? _defaultThemeData.requestMessageShape, - responseMessageShape: widget.responseMessageSettings.shape ?? + responseMessageShape: + widget.responseMessageSettings.shape ?? _userDefinedThemeData.responseMessageShape ?? _defaultThemeData.responseMessageShape, suggestionItemBackgroundColor: _userDefinedThemeData.suggestionItemBackgroundColor ?? - _defaultThemeData.suggestionItemBackgroundColor, - suggestionItemShape: _userDefinedThemeData.suggestionItemShape ?? + _defaultThemeData.suggestionItemBackgroundColor, + suggestionItemShape: + _userDefinedThemeData.suggestionItemShape ?? _defaultThemeData.suggestionItemShape, responseToolbarItemBackgroundColor: _userDefinedThemeData.responseToolbarItemBackgroundColor ?? - _defaultThemeData.responseToolbarItemBackgroundColor, + _defaultThemeData.responseToolbarItemBackgroundColor, responseToolbarItemShape: _userDefinedThemeData.responseToolbarItemShape ?? - _defaultThemeData.responseToolbarItemShape, + _defaultThemeData.responseToolbarItemShape, ); } TextStyle _suggestionTextStyle(Set states) { TextStyle? userTextStyle; - final TextStyle baseTextStyle = _themeData.textTheme.bodyMedium! - .copyWith(color: _themeData.colorScheme.onSurface); + final TextStyle baseTextStyle = _themeData.textTheme.bodyMedium!.copyWith( + color: _themeData.colorScheme.onSurface, + ); final TextStyle defaultTextStyle = _defaultThemeData.suggestionItemTextStyle!.resolve(states)!; if (_userDefinedThemeData.suggestionItemTextStyle != null) { - userTextStyle = - _userDefinedThemeData.suggestionItemTextStyle?.resolve(states); + userTextStyle = _userDefinedThemeData.suggestionItemTextStyle?.resolve( + states, + ); } return baseTextStyle.merge(userTextStyle).merge(defaultTextStyle); @@ -859,13 +878,16 @@ class _SfAIAssistViewState extends State { children: [ AssistConversationArea( messages: widget.messages, - outgoingBubbleSettings: - _requestMessageSettings.mergeWith(widget.requestMessageSettings), - incomingBubbleSettings: _responseMessageSettings - .mergeWith(widget.responseMessageSettings), + outgoingBubbleSettings: _requestMessageSettings.mergeWith( + widget.requestMessageSettings, + ), + incomingBubbleSettings: _responseMessageSettings.mergeWith( + widget.responseMessageSettings, + ), bubbleAlignment: _toBubbleAlignment(widget.messageAlignment), - placeholderBehavior: - _toPlaceholderBehavior(widget.placeholderBehavior), + placeholderBehavior: _toPlaceholderBehavior( + widget.placeholderBehavior, + ), placeholderBuilder: widget.placeholderBuilder, bubbleHeaderBuilder: widget.messageHeaderBuilder, bubbleAvatarBuilder: widget.messageAvatarBuilder, diff --git a/packages/syncfusion_flutter_chat/lib/src/assist_view/conversion_area.dart b/packages/syncfusion_flutter_chat/lib/src/assist_view/conversion_area.dart index a221a53bd..3ebc03aa9 100644 --- a/packages/syncfusion_flutter_chat/lib/src/assist_view/conversion_area.dart +++ b/packages/syncfusion_flutter_chat/lib/src/assist_view/conversion_area.dart @@ -203,8 +203,10 @@ class _AssistConversationAreaState suggestionItemTextStyle: widget.suggestionItemTextStyle, padding: settings.margin ?? EdgeInsets.zero, contentPadding: settings.padding ?? EdgeInsets.zero, - avatarPadding: - effectiveAvatarPadding(isFromCurrentUser, settings.avatarPadding), + avatarPadding: effectiveAvatarPadding( + isFromCurrentUser, + settings.avatarPadding, + ), headerPadding: settings.headerPadding, footerPadding: settings.footerPadding, avatarSize: settings.avatarSize, @@ -222,8 +224,10 @@ class _AssistConversationAreaState responseToolbarSettings: widget.responseToolbarSettings, themeData: widget.themeData, textDirection: textDirection, - alignmentDirection: - alignmentBasedTextDirection(isFromCurrentUser, textDirection), + alignmentDirection: alignmentBasedTextDirection( + isFromCurrentUser, + textDirection, + ), ); if (index == 0 && @@ -243,10 +247,7 @@ class _AssistConversationAreaState ); } - return KeyedSubtree( - key: IndexedValueKey(index), - child: result, - ); + return KeyedSubtree(key: IndexedValueKey(index), child: result); } } @@ -276,11 +277,15 @@ class _AssistMessageBubble extends MessageBubble { super.secondaryHeaderTextStyle, super.suggestionItemTextStyle, super.padding = const EdgeInsets.all(2.0), - super.contentPadding = - const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + super.contentPadding = const EdgeInsets.symmetric( + horizontal: 16.0, + vertical: 8.0, + ), required super.avatarPadding, - super.headerPadding = - const EdgeInsetsDirectional.only(top: 14.0, bottom: 4.0), + super.headerPadding = const EdgeInsetsDirectional.only( + top: 14.0, + bottom: 4.0, + ), super.footerPadding = const EdgeInsetsDirectional.only(top: 4.0), super.avatarSize = const Size.square(32.0), super.suggestionBackgroundColor, @@ -319,13 +324,13 @@ class _AssistMessageBubble extends MessageBubble { required super.themeData, required super.textDirection, required super.alignmentDirection, - }) : showLoadingIndicator = true, - onSuggestionItemSelected = null, - onToolbarItemSelected = null, - responseToolbarBackgroundColor = null, - responseToolbarBackgroundShape = null, - responseToolbarItemBackgroundColor = null, - responseToolbarItemShape = null; + }) : showLoadingIndicator = true, + onSuggestionItemSelected = null, + onToolbarItemSelected = null, + responseToolbarBackgroundColor = null, + responseToolbarBackgroundShape = null, + responseToolbarItemBackgroundColor = null, + responseToolbarItemShape = null; final bool showLoadingIndicator; final AssistWidgetBuilder? responseLoadingBuilder; @@ -399,9 +404,10 @@ class _AssistMessageBubbleState extends MessageBubbleState { @override Widget buildMessage(BuildContext context) { return Column( - crossAxisAlignment: widget.alignment == BubbleAlignment.end - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + crossAxisAlignment: + widget.alignment == BubbleAlignment.end + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, textDirection: TextDirection.ltr, children: _buildElements(context), @@ -428,10 +434,7 @@ class _AssistMessageBubbleState extends MessageBubbleState { avatarSize: widget.avatarSize, avatarPadding: widget.avatarPadding.resolve(widget.alignmentDirection), alignment: widget.alignment, - children: [ - if (avatar != null) avatar, - buildContent(context), - ], + children: [if (avatar != null) avatar, buildContent(context)], ), ); @@ -478,8 +481,11 @@ class _AssistMessageBubbleState extends MessageBubbleState { Widget _buildLoadingIndicator(BuildContext context, bool showAvatar) { if (widget.responseLoadingBuilder != null) { - return widget.responseLoadingBuilder! - .call(context, widget.index, widget.message); + return widget.responseLoadingBuilder!.call( + context, + widget.index, + widget.message, + ); } final Color edgeColor; @@ -497,9 +503,10 @@ class _AssistMessageBubbleState extends MessageBubbleState { edgeColor: edgeColor, midColor: midColor, avatarSize: showAvatar ? widget.avatarSize : Size.zero, - avatarPadding: showAvatar - ? widget.avatarPadding.resolve(widget.alignmentDirection) - : null, + avatarPadding: + showAvatar + ? widget.avatarPadding.resolve(widget.alignmentDirection) + : null, alignment: widget.alignment, ); } @@ -684,10 +691,7 @@ class _AssistSuggestionItemState extends SuggestionItemState { _AssistSuggestionItem get widget => super.widget as _AssistSuggestionItem; @override - void invokeSelectedCallback( - int suggestionIndex, { - required bool selected, - }) { + void invokeSelectedCallback(int suggestionIndex, {required bool selected}) { final AssistMessageSuggestion suggestion = widget.message.suggestions![suggestionIndex]; widget.onSuggestionItemSelected?.call( @@ -726,9 +730,8 @@ class _ShimmerState extends State<_Shimmer> @override void initState() { - _animationController = AnimationController.unbounded( - vsync: this, - )..repeat(min: -1.0, max: 1.0, period: const Duration(milliseconds: 750)); + _animationController = AnimationController.unbounded(vsync: this) + ..repeat(min: -1.0, max: 1.0, period: const Duration(milliseconds: 750)); super.initState(); } @@ -810,13 +813,13 @@ class _ShimmerRenderBox extends RenderBox { required EdgeInsets? avatarPadding, required BubbleAlignment alignment, required Animation animation, - }) : _bubbleWidth = bubbleWidth, - _edgeColor = edgeColor, - _midColor = midColor, - _avatarSize = avatarSize, - _avatarPadding = avatarPadding, - _alignment = alignment, - _animation = animation; + }) : _bubbleWidth = bubbleWidth, + _edgeColor = edgeColor, + _midColor = midColor, + _avatarSize = avatarSize, + _avatarPadding = avatarPadding, + _alignment = alignment, + _animation = animation; final Animation _animation; final double _stripeHeight = 16.0; @@ -890,11 +893,7 @@ class _ShimmerRenderBox extends RenderBox { ).createShader(offset & size); } - void _drawCircle( - PaintingContext context, - Offset offset, - Paint paint, - ) { + void _drawCircle(PaintingContext context, Offset offset, Paint paint) { context.canvas.drawOval(offset & avatarSize, paint); } @@ -904,8 +903,10 @@ class _ShimmerRenderBox extends RenderBox { Size size, Paint paint, ) { - final RRect rRect = - RRect.fromRectAndRadius(offset & size, _stripeBorderRadius); + final RRect rRect = RRect.fromRectAndRadius( + offset & size, + _stripeBorderRadius, + ); context.canvas.drawRRect(rRect, paint); } @@ -953,8 +954,10 @@ class _ShimmerRenderBox extends RenderBox { case BubbleAlignment.auto: stripeStartX = offset.dx; if (avatarWidth > 0.0) { - circleOffset = - offset.translate(_stripeWidth + avatarPad.left, avatarPad.top); + circleOffset = offset.translate( + _stripeWidth + avatarPad.left, + avatarPad.top, + ); } break; } @@ -1048,10 +1051,7 @@ class _ToolbarArea extends StatelessWidget { ); if (toolbarItem.tooltip != null && toolbarItem.tooltip!.isNotEmpty) { - result = Tooltip( - message: toolbarItem.tooltip, - child: result, - ); + result = Tooltip(message: toolbarItem.tooltip, child: result); } return result; @@ -1175,8 +1175,9 @@ class _ToolbarItemState extends State<_ToolbarItem> { @override void initState() { if (widget.selected) { - _stateChangeNotifier = - ValueNotifier>({WidgetState.selected}); + _stateChangeNotifier = ValueNotifier>({ + WidgetState.selected, + }); } else { _stateChangeNotifier = ValueNotifier>({}); } diff --git a/packages/syncfusion_flutter_chat/lib/src/assist_view/settings.dart b/packages/syncfusion_flutter_chat/lib/src/assist_view/settings.dart index 3222a9b35..b4aaf664c 100644 --- a/packages/syncfusion_flutter_chat/lib/src/assist_view/settings.dart +++ b/packages/syncfusion_flutter_chat/lib/src/assist_view/settings.dart @@ -6,19 +6,21 @@ import '../settings.dart'; typedef AssistWidgetBuilder = BaseWidgetBuilder; /// Callback that get invoked when the toolbar item got selected. -typedef AssistSuggestionItemSelectedCallback = void Function( - bool selected, - int messageIndex, - AssistMessageSuggestion suggestion, - int suggestionIndex, -); - -typedef AssistToolbarItemSelectedCallback = void Function( - bool selected, - int messageIndex, - AssistMessageToolbarItem toolbarItem, - int toolbarItemIndex, -); +typedef AssistSuggestionItemSelectedCallback = + void Function( + bool selected, + int messageIndex, + AssistMessageSuggestion suggestion, + int suggestionIndex, + ); + +typedef AssistToolbarItemSelectedCallback = + void Function( + bool selected, + int messageIndex, + AssistMessageToolbarItem toolbarItem, + int toolbarItemIndex, + ); /// It determined the behavior of the placeholder which is need to be scroll or /// hide when new message added. @@ -156,15 +158,12 @@ enum AssistSuggestionSelectionType { /// } /// ``` class AssistMessage extends Message { - const AssistMessage.request({ - required this.data, - this.time, - this.author, - }) : text = data, - isRequested = true, - suggestions = null, - suggestionSettings = null, - toolbarItems = null; + const AssistMessage.request({required this.data, this.time, this.author}) + : text = data, + isRequested = true, + suggestions = null, + suggestionSettings = null, + toolbarItems = null; const AssistMessage.response({ required this.data, @@ -173,8 +172,8 @@ class AssistMessage extends Message { this.suggestions, this.suggestionSettings, this.toolbarItems, - }) : text = data, - isRequested = false; + }) : text = data, + isRequested = false; /// Content of the message. /// @@ -392,16 +391,9 @@ class AssistMessage extends Message { class AssistMessageAuthor extends MessageAuthor { /// Creates a new [AssistMessageAuthor] with the specified [id], [name], and /// optional [avatar]. - const AssistMessageAuthor({ - this.id, - required this.name, - this.avatar, - }); + const AssistMessageAuthor({this.id, required this.name, this.avatar}); - const AssistMessageAuthor.empty() - : id = '', - name = '', - avatar = null; + const AssistMessageAuthor.empty() : id = '', name = '', avatar = null; /// Unique identifier of the author, it can be used for customize the message /// appearance and behavior. @@ -528,10 +520,8 @@ class AssistMessageAuthor extends MessageAuthor { class AssistMessageSuggestion extends MessageSuggestion { /// Creates a new [AssistMessageSuggestion] with the [data], and optional /// [selected] field. - const AssistMessageSuggestion({ - required this.data, - this.selected = false, - }) : builder = null; + const AssistMessageSuggestion({required this.data, this.selected = false}) + : builder = null; const AssistMessageSuggestion.builder({ required this.builder, @@ -666,20 +656,24 @@ class AssistSuggestionSettings extends SuggestionSettings { this.itemShape, this.textStyle, this.margin = const EdgeInsetsDirectional.symmetric(vertical: 5.0), - this.itemPadding = - const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + this.itemPadding = const EdgeInsets.symmetric( + horizontal: 12.0, + vertical: 8.0, + ), this.orientation = Axis.horizontal, AssistSuggestionOverflow itemOverflow = AssistSuggestionOverflow.wrap, AssistSuggestionSelectionType selectionType = AssistSuggestionSelectionType.single, this.runSpacing = 12.0, this.spacing = 16.0, - }) : itemOverflow = itemOverflow == AssistSuggestionOverflow.wrap - ? SuggestionOverflow.wrap - : SuggestionOverflow.scroll, - selectionType = selectionType == AssistSuggestionSelectionType.single - ? SuggestionSelectionType.single - : SuggestionSelectionType.multiple; + }) : itemOverflow = + itemOverflow == AssistSuggestionOverflow.wrap + ? SuggestionOverflow.wrap + : SuggestionOverflow.scroll, + selectionType = + selectionType == AssistSuggestionSelectionType.single + ? SuggestionSelectionType.single + : SuggestionSelectionType.multiple; /// The [backgroundColor] property sets the background color for the /// suggestion area. @@ -1407,10 +1401,10 @@ class AssistComposer extends Composer { const AssistComposer.builder({ required this.builder, this.margin = const EdgeInsets.only(top: 24.0), - }) : maxLines = 0, - minLines = 0, - textStyle = null, - decoration = null; + }) : maxLines = 0, + minLines = 0, + textStyle = null, + decoration = null; /// The [maxLines] property defines the maximum number of lines the composer /// can occupy. diff --git a/packages/syncfusion_flutter_chat/lib/src/assist_view/theme.dart b/packages/syncfusion_flutter_chat/lib/src/assist_view/theme.dart index 498ccea9e..56382a841 100644 --- a/packages/syncfusion_flutter_chat/lib/src/assist_view/theme.dart +++ b/packages/syncfusion_flutter_chat/lib/src/assist_view/theme.dart @@ -18,14 +18,14 @@ Color _saturatedColor(Color color, double factor) { class AIAssistViewM2ThemeData extends SfAIAssistViewThemeData { AIAssistViewM2ThemeData(this.context) - : super( - requestMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - responseMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - ); + : super( + requestMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + responseMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + ); final BuildContext context; late final ColorScheme _colorScheme = Theme.of(context).colorScheme; @@ -61,8 +61,8 @@ class AIAssistViewM2ThemeData extends SfAIAssistViewThemeData { @override ShapeBorder? get actionButtonShape => const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(20.0)), - ); + borderRadius: BorderRadius.all(Radius.circular(20.0)), + ); @override Color? get requestMessageBackgroundColor => _colorScheme.surfaceContainer; @@ -78,18 +78,16 @@ class AIAssistViewM2ThemeData extends SfAIAssistViewThemeData { @override WidgetStateProperty get suggestionItemBackgroundColor => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused)) { - return _saturatedColor(_colorScheme.surfaceContainer, 0.08); - } - if (states.contains(WidgetState.disabled)) { - return _saturatedColor(_colorScheme.surfaceContainer, 0.12); - } - return _colorScheme.surfaceContainer; - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused)) { + return _saturatedColor(_colorScheme.surfaceContainer, 0.08); + } + if (states.contains(WidgetState.disabled)) { + return _saturatedColor(_colorScheme.surfaceContainer, 0.12); + } + return _colorScheme.surfaceContainer; + }); @override WidgetStateProperty? get suggestionItemShape => @@ -101,19 +99,17 @@ class AIAssistViewM2ThemeData extends SfAIAssistViewThemeData { @override WidgetStateProperty get responseToolbarItemBackgroundColor => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused)) { - return _colorScheme.onSurface.withValues(alpha: 0.08); - } - if (states.contains(WidgetState.pressed) || - states.contains(WidgetState.selected)) { - return _colorScheme.onSurface.withValues(alpha: 0.01); - } - return _colorScheme.surface; - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused)) { + return _colorScheme.onSurface.withValues(alpha: 0.08); + } + if (states.contains(WidgetState.pressed) || + states.contains(WidgetState.selected)) { + return _colorScheme.onSurface.withValues(alpha: 0.01); + } + return _colorScheme.surface; + }); @override WidgetStateProperty? get responseToolbarItemShape => @@ -125,28 +121,26 @@ class AIAssistViewM2ThemeData extends SfAIAssistViewThemeData { @override WidgetStateProperty? get suggestionItemTextStyle => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.disabled)) { - return TextStyle( - color: _colorScheme.onSurface.withValues(alpha: 0.38), - ); - } - return TextStyle(color: _colorScheme.onSurface); - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.disabled)) { + return TextStyle( + color: _colorScheme.onSurface.withValues(alpha: 0.38), + ); + } + return TextStyle(color: _colorScheme.onSurface); + }); } class AIAssistViewM3ThemeData extends SfAIAssistViewThemeData { AIAssistViewM3ThemeData(this.context) - : super( - requestMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - responseMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - ); + : super( + requestMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + responseMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + ); final BuildContext context; late final ColorScheme _colorScheme = Theme.of(context).colorScheme; @@ -182,8 +176,8 @@ class AIAssistViewM3ThemeData extends SfAIAssistViewThemeData { @override ShapeBorder? get actionButtonShape => const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(20.0)), - ); + borderRadius: BorderRadius.all(Radius.circular(20.0)), + ); @override Color? get requestMessageBackgroundColor => _colorScheme.surfaceContainer; @@ -199,18 +193,16 @@ class AIAssistViewM3ThemeData extends SfAIAssistViewThemeData { @override WidgetStateProperty get suggestionItemBackgroundColor => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused)) { - return _saturatedColor(_colorScheme.surfaceContainer, 0.08); - } - if (states.contains(WidgetState.disabled)) { - return _saturatedColor(_colorScheme.surfaceContainer, 0.12); - } - return _colorScheme.surfaceContainer; - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused)) { + return _saturatedColor(_colorScheme.surfaceContainer, 0.08); + } + if (states.contains(WidgetState.disabled)) { + return _saturatedColor(_colorScheme.surfaceContainer, 0.12); + } + return _colorScheme.surfaceContainer; + }); @override WidgetStateProperty? get suggestionItemShape => @@ -222,19 +214,17 @@ class AIAssistViewM3ThemeData extends SfAIAssistViewThemeData { @override WidgetStateProperty get responseToolbarItemBackgroundColor => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused)) { - return _colorScheme.onSurface.withValues(alpha: 0.08); - } - if (states.contains(WidgetState.pressed) || - states.contains(WidgetState.selected)) { - return _colorScheme.onSurface.withValues(alpha: 0.01); - } - return _colorScheme.surface; - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused)) { + return _colorScheme.onSurface.withValues(alpha: 0.08); + } + if (states.contains(WidgetState.pressed) || + states.contains(WidgetState.selected)) { + return _colorScheme.onSurface.withValues(alpha: 0.01); + } + return _colorScheme.surface; + }); @override WidgetStateProperty? get responseToolbarItemShape => @@ -246,14 +236,12 @@ class AIAssistViewM3ThemeData extends SfAIAssistViewThemeData { @override WidgetStateProperty? get suggestionItemTextStyle => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.disabled)) { - return TextStyle( - color: _colorScheme.onSurface.withValues(alpha: 0.38), - ); - } - return TextStyle(color: _colorScheme.onSurface); - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.disabled)) { + return TextStyle( + color: _colorScheme.onSurface.withValues(alpha: 0.38), + ); + } + return TextStyle(color: _colorScheme.onSurface); + }); } diff --git a/packages/syncfusion_flutter_chat/lib/src/base_layout.dart b/packages/syncfusion_flutter_chat/lib/src/base_layout.dart index 889309e04..a96b767a0 100644 --- a/packages/syncfusion_flutter_chat/lib/src/base_layout.dart +++ b/packages/syncfusion_flutter_chat/lib/src/base_layout.dart @@ -30,12 +30,14 @@ class _RenderLayoutHandler extends RenderBox @override void performLayout() { const Size minConstraints = Size(300.0, 300.0); - final double boxWidth = constraints.maxWidth.isFinite - ? constraints.maxWidth - : minConstraints.width; - final double boxHeight = constraints.maxHeight.isFinite - ? constraints.maxHeight - : minConstraints.height; + final double boxWidth = + constraints.maxWidth.isFinite + ? constraints.maxWidth + : minConstraints.width; + final double boxHeight = + constraints.maxHeight.isFinite + ? constraints.maxHeight + : minConstraints.height; double availableHeight = boxHeight; RenderBox? child = lastChild; diff --git a/packages/syncfusion_flutter_chat/lib/src/chat/chat.dart b/packages/syncfusion_flutter_chat/lib/src/chat/chat.dart index 53176a133..e5a0841f3 100644 --- a/packages/syncfusion_flutter_chat/lib/src/chat/chat.dart +++ b/packages/syncfusion_flutter_chat/lib/src/chat/chat.dart @@ -853,69 +853,83 @@ class _SfChatState extends State { void _updateThemeData(BuildContext context) { _themeData = Theme.of(context); - _defaultThemeData = _themeData.useMaterial3 - ? ChatM3ThemeData(context) - : ChatM2ThemeData(context); + _defaultThemeData = + _themeData.useMaterial3 + ? ChatM3ThemeData(context) + : ChatM2ThemeData(context); _userDefinedThemeData = SfChatTheme.of(context); final TextStyle contentBaseTextStyle = _themeData.textTheme.bodyMedium! .copyWith(color: _themeData.colorScheme.onSurface); final TextStyle primaryHeaderBaseTextStyle = _themeData - .textTheme.labelMedium! + .textTheme + .labelMedium! .copyWith(color: _themeData.colorScheme.primary); final TextStyle secondaryHeaderBaseTextStyle = _themeData - .textTheme.labelSmall! + .textTheme + .labelSmall! .copyWith(color: _themeData.colorScheme.onSurfaceVariant); _effectiveChatThemeData = _userDefinedThemeData.copyWith( - actionButtonForegroundColor: widget.actionButton?.foregroundColor ?? + actionButtonForegroundColor: + widget.actionButton?.foregroundColor ?? _userDefinedThemeData.actionButtonForegroundColor ?? _defaultThemeData.actionButtonForegroundColor, - actionButtonBackgroundColor: widget.actionButton?.backgroundColor ?? + actionButtonBackgroundColor: + widget.actionButton?.backgroundColor ?? _userDefinedThemeData.actionButtonBackgroundColor ?? _defaultThemeData.actionButtonBackgroundColor, actionButtonDisabledForegroundColor: _userDefinedThemeData.actionButtonDisabledForegroundColor ?? - _defaultThemeData.actionButtonDisabledForegroundColor, + _defaultThemeData.actionButtonDisabledForegroundColor, actionButtonDisabledBackgroundColor: _userDefinedThemeData.actionButtonDisabledBackgroundColor ?? - _defaultThemeData.actionButtonDisabledBackgroundColor, - actionButtonFocusColor: widget.actionButton?.focusColor ?? + _defaultThemeData.actionButtonDisabledBackgroundColor, + actionButtonFocusColor: + widget.actionButton?.focusColor ?? _userDefinedThemeData.actionButtonFocusColor ?? _defaultThemeData.actionButtonFocusColor, - actionButtonHoverColor: widget.actionButton?.hoverColor ?? + actionButtonHoverColor: + widget.actionButton?.hoverColor ?? _userDefinedThemeData.actionButtonHoverColor ?? _defaultThemeData.actionButtonHoverColor, - actionButtonSplashColor: widget.actionButton?.splashColor ?? + actionButtonSplashColor: + widget.actionButton?.splashColor ?? _userDefinedThemeData.actionButtonSplashColor ?? _defaultThemeData.actionButtonSplashColor, - actionButtonElevation: widget.actionButton?.elevation ?? + actionButtonElevation: + widget.actionButton?.elevation ?? _userDefinedThemeData.actionButtonElevation, - actionButtonFocusElevation: widget.actionButton?.focusElevation ?? + actionButtonFocusElevation: + widget.actionButton?.focusElevation ?? _userDefinedThemeData.actionButtonFocusElevation, - actionButtonHoverElevation: widget.actionButton?.hoverElevation ?? + actionButtonHoverElevation: + widget.actionButton?.hoverElevation ?? _userDefinedThemeData.actionButtonHoverElevation, - actionButtonHighlightElevation: widget.actionButton?.highlightElevation ?? + actionButtonHighlightElevation: + widget.actionButton?.highlightElevation ?? _userDefinedThemeData.actionButtonHighlightElevation, - actionButtonMouseCursor: widget.actionButton?.mouseCursor ?? + actionButtonMouseCursor: + widget.actionButton?.mouseCursor ?? _userDefinedThemeData.actionButtonMouseCursor ?? _defaultThemeData.actionButtonMouseCursor, - actionButtonShape: widget.actionButton?.shape ?? + actionButtonShape: + widget.actionButton?.shape ?? _userDefinedThemeData.actionButtonShape ?? _defaultThemeData.actionButtonShape, outgoingAvatarBackgroundColor: _userDefinedThemeData.outgoingAvatarBackgroundColor ?? - _defaultThemeData.outgoingAvatarBackgroundColor, + _defaultThemeData.outgoingAvatarBackgroundColor, incomingAvatarBackgroundColor: _userDefinedThemeData.incomingAvatarBackgroundColor ?? - _defaultThemeData.incomingAvatarBackgroundColor, + _defaultThemeData.incomingAvatarBackgroundColor, outgoingMessageBackgroundColor: widget.outgoingMessageSettings.backgroundColor ?? - _userDefinedThemeData.outgoingMessageBackgroundColor ?? - _defaultThemeData.outgoingMessageBackgroundColor, + _userDefinedThemeData.outgoingMessageBackgroundColor ?? + _defaultThemeData.outgoingMessageBackgroundColor, incomingMessageBackgroundColor: widget.incomingMessageSettings.backgroundColor ?? - _userDefinedThemeData.incomingMessageBackgroundColor ?? - _defaultThemeData.incomingMessageBackgroundColor, + _userDefinedThemeData.incomingMessageBackgroundColor ?? + _defaultThemeData.incomingMessageBackgroundColor, editorTextStyle: contentBaseTextStyle .merge(_userDefinedThemeData.editorTextStyle) .merge(widget.composer?.textStyle), @@ -937,29 +951,34 @@ class _SfChatState extends State { incomingSecondaryHeaderTextStyle: secondaryHeaderBaseTextStyle .merge(_userDefinedThemeData.incomingSecondaryHeaderTextStyle) .merge(widget.incomingMessageSettings.headerTextStyle), - outgoingMessageShape: widget.outgoingMessageSettings.shape ?? + outgoingMessageShape: + widget.outgoingMessageSettings.shape ?? _userDefinedThemeData.outgoingMessageShape ?? _defaultThemeData.outgoingMessageShape, - incomingMessageShape: widget.incomingMessageSettings.shape ?? + incomingMessageShape: + widget.incomingMessageSettings.shape ?? _userDefinedThemeData.incomingMessageShape ?? _defaultThemeData.incomingMessageShape, suggestionItemBackgroundColor: _userDefinedThemeData.suggestionItemBackgroundColor ?? - _defaultThemeData.suggestionItemBackgroundColor, - suggestionItemShape: _userDefinedThemeData.suggestionItemShape ?? + _defaultThemeData.suggestionItemBackgroundColor, + suggestionItemShape: + _userDefinedThemeData.suggestionItemShape ?? _defaultThemeData.suggestionItemShape, ); } TextStyle _suggestionTextStyle(Set states) { TextStyle? userTextStyle; - final TextStyle baseTextStyle = _themeData.textTheme.bodyMedium! - .copyWith(color: _themeData.colorScheme.onSurface); + final TextStyle baseTextStyle = _themeData.textTheme.bodyMedium!.copyWith( + color: _themeData.colorScheme.onSurface, + ); final TextStyle defaultTextStyle = _defaultThemeData.suggestionItemTextStyle!.resolve(states)!; if (_userDefinedThemeData.suggestionItemTextStyle != null) { - userTextStyle = - _userDefinedThemeData.suggestionItemTextStyle?.resolve(states); + userTextStyle = _userDefinedThemeData.suggestionItemTextStyle?.resolve( + states, + ); } return baseTextStyle.merge(userTextStyle).merge(defaultTextStyle); diff --git a/packages/syncfusion_flutter_chat/lib/src/chat/conversion_area.dart b/packages/syncfusion_flutter_chat/lib/src/chat/conversion_area.dart index c7d577576..6b773580d 100644 --- a/packages/syncfusion_flutter_chat/lib/src/chat/conversion_area.dart +++ b/packages/syncfusion_flutter_chat/lib/src/chat/conversion_area.dart @@ -138,8 +138,10 @@ class _ChatConversationAreaState extends ConversationAreaState { suggestionItemTextStyle: widget.suggestionItemTextStyle, padding: settings.padding ?? EdgeInsets.zero, contentPadding: settings.padding ?? EdgeInsets.zero, - avatarPadding: - effectiveAvatarPadding(isFromCurrentUser, settings.avatarPadding), + avatarPadding: effectiveAvatarPadding( + isFromCurrentUser, + settings.avatarPadding, + ), headerPadding: settings.headerPadding, footerPadding: settings.footerPadding, avatarSize: settings.avatarSize, @@ -150,8 +152,10 @@ class _ChatConversationAreaState extends ConversationAreaState { onSuggestionItemSelected: widget.onSuggestionItemSelected, themeData: widget.themeData, textDirection: textDirection, - alignmentDirection: - alignmentBasedTextDirection(isFromCurrentUser, textDirection), + alignmentDirection: alignmentBasedTextDirection( + isFromCurrentUser, + textDirection, + ), ); if (index == 0 && @@ -171,10 +175,7 @@ class _ChatConversationAreaState extends ConversationAreaState { ); } - return KeyedSubtree( - key: IndexedValueKey(index), - child: result, - ); + return KeyedSubtree(key: IndexedValueKey(index), child: result); } } @@ -204,11 +205,15 @@ class _ChatMessageBubble extends MessageBubble { super.secondaryHeaderTextStyle, super.suggestionItemTextStyle, super.padding = const EdgeInsets.all(2.0), - super.contentPadding = - const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + super.contentPadding = const EdgeInsets.symmetric( + horizontal: 16.0, + vertical: 8.0, + ), required super.avatarPadding, - super.headerPadding = - const EdgeInsetsDirectional.only(top: 14.0, bottom: 4.0), + super.headerPadding = const EdgeInsetsDirectional.only( + top: 14.0, + bottom: 4.0, + ), super.footerPadding = const EdgeInsetsDirectional.only(top: 4.0), super.avatarSize = const Size.square(32.0), super.suggestionBackgroundColor, @@ -237,9 +242,10 @@ class _ChatMessageBubbleState extends MessageBubbleState { final ChatMessage current = widget.message; final ChatMessage? previous = widget.index - 1 >= 0 ? widget.messages[widget.index - 1] : null; - final ChatMessage? next = widget.index + 1 < messageCount - ? widget.messages[widget.index + 1] - : null; + final ChatMessage? next = + widget.index + 1 < messageCount + ? widget.messages[widget.index + 1] + : null; final EdgeInsets padding = super.effectiveMessagePadding(); double top = padding.top; @@ -478,10 +484,7 @@ class _ChatSuggestionItemState extends SuggestionItemState { _ChatSuggestionItem get widget => super.widget as _ChatSuggestionItem; @override - void invokeSelectedCallback( - int suggestionIndex, { - required bool selected, - }) { + void invokeSelectedCallback(int suggestionIndex, {required bool selected}) { final ChatMessageSuggestion suggestion = widget.message.suggestions![suggestionIndex]; widget.onSuggestionItemSelected?.call( diff --git a/packages/syncfusion_flutter_chat/lib/src/chat/settings.dart b/packages/syncfusion_flutter_chat/lib/src/chat/settings.dart index 3bf4456fc..f8289d413 100644 --- a/packages/syncfusion_flutter_chat/lib/src/chat/settings.dart +++ b/packages/syncfusion_flutter_chat/lib/src/chat/settings.dart @@ -14,12 +14,13 @@ typedef ChatWidgetBuilder = BaseWidgetBuilder; /// It takes a [selected] flag, the [messageIndex] for the message, /// the [suggestion] being interacted with, and the [suggestionIndex] /// indicating the position of the suggestion. -typedef ChatSuggestionItemSelectedCallback = void Function( - bool selected, - int messageIndex, - ChatMessageSuggestion suggestion, - int suggestionIndex, -); +typedef ChatSuggestionItemSelectedCallback = + void Function( + bool selected, + int messageIndex, + ChatMessageSuggestion suggestion, + int suggestionIndex, + ); /// Mode to handle the chat Suggestion items overflow. enum ChatSuggestionOverflow { @@ -293,11 +294,7 @@ class ChatMessage extends Message { class ChatAuthor extends MessageAuthor { /// Creates a new [ChatAuthor] with the specified [id], [name], and optional /// [avatar]. - const ChatAuthor({ - required this.id, - required this.name, - this.avatar, - }); + const ChatAuthor({required this.id, required this.name, this.avatar}); /// Unique identifier for the author which contains information about /// user name and user ID. @@ -411,10 +408,8 @@ class ChatAuthor extends MessageAuthor { class ChatMessageSuggestion extends MessageSuggestion { /// Creates a [ChatMessageSuggestion] with the given [data] and /// optional [selected]. - const ChatMessageSuggestion({ - required this.data, - this.selected = false, - }) : builder = null; + const ChatMessageSuggestion({required this.data, this.selected = false}) + : builder = null; const ChatMessageSuggestion.builder({ required this.builder, @@ -571,20 +566,24 @@ class ChatSuggestionSettings extends SuggestionSettings { this.itemShape, this.textStyle, this.margin = const EdgeInsetsDirectional.symmetric(vertical: 5.0), - this.itemPadding = - const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + this.itemPadding = const EdgeInsets.symmetric( + horizontal: 12.0, + vertical: 8.0, + ), this.orientation = Axis.horizontal, ChatSuggestionOverflow itemOverflow = ChatSuggestionOverflow.wrap, ChatSuggestionSelectionType selectionType = ChatSuggestionSelectionType.single, this.runSpacing = 12.0, this.spacing = 16.0, - }) : itemOverflow = itemOverflow == ChatSuggestionOverflow.scroll - ? SuggestionOverflow.scroll - : SuggestionOverflow.wrap, - selectionType = selectionType == ChatSuggestionSelectionType.multiple - ? SuggestionSelectionType.multiple - : SuggestionSelectionType.single; + }) : itemOverflow = + itemOverflow == ChatSuggestionOverflow.scroll + ? SuggestionOverflow.scroll + : SuggestionOverflow.wrap, + selectionType = + selectionType == ChatSuggestionSelectionType.multiple + ? SuggestionSelectionType.multiple + : SuggestionSelectionType.single; /// Background color of the suggestion area. /// @@ -1283,10 +1282,10 @@ class ChatComposer extends Composer { const ChatComposer.builder({ required this.builder, this.margin = const EdgeInsets.only(top: 16.0), - }) : textStyle = null, - decoration = null, - minLines = 0, - maxLines = 0; + }) : textStyle = null, + decoration = null, + minLines = 0, + maxLines = 0; /// Maximum number of lines the text input field can contain. /// diff --git a/packages/syncfusion_flutter_chat/lib/src/chat/theme.dart b/packages/syncfusion_flutter_chat/lib/src/chat/theme.dart index f878528c3..386e718f7 100644 --- a/packages/syncfusion_flutter_chat/lib/src/chat/theme.dart +++ b/packages/syncfusion_flutter_chat/lib/src/chat/theme.dart @@ -3,14 +3,14 @@ import 'package:syncfusion_flutter_core/theme.dart'; class ChatM2ThemeData extends SfChatThemeData { ChatM2ThemeData(this.context) - : super( - outgoingMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - incomingMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - ); + : super( + outgoingMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + incomingMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + ); final BuildContext context; late final ColorScheme _colorScheme = Theme.of(context).colorScheme; @@ -46,8 +46,8 @@ class ChatM2ThemeData extends SfChatThemeData { @override ShapeBorder? get actionButtonShape => const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(20.0)), - ); + borderRadius: BorderRadius.all(Radius.circular(20.0)), + ); @override Color? get outgoingMessageBackgroundColor => _colorScheme.primaryContainer; @@ -63,54 +63,48 @@ class ChatM2ThemeData extends SfChatThemeData { @override WidgetStateProperty get suggestionItemBackgroundColor => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused)) { - return _colorScheme.surfaceContainer.withValues(alpha: 0.8); - } - if (states.contains(WidgetState.pressed) || - states.contains(WidgetState.disabled)) { - return _colorScheme.surfaceContainer.withValues(alpha: 0.12); - } - return _colorScheme.surfaceContainer; - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused)) { + return _colorScheme.surfaceContainer.withValues(alpha: 0.8); + } + if (states.contains(WidgetState.pressed) || + states.contains(WidgetState.disabled)) { + return _colorScheme.surfaceContainer.withValues(alpha: 0.12); + } + return _colorScheme.surfaceContainer; + }); @override WidgetStateProperty? get suggestionItemShape => - WidgetStateProperty.resolveWith( - (Set states) { - return const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8.0)), - ); - }, - ); + WidgetStateProperty.resolveWith((Set states) { + return const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8.0)), + ); + }); @override WidgetStateProperty? get suggestionItemTextStyle => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.disabled)) { - return TextStyle( - color: _colorScheme.onSurface.withValues(alpha: 0.38), - ); - } - return TextStyle(color: _colorScheme.onSurface); - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.disabled)) { + return TextStyle( + color: _colorScheme.onSurface.withValues(alpha: 0.38), + ); + } + return TextStyle(color: _colorScheme.onSurface); + }); } class ChatM3ThemeData extends SfChatThemeData { ChatM3ThemeData(this.context) - : super( - outgoingMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - incomingMessageShape: const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), - ); + : super( + outgoingMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + incomingMessageShape: const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), + ); final BuildContext context; late final ColorScheme _colorScheme = Theme.of(context).colorScheme; @@ -146,8 +140,8 @@ class ChatM3ThemeData extends SfChatThemeData { @override ShapeBorder? get actionButtonShape => const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(20.0)), - ); + borderRadius: BorderRadius.all(Radius.circular(20.0)), + ); @override Color? get outgoingMessageBackgroundColor => _colorScheme.primaryContainer; @@ -163,40 +157,34 @@ class ChatM3ThemeData extends SfChatThemeData { @override WidgetStateProperty get suggestionItemBackgroundColor => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.hovered) || - states.contains(WidgetState.focused)) { - return _colorScheme.surfaceContainer.withValues(alpha: 0.8); - } - if (states.contains(WidgetState.pressed) || - states.contains(WidgetState.disabled)) { - return _colorScheme.surfaceContainer.withValues(alpha: 0.12); - } - return _colorScheme.surfaceContainer; - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused)) { + return _colorScheme.surfaceContainer.withValues(alpha: 0.8); + } + if (states.contains(WidgetState.pressed) || + states.contains(WidgetState.disabled)) { + return _colorScheme.surfaceContainer.withValues(alpha: 0.12); + } + return _colorScheme.surfaceContainer; + }); @override WidgetStateProperty? get suggestionItemShape => - WidgetStateProperty.resolveWith( - (Set states) { - return const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(8.0)), - ); - }, - ); + WidgetStateProperty.resolveWith((Set states) { + return const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(8.0)), + ); + }); @override WidgetStateProperty? get suggestionItemTextStyle => - WidgetStateProperty.resolveWith( - (Set states) { - if (states.contains(WidgetState.disabled)) { - return TextStyle( - color: _colorScheme.onSurface.withValues(alpha: 0.38), - ); - } - return TextStyle(color: _colorScheme.onSurface); - }, - ); + WidgetStateProperty.resolveWith((Set states) { + if (states.contains(WidgetState.disabled)) { + return TextStyle( + color: _colorScheme.onSurface.withValues(alpha: 0.38), + ); + } + return TextStyle(color: _colorScheme.onSurface); + }); } diff --git a/packages/syncfusion_flutter_chat/lib/src/composer_area.dart b/packages/syncfusion_flutter_chat/lib/src/composer_area.dart index 9e7edacac..33b26e227 100644 --- a/packages/syncfusion_flutter_chat/lib/src/composer_area.dart +++ b/packages/syncfusion_flutter_chat/lib/src/composer_area.dart @@ -37,10 +37,7 @@ class TextEditor extends StatelessWidget { } if (composer.margin != EdgeInsets.zero) { - result = Padding( - padding: composer.margin, - child: result, - ); + result = Padding(padding: composer.margin, child: result); } return result; @@ -108,9 +105,10 @@ class _ActionButtonWidgetState extends State { return Icon( Icons.send, size: _defaultActionButtonIconSize, - color: enabled - ? widget.actionButtonForegroundColor - : widget.actionButtonDisabledForegroundColor, + color: + enabled + ? widget.actionButtonForegroundColor + : widget.actionButtonDisabledForegroundColor, ); } } @@ -136,7 +134,8 @@ class _ActionButtonWidgetState extends State { @override void initState() { widget.textController.addListener(_handleTextChange); - _editorIsEmpty = widget.composer != null && + _editorIsEmpty = + widget.composer != null && widget.composer!.builder == null && widget.textController.text.isEmpty; super.initState(); @@ -160,9 +159,10 @@ class _ActionButtonWidgetState extends State { hoverElevation: widget.actionButtonHoverElevation, highlightElevation: widget.actionButtonHighlightElevation, disabledElevation: widget.actionButtonDisabledElevation, - fillColor: enabled - ? widget.actionButtonBackgroundColor - : widget.actionButtonDisabledBackgroundColor, + fillColor: + enabled + ? widget.actionButtonBackgroundColor + : widget.actionButtonDisabledBackgroundColor, focusColor: widget.actionButtonFocusColor, hoverColor: widget.actionButtonHoverColor, splashColor: widget.actionButtonSplashColor, diff --git a/packages/syncfusion_flutter_chat/lib/src/conversion_area.dart b/packages/syncfusion_flutter_chat/lib/src/conversion_area.dart index 4a3f79155..fc3f6374f 100644 --- a/packages/syncfusion_flutter_chat/lib/src/conversion_area.dart +++ b/packages/syncfusion_flutter_chat/lib/src/conversion_area.dart @@ -235,11 +235,15 @@ abstract class MessageBubble extends StatefulWidget { this.secondaryHeaderTextStyle, this.suggestionItemTextStyle, this.padding = const EdgeInsets.all(2.0), - this.contentPadding = - const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + this.contentPadding = const EdgeInsets.symmetric( + horizontal: 16.0, + vertical: 8.0, + ), required this.avatarPadding, - this.headerPadding = - const EdgeInsetsDirectional.only(top: 14.0, bottom: 4.0), + this.headerPadding = const EdgeInsetsDirectional.only( + top: 14.0, + bottom: 4.0, + ), this.footerPadding = const EdgeInsetsDirectional.only(top: 4.0), this.avatarSize = const Size.square(32.0), this.suggestionBackgroundColor, @@ -297,9 +301,10 @@ abstract class MessageBubbleState extends State> { final Widget? suggestion = buildSuggestion(context); final Widget? footer = buildFooter(context); return Column( - crossAxisAlignment: widget.alignment == BubbleAlignment.end - ? CrossAxisAlignment.end - : CrossAxisAlignment.start, + crossAxisAlignment: + widget.alignment == BubbleAlignment.end + ? CrossAxisAlignment.end + : CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, textDirection: TextDirection.ltr, children: [ @@ -307,13 +312,11 @@ abstract class MessageBubbleState extends State> { BubbleLayout( showUserAvatar: hasAvatar(), avatarSize: widget.avatarSize, - avatarPadding: - widget.avatarPadding.resolve(widget.alignmentDirection), + avatarPadding: widget.avatarPadding.resolve( + widget.alignmentDirection, + ), alignment: widget.alignment, - children: [ - if (avatar != null) avatar, - buildContent(context), - ], + children: [if (avatar != null) avatar, buildContent(context)], ), if (suggestion != null) suggestion, if (footer != null) footer, @@ -352,8 +355,9 @@ abstract class MessageBubbleState extends State> { child: result, ); - final EdgeInsets effectiveAvatarPadding = - widget.avatarPadding.resolve(widget.alignmentDirection); + final EdgeInsets effectiveAvatarPadding = widget.avatarPadding.resolve( + widget.alignmentDirection, + ); if (effectiveAvatarPadding != EdgeInsets.zero) { result = Padding(padding: effectiveAvatarPadding, child: result); } @@ -400,11 +404,12 @@ abstract class MessageBubbleState extends State> { Widget buildText(); double availableContentWidth() { - final double sizeToBeExcluded = hasAvatar() - ? widget.avatarSize.width + - widget.avatarPadding.horizontal + - widget.padding.horizontal - : widget.padding.horizontal; + final double sizeToBeExcluded = + hasAvatar() + ? widget.avatarSize.width + + widget.avatarPadding.horizontal + + widget.padding.horizontal + : widget.padding.horizontal; final double availableWidth = widget.maxWidth - sizeToBeExcluded; return clampDouble( availableWidth * widget.widthFactor, @@ -416,8 +421,11 @@ abstract class MessageBubbleState extends State> { Widget? buildSuggestion(BuildContext context); Widget? buildFooter(BuildContext context) { - Widget? result = - widget.footerBuilder?.call(context, widget.index, widget.message); + Widget? result = widget.footerBuilder?.call( + context, + widget.index, + widget.message, + ); if (result != null && widget.footerPadding != EdgeInsets.zero) { result = Padding( padding: widget.footerPadding.resolve(widget.alignmentDirection), @@ -525,10 +533,10 @@ class RenderBubbleLayout extends RenderBox required Size avatarSize, required EdgeInsets avatarPadding, required BubbleAlignment alignment, - }) : _showUserAvatar = showUserAvatar, - _avatarSize = avatarSize, - _avatarPadding = avatarPadding, - _alignment = alignment; + }) : _showUserAvatar = showUserAvatar, + _avatarSize = avatarSize, + _avatarPadding = avatarPadding, + _alignment = alignment; BubbleAlignment get alignment => _alignment; BubbleAlignment _alignment = BubbleAlignment.auto; @@ -720,10 +728,7 @@ abstract class SuggestionAreaState extends State> { } if (widget.padding != EdgeInsets.zero) { - result = Padding( - padding: widget.padding, - child: result, - ); + result = Padding(padding: widget.padding, child: result); } if (widget.shape != null && @@ -902,10 +907,7 @@ abstract class SuggestionItemState extends State> { invokeSelectedCallback(selectedIndex, selected: true); } - void invokeSelectedCallback( - int suggestionIndex, { - required bool selected, - }); + void invokeSelectedCallback(int suggestionIndex, {required bool selected}); Widget _buildContent(BuildContext context) { Widget? result; @@ -919,10 +921,7 @@ abstract class SuggestionItemState extends State> { } if (widget.itemPadding != EdgeInsets.zero) { - result = Padding( - padding: widget.itemPadding, - child: result, - ); + result = Padding(padding: widget.itemPadding, child: result); } return result; @@ -951,8 +950,9 @@ abstract class SuggestionItemState extends State> { if (widget.enabled) { if (widget.selected) { if (widget.selectionType == SuggestionSelectionType.single) { - _stateChangeNotifier = - ValueNotifier>({WidgetState.selected}); + _stateChangeNotifier = ValueNotifier>({ + WidgetState.selected, + }); } else { _stateChangeNotifier = ValueNotifier>({}); } @@ -960,8 +960,9 @@ abstract class SuggestionItemState extends State> { _stateChangeNotifier = ValueNotifier>({}); } } else { - _stateChangeNotifier = - ValueNotifier>({WidgetState.disabled}); + _stateChangeNotifier = ValueNotifier>({ + WidgetState.disabled, + }); } super.initState(); } @@ -1020,8 +1021,11 @@ abstract class SuggestionItemState extends State> { absorbing: !widget.enabled || widget.selected, child: ValueListenableBuilder>( valueListenable: _stateChangeNotifier, - builder: - (BuildContext context, Set states, Widget? child) { + builder: ( + BuildContext context, + Set states, + Widget? child, + ) { return BorderShape( shape: widget.itemShape?.resolve(states), color: widget.itemBackgroundColor?.resolve(states), @@ -1086,8 +1090,8 @@ class RenderBorderShapeBox extends RenderProxyBox { Color? color, this.states, this.shadowDetails, - }) : _shape = shape, - _color = color; + }) : _shape = shape, + _color = color; Set? states; List Function(Set)? shadowDetails; @@ -1134,8 +1138,10 @@ class RenderBorderShapeBox extends RenderProxyBox { } } - context.canvas - .drawPath(shape!.getOuterPath(bounds), Paint()..color = color!); + context.canvas.drawPath( + shape!.getOuterPath(bounds), + Paint()..color = color!, + ); } context.paintChild(child!, offset); diff --git a/packages/syncfusion_flutter_chat/lib/src/settings.dart b/packages/syncfusion_flutter_chat/lib/src/settings.dart index b27032453..1408b23da 100644 --- a/packages/syncfusion_flutter_chat/lib/src/settings.dart +++ b/packages/syncfusion_flutter_chat/lib/src/settings.dart @@ -1,37 +1,16 @@ import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; -typedef BaseWidgetBuilder = Widget Function( - BuildContext context, - int index, - T message, -); +typedef BaseWidgetBuilder = + Widget Function(BuildContext context, int index, T message); -enum PlaceholderBehavior { - hideOnMessage, +enum PlaceholderBehavior { hideOnMessage, scrollWithMessage } - scrollWithMessage, -} - -enum BubbleAlignment { - start, - - end, - - auto, -} +enum BubbleAlignment { start, end, auto } -enum SuggestionOverflow { - scroll, +enum SuggestionOverflow { scroll, wrap } - wrap, -} - -enum SuggestionSelectionType { - single, - - multiple, -} +enum SuggestionSelectionType { single, multiple } /// Represents a message. abstract class Message { diff --git a/packages/syncfusion_flutter_chat/pubspec.yaml b/packages/syncfusion_flutter_chat/pubspec.yaml index f479b6218..c9ca5e491 100644 --- a/packages/syncfusion_flutter_chat/pubspec.yaml +++ b/packages/syncfusion_flutter_chat/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_chat description: The Flutter Chat package is a UI library designed for creating customizable chat applications, both standard and AI-driven, using Flutter. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_chat screenshots: @@ -10,7 +10,7 @@ screenshots: path: screenshots/flutter_appointment_selection_chat.gif environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 flutter: ">=3.22.0" dependencies: @@ -23,3 +23,9 @@ dependencies: + +flutter: + uses-material-design: true + assets: + - assets/Roboto-Medium.ttf + - assets/images/ \ No newline at end of file diff --git a/packages/syncfusion_flutter_core/CHANGELOG.md b/packages/syncfusion_flutter_core/CHANGELOG.md index 3b975ab97..6c538493f 100644 --- a/packages/syncfusion_flutter_core/CHANGELOG.md +++ b/packages/syncfusion_flutter_core/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of all our Flutter widgets has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of all our Flutter widgets has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter core example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter core example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_core/example/lib/main.dart b/packages/syncfusion_flutter_core/example/lib/main.dart index 4e5e00da9..ac1c9ae53 100644 --- a/packages/syncfusion_flutter_core/example/lib/main.dart +++ b/packages/syncfusion_flutter_core/example/lib/main.dart @@ -10,10 +10,7 @@ class ChartApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - title: 'Chart Demo', - home: _SalesAnalysisPage(), - ); + return MaterialApp(title: 'Chart Demo', home: _SalesAnalysisPage()); } } diff --git a/packages/syncfusion_flutter_core/example/pubspec.yaml b/packages/syncfusion_flutter_core/example/pubspec.yaml index 9e4dd7f79..22fb6ed42 100644 --- a/packages/syncfusion_flutter_core/example/pubspec.yaml +++ b/packages/syncfusion_flutter_core/example/pubspec.yaml @@ -3,7 +3,7 @@ description: This project holds information about registering a license key with version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_core/lib/src/calendar/calendar_helper.dart b/packages/syncfusion_flutter_core/lib/src/calendar/calendar_helper.dart index 2f435f922..f912089a1 100644 --- a/packages/syncfusion_flutter_core/lib/src/calendar/calendar_helper.dart +++ b/packages/syncfusion_flutter_core/lib/src/calendar/calendar_helper.dart @@ -15,8 +15,9 @@ part of core; dynamic addDuration(dynamic date, Duration duration) { dynamic currentDate = date.add(duration); if (date.timeZoneOffset != currentDate.timeZoneOffset) { - currentDate = - currentDate.add(date.timeZoneOffset - currentDate.timeZoneOffset); + currentDate = currentDate.add( + date.timeZoneOffset - currentDate.timeZoneOffset, + ); } return currentDate; @@ -38,8 +39,9 @@ dynamic addDuration(dynamic date, Duration duration) { dynamic subtractDuration(dynamic date, Duration duration) { dynamic currentDate = date.subtract(duration); if (date.timeZoneOffset != currentDate.timeZoneOffset) { - currentDate = - currentDate.add(date.timeZoneOffset - currentDate.timeZoneOffset); + currentDate = currentDate.add( + date.timeZoneOffset - currentDate.timeZoneOffset, + ); } return currentDate; @@ -137,8 +139,12 @@ bool isSameOrAfterDate(dynamic firstDate, dynamic date) { /// Get the visible dates based on the date value and visible dates count. // ignore: always_specify_types, strict_raw_type -List getVisibleDates(dynamic date, List? nonWorkingDays, - int firstDayOfWeek, int visibleDatesCount) { +List getVisibleDates( + dynamic date, + List? nonWorkingDays, + int firstDayOfWeek, + int visibleDatesCount, +) { // ignore: always_specify_types, strict_raw_type List datesCollection; if (date is HijriDateTime) { @@ -150,7 +156,10 @@ List getVisibleDates(dynamic date, List? nonWorkingDays, final int nonWorkingDaysCount = nonWorkingDays == null ? 0 : nonWorkingDays.length; final dynamic currentDate = getFirstDayOfWeekDate( - visibleDatesCount + nonWorkingDaysCount, date, firstDayOfWeek); + visibleDatesCount + nonWorkingDaysCount, + date, + firstDayOfWeek, + ); for (int i = 0; i < visibleDatesCount; i++) { final dynamic visibleDate = addDays(currentDate, i); @@ -178,7 +187,10 @@ dynamic addDays(dynamic date, int days) { /// Calculate first day of week date value based original date with first day of /// week value. dynamic getFirstDayOfWeekDate( - int visibleDatesCount, dynamic date, int firstDayOfWeek) { + int visibleDatesCount, + dynamic date, + int firstDayOfWeek, +) { if (visibleDatesCount % 7 != 0) { return date; } diff --git a/packages/syncfusion_flutter_core/lib/src/calendar/custom_looping_widget.dart b/packages/syncfusion_flutter_core/lib/src/calendar/custom_looping_widget.dart index 89880cfc0..943cad033 100644 --- a/packages/syncfusion_flutter_core/lib/src/calendar/custom_looping_widget.dart +++ b/packages/syncfusion_flutter_core/lib/src/calendar/custom_looping_widget.dart @@ -45,10 +45,13 @@ class CustomScrollViewerLayout extends MultiChildRenderObjectWidget { /// } /// /// ``` - const CustomScrollViewerLayout(List children, - this._navigationDirection, this._position, this._currentChildIndex, - {super.key}) - : super(children: children); + const CustomScrollViewerLayout( + List children, + this._navigationDirection, + this._position, + this._currentChildIndex, { + super.key, + }) : super(children: children); final CustomScrollDirection _navigationDirection; final double _position; final int _currentChildIndex; @@ -56,12 +59,17 @@ class CustomScrollViewerLayout extends MultiChildRenderObjectWidget { @override _CustomScrollViewLayout createRenderObject(BuildContext context) { return _CustomScrollViewLayout( - _navigationDirection, _position, _currentChildIndex); + _navigationDirection, + _position, + _currentChildIndex, + ); } @override void updateRenderObject( - BuildContext context, _CustomScrollViewLayout renderObject) { + BuildContext context, + _CustomScrollViewLayout renderObject, + ) { renderObject ..position = _position ..navigationDirection = _navigationDirection @@ -71,7 +79,10 @@ class CustomScrollViewerLayout extends MultiChildRenderObjectWidget { class _CustomScrollViewLayout extends RenderWrap { _CustomScrollViewLayout( - this._navigationDirection, this._position, this._currentChildIndex); + this._navigationDirection, + this._position, + this._currentChildIndex, + ); CustomScrollDirection _navigationDirection; @@ -197,12 +208,12 @@ class _CustomScrollViewLayout extends RenderWrap { currentChildParentData.offset = Offset(currentChildXPos, currentChildYPos); lastChildParentData.offset = Offset(lastChildXPos, lastChildYPos); - children.forEach((dynamic child) => child.layout( - BoxConstraints( - maxWidth: width, - maxHeight: height, - ), - parentUsesSize: true)); + children.forEach( + (dynamic child) => child.layout( + BoxConstraints(maxWidth: width, maxHeight: height), + parentUsesSize: true, + ), + ); size = Size(constraints.maxWidth, constraints.maxHeight); } diff --git a/packages/syncfusion_flutter_core/lib/src/calendar/hijri_date_time.dart b/packages/syncfusion_flutter_core/lib/src/calendar/hijri_date_time.dart index 9a189e8fa..70e003e4a 100644 --- a/packages/syncfusion_flutter_core/lib/src/calendar/hijri_date_time.dart +++ b/packages/syncfusion_flutter_core/lib/src/calendar/hijri_date_time.dart @@ -1742,7 +1742,7 @@ const List _kDateCollection = [ 79900, 79930, 79960, - 79990 + 79990, ]; /// An HijriDateTime data. @@ -1757,8 +1757,7 @@ const List _kDateCollection = [ class HijriDateTime { /// Creates a instance for HijriDateTime instance with given data. HijriDateTime(this.year, this.month, this.day) - : _date = - convertToGregorianDate(null, year: year, month: month, day: day); + : _date = convertToGregorianDate(null, year: year, month: month, day: day); /// returns the hijri date value based on the current date /// @@ -1992,7 +1991,8 @@ HijriDateTime convertToHijriDate(DateTime date) { } int yPrefix = (tYear / 100).floor(); int julianOffset = yPrefix - (yPrefix / 4.0).floor() - 2; - final int julianNumber = (365.25 * (tYear + 4716)).floor() + + final int julianNumber = + (365.25 * (tYear + 4716)).floor() + (30.6001 * (tMonth + 1)).floor() + day - julianOffset - @@ -2048,8 +2048,12 @@ HijriDateTime convertToHijriDate(DateTime date) { } /// Converts and returns the gregorian date from the given hijri date values. -DateTime convertToGregorianDate(HijriDateTime? date, - {int year = 0, int month = 0, int day = 0}) { +DateTime convertToGregorianDate( + HijriDateTime? date, { + int year = 0, + int month = 0, + int day = 0, +}) { if (date != null) { return date._date; } diff --git a/packages/syncfusion_flutter_core/lib/src/legend/legend.dart b/packages/syncfusion_flutter_core/lib/src/legend/legend.dart index 71eeabf71..d75922dec 100644 --- a/packages/syncfusion_flutter_core/lib/src/legend/legend.dart +++ b/packages/syncfusion_flutter_core/lib/src/legend/legend.dart @@ -10,15 +10,15 @@ import '../utils/shape_helper.dart'; import '../utils/shape_helper.dart' as shape_helper; /// Callback which returns toggled indices and teh current toggled index. -typedef ToggledIndicesChangedCallback = void Function( - List indices, int currentIndex); +typedef ToggledIndicesChangedCallback = + void Function(List indices, int currentIndex); /// Called with the details of single legend item. typedef ItemRenderCallback = void Function(ItemRendererDetails); /// Signature to return a [Widget] for the given value. -typedef LegendPointerBuilder = Widget Function( - BuildContext context, dynamic value); +typedef LegendPointerBuilder = + Widget Function(BuildContext context, dynamic value); enum _LegendType { vector, solidBar, gradientBar } @@ -62,7 +62,7 @@ enum LegendLabelsPlacement { /// [LegendLabelsPlacement.betweenItems] places labels /// in-between two bars. - betweenItems + betweenItems, } /// Placement of edge labels in the bar legend. @@ -72,7 +72,7 @@ enum LegendEdgeLabelsPlacement { /// Place the edge labels in the center of the starting position of the /// legend bars. - center + center, } /// Behavior of the labels when it overflowed from the shape. @@ -85,7 +85,7 @@ enum LegendLabelOverflow { /// It trims the labels based on the available space in their respective /// legend item. - ellipsis + ellipsis, } /// Applies gradient or solid color for the bar segments. @@ -94,7 +94,7 @@ enum LegendPaintingStyle { solid, /// Applies gradient color for bar segments. - gradient + gradient, } /// Specifies the alignment of legend. @@ -139,18 +139,18 @@ class ItemRendererDetails { /// Represents the class of items in legends. class LegendItem { /// Creates a [LegendItem]. - const LegendItem( - {required this.text, - this.color, - this.shader, - this.imageProvider, - this.iconType, - this.iconStrokeWidth, - this.overlayMarkerType, - this.degree, - this.endAngle, - this.startAngle}) - : assert(color != null || shader != null || imageProvider != null); + const LegendItem({ + required this.text, + this.color, + this.shader, + this.imageProvider, + this.iconType, + this.iconStrokeWidth, + this.overlayMarkerType, + this.degree, + this.endAngle, + this.startAngle, + }) : assert(color != null || shader != null || imageProvider != null); /// Specifies the text of the legend. final String text; @@ -218,23 +218,23 @@ class SfLegend extends StatefulWidget { this.isComplex = false, this.toggledIndices, required this.child, - }) : _type = _LegendType.vector, - segmentSize = null, - labelsPlacement = null, - edgeLabelsPlacement = null, - labelOverflow = null, - segmentPaintingStyle = null, - itemBuilder = null, - itemCount = 0, - toggledItemColor = null, - pointerBuilder = null, - pointerSize = Size.zero, - pointerColor = null, - pointerController = null, - assert(itemSpacing >= 0), - assert(spacing >= 0), - assert(!isComplex || (isComplex && offset == null)), - super(key: key); + }) : _type = _LegendType.vector, + segmentSize = null, + labelsPlacement = null, + edgeLabelsPlacement = null, + labelOverflow = null, + segmentPaintingStyle = null, + itemBuilder = null, + itemCount = 0, + toggledItemColor = null, + pointerBuilder = null, + pointerSize = Size.zero, + pointerColor = null, + pointerController = null, + assert(itemSpacing >= 0), + assert(spacing >= 0), + assert(!isComplex || (isComplex && offset == null)), + super(key: key); /// Creates a [SfLegend]. const SfLegend.builder({ @@ -263,27 +263,27 @@ class SfLegend extends StatefulWidget { this.isComplex = false, this.toggledIndices, required this.child, - }) : _type = _LegendType.vector, - items = null, - iconSize = Size.zero, - textStyle = null, - imageProvider = null, - iconType = null, - iconBorder = null, - segmentSize = null, - labelsPlacement = null, - edgeLabelsPlacement = null, - labelOverflow = null, - segmentPaintingStyle = null, - toggledIconColor = null, - toggledTextOpacity = 0.5, - onItemRenderer = null, - pointerBuilder = null, - pointerSize = Size.zero, - pointerColor = null, - pointerController = null, - assert(!isComplex || (isComplex && offset == null)), - super(key: key); + }) : _type = _LegendType.vector, + items = null, + iconSize = Size.zero, + textStyle = null, + imageProvider = null, + iconType = null, + iconBorder = null, + segmentSize = null, + labelsPlacement = null, + edgeLabelsPlacement = null, + labelOverflow = null, + segmentPaintingStyle = null, + toggledIconColor = null, + toggledTextOpacity = 0.5, + onItemRenderer = null, + pointerBuilder = null, + pointerSize = Size.zero, + pointerColor = null, + pointerController = null, + assert(!isComplex || (isComplex && offset == null)), + super(key: key); /// Creates a [SfLegend]. const SfLegend.bar({ @@ -314,28 +314,29 @@ class SfLegend extends StatefulWidget { this.pointerColor, this.pointerController, required this.child, - }) : _type = segmentPaintingStyle == LegendPaintingStyle.solid - ? _LegendType.solidBar - : _LegendType.gradientBar, - iconType = null, - imageProvider = null, - iconSize = Size.zero, - iconBorder = null, - itemRunSpacing = null, - spacing = 0.0, - itemBuilder = null, - itemCount = 0, - alignment = null, - width = null, - height = null, - toggledIconColor = null, - toggledItemColor = null, - toggledTextOpacity = 0.0, - onToggledIndicesChanged = null, - onItemRenderer = null, - assert(itemSpacing >= 0), - assert(!isComplex || (isComplex && offset == null)), - super(key: key); + }) : _type = + segmentPaintingStyle == LegendPaintingStyle.solid + ? _LegendType.solidBar + : _LegendType.gradientBar, + iconType = null, + imageProvider = null, + iconSize = Size.zero, + iconBorder = null, + itemRunSpacing = null, + spacing = 0.0, + itemBuilder = null, + itemCount = 0, + alignment = null, + width = null, + height = null, + toggledIconColor = null, + toggledItemColor = null, + toggledTextOpacity = 0.0, + onToggledIndicesChanged = null, + onItemRenderer = null, + assert(itemSpacing >= 0), + assert(!isComplex || (isComplex && offset == null)), + super(key: key); /// Specifies the legend items. final List? items; @@ -485,8 +486,10 @@ class _SfLegendState extends State { bool _omitLegend = false; TextStyle? _textStyle; final ScrollController _scrollController = ScrollController(); - Widget _buildResponsiveLayout(Widget? current, - [BoxConstraints? baseConstraints]) { + Widget _buildResponsiveLayout( + Widget? current, [ + BoxConstraints? baseConstraints, + ]) { if (current == null) { return widget.child; } @@ -494,42 +497,60 @@ class _SfLegendState extends State { if (widget.offset == null) { switch (widget.position) { case LegendPosition.top: - current = Column(children: [ - Align( - alignment: _getEffectiveLegendItemsAlignment( - widget.position, widget.alignment ?? LegendAlignment.center), - child: current, - ), - _buildChild(baseConstraints) - ]); + current = Column( + children: [ + Align( + alignment: _getEffectiveLegendItemsAlignment( + widget.position, + widget.alignment ?? LegendAlignment.center, + ), + child: current, + ), + _buildChild(baseConstraints), + ], + ); break; case LegendPosition.bottom: - current = Column(children: [ - _buildChild(baseConstraints), - Align( - alignment: _getEffectiveLegendItemsAlignment( - widget.position, widget.alignment ?? LegendAlignment.center), - child: current, - ) - ]); + current = Column( + children: [ + _buildChild(baseConstraints), + Align( + alignment: _getEffectiveLegendItemsAlignment( + widget.position, + widget.alignment ?? LegendAlignment.center, + ), + child: current, + ), + ], + ); break; case LegendPosition.left: - current = Row(children: [ - Align( - alignment: _getEffectiveLegendItemsAlignment(widget.position, - widget.alignment ?? LegendAlignment.center), - child: current), - _buildChild(baseConstraints) - ]); + current = Row( + children: [ + Align( + alignment: _getEffectiveLegendItemsAlignment( + widget.position, + widget.alignment ?? LegendAlignment.center, + ), + child: current, + ), + _buildChild(baseConstraints), + ], + ); break; case LegendPosition.right: - current = Row(children: [ - _buildChild(baseConstraints), - Align( - alignment: _getEffectiveLegendItemsAlignment(widget.position, - widget.alignment ?? LegendAlignment.center), - child: current) - ]); + current = Row( + children: [ + _buildChild(baseConstraints), + Align( + alignment: _getEffectiveLegendItemsAlignment( + widget.position, + widget.alignment ?? LegendAlignment.center, + ), + child: current, + ), + ], + ); break; } } else { @@ -558,13 +579,13 @@ class _SfLegendState extends State { childConstraints.biggest) { child = widget.child; } else { - SchedulerBinding.instance.addPostFrameCallback( - (Duration timeStamp) { - setState(() { - _omitLegend = true; - }); - }, - ); + SchedulerBinding.instance.addPostFrameCallback(( + Duration timeStamp, + ) { + setState(() { + _omitLegend = true; + }); + }); } return SizedBox( @@ -665,11 +686,13 @@ class _SfLegendState extends State { controller: _scrollController, thumbVisibility: widget.shouldAlwaysShowScrollbar, child: ScrollConfiguration( - behavior: - ScrollConfiguration.of(context).copyWith(scrollbars: false), + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), child: SingleChildScrollView( controller: _scrollController, - scrollDirection: widget.scrollDirection ?? + scrollDirection: + widget.scrollDirection ?? (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom ? Axis.horizontal @@ -684,13 +707,15 @@ class _SfLegendState extends State { controller: _scrollController, thumbVisibility: widget.shouldAlwaysShowScrollbar, child: ScrollConfiguration( - behavior: - ScrollConfiguration.of(context).copyWith(scrollbars: false), + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), child: SingleChildScrollView( controller: _scrollController, - scrollDirection: widget.direction == Axis.horizontal - ? Axis.vertical - : Axis.horizontal, + scrollDirection: + widget.direction == Axis.horizontal + ? Axis.vertical + : Axis.horizontal, child: current, ), ), @@ -699,54 +724,40 @@ class _SfLegendState extends State { current = ScrollConfiguration( behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), child: SingleChildScrollView( - scrollDirection: widget.scrollDirection == Axis.horizontal - ? Axis.horizontal - : Axis.vertical, - physics: const NeverScrollableScrollPhysics(), - child: current), + scrollDirection: + widget.scrollDirection == Axis.horizontal + ? Axis.horizontal + : Axis.vertical, + physics: const NeverScrollableScrollPhysics(), + child: current, + ), ); } } else { if (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom) { current = Column( - mainAxisAlignment: widget.position == LegendPosition.top - ? MainAxisAlignment.start - : MainAxisAlignment.end, + mainAxisAlignment: + widget.position == LegendPosition.top + ? MainAxisAlignment.start + : MainAxisAlignment.end, children: [ widget.title!, if (widget.overflowMode == LegendOverflowMode.scroll) (widget.width != null || widget.height != null) ? Expanded( - child: Scrollbar( - thickness: scrollbarThickness, - controller: _scrollController, - thumbVisibility: widget.shouldAlwaysShowScrollbar, - child: ScrollConfiguration( - behavior: ScrollConfiguration.of(context) - .copyWith(scrollbars: false), - child: SingleChildScrollView( - controller: _scrollController, - scrollDirection: widget.scrollDirection ?? - (widget.position == LegendPosition.top || - widget.position == LegendPosition.bottom - ? Axis.horizontal - : Axis.vertical), - child: current, - ), - ), - ), - ) - : Scrollbar( + child: Scrollbar( thickness: scrollbarThickness, controller: _scrollController, thumbVisibility: widget.shouldAlwaysShowScrollbar, child: ScrollConfiguration( - behavior: ScrollConfiguration.of(context) - .copyWith(scrollbars: false), + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), child: SingleChildScrollView( controller: _scrollController, - scrollDirection: widget.scrollDirection ?? + scrollDirection: + widget.scrollDirection ?? (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom ? Axis.horizontal @@ -754,7 +765,28 @@ class _SfLegendState extends State { child: current, ), ), - ) + ), + ) + : Scrollbar( + thickness: scrollbarThickness, + controller: _scrollController, + thumbVisibility: widget.shouldAlwaysShowScrollbar, + child: ScrollConfiguration( + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), + child: SingleChildScrollView( + controller: _scrollController, + scrollDirection: + widget.scrollDirection ?? + (widget.position == LegendPosition.top || + widget.position == LegendPosition.bottom + ? Axis.horizontal + : Axis.vertical), + child: current, + ), + ), + ) else if (widget.overflowMode == LegendOverflowMode.wrapScroll) Expanded( child: Scrollbar( @@ -762,11 +794,13 @@ class _SfLegendState extends State { controller: _scrollController, thumbVisibility: widget.shouldAlwaysShowScrollbar, child: ScrollConfiguration( - behavior: ScrollConfiguration.of(context) - .copyWith(scrollbars: false), + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), child: SingleChildScrollView( controller: _scrollController, - scrollDirection: widget.scrollDirection ?? + scrollDirection: + widget.scrollDirection ?? (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom ? Axis.horizontal @@ -778,20 +812,23 @@ class _SfLegendState extends State { ) else if (widget.overflowMode == LegendOverflowMode.none) ScrollConfiguration( - behavior: - ScrollConfiguration.of(context).copyWith(scrollbars: false), + behavior: ScrollConfiguration.of( + context, + ).copyWith(scrollbars: false), child: SingleChildScrollView( - controller: _scrollController, - scrollDirection: widget.scrollDirection == Axis.horizontal - ? Axis.horizontal - : Axis.vertical, - physics: const NeverScrollableScrollPhysics(), - child: current), + controller: _scrollController, + scrollDirection: + widget.scrollDirection == Axis.horizontal + ? Axis.horizontal + : Axis.vertical, + physics: const NeverScrollableScrollPhysics(), + child: current, + ), ) else (widget.width != null || widget.height != null) ? Expanded(child: current) - : current + : current, ], ); } else { @@ -800,25 +837,31 @@ class _SfLegendState extends State { children: [ widget.title!, Flexible( - child: widget.overflowMode == LegendOverflowMode.scroll - ? SingleChildScrollView( - scrollDirection: widget.scrollDirection ?? Axis.vertical, - child: current) - : widget.overflowMode == LegendOverflowMode.wrapScroll + child: + widget.overflowMode == LegendOverflowMode.scroll ? SingleChildScrollView( - scrollDirection: widget.direction == Axis.horizontal - ? Axis.vertical - : Axis.horizontal, - child: current) + scrollDirection: + widget.scrollDirection ?? Axis.vertical, + child: current, + ) + : widget.overflowMode == LegendOverflowMode.wrapScroll + ? SingleChildScrollView( + scrollDirection: + widget.direction == Axis.horizontal + ? Axis.vertical + : Axis.horizontal, + child: current, + ) : widget.overflowMode == LegendOverflowMode.none - ? SingleChildScrollView( - scrollDirection: - widget.direction == Axis.horizontal - ? Axis.vertical - : Axis.horizontal, - physics: const NeverScrollableScrollPhysics(), - child: current) - : current, + ? SingleChildScrollView( + scrollDirection: + widget.direction == Axis.horizontal + ? Axis.vertical + : Axis.horizontal, + physics: const NeverScrollableScrollPhysics(), + child: current, + ) + : current, ), ], ); @@ -829,10 +872,13 @@ class _SfLegendState extends State { current = DecoratedBox( decoration: BoxDecoration( color: widget.color, - border: widget.border != null - ? Border.all( - color: widget.border!.color, width: widget.border!.width) - : null, + border: + widget.border != null + ? Border.all( + color: widget.border!.color, + width: widget.border!.width, + ) + : null, ), child: current, ); @@ -867,7 +913,9 @@ class _SfLegendState extends State { } AlignmentGeometry _getEffectiveLegendItemsAlignment( - LegendPosition position, LegendAlignment alignment) { + LegendPosition position, + LegendAlignment alignment, + ) { switch (position) { case LegendPosition.top: case LegendPosition.bottom: @@ -896,24 +944,28 @@ class _SfLegendState extends State { switch (legendPosition) { case LegendPosition.top: return EdgeInsets.only( - left: offset.dx > 0 ? offset.dx * 2 : 0, - right: offset.dx < 0 ? offset.dx.abs() * 2 : 0, - top: offset.dy > 0 ? offset.dy : 0); + left: offset.dx > 0 ? offset.dx * 2 : 0, + right: offset.dx < 0 ? offset.dx.abs() * 2 : 0, + top: offset.dy > 0 ? offset.dy : 0, + ); case LegendPosition.left: return EdgeInsets.only( - top: offset.dy > 0 ? offset.dy * 2 : 0, - bottom: offset.dy < 0 ? offset.dy.abs() * 2 : 0, - left: offset.dx > 0 ? offset.dx : 0); + top: offset.dy > 0 ? offset.dy * 2 : 0, + bottom: offset.dy < 0 ? offset.dy.abs() * 2 : 0, + left: offset.dx > 0 ? offset.dx : 0, + ); case LegendPosition.right: return EdgeInsets.only( - top: offset.dy > 0 ? offset.dy * 2 : 0, - bottom: offset.dy < 0 ? offset.dy.abs() * 2 : 0, - right: offset.dx < 0 ? offset.dx.abs() : 0); + top: offset.dy > 0 ? offset.dy * 2 : 0, + bottom: offset.dy < 0 ? offset.dy.abs() * 2 : 0, + right: offset.dx < 0 ? offset.dx.abs() : 0, + ); case LegendPosition.bottom: return EdgeInsets.only( - left: offset.dx > 0 ? offset.dx * 2 : 0, - right: offset.dx < 0 ? offset.dx.abs() * 2 : 0, - bottom: offset.dy < 0 ? offset.dy.abs() : 0); + left: offset.dx > 0 ? offset.dx * 2 : 0, + right: offset.dx < 0 ? offset.dx.abs() * 2 : 0, + bottom: offset.dy < 0 ? offset.dy.abs() : 0, + ); } } @@ -923,8 +975,10 @@ class _SfLegendState extends State { if (widget.itemBuilder == null) { _textStyle = themeData.textTheme.bodySmall! .copyWith( - color: - themeData.textTheme.bodySmall!.color!.withValues(alpha: 0.87)) + color: themeData.textTheme.bodySmall!.color!.withValues( + alpha: 0.87, + ), + ) .merge(widget.textStyle); } if (!widget.isComplex) { @@ -1034,40 +1088,44 @@ class _VectorLegendState extends State<_VectorLegend> final int length = widget.items!.length; for (int index = 0; index < length; index++) { final LegendItem item = widget.items![index]; - items.add(_LegendItem( - index: index, - text: item.text, - textStyle: widget.textStyle, - iconType: item.iconType ?? widget.iconType, - iconStrokeWidth: item.iconStrokeWidth, - imageProvider: item.imageProvider ?? widget.imageProvider, - shader: item.shader, - iconSize: widget.iconSize, - iconColor: item.color, - iconBorder: widget.iconBorder, - spacing: widget.spacing, - toggledIndices: widget.toggledIndices, - toggledColor: _getEffectiveToggledColor(themeData), - toggledTextOpacity: widget.toggledTextOpacity, - onToggledIndicesChanged: widget.onToggledIndicesChanged, - onItemRenderer: widget.onItemRenderer, - overlayMarkerType: item.overlayMarkerType, - degree: item.degree, - startAngle: item.startAngle, - endAngle: item.endAngle, - )); + items.add( + _LegendItem( + index: index, + text: item.text, + textStyle: widget.textStyle, + iconType: item.iconType ?? widget.iconType, + iconStrokeWidth: item.iconStrokeWidth, + imageProvider: item.imageProvider ?? widget.imageProvider, + shader: item.shader, + iconSize: widget.iconSize, + iconColor: item.color, + iconBorder: widget.iconBorder, + spacing: widget.spacing, + toggledIndices: widget.toggledIndices, + toggledColor: _getEffectiveToggledColor(themeData), + toggledTextOpacity: widget.toggledTextOpacity, + onToggledIndicesChanged: widget.onToggledIndicesChanged, + onItemRenderer: widget.onItemRenderer, + overlayMarkerType: item.overlayMarkerType, + degree: item.degree, + startAngle: item.startAngle, + endAngle: item.endAngle, + ), + ); } } else if (widget.itemCount != null && widget.itemCount! > 0 && widget.itemBuilder != null) { for (int index = 0; index < widget.itemCount!; index++) { - items.add(_LegendItem( - index: index, - itemBuilder: widget.itemBuilder, - toggledColor: _getEffectiveToggledColor(themeData), - toggledIndices: widget.toggledIndices, - onToggledIndicesChanged: widget.onToggledIndicesChanged, - )); + items.add( + _LegendItem( + index: index, + itemBuilder: widget.itemBuilder, + toggledColor: _getEffectiveToggledColor(themeData), + toggledIndices: widget.toggledIndices, + onToggledIndicesChanged: widget.onToggledIndicesChanged, + ), + ); } } return items; @@ -1078,9 +1136,10 @@ class _VectorLegendState extends State<_VectorLegend> if (widget.onToggledIndicesChanged != null) { toggledColor = widget.toggledIconColor ?? widget.toggledItemColor; if (toggledColor == null || toggledColor == Colors.transparent) { - toggledColor = themeData.brightness == Brightness.light - ? const Color.fromRGBO(230, 230, 230, 1) - : const Color.fromRGBO(66, 66, 66, 1); + toggledColor = + themeData.brightness == Brightness.light + ? const Color.fromRGBO(230, 230, 230, 1) + : const Color.fromRGBO(66, 66, 66, 1); } } @@ -1092,7 +1151,8 @@ class _VectorLegendState extends State<_VectorLegend> final ThemeData themeData = Theme.of(context); final Widget current = Wrap( - direction: widget.direction ?? + direction: + widget.direction ?? (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom ? Axis.horizontal @@ -1214,20 +1274,23 @@ class _LegendItemState extends State<_LegendItem> Future? _obtainImage; Widget _buildCustomPaint( - ItemRendererDetails details, AsyncSnapshot snapshot) { + ItemRendererDetails details, + AsyncSnapshot snapshot, + ) { Widget current = CustomPaint( size: widget.iconSize, painter: _LegendIconShape( - color: details.color, - iconType: details.iconType, - iconBorder: details.iconBorder, - iconStrokeWidth: widget.iconStrokeWidth, - image: snapshot.data, - shader: widget.shader, - overlayMarkerType: widget.overlayMarkerType, - degree: widget.degree, - startAngle: widget.startAngle, - endAngle: widget.endAngle), + color: details.color, + iconType: details.iconType, + iconBorder: details.iconBorder, + iconStrokeWidth: widget.iconStrokeWidth, + image: snapshot.data, + shader: widget.shader, + overlayMarkerType: widget.overlayMarkerType, + degree: widget.degree, + startAngle: widget.startAngle, + endAngle: widget.endAngle, + ), ); if (widget.shader != null && @@ -1243,8 +1306,9 @@ class _LegendItemState extends State<_LegendItem> return ShaderMask( blendMode: BlendMode.srcATop, shaderCallback: (Rect bounds) { - return LinearGradient(colors: [color, color]) - .createShader(bounds); + return LinearGradient( + colors: [color, color], + ).createShader(bounds); }, child: current, ); @@ -1252,8 +1316,9 @@ class _LegendItemState extends State<_LegendItem> void _handleTapUp(TapUpDetails details) { if (widget.toggledIndices != null) { - final List newToggledIndices = - List.from(widget.toggledIndices!); + final List newToggledIndices = List.from( + widget.toggledIndices!, + ); if (!newToggledIndices.contains(widget.index)) { newToggledIndices.add(widget.index); } else { @@ -1293,14 +1358,19 @@ class _LegendItemState extends State<_LegendItem> @override void initState() { _toggleAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); _toggleAnimation = CurvedAnimation( - parent: _toggleAnimationController, curve: Curves.easeInOut); + parent: _toggleAnimationController, + curve: Curves.easeInOut, + ); _toggleAnimation.addListener(rebuild); - final Color? begin = widget.shader == null && widget.imageProvider == null - ? widget.iconColor - : null; + final Color? begin = + widget.shader == null && widget.imageProvider == null + ? widget.iconColor + : null; _iconColorTween = ColorTween(begin: begin, end: widget.toggledColor); _opacityTween = Tween(begin: 1.0, end: widget.toggledTextOpacity); @@ -1319,9 +1389,10 @@ class _LegendItemState extends State<_LegendItem> @override void didUpdateWidget(_LegendItem oldWidget) { if (widget.iconColor != oldWidget.iconColor) { - final Color? begin = widget.shader == null && widget.imageProvider == null - ? widget.iconColor - : null; + final Color? begin = + widget.shader == null && widget.imageProvider == null + ? widget.iconColor + : null; _iconColorTween.begin = begin; } @@ -1372,8 +1443,9 @@ class _LegendItemState extends State<_LegendItem> } } } else { - final Color? referenceIconColor = - _iconColorTween.evaluate(_toggleAnimation); + final Color? referenceIconColor = _iconColorTween.evaluate( + _toggleAnimation, + ); final ItemRendererDetails details = ItemRendererDetails( index: widget.index, text: widget.text!, @@ -1395,12 +1467,14 @@ class _LegendItemState extends State<_LegendItem> Text( details.text, style: widget.textStyle!.copyWith( - color: widget.textStyle!.foreground == null - ? widget.textStyle!.color!.withValues( - alpha: _opacityTween.evaluate(_toggleAnimation)) - : widget.textStyle!.foreground!.color, + color: + widget.textStyle!.foreground == null + ? widget.textStyle!.color!.withValues( + alpha: _opacityTween.evaluate(_toggleAnimation), + ) + : widget.textStyle!.foreground!.color, ), - ) + ), ], ); } @@ -1425,17 +1499,18 @@ class _LegendItemState extends State<_LegendItem> /// Represents the class for rendering icon shape. class _LegendIconShape extends CustomPainter { /// Represents [LegendIconShape] - _LegendIconShape( - {required this.color, - required this.iconType, - this.iconBorder, - this.iconStrokeWidth, - this.image, - this.shader, - this.overlayMarkerType, - this.degree, - this.startAngle, - this.endAngle}); + _LegendIconShape({ + required this.color, + required this.iconType, + this.iconBorder, + this.iconStrokeWidth, + this.image, + this.shader, + this.overlayMarkerType, + this.degree, + this.startAngle, + this.endAngle, + }); /// Specifies the color of the icon. final Color? color; @@ -1495,15 +1570,16 @@ class _LegendIconShape extends CustomPainter { paintImage(canvas: canvas, rect: Offset.zero & size, image: image!); } else { shape_helper.paint( - canvas: canvas, - rect: Offset.zero & size, - shapeType: iconType!, - paint: _getFillPaint(), - borderPaint: _getStrokePaint(), - overlayMarkerType: overlayMarkerType, - degree: degree, - startAngle: startAngle, - endAngle: endAngle); + canvas: canvas, + rect: Offset.zero & size, + shapeType: iconType!, + paint: _getFillPaint(), + borderPaint: _getStrokePaint(), + overlayMarkerType: overlayMarkerType, + degree: degree, + startAngle: startAngle, + endAngle: endAngle, + ); } } @@ -1600,14 +1676,16 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { Widget build(BuildContext context) { _segmentSize = widget.segmentSize ?? const Size(80.0, 12.0); final TextDirection textDirection = Directionality.of(context); - _direction = widget.direction ?? + _direction = + widget.direction ?? (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom ? Axis.horizontal : Axis.vertical); - _textDirection = textDirection == TextDirection.ltr - ? textDirection - : (_direction == Axis.vertical ? TextDirection.ltr : textDirection); + _textDirection = + textDirection == TextDirection.ltr + ? textDirection + : (_direction == Axis.vertical ? TextDirection.ltr : textDirection); _textPainter.textScaler = MediaQuery.of(context).textScaler; final Widget child = Directionality( @@ -1640,8 +1718,9 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { currentText = _getTrimmedText(item.text, currentText, i, length); } else { if (i == 0) { - final List firstSegmentLabels = - _getStartSegmentLabel(item.text); + final List firstSegmentLabels = _getStartSegmentLabel( + item.text, + ); if (firstSegmentLabels.length > 1) { startText = firstSegmentLabels[0]; currentText = firstSegmentLabels[1]; @@ -1654,7 +1733,11 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { } currentText = _getTrimmedText( - currentText, widget.items![i + 1].text, i, length); + currentText, + widget.items![i + 1].text, + i, + length, + ); } } else { currentText = item.text; @@ -1669,24 +1752,26 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { } } } - legendItems.add(_SolidBarLegendItem( - labelsPlacement: widget.labelsPlacement, - labelOverflow: widget.labelOverflow, - segmentSize: _segmentSize, - iconColor: item.color, - direction: _direction, - textStyle: widget.textStyle, - index: i, - length: length, - startText: startText, - text: currentText, - itemSpacing: widget.itemSpacing, - edgeLabelsPlacement: widget.edgeLabelsPlacement, - pointerSize: widget.pointerSize, - pointerColor: widget.pointerColor, - pointerBuilder: widget.pointerBuilder, - pointerController: widget.pointerController, - )); + legendItems.add( + _SolidBarLegendItem( + labelsPlacement: widget.labelsPlacement, + labelOverflow: widget.labelOverflow, + segmentSize: _segmentSize, + iconColor: item.color, + direction: _direction, + textStyle: widget.textStyle, + index: i, + length: length, + startText: startText, + text: currentText, + itemSpacing: widget.itemSpacing, + edgeLabelsPlacement: widget.edgeLabelsPlacement, + pointerSize: widget.pointerSize, + pointerColor: widget.pointerColor, + pointerBuilder: widget.pointerBuilder, + pointerController: widget.pointerController, + ), + ); } } @@ -1708,7 +1793,11 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { } String _getTrimmedText( - String currentText, String? nextText, int index, int length) { + String currentText, + String? nextText, + int index, + int length, + ) { if (widget.labelOverflow == LegendLabelOverflow.visible || currentText.isEmpty || (nextText != null && nextText.isEmpty) || @@ -1726,17 +1815,21 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { isLastInsideItem = widget.edgeLabelsPlacement == LegendEdgeLabelsPlacement.inside; refNextTextWidth = _getTextWidth(nextText) / 2; - refCurrentTextWidth = isLastInsideItem - ? _getTextWidth(currentText) - : _getTextWidth(currentText) / 2; + refCurrentTextWidth = + isLastInsideItem + ? _getTextWidth(currentText) + : _getTextWidth(currentText) / 2; } else { refCurrentTextWidth = _getTextWidth(currentText) / 2; - refNextTextWidth = index + 1 == length - 1 && - widget.edgeLabelsPlacement == LegendEdgeLabelsPlacement.inside - ? _getTextWidth(nextText) - : _getTextWidth(nextText) / 2; + refNextTextWidth = + index + 1 == length - 1 && + widget.edgeLabelsPlacement == + LegendEdgeLabelsPlacement.inside + ? _getTextWidth(nextText) + : _getTextWidth(nextText) / 2; } - _isOverlapSegmentText = refCurrentTextWidth + refNextTextWidth > + _isOverlapSegmentText = + refCurrentTextWidth + refNextTextWidth > barSize.width + widget.itemSpacing!; // Returning empty string in case of text overlapping the segment size @@ -1747,13 +1840,14 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { } else if (widget.labelOverflow == LegendLabelOverflow.ellipsis) { final double textWidth = refCurrentTextWidth + refNextTextWidth; return _getTrimText( - currentText, - widget.textStyle!, - _segmentSize.width + widget.itemSpacing! / 2, - _textPainter, - textWidth, - refNextTextWidth, - isLastInsideItem); + currentText, + widget.textStyle!, + _segmentSize.width + widget.itemSpacing! / 2, + _textPainter, + textWidth, + refNextTextWidth, + isLastInsideItem, + ); } } @@ -1767,9 +1861,15 @@ class _SolidBarLegendState extends State<_SolidBarLegend> { } } -String _getTrimText(String text, TextStyle style, double maxWidth, - TextPainter painter, double width, - [double? nextTextHalfWidth, bool isInsideLastItem = false]) { +String _getTrimText( + String text, + TextStyle style, + double maxWidth, + TextPainter painter, + double width, [ + double? nextTextHalfWidth, + bool isInsideLastItem = false, +]) { final int actualTextLength = text.length; String trimmedText = text; int trimLength = 3; // 3 dots @@ -1781,7 +1881,10 @@ String _getTrimText(String text, TextStyle style, double maxWidth, break; } else { trimmedText = text.replaceRange( - actualTextLength - trimLength, actualTextLength, '...'); + actualTextLength - trimLength, + actualTextLength, + '...', + ); painter.text = TextSpan(style: style, text: trimmedText); painter.layout(); trimLength++; @@ -1790,9 +1893,10 @@ String _getTrimText(String text, TextStyle style, double maxWidth, if (isInsideLastItem && nextTextHalfWidth != null) { width = painter.width + nextTextHalfWidth; } else { - width = nextTextHalfWidth != null - ? painter.width / 2 + nextTextHalfWidth - : painter.width; + width = + nextTextHalfWidth != null + ? painter.width / 2 + nextTextHalfWidth + : painter.width; } } @@ -1878,7 +1982,11 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { } Offset _getTextOffset( - int index, String text, int dataSourceLength, bool isStartText) { + int index, + String text, + int dataSourceLength, + bool isStartText, + ) { _textPainter.text = TextSpan(text: text, style: widget.textStyle); _textPainter.layout(); @@ -1907,14 +2015,18 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { } Offset _getHorizontalTextOffset( - int index, String text, int dataSourceLength) { + int index, + String text, + int dataSourceLength, + ) { _textPainter.text = TextSpan(text: text, style: widget.textStyle); _textPainter.layout(); if (widget.labelsPlacement == LegendLabelsPlacement.betweenItems) { - final double width = _textDirection == TextDirection.rtl && - widget.segmentSize!.width < _textPainter.width - ? _textPainter.width - : widget.segmentSize!.width; + final double width = + _textDirection == TextDirection.rtl && + widget.segmentSize!.width < _textPainter.width + ? _textPainter.width + : widget.segmentSize!.width; if (index == dataSourceLength - 1) { if (widget.edgeLabelsPlacement == LegendEdgeLabelsPlacement.inside) { return Offset(width - _textPainter.width, 0.0); @@ -1923,12 +2035,15 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { } return Offset( - width - _textPainter.width / 2 + widget.itemSpacing! / 2, 0.0); + width - _textPainter.width / 2 + widget.itemSpacing! / 2, + 0.0, + ); } else { - final double xPosition = _textDirection == TextDirection.rtl && - widget.segmentSize!.width < _textPainter.width - ? _textPainter.width / 2 - widget.segmentSize!.width / 2 - : widget.segmentSize!.width / 2 - _textPainter.width / 2; + final double xPosition = + _textDirection == TextDirection.rtl && + widget.segmentSize!.width < _textPainter.width + ? _textPainter.width / 2 - widget.segmentSize!.width / 2 + : widget.segmentSize!.width / 2 - _textPainter.width / 2; return Offset(xPosition, 0.0); } } @@ -1945,13 +2060,16 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { } return Offset( - 0.0, - widget.segmentSize!.width - - _textPainter.height / 2 + - widget.itemSpacing! / 2); + 0.0, + widget.segmentSize!.width - + _textPainter.height / 2 + + widget.itemSpacing! / 2, + ); } else { return Offset( - 0.0, widget.segmentSize!.width / 2 - _textPainter.height / 2); + 0.0, + widget.segmentSize!.width / 2 - _textPainter.height / 2, + ); } } @@ -1963,41 +2081,53 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { return Directionality( textDirection: TextDirection.ltr, - child: offset != Offset.zero - ? Transform.translate( - offset: offset, - child: Text( + child: + offset != Offset.zero + ? Transform.translate( + offset: offset, + child: Text( + text, + softWrap: false, + overflow: TextOverflow.visible, + style: widget.textStyle, + ), + ) + : Text( text, + textAlign: TextAlign.center, softWrap: false, - overflow: TextOverflow.visible, + overflow: + widget.labelOverflow == LegendLabelOverflow.ellipsis && + widget.labelsPlacement == + LegendLabelsPlacement.onItem + ? TextOverflow.ellipsis + : TextOverflow.visible, style: widget.textStyle, ), - ) - : Text( - text, - textAlign: TextAlign.center, - softWrap: false, - overflow: widget.labelOverflow == LegendLabelOverflow.ellipsis && - widget.labelsPlacement == LegendLabelsPlacement.onItem - ? TextOverflow.ellipsis - : TextOverflow.visible, - style: widget.textStyle, - ), ); } Widget _getTextWidget(String? startText, String text) { Offset? startTextOffset; if (widget.index == 0 && startText != null) { + startTextOffset = _getTextOffset( + widget.index!, + startText, + widget.length!, + true, + ); startTextOffset = - _getTextOffset(widget.index!, startText, widget.length!, true); - startTextOffset = _textDirection == TextDirection.rtl && - widget.direction == Axis.horizontal - ? -startTextOffset - : startTextOffset; + _textDirection == TextDirection.rtl && + widget.direction == Axis.horizontal + ? -startTextOffset + : startTextOffset; } - Offset textOffset = - _getTextOffset(widget.index!, text, widget.length!, false); + Offset textOffset = _getTextOffset( + widget.index!, + text, + widget.length!, + false, + ); textOffset = _textDirection == TextDirection.rtl ? -textOffset : textOffset; if (widget.index == 0 && @@ -2025,14 +2155,17 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { current = SizedBox( width: widget.pointerSize!.width, height: widget.pointerSize!.height, - child: widget.pointerBuilder! - .call(context, widget.pointerController!.colorValue), + child: widget.pointerBuilder!.call( + context, + widget.pointerController!.colorValue, + ), ); } else { current = CustomPaint( size: widget.pointerSize!, painter: _LegendIconShape( - color: widget.pointerColor ?? + color: + widget.pointerColor ?? (Theme.of(context).brightness == Brightness.light ? const Color.fromRGBO(0, 0, 0, 0.54) : const Color.fromRGBO(255, 255, 255, 0.7)), @@ -2042,32 +2175,38 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { } if (widget.direction == Axis.horizontal) { - matrix4 = Matrix4.identity() - ..translate(widget.pointerController!.position!.dx * - widget.segmentSize!.width - - (widget.pointerSize!.width / 2)); + matrix4 = + Matrix4.identity()..translate( + widget.pointerController!.position!.dx * + widget.segmentSize!.width - + (widget.pointerSize!.width / 2), + ); if (_textDirection == TextDirection.rtl) { matrix4.invert(); } current = Transform(transform: matrix4, child: current); } else { current = RotatedBox(quarterTurns: 3, child: current); - matrix4 = Matrix4.identity() - ..translate( + matrix4 = + Matrix4.identity()..translate( 0.0, widget.pointerController!.position!.dy * widget.segmentSize!.width - - (widget.pointerSize!.width / 2)); + (widget.pointerSize!.width / 2), + ); current = Transform(transform: matrix4, child: current); } } else { - current = widget.direction == Axis.horizontal - ? SizedBox( - height: widget.pointerSize!.height, - width: widget.pointerSize!.width) - : SizedBox( - height: widget.pointerSize!.width, - width: widget.pointerSize!.height); + current = + widget.direction == Axis.horizontal + ? SizedBox( + height: widget.pointerSize!.height, + width: widget.pointerSize!.width, + ) + : SizedBox( + height: widget.pointerSize!.width, + width: widget.pointerSize!.height, + ); } return current; @@ -2083,10 +2222,12 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { crossAxisAlignment: _getCrossAxisAlignment(), children: [ Align( - alignment: _textDirection == TextDirection.ltr - ? Alignment.centerLeft - : Alignment.centerRight, - child: _buildPointer()), + alignment: + _textDirection == TextDirection.ltr + ? Alignment.centerLeft + : Alignment.centerRight, + child: _buildPointer(), + ), Padding( // Gap between segment text and icon. padding: const EdgeInsets.only(bottom: 7.0), @@ -2095,7 +2236,7 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { color: widget.iconColor, ), ), - _getTextWidget(widget.startText, widget.text!) + _getTextWidget(widget.startText, widget.text!), ], ), ); @@ -2114,7 +2255,7 @@ class __SolidBarLegendItemState extends State<_SolidBarLegendItem> { color: widget.iconColor, ), ), - _getTextWidget(widget.startText, widget.text!) + _getTextWidget(widget.startText, widget.text!), ], ), ); @@ -2204,29 +2345,35 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { void _updateSegmentSize(double shortestSide) { if (_direction == Axis.horizontal) { - final double availableWidth = widget.padding != null - ? shortestSide - widget.padding!.horizontal - : shortestSide; - _segmentSize = widget.segmentSize == null - ? Size(availableWidth, 12.0) - : Size( - widget.segmentSize!.width > availableWidth - ? availableWidth - : widget.segmentSize!.width, - widget.segmentSize!.height); + final double availableWidth = + widget.padding != null + ? shortestSide - widget.padding!.horizontal + : shortestSide; + _segmentSize = + widget.segmentSize == null + ? Size(availableWidth, 12.0) + : Size( + widget.segmentSize!.width > availableWidth + ? availableWidth + : widget.segmentSize!.width, + widget.segmentSize!.height, + ); return; } - final double availableHeight = widget.padding != null - ? shortestSide - widget.padding!.vertical - : shortestSide; - _segmentSize = widget.segmentSize == null - ? Size(12.0, availableHeight) - : Size( - widget.segmentSize!.width, - widget.segmentSize!.height > availableHeight - ? availableHeight - : widget.segmentSize!.height); + final double availableHeight = + widget.padding != null + ? shortestSide - widget.padding!.vertical + : shortestSide; + _segmentSize = + widget.segmentSize == null + ? Size(12.0, availableHeight) + : Size( + widget.segmentSize!.width, + widget.segmentSize!.height > availableHeight + ? availableHeight + : widget.segmentSize!.height, + ); } void _collectLabelsAndColors() { @@ -2236,13 +2383,15 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { /// Creating new instance at this point, since we are modifying /// the same list during the run time. _colors = []; - _referenceArea = _direction == Axis.horizontal - ? _segmentSize.width - : _segmentSize.height; + _referenceArea = + _direction == Axis.horizontal + ? _segmentSize.width + : _segmentSize.height; if (widget.items != null) { final int length = widget.items!.length; - final double slab = _referenceArea / + final double slab = + _referenceArea / (widget.labelsPlacement == LegendLabelsPlacement.betweenItems && widget.items![0].text[0] != '{' ? length - 1 @@ -2254,9 +2403,10 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { String text; if (i == 0) { final List firstSegmentLabels = _getStartSegmentLabel(item); - text = firstSegmentLabels.length > 1 - ? firstSegmentLabels[1] - : firstSegmentLabels[0]; + text = + firstSegmentLabels.length > 1 + ? firstSegmentLabels[1] + : firstSegmentLabels[0]; } else { text = item.text; } @@ -2273,13 +2423,21 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { text = _getTrimmedText(text, i, length, slab); } else if (i < length - 1) { text = _getTrimmedText( - text, i, length, slab, widget.items![i + 1].text); + text, + i, + length, + slab, + widget.items![i + 1].text, + ); } - _labels.add(_GradientBarLabel( + _labels.add( + _GradientBarLabel( text, _getTextOffset(text, positionIndex, length - 1, slab), - _isOverlapSegmentText)); + _isOverlapSegmentText, + ), + ); } _colors.add(item.color!); } @@ -2287,7 +2445,12 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { } void _collectRageColorMapperLabels( - int i, LegendItem item, String text, double slab, int length) { + int i, + LegendItem item, + String text, + double slab, + int length, + ) { if (i == 0 && widget.labelsPlacement == LegendLabelsPlacement.betweenItems) { String startText; @@ -2307,26 +2470,47 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { if (widget.labelOverflow == LegendLabelOverflow.ellipsis) { if (widget.labelsPlacement == LegendLabelsPlacement.betweenItems) { final double textWidth = refCurrentTextWidth + refNextTextWidth; - startText = _getTrimText(startText, widget.textStyle!, slab, - _textPainter, textWidth, refNextTextWidth); + startText = _getTrimText( + startText, + widget.textStyle!, + slab, + _textPainter, + textWidth, + refNextTextWidth, + ); } } } - _labels.add(_GradientBarLabel(startText, - _getTextOffset(startText, i, length, slab), _isOverlapSegmentText)); + _labels.add( + _GradientBarLabel( + startText, + _getTextOffset(startText, i, length, slab), + _isOverlapSegmentText, + ), + ); } else if (i < length - 1) { text = _getTrimmedText(text, i, length, slab, widget.items![i + 1].text); } // For range color mapper, slab is equals to the color mapper // length. So adding +1 to point out its position index. - _labels.add(_GradientBarLabel(text, - _getTextOffset(text, i + 1, length, slab), _isOverlapSegmentText)); + _labels.add( + _GradientBarLabel( + text, + _getTextOffset(text, i + 1, length, slab), + _isOverlapSegmentText, + ), + ); } - String _getTrimmedText(String currentText, int index, int length, double slab, - [String? nextText]) { + String _getTrimmedText( + String currentText, + int index, + int length, + double slab, [ + String? nextText, + ]) { if (widget.labelOverflow == LegendLabelOverflow.visible || currentText.isEmpty || (nextText != null && nextText.isEmpty) || @@ -2351,18 +2535,27 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { } } else { refCurrentTextWidth = _getTextWidth(currentText) / 2; - refNextTextWidth = index + 1 == length - 1 && - widget.edgeLabelsPlacement == LegendEdgeLabelsPlacement.inside - ? _getTextWidth(nextText) - : _getTextWidth(nextText) / 2; + refNextTextWidth = + index + 1 == length - 1 && + widget.edgeLabelsPlacement == + LegendEdgeLabelsPlacement.inside + ? _getTextWidth(nextText) + : _getTextWidth(nextText) / 2; } _isOverlapSegmentText = refCurrentTextWidth + refNextTextWidth > slab; if (widget.labelOverflow == LegendLabelOverflow.ellipsis && _isOverlapSegmentText) { if (widget.labelsPlacement == LegendLabelsPlacement.betweenItems) { final double textWidth = refCurrentTextWidth + refNextTextWidth; - return _getTrimText(currentText, widget.textStyle!, slab, - _textPainter, textWidth, refNextTextWidth, isLastInsideItem); + return _getTrimText( + currentText, + widget.textStyle!, + slab, + _textPainter, + textWidth, + refNextTextWidth, + isLastInsideItem, + ); } } } else if (_direction == Axis.horizontal && @@ -2371,7 +2564,12 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { _isOverlapSegmentText = textWidth > slab; if (_isOverlapSegmentText) { return _getTrimText( - currentText, widget.textStyle!, slab, _textPainter, textWidth); + currentText, + widget.textStyle!, + slab, + _textPainter, + textWidth, + ); } } @@ -2400,36 +2598,52 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { } Offset _getTextOffset( - String? text, int positionIndex, int length, double slab) { + String? text, + int positionIndex, + int length, + double slab, + ) { _textPainter.text = TextSpan(text: text, style: widget.textStyle); _textPainter.layout(); final bool canAdjustLabelToCenter = widget.edgeLabelsPlacement == LegendEdgeLabelsPlacement.center && - (positionIndex == 0 || positionIndex == length) || - (positionIndex > 0 && positionIndex < length) || - widget.labelsPlacement == LegendLabelsPlacement.onItem; + (positionIndex == 0 || positionIndex == length) || + (positionIndex > 0 && positionIndex < length) || + widget.labelsPlacement == LegendLabelsPlacement.onItem; if (_direction == Axis.horizontal) { return _getHorizontalOffset( - canAdjustLabelToCenter, positionIndex, slab, length); + canAdjustLabelToCenter, + positionIndex, + slab, + length, + ); } else { - final double referenceTextWidth = canAdjustLabelToCenter - ? _textPainter.height / 2 - : (positionIndex == length ? _textPainter.height : 0.0); + final double referenceTextWidth = + canAdjustLabelToCenter + ? _textPainter.height / 2 + : (positionIndex == length ? _textPainter.height : 0.0); if (widget.labelsPlacement == LegendLabelsPlacement.betweenItems) { return Offset(0.0, slab * positionIndex - referenceTextWidth); } return Offset( - 0.0, (slab * positionIndex) - referenceTextWidth - slab / 2); + 0.0, + (slab * positionIndex) - referenceTextWidth - slab / 2, + ); } } Offset _getHorizontalOffset( - bool canAdjustLabelToCenter, int positionIndex, double slab, int length) { + bool canAdjustLabelToCenter, + int positionIndex, + double slab, + int length, + ) { if (_isRTL) { - final double referenceTextWidth = canAdjustLabelToCenter - ? -_textPainter.width / 2 - : (positionIndex == 0 ? -_textPainter.width : 0.0); + final double referenceTextWidth = + canAdjustLabelToCenter + ? -_textPainter.width / 2 + : (positionIndex == 0 ? -_textPainter.width : 0.0); double dx = _segmentSize.width - (slab * positionIndex - referenceTextWidth); @@ -2442,25 +2656,30 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { return Offset(dx + slab / 2 - _textPainter.width / 2, 0.0); } - final double referenceTextWidth = canAdjustLabelToCenter - ? _textPainter.width / 2 - : (positionIndex == length ? _textPainter.width : 0.0); + final double referenceTextWidth = + canAdjustLabelToCenter + ? _textPainter.width / 2 + : (positionIndex == length ? _textPainter.width : 0.0); if (widget.labelsPlacement == LegendLabelsPlacement.betweenItems) { return Offset(slab * positionIndex - referenceTextWidth, 0.0); } return Offset( - slab * positionIndex - _textPainter.width / 2 - slab / 2, 0.0); + slab * positionIndex - _textPainter.width / 2 - slab / 2, + 0.0, + ); } Widget _buildGradientBar() { return _direction == Axis.horizontal ? Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: _getChildren()) + crossAxisAlignment: CrossAxisAlignment.start, + children: _getChildren(), + ) : Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: _getChildren()); + crossAxisAlignment: CrossAxisAlignment.start, + children: _getChildren(), + ); } List _getChildren() { @@ -2495,14 +2714,21 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { height: _segmentSize.height, decoration: BoxDecoration( gradient: LinearGradient( - begin: startAlignment, end: endAlignment, colors: _colors), + begin: startAlignment, + end: endAlignment, + colors: _colors, + ), ), ), SizedBox( - width: _direction == Axis.vertical ? 7.0 : 0.0, - height: _direction == Axis.horizontal ? 7.0 : 0.0), + width: _direction == Axis.vertical ? 7.0 : 0.0, + height: _direction == Axis.horizontal ? 7.0 : 0.0, + ), SizedBox( - width: labelBoxWidth, height: labelBoxHeight, child: _getLabels()), + width: labelBoxWidth, + height: labelBoxHeight, + child: _getLabels(), + ), ]; } @@ -2516,14 +2742,17 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { current = SizedBox( width: widget.pointerSize!.width, height: widget.pointerSize!.height, - child: widget.pointerBuilder! - .call(context, widget.pointerController!.colorValue), + child: widget.pointerBuilder!.call( + context, + widget.pointerController!.colorValue, + ), ); } else { current = CustomPaint( size: widget.pointerSize!, painter: _LegendIconShape( - color: widget.pointerColor ?? + color: + widget.pointerColor ?? (themeData.brightness == Brightness.light ? const Color.fromRGBO(0, 0, 0, 0.54) : const Color.fromRGBO(255, 255, 255, 0.7)), @@ -2533,31 +2762,36 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { } if (_direction == Axis.horizontal) { - matrix4 = Matrix4.identity() - ..translate( + matrix4 = + Matrix4.identity()..translate( widget.pointerController!.position!.dx * _segmentSize.width - - (widget.pointerSize!.width / 2)); + (widget.pointerSize!.width / 2), + ); if (_isRTL) { matrix4.invert(); } current = Transform(transform: matrix4, child: current); } else { current = RotatedBox(quarterTurns: 3, child: current); - matrix4 = Matrix4.identity() - ..translate( + matrix4 = + Matrix4.identity()..translate( 0.0, widget.pointerController!.position!.dy * _segmentSize.height - - (widget.pointerSize!.width / 2)); + (widget.pointerSize!.width / 2), + ); current = Transform(transform: matrix4, child: current); } } else { - current = _direction == Axis.horizontal - ? SizedBox( - height: widget.pointerSize!.height, - width: widget.pointerSize!.width) - : SizedBox( - height: widget.pointerSize!.width, - width: widget.pointerSize!.height); + current = + _direction == Axis.horizontal + ? SizedBox( + height: widget.pointerSize!.height, + width: widget.pointerSize!.width, + ) + : SizedBox( + height: widget.pointerSize!.width, + width: widget.pointerSize!.height, + ); } return current; @@ -2615,29 +2849,33 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { TextDirection textDirection = Directionality.of(context); _isRTL = textDirection == TextDirection.rtl; _textPainter = TextPainter( - textDirection: TextDirection.ltr, - textScaler: MediaQuery.of(context).textScaler); - _direction = widget.direction ?? + textDirection: TextDirection.ltr, + textScaler: MediaQuery.of(context).textScaler, + ); + _direction = + widget.direction ?? (widget.position == LegendPosition.top || widget.position == LegendPosition.bottom ? Axis.horizontal : Axis.vertical); - textDirection = _isRTL - ? (_direction == Axis.vertical ? TextDirection.ltr : textDirection) - : textDirection; + textDirection = + _isRTL + ? (_direction == Axis.vertical ? TextDirection.ltr : textDirection) + : textDirection; final Widget child = Directionality( textDirection: textDirection, child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - final double width = - constraints.hasBoundedWidth ? constraints.maxWidth : 300; - final double height = - constraints.hasBoundedHeight ? constraints.maxHeight : 300; - _updateSegmentSize(Size(width, height).shortestSide); - _collectLabelsAndColors(); - return _buildGradientBar(); - }), + builder: (BuildContext context, BoxConstraints constraints) { + final double width = + constraints.hasBoundedWidth ? constraints.maxWidth : 300; + final double height = + constraints.hasBoundedHeight ? constraints.maxHeight : 300; + _updateSegmentSize(Size(width, height).shortestSide); + _collectLabelsAndColors(); + return _buildGradientBar(); + }, + ), ); return child; @@ -2645,8 +2883,11 @@ class _GradientBarLegendState extends State<_GradientBarLegend> { } class _GradientBarLabel { - _GradientBarLabel(this.label, - [this.offset = Offset.zero, this.isOverlapping = false]); + _GradientBarLabel( + this.label, [ + this.offset = Offset.zero, + this.isOverlapping = false, + ]); String label; Offset offset; diff --git a/packages/syncfusion_flutter_core/lib/src/slider_controller.dart b/packages/syncfusion_flutter_core/lib/src/slider_controller.dart index 692c9a82f..83ae2ea33 100644 --- a/packages/syncfusion_flutter_core/lib/src/slider_controller.dart +++ b/packages/syncfusion_flutter_core/lib/src/slider_controller.dart @@ -190,12 +190,12 @@ class RangeController extends DiagnosticableTree with ChangeNotifier { /// /// [start] and [end] RangeController({@required dynamic start, @required dynamic end}) - : assert(start != null), - assert(end != null), - _previousStart = start, - _previousEnd = end, - _start = start, - _end = end; + : assert(start != null), + assert(end != null), + _previousStart = start, + _previousEnd = end, + _start = start, + _end = end; /// The current selected start value. /// diff --git a/packages/syncfusion_flutter_core/lib/src/theme/assistview_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/assistview_theme.dart index f80f1e051..2546db57c 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/assistview_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/assistview_theme.dart @@ -920,10 +920,10 @@ class SfAIAssistViewThemeData with Diagnosticable { actionButtonSplashColor ?? this.actionButtonSplashColor, actionButtonDisabledForegroundColor: actionButtonDisabledForegroundColor ?? - this.actionButtonDisabledForegroundColor, + this.actionButtonDisabledForegroundColor, actionButtonDisabledBackgroundColor: actionButtonDisabledBackgroundColor ?? - this.actionButtonDisabledBackgroundColor, + this.actionButtonDisabledBackgroundColor, actionButtonElevation: actionButtonElevation ?? this.actionButtonElevation, actionButtonFocusElevation: @@ -954,9 +954,11 @@ class SfAIAssistViewThemeData with Diagnosticable { requestPrimaryHeaderTextStyle ?? this.requestPrimaryHeaderTextStyle, responsePrimaryHeaderTextStyle: responsePrimaryHeaderTextStyle ?? this.responsePrimaryHeaderTextStyle, - requestSecondaryHeaderTextStyle: requestSecondaryHeaderTextStyle ?? + requestSecondaryHeaderTextStyle: + requestSecondaryHeaderTextStyle ?? this.requestSecondaryHeaderTextStyle, - responseSecondaryHeaderTextStyle: responseSecondaryHeaderTextStyle ?? + responseSecondaryHeaderTextStyle: + responseSecondaryHeaderTextStyle ?? this.responseSecondaryHeaderTextStyle, suggestionItemTextStyle: suggestionItemTextStyle ?? this.suggestionItemTextStyle, @@ -973,7 +975,8 @@ class SfAIAssistViewThemeData with Diagnosticable { responseToolbarBackgroundColor ?? this.responseToolbarBackgroundColor, responseToolbarBackgroundShape: responseToolbarBackgroundShape ?? this.responseToolbarBackgroundShape, - responseToolbarItemBackgroundColor: responseToolbarItemBackgroundColor ?? + responseToolbarItemBackgroundColor: + responseToolbarItemBackgroundColor ?? this.responseToolbarItemBackgroundColor, responseToolbarItemShape: responseToolbarItemShape ?? this.responseToolbarItemShape, @@ -981,93 +984,164 @@ class SfAIAssistViewThemeData with Diagnosticable { } static SfAIAssistViewThemeData? lerp( - SfAIAssistViewThemeData? a, SfAIAssistViewThemeData? b, double t) { + SfAIAssistViewThemeData? a, + SfAIAssistViewThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfAIAssistViewThemeData( actionButtonForegroundColor: Color.lerp( - a!.actionButtonForegroundColor, b!.actionButtonForegroundColor, t), + a!.actionButtonForegroundColor, + b!.actionButtonForegroundColor, + t, + ), actionButtonBackgroundColor: Color.lerp( - a.actionButtonBackgroundColor, b.actionButtonBackgroundColor, t), - actionButtonFocusColor: - Color.lerp(a.actionButtonFocusColor, b.actionButtonFocusColor, t), - actionButtonHoverColor: - Color.lerp(a.actionButtonHoverColor, b.actionButtonHoverColor, t), - actionButtonSplashColor: - Color.lerp(a.actionButtonSplashColor, b.actionButtonSplashColor, t), + a.actionButtonBackgroundColor, + b.actionButtonBackgroundColor, + t, + ), + actionButtonFocusColor: Color.lerp( + a.actionButtonFocusColor, + b.actionButtonFocusColor, + t, + ), + actionButtonHoverColor: Color.lerp( + a.actionButtonHoverColor, + b.actionButtonHoverColor, + t, + ), + actionButtonSplashColor: Color.lerp( + a.actionButtonSplashColor, + b.actionButtonSplashColor, + t, + ), actionButtonDisabledForegroundColor: Color.lerp( - a.actionButtonDisabledForegroundColor, - b.actionButtonDisabledForegroundColor, - t), + a.actionButtonDisabledForegroundColor, + b.actionButtonDisabledForegroundColor, + t, + ), actionButtonDisabledBackgroundColor: Color.lerp( - a.actionButtonDisabledBackgroundColor, - b.actionButtonDisabledBackgroundColor, - t), + a.actionButtonDisabledBackgroundColor, + b.actionButtonDisabledBackgroundColor, + t, + ), actionButtonElevation: lerpDouble(a.actionButtonElevation, b.actionButtonElevation, t) ?? - 0.0, - actionButtonFocusElevation: lerpDouble( - a.actionButtonFocusElevation, b.actionButtonFocusElevation, t) ?? 0.0, - actionButtonHoverElevation: lerpDouble( - a.actionButtonHoverElevation, b.actionButtonHoverElevation, t) ?? + actionButtonFocusElevation: + lerpDouble( + a.actionButtonFocusElevation, + b.actionButtonFocusElevation, + t, + ) ?? 0.0, - actionButtonDisabledElevation: lerpDouble(a.actionButtonDisabledElevation, - b.actionButtonDisabledElevation, t) ?? + actionButtonHoverElevation: + lerpDouble( + a.actionButtonHoverElevation, + b.actionButtonHoverElevation, + t, + ) ?? + 0.0, + actionButtonDisabledElevation: + lerpDouble( + a.actionButtonDisabledElevation, + b.actionButtonDisabledElevation, + t, + ) ?? 0.0, - actionButtonHighlightElevation: lerpDouble( - a.actionButtonHighlightElevation, - b.actionButtonHighlightElevation, - t) ?? + actionButtonHighlightElevation: + lerpDouble( + a.actionButtonHighlightElevation, + b.actionButtonHighlightElevation, + t, + ) ?? 0.0, - actionButtonShape: - ShapeBorder.lerp(a.actionButtonShape, b.actionButtonShape, t), + actionButtonShape: ShapeBorder.lerp( + a.actionButtonShape, + b.actionButtonShape, + t, + ), actionButtonMouseCursor: t < 0.5 ? a.actionButtonMouseCursor : b.actionButtonMouseCursor, requestAvatarBackgroundColor: Color.lerp( - a.requestAvatarBackgroundColor, b.requestAvatarBackgroundColor, t), + a.requestAvatarBackgroundColor, + b.requestAvatarBackgroundColor, + t, + ), responseAvatarBackgroundColor: Color.lerp( - a.responseAvatarBackgroundColor, b.responseAvatarBackgroundColor, t), + a.responseAvatarBackgroundColor, + b.responseAvatarBackgroundColor, + t, + ), requestMessageBackgroundColor: Color.lerp( - a.requestMessageBackgroundColor, b.requestMessageBackgroundColor, t), + a.requestMessageBackgroundColor, + b.requestMessageBackgroundColor, + t, + ), responseMessageBackgroundColor: Color.lerp( - a.responseMessageBackgroundColor, - b.responseMessageBackgroundColor, - t), + a.responseMessageBackgroundColor, + b.responseMessageBackgroundColor, + t, + ), editorTextStyle: TextStyle.lerp(a.editorTextStyle, b.editorTextStyle, t), requestContentTextStyle: TextStyle.lerp( - a.requestContentTextStyle, b.requestContentTextStyle, t), + a.requestContentTextStyle, + b.requestContentTextStyle, + t, + ), responseContentTextStyle: TextStyle.lerp( - a.responseContentTextStyle, b.responseContentTextStyle, t), + a.responseContentTextStyle, + b.responseContentTextStyle, + t, + ), requestPrimaryHeaderTextStyle: TextStyle.lerp( - a.requestPrimaryHeaderTextStyle, b.requestPrimaryHeaderTextStyle, t), + a.requestPrimaryHeaderTextStyle, + b.requestPrimaryHeaderTextStyle, + t, + ), responsePrimaryHeaderTextStyle: TextStyle.lerp( - a.responsePrimaryHeaderTextStyle, - b.responsePrimaryHeaderTextStyle, - t), + a.responsePrimaryHeaderTextStyle, + b.responsePrimaryHeaderTextStyle, + t, + ), requestSecondaryHeaderTextStyle: TextStyle.lerp( - a.requestSecondaryHeaderTextStyle, - b.requestSecondaryHeaderTextStyle, - t), + a.requestSecondaryHeaderTextStyle, + b.requestSecondaryHeaderTextStyle, + t, + ), responseSecondaryHeaderTextStyle: TextStyle.lerp( - a.responseSecondaryHeaderTextStyle, - b.responseSecondaryHeaderTextStyle, - t), + a.responseSecondaryHeaderTextStyle, + b.responseSecondaryHeaderTextStyle, + t, + ), suggestionItemTextStyle: WidgetStateProperty.lerp( a.suggestionItemTextStyle, b.suggestionItemTextStyle, t, TextStyle.lerp, ), - requestMessageShape: - ShapeBorder.lerp(a.requestMessageShape, b.requestMessageShape, t), - responseMessageShape: - ShapeBorder.lerp(a.responseMessageShape, b.responseMessageShape, t), + requestMessageShape: ShapeBorder.lerp( + a.requestMessageShape, + b.requestMessageShape, + t, + ), + responseMessageShape: ShapeBorder.lerp( + a.responseMessageShape, + b.responseMessageShape, + t, + ), suggestionBackgroundColor: Color.lerp( - a.suggestionBackgroundColor, b.suggestionBackgroundColor, t), + a.suggestionBackgroundColor, + b.suggestionBackgroundColor, + t, + ), suggestionBackgroundShape: ShapeBorder.lerp( - a.suggestionBackgroundShape, b.suggestionBackgroundShape, t), + a.suggestionBackgroundShape, + b.suggestionBackgroundShape, + t, + ), suggestionItemBackgroundColor: WidgetStateProperty.lerp( a.suggestionItemBackgroundColor, b.suggestionItemBackgroundColor, @@ -1081,13 +1155,15 @@ class SfAIAssistViewThemeData with Diagnosticable { ShapeBorder.lerp, ), responseToolbarBackgroundColor: Color.lerp( - a.responseToolbarBackgroundColor, - b.responseToolbarBackgroundColor, - t), + a.responseToolbarBackgroundColor, + b.responseToolbarBackgroundColor, + t, + ), responseToolbarBackgroundShape: ShapeBorder.lerp( - a.responseToolbarBackgroundShape, - b.responseToolbarBackgroundShape, - t), + a.responseToolbarBackgroundShape, + b.responseToolbarBackgroundShape, + t, + ), responseToolbarItemBackgroundColor: WidgetStateProperty.lerp( a.responseToolbarItemBackgroundColor, b.responseToolbarItemBackgroundColor, diff --git a/packages/syncfusion_flutter_core/lib/src/theme/barcodes_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/barcodes_theme.dart index c7355697d..62ab8701c 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/barcodes_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/barcodes_theme.dart @@ -31,7 +31,7 @@ import '../../theme.dart'; class SfBarcodeTheme extends InheritedTheme { /// Initialize the class of SfBarcodeTheme const SfBarcodeTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant barcode widgets. /// @@ -267,24 +267,29 @@ class SfBarcodeThemeData with Diagnosticable { TextStyle? textStyle, }) { return SfBarcodeThemeData.raw( - brightness: brightness, - backgroundColor: backgroundColor ?? this.backgroundColor, - barColor: barColor ?? this.barColor, - textColor: textColor ?? this.textColor, - textStyle: textStyle ?? this.textStyle); + brightness: brightness, + backgroundColor: backgroundColor ?? this.backgroundColor, + barColor: barColor ?? this.barColor, + textColor: textColor ?? this.textColor, + textStyle: textStyle ?? this.textStyle, + ); } /// Returns the barcode theme data static SfBarcodeThemeData? lerp( - SfBarcodeThemeData? a, SfBarcodeThemeData? b, double t) { + SfBarcodeThemeData? a, + SfBarcodeThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfBarcodeThemeData( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - barColor: Color.lerp(a.barColor, b.barColor, t), - textColor: Color.lerp(a.textColor, b.textColor, t), - textStyle: TextStyle.lerp(a.textStyle, b.textStyle, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + barColor: Color.lerp(a.barColor, b.barColor, t), + textColor: Color.lerp(a.textColor, b.textColor, t), + textStyle: TextStyle.lerp(a.textStyle, b.textStyle, t), + ); } @override @@ -309,7 +314,7 @@ class SfBarcodeThemeData with Diagnosticable { backgroundColor, barColor, textColor, - textStyle + textStyle, ]; return Object.hashAll(values); } @@ -318,13 +323,29 @@ class SfBarcodeThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfBarcodeThemeData defaultData = SfBarcodeThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('barColor', barColor, - defaultValue: defaultData.barColor)); - properties.add(ColorProperty('textColor', textColor, - defaultValue: defaultData.textColor)); - properties.add(DiagnosticsProperty('textStyle', textStyle, - defaultValue: defaultData.textStyle)); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty('barColor', barColor, defaultValue: defaultData.barColor), + ); + properties.add( + ColorProperty( + 'textColor', + textColor, + defaultValue: defaultData.textColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'textStyle', + textStyle, + defaultValue: defaultData.textStyle, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/calendar_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/calendar_theme.dart index 4dbabc7d5..31640507a 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/calendar_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/calendar_theme.dart @@ -21,7 +21,7 @@ class SfCalendarTheme extends InheritedTheme { /// Constructor for the calendar theme class, which applies a theme to /// descendant Syncfusion calendar widgets. const SfCalendarTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant calendar widgets. /// @@ -108,34 +108,35 @@ class SfCalendarThemeData with Diagnosticable { /// This will rarely be used directly. It is used by [lerp] to /// create intermediate themes based on two themes created with the /// [SfCalendarThemeData] constructor. - const SfCalendarThemeData( - {this.backgroundColor, - this.headerTextStyle, - this.headerBackgroundColor, - this.agendaBackgroundColor, - this.cellBorderColor, - this.viewHeaderDateTextStyle, - this.viewHeaderDayTextStyle, - this.viewHeaderBackgroundColor, - this.agendaDayTextStyle, - this.agendaDateTextStyle, - this.timeTextStyle, - this.activeDatesTextStyle, - this.activeDatesBackgroundColor, - this.todayBackgroundColor, - this.trailingDatesBackgroundColor, - this.leadingDatesBackgroundColor, - this.trailingDatesTextStyle, - this.blackoutDatesTextStyle, - this.displayNameTextStyle, - this.leadingDatesTextStyle, - this.todayTextStyle, - this.todayHighlightColor, - this.weekNumberBackgroundColor, - this.selectionBorderColor, - this.weekNumberTextStyle, - this.timeIndicatorTextStyle, - this.allDayPanelColor}); + const SfCalendarThemeData({ + this.backgroundColor, + this.headerTextStyle, + this.headerBackgroundColor, + this.agendaBackgroundColor, + this.cellBorderColor, + this.viewHeaderDateTextStyle, + this.viewHeaderDayTextStyle, + this.viewHeaderBackgroundColor, + this.agendaDayTextStyle, + this.agendaDateTextStyle, + this.timeTextStyle, + this.activeDatesTextStyle, + this.activeDatesBackgroundColor, + this.todayBackgroundColor, + this.trailingDatesBackgroundColor, + this.leadingDatesBackgroundColor, + this.trailingDatesTextStyle, + this.blackoutDatesTextStyle, + this.displayNameTextStyle, + this.leadingDatesTextStyle, + this.todayTextStyle, + this.todayHighlightColor, + this.weekNumberBackgroundColor, + this.selectionBorderColor, + this.weekNumberTextStyle, + this.timeIndicatorTextStyle, + this.allDayPanelColor, + }); /// Create a [SfCalendarThemeData] that's used to configure a /// [SfCalendarTheme]. @@ -171,33 +172,34 @@ class SfCalendarThemeData with Diagnosticable { }) { brightness = brightness ?? Brightness.light; return SfCalendarThemeData( - backgroundColor: backgroundColor, - headerTextStyle: headerTextStyle, - headerBackgroundColor: headerBackgroundColor, - agendaBackgroundColor: agendaBackgroundColor, - viewHeaderDateTextStyle: viewHeaderDateTextStyle, - viewHeaderDayTextStyle: viewHeaderDayTextStyle, - agendaDayTextStyle: agendaDayTextStyle, - agendaDateTextStyle: agendaDateTextStyle, - cellBorderColor: cellBorderColor, - timeTextStyle: timeTextStyle, - activeDatesTextStyle: activeDatesTextStyle, - activeDatesBackgroundColor: activeDatesBackgroundColor, - todayBackgroundColor: todayBackgroundColor, - trailingDatesBackgroundColor: trailingDatesBackgroundColor, - leadingDatesBackgroundColor: leadingDatesBackgroundColor, - allDayPanelColor: allDayPanelColor, - trailingDatesTextStyle: trailingDatesTextStyle, - blackoutDatesTextStyle: blackoutDatesTextStyle, - displayNameTextStyle: displayNameTextStyle, - leadingDatesTextStyle: leadingDatesTextStyle, - todayTextStyle: todayTextStyle, - todayHighlightColor: todayHighlightColor, - viewHeaderBackgroundColor: viewHeaderBackgroundColor, - weekNumberBackgroundColor: weekNumberBackgroundColor, - selectionBorderColor: selectionBorderColor, - weekNumberTextStyle: weekNumberTextStyle, - timeIndicatorTextStyle: timeIndicatorTextStyle); + backgroundColor: backgroundColor, + headerTextStyle: headerTextStyle, + headerBackgroundColor: headerBackgroundColor, + agendaBackgroundColor: agendaBackgroundColor, + viewHeaderDateTextStyle: viewHeaderDateTextStyle, + viewHeaderDayTextStyle: viewHeaderDayTextStyle, + agendaDayTextStyle: agendaDayTextStyle, + agendaDateTextStyle: agendaDateTextStyle, + cellBorderColor: cellBorderColor, + timeTextStyle: timeTextStyle, + activeDatesTextStyle: activeDatesTextStyle, + activeDatesBackgroundColor: activeDatesBackgroundColor, + todayBackgroundColor: todayBackgroundColor, + trailingDatesBackgroundColor: trailingDatesBackgroundColor, + leadingDatesBackgroundColor: leadingDatesBackgroundColor, + allDayPanelColor: allDayPanelColor, + trailingDatesTextStyle: trailingDatesTextStyle, + blackoutDatesTextStyle: blackoutDatesTextStyle, + displayNameTextStyle: displayNameTextStyle, + leadingDatesTextStyle: leadingDatesTextStyle, + todayTextStyle: todayTextStyle, + todayHighlightColor: todayHighlightColor, + viewHeaderBackgroundColor: viewHeaderBackgroundColor, + weekNumberBackgroundColor: weekNumberBackgroundColor, + selectionBorderColor: selectionBorderColor, + weekNumberTextStyle: weekNumberTextStyle, + timeIndicatorTextStyle: timeIndicatorTextStyle, + ); } /// Specifies the background color of calendar widgets. @@ -785,110 +787,145 @@ class SfCalendarThemeData with Diagnosticable { /// Creates a copy of this theme but with the given /// fields replaced with the new values. - SfCalendarThemeData copyWith( - {Brightness? brightness, - Color? backgroundColor, - TextStyle? headerTextStyle, - Color? headerBackgroundColor, - Color? agendaBackgroundColor, - Color? cellBorderColor, - TextStyle? viewHeaderDateTextStyle, - TextStyle? viewHeaderDayTextStyle, - TextStyle? agendaDayTextStyle, - TextStyle? agendaDateTextStyle, - TextStyle? timeTextStyle, - TextStyle? activeDatesTextStyle, - Color? activeDatesBackgroundColor, - Color? todayBackgroundColor, - Color? trailingDatesBackgroundColor, - Color? leadingDatesBackgroundColor, - TextStyle? trailingDatesTextStyle, - TextStyle? blackoutDatesTextStyle, - TextStyle? displayNameTextStyle, - TextStyle? leadingDatesTextStyle, - TextStyle? todayTextStyle, - TextStyle? weekNumberTextStyle, - TextStyle? timeIndicatorTextStyle, - Color? todayHighlightColor, - Color? viewHeaderBackgroundColor, - Color? weekNumberBackgroundColor, - Color? selectionBorderColor, - Color? allDayPanelColor}) { + SfCalendarThemeData copyWith({ + Brightness? brightness, + Color? backgroundColor, + TextStyle? headerTextStyle, + Color? headerBackgroundColor, + Color? agendaBackgroundColor, + Color? cellBorderColor, + TextStyle? viewHeaderDateTextStyle, + TextStyle? viewHeaderDayTextStyle, + TextStyle? agendaDayTextStyle, + TextStyle? agendaDateTextStyle, + TextStyle? timeTextStyle, + TextStyle? activeDatesTextStyle, + Color? activeDatesBackgroundColor, + Color? todayBackgroundColor, + Color? trailingDatesBackgroundColor, + Color? leadingDatesBackgroundColor, + TextStyle? trailingDatesTextStyle, + TextStyle? blackoutDatesTextStyle, + TextStyle? displayNameTextStyle, + TextStyle? leadingDatesTextStyle, + TextStyle? todayTextStyle, + TextStyle? weekNumberTextStyle, + TextStyle? timeIndicatorTextStyle, + Color? todayHighlightColor, + Color? viewHeaderBackgroundColor, + Color? weekNumberBackgroundColor, + Color? selectionBorderColor, + Color? allDayPanelColor, + }) { return SfCalendarThemeData.raw( - brightness: brightness, - backgroundColor: backgroundColor ?? this.backgroundColor, - headerTextStyle: headerTextStyle ?? this.headerTextStyle, - headerBackgroundColor: - headerBackgroundColor ?? this.headerBackgroundColor, - agendaBackgroundColor: - agendaBackgroundColor ?? this.agendaBackgroundColor, - cellBorderColor: cellBorderColor ?? this.cellBorderColor, - viewHeaderDateTextStyle: - viewHeaderDateTextStyle ?? this.viewHeaderDateTextStyle, - viewHeaderDayTextStyle: - viewHeaderDayTextStyle ?? this.viewHeaderDayTextStyle, - agendaDayTextStyle: agendaDayTextStyle ?? this.agendaDayTextStyle, - agendaDateTextStyle: agendaDateTextStyle ?? this.agendaDateTextStyle, - timeTextStyle: timeTextStyle ?? this.timeTextStyle, - activeDatesTextStyle: activeDatesTextStyle ?? this.activeDatesTextStyle, - activeDatesBackgroundColor: - activeDatesBackgroundColor ?? this.activeDatesBackgroundColor, - todayBackgroundColor: todayBackgroundColor ?? this.todayBackgroundColor, - trailingDatesBackgroundColor: - trailingDatesBackgroundColor ?? this.trailingDatesBackgroundColor, - leadingDatesBackgroundColor: - leadingDatesBackgroundColor ?? this.leadingDatesBackgroundColor, - trailingDatesTextStyle: - trailingDatesTextStyle ?? this.trailingDatesTextStyle, - blackoutDatesTextStyle: - blackoutDatesTextStyle ?? this.blackoutDatesTextStyle, - displayNameTextStyle: displayNameTextStyle ?? this.displayNameTextStyle, - leadingDatesTextStyle: - leadingDatesTextStyle ?? this.leadingDatesTextStyle, - todayTextStyle: todayTextStyle ?? this.todayTextStyle, - weekNumberTextStyle: weekNumberTextStyle ?? this.weekNumberTextStyle, - todayHighlightColor: todayHighlightColor ?? this.todayHighlightColor, - timeIndicatorTextStyle: - timeIndicatorTextStyle ?? this.timeIndicatorTextStyle, - viewHeaderBackgroundColor: - viewHeaderBackgroundColor ?? this.viewHeaderBackgroundColor, - weekNumberBackgroundColor: - weekNumberBackgroundColor ?? this.weekNumberBackgroundColor, - selectionBorderColor: selectionBorderColor ?? this.selectionBorderColor, - allDayPanelColor: allDayPanelColor ?? this.allDayPanelColor); + brightness: brightness, + backgroundColor: backgroundColor ?? this.backgroundColor, + headerTextStyle: headerTextStyle ?? this.headerTextStyle, + headerBackgroundColor: + headerBackgroundColor ?? this.headerBackgroundColor, + agendaBackgroundColor: + agendaBackgroundColor ?? this.agendaBackgroundColor, + cellBorderColor: cellBorderColor ?? this.cellBorderColor, + viewHeaderDateTextStyle: + viewHeaderDateTextStyle ?? this.viewHeaderDateTextStyle, + viewHeaderDayTextStyle: + viewHeaderDayTextStyle ?? this.viewHeaderDayTextStyle, + agendaDayTextStyle: agendaDayTextStyle ?? this.agendaDayTextStyle, + agendaDateTextStyle: agendaDateTextStyle ?? this.agendaDateTextStyle, + timeTextStyle: timeTextStyle ?? this.timeTextStyle, + activeDatesTextStyle: activeDatesTextStyle ?? this.activeDatesTextStyle, + activeDatesBackgroundColor: + activeDatesBackgroundColor ?? this.activeDatesBackgroundColor, + todayBackgroundColor: todayBackgroundColor ?? this.todayBackgroundColor, + trailingDatesBackgroundColor: + trailingDatesBackgroundColor ?? this.trailingDatesBackgroundColor, + leadingDatesBackgroundColor: + leadingDatesBackgroundColor ?? this.leadingDatesBackgroundColor, + trailingDatesTextStyle: + trailingDatesTextStyle ?? this.trailingDatesTextStyle, + blackoutDatesTextStyle: + blackoutDatesTextStyle ?? this.blackoutDatesTextStyle, + displayNameTextStyle: displayNameTextStyle ?? this.displayNameTextStyle, + leadingDatesTextStyle: + leadingDatesTextStyle ?? this.leadingDatesTextStyle, + todayTextStyle: todayTextStyle ?? this.todayTextStyle, + weekNumberTextStyle: weekNumberTextStyle ?? this.weekNumberTextStyle, + todayHighlightColor: todayHighlightColor ?? this.todayHighlightColor, + timeIndicatorTextStyle: + timeIndicatorTextStyle ?? this.timeIndicatorTextStyle, + viewHeaderBackgroundColor: + viewHeaderBackgroundColor ?? this.viewHeaderBackgroundColor, + weekNumberBackgroundColor: + weekNumberBackgroundColor ?? this.weekNumberBackgroundColor, + selectionBorderColor: selectionBorderColor ?? this.selectionBorderColor, + allDayPanelColor: allDayPanelColor ?? this.allDayPanelColor, + ); } /// Linearly interpolate between two themes. static SfCalendarThemeData? lerp( - SfCalendarThemeData? a, SfCalendarThemeData? b, double t) { + SfCalendarThemeData? a, + SfCalendarThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfCalendarThemeData( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - headerBackgroundColor: - Color.lerp(a.headerBackgroundColor, b.headerBackgroundColor, t), - agendaBackgroundColor: - Color.lerp(a.agendaBackgroundColor, b.agendaBackgroundColor, t), - cellBorderColor: Color.lerp(a.cellBorderColor, b.cellBorderColor, t), - selectionBorderColor: - Color.lerp(a.selectionBorderColor, b.selectionBorderColor, t), - activeDatesBackgroundColor: Color.lerp( - a.activeDatesBackgroundColor, b.activeDatesBackgroundColor, t), - todayBackgroundColor: - Color.lerp(a.todayBackgroundColor, b.todayBackgroundColor, t), - trailingDatesBackgroundColor: Color.lerp( - a.trailingDatesBackgroundColor, b.trailingDatesBackgroundColor, t), - leadingDatesBackgroundColor: Color.lerp( - a.leadingDatesBackgroundColor, b.leadingDatesBackgroundColor, t), - todayHighlightColor: - Color.lerp(a.todayHighlightColor, b.todayHighlightColor, t), - viewHeaderBackgroundColor: Color.lerp( - a.viewHeaderBackgroundColor, b.viewHeaderBackgroundColor, t), - weekNumberBackgroundColor: Color.lerp( - a.weekNumberBackgroundColor, b.weekNumberBackgroundColor, t), - allDayPanelColor: - Color.lerp(a.allDayPanelColor, b.allDayPanelColor, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + headerBackgroundColor: Color.lerp( + a.headerBackgroundColor, + b.headerBackgroundColor, + t, + ), + agendaBackgroundColor: Color.lerp( + a.agendaBackgroundColor, + b.agendaBackgroundColor, + t, + ), + cellBorderColor: Color.lerp(a.cellBorderColor, b.cellBorderColor, t), + selectionBorderColor: Color.lerp( + a.selectionBorderColor, + b.selectionBorderColor, + t, + ), + activeDatesBackgroundColor: Color.lerp( + a.activeDatesBackgroundColor, + b.activeDatesBackgroundColor, + t, + ), + todayBackgroundColor: Color.lerp( + a.todayBackgroundColor, + b.todayBackgroundColor, + t, + ), + trailingDatesBackgroundColor: Color.lerp( + a.trailingDatesBackgroundColor, + b.trailingDatesBackgroundColor, + t, + ), + leadingDatesBackgroundColor: Color.lerp( + a.leadingDatesBackgroundColor, + b.leadingDatesBackgroundColor, + t, + ), + todayHighlightColor: Color.lerp( + a.todayHighlightColor, + b.todayHighlightColor, + t, + ), + viewHeaderBackgroundColor: Color.lerp( + a.viewHeaderBackgroundColor, + b.viewHeaderBackgroundColor, + t, + ), + weekNumberBackgroundColor: Color.lerp( + a.weekNumberBackgroundColor, + b.weekNumberBackgroundColor, + t, + ), + allDayPanelColor: Color.lerp(a.allDayPanelColor, b.allDayPanelColor, t), + ); } @override @@ -966,36 +1003,96 @@ class SfCalendarThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfCalendarThemeData defaultData = SfCalendarThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('headerBackgroundColor', headerBackgroundColor, - defaultValue: defaultData.headerBackgroundColor)); - properties.add(ColorProperty('agendaBackgroundColor', agendaBackgroundColor, - defaultValue: defaultData.agendaBackgroundColor)); - properties.add(ColorProperty('cellBorderColor', cellBorderColor, - defaultValue: defaultData.cellBorderColor)); - properties.add(ColorProperty( - 'activeDatesBackgroundColor', activeDatesBackgroundColor, - defaultValue: defaultData.activeDatesBackgroundColor)); - properties.add(ColorProperty('todayBackgroundColor', todayBackgroundColor, - defaultValue: defaultData.todayBackgroundColor)); - properties.add(ColorProperty( - 'trailingDatesBackgroundColor', trailingDatesBackgroundColor, - defaultValue: defaultData.trailingDatesBackgroundColor)); - properties.add(ColorProperty( - 'leadingDatesBackgroundColor', leadingDatesBackgroundColor, - defaultValue: defaultData.leadingDatesBackgroundColor)); - properties.add(ColorProperty('todayHighlightColor', todayHighlightColor, - defaultValue: defaultData.todayHighlightColor)); - properties.add(ColorProperty( - 'viewHeaderBackgroundColor', viewHeaderBackgroundColor, - defaultValue: defaultData.viewHeaderBackgroundColor)); - properties.add(ColorProperty( - 'weekNumberBackgroundColor', weekNumberBackgroundColor, - defaultValue: defaultData.weekNumberBackgroundColor)); - properties.add(ColorProperty('selectionBorderColor', selectionBorderColor, - defaultValue: defaultData.selectionBorderColor)); - properties.add(ColorProperty('allDayPanelColor ', allDayPanelColor, - defaultValue: defaultData.allDayPanelColor)); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty( + 'headerBackgroundColor', + headerBackgroundColor, + defaultValue: defaultData.headerBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'agendaBackgroundColor', + agendaBackgroundColor, + defaultValue: defaultData.agendaBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'cellBorderColor', + cellBorderColor, + defaultValue: defaultData.cellBorderColor, + ), + ); + properties.add( + ColorProperty( + 'activeDatesBackgroundColor', + activeDatesBackgroundColor, + defaultValue: defaultData.activeDatesBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'todayBackgroundColor', + todayBackgroundColor, + defaultValue: defaultData.todayBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'trailingDatesBackgroundColor', + trailingDatesBackgroundColor, + defaultValue: defaultData.trailingDatesBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'leadingDatesBackgroundColor', + leadingDatesBackgroundColor, + defaultValue: defaultData.leadingDatesBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'todayHighlightColor', + todayHighlightColor, + defaultValue: defaultData.todayHighlightColor, + ), + ); + properties.add( + ColorProperty( + 'viewHeaderBackgroundColor', + viewHeaderBackgroundColor, + defaultValue: defaultData.viewHeaderBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'weekNumberBackgroundColor', + weekNumberBackgroundColor, + defaultValue: defaultData.weekNumberBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'selectionBorderColor', + selectionBorderColor, + defaultValue: defaultData.selectionBorderColor, + ), + ); + properties.add( + ColorProperty( + 'allDayPanelColor ', + allDayPanelColor, + defaultValue: defaultData.allDayPanelColor, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/charts_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/charts_theme.dart index 5dbcde093..7bdec1354 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/charts_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/charts_theme.dart @@ -29,7 +29,7 @@ import '../../theme.dart'; class SfChartTheme extends InheritedTheme { /// Creating an argument constructor of SfChartTheme class. const SfChartTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant chart widgets. /// @@ -1232,7 +1232,8 @@ class SfChartThemeData with Diagnosticable { selectionRectColor: selectionRectColor ?? this.selectionRectColor, selectionRectBorderColor: selectionRectBorderColor ?? this.selectionRectBorderColor, - selectionTooltipConnectorLineColor: selectionTooltipConnectorLineColor ?? + selectionTooltipConnectorLineColor: + selectionTooltipConnectorLineColor ?? this.selectionTooltipConnectorLineColor, titleBackgroundColor: titleBackgroundColor ?? this.titleBackgroundColor, tooltipColor: tooltipColor ?? this.tooltipColor, @@ -1254,14 +1255,18 @@ class SfChartThemeData with Diagnosticable { tooltipTextStyle: tooltipTextStyle ?? this.tooltipTextStyle, trackballTextStyle: trackballTextStyle ?? this.trackballTextStyle, crosshairTextStyle: crosshairTextStyle ?? this.crosshairTextStyle, - selectionZoomingTooltipTextStyle: selectionZoomingTooltipTextStyle ?? + selectionZoomingTooltipTextStyle: + selectionZoomingTooltipTextStyle ?? this.selectionZoomingTooltipTextStyle, ); } /// Linearly interpolate between two themes. static SfChartThemeData? lerp( - SfChartThemeData? a, SfChartThemeData? b, double t) { + SfChartThemeData? a, + SfChartThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } @@ -1271,69 +1276,146 @@ class SfChartThemeData with Diagnosticable { axisTitleColor: Color.lerp(a.axisTitleColor, b.axisTitleColor, t), backgroundColor: Color.lerp(a.backgroundColor, b.backgroundColor, t), titleTextColor: Color.lerp(a.titleTextColor, b.titleTextColor, t), - crosshairBackgroundColor: - Color.lerp(a.crosshairBackgroundColor, b.crosshairBackgroundColor, t), - crosshairLabelColor: - Color.lerp(a.crosshairLabelColor, b.crosshairLabelColor, t), - crosshairLineColor: - Color.lerp(a.crosshairLineColor, b.crosshairLineColor, t), - legendBackgroundColor: - Color.lerp(a.legendBackgroundColor, b.legendBackgroundColor, t), + crosshairBackgroundColor: Color.lerp( + a.crosshairBackgroundColor, + b.crosshairBackgroundColor, + t, + ), + crosshairLabelColor: Color.lerp( + a.crosshairLabelColor, + b.crosshairLabelColor, + t, + ), + crosshairLineColor: Color.lerp( + a.crosshairLineColor, + b.crosshairLineColor, + t, + ), + legendBackgroundColor: Color.lerp( + a.legendBackgroundColor, + b.legendBackgroundColor, + t, + ), legendTextColor: Color.lerp(a.legendTextColor, b.legendTextColor, t), legendTitleColor: Color.lerp(a.legendTitleColor, b.legendTitleColor, t), - majorGridLineColor: - Color.lerp(a.majorGridLineColor, b.majorGridLineColor, t), - majorTickLineColor: - Color.lerp(a.majorTickLineColor, b.majorTickLineColor, t), - minorGridLineColor: - Color.lerp(a.minorGridLineColor, b.minorGridLineColor, t), - minorTickLineColor: - Color.lerp(a.minorTickLineColor, b.minorTickLineColor, t), - plotAreaBackgroundColor: - Color.lerp(a.plotAreaBackgroundColor, b.plotAreaBackgroundColor, t), - plotAreaBorderColor: - Color.lerp(a.plotAreaBorderColor, b.plotAreaBorderColor, t), - selectionRectColor: - Color.lerp(a.selectionRectColor, b.selectionRectColor, t), - selectionRectBorderColor: - Color.lerp(a.selectionRectBorderColor, b.selectionRectBorderColor, t), + majorGridLineColor: Color.lerp( + a.majorGridLineColor, + b.majorGridLineColor, + t, + ), + majorTickLineColor: Color.lerp( + a.majorTickLineColor, + b.majorTickLineColor, + t, + ), + minorGridLineColor: Color.lerp( + a.minorGridLineColor, + b.minorGridLineColor, + t, + ), + minorTickLineColor: Color.lerp( + a.minorTickLineColor, + b.minorTickLineColor, + t, + ), + plotAreaBackgroundColor: Color.lerp( + a.plotAreaBackgroundColor, + b.plotAreaBackgroundColor, + t, + ), + plotAreaBorderColor: Color.lerp( + a.plotAreaBorderColor, + b.plotAreaBorderColor, + t, + ), + selectionRectColor: Color.lerp( + a.selectionRectColor, + b.selectionRectColor, + t, + ), + selectionRectBorderColor: Color.lerp( + a.selectionRectBorderColor, + b.selectionRectBorderColor, + t, + ), selectionTooltipConnectorLineColor: Color.lerp( - a.selectionTooltipConnectorLineColor, - b.selectionTooltipConnectorLineColor, - t), - titleBackgroundColor: - Color.lerp(a.titleBackgroundColor, b.titleBackgroundColor, t), + a.selectionTooltipConnectorLineColor, + b.selectionTooltipConnectorLineColor, + t, + ), + titleBackgroundColor: Color.lerp( + a.titleBackgroundColor, + b.titleBackgroundColor, + t, + ), tooltipColor: Color.lerp(a.tooltipColor, b.tooltipColor, t), - tooltipSeparatorColor: - Color.lerp(a.tooltipSeparatorColor, b.tooltipSeparatorColor, t), - tooltipLabelColor: - Color.lerp(a.tooltipLabelColor, b.tooltipLabelColor, t), + tooltipSeparatorColor: Color.lerp( + a.tooltipSeparatorColor, + b.tooltipSeparatorColor, + t, + ), + tooltipLabelColor: Color.lerp( + a.tooltipLabelColor, + b.tooltipLabelColor, + t, + ), waterfallConnectorLineColor: Color.lerp( - a.waterfallConnectorLineColor, b.waterfallConnectorLineColor, t), + a.waterfallConnectorLineColor, + b.waterfallConnectorLineColor, + t, + ), titleTextStyle: TextStyle.lerp(a.titleTextStyle, b.titleTextStyle, t), - axisTitleTextStyle: - TextStyle.lerp(a.axisTitleTextStyle, b.axisTitleTextStyle, t), - axisLabelTextStyle: - TextStyle.lerp(a.axisLabelTextStyle, b.axisLabelTextStyle, t), + axisTitleTextStyle: TextStyle.lerp( + a.axisTitleTextStyle, + b.axisTitleTextStyle, + t, + ), + axisLabelTextStyle: TextStyle.lerp( + a.axisLabelTextStyle, + b.axisLabelTextStyle, + t, + ), axisMultiLevelLabelTextStyle: TextStyle.lerp( - a.axisMultiLevelLabelTextStyle, b.axisMultiLevelLabelTextStyle, t), - plotBandLabelTextStyle: - TextStyle.lerp(a.plotBandLabelTextStyle, b.plotBandLabelTextStyle, t), - legendTitleTextStyle: - TextStyle.lerp(a.legendTitleTextStyle, b.legendTitleTextStyle, t), + a.axisMultiLevelLabelTextStyle, + b.axisMultiLevelLabelTextStyle, + t, + ), + plotBandLabelTextStyle: TextStyle.lerp( + a.plotBandLabelTextStyle, + b.plotBandLabelTextStyle, + t, + ), + legendTitleTextStyle: TextStyle.lerp( + a.legendTitleTextStyle, + b.legendTitleTextStyle, + t, + ), legendTextStyle: TextStyle.lerp(a.legendTextStyle, b.legendTextStyle, t), - dataLabelTextStyle: - TextStyle.lerp(a.dataLabelTextStyle, b.dataLabelTextStyle, t), - tooltipTextStyle: - TextStyle.lerp(a.tooltipTextStyle, b.tooltipTextStyle, t), - trackballTextStyle: - TextStyle.lerp(a.trackballTextStyle, b.trackballTextStyle, t), - crosshairTextStyle: - TextStyle.lerp(a.crosshairTextStyle, b.crosshairTextStyle, t), + dataLabelTextStyle: TextStyle.lerp( + a.dataLabelTextStyle, + b.dataLabelTextStyle, + t, + ), + tooltipTextStyle: TextStyle.lerp( + a.tooltipTextStyle, + b.tooltipTextStyle, + t, + ), + trackballTextStyle: TextStyle.lerp( + a.trackballTextStyle, + b.trackballTextStyle, + t, + ), + crosshairTextStyle: TextStyle.lerp( + a.crosshairTextStyle, + b.crosshairTextStyle, + t, + ), selectionZoomingTooltipTextStyle: TextStyle.lerp( - a.selectionZoomingTooltipTextStyle, - b.selectionZoomingTooltipTextStyle, - t), + a.selectionZoomingTooltipTextStyle, + b.selectionZoomingTooltipTextStyle, + t, + ), ); } @@ -1427,7 +1509,7 @@ class SfChartThemeData with Diagnosticable { tooltipTextStyle, trackballTextStyle, crosshairTextStyle, - selectionZoomingTooltipTextStyle + selectionZoomingTooltipTextStyle, ]; return Object.hashAll(values); } @@ -1436,96 +1518,264 @@ class SfChartThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfChartThemeData defaultData = SfChartThemeData(); - properties.add(ColorProperty('axisLabelColor', axisLabelColor, - defaultValue: defaultData.axisLabelColor)); - properties.add(ColorProperty('axisLineColor', axisLineColor, - defaultValue: defaultData.axisLineColor)); - properties.add(ColorProperty('axisTitleColor', axisTitleColor, - defaultValue: defaultData.axisTitleColor)); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('titleTextColor', titleTextColor, - defaultValue: defaultData.titleTextColor)); - properties.add(ColorProperty( - 'crosshairBackgroundColor', crosshairBackgroundColor, - defaultValue: defaultData.crosshairBackgroundColor)); - properties.add(ColorProperty('crosshairLabelColor', crosshairLabelColor, - defaultValue: defaultData.crosshairLabelColor)); - properties.add(ColorProperty('crosshairLineColor', crosshairLineColor, - defaultValue: defaultData.crosshairLineColor)); - properties.add(ColorProperty('legendBackgroundColor', legendBackgroundColor, - defaultValue: defaultData.legendBackgroundColor)); - properties.add(ColorProperty('legendTextColor', legendTextColor, - defaultValue: defaultData.legendTextColor)); - properties.add(ColorProperty('legendTitleColor', legendTitleColor, - defaultValue: defaultData.legendTitleColor)); - properties.add(ColorProperty('majorGridLineColor', majorGridLineColor, - defaultValue: defaultData.majorGridLineColor)); - properties.add(ColorProperty('majorTickLineColor', majorTickLineColor, - defaultValue: defaultData.majorTickLineColor)); - properties.add(ColorProperty('minorGridLineColor', minorGridLineColor, - defaultValue: defaultData.minorGridLineColor)); - properties.add(ColorProperty('minorTickLineColor', minorTickLineColor, - defaultValue: defaultData.minorTickLineColor)); - properties.add(ColorProperty( - 'plotAreaBackgroundColor', plotAreaBackgroundColor, - defaultValue: defaultData.plotAreaBackgroundColor)); - properties.add(ColorProperty('plotAreaBorderColor', plotAreaBorderColor, - defaultValue: defaultData.plotAreaBorderColor)); - properties.add(ColorProperty('selectionRectColor', selectionRectColor, - defaultValue: defaultData.selectionRectColor)); - properties.add(ColorProperty( - 'selectionRectBorderColor', selectionRectBorderColor, - defaultValue: defaultData.selectionRectBorderColor)); - properties.add(ColorProperty('selectionTooltipConnectorLineColor', + properties.add( + ColorProperty( + 'axisLabelColor', + axisLabelColor, + defaultValue: defaultData.axisLabelColor, + ), + ); + properties.add( + ColorProperty( + 'axisLineColor', + axisLineColor, + defaultValue: defaultData.axisLineColor, + ), + ); + properties.add( + ColorProperty( + 'axisTitleColor', + axisTitleColor, + defaultValue: defaultData.axisTitleColor, + ), + ); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty( + 'titleTextColor', + titleTextColor, + defaultValue: defaultData.titleTextColor, + ), + ); + properties.add( + ColorProperty( + 'crosshairBackgroundColor', + crosshairBackgroundColor, + defaultValue: defaultData.crosshairBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'crosshairLabelColor', + crosshairLabelColor, + defaultValue: defaultData.crosshairLabelColor, + ), + ); + properties.add( + ColorProperty( + 'crosshairLineColor', + crosshairLineColor, + defaultValue: defaultData.crosshairLineColor, + ), + ); + properties.add( + ColorProperty( + 'legendBackgroundColor', + legendBackgroundColor, + defaultValue: defaultData.legendBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'legendTextColor', + legendTextColor, + defaultValue: defaultData.legendTextColor, + ), + ); + properties.add( + ColorProperty( + 'legendTitleColor', + legendTitleColor, + defaultValue: defaultData.legendTitleColor, + ), + ); + properties.add( + ColorProperty( + 'majorGridLineColor', + majorGridLineColor, + defaultValue: defaultData.majorGridLineColor, + ), + ); + properties.add( + ColorProperty( + 'majorTickLineColor', + majorTickLineColor, + defaultValue: defaultData.majorTickLineColor, + ), + ); + properties.add( + ColorProperty( + 'minorGridLineColor', + minorGridLineColor, + defaultValue: defaultData.minorGridLineColor, + ), + ); + properties.add( + ColorProperty( + 'minorTickLineColor', + minorTickLineColor, + defaultValue: defaultData.minorTickLineColor, + ), + ); + properties.add( + ColorProperty( + 'plotAreaBackgroundColor', + plotAreaBackgroundColor, + defaultValue: defaultData.plotAreaBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'plotAreaBorderColor', + plotAreaBorderColor, + defaultValue: defaultData.plotAreaBorderColor, + ), + ); + properties.add( + ColorProperty( + 'selectionRectColor', + selectionRectColor, + defaultValue: defaultData.selectionRectColor, + ), + ); + properties.add( + ColorProperty( + 'selectionRectBorderColor', + selectionRectBorderColor, + defaultValue: defaultData.selectionRectBorderColor, + ), + ); + properties.add( + ColorProperty( + 'selectionTooltipConnectorLineColor', selectionTooltipConnectorLineColor, - defaultValue: defaultData.selectionTooltipConnectorLineColor)); - properties.add(ColorProperty('titleBackgroundColor', titleBackgroundColor, - defaultValue: defaultData.titleBackgroundColor)); - properties.add(ColorProperty('tooltipColor', tooltipColor, - defaultValue: defaultData.tooltipColor)); - properties.add(ColorProperty('tooltipSeparatorColor', tooltipSeparatorColor, - defaultValue: defaultData.tooltipSeparatorColor)); - properties.add(ColorProperty('tooltipLabelColor', tooltipLabelColor, - defaultValue: defaultData.tooltipLabelColor)); - properties.add(ColorProperty( - 'waterfallConnectorLineColor', waterfallConnectorLineColor, - defaultValue: defaultData.waterfallConnectorLineColor)); - properties.add(DiagnosticsProperty( - 'titleTextStyle', titleTextStyle, - defaultValue: defaultData.titleTextStyle)); - properties.add(DiagnosticsProperty( - 'axisTitleTextStyle', axisTitleTextStyle, - defaultValue: defaultData.axisTitleTextStyle)); - properties.add(DiagnosticsProperty( - 'axisLabelTextStyle', axisLabelTextStyle, - defaultValue: defaultData.axisLabelTextStyle)); - properties.add(DiagnosticsProperty( - 'axisMultiLevelLabelTextStyle', axisMultiLevelLabelTextStyle, - defaultValue: defaultData.axisMultiLevelLabelTextStyle)); - properties.add(DiagnosticsProperty( - 'plotBandLabelTextStyle', plotBandLabelTextStyle, - defaultValue: defaultData.plotBandLabelTextStyle)); - properties.add(DiagnosticsProperty( - 'legendTitleTextStyle', legendTitleTextStyle, - defaultValue: defaultData.legendTitleTextStyle)); - properties.add(DiagnosticsProperty( - 'legendTextStyle', legendTextStyle, - defaultValue: defaultData.legendTextStyle)); - properties.add(DiagnosticsProperty( - 'dataLabelTextStyle', dataLabelTextStyle, - defaultValue: defaultData.dataLabelTextStyle)); - properties.add(DiagnosticsProperty( - 'tooltipTextStyle', tooltipTextStyle, - defaultValue: defaultData.tooltipTextStyle)); - properties.add(DiagnosticsProperty( - 'trackballTextStyle', trackballTextStyle, - defaultValue: defaultData.trackballTextStyle)); - properties.add(DiagnosticsProperty( - 'crosshairTextStyle', crosshairTextStyle, - defaultValue: defaultData.crosshairTextStyle)); - properties.add(DiagnosticsProperty( - 'selectionZoomingTooltipTextStyle', selectionZoomingTooltipTextStyle, - defaultValue: defaultData.selectionZoomingTooltipTextStyle)); + defaultValue: defaultData.selectionTooltipConnectorLineColor, + ), + ); + properties.add( + ColorProperty( + 'titleBackgroundColor', + titleBackgroundColor, + defaultValue: defaultData.titleBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipColor', + tooltipColor, + defaultValue: defaultData.tooltipColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipSeparatorColor', + tooltipSeparatorColor, + defaultValue: defaultData.tooltipSeparatorColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipLabelColor', + tooltipLabelColor, + defaultValue: defaultData.tooltipLabelColor, + ), + ); + properties.add( + ColorProperty( + 'waterfallConnectorLineColor', + waterfallConnectorLineColor, + defaultValue: defaultData.waterfallConnectorLineColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'titleTextStyle', + titleTextStyle, + defaultValue: defaultData.titleTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'axisTitleTextStyle', + axisTitleTextStyle, + defaultValue: defaultData.axisTitleTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'axisLabelTextStyle', + axisLabelTextStyle, + defaultValue: defaultData.axisLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'axisMultiLevelLabelTextStyle', + axisMultiLevelLabelTextStyle, + defaultValue: defaultData.axisMultiLevelLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'plotBandLabelTextStyle', + plotBandLabelTextStyle, + defaultValue: defaultData.plotBandLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'legendTitleTextStyle', + legendTitleTextStyle, + defaultValue: defaultData.legendTitleTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'legendTextStyle', + legendTextStyle, + defaultValue: defaultData.legendTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'dataLabelTextStyle', + dataLabelTextStyle, + defaultValue: defaultData.dataLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'tooltipTextStyle', + tooltipTextStyle, + defaultValue: defaultData.tooltipTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'trackballTextStyle', + trackballTextStyle, + defaultValue: defaultData.trackballTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'crosshairTextStyle', + crosshairTextStyle, + defaultValue: defaultData.crosshairTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'selectionZoomingTooltipTextStyle', + selectionZoomingTooltipTextStyle, + defaultValue: defaultData.selectionZoomingTooltipTextStyle, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/chat_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/chat_theme.dart index e3c7cff26..845a5e38b 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/chat_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/chat_theme.dart @@ -23,11 +23,7 @@ class SfChatTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. /// /// The [data] and [child] arguments must not be null. - const SfChatTheme({ - super.key, - required this.data, - required super.child, - }); + const SfChatTheme({super.key, required this.data, required super.child}); /// Specifies the color and typography values for descendant Chat widgets. /// @@ -813,10 +809,10 @@ class SfChatThemeData with Diagnosticable { actionButtonSplashColor ?? this.actionButtonSplashColor, actionButtonDisabledForegroundColor: actionButtonDisabledForegroundColor ?? - this.actionButtonDisabledForegroundColor, + this.actionButtonDisabledForegroundColor, actionButtonDisabledBackgroundColor: actionButtonDisabledBackgroundColor ?? - this.actionButtonDisabledBackgroundColor, + this.actionButtonDisabledBackgroundColor, actionButtonElevation: actionButtonElevation ?? this.actionButtonElevation, actionButtonFocusElevation: @@ -847,9 +843,11 @@ class SfChatThemeData with Diagnosticable { outgoingPrimaryHeaderTextStyle ?? this.outgoingPrimaryHeaderTextStyle, incomingPrimaryHeaderTextStyle: incomingPrimaryHeaderTextStyle ?? this.incomingPrimaryHeaderTextStyle, - outgoingSecondaryHeaderTextStyle: outgoingSecondaryHeaderTextStyle ?? + outgoingSecondaryHeaderTextStyle: + outgoingSecondaryHeaderTextStyle ?? this.outgoingSecondaryHeaderTextStyle, - incomingSecondaryHeaderTextStyle: incomingSecondaryHeaderTextStyle ?? + incomingSecondaryHeaderTextStyle: + incomingSecondaryHeaderTextStyle ?? this.incomingSecondaryHeaderTextStyle, suggestionItemTextStyle: suggestionItemTextStyle ?? this.suggestionItemTextStyle, @@ -866,97 +864,164 @@ class SfChatThemeData with Diagnosticable { } static SfChatThemeData? lerp( - SfChatThemeData? a, SfChatThemeData? b, double t) { + SfChatThemeData? a, + SfChatThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfChatThemeData( actionButtonForegroundColor: Color.lerp( - a!.actionButtonForegroundColor, b!.actionButtonForegroundColor, t), + a!.actionButtonForegroundColor, + b!.actionButtonForegroundColor, + t, + ), actionButtonBackgroundColor: Color.lerp( - a.actionButtonBackgroundColor, b.actionButtonBackgroundColor, t), - actionButtonFocusColor: - Color.lerp(a.actionButtonFocusColor, b.actionButtonFocusColor, t), - actionButtonHoverColor: - Color.lerp(a.actionButtonHoverColor, b.actionButtonHoverColor, t), - actionButtonSplashColor: - Color.lerp(a.actionButtonSplashColor, b.actionButtonSplashColor, t), + a.actionButtonBackgroundColor, + b.actionButtonBackgroundColor, + t, + ), + actionButtonFocusColor: Color.lerp( + a.actionButtonFocusColor, + b.actionButtonFocusColor, + t, + ), + actionButtonHoverColor: Color.lerp( + a.actionButtonHoverColor, + b.actionButtonHoverColor, + t, + ), + actionButtonSplashColor: Color.lerp( + a.actionButtonSplashColor, + b.actionButtonSplashColor, + t, + ), actionButtonDisabledForegroundColor: Color.lerp( - a.actionButtonDisabledForegroundColor, - b.actionButtonDisabledForegroundColor, - t), + a.actionButtonDisabledForegroundColor, + b.actionButtonDisabledForegroundColor, + t, + ), actionButtonDisabledBackgroundColor: Color.lerp( - a.actionButtonDisabledBackgroundColor, - b.actionButtonDisabledBackgroundColor, - t), + a.actionButtonDisabledBackgroundColor, + b.actionButtonDisabledBackgroundColor, + t, + ), actionButtonElevation: lerpDouble(a.actionButtonElevation, b.actionButtonElevation, t) ?? - 0.0, - actionButtonFocusElevation: lerpDouble( - a.actionButtonFocusElevation, b.actionButtonFocusElevation, t) ?? 0.0, - actionButtonHoverElevation: lerpDouble( - a.actionButtonHoverElevation, b.actionButtonHoverElevation, t) ?? + actionButtonFocusElevation: + lerpDouble( + a.actionButtonFocusElevation, + b.actionButtonFocusElevation, + t, + ) ?? 0.0, - actionButtonDisabledElevation: lerpDouble(a.actionButtonDisabledElevation, - b.actionButtonDisabledElevation, t) ?? + actionButtonHoverElevation: + lerpDouble( + a.actionButtonHoverElevation, + b.actionButtonHoverElevation, + t, + ) ?? 0.0, - actionButtonHighlightElevation: lerpDouble( - a.actionButtonHighlightElevation, - b.actionButtonHighlightElevation, - t) ?? + actionButtonDisabledElevation: + lerpDouble( + a.actionButtonDisabledElevation, + b.actionButtonDisabledElevation, + t, + ) ?? 0.0, - actionButtonShape: - ShapeBorder.lerp(a.actionButtonShape, b.actionButtonShape, t), + actionButtonHighlightElevation: + lerpDouble( + a.actionButtonHighlightElevation, + b.actionButtonHighlightElevation, + t, + ) ?? + 0.0, + actionButtonShape: ShapeBorder.lerp( + a.actionButtonShape, + b.actionButtonShape, + t, + ), actionButtonMouseCursor: t < 0.5 ? a.actionButtonMouseCursor : b.actionButtonMouseCursor, outgoingAvatarBackgroundColor: Color.lerp( - a.outgoingAvatarBackgroundColor, b.outgoingAvatarBackgroundColor, t), + a.outgoingAvatarBackgroundColor, + b.outgoingAvatarBackgroundColor, + t, + ), incomingAvatarBackgroundColor: Color.lerp( - a.incomingAvatarBackgroundColor, b.incomingAvatarBackgroundColor, t), + a.incomingAvatarBackgroundColor, + b.incomingAvatarBackgroundColor, + t, + ), outgoingMessageBackgroundColor: Color.lerp( - a.outgoingMessageBackgroundColor, - b.outgoingMessageBackgroundColor, - t), + a.outgoingMessageBackgroundColor, + b.outgoingMessageBackgroundColor, + t, + ), incomingMessageBackgroundColor: Color.lerp( - a.incomingMessageBackgroundColor, - b.incomingMessageBackgroundColor, - t), + a.incomingMessageBackgroundColor, + b.incomingMessageBackgroundColor, + t, + ), editorTextStyle: TextStyle.lerp(a.editorTextStyle, b.editorTextStyle, t), outgoingContentTextStyle: TextStyle.lerp( - a.outgoingContentTextStyle, b.outgoingContentTextStyle, t), + a.outgoingContentTextStyle, + b.outgoingContentTextStyle, + t, + ), incomingContentTextStyle: TextStyle.lerp( - a.incomingContentTextStyle, b.incomingContentTextStyle, t), + a.incomingContentTextStyle, + b.incomingContentTextStyle, + t, + ), outgoingPrimaryHeaderTextStyle: TextStyle.lerp( - a.outgoingPrimaryHeaderTextStyle, - b.outgoingPrimaryHeaderTextStyle, - t), + a.outgoingPrimaryHeaderTextStyle, + b.outgoingPrimaryHeaderTextStyle, + t, + ), incomingPrimaryHeaderTextStyle: TextStyle.lerp( - a.incomingPrimaryHeaderTextStyle, - b.incomingPrimaryHeaderTextStyle, - t), + a.incomingPrimaryHeaderTextStyle, + b.incomingPrimaryHeaderTextStyle, + t, + ), outgoingSecondaryHeaderTextStyle: TextStyle.lerp( - a.outgoingSecondaryHeaderTextStyle, - b.outgoingSecondaryHeaderTextStyle, - t), + a.outgoingSecondaryHeaderTextStyle, + b.outgoingSecondaryHeaderTextStyle, + t, + ), incomingSecondaryHeaderTextStyle: TextStyle.lerp( - a.incomingSecondaryHeaderTextStyle, - b.incomingSecondaryHeaderTextStyle, - t), + a.incomingSecondaryHeaderTextStyle, + b.incomingSecondaryHeaderTextStyle, + t, + ), suggestionItemTextStyle: WidgetStateProperty.lerp( a.suggestionItemTextStyle, b.suggestionItemTextStyle, t, TextStyle.lerp, ), - outgoingMessageShape: - ShapeBorder.lerp(a.outgoingMessageShape, b.outgoingMessageShape, t), - incomingMessageShape: - ShapeBorder.lerp(a.incomingMessageShape, b.incomingMessageShape, t), + outgoingMessageShape: ShapeBorder.lerp( + a.outgoingMessageShape, + b.outgoingMessageShape, + t, + ), + incomingMessageShape: ShapeBorder.lerp( + a.incomingMessageShape, + b.incomingMessageShape, + t, + ), suggestionBackgroundColor: Color.lerp( - a.suggestionBackgroundColor, b.suggestionBackgroundColor, t), + a.suggestionBackgroundColor, + b.suggestionBackgroundColor, + t, + ), suggestionBackgroundShape: ShapeBorder.lerp( - a.suggestionBackgroundShape, b.suggestionBackgroundShape, t), + a.suggestionBackgroundShape, + b.suggestionBackgroundShape, + t, + ), suggestionItemBackgroundColor: WidgetStateProperty.lerp( a.suggestionItemBackgroundColor, b.suggestionItemBackgroundColor, diff --git a/packages/syncfusion_flutter_core/lib/src/theme/color_scheme.dart b/packages/syncfusion_flutter_core/lib/src/theme/color_scheme.dart index 53091da79..52ecc79f5 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/color_scheme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/color_scheme.dart @@ -27,263 +27,268 @@ class SfColorScheme { required Color transparent, required this.palettes, }) { - this.primary = MaterialColor( - primary.toInt32, - { - 1: primary, - 26: primary.withValues(alpha: 0.1), - 27: brightness == Brightness.light - ? const Color.fromRGBO(41, 171, 226, 0.1) - : const Color.fromRGBO(255, 217, 57, 0.3), - 28: brightness == Brightness.light - ? const Color.fromRGBO(41, 171, 226, 1) - : const Color.fromRGBO(255, 255, 255, 1), - 20: primary.withValues(alpha: 0.08), - 30: primary.withValues(alpha: 0.1), - 31: primary.withValues(alpha: 0.12), - 61: primary.withValues(alpha: 0.24), - 138: primary.withValues(alpha: 0.54), - 97: brightness == Brightness.light - ? const Color.fromRGBO(97, 97, 97, 1) - : const Color.fromRGBO(224, 224, 224, 1), - 98: brightness == Brightness.light - ? const Color.fromRGBO(98, 0, 238, 1) - : const Color.fromRGBO(187, 134, 252, 1), - }, - ); - - this.onPrimary = MaterialColor( - onPrimary.toInt32, - { - 74: onPrimary.withValues(alpha: 0.29), - 75: brightness == Brightness.light - ? onPrimary.withValues(alpha: 0.29) - : surface.withValues(alpha: 0.56), - 31: onPrimary.withValues(alpha: 0.12), - 138: onPrimary.withValues(alpha: 0.54), - }, - ); - - this.primaryContainer = MaterialColor( - primaryContainer.toInt32, - { - 20: brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.08) - : Colors.white.withValues(alpha: 0.12), - }, - ); - - this.secondaryContainer = MaterialColor( - secondaryContainer.toInt32, - { - 204: secondaryContainer.withValues(alpha: 0.8), - 205: secondaryContainer.withValues(alpha: 0.8), - }, - ); - - this.surface = MaterialColor( - surface.toInt32, - { - 0: surface.withValues(alpha: 0.0001), - 31: surface.withValues(alpha: 0.12), - 143: surface.withValues(alpha: 0.56), - 150: surface, - 250: brightness == Brightness.light - ? const Color(0xFFFAFAFA) - : const Color(0xFF303030), - 251: brightness == Brightness.light - ? const Color(0xFFFAFAFA) - : const Color(0xFF303030), - 255: surface, - }, - ); - - this.onSurface = MaterialColor( - onSurface.toInt32, - { - 0: onSurface.withValues(alpha: 0.001), - 10: onSurface.withValues(alpha: 0.04), - 11: onSurface.withValues(alpha: 0.04), - 19: onSurface.withValues(alpha: 0.08), - 20: onSurface.withValues(alpha: 0.08), - 21: onSurface.withValues(alpha: 0.081), - 22: onSurface.withValues(alpha: 0.08), - 24: brightness == Brightness.light - ? onPrimary - : onSurface.withValues(alpha: 0.09), - 23: onSurface.withValues(alpha: 0.09), - 28: onSurface.withValues(alpha: 0.11), - 29: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.11) - : onSurface.withValues(alpha: 0.24), - 31: onSurface.withValues(alpha: 0.12), - 32: onSurface.withValues(alpha: 0.12), - 33: onSurface.withValues(alpha: 0.12), - 34: onSurface.withValues(alpha: 0.12), - 35: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.12) - : onSurface.withValues(alpha: 0.24), - 41: onSurface.withValues(alpha: 0.16), - 42: onSurface.withValues(alpha: 0.16), - 43: onSurface.withValues(alpha: 0.17), - 46: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.18) - : onSurface.withValues(alpha: 0.27), - 47: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.18) - : onSurface.withValues(alpha: 0.43), - 61: onSurface.withValues(alpha: 0.24), - 66: onSurface.withValues(alpha: 0.26), - 69: onSurface.withValues(alpha: 0.27), - 70: brightness == Brightness.light - ? const Color(0xFF212121) - : const Color(0xFFE0E0E0), - 71: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.28) - : onSurface.withValues(alpha: 0.33), - 76: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.26) - : onSurface.withValues(alpha: 0.30), - 77: onSurface.withValues(alpha: 0.30), - 82: onSurface.withValues(alpha: 0.32), - 84: onSurface.withValues(alpha: 0.33), - 92: onSurface.withValues(alpha: 0.36), - 94: onSurface.withValues(alpha: 0.37), - 95: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.37) - : onSurface.withValues(alpha: 0.17), - 97: onSurface.withValues(alpha: 0.38), - 98: onSurface.withValues(alpha: 0.38), - 110: onSurface.withValues(alpha: 0.43), - 135: onSurface.withValues(alpha: 0.53), - 138: onSurface.withValues(alpha: 0.54), - 153: onSurface.withValues(alpha: 0.6), - 154: onSurface.withValues(alpha: 0.6), - 179: onSurface.withValues(alpha: 0.7), - 184: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.72) - : onSurface, - 217: onSurface.withValues(alpha: 0.85), - 222: onSurface.withValues(alpha: 0.87), - 223: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.87) - : onSurface, - 224: brightness == Brightness.light - ? const Color.fromRGBO(97, 97, 97, 1) - : const Color.fromRGBO(224, 224, 224, 1), - 227: onSurface.withValues(alpha: 0.89), - 228: onSurface.withValues(alpha: 0.89), - 255: onSurface, - 256: brightness == Brightness.light - ? const Color.fromRGBO(117, 117, 117, 1) - : const Color.fromRGBO(245, 245, 245, 1), - }, - ); - - this.surfaceVariant = MaterialColor( - surfaceVariant.toInt32, - { - 219: brightness == Brightness.light - ? const Color.fromRGBO(219, 219, 219, 1) - : const Color.fromRGBO(70, 74, 86, 1) - }, - ); - - this.onSurfaceVariant = MaterialColor( - onSurfaceVariant.toInt32, - { - 97: onSurfaceVariant.withValues(alpha: 0.38), - 138: brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.54) - : Colors.white.withValues(alpha: 0.54), - 153: brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), - 104: brightness == Brightness.light - ? const Color.fromRGBO(104, 104, 104, 1) - : const Color.fromRGBO(242, 242, 242, 1), - 66: brightness == Brightness.light - ? const Color.fromRGBO(66, 66, 66, 1) - : const Color.fromRGBO(255, 255, 255, 1), - 79: brightness == Brightness.light - ? const Color.fromRGBO(79, 79, 79, 1) - : const Color.fromRGBO(255, 255, 255, 1), - 80: brightness == Brightness.light - ? const Color.fromRGBO(79, 79, 79, 1) - : const Color.fromRGBO(150, 150, 150, 1), - 53: brightness == Brightness.light - ? const Color.fromRGBO(53, 53, 53, 1) - : const Color.fromRGBO(255, 255, 255, 1), - 255: brightness == Brightness.light - ? const Color.fromRGBO(0, 0, 0, 1) - : const Color.fromRGBO(255, 255, 255, 1) - }, - ); - - this.inverseSurface = MaterialColor( - inverseSurface.toInt32, - { - 255: brightness == Brightness.light - ? const Color(0xFFFAFAFA) - : const Color(0xFF424242), - 257: Colors.transparent, - 79: brightness == Brightness.light - ? const Color.fromRGBO(79, 79, 79, 1) - : const Color.fromRGBO(255, 255, 255, 1), - 258: brightness == Brightness.light - ? const Color.fromRGBO(0, 8, 22, 1) - : const Color.fromRGBO(255, 255, 255, 1), - }, - ); - - this.onInverseSurface = MaterialColor( - onInverseSurface.toInt32, - { - 150: brightness == Brightness.light - ? const Color.fromRGBO(255, 255, 255, 1) - : const Color.fromRGBO(150, 150, 150, 1), - 255: Colors.white, - 256: brightness == Brightness.light - ? const Color.fromRGBO(255, 255, 255, 1) - : const Color.fromRGBO(0, 0, 0, 1), - }, - ); - - this.outlineVariant = MaterialColor( - outlineVariant.toInt32, - { - 41: brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.16) - : Colors.white.withValues(alpha: 0.16), - 255: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.53) - : onSurface.withValues(alpha: 0.85), - 181: brightness == Brightness.light - ? const Color.fromRGBO(181, 181, 181, 1) - : const Color.fromRGBO(101, 101, 101, 1), - 182: brightness == Brightness.light - ? const Color.fromRGBO(181, 181, 181, 1) - : const Color.fromRGBO(191, 191, 191, 1) - }, - ); - - this.transparent = MaterialColor( - transparent.toInt32, - { - 0: transparent.withValues(alpha: 0.0001), - 20: transparent, - 255: transparent, - }, - ); - - scrim = MaterialColor( - onSurface.toInt32, - { - 82: brightness == Brightness.light - ? Colors.white.withValues(alpha: 0.75) - : const Color.fromRGBO(48, 48, 48, 1).withValues(alpha: 0.75), - }, - ); + this.primary = MaterialColor(primary.toInt32, { + 1: primary, + 26: primary.withValues(alpha: 0.1), + 27: + brightness == Brightness.light + ? const Color.fromRGBO(41, 171, 226, 0.1) + : const Color.fromRGBO(255, 217, 57, 0.3), + 28: + brightness == Brightness.light + ? const Color.fromRGBO(41, 171, 226, 1) + : const Color.fromRGBO(255, 255, 255, 1), + 20: primary.withValues(alpha: 0.08), + 30: primary.withValues(alpha: 0.1), + 31: primary.withValues(alpha: 0.12), + 61: primary.withValues(alpha: 0.24), + 138: primary.withValues(alpha: 0.54), + 97: + brightness == Brightness.light + ? const Color.fromRGBO(97, 97, 97, 1) + : const Color.fromRGBO(224, 224, 224, 1), + 98: + brightness == Brightness.light + ? const Color.fromRGBO(98, 0, 238, 1) + : const Color.fromRGBO(187, 134, 252, 1), + }); + + this.onPrimary = MaterialColor(onPrimary.toInt32, { + 74: onPrimary.withValues(alpha: 0.29), + 75: + brightness == Brightness.light + ? onPrimary.withValues(alpha: 0.29) + : surface.withValues(alpha: 0.56), + 31: onPrimary.withValues(alpha: 0.12), + 138: onPrimary.withValues(alpha: 0.54), + }); + + this.primaryContainer = + MaterialColor(primaryContainer.toInt32, { + 20: + brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.08) + : Colors.white.withValues(alpha: 0.12), + }); + + this.secondaryContainer = + MaterialColor(secondaryContainer.toInt32, { + 204: secondaryContainer.withValues(alpha: 0.8), + 205: secondaryContainer.withValues(alpha: 0.8), + }); + + this.surface = MaterialColor(surface.toInt32, { + 0: surface.withValues(alpha: 0.0001), + 31: surface.withValues(alpha: 0.12), + 143: surface.withValues(alpha: 0.56), + 150: surface, + 250: + brightness == Brightness.light + ? const Color(0xFFFAFAFA) + : const Color(0xFF303030), + 251: + brightness == Brightness.light + ? const Color(0xFFFAFAFA) + : const Color(0xFF303030), + 255: surface, + }); + + this.onSurface = MaterialColor(onSurface.toInt32, { + 0: onSurface.withValues(alpha: 0.001), + 10: onSurface.withValues(alpha: 0.04), + 11: onSurface.withValues(alpha: 0.04), + 19: onSurface.withValues(alpha: 0.08), + 20: onSurface.withValues(alpha: 0.08), + 21: onSurface.withValues(alpha: 0.081), + 22: onSurface.withValues(alpha: 0.08), + 24: + brightness == Brightness.light + ? onPrimary + : onSurface.withValues(alpha: 0.09), + 23: onSurface.withValues(alpha: 0.09), + 28: onSurface.withValues(alpha: 0.11), + 29: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.11) + : onSurface.withValues(alpha: 0.24), + 31: onSurface.withValues(alpha: 0.12), + 32: onSurface.withValues(alpha: 0.12), + 33: onSurface.withValues(alpha: 0.12), + 34: onSurface.withValues(alpha: 0.12), + 35: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.12) + : onSurface.withValues(alpha: 0.24), + 41: onSurface.withValues(alpha: 0.16), + 42: onSurface.withValues(alpha: 0.16), + 43: onSurface.withValues(alpha: 0.17), + 46: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.18) + : onSurface.withValues(alpha: 0.27), + 47: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.18) + : onSurface.withValues(alpha: 0.43), + 61: onSurface.withValues(alpha: 0.24), + 66: onSurface.withValues(alpha: 0.26), + 69: onSurface.withValues(alpha: 0.27), + 70: + brightness == Brightness.light + ? const Color(0xFF212121) + : const Color(0xFFE0E0E0), + 71: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.28) + : onSurface.withValues(alpha: 0.33), + 76: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.26) + : onSurface.withValues(alpha: 0.30), + 77: onSurface.withValues(alpha: 0.30), + 82: onSurface.withValues(alpha: 0.32), + 84: onSurface.withValues(alpha: 0.33), + 92: onSurface.withValues(alpha: 0.36), + 94: onSurface.withValues(alpha: 0.37), + 95: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.37) + : onSurface.withValues(alpha: 0.17), + 97: onSurface.withValues(alpha: 0.38), + 98: onSurface.withValues(alpha: 0.38), + 110: onSurface.withValues(alpha: 0.43), + 135: onSurface.withValues(alpha: 0.53), + 138: onSurface.withValues(alpha: 0.54), + 153: onSurface.withValues(alpha: 0.6), + 154: onSurface.withValues(alpha: 0.6), + 179: onSurface.withValues(alpha: 0.7), + 184: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.72) + : onSurface, + 217: onSurface.withValues(alpha: 0.85), + 222: onSurface.withValues(alpha: 0.87), + 223: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.87) + : onSurface, + 224: + brightness == Brightness.light + ? const Color.fromRGBO(97, 97, 97, 1) + : const Color.fromRGBO(224, 224, 224, 1), + 227: onSurface.withValues(alpha: 0.89), + 228: onSurface.withValues(alpha: 0.89), + 255: onSurface, + 256: + brightness == Brightness.light + ? const Color.fromRGBO(117, 117, 117, 1) + : const Color.fromRGBO(245, 245, 245, 1), + }); + + this.surfaceVariant = MaterialColor(surfaceVariant.toInt32, { + 219: + brightness == Brightness.light + ? const Color.fromRGBO(219, 219, 219, 1) + : const Color.fromRGBO(70, 74, 86, 1), + }); + + this.onSurfaceVariant = + MaterialColor(onSurfaceVariant.toInt32, { + 97: onSurfaceVariant.withValues(alpha: 0.38), + 138: + brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.54) + : Colors.white.withValues(alpha: 0.54), + 153: + brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), + 104: + brightness == Brightness.light + ? const Color.fromRGBO(104, 104, 104, 1) + : const Color.fromRGBO(242, 242, 242, 1), + 66: + brightness == Brightness.light + ? const Color.fromRGBO(66, 66, 66, 1) + : const Color.fromRGBO(255, 255, 255, 1), + 79: + brightness == Brightness.light + ? const Color.fromRGBO(79, 79, 79, 1) + : const Color.fromRGBO(255, 255, 255, 1), + 80: + brightness == Brightness.light + ? const Color.fromRGBO(79, 79, 79, 1) + : const Color.fromRGBO(150, 150, 150, 1), + 53: + brightness == Brightness.light + ? const Color.fromRGBO(53, 53, 53, 1) + : const Color.fromRGBO(255, 255, 255, 1), + 255: + brightness == Brightness.light + ? const Color.fromRGBO(0, 0, 0, 1) + : const Color.fromRGBO(255, 255, 255, 1), + }); + + this.inverseSurface = MaterialColor(inverseSurface.toInt32, { + 255: + brightness == Brightness.light + ? const Color(0xFFFAFAFA) + : const Color(0xFF424242), + 257: Colors.transparent, + 79: + brightness == Brightness.light + ? const Color.fromRGBO(79, 79, 79, 1) + : const Color.fromRGBO(255, 255, 255, 1), + 258: + brightness == Brightness.light + ? const Color.fromRGBO(0, 8, 22, 1) + : const Color.fromRGBO(255, 255, 255, 1), + }); + + this.onInverseSurface = + MaterialColor(onInverseSurface.toInt32, { + 150: + brightness == Brightness.light + ? const Color.fromRGBO(255, 255, 255, 1) + : const Color.fromRGBO(150, 150, 150, 1), + 255: Colors.white, + 256: + brightness == Brightness.light + ? const Color.fromRGBO(255, 255, 255, 1) + : const Color.fromRGBO(0, 0, 0, 1), + }); + + this.outlineVariant = MaterialColor(outlineVariant.toInt32, { + 41: + brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.16) + : Colors.white.withValues(alpha: 0.16), + 255: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.53) + : onSurface.withValues(alpha: 0.85), + 181: + brightness == Brightness.light + ? const Color.fromRGBO(181, 181, 181, 1) + : const Color.fromRGBO(101, 101, 101, 1), + 182: + brightness == Brightness.light + ? const Color.fromRGBO(181, 181, 181, 1) + : const Color.fromRGBO(191, 191, 191, 1), + }); + + this.transparent = MaterialColor(transparent.toInt32, { + 0: transparent.withValues(alpha: 0.0001), + 20: transparent, + 255: transparent, + }); + + scrim = MaterialColor(onSurface.toInt32, { + 82: + brightness == Brightness.light + ? Colors.white.withValues(alpha: 0.75) + : const Color.fromRGBO(48, 48, 48, 1).withValues(alpha: 0.75), + }); } /// Creating an argument constructor of [SfColorScheme] class with M3 design. @@ -311,37 +316,30 @@ class SfColorScheme { required Color scrim, required this.palettes, }) { - this.primary = MaterialColor( - primary.toInt32, - { - 1: primaryContainer, - 27: brightness == Brightness.light - ? primary.withValues(alpha: 0.1) - : primary.withValues(alpha: 0.3), - 28: primary, - 30: primary.withValues(alpha: 0.12), - 31: primary.withValues(alpha: 0.08), - 61: surfaceVariant, - 138: onSurfaceVariant.withValues(alpha: 0.38), - 97: primary, - 98: primary, - }, - ); - - this.onPrimary = MaterialColor( - onPrimary.toInt32, - { - 31: onSurfaceVariant.withValues(alpha: 0.38), - 75: outlineVariant, - 138: onPrimary.withValues(alpha: 0.38), - }, - ); + this.primary = MaterialColor(primary.toInt32, { + 1: primaryContainer, + 27: + brightness == Brightness.light + ? primary.withValues(alpha: 0.1) + : primary.withValues(alpha: 0.3), + 28: primary, + 30: primary.withValues(alpha: 0.12), + 31: primary.withValues(alpha: 0.08), + 61: surfaceVariant, + 138: onSurfaceVariant.withValues(alpha: 0.38), + 97: primary, + 98: primary, + }); + + this.onPrimary = MaterialColor(onPrimary.toInt32, { + 31: onSurfaceVariant.withValues(alpha: 0.38), + 75: outlineVariant, + 138: onPrimary.withValues(alpha: 0.38), + }); this.primaryContainer = MaterialColor( primaryContainer.toInt32, - { - 20: primaryContainer, - }, + {20: primaryContainer}, ); this.secondaryContainer = MaterialColor( @@ -352,101 +350,92 @@ class SfColorScheme { }, ); - this.surface = MaterialColor( - surface.toInt32, - { - 0: surface.withValues(alpha: 0.0001), - 31: surface.withValues(alpha: 0.12), - 150: brightness == Brightness.light - ? const Color.fromRGBO(150, 60, 112, 1) - : const Color.fromRGBO(77, 170, 255, 1), - 250: surface, - 251: brightness == Brightness.light - ? const Color(0xFFEEE8F4) - : const Color(0xFF302D38), - 255: surface, - }, - ); - - this.onSurface = MaterialColor( - onSurface.toInt32, - { - 0: brightness == Brightness.light - ? const Color(0xFFEEE8F4) - : const Color(0xFF302D38), - 10: primary.withValues(alpha: 0.08), - 11: onSurface.withValues(alpha: 0.04), - 19: primaryContainer, - 20: primary.withValues(alpha: 0.12), - 22: surfaceVariant, - 24: brightness == Brightness.light - ? onPrimary - : onSurface.withValues(alpha: 0.09), - 29: surfaceVariant, - 31: onSurface.withValues(alpha: 0.12), - 32: outline, - 33: outlineVariant, - 34: onSurfaceVariant.withValues(alpha: 0.38), - 35: surfaceVariant, - 42: outlineVariant, - 46: outlineVariant, - 47: outlineVariant, - 61: onSurface.withValues(alpha: 0.38), - 66: primary, - 70: onSurface, - 71: outlineVariant, - 76: surfaceVariant, - 82: onSurface.withValues(alpha: 0.38), - 92: onSurface.withValues(alpha: 0.36), - 94: outlineVariant, - 95: brightness == Brightness.light - ? onSurface.withValues(alpha: 0.37) - : onSurface.withValues(alpha: 0.17), - 97: onSurface.withValues(alpha: 0.38), - 98: outline, - 153: onSurface.withValues(alpha: 0.6), - 154: onSurfaceVariant, - 184: onSurface, - 222: onSurface.withValues(alpha: 0.87), - 223: onSurfaceVariant, - 224: inverseSurface, - 227: onSurface.withValues(alpha: 0.89), - 228: const Color(0xFF49454F), - 255: onSurfaceVariant, - 256: onSurface, - }, - ); - - this.surfaceVariant = MaterialColor( - surfaceVariant.toInt32, - { - 219: surfaceVariant, - }, - ); - - this.onSurfaceVariant = MaterialColor( - onSurfaceVariant.toInt32, - { - 138: onSurfaceVariant, - 153: onSurfaceVariant, - 104: onSurfaceVariant, - 66: onSurfaceVariant, - 79: onSurfaceVariant, - 80: onSurfaceVariant, - 53: onSurfaceVariant, - 255: onSurfaceVariant, - }, - ); - - this.inverseSurface = MaterialColor( - inverseSurface.toInt32, - { - 255: inverseSurface, - 257: inverseSurface, - 79: inverseSurface, - 258: inverseSurface - }, - ); + this.surface = MaterialColor(surface.toInt32, { + 0: surface.withValues(alpha: 0.0001), + 31: surface.withValues(alpha: 0.12), + 150: + brightness == Brightness.light + ? const Color.fromRGBO(150, 60, 112, 1) + : const Color.fromRGBO(77, 170, 255, 1), + 250: surface, + 251: + brightness == Brightness.light + ? const Color(0xFFEEE8F4) + : const Color(0xFF302D38), + 255: surface, + }); + + this.onSurface = MaterialColor(onSurface.toInt32, { + 0: + brightness == Brightness.light + ? const Color(0xFFEEE8F4) + : const Color(0xFF302D38), + 10: primary.withValues(alpha: 0.08), + 11: onSurface.withValues(alpha: 0.04), + 19: primaryContainer, + 20: primary.withValues(alpha: 0.12), + 22: surfaceVariant, + 24: + brightness == Brightness.light + ? onPrimary + : onSurface.withValues(alpha: 0.09), + 29: surfaceVariant, + 31: onSurface.withValues(alpha: 0.12), + 32: outline, + 33: outlineVariant, + 34: onSurfaceVariant.withValues(alpha: 0.38), + 35: surfaceVariant, + 42: outlineVariant, + 46: outlineVariant, + 47: outlineVariant, + 61: onSurface.withValues(alpha: 0.38), + 66: primary, + 70: onSurface, + 71: outlineVariant, + 76: surfaceVariant, + 82: onSurface.withValues(alpha: 0.38), + 92: onSurface.withValues(alpha: 0.36), + 94: outlineVariant, + 95: + brightness == Brightness.light + ? onSurface.withValues(alpha: 0.37) + : onSurface.withValues(alpha: 0.17), + 97: onSurface.withValues(alpha: 0.38), + 98: outline, + 153: onSurface.withValues(alpha: 0.6), + 154: onSurfaceVariant, + 184: onSurface, + 222: onSurface.withValues(alpha: 0.87), + 223: onSurfaceVariant, + 224: inverseSurface, + 227: onSurface.withValues(alpha: 0.89), + 228: const Color(0xFF49454F), + 255: onSurfaceVariant, + 256: onSurface, + }); + + this.surfaceVariant = MaterialColor(surfaceVariant.toInt32, { + 219: surfaceVariant, + }); + + this.onSurfaceVariant = + MaterialColor(onSurfaceVariant.toInt32, { + 138: onSurfaceVariant, + 153: onSurfaceVariant, + 104: onSurfaceVariant, + 66: onSurfaceVariant, + 79: onSurfaceVariant, + 80: onSurfaceVariant, + 53: onSurfaceVariant, + 255: onSurfaceVariant, + }); + + this.inverseSurface = MaterialColor(inverseSurface.toInt32, { + 255: inverseSurface, + 257: inverseSurface, + 79: inverseSurface, + 258: inverseSurface, + }); this.onInverseSurface = MaterialColor( onInverseSurface.toInt32, @@ -457,31 +446,22 @@ class SfColorScheme { }, ); - this.outlineVariant = MaterialColor( - outlineVariant.toInt32, - { - 41: outlineVariant, - 255: outlineVariant, - 181: outlineVariant, - 182: outlineVariant, - }, - ); - - this.transparent = MaterialColor( - transparent.toInt32, - { - 0: transparent.withValues(alpha: 0.0001), - 20: primary.withValues(alpha: 0.08), - 255: Colors.white - }, - ); - - this.scrim = MaterialColor( - onSurface.toInt32, - { - 82: scrim.withValues(alpha: 0.32), - }, - ); + this.outlineVariant = MaterialColor(outlineVariant.toInt32, { + 41: outlineVariant, + 255: outlineVariant, + 181: outlineVariant, + 182: outlineVariant, + }); + + this.transparent = MaterialColor(transparent.toInt32, { + 0: transparent.withValues(alpha: 0.0001), + 20: primary.withValues(alpha: 0.08), + 255: Colors.white, + }); + + this.scrim = MaterialColor(onSurface.toInt32, { + 82: scrim.withValues(alpha: 0.32), + }); } /// A boolean property to decide whether to use material 3 or not. diff --git a/packages/syncfusion_flutter_core/lib/src/theme/datagrid_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/datagrid_theme.dart index c7c3165da..68e6fea85 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/datagrid_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/datagrid_theme.dart @@ -21,7 +21,7 @@ import '../../theme.dart'; class SfDataGridTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. const SfDataGridTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant [SfDataGrid] /// widgets. @@ -107,34 +107,69 @@ class SfDataGridTheme extends InheritedTheme { class SfDataGridThemeData with Diagnosticable { /// Create a [SfDataGridThemeData] that's used to configure a /// [SfDataGridTheme]. - const SfDataGridThemeData( - {this.gridLineColor, - this.gridLineStrokeWidth, - this.selectionColor, - this.currentCellStyle, - this.frozenPaneLineColor, - this.frozenPaneLineWidth, - this.sortIconColor, - this.headerColor, - this.headerHoverColor, - this.frozenPaneElevation, - this.columnResizeIndicatorColor, - this.columnResizeIndicatorStrokeWidth, - this.rowHoverColor, - this.rowHoverTextStyle, - this.sortIcon, - this.filterIcon, - this.filterIconColor, - this.filterIconHoverColor, - this.sortOrderNumberColor, - this.sortOrderNumberBackgroundColor, - this.filterPopupTextStyle, - this.filterPopupDisabledTextStyle, - this.columnDragIndicatorColor, - this.columnDragIndicatorStrokeWidth, - this.groupExpanderIcon, - this.indentColumnWidth, - this.indentColumnColor}); + const SfDataGridThemeData({ + this.gridLineColor, + this.gridLineStrokeWidth, + this.selectionColor, + this.currentCellStyle, + this.frozenPaneLineColor, + this.frozenPaneLineWidth, + this.sortIconColor, + this.headerColor, + this.headerHoverColor, + this.frozenPaneElevation, + this.columnResizeIndicatorColor, + this.columnResizeIndicatorStrokeWidth, + this.rowHoverColor, + this.rowHoverTextStyle, + this.sortIcon, + this.filterIcon, + this.filterIconColor, + this.filterIconHoverColor, + this.sortOrderNumberColor, + this.sortOrderNumberBackgroundColor, + this.filterPopupTextStyle, + this.filterPopupDisabledTextStyle, + this.columnDragIndicatorColor, + this.columnDragIndicatorStrokeWidth, + this.groupExpanderIcon, + this.indentColumnWidth, + this.indentColumnColor, + this.captionSummaryRowColor, + this.filterPopupCheckColor, + this.filterPopupCheckboxFillColor, + this.filterPopupInputBorderColor, + this.filterPopupBackgroundColor, + this.filterPopupIconColor, + this.filterPopupDisabledIconColor, + this.advancedFilterPopupDropdownColor, + this.noMatchesFilteringLabelColor, + this.okFilteringLabelColor, + this.okFilteringLabelButtonColor, + this.cancelFilteringLabelColor, + this.cancelFilteringLabelButtonColor, + this.searchAreaFocusedBorderColor, + this.searchAreaCursorColor, + this.andRadioActiveColor, + this.andRadioFillColor, + this.orRadioActiveColor, + this.orRadioFillColor, + this.advancedFilterValueDropdownFocusedBorderColor, + this.advancedFilterTypeDropdownFocusedBorderColor, + this.calendarIconColor, + this.advancedFilterValueTextAreaCursorColor, + this.caseSensitiveIconColor, + this.caseSensitiveIconActiveColor, + this.advancedFilterPopupDropdownIconColor, + this.searchIconColor, + this.closeIconColor, + this.advancedFilterValueDropdownIconColor, + this.advancedFilterTypeDropdownIconColor, + this.filterPopupTopDividerColor, + this.filterPopupBottomDividerColor, + this.okFilteringLabelDisabledButtonColor, + this.appBarBottomBorderColor, + }); /// Create a [SfDataGridThemeData] that's used to configure a /// [SfDataGridTheme]. @@ -167,36 +202,110 @@ class SfDataGridThemeData with Diagnosticable { Widget? groupExpanderIcon, double? indentColumnWidth, Color? indentColumnColor, + Color? captionSummaryRowColor, + Color? filterPopupCheckColor, + WidgetStateProperty? filterPopupCheckboxFillColor, + Color? filterPopupInputBorderColor, + Color? filterPopupBackgroundColor, + Color? filterPopupIconColor, + Color? filterPopupDisabledIconColor, + Color? advancedFilterPopupDropdownColor, + Color? noMatchesFilteringLabelColor, + Color? okFilteringLabelColor, + Color? okFilteringLabelButtonColor, + Color? cancelFilteringLabelColor, + Color? cancelFilteringLabelButtonColor, + Color? searchAreaCursorColor, + Color? searchAreaFocusedBorderColor, + Color? andRadioActiveColor, + WidgetStateProperty? andRadioFillColor, + Color? orRadioActiveColor, + WidgetStateProperty? orRadioFillColor, + Color? advancedFilterValueDropdownFocusedBorderColor, + Color? advancedFilterTypeDropdownFocusedBorderColor, + Color? calendarIconColor, + Color? advancedFilterValueTextAreaCursorColor, + Color? searchIconColor, + Color? closeIconColor, + Color? advancedFilterPopupDropdownIconColor, + Color? caseSensitiveIconActiveColor, + Color? caseSensitiveIconColor, + Color? advancedFilterTypeDropdownIconColor, + Color? advancedFilterValueDropdownIconColor, + Color? filterPopupTopDividerColor, + Color? filterPopupBottomDividerColor, + Color? okFilteringLabelDisabledButtonColor, + Color? appBarBottomBorderColor, }) { brightness = brightness ?? Brightness.light; return SfDataGridThemeData( - gridLineColor: gridLineColor, - gridLineStrokeWidth: gridLineStrokeWidth, - selectionColor: selectionColor, - currentCellStyle: currentCellStyle, - frozenPaneLineColor: frozenPaneLineColor, - frozenPaneLineWidth: frozenPaneLineWidth, - headerHoverColor: headerHoverColor, - sortIconColor: sortIconColor, - headerColor: headerColor, - frozenPaneElevation: frozenPaneElevation, - rowHoverColor: rowHoverColor, - columnResizeIndicatorColor: columnResizeIndicatorColor, - columnResizeIndicatorStrokeWidth: columnResizeIndicatorStrokeWidth, - rowHoverTextStyle: rowHoverTextStyle, - sortIcon: sortIcon, - filterIcon: filterIcon, - filterIconColor: filterIconColor, - filterIconHoverColor: filterIconHoverColor, - sortOrderNumberColor: sortOrderNumberColor, - sortOrderNumberBackgroundColor: sortOrderNumberBackgroundColor, - filterPopupTextStyle: filterPopupTextStyle, - filterPopupDisabledTextStyle: filterPopupDisabledTextStyle, - columnDragIndicatorColor: columnDragIndicatorColor, - columnDragIndicatorStrokeWidth: columnDragIndicatorStrokeWidth, - groupExpanderIcon: groupExpanderIcon, - indentColumnWidth: indentColumnWidth, - indentColumnColor: indentColumnColor); + gridLineColor: gridLineColor, + gridLineStrokeWidth: gridLineStrokeWidth, + selectionColor: selectionColor, + currentCellStyle: currentCellStyle, + frozenPaneLineColor: frozenPaneLineColor, + frozenPaneLineWidth: frozenPaneLineWidth, + headerHoverColor: headerHoverColor, + sortIconColor: sortIconColor, + headerColor: headerColor, + frozenPaneElevation: frozenPaneElevation, + rowHoverColor: rowHoverColor, + columnResizeIndicatorColor: columnResizeIndicatorColor, + columnResizeIndicatorStrokeWidth: columnResizeIndicatorStrokeWidth, + rowHoverTextStyle: rowHoverTextStyle, + sortIcon: sortIcon, + filterIcon: filterIcon, + filterIconColor: filterIconColor, + filterIconHoverColor: filterIconHoverColor, + sortOrderNumberColor: sortOrderNumberColor, + sortOrderNumberBackgroundColor: sortOrderNumberBackgroundColor, + filterPopupTextStyle: filterPopupTextStyle, + filterPopupDisabledTextStyle: filterPopupDisabledTextStyle, + columnDragIndicatorColor: columnDragIndicatorColor, + columnDragIndicatorStrokeWidth: columnDragIndicatorStrokeWidth, + groupExpanderIcon: groupExpanderIcon, + indentColumnWidth: indentColumnWidth, + indentColumnColor: indentColumnColor, + captionSummaryRowColor: captionSummaryRowColor, + filterPopupCheckColor: filterPopupCheckColor, + filterPopupCheckboxFillColor: filterPopupCheckboxFillColor, + filterPopupInputBorderColor: filterPopupInputBorderColor, + filterPopupBackgroundColor: filterPopupBackgroundColor, + filterPopupIconColor: filterPopupIconColor, + filterPopupDisabledIconColor: filterPopupDisabledIconColor, + advancedFilterPopupDropdownColor: advancedFilterPopupDropdownColor, + noMatchesFilteringLabelColor: noMatchesFilteringLabelColor, + okFilteringLabelColor: okFilteringLabelColor, + okFilteringLabelButtonColor: okFilteringLabelButtonColor, + cancelFilteringLabelColor: cancelFilteringLabelColor, + cancelFilteringLabelButtonColor: cancelFilteringLabelButtonColor, + searchAreaCursorColor: searchAreaCursorColor, + searchAreaFocusedBorderColor: searchAreaFocusedBorderColor, + andRadioActiveColor: andRadioActiveColor, + andRadioFillColor: andRadioFillColor, + orRadioActiveColor: orRadioActiveColor, + orRadioFillColor: orRadioFillColor, + calendarIconColor: calendarIconColor, + advancedFilterTypeDropdownFocusedBorderColor: + advancedFilterTypeDropdownFocusedBorderColor, + advancedFilterValueDropdownFocusedBorderColor: + advancedFilterValueDropdownFocusedBorderColor, + advancedFilterValueTextAreaCursorColor: + advancedFilterValueTextAreaCursorColor, + searchIconColor: searchIconColor, + closeIconColor: closeIconColor, + advancedFilterPopupDropdownIconColor: + advancedFilterPopupDropdownIconColor, + caseSensitiveIconActiveColor: caseSensitiveIconActiveColor, + caseSensitiveIconColor: caseSensitiveIconColor, + advancedFilterTypeDropdownIconColor: advancedFilterTypeDropdownIconColor, + advancedFilterValueDropdownIconColor: + advancedFilterValueDropdownIconColor, + filterPopupBottomDividerColor: filterPopupBottomDividerColor, + filterPopupTopDividerColor: filterPopupTopDividerColor, + okFilteringLabelDisabledButtonColor: okFilteringLabelDisabledButtonColor, + appBarBottomBorderColor: appBarBottomBorderColor, + ); } /// The color for grid line. @@ -498,6 +607,108 @@ class SfDataGridThemeData with Diagnosticable { /// The color of an indent column. final Color? indentColumnColor; + /// The color of the caption summary row. + final Color? captionSummaryRowColor; + + /// The checkmark color of the checkbox in the filter popup. + final Color? filterPopupCheckColor; + + /// The fill color of the checkbox in the filter popup. + final WidgetStateProperty? filterPopupCheckboxFillColor; + + /// The border color of the text field (input box) inside the filter popup. + final Color? filterPopupInputBorderColor; + + /// The background color of the filter popup. + final Color? filterPopupBackgroundColor; + + /// The color of icons displayed in the filter popup. + final Color? filterPopupIconColor; + + /// The color of disabled icons in the filter popup. + final Color? filterPopupDisabledIconColor; + + /// The background color of the dropdown in the advanced filter popup. + final Color? advancedFilterPopupDropdownColor; + + /// The color of the "No Matches" filtering label when no results are found. + final Color? noMatchesFilteringLabelColor; + + /// The color of the OK label in the filtering popup. + final Color? okFilteringLabelColor; + + /// The color of the OK button in the filtering popup. + final Color? okFilteringLabelButtonColor; + + /// The color of the cancel label in the filtering popup. + final Color? cancelFilteringLabelColor; + + /// The color of the cancel button in the filtering popup. + final Color? cancelFilteringLabelButtonColor; + + /// The cursor color in the search area. + final Color? searchAreaCursorColor; + + /// The focused border color of the search area. + final Color? searchAreaFocusedBorderColor; + + /// The active (selected) color of the "AND" radio button. + final Color? andRadioActiveColor; + + /// The fill color of the "AND" radio button. + final WidgetStateProperty? andRadioFillColor; + + /// The active (selected) color of the "OR" radio button. + final Color? orRadioActiveColor; + + /// The fill color of the "OR" radio button. + final WidgetStateProperty? orRadioFillColor; + + /// The color of the calendar icon. + final Color? calendarIconColor; + + /// The focused border color of the advanced filter type dropdown. + final Color? advancedFilterTypeDropdownFocusedBorderColor; + + /// The focused border color of the advanced filter value dropdown. + final Color? advancedFilterValueDropdownFocusedBorderColor; + + /// The cursor color in the advanced filter value text area. + final Color? advancedFilterValueTextAreaCursorColor; + + /// The color of the search icon. + final Color? searchIconColor; + + /// The color of the close icon. + final Color? closeIconColor; + + /// The color of the dropdown icon of the advanced filter popup. + final Color? advancedFilterPopupDropdownIconColor; + + /// The active color of the case-sensitive icon. + final Color? caseSensitiveIconActiveColor; + + /// The default color of the case-sensitive icon. + final Color? caseSensitiveIconColor; + + /// The background color of the advanced filter type dropdown icon. + final Color? advancedFilterTypeDropdownIconColor; + + /// The background color of the advanced filter value dropdown icon. + final Color? advancedFilterValueDropdownIconColor; + + /// The color of the bottom divider in the filter popup. + final Color? filterPopupBottomDividerColor; + + /// The color of the top divider in the filter popup. + final Color? filterPopupTopDividerColor; + + /// The color of the disabled OK button in the filtering popup. + final Color? okFilteringLabelDisabledButtonColor; + + /// The color of the bottom border of the app bar. + final Color? appBarBottomBorderColor; + /// Creates a copy of this theme but with the given /// fields replaced with the new values. SfDataGridThemeData copyWith({ @@ -529,96 +740,420 @@ class SfDataGridThemeData with Diagnosticable { Widget? groupExpanderIcon, double indentColumnWidth = 40.0, Color? indentColumnColor, + Color? captionSummaryRowColor, + Color? filterPopupCheckColor, + WidgetStateProperty? filterPopupCheckboxFillColor, + Color? filterPopupInputBorderColor, + Color? filterPopupBackgroundColor, + Color? filterPopupIconColor, + Color? filterPopupDisabledIconColor, + Color? advancedFilterPopupDropdownColor, + Color? noMatchesFilteringLabelColor, + Color? okFilteringLabelColor, + Color? okFilteringLabelButtonColor, + Color? cancelFilteringLabelColor, + Color? cancelFilteringLabelButtonColor, + Color? searchAreaCursorColor, + Color? searchAreaFocusedBorderColor, + Color? andRadioActiveColor, + WidgetStateProperty? andRadioFillColor, + Color? orRadioActiveColor, + WidgetStateProperty? orRadioFillColor, + Color? advancedFilterTypeDropdownFocusedBorderColor, + Color? advancedFilterValueDropdownFocusedBorderColor, + Color? calendarIconColor, + Color? advancedFilterValueTextAreaCursorColor, + Color? searchIconColor, + Color? closeIconColor, + Color? advancedFilterPopupDropdownIconColor, + Color? caseSensitiveIconActiveColor, + Color? caseSensitiveIconColor, + Color? advancedFilterTypeDropdownIconColor, + Color? advancedFilterValueDropdownIconColor, + Color? filterPopupTopDividerColor, + Color? filterPopupBottomDividerColor, + Color? okFilteringLabelDisabledButtonColor, + Color? appBarBottomBorderColor, }) { return SfDataGridThemeData.raw( - brightness: brightness, - gridLineColor: gridLineColor ?? this.gridLineColor, - gridLineStrokeWidth: gridLineStrokeWidth ?? this.gridLineStrokeWidth, - selectionColor: selectionColor ?? this.selectionColor, - currentCellStyle: currentCellStyle ?? this.currentCellStyle, - frozenPaneLineColor: frozenPaneLineColor ?? this.frozenPaneLineColor, - frozenPaneLineWidth: frozenPaneLineWidth ?? this.frozenPaneLineWidth, - sortIconColor: sortIconColor ?? this.sortIconColor, - headerColor: headerColor ?? this.headerColor, - headerHoverColor: headerHoverColor ?? this.headerHoverColor, - frozenPaneElevation: frozenPaneElevation ?? this.frozenPaneElevation, - columnResizeIndicatorColor: - columnResizeIndicatorColor ?? this.columnResizeIndicatorColor, - columnResizeIndicatorStrokeWidth: columnResizeIndicatorStrokeWidth ?? - this.columnResizeIndicatorStrokeWidth, - rowHoverColor: rowHoverColor ?? this.rowHoverColor, - rowHoverTextStyle: rowHoverTextStyle ?? this.rowHoverTextStyle, - sortIcon: sortIcon ?? this.sortIcon, - filterIcon: filterIcon ?? this.filterIcon, - filterIconColor: filterIconColor ?? this.filterIconColor, - filterIconHoverColor: filterIconHoverColor ?? this.filterIconHoverColor, - sortOrderNumberColor: sortOrderNumberColor ?? this.sortOrderNumberColor, - sortOrderNumberBackgroundColor: sortOrderNumberBackgroundColor ?? - this.sortOrderNumberBackgroundColor, - filterPopupTextStyle: filterPopupTextStyle ?? this.filterPopupTextStyle, - filterPopupDisabledTextStyle: - filterPopupDisabledTextStyle ?? this.filterPopupDisabledTextStyle, - columnDragIndicatorColor: - columnDragIndicatorColor ?? this.columnDragIndicatorColor, - columnDragIndicatorStrokeWidth: columnDragIndicatorStrokeWidth ?? - this.columnDragIndicatorStrokeWidth, - groupExpanderIcon: groupExpanderIcon ?? this.groupExpanderIcon, - indentColumnWidth: indentColumnWidth, - indentColumnColor: indentColumnColor ?? this.indentColumnColor); + brightness: brightness, + gridLineColor: gridLineColor ?? this.gridLineColor, + gridLineStrokeWidth: gridLineStrokeWidth ?? this.gridLineStrokeWidth, + selectionColor: selectionColor ?? this.selectionColor, + currentCellStyle: currentCellStyle ?? this.currentCellStyle, + frozenPaneLineColor: frozenPaneLineColor ?? this.frozenPaneLineColor, + frozenPaneLineWidth: frozenPaneLineWidth ?? this.frozenPaneLineWidth, + sortIconColor: sortIconColor ?? this.sortIconColor, + headerColor: headerColor ?? this.headerColor, + headerHoverColor: headerHoverColor ?? this.headerHoverColor, + frozenPaneElevation: frozenPaneElevation ?? this.frozenPaneElevation, + columnResizeIndicatorColor: + columnResizeIndicatorColor ?? this.columnResizeIndicatorColor, + columnResizeIndicatorStrokeWidth: + columnResizeIndicatorStrokeWidth ?? + this.columnResizeIndicatorStrokeWidth, + rowHoverColor: rowHoverColor ?? this.rowHoverColor, + rowHoverTextStyle: rowHoverTextStyle ?? this.rowHoverTextStyle, + sortIcon: sortIcon ?? this.sortIcon, + filterIcon: filterIcon ?? this.filterIcon, + filterIconColor: filterIconColor ?? this.filterIconColor, + filterIconHoverColor: filterIconHoverColor ?? this.filterIconHoverColor, + sortOrderNumberColor: sortOrderNumberColor ?? this.sortOrderNumberColor, + sortOrderNumberBackgroundColor: + sortOrderNumberBackgroundColor ?? this.sortOrderNumberBackgroundColor, + filterPopupTextStyle: filterPopupTextStyle ?? this.filterPopupTextStyle, + filterPopupDisabledTextStyle: + filterPopupDisabledTextStyle ?? this.filterPopupDisabledTextStyle, + columnDragIndicatorColor: + columnDragIndicatorColor ?? this.columnDragIndicatorColor, + columnDragIndicatorStrokeWidth: + columnDragIndicatorStrokeWidth ?? this.columnDragIndicatorStrokeWidth, + groupExpanderIcon: groupExpanderIcon ?? this.groupExpanderIcon, + indentColumnWidth: indentColumnWidth, + indentColumnColor: indentColumnColor ?? this.indentColumnColor, + captionSummaryRowColor: + captionSummaryRowColor ?? this.captionSummaryRowColor, + filterPopupCheckColor: + filterPopupCheckColor ?? this.filterPopupCheckColor, + filterPopupCheckboxFillColor: + filterPopupCheckboxFillColor ?? this.filterPopupCheckboxFillColor, + filterPopupInputBorderColor: + filterPopupInputBorderColor ?? this.filterPopupInputBorderColor, + filterPopupBackgroundColor: + filterPopupBackgroundColor ?? this.filterPopupBackgroundColor, + filterPopupIconColor: filterPopupIconColor ?? this.filterPopupIconColor, + filterPopupDisabledIconColor: + filterPopupDisabledIconColor ?? this.filterPopupDisabledIconColor, + advancedFilterPopupDropdownColor: + advancedFilterPopupDropdownColor ?? + this.advancedFilterPopupDropdownColor, + noMatchesFilteringLabelColor: + noMatchesFilteringLabelColor ?? this.noMatchesFilteringLabelColor, + okFilteringLabelColor: + okFilteringLabelColor ?? this.okFilteringLabelColor, + okFilteringLabelButtonColor: + okFilteringLabelButtonColor ?? this.okFilteringLabelButtonColor, + cancelFilteringLabelColor: + cancelFilteringLabelColor ?? this.cancelFilteringLabelColor, + cancelFilteringLabelButtonColor: + cancelFilteringLabelButtonColor ?? + this.cancelFilteringLabelButtonColor, + searchAreaCursorColor: + searchAreaCursorColor ?? this.searchAreaCursorColor, + searchAreaFocusedBorderColor: + searchAreaFocusedBorderColor ?? this.searchAreaFocusedBorderColor, + andRadioActiveColor: andRadioActiveColor ?? this.andRadioActiveColor, + andRadioFillColor: andRadioFillColor ?? this.andRadioFillColor, + orRadioActiveColor: orRadioActiveColor ?? this.orRadioActiveColor, + orRadioFillColor: orRadioFillColor ?? this.orRadioFillColor, + calendarIconColor: calendarIconColor ?? this.calendarIconColor, + advancedFilterValueDropdownFocusedBorderColor: + advancedFilterValueDropdownFocusedBorderColor ?? + this.advancedFilterValueDropdownFocusedBorderColor, + advancedFilterTypeDropdownFocusedBorderColor: + advancedFilterTypeDropdownFocusedBorderColor ?? + this.advancedFilterTypeDropdownFocusedBorderColor, + advancedFilterValueTextAreaCursorColor: + advancedFilterValueTextAreaCursorColor ?? + this.advancedFilterValueTextAreaCursorColor, + searchIconColor: searchIconColor ?? this.searchIconColor, + closeIconColor: closeIconColor ?? this.closeIconColor, + advancedFilterPopupDropdownIconColor: + advancedFilterPopupDropdownIconColor ?? + this.advancedFilterPopupDropdownIconColor, + caseSensitiveIconActiveColor: + caseSensitiveIconActiveColor ?? this.caseSensitiveIconActiveColor, + caseSensitiveIconColor: + caseSensitiveIconColor ?? this.caseSensitiveIconColor, + advancedFilterTypeDropdownIconColor: + advancedFilterTypeDropdownIconColor ?? + this.advancedFilterTypeDropdownIconColor, + advancedFilterValueDropdownIconColor: + advancedFilterValueDropdownIconColor ?? + this.advancedFilterValueDropdownIconColor, + filterPopupBottomDividerColor: + filterPopupBottomDividerColor ?? this.filterPopupBottomDividerColor, + filterPopupTopDividerColor: + filterPopupTopDividerColor ?? this.filterPopupTopDividerColor, + okFilteringLabelDisabledButtonColor: + okFilteringLabelDisabledButtonColor ?? + this.okFilteringLabelDisabledButtonColor, + appBarBottomBorderColor: + appBarBottomBorderColor ?? this.appBarBottomBorderColor, + ); } /// Linearly interpolate between two themes. static SfDataGridThemeData? lerp( - SfDataGridThemeData? a, SfDataGridThemeData? b, double t) { + SfDataGridThemeData? a, + SfDataGridThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfDataGridThemeData( gridLineColor: Color.lerp(a!.gridLineColor, b!.gridLineColor, t), - gridLineStrokeWidth: - lerpDouble(a.gridLineStrokeWidth, b.gridLineStrokeWidth, t), + gridLineStrokeWidth: lerpDouble( + a.gridLineStrokeWidth, + b.gridLineStrokeWidth, + t, + ), selectionColor: Color.lerp(a.selectionColor, b.selectionColor, t), currentCellStyle: DataGridCurrentCellStyle.lerp( - a.currentCellStyle, b.currentCellStyle, t), - frozenPaneLineColor: - Color.lerp(a.frozenPaneLineColor, b.frozenPaneLineColor, t), - frozenPaneLineWidth: - lerpDouble(a.frozenPaneLineWidth, b.frozenPaneLineWidth, t), + a.currentCellStyle, + b.currentCellStyle, + t, + ), + frozenPaneLineColor: Color.lerp( + a.frozenPaneLineColor, + b.frozenPaneLineColor, + t, + ), + frozenPaneLineWidth: lerpDouble( + a.frozenPaneLineWidth, + b.frozenPaneLineWidth, + t, + ), sortIconColor: Color.lerp(a.sortIconColor, b.sortIconColor, t), headerHoverColor: Color.lerp(a.headerHoverColor, b.headerHoverColor, t), headerColor: Color.lerp(a.headerColor, b.headerColor, t), - frozenPaneElevation: - lerpDouble(a.frozenPaneElevation, b.frozenPaneElevation, t), + frozenPaneElevation: lerpDouble( + a.frozenPaneElevation, + b.frozenPaneElevation, + t, + ), rowHoverColor: Color.lerp(a.rowHoverColor, b.rowHoverColor, t), columnResizeIndicatorColor: Color.lerp( - a.columnResizeIndicatorColor, b.columnResizeIndicatorColor, t), + a.columnResizeIndicatorColor, + b.columnResizeIndicatorColor, + t, + ), columnResizeIndicatorStrokeWidth: lerpDouble( - a.columnResizeIndicatorStrokeWidth, - b.columnResizeIndicatorStrokeWidth, - t), - rowHoverTextStyle: - TextStyle.lerp(a.rowHoverTextStyle, b.rowHoverTextStyle, t), + a.columnResizeIndicatorStrokeWidth, + b.columnResizeIndicatorStrokeWidth, + t, + ), + rowHoverTextStyle: TextStyle.lerp( + a.rowHoverTextStyle, + b.rowHoverTextStyle, + t, + ), filterIconColor: Color.lerp(a.filterIconColor, b.filterIconColor, t), - filterIconHoverColor: - Color.lerp(a.filterIconHoverColor, b.filterIconHoverColor, t), - sortOrderNumberColor: - Color.lerp(a.sortOrderNumberColor, b.sortOrderNumberColor, t), + filterIconHoverColor: Color.lerp( + a.filterIconHoverColor, + b.filterIconHoverColor, + t, + ), + sortOrderNumberColor: Color.lerp( + a.sortOrderNumberColor, + b.sortOrderNumberColor, + t, + ), sortOrderNumberBackgroundColor: Color.lerp( - a.sortOrderNumberBackgroundColor, - b.sortOrderNumberBackgroundColor, - t), - filterPopupTextStyle: - TextStyle.lerp(a.filterPopupTextStyle, b.filterPopupTextStyle, t), + a.sortOrderNumberBackgroundColor, + b.sortOrderNumberBackgroundColor, + t, + ), + filterPopupTextStyle: TextStyle.lerp( + a.filterPopupTextStyle, + b.filterPopupTextStyle, + t, + ), filterPopupDisabledTextStyle: TextStyle.lerp( - a.filterPopupDisabledTextStyle, b.filterPopupDisabledTextStyle, t), - columnDragIndicatorColor: - Color.lerp(a.columnDragIndicatorColor, b.columnDragIndicatorColor, t), + a.filterPopupDisabledTextStyle, + b.filterPopupDisabledTextStyle, + t, + ), + columnDragIndicatorColor: Color.lerp( + a.columnDragIndicatorColor, + b.columnDragIndicatorColor, + t, + ), columnDragIndicatorStrokeWidth: lerpDouble( - a.columnDragIndicatorStrokeWidth, - b.columnDragIndicatorStrokeWidth, - t), - indentColumnColor: - Color.lerp(a.indentColumnColor, b.indentColumnColor, t), + a.columnDragIndicatorStrokeWidth, + b.columnDragIndicatorStrokeWidth, + t, + ), + indentColumnColor: Color.lerp( + a.indentColumnColor, + b.indentColumnColor, + t, + ), + captionSummaryRowColor: Color.lerp( + a.captionSummaryRowColor, + b.captionSummaryRowColor, + t, + ), + filterPopupCheckColor: Color.lerp( + a.filterPopupCheckColor, + b.filterPopupCheckColor, + t, + ), + filterPopupCheckboxFillColor: WidgetStateProperty.resolveWith(( + Set states, + ) { + return Color.lerp( + a.filterPopupCheckboxFillColor?.resolve(states), + b.filterPopupCheckboxFillColor?.resolve(states), + t, + ); + }), + filterPopupInputBorderColor: Color.lerp( + a.filterPopupInputBorderColor, + b.filterPopupInputBorderColor, + t, + ), + filterPopupBackgroundColor: Color.lerp( + a.filterPopupBackgroundColor, + b.filterPopupBackgroundColor, + t, + ), + filterPopupIconColor: Color.lerp( + a.filterPopupIconColor, + b.filterPopupIconColor, + t, + ), + filterPopupDisabledIconColor: Color.lerp( + a.filterPopupDisabledIconColor, + b.filterPopupDisabledIconColor, + t, + ), + advancedFilterPopupDropdownColor: Color.lerp( + a.advancedFilterPopupDropdownColor, + b.advancedFilterPopupDropdownColor, + t, + ), + noMatchesFilteringLabelColor: Color.lerp( + a.noMatchesFilteringLabelColor, + b.noMatchesFilteringLabelColor, + t, + ), + okFilteringLabelColor: Color.lerp( + a.okFilteringLabelColor, + b.okFilteringLabelColor, + t, + ), + okFilteringLabelButtonColor: Color.lerp( + a.okFilteringLabelButtonColor, + b.okFilteringLabelButtonColor, + t, + ), + cancelFilteringLabelColor: Color.lerp( + a.cancelFilteringLabelColor, + b.cancelFilteringLabelColor, + t, + ), + cancelFilteringLabelButtonColor: Color.lerp( + a.cancelFilteringLabelButtonColor, + b.cancelFilteringLabelButtonColor, + t, + ), + searchAreaFocusedBorderColor: Color.lerp( + a.searchAreaFocusedBorderColor, + b.searchAreaFocusedBorderColor, + t, + ), + searchAreaCursorColor: Color.lerp( + a.searchAreaCursorColor, + b.searchAreaCursorColor, + t, + ), + andRadioActiveColor: Color.lerp( + a.andRadioActiveColor, + b.andRadioActiveColor, + t, + ), + andRadioFillColor: WidgetStateProperty.resolveWith(( + Set states, + ) { + return Color.lerp( + a.andRadioFillColor?.resolve(states), + b.andRadioFillColor?.resolve(states), + t, + ); + }), + orRadioActiveColor: Color.lerp( + a.orRadioActiveColor, + b.orRadioActiveColor, + t, + ), + orRadioFillColor: WidgetStateProperty.resolveWith(( + Set states, + ) { + return Color.lerp( + a.orRadioFillColor?.resolve(states), + b.orRadioFillColor?.resolve(states), + t, + ); + }), + calendarIconColor: Color.lerp( + a.calendarIconColor, + b.calendarIconColor, + t, + ), + advancedFilterValueDropdownFocusedBorderColor: Color.lerp( + a.advancedFilterValueDropdownFocusedBorderColor, + b.advancedFilterValueDropdownFocusedBorderColor, + t, + ), + advancedFilterTypeDropdownFocusedBorderColor: Color.lerp( + a.advancedFilterTypeDropdownFocusedBorderColor, + b.advancedFilterTypeDropdownFocusedBorderColor, + t, + ), + advancedFilterValueTextAreaCursorColor: Color.lerp( + a.advancedFilterValueTextAreaCursorColor, + b.advancedFilterValueTextAreaCursorColor, + t, + ), + searchIconColor: Color.lerp(a.searchIconColor, b.searchIconColor, t), + closeIconColor: Color.lerp(a.closeIconColor, b.closeIconColor, t), + advancedFilterPopupDropdownIconColor: Color.lerp( + a.advancedFilterPopupDropdownIconColor, + b.advancedFilterPopupDropdownIconColor, + t, + ), + caseSensitiveIconActiveColor: Color.lerp( + a.caseSensitiveIconActiveColor, + b.caseSensitiveIconActiveColor, + t, + ), + caseSensitiveIconColor: Color.lerp( + a.caseSensitiveIconColor, + b.caseSensitiveIconColor, + t, + ), + advancedFilterValueDropdownIconColor: Color.lerp( + a.advancedFilterValueDropdownIconColor, + b.advancedFilterValueDropdownIconColor, + t, + ), + advancedFilterTypeDropdownIconColor: Color.lerp( + a.advancedFilterTypeDropdownIconColor, + b.advancedFilterTypeDropdownIconColor, + t, + ), + filterPopupBottomDividerColor: Color.lerp( + a.filterPopupBottomDividerColor, + b.filterPopupBottomDividerColor, + t, + ), + filterPopupTopDividerColor: Color.lerp( + a.filterPopupTopDividerColor, + b.filterPopupTopDividerColor, + t, + ), + okFilteringLabelDisabledButtonColor: Color.lerp( + a.okFilteringLabelDisabledButtonColor, + b.okFilteringLabelDisabledButtonColor, + t, + ), + appBarBottomBorderColor: Color.lerp( + a.appBarBottomBorderColor, + b.appBarBottomBorderColor, + t, + ), ); } @@ -661,7 +1196,50 @@ class SfDataGridThemeData with Diagnosticable { columnDragIndicatorStrokeWidth && other.groupExpanderIcon == groupExpanderIcon && other.indentColumnWidth == indentColumnWidth && - other.indentColumnColor == indentColumnColor; + other.indentColumnColor == indentColumnColor && + other.captionSummaryRowColor == captionSummaryRowColor && + other.filterPopupCheckColor == filterPopupCheckColor && + other.filterPopupCheckboxFillColor == filterPopupCheckboxFillColor && + other.filterPopupInputBorderColor == filterPopupInputBorderColor && + other.filterPopupBackgroundColor == filterPopupBackgroundColor && + other.filterPopupIconColor == filterPopupIconColor && + other.filterPopupDisabledIconColor == filterPopupDisabledIconColor && + other.advancedFilterPopupDropdownColor == + advancedFilterPopupDropdownColor && + other.noMatchesFilteringLabelColor == noMatchesFilteringLabelColor && + other.okFilteringLabelColor == okFilteringLabelColor && + other.okFilteringLabelButtonColor == okFilteringLabelButtonColor && + other.cancelFilteringLabelColor == cancelFilteringLabelColor && + other.cancelFilteringLabelButtonColor == + cancelFilteringLabelButtonColor && + other.searchAreaFocusedBorderColor == searchAreaFocusedBorderColor && + other.searchAreaCursorColor == searchAreaCursorColor && + other.andRadioActiveColor == andRadioActiveColor && + other.andRadioFillColor == andRadioFillColor && + other.orRadioActiveColor == orRadioActiveColor && + other.orRadioFillColor == orRadioFillColor && + other.calendarIconColor == calendarIconColor && + other.advancedFilterValueDropdownFocusedBorderColor == + advancedFilterValueDropdownFocusedBorderColor && + other.advancedFilterTypeDropdownFocusedBorderColor == + advancedFilterTypeDropdownFocusedBorderColor && + other.advancedFilterValueTextAreaCursorColor == + advancedFilterValueTextAreaCursorColor && + other.searchIconColor == searchIconColor && + other.closeIconColor == closeIconColor && + other.advancedFilterPopupDropdownIconColor == + advancedFilterPopupDropdownIconColor && + other.caseSensitiveIconActiveColor == caseSensitiveIconActiveColor && + other.caseSensitiveIconColor == caseSensitiveIconColor && + other.advancedFilterValueDropdownIconColor == + advancedFilterValueDropdownIconColor && + other.advancedFilterTypeDropdownIconColor == + advancedFilterTypeDropdownIconColor && + other.filterPopupBottomDividerColor == filterPopupBottomDividerColor && + other.filterPopupTopDividerColor == filterPopupTopDividerColor && + other.okFilteringLabelDisabledButtonColor == + okFilteringLabelDisabledButtonColor && + other.appBarBottomBorderColor == appBarBottomBorderColor; } @override @@ -693,7 +1271,41 @@ class SfDataGridThemeData with Diagnosticable { columnDragIndicatorStrokeWidth, groupExpanderIcon, indentColumnWidth, - indentColumnColor + indentColumnColor, + captionSummaryRowColor, + filterPopupCheckColor, + filterPopupCheckboxFillColor, + filterPopupInputBorderColor, + filterPopupBackgroundColor, + filterPopupIconColor, + filterPopupDisabledIconColor, + advancedFilterPopupDropdownColor, + noMatchesFilteringLabelColor, + okFilteringLabelColor, + okFilteringLabelButtonColor, + cancelFilteringLabelColor, + cancelFilteringLabelButtonColor, + searchAreaFocusedBorderColor, + searchAreaCursorColor, + andRadioActiveColor, + andRadioFillColor, + orRadioActiveColor, + orRadioFillColor, + calendarIconColor, + advancedFilterValueDropdownFocusedBorderColor, + advancedFilterTypeDropdownFocusedBorderColor, + advancedFilterValueTextAreaCursorColor, + searchIconColor, + closeIconColor, + advancedFilterPopupDropdownIconColor, + caseSensitiveIconActiveColor, + caseSensitiveIconColor, + advancedFilterTypeDropdownIconColor, + advancedFilterValueDropdownIconColor, + filterPopupBottomDividerColor, + filterPopupTopDividerColor, + okFilteringLabelDisabledButtonColor, + appBarBottomBorderColor, ]; return Object.hashAll(values); } @@ -702,71 +1314,433 @@ class SfDataGridThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfDataGridThemeData defaultData = SfDataGridThemeData(); - properties.add(ColorProperty('gridLineColor', gridLineColor, - defaultValue: defaultData.gridLineColor)); - properties.add(DoubleProperty('gridLineStrokeWidth', gridLineStrokeWidth, - defaultValue: defaultData.gridLineStrokeWidth)); - properties.add(ColorProperty('selectionColor', selectionColor, - defaultValue: defaultData.selectionColor)); - properties.add(DiagnosticsProperty( - 'currentCellStyle', currentCellStyle, - defaultValue: defaultData.currentCellStyle)); - properties.add(ColorProperty('frozenPaneLineColor', frozenPaneLineColor, - defaultValue: defaultData.frozenPaneLineColor)); - properties.add(DoubleProperty('frozenPaneLineWidth', frozenPaneLineWidth, - defaultValue: defaultData.frozenPaneLineWidth)); - properties.add(ColorProperty('sortIconColor', sortIconColor, - defaultValue: defaultData.sortIconColor)); - properties.add(ColorProperty('headerHoverColor', headerHoverColor, - defaultValue: defaultData.headerHoverColor)); - properties.add(ColorProperty('headerColor', headerColor, - defaultValue: defaultData.headerColor)); - properties.add(DoubleProperty('frozenPaneElevation', frozenPaneElevation, - defaultValue: defaultData.frozenPaneElevation)); - properties.add(ColorProperty( - 'columnResizeIndicatorColor', columnResizeIndicatorColor, - defaultValue: defaultData.columnResizeIndicatorColor)); - properties.add(DoubleProperty( - 'columnResizeIndicatorStrokeWidth', columnResizeIndicatorStrokeWidth, - defaultValue: defaultData.columnResizeIndicatorStrokeWidth)); - properties.add(ColorProperty('rowHoverColor', rowHoverColor, - defaultValue: defaultData.rowHoverColor)); - properties.add(DiagnosticsProperty( - 'rowHoverTextStyle', rowHoverTextStyle, - defaultValue: defaultData.rowHoverTextStyle)); - properties.add(DiagnosticsProperty('sortIcon', sortIcon, - defaultValue: defaultData.sortIcon)); - properties.add(DiagnosticsProperty('filterIcon', filterIcon, - defaultValue: defaultData.filterIcon)); - properties.add(ColorProperty('filterIconColor', filterIconColor, - defaultValue: defaultData.filterIconColor)); - properties.add(ColorProperty('filterIconHoverColor', filterIconHoverColor, - defaultValue: defaultData.filterIconHoverColor)); - properties.add(ColorProperty('sortOrderNumberColor', sortOrderNumberColor, - defaultValue: defaultData.sortOrderNumberColor)); - properties.add(ColorProperty( - 'sortOrderNumberBackgroundColor', sortOrderNumberBackgroundColor, - defaultValue: defaultData.sortOrderNumberBackgroundColor)); - properties.add(DiagnosticsProperty( - 'filterPopupTextStyle', filterPopupTextStyle, - defaultValue: defaultData.filterPopupTextStyle)); - properties.add(DiagnosticsProperty( - 'filterPopupDisabledTextStyle', filterPopupDisabledTextStyle, - defaultValue: defaultData.filterPopupDisabledTextStyle)); - properties.add(ColorProperty( - 'columnDragIndicatorColor', columnDragIndicatorColor, - defaultValue: defaultData.columnDragIndicatorColor)); - properties.add(DiagnosticsProperty( - 'columnDragIndicatorStrokeWidth', columnDragIndicatorStrokeWidth, - defaultValue: defaultData.columnDragIndicatorStrokeWidth)); - properties.add(DiagnosticsProperty( - 'groupExpanderIcon', groupExpanderIcon, - defaultValue: defaultData.groupExpanderIcon)); - properties.add(DiagnosticsProperty( - 'indentColumnWidth', indentColumnWidth, - defaultValue: defaultData.indentColumnWidth)); - properties.add(ColorProperty('indentColumnColor', indentColumnColor, - defaultValue: defaultData.indentColumnColor)); + properties.add( + ColorProperty( + 'gridLineColor', + gridLineColor, + defaultValue: defaultData.gridLineColor, + ), + ); + properties.add( + DoubleProperty( + 'gridLineStrokeWidth', + gridLineStrokeWidth, + defaultValue: defaultData.gridLineStrokeWidth, + ), + ); + properties.add( + ColorProperty( + 'selectionColor', + selectionColor, + defaultValue: defaultData.selectionColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'currentCellStyle', + currentCellStyle, + defaultValue: defaultData.currentCellStyle, + ), + ); + properties.add( + ColorProperty( + 'frozenPaneLineColor', + frozenPaneLineColor, + defaultValue: defaultData.frozenPaneLineColor, + ), + ); + properties.add( + DoubleProperty( + 'frozenPaneLineWidth', + frozenPaneLineWidth, + defaultValue: defaultData.frozenPaneLineWidth, + ), + ); + properties.add( + ColorProperty( + 'sortIconColor', + sortIconColor, + defaultValue: defaultData.sortIconColor, + ), + ); + properties.add( + ColorProperty( + 'headerHoverColor', + headerHoverColor, + defaultValue: defaultData.headerHoverColor, + ), + ); + properties.add( + ColorProperty( + 'headerColor', + headerColor, + defaultValue: defaultData.headerColor, + ), + ); + properties.add( + DoubleProperty( + 'frozenPaneElevation', + frozenPaneElevation, + defaultValue: defaultData.frozenPaneElevation, + ), + ); + properties.add( + ColorProperty( + 'columnResizeIndicatorColor', + columnResizeIndicatorColor, + defaultValue: defaultData.columnResizeIndicatorColor, + ), + ); + properties.add( + DoubleProperty( + 'columnResizeIndicatorStrokeWidth', + columnResizeIndicatorStrokeWidth, + defaultValue: defaultData.columnResizeIndicatorStrokeWidth, + ), + ); + properties.add( + ColorProperty( + 'rowHoverColor', + rowHoverColor, + defaultValue: defaultData.rowHoverColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'rowHoverTextStyle', + rowHoverTextStyle, + defaultValue: defaultData.rowHoverTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'sortIcon', + sortIcon, + defaultValue: defaultData.sortIcon, + ), + ); + properties.add( + DiagnosticsProperty( + 'filterIcon', + filterIcon, + defaultValue: defaultData.filterIcon, + ), + ); + properties.add( + ColorProperty( + 'filterIconColor', + filterIconColor, + defaultValue: defaultData.filterIconColor, + ), + ); + properties.add( + ColorProperty( + 'filterIconHoverColor', + filterIconHoverColor, + defaultValue: defaultData.filterIconHoverColor, + ), + ); + properties.add( + ColorProperty( + 'sortOrderNumberColor', + sortOrderNumberColor, + defaultValue: defaultData.sortOrderNumberColor, + ), + ); + properties.add( + ColorProperty( + 'sortOrderNumberBackgroundColor', + sortOrderNumberBackgroundColor, + defaultValue: defaultData.sortOrderNumberBackgroundColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'filterPopupTextStyle', + filterPopupTextStyle, + defaultValue: defaultData.filterPopupTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'filterPopupDisabledTextStyle', + filterPopupDisabledTextStyle, + defaultValue: defaultData.filterPopupDisabledTextStyle, + ), + ); + properties.add( + ColorProperty( + 'columnDragIndicatorColor', + columnDragIndicatorColor, + defaultValue: defaultData.columnDragIndicatorColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'columnDragIndicatorStrokeWidth', + columnDragIndicatorStrokeWidth, + defaultValue: defaultData.columnDragIndicatorStrokeWidth, + ), + ); + properties.add( + DiagnosticsProperty( + 'groupExpanderIcon', + groupExpanderIcon, + defaultValue: defaultData.groupExpanderIcon, + ), + ); + properties.add( + DiagnosticsProperty( + 'indentColumnWidth', + indentColumnWidth, + defaultValue: defaultData.indentColumnWidth, + ), + ); + properties.add( + ColorProperty( + 'indentColumnColor', + indentColumnColor, + defaultValue: defaultData.indentColumnColor, + ), + ); + properties.add( + ColorProperty( + 'captionSummaryRowColor', + captionSummaryRowColor, + defaultValue: defaultData.captionSummaryRowColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupCheckColor', + filterPopupCheckColor, + defaultValue: defaultData.filterPopupCheckColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupCheckboxFillColor', + filterPopupCheckboxFillColor?.resolve({}), + defaultValue: defaultData.filterPopupCheckboxFillColor?.resolve({}), + ), + ); + properties.add( + ColorProperty( + 'filterPopupInputBorderColor', + filterPopupInputBorderColor, + defaultValue: defaultData.filterPopupInputBorderColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupBackgroundColor', + filterPopupBackgroundColor, + defaultValue: defaultData.filterPopupBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupIconColor', + filterPopupIconColor, + defaultValue: defaultData.filterPopupIconColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupDisabledIconColor', + filterPopupDisabledIconColor, + defaultValue: defaultData.filterPopupDisabledIconColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterPopupDropdownColor', + advancedFilterPopupDropdownColor, + defaultValue: defaultData.advancedFilterPopupDropdownColor, + ), + ); + properties.add( + ColorProperty( + 'noMatchesFilteringLabelColor', + noMatchesFilteringLabelColor, + defaultValue: defaultData.noMatchesFilteringLabelColor, + ), + ); + properties.add( + ColorProperty( + 'okFilteringLabelColor', + okFilteringLabelColor, + defaultValue: defaultData.okFilteringLabelColor, + ), + ); + properties.add( + ColorProperty( + 'okFilteringLabelButtonColor', + okFilteringLabelButtonColor, + defaultValue: defaultData.okFilteringLabelButtonColor, + ), + ); + properties.add( + ColorProperty( + 'cancelFilteringLabelColor', + cancelFilteringLabelColor, + defaultValue: defaultData.cancelFilteringLabelColor, + ), + ); + properties.add( + ColorProperty( + 'cancelFilteringLabelButtonColor', + cancelFilteringLabelButtonColor, + defaultValue: defaultData.cancelFilteringLabelButtonColor, + ), + ); + properties.add( + ColorProperty( + 'searchAreaFocusedBorderColor', + searchAreaFocusedBorderColor, + defaultValue: defaultData.searchAreaFocusedBorderColor, + ), + ); + properties.add( + ColorProperty( + 'searchAreaCursorColor', + searchAreaCursorColor, + defaultValue: defaultData.searchAreaCursorColor, + ), + ); + properties.add( + ColorProperty( + 'andRadioActiveColor', + andRadioActiveColor, + defaultValue: defaultData.andRadioActiveColor, + ), + ); + properties.add( + ColorProperty( + 'andRadioFillColor', + andRadioFillColor?.resolve({}), + defaultValue: defaultData.andRadioFillColor?.resolve({}), + ), + ); + properties.add( + ColorProperty( + 'orRadioActiveColor', + orRadioActiveColor, + defaultValue: defaultData.orRadioActiveColor, + ), + ); + properties.add( + ColorProperty( + 'orRadioFillColor', + orRadioFillColor?.resolve({}), + defaultValue: defaultData.orRadioFillColor?.resolve({}), + ), + ); + properties.add( + ColorProperty( + 'calendarIconColor', + calendarIconColor, + defaultValue: defaultData.calendarIconColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterValueDropdownFocusedBorderColor', + advancedFilterValueDropdownFocusedBorderColor, + defaultValue: defaultData.advancedFilterValueDropdownFocusedBorderColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterTypeDropdownFocusedBorderColor', + advancedFilterTypeDropdownFocusedBorderColor, + defaultValue: defaultData.advancedFilterTypeDropdownFocusedBorderColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterValueTextAreaCursorColor', + advancedFilterValueTextAreaCursorColor, + defaultValue: defaultData.advancedFilterValueTextAreaCursorColor, + ), + ); + properties.add( + ColorProperty( + 'searchIconColor', + searchIconColor, + defaultValue: defaultData.searchIconColor, + ), + ); + properties.add( + ColorProperty( + 'closeIconColor', + closeIconColor, + defaultValue: defaultData.closeIconColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterPopupDropdownIconColor', + advancedFilterPopupDropdownIconColor, + defaultValue: defaultData.advancedFilterPopupDropdownIconColor, + ), + ); + properties.add( + ColorProperty( + 'caseSensitiveIconActiveColor', + caseSensitiveIconActiveColor, + defaultValue: defaultData.caseSensitiveIconActiveColor, + ), + ); + properties.add( + ColorProperty( + 'caseSensitiveIconColor', + caseSensitiveIconColor, + defaultValue: defaultData.caseSensitiveIconColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterValueDropdownIconColor', + advancedFilterValueDropdownIconColor, + defaultValue: defaultData.advancedFilterValueDropdownIconColor, + ), + ); + properties.add( + ColorProperty( + 'advancedFilterTypeDropdownIconColor', + advancedFilterTypeDropdownIconColor, + defaultValue: defaultData.advancedFilterTypeDropdownIconColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupBottomDividerColor', + filterPopupBottomDividerColor, + defaultValue: defaultData.filterPopupBottomDividerColor, + ), + ); + properties.add( + ColorProperty( + 'filterPopupTopDividerColor', + filterPopupTopDividerColor, + defaultValue: defaultData.filterPopupTopDividerColor, + ), + ); + properties.add( + ColorProperty( + 'okFilteringLabelDisabledButtonColor', + okFilteringLabelDisabledButtonColor, + defaultValue: defaultData.okFilteringLabelDisabledButtonColor, + ), + ); + properties.add( + ColorProperty( + 'appBarBottomBorderColor', + appBarBottomBorderColor, + defaultValue: defaultData.appBarBottomBorderColor, + ), + ); } } @@ -774,8 +1748,10 @@ class SfDataGridThemeData with Diagnosticable { class DataGridCurrentCellStyle { /// Create a [DataGridCurrentCellStyle] that's used to configure /// a style for the current cell in [SfDataGrid]. - const DataGridCurrentCellStyle( - {required this.borderColor, required this.borderWidth}); + const DataGridCurrentCellStyle({ + required this.borderColor, + required this.borderWidth, + }); /// The color of the border in current cell. final Color borderColor; @@ -800,21 +1776,22 @@ class DataGridCurrentCellStyle { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode { - final List values = [ - borderColor, - borderWidth, - ]; + final List values = [borderColor, borderWidth]; return Object.hashAll(values); } /// Linearly interpolate between two styles. static DataGridCurrentCellStyle? lerp( - DataGridCurrentCellStyle? a, DataGridCurrentCellStyle? b, double t) { + DataGridCurrentCellStyle? a, + DataGridCurrentCellStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return DataGridCurrentCellStyle( - borderColor: Color.lerp(a!.borderColor, b!.borderColor, t)!, - borderWidth: lerpDouble(a.borderWidth, b.borderWidth, t)!); + borderColor: Color.lerp(a!.borderColor, b!.borderColor, t)!, + borderWidth: lerpDouble(a.borderWidth, b.borderWidth, t)!, + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/datapager_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/datapager_theme.dart index ddc4a28f8..7010a60bb 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/datapager_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/datapager_theme.dart @@ -9,7 +9,7 @@ import '../../theme.dart'; class SfDataPagerTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. const SfDataPagerTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant [SfDataPager] /// widgets. @@ -51,47 +51,50 @@ class SfDataPagerTheme extends InheritedTheme { class SfDataPagerThemeData with Diagnosticable { /// Create a [SfDataPagerThemeData] that's used to configure a /// [SfDataPagerTheme]. - const SfDataPagerThemeData( - {this.backgroundColor, - this.itemColor, - this.itemTextStyle, - this.selectedItemColor, - this.selectedItemTextStyle, - this.disabledItemColor, - this.disabledItemTextStyle, - this.itemBorderColor, - this.itemBorderWidth, - this.itemBorderRadius, - this.dropdownButtonBorderColor}); + const SfDataPagerThemeData({ + this.backgroundColor, + this.itemColor, + this.itemTextStyle, + this.selectedItemColor, + this.selectedItemTextStyle, + this.disabledItemColor, + this.disabledItemTextStyle, + this.itemBorderColor, + this.itemBorderWidth, + this.itemBorderRadius, + this.dropdownButtonBorderColor, + }); /// Create a [SfDataPagerThemeData] that's used to configure a /// [SfDataPagerTheme]. - factory SfDataPagerThemeData.raw( - {Brightness? brightness, - Color? backgroundColor, - Color? itemColor, - TextStyle? itemTextStyle, - Color? selectedItemColor, - TextStyle? selectedItemTextStyle, - Color? disabledItemColor, - TextStyle? disabledItemTextStyle, - Color? itemBorderColor, - double? itemBorderWidth, - BorderRadiusGeometry? itemBorderRadius, - Color? dropdownButtonBorderColor}) { + factory SfDataPagerThemeData.raw({ + Brightness? brightness, + Color? backgroundColor, + Color? itemColor, + TextStyle? itemTextStyle, + Color? selectedItemColor, + TextStyle? selectedItemTextStyle, + Color? disabledItemColor, + TextStyle? disabledItemTextStyle, + Color? itemBorderColor, + double? itemBorderWidth, + BorderRadiusGeometry? itemBorderRadius, + Color? dropdownButtonBorderColor, + }) { brightness = brightness ?? Brightness.light; return SfDataPagerThemeData( - backgroundColor: backgroundColor, - itemColor: itemColor, - itemTextStyle: itemTextStyle, - selectedItemColor: selectedItemColor, - selectedItemTextStyle: selectedItemTextStyle, - disabledItemColor: disabledItemColor, - disabledItemTextStyle: disabledItemTextStyle, - itemBorderColor: itemBorderColor, - itemBorderWidth: itemBorderWidth, - itemBorderRadius: itemBorderRadius, - dropdownButtonBorderColor: dropdownButtonBorderColor); + backgroundColor: backgroundColor, + itemColor: itemColor, + itemTextStyle: itemTextStyle, + selectedItemColor: selectedItemColor, + selectedItemTextStyle: selectedItemTextStyle, + disabledItemColor: disabledItemColor, + disabledItemTextStyle: disabledItemTextStyle, + itemBorderColor: itemBorderColor, + itemBorderWidth: itemBorderWidth, + itemBorderRadius: itemBorderRadius, + dropdownButtonBorderColor: dropdownButtonBorderColor, + ); } /// The color of the page Items @@ -135,61 +138,85 @@ class SfDataPagerThemeData with Diagnosticable { /// Creates a copy of this theme but with the given /// fields replaced with the new values. - SfDataPagerThemeData copyWith( - {Brightness? brightness, - Color? backgroundColor, - Color? itemColor, - TextStyle? itemTextStyle, - Color? selectedItemColor, - TextStyle? selectedItemTextStyle, - Color? disabledItemColor, - TextStyle? disabledItemTextStyle, - Color? itemBorderColor, - double? itemBorderWidth, - BorderRadiusGeometry? itemBorderRadius, - Color? dropdownButtonBorderColor}) { + SfDataPagerThemeData copyWith({ + Brightness? brightness, + Color? backgroundColor, + Color? itemColor, + TextStyle? itemTextStyle, + Color? selectedItemColor, + TextStyle? selectedItemTextStyle, + Color? disabledItemColor, + TextStyle? disabledItemTextStyle, + Color? itemBorderColor, + double? itemBorderWidth, + BorderRadiusGeometry? itemBorderRadius, + Color? dropdownButtonBorderColor, + }) { return SfDataPagerThemeData.raw( - brightness: brightness, - backgroundColor: backgroundColor ?? this.backgroundColor, - itemColor: itemColor ?? this.itemColor, - itemTextStyle: itemTextStyle ?? this.itemTextStyle, - selectedItemColor: selectedItemColor ?? this.selectedItemColor, - selectedItemTextStyle: - selectedItemTextStyle ?? this.selectedItemTextStyle, - disabledItemColor: disabledItemColor ?? this.disabledItemColor, - disabledItemTextStyle: - disabledItemTextStyle ?? this.disabledItemTextStyle, - itemBorderColor: itemBorderColor ?? this.itemBorderColor, - itemBorderWidth: itemBorderWidth ?? this.itemBorderWidth, - itemBorderRadius: itemBorderRadius ?? this.itemBorderRadius, - dropdownButtonBorderColor: - dropdownButtonBorderColor ?? this.dropdownButtonBorderColor); + brightness: brightness, + backgroundColor: backgroundColor ?? this.backgroundColor, + itemColor: itemColor ?? this.itemColor, + itemTextStyle: itemTextStyle ?? this.itemTextStyle, + selectedItemColor: selectedItemColor ?? this.selectedItemColor, + selectedItemTextStyle: + selectedItemTextStyle ?? this.selectedItemTextStyle, + disabledItemColor: disabledItemColor ?? this.disabledItemColor, + disabledItemTextStyle: + disabledItemTextStyle ?? this.disabledItemTextStyle, + itemBorderColor: itemBorderColor ?? this.itemBorderColor, + itemBorderWidth: itemBorderWidth ?? this.itemBorderWidth, + itemBorderRadius: itemBorderRadius ?? this.itemBorderRadius, + dropdownButtonBorderColor: + dropdownButtonBorderColor ?? this.dropdownButtonBorderColor, + ); } /// Linearly interpolate between two themes. static SfDataPagerThemeData? lerp( - SfDataPagerThemeData? a, SfDataPagerThemeData? b, double t) { + SfDataPagerThemeData? a, + SfDataPagerThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfDataPagerThemeData( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - itemColor: Color.lerp(a.itemColor, b.itemColor, t), - itemTextStyle: TextStyle.lerp(a.itemTextStyle, b.itemTextStyle, t), - selectedItemColor: - Color.lerp(a.selectedItemColor, b.selectedItemColor, t), - selectedItemTextStyle: - TextStyle.lerp(a.selectedItemTextStyle, b.selectedItemTextStyle, t), - disabledItemColor: - Color.lerp(a.disabledItemColor, b.disabledItemColor, t), - disabledItemTextStyle: - TextStyle.lerp(a.disabledItemTextStyle, b.disabledItemTextStyle, t), - itemBorderColor: Color.lerp(a.itemBorderColor, b.itemBorderColor, t), - itemBorderWidth: lerpDouble(a.itemBorderWidth, b.itemBorderWidth, t), - itemBorderRadius: BorderRadiusGeometry.lerp( - a.itemBorderRadius, b.itemBorderRadius, t), - dropdownButtonBorderColor: Color.lerp( - a.dropdownButtonBorderColor, b.dropdownButtonBorderColor, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + itemColor: Color.lerp(a.itemColor, b.itemColor, t), + itemTextStyle: TextStyle.lerp(a.itemTextStyle, b.itemTextStyle, t), + selectedItemColor: Color.lerp( + a.selectedItemColor, + b.selectedItemColor, + t, + ), + selectedItemTextStyle: TextStyle.lerp( + a.selectedItemTextStyle, + b.selectedItemTextStyle, + t, + ), + disabledItemColor: Color.lerp( + a.disabledItemColor, + b.disabledItemColor, + t, + ), + disabledItemTextStyle: TextStyle.lerp( + a.disabledItemTextStyle, + b.disabledItemTextStyle, + t, + ), + itemBorderColor: Color.lerp(a.itemBorderColor, b.itemBorderColor, t), + itemBorderWidth: lerpDouble(a.itemBorderWidth, b.itemBorderWidth, t), + itemBorderRadius: BorderRadiusGeometry.lerp( + a.itemBorderRadius, + b.itemBorderRadius, + t, + ), + dropdownButtonBorderColor: Color.lerp( + a.dropdownButtonBorderColor, + b.dropdownButtonBorderColor, + t, + ), + ); } @override @@ -228,7 +255,7 @@ class SfDataPagerThemeData with Diagnosticable { itemBorderColor, itemBorderWidth, itemBorderRadius, - dropdownButtonBorderColor + dropdownButtonBorderColor, ]; return Object.hashAll(values); } @@ -237,32 +264,82 @@ class SfDataPagerThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfDataPagerThemeData defaultData = SfDataPagerThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('itemColor', itemColor, - defaultValue: defaultData.itemColor)); - properties.add(ColorProperty('selectedItemColor', selectedItemColor, - defaultValue: defaultData.selectedItemColor)); - properties.add(ColorProperty('disabledItemColor', disabledItemColor, - defaultValue: defaultData.disabledItemColor)); - properties.add(ColorProperty('itemBorderColor', itemBorderColor, - defaultValue: defaultData.itemBorderColor)); - properties.add(DiagnosticsProperty( - 'itemTextStyle', itemTextStyle, - defaultValue: defaultData.itemTextStyle)); - properties.add(DiagnosticsProperty( - 'selectedItemTextStyle', selectedItemTextStyle, - defaultValue: defaultData.selectedItemTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledItemTextStyle', disabledItemTextStyle, - defaultValue: defaultData.disabledItemTextStyle)); - properties.add(DoubleProperty('itemBorderWidth', itemBorderWidth, - defaultValue: defaultData.itemBorderWidth)); - properties.add(DiagnosticsProperty( - 'itemBorderRadius', itemBorderRadius, - defaultValue: defaultData.itemBorderRadius)); - properties.add(ColorProperty( - 'dropdownButtonBorderColor', dropdownButtonBorderColor, - defaultValue: defaultData.dropdownButtonBorderColor)); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty( + 'itemColor', + itemColor, + defaultValue: defaultData.itemColor, + ), + ); + properties.add( + ColorProperty( + 'selectedItemColor', + selectedItemColor, + defaultValue: defaultData.selectedItemColor, + ), + ); + properties.add( + ColorProperty( + 'disabledItemColor', + disabledItemColor, + defaultValue: defaultData.disabledItemColor, + ), + ); + properties.add( + ColorProperty( + 'itemBorderColor', + itemBorderColor, + defaultValue: defaultData.itemBorderColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'itemTextStyle', + itemTextStyle, + defaultValue: defaultData.itemTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'selectedItemTextStyle', + selectedItemTextStyle, + defaultValue: defaultData.selectedItemTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledItemTextStyle', + disabledItemTextStyle, + defaultValue: defaultData.disabledItemTextStyle, + ), + ); + properties.add( + DoubleProperty( + 'itemBorderWidth', + itemBorderWidth, + defaultValue: defaultData.itemBorderWidth, + ), + ); + properties.add( + DiagnosticsProperty( + 'itemBorderRadius', + itemBorderRadius, + defaultValue: defaultData.itemBorderRadius, + ), + ); + properties.add( + ColorProperty( + 'dropdownButtonBorderColor', + dropdownButtonBorderColor, + defaultValue: defaultData.dropdownButtonBorderColor, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/daterangepicker_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/daterangepicker_theme.dart index 9bcf9a4a3..fdb7dedbc 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/daterangepicker_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/daterangepicker_theme.dart @@ -20,9 +20,11 @@ import '../../theme.dart'; class SfDateRangePickerTheme extends InheritedTheme { /// Constructor for teh calendar theme class, which applies a theme to /// descendant Syncfusion date range picker widgets. - const SfDateRangePickerTheme( - {Key? key, required this.data, required this.child}) - : super(key: key, child: child); + const SfDateRangePickerTheme({ + Key? key, + required this.data, + required this.child, + }) : super(key: key, child: child); /// Specifies the color and typography values for descendant chart widgets. /// @@ -111,33 +113,34 @@ class SfDateRangePickerThemeData with Diagnosticable { /// This will rarely be used directly. It is used by [lerp] to /// create intermediate themes based on two themes created with the /// [SfDateRangePickerThemeData] constructor. - const SfDateRangePickerThemeData( - {this.backgroundColor, - this.viewHeaderTextStyle, - this.headerTextStyle, - this.trailingDatesTextStyle, - this.leadingCellTextStyle, - this.activeDatesTextStyle, - this.cellTextStyle, - this.rangeSelectionTextStyle, - this.rangeSelectionColor, - this.leadingDatesTextStyle, - this.disabledDatesTextStyle, - this.disabledCellTextStyle, - this.selectionColor, - this.selectionTextStyle, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.headerBackgroundColor, - this.viewHeaderBackgroundColor, - this.weekNumberBackgroundColor, - this.blackoutDatesTextStyle, - this.todayHighlightColor, - this.todayTextStyle, - this.todayCellTextStyle, - this.weekendDatesTextStyle, - this.specialDatesTextStyle, - this.weekNumberTextStyle}); + const SfDateRangePickerThemeData({ + this.backgroundColor, + this.viewHeaderTextStyle, + this.headerTextStyle, + this.trailingDatesTextStyle, + this.leadingCellTextStyle, + this.activeDatesTextStyle, + this.cellTextStyle, + this.rangeSelectionTextStyle, + this.rangeSelectionColor, + this.leadingDatesTextStyle, + this.disabledDatesTextStyle, + this.disabledCellTextStyle, + this.selectionColor, + this.selectionTextStyle, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.headerBackgroundColor, + this.viewHeaderBackgroundColor, + this.weekNumberBackgroundColor, + this.blackoutDatesTextStyle, + this.todayHighlightColor, + this.todayTextStyle, + this.todayCellTextStyle, + this.weekendDatesTextStyle, + this.specialDatesTextStyle, + this.weekNumberTextStyle, + }); /// Create a [SfDateRangePickerThemeData] that's used to configure a /// [SfDateRangePickerTheme]. @@ -172,32 +175,33 @@ class SfDateRangePickerThemeData with Diagnosticable { }) { brightness = brightness ?? Brightness.light; return SfDateRangePickerThemeData( - backgroundColor: backgroundColor, - viewHeaderTextStyle: viewHeaderTextStyle, - headerTextStyle: headerTextStyle, - trailingDatesTextStyle: trailingDatesTextStyle, - leadingCellTextStyle: leadingCellTextStyle, - activeDatesTextStyle: activeDatesTextStyle, - cellTextStyle: cellTextStyle, - rangeSelectionTextStyle: rangeSelectionTextStyle, - rangeSelectionColor: rangeSelectionColor, - weekNumberBackgroundColor: weekNumberBackgroundColor, - leadingDatesTextStyle: leadingDatesTextStyle, - disabledDatesTextStyle: disabledDatesTextStyle, - disabledCellTextStyle: disabledCellTextStyle, - selectionColor: selectionColor, - selectionTextStyle: selectionTextStyle, - startRangeSelectionColor: startRangeSelectionColor, - endRangeSelectionColor: endRangeSelectionColor, - headerBackgroundColor: headerBackgroundColor, - viewHeaderBackgroundColor: viewHeaderBackgroundColor, - blackoutDatesTextStyle: blackoutDatesTextStyle, - todayHighlightColor: todayHighlightColor, - todayTextStyle: todayTextStyle, - todayCellTextStyle: todayCellTextStyle, - weekendDatesTextStyle: weekendDatesTextStyle, - specialDatesTextStyle: specialDatesTextStyle, - weekNumberTextStyle: weekNumberTextStyle); + backgroundColor: backgroundColor, + viewHeaderTextStyle: viewHeaderTextStyle, + headerTextStyle: headerTextStyle, + trailingDatesTextStyle: trailingDatesTextStyle, + leadingCellTextStyle: leadingCellTextStyle, + activeDatesTextStyle: activeDatesTextStyle, + cellTextStyle: cellTextStyle, + rangeSelectionTextStyle: rangeSelectionTextStyle, + rangeSelectionColor: rangeSelectionColor, + weekNumberBackgroundColor: weekNumberBackgroundColor, + leadingDatesTextStyle: leadingDatesTextStyle, + disabledDatesTextStyle: disabledDatesTextStyle, + disabledCellTextStyle: disabledCellTextStyle, + selectionColor: selectionColor, + selectionTextStyle: selectionTextStyle, + startRangeSelectionColor: startRangeSelectionColor, + endRangeSelectionColor: endRangeSelectionColor, + headerBackgroundColor: headerBackgroundColor, + viewHeaderBackgroundColor: viewHeaderBackgroundColor, + blackoutDatesTextStyle: blackoutDatesTextStyle, + todayHighlightColor: todayHighlightColor, + todayTextStyle: todayTextStyle, + todayCellTextStyle: todayCellTextStyle, + weekendDatesTextStyle: weekendDatesTextStyle, + specialDatesTextStyle: specialDatesTextStyle, + weekNumberTextStyle: weekNumberTextStyle, + ); } /// Specifies the background color of date picker widget. @@ -837,27 +841,51 @@ class SfDateRangePickerThemeData with Diagnosticable { /// Linearly interpolate between two themes. static SfDateRangePickerThemeData? lerp( - SfDateRangePickerThemeData? a, SfDateRangePickerThemeData? b, double t) { + SfDateRangePickerThemeData? a, + SfDateRangePickerThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfDateRangePickerThemeData( backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - rangeSelectionColor: - Color.lerp(a.rangeSelectionColor, b.rangeSelectionColor, t), + rangeSelectionColor: Color.lerp( + a.rangeSelectionColor, + b.rangeSelectionColor, + t, + ), selectionColor: Color.lerp(a.selectionColor, b.selectionColor, t), - startRangeSelectionColor: - Color.lerp(a.startRangeSelectionColor, b.startRangeSelectionColor, t), - endRangeSelectionColor: - Color.lerp(a.endRangeSelectionColor, b.endRangeSelectionColor, t), - headerBackgroundColor: - Color.lerp(a.headerBackgroundColor, b.headerBackgroundColor, t), + startRangeSelectionColor: Color.lerp( + a.startRangeSelectionColor, + b.startRangeSelectionColor, + t, + ), + endRangeSelectionColor: Color.lerp( + a.endRangeSelectionColor, + b.endRangeSelectionColor, + t, + ), + headerBackgroundColor: Color.lerp( + a.headerBackgroundColor, + b.headerBackgroundColor, + t, + ), viewHeaderBackgroundColor: Color.lerp( - a.viewHeaderBackgroundColor, b.viewHeaderBackgroundColor, t), - todayHighlightColor: - Color.lerp(a.todayHighlightColor, b.todayHighlightColor, t), + a.viewHeaderBackgroundColor, + b.viewHeaderBackgroundColor, + t, + ), + todayHighlightColor: Color.lerp( + a.todayHighlightColor, + b.todayHighlightColor, + t, + ), weekNumberBackgroundColor: Color.lerp( - a.weekNumberBackgroundColor, b.weekNumberBackgroundColor, t), + a.weekNumberBackgroundColor, + b.weekNumberBackgroundColor, + t, + ), ); } @@ -927,7 +955,7 @@ class SfDateRangePickerThemeData with Diagnosticable { todayCellTextStyle, weekendDatesTextStyle, specialDatesTextStyle, - weekNumberTextStyle + weekNumberTextStyle, ]; return Object.hashAll(values); } @@ -936,27 +964,68 @@ class SfDateRangePickerThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfDateRangePickerThemeData defaultData = SfDateRangePickerThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('rangeSelectionColor', rangeSelectionColor, - defaultValue: defaultData.rangeSelectionColor)); - properties.add(ColorProperty( - 'weekNumberBackgroundColor', weekNumberBackgroundColor, - defaultValue: defaultData.weekNumberBackgroundColor)); - properties.add(ColorProperty('selectionColor', selectionColor, - defaultValue: defaultData.selectionColor)); - properties.add(ColorProperty( - 'startRangeSelectionColor', startRangeSelectionColor, - defaultValue: defaultData.startRangeSelectionColor)); - properties.add(ColorProperty( - 'endRangeSelectionColor', endRangeSelectionColor, - defaultValue: defaultData.endRangeSelectionColor)); - properties.add(ColorProperty('headerBackgroundColor', headerBackgroundColor, - defaultValue: defaultData.headerBackgroundColor)); - properties.add(ColorProperty( - 'viewHeaderBackgroundColor', viewHeaderBackgroundColor, - defaultValue: defaultData.viewHeaderBackgroundColor)); - properties.add(ColorProperty('todayHighlightColor', todayHighlightColor, - defaultValue: defaultData.todayHighlightColor)); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty( + 'rangeSelectionColor', + rangeSelectionColor, + defaultValue: defaultData.rangeSelectionColor, + ), + ); + properties.add( + ColorProperty( + 'weekNumberBackgroundColor', + weekNumberBackgroundColor, + defaultValue: defaultData.weekNumberBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'selectionColor', + selectionColor, + defaultValue: defaultData.selectionColor, + ), + ); + properties.add( + ColorProperty( + 'startRangeSelectionColor', + startRangeSelectionColor, + defaultValue: defaultData.startRangeSelectionColor, + ), + ); + properties.add( + ColorProperty( + 'endRangeSelectionColor', + endRangeSelectionColor, + defaultValue: defaultData.endRangeSelectionColor, + ), + ); + properties.add( + ColorProperty( + 'headerBackgroundColor', + headerBackgroundColor, + defaultValue: defaultData.headerBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'viewHeaderBackgroundColor', + viewHeaderBackgroundColor, + defaultValue: defaultData.viewHeaderBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'todayHighlightColor', + todayHighlightColor, + defaultValue: defaultData.todayHighlightColor, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/gauges_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/gauges_theme.dart index 780e83705..886e60075 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/gauges_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/gauges_theme.dart @@ -29,7 +29,7 @@ import '../../theme.dart'; class SfGaugeTheme extends InheritedTheme { /// Initialize the gauge theme const SfGaugeTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant gauges widgets. /// @@ -118,27 +118,28 @@ class SfGaugeTheme extends InheritedTheme { @immutable class SfGaugeThemeData with Diagnosticable { /// Initialize the gauge theme data - const SfGaugeThemeData( - {this.backgroundColor = Colors.transparent, - this.titleColor, - this.axisLabelColor, - this.axisLineColor, - this.majorTickColor, - this.minorTickColor, - this.markerColor, - this.markerBorderColor = Colors.transparent, - this.needleColor, - this.knobColor, - this.knobBorderColor = Colors.transparent, - this.tailColor, - this.tailBorderColor = Colors.transparent, - this.rangePointerColor, - this.rangeColor, - this.titleBorderColor = Colors.transparent, - this.titleBackgroundColor = Colors.transparent, - this.titleTextStyle, - this.axisLabelTextStyle, - this.markerTextStyle}); + const SfGaugeThemeData({ + this.backgroundColor = Colors.transparent, + this.titleColor, + this.axisLabelColor, + this.axisLineColor, + this.majorTickColor, + this.minorTickColor, + this.markerColor, + this.markerBorderColor = Colors.transparent, + this.needleColor, + this.knobColor, + this.knobBorderColor = Colors.transparent, + this.tailColor, + this.tailBorderColor = Colors.transparent, + this.rangePointerColor, + this.rangeColor, + this.titleBorderColor = Colors.transparent, + this.titleBackgroundColor = Colors.transparent, + this.titleTextStyle, + this.axisLabelTextStyle, + this.markerTextStyle, + }); /// Create a [SfGaugeThemeData] given a set of exact values. /// @@ -171,26 +172,27 @@ class SfGaugeThemeData with Diagnosticable { }) { brightness = brightness ?? Brightness.light; return SfGaugeThemeData( - backgroundColor: backgroundColor, - titleColor: titleColor, - axisLabelColor: axisLabelColor, - axisLineColor: axisLineColor, - majorTickColor: majorTickColor, - minorTickColor: minorTickColor, - markerColor: markerColor, - markerBorderColor: markerBorderColor, - needleColor: needleColor, - knobColor: knobColor, - knobBorderColor: knobBorderColor, - tailColor: tailColor, - tailBorderColor: tailBorderColor, - rangePointerColor: rangePointerColor, - rangeColor: rangeColor, - titleBorderColor: titleBorderColor, - titleBackgroundColor: titleBackgroundColor, - titleTextStyle: titleTextStyle, - axisLabelTextStyle: axisLabelTextStyle, - markerTextStyle: markerTextStyle); + backgroundColor: backgroundColor, + titleColor: titleColor, + axisLabelColor: axisLabelColor, + axisLineColor: axisLineColor, + majorTickColor: majorTickColor, + minorTickColor: minorTickColor, + markerColor: markerColor, + markerBorderColor: markerBorderColor, + needleColor: needleColor, + knobColor: knobColor, + knobBorderColor: knobBorderColor, + tailColor: tailColor, + tailBorderColor: tailBorderColor, + rangePointerColor: rangePointerColor, + rangeColor: rangeColor, + titleBorderColor: titleBorderColor, + titleBackgroundColor: titleBackgroundColor, + titleTextStyle: titleTextStyle, + axisLabelTextStyle: axisLabelTextStyle, + markerTextStyle: markerTextStyle, + ); } /// Create a [SfGaugeThemeData] given a set of exact values. @@ -761,55 +763,60 @@ class SfGaugeThemeData with Diagnosticable { /// Creates a copy of this gauge theme data object with the matching fields /// replaced with the non-null parameter values. - SfGaugeThemeData copyWith( - {Brightness? brightness, - Color? backgroundColor, - Color? titleColor, - Color? axisLabelColor, - Color? axisLineColor, - Color? majorTickColor, - Color? minorTickColor, - Color? markerColor, - Color? markerBorderColor, - Color? needleColor, - Color? knobColor, - Color? knobBorderColor, - Color? tailColor, - Color? tailBorderColor, - Color? rangePointerColor, - Color? rangeColor, - Color? titleBorderColor, - Color? titleBackgroundColor, - TextStyle? titleTextStyle, - TextStyle? axisLabelTextStyle, - TextStyle? markerTextStyle}) { + SfGaugeThemeData copyWith({ + Brightness? brightness, + Color? backgroundColor, + Color? titleColor, + Color? axisLabelColor, + Color? axisLineColor, + Color? majorTickColor, + Color? minorTickColor, + Color? markerColor, + Color? markerBorderColor, + Color? needleColor, + Color? knobColor, + Color? knobBorderColor, + Color? tailColor, + Color? tailBorderColor, + Color? rangePointerColor, + Color? rangeColor, + Color? titleBorderColor, + Color? titleBackgroundColor, + TextStyle? titleTextStyle, + TextStyle? axisLabelTextStyle, + TextStyle? markerTextStyle, + }) { return SfGaugeThemeData.raw( - brightness: brightness, - backgroundColor: backgroundColor ?? this.backgroundColor, - titleColor: titleColor ?? this.titleColor, - axisLabelColor: axisLabelColor ?? this.axisLabelColor, - axisLineColor: axisLineColor ?? this.axisLineColor, - majorTickColor: majorTickColor ?? this.majorTickColor, - minorTickColor: minorTickColor ?? this.minorTickColor, - markerColor: markerColor ?? this.markerColor, - markerBorderColor: markerBorderColor ?? this.markerBorderColor, - needleColor: needleColor ?? this.needleColor, - knobColor: knobColor ?? this.knobColor, - knobBorderColor: knobBorderColor ?? this.knobBorderColor, - tailColor: tailColor ?? this.tailColor, - tailBorderColor: tailBorderColor ?? this.tailBorderColor, - rangePointerColor: rangePointerColor ?? this.rangePointerColor, - rangeColor: rangeColor ?? this.rangeColor, - titleBorderColor: titleBorderColor ?? this.titleBorderColor, - titleBackgroundColor: titleBackgroundColor ?? this.titleBackgroundColor, - titleTextStyle: titleTextStyle ?? this.titleTextStyle, - axisLabelTextStyle: axisLabelTextStyle ?? this.axisLabelTextStyle, - markerTextStyle: markerTextStyle ?? this.markerTextStyle); + brightness: brightness, + backgroundColor: backgroundColor ?? this.backgroundColor, + titleColor: titleColor ?? this.titleColor, + axisLabelColor: axisLabelColor ?? this.axisLabelColor, + axisLineColor: axisLineColor ?? this.axisLineColor, + majorTickColor: majorTickColor ?? this.majorTickColor, + minorTickColor: minorTickColor ?? this.minorTickColor, + markerColor: markerColor ?? this.markerColor, + markerBorderColor: markerBorderColor ?? this.markerBorderColor, + needleColor: needleColor ?? this.needleColor, + knobColor: knobColor ?? this.knobColor, + knobBorderColor: knobBorderColor ?? this.knobBorderColor, + tailColor: tailColor ?? this.tailColor, + tailBorderColor: tailBorderColor ?? this.tailBorderColor, + rangePointerColor: rangePointerColor ?? this.rangePointerColor, + rangeColor: rangeColor ?? this.rangeColor, + titleBorderColor: titleBorderColor ?? this.titleBorderColor, + titleBackgroundColor: titleBackgroundColor ?? this.titleBackgroundColor, + titleTextStyle: titleTextStyle ?? this.titleTextStyle, + axisLabelTextStyle: axisLabelTextStyle ?? this.axisLabelTextStyle, + markerTextStyle: markerTextStyle ?? this.markerTextStyle, + ); } /// Returns the gauge theme data static SfGaugeThemeData? lerp( - SfGaugeThemeData? a, SfGaugeThemeData? b, double t) { + SfGaugeThemeData? a, + SfGaugeThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } @@ -828,15 +835,21 @@ class SfGaugeThemeData with Diagnosticable { knobBorderColor: Color.lerp(a.knobBorderColor, b.knobBorderColor, t)!, tailColor: Color.lerp(a.tailColor, b.tailColor, t), tailBorderColor: Color.lerp(a.tailBorderColor, b.tailBorderColor, t)!, - rangePointerColor: - Color.lerp(a.rangePointerColor, b.rangePointerColor, t), + rangePointerColor: Color.lerp( + a.rangePointerColor, + b.rangePointerColor, + t, + ), rangeColor: Color.lerp(a.rangeColor, b.rangeColor, t), titleBorderColor: Color.lerp(a.titleBorderColor, b.titleBorderColor, t)!, titleBackgroundColor: Color.lerp(a.titleBackgroundColor, b.titleBackgroundColor, t)!, titleTextStyle: TextStyle.lerp(a.titleTextStyle, b.titleTextStyle, t), - axisLabelTextStyle: - TextStyle.lerp(a.axisLabelTextStyle, b.axisLabelTextStyle, t), + axisLabelTextStyle: TextStyle.lerp( + a.axisLabelTextStyle, + b.axisLabelTextStyle, + t, + ), markerTextStyle: TextStyle.lerp(a.markerTextStyle, b.markerTextStyle, t), ); } @@ -894,7 +907,7 @@ class SfGaugeThemeData with Diagnosticable { titleBackgroundColor, titleTextStyle, axisLabelTextStyle, - markerTextStyle + markerTextStyle, ]; return Object.hashAll(values); } @@ -903,48 +916,145 @@ class SfGaugeThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfGaugeThemeData defaultData = SfGaugeThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('titleColor', titleColor, - defaultValue: defaultData.titleColor)); - properties.add(ColorProperty('axisLabelColor', axisLabelColor, - defaultValue: defaultData.axisLabelColor)); - properties.add(ColorProperty('axisLineColor', axisLineColor, - defaultValue: defaultData.axisLineColor)); - properties.add(ColorProperty('majorTickColor', majorTickColor, - defaultValue: defaultData.majorTickColor)); - properties.add(ColorProperty('minorTickColor', minorTickColor, - defaultValue: defaultData.minorTickColor)); - properties.add(ColorProperty('markerColor', markerColor, - defaultValue: defaultData.markerColor)); - properties.add(ColorProperty('markerBorderColor', markerBorderColor, - defaultValue: defaultData.markerBorderColor)); - properties.add(ColorProperty('needleColor', needleColor, - defaultValue: defaultData.needleColor)); - properties.add(ColorProperty('knobColor', knobColor, - defaultValue: defaultData.knobColor)); - properties.add(ColorProperty('knobBorderColor', knobBorderColor, - defaultValue: defaultData.knobBorderColor)); - properties.add(ColorProperty('tailColor', tailColor, - defaultValue: defaultData.tailColor)); - properties.add(ColorProperty('tailBorderColor', tailBorderColor, - defaultValue: defaultData.tailBorderColor)); - properties.add(ColorProperty('rangePointerColor', rangePointerColor, - defaultValue: defaultData.rangePointerColor)); - properties.add(ColorProperty('rangeColor', rangeColor, - defaultValue: defaultData.rangeColor)); - properties.add(ColorProperty('titleBorderColor', titleBorderColor, - defaultValue: defaultData.titleBorderColor)); - properties.add(ColorProperty('titleBackgroundColor', titleBackgroundColor, - defaultValue: defaultData.titleBackgroundColor)); - properties.add(DiagnosticsProperty( - 'titleTextStyle', titleTextStyle, - defaultValue: defaultData.titleTextStyle)); - properties.add(DiagnosticsProperty( - 'axisLabelTextStyle', axisLabelTextStyle, - defaultValue: defaultData.axisLabelTextStyle)); - properties.add(DiagnosticsProperty( - 'markerTextStyle', markerTextStyle, - defaultValue: defaultData.markerTextStyle)); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty( + 'titleColor', + titleColor, + defaultValue: defaultData.titleColor, + ), + ); + properties.add( + ColorProperty( + 'axisLabelColor', + axisLabelColor, + defaultValue: defaultData.axisLabelColor, + ), + ); + properties.add( + ColorProperty( + 'axisLineColor', + axisLineColor, + defaultValue: defaultData.axisLineColor, + ), + ); + properties.add( + ColorProperty( + 'majorTickColor', + majorTickColor, + defaultValue: defaultData.majorTickColor, + ), + ); + properties.add( + ColorProperty( + 'minorTickColor', + minorTickColor, + defaultValue: defaultData.minorTickColor, + ), + ); + properties.add( + ColorProperty( + 'markerColor', + markerColor, + defaultValue: defaultData.markerColor, + ), + ); + properties.add( + ColorProperty( + 'markerBorderColor', + markerBorderColor, + defaultValue: defaultData.markerBorderColor, + ), + ); + properties.add( + ColorProperty( + 'needleColor', + needleColor, + defaultValue: defaultData.needleColor, + ), + ); + properties.add( + ColorProperty( + 'knobColor', + knobColor, + defaultValue: defaultData.knobColor, + ), + ); + properties.add( + ColorProperty( + 'knobBorderColor', + knobBorderColor, + defaultValue: defaultData.knobBorderColor, + ), + ); + properties.add( + ColorProperty( + 'tailColor', + tailColor, + defaultValue: defaultData.tailColor, + ), + ); + properties.add( + ColorProperty( + 'tailBorderColor', + tailBorderColor, + defaultValue: defaultData.tailBorderColor, + ), + ); + properties.add( + ColorProperty( + 'rangePointerColor', + rangePointerColor, + defaultValue: defaultData.rangePointerColor, + ), + ); + properties.add( + ColorProperty( + 'rangeColor', + rangeColor, + defaultValue: defaultData.rangeColor, + ), + ); + properties.add( + ColorProperty( + 'titleBorderColor', + titleBorderColor, + defaultValue: defaultData.titleBorderColor, + ), + ); + properties.add( + ColorProperty( + 'titleBackgroundColor', + titleBackgroundColor, + defaultValue: defaultData.titleBackgroundColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'titleTextStyle', + titleTextStyle, + defaultValue: defaultData.titleTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'axisLabelTextStyle', + axisLabelTextStyle, + defaultValue: defaultData.axisLabelTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'markerTextStyle', + markerTextStyle, + defaultValue: defaultData.markerTextStyle, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/maps_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/maps_theme.dart index 398532110..992dbd87c 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/maps_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/maps_theme.dart @@ -24,7 +24,7 @@ class SfMapsTheme extends InheritedTheme { /// /// The [data] and [child] arguments must not be null. const SfMapsTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant maps widgets. /// @@ -902,7 +902,10 @@ class SfMapsThemeData with Diagnosticable { /// /// The arguments must not be null. static SfMapsThemeData? lerp( - SfMapsThemeData? a, SfMapsThemeData? b, double t) { + SfMapsThemeData? a, + SfMapsThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } @@ -911,45 +914,82 @@ class SfMapsThemeData with Diagnosticable { layerStrokeColor: Color.lerp(a.layerStrokeColor, b.layerStrokeColor, t), layerStrokeWidth: lerpDouble(a.layerStrokeWidth, b.layerStrokeWidth, t)!, shapeHoverColor: Color.lerp(a.shapeHoverColor, b.shapeHoverColor, t), - shapeHoverStrokeColor: - Color.lerp(a.shapeHoverStrokeColor, b.shapeHoverStrokeColor, t), - shapeHoverStrokeWidth: - lerpDouble(a.shapeHoverStrokeWidth, b.shapeHoverStrokeWidth, t), + shapeHoverStrokeColor: Color.lerp( + a.shapeHoverStrokeColor, + b.shapeHoverStrokeColor, + t, + ), + shapeHoverStrokeWidth: lerpDouble( + a.shapeHoverStrokeWidth, + b.shapeHoverStrokeWidth, + t, + ), legendTextStyle: TextStyle.lerp(a.legendTextStyle, b.legendTextStyle, t), markerIconColor: Color.lerp(a.markerIconColor, b.markerIconColor, t), - markerIconStrokeColor: - Color.lerp(a.markerIconStrokeColor, b.markerIconStrokeColor, t), + markerIconStrokeColor: Color.lerp( + a.markerIconStrokeColor, + b.markerIconStrokeColor, + t, + ), markerIconStrokeWidth: lerpDouble(a.markerIconStrokeWidth, b.markerIconStrokeWidth, t)!, - dataLabelTextStyle: - TextStyle.lerp(a.dataLabelTextStyle, b.dataLabelTextStyle, t), + dataLabelTextStyle: TextStyle.lerp( + a.dataLabelTextStyle, + b.dataLabelTextStyle, + t, + ), bubbleColor: Color.lerp(a.bubbleColor, b.bubbleColor, t), - bubbleStrokeColor: - Color.lerp(a.bubbleStrokeColor, b.bubbleStrokeColor, t), + bubbleStrokeColor: Color.lerp( + a.bubbleStrokeColor, + b.bubbleStrokeColor, + t, + ), bubbleStrokeWidth: lerpDouble(a.bubbleStrokeWidth, b.bubbleStrokeWidth, t)!, bubbleHoverColor: Color.lerp(a.bubbleHoverColor, b.bubbleHoverColor, t), - bubbleHoverStrokeColor: - Color.lerp(a.bubbleHoverStrokeColor, b.bubbleHoverStrokeColor, t), - bubbleHoverStrokeWidth: - lerpDouble(a.bubbleHoverStrokeWidth, b.bubbleHoverStrokeWidth, t), + bubbleHoverStrokeColor: Color.lerp( + a.bubbleHoverStrokeColor, + b.bubbleHoverStrokeColor, + t, + ), + bubbleHoverStrokeWidth: lerpDouble( + a.bubbleHoverStrokeWidth, + b.bubbleHoverStrokeWidth, + t, + ), selectionColor: Color.lerp(a.selectionColor, b.selectionColor, t), - selectionStrokeColor: - Color.lerp(a.selectionStrokeColor, b.selectionStrokeColor, t), + selectionStrokeColor: Color.lerp( + a.selectionStrokeColor, + b.selectionStrokeColor, + t, + ), selectionStrokeWidth: lerpDouble(a.selectionStrokeWidth, b.selectionStrokeWidth, t)!, tooltipColor: Color.lerp(a.tooltipColor, b.tooltipColor, t), - tooltipStrokeColor: - Color.lerp(a.tooltipStrokeColor, b.tooltipStrokeColor, t), + tooltipStrokeColor: Color.lerp( + a.tooltipStrokeColor, + b.tooltipStrokeColor, + t, + ), tooltipStrokeWidth: lerpDouble(a.tooltipStrokeWidth, b.tooltipStrokeWidth, t)!, - tooltipBorderRadius: BorderRadiusGeometry.lerp( - a.tooltipBorderRadius, b.tooltipBorderRadius, t)!, + tooltipBorderRadius: + BorderRadiusGeometry.lerp( + a.tooltipBorderRadius, + b.tooltipBorderRadius, + t, + )!, toggledItemColor: Color.lerp(a.toggledItemColor, b.toggledItemColor, t), - toggledItemStrokeColor: - Color.lerp(a.toggledItemStrokeColor, b.toggledItemStrokeColor, t), - toggledItemStrokeWidth: - lerpDouble(a.toggledItemStrokeWidth, b.toggledItemStrokeWidth, t), + toggledItemStrokeColor: Color.lerp( + a.toggledItemStrokeColor, + b.toggledItemStrokeColor, + t, + ), + toggledItemStrokeWidth: lerpDouble( + a.toggledItemStrokeWidth, + b.toggledItemStrokeWidth, + t, + ), ); } @@ -1029,68 +1069,194 @@ class SfMapsThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfMapsThemeData defaultData = SfMapsThemeData(); - properties.add(ColorProperty('layerColor', layerColor, - defaultValue: defaultData.layerColor)); - properties.add(ColorProperty('layerStrokeColor', layerStrokeColor, - defaultValue: defaultData.layerStrokeColor)); - properties.add(DoubleProperty('layerStrokeWidth', layerStrokeWidth, - defaultValue: defaultData.layerStrokeWidth)); - properties.add(ColorProperty('shapeHoverColor', shapeHoverColor, - defaultValue: defaultData.shapeHoverColor)); - properties.add(ColorProperty('shapeHoverStrokeColor', shapeHoverStrokeColor, - defaultValue: defaultData.shapeHoverStrokeColor)); - properties.add(DoubleProperty( - 'shapeHoverStrokeWidth', shapeHoverStrokeWidth, - defaultValue: defaultData.shapeHoverStrokeWidth)); - properties.add(DiagnosticsProperty( - 'legendTextStyle', legendTextStyle, - defaultValue: defaultData.legendTextStyle)); - properties.add(ColorProperty('markerIconColor', markerIconColor, - defaultValue: defaultData.markerIconColor)); - properties.add(ColorProperty('markerIconStrokeColor', markerIconStrokeColor, - defaultValue: defaultData.markerIconStrokeColor)); - properties.add(DoubleProperty( - 'markerIconStrokeWidth', markerIconStrokeWidth, - defaultValue: defaultData.markerIconStrokeWidth)); - properties.add(DiagnosticsProperty( - 'dataLabelTextStyle', dataLabelTextStyle, - defaultValue: defaultData.dataLabelTextStyle)); - properties.add(ColorProperty('bubbleColor', bubbleColor, - defaultValue: defaultData.bubbleColor)); - properties.add(ColorProperty('bubbleStrokeColor', bubbleStrokeColor, - defaultValue: defaultData.bubbleStrokeColor)); - properties.add(DoubleProperty('bubbleStrokeWidth', bubbleStrokeWidth, - defaultValue: defaultData.bubbleStrokeWidth)); - properties.add(ColorProperty('bubbleHoverColor', bubbleHoverColor, - defaultValue: defaultData.bubbleHoverColor)); - properties.add(ColorProperty( - 'bubbleHoverStrokeColor', bubbleHoverStrokeColor, - defaultValue: defaultData.bubbleHoverStrokeColor)); - properties.add(DoubleProperty( - 'bubbleHoverStrokeWidth', bubbleHoverStrokeWidth, - defaultValue: defaultData.bubbleHoverStrokeWidth)); - properties.add(ColorProperty('selectionColor', selectionColor, - defaultValue: defaultData.selectionColor)); - properties.add(ColorProperty('selectionStrokeColor', selectionStrokeColor, - defaultValue: defaultData.selectionStrokeColor)); - properties.add(DoubleProperty('selectionStrokeWidth', selectionStrokeWidth, - defaultValue: defaultData.selectionStrokeWidth)); - properties.add(ColorProperty('tooltipColor', tooltipColor, - defaultValue: defaultData.tooltipColor)); - properties.add(ColorProperty('tooltipStrokeColor', tooltipStrokeColor, - defaultValue: defaultData.tooltipStrokeColor)); - properties.add(DoubleProperty('tooltipStrokeWidth', tooltipStrokeWidth, - defaultValue: defaultData.tooltipStrokeWidth)); - properties.add(DiagnosticsProperty( - 'tooltipBorderRadius', tooltipBorderRadius, - defaultValue: defaultData.tooltipBorderRadius)); - properties.add(ColorProperty('toggledItemColor', toggledItemColor, - defaultValue: defaultData.toggledItemColor)); - properties.add(ColorProperty( - 'toggledItemStrokeColor', toggledItemStrokeColor, - defaultValue: defaultData.toggledItemStrokeColor)); - properties.add(DoubleProperty( - 'toggledItemStrokeWidth', toggledItemStrokeWidth, - defaultValue: defaultData.toggledItemStrokeWidth)); + properties.add( + ColorProperty( + 'layerColor', + layerColor, + defaultValue: defaultData.layerColor, + ), + ); + properties.add( + ColorProperty( + 'layerStrokeColor', + layerStrokeColor, + defaultValue: defaultData.layerStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'layerStrokeWidth', + layerStrokeWidth, + defaultValue: defaultData.layerStrokeWidth, + ), + ); + properties.add( + ColorProperty( + 'shapeHoverColor', + shapeHoverColor, + defaultValue: defaultData.shapeHoverColor, + ), + ); + properties.add( + ColorProperty( + 'shapeHoverStrokeColor', + shapeHoverStrokeColor, + defaultValue: defaultData.shapeHoverStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'shapeHoverStrokeWidth', + shapeHoverStrokeWidth, + defaultValue: defaultData.shapeHoverStrokeWidth, + ), + ); + properties.add( + DiagnosticsProperty( + 'legendTextStyle', + legendTextStyle, + defaultValue: defaultData.legendTextStyle, + ), + ); + properties.add( + ColorProperty( + 'markerIconColor', + markerIconColor, + defaultValue: defaultData.markerIconColor, + ), + ); + properties.add( + ColorProperty( + 'markerIconStrokeColor', + markerIconStrokeColor, + defaultValue: defaultData.markerIconStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'markerIconStrokeWidth', + markerIconStrokeWidth, + defaultValue: defaultData.markerIconStrokeWidth, + ), + ); + properties.add( + DiagnosticsProperty( + 'dataLabelTextStyle', + dataLabelTextStyle, + defaultValue: defaultData.dataLabelTextStyle, + ), + ); + properties.add( + ColorProperty( + 'bubbleColor', + bubbleColor, + defaultValue: defaultData.bubbleColor, + ), + ); + properties.add( + ColorProperty( + 'bubbleStrokeColor', + bubbleStrokeColor, + defaultValue: defaultData.bubbleStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'bubbleStrokeWidth', + bubbleStrokeWidth, + defaultValue: defaultData.bubbleStrokeWidth, + ), + ); + properties.add( + ColorProperty( + 'bubbleHoverColor', + bubbleHoverColor, + defaultValue: defaultData.bubbleHoverColor, + ), + ); + properties.add( + ColorProperty( + 'bubbleHoverStrokeColor', + bubbleHoverStrokeColor, + defaultValue: defaultData.bubbleHoverStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'bubbleHoverStrokeWidth', + bubbleHoverStrokeWidth, + defaultValue: defaultData.bubbleHoverStrokeWidth, + ), + ); + properties.add( + ColorProperty( + 'selectionColor', + selectionColor, + defaultValue: defaultData.selectionColor, + ), + ); + properties.add( + ColorProperty( + 'selectionStrokeColor', + selectionStrokeColor, + defaultValue: defaultData.selectionStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'selectionStrokeWidth', + selectionStrokeWidth, + defaultValue: defaultData.selectionStrokeWidth, + ), + ); + properties.add( + ColorProperty( + 'tooltipColor', + tooltipColor, + defaultValue: defaultData.tooltipColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipStrokeColor', + tooltipStrokeColor, + defaultValue: defaultData.tooltipStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'tooltipStrokeWidth', + tooltipStrokeWidth, + defaultValue: defaultData.tooltipStrokeWidth, + ), + ); + properties.add( + DiagnosticsProperty( + 'tooltipBorderRadius', + tooltipBorderRadius, + defaultValue: defaultData.tooltipBorderRadius, + ), + ); + properties.add( + ColorProperty( + 'toggledItemColor', + toggledItemColor, + defaultValue: defaultData.toggledItemColor, + ), + ); + properties.add( + ColorProperty( + 'toggledItemStrokeColor', + toggledItemStrokeColor, + defaultValue: defaultData.toggledItemStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'toggledItemStrokeWidth', + toggledItemStrokeWidth, + defaultValue: defaultData.toggledItemStrokeWidth, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/pdfviewer_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/pdfviewer_theme.dart index 136fb1e65..3eb02145f 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/pdfviewer_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/pdfviewer_theme.dart @@ -23,7 +23,7 @@ import '../../theme.dart'; class SfPdfViewerTheme extends InheritedTheme { /// Creates an argument constructor of [SfPdfViewerTheme] class. const SfPdfViewerTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant /// [SfPdfViewer] widgets. @@ -127,24 +127,26 @@ class SfPdfViewerThemeData with Diagnosticable { }); /// Creating an argument constructor of SfPdfViewerThemeData class. - factory SfPdfViewerThemeData.raw( - {Color? backgroundColor, - Color? progressBarColor, - PdfScrollStatusStyle? scrollStatusStyle, - PdfScrollHeadStyle? scrollHeadStyle, - PdfBookmarkViewStyle? bookmarkViewStyle, - PdfPaginationDialogStyle? paginationDialogStyle, - PdfHyperlinkDialogStyle? hyperlinkDialogStyle, - PdfPasswordDialogStyle? passwordDialogStyle}) { + factory SfPdfViewerThemeData.raw({ + Color? backgroundColor, + Color? progressBarColor, + PdfScrollStatusStyle? scrollStatusStyle, + PdfScrollHeadStyle? scrollHeadStyle, + PdfBookmarkViewStyle? bookmarkViewStyle, + PdfPaginationDialogStyle? paginationDialogStyle, + PdfHyperlinkDialogStyle? hyperlinkDialogStyle, + PdfPasswordDialogStyle? passwordDialogStyle, + }) { return SfPdfViewerThemeData( - backgroundColor: backgroundColor, - progressBarColor: progressBarColor, - scrollStatusStyle: scrollStatusStyle, - scrollHeadStyle: scrollHeadStyle, - bookmarkViewStyle: bookmarkViewStyle, - paginationDialogStyle: paginationDialogStyle, - hyperlinkDialogStyle: hyperlinkDialogStyle, - passwordDialogStyle: passwordDialogStyle); + backgroundColor: backgroundColor, + progressBarColor: progressBarColor, + scrollStatusStyle: scrollStatusStyle, + scrollHeadStyle: scrollHeadStyle, + bookmarkViewStyle: bookmarkViewStyle, + paginationDialogStyle: paginationDialogStyle, + hyperlinkDialogStyle: hyperlinkDialogStyle, + passwordDialogStyle: passwordDialogStyle, + ); } /// Specifies the background color of [SfPdfViewer] widget. @@ -369,15 +371,16 @@ class SfPdfViewerThemeData with Diagnosticable { /// Creates a copy of this [SfPdfViewer] theme data object with the /// matching fields replaced with the non-null parameter values. - SfPdfViewerThemeData copyWith( - {Color? backgroundColor, - Color? progressBarColor, - PdfScrollStatusStyle? scrollStatusStyle, - PdfScrollHeadStyle? scrollHeadStyle, - PdfBookmarkViewStyle? bookmarkViewStyle, - PdfPaginationDialogStyle? paginationDialogStyle, - PdfHyperlinkDialogStyle? hyperlinkDialogStyle, - PdfPasswordDialogStyle? passwordDialogStyle}) { + SfPdfViewerThemeData copyWith({ + Color? backgroundColor, + Color? progressBarColor, + PdfScrollStatusStyle? scrollStatusStyle, + PdfScrollHeadStyle? scrollHeadStyle, + PdfBookmarkViewStyle? bookmarkViewStyle, + PdfPaginationDialogStyle? paginationDialogStyle, + PdfHyperlinkDialogStyle? hyperlinkDialogStyle, + PdfPasswordDialogStyle? passwordDialogStyle, + }) { return SfPdfViewerThemeData.raw( backgroundColor: backgroundColor ?? this.backgroundColor, progressBarColor: progressBarColor ?? this.progressBarColor, @@ -393,25 +396,47 @@ class SfPdfViewerThemeData with Diagnosticable { /// Linearly interpolate between two themes. static SfPdfViewerThemeData? lerp( - SfPdfViewerThemeData? a, SfPdfViewerThemeData? b, double t) { + SfPdfViewerThemeData? a, + SfPdfViewerThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfPdfViewerThemeData( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - progressBarColor: Color.lerp(a.progressBarColor, b.progressBarColor, t), - scrollStatusStyle: PdfScrollStatusStyle.lerp( - a.scrollStatusStyle, b.scrollStatusStyle, t), - scrollHeadStyle: - PdfScrollHeadStyle.lerp(a.scrollHeadStyle, b.scrollHeadStyle, t), - bookmarkViewStyle: PdfBookmarkViewStyle.lerp( - a.bookmarkViewStyle, b.bookmarkViewStyle, t), - paginationDialogStyle: PdfPaginationDialogStyle.lerp( - a.paginationDialogStyle, b.paginationDialogStyle, t), - hyperlinkDialogStyle: PdfHyperlinkDialogStyle.lerp( - a.hyperlinkDialogStyle, b.hyperlinkDialogStyle, t), - passwordDialogStyle: PdfPasswordDialogStyle.lerp( - a.passwordDialogStyle, b.passwordDialogStyle, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + progressBarColor: Color.lerp(a.progressBarColor, b.progressBarColor, t), + scrollStatusStyle: PdfScrollStatusStyle.lerp( + a.scrollStatusStyle, + b.scrollStatusStyle, + t, + ), + scrollHeadStyle: PdfScrollHeadStyle.lerp( + a.scrollHeadStyle, + b.scrollHeadStyle, + t, + ), + bookmarkViewStyle: PdfBookmarkViewStyle.lerp( + a.bookmarkViewStyle, + b.bookmarkViewStyle, + t, + ), + paginationDialogStyle: PdfPaginationDialogStyle.lerp( + a.paginationDialogStyle, + b.paginationDialogStyle, + t, + ), + hyperlinkDialogStyle: PdfHyperlinkDialogStyle.lerp( + a.hyperlinkDialogStyle, + b.hyperlinkDialogStyle, + t, + ), + passwordDialogStyle: PdfPasswordDialogStyle.lerp( + a.passwordDialogStyle, + b.passwordDialogStyle, + t, + ), + ); } @override @@ -453,28 +478,62 @@ class SfPdfViewerThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfPdfViewerThemeData defaultData = SfPdfViewerThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties.add(ColorProperty('progressBarColor', progressBarColor, - defaultValue: defaultData.progressBarColor)); - properties.add(DiagnosticsProperty( - 'scrollStatusStyle', scrollStatusStyle, - defaultValue: defaultData.scrollStatusStyle)); - properties.add(DiagnosticsProperty( - 'scrollHeadStyle', scrollHeadStyle, - defaultValue: defaultData.scrollHeadStyle)); - properties.add(DiagnosticsProperty( - 'bookmarkViewStyle', bookmarkViewStyle, - defaultValue: defaultData.bookmarkViewStyle)); - properties.add(DiagnosticsProperty( - 'paginationDialogStyle', paginationDialogStyle, - defaultValue: defaultData.paginationDialogStyle)); - properties.add(DiagnosticsProperty( - 'hyperlinkDialogStyle', hyperlinkDialogStyle, - defaultValue: defaultData.hyperlinkDialogStyle)); - properties.add(DiagnosticsProperty( - 'passwordDialogStyle', passwordDialogStyle, - defaultValue: defaultData.passwordDialogStyle)); + properties.add( + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty( + 'progressBarColor', + progressBarColor, + defaultValue: defaultData.progressBarColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'scrollStatusStyle', + scrollStatusStyle, + defaultValue: defaultData.scrollStatusStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'scrollHeadStyle', + scrollHeadStyle, + defaultValue: defaultData.scrollHeadStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'bookmarkViewStyle', + bookmarkViewStyle, + defaultValue: defaultData.bookmarkViewStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'paginationDialogStyle', + paginationDialogStyle, + defaultValue: defaultData.paginationDialogStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'hyperlinkDialogStyle', + hyperlinkDialogStyle, + defaultValue: defaultData.hyperlinkDialogStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'passwordDialogStyle', + passwordDialogStyle, + defaultValue: defaultData.passwordDialogStyle, + ), + ); } } @@ -513,14 +572,21 @@ class PdfScrollStatusStyle { /// Linearly interpolate between two styles. static PdfScrollStatusStyle? lerp( - PdfScrollStatusStyle? a, PdfScrollStatusStyle? b, double t) { + PdfScrollStatusStyle? a, + PdfScrollStatusStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return PdfScrollStatusStyle( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - pageInfoTextStyle: - TextStyle.lerp(a.pageInfoTextStyle, b.pageInfoTextStyle, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + pageInfoTextStyle: TextStyle.lerp( + a.pageInfoTextStyle, + b.pageInfoTextStyle, + t, + ), + ); } } @@ -541,7 +607,7 @@ class PdfScrollHeadStyle { int get hashCode { final List values = [ backgroundColor, - pageNumberTextStyle + pageNumberTextStyle, ]; return Object.hashAll(values); } @@ -562,14 +628,21 @@ class PdfScrollHeadStyle { /// Linearly interpolate between two styles. static PdfScrollHeadStyle? lerp( - PdfScrollHeadStyle? a, PdfScrollHeadStyle? b, double t) { + PdfScrollHeadStyle? a, + PdfScrollHeadStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return PdfScrollHeadStyle( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - pageNumberTextStyle: - TextStyle.lerp(a.pageNumberTextStyle, b.pageNumberTextStyle, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + pageNumberTextStyle: TextStyle.lerp( + a.pageNumberTextStyle, + b.pageNumberTextStyle, + t, + ), + ); } } @@ -577,16 +650,17 @@ class PdfScrollHeadStyle { class PdfBookmarkViewStyle { /// Creates a [PdfBookmarkViewStyle] that's used to configure styles for the /// bookmark view in [SfPdfViewer]. - const PdfBookmarkViewStyle( - {this.backgroundColor, - this.headerBarColor, - this.closeIconColor, - this.backIconColor, - this.navigationIconColor, - this.selectionColor, - this.titleSeparatorColor, - this.titleTextStyle, - this.headerTextStyle}); + const PdfBookmarkViewStyle({ + this.backgroundColor, + this.headerBarColor, + this.closeIconColor, + this.backIconColor, + this.navigationIconColor, + this.selectionColor, + this.titleSeparatorColor, + this.titleTextStyle, + this.headerTextStyle, + }); /// The background color of bookmark view in [SfPdfViewer]. final Color? backgroundColor; @@ -627,7 +701,7 @@ class PdfBookmarkViewStyle { selectionColor, titleSeparatorColor, titleTextStyle, - headerTextStyle + headerTextStyle, ]; return Object.hashAll(values); } @@ -655,23 +729,32 @@ class PdfBookmarkViewStyle { /// Linearly interpolate between two styles. static PdfBookmarkViewStyle? lerp( - PdfBookmarkViewStyle? a, PdfBookmarkViewStyle? b, double t) { + PdfBookmarkViewStyle? a, + PdfBookmarkViewStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return PdfBookmarkViewStyle( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - headerBarColor: Color.lerp(a.headerBarColor, b.headerBarColor, t), - closeIconColor: Color.lerp(a.closeIconColor, b.closeIconColor, t), - backIconColor: Color.lerp(a.backIconColor, b.backIconColor, t), - navigationIconColor: - Color.lerp(a.navigationIconColor, b.navigationIconColor, t), - selectionColor: Color.lerp(a.selectionColor, b.selectionColor, t), - titleSeparatorColor: - Color.lerp(a.titleSeparatorColor, b.titleSeparatorColor, t), - titleTextStyle: TextStyle.lerp(a.titleTextStyle, b.titleTextStyle, t), - headerTextStyle: - TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + headerBarColor: Color.lerp(a.headerBarColor, b.headerBarColor, t), + closeIconColor: Color.lerp(a.closeIconColor, b.closeIconColor, t), + backIconColor: Color.lerp(a.backIconColor, b.backIconColor, t), + navigationIconColor: Color.lerp( + a.navigationIconColor, + b.navigationIconColor, + t, + ), + selectionColor: Color.lerp(a.selectionColor, b.selectionColor, t), + titleSeparatorColor: Color.lerp( + a.titleSeparatorColor, + b.titleSeparatorColor, + t, + ), + titleTextStyle: TextStyle.lerp(a.titleTextStyle, b.titleTextStyle, t), + headerTextStyle: TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t), + ); } } @@ -680,15 +763,16 @@ class PdfBookmarkViewStyle { class PdfPaginationDialogStyle { /// Creates a [PdfPaginationDialogStyle] that's used to configure styles for /// the pagination dialog in [SfPdfViewer]. - const PdfPaginationDialogStyle( - {this.backgroundColor, - this.headerTextStyle, - this.inputFieldTextStyle, - this.hintTextStyle, - this.pageInfoTextStyle, - this.validationTextStyle, - this.okTextStyle, - this.cancelTextStyle}); + const PdfPaginationDialogStyle({ + this.backgroundColor, + this.headerTextStyle, + this.inputFieldTextStyle, + this.hintTextStyle, + this.pageInfoTextStyle, + this.validationTextStyle, + this.okTextStyle, + this.cancelTextStyle, + }); /// The background color of pagination dialog in [SfPdfViewer]. final Color? backgroundColor; @@ -727,7 +811,7 @@ class PdfPaginationDialogStyle { pageInfoTextStyle, validationTextStyle, okTextStyle, - cancelTextStyle + cancelTextStyle, ]; return Object.hashAll(values); } @@ -754,24 +838,35 @@ class PdfPaginationDialogStyle { /// Linearly interpolate between two styles. static PdfPaginationDialogStyle? lerp( - PdfPaginationDialogStyle? a, PdfPaginationDialogStyle? b, double t) { + PdfPaginationDialogStyle? a, + PdfPaginationDialogStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return PdfPaginationDialogStyle( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - headerTextStyle: - TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t), - inputFieldTextStyle: - TextStyle.lerp(a.inputFieldTextStyle, b.inputFieldTextStyle, t), - hintTextStyle: TextStyle.lerp(a.hintTextStyle, b.hintTextStyle, t), - pageInfoTextStyle: - TextStyle.lerp(a.pageInfoTextStyle, b.pageInfoTextStyle, t), - validationTextStyle: - TextStyle.lerp(a.validationTextStyle, b.validationTextStyle, t), - okTextStyle: TextStyle.lerp(a.okTextStyle, b.okTextStyle, t), - cancelTextStyle: - TextStyle.lerp(a.cancelTextStyle, b.cancelTextStyle, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + headerTextStyle: TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t), + inputFieldTextStyle: TextStyle.lerp( + a.inputFieldTextStyle, + b.inputFieldTextStyle, + t, + ), + hintTextStyle: TextStyle.lerp(a.hintTextStyle, b.hintTextStyle, t), + pageInfoTextStyle: TextStyle.lerp( + a.pageInfoTextStyle, + b.pageInfoTextStyle, + t, + ), + validationTextStyle: TextStyle.lerp( + a.validationTextStyle, + b.validationTextStyle, + t, + ), + okTextStyle: TextStyle.lerp(a.okTextStyle, b.okTextStyle, t), + cancelTextStyle: TextStyle.lerp(a.cancelTextStyle, b.cancelTextStyle, t), + ); } } @@ -780,13 +875,14 @@ class PdfPaginationDialogStyle { class PdfHyperlinkDialogStyle { /// Creates a [PdfHyperlinkDialogStyle] that's used to configure styles for /// the hyperlink dialog in [SfPdfViewer]. - const PdfHyperlinkDialogStyle( - {this.backgroundColor, - this.headerTextStyle, - this.contentTextStyle, - this.openTextStyle, - this.cancelTextStyle, - this.closeIconColor}); + const PdfHyperlinkDialogStyle({ + this.backgroundColor, + this.headerTextStyle, + this.contentTextStyle, + this.openTextStyle, + this.cancelTextStyle, + this.closeIconColor, + }); /// The background color of hyperlink dialog in [SfPdfViewer]. final Color? backgroundColor; @@ -841,20 +937,25 @@ class PdfHyperlinkDialogStyle { /// Linearly interpolate between two styles. static PdfHyperlinkDialogStyle? lerp( - PdfHyperlinkDialogStyle? a, PdfHyperlinkDialogStyle? b, double t) { + PdfHyperlinkDialogStyle? a, + PdfHyperlinkDialogStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return PdfHyperlinkDialogStyle( - backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), - headerTextStyle: - TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t), - contentTextStyle: - TextStyle.lerp(a.contentTextStyle, b.contentTextStyle, t), - openTextStyle: TextStyle.lerp(a.openTextStyle, b.openTextStyle, t), - cancelTextStyle: - TextStyle.lerp(a.cancelTextStyle, b.cancelTextStyle, t), - closeIconColor: Color.lerp(a.closeIconColor, b.closeIconColor, t)); + backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), + headerTextStyle: TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t), + contentTextStyle: TextStyle.lerp( + a.contentTextStyle, + b.contentTextStyle, + t, + ), + openTextStyle: TextStyle.lerp(a.openTextStyle, b.openTextStyle, t), + cancelTextStyle: TextStyle.lerp(a.cancelTextStyle, b.cancelTextStyle, t), + closeIconColor: Color.lerp(a.closeIconColor, b.closeIconColor, t), + ); } } @@ -937,7 +1038,7 @@ class PdfPasswordDialogStyle { closeIconColor, visibleIconColor, inputFieldBorderColor, - errorBorderColor + errorBorderColor, ]; return Object.hashAll(values); } @@ -969,28 +1070,46 @@ class PdfPasswordDialogStyle { /// Linearly interpolate between two styles. static PdfPasswordDialogStyle? lerp( - PdfPasswordDialogStyle? a, PdfPasswordDialogStyle? b, double t) { + PdfPasswordDialogStyle? a, + PdfPasswordDialogStyle? b, + double t, + ) { if (a == null && b == null) { return null; } return PdfPasswordDialogStyle( backgroundColor: Color.lerp(a!.backgroundColor, b!.backgroundColor, t), headerTextStyle: TextStyle.lerp(a.headerTextStyle, b.headerTextStyle, t), - contentTextStyle: - TextStyle.lerp(a.contentTextStyle, b.contentTextStyle, t), - inputFieldTextStyle: - TextStyle.lerp(a.inputFieldTextStyle, b.inputFieldTextStyle, t), + contentTextStyle: TextStyle.lerp( + a.contentTextStyle, + b.contentTextStyle, + t, + ), + inputFieldTextStyle: TextStyle.lerp( + a.inputFieldTextStyle, + b.inputFieldTextStyle, + t, + ), inputFieldHintTextStyle: TextStyle.lerp( - a.inputFieldHintTextStyle, b.inputFieldHintTextStyle, t), + a.inputFieldHintTextStyle, + b.inputFieldHintTextStyle, + t, + ), inputFieldLabelTextStyle: TextStyle.lerp( - a.inputFieldLabelTextStyle, b.inputFieldLabelTextStyle, t), + a.inputFieldLabelTextStyle, + b.inputFieldLabelTextStyle, + t, + ), errorTextStyle: TextStyle.lerp(a.errorTextStyle, b.errorTextStyle, t), openTextStyle: TextStyle.lerp(a.openTextStyle, b.openTextStyle, t), cancelTextStyle: TextStyle.lerp(a.cancelTextStyle, b.cancelTextStyle, t), closeIconColor: Color.lerp(a.closeIconColor, b.closeIconColor, t), visibleIconColor: Color.lerp(a.visibleIconColor, b.visibleIconColor, t), - inputFieldBorderColor: - Color.lerp(a.inputFieldBorderColor, b.inputFieldBorderColor, t), + inputFieldBorderColor: Color.lerp( + a.inputFieldBorderColor, + b.inputFieldBorderColor, + t, + ), errorBorderColor: Color.lerp(a.errorBorderColor, b.errorBorderColor, t), ); } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/range_selector_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/range_selector_theme.dart index 5c12d304e..b6b885cdc 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/range_selector_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/range_selector_theme.dart @@ -10,9 +10,11 @@ class SfRangeSelectorTheme extends InheritedTheme { /// Applies the given theme [data] to [child]. /// /// The [data] and [child] arguments must not be null. - const SfRangeSelectorTheme( - {Key? key, required this.data, required this.child}) - : super(key: key, child: child); + const SfRangeSelectorTheme({ + Key? key, + required this.data, + required this.child, + }) : super(key: key, child: child); /// Specifies the color and typography values for descendant /// range selector widgets. @@ -150,94 +152,95 @@ class SfRangeSelectorTheme extends InheritedTheme { /// for customizing the visual appearance of the range selector. class SfRangeSelectorThemeData extends SfRangeSliderThemeData { /// Creating an argument constructor of SfRangeSelectorThemeData class. - const SfRangeSelectorThemeData( - {double activeTrackHeight = 6.0, - double inactiveTrackHeight = 4.0, - Size? tickSize, - Size? minorTickSize, - Offset? tickOffset, - Offset? labelOffset, - TextStyle? inactiveLabelStyle, - TextStyle? activeLabelStyle, - TextStyle? tooltipTextStyle, - Color? inactiveTrackColor, - Color? activeTrackColor, - Color? thumbColor, - Color? activeTickColor, - Color? inactiveTickColor, - Color? disabledActiveTickColor, - Color? disabledInactiveTickColor, - Color? activeMinorTickColor, - Color? inactiveMinorTickColor, - Color? disabledActiveMinorTickColor, - Color? disabledInactiveMinorTickColor, - Color? overlayColor, - Color? inactiveDividerColor, - Color? activeDividerColor, - Color? disabledActiveTrackColor, - Color? disabledInactiveTrackColor, - Color? disabledActiveDividerColor, - Color? disabledInactiveDividerColor, - Color? disabledThumbColor, - this.activeRegionColor, - this.inactiveRegionColor, - Color? tooltipBackgroundColor, - Color? overlappingTooltipStrokeColor, - Color? thumbStrokeColor, - Color? overlappingThumbStrokeColor, - Color? activeDividerStrokeColor, - Color? inactiveDividerStrokeColor, - double? trackCornerRadius, - double overlayRadius = 24.0, - double thumbRadius = 10.0, - double? activeDividerRadius, - double? inactiveDividerRadius, - double? thumbStrokeWidth, - double? activeDividerStrokeWidth, - double? inactiveDividerStrokeWidth}) - : super( - activeTrackHeight: activeTrackHeight, - inactiveTrackHeight: inactiveTrackHeight, - tickSize: tickSize, - minorTickSize: minorTickSize, - tickOffset: tickOffset, - labelOffset: labelOffset, - inactiveLabelStyle: inactiveLabelStyle, - activeLabelStyle: activeLabelStyle, - tooltipTextStyle: tooltipTextStyle, - inactiveTrackColor: inactiveTrackColor, - activeTrackColor: activeTrackColor, - inactiveDividerColor: inactiveDividerColor, - activeDividerColor: activeDividerColor, - thumbColor: thumbColor, - thumbStrokeColor: thumbStrokeColor, - overlappingThumbStrokeColor: overlappingThumbStrokeColor, - activeDividerStrokeColor: activeDividerStrokeColor, - inactiveDividerStrokeColor: inactiveDividerStrokeColor, - overlayColor: overlayColor, - activeTickColor: activeTickColor, - inactiveTickColor: inactiveTickColor, - disabledActiveTickColor: disabledActiveTickColor, - disabledInactiveTickColor: disabledInactiveTickColor, - activeMinorTickColor: activeMinorTickColor, - inactiveMinorTickColor: inactiveMinorTickColor, - disabledActiveMinorTickColor: disabledActiveMinorTickColor, - disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, - disabledActiveTrackColor: disabledActiveTrackColor, - disabledInactiveTrackColor: disabledInactiveTrackColor, - disabledActiveDividerColor: disabledActiveDividerColor, - disabledInactiveDividerColor: disabledInactiveDividerColor, - disabledThumbColor: disabledThumbColor, - tooltipBackgroundColor: tooltipBackgroundColor, - overlappingTooltipStrokeColor: overlappingTooltipStrokeColor, - overlayRadius: overlayRadius, - thumbRadius: thumbRadius, - activeDividerRadius: activeDividerRadius, - inactiveDividerRadius: inactiveDividerRadius, - thumbStrokeWidth: thumbStrokeWidth, - activeDividerStrokeWidth: activeDividerStrokeWidth, - inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, - trackCornerRadius: trackCornerRadius); + const SfRangeSelectorThemeData({ + double activeTrackHeight = 6.0, + double inactiveTrackHeight = 4.0, + Size? tickSize, + Size? minorTickSize, + Offset? tickOffset, + Offset? labelOffset, + TextStyle? inactiveLabelStyle, + TextStyle? activeLabelStyle, + TextStyle? tooltipTextStyle, + Color? inactiveTrackColor, + Color? activeTrackColor, + Color? thumbColor, + Color? activeTickColor, + Color? inactiveTickColor, + Color? disabledActiveTickColor, + Color? disabledInactiveTickColor, + Color? activeMinorTickColor, + Color? inactiveMinorTickColor, + Color? disabledActiveMinorTickColor, + Color? disabledInactiveMinorTickColor, + Color? overlayColor, + Color? inactiveDividerColor, + Color? activeDividerColor, + Color? disabledActiveTrackColor, + Color? disabledInactiveTrackColor, + Color? disabledActiveDividerColor, + Color? disabledInactiveDividerColor, + Color? disabledThumbColor, + this.activeRegionColor, + this.inactiveRegionColor, + Color? tooltipBackgroundColor, + Color? overlappingTooltipStrokeColor, + Color? thumbStrokeColor, + Color? overlappingThumbStrokeColor, + Color? activeDividerStrokeColor, + Color? inactiveDividerStrokeColor, + double? trackCornerRadius, + double overlayRadius = 24.0, + double thumbRadius = 10.0, + double? activeDividerRadius, + double? inactiveDividerRadius, + double? thumbStrokeWidth, + double? activeDividerStrokeWidth, + double? inactiveDividerStrokeWidth, + }) : super( + activeTrackHeight: activeTrackHeight, + inactiveTrackHeight: inactiveTrackHeight, + tickSize: tickSize, + minorTickSize: minorTickSize, + tickOffset: tickOffset, + labelOffset: labelOffset, + inactiveLabelStyle: inactiveLabelStyle, + activeLabelStyle: activeLabelStyle, + tooltipTextStyle: tooltipTextStyle, + inactiveTrackColor: inactiveTrackColor, + activeTrackColor: activeTrackColor, + inactiveDividerColor: inactiveDividerColor, + activeDividerColor: activeDividerColor, + thumbColor: thumbColor, + thumbStrokeColor: thumbStrokeColor, + overlappingThumbStrokeColor: overlappingThumbStrokeColor, + activeDividerStrokeColor: activeDividerStrokeColor, + inactiveDividerStrokeColor: inactiveDividerStrokeColor, + overlayColor: overlayColor, + activeTickColor: activeTickColor, + inactiveTickColor: inactiveTickColor, + disabledActiveTickColor: disabledActiveTickColor, + disabledInactiveTickColor: disabledInactiveTickColor, + activeMinorTickColor: activeMinorTickColor, + inactiveMinorTickColor: inactiveMinorTickColor, + disabledActiveMinorTickColor: disabledActiveMinorTickColor, + disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, + disabledActiveTrackColor: disabledActiveTrackColor, + disabledInactiveTrackColor: disabledInactiveTrackColor, + disabledActiveDividerColor: disabledActiveDividerColor, + disabledInactiveDividerColor: disabledInactiveDividerColor, + disabledThumbColor: disabledThumbColor, + tooltipBackgroundColor: tooltipBackgroundColor, + overlappingTooltipStrokeColor: overlappingTooltipStrokeColor, + overlayRadius: overlayRadius, + thumbRadius: thumbRadius, + activeDividerRadius: activeDividerRadius, + inactiveDividerRadius: inactiveDividerRadius, + thumbStrokeWidth: thumbStrokeWidth, + activeDividerStrokeWidth: activeDividerStrokeWidth, + inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, + trackCornerRadius: trackCornerRadius, + ); /// Returns a new instance of [SfRangeSelectorThemeData] for the given values. factory SfRangeSelectorThemeData.raw({ @@ -296,50 +299,51 @@ class SfRangeSelectorThemeData extends SfRangeSliderThemeData { thumbRadius ??= 10.0; return SfRangeSelectorThemeData( - activeTrackHeight: activeTrackHeight, - inactiveTrackHeight: inactiveTrackHeight, - tickSize: tickSize, - minorTickSize: minorTickSize, - tickOffset: tickOffset, - labelOffset: labelOffset, - inactiveLabelStyle: inactiveLabelStyle, - activeLabelStyle: activeLabelStyle, - tooltipTextStyle: tooltipTextStyle, - inactiveTrackColor: inactiveTrackColor, - activeTrackColor: activeTrackColor, - inactiveDividerColor: inactiveDividerColor, - activeDividerColor: activeDividerColor, - thumbColor: thumbColor, - thumbStrokeColor: thumbStrokeColor, - overlappingThumbStrokeColor: overlappingThumbStrokeColor, - activeDividerStrokeColor: activeDividerStrokeColor, - inactiveDividerStrokeColor: inactiveDividerStrokeColor, - overlayColor: overlayColor, - activeTickColor: activeTickColor, - inactiveTickColor: inactiveTickColor, - disabledActiveTickColor: disabledActiveTickColor, - disabledInactiveTickColor: disabledInactiveTickColor, - activeMinorTickColor: activeMinorTickColor, - inactiveMinorTickColor: inactiveMinorTickColor, - disabledActiveMinorTickColor: disabledActiveMinorTickColor, - disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, - disabledActiveTrackColor: disabledActiveTrackColor, - disabledInactiveTrackColor: disabledInactiveTrackColor, - disabledActiveDividerColor: disabledActiveDividerColor, - disabledInactiveDividerColor: disabledInactiveDividerColor, - disabledThumbColor: disabledThumbColor, - activeRegionColor: activeRegionColor, - inactiveRegionColor: inactiveRegionColor, - tooltipBackgroundColor: tooltipBackgroundColor, - overlappingTooltipStrokeColor: overlappingTooltipStrokeColor, - overlayRadius: overlayRadius, - thumbRadius: thumbRadius, - activeDividerRadius: activeDividerRadius, - inactiveDividerRadius: inactiveDividerRadius, - thumbStrokeWidth: thumbStrokeWidth, - activeDividerStrokeWidth: activeDividerStrokeWidth, - inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, - trackCornerRadius: trackCornerRadius); + activeTrackHeight: activeTrackHeight, + inactiveTrackHeight: inactiveTrackHeight, + tickSize: tickSize, + minorTickSize: minorTickSize, + tickOffset: tickOffset, + labelOffset: labelOffset, + inactiveLabelStyle: inactiveLabelStyle, + activeLabelStyle: activeLabelStyle, + tooltipTextStyle: tooltipTextStyle, + inactiveTrackColor: inactiveTrackColor, + activeTrackColor: activeTrackColor, + inactiveDividerColor: inactiveDividerColor, + activeDividerColor: activeDividerColor, + thumbColor: thumbColor, + thumbStrokeColor: thumbStrokeColor, + overlappingThumbStrokeColor: overlappingThumbStrokeColor, + activeDividerStrokeColor: activeDividerStrokeColor, + inactiveDividerStrokeColor: inactiveDividerStrokeColor, + overlayColor: overlayColor, + activeTickColor: activeTickColor, + inactiveTickColor: inactiveTickColor, + disabledActiveTickColor: disabledActiveTickColor, + disabledInactiveTickColor: disabledInactiveTickColor, + activeMinorTickColor: activeMinorTickColor, + inactiveMinorTickColor: inactiveMinorTickColor, + disabledActiveMinorTickColor: disabledActiveMinorTickColor, + disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, + disabledActiveTrackColor: disabledActiveTrackColor, + disabledInactiveTrackColor: disabledInactiveTrackColor, + disabledActiveDividerColor: disabledActiveDividerColor, + disabledInactiveDividerColor: disabledInactiveDividerColor, + disabledThumbColor: disabledThumbColor, + activeRegionColor: activeRegionColor, + inactiveRegionColor: inactiveRegionColor, + tooltipBackgroundColor: tooltipBackgroundColor, + overlappingTooltipStrokeColor: overlappingTooltipStrokeColor, + overlayRadius: overlayRadius, + thumbRadius: thumbRadius, + activeDividerRadius: activeDividerRadius, + inactiveDividerRadius: inactiveDividerRadius, + thumbStrokeWidth: thumbStrokeWidth, + activeDividerStrokeWidth: activeDividerStrokeWidth, + inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, + trackCornerRadius: trackCornerRadius, + ); } /// Specifies the color for the active region of the @@ -538,89 +542,187 @@ class SfRangeSelectorThemeData extends SfRangeSliderThemeData { /// /// The arguments must not be null. static SfRangeSelectorThemeData? lerp( - SfRangeSelectorThemeData? a, SfRangeSelectorThemeData? b, double t) { + SfRangeSelectorThemeData? a, + SfRangeSelectorThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfRangeSelectorThemeData( - activeTrackHeight: - lerpDouble(a!.activeTrackHeight, b!.activeTrackHeight, t)!, - inactiveTrackHeight: - lerpDouble(a.inactiveTrackHeight, b.inactiveTrackHeight, t)!, - tickSize: Size.lerp(a.tickSize, b.tickSize, t), - minorTickSize: Size.lerp(a.minorTickSize, b.minorTickSize, t), - tickOffset: Offset.lerp(a.tickOffset, b.tickOffset, t), - labelOffset: Offset.lerp(a.labelOffset, b.labelOffset, t), - inactiveLabelStyle: - TextStyle.lerp(a.inactiveLabelStyle, b.inactiveLabelStyle, t), - activeLabelStyle: - TextStyle.lerp(a.activeLabelStyle, b.activeLabelStyle, t), - tooltipTextStyle: - TextStyle.lerp(a.tooltipTextStyle, b.tooltipTextStyle, t), - inactiveTrackColor: - Color.lerp(a.inactiveTrackColor, b.inactiveTrackColor, t), - activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), - thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), - thumbStrokeColor: Color.lerp(a.thumbStrokeColor, b.thumbStrokeColor, t), - overlappingThumbStrokeColor: Color.lerp( - a.overlappingThumbStrokeColor, b.overlappingThumbStrokeColor, t), - activeDividerStrokeColor: Color.lerp( - a.activeDividerStrokeColor, b.activeDividerStrokeColor, t), - inactiveDividerStrokeColor: Color.lerp( - a.inactiveDividerStrokeColor, b.inactiveDividerStrokeColor, t), - activeTickColor: Color.lerp(a.activeTickColor, b.activeTickColor, t), - inactiveTickColor: - Color.lerp(a.inactiveTickColor, b.inactiveTickColor, t), - disabledActiveTickColor: - Color.lerp(a.disabledActiveTickColor, b.disabledActiveTickColor, t), - disabledInactiveTickColor: Color.lerp( - a.disabledInactiveTickColor, b.disabledInactiveTickColor, t), - activeMinorTickColor: - Color.lerp(a.activeMinorTickColor, b.activeMinorTickColor, t), - inactiveMinorTickColor: - Color.lerp(a.inactiveMinorTickColor, b.inactiveMinorTickColor, t), - disabledActiveMinorTickColor: Color.lerp( - a.disabledActiveMinorTickColor, b.disabledActiveMinorTickColor, t), - disabledInactiveMinorTickColor: Color.lerp( - a.disabledInactiveMinorTickColor, - b.disabledInactiveMinorTickColor, - t), - overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), - inactiveDividerColor: - Color.lerp(a.inactiveDividerColor, b.inactiveDividerColor, t), - activeDividerColor: - Color.lerp(a.activeDividerColor, b.activeDividerColor, t), - disabledActiveTrackColor: Color.lerp( - a.disabledActiveTrackColor, b.disabledActiveTrackColor, t), - disabledInactiveTrackColor: Color.lerp( - a.disabledInactiveTrackColor, b.disabledInactiveTrackColor, t), - disabledActiveDividerColor: Color.lerp( - a.disabledActiveDividerColor, b.disabledActiveDividerColor, t), - disabledInactiveDividerColor: Color.lerp( - a.disabledInactiveDividerColor, b.disabledInactiveDividerColor, t), - disabledThumbColor: - Color.lerp(a.disabledThumbColor, b.disabledThumbColor, t), - activeRegionColor: - Color.lerp(a.activeRegionColor, b.activeRegionColor, t), - inactiveRegionColor: - Color.lerp(a.inactiveRegionColor, b.inactiveRegionColor, t), - tooltipBackgroundColor: - Color.lerp(a.tooltipBackgroundColor, b.tooltipBackgroundColor, t), - // ignore: lines_longer_than_80_chars - overlappingTooltipStrokeColor: Color.lerp(a.overlappingTooltipStrokeColor, b.overlappingTooltipStrokeColor, t), - // ignore: lines_longer_than_80_chars - trackCornerRadius: lerpDouble(a.trackCornerRadius, b.trackCornerRadius, t), - overlayRadius: lerpDouble(a.overlayRadius, b.overlayRadius, t)!, - thumbRadius: lerpDouble(a.thumbRadius, b.thumbRadius, t)!, - // ignore: lines_longer_than_80_chars - activeDividerRadius: lerpDouble(a.activeDividerRadius, b.activeDividerRadius, t), - // ignore: lines_longer_than_80_chars - inactiveDividerRadius: lerpDouble(a.inactiveDividerRadius, b.inactiveDividerRadius, t), - thumbStrokeWidth: lerpDouble(a.thumbStrokeWidth, b.thumbStrokeWidth, t), - // ignore: lines_longer_than_80_chars - activeDividerStrokeWidth: lerpDouble(a.activeDividerStrokeWidth, b.activeDividerStrokeWidth, t), - // ignore: lines_longer_than_80_chars - inactiveDividerStrokeWidth: lerpDouble(a.inactiveDividerStrokeWidth, b.inactiveDividerStrokeWidth, t)); + activeTrackHeight: + lerpDouble(a!.activeTrackHeight, b!.activeTrackHeight, t)!, + inactiveTrackHeight: + lerpDouble(a.inactiveTrackHeight, b.inactiveTrackHeight, t)!, + tickSize: Size.lerp(a.tickSize, b.tickSize, t), + minorTickSize: Size.lerp(a.minorTickSize, b.minorTickSize, t), + tickOffset: Offset.lerp(a.tickOffset, b.tickOffset, t), + labelOffset: Offset.lerp(a.labelOffset, b.labelOffset, t), + inactiveLabelStyle: TextStyle.lerp( + a.inactiveLabelStyle, + b.inactiveLabelStyle, + t, + ), + activeLabelStyle: TextStyle.lerp( + a.activeLabelStyle, + b.activeLabelStyle, + t, + ), + tooltipTextStyle: TextStyle.lerp( + a.tooltipTextStyle, + b.tooltipTextStyle, + t, + ), + inactiveTrackColor: Color.lerp( + a.inactiveTrackColor, + b.inactiveTrackColor, + t, + ), + activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), + thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), + thumbStrokeColor: Color.lerp(a.thumbStrokeColor, b.thumbStrokeColor, t), + overlappingThumbStrokeColor: Color.lerp( + a.overlappingThumbStrokeColor, + b.overlappingThumbStrokeColor, + t, + ), + activeDividerStrokeColor: Color.lerp( + a.activeDividerStrokeColor, + b.activeDividerStrokeColor, + t, + ), + inactiveDividerStrokeColor: Color.lerp( + a.inactiveDividerStrokeColor, + b.inactiveDividerStrokeColor, + t, + ), + activeTickColor: Color.lerp(a.activeTickColor, b.activeTickColor, t), + inactiveTickColor: Color.lerp( + a.inactiveTickColor, + b.inactiveTickColor, + t, + ), + disabledActiveTickColor: Color.lerp( + a.disabledActiveTickColor, + b.disabledActiveTickColor, + t, + ), + disabledInactiveTickColor: Color.lerp( + a.disabledInactiveTickColor, + b.disabledInactiveTickColor, + t, + ), + activeMinorTickColor: Color.lerp( + a.activeMinorTickColor, + b.activeMinorTickColor, + t, + ), + inactiveMinorTickColor: Color.lerp( + a.inactiveMinorTickColor, + b.inactiveMinorTickColor, + t, + ), + disabledActiveMinorTickColor: Color.lerp( + a.disabledActiveMinorTickColor, + b.disabledActiveMinorTickColor, + t, + ), + disabledInactiveMinorTickColor: Color.lerp( + a.disabledInactiveMinorTickColor, + b.disabledInactiveMinorTickColor, + t, + ), + overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), + inactiveDividerColor: Color.lerp( + a.inactiveDividerColor, + b.inactiveDividerColor, + t, + ), + activeDividerColor: Color.lerp( + a.activeDividerColor, + b.activeDividerColor, + t, + ), + disabledActiveTrackColor: Color.lerp( + a.disabledActiveTrackColor, + b.disabledActiveTrackColor, + t, + ), + disabledInactiveTrackColor: Color.lerp( + a.disabledInactiveTrackColor, + b.disabledInactiveTrackColor, + t, + ), + disabledActiveDividerColor: Color.lerp( + a.disabledActiveDividerColor, + b.disabledActiveDividerColor, + t, + ), + disabledInactiveDividerColor: Color.lerp( + a.disabledInactiveDividerColor, + b.disabledInactiveDividerColor, + t, + ), + disabledThumbColor: Color.lerp( + a.disabledThumbColor, + b.disabledThumbColor, + t, + ), + activeRegionColor: Color.lerp( + a.activeRegionColor, + b.activeRegionColor, + t, + ), + inactiveRegionColor: Color.lerp( + a.inactiveRegionColor, + b.inactiveRegionColor, + t, + ), + tooltipBackgroundColor: Color.lerp( + a.tooltipBackgroundColor, + b.tooltipBackgroundColor, + t, + ), + // ignore: lines_longer_than_80_chars + overlappingTooltipStrokeColor: Color.lerp( + a.overlappingTooltipStrokeColor, + b.overlappingTooltipStrokeColor, + t, + ), + // ignore: lines_longer_than_80_chars + trackCornerRadius: lerpDouble( + a.trackCornerRadius, + b.trackCornerRadius, + t, + ), + overlayRadius: lerpDouble(a.overlayRadius, b.overlayRadius, t)!, + thumbRadius: lerpDouble(a.thumbRadius, b.thumbRadius, t)!, + // ignore: lines_longer_than_80_chars + activeDividerRadius: lerpDouble( + a.activeDividerRadius, + b.activeDividerRadius, + t, + ), + // ignore: lines_longer_than_80_chars + inactiveDividerRadius: lerpDouble( + a.inactiveDividerRadius, + b.inactiveDividerRadius, + t, + ), + thumbStrokeWidth: lerpDouble(a.thumbStrokeWidth, b.thumbStrokeWidth, t), + // ignore: lines_longer_than_80_chars + activeDividerStrokeWidth: lerpDouble( + a.activeDividerStrokeWidth, + b.activeDividerStrokeWidth, + t, + ), + // ignore: lines_longer_than_80_chars + inactiveDividerStrokeWidth: lerpDouble( + a.inactiveDividerStrokeWidth, + b.inactiveDividerStrokeWidth, + t, + ), + ); } @override @@ -734,113 +836,313 @@ class SfRangeSelectorThemeData extends SfRangeSliderThemeData { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfRangeSelectorThemeData defaultData = SfRangeSelectorThemeData(); - properties.add(DoubleProperty('activeTrackHeight', activeTrackHeight, - defaultValue: defaultData.activeTrackHeight)); - properties.add(DoubleProperty('inactiveTrackHeight', inactiveTrackHeight, - defaultValue: defaultData.inactiveTrackHeight)); - properties.add(DiagnosticsProperty('tickSize', tickSize, - defaultValue: defaultData.tickSize)); - properties.add(DiagnosticsProperty('minorTickSize', minorTickSize, - defaultValue: defaultData.minorTickSize)); - properties.add(DiagnosticsProperty('tickOffset', tickOffset, - defaultValue: defaultData.tickOffset)); - properties.add(DiagnosticsProperty('labelOffset', labelOffset, - defaultValue: defaultData.labelOffset)); - properties.add(DiagnosticsProperty( - 'inactiveLabelStyle', inactiveLabelStyle, - defaultValue: defaultData.inactiveLabelStyle)); - properties.add(DiagnosticsProperty( - 'activeLabelStyle', activeLabelStyle, - defaultValue: defaultData.activeLabelStyle)); - properties.add(DiagnosticsProperty( - 'tooltipTextStyle', tooltipTextStyle, - defaultValue: defaultData.tooltipTextStyle)); - properties.add(ColorProperty('inactiveTrackColor', inactiveTrackColor, - defaultValue: defaultData.inactiveTrackColor)); - properties.add(ColorProperty('activeTrackColor', activeTrackColor, - defaultValue: defaultData.activeTrackColor)); - properties.add(ColorProperty('thumbColor', thumbColor, - defaultValue: defaultData.thumbColor)); - properties.add(ColorProperty('thumbStrokeColor', thumbStrokeColor, - defaultValue: defaultData.thumbStrokeColor)); - properties.add(ColorProperty( - 'overlappingThumbStrokeColor', overlappingThumbStrokeColor, - defaultValue: defaultData.overlappingThumbStrokeColor)); - properties.add(ColorProperty( - 'activeDividerStrokeColor', activeDividerStrokeColor, - defaultValue: defaultData.activeDividerStrokeColor)); - properties.add(ColorProperty( - 'inactiveDividerStrokeColor', inactiveDividerStrokeColor, - defaultValue: defaultData.inactiveDividerStrokeColor)); - properties.add(ColorProperty('activeTickColor', activeTickColor, - defaultValue: defaultData.activeTickColor)); - properties.add(ColorProperty('inactiveTickColor', inactiveTickColor, - defaultValue: defaultData.inactiveTickColor)); - properties.add(ColorProperty( - 'disabledActiveTickColor', disabledActiveTickColor, - defaultValue: defaultData.disabledActiveTickColor)); - properties.add(ColorProperty( - 'disabledInactiveTickColor', disabledInactiveTickColor, - defaultValue: defaultData.disabledInactiveTickColor)); - properties.add(ColorProperty('activeMinorTickColor', activeMinorTickColor, - defaultValue: defaultData.activeMinorTickColor)); - properties.add(ColorProperty( - 'inactiveMinorTickColor', inactiveMinorTickColor, - defaultValue: defaultData.inactiveMinorTickColor)); - properties.add(ColorProperty( - 'disabledActiveMinorTickColor', disabledActiveMinorTickColor, - defaultValue: defaultData.disabledActiveMinorTickColor)); - properties.add(ColorProperty( - 'disabledInactiveMinorTickColor', disabledInactiveMinorTickColor, - defaultValue: defaultData.disabledInactiveMinorTickColor)); - properties.add(ColorProperty('overlayColor', overlayColor, - defaultValue: defaultData.overlayColor)); - properties.add(ColorProperty('inactiveDividerColor', inactiveDividerColor, - defaultValue: defaultData.inactiveDividerColor)); - properties.add(ColorProperty('activeDividerColor', activeDividerColor, - defaultValue: defaultData.activeDividerColor)); - properties.add(ColorProperty( - 'disabledActiveTrackColor', disabledActiveTrackColor, - defaultValue: defaultData.disabledActiveTrackColor)); - properties.add(ColorProperty( - 'disabledInactiveTrackColor', disabledInactiveTrackColor, - defaultValue: defaultData.disabledInactiveTrackColor)); - properties.add(ColorProperty( - 'disabledActiveDividerColor', disabledActiveDividerColor, - defaultValue: defaultData.disabledActiveDividerColor)); - properties.add(ColorProperty( - 'disabledInactiveDividerColor', disabledInactiveDividerColor, - defaultValue: defaultData.disabledInactiveDividerColor)); - properties.add(ColorProperty('disabledThumbColor', disabledThumbColor, - defaultValue: defaultData.disabledThumbColor)); - properties.add(ColorProperty('activeRegionColor', activeRegionColor, - defaultValue: defaultData.activeRegionColor)); - properties.add(ColorProperty('inactiveRegionColor', inactiveRegionColor, - defaultValue: defaultData.inactiveRegionColor)); - properties.add(ColorProperty( - 'tooltipBackgroundColor', tooltipBackgroundColor, - defaultValue: defaultData.tooltipBackgroundColor)); - properties.add(ColorProperty( - 'overlappingTooltipStrokeColor', overlappingTooltipStrokeColor, - defaultValue: defaultData.overlappingTooltipStrokeColor)); - properties.add(DoubleProperty('trackCornerRadius', trackCornerRadius, - defaultValue: defaultData.trackCornerRadius)); - properties.add(DoubleProperty('overlayRadius', overlayRadius, - defaultValue: defaultData.overlayRadius)); - properties.add(DoubleProperty('thumbRadius', thumbRadius, - defaultValue: defaultData.thumbRadius)); - properties.add(DoubleProperty('activeDividerRadius', activeDividerRadius, - defaultValue: defaultData.activeDividerRadius)); - properties.add(DoubleProperty( - 'inactiveDividerRadius', inactiveDividerRadius, - defaultValue: defaultData.inactiveDividerRadius)); - properties.add(DoubleProperty('thumbStrokeWidth', thumbStrokeWidth, - defaultValue: defaultData.thumbStrokeWidth)); - properties.add(DoubleProperty( - 'activeDividerStrokeWidth', activeDividerStrokeWidth, - defaultValue: defaultData.activeDividerStrokeWidth)); - properties.add(DoubleProperty( - 'inactiveDividerStrokeWidth', inactiveDividerStrokeWidth, - defaultValue: defaultData.inactiveDividerStrokeWidth)); + properties.add( + DoubleProperty( + 'activeTrackHeight', + activeTrackHeight, + defaultValue: defaultData.activeTrackHeight, + ), + ); + properties.add( + DoubleProperty( + 'inactiveTrackHeight', + inactiveTrackHeight, + defaultValue: defaultData.inactiveTrackHeight, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickSize', + tickSize, + defaultValue: defaultData.tickSize, + ), + ); + properties.add( + DiagnosticsProperty( + 'minorTickSize', + minorTickSize, + defaultValue: defaultData.minorTickSize, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickOffset', + tickOffset, + defaultValue: defaultData.tickOffset, + ), + ); + properties.add( + DiagnosticsProperty( + 'labelOffset', + labelOffset, + defaultValue: defaultData.labelOffset, + ), + ); + properties.add( + DiagnosticsProperty( + 'inactiveLabelStyle', + inactiveLabelStyle, + defaultValue: defaultData.inactiveLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'activeLabelStyle', + activeLabelStyle, + defaultValue: defaultData.activeLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'tooltipTextStyle', + tooltipTextStyle, + defaultValue: defaultData.tooltipTextStyle, + ), + ); + properties.add( + ColorProperty( + 'inactiveTrackColor', + inactiveTrackColor, + defaultValue: defaultData.inactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'activeTrackColor', + activeTrackColor, + defaultValue: defaultData.activeTrackColor, + ), + ); + properties.add( + ColorProperty( + 'thumbColor', + thumbColor, + defaultValue: defaultData.thumbColor, + ), + ); + properties.add( + ColorProperty( + 'thumbStrokeColor', + thumbStrokeColor, + defaultValue: defaultData.thumbStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'overlappingThumbStrokeColor', + overlappingThumbStrokeColor, + defaultValue: defaultData.overlappingThumbStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'activeDividerStrokeColor', + activeDividerStrokeColor, + defaultValue: defaultData.activeDividerStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveDividerStrokeColor', + inactiveDividerStrokeColor, + defaultValue: defaultData.inactiveDividerStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'activeTickColor', + activeTickColor, + defaultValue: defaultData.activeTickColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveTickColor', + inactiveTickColor, + defaultValue: defaultData.inactiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTickColor', + disabledActiveTickColor, + defaultValue: defaultData.disabledActiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTickColor', + disabledInactiveTickColor, + defaultValue: defaultData.disabledInactiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'activeMinorTickColor', + activeMinorTickColor, + defaultValue: defaultData.activeMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveMinorTickColor', + inactiveMinorTickColor, + defaultValue: defaultData.inactiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveMinorTickColor', + disabledActiveMinorTickColor, + defaultValue: defaultData.disabledActiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveMinorTickColor', + disabledInactiveMinorTickColor, + defaultValue: defaultData.disabledInactiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'overlayColor', + overlayColor, + defaultValue: defaultData.overlayColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveDividerColor', + inactiveDividerColor, + defaultValue: defaultData.inactiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'activeDividerColor', + activeDividerColor, + defaultValue: defaultData.activeDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTrackColor', + disabledActiveTrackColor, + defaultValue: defaultData.disabledActiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTrackColor', + disabledInactiveTrackColor, + defaultValue: defaultData.disabledInactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveDividerColor', + disabledActiveDividerColor, + defaultValue: defaultData.disabledActiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveDividerColor', + disabledInactiveDividerColor, + defaultValue: defaultData.disabledInactiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledThumbColor', + disabledThumbColor, + defaultValue: defaultData.disabledThumbColor, + ), + ); + properties.add( + ColorProperty( + 'activeRegionColor', + activeRegionColor, + defaultValue: defaultData.activeRegionColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveRegionColor', + inactiveRegionColor, + defaultValue: defaultData.inactiveRegionColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipBackgroundColor', + tooltipBackgroundColor, + defaultValue: defaultData.tooltipBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'overlappingTooltipStrokeColor', + overlappingTooltipStrokeColor, + defaultValue: defaultData.overlappingTooltipStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'trackCornerRadius', + trackCornerRadius, + defaultValue: defaultData.trackCornerRadius, + ), + ); + properties.add( + DoubleProperty( + 'overlayRadius', + overlayRadius, + defaultValue: defaultData.overlayRadius, + ), + ); + properties.add( + DoubleProperty( + 'thumbRadius', + thumbRadius, + defaultValue: defaultData.thumbRadius, + ), + ); + properties.add( + DoubleProperty( + 'activeDividerRadius', + activeDividerRadius, + defaultValue: defaultData.activeDividerRadius, + ), + ); + properties.add( + DoubleProperty( + 'inactiveDividerRadius', + inactiveDividerRadius, + defaultValue: defaultData.inactiveDividerRadius, + ), + ); + properties.add( + DoubleProperty( + 'thumbStrokeWidth', + thumbStrokeWidth, + defaultValue: defaultData.thumbStrokeWidth, + ), + ); + properties.add( + DoubleProperty( + 'activeDividerStrokeWidth', + activeDividerStrokeWidth, + defaultValue: defaultData.activeDividerStrokeWidth, + ), + ); + properties.add( + DoubleProperty( + 'inactiveDividerStrokeWidth', + inactiveDividerStrokeWidth, + defaultValue: defaultData.inactiveDividerStrokeWidth, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/range_slider_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/range_slider_theme.dart index 360a3da79..a459d6d22 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/range_slider_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/range_slider_theme.dart @@ -9,7 +9,7 @@ class SfRangeSliderTheme extends InheritedTheme { /// /// The [data] and [child] arguments must not be null. const SfRangeSliderTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for /// descendant range slider widgets. @@ -83,90 +83,91 @@ class SfRangeSliderTheme extends InheritedTheme { /// for customizing the visual appearance of the range slider. class SfRangeSliderThemeData extends SfSliderThemeData { /// Creating an argument constructor of SfRangeSliderThemeData class. - const SfRangeSliderThemeData( - {double activeTrackHeight = 6.0, - double inactiveTrackHeight = 4.0, - Size? tickSize, - Size? minorTickSize, - Offset? tickOffset, - Offset? labelOffset, - TextStyle? inactiveLabelStyle, - TextStyle? activeLabelStyle, - TextStyle? tooltipTextStyle, - Color? inactiveTrackColor, - Color? activeTrackColor, - Color? thumbColor, - Color? activeTickColor, - Color? inactiveTickColor, - Color? disabledActiveTickColor, - Color? disabledInactiveTickColor, - Color? activeMinorTickColor, - Color? inactiveMinorTickColor, - Color? disabledActiveMinorTickColor, - Color? disabledInactiveMinorTickColor, - Color? overlayColor, - Color? inactiveDividerColor, - Color? activeDividerColor, - Color? disabledActiveTrackColor, - Color? disabledInactiveTrackColor, - Color? disabledActiveDividerColor, - Color? disabledInactiveDividerColor, - Color? disabledThumbColor, - Color? tooltipBackgroundColor, - this.overlappingTooltipStrokeColor, - Color? thumbStrokeColor, - this.overlappingThumbStrokeColor, - Color? activeDividerStrokeColor, - Color? inactiveDividerStrokeColor, - double? trackCornerRadius, - double overlayRadius = 24.0, - double thumbRadius = 10.0, - double? activeDividerRadius, - double? inactiveDividerRadius, - double? thumbStrokeWidth, - double? activeDividerStrokeWidth, - double? inactiveDividerStrokeWidth}) - : super( - activeTrackHeight: activeTrackHeight, - inactiveTrackHeight: inactiveTrackHeight, - tickSize: tickSize, - minorTickSize: minorTickSize, - tickOffset: tickOffset, - labelOffset: labelOffset, - inactiveLabelStyle: inactiveLabelStyle, - activeLabelStyle: activeLabelStyle, - tooltipTextStyle: tooltipTextStyle, - inactiveTrackColor: inactiveTrackColor, - activeTrackColor: activeTrackColor, - inactiveDividerColor: inactiveDividerColor, - activeDividerColor: activeDividerColor, - thumbColor: thumbColor, - thumbStrokeColor: thumbStrokeColor, - activeDividerStrokeColor: activeDividerStrokeColor, - inactiveDividerStrokeColor: inactiveDividerStrokeColor, - overlayColor: overlayColor, - activeTickColor: activeTickColor, - inactiveTickColor: inactiveTickColor, - disabledActiveTickColor: disabledActiveTickColor, - disabledInactiveTickColor: disabledInactiveTickColor, - activeMinorTickColor: activeMinorTickColor, - inactiveMinorTickColor: inactiveMinorTickColor, - disabledActiveMinorTickColor: disabledActiveMinorTickColor, - disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, - disabledActiveTrackColor: disabledActiveTrackColor, - disabledInactiveTrackColor: disabledInactiveTrackColor, - disabledActiveDividerColor: disabledActiveDividerColor, - disabledInactiveDividerColor: disabledInactiveDividerColor, - disabledThumbColor: disabledThumbColor, - tooltipBackgroundColor: tooltipBackgroundColor, - overlayRadius: overlayRadius, - thumbRadius: thumbRadius, - activeDividerRadius: activeDividerRadius, - inactiveDividerRadius: inactiveDividerRadius, - thumbStrokeWidth: thumbStrokeWidth, - activeDividerStrokeWidth: activeDividerStrokeWidth, - inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, - trackCornerRadius: trackCornerRadius); + const SfRangeSliderThemeData({ + double activeTrackHeight = 6.0, + double inactiveTrackHeight = 4.0, + Size? tickSize, + Size? minorTickSize, + Offset? tickOffset, + Offset? labelOffset, + TextStyle? inactiveLabelStyle, + TextStyle? activeLabelStyle, + TextStyle? tooltipTextStyle, + Color? inactiveTrackColor, + Color? activeTrackColor, + Color? thumbColor, + Color? activeTickColor, + Color? inactiveTickColor, + Color? disabledActiveTickColor, + Color? disabledInactiveTickColor, + Color? activeMinorTickColor, + Color? inactiveMinorTickColor, + Color? disabledActiveMinorTickColor, + Color? disabledInactiveMinorTickColor, + Color? overlayColor, + Color? inactiveDividerColor, + Color? activeDividerColor, + Color? disabledActiveTrackColor, + Color? disabledInactiveTrackColor, + Color? disabledActiveDividerColor, + Color? disabledInactiveDividerColor, + Color? disabledThumbColor, + Color? tooltipBackgroundColor, + this.overlappingTooltipStrokeColor, + Color? thumbStrokeColor, + this.overlappingThumbStrokeColor, + Color? activeDividerStrokeColor, + Color? inactiveDividerStrokeColor, + double? trackCornerRadius, + double overlayRadius = 24.0, + double thumbRadius = 10.0, + double? activeDividerRadius, + double? inactiveDividerRadius, + double? thumbStrokeWidth, + double? activeDividerStrokeWidth, + double? inactiveDividerStrokeWidth, + }) : super( + activeTrackHeight: activeTrackHeight, + inactiveTrackHeight: inactiveTrackHeight, + tickSize: tickSize, + minorTickSize: minorTickSize, + tickOffset: tickOffset, + labelOffset: labelOffset, + inactiveLabelStyle: inactiveLabelStyle, + activeLabelStyle: activeLabelStyle, + tooltipTextStyle: tooltipTextStyle, + inactiveTrackColor: inactiveTrackColor, + activeTrackColor: activeTrackColor, + inactiveDividerColor: inactiveDividerColor, + activeDividerColor: activeDividerColor, + thumbColor: thumbColor, + thumbStrokeColor: thumbStrokeColor, + activeDividerStrokeColor: activeDividerStrokeColor, + inactiveDividerStrokeColor: inactiveDividerStrokeColor, + overlayColor: overlayColor, + activeTickColor: activeTickColor, + inactiveTickColor: inactiveTickColor, + disabledActiveTickColor: disabledActiveTickColor, + disabledInactiveTickColor: disabledInactiveTickColor, + activeMinorTickColor: activeMinorTickColor, + inactiveMinorTickColor: inactiveMinorTickColor, + disabledActiveMinorTickColor: disabledActiveMinorTickColor, + disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, + disabledActiveTrackColor: disabledActiveTrackColor, + disabledInactiveTrackColor: disabledInactiveTrackColor, + disabledActiveDividerColor: disabledActiveDividerColor, + disabledInactiveDividerColor: disabledInactiveDividerColor, + disabledThumbColor: disabledThumbColor, + tooltipBackgroundColor: tooltipBackgroundColor, + overlayRadius: overlayRadius, + thumbRadius: thumbRadius, + activeDividerRadius: activeDividerRadius, + inactiveDividerRadius: inactiveDividerRadius, + thumbStrokeWidth: thumbStrokeWidth, + activeDividerStrokeWidth: activeDividerStrokeWidth, + inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, + trackCornerRadius: trackCornerRadius, + ); /// Returns a new instance of [SfRangeSliderThemeData] for the given values. factory SfRangeSliderThemeData.raw({ @@ -221,48 +222,49 @@ class SfRangeSliderThemeData extends SfSliderThemeData { thumbRadius ??= 10.0; return SfRangeSliderThemeData( - activeTrackHeight: activeTrackHeight, - inactiveTrackHeight: inactiveTrackHeight, - tickSize: tickSize, - minorTickSize: minorTickSize, - tickOffset: tickOffset, - labelOffset: labelOffset, - inactiveLabelStyle: inactiveLabelStyle, - activeLabelStyle: activeLabelStyle, - tooltipTextStyle: tooltipTextStyle, - inactiveTrackColor: inactiveTrackColor, - activeTrackColor: activeTrackColor, - inactiveDividerColor: inactiveDividerColor, - activeDividerColor: activeDividerColor, - thumbColor: thumbColor, - thumbStrokeColor: thumbStrokeColor, - overlappingThumbStrokeColor: overlappingThumbStrokeColor, - activeDividerStrokeColor: activeDividerStrokeColor, - inactiveDividerStrokeColor: inactiveDividerStrokeColor, - overlayColor: overlayColor, - activeTickColor: activeTickColor, - inactiveTickColor: inactiveTickColor, - disabledActiveTickColor: disabledActiveTickColor, - disabledInactiveTickColor: disabledInactiveTickColor, - activeMinorTickColor: activeMinorTickColor, - inactiveMinorTickColor: inactiveMinorTickColor, - disabledActiveMinorTickColor: disabledActiveMinorTickColor, - disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, - disabledActiveTrackColor: disabledActiveTrackColor, - disabledInactiveTrackColor: disabledInactiveTrackColor, - disabledActiveDividerColor: disabledActiveDividerColor, - disabledInactiveDividerColor: disabledInactiveDividerColor, - disabledThumbColor: disabledThumbColor, - tooltipBackgroundColor: tooltipBackgroundColor, - overlappingTooltipStrokeColor: overlappingTooltipStrokeColor, - overlayRadius: overlayRadius, - thumbRadius: thumbRadius, - activeDividerRadius: activeDividerRadius, - inactiveDividerRadius: inactiveDividerRadius, - thumbStrokeWidth: thumbStrokeWidth, - activeDividerStrokeWidth: activeDividerStrokeWidth, - inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, - trackCornerRadius: trackCornerRadius); + activeTrackHeight: activeTrackHeight, + inactiveTrackHeight: inactiveTrackHeight, + tickSize: tickSize, + minorTickSize: minorTickSize, + tickOffset: tickOffset, + labelOffset: labelOffset, + inactiveLabelStyle: inactiveLabelStyle, + activeLabelStyle: activeLabelStyle, + tooltipTextStyle: tooltipTextStyle, + inactiveTrackColor: inactiveTrackColor, + activeTrackColor: activeTrackColor, + inactiveDividerColor: inactiveDividerColor, + activeDividerColor: activeDividerColor, + thumbColor: thumbColor, + thumbStrokeColor: thumbStrokeColor, + overlappingThumbStrokeColor: overlappingThumbStrokeColor, + activeDividerStrokeColor: activeDividerStrokeColor, + inactiveDividerStrokeColor: inactiveDividerStrokeColor, + overlayColor: overlayColor, + activeTickColor: activeTickColor, + inactiveTickColor: inactiveTickColor, + disabledActiveTickColor: disabledActiveTickColor, + disabledInactiveTickColor: disabledInactiveTickColor, + activeMinorTickColor: activeMinorTickColor, + inactiveMinorTickColor: inactiveMinorTickColor, + disabledActiveMinorTickColor: disabledActiveMinorTickColor, + disabledInactiveMinorTickColor: disabledInactiveMinorTickColor, + disabledActiveTrackColor: disabledActiveTrackColor, + disabledInactiveTrackColor: disabledInactiveTrackColor, + disabledActiveDividerColor: disabledActiveDividerColor, + disabledInactiveDividerColor: disabledInactiveDividerColor, + disabledThumbColor: disabledThumbColor, + tooltipBackgroundColor: tooltipBackgroundColor, + overlappingTooltipStrokeColor: overlappingTooltipStrokeColor, + overlayRadius: overlayRadius, + thumbRadius: thumbRadius, + activeDividerRadius: activeDividerRadius, + inactiveDividerRadius: inactiveDividerRadius, + thumbStrokeWidth: thumbStrokeWidth, + activeDividerStrokeWidth: activeDividerStrokeWidth, + inactiveDividerStrokeWidth: inactiveDividerStrokeWidth, + trackCornerRadius: trackCornerRadius, + ); } /// Create a [SfRangeSliderThemeData] given a set of exact values. @@ -452,90 +454,177 @@ class SfRangeSliderThemeData extends SfSliderThemeData { /// /// The arguments must not be null. static SfRangeSliderThemeData? lerp( - SfRangeSliderThemeData? a, SfRangeSliderThemeData? b, double t) { + SfRangeSliderThemeData? a, + SfRangeSliderThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfRangeSliderThemeData( - activeTrackHeight: - lerpDouble(a!.activeTrackHeight, b!.activeTrackHeight, t)!, - inactiveTrackHeight: - lerpDouble(a.inactiveTrackHeight, b.inactiveTrackHeight, t)!, - tickSize: Size.lerp(a.tickSize, b.tickSize, t), - minorTickSize: Size.lerp(a.minorTickSize, b.minorTickSize, t), - tickOffset: Offset.lerp(a.tickOffset, b.tickOffset, t), - labelOffset: Offset.lerp(a.labelOffset, b.labelOffset, t), - inactiveLabelStyle: - TextStyle.lerp(a.inactiveLabelStyle, b.inactiveLabelStyle, t), - activeLabelStyle: - TextStyle.lerp(a.activeLabelStyle, b.activeLabelStyle, t), - tooltipTextStyle: - TextStyle.lerp(a.tooltipTextStyle, b.tooltipTextStyle, t), - inactiveTrackColor: - Color.lerp(a.inactiveTrackColor, b.inactiveTrackColor, t), - activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), - thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), - thumbStrokeColor: Color.lerp(a.thumbStrokeColor, b.thumbStrokeColor, t), - overlappingThumbStrokeColor: Color.lerp( - a.overlappingThumbStrokeColor, b.overlappingThumbStrokeColor, t), - activeDividerStrokeColor: Color.lerp( - a.activeDividerStrokeColor, b.activeDividerStrokeColor, t), - inactiveDividerStrokeColor: Color.lerp( - a.inactiveDividerStrokeColor, b.inactiveDividerStrokeColor, t), - activeTickColor: Color.lerp(a.activeTickColor, b.activeTickColor, t), - inactiveTickColor: - Color.lerp(a.inactiveTickColor, b.inactiveTickColor, t), - disabledActiveTickColor: - Color.lerp(a.disabledActiveTickColor, b.disabledActiveTickColor, t), - disabledInactiveTickColor: Color.lerp( - a.disabledInactiveTickColor, b.disabledInactiveTickColor, t), - activeMinorTickColor: - Color.lerp(a.activeMinorTickColor, b.activeMinorTickColor, t), - inactiveMinorTickColor: - Color.lerp(a.inactiveMinorTickColor, b.inactiveMinorTickColor, t), - disabledActiveMinorTickColor: Color.lerp( - a.disabledActiveMinorTickColor, b.disabledActiveMinorTickColor, t), - disabledInactiveMinorTickColor: Color.lerp( - a.disabledInactiveMinorTickColor, - b.disabledInactiveMinorTickColor, - t), - overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), - inactiveDividerColor: - Color.lerp(a.inactiveDividerColor, b.inactiveDividerColor, t), - activeDividerColor: - Color.lerp(a.activeDividerColor, b.activeDividerColor, t), - disabledActiveTrackColor: Color.lerp( - a.disabledActiveTrackColor, b.disabledActiveTrackColor, t), - disabledInactiveTrackColor: Color.lerp( - a.disabledInactiveTrackColor, b.disabledInactiveTrackColor, t), - disabledActiveDividerColor: Color.lerp( - a.disabledActiveDividerColor, b.disabledActiveDividerColor, t), - disabledInactiveDividerColor: Color.lerp( - a.disabledInactiveDividerColor, b.disabledInactiveDividerColor, t), - disabledThumbColor: - Color.lerp(a.disabledThumbColor, b.disabledThumbColor, t), - tooltipBackgroundColor: - Color.lerp(a.tooltipBackgroundColor, b.tooltipBackgroundColor, t), - overlappingTooltipStrokeColor: Color.lerp( - // ignore: lines_longer_than_80_chars - a.overlappingTooltipStrokeColor, - b.overlappingTooltipStrokeColor, - t), + activeTrackHeight: + lerpDouble(a!.activeTrackHeight, b!.activeTrackHeight, t)!, + inactiveTrackHeight: + lerpDouble(a.inactiveTrackHeight, b.inactiveTrackHeight, t)!, + tickSize: Size.lerp(a.tickSize, b.tickSize, t), + minorTickSize: Size.lerp(a.minorTickSize, b.minorTickSize, t), + tickOffset: Offset.lerp(a.tickOffset, b.tickOffset, t), + labelOffset: Offset.lerp(a.labelOffset, b.labelOffset, t), + inactiveLabelStyle: TextStyle.lerp( + a.inactiveLabelStyle, + b.inactiveLabelStyle, + t, + ), + activeLabelStyle: TextStyle.lerp( + a.activeLabelStyle, + b.activeLabelStyle, + t, + ), + tooltipTextStyle: TextStyle.lerp( + a.tooltipTextStyle, + b.tooltipTextStyle, + t, + ), + inactiveTrackColor: Color.lerp( + a.inactiveTrackColor, + b.inactiveTrackColor, + t, + ), + activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), + thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), + thumbStrokeColor: Color.lerp(a.thumbStrokeColor, b.thumbStrokeColor, t), + overlappingThumbStrokeColor: Color.lerp( + a.overlappingThumbStrokeColor, + b.overlappingThumbStrokeColor, + t, + ), + activeDividerStrokeColor: Color.lerp( + a.activeDividerStrokeColor, + b.activeDividerStrokeColor, + t, + ), + inactiveDividerStrokeColor: Color.lerp( + a.inactiveDividerStrokeColor, + b.inactiveDividerStrokeColor, + t, + ), + activeTickColor: Color.lerp(a.activeTickColor, b.activeTickColor, t), + inactiveTickColor: Color.lerp( + a.inactiveTickColor, + b.inactiveTickColor, + t, + ), + disabledActiveTickColor: Color.lerp( + a.disabledActiveTickColor, + b.disabledActiveTickColor, + t, + ), + disabledInactiveTickColor: Color.lerp( + a.disabledInactiveTickColor, + b.disabledInactiveTickColor, + t, + ), + activeMinorTickColor: Color.lerp( + a.activeMinorTickColor, + b.activeMinorTickColor, + t, + ), + inactiveMinorTickColor: Color.lerp( + a.inactiveMinorTickColor, + b.inactiveMinorTickColor, + t, + ), + disabledActiveMinorTickColor: Color.lerp( + a.disabledActiveMinorTickColor, + b.disabledActiveMinorTickColor, + t, + ), + disabledInactiveMinorTickColor: Color.lerp( + a.disabledInactiveMinorTickColor, + b.disabledInactiveMinorTickColor, + t, + ), + overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), + inactiveDividerColor: Color.lerp( + a.inactiveDividerColor, + b.inactiveDividerColor, + t, + ), + activeDividerColor: Color.lerp( + a.activeDividerColor, + b.activeDividerColor, + t, + ), + disabledActiveTrackColor: Color.lerp( + a.disabledActiveTrackColor, + b.disabledActiveTrackColor, + t, + ), + disabledInactiveTrackColor: Color.lerp( + a.disabledInactiveTrackColor, + b.disabledInactiveTrackColor, + t, + ), + disabledActiveDividerColor: Color.lerp( + a.disabledActiveDividerColor, + b.disabledActiveDividerColor, + t, + ), + disabledInactiveDividerColor: Color.lerp( + a.disabledInactiveDividerColor, + b.disabledInactiveDividerColor, + t, + ), + disabledThumbColor: Color.lerp( + a.disabledThumbColor, + b.disabledThumbColor, + t, + ), + tooltipBackgroundColor: Color.lerp( + a.tooltipBackgroundColor, + b.tooltipBackgroundColor, + t, + ), + overlappingTooltipStrokeColor: Color.lerp( // ignore: lines_longer_than_80_chars - trackCornerRadius: - lerpDouble(a.trackCornerRadius, b.trackCornerRadius, t), - overlayRadius: lerpDouble(a.overlayRadius, b.overlayRadius, t)!, - thumbRadius: lerpDouble(a.thumbRadius, b.thumbRadius, t)!, - // ignore: lines_longer_than_80_chars - activeDividerRadius: - lerpDouble(a.activeDividerRadius, b.activeDividerRadius, t), - // ignore: lines_longer_than_80_chars - inactiveDividerRadius: lerpDouble(a.inactiveDividerRadius, b.inactiveDividerRadius, t), - thumbStrokeWidth: lerpDouble(a.thumbStrokeWidth, b.thumbStrokeWidth, t), - // ignore: lines_longer_than_80_chars - activeDividerStrokeWidth: lerpDouble(a.activeDividerStrokeWidth, b.activeDividerStrokeWidth, t), - // ignore: lines_longer_than_80_chars - inactiveDividerStrokeWidth: lerpDouble(a.inactiveDividerStrokeWidth, b.inactiveDividerStrokeWidth, t)); + a.overlappingTooltipStrokeColor, + b.overlappingTooltipStrokeColor, + t, + ), + // ignore: lines_longer_than_80_chars + trackCornerRadius: lerpDouble( + a.trackCornerRadius, + b.trackCornerRadius, + t, + ), + overlayRadius: lerpDouble(a.overlayRadius, b.overlayRadius, t)!, + thumbRadius: lerpDouble(a.thumbRadius, b.thumbRadius, t)!, + // ignore: lines_longer_than_80_chars + activeDividerRadius: lerpDouble( + a.activeDividerRadius, + b.activeDividerRadius, + t, + ), + // ignore: lines_longer_than_80_chars + inactiveDividerRadius: lerpDouble( + a.inactiveDividerRadius, + b.inactiveDividerRadius, + t, + ), + thumbStrokeWidth: lerpDouble(a.thumbStrokeWidth, b.thumbStrokeWidth, t), + // ignore: lines_longer_than_80_chars + activeDividerStrokeWidth: lerpDouble( + a.activeDividerStrokeWidth, + b.activeDividerStrokeWidth, + t, + ), + // ignore: lines_longer_than_80_chars + inactiveDividerStrokeWidth: lerpDouble( + a.inactiveDividerStrokeWidth, + b.inactiveDividerStrokeWidth, + t, + ), + ); } @override @@ -645,109 +734,299 @@ class SfRangeSliderThemeData extends SfSliderThemeData { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfRangeSliderThemeData defaultData = SfRangeSliderThemeData(); - properties.add(DoubleProperty('activeTrackHeight', activeTrackHeight, - defaultValue: defaultData.activeTrackHeight)); - properties.add(DoubleProperty('inactiveTrackHeight', inactiveTrackHeight, - defaultValue: defaultData.inactiveTrackHeight)); - properties.add(DiagnosticsProperty('tickSize', tickSize, - defaultValue: defaultData.tickSize)); - properties.add(DiagnosticsProperty('minorTickSize', minorTickSize, - defaultValue: defaultData.minorTickSize)); - properties.add(DiagnosticsProperty('tickOffset', tickOffset, - defaultValue: defaultData.tickOffset)); - properties.add(DiagnosticsProperty('labelOffset', labelOffset, - defaultValue: defaultData.labelOffset)); - properties.add(DiagnosticsProperty( - 'inactiveLabelStyle', inactiveLabelStyle, - defaultValue: defaultData.inactiveLabelStyle)); - properties.add(DiagnosticsProperty( - 'activeLabelStyle', activeLabelStyle, - defaultValue: defaultData.activeLabelStyle)); - properties.add(DiagnosticsProperty( - 'tooltipTextStyle', tooltipTextStyle, - defaultValue: defaultData.tooltipTextStyle)); - properties.add(ColorProperty('inactiveTrackColor', inactiveTrackColor, - defaultValue: defaultData.inactiveTrackColor)); - properties.add(ColorProperty('activeTrackColor', activeTrackColor, - defaultValue: defaultData.activeTrackColor)); - properties.add(ColorProperty('thumbColor', thumbColor, - defaultValue: defaultData.thumbColor)); - properties.add(ColorProperty('thumbStrokeColor', thumbStrokeColor, - defaultValue: defaultData.thumbStrokeColor)); - properties.add(ColorProperty( - 'overlappingThumbStrokeColor', overlappingThumbStrokeColor, - defaultValue: defaultData.overlappingThumbStrokeColor)); - properties.add(ColorProperty( - 'activeDividerStrokeColor', activeDividerStrokeColor, - defaultValue: defaultData.activeDividerStrokeColor)); - properties.add(ColorProperty( - 'inactiveDividerStrokeColor', inactiveDividerStrokeColor, - defaultValue: defaultData.inactiveDividerStrokeColor)); - properties.add(ColorProperty('activeTickColor', activeTickColor, - defaultValue: defaultData.activeTickColor)); - properties.add(ColorProperty('inactiveTickColor', inactiveTickColor, - defaultValue: defaultData.inactiveTickColor)); - properties.add(ColorProperty( - 'disabledActiveTickColor', disabledActiveTickColor, - defaultValue: defaultData.disabledActiveTickColor)); - properties.add(ColorProperty( - 'disabledInactiveTickColor', disabledInactiveTickColor, - defaultValue: defaultData.disabledInactiveTickColor)); - properties.add(ColorProperty('activeMinorTickColor', activeMinorTickColor, - defaultValue: defaultData.activeMinorTickColor)); - properties.add(ColorProperty( - 'inactiveMinorTickColor', inactiveMinorTickColor, - defaultValue: defaultData.inactiveMinorTickColor)); - properties.add(ColorProperty( - 'disabledActiveMinorTickColor', disabledActiveMinorTickColor, - defaultValue: defaultData.disabledActiveMinorTickColor)); - properties.add(ColorProperty( - 'disabledInactiveMinorTickColor', disabledInactiveMinorTickColor, - defaultValue: defaultData.disabledInactiveMinorTickColor)); - properties.add(ColorProperty('overlayColor', overlayColor, - defaultValue: defaultData.overlayColor)); - properties.add(ColorProperty('inactiveDividerColor', inactiveDividerColor, - defaultValue: defaultData.inactiveDividerColor)); - properties.add(ColorProperty('activeDividerColor', activeDividerColor, - defaultValue: defaultData.activeDividerColor)); - properties.add(ColorProperty( - 'disabledActiveTrackColor', disabledActiveTrackColor, - defaultValue: defaultData.disabledActiveTrackColor)); - properties.add(ColorProperty( - 'disabledInactiveTrackColor', disabledInactiveTrackColor, - defaultValue: defaultData.disabledInactiveTrackColor)); - properties.add(ColorProperty( - 'disabledActiveDividerColor', disabledActiveDividerColor, - defaultValue: defaultData.disabledActiveDividerColor)); - properties.add(ColorProperty( - 'disabledInactiveDividerColor', disabledInactiveDividerColor, - defaultValue: defaultData.disabledInactiveDividerColor)); - properties.add(ColorProperty('disabledThumbColor', disabledThumbColor, - defaultValue: defaultData.disabledThumbColor)); - properties.add(ColorProperty( - 'tooltipBackgroundColor', tooltipBackgroundColor, - defaultValue: defaultData.tooltipBackgroundColor)); - properties.add(ColorProperty( - 'overlappingTooltipStrokeColor', overlappingTooltipStrokeColor, - defaultValue: defaultData.overlappingTooltipStrokeColor)); - properties.add(DoubleProperty('trackCornerRadius', trackCornerRadius, - defaultValue: defaultData.trackCornerRadius)); - properties.add(DoubleProperty('overlayRadius', overlayRadius, - defaultValue: defaultData.overlayRadius)); - properties.add(DoubleProperty('thumbRadius', thumbRadius, - defaultValue: defaultData.thumbRadius)); - properties.add(DoubleProperty('activeDividerRadius', activeDividerRadius, - defaultValue: defaultData.activeDividerRadius)); - properties.add(DoubleProperty( - 'inactiveDividerRadius', inactiveDividerRadius, - defaultValue: defaultData.inactiveDividerRadius)); - properties.add(DoubleProperty('thumbStrokeWidth', thumbStrokeWidth, - defaultValue: defaultData.thumbStrokeWidth)); - properties.add(DoubleProperty( - 'activeDividerStrokeWidth', activeDividerStrokeWidth, - defaultValue: defaultData.activeDividerStrokeWidth)); - properties.add(DoubleProperty( - 'inactiveDividerStrokeWidth', inactiveDividerStrokeWidth, - defaultValue: defaultData.inactiveDividerStrokeWidth)); + properties.add( + DoubleProperty( + 'activeTrackHeight', + activeTrackHeight, + defaultValue: defaultData.activeTrackHeight, + ), + ); + properties.add( + DoubleProperty( + 'inactiveTrackHeight', + inactiveTrackHeight, + defaultValue: defaultData.inactiveTrackHeight, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickSize', + tickSize, + defaultValue: defaultData.tickSize, + ), + ); + properties.add( + DiagnosticsProperty( + 'minorTickSize', + minorTickSize, + defaultValue: defaultData.minorTickSize, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickOffset', + tickOffset, + defaultValue: defaultData.tickOffset, + ), + ); + properties.add( + DiagnosticsProperty( + 'labelOffset', + labelOffset, + defaultValue: defaultData.labelOffset, + ), + ); + properties.add( + DiagnosticsProperty( + 'inactiveLabelStyle', + inactiveLabelStyle, + defaultValue: defaultData.inactiveLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'activeLabelStyle', + activeLabelStyle, + defaultValue: defaultData.activeLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'tooltipTextStyle', + tooltipTextStyle, + defaultValue: defaultData.tooltipTextStyle, + ), + ); + properties.add( + ColorProperty( + 'inactiveTrackColor', + inactiveTrackColor, + defaultValue: defaultData.inactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'activeTrackColor', + activeTrackColor, + defaultValue: defaultData.activeTrackColor, + ), + ); + properties.add( + ColorProperty( + 'thumbColor', + thumbColor, + defaultValue: defaultData.thumbColor, + ), + ); + properties.add( + ColorProperty( + 'thumbStrokeColor', + thumbStrokeColor, + defaultValue: defaultData.thumbStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'overlappingThumbStrokeColor', + overlappingThumbStrokeColor, + defaultValue: defaultData.overlappingThumbStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'activeDividerStrokeColor', + activeDividerStrokeColor, + defaultValue: defaultData.activeDividerStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveDividerStrokeColor', + inactiveDividerStrokeColor, + defaultValue: defaultData.inactiveDividerStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'activeTickColor', + activeTickColor, + defaultValue: defaultData.activeTickColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveTickColor', + inactiveTickColor, + defaultValue: defaultData.inactiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTickColor', + disabledActiveTickColor, + defaultValue: defaultData.disabledActiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTickColor', + disabledInactiveTickColor, + defaultValue: defaultData.disabledInactiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'activeMinorTickColor', + activeMinorTickColor, + defaultValue: defaultData.activeMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveMinorTickColor', + inactiveMinorTickColor, + defaultValue: defaultData.inactiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveMinorTickColor', + disabledActiveMinorTickColor, + defaultValue: defaultData.disabledActiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveMinorTickColor', + disabledInactiveMinorTickColor, + defaultValue: defaultData.disabledInactiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'overlayColor', + overlayColor, + defaultValue: defaultData.overlayColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveDividerColor', + inactiveDividerColor, + defaultValue: defaultData.inactiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'activeDividerColor', + activeDividerColor, + defaultValue: defaultData.activeDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTrackColor', + disabledActiveTrackColor, + defaultValue: defaultData.disabledActiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTrackColor', + disabledInactiveTrackColor, + defaultValue: defaultData.disabledInactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveDividerColor', + disabledActiveDividerColor, + defaultValue: defaultData.disabledActiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveDividerColor', + disabledInactiveDividerColor, + defaultValue: defaultData.disabledInactiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledThumbColor', + disabledThumbColor, + defaultValue: defaultData.disabledThumbColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipBackgroundColor', + tooltipBackgroundColor, + defaultValue: defaultData.tooltipBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'overlappingTooltipStrokeColor', + overlappingTooltipStrokeColor, + defaultValue: defaultData.overlappingTooltipStrokeColor, + ), + ); + properties.add( + DoubleProperty( + 'trackCornerRadius', + trackCornerRadius, + defaultValue: defaultData.trackCornerRadius, + ), + ); + properties.add( + DoubleProperty( + 'overlayRadius', + overlayRadius, + defaultValue: defaultData.overlayRadius, + ), + ); + properties.add( + DoubleProperty( + 'thumbRadius', + thumbRadius, + defaultValue: defaultData.thumbRadius, + ), + ); + properties.add( + DoubleProperty( + 'activeDividerRadius', + activeDividerRadius, + defaultValue: defaultData.activeDividerRadius, + ), + ); + properties.add( + DoubleProperty( + 'inactiveDividerRadius', + inactiveDividerRadius, + defaultValue: defaultData.inactiveDividerRadius, + ), + ); + properties.add( + DoubleProperty( + 'thumbStrokeWidth', + thumbStrokeWidth, + defaultValue: defaultData.thumbStrokeWidth, + ), + ); + properties.add( + DoubleProperty( + 'activeDividerStrokeWidth', + activeDividerStrokeWidth, + defaultValue: defaultData.activeDividerStrokeWidth, + ), + ); + properties.add( + DoubleProperty( + 'inactiveDividerStrokeWidth', + inactiveDividerStrokeWidth, + defaultValue: defaultData.inactiveDividerStrokeWidth, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/slider_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/slider_theme.dart index c050b183a..572194ef8 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/slider_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/slider_theme.dart @@ -11,7 +11,7 @@ class SfSliderTheme extends InheritedTheme { /// /// The [data] and [child] arguments must not be null. const SfSliderTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant slider widgets. final SfSliderThemeData data; @@ -330,82 +330,160 @@ class SfSliderThemeData with Diagnosticable { /// /// The arguments must not be null. static SfSliderThemeData? lerp( - SfSliderThemeData? a, SfSliderThemeData? b, double t) { + SfSliderThemeData? a, + SfSliderThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfSliderThemeData( - activeTrackHeight: - lerpDouble(a!.activeTrackHeight, b!.activeTrackHeight, t)!, - inactiveTrackHeight: - lerpDouble(a.inactiveTrackHeight, b.inactiveTrackHeight, t)!, - tickSize: Size.lerp(a.tickSize, b.tickSize, t), - minorTickSize: Size.lerp(a.minorTickSize, b.minorTickSize, t), - tickOffset: Offset.lerp(a.tickOffset, b.tickOffset, t), - labelOffset: Offset.lerp(a.labelOffset, b.labelOffset, t), - inactiveLabelStyle: - TextStyle.lerp(a.inactiveLabelStyle, b.inactiveLabelStyle, t), - activeLabelStyle: - TextStyle.lerp(a.activeLabelStyle, b.activeLabelStyle, t), - tooltipTextStyle: - TextStyle.lerp(a.tooltipTextStyle, b.tooltipTextStyle, t), - inactiveTrackColor: - Color.lerp(a.inactiveTrackColor, b.inactiveTrackColor, t), - activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), - thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), - thumbStrokeColor: Color.lerp(a.thumbStrokeColor, b.thumbStrokeColor, t), - activeDividerStrokeColor: Color.lerp( - a.activeDividerStrokeColor, b.activeDividerStrokeColor, t), - inactiveDividerStrokeColor: Color.lerp( - a.inactiveDividerStrokeColor, b.inactiveDividerStrokeColor, t), - activeTickColor: Color.lerp(a.activeTickColor, b.activeTickColor, t), - inactiveTickColor: - Color.lerp(a.inactiveTickColor, b.inactiveTickColor, t), - disabledActiveTickColor: - Color.lerp(a.disabledActiveTickColor, b.disabledActiveTickColor, t), - disabledInactiveTickColor: Color.lerp( - a.disabledInactiveTickColor, b.disabledInactiveTickColor, t), - activeMinorTickColor: - Color.lerp(a.activeMinorTickColor, b.activeMinorTickColor, t), - inactiveMinorTickColor: - Color.lerp(a.inactiveMinorTickColor, b.inactiveMinorTickColor, t), - disabledActiveMinorTickColor: Color.lerp( - a.disabledActiveMinorTickColor, b.disabledActiveMinorTickColor, t), - disabledInactiveMinorTickColor: Color.lerp( - a.disabledInactiveMinorTickColor, - b.disabledInactiveMinorTickColor, - t), - overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), - inactiveDividerColor: - Color.lerp(a.inactiveDividerColor, b.inactiveDividerColor, t), - activeDividerColor: - Color.lerp(a.activeDividerColor, b.activeDividerColor, t), - disabledActiveTrackColor: Color.lerp( - a.disabledActiveTrackColor, b.disabledActiveTrackColor, t), - disabledInactiveTrackColor: Color.lerp( - a.disabledInactiveTrackColor, b.disabledInactiveTrackColor, t), - disabledActiveDividerColor: Color.lerp( - a.disabledActiveDividerColor, b.disabledActiveDividerColor, t), - disabledInactiveDividerColor: Color.lerp( - a.disabledInactiveDividerColor, b.disabledInactiveDividerColor, t), - disabledThumbColor: - Color.lerp(a.disabledThumbColor, b.disabledThumbColor, t), - tooltipBackgroundColor: - Color.lerp(a.tooltipBackgroundColor, b.tooltipBackgroundColor, t), - trackCornerRadius: - lerpDouble(a.trackCornerRadius, b.trackCornerRadius, t), - overlayRadius: lerpDouble(a.overlayRadius, b.overlayRadius, t)!, - thumbRadius: lerpDouble(a.thumbRadius, b.thumbRadius, t)!, - activeDividerRadius: - lerpDouble(a.activeDividerRadius, b.activeDividerRadius, t), - inactiveDividerRadius: - lerpDouble(a.inactiveDividerRadius, b.inactiveDividerRadius, t), - thumbStrokeWidth: lerpDouble(a.thumbStrokeWidth, b.thumbStrokeWidth, t), - activeDividerStrokeWidth: - // ignore: lines_longer_than_80_chars - lerpDouble(a.activeDividerStrokeWidth, b.activeDividerStrokeWidth, t), - // ignore: lines_longer_than_80_chars - inactiveDividerStrokeWidth: lerpDouble(a.inactiveDividerStrokeWidth, b.inactiveDividerStrokeWidth, t)); + activeTrackHeight: + lerpDouble(a!.activeTrackHeight, b!.activeTrackHeight, t)!, + inactiveTrackHeight: + lerpDouble(a.inactiveTrackHeight, b.inactiveTrackHeight, t)!, + tickSize: Size.lerp(a.tickSize, b.tickSize, t), + minorTickSize: Size.lerp(a.minorTickSize, b.minorTickSize, t), + tickOffset: Offset.lerp(a.tickOffset, b.tickOffset, t), + labelOffset: Offset.lerp(a.labelOffset, b.labelOffset, t), + inactiveLabelStyle: TextStyle.lerp( + a.inactiveLabelStyle, + b.inactiveLabelStyle, + t, + ), + activeLabelStyle: TextStyle.lerp( + a.activeLabelStyle, + b.activeLabelStyle, + t, + ), + tooltipTextStyle: TextStyle.lerp( + a.tooltipTextStyle, + b.tooltipTextStyle, + t, + ), + inactiveTrackColor: Color.lerp( + a.inactiveTrackColor, + b.inactiveTrackColor, + t, + ), + activeTrackColor: Color.lerp(a.activeTrackColor, b.activeTrackColor, t), + thumbColor: Color.lerp(a.thumbColor, b.thumbColor, t), + thumbStrokeColor: Color.lerp(a.thumbStrokeColor, b.thumbStrokeColor, t), + activeDividerStrokeColor: Color.lerp( + a.activeDividerStrokeColor, + b.activeDividerStrokeColor, + t, + ), + inactiveDividerStrokeColor: Color.lerp( + a.inactiveDividerStrokeColor, + b.inactiveDividerStrokeColor, + t, + ), + activeTickColor: Color.lerp(a.activeTickColor, b.activeTickColor, t), + inactiveTickColor: Color.lerp( + a.inactiveTickColor, + b.inactiveTickColor, + t, + ), + disabledActiveTickColor: Color.lerp( + a.disabledActiveTickColor, + b.disabledActiveTickColor, + t, + ), + disabledInactiveTickColor: Color.lerp( + a.disabledInactiveTickColor, + b.disabledInactiveTickColor, + t, + ), + activeMinorTickColor: Color.lerp( + a.activeMinorTickColor, + b.activeMinorTickColor, + t, + ), + inactiveMinorTickColor: Color.lerp( + a.inactiveMinorTickColor, + b.inactiveMinorTickColor, + t, + ), + disabledActiveMinorTickColor: Color.lerp( + a.disabledActiveMinorTickColor, + b.disabledActiveMinorTickColor, + t, + ), + disabledInactiveMinorTickColor: Color.lerp( + a.disabledInactiveMinorTickColor, + b.disabledInactiveMinorTickColor, + t, + ), + overlayColor: Color.lerp(a.overlayColor, b.overlayColor, t), + inactiveDividerColor: Color.lerp( + a.inactiveDividerColor, + b.inactiveDividerColor, + t, + ), + activeDividerColor: Color.lerp( + a.activeDividerColor, + b.activeDividerColor, + t, + ), + disabledActiveTrackColor: Color.lerp( + a.disabledActiveTrackColor, + b.disabledActiveTrackColor, + t, + ), + disabledInactiveTrackColor: Color.lerp( + a.disabledInactiveTrackColor, + b.disabledInactiveTrackColor, + t, + ), + disabledActiveDividerColor: Color.lerp( + a.disabledActiveDividerColor, + b.disabledActiveDividerColor, + t, + ), + disabledInactiveDividerColor: Color.lerp( + a.disabledInactiveDividerColor, + b.disabledInactiveDividerColor, + t, + ), + disabledThumbColor: Color.lerp( + a.disabledThumbColor, + b.disabledThumbColor, + t, + ), + tooltipBackgroundColor: Color.lerp( + a.tooltipBackgroundColor, + b.tooltipBackgroundColor, + t, + ), + trackCornerRadius: lerpDouble( + a.trackCornerRadius, + b.trackCornerRadius, + t, + ), + overlayRadius: lerpDouble(a.overlayRadius, b.overlayRadius, t)!, + thumbRadius: lerpDouble(a.thumbRadius, b.thumbRadius, t)!, + activeDividerRadius: lerpDouble( + a.activeDividerRadius, + b.activeDividerRadius, + t, + ), + inactiveDividerRadius: lerpDouble( + a.inactiveDividerRadius, + b.inactiveDividerRadius, + t, + ), + thumbStrokeWidth: lerpDouble(a.thumbStrokeWidth, b.thumbStrokeWidth, t), + activeDividerStrokeWidth: + // ignore: lines_longer_than_80_chars + lerpDouble(a.activeDividerStrokeWidth, b.activeDividerStrokeWidth, t), + // ignore: lines_longer_than_80_chars + inactiveDividerStrokeWidth: lerpDouble( + a.inactiveDividerStrokeWidth, + b.inactiveDividerStrokeWidth, + t, + ), + ); } @override @@ -511,104 +589,286 @@ class SfSliderThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfSliderThemeData defaultData = SfSliderThemeData(); - properties.add(DoubleProperty('activeTrackHeight', activeTrackHeight, - defaultValue: defaultData.activeTrackHeight)); - properties.add(DoubleProperty('inactiveTrackHeight', inactiveTrackHeight, - defaultValue: defaultData.inactiveTrackHeight)); - properties.add(DiagnosticsProperty('tickSize', tickSize, - defaultValue: defaultData.tickSize)); - properties.add(DiagnosticsProperty('minorTickSize', minorTickSize, - defaultValue: defaultData.minorTickSize)); - properties.add(DiagnosticsProperty('tickOffset', tickOffset, - defaultValue: defaultData.tickOffset)); - properties.add(DiagnosticsProperty('labelOffset', labelOffset, - defaultValue: defaultData.labelOffset)); - properties.add(DiagnosticsProperty( - 'inactiveLabelStyle', inactiveLabelStyle, - defaultValue: defaultData.inactiveLabelStyle)); - properties.add(DiagnosticsProperty( - 'activeLabelStyle', activeLabelStyle, - defaultValue: defaultData.activeLabelStyle)); - properties.add(DiagnosticsProperty( - 'tooltipTextStyle', tooltipTextStyle, - defaultValue: defaultData.tooltipTextStyle)); - properties.add(ColorProperty('inactiveTrackColor', inactiveTrackColor, - defaultValue: defaultData.inactiveTrackColor)); - properties.add(ColorProperty('activeTrackColor', activeTrackColor, - defaultValue: defaultData.activeTrackColor)); - properties.add(ColorProperty('thumbColor', thumbColor, - defaultValue: defaultData.thumbColor)); - properties.add(ColorProperty('thumbStrokeColor', thumbStrokeColor, - defaultValue: defaultData.thumbStrokeColor)); - properties.add(ColorProperty( - 'activeDividerStrokeColor', activeDividerStrokeColor, - defaultValue: defaultData.activeDividerStrokeColor)); - properties.add(ColorProperty( - 'inactiveDividerStrokeColor', inactiveDividerStrokeColor, - defaultValue: defaultData.inactiveDividerStrokeColor)); - properties.add(ColorProperty('activeTickColor', activeTickColor, - defaultValue: defaultData.activeTickColor)); - properties.add(ColorProperty('inactiveTickColor', inactiveTickColor, - defaultValue: defaultData.inactiveTickColor)); - properties.add(ColorProperty( - 'disabledActiveTickColor', disabledActiveTickColor, - defaultValue: defaultData.disabledActiveTickColor)); - properties.add(ColorProperty( - 'disabledInactiveTickColor', disabledInactiveTickColor, - defaultValue: defaultData.disabledInactiveTickColor)); - properties.add(ColorProperty('activeMinorTickColor', activeMinorTickColor, - defaultValue: defaultData.activeMinorTickColor)); - properties.add(ColorProperty( - 'inactiveMinorTickColor', inactiveMinorTickColor, - defaultValue: defaultData.inactiveMinorTickColor)); - properties.add(ColorProperty( - 'disabledActiveMinorTickColor', disabledActiveMinorTickColor, - defaultValue: defaultData.disabledActiveMinorTickColor)); - properties.add(ColorProperty( - 'disabledInactiveMinorTickColor', disabledInactiveMinorTickColor, - defaultValue: defaultData.disabledInactiveMinorTickColor)); - properties.add(ColorProperty('overlayColor', overlayColor, - defaultValue: defaultData.overlayColor)); - properties.add(ColorProperty('inactiveDividerColor', inactiveDividerColor, - defaultValue: defaultData.inactiveDividerColor)); - properties.add(ColorProperty('activeDividerColor', activeDividerColor, - defaultValue: defaultData.activeDividerColor)); - properties.add(ColorProperty( - 'disabledActiveTrackColor', disabledActiveTrackColor, - defaultValue: defaultData.disabledActiveTrackColor)); - properties.add(ColorProperty( - 'disabledInactiveTrackColor', disabledInactiveTrackColor, - defaultValue: defaultData.disabledInactiveTrackColor)); - properties.add(ColorProperty( - 'disabledActiveDividerColor', disabledActiveDividerColor, - defaultValue: defaultData.disabledActiveDividerColor)); - properties.add(ColorProperty( - 'disabledInactiveDividerColor', disabledInactiveDividerColor, - defaultValue: defaultData.disabledInactiveDividerColor)); - properties.add(ColorProperty('disabledThumbColor', disabledThumbColor, - defaultValue: defaultData.disabledThumbColor)); - properties.add(ColorProperty( - 'tooltipBackgroundColor', tooltipBackgroundColor, - defaultValue: defaultData.tooltipBackgroundColor)); - properties.add(DoubleProperty('trackCornerRadius', trackCornerRadius, - defaultValue: defaultData.trackCornerRadius)); - properties.add(DoubleProperty('overlayRadius', overlayRadius, - defaultValue: defaultData.overlayRadius)); - properties.add(DoubleProperty('thumbRadius', thumbRadius, - defaultValue: defaultData.thumbRadius)); - properties.add(DoubleProperty('activeDividerRadius', activeDividerRadius, - defaultValue: defaultData.activeDividerRadius)); - properties.add(DoubleProperty( - 'inactiveDividerRadius', inactiveDividerRadius, - defaultValue: defaultData.inactiveDividerRadius)); - properties.add(DoubleProperty('thumbStrokeWidth', thumbStrokeWidth, - defaultValue: defaultData.thumbStrokeWidth)); - properties.add(DoubleProperty( - 'activeDividerStrokeWidth', activeDividerStrokeWidth, - defaultValue: defaultData.activeDividerStrokeWidth)); - properties.add(DoubleProperty( - 'inactiveDividerStrokeWidth', inactiveDividerStrokeWidth, - defaultValue: defaultData.inactiveDividerStrokeWidth)); + properties.add( + DoubleProperty( + 'activeTrackHeight', + activeTrackHeight, + defaultValue: defaultData.activeTrackHeight, + ), + ); + properties.add( + DoubleProperty( + 'inactiveTrackHeight', + inactiveTrackHeight, + defaultValue: defaultData.inactiveTrackHeight, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickSize', + tickSize, + defaultValue: defaultData.tickSize, + ), + ); + properties.add( + DiagnosticsProperty( + 'minorTickSize', + minorTickSize, + defaultValue: defaultData.minorTickSize, + ), + ); + properties.add( + DiagnosticsProperty( + 'tickOffset', + tickOffset, + defaultValue: defaultData.tickOffset, + ), + ); + properties.add( + DiagnosticsProperty( + 'labelOffset', + labelOffset, + defaultValue: defaultData.labelOffset, + ), + ); + properties.add( + DiagnosticsProperty( + 'inactiveLabelStyle', + inactiveLabelStyle, + defaultValue: defaultData.inactiveLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'activeLabelStyle', + activeLabelStyle, + defaultValue: defaultData.activeLabelStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'tooltipTextStyle', + tooltipTextStyle, + defaultValue: defaultData.tooltipTextStyle, + ), + ); + properties.add( + ColorProperty( + 'inactiveTrackColor', + inactiveTrackColor, + defaultValue: defaultData.inactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'activeTrackColor', + activeTrackColor, + defaultValue: defaultData.activeTrackColor, + ), + ); + properties.add( + ColorProperty( + 'thumbColor', + thumbColor, + defaultValue: defaultData.thumbColor, + ), + ); + properties.add( + ColorProperty( + 'thumbStrokeColor', + thumbStrokeColor, + defaultValue: defaultData.thumbStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'activeDividerStrokeColor', + activeDividerStrokeColor, + defaultValue: defaultData.activeDividerStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveDividerStrokeColor', + inactiveDividerStrokeColor, + defaultValue: defaultData.inactiveDividerStrokeColor, + ), + ); + properties.add( + ColorProperty( + 'activeTickColor', + activeTickColor, + defaultValue: defaultData.activeTickColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveTickColor', + inactiveTickColor, + defaultValue: defaultData.inactiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTickColor', + disabledActiveTickColor, + defaultValue: defaultData.disabledActiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTickColor', + disabledInactiveTickColor, + defaultValue: defaultData.disabledInactiveTickColor, + ), + ); + properties.add( + ColorProperty( + 'activeMinorTickColor', + activeMinorTickColor, + defaultValue: defaultData.activeMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveMinorTickColor', + inactiveMinorTickColor, + defaultValue: defaultData.inactiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveMinorTickColor', + disabledActiveMinorTickColor, + defaultValue: defaultData.disabledActiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveMinorTickColor', + disabledInactiveMinorTickColor, + defaultValue: defaultData.disabledInactiveMinorTickColor, + ), + ); + properties.add( + ColorProperty( + 'overlayColor', + overlayColor, + defaultValue: defaultData.overlayColor, + ), + ); + properties.add( + ColorProperty( + 'inactiveDividerColor', + inactiveDividerColor, + defaultValue: defaultData.inactiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'activeDividerColor', + activeDividerColor, + defaultValue: defaultData.activeDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveTrackColor', + disabledActiveTrackColor, + defaultValue: defaultData.disabledActiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveTrackColor', + disabledInactiveTrackColor, + defaultValue: defaultData.disabledInactiveTrackColor, + ), + ); + properties.add( + ColorProperty( + 'disabledActiveDividerColor', + disabledActiveDividerColor, + defaultValue: defaultData.disabledActiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledInactiveDividerColor', + disabledInactiveDividerColor, + defaultValue: defaultData.disabledInactiveDividerColor, + ), + ); + properties.add( + ColorProperty( + 'disabledThumbColor', + disabledThumbColor, + defaultValue: defaultData.disabledThumbColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipBackgroundColor', + tooltipBackgroundColor, + defaultValue: defaultData.tooltipBackgroundColor, + ), + ); + properties.add( + DoubleProperty( + 'trackCornerRadius', + trackCornerRadius, + defaultValue: defaultData.trackCornerRadius, + ), + ); + properties.add( + DoubleProperty( + 'overlayRadius', + overlayRadius, + defaultValue: defaultData.overlayRadius, + ), + ); + properties.add( + DoubleProperty( + 'thumbRadius', + thumbRadius, + defaultValue: defaultData.thumbRadius, + ), + ); + properties.add( + DoubleProperty( + 'activeDividerRadius', + activeDividerRadius, + defaultValue: defaultData.activeDividerRadius, + ), + ); + properties.add( + DoubleProperty( + 'inactiveDividerRadius', + inactiveDividerRadius, + defaultValue: defaultData.inactiveDividerRadius, + ), + ); + properties.add( + DoubleProperty( + 'thumbStrokeWidth', + thumbStrokeWidth, + defaultValue: defaultData.thumbStrokeWidth, + ), + ); + properties.add( + DoubleProperty( + 'activeDividerStrokeWidth', + activeDividerStrokeWidth, + defaultValue: defaultData.activeDividerStrokeWidth, + ), + ); + properties.add( + DoubleProperty( + 'inactiveDividerStrokeWidth', + inactiveDividerStrokeWidth, + defaultValue: defaultData.inactiveDividerStrokeWidth, + ), + ); } /// Specifies the height for the active track in the [SfSlider], diff --git a/packages/syncfusion_flutter_core/lib/src/theme/spark_charts_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/spark_charts_theme.dart index cfde765bc..0a0d31eb3 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/spark_charts_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/spark_charts_theme.dart @@ -28,7 +28,7 @@ import '../../theme.dart'; class SfSparkChartTheme extends InheritedTheme { /// Initialize the class of SfSparkChartTheme const SfSparkChartTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant /// spark chart widgets. @@ -392,23 +392,27 @@ class SfSparkChartThemeData with Diagnosticable { TextStyle? trackballTextStyle, }) { return SfSparkChartThemeData.raw( - brightness: brightness, - backgroundColor: backgroundColor ?? this.backgroundColor, - color: color ?? this.color, - axisLineColor: axisLineColor ?? this.axisLineColor, - markerFillColor: markerFillColor ?? this.markerFillColor, - dataLabelBackgroundColor: - dataLabelBackgroundColor ?? this.dataLabelBackgroundColor, - tooltipColor: tooltipColor ?? this.tooltipColor, - trackballLineColor: trackballLineColor ?? this.trackballLineColor, - tooltipLabelColor: tooltipLabelColor ?? this.tooltipLabelColor, - dataLabelTextStyle: dataLabelTextStyle ?? this.dataLabelTextStyle, - trackballTextStyle: trackballTextStyle ?? this.trackballTextStyle); + brightness: brightness, + backgroundColor: backgroundColor ?? this.backgroundColor, + color: color ?? this.color, + axisLineColor: axisLineColor ?? this.axisLineColor, + markerFillColor: markerFillColor ?? this.markerFillColor, + dataLabelBackgroundColor: + dataLabelBackgroundColor ?? this.dataLabelBackgroundColor, + tooltipColor: tooltipColor ?? this.tooltipColor, + trackballLineColor: trackballLineColor ?? this.trackballLineColor, + tooltipLabelColor: tooltipLabelColor ?? this.tooltipLabelColor, + dataLabelTextStyle: dataLabelTextStyle ?? this.dataLabelTextStyle, + trackballTextStyle: trackballTextStyle ?? this.trackballTextStyle, + ); } /// Returns the spark chart theme data static SfSparkChartThemeData? lerp( - SfSparkChartThemeData? a, SfSparkChartThemeData? b, double t) { + SfSparkChartThemeData? a, + SfSparkChartThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } @@ -417,17 +421,32 @@ class SfSparkChartThemeData with Diagnosticable { color: Color.lerp(a.color, b.color, t), axisLineColor: Color.lerp(a.axisLineColor, b.axisLineColor, t), markerFillColor: Color.lerp(a.markerFillColor, b.markerFillColor, t), - dataLabelBackgroundColor: - Color.lerp(a.dataLabelBackgroundColor, b.dataLabelBackgroundColor, t), + dataLabelBackgroundColor: Color.lerp( + a.dataLabelBackgroundColor, + b.dataLabelBackgroundColor, + t, + ), tooltipColor: Color.lerp(a.tooltipColor, b.tooltipColor, t), - trackballLineColor: - Color.lerp(a.trackballLineColor, b.trackballLineColor, t), - tooltipLabelColor: - Color.lerp(a.tooltipLabelColor, b.tooltipLabelColor, t), - dataLabelTextStyle: - TextStyle.lerp(a.dataLabelTextStyle, b.dataLabelTextStyle, t), - trackballTextStyle: - TextStyle.lerp(a.trackballTextStyle, b.trackballTextStyle, t), + trackballLineColor: Color.lerp( + a.trackballLineColor, + b.trackballLineColor, + t, + ), + tooltipLabelColor: Color.lerp( + a.tooltipLabelColor, + b.tooltipLabelColor, + t, + ), + dataLabelTextStyle: TextStyle.lerp( + a.dataLabelTextStyle, + b.dataLabelTextStyle, + t, + ), + trackballTextStyle: TextStyle.lerp( + a.trackballTextStyle, + b.trackballTextStyle, + t, + ), ); } @@ -474,30 +493,71 @@ class SfSparkChartThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfSparkChartThemeData defaultData = SfSparkChartThemeData(); - properties.add(ColorProperty('backgroundColor', backgroundColor, - defaultValue: defaultData.backgroundColor)); - properties - .add(ColorProperty('color', color, defaultValue: defaultData.color)); - properties.add(ColorProperty('axisLineColor', axisLineColor, - defaultValue: defaultData.axisLineColor)); - properties.add(ColorProperty('markerFillColor', markerFillColor, - defaultValue: defaultData.markerFillColor)); - properties.add(ColorProperty( - 'dataLabelBackgroundColor', dataLabelBackgroundColor, - defaultValue: defaultData.dataLabelBackgroundColor)); - properties.add(ColorProperty('tooltipColor', tooltipColor, - defaultValue: defaultData.tooltipColor)); - properties.add(ColorProperty('trackballLineColor', trackballLineColor, - defaultValue: defaultData.trackballLineColor)); - properties.add(ColorProperty('tooltipLabelColor', tooltipLabelColor, - defaultValue: defaultData.tooltipLabelColor)); properties.add( - DiagnosticsProperty('dataLabelTextStyle', dataLabelTextStyle, - defaultValue: defaultData.dataLabelTextStyle), + ColorProperty( + 'backgroundColor', + backgroundColor, + defaultValue: defaultData.backgroundColor, + ), + ); + properties.add( + ColorProperty('color', color, defaultValue: defaultData.color), + ); + properties.add( + ColorProperty( + 'axisLineColor', + axisLineColor, + defaultValue: defaultData.axisLineColor, + ), + ); + properties.add( + ColorProperty( + 'markerFillColor', + markerFillColor, + defaultValue: defaultData.markerFillColor, + ), + ); + properties.add( + ColorProperty( + 'dataLabelBackgroundColor', + dataLabelBackgroundColor, + defaultValue: defaultData.dataLabelBackgroundColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipColor', + tooltipColor, + defaultValue: defaultData.tooltipColor, + ), + ); + properties.add( + ColorProperty( + 'trackballLineColor', + trackballLineColor, + defaultValue: defaultData.trackballLineColor, + ), + ); + properties.add( + ColorProperty( + 'tooltipLabelColor', + tooltipLabelColor, + defaultValue: defaultData.tooltipLabelColor, + ), + ); + properties.add( + DiagnosticsProperty( + 'dataLabelTextStyle', + dataLabelTextStyle, + defaultValue: defaultData.dataLabelTextStyle, + ), ); properties.add( - DiagnosticsProperty('trackballTextStyle', trackballTextStyle, - defaultValue: defaultData.trackballTextStyle), + DiagnosticsProperty( + 'trackballTextStyle', + trackballTextStyle, + defaultValue: defaultData.trackballTextStyle, + ), ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/theme_widget.dart b/packages/syncfusion_flutter_core/lib/src/theme/theme_widget.dart index 03ebf6052..71a73cc8e 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/theme_widget.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/theme_widget.dart @@ -45,11 +45,7 @@ import 'treemap_theme.dart'; /// ``` class SfTheme extends StatelessWidget { /// Creating an argument constructor of [SfTheme] class. - const SfTheme({ - Key? key, - this.data, - required this.child, - }) : super(key: key); + const SfTheme({Key? key, this.data, required this.child}) : super(key: key); /// Specifies a widget that can hold single child. /// @@ -176,7 +172,7 @@ class SfTheme extends StatelessWidget { Color.fromRGBO(71, 59, 137, 1), Color.fromRGBO(236, 92, 123, 1), Color.fromRGBO(59, 163, 26, 1), - Color.fromRGBO(236, 131, 23, 1) + Color.fromRGBO(236, 131, 23, 1), ]; } else { return const [ @@ -189,7 +185,7 @@ class SfTheme extends StatelessWidget { Color.fromRGBO(178, 243, 46, 1), Color.fromRGBO(185, 60, 228, 1), Color.fromRGBO(48, 167, 6, 1), - Color.fromRGBO(207, 142, 14, 1) + Color.fromRGBO(207, 142, 14, 1), ]; } } @@ -205,7 +201,7 @@ class SfTheme extends StatelessWidget { Color.fromRGBO(73, 76, 162, 1), Color.fromRGBO(255, 205, 96, 1), Color.fromRGBO(255, 240, 219, 1), - Color.fromRGBO(238, 238, 238, 1) + Color.fromRGBO(238, 238, 238, 1), ]; } @@ -217,7 +213,7 @@ class SfTheme extends StatelessWidget { class _SfInheritedTheme extends InheritedTheme { const _SfInheritedTheme({Key? key, this.data, required Widget child}) - : super(key: key, child: child); + : super(key: key, child: child); final SfThemeData? data; @override bool updateShouldNotify(_SfInheritedTheme oldWidget) => @@ -279,7 +275,8 @@ class SfThemeData with Diagnosticable { }) { brightness ??= Brightness.light; pdfViewerThemeData = pdfViewerThemeData ?? SfPdfViewerThemeData.raw(); - sparkChartThemeData = sparkChartThemeData ?? + sparkChartThemeData = + sparkChartThemeData ?? SfSparkChartThemeData.raw(brightness: brightness); chartThemeData = chartThemeData ?? SfChartThemeData.raw(brightness: brightness); @@ -287,7 +284,8 @@ class SfThemeData with Diagnosticable { calendarThemeData ?? SfCalendarThemeData.raw(brightness: brightness); dataGridThemeData = dataGridThemeData ?? SfDataGridThemeData.raw(brightness: brightness); - dateRangePickerThemeData = dateRangePickerThemeData ?? + dateRangePickerThemeData = + dateRangePickerThemeData ?? SfDateRangePickerThemeData.raw(brightness: brightness); barcodeThemeData = barcodeThemeData ?? SfBarcodeThemeData.raw(brightness: brightness); @@ -295,9 +293,11 @@ class SfThemeData with Diagnosticable { gaugeThemeData ?? SfGaugeThemeData.raw(brightness: brightness); sliderThemeData = sliderThemeData ?? SfSliderThemeData.raw(brightness: brightness); - rangeSelectorThemeData = rangeSelectorThemeData ?? + rangeSelectorThemeData = + rangeSelectorThemeData ?? SfRangeSelectorThemeData.raw(brightness: brightness); - rangeSliderThemeData = rangeSliderThemeData ?? + rangeSliderThemeData = + rangeSliderThemeData ?? SfRangeSliderThemeData.raw(brightness: brightness); mapsThemeData = mapsThemeData ?? SfMapsThemeData.raw(brightness: brightness); @@ -748,36 +748,72 @@ class SfThemeData with Diagnosticable { assert(b != null); return SfThemeData.raw( brightness: t < 0.5 ? a!.brightness : b!.brightness, - pdfViewerThemeData: SfPdfViewerThemeData.lerp( - a!.pdfViewerThemeData, b!.pdfViewerThemeData, t)!, + pdfViewerThemeData: + SfPdfViewerThemeData.lerp( + a!.pdfViewerThemeData, + b!.pdfViewerThemeData, + t, + )!, chartThemeData: SfChartThemeData.lerp(a.chartThemeData, b.chartThemeData, t)!, - sparkChartThemeData: SfSparkChartThemeData.lerp( - a.sparkChartThemeData, b.sparkChartThemeData, t)!, - calendarThemeData: SfCalendarThemeData.lerp( - a.calendarThemeData, b.calendarThemeData, t)!, - dataGridThemeData: SfDataGridThemeData.lerp( - a.dataGridThemeData, b.dataGridThemeData, t)!, - dataPagerThemeData: SfDataPagerThemeData.lerp( - a.dataPagerThemeData, b.dataPagerThemeData, t)!, - dateRangePickerThemeData: SfDateRangePickerThemeData.lerp( - a.dateRangePickerThemeData, b.dateRangePickerThemeData, t)!, + sparkChartThemeData: + SfSparkChartThemeData.lerp( + a.sparkChartThemeData, + b.sparkChartThemeData, + t, + )!, + calendarThemeData: + SfCalendarThemeData.lerp( + a.calendarThemeData, + b.calendarThemeData, + t, + )!, + dataGridThemeData: + SfDataGridThemeData.lerp( + a.dataGridThemeData, + b.dataGridThemeData, + t, + )!, + dataPagerThemeData: + SfDataPagerThemeData.lerp( + a.dataPagerThemeData, + b.dataPagerThemeData, + t, + )!, + dateRangePickerThemeData: + SfDateRangePickerThemeData.lerp( + a.dateRangePickerThemeData, + b.dateRangePickerThemeData, + t, + )!, barcodeThemeData: SfBarcodeThemeData.lerp(a.barcodeThemeData, b.barcodeThemeData, t)!, gaugeThemeData: SfGaugeThemeData.lerp(a.gaugeThemeData, b.gaugeThemeData, t)!, sliderThemeData: SfSliderThemeData.lerp(a.sliderThemeData, b.sliderThemeData, t)!, - rangeSelectorThemeData: SfRangeSelectorThemeData.lerp( - a.rangeSelectorThemeData, b.rangeSelectorThemeData, t)!, - rangeSliderThemeData: SfRangeSliderThemeData.lerp( - a.rangeSliderThemeData, b.rangeSliderThemeData, t)!, + rangeSelectorThemeData: + SfRangeSelectorThemeData.lerp( + a.rangeSelectorThemeData, + b.rangeSelectorThemeData, + t, + )!, + rangeSliderThemeData: + SfRangeSliderThemeData.lerp( + a.rangeSliderThemeData, + b.rangeSliderThemeData, + t, + )!, mapsThemeData: SfMapsThemeData.lerp(a.mapsThemeData, b.mapsThemeData, t)!, treemapThemeData: SfTreemapThemeData.lerp(a.treemapThemeData, b.treemapThemeData, t)!, chatThemeData: SfChatThemeData.lerp(a.chatThemeData, b.chatThemeData, t)!, - assistThemeData: SfAIAssistViewThemeData.lerp( - a.assistThemeData, b.assistThemeData, t)!, + assistThemeData: + SfAIAssistViewThemeData.lerp( + a.assistThemeData, + b.assistThemeData, + t, + )!, ); } @@ -834,55 +870,124 @@ class SfThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); final SfThemeData defaultData = SfThemeData.fallback(); - properties.add(EnumProperty('brightness', brightness, - defaultValue: defaultData.brightness)); - properties.add(DiagnosticsProperty( - 'pdfViewerThemeData', pdfViewerThemeData, - defaultValue: defaultData.pdfViewerThemeData)); - properties.add(DiagnosticsProperty( - 'chartThemeData', chartThemeData, - defaultValue: defaultData.chartThemeData)); - properties.add(DiagnosticsProperty( - 'sparkChartThemeData', sparkChartThemeData, - defaultValue: defaultData.sparkChartThemeData)); - properties.add(DiagnosticsProperty( - 'calendarThemeData', calendarThemeData, - defaultValue: defaultData.calendarThemeData)); - properties.add(DiagnosticsProperty( - 'dataGridThemeData', dataGridThemeData, - defaultValue: defaultData.dataGridThemeData)); - properties.add(DiagnosticsProperty( - 'dataPagerThemeData', dataPagerThemeData, - defaultValue: defaultData.dataPagerThemeData)); - properties.add(DiagnosticsProperty( - 'dateRangePickerThemeData', dateRangePickerThemeData, - defaultValue: defaultData.dateRangePickerThemeData)); - properties.add(DiagnosticsProperty( - 'barcodeThemeData', barcodeThemeData, - defaultValue: defaultData.barcodeThemeData)); - properties.add(DiagnosticsProperty( - 'gaugeThemeData', gaugeThemeData, - defaultValue: defaultData.gaugeThemeData)); - properties.add(DiagnosticsProperty( - 'rangeSelectorThemeData', rangeSelectorThemeData, - defaultValue: defaultData.rangeSelectorThemeData)); - properties.add(DiagnosticsProperty( - 'rangeSliderThemeData', rangeSliderThemeData, - defaultValue: defaultData.rangeSliderThemeData)); - properties.add(DiagnosticsProperty( - 'sliderThemeData', sliderThemeData, - defaultValue: defaultData.sliderThemeData)); - properties.add(DiagnosticsProperty( - 'mapsThemeData', mapsThemeData, - defaultValue: defaultData.mapsThemeData)); - properties.add(DiagnosticsProperty( - 'treemapThemeData', treemapThemeData, - defaultValue: defaultData.treemapThemeData)); - properties.add(DiagnosticsProperty( - 'chatThemeData', chatThemeData, - defaultValue: defaultData.chatThemeData)); - properties.add(DiagnosticsProperty( - 'assistThemeData', assistThemeData, - defaultValue: defaultData.assistThemeData)); + properties.add( + EnumProperty( + 'brightness', + brightness, + defaultValue: defaultData.brightness, + ), + ); + properties.add( + DiagnosticsProperty( + 'pdfViewerThemeData', + pdfViewerThemeData, + defaultValue: defaultData.pdfViewerThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'chartThemeData', + chartThemeData, + defaultValue: defaultData.chartThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'sparkChartThemeData', + sparkChartThemeData, + defaultValue: defaultData.sparkChartThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'calendarThemeData', + calendarThemeData, + defaultValue: defaultData.calendarThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'dataGridThemeData', + dataGridThemeData, + defaultValue: defaultData.dataGridThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'dataPagerThemeData', + dataPagerThemeData, + defaultValue: defaultData.dataPagerThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'dateRangePickerThemeData', + dateRangePickerThemeData, + defaultValue: defaultData.dateRangePickerThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'barcodeThemeData', + barcodeThemeData, + defaultValue: defaultData.barcodeThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'gaugeThemeData', + gaugeThemeData, + defaultValue: defaultData.gaugeThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangeSelectorThemeData', + rangeSelectorThemeData, + defaultValue: defaultData.rangeSelectorThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'rangeSliderThemeData', + rangeSliderThemeData, + defaultValue: defaultData.rangeSliderThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'sliderThemeData', + sliderThemeData, + defaultValue: defaultData.sliderThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'mapsThemeData', + mapsThemeData, + defaultValue: defaultData.mapsThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'treemapThemeData', + treemapThemeData, + defaultValue: defaultData.treemapThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'chatThemeData', + chatThemeData, + defaultValue: defaultData.chatThemeData, + ), + ); + properties.add( + DiagnosticsProperty( + 'assistThemeData', + assistThemeData, + defaultValue: defaultData.assistThemeData, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/theme/treemap_theme.dart b/packages/syncfusion_flutter_core/lib/src/theme/treemap_theme.dart index ca5e842c6..a77d2491d 100644 --- a/packages/syncfusion_flutter_core/lib/src/theme/treemap_theme.dart +++ b/packages/syncfusion_flutter_core/lib/src/theme/treemap_theme.dart @@ -29,7 +29,7 @@ import '../../theme.dart'; class SfTreemapTheme extends InheritedTheme { ///Initialize the class of SfTreemapTheme const SfTreemapTheme({Key? key, required this.data, required this.child}) - : super(key: key, child: child); + : super(key: key, child: child); /// Specifies the color and typography values for descendant Treemap widgets. /// @@ -121,9 +121,7 @@ class SfTreemapThemeData with Diagnosticable { /// This will rarely be used directly. It is used by [lerp] to /// create intermediate themes based on two themes created with the /// [SfTreemapThemeData] constructor. - const SfTreemapThemeData({ - this.legendTextStyle, - }); + const SfTreemapThemeData({this.legendTextStyle}); ///Initialize the sfTreemap theme data factory SfTreemapThemeData.raw({ @@ -163,19 +161,27 @@ class SfTreemapThemeData with Diagnosticable { TextStyle? legendTextStyle, }) { return SfTreemapThemeData.raw( - brightness: brightness, - legendTextStyle: legendTextStyle ?? this.legendTextStyle); + brightness: brightness, + legendTextStyle: legendTextStyle ?? this.legendTextStyle, + ); } /// Returns the treemap theme data static SfTreemapThemeData? lerp( - SfTreemapThemeData? a, SfTreemapThemeData? b, double t) { + SfTreemapThemeData? a, + SfTreemapThemeData? b, + double t, + ) { if (a == null && b == null) { return null; } return SfTreemapThemeData( - legendTextStyle: - TextStyle.lerp(a!.legendTextStyle, b!.legendTextStyle, t)); + legendTextStyle: TextStyle.lerp( + a!.legendTextStyle, + b!.legendTextStyle, + t, + ), + ); } @override @@ -201,8 +207,12 @@ class SfTreemapThemeData with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); const SfTreemapThemeData defaultData = SfTreemapThemeData(); - properties.add(DiagnosticsProperty( - 'legendTextStyle', legendTextStyle, - defaultValue: defaultData.legendTextStyle)); + properties.add( + DiagnosticsProperty( + 'legendTextStyle', + legendTextStyle, + defaultValue: defaultData.legendTextStyle, + ), + ); } } diff --git a/packages/syncfusion_flutter_core/lib/src/tooltip/tooltip.dart b/packages/syncfusion_flutter_core/lib/src/tooltip/tooltip.dart index f94a952da..2befed42d 100644 --- a/packages/syncfusion_flutter_core/lib/src/tooltip/tooltip.dart +++ b/packages/syncfusion_flutter_core/lib/src/tooltip/tooltip.dart @@ -8,28 +8,28 @@ part of tooltip_internal; class SfTooltip extends StatefulWidget { /// Creating an argument constructor of SfTooltip class. // ignore: prefer_const_constructors_in_immutables - SfTooltip( - {this.textStyle = const TextStyle(), - this.animationDuration = 500, - this.animationCurve = const Interval(0.0, 1.0), - this.enable = true, - this.opacity = 1, - this.borderColor = Colors.black, - this.borderWidth = 0, - this.duration = 3000, - this.shouldAlwaysShow = false, - this.elevation = 0, - this.canShowMarker = true, - this.textAlignment = TooltipAlignment.near, - this.decimalPlaces = 2, - this.color = Colors.black, - this.labelColor = Colors.white, - this.header, - this.format, - this.shadowColor, - Key? key, - this.onTooltipRender}) - : super(key: key); + SfTooltip({ + this.textStyle = const TextStyle(), + this.animationDuration = 500, + this.animationCurve = const Interval(0.0, 1.0), + this.enable = true, + this.opacity = 1, + this.borderColor = Colors.black, + this.borderWidth = 0, + this.duration = 3000, + this.shouldAlwaysShow = false, + this.elevation = 0, + this.canShowMarker = true, + this.textAlignment = TooltipAlignment.near, + this.decimalPlaces = 2, + this.color = Colors.black, + this.labelColor = Colors.white, + this.header, + this.format, + this.shadowColor, + Key? key, + this.onTooltipRender, + }) : super(key: key); ///Toggles the visibility of the tooltip. /// @@ -178,13 +178,14 @@ class SfTooltipState extends State /// *template - the widget that will be rendered instead of default tooltip /// *tooltipData - the data which allows this widget to decide whether it is /// activated for the same point - void show( - {int? duration, - Offset? position, - Object? tooltipData, - String? tooltipContent, - String? tooltipHeader, - Widget? template}) { + void show({ + int? duration, + Offset? position, + Object? tooltipData, + String? tooltipContent, + String? tooltipHeader, + Widget? template, + }) { duration ??= widget.animationDuration; _hidden = false; animationController!.duration = Duration(milliseconds: duration); @@ -246,8 +247,9 @@ class SfTooltipState extends State _show = false; needMarker = widget.canShowMarker; animationController = AnimationController( - duration: Duration(milliseconds: widget.animationDuration), vsync: this) - ..addStatusListener(_animationStatusListener); + duration: Duration(milliseconds: widget.animationDuration), + vsync: this, + )..addStatusListener(_animationStatusListener); super.initState(); } @@ -259,11 +261,15 @@ class SfTooltipState extends State @override Widget build(BuildContext context) { - final Animation tooltipAnimation = - Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation( - parent: animationController!, - curve: widget.animationCurve, - )); + final Animation tooltipAnimation = Tween( + begin: 0.0, + end: 1.0, + ).animate( + CurvedAnimation( + parent: animationController!, + curve: widget.animationCurve, + ), + ); if (_show && !_didUpdate) { if (animationController?.status != AnimationStatus.forward) { animationController!.forward(from: 0.0); @@ -283,10 +289,11 @@ class SfTooltipState extends State return child!; }, child: TooltipRenderObject( - template: _template, - tooltipAnimation: tooltipAnimation, - tooltipState: this, - animationController: animationController!), + template: _template, + tooltipAnimation: tooltipAnimation, + tooltipState: this, + animationController: animationController!, + ), ); } @@ -315,16 +322,16 @@ class SfTooltipState extends State class TooltipRenderObject extends SingleChildRenderObjectWidget { /// Creating an argument constructor of TooltipRenderObject class. // ignore: prefer_const_constructors_in_immutables - TooltipRenderObject( - {super.key, - Widget? template, - required SfTooltipState tooltipState, - required Animation tooltipAnimation, - required AnimationController animationController}) - : _tooltipState = tooltipState, - _tooltipAnimation = tooltipAnimation, - _animationController = animationController, - super(child: template); + TooltipRenderObject({ + super.key, + Widget? template, + required SfTooltipState tooltipState, + required Animation tooltipAnimation, + required AnimationController animationController, + }) : _tooltipState = tooltipState, + _tooltipAnimation = tooltipAnimation, + _animationController = animationController, + super(child: template); final SfTooltipState _tooltipState; final Animation _tooltipAnimation; @@ -333,7 +340,10 @@ class TooltipRenderObject extends SingleChildRenderObjectWidget { @override TooltipRenderBox createRenderObject(BuildContext context) { _tooltipState.renderBox = TooltipRenderBox( - _tooltipState, _tooltipAnimation, _animationController); + _tooltipState, + _tooltipAnimation, + _animationController, + ); return _tooltipState.renderBox!; } @@ -351,9 +361,11 @@ class TooltipRenderObject extends SingleChildRenderObjectWidget { class TooltipRenderBox extends RenderShiftedBox { /// Creating an argument constructor of TooltipRenderBox class. TooltipRenderBox( - this._tooltipState, this._tooltipAnimation, this._animationController, - [RenderBox? child]) - : super(child); + this._tooltipState, + this._tooltipAnimation, + this._animationController, [ + RenderBox? child, + ]) : super(child); SfTooltip get _tooltip => _tooltipState.widget; SfTooltipState _tooltipState; @@ -489,12 +501,15 @@ class TooltipRenderBox extends RenderShiftedBox { if (child == null || _tooltipRect == null) { return false; } else { - return child!.hitTest(result, - position: position - - (_isOutOfBoundInTop - ? _tooltipRect!.topLeft + - Offset(0, _templateArrowHeight + _tooltipRect!.height) - : _tooltipRect!.topLeft)); + return child!.hitTest( + result, + position: + position - + (_isOutOfBoundInTop + ? _tooltipRect!.topLeft + + Offset(0, _templateArrowHeight + _tooltipRect!.height) + : _tooltipRect!.topLeft), + ); } } @@ -507,18 +522,21 @@ class TooltipRenderBox extends RenderShiftedBox { size = Size.copy(child!.size); } } else { - size = Size(constraints.maxWidth.isFinite ? constraints.maxWidth : 0, - constraints.maxHeight.isFinite ? constraints.maxHeight : 0); + size = Size( + constraints.maxWidth.isFinite ? constraints.maxWidth : 0, + constraints.maxHeight.isFinite ? constraints.maxHeight : 0, + ); child?.layout(constraints); } } @override void paint(PaintingContext context, Offset offset) { - final Offset parentOffset = parentData is BoxParentData - //ignore: avoid_as - ? (parentData! as BoxParentData).offset - : Offset.zero; + final Offset parentOffset = + parentData is BoxParentData + //ignore: avoid_as + ? (parentData! as BoxParentData).offset + : Offset.zero; final Offset relativeOffset = offset - parentOffset; calculateLocation(_position != null ? (_position!) : parentOffset); context.canvas.translate(relativeOffset.dx, relativeOffset.dy); @@ -527,8 +545,11 @@ class TooltipRenderBox extends RenderShiftedBox { _tooltipState._showDuration == 0) && _animationController.status != AnimationStatus.dismissed) && _tooltipState.widget.onTooltipRender != null) { - final TooltipRenderArgs tooltipRenderArgs = TooltipRenderArgs(_header, - _stringValue, _x != null && _y != null ? Offset(_x!, _y!) : null); + final TooltipRenderArgs tooltipRenderArgs = TooltipRenderArgs( + _header, + _stringValue, + _x != null && _y != null ? Offset(_x!, _y!) : null, + ); _tooltipState.widget.onTooltipRender!(tooltipRenderArgs); _x = tooltipRenderArgs.location!.dx; _y = tooltipRenderArgs.location!.dy; @@ -550,18 +571,24 @@ class TooltipRenderBox extends RenderShiftedBox { void _renderTemplateTooltipView(PaintingContext context, Offset offset) { _templateSize = Size.copy(child!.size); _tooltipRect = Rect.fromLTWH( - _x! - _templateSize.width / 2, - _y! - _templateSize.height - _templateArrowHeight, - _templateSize.width, - _templateSize.height); + _x! - _templateSize.width / 2, + _y! - _templateSize.height - _templateArrowHeight, + _templateSize.width, + _templateSize.height, + ); double top = _y!; double paddingTop = 0; final Rect bounds = _boundaryRect.translate(-offset.dx, -offset.dy); - final Offset tooltipLocation = - _getTemplateLocation(_tooltipRect!, bounds, offset); - Offset arrowLocation = Offset(_x! - _templateSize.width / 2, - _isOutOfBoundInTop ? _y! : _y! - _templateArrowHeight); + final Offset tooltipLocation = _getTemplateLocation( + _tooltipRect!, + bounds, + offset, + ); + Offset arrowLocation = Offset( + _x! - _templateSize.width / 2, + _isOutOfBoundInTop ? _y! : _y! - _templateArrowHeight, + ); if (_y! < bounds.top + offset.dy) { paddingTop = bounds.top + offset.dy + _templateArrowHeight; top = tooltipLocation.dy; @@ -571,53 +598,70 @@ class TooltipRenderBox extends RenderShiftedBox { if (_y! >= bounds.top + offset.dy) { paddingTop = top; } - final Offset renderOffset = (_isOutOfBoundInTop + final Offset renderOffset = + (_isOutOfBoundInTop ? Offset(tooltipLocation.dx, tooltipLocation.dy + paddingTop) : tooltipLocation) + offset; - context.pushTransform(true, Offset(_x!, arrowLocation.dy) + offset, - Matrix4.diagonal3Values(_animationFactor, _animationFactor, 1), - (PaintingContext tooltipTemplateContext, Offset tooltipTemplateOffset) { - _renderArrowAndTemplatePath( - tooltipTemplateContext.canvas, arrowLocation + offset, renderOffset); - tooltipTemplateContext.paintChild(child!, renderOffset); - }); + context.pushTransform( + true, + Offset(_x!, arrowLocation.dy) + offset, + Matrix4.diagonal3Values(_animationFactor, _animationFactor, 1), + (PaintingContext tooltipTemplateContext, Offset tooltipTemplateOffset) { + _renderArrowAndTemplatePath( + tooltipTemplateContext.canvas, + arrowLocation + offset, + renderOffset, + ); + tooltipTemplateContext.paintChild(child!, renderOffset); + }, + ); } /// This method renders the path for tooltip template mode void _renderArrowAndTemplatePath( - Canvas canvas, Offset location, Offset templateLocation) { - final Paint strokePaint = Paint() - ..style = PaintingStyle.stroke - ..color = - _tooltip.borderWidth == 0 ? Colors.transparent : _tooltip.borderColor - ..strokeWidth = _tooltip.borderWidth; - final Paint fillPaint = Paint() - ..color = (_tooltip.color).withValues(alpha: _tooltip.opacity) - ..style = PaintingStyle.fill; + Canvas canvas, + Offset location, + Offset templateLocation, + ) { + final Paint strokePaint = + Paint() + ..style = PaintingStyle.stroke + ..color = + _tooltip.borderWidth == 0 + ? Colors.transparent + : _tooltip.borderColor + ..strokeWidth = _tooltip.borderWidth; + final Paint fillPaint = + Paint() + ..color = (_tooltip.color).withValues(alpha: _tooltip.opacity) + ..style = PaintingStyle.fill; const double currentHeight = 5.0; const double arrowWidth = 8; const double padding = 0.1; final Size currentSize = Size(_templateSize.width, currentHeight); final num templateHeight = _templateSize.height; final num arrowHeight = currentSize.height + padding; - final num centerTemplateY = _isOutOfBoundInTop - ? location.dy + currentSize.height + templateHeight / 2 + padding - : location.dy - templateHeight / 2 - padding; - double locationY = _isOutOfBoundInTop - ? centerTemplateY - (templateHeight / 2) - arrowHeight - : centerTemplateY + templateHeight / 2; + final num centerTemplateY = + _isOutOfBoundInTop + ? location.dy + currentSize.height + templateHeight / 2 + padding + : location.dy - templateHeight / 2 - padding; + double locationY = + _isOutOfBoundInTop + ? centerTemplateY - (templateHeight / 2) - arrowHeight + : centerTemplateY + templateHeight / 2; final num centerX = location.dx + currentSize.width / 2; final Path path = Path(); final RRect rect = RRect.fromLTRBAndCorners( - templateLocation.dx, - templateLocation.dy, - templateLocation.dx + _templateSize.width, - templateLocation.dy + _templateSize.height, - topLeft: Radius.circular(_borderRadius), - topRight: Radius.circular(_borderRadius), - bottomRight: Radius.circular(_borderRadius), - bottomLeft: Radius.circular(_borderRadius)); + templateLocation.dx, + templateLocation.dy, + templateLocation.dx + _templateSize.width, + templateLocation.dy + _templateSize.height, + topLeft: Radius.circular(_borderRadius), + topRight: Radius.circular(_borderRadius), + bottomRight: Radius.circular(_borderRadius), + bottomLeft: Radius.circular(_borderRadius), + ); bool isVTypeArrow = true; final String side = (centerX < rect.left + rect.width / 2) ? 'left' : 'right'; @@ -625,11 +669,17 @@ class TooltipRenderBox extends RenderShiftedBox { locationY += arrowHeight - padding; } path.moveTo(rect.left + rect.tlRadiusX, rect.top); - path.arcToPoint(Offset(rect.left, rect.top + rect.tlRadiusY), - radius: rect.tlRadius, clockwise: false); + path.arcToPoint( + Offset(rect.left, rect.top + rect.tlRadiusY), + radius: rect.tlRadius, + clockwise: false, + ); path.lineTo(rect.left, rect.bottom - rect.blRadiusY); - path.arcToPoint(Offset(rect.left + rect.blRadiusX, rect.bottom), - radius: rect.blRadius, clockwise: false); + path.arcToPoint( + Offset(rect.left + rect.blRadiusX, rect.bottom), + radius: rect.blRadius, + clockwise: false, + ); if ((centerX > rect.left + rect.blRadiusX + arrowWidth / 2) && (centerX < rect.right - rect.brRadiusX - arrowWidth / 2)) { path.lineTo(centerX - arrowWidth / 2, rect.bottom); @@ -643,19 +693,26 @@ class TooltipRenderBox extends RenderShiftedBox { //bottom arrow path.lineTo(centerX.toDouble(), locationY); path.lineTo( - isVTypeArrow - ? (centerX + arrowWidth / 2) - : side == 'left' - ? (rect.left + rect.blRadiusX + arrowWidth * 2) - : (rect.right - rect.brRadiusX), - rect.bottom); + isVTypeArrow + ? (centerX + arrowWidth / 2) + : side == 'left' + ? (rect.left + rect.blRadiusX + arrowWidth * 2) + : (rect.right - rect.brRadiusX), + rect.bottom, + ); } path.lineTo(rect.right - rect.brRadiusX, rect.bottom); - path.arcToPoint(Offset(rect.right, rect.bottom - rect.brRadiusY), - radius: rect.brRadius, clockwise: false); + path.arcToPoint( + Offset(rect.right, rect.bottom - rect.brRadiusY), + radius: rect.brRadius, + clockwise: false, + ); path.lineTo(rect.right, rect.top + rect.trRadiusY); - path.arcToPoint(Offset(rect.right - rect.brRadiusX, rect.top), - radius: rect.trRadius, clockwise: false); + path.arcToPoint( + Offset(rect.right - rect.brRadiusX, rect.top), + radius: rect.trRadius, + clockwise: false, + ); if (isVTypeArrow) { path.lineTo(centerX + arrowWidth / 2, rect.top); } else { @@ -667,12 +724,13 @@ class TooltipRenderBox extends RenderShiftedBox { //top arrow path.lineTo(centerX.toDouble(), locationY); path.lineTo( - isVTypeArrow - ? (centerX - arrowWidth / 2) - : side == 'left' - ? (rect.left + rect.blRadiusX) - : (rect.right - rect.brRadiusX - arrowWidth * 2), - rect.top); + isVTypeArrow + ? (centerX - arrowWidth / 2) + : side == 'left' + ? (rect.left + rect.blRadiusX) + : (rect.right - rect.brRadiusX - arrowWidth * 2), + rect.top, + ); } path.lineTo(rect.left + rect.tlRadiusX, rect.top); @@ -696,14 +754,16 @@ class TooltipRenderBox extends RenderShiftedBox { _totalWidth = _boundaryRect.left + _boundaryRect.width; //ignore: prefer_final_locals TextStyle style = _tooltip.textStyle; - final TextStyle textStyle = - style.copyWith(color: style.color ?? _tooltip.labelColor); + final TextStyle textStyle = style.copyWith( + color: style.color ?? _tooltip.labelColor, + ); width = measureText(_stringValue!, textStyle).width; height = measureText(_stringValue!, textStyle).height; if (_header!.isNotEmpty) { final TextStyle headerTextStyle = style.copyWith( - color: style.color ?? _tooltip.labelColor, - fontWeight: FontWeight.bold); + color: style.color ?? _tooltip.labelColor, + fontWeight: FontWeight.bold, + ); headerTextWidth = measureText(_header!, headerTextStyle).width; headerTextHeight = measureText(_header!, headerTextStyle).height + 10; width = width > headerTextWidth ? width : headerTextWidth; @@ -720,33 +780,42 @@ class TooltipRenderBox extends RenderShiftedBox { _y != null && (_inversePadding != null || _normalPadding != null) && (_stringValue != '' || _header != '')) { - final Rect backRect = - _calculateBackgroundRect(canvas, height, width, headerTextHeight); + final Rect backRect = _calculateBackgroundRect( + canvas, + height, + width, + headerTextHeight, + ); final double startArrow = _pointerLength / 2; final double endArrow = _pointerLength / 2; final double xPosition = _nosePointX; final double yPosition = _nosePointY; _drawTooltipBackground( - canvas, - _isTop, - backRect, - xPosition, - yPosition, - xPosition - startArrow, - _isTop ? (yPosition - startArrow) : (yPosition + startArrow), - xPosition + endArrow, - _isTop ? (yPosition - endArrow) : (yPosition + endArrow), - _borderRadius, - _arrowPath, - _isLeft, - _isRight, - _tooltipAnimation); + canvas, + _isTop, + backRect, + xPosition, + yPosition, + xPosition - startArrow, + _isTop ? (yPosition - startArrow) : (yPosition + startArrow), + xPosition + endArrow, + _isTop ? (yPosition - endArrow) : (yPosition + endArrow), + _borderRadius, + _arrowPath, + _isLeft, + _isRight, + _tooltipAnimation, + ); } } /// calculate tooltip rect and arrow head for default tooltip mode Rect _calculateBackgroundRect( - Canvas canvas, double height, double width, double headerTextHeight) { + Canvas canvas, + double height, + double width, + double headerTextHeight, + ) { double widthPadding = 15; if (_tooltip.canShowMarker && _tooltipState.needMarker) { _markerSize = 5; @@ -754,19 +823,29 @@ class TooltipRenderBox extends RenderShiftedBox { } final Rect rect = Rect.fromLTWH( - _x!, - _y!, - width + (2 * _markerSize) + widthPadding, - height + headerTextHeight + 10); - final Rect newRect = Rect.fromLTWH(_boundaryRect.left + 20, - _boundaryRect.top, _boundaryRect.width - 40, _boundaryRect.height); + _x!, + _y!, + width + (2 * _markerSize) + widthPadding, + height + headerTextHeight + 10, + ); + final Rect newRect = Rect.fromLTWH( + _boundaryRect.left + 20, + _boundaryRect.top, + _boundaryRect.width - 40, + _boundaryRect.height, + ); final Rect leftRect = Rect.fromLTWH( - _boundaryRect.left - 5, - _boundaryRect.top - 20, - newRect.left - (_boundaryRect.left - 5), - _boundaryRect.height + 40); - final Rect rightRect = Rect.fromLTWH(newRect.right, _boundaryRect.top - 20, - (_boundaryRect.right + 5) + newRect.right, _boundaryRect.height + 40); + _boundaryRect.left - 5, + _boundaryRect.top - 20, + newRect.left - (_boundaryRect.left - 5), + _boundaryRect.height + 40, + ); + final Rect rightRect = Rect.fromLTWH( + newRect.right, + _boundaryRect.top - 20, + (_boundaryRect.right + 5) + newRect.right, + _boundaryRect.height + 40, + ); if (leftRect.contains(Offset(_x!, _y!))) { _isLeft = true; @@ -783,25 +862,29 @@ class TooltipRenderBox extends RenderShiftedBox { _nosePointY = rect.top - (_normalPadding ?? 0); _nosePointX = rect.left; final double tooltipRightEnd = _x! + (rect.width / 2); - _xPos = _xPos! < _boundaryRect.left - ? _boundaryRect.left - : tooltipRightEnd > _totalWidth + _xPos = + _xPos! < _boundaryRect.left + ? _boundaryRect.left + : tooltipRightEnd > _totalWidth ? _totalWidth - rect.width : _xPos; _yPos = _yPos! - (_pointerLength / 2); } else { _isTop = false; _xPos = _x! - (rect.width / 2); - _yPos = ((_y! >= _boundaryRect.top ? _y! : _boundaryRect.top) + + _yPos = + ((_y! >= _boundaryRect.top ? _y! : _boundaryRect.top) + _pointerLength / 2) + (_inversePadding ?? 0); _nosePointX = rect.left; - _nosePointY = (_y! >= _boundaryRect.top ? _y! : _boundaryRect.top) + + _nosePointY = + (_y! >= _boundaryRect.top ? _y! : _boundaryRect.top) + (_inversePadding ?? 0); final double tooltipRightEnd = _x! + (rect.width / 2); - _xPos = _xPos! < _boundaryRect.left - ? _boundaryRect.left - : tooltipRightEnd > _totalWidth + _xPos = + _xPos! < _boundaryRect.left + ? _boundaryRect.left + : tooltipRightEnd > _totalWidth ? _totalWidth - rect.width : _xPos; } @@ -816,20 +899,21 @@ class TooltipRenderBox extends RenderShiftedBox { /// This method renders the tooltip background on which the content is to be /// displayed void _drawTooltipBackground( - Canvas canvas, - bool isTop, - Rect rectF, - double xPosition, - double yPosition, - double startX, - double startY, - double endX, - double endY, - double borderRadius, - Path backgroundPath, - bool isLeft, - bool isRight, - Animation? tooltipAnimation) { + Canvas canvas, + bool isTop, + Rect rectF, + double xPosition, + double yPosition, + double startX, + double startY, + double endX, + double endY, + double borderRadius, + Path backgroundPath, + bool isLeft, + bool isRight, + Animation? tooltipAnimation, + ) { final double animationFactor = tooltipAnimation == null ? 1 : tooltipAnimation.value; backgroundPath.reset(); @@ -842,10 +926,11 @@ class TooltipRenderBox extends RenderShiftedBox { } final Rect rect = Rect.fromLTWH( - rectF.width / 2 + (rectF.left - rectF.width / 2 * animationFactor), - rectF.height / 2 + (rectF.top - rectF.height / 2 * animationFactor), - rectF.width * animationFactor, - rectF.height * animationFactor); + rectF.width / 2 + (rectF.left - rectF.width / 2 * animationFactor), + rectF.height / 2 + (rectF.top - rectF.height / 2 * animationFactor), + rectF.width * animationFactor, + rectF.height * animationFactor, + ); _tooltipRect = rect; @@ -856,11 +941,24 @@ class TooltipRenderBox extends RenderShiftedBox { topLeft: Radius.circular(borderRadius), topRight: Radius.circular(borderRadius), ); - _drawTooltipPath(canvas, tooltipRect, rect, backgroundPath, isTop, isLeft, - isRight, startX, endX, animationFactor, xPosition, yPosition); + _drawTooltipPath( + canvas, + tooltipRect, + rect, + backgroundPath, + isTop, + isLeft, + isRight, + startX, + endX, + animationFactor, + xPosition, + yPosition, + ); final TextStyle textStyle = _tooltip.textStyle.copyWith( - color: _tooltip.textStyle.color?.withValues(alpha: _tooltip.opacity) ?? + color: + _tooltip.textStyle.color?.withValues(alpha: _tooltip.opacity) ?? _tooltip.labelColor, fontSize: (_tooltip.textStyle.fontSize ?? 12.0) * animationFactor, ); @@ -871,8 +969,11 @@ class TooltipRenderBox extends RenderShiftedBox { _tooltipState.needMarker && _markerTypes.isNotEmpty) { if (_markerTypes.length == 1) { - final Offset markerPoint = - _getMarkerPosition(result, markerSize, tooltipRect); + final Offset markerPoint = _getMarkerPosition( + result, + markerSize, + tooltipRect, + ); _drawMarkers(markerPoint, canvas, animationFactor, 0); } else { double height = 0; @@ -883,10 +984,11 @@ class TooltipRenderBox extends RenderShiftedBox { str += textValues[i]; final Size result1 = measureText(str, textStyle); final Offset markerPoint = Offset( - _tooltipState._isRtl - ? tooltipRect.right - tooltipRect.width / 2 + result.width / 2 - : tooltipRect.left + tooltipRect.width / 2 - result.width / 2, - (_markerPointY + height) - markerSize); + _tooltipState._isRtl + ? tooltipRect.right - tooltipRect.width / 2 + result.width / 2 + : tooltipRect.left + tooltipRect.width / 2 - result.width / 2, + (_markerPointY + height) - markerSize, + ); textSize = result1; height += textSize.height; if (_markerTypes[i] != null) { @@ -901,94 +1003,124 @@ class TooltipRenderBox extends RenderShiftedBox { /// To get the marker offset. Offset _getMarkerPosition( - Size textSize, double markerSize, RRect tooltipRect) => - Offset( - _tooltipState._isRtl - ? tooltipRect.right - tooltipRect.width / 2 + textSize.width / 2 - : tooltipRect.left + tooltipRect.width / 2 - textSize.width / 2, - ((tooltipRect.top + tooltipRect.height) - textSize.height / 2) - - markerSize); + Size textSize, + double markerSize, + RRect tooltipRect, + ) => Offset( + _tooltipState._isRtl + ? tooltipRect.right - tooltipRect.width / 2 + textSize.width / 2 + : tooltipRect.left + tooltipRect.width / 2 - textSize.width / 2, + ((tooltipRect.top + tooltipRect.height) - textSize.height / 2) - markerSize, + ); /// This method renders the tooltip marker shapes at the specific line indices /// of the marker paint list void _drawMarkers( - Offset markerPoint, Canvas canvas, double animationFactor, int i) { + Offset markerPoint, + Canvas canvas, + double animationFactor, + int i, + ) { if (_markerImages[i] == null) { final Path markerPath = _getMarkerShapesPath( _markerTypes[i]!, markerPoint, _markerImages[i], - Size((2 * _markerSize) * animationFactor, - (2 * _markerSize) * animationFactor), + Size( + (2 * _markerSize) * animationFactor, + (2 * _markerSize) * animationFactor, + ), ); if (_markerGradients![i] != null) { - _markerPaints[i] = Paint() - ..shader = _markerGradients![i]!.createShader( - _getMarkerShapesPath( - _markerTypes[i]!, - Offset(markerPoint.dx, markerPoint.dy), - _markerImages[i], - Size((2 * _markerSize) * animationFactor, - (2 * _markerSize) * animationFactor)) - .getBounds(), - ) - ..style = PaintingStyle.fill; + _markerPaints[i] = + Paint() + ..shader = _markerGradients![i]!.createShader( + _getMarkerShapesPath( + _markerTypes[i]!, + Offset(markerPoint.dx, markerPoint.dy), + _markerImages[i], + Size( + (2 * _markerSize) * animationFactor, + (2 * _markerSize) * animationFactor, + ), + ).getBounds(), + ) + ..style = PaintingStyle.fill; } canvas.drawPath(markerPath, _markerPaints[i]!); // ignore: omit_local_variable_types final Paint markerBorderPaint = Paint(); - markerBorderPaint.color = - Colors.white.withValues(alpha: _tooltip.opacity); + markerBorderPaint.color = Colors.white.withValues( + alpha: _tooltip.opacity, + ); markerBorderPaint.strokeWidth = 1; markerBorderPaint.style = PaintingStyle.stroke; canvas.drawPath(markerPath, markerBorderPaint); } else { _markerSize *= 2 * animationFactor; // ignore: omit_local_variable_types - final Rect positionRect = Rect.fromLTWH(markerPoint.dx - _markerSize / 2, - markerPoint.dy - _markerSize / 2, _markerSize, _markerSize); + final Rect positionRect = Rect.fromLTWH( + markerPoint.dx - _markerSize / 2, + markerPoint.dy - _markerSize / 2, + _markerSize, + _markerSize, + ); paintImage( - canvas: canvas, - image: _markerImages[i], - rect: positionRect, - fit: BoxFit.fill); + canvas: canvas, + image: _markerImages[i], + rect: positionRect, + fit: BoxFit.fill, + ); } } /// This method renders the tooltip rect and arrow for default tooltip mode void _drawTooltipPath( - Canvas canvas, - RRect tooltipRect, - Rect rect, - Path backgroundPath, - bool isTop, - bool isLeft, - bool isRight, - double startX, - double endX, - double animationFactor, - double xPosition, - double yPosition) { + Canvas canvas, + RRect tooltipRect, + Rect rect, + Path backgroundPath, + bool isTop, + bool isLeft, + bool isRight, + double startX, + double endX, + double animationFactor, + double xPosition, + double yPosition, + ) { double factor = 0; - assert(_tooltip.elevation >= 0, - 'The elevation of the tooltip for all series must not be less than 0.'); + assert( + _tooltip.elevation >= 0, + 'The elevation of the tooltip for all series must not be less than 0.', + ); if (isRight) { factor = isTop ? rect.bottom : rect.top; backgroundPath.moveTo(rect.right - 20, factor); backgroundPath.lineTo(xPosition, yPosition); - backgroundPath.lineTo(rect.right, - isTop ? (factor - _borderRadius) : (factor + _borderRadius)); - backgroundPath.arcToPoint(Offset(rect.right - _borderRadius, factor), - radius: Radius.circular(_borderRadius), clockwise: isTop); + backgroundPath.lineTo( + rect.right, + isTop ? (factor - _borderRadius) : (factor + _borderRadius), + ); + backgroundPath.arcToPoint( + Offset(rect.right - _borderRadius, factor), + radius: Radius.circular(_borderRadius), + clockwise: isTop, + ); backgroundPath.lineTo(rect.right - 20, factor); } else if (isLeft) { factor = isTop ? rect.bottom : rect.top; backgroundPath.moveTo(rect.left + 20, factor); backgroundPath.lineTo(xPosition, yPosition); - backgroundPath.lineTo(rect.left, - isTop ? (factor - _borderRadius) : (factor + _borderRadius)); - backgroundPath.arcToPoint(Offset(rect.left + _borderRadius, factor), - radius: Radius.circular(_borderRadius), clockwise: !isTop); + backgroundPath.lineTo( + rect.left, + isTop ? (factor - _borderRadius) : (factor + _borderRadius), + ); + backgroundPath.arcToPoint( + Offset(rect.left + _borderRadius, factor), + radius: Radius.circular(_borderRadius), + clockwise: !isTop, + ); backgroundPath.lineTo(rect.left + 20, factor); } else { factor = isTop ? tooltipRect.bottom : tooltipRect.top; @@ -997,18 +1129,21 @@ class TooltipRenderBox extends RenderShiftedBox { backgroundPath.lineTo(endX + ((endX - startX) / 4), factor); backgroundPath.lineTo(startX + ((endX - startX) / 4), factor); } - final Paint fillPaint = Paint() - ..color = (_tooltip.color).withValues(alpha: _tooltip.opacity) - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.fill; - - final Paint strokePaint = Paint() - ..color = _tooltip.borderColor == Colors.transparent - ? Colors.transparent - : _tooltip.borderColor.withValues(alpha: _tooltip.opacity) - ..strokeCap = StrokeCap.butt - ..style = PaintingStyle.stroke - ..strokeWidth = _tooltip.borderWidth; + final Paint fillPaint = + Paint() + ..color = (_tooltip.color).withValues(alpha: _tooltip.opacity) + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.fill; + + final Paint strokePaint = + Paint() + ..color = + _tooltip.borderColor == Colors.transparent + ? Colors.transparent + : _tooltip.borderColor.withValues(alpha: _tooltip.opacity) + ..strokeCap = StrokeCap.butt + ..style = PaintingStyle.stroke + ..strokeWidth = _tooltip.borderWidth; _tooltip.borderWidth == 0 ? strokePaint.color = Colors.transparent : strokePaint.color = strokePaint.color; @@ -1017,11 +1152,19 @@ class TooltipRenderBox extends RenderShiftedBox { tooltipPath.addRRect(tooltipRect); if (_tooltip.elevation > 0) { if (tooltipRect.width * animationFactor > tooltipRect.width * 0.85) { - canvas.drawShadow(_arrowPath, _tooltip.shadowColor ?? fillPaint.color, - _tooltip.elevation, true); + canvas.drawShadow( + _arrowPath, + _tooltip.shadowColor ?? fillPaint.color, + _tooltip.elevation, + true, + ); } - canvas.drawShadow(tooltipPath, _tooltip.shadowColor ?? fillPaint.color, - _tooltip.elevation, true); + canvas.drawShadow( + tooltipPath, + _tooltip.shadowColor ?? fillPaint.color, + _tooltip.elevation, + true, + ); } if (tooltipRect.width * animationFactor > tooltipRect.width * 0.85) { @@ -1034,37 +1177,46 @@ class TooltipRenderBox extends RenderShiftedBox { /// This method renders the tooltip header text, content text and the divider /// line for default tooltip mode - void _drawTooltipText(Canvas canvas, RRect tooltipRect, TextStyle textStyle, - Size result, double animationFactor) { + void _drawTooltipText( + Canvas canvas, + RRect tooltipRect, + TextStyle textStyle, + Size result, + double animationFactor, + ) { const double padding = 10; final int maxLinesOfTooltipContent = getMaxLinesContent(_stringValue); if (_header!.isNotEmpty) { final TextStyle headerTextStyle = _tooltip.textStyle.copyWith( - color: textStyle.color?.withValues(alpha: _tooltip.opacity) ?? + color: + textStyle.color?.withValues(alpha: _tooltip.opacity) ?? _tooltip.labelColor, fontSize: (textStyle.fontSize ?? 12) * animationFactor, fontWeight: FontWeight.bold, ); final Size headerResult = measureText(_header!, headerTextStyle); - _markerPointY = tooltipRect.top + + _markerPointY = + tooltipRect.top + ((_header!.isNotEmpty) ? headerResult.height + (padding * 2) + 6 : (padding * 1.7)); final int maxLinesOfHeader = getMaxLinesContent(_header); _drawText( - _tooltip, - canvas, - _header!, - Offset( - (tooltipRect.left + tooltipRect.width / 2) - - headerResult.width / 2, - tooltipRect.top + padding / 2), - headerTextStyle, - maxLines: maxLinesOfHeader); + _tooltip, + canvas, + _header!, + Offset( + (tooltipRect.left + tooltipRect.width / 2) - headerResult.width / 2, + tooltipRect.top + padding / 2, + ), + headerTextStyle, + maxLines: maxLinesOfHeader, + ); final Paint dividerPaint = Paint(); - dividerPaint.color = - _tooltip.labelColor.withValues(alpha: _tooltip.opacity); + dividerPaint.color = _tooltip.labelColor.withValues( + alpha: _tooltip.opacity, + ); dividerPaint.strokeWidth = 0.5 * animationFactor; dividerPaint.style = PaintingStyle.stroke; num lineOffset = 0; @@ -1077,25 +1229,45 @@ class TooltipRenderBox extends RenderShiftedBox { } if (animationFactor > 0.5) { canvas.drawLine( - Offset(tooltipRect.left + padding - lineOffset, - tooltipRect.top + headerResult.height + padding), - Offset(tooltipRect.right - padding - lineOffset, - tooltipRect.top + headerResult.height + padding), - dividerPaint); + Offset( + tooltipRect.left + padding - lineOffset, + tooltipRect.top + headerResult.height + padding, + ), + Offset( + tooltipRect.right - padding - lineOffset, + tooltipRect.top + headerResult.height + padding, + ), + dividerPaint, + ); } } _renderTooltipText( - canvas, tooltipRect, result, textStyle, maxLinesOfTooltipContent); + canvas, + tooltipRect, + result, + textStyle, + maxLinesOfTooltipContent, + ); } - void _renderTooltipText(Canvas canvas, RRect tooltipRect, Size textSize, - TextStyle textStyle, int maxLines) { + void _renderTooltipText( + Canvas canvas, + RRect tooltipRect, + Size textSize, + TextStyle textStyle, + int maxLines, + ) { if (_tooltipState._isRtl && _stringValue!.contains('\n')) { - _drawMultiLineRtlText(_tooltip, canvas, _stringValue!, - _getTextPosition(textSize, tooltipRect, maxLines), textStyle, - markerSize: markerSize, - tooltipRect: tooltipRect, - totalTextSize: textSize); + _drawMultiLineRtlText( + _tooltip, + canvas, + _stringValue!, + _getTextPosition(textSize, tooltipRect, maxLines), + textStyle, + markerSize: markerSize, + tooltipRect: tooltipRect, + totalTextSize: textSize, + ); } else { _drawText( _tooltip, @@ -1115,7 +1287,8 @@ class TooltipRenderBox extends RenderShiftedBox { textOffsetX = tooltipRect.left + tooltipRect.width / 2 - textSize.width / 2; } else { - textOffsetX = tooltipRect.right - + textOffsetX = + tooltipRect.right - tooltipRect.width / 2 - textSize.width / 2 - 2 * markerSize; @@ -1123,34 +1296,46 @@ class TooltipRenderBox extends RenderShiftedBox { } else { textOffsetX = (tooltipRect.left + 2 * markerSize + tooltipRect.width / 2) - - textSize.width / 2; + textSize.width / 2; } return Offset( - textOffsetX, - _header!.isNotEmpty - ? (tooltipRect.top + tooltipRect.height) - textSize.height - 5 - : (tooltipRect.top + tooltipRect.height / 2) - textSize.height / 2); + textOffsetX, + _header!.isNotEmpty + ? (tooltipRect.top + tooltipRect.height) - textSize.height - 5 + : (tooltipRect.top + tooltipRect.height / 2) - textSize.height / 2, + ); } - void _drawMultiLineRtlText(SfTooltip tooltip, Canvas canvas, String text, - Offset point, TextStyle style, - {double? markerSize, RRect? tooltipRect, Size? totalTextSize}) { + void _drawMultiLineRtlText( + SfTooltip tooltip, + Canvas canvas, + String text, + Offset point, + TextStyle style, { + double? markerSize, + RRect? tooltipRect, + Size? totalTextSize, + }) { final List textCollections = text.split('\n'); - final double rectEndPointBeforeMarker = _getMarkerPosition( - totalTextSize ?? Size.zero, - markerSize ?? 0.0, - tooltipRect ?? RRect.zero) - .dx - + final double rectEndPointBeforeMarker = + _getMarkerPosition( + totalTextSize ?? Size.zero, + markerSize ?? 0.0, + tooltipRect ?? RRect.zero, + ).dx - (2 * (markerSize ?? 0.0)); for (int count = 0; count < textCollections.length; count++) { final Size currentTextSize = measureText(textCollections[count], style); _drawText( - tooltip, - canvas, - textCollections[count], - Offset(rectEndPointBeforeMarker - currentTextSize.width, - point.dy + (currentTextSize.height * count)), - style); + tooltip, + canvas, + textCollections[count], + Offset( + rectEndPointBeforeMarker - currentTextSize.width, + point.dy + (currentTextSize.height * count), + ), + style, + ); } } @@ -1182,18 +1367,21 @@ class TooltipRenderBox extends RenderShiftedBox { if (kIsWeb) { if (_animationFactor < 0.5) { style = style.copyWith( - color: style.color!.withValues(alpha: _animationFactor)); + color: style.color!.withValues(alpha: _animationFactor), + ); } else if (_animationFactor <= 1) { style = style.copyWith( - color: style.color!.withValues(alpha: tooltip.opacity)); + color: style.color!.withValues(alpha: tooltip.opacity), + ); } } final TextSpan span = TextSpan(text: text, style: style); final TextPainter tp = TextPainter( - text: span, - textDirection: TextDirection.ltr, - textAlign: tooltipTextAlign, - maxLines: maxLines ?? 1); + text: span, + textDirection: TextDirection.ltr, + textAlign: tooltipTextAlign, + maxLines: maxLines ?? 1, + ); tp.layout(); canvas.save(); canvas.translate(pointX, point.dy); @@ -1218,7 +1406,8 @@ class TooltipRenderBox extends RenderShiftedBox { } if (tooltipRect.left + tooltipRect.width > bounds.left + offset.dx + bounds.width) { - left = (bounds.left + bounds.width + offset.dx) - + left = + (bounds.left + bounds.width + offset.dx) - tooltipRect.width - padding; } @@ -1233,7 +1422,11 @@ class TooltipRenderBox extends RenderShiftedBox { /// This method returns the path of marker shapes at the position at which the /// marker needs to be rendered Path _getMarkerShapesPath( - DataMarkerType markerType, Offset position, dynamic image, Size size) { + DataMarkerType markerType, + Offset position, + dynamic image, + Size size, +) { final Path path = Path(); switch (markerType) { case DataMarkerType.circle: @@ -1257,19 +1450,34 @@ Path _getMarkerShapesPath( case DataMarkerType.verticalLine: { drawVerticalLine( - path, position.dx, position.dy, size.width, size.height); + path, + position.dx, + position.dy, + size.width, + size.height, + ); } break; case DataMarkerType.invertedTriangle: { drawInvertedTriangle( - path, position.dx, position.dy, size.width, size.height); + path, + position.dx, + position.dy, + size.width, + size.height, + ); } break; case DataMarkerType.horizontalLine: { drawHorizontalLine( - path, position.dx, position.dy, size.width, size.height); + path, + position.dx, + position.dy, + size.width, + size.height, + ); } break; case DataMarkerType.diamond: diff --git a/packages/syncfusion_flutter_core/lib/src/utils/helper.dart b/packages/syncfusion_flutter_core/lib/src/utils/helper.dart index 38952b662..794b5d779 100644 --- a/packages/syncfusion_flutter_core/lib/src/utils/helper.dart +++ b/packages/syncfusion_flutter_core/lib/src/utils/helper.dart @@ -29,7 +29,7 @@ enum TooltipAlignment { center, ///- TooltipAlignment.far, will align the tooltip content far from center. - far + far, } /// Data marker shapes. @@ -73,16 +73,17 @@ enum DataMarkerType { /// Draw the circle shape marker void drawCircle(Path path, double x, double y, double width, double height) { path.addArc( - Rect.fromLTRB( - x - width / 2, y - height / 2, x + width / 2, y + height / 2), - 0.0, - 2 * math.pi); + Rect.fromLTRB(x - width / 2, y - height / 2, x + width / 2, y + height / 2), + 0.0, + 2 * math.pi, + ); } /// Draw the Rectangle shape marker void drawRectangle(Path path, double x, double y, double width, double height) { - path.addRect(Rect.fromLTRB( - x - width / 2, y - height / 2, x + width / 2, y + height / 2)); + path.addRect( + Rect.fromLTRB(x - width / 2, y - height / 2, x + width / 2, y + height / 2), + ); } ///Draw the Pentagon shape marker @@ -102,14 +103,24 @@ void drawPentagon(Path path, double x, double y, double width, double height) { ///Draw the Vertical line shape marker void drawVerticalLine( - Path path, double x, double y, double width, double height) { + Path path, + double x, + double y, + double width, + double height, +) { path.moveTo(x, y + height / 2); path.lineTo(x, y - height / 2); } ///Draw the Inverted Triangle shape marker void drawInvertedTriangle( - Path path, double x, double y, double width, double height) { + Path path, + double x, + double y, + double width, + double height, +) { path.moveTo(x + width / 2, y - height / 2); path.lineTo(x, y + height / 2); @@ -120,7 +131,12 @@ void drawInvertedTriangle( ///Draw the Horizontal line shape marker void drawHorizontalLine( - Path path, double x, double y, double width, double height) { + Path path, + double x, + double y, + double width, + double height, +) { path.moveTo(x - width / 2, y); path.lineTo(x + width / 2, y); } @@ -148,9 +164,10 @@ void drawTriangle(Path path, double x, double y, double width, double height) { Size measureText(String textValue, TextStyle textStyle, [int? angle]) { Size size; final TextPainter textPainter = TextPainter( - textAlign: TextAlign.center, - textDirection: TextDirection.ltr, - text: TextSpan(text: textValue, style: textStyle)); + textAlign: TextAlign.center, + textDirection: TextDirection.ltr, + text: TextSpan(text: textValue, style: textStyle), + ); textPainter.layout(); if (angle != null) { @@ -165,8 +182,9 @@ Size measureText(String textValue, TextStyle textStyle, [int? angle]) { /// This method returns the rect for given size and angle Rect rotatedTextSize(Size size, int angle) { final Rect rect = Rect.fromLTWH(0, 0, size.width, size.height); - final vector.Matrix2 rotatorMatrix = - vector.Matrix2.rotation(degreeToRadian(angle)); + final vector.Matrix2 rotatorMatrix = vector.Matrix2.rotation( + degreeToRadian(angle), + ); final Rect movedToCenterAsOrigin = rect.shift(-rect.center); @@ -184,17 +202,21 @@ Rect rotatedTextSize(Size size, int angle) { topLeft, topRight, bottomLeft, - bottomRight + bottomRight, ]; - final double minX = - rotOffsets.map((Offset offset) => offset.dx).reduce(math.min); - final double maxX = - rotOffsets.map((Offset offset) => offset.dx).reduce(math.max); - final double minY = - rotOffsets.map((Offset offset) => offset.dy).reduce(math.min); - final double maxY = - rotOffsets.map((Offset offset) => offset.dy).reduce(math.max); + final double minX = rotOffsets + .map((Offset offset) => offset.dx) + .reduce(math.min); + final double maxX = rotOffsets + .map((Offset offset) => offset.dx) + .reduce(math.max); + final double minY = rotOffsets + .map((Offset offset) => offset.dy) + .reduce(math.min); + final double maxY = rotOffsets + .map((Offset offset) => offset.dy) + .reduce(math.max); final Rect rotateRect = Rect.fromPoints( Offset(minX, minY), @@ -214,10 +236,7 @@ vector.Vector2 offsetToVector2(Offset offset) => Offset vector2ToOffset(vector.Vector2 vector) => Offset(vector.x, vector.y); /// This method transforms the given offset with respect ot the given matrix -Offset transform( - vector.Matrix2 matrix, - Offset offset, -) { +Offset transform(vector.Matrix2 matrix, Offset offset) { return vector2ToOffset(matrix * offsetToVector2(offset)); } diff --git a/packages/syncfusion_flutter_core/lib/src/utils/shape_helper.dart b/packages/syncfusion_flutter_core/lib/src/utils/shape_helper.dart index bcf421012..556b03785 100644 --- a/packages/syncfusion_flutter_core/lib/src/utils/shape_helper.dart +++ b/packages/syncfusion_flutter_core/lib/src/utils/shape_helper.dart @@ -177,65 +177,69 @@ enum ShapeMarkerType { pyramidSeries, /// ShapeMarkerType.funnelSeries which draws the funnel series marker. - funnelSeries + funnelSeries, } /// Draws the different marker shapes. -void paint( - {required Canvas canvas, - required Rect rect, - required ShapeMarkerType shapeType, - required Paint paint, - ShapeMarkerType? overlayMarkerType, - Path? path, - double? elevation, - Color? elevationColor, - Paint? borderPaint, - double? degree, - double? startAngle, - double? endAngle}) { +void paint({ + required Canvas canvas, + required Rect rect, + required ShapeMarkerType shapeType, + required Paint paint, + ShapeMarkerType? overlayMarkerType, + Path? path, + double? elevation, + Color? elevationColor, + Paint? borderPaint, + double? degree, + double? startAngle, + double? endAngle, +}) { _processShapes( - canvas: canvas, - rect: rect, - shapeType: shapeType, - paint: paint, - path: path ?? Path(), - borderPaint: borderPaint, - isNeedToReturnPath: false, - elevation: elevation, - elevationColor: elevationColor, - overlayMarkerType: overlayMarkerType, - degree: degree, - startAngle: startAngle, - endAngle: endAngle); + canvas: canvas, + rect: rect, + shapeType: shapeType, + paint: paint, + path: path ?? Path(), + borderPaint: borderPaint, + isNeedToReturnPath: false, + elevation: elevation, + elevationColor: elevationColor, + overlayMarkerType: overlayMarkerType, + degree: degree, + startAngle: startAngle, + endAngle: endAngle, + ); } /// Get the various shape path -Path getShapesPath( - {Canvas? canvas, - Paint? paint, - Paint? borderPaint, - required Rect rect, - required ShapeMarkerType shapeType, - Path? path, - double? pentagonRotation = -pi / 2, - double? radius, - double? degree, - double? startAngle, - double? endAngle}) { +Path getShapesPath({ + Canvas? canvas, + Paint? paint, + Paint? borderPaint, + required Rect rect, + required ShapeMarkerType shapeType, + Path? path, + double? pentagonRotation = -pi / 2, + double? radius, + double? degree, + double? startAngle, + double? endAngle, +}) { return _processShapes( - canvas: canvas ?? Canvas(PictureRecorder()), - paint: paint ?? Paint(), - borderPaint: borderPaint, - rect: rect, - path: path ?? Path(), - shapeType: shapeType, - isNeedToReturnPath: true, - pentagonRotation: pentagonRotation, - radius: radius, - degree: degree, - startAngle: startAngle, - endAngle: endAngle); + canvas: canvas ?? Canvas(PictureRecorder()), + paint: paint ?? Paint(), + borderPaint: borderPaint, + rect: rect, + path: path ?? Path(), + shapeType: shapeType, + isNeedToReturnPath: true, + pentagonRotation: pentagonRotation, + radius: radius, + degree: degree, + startAngle: startAngle, + endAngle: endAngle, + ); } Paint _lineTypePaint(Paint fillPaint, {Paint? strokePaint}) { @@ -253,328 +257,360 @@ Paint _lineTypePaint(Paint fillPaint, {Paint? strokePaint}) { return paint; } -Path _processShapes( - {required Canvas canvas, - required Rect rect, - required ShapeMarkerType shapeType, - required Paint paint, - required bool isNeedToReturnPath, - required Path path, - ShapeMarkerType? overlayMarkerType, - double? elevation, - Color? elevationColor, - Paint? borderPaint, - double? pentagonRotation = -pi / 2, - double? radius, - double? degree, - double? startAngle, - double? endAngle}) { +Path _processShapes({ + required Canvas canvas, + required Rect rect, + required ShapeMarkerType shapeType, + required Paint paint, + required bool isNeedToReturnPath, + required Path path, + ShapeMarkerType? overlayMarkerType, + double? elevation, + Color? elevationColor, + Paint? borderPaint, + double? pentagonRotation = -pi / 2, + double? radius, + double? degree, + double? startAngle, + double? endAngle, +}) { switch (shapeType) { case ShapeMarkerType.circle: return _processCircleShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.rectangle: return _processRectangleShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.diamond: return _processDiamondShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.triangle: return _processTriangleShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.invertedTriangle: return _processInvertedTriangleShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.verticalTriangle: return _processVerticalTriangleShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.verticalInvertedTriangle: return _processVerticalInvertedTriangleShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.pentagon: return _processPentagonShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - rotation: pentagonRotation, - elevation: elevation, - elevationColor: elevationColor, - paint: paint, - borderPaint: borderPaint); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + rotation: pentagonRotation, + elevation: elevation, + elevationColor: elevationColor, + paint: paint, + borderPaint: borderPaint, + ); case ShapeMarkerType.verticalLine: return _processVerticalLineShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + ); case ShapeMarkerType.horizontalLine: return _processHorizontalLineShape( - canvas: canvas, - rect: rect, - path: path, - isNeedToReturnPath: isNeedToReturnPath, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null); + canvas: canvas, + rect: rect, + path: path, + isNeedToReturnPath: isNeedToReturnPath, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + ); case ShapeMarkerType.lineSeries: case ShapeMarkerType.fastLineSeries: case ShapeMarkerType.stackedLineSeries: case ShapeMarkerType.stackedLine100Series: return _processLineShape( - canvas: canvas, - path: path, - rect: rect, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath, - isNeedMarker: true, - overlayMarkerType: overlayMarkerType, - isDashArray: false); + canvas: canvas, + path: path, + rect: rect, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + isNeedMarker: true, + overlayMarkerType: overlayMarkerType, + isDashArray: false, + ); case ShapeMarkerType.lineSeriesWithDashArray: case ShapeMarkerType.fastLineSeriesWithDashArray: case ShapeMarkerType.stackedLineSeriesWithDashArray: case ShapeMarkerType.stackedLine100SeriesWithDashArray: return _processLineShape( - canvas: canvas, - path: path, - rect: rect, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath, - isNeedMarker: true, - overlayMarkerType: overlayMarkerType, - isDashArray: true); + canvas: canvas, + path: path, + rect: rect, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + isNeedMarker: true, + overlayMarkerType: overlayMarkerType, + isDashArray: true, + ); case ShapeMarkerType.splineSeries: return _processSplineShape( - canvas: canvas, - rect: rect, - path: path, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath, - isDashArray: false); + canvas: canvas, + rect: rect, + path: path, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + isDashArray: false, + ); case ShapeMarkerType.splineSeriesWithDashArray: return _processSplineShape( - canvas: canvas, - rect: rect, - path: path, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath, - isDashArray: true); + canvas: canvas, + rect: rect, + path: path, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + isDashArray: true, + ); case ShapeMarkerType.splineAreaSeries: case ShapeMarkerType.splineRangeAreaSeries: return _processSplineAreaShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.areaSeries: case ShapeMarkerType.stackedAreaSeries: case ShapeMarkerType.rangeAreaSeries: case ShapeMarkerType.stackedArea100Series: return _processAreaShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.stepAreaSeries: return _processStepAreaShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.stepLineSeries: return _processStepLineShape( - canvas: canvas, - rect: rect, - path: path, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath, - isDashArray: false); + canvas: canvas, + rect: rect, + path: path, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + isDashArray: false, + ); case ShapeMarkerType.stepLineSeriesWithDashArray: return _processStepLineShape( - canvas: canvas, - rect: rect, - path: path, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath, - isDashArray: true); + canvas: canvas, + rect: rect, + path: path, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + isDashArray: true, + ); case ShapeMarkerType.bubbleSeries: return _processBubbleShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.columnSeries: case ShapeMarkerType.stackedColumnSeries: case ShapeMarkerType.stackedColumn100Series: case ShapeMarkerType.rangeColumnSeries: case ShapeMarkerType.histogramSeries: return _processColumnShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.barSeries: case ShapeMarkerType.stackedBarSeries: case ShapeMarkerType.stackedBar100Series: return _processBarShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.hiloSeries: return _processHiloShape( - canvas: canvas, - rect: rect, - path: path, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.hiloOpenCloseSeries: case ShapeMarkerType.candleSeries: return _processHiloOpenCloseShape( - canvas: canvas, - rect: rect, - path: path, - paint: _lineTypePaint(paint, strokePaint: borderPaint), - shaderPaint: paint.shader != null ? paint : null, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: _lineTypePaint(paint, strokePaint: borderPaint), + shaderPaint: paint.shader != null ? paint : null, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.waterfallSeries: case ShapeMarkerType.boxAndWhiskerSeries: return _processWaterfallShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.pieSeries: return _processPieShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.doughnutSeries: return _processDoughnutShape( - canvas: canvas, - rect: rect, - radius: radius, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + radius: radius, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.radialBarSeries: return _processRadialBarShape( - rect: rect, - canvas: canvas, - radius: radius, - path: path, - paint: paint, - borderPaint: borderPaint, - degree: degree, - startAngle: startAngle, - endAngle: endAngle, - isNeedToReturnPath: isNeedToReturnPath); + rect: rect, + canvas: canvas, + radius: radius, + path: path, + paint: paint, + borderPaint: borderPaint, + degree: degree, + startAngle: startAngle, + endAngle: endAngle, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.pyramidSeries: return _processPyramidShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.funnelSeries: return _processFunnelShape( - canvas: canvas, - rect: rect, - path: path, - paint: paint, - borderPaint: borderPaint, - isNeedToReturnPath: isNeedToReturnPath); + canvas: canvas, + rect: rect, + path: path, + paint: paint, + borderPaint: borderPaint, + isNeedToReturnPath: isNeedToReturnPath, + ); case ShapeMarkerType.image: return Path(); } } /// Draw the circle shape marker. -Path _processCircleShape( - {required Canvas canvas, - required Rect rect, - required Paint paint, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - Paint? borderPaint}) { +Path _processCircleShape({ + required Canvas canvas, + required Rect rect, + required Paint paint, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + Paint? borderPaint, +}) { path.addOval(rect); if (isNeedToReturnPath) { @@ -596,15 +632,16 @@ Path _processCircleShape( } /// Draw the rectangle shape marker. -Path _processRectangleShape( - {required Canvas canvas, - required Rect rect, - required Paint paint, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - Paint? borderPaint}) { +Path _processRectangleShape({ + required Canvas canvas, + required Rect rect, + required Paint paint, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + Paint? borderPaint, +}) { path.addRect(rect); if (isNeedToReturnPath) { @@ -626,15 +663,16 @@ Path _processRectangleShape( } /// Draw the inverted triangle shape marker. -Path _processInvertedTriangleShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - required Paint paint, - Paint? borderPaint}) { +Path _processInvertedTriangleShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + required Paint paint, + Paint? borderPaint, +}) { path.moveTo(rect.left, rect.top); path.lineTo(rect.left + rect.width, rect.top); path.lineTo(rect.left + (rect.width / 2), rect.top + rect.height); @@ -660,15 +698,16 @@ Path _processInvertedTriangleShape( } /// Draw the triangle shape marker. -Path _processTriangleShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - required Paint paint, - Paint? borderPaint}) { +Path _processTriangleShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + required Paint paint, + Paint? borderPaint, +}) { path.moveTo(rect.left + (rect.width / 2), rect.top); path.lineTo(rect.left, rect.top + rect.height); path.lineTo(rect.left + rect.width, rect.top + rect.height); @@ -693,15 +732,16 @@ Path _processTriangleShape( } ///Draw the triangle shape marker -Path _processVerticalTriangleShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - required Paint paint, - Paint? borderPaint}) { +Path _processVerticalTriangleShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + required Paint paint, + Paint? borderPaint, +}) { path.moveTo(rect.left, rect.top + (rect.height / 2)); path.lineTo(rect.left + rect.width, rect.top); path.lineTo(rect.left + rect.width, rect.top + rect.height); @@ -726,15 +766,16 @@ Path _processVerticalTriangleShape( } ///Draw the vertical inverted triangle shape marker -Path _processVerticalInvertedTriangleShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - required Paint paint, - Paint? borderPaint}) { +Path _processVerticalInvertedTriangleShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + required Paint paint, + Paint? borderPaint, +}) { path.moveTo(rect.left, rect.top); path.lineTo(rect.left + rect.width, rect.top + (rect.height / 2)); path.lineTo(rect.left, rect.top + rect.height); @@ -759,15 +800,16 @@ Path _processVerticalInvertedTriangleShape( } /// Draw the diamond shape marker. -Path _processDiamondShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - required Paint paint, - Paint? borderPaint}) { +Path _processDiamondShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + required Paint paint, + Paint? borderPaint, +}) { path.moveTo(rect.left + rect.width / 2.0, rect.top); path.lineTo(rect.left, rect.top + rect.height / 2.0); path.lineTo(rect.left + rect.width / 2.0, rect.top + rect.height); @@ -794,16 +836,17 @@ Path _processDiamondShape( } ///Draw the pentagon shape marker -Path _processPentagonShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - double? elevation, - Color? elevationColor, - required Paint paint, - Paint? borderPaint, - double? rotation}) { +Path _processPentagonShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + double? elevation, + Color? elevationColor, + required Paint paint, + Paint? borderPaint, + double? rotation, +}) { const int numberOfSides = 5; final double left = rect.left + rect.width / 2; final double top = rect.top + rect.height / 2; @@ -833,13 +876,14 @@ Path _processPentagonShape( } /// Draw the vertical line shape marker. -Path _processVerticalLineShape( - {required Canvas canvas, - required bool isNeedToReturnPath, - required Path path, - required Rect rect, - required Paint? paint, - Paint? shaderPaint}) { +Path _processVerticalLineShape({ + required Canvas canvas, + required bool isNeedToReturnPath, + required Path path, + required Rect rect, + required Paint? paint, + Paint? shaderPaint, +}) { final double left = rect.left + rect.width / 2; final double top = rect.top + rect.height / 2; @@ -859,13 +903,14 @@ Path _processVerticalLineShape( } /// Draw the horizontal line shape marker. -Path _processHorizontalLineShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - required Paint? paint, - Paint? shaderPaint}) { +Path _processHorizontalLineShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + required Paint? paint, + Paint? shaderPaint, +}) { final double left = rect.left + rect.width / 2; final double top = rect.top + rect.height / 2; @@ -884,14 +929,15 @@ Path _processHorizontalLineShape( } /// Draw the step line series type. -Path _processStepLineShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? shaderPaint, - bool? isDashArray}) { +Path _processStepLineShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? shaderPaint, + bool? isDashArray, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -916,26 +962,34 @@ Path _processStepLineShape( if (paint != null) { paint.shader = shaderPaint != null ? shaderPaint.shader : paint.shader; canvas.drawPath( - isDashArray! - ? _processDashPath(path, - dashArray: _CircularIntervalList([3, 2])) - : path, - paint..style = PaintingStyle.stroke); + isDashArray! + ? _processDashPath( + path, + dashArray: _CircularIntervalList([3, 2]), + ) + : path, + paint..style = PaintingStyle.stroke, + ); } return path; } /// Draw the pie series type. -Path _processPieShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { - rect = - Rect.fromLTWH(rect.left, rect.top + 1, rect.width - 1, rect.height - 1); +Path _processPieShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { + rect = Rect.fromLTWH( + rect.left, + rect.top + 1, + rect.width - 1, + rect.height - 1, + ); final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -944,13 +998,21 @@ Path _processPieShape( final double r = min(height, width) / 2; path.moveTo(x, y); path.lineTo(x + r, y); - path.arcTo(Rect.fromCircle(center: Offset(x, y), radius: r), - _degreesToRadians(0), _degreesToRadians(270), false); + path.arcTo( + Rect.fromCircle(center: Offset(x, y), radius: r), + _degreesToRadians(0), + _degreesToRadians(270), + false, + ); path.close(); path.moveTo(x + width / 10, y - height / 10); path.lineTo(x + r, y - height / 10); - path.arcTo(Rect.fromCircle(center: Offset(x + 1, y - 1), radius: r), - _degreesToRadians(0), _degreesToRadians(-90), false); + path.arcTo( + Rect.fromCircle(center: Offset(x + 1, y - 1), radius: r), + _degreesToRadians(0), + _degreesToRadians(-90), + false, + ); path.close(); if (isNeedToReturnPath) { @@ -968,72 +1030,116 @@ Path _processPieShape( } /// Draw the doughnut series type. -Path _processDoughnutShape( - {required Canvas canvas, - required Rect rect, - required Path path, - required bool isNeedToReturnPath, - double? radius, - Paint? paint, - Paint? borderPaint}) { - rect = - Rect.fromLTWH(rect.left, rect.top + 1, rect.width - 1, rect.height - 1); +Path _processDoughnutShape({ + required Canvas canvas, + required Rect rect, + required Path path, + required bool isNeedToReturnPath, + double? radius, + Paint? paint, + Paint? borderPaint, +}) { + rect = Rect.fromLTWH( + rect.left, + rect.top + 1, + rect.width - 1, + rect.height - 1, + ); final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; late Path path1, path2; radius ??= (rect.width + rect.height) / 2; - final bool hasBorder = borderPaint != null && + final bool hasBorder = + borderPaint != null && borderPaint.color != Colors.transparent && borderPaint.strokeWidth > 0; if (isNeedToReturnPath) { if (hasBorder) { path1 = _getArcPath( - path, radius / 4, radius / 2, Offset(x, y), 0, 270, 270, true); + path, + radius / 4, + radius / 2, + Offset(x, y), + 0, + 270, + 270, + true, + ); } else { - path2 = _getArcPath(path, radius / 4, radius / 2, Offset(x + 1, y - 1), 0, - -90, -90, true); + path2 = _getArcPath( + path, + radius / 4, + radius / 2, + Offset(x + 1, y - 1), + 0, + -90, + -90, + true, + ); } return path; } path1 = _getArcPath( - path, radius / 4, radius / 2, Offset(x, y), 0, 270, 270, true); + path, + radius / 4, + radius / 2, + Offset(x, y), + 0, + 270, + 270, + true, + ); path2 = _getArcPath( - Path(), radius / 4, radius / 2, Offset(x + 1, y - 1), 0, -90, -90, true); + Path(), + radius / 4, + radius / 2, + Offset(x + 1, y - 1), + 0, + -90, + -90, + true, + ); canvas.drawPath(path1, paint!); if (hasBorder) { - canvas.drawPath(path1, - borderPaint..color = Colors.grey.shade300.withValues(alpha: 0.5)); + canvas.drawPath( + path1, + borderPaint..color = Colors.grey.shade300.withValues(alpha: 0.5), + ); } canvas.drawPath(path2, paint); if (hasBorder) { - canvas.drawPath(path2, - borderPaint..color = Colors.grey.shade300.withValues(alpha: 0.5)); + canvas.drawPath( + path2, + borderPaint..color = Colors.grey.shade300.withValues(alpha: 0.5), + ); } return path; } /// Draw the radial bar series type. -Path _processRadialBarShape( - {required Canvas canvas, - required Rect rect, - required Path path, - required bool isNeedToReturnPath, - double? degree, - double? startAngle, - double? endAngle, - double? radius, - Paint? paint, - Paint? borderPaint}) { +Path _processRadialBarShape({ + required Canvas canvas, + required Rect rect, + required Path path, + required bool isNeedToReturnPath, + double? degree, + double? startAngle, + double? endAngle, + double? radius, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; late Path path1, path2; - final bool hasBorder = borderPaint != null && + final bool hasBorder = + borderPaint != null && borderPaint.color != Colors.transparent && borderPaint.strokeWidth > 0; @@ -1041,30 +1147,65 @@ Path _processRadialBarShape( if (isNeedToReturnPath) { if (hasBorder) { - path1 = _getArcPath(path, (radius / 2) - 2, radius / 2, Offset(x, y), 0, - 360 - 0.01, 360 - 0.01, true); + path1 = _getArcPath( + path, + (radius / 2) - 2, + radius / 2, + Offset(x, y), + 0, + 360 - 0.01, + 360 - 0.01, + true, + ); } else { - path2 = _getArcPath(path, (radius / 2) - 2, radius / 2, Offset(x, y), - startAngle!, endAngle!, degree!, true); + path2 = _getArcPath( + path, + (radius / 2) - 2, + radius / 2, + Offset(x, y), + startAngle!, + endAngle!, + degree!, + true, + ); } return path; } - path1 = _getArcPath(path, (radius / 2) - 2, radius / 2, Offset(x, y), 0, - 360 - 0.01, 360 - 0.01, true); + path1 = _getArcPath( + path, + (radius / 2) - 2, + radius / 2, + Offset(x, y), + 0, + 360 - 0.01, + 360 - 0.01, + true, + ); - path2 = _getArcPath(Path(), (radius / 2) - 2, radius / 2, Offset(x, y), - startAngle!, endAngle!, degree!, true); + path2 = _getArcPath( + Path(), + (radius / 2) - 2, + radius / 2, + Offset(x, y), + startAngle!, + endAngle!, + degree!, + true, + ); if (hasBorder) { canvas.drawPath( - path1, - Paint() - ..color = Colors.grey.shade100 - ..strokeWidth = borderPaint.strokeWidth); + path1, + Paint() + ..color = Colors.grey.shade100 + ..strokeWidth = borderPaint.strokeWidth, + ); - canvas.drawPath(path1, - borderPaint..color = Colors.grey.shade300.withValues(alpha: 0.5)); + canvas.drawPath( + path1, + borderPaint..color = Colors.grey.shade300.withValues(alpha: 0.5), + ); } canvas.drawPath(path2, paint!); @@ -1077,22 +1218,33 @@ Path _processRadialBarShape( } /// Get the path of arc -Path _getArcPath(Path path, double innerRadius, double radius, Offset center, - double startAngle, double endAngle, double degree, bool isAnimate) { +Path _getArcPath( + Path path, + double innerRadius, + double radius, + Offset center, + double startAngle, + double endAngle, + double degree, + bool isAnimate, +) { startAngle = _degreesToRadians(startAngle); endAngle = _degreesToRadians(endAngle); degree = _degreesToRadians(degree); final Point innerRadiusStartPoint = Point( - innerRadius * cos(startAngle) + center.dx, - innerRadius * sin(startAngle) + center.dy); + innerRadius * cos(startAngle) + center.dx, + innerRadius * sin(startAngle) + center.dy, + ); final Point innerRadiusEndPoint = Point( - innerRadius * cos(endAngle) + center.dx, - innerRadius * sin(endAngle) + center.dy); + innerRadius * cos(endAngle) + center.dx, + innerRadius * sin(endAngle) + center.dy, + ); final Point radiusStartPoint = Point( - radius * cos(startAngle) + center.dx, - radius * sin(startAngle) + center.dy); + radius * cos(startAngle) + center.dx, + radius * sin(startAngle) + center.dy, + ); if (isAnimate) { path.moveTo(innerRadiusStartPoint.x, innerRadiusStartPoint.y); @@ -1102,25 +1254,49 @@ Path _getArcPath(Path path, double innerRadius, double radius, Offset center, final num midpointAngle = (endAngle + startAngle) / 2; if (isFullCircle) { - path.arcTo(Rect.fromCircle(center: center, radius: radius), startAngle, - midpointAngle.toDouble() - startAngle, true); - path.arcTo(Rect.fromCircle(center: center, radius: radius), - midpointAngle.toDouble(), endAngle - midpointAngle.toDouble(), true); + path.arcTo( + Rect.fromCircle(center: center, radius: radius), + startAngle, + midpointAngle.toDouble() - startAngle, + true, + ); + path.arcTo( + Rect.fromCircle(center: center, radius: radius), + midpointAngle.toDouble(), + endAngle - midpointAngle.toDouble(), + true, + ); } else { path.lineTo(radiusStartPoint.x, radiusStartPoint.y); - path.arcTo(Rect.fromCircle(center: center, radius: radius), startAngle, - degree, true); + path.arcTo( + Rect.fromCircle(center: center, radius: radius), + startAngle, + degree, + true, + ); } if (isFullCircle) { - path.arcTo(Rect.fromCircle(center: center, radius: innerRadius), endAngle, - midpointAngle.toDouble() - endAngle, true); - path.arcTo(Rect.fromCircle(center: center, radius: innerRadius), - midpointAngle.toDouble(), startAngle - midpointAngle.toDouble(), true); + path.arcTo( + Rect.fromCircle(center: center, radius: innerRadius), + endAngle, + midpointAngle.toDouble() - endAngle, + true, + ); + path.arcTo( + Rect.fromCircle(center: center, radius: innerRadius), + midpointAngle.toDouble(), + startAngle - midpointAngle.toDouble(), + true, + ); } else { path.lineTo(innerRadiusEndPoint.x, innerRadiusEndPoint.y); - path.arcTo(Rect.fromCircle(center: center, radius: innerRadius), endAngle, - startAngle - endAngle, true); + path.arcTo( + Rect.fromCircle(center: center, radius: innerRadius), + endAngle, + startAngle - endAngle, + true, + ); path.lineTo(radiusStartPoint.x, radiusStartPoint.y); } return path; @@ -1130,13 +1306,14 @@ Path _getArcPath(Path path, double innerRadius, double radius, Offset center, double _degreesToRadians(double deg) => deg * (pi / 180); /// Draw the hilo series type. -Path _processHiloShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? shaderPaint}) { +Path _processHiloShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? shaderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double height = rect.height; @@ -1157,13 +1334,14 @@ Path _processHiloShape( } /// Draw the hilo open close series type. -Path _processHiloOpenCloseShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? shaderPaint}) { +Path _processHiloOpenCloseShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? shaderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1184,19 +1362,21 @@ Path _processHiloOpenCloseShape( } /// Draw the waterfall series type. -Path _processWaterfallShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processWaterfallShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; final double height = rect.height; - path.addRect(Rect.fromLTRB( - x - width / 2, y - height / 2, x + width / 2, y + height / 2)); + path.addRect( + Rect.fromLTRB(x - width / 2, y - height / 2, x + width / 2, y + height / 2), + ); if (isNeedToReturnPath) { return path; @@ -1213,13 +1393,14 @@ Path _processWaterfallShape( } /// Draw the pyramid series type. -Path _processPyramidShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processPyramidShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1245,13 +1426,14 @@ Path _processPyramidShape( } /// Draw the funnel series type. -Path _processFunnelShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processFunnelShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1278,20 +1460,24 @@ Path _processFunnelShape( } /// Draw the bubble series type. -Path _processBubbleShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processBubbleShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; final double height = rect.height; path.addArc( - Rect.fromLTWH(x - width / 2, y - height / 2, width, height), 0.0, 2 * pi); + Rect.fromLTWH(x - width / 2, y - height / 2, width, height), + 0.0, + 2 * pi, + ); if (isNeedToReturnPath) { return path; @@ -1308,13 +1494,14 @@ Path _processBubbleShape( } /// Draw the step are series type. -Path _processStepAreaShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processStepAreaShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1346,13 +1533,14 @@ Path _processStepAreaShape( } /// Draw the spline area series type. -Path _processSplineAreaShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processSplineAreaShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1361,7 +1549,11 @@ Path _processSplineAreaShape( path.moveTo(x - width / 2, y + height / 2); path.quadraticBezierTo(x, y - height, x, y + height / 5); path.quadraticBezierTo( - x + width / 2, y - height / 2, x + width / 2, y + height / 2); + x + width / 2, + y - height / 2, + x + width / 2, + y + height / 2, + ); if (isNeedToReturnPath) { return path; @@ -1378,23 +1570,27 @@ Path _processSplineAreaShape( } /// Draw the line series type. -Path _processLineShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? shaderPaint, - bool? isNeedMarker, - ShapeMarkerType? overlayMarkerType, - bool? isDashArray}) { +Path _processLineShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? shaderPaint, + bool? isNeedMarker, + ShapeMarkerType? overlayMarkerType, + bool? isDashArray, +}) { if (isNeedMarker! && overlayMarkerType != null) { final Rect pathRect = Rect.fromCenter( - center: rect.center, - width: rect.width / 1.5, - height: rect.height / 1.5); - canvas.drawPath(getShapesPath(rect: pathRect, shapeType: overlayMarkerType), - Paint()..color = paint!.color); + center: rect.center, + width: rect.width / 1.5, + height: rect.height / 1.5, + ); + canvas.drawPath( + getShapesPath(rect: pathRect, shapeType: overlayMarkerType), + Paint()..color = paint!.color, + ); } final double left = rect.left + rect.width / 2; @@ -1410,23 +1606,27 @@ Path _processLineShape( paint.shader = shaderPaint != null ? shaderPaint.shader : paint.shader; canvas.drawPath( - isDashArray! - ? _processDashPath(path, - dashArray: _CircularIntervalList([3, 2])) - : path, - paint..style = PaintingStyle.stroke); + isDashArray! + ? _processDashPath( + path, + dashArray: _CircularIntervalList([3, 2]), + ) + : path, + paint..style = PaintingStyle.stroke, + ); } return path; } /// Draw the column series type. -Path _processColumnShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processColumnShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double left = rect.left + rect.width / 2; final double top = rect.top + rect.height / 2; @@ -1436,19 +1636,29 @@ Path _processColumnShape( path.moveTo(left - space * (rect.width / temp), top - (rect.height / temp)); path.lineTo( - left + space * (-rect.width / padding), top - (rect.height / temp)); + left + space * (-rect.width / padding), + top - (rect.height / temp), + ); path.lineTo(left + space * (-rect.width / padding), top + (rect.height / 2)); path.lineTo(left - space * (rect.width / temp), top + (rect.height / 2)); path.close(); - path.moveTo(left - (rect.width / padding) - (rect.width / (padding * 2)), - top - (rect.height / 4) - (padding / 2)); - path.lineTo(left + (rect.width / padding) + (rect.width / (padding * 2)), - top - (rect.height / 4) - (padding / 2)); - path.lineTo(left + (rect.width / padding) + (rect.width / (padding * 2)), - top + (rect.height / 2)); - path.lineTo(left - (rect.width / padding) - (rect.width / (padding * 2)), - top + (rect.height / 2)); + path.moveTo( + left - (rect.width / padding) - (rect.width / (padding * 2)), + top - (rect.height / 4) - (padding / 2), + ); + path.lineTo( + left + (rect.width / padding) + (rect.width / (padding * 2)), + top - (rect.height / 4) - (padding / 2), + ); + path.lineTo( + left + (rect.width / padding) + (rect.width / (padding * 2)), + top + (rect.height / 2), + ); + path.lineTo( + left - (rect.width / padding) - (rect.width / (padding * 2)), + top + (rect.height / 2), + ); path.close(); path.moveTo(left + space * (rect.width / padding), top); @@ -1472,13 +1682,14 @@ Path _processColumnShape( } /// Draw the area series type. -Path _processAreaShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processAreaShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1508,13 +1719,14 @@ Path _processAreaShape( } /// Draw the bar series type. -Path _processBarShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? borderPaint}) { +Path _processBarShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? borderPaint, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1528,20 +1740,32 @@ Path _processBarShape( path.lineTo(x - (width / 2) - padding / 4, y - 3 * (height / 10)); path.close(); path.moveTo( - x - (width / 2) - (padding / 4), y - (height / 5) + (padding / 20)); + x - (width / 2) - (padding / 4), + y - (height / 5) + (padding / 20), + ); path.lineTo( - x + (width / 2) + (padding / 4), y - (height / 5) + (padding / 20)); + x + (width / 2) + (padding / 4), + y - (height / 5) + (padding / 20), + ); path.lineTo( - x + (width / 2) + (padding / 4), y + (height / 10) + (padding / 20)); + x + (width / 2) + (padding / 4), + y + (height / 10) + (padding / 20), + ); path.lineTo( - x - (width / 2) - (padding / 4), y + (height / 10) + (padding / 20)); + x - (width / 2) - (padding / 4), + y + (height / 10) + (padding / 20), + ); path.close(); path.moveTo( - x - (width / 2) - (padding / 4), y + (height / 5) + (padding / 10)); + x - (width / 2) - (padding / 4), + y + (height / 5) + (padding / 10), + ); path.lineTo(x - width / 4, y + (height / 5) + (padding / 10)); path.lineTo(x - width / 4, y + (height / 2) + (padding / 10)); path.lineTo( - x - (width / 2) - (padding / 4), y + (height / 2) + (padding / 10)); + x - (width / 2) - (padding / 4), + y + (height / 2) + (padding / 10), + ); path.close(); if (isNeedToReturnPath) { @@ -1560,14 +1784,15 @@ Path _processBarShape( } /// Draw the spline series type. -Path _processSplineShape( - {required Canvas canvas, - required Rect rect, - required bool isNeedToReturnPath, - required Path path, - Paint? paint, - Paint? shaderPaint, - bool? isDashArray}) { +Path _processSplineShape({ + required Canvas canvas, + required Rect rect, + required bool isNeedToReturnPath, + required Path path, + Paint? paint, + Paint? shaderPaint, + bool? isDashArray, +}) { final double x = rect.left + rect.width / 2; final double y = rect.top + rect.height / 2; final double width = rect.width; @@ -1577,7 +1802,11 @@ Path _processSplineShape( path.quadraticBezierTo(x, y - height, x, y + height / 5); path.moveTo(x, y + height / 5); path.quadraticBezierTo( - x + width / 2, y + height / 2, x + width / 2, y - height / 2); + x + width / 2, + y + height / 2, + x + width / 2, + y - height / 2, + ); if (isNeedToReturnPath) { return path; @@ -1587,11 +1816,14 @@ Path _processSplineShape( paint.shader = shaderPaint != null ? shaderPaint.shader : paint.shader; canvas.drawPath( - isDashArray! - ? _processDashPath(path, - dashArray: _CircularIntervalList([3, 2])) - : path, - paint..style = PaintingStyle.stroke); + isDashArray! + ? _processDashPath( + path, + dashArray: _CircularIntervalList([3, 2]), + ) + : path, + paint..style = PaintingStyle.stroke, + ); } return path; @@ -1610,7 +1842,9 @@ Path _processDashPath( final double length = dashArray.next; if (draw) { path.addPath( - measurePath.extractPath(distance, distance + length), Offset.zero); + measurePath.extractPath(distance, distance + length), + Offset.zero, + ); } distance += length; draw = !draw; diff --git a/packages/syncfusion_flutter_core/lib/src/widgets/interactive_scroll_viewer.dart b/packages/syncfusion_flutter_core/lib/src/widgets/interactive_scroll_viewer.dart index ab1a32ada..bfc9fc4bb 100644 --- a/packages/syncfusion_flutter_core/lib/src/widgets/interactive_scroll_viewer.dart +++ b/packages/syncfusion_flutter_core/lib/src/widgets/interactive_scroll_viewer.dart @@ -1,32 +1,33 @@ part of interactive_scroll_viewer_internal; /// Triggers when double tap zoom invoked. -typedef _DoubleTapZoomInvokedCallback = Offset Function( - Offset value, Offset tapPosition); +typedef _DoubleTapZoomInvokedCallback = + Offset Function(Offset value, Offset tapPosition); /// [InteractiveScrollViewer] enables pan and zoom interactions with its child. @immutable class InteractiveScrollViewer extends StatefulWidget { /// Constructor for InteractiveScrollable. - const InteractiveScrollViewer(this.child, - {Key? key, - this.clipBehavior = Clip.hardEdge, - this.onDoubleTapZoomInvoked, - this.panAxis = PanAxis.free, - this.boundaryMargin = EdgeInsets.zero, - // These default scale values were eyeballed as reasonable - //limits for common use cases. - this.maxScale = 3, - this.minScale = 1, - this.onInteractionStart, - this.onInteractionUpdate, - this.onInteractionEnd, - this.panEnabled = true, - this.scaleEnabled = true, - this.constrained = true, - this.enableDoubleTapZooming = true, - this.transformationController}) - : super(key: key); + const InteractiveScrollViewer( + this.child, { + Key? key, + this.clipBehavior = Clip.hardEdge, + this.onDoubleTapZoomInvoked, + this.panAxis = PanAxis.free, + this.boundaryMargin = EdgeInsets.zero, + // These default scale values were eyeballed as reasonable + //limits for common use cases. + this.maxScale = 3, + this.minScale = 1, + this.onInteractionStart, + this.onInteractionUpdate, + this.onInteractionEnd, + this.panEnabled = true, + this.scaleEnabled = true, + this.constrained = true, + this.enableDoubleTapZooming = true, + this.transformationController, + }) : super(key: key); /// Whether the normal size constraints at this point in the widget tree are /// applied to the child. @@ -184,12 +185,14 @@ class InteractiveScrollViewerState extends State { /// ``` void scrollTo(Offset offset) { if (widget.transformationController != null) { - final Offset previousOffset = - widget.transformationController!.toScene(Offset.zero); + final Offset previousOffset = widget.transformationController!.toScene( + Offset.zero, + ); widget.transformationController?.value = - widget.transformationController!.value.clone() - ..translate( - previousOffset.dx - offset.dx, previousOffset.dy - offset.dy); + widget.transformationController!.value.clone()..translate( + previousOffset.dx - offset.dx, + previousOffset.dy - offset.dy, + ); } } @@ -228,8 +231,9 @@ class InteractiveScrollViewerState extends State { scale = scale.clamp(widget.minScale, widget.maxScale); final double zoomLevel = widget.transformationController!.value.getMaxScaleOnAxis(); - final Offset previousOffset = - widget.transformationController!.toScene(Offset.zero); + final Offset previousOffset = widget.transformationController!.toScene( + Offset.zero, + ); widget.transformationController?.value = widget.transformationController!.value.clone() ..scale(scale / zoomLevel, scale / zoomLevel); @@ -252,12 +256,14 @@ class InteractiveScrollViewerState extends State { Offset normalizedOffset; Offset offset; if (zoomLevel <= minimumZoomLevel) { - normalizedOffset = (-_tapPosition - + normalizedOffset = + (-_tapPosition - widget.transformationController!.toScene(Offset.zero) * zoomLevel) / zoomLevel; scaleTo(maximumZoomLevel); - offset = (-_tapPosition - normalizedOffset * maximumZoomLevel) / + offset = + (-_tapPosition - normalizedOffset * maximumZoomLevel) / maximumZoomLevel; // Triggered when double tap if (widget.onDoubleTapZoomInvoked != null) { @@ -265,12 +271,14 @@ class InteractiveScrollViewerState extends State { } scrollTo(offset); } else { - normalizedOffset = (-_tapPosition - + normalizedOffset = + (-_tapPosition - widget.transformationController!.toScene(Offset.zero) * zoomLevel) / zoomLevel; scaleTo(minimumZoomLevel); - offset = (-_tapPosition - normalizedOffset * minimumZoomLevel) / + offset = + (-_tapPosition - normalizedOffset * minimumZoomLevel) / minimumZoomLevel; // Triggered when double tap if (widget.onDoubleTapZoomInvoked != null) { diff --git a/packages/syncfusion_flutter_core/lib/src/zoomable/zoomable.dart b/packages/syncfusion_flutter_core/lib/src/zoomable/zoomable.dart index d91c33a54..d72227d95 100644 --- a/packages/syncfusion_flutter_core/lib/src/zoomable/zoomable.dart +++ b/packages/syncfusion_flutter_core/lib/src/zoomable/zoomable.dart @@ -34,7 +34,7 @@ enum ActionType { fling, /// Denotes there is no action currently. - none + none, } /// Contains details about the current zooming and panning action. @@ -94,9 +94,9 @@ class Zoomable extends StatefulWidget { this.onWillUpdate, this.onComplete, this.child, - }) : assert(minZoomLevel >= 1 && minZoomLevel <= maxZoomLevel), - assert(frictionCoefficient > 0.0), - super(key: key); + }) : assert(minZoomLevel >= 1 && minZoomLevel <= maxZoomLevel), + assert(frictionCoefficient > 0.0), + super(key: key); /// Holds the details of the current zoom level and actual rect. These details /// can be used in multiple widget which used the same zoomable widget. @@ -196,8 +196,10 @@ class _ZoomableState extends State with TickerProviderStateMixin { } Size _getAbsoluteChildSize(double zoomLevel) { - return Size((widget.boundary.width / 2) * pow(2, zoomLevel).toDouble(), - (widget.boundary.height / 2) * pow(2, zoomLevel).toDouble()); + return Size( + (widget.boundary.width / 2) * pow(2, zoomLevel).toDouble(), + (widget.boundary.height / 2) * pow(2, zoomLevel).toDouble(), + ); } void _handlePointerDown(PointerDownEvent event) { @@ -229,8 +231,10 @@ class _ZoomableState extends State with TickerProviderStateMixin { _scaleFocalPoint = details.localFocalPoint; _referenceScale = widget.controller.matrix.getMaxScaleOnAxis(); - _referenceFocalPoint = - _getPointOnChild(widget.controller.matrix, _scaleFocalPoint); + _referenceFocalPoint = _getPointOnChild( + widget.controller.matrix, + _scaleFocalPoint, + ); } } @@ -239,7 +243,9 @@ class _ZoomableState extends State with TickerProviderStateMixin { !_translationController.isAnimating) { if (widget.controller._action == ActionType.none) { widget.controller._action = _getActionTypes( - details.scale, details.localFocalPoint - _scaleFocalPoint); + details.scale, + details.localFocalPoint - _scaleFocalPoint, + ); } if (widget.controller._action == ActionType.none) { @@ -262,10 +268,12 @@ class _ZoomableState extends State with TickerProviderStateMixin { _currentScale = details.scale; double newScale = (_referenceScale! * details.scale) / prevScale; newScale = (newScale * prevScale).clamp( - Zoomable.getScale(widget.minZoomLevel), - Zoomable.getScale(widget.maxZoomLevel)); - final Size childSize = - _getAbsoluteChildSize(Zoomable.getZoomLevel(newScale)); + Zoomable.getScale(widget.minZoomLevel), + Zoomable.getScale(widget.maxZoomLevel), + ); + final Size childSize = _getAbsoluteChildSize( + Zoomable.getZoomLevel(newScale), + ); newScale /= prevScale; if (newScale == 1.0) { return; @@ -282,8 +290,13 @@ class _ZoomableState extends State with TickerProviderStateMixin { } _scale(newScale, pinchCenter, matrix); - _invokeOnWillUpdate(matrix, details.localFocalPoint, - details.focalPoint, details.scale, _scaleFocalPoint); + _invokeOnWillUpdate( + matrix, + details.localFocalPoint, + details.focalPoint, + details.scale, + _scaleFocalPoint, + ); break; case ActionType.pan: @@ -292,13 +305,19 @@ class _ZoomableState extends State with TickerProviderStateMixin { } _translate( - matrix, - _getPointOnChild(matrix, details.localFocalPoint) - - _referenceFocalPoint!); - _referenceFocalPoint = - _getPointOnChild(matrix, details.localFocalPoint); + matrix, + _getPointOnChild(matrix, details.localFocalPoint) - + _referenceFocalPoint!, + ); + _referenceFocalPoint = _getPointOnChild( + matrix, + details.localFocalPoint, + ); _invokeOnWillUpdate( - matrix, details.localFocalPoint, details.focalPoint); + matrix, + details.localFocalPoint, + details.focalPoint, + ); break; case ActionType.tap: @@ -321,14 +340,19 @@ class _ZoomableState extends State with TickerProviderStateMixin { if (_pointerCount == 2) { _resetDoubleTapTimer(); // By default, we have increased the zoom level by 1 while double tapping. - final double prevZoomLevel = - Zoomable.getZoomLevel(widget.controller.matrix.getMaxScaleOnAxis()); + final double prevZoomLevel = Zoomable.getZoomLevel( + widget.controller.matrix.getMaxScaleOnAxis(), + ); double newZoomLevel = prevZoomLevel + 1; - newZoomLevel = - newZoomLevel.clamp(widget.minZoomLevel, widget.maxZoomLevel); + newZoomLevel = newZoomLevel.clamp( + widget.minZoomLevel, + widget.maxZoomLevel, + ); if (newZoomLevel != prevZoomLevel) { _handleDoubleTap( - event.localPosition, pow(2, newZoomLevel - 1).toDouble()); + event.localPosition, + pow(2, newZoomLevel - 1).toDouble(), + ); } } } @@ -343,8 +367,11 @@ class _ZoomableState extends State with TickerProviderStateMixin { } final double newScale = exp(-event.scrollDelta.dy / 200); - final Size childSize = _getAbsoluteChildSize(Zoomable.getZoomLevel( - newScale * widget.controller.matrix.getMaxScaleOnAxis())); + final Size childSize = _getAbsoluteChildSize( + Zoomable.getZoomLevel( + newScale * widget.controller.matrix.getMaxScaleOnAxis(), + ), + ); final Size viewportSize = (context.findRenderObject()! as RenderBox).size; Offset pinchCenter = event.localPosition; if (childSize.width < viewportSize.width) { @@ -398,8 +425,9 @@ class _ZoomableState extends State with TickerProviderStateMixin { Offset _getPointOnChild(Matrix4 matrix, Offset viewportPoint) { final Matrix4 invertedMatrix = Matrix4.inverted(matrix); - final Vector3 untransformed = invertedMatrix - .transform3(Vector3(viewportPoint.dx, viewportPoint.dy, 0)); + final Vector3 untransformed = invertedMatrix.transform3( + Vector3(viewportPoint.dx, viewportPoint.dy, 0), + ); return Offset(untransformed.x, untransformed.y); } @@ -435,7 +463,8 @@ class _ZoomableState extends State with TickerProviderStateMixin { void _translate(Matrix4 matrix, Offset translation) { final Size childSize = _getAbsoluteChildSize( - Zoomable.getZoomLevel(matrix.getMaxScaleOnAxis())); + Zoomable.getZoomLevel(matrix.getMaxScaleOnAxis()), + ); final Rect viewport = Offset.zero & (context.findRenderObject()! as RenderBox).size; final bool widthExceeds = childSize.width > viewport.width; @@ -447,10 +476,14 @@ class _ZoomableState extends State with TickerProviderStateMixin { matrix.translate(0.0, translation.dy); } - final Offset effectiveViewportTopLeft = - _getPointOnChild(matrix, viewport.topLeft); - final Offset effectiveViewportBottomRight = - _getPointOnChild(matrix, viewport.bottomRight); + final Offset effectiveViewportTopLeft = _getPointOnChild( + matrix, + viewport.topLeft, + ); + final Offset effectiveViewportBottomRight = _getPointOnChild( + matrix, + viewport.bottomRight, + ); Offset correctedTranslation = Offset.zero; if (widthExceeds) { @@ -468,13 +501,17 @@ class _ZoomableState extends State with TickerProviderStateMixin { if (heightExceeds) { double exceed = effectiveViewportTopLeft.dy - widget.boundary.top; if (exceed < 0.0) { - correctedTranslation = - Offset(correctedTranslation.dx, correctedTranslation.dy + exceed); + correctedTranslation = Offset( + correctedTranslation.dx, + correctedTranslation.dy + exceed, + ); } else { exceed = effectiveViewportBottomRight.dy - widget.boundary.bottom; if (exceed > 0.0) { - correctedTranslation = - Offset(correctedTranslation.dx, correctedTranslation.dy + exceed); + correctedTranslation = Offset( + correctedTranslation.dx, + correctedTranslation.dy + exceed, + ); } } } @@ -484,11 +521,13 @@ class _ZoomableState extends State with TickerProviderStateMixin { } } - void _invokeOnWillUpdate(Matrix4 matrix, - [Offset? localFocalPoint, - Offset? globalFocalPoint, - double scale = 1.0, - Offset? pinchCenter]) { + void _invokeOnWillUpdate( + Matrix4 matrix, [ + Offset? localFocalPoint, + Offset? globalFocalPoint, + double scale = 1.0, + Offset? pinchCenter, + ]) { final double zoomLevel = Zoomable.getZoomLevel(matrix.getMaxScaleOnAxis()); if (localFocalPoint == null) { final RenderBox box = context.findRenderObject()! as RenderBox; @@ -499,7 +538,8 @@ class _ZoomableState extends State with TickerProviderStateMixin { globalFocalPoint = renderBox.localToGlobal(localFocalPoint); } - final Rect bounds = _getPointOnChild(matrix, widget.boundary.topLeft) & + final Rect bounds = + _getPointOnChild(matrix, widget.boundary.topLeft) & _getAbsoluteChildSize(zoomLevel); final ZoomableDetails details = ZoomableDetails( localFocalPoint: localFocalPoint, @@ -524,13 +564,15 @@ class _ZoomableState extends State with TickerProviderStateMixin { return widget.onWillUpdate?.call(details) ?? true; } - void _invokeOnComplete( - [Offset? localFocalPoint, - Offset? globalFocalPoint, - double scale = 1.0, - Offset? pinchCenter]) { - final double zoomLevel = - Zoomable.getZoomLevel(widget.controller.matrix.getMaxScaleOnAxis()); + void _invokeOnComplete([ + Offset? localFocalPoint, + Offset? globalFocalPoint, + double scale = 1.0, + Offset? pinchCenter, + ]) { + final double zoomLevel = Zoomable.getZoomLevel( + widget.controller.matrix.getMaxScaleOnAxis(), + ); if (localFocalPoint == null) { final RenderBox box = context.findRenderObject()! as RenderBox; localFocalPoint = box.size.center(Offset.zero); @@ -574,10 +616,12 @@ class _ZoomableState extends State with TickerProviderStateMixin { // This methods performs fling animation for pinching. void _startPinchFlingAnimation(ScaleEndDetails details) { - final double zoomLevel = - Zoomable.getZoomLevel(widget.controller.matrix.getMaxScaleOnAxis()); + final double zoomLevel = Zoomable.getZoomLevel( + widget.controller.matrix.getMaxScaleOnAxis(), + ); final int direction = _currentScale >= _maxAttainedScale ? 1 : -1; - double newZoomLevel = zoomLevel + + double newZoomLevel = + zoomLevel + (direction * (details.velocity.pixelsPerSecond.distance / kMaxFlingVelocity) * widget.maxZoomLevel); @@ -587,18 +631,21 @@ class _ZoomableState extends State with TickerProviderStateMixin { ..end = Zoomable.getScale(newZoomLevel); widget.controller._action = ActionType.fling; _zoomLevelController - ..duration = - _getFlingAnimationDuration(details.velocity.pixelsPerSecond.distance) + ..duration = _getFlingAnimationDuration( + details.velocity.pixelsPerSecond.distance, + ) ..forward(from: 0.0); } void _handleZoomLevelAnimation() { - _zoomLevelAnimation.curve = widget.controller._action == ActionType.fling - ? Curves.decelerate - : Curves.easeInOut; + _zoomLevelAnimation.curve = + widget.controller._action == ActionType.fling + ? Curves.decelerate + : Curves.easeInOut; final double newScale = _zoomLevelTween.evaluate(_zoomLevelAnimation); - final Size childSize = - _getAbsoluteChildSize(Zoomable.getZoomLevel(newScale)); + final Size childSize = _getAbsoluteChildSize( + Zoomable.getZoomLevel(newScale), + ); final Size viewportSize = (context.findRenderObject()! as RenderBox).size; Offset pinchCenter = _scaleFocalPoint; @@ -607,12 +654,15 @@ class _ZoomableState extends State with TickerProviderStateMixin { pinchCenter = viewportSize.center(Offset.zero); } final Matrix4 matrix = _scale( - newScale / widget.controller.matrix.getMaxScaleOnAxis(), pinchCenter); + newScale / widget.controller.matrix.getMaxScaleOnAxis(), + pinchCenter, + ); if (widget.controller._action == ActionType.none || widget.controller._action == ActionType.fling) { - final double zoomLevel = - Zoomable.getZoomLevel(matrix.getMaxScaleOnAxis()); + final double zoomLevel = Zoomable.getZoomLevel( + matrix.getMaxScaleOnAxis(), + ); final Offset translation = _getCurrentTranslation(matrix); final Rect actualRect = translation & _getAbsoluteChildSize(zoomLevel); widget.controller._internalSetValues(matrix, zoomLevel, actualRect); @@ -625,8 +675,10 @@ class _ZoomableState extends State with TickerProviderStateMixin { if (widget.enablePinching && zoomLevel != widget.controller.zoomLevel) { final RenderBox box = context.findRenderObject()! as RenderBox; _scaleFocalPoint = box.size.center(Offset.zero); - _referenceFocalPoint = - _getPointOnChild(widget.controller.matrix, _scaleFocalPoint); + _referenceFocalPoint = _getPointOnChild( + widget.controller.matrix, + _scaleFocalPoint, + ); zoomLevel = zoomLevel.clamp(widget.minZoomLevel, widget.maxZoomLevel); _zoomLevelTween ..begin = widget.controller.matrix.getMaxScaleOnAxis() @@ -669,28 +721,34 @@ class _ZoomableState extends State with TickerProviderStateMixin { ..end = Offset(frictionSimulationX.finalX, frictionSimulationY.finalX); widget.controller._action = ActionType.fling; _translationController - ..duration = - _getFlingAnimationDuration(details.velocity.pixelsPerSecond.distance) + ..duration = _getFlingAnimationDuration( + details.velocity.pixelsPerSecond.distance, + ) ..forward(from: 0.0); } void _handleTranslationAnimation() { - _translationAnimation.curve = widget.controller._action == ActionType.fling - ? Curves.decelerate - : Curves.easeInOut; + _translationAnimation.curve = + widget.controller._action == ActionType.fling + ? Curves.decelerate + : Curves.easeInOut; final Matrix4 matrix = widget.controller.matrix.clone(); final Offset prevTranslation = _getCurrentTranslation(matrix); - final Offset newTranslation = - _translationTween.evaluate(_translationAnimation); - final Offset translation = _getPointOnChild(matrix, newTranslation) - + final Offset newTranslation = _translationTween.evaluate( + _translationAnimation, + ); + final Offset translation = + _getPointOnChild(matrix, newTranslation) - _getPointOnChild(matrix, prevTranslation); _translate(matrix, translation); if (widget.controller._action == ActionType.none || widget.controller._action == ActionType.fling) { - final double zoomLevel = - Zoomable.getZoomLevel(matrix.getMaxScaleOnAxis()); - final Rect bounds = _getPointOnChild(matrix, widget.boundary.topLeft) & + final double zoomLevel = Zoomable.getZoomLevel( + matrix.getMaxScaleOnAxis(), + ); + final Rect bounds = + _getPointOnChild(matrix, widget.boundary.topLeft) & _getAbsoluteChildSize(zoomLevel); widget.controller._internalSetValues(matrix, zoomLevel, bounds); } else { @@ -736,17 +794,21 @@ class _ZoomableState extends State with TickerProviderStateMixin { ..addListener(_handleTranslationAnimation) ..addStatusListener(_handleTranslationAnimationStatusChange); - _zoomLevelAnimation = - CurvedAnimation(parent: _zoomLevelController, curve: Curves.easeInOut); + _zoomLevelAnimation = CurvedAnimation( + parent: _zoomLevelController, + curve: Curves.easeInOut, + ); _translationAnimation = CurvedAnimation( - parent: _translationController, curve: Curves.easeInOut); + parent: _translationController, + curve: Curves.easeInOut, + ); _translationTween = Tween(); _zoomLevelTween = Tween(); - final double initialZoomLevel = - Zoomable.getZoomLevel(widget.controller.matrix.getMaxScaleOnAxis()) - .clamp(widget.minZoomLevel, widget.maxZoomLevel); + final double initialZoomLevel = Zoomable.getZoomLevel( + widget.controller.matrix.getMaxScaleOnAxis(), + ).clamp(widget.minZoomLevel, widget.maxZoomLevel); widget.controller .._zoomLevel = initialZoomLevel .._absoluteBounds = widget.boundary @@ -793,7 +855,7 @@ class _ZoomableState extends State with TickerProviderStateMixin { class ZoomableController extends ChangeNotifier { /// Creates a [ZoomableController]. ZoomableController({Matrix4? matrix}) - : _matrix = matrix ?? Matrix4.identity(); + : _matrix = matrix ?? Matrix4.identity(); // ignore: unused_field late ScaleCallback? _onZoomLevelChange; diff --git a/packages/syncfusion_flutter_core/pubspec.yaml b/packages/syncfusion_flutter_core/pubspec.yaml index c74f2b78c..1a0901b6b 100644 --- a/packages/syncfusion_flutter_core/pubspec.yaml +++ b/packages/syncfusion_flutter_core/pubspec.yaml @@ -1,10 +1,10 @@ name: syncfusion_flutter_core description: Syncfusion Flutter Core is a dependent package for all the Syncfusion Flutter widgets. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_core environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: vector_math: ">=2.1.0 <=4.0.0" diff --git a/packages/syncfusion_flutter_datagrid/CHANGELOG.md b/packages/syncfusion_flutter_datagrid/CHANGELOG.md index a8f96ab28..fd6b53b19 100644 --- a/packages/syncfusion_flutter_datagrid/CHANGELOG.md +++ b/packages/syncfusion_flutter_datagrid/CHANGELOG.md @@ -2,6 +2,24 @@ **General** +* The compatible version of our Flutter DataGrid widget has been updated to Flutter SDK 3.32.0. + +**Features** + +- Provided support to customize the default appearance of checkbox and advanced filtering popup menus. +- Provided support to obtain the row details by row index using a helper method. +- Provided built-in support to customize the background color of the caption summary row. + +## [29.1.39] - 04/22/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 03/25/2025 + +**General** + * The compatible version of our Flutter DataGrid widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter DataGrid example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter DataGrid example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. @@ -22,12 +40,6 @@ * The `SfDataGrid` now handles selection and provides selected details based on visible rows. -## [28.2.6] - 18/02/2025 - -**General** - -* The minimum Dart version of our Flutter widgets has been updated to 3.4 from 3.3. - ## [28.2.3] - 01/29/2025 **Bugs** @@ -40,19 +52,6 @@ * The `SfDataGrid` now creates new rows instead of reusing them when the `rowCacheExtent` is set. -## [28.1.36] - 24/12/2024 - -**General** - -* The compatible version of our Flutter DataGrid widget has been updated to Flutter SDK 3.27.0. - -## [28.1.33] - 12/12/2024 - -**General** - -* All of our Syncfusion® Flutter widgets have been updated to support [`WebAssembly`](https://docs.flutter.dev/platform-integration/web/wasm) (WASM) as a compilation target for building web applications. -* The minimum Dart version of our Flutter widgets has been updated to 3.3 from 2.17. - ## [27.1.58] - 11/05/2024 **Bugs** @@ -71,12 +70,6 @@ * The RangeError exception will no longer occur when collapsing a group with the column width mode set to fill the last column for all rows. -## [27.1.48] - 09/18/2024 - -**General** - -* The compatible version of our Flutter DataGrid widget has been updated to Flutter SDK 3.24.0. - ## [27.0.0] - 09/09/2024 **General** @@ -129,9 +122,6 @@ ## [25.1.35] - 03/15/2024 -**General** -* Provided th​e Material 3 themes support. - **Features** * Implemented support for scrolling to a specific position upon initial loading. @@ -665,4 +655,4 @@ Initial release. * Styling - Customize the appearance of cells and headers. Conditional styling is also supported. * Theme - Use a dark or light theme. * Accessibility - The DataGrid can easily be accessed by screen readers. -* Right to Left (RTL) - Right-to-left direction support for users working in RTL languages like Hebrew and Arabic. +* Right to Left (RTL) - Right-to-left direction support for users working in RTL languages like Hebrew and Arabic. \ No newline at end of file diff --git a/packages/syncfusion_flutter_datagrid/example/android/.gitignore b/packages/syncfusion_flutter_datagrid/example/android/.gitignore index be3943c96..55afd919c 100644 --- a/packages/syncfusion_flutter_datagrid/example/android/.gitignore +++ b/packages/syncfusion_flutter_datagrid/example/android/.gitignore @@ -5,7 +5,6 @@ gradle-wrapper.jar /gradlew.bat /local.properties GeneratedPluginRegistrant.java -.cxx/ # Remember to never publicly share your keystore. # See https://flutter.dev/to/reference-keystore diff --git a/packages/syncfusion_flutter_datagrid/example/android/app/src/main/AndroidManifest.xml b/packages/syncfusion_flutter_datagrid/example/android/app/src/main/AndroidManifest.xml index 32321703f..74a78b939 100644 --- a/packages/syncfusion_flutter_datagrid/example/android/app/src/main/AndroidManifest.xml +++ b/packages/syncfusion_flutter_datagrid/example/android/app/src/main/AndroidManifest.xml @@ -1,6 +1,6 @@ CFBundleDevelopmentRegion - en + $(DEVELOPMENT_LANGUAGE) CFBundleExecutable App CFBundleIdentifier @@ -21,6 +21,6 @@ CFBundleVersion 1.0 MinimumOSVersion - 12.0 + 8.0 diff --git a/packages/syncfusion_flutter_datagrid/example/ios/Flutter/ephemeral/flutter_lldb_helper.py b/packages/syncfusion_flutter_datagrid/example/ios/Flutter/ephemeral/flutter_lldb_helper.py new file mode 100644 index 000000000..a88caf99d --- /dev/null +++ b/packages/syncfusion_flutter_datagrid/example/ios/Flutter/ephemeral/flutter_lldb_helper.py @@ -0,0 +1,32 @@ +# +# Generated file, do not edit. +# + +import lldb + +def handle_new_rx_page(frame: lldb.SBFrame, bp_loc, extra_args, intern_dict): + """Intercept NOTIFY_DEBUGGER_ABOUT_RX_PAGES and touch the pages.""" + base = frame.register["x0"].GetValueAsAddress() + page_len = frame.register["x1"].GetValueAsUnsigned() + + # Note: NOTIFY_DEBUGGER_ABOUT_RX_PAGES will check contents of the + # first page to see if handled it correctly. This makes diagnosing + # misconfiguration (e.g. missing breakpoint) easier. + data = bytearray(page_len) + data[0:8] = b'IHELPED!' + + error = lldb.SBError() + frame.GetThread().GetProcess().WriteMemory(base, data, error) + if not error.Success(): + print(f'Failed to write into {base}[+{page_len}]', error) + return + +def __lldb_init_module(debugger: lldb.SBDebugger, _): + target = debugger.GetDummyTarget() + # Caveat: must use BreakpointCreateByRegEx here and not + # BreakpointCreateByName. For some reasons callback function does not + # get carried over from dummy target for the later. + bp = target.BreakpointCreateByRegex("^NOTIFY_DEBUGGER_ABOUT_RX_PAGES$") + bp.SetScriptCallbackFunction('{}.handle_new_rx_page'.format(__name__)) + bp.SetAutoContinue(True) + print("-- LLDB integration loaded --") diff --git a/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.pbxproj b/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.pbxproj index 767d091eb..13ee6f8f1 100644 --- a/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.pbxproj +++ b/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.pbxproj @@ -3,12 +3,11 @@ archiveVersion = 1; classes = { }; - objectVersion = 54; + objectVersion = 46; objects = { /* Begin PBXBuildFile section */ 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; - 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; @@ -16,16 +15,6 @@ 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; /* End PBXBuildFile section */ -/* Begin PBXContainerItemProxy section */ - 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 97C146E61CF9000F007C117D /* Project object */; - proxyType = 1; - remoteGlobalIDString = 97C146ED1CF9000F007C117D; - remoteInfo = Runner; - }; -/* End PBXContainerItemProxy section */ - /* Begin PBXCopyFilesBuildPhase section */ 9705A1C41CF9048500538489 /* Embed Frameworks */ = { isa = PBXCopyFilesBuildPhase; @@ -42,8 +31,6 @@ /* Begin PBXFileReference section */ 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; - 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; - 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -68,14 +55,6 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 331C8082294A63A400263BE5 /* RunnerTests */ = { - isa = PBXGroup; - children = ( - 331C807B294A618700263BE5 /* RunnerTests.swift */, - ); - path = RunnerTests; - sourceTree = ""; - }; 9740EEB11CF90186004384FC /* Flutter */ = { isa = PBXGroup; children = ( @@ -93,7 +72,6 @@ 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, 97C146EF1CF9000F007C117D /* Products */, - 331C8082294A63A400263BE5 /* RunnerTests */, ); sourceTree = ""; }; @@ -101,7 +79,6 @@ isa = PBXGroup; children = ( 97C146EE1CF9000F007C117D /* Runner.app */, - 331C8081294A63A400263BE5 /* RunnerTests.xctest */, ); name = Products; sourceTree = ""; @@ -113,6 +90,7 @@ 97C146FD1CF9000F007C117D /* Assets.xcassets */, 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, 97C147021CF9000F007C117D /* Info.plist */, + 97C146F11CF9000F007C117D /* Supporting Files */, 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, @@ -121,26 +99,16 @@ path = Runner; sourceTree = ""; }; + 97C146F11CF9000F007C117D /* Supporting Files */ = { + isa = PBXGroup; + children = ( + ); + name = "Supporting Files"; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 331C8080294A63A400263BE5 /* RunnerTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; - buildPhases = ( - 331C807D294A63A400263BE5 /* Sources */, - 331C807F294A63A400263BE5 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 331C8086294A63A400263BE5 /* PBXTargetDependency */, - ); - name = RunnerTests; - productName = RunnerTests; - productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; 97C146ED1CF9000F007C117D /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; @@ -167,14 +135,9 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - BuildIndependentTargetsInParallel = YES; - LastUpgradeCheck = 1510; + LastUpgradeCheck = 1020; ORGANIZATIONNAME = ""; TargetAttributes = { - 331C8080294A63A400263BE5 = { - CreatedOnToolsVersion = 14.0; - TestTargetID = 97C146ED1CF9000F007C117D; - }; 97C146ED1CF9000F007C117D = { CreatedOnToolsVersion = 7.3.1; LastSwiftMigration = 1100; @@ -195,19 +158,11 @@ projectRoot = ""; targets = ( 97C146ED1CF9000F007C117D /* Runner */, - 331C8080294A63A400263BE5 /* RunnerTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 331C807F294A63A400263BE5 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; 97C146EC1CF9000F007C117D /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -224,12 +179,10 @@ /* Begin PBXShellScriptBuildPhase section */ 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); inputPaths = ( - "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", ); name = "Thin Binary"; outputPaths = ( @@ -240,7 +193,6 @@ }; 9740EEB61CF901F6004384FC /* Run Script */ = { isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); @@ -256,14 +208,6 @@ /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 331C807D294A63A400263BE5 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 97C146EA1CF9000F007C117D /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -275,14 +219,6 @@ }; /* End PBXSourcesBuildPhase section */ -/* Begin PBXTargetDependency section */ - 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 97C146ED1CF9000F007C117D /* Runner */; - targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - /* Begin PBXVariantGroup section */ 97C146FA1CF9000F007C117D /* Main.storyboard */ = { isa = PBXVariantGroup; @@ -305,9 +241,9 @@ /* Begin XCBuildConfiguration section */ 249021D3217E4FDB00AE95B9 /* Profile */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -337,7 +273,6 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -346,7 +281,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; @@ -363,12 +298,17 @@ CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( "$(inherited)", - "@executable_path/Frameworks", + "$(PROJECT_DIR)/Flutter", ); - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridSample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -376,58 +316,11 @@ }; name = Profile; }; - 331C8088294A63A400263BE5 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; - }; - name = Debug; - }; - 331C8089294A63A400263BE5 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; - }; - name = Release; - }; - 331C808A294A63A400263BE5 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; - }; - name = Profile; - }; 97C147031CF9000F007C117D /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -457,7 +350,6 @@ DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -472,7 +364,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -482,9 +374,9 @@ }; 97C147041CF9000F007C117D /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; @@ -514,7 +406,6 @@ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -523,12 +414,11 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 12.0; + IPHONEOS_DEPLOYMENT_TARGET = 8.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SUPPORTED_PLATFORMS = iphoneos; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; TARGETED_DEVICE_FAMILY = "1,2"; VALIDATE_PRODUCT = YES; }; @@ -542,12 +432,17 @@ CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( "$(inherited)", - "@executable_path/Frameworks", + "$(PROJECT_DIR)/Flutter", ); - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridSample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; @@ -564,12 +459,17 @@ CLANG_ENABLE_MODULES = YES; CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/Flutter", + ); INFOPLIST_FILE = Runner/Info.plist; - LD_RUNPATH_SEARCH_PATHS = ( + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + LIBRARY_SEARCH_PATHS = ( "$(inherited)", - "@executable_path/Frameworks", + "$(PROJECT_DIR)/Flutter", ); - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample; + PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridSample; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; SWIFT_VERSION = 5.0; @@ -580,16 +480,6 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 331C8088294A63A400263BE5 /* Debug */, - 331C8089294A63A400263BE5 /* Release */, - 331C808A294A63A400263BE5 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata index 919434a62..1d526a16e 100644 --- a/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ b/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -2,6 +2,6 @@ + location = "group:Runner.xcodeproj"> diff --git a/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index 15cada483..a28140cfd 100644 --- a/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/packages/syncfusion_flutter_datagrid/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ + + - - - - - - + + @@ -71,6 +61,8 @@ ReferencedContainer = "container:Runner.xcodeproj"> + + CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) - CFBundleDisplayName - Datagrid Example CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier @@ -41,9 +39,7 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight - CADisableMinimumFrameDurationOnPhone - - UIApplicationSupportsIndirectInputEvents - + UIViewControllerBasedStatusBarAppearance + diff --git a/packages/syncfusion_flutter_datagrid/example/lib/main.dart b/packages/syncfusion_flutter_datagrid/example/lib/main.dart index c20855936..91e9cc9de 100644 --- a/packages/syncfusion_flutter_datagrid/example/lib/main.dart +++ b/packages/syncfusion_flutter_datagrid/example/lib/main.dart @@ -40,42 +40,43 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Flutter DataGrid'), - ), + appBar: AppBar(title: const Text('Syncfusion Flutter DataGrid')), body: SfDataGrid( source: employeeDataSource, columnWidthMode: ColumnWidthMode.fill, columns: [ GridColumn( - columnName: 'id', - label: Container( - padding: EdgeInsets.all(16.0), - alignment: Alignment.center, - child: Text( - 'ID', - ))), + columnName: 'id', + label: Container( + padding: EdgeInsets.all(16.0), + alignment: Alignment.center, + child: Text('ID'), + ), + ), GridColumn( - columnName: 'name', - label: Container( - padding: EdgeInsets.all(8.0), - alignment: Alignment.center, - child: Text('Name'))), + columnName: 'name', + label: Container( + padding: EdgeInsets.all(8.0), + alignment: Alignment.center, + child: Text('Name'), + ), + ), GridColumn( - columnName: 'designation', - label: Container( - padding: EdgeInsets.all(8.0), - alignment: Alignment.center, - child: Text( - 'Designation', - overflow: TextOverflow.ellipsis, - ))), + columnName: 'designation', + label: Container( + padding: EdgeInsets.all(8.0), + alignment: Alignment.center, + child: Text('Designation', overflow: TextOverflow.ellipsis), + ), + ), GridColumn( - columnName: 'salary', - label: Container( - padding: EdgeInsets.all(8.0), - alignment: Alignment.center, - child: Text('Salary'))), + columnName: 'salary', + label: Container( + padding: EdgeInsets.all(8.0), + alignment: Alignment.center, + child: Text('Salary'), + ), + ), ], ), ); @@ -92,7 +93,7 @@ class _MyHomePageState extends State { Employee(10007, 'Balnc', 'Developer', 15000), Employee(10008, 'Perry', 'Developer', 15000), Employee(10009, 'Gable', 'Developer', 15000), - Employee(10010, 'Grimes', 'Developer', 15000) + Employee(10010, 'Grimes', 'Developer', 15000), ]; } } @@ -121,15 +122,22 @@ class Employee { class EmployeeDataSource extends DataGridSource { /// Creates the employee data source class with required details. EmployeeDataSource({required List employeeData}) { - _employeeData = employeeData - .map((e) => DataGridRow(cells: [ - DataGridCell(columnName: 'id', value: e.id), - DataGridCell(columnName: 'name', value: e.name), - DataGridCell( - columnName: 'designation', value: e.designation), - DataGridCell(columnName: 'salary', value: e.salary), - ])) - .toList(); + _employeeData = + employeeData + .map( + (e) => DataGridRow( + cells: [ + DataGridCell(columnName: 'id', value: e.id), + DataGridCell(columnName: 'name', value: e.name), + DataGridCell( + columnName: 'designation', + value: e.designation, + ), + DataGridCell(columnName: 'salary', value: e.salary), + ], + ), + ) + .toList(); } List _employeeData = []; @@ -140,12 +148,14 @@ class EmployeeDataSource extends DataGridSource { @override DataGridRowAdapter buildRow(DataGridRow row) { return DataGridRowAdapter( - cells: row.getCells().map((e) { - return Container( - alignment: Alignment.center, - padding: EdgeInsets.all(8.0), - child: Text(e.value.toString()), - ); - }).toList()); + cells: + row.getCells().map((e) { + return Container( + alignment: Alignment.center, + padding: EdgeInsets.all(8.0), + child: Text(e.value.toString()), + ); + }).toList(), + ); } } diff --git a/packages/syncfusion_flutter_datagrid/example/macos/.gitignore b/packages/syncfusion_flutter_datagrid/example/macos/.gitignore index 746adbb6b..d2fd37723 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/.gitignore +++ b/packages/syncfusion_flutter_datagrid/example/macos/.gitignore @@ -3,5 +3,4 @@ **/Pods/ # Xcode-related -**/dgph **/xcuserdata/ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/project.pbxproj b/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/project.pbxproj index 65da0ce05..cc89c8782 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/project.pbxproj +++ b/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/project.pbxproj @@ -3,7 +3,7 @@ archiveVersion = 1; classes = { }; - objectVersion = 54; + objectVersion = 51; objects = { /* Begin PBXAggregateTarget section */ @@ -21,7 +21,6 @@ /* End PBXAggregateTarget section */ /* Begin PBXBuildFile section */ - 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; @@ -30,13 +29,6 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = 33CC10E52044A3C60003C045 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 33CC10EC2044A3C60003C045; - remoteInfo = Runner; - }; 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 33CC10E52044A3C60003C045 /* Project object */; @@ -60,11 +52,9 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; - 33CC10ED2044A3C60003C045 /* datagrid_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "datagrid_example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10ED2044A3C60003C045 /* example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "example.app"; sourceTree = BUILT_PRODUCTS_DIR; }; 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; @@ -81,13 +71,6 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - 331C80D2294CF70F00263BE5 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; 33CC10EA2044A3C60003C045 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -98,14 +81,6 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 331C80D6294CF71000263BE5 /* RunnerTests */ = { - isa = PBXGroup; - children = ( - 331C80D7294CF71000263BE5 /* RunnerTests.swift */, - ); - path = RunnerTests; - sourceTree = ""; - }; 33BA886A226E78AF003329D5 /* Configs */ = { isa = PBXGroup; children = ( @@ -122,7 +97,6 @@ children = ( 33FAB671232836740065AC1E /* Runner */, 33CEB47122A05771004F2AC0 /* Flutter */, - 331C80D6294CF71000263BE5 /* RunnerTests */, 33CC10EE2044A3C60003C045 /* Products */, D73912EC22F37F3D000D13A0 /* Frameworks */, ); @@ -131,8 +105,7 @@ 33CC10EE2044A3C60003C045 /* Products */ = { isa = PBXGroup; children = ( - 33CC10ED2044A3C60003C045 /* datagrid_example.app */, - 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + 33CC10ED2044A3C60003C045 /* example.app */, ); name = Products; sourceTree = ""; @@ -182,24 +155,6 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - 331C80D4294CF70F00263BE5 /* RunnerTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; - buildPhases = ( - 331C80D1294CF70F00263BE5 /* Sources */, - 331C80D2294CF70F00263BE5 /* Frameworks */, - 331C80D3294CF70F00263BE5 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - 331C80DA294CF71000263BE5 /* PBXTargetDependency */, - ); - name = RunnerTests; - productName = RunnerTests; - productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; - productType = "com.apple.product-type.bundle.unit-test"; - }; 33CC10EC2044A3C60003C045 /* Runner */ = { isa = PBXNativeTarget; buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; @@ -217,7 +172,7 @@ ); name = Runner; productName = Runner; - productReference = 33CC10ED2044A3C60003C045 /* datagrid_example.app */; + productReference = 33CC10ED2044A3C60003C045 /* example.app */; productType = "com.apple.product-type.application"; }; /* End PBXNativeTarget section */ @@ -226,15 +181,10 @@ 33CC10E52044A3C60003C045 /* Project object */ = { isa = PBXProject; attributes = { - BuildIndependentTargetsInParallel = YES; LastSwiftUpdateCheck = 0920; - LastUpgradeCheck = 1510; + LastUpgradeCheck = 0930; ORGANIZATIONNAME = ""; TargetAttributes = { - 331C80D4294CF70F00263BE5 = { - CreatedOnToolsVersion = 14.0; - TestTargetID = 33CC10EC2044A3C60003C045; - }; 33CC10EC2044A3C60003C045 = { CreatedOnToolsVersion = 9.2; LastSwiftMigration = 1100; @@ -265,20 +215,12 @@ projectRoot = ""; targets = ( 33CC10EC2044A3C60003C045 /* Runner */, - 331C80D4294CF70F00263BE5 /* RunnerTests */, 33CC111A2044C6BA0003C045 /* Flutter Assemble */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - 331C80D3294CF70F00263BE5 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; 33CC10EB2044A3C60003C045 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -293,7 +235,6 @@ /* Begin PBXShellScriptBuildPhase section */ 3399D490228B24CF009A79C7 /* ShellScript */ = { isa = PBXShellScriptBuildPhase; - alwaysOutOfDate = 1; buildActionMask = 2147483647; files = ( ); @@ -332,14 +273,6 @@ /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - 331C80D1294CF70F00263BE5 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; 33CC10E92044A3C60003C045 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -353,11 +286,6 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - target = 33CC10EC2044A3C60003C045 /* Runner */; - targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; - }; 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { isa = PBXTargetDependency; target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; @@ -378,54 +306,11 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ - 331C80DB294CF71000263BE5 /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/datagrid_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/datagrid_example"; - }; - name = Debug; - }; - 331C80DC294CF71000263BE5 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/datagrid_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/datagrid_example"; - }; - name = Release; - }; - 331C80DD294CF71000263BE5 /* Profile */ = { - isa = XCBuildConfiguration; - buildSettings = { - BUNDLE_LOADER = "$(TEST_HOST)"; - CURRENT_PROJECT_VERSION = 1; - GENERATE_INFOPLIST_FILE = YES; - MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample.RunnerTests; - PRODUCT_NAME = "$(TARGET_NAME)"; - SWIFT_VERSION = 5.0; - TEST_HOST = "$(BUILT_PRODUCTS_DIR)/datagrid_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/datagrid_example"; - }; - name = Profile; - }; 338D0CE9231458BD00FA5F75 /* Profile */ = { isa = XCBuildConfiguration; baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; @@ -449,11 +334,9 @@ CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; - DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -461,7 +344,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -501,7 +384,6 @@ baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; @@ -525,11 +407,9 @@ CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; - DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_DYNAMIC_NO_PIC = NO; GCC_NO_COMMON_BLOCKS = YES; @@ -543,7 +423,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = macosx; @@ -557,7 +437,6 @@ baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; CLANG_ANALYZER_NONNULL = YES; CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; @@ -581,11 +460,9 @@ CLANG_WARN_SUSPICIOUS_MOVE = YES; CODE_SIGN_IDENTITY = "-"; COPY_PHASE_STRIP = NO; - DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_USER_SCRIPT_SANDBOXING = NO; GCC_C_LANGUAGE_STANDARD = gnu11; GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; @@ -593,7 +470,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.14; + MACOSX_DEPLOYMENT_TARGET = 10.11; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = macosx; SWIFT_COMPILATION_MODE = wholemodule; @@ -659,16 +536,6 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 331C80DB294CF71000263BE5 /* Debug */, - 331C80DC294CF71000263BE5 /* Release */, - 331C80DD294CF71000263BE5 /* Profile */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index bb3c7e5d8..ae8ff59d9 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/packages/syncfusion_flutter_datagrid/example/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ @@ -31,24 +31,13 @@ - - - - - - + + + + diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/AppDelegate.swift b/packages/syncfusion_flutter_datagrid/example/macos/Runner/AppDelegate.swift index b3c176141..d53ef6437 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/Runner/AppDelegate.swift +++ b/packages/syncfusion_flutter_datagrid/example/macos/Runner/AppDelegate.swift @@ -1,13 +1,9 @@ import Cocoa import FlutterMacOS -@main +@NSApplicationMain class AppDelegate: FlutterAppDelegate { override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { return true } - - override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { - return true - } } diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png index 82b6f9d9a..3c4935a7c 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png index 13b35eba5..ed4cc1642 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png index 0a3f5fa40..483be6138 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png index bdb57226d..bcbf36df2 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png index f083318e0..9c0a65286 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png index 326c0e72c..e71a72613 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png index 2f1632cfd..8a31fe2dd 100644 Binary files a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png and b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Base.lproj/MainMenu.xib b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Base.lproj/MainMenu.xib index 80e867a4e..537341abf 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Base.lproj/MainMenu.xib +++ b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Base.lproj/MainMenu.xib @@ -323,10 +323,6 @@ - - - - diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Configs/AppInfo.xcconfig b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Configs/AppInfo.xcconfig index a7ea9ce20..cf9be60ca 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/Runner/Configs/AppInfo.xcconfig +++ b/packages/syncfusion_flutter_datagrid/example/macos/Runner/Configs/AppInfo.xcconfig @@ -5,10 +5,10 @@ // 'flutter create' template. // The application's name. By default this is also the title of the Flutter window. -PRODUCT_NAME = datagrid_example +PRODUCT_NAME = example // The application's bundle identifier -PRODUCT_BUNDLE_IDENTIFIER = com.example.datagridExample +PRODUCT_BUNDLE_IDENTIFIER = com.example.example // The copyright displayed in application information -PRODUCT_COPYRIGHT = Copyright © 2025 com.example. All rights reserved. +PRODUCT_COPYRIGHT = Copyright © 2021 com.example. All rights reserved. diff --git a/packages/syncfusion_flutter_datagrid/example/macos/Runner/MainFlutterWindow.swift b/packages/syncfusion_flutter_datagrid/example/macos/Runner/MainFlutterWindow.swift index 3cc05eb23..2722837ec 100644 --- a/packages/syncfusion_flutter_datagrid/example/macos/Runner/MainFlutterWindow.swift +++ b/packages/syncfusion_flutter_datagrid/example/macos/Runner/MainFlutterWindow.swift @@ -3,7 +3,7 @@ import FlutterMacOS class MainFlutterWindow: NSWindow { override func awakeFromNib() { - let flutterViewController = FlutterViewController() + let flutterViewController = FlutterViewController.init() let windowFrame = self.frame self.contentViewController = flutterViewController self.setFrame(windowFrame, display: true) diff --git a/packages/syncfusion_flutter_datagrid/example/pubspec.yaml b/packages/syncfusion_flutter_datagrid/example/pubspec.yaml index 44d032f73..ad116ff64 100644 --- a/packages/syncfusion_flutter_datagrid/example/pubspec.yaml +++ b/packages/syncfusion_flutter_datagrid/example/pubspec.yaml @@ -3,7 +3,7 @@ description: This project demonstrates how to use Syncfusion Flutter DataGrid wi version: 1.0.0+1 environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/grouping/grouping.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/grouping/grouping.dart index b1ef61486..dd34d1807 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/grouping/grouping.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/grouping/grouping.dart @@ -33,8 +33,11 @@ class Group extends DataRowEntry { TopLevelGroup? topLevelGroup; /// Refreshes the top-level group for the DataGridSource. - void refreshTopLevelGroup(DataGridConfiguration dataGridConfiguration, - List groupedColumn, bool autoExpandGroup) { + void refreshTopLevelGroup( + DataGridConfiguration dataGridConfiguration, + List groupedColumn, + bool autoExpandGroup, + ) { if (hasGroups) { initializeTopLevelGroup(dataGridConfiguration, autoExpandGroup); } else { @@ -47,7 +50,9 @@ class Group extends DataRowEntry { /// used to initalize the grouping. void initializeTopLevelGroup( - DataGridConfiguration dataGridConfiguration, bool autoExpandGroup) { + DataGridConfiguration dataGridConfiguration, + bool autoExpandGroup, + ) { final List groupedColumn = []; for (final ColumnGroup columnGroupDescription in dataGridConfiguration.source.groupedColumns) { @@ -59,16 +64,20 @@ class Group extends DataRowEntry { if (groupedColumn.isNotEmpty) { final List result = _performGroupBy( - effectiveRows(dataGridConfiguration.source), - groupedColumn, - dataGridConfiguration.source); + effectiveRows(dataGridConfiguration.source), + groupedColumn, + dataGridConfiguration.source, + ); topLevelGroup?._populate(result, autoExpandGroup); } dataGridConfiguration.group = topLevelGroup; } - List _performGroupBy(List rows, List columnNames, - DataGridSource? source) { + List _performGroupBy( + List rows, + List columnNames, + DataGridSource? source, + ) { final Map groupedData = {}; for (final DataGridRow row in rows) { @@ -81,15 +90,19 @@ class Group extends DataRowEntry { groupedData[key] = [row]; } } else { - dynamic currentGroup = - groupedData.putIfAbsent(key, () => {}); + dynamic currentGroup = groupedData.putIfAbsent( + key, + () => {}, + ); for (int i = 1; i < columnNames.length; i++) { final dynamic innerKey = performGrouping(source, columnNames[i], row); if (i != columnNames.length - 1) { - currentGroup = - currentGroup.putIfAbsent(innerKey, () => {}); + currentGroup = currentGroup.putIfAbsent( + innerKey, + () => {}, + ); } else { currentGroup.putIfAbsent(innerKey, () => []).add(row); } @@ -102,8 +115,10 @@ class Group extends DataRowEntry { for (final MapEntry entry in groupedData.entries) { final Group groupResult = Group()..key = entry.key; - final Group innerGroupResult = - _createGroupResult(entry: entry, groupResult: groupResult); + final Group innerGroupResult = _createGroupResult( + entry: entry, + groupResult: groupResult, + ); groupResult.rows = innerGroupResult.rows; groupResults.add(groupResult); } @@ -111,8 +126,10 @@ class Group extends DataRowEntry { return groupResults; } - dynamic _createGroupResult( - {MapEntry? entry, Group? groupResult}) { + dynamic _createGroupResult({ + MapEntry? entry, + Group? groupResult, + }) { if (entry!.value is List) { entry.value.forEach((dynamic item) { groupResult!.rows.add(item); @@ -121,12 +138,15 @@ class Group extends DataRowEntry { return groupResult; } else { entry.value.entries.forEach((dynamic newEntry) { - Group newGroupResult = Group() - ..key = newEntry.key - ..length = newEntry.value.length; - - newGroupResult = - _createGroupResult(entry: newEntry, groupResult: newGroupResult); + Group newGroupResult = + Group() + ..key = newEntry.key + ..length = newEntry.value.length; + + newGroupResult = _createGroupResult( + entry: newEntry, + groupResult: newGroupResult, + ); groupResult!.rows.addAll(newGroupResult.rows); groupResult.subGroups.add(newGroupResult); @@ -202,7 +222,10 @@ class Group extends DataRowEntry { } Group? _expandAndCollapseGroup( - Group groupsToPopulate, bool expand, Group? newGroup) { + Group groupsToPopulate, + bool expand, + Group? newGroup, + ) { final Group group = groupsToPopulate; if (group.subGroups.isEmpty) { @@ -238,13 +261,18 @@ class Group extends DataRowEntry { } int _addSubGroups( - dynamic individualGroup, Group? newGrouping, int startIndex) { + dynamic individualGroup, + Group? newGrouping, + int startIndex, + ) { int groupIndex = startIndex + 1; if (individualGroup.subGroups.isNotEmpty) { for (final Group nestedSubGroup in individualGroup.subGroups) { - newGrouping!.displayElements!.grouped - .insert(groupIndex, nestedSubGroup); + newGrouping!.displayElements!.grouped.insert( + groupIndex, + nestedSubGroup, + ); if (nestedSubGroup.isExpanded) { nestedSubGroup.isExpanded = true; groupIndex = _addSubGroups(nestedSubGroup, newGrouping, groupIndex); @@ -264,7 +292,10 @@ class Group extends DataRowEntry { /// Collapses a specific group in SfDataGrid. Group? collapseGroups( - dynamic individualGroup, Group? newGrouping, int groupIndex) { + dynamic individualGroup, + Group? newGrouping, + int groupIndex, + ) { if (individualGroup is DataGridRow || !individualGroup.isExpanded) { return newGrouping; } @@ -344,7 +375,9 @@ class Group extends DataRowEntry { /// Called when the sorting is applied to the column. @protected void performSorting( - DataGridConfiguration dataGridConfiguration, List sortedColumn) { + DataGridConfiguration dataGridConfiguration, + List sortedColumn, + ) { bool expand = false; Group groupsToPopulate; final Group newGroup = Group(); @@ -356,8 +389,13 @@ class Group extends DataRowEntry { if (group.level == 1) { expand = true; groupsToPopulate = group; - _sortGroupedRows(dataGridConfiguration, groupsToPopulate, expand, - newGroup, sortedColumn); + _sortGroupedRows( + dataGridConfiguration, + groupsToPopulate, + expand, + newGroup, + sortedColumn, + ); } } } @@ -368,11 +406,12 @@ class Group extends DataRowEntry { } Group? _sortGroupedRows( - DataGridConfiguration dataGridConfiguration, - Group groupsToPopulate, - bool expand, - Group? newGroup, - List sortedColumn) { + DataGridConfiguration dataGridConfiguration, + Group groupsToPopulate, + bool expand, + Group? newGroup, + List sortedColumn, + ) { final Group group = groupsToPopulate; if (group.subGroups.isEmpty) { @@ -393,7 +432,12 @@ class Group extends DataRowEntry { for (final Group subGroups in group.subGroups) { group.isExpanded = expand; _sortGroupedRows( - dataGridConfiguration, subGroups, expand, newGroup, sortedColumn); + dataGridConfiguration, + subGroups, + expand, + newGroup, + sortedColumn, + ); } } return newGroup; @@ -416,8 +460,9 @@ class Group extends DataRowEntry { if (compareResult == 0) { return compareResult; } else { - final List remainingSortColumns = - sortedColumns.sublist(i + 1); + final List remainingSortColumns = sortedColumns.sublist( + i + 1, + ); return _compareValues(remainingSortColumns, a, b); } } @@ -444,7 +489,8 @@ class Group extends DataRowEntry { Object? _getCellValue(List? cells, String columnName) { return cells ?.firstWhereOrNull( - (DataGridCell element) => element.columnName == columnName) + (DataGridCell element) => element.columnName == columnName, + ) ?.value; } } @@ -505,15 +551,23 @@ class GroupPopulate extends Group { hasGroups = true; if (groupsToPopulate != null) { - rowsCacheCount = - _populateGroup(groupsToPopulate, groups, this, level + 1); + rowsCacheCount = _populateGroup( + groupsToPopulate, + groups, + this, + level + 1, + ); displayElements?.length = rowsCacheCount; } return rowsCacheCount; } - int _populateGroup(List groupsToPopulate, - List groupPopulates, GroupPopulate parent, int level) { + int _populateGroup( + List groupsToPopulate, + List groupPopulates, + GroupPopulate parent, + int level, + ) { int parentCounter = 0; final List groups = groupsToPopulate.asMap().values.toList(); @@ -547,7 +601,11 @@ class GroupPopulate extends Group { displayElements?.grouped.add(newGroup); } counter += _populateGroup( - groupResult.subGroups, group.groups, group, level + 1); + groupResult.subGroups, + group.groups, + group, + level + 1, + ); group._getRowsCacheCount(); parentCounter += counter; counter = 0; diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/callbackargs.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/callbackargs.dart index 017a07be0..a40f68e11 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/callbackargs.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/callbackargs.dart @@ -23,8 +23,10 @@ import 'datagrid_configuration.dart'; class DataGridCellDetails { /// Creates a [DataGridCellDetails] with the specified [rowColumnIndex] and /// [column]. - const DataGridCellDetails( - {required this.rowColumnIndex, required this.column}); + const DataGridCellDetails({ + required this.rowColumnIndex, + required this.column, + }); /// The coordinates of the cell in [SfDataGrid]. final RowColumnIndex rowColumnIndex; @@ -42,13 +44,13 @@ class DataGridCellDetails { class DataGridCellTapDetails extends DataGridCellDetails { /// Creates a [DataGridCellTapDetails] with the specified [rowColumnIndex], /// [column], [globalPosition], [localPosition] and [kind]. - const DataGridCellTapDetails( - {required RowColumnIndex rowColumnIndex, - required GridColumn column, - required this.globalPosition, - required this.localPosition, - required this.kind}) - : super(rowColumnIndex: rowColumnIndex, column: column); + const DataGridCellTapDetails({ + required RowColumnIndex rowColumnIndex, + required GridColumn column, + required this.globalPosition, + required this.localPosition, + required this.kind, + }) : super(rowColumnIndex: rowColumnIndex, column: column); /// The global position at which the pointer contacted the screen. final Offset globalPosition; @@ -95,12 +97,17 @@ class RowHeightDetails { /// [SfDataGrid.columnSizer] property. /// /// The auto size is calculated based on default [TextStyle] of the datagrid. - double getIntrinsicRowHeight(int rowIndex, - {bool canIncludeHiddenColumns = false, - List excludedColumns = const []}) { - return getAutoFitRowHeight(_columnSizer, rowIndex, - canIncludeHiddenColumns: canIncludeHiddenColumns, - excludedColumns: excludedColumns); + double getIntrinsicRowHeight( + int rowIndex, { + bool canIncludeHiddenColumns = false, + List excludedColumns = const [], + }) { + return getAutoFitRowHeight( + _columnSizer, + rowIndex, + canIncludeHiddenColumns: canIncludeHiddenColumns, + excludedColumns: excludedColumns, + ); } } @@ -113,9 +120,10 @@ class RowHeightDetails { class DataGridCellDoubleTapDetails extends DataGridCellDetails { /// Creates a [DataGridCellDoubleTapDetails] with the specified [rowColumnIndex] /// and [column]. - const DataGridCellDoubleTapDetails( - {required RowColumnIndex rowColumnIndex, required GridColumn column}) - : super(rowColumnIndex: rowColumnIndex, column: column); + const DataGridCellDoubleTapDetails({ + required RowColumnIndex rowColumnIndex, + required GridColumn column, + }) : super(rowColumnIndex: rowColumnIndex, column: column); } /// Details for callbacks that use [DataGridCellLongPressDetails]. @@ -186,10 +194,11 @@ class DataGridSwipeStartDetails { @immutable class DataGridSwipeUpdateDetails { /// Creates a [DataGridSwipeUpdateDetails] class for [SfDataGrid]. - const DataGridSwipeUpdateDetails( - {required this.rowIndex, - required this.swipeOffset, - required this.swipeDirection}); + const DataGridSwipeUpdateDetails({ + required this.rowIndex, + required this.swipeOffset, + required this.swipeDirection, + }); /// An index of a row which is swiped. final int rowIndex; @@ -205,8 +214,10 @@ class DataGridSwipeUpdateDetails { @immutable class DataGridSwipeEndDetails { /// Creates a [DataGridSwipeEndDetails] class for [SfDataGrid]. - const DataGridSwipeEndDetails( - {required this.rowIndex, required this.swipeDirection}); + const DataGridSwipeEndDetails({ + required this.rowIndex, + required this.swipeDirection, + }); /// An index of a row which is swiped. final int rowIndex; @@ -219,8 +230,11 @@ class DataGridSwipeEndDetails { @immutable class ColumnResizeStartDetails { /// Creates the [ColumnResizeStartDetails] with the specified [column] and [width]. - const ColumnResizeStartDetails( - {required this.column, required this.width, required this.columnIndex}); + const ColumnResizeStartDetails({ + required this.column, + required this.width, + required this.columnIndex, + }); /// A column that is going to be resized. final GridColumn column; @@ -236,8 +250,11 @@ class ColumnResizeStartDetails { @immutable class ColumnResizeUpdateDetails { /// Creates the [ColumnResizeUpdateDetails] with the specified [column] and [width]. - const ColumnResizeUpdateDetails( - {required this.column, required this.width, required this.columnIndex}); + const ColumnResizeUpdateDetails({ + required this.column, + required this.width, + required this.columnIndex, + }); /// A column that is being resized. final GridColumn column; @@ -253,8 +270,11 @@ class ColumnResizeUpdateDetails { @immutable class ColumnResizeEndDetails { /// Creates the [ColumnResizeEndDetails] with the specified [column] and [width]. - const ColumnResizeEndDetails( - {required this.column, required this.width, required this.columnIndex}); + const ColumnResizeEndDetails({ + required this.column, + required this.width, + required this.columnIndex, + }); /// A column that is resized. final GridColumn column; @@ -276,8 +296,10 @@ class ColumnResizeEndDetails { class DataGridFilterChangeDetails { /// Creates the [DataGridFilterChangeDetails] for the /// `DataGridFilterChangingCallback` and `DataGridFilterChangedCallback`. - const DataGridFilterChangeDetails( - {required this.column, required this.filterConditions}); + const DataGridFilterChangeDetails({ + required this.column, + required this.filterConditions, + }); /// The column where the current filtering is applied. final GridColumn column; @@ -289,14 +311,17 @@ class DataGridFilterChangeDetails { /// Sets the `columnSizer` instance to the [RowHeightDetails] class. void setColumnSizerInRowHeightDetailsArgs( - RowHeightDetails rowHeightDetails, ColumnSizer columnSizer) { + RowHeightDetails rowHeightDetails, + ColumnSizer columnSizer, +) { rowHeightDetails._columnSizer = columnSizer; } ///Sets the `dataGridConfiguration` instance to the [DataGridSwipeStartDetails] class void setSwipeOffsetInDataGridSwipeStartDetailsArgs( - DataGridConfiguration dataGridConfiguration, - DataGridSwipeStartDetails swipeStartDetails) { + DataGridConfiguration dataGridConfiguration, + DataGridSwipeStartDetails swipeStartDetails, +) { swipeStartDetails._dataGridConfiguration = dataGridConfiguration; } @@ -305,11 +330,12 @@ void setSwipeOffsetInDataGridSwipeStartDetailsArgs( class DataGridColumnDragDetails { /// Creates the [DataGridColumnDragDetails] for the /// `DataGridColumnDraggingCallback`. - const DataGridColumnDragDetails( - {required this.from, - required this.to, - required this.action, - required this.offset}); + const DataGridColumnDragDetails({ + required this.from, + required this.to, + required this.action, + required this.offset, + }); //// An index of a column that is being dragged. final int from; @@ -340,8 +366,11 @@ class ColumnGroup { @immutable class DataGridGroupChangingDetails { /// - const DataGridGroupChangingDetails( - {required this.key, required this.groupLevel, required this.isExpanded}); + const DataGridGroupChangingDetails({ + required this.key, + required this.groupLevel, + required this.isExpanded, + }); /// Specifies the key in a caption summary row. final String key; @@ -359,8 +388,11 @@ class DataGridGroupChangingDetails { @immutable class DataGridGroupChangedDetails { /// - const DataGridGroupChangedDetails( - {required this.key, required this.groupLevel, required this.isExpanded}); + const DataGridGroupChangedDetails({ + required this.key, + required this.groupLevel, + required this.isExpanded, + }); /// Specifies the key in a caption summary row. final String key; @@ -377,8 +409,11 @@ class DataGridGroupChangedDetails { /// Signature for [SfDataGrid.onCheckboxValueChanged] callbacks. class DataGridCheckboxValueChangedDetails { /// - const DataGridCheckboxValueChangedDetails( - {required this.value, required this.row, required this.rowType}); + const DataGridCheckboxValueChangedDetails({ + required this.value, + required this.row, + required this.rowType, + }); /// Specifies the current value of the checkbox. final bool value; diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/datagrid_helper.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/datagrid_helper.dart index 8fbad9df4..e37535502 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/datagrid_helper.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/datagrid_helper.dart @@ -27,7 +27,9 @@ int getHeaderIndex(DataGridConfiguration dataGridConfiguration) { // actual column header row index. if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { headerIndex -= getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.top); + dataGridConfiguration, + GridTableSummaryRowPosition.top, + ); } return headerIndex < 0 ? 0 : headerIndex; @@ -37,7 +39,9 @@ int getHeaderIndex(DataGridConfiguration dataGridConfiguration) { /// In this we will not include the column like, indent column, row /// header etc int resolveToGridVisibleColumnIndex( - DataGridConfiguration dataGridConfiguration, int columnIndex) { + DataGridConfiguration dataGridConfiguration, + int columnIndex, +) { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { final int length = dataGridConfiguration.source.groupedColumns.length; columnIndex -= length; @@ -53,8 +57,11 @@ int resolveToGridVisibleColumnIndex( /// Helps to resolve the column index based on the [DataGridRowAdapter.cells] /// count when indent cell, row header, [SfDataGrid.showCheckboxColumn] are enabled. int resolveToDataGridRowAdapterCellIndex( - DataGridConfiguration dataGridConfiguration, int columnIndex) { - final int totalColumnCount = dataGridConfiguration.container.columnCount + + DataGridConfiguration dataGridConfiguration, + int columnIndex, +) { + final int totalColumnCount = + dataGridConfiguration.container.columnCount + dataGridConfiguration.source.groupedColumns.length; if (columnIndex >= totalColumnCount) { @@ -72,7 +79,9 @@ int resolveToDataGridRowAdapterCellIndex( /// Help to resolve the record index to [SfDataGrid] position row index. int resolveToRowIndex( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (rowIndex < 0) { return -1; } @@ -87,16 +96,20 @@ int resolveToRowIndex( /// Help to resolve the record index to display element position row index. int resolveStartRecordIndex( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (rowIndex < 0) { return -1; } - final int headerLineCount = - resolveStartIndexBasedOnPosition(dataGridConfiguration); + final int headerLineCount = resolveStartIndexBasedOnPosition( + dataGridConfiguration, + ); rowIndex -= headerLineCount; - final int totalCount = dataGridConfiguration.source.groupedColumns.isNotEmpty - ? dataGridConfiguration.group!.displayElements!.grouped.length - : dataGridConfiguration.container.rowCount; + final int totalCount = + dataGridConfiguration.source.groupedColumns.isNotEmpty + ? dataGridConfiguration.group!.displayElements!.grouped.length + : dataGridConfiguration.container.rowCount; if (rowIndex >= 0 && rowIndex < totalCount) { return rowIndex; } else { @@ -106,7 +119,9 @@ int resolveStartRecordIndex( /// Help to resolve the group from the display elements. dynamic getGroupElement( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (rowIndex >= 0 && rowIndex < dataGridConfiguration.group!.displayElements!.grouped.length) { return dataGridConfiguration.group!.displayElements!.grouped[rowIndex]; @@ -116,7 +131,9 @@ dynamic getGroupElement( /// Help to get the row by the row index. DataGridRow? getDataRow( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { final dynamic element = getGroupElement(dataGridConfiguration, rowIndex); return element is DataGridRow ? element : null; @@ -135,7 +152,9 @@ int resolveEffectiveRowCount(DataGridConfiguration dataGridConfiguration) { /// Help to resolve the next grouped row from the display elements. dynamic getNextGroupInfo( - dynamic rowData, DataGridConfiguration dataGridConfiguration) { + dynamic rowData, + DataGridConfiguration dataGridConfiguration, +) { final List grouped = dataGridConfiguration.group!.displayElements!.grouped; final int index = grouped.indexOf(rowData) + 1; @@ -155,7 +174,9 @@ double getSwipeMaxOffset(DataGridConfiguration dataGridConfiguration) { /// Help to resolve the [SfDataGrid] position row index to record index. int resolveToRecordIndex( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (rowIndex < 0) { return -1; } @@ -165,9 +186,10 @@ int resolveToRecordIndex( } rowIndex = rowIndex - resolveStartIndexBasedOnPosition(dataGridConfiguration); - final int endIndex = dataGridConfiguration.source.groupedColumns.isNotEmpty - ? dataGridConfiguration.group!.displayElements!.grouped.length - : effectiveRows(dataGridConfiguration.source).length; + final int endIndex = + dataGridConfiguration.source.groupedColumns.isNotEmpty + ? dataGridConfiguration.group!.displayElements!.grouped.length + : effectiveRows(dataGridConfiguration.source).length; if (rowIndex >= 0 && (rowIndex < endIndex)) { return rowIndex; } else { @@ -177,29 +199,40 @@ int resolveToRecordIndex( /// Helps to resolve the [SfDataGrid] row column index to record [RowColumnIndex]. RowColumnIndex resolveToRecordRowColumnIndex( - DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { - final int rowIndex = - resolveToRecordIndex(dataGridConfiguration, rowColumnIndex.rowIndex); + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, +) { + final int rowIndex = resolveToRecordIndex( + dataGridConfiguration, + rowColumnIndex.rowIndex, + ); final int columnIndex = resolveToGridVisibleColumnIndex( - dataGridConfiguration, rowColumnIndex.columnIndex); + dataGridConfiguration, + rowColumnIndex.columnIndex, + ); return RowColumnIndex(rowIndex, columnIndex); } /// Helps to resolve the row and column index according to DataGrid alignment RowColumnIndex resolveToRowColumnIndex( - DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { - final int rowIndex = - resolveToRowIndex(dataGridConfiguration, rowColumnIndex.rowIndex); + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, +) { + final int rowIndex = resolveToRowIndex( + dataGridConfiguration, + rowColumnIndex.rowIndex, + ); final int columnIndex = resolveToGridVisibleColumnIndex( - dataGridConfiguration, rowColumnIndex.columnIndex); + dataGridConfiguration, + rowColumnIndex.columnIndex, + ); return RowColumnIndex(rowIndex, columnIndex); } /// Helps to find the exact starting scrolling row index. int resolveStartIndexBasedOnPosition( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { return dataGridConfiguration.headerLineCount; } @@ -212,7 +245,9 @@ int resolveToStartColumnIndex(DataGridConfiguration dataGridConfiguration) => 0; /// order. Its ignore the indent column, row header and provide the exact /// column index int resolveToScrollColumnIndex( - DataGridConfiguration dataGridConfiguration, int gridColumnIndex) { + DataGridConfiguration dataGridConfiguration, + int gridColumnIndex, +) { final int indentColumnCount = dataGridConfiguration.source.groupedColumns.length; @@ -234,7 +269,8 @@ int getLastFrozenColumnIndex(DataGridConfiguration dataGridConfiguration) { /// Get the starting index of frozen column in right side view, it /// will consider the right frozen pane int getStartFooterFrozenColumnIndex( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { final int columnsCount = dataGridConfiguration.container.columnCount; if (columnsCount <= 0 || dataGridConfiguration.footerFrozenColumnsCount <= 0) { @@ -264,7 +300,7 @@ int getStartFooterFrozenRowIndex(DataGridConfiguration dataGridConfiguration) { // Check footer frozen rows count exceeds the effective row count. final bool isFrozenRowCountExceeded = (effectiveRowCount - dataGridConfiguration.frozenRowsCount).isNegative || - dataGridConfiguration.footerFrozenRowsCount > effectiveRowCount; + dataGridConfiguration.footerFrozenRowsCount > effectiveRowCount; final int rowCount = dataGridConfiguration.container.rowCount; if (rowCount <= 0 || @@ -282,17 +318,24 @@ int getStartFooterFrozenRowIndex(DataGridConfiguration dataGridConfiguration) { /// Checks whether the row is a footer widget row or not. bool isFooterWidgetRow( - int rowIndex, DataGridConfiguration dataGridConfiguration) { + int rowIndex, + DataGridConfiguration dataGridConfiguration, +) { final int bottomSummariesCount = getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); final int footerIndex = dataGridConfiguration.container.rowCount - bottomSummariesCount - 1; return dataGridConfiguration.footer != null && rowIndex == footerIndex; } /// Checks whether the row is a caption summary row or not. -bool isCaptionSummaryRow(DataGridConfiguration dataGridConfiguration, - int rowIndex, bool canResolveIndex) { +bool isCaptionSummaryRow( + DataGridConfiguration dataGridConfiguration, + int rowIndex, + bool canResolveIndex, +) { if (canResolveIndex) { if (rowIndex == getHeaderIndex(dataGridConfiguration)) { return false; @@ -300,7 +343,7 @@ bool isCaptionSummaryRow(DataGridConfiguration dataGridConfiguration, rowIndex = resolveToRecordIndex(dataGridConfiguration, rowIndex); } - if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { + if (rowIndex >= 0 && dataGridConfiguration.source.groupedColumns.isNotEmpty) { final dynamic group = dataGridConfiguration.group?.displayElements?.grouped[rowIndex]; return group != null && group is Group; @@ -312,7 +355,9 @@ bool isCaptionSummaryRow(DataGridConfiguration dataGridConfiguration, /// Returns the row index of a footer widget row. int getFooterViewRowIndex(DataGridConfiguration dataGridConfiguration) { final int bottomSummaryRowsCount = getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); return dataGridConfiguration.container.rowCount - bottomSummaryRowsCount - 1; } @@ -320,14 +365,19 @@ int getFooterViewRowIndex(DataGridConfiguration dataGridConfiguration) { /// Checks whether the given row is a top summary row or not. bool isTopTableSummaryRow( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (dataGridConfiguration.tableSummaryRows.isNotEmpty && rowIndex < dataGridConfiguration.headerLineCount) { final int tableSummaryStartIndex = dataGridConfiguration.stackedHeaderRows.length + 1; - final int tableSummaryEndIndex = tableSummaryStartIndex + + final int tableSummaryEndIndex = + tableSummaryStartIndex + getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.top); + dataGridConfiguration, + GridTableSummaryRowPosition.top, + ); return rowIndex >= tableSummaryStartIndex && rowIndex < tableSummaryEndIndex; } @@ -336,12 +386,17 @@ bool isTopTableSummaryRow( /// Checks whether the given row is a bottom summary row or not. bool isBottomTableSummaryRow( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { final int tableSummaryEndIndex = dataGridConfiguration.container.rowCount; - final int tableSummaryStartIndex = tableSummaryEndIndex - + final int tableSummaryStartIndex = + tableSummaryEndIndex - getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); return rowIndex >= tableSummaryStartIndex && rowIndex < tableSummaryEndIndex; } @@ -350,7 +405,9 @@ bool isBottomTableSummaryRow( /// Checks whether the given row index is a table summary row or not. bool isTableSummaryIndex( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { return isTopTableSummaryRow(dataGridConfiguration, rowIndex) || isBottomTableSummaryRow(dataGridConfiguration, rowIndex); } @@ -358,13 +415,17 @@ bool isTableSummaryIndex( /// Checks whether the row index is a start index of a bottom summary rows or not. int getStartBottomSummaryRowIndex(DataGridConfiguration dataGridConfiguration) { final int bottomSummariesCount = getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); return dataGridConfiguration.container.rowCount - bottomSummariesCount; } /// Returns the table summary count based on position. -int getTableSummaryCount(DataGridConfiguration dataGridConfiguration, - GridTableSummaryRowPosition position) { +int getTableSummaryCount( + DataGridConfiguration dataGridConfiguration, + GridTableSummaryRowPosition position, +) { if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { return dataGridConfiguration.tableSummaryRows .where((GridTableSummaryRow row) => row.position == position) @@ -374,20 +435,29 @@ int getTableSummaryCount(DataGridConfiguration dataGridConfiguration, } /// Returns the title column span to the table summary column. -int getSummaryTitleColumnSpan(DataGridConfiguration dataGridConfiguration, - GridTableSummaryRow tableSummaryRow) { - int titleSpan = dataGridConfiguration.frozenColumnsCount > 0 - ? min(dataGridConfiguration.frozenColumnsCount, - tableSummaryRow.titleColumnSpan) - : tableSummaryRow.titleColumnSpan; +int getSummaryTitleColumnSpan( + DataGridConfiguration dataGridConfiguration, + GridTableSummaryRow tableSummaryRow, +) { + int titleSpan = + dataGridConfiguration.frozenColumnsCount > 0 + ? min( + dataGridConfiguration.frozenColumnsCount, + tableSummaryRow.titleColumnSpan, + ) + : tableSummaryRow.titleColumnSpan; titleSpan = min(titleSpan, dataGridConfiguration.container.columnCount); return titleSpan; } /// Returns the span count for the table summary column. -int getSummaryColumnSpan(DataGridConfiguration dataGridConfiguration, int index, - RowType rowType, GridTableSummaryRow? tableSummaryRow, - [int rowLevel = 0]) { +int getSummaryColumnSpan( + DataGridConfiguration dataGridConfiguration, + int index, + RowType rowType, + GridTableSummaryRow? tableSummaryRow, [ + int rowLevel = 0, +]) { int span = 0; int columnCount = dataGridConfiguration.container.columnCount; if (rowType == RowType.captionSummaryCoveredRow) { @@ -401,8 +471,10 @@ int getSummaryColumnSpan(DataGridConfiguration dataGridConfiguration, int index, index = resolveToScrollColumnIndex(dataGridConfiguration, index); if (rowType == RowType.tableSummaryRow) { if (tableSummaryRow != null) { - final int titleSpan = - getSummaryTitleColumnSpan(dataGridConfiguration, tableSummaryRow); + final int titleSpan = getSummaryTitleColumnSpan( + dataGridConfiguration, + tableSummaryRow, + ); if (titleSpan > 0 && index < titleSpan) { span = titleSpan - 1; } @@ -416,15 +488,18 @@ int getSummaryColumnSpan(DataGridConfiguration dataGridConfiguration, int index, /// Helps to get the table summary row for the given rowIndex from the /// `SfDataGrid.tableSummaryRows` collection. GridTableSummaryRow? getTableSummaryRow( - DataGridConfiguration dataGridConfiguration, - int rowIndex, - GridTableSummaryRowPosition position) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, + GridTableSummaryRowPosition position, +) { GridTableSummaryRow getSummaryRowByPosition( - GridTableSummaryRowPosition position, int index) { - final List summaryRows = dataGridConfiguration - .tableSummaryRows - .where((GridTableSummaryRow row) => row.position == position) - .toList(); + GridTableSummaryRowPosition position, + int index, + ) { + final List summaryRows = + dataGridConfiguration.tableSummaryRows + .where((GridTableSummaryRow row) => row.position == position) + .toList(); return summaryRows[index]; } @@ -432,8 +507,10 @@ GridTableSummaryRow? getTableSummaryRow( if (position == GridTableSummaryRowPosition.bottom) { final int startTableSummaryIndex = dataGridConfiguration.container.rowCount - - getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + getTableSummaryCount( + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); currentSummaryRowIndex = rowIndex - startTableSummaryIndex; } else if (position == GridTableSummaryRowPosition.top) { final int startTableSummaryIndex = @@ -446,7 +523,9 @@ GridTableSummaryRow? getTableSummaryRow( /// Calculates the summary value for the given summary column based on the /// summary type. String getSummaryValue( - GridSummaryColumn summaryColumn, List rows) { + GridSummaryColumn summaryColumn, + List rows, +) { switch (summaryColumn.summaryType) { case GridSummaryType.sum: return calculateSum(rows, summaryColumn); @@ -467,8 +546,8 @@ String calculateSum(List rows, GridSummaryColumn summaryColumn) { bool isNumericColumn = false; for (final DataGridRow row in rows) { final DataGridCell? cell = row.getCells().firstWhereOrNull( - (DataGridCell element) => - element.columnName == summaryColumn.columnName); + (DataGridCell element) => element.columnName == summaryColumn.columnName, + ); if (cell != null && cell.value != null) { if (!isNumericColumn && cell.value is! num) { break; @@ -487,13 +566,15 @@ String calculateSum(List rows, GridSummaryColumn summaryColumn) { /// Calculates the minimum value for the given summary column. String calculateMinimum( - List rows, GridSummaryColumn summaryColumn) { + List rows, + GridSummaryColumn summaryColumn, +) { dynamic minimum; bool isNumericColumn = false; for (final DataGridRow row in rows) { final DataGridCell? cell = row.getCells().firstWhereOrNull( - (DataGridCell element) => - element.columnName == summaryColumn.columnName); + (DataGridCell element) => element.columnName == summaryColumn.columnName, + ); if (cell != null && cell.value != null) { if (!isNumericColumn && cell.value is! num) { break; @@ -513,13 +594,15 @@ String calculateMinimum( /// Calculates the maximum value for the given summary column. String calculateMaximum( - List rows, GridSummaryColumn summaryColumn) { + List rows, + GridSummaryColumn summaryColumn, +) { dynamic maximum; bool isNumericColumn = false; for (final DataGridRow row in rows) { final DataGridCell? cell = row.getCells().firstWhereOrNull( - (DataGridCell element) => - element.columnName == summaryColumn.columnName); + (DataGridCell element) => element.columnName == summaryColumn.columnName, + ); if (cell != null && cell.value != null) { if (!isNumericColumn && cell.value is! num) { break; @@ -539,14 +622,16 @@ String calculateMaximum( /// Calculates the average value for the given summary column. String calculateAverage( - List rows, GridSummaryColumn summaryColumn) { + List rows, + GridSummaryColumn summaryColumn, +) { num? sum; int count = 0; bool isNumericColumn = false; for (final DataGridRow row in rows) { final DataGridCell? cell = row.getCells().firstWhereOrNull( - (DataGridCell element) => - element.columnName == summaryColumn.columnName); + (DataGridCell element) => element.columnName == summaryColumn.columnName, + ); if (cell != null && cell.value != null) { if (!isNumericColumn && cell.value is! num) { @@ -644,8 +729,11 @@ bool _compareByType(FilterCondition condition, Object? cellValue, String type) { } /// Checkes whether any cell has greater value than the filter value. -bool compareGreaterThan(FilterCondition condition, Object? cellValue, - [bool checkEqual = false]) { +bool compareGreaterThan( + FilterCondition condition, + Object? cellValue, [ + bool checkEqual = false, +]) { if (condition.value == null || cellValue == null) { return false; } @@ -659,8 +747,11 @@ bool compareGreaterThan(FilterCondition condition, Object? cellValue, } /// Checkes whether any cell has less value than the filter value. -bool compareLessThan(FilterCondition condition, Object? cellValue, - [bool checkEqual = false]) { +bool compareLessThan( + FilterCondition condition, + Object? cellValue, [ + bool checkEqual = false, +]) { if (condition.value == null || cellValue == null) { return false; } @@ -690,7 +781,9 @@ int? _getCompareValue(Object? cellValue, Object? filterValue) { /// Gets the advanced filter name. String getFilterTileText( - SfLocalizations localizations, AdvancedFilterType type) { + SfLocalizations localizations, + AdvancedFilterType type, +) { switch (type) { case AdvancedFilterType.text: return localizations.textFiltersDataGridFilteringLabel; @@ -703,7 +796,10 @@ String getFilterTileText( /// Returns the Sort button text based on the filter type. String getSortButtonText( - SfLocalizations localizations, bool isAscending, AdvancedFilterType type) { + SfLocalizations localizations, + bool isAscending, + AdvancedFilterType type, +) { switch (type) { case AdvancedFilterType.text: return isAscending @@ -722,7 +818,9 @@ String getSortButtonText( /// Returns the `FilterType` based on the given value. FilterType getFilterType( - DataGridConfiguration dataGridConfiguration, String value) { + DataGridConfiguration dataGridConfiguration, + String value, +) { bool isEqual(String labelValue) { return labelValue == value; } @@ -766,8 +864,11 @@ FilterType getFilterType( } /// Gets the name of the given `FilterType`. -String getFilterName(DataGridConfiguration dataGridConfiguration, - FilterType type, Object? value) { +String getFilterName( + DataGridConfiguration dataGridConfiguration, + FilterType type, + Object? value, +) { final SfLocalizations localizations = dataGridConfiguration.localizations; switch (type) { case FilterType.equals: @@ -828,8 +929,11 @@ String getFilterName(DataGridConfiguration dataGridConfiguration, //----------------------------------------------------------------------------// /// Helps to get the sequence of spanned cell indexes -List getChildSequence(DataGridConfiguration dataGridConfiguration, - StackedHeaderCell? column, int rowIndex) { +List getChildSequence( + DataGridConfiguration dataGridConfiguration, + StackedHeaderCell? column, + int rowIndex, +) { final List childSequenceNo = []; if (column != null && column.columnNames.isNotEmpty) { @@ -847,17 +951,24 @@ List getChildSequence(DataGridConfiguration dataGridConfiguration, } /// Helps to find the total count of row spanned. -int getRowSpan(DataGridConfiguration dataGridConfiguration, int rowIndex, - int columnIndex, bool isStackedHeader, - {String? mappingName, StackedHeaderCell? stackedHeaderCell}) { +int getRowSpan( + DataGridConfiguration dataGridConfiguration, + int rowIndex, + int columnIndex, + bool isStackedHeader, { + String? mappingName, + StackedHeaderCell? stackedHeaderCell, +}) { int rowSpan = 0; int startIndex = 0; int endIndex = 0; if (isStackedHeader && stackedHeaderCell != null) { - final List> spannedColumns = - getConsecutiveRanges(getChildColumnIndexes(stackedHeaderCell)); - final List? spannedColumn = spannedColumns - .singleWhereOrNull((List element) => element.first == columnIndex); + final List> spannedColumns = getConsecutiveRanges( + getChildColumnIndexes(stackedHeaderCell), + ); + final List? spannedColumn = spannedColumns.singleWhereOrNull( + (List element) => element.first == columnIndex, + ); if (spannedColumn != null) { startIndex = spannedColumn.reduce(min); endIndex = startIndex + spannedColumn.length - 1; @@ -874,8 +985,9 @@ int getRowSpan(DataGridConfiguration dataGridConfiguration, int rowIndex, dataGridConfiguration.stackedHeaderRows[rowIndex]; for (final StackedHeaderCell stackedColumn in stackedHeaderRow.cells) { if (isStackedHeader) { - final List> columnsRange = - getConsecutiveRanges(getChildColumnIndexes(stackedColumn)); + final List> columnsRange = getConsecutiveRanges( + getChildColumnIndexes(stackedColumn), + ); for (final List column in columnsRange) { if ((startIndex >= column.first && startIndex <= column.last) || (endIndex >= column.first && endIndex <= column.last)) { @@ -931,20 +1043,24 @@ List> getConsecutiveRanges(List columnsIndex) { /// Get the visible line based on view size and scroll offset. /// Based on the [TextDirection] it will return visible lines info. VisibleLinesCollection getVisibleLines( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { if (dataGridConfiguration.textDirection == TextDirection.rtl) { dataGridConfiguration.container.scrollColumns.markDirty(); } return dataGridConfiguration.container.scrollColumns.getVisibleLines( - dataGridConfiguration.textDirection == TextDirection.rtl); + dataGridConfiguration.textDirection == TextDirection.rtl, + ); } /// Helps to scroll the [SfDataGrid] vertically. /// [canAnimate]: decide to apply animation on scrolling or not. Future scrollVertical( - DataGridConfiguration dataGridConfiguration, double verticalOffset, - [bool canAnimate = false]) async { + DataGridConfiguration dataGridConfiguration, + double verticalOffset, [ + bool canAnimate = false, +]) async { final ScrollController? verticalController = dataGridConfiguration.verticalScrollController; @@ -953,19 +1069,22 @@ Future scrollVertical( } final double maxScrollExtent = max( - dataGridConfiguration.container.rowHeights.totalExtent - - dataGridConfiguration.viewHeight, - 0.0); + dataGridConfiguration.container.rowHeights.totalExtent - + dataGridConfiguration.viewHeight, + 0.0, + ); verticalOffset = min(verticalOffset, maxScrollExtent); - verticalOffset = verticalOffset.isNegative || verticalOffset == 0.0 - ? verticalController.position.minScrollExtent - : verticalOffset; + verticalOffset = + verticalOffset.isNegative || verticalOffset == 0.0 + ? verticalController.position.minScrollExtent + : verticalOffset; if (canAnimate) { await dataGridConfiguration.verticalScrollController!.animateTo( - verticalOffset, - duration: const Duration(milliseconds: 1000), - curve: Curves.fastOutSlowIn); + verticalOffset, + duration: const Duration(milliseconds: 1000), + curve: Curves.fastOutSlowIn, + ); } else { dataGridConfiguration.verticalScrollController!.jumpTo(verticalOffset); } @@ -975,8 +1094,10 @@ Future scrollVertical( /// Helps to scroll the [SfDataGrid] horizontally. /// [canAnimate]: decide to apply animation on scrolling or not. Future scrollHorizontal( - DataGridConfiguration dataGridConfiguration, double horizontalOffset, - [bool canAnimate = false]) async { + DataGridConfiguration dataGridConfiguration, + double horizontalOffset, [ + bool canAnimate = false, +]) async { final ScrollController? horizontalController = dataGridConfiguration.horizontalScrollController; @@ -985,19 +1106,22 @@ Future scrollHorizontal( } final double maxScrollExtent = max( - dataGridConfiguration.container.columnWidths.totalExtent - - dataGridConfiguration.viewWidth, - 0.0); + dataGridConfiguration.container.columnWidths.totalExtent - + dataGridConfiguration.viewWidth, + 0.0, + ); horizontalOffset = min(horizontalOffset, maxScrollExtent); - horizontalOffset = horizontalOffset.isNegative || horizontalOffset == 0.0 - ? horizontalController.position.minScrollExtent - : horizontalOffset; + horizontalOffset = + horizontalOffset.isNegative || horizontalOffset == 0.0 + ? horizontalController.position.minScrollExtent + : horizontalOffset; if (canAnimate) { await dataGridConfiguration.horizontalScrollController!.animateTo( - horizontalOffset, - duration: const Duration(milliseconds: 1000), - curve: Curves.fastOutSlowIn); + horizontalOffset, + duration: const Duration(milliseconds: 1000), + curve: Curves.fastOutSlowIn, + ); } else { dataGridConfiguration.horizontalScrollController!.jumpTo(horizontalOffset); } @@ -1005,8 +1129,11 @@ Future scrollHorizontal( } /// Decide to enable swipe in [SfDataGrid] -bool canSwipeRow(DataGridConfiguration dataGridConfiguration, - DataGridRowSwipeDirection swipeDirection, double swipeOffset) { +bool canSwipeRow( + DataGridConfiguration dataGridConfiguration, + DataGridRowSwipeDirection swipeDirection, + double swipeOffset, +) { if (dataGridConfiguration.container.horizontalOffset == 0) { if ((dataGridConfiguration.container.extentWidth > dataGridConfiguration.viewWidth) && @@ -1034,32 +1161,41 @@ bool canSwipeRow(DataGridConfiguration dataGridConfiguration, /// Decide the swipe direction based on [TextDirection]. DataGridRowSwipeDirection getSwipeDirection( - DataGridConfiguration dataGridConfiguration, double swipingOffset) { + DataGridConfiguration dataGridConfiguration, + double swipingOffset, +) { return swipingOffset >= 0 ? dataGridConfiguration.textDirection == TextDirection.ltr ? DataGridRowSwipeDirection.startToEnd : DataGridRowSwipeDirection.endToStart : dataGridConfiguration.textDirection == TextDirection.ltr - ? DataGridRowSwipeDirection.endToStart - : DataGridRowSwipeDirection.startToEnd; + ? DataGridRowSwipeDirection.endToStart + : DataGridRowSwipeDirection.startToEnd; } /// Helps to get the [DataGridRow] based on respective rowIndex. DataGridRow getDataGridRow( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { final int recordIndex = resolveToRecordIndex(dataGridConfiguration, rowIndex); return effectiveRows(dataGridConfiguration.source)[recordIndex]; } /// Helps to get the [DataGridRowAdapter] based on respective [DataGridRow]. DataGridRowAdapter? getDataGridRowAdapter( - DataGridConfiguration dataGridConfiguration, DataGridRow dataGridRow) { + DataGridConfiguration dataGridConfiguration, + DataGridRow dataGridRow, +) { DataGridRowAdapter buildBlankRow(DataGridRow dataGridRow) { return DataGridRowAdapter( - cells: dataGridConfiguration.columns - .map( - (GridColumn dataCell) => SizedBox.fromSize(size: Size.zero)) - .toList()); + cells: + dataGridConfiguration.columns + .map( + (GridColumn dataCell) => SizedBox.fromSize(size: Size.zero), + ) + .toList(), + ); } return dataGridConfiguration.source.buildRow(dataGridRow) ?? @@ -1068,8 +1204,12 @@ DataGridRowAdapter? getDataGridRowAdapter( /// Check the length of two list. /// If its not satisfies it throw a exception. -bool debugCheckTheLength(DataGridConfiguration dataGridConfiguration, - int columnLength, int cellLength, String message) { +bool debugCheckTheLength( + DataGridConfiguration dataGridConfiguration, + int columnLength, + int cellLength, + String message, +) { cellLength += dataGridConfiguration.showCheckboxColumn ? 1 : 0; assert(() { if (columnLength != cellLength) { @@ -1085,7 +1225,8 @@ bool debugCheckTheLength(DataGridConfiguration dataGridConfiguration, /// Return the cumulative distance of frozen top rows. The cumulative distance /// covered the header, stacked header and freeze pane double getCumulativeFrozenRowsHeight( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { final int topFrozenRowsLength = dataGridConfiguration.container.frozenRows; double cumulativeFrozenRowsHeight = 0.0; for (int index = 0; index < topFrozenRowsLength; index++) { @@ -1097,7 +1238,8 @@ double getCumulativeFrozenRowsHeight( /// Return the cumulative distance of frozen bottom rows. double getCumulativeFooterFrozenRowsHeight( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { final int bottomFrozenRowsLength = dataGridConfiguration.container.footerFrozenRows; double cumulativeFooterFrozenRowsHeight = 0.0; @@ -1112,7 +1254,8 @@ double getCumulativeFooterFrozenRowsHeight( /// Return the cumulative distance of frozen column on left side. The /// cumulative distance covered the row header, indent cell, freeze pane double getCumulativeFrozenColumnsWidth( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { final int leftColumnCount = dataGridConfiguration.container.frozenColumns; double cumulativeFrozenColumnWidth = 0.0; for (int index = 0; index < leftColumnCount; index++) { @@ -1124,7 +1267,8 @@ double getCumulativeFrozenColumnsWidth( /// Return the cumulative distance of frozen right side columns. double getCumulativeFooterFrozenColumnsWidth( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { final int rightColumnCount = dataGridConfiguration.container.footerFrozenColumns; double cumulativeFooterFrozenColumnWidth = 0.0; @@ -1138,21 +1282,29 @@ double getCumulativeFooterFrozenColumnsWidth( /// Resolve the cumulative horizontal offset with frozen rows. double resolveVerticalScrollOffset( - DataGridConfiguration dataGridConfiguration, double verticalOffset) { - final double leftOffset = - getCumulativeFrozenRowsHeight(dataGridConfiguration); - final double rightOffset = - getCumulativeFooterFrozenRowsHeight(dataGridConfiguration); + DataGridConfiguration dataGridConfiguration, + double verticalOffset, +) { + final double leftOffset = getCumulativeFrozenRowsHeight( + dataGridConfiguration, + ); + final double rightOffset = getCumulativeFooterFrozenRowsHeight( + dataGridConfiguration, + ); final double bottomOffset = dataGridConfiguration.container.extentHeight - rightOffset; if (verticalOffset >= bottomOffset) { return dataGridConfiguration - .verticalScrollController!.position.maxScrollExtent; + .verticalScrollController! + .position + .maxScrollExtent; } if (verticalOffset <= leftOffset) { return dataGridConfiguration - .verticalScrollController!.position.minScrollExtent; + .verticalScrollController! + .position + .minScrollExtent; } for (int i = 0; i < dataGridConfiguration.container.frozenRows; i++) { @@ -1164,21 +1316,29 @@ double resolveVerticalScrollOffset( /// Resolve the cumulative horizontal offset with frozen column. double resolveHorizontalScrollOffset( - DataGridConfiguration dataGridConfiguration, double horizontalOffset) { - final double topOffset = - getCumulativeFrozenColumnsWidth(dataGridConfiguration); - final double bottomOffset = - getCumulativeFooterFrozenColumnsWidth(dataGridConfiguration); + DataGridConfiguration dataGridConfiguration, + double horizontalOffset, +) { + final double topOffset = getCumulativeFrozenColumnsWidth( + dataGridConfiguration, + ); + final double bottomOffset = getCumulativeFooterFrozenColumnsWidth( + dataGridConfiguration, + ); final double rightOffset = dataGridConfiguration.container.extentWidth - bottomOffset; if (horizontalOffset >= rightOffset) { return dataGridConfiguration - .horizontalScrollController!.position.maxScrollExtent; + .horizontalScrollController! + .position + .maxScrollExtent; } if (horizontalOffset <= topOffset) { return dataGridConfiguration - .horizontalScrollController!.position.minScrollExtent; + .horizontalScrollController! + .position + .minScrollExtent; } for (int i = 0; i < dataGridConfiguration.container.frozenColumns; i++) { @@ -1190,7 +1350,9 @@ double resolveHorizontalScrollOffset( /// Get the vertical offset with reduction of frozen rows double getVerticalOffset( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { if (rowIndex < 0) { return dataGridConfiguration.container.verticalOffset; } @@ -1203,7 +1365,9 @@ double getVerticalOffset( /// Get the vertical offset with reduction of frozen columns double getHorizontalOffset( - DataGridConfiguration dataGridConfiguration, int columnIndex) { + DataGridConfiguration dataGridConfiguration, + int columnIndex, +) { if (columnIndex < 0) { return dataGridConfiguration.container.horizontalOffset; } @@ -1218,21 +1382,24 @@ double getHorizontalOffset( /// It's helps to get the position of rows and column scroll into desired /// DataGridScrollPosition. double resolveScrollOffsetToPosition( - DataGridScrollPosition position, - ScrollAxisBase scrollAxisBase, - double measuredScrollOffset, - double viewDimension, - double headerExtent, - double bottomExtent, - double defaultDimension, - double defaultScrollOffset, - int index) { + DataGridScrollPosition position, + ScrollAxisBase scrollAxisBase, + double measuredScrollOffset, + double viewDimension, + double headerExtent, + double bottomExtent, + double defaultDimension, + double defaultScrollOffset, + int index, +) { if (position == DataGridScrollPosition.center) { - measuredScrollOffset = measuredScrollOffset - + measuredScrollOffset = + measuredScrollOffset - ((viewDimension - bottomExtent - headerExtent) / 2) + (defaultDimension / 2); } else if (position == DataGridScrollPosition.end) { - measuredScrollOffset = measuredScrollOffset - + measuredScrollOffset = + measuredScrollOffset - (viewDimension - bottomExtent - headerExtent) + defaultDimension; } else if (position == DataGridScrollPosition.makeVisible) { @@ -1246,7 +1413,8 @@ double resolveScrollOffsetToPosition( measuredScrollOffset = defaultScrollOffset; } if (defaultScrollOffset - measuredScrollOffset < 0) { - measuredScrollOffset = measuredScrollOffset - + measuredScrollOffset = + measuredScrollOffset - (viewDimension - bottomExtent - headerExtent) + defaultDimension; } @@ -1257,7 +1425,9 @@ double resolveScrollOffsetToPosition( /// This method helps to resolve getting the column for the tap interaction callbacks. GridColumn? getGridColumn( - DataGridConfiguration dataGridConfiguration, DataCellBase dataCell) { + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, +) { GridColumn? column = dataCell.gridColumn; if (dataCell.dataRow != null && (dataCell.dataRow!.rowType == RowType.captionSummaryCoveredRow || @@ -1265,10 +1435,11 @@ GridColumn? getGridColumn( final int startIndex = dataGridConfiguration.showCheckboxColumn ? 1 : 0; column = dataGridConfiguration.columns.firstWhereOrNull( - (GridColumn element) => - element.actualWidth > 0 && - element.visible && - dataGridConfiguration.columns.indexOf(element) >= startIndex); + (GridColumn element) => + element.actualWidth > 0 && + element.visible && + dataGridConfiguration.columns.indexOf(element) >= startIndex, + ); } return column; } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/enums.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/enums.dart index 389e14fc1..0238b0d0f 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/enums.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/enums.dart @@ -35,7 +35,7 @@ enum RowType { tableSummaryCoveredRow, /// Specifies the SpannedDataRow that displays the caption summary value in row. - captionSummaryCoveredRow + captionSummaryCoveredRow, } /// Describes the possible values for cell types. @@ -154,7 +154,7 @@ enum SelectionMode { singleDeselect, /// Specifies that multiple rows can be selected. - multiple + multiple, } /// Decides whether the navigation in the [SfDataGrid] should be cell wise @@ -166,7 +166,7 @@ enum GridNavigationMode { /// The selection can be moved among /// the rows alone and current cell will not be shown. - row + row, } /// Specifies the direction of the sort operation. @@ -175,7 +175,7 @@ enum DataGridSortDirection { ascending, /// Sorts in descending order. - descending + descending, } /// Specifies the different tap actions available for applying sorting. @@ -230,7 +230,7 @@ enum EditingGestureType { tap, /// Editing is triggered on double tap. - doubleTap + doubleTap, } /// Determines how table summary row should be positioned in [SfDataGrid]. @@ -384,5 +384,5 @@ enum DataGridColumnDragAction { dropping, /// Specifies the dragging operation is ended for a column. - dropped + dropped, } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/selection_helper.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/selection_helper.dart index f794ed542..4d76ed989 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/selection_helper.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/helper/selection_helper.dart @@ -15,19 +15,24 @@ import 'enums.dart'; /// Get the row index in data grid based provided DataGridRow int resolveToRowIndex( - DataGridConfiguration dataGridConfiguration, DataGridRow record) { - final DataGridRow? rec = effectiveRows(dataGridConfiguration.source) - .firstWhereOrNull((DataGridRow rec) => rec == record); + DataGridConfiguration dataGridConfiguration, + DataGridRow record, +) { + final DataGridRow? rec = effectiveRows( + dataGridConfiguration.source, + ).firstWhereOrNull((DataGridRow rec) => rec == record); if (rec == null) { return -1; } - int recordIndex = dataGridConfiguration.source.groupedColumns.isNotEmpty - ? dataGridConfiguration.group!.displayElements!.grouped.indexOf(rec) - : effectiveRows(dataGridConfiguration.source).indexOf(rec); + int recordIndex = + dataGridConfiguration.source.groupedColumns.isNotEmpty + ? dataGridConfiguration.group!.displayElements!.grouped.indexOf(rec) + : effectiveRows(dataGridConfiguration.source).indexOf(rec); - recordIndex += - grid_helper.resolveStartIndexBasedOnPosition(dataGridConfiguration); + recordIndex += grid_helper.resolveStartIndexBasedOnPosition( + dataGridConfiguration, + ); return recordIndex.isNegative ? -1 : recordIndex; } @@ -68,8 +73,10 @@ int getFirstNavigatingRowIndex(DataGridConfiguration dataGridConfiguration) { final int index = getFirstRowIndex(dataGridConfiguration); const int count = 0; for (int start = index; start >= 0; start--) { - final List hiddenRowInfo = - dataGridConfiguration.container.rowHeights.getHidden(start, count); + final List hiddenRowInfo = dataGridConfiguration + .container + .rowHeights + .getHidden(start, count); final bool isHiddenRow = hiddenRowInfo.first as bool; if (!isHiddenRow) { return start; @@ -100,12 +107,16 @@ int getLastNavigatingRowIndex(DataGridConfiguration dataGridConfiguration) { } if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { lastRowIndex -= grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); } for (int start = lastRowIndex; start >= 0; start--) { - final List hiddenRowInfo = - dataGridConfiguration.container.rowHeights.getHidden(start, count); + final List hiddenRowInfo = dataGridConfiguration + .container + .rowHeights + .getHidden(start, count); final bool isHiddenRow = hiddenRowInfo.first as bool; if (!isHiddenRow) { return start; @@ -125,15 +136,19 @@ int getFirstRowIndex(DataGridConfiguration dataGridConfiguration) { if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { index += grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.top); + dataGridConfiguration, + GridTableSummaryRowPosition.top, + ); } return index; } /// Help to get the last row index in data grid -int getLastRowIndex(DataGridConfiguration dataGridConfiguration, - [bool isLastRow = false]) { +int getLastRowIndex( + DataGridConfiguration dataGridConfiguration, [ + bool isLastRow = false, +]) { if (getRecordsCount(dataGridConfiguration) == 0) { return -1; } @@ -152,13 +167,17 @@ int getLastRowIndex(DataGridConfiguration dataGridConfiguration, if (!isLastRow) { if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { index -= grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); } } for (int start = index; start >= 0; start--) { - final List hiddenRowInfo = - dataGridConfiguration.container.rowHeights.getHidden(start, count); + final List hiddenRowInfo = dataGridConfiguration + .container + .rowHeights + .getHidden(start, count); final bool isHiddenRow = hiddenRowInfo.first as bool; if (!isHiddenRow) { return start; @@ -170,15 +189,18 @@ int getLastRowIndex(DataGridConfiguration dataGridConfiguration, /// Help to get the first column index in row int getFirstCellIndex(DataGridConfiguration dataGridConfiguration) { - final GridColumn? gridColumn = dataGridConfiguration.columns - .firstWhereOrNull((GridColumn col) => col.visible); + final GridColumn? gridColumn = dataGridConfiguration.columns.firstWhereOrNull( + (GridColumn col) => col.visible, + ); if (gridColumn == null) { return -1; } if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { if (dataGridConfiguration.selectionMode == SelectionMode.multiple) { final int rowIndex = resolveStartRecordIndex( - dataGridConfiguration, dataGridConfiguration.currentCell.rowIndex); + dataGridConfiguration, + dataGridConfiguration.currentCell.rowIndex, + ); final dynamic group = getGroupElement(dataGridConfiguration, rowIndex); final dynamic nextGroup = getNextGroupInfo(group, dataGridConfiguration); if ((group is Group && nextGroup is Group) || rowIndex < 0) { @@ -206,7 +228,8 @@ int getFirstCellIndex(DataGridConfiguration dataGridConfiguration) { /// Help to get the last column index in row int getLastCellIndex(DataGridConfiguration dataGridConfiguration) { final GridColumn? lastColumn = dataGridConfiguration.columns.lastWhereOrNull( - (GridColumn col) => col.visible && col.actualWidth > 0.0); + (GridColumn col) => col.visible && col.actualWidth > 0.0, + ); if (lastColumn != null) { int lastCellIndex = dataGridConfiguration.columns.indexOf(lastColumn); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { @@ -269,13 +292,20 @@ int getNextPageIndex(DataGridConfiguration dataGridConfiguration) { /// Help to get the previous cell index from current cell index. int getPreviousColumnIndex( - DataGridConfiguration dataGridConfiguration, int currentColumnIndex) { + DataGridConfiguration dataGridConfiguration, + int currentColumnIndex, +) { int previousCellIndex = currentColumnIndex; - final GridColumn? column = - getNextGridColumn(dataGridConfiguration, currentColumnIndex - 1, false); + final GridColumn? column = getNextGridColumn( + dataGridConfiguration, + currentColumnIndex - 1, + false, + ); if (column != null) { previousCellIndex = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, dataGridConfiguration.columns.indexOf(column)); + dataGridConfiguration, + dataGridConfiguration.columns.indexOf(column), + ); } // Need to set column index as -1 to disable navigation since there are no @@ -289,16 +319,23 @@ int getPreviousColumnIndex( /// Help to get the next cell index from current cell index. int getNextColumnIndex( - DataGridConfiguration dataGridConfiguration, int currentColumnIndex) { + DataGridConfiguration dataGridConfiguration, + int currentColumnIndex, +) { int nextCellIndex = currentColumnIndex; final int lastCellIndex = getLastCellIndex(dataGridConfiguration); - final GridColumn? column = - getNextGridColumn(dataGridConfiguration, currentColumnIndex + 1, true); + final GridColumn? column = getNextGridColumn( + dataGridConfiguration, + currentColumnIndex + 1, + true, + ); if (column != null) { final int columnIndex = dataGridConfiguration.columns.indexOf(column); nextCellIndex = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, columnIndex); + dataGridConfiguration, + columnIndex, + ); } // Need to set column index to -1 to disable navigation since there are no @@ -314,24 +351,31 @@ int getNextColumnIndex( /// Help to get the previous row index from current cell index. int getPreviousRowIndex( - DataGridConfiguration dataGridConfiguration, int currentRowIndex) { + DataGridConfiguration dataGridConfiguration, + int currentRowIndex, +) { final int lastRowIndex = getLastNavigatingRowIndex(dataGridConfiguration); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { if (dataGridConfiguration.selectionMode != SelectionMode.multiple) { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; - final List dataGridRowIndexes = dataGridConfiguration - .group!.displayElements!.grouped - .whereType() - .map((DataGridRow row) => dataGridConfiguration - .group!.displayElements!.grouped - .indexOf(row)) - .toList(); + final List dataGridRowIndexes = + dataGridConfiguration.group!.displayElements!.grouped + .whereType() + .map( + (DataGridRow row) => dataGridConfiguration + .group! + .displayElements! + .grouped + .indexOf(row), + ) + .toList(); if (currentCell.rowIndex == dataGridConfiguration.source.groupedColumns.length + 1) { return currentCell.rowIndex; } else { - final int indexInDataGridRowIndexes = - dataGridRowIndexes.indexOf(currentCell.rowIndex - 1); + final int indexInDataGridRowIndexes = dataGridRowIndexes.indexOf( + currentCell.rowIndex - 1, + ); return dataGridRowIndexes[indexInDataGridRowIndexes - 1] + grid_helper.resolveStartIndexBasedOnPosition(dataGridConfiguration); } @@ -358,31 +402,41 @@ int getPreviousRowIndex( } /// Help to get the column index for down key. -int getDownKeyColumnIndex(DataGridConfiguration dataGridConfiguration, - CurrentCellManager currentCell) { +int getDownKeyColumnIndex( + DataGridConfiguration dataGridConfiguration, + CurrentCellManager currentCell, +) { return currentCell.columnIndex; } /// Help to get the column index for down key. -int getUpKeyColumnIndex(DataGridConfiguration dataGridConfiguration, - CurrentCellManager currentCell) { +int getUpKeyColumnIndex( + DataGridConfiguration dataGridConfiguration, + CurrentCellManager currentCell, +) { return currentCell.columnIndex; } /// Help to get the next row index from current cell index. int getNextRowIndex( - DataGridConfiguration dataGridConfiguration, int currentRowIndex) { + DataGridConfiguration dataGridConfiguration, + int currentRowIndex, +) { final int lastRowIndex = getLastNavigatingRowIndex(dataGridConfiguration); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; if (dataGridConfiguration.selectionMode != SelectionMode.multiple) { - final List dataGridRowIndexes = dataGridConfiguration - .group!.displayElements!.grouped - .whereType() - .map((DataGridRow row) => dataGridConfiguration - .group!.displayElements!.grouped - .indexOf(row)) - .toList(); + final List dataGridRowIndexes = + dataGridConfiguration.group!.displayElements!.grouped + .whereType() + .map( + (DataGridRow row) => dataGridConfiguration + .group! + .displayElements! + .grouped + .indexOf(row), + ) + .toList(); if (currentCell.rowIndex >= lastRowIndex) { return lastRowIndex; @@ -391,9 +445,11 @@ int getNextRowIndex( grid_helper.resolveStartIndexBasedOnPosition(dataGridConfiguration); } else { final int indexInDataGridRowIndexes = dataGridRowIndexes.indexOf( - currentCell.rowIndex - - grid_helper - .resolveStartIndexBasedOnPosition(dataGridConfiguration)); + currentCell.rowIndex - + grid_helper.resolveStartIndexBasedOnPosition( + dataGridConfiguration, + ), + ); return dataGridRowIndexes[indexInDataGridRowIndexes + 1] + grid_helper.resolveStartIndexBasedOnPosition(dataGridConfiguration); } @@ -415,8 +471,9 @@ int getNextRowIndex( } int nextIndex = 0; - nextIndex = dataGridConfiguration.container.scrollRows - .getNextScrollLineIndex(currentRowIndex); + nextIndex = dataGridConfiguration.container.scrollRows.getNextScrollLineIndex( + currentRowIndex, + ); if (nextIndex == currentRowIndex) { nextIndex = nextIndex + 1; } @@ -428,10 +485,15 @@ int getNextRowIndex( /// index /// moveToRight: Consider to check on next column else it will check the /// previous column -GridColumn? getNextGridColumn(DataGridConfiguration dataGridConfiguration, - int columnIndex, bool moveToRight) { +GridColumn? getNextGridColumn( + DataGridConfiguration dataGridConfiguration, + int columnIndex, + bool moveToRight, +) { final int resolvedIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, columnIndex); + dataGridConfiguration, + columnIndex, + ); if (resolvedIndex < 0 || resolvedIndex >= dataGridConfiguration.columns.length) { return null; @@ -439,8 +501,11 @@ GridColumn? getNextGridColumn(DataGridConfiguration dataGridConfiguration, GridColumn? gridColumn = dataGridConfiguration.columns[resolvedIndex]; if (!gridColumn.visible || gridColumn.actualWidth == 0.0) { - gridColumn = getNextGridColumn(dataGridConfiguration, - moveToRight ? columnIndex + 1 : columnIndex - 1, moveToRight); + gridColumn = getNextGridColumn( + dataGridConfiguration, + moveToRight ? columnIndex + 1 : columnIndex - 1, + moveToRight, + ); } return gridColumn; @@ -448,7 +513,9 @@ GridColumn? getNextGridColumn(DataGridConfiguration dataGridConfiguration, /// Helps to get the cumulative distance of provided row index double getVerticalCumulativeDistance( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, +) { double verticalOffset = 0.0; final int headerRowIndex = grid_helper.getHeaderIndex(dataGridConfiguration); rowIndex = rowIndex > headerRowIndex ? rowIndex : headerRowIndex + 1; @@ -460,17 +527,22 @@ double getVerticalCumulativeDistance( /// Helps to get the cumulative distance of provided column index double getHorizontalCumulativeDistance( - DataGridConfiguration dataGridConfiguration, int columnIndex) { + DataGridConfiguration dataGridConfiguration, + int columnIndex, +) { double horizontalOffset = 0.0; - final int firstVisibleColumnIndex = - grid_helper.resolveToStartColumnIndex(dataGridConfiguration); - columnIndex = columnIndex < firstVisibleColumnIndex - ? firstVisibleColumnIndex - : columnIndex; + final int firstVisibleColumnIndex = grid_helper.resolveToStartColumnIndex( + dataGridConfiguration, + ); + columnIndex = + columnIndex < firstVisibleColumnIndex + ? firstVisibleColumnIndex + : columnIndex; final PixelScrollAxis scrollColumns = dataGridConfiguration.container.scrollColumns as PixelScrollAxis; - horizontalOffset = - scrollColumns.distances!.getCumulatedDistanceAt(columnIndex); + horizontalOffset = scrollColumns.distances!.getCumulatedDistanceAt( + columnIndex, + ); return horizontalOffset; } @@ -480,7 +552,9 @@ double getHorizontalCumulativeDistance( /// If next row index not present in view it will return true, else it will /// return false bool needToScrollDown( - DataGridConfiguration dataGridConfiguration, int nextRowIndex) { + DataGridConfiguration dataGridConfiguration, + int nextRowIndex, +) { final VisibleLinesCollection visibleLines = dataGridConfiguration.container.scrollRows.getVisibleLines(); if (visibleLines.isEmpty) { @@ -488,7 +562,8 @@ bool needToScrollDown( } final VisibleLineInfo? nextRowInfo = dataGridConfiguration - .container.scrollRows + .container + .scrollRows .getVisibleLineAtLineIndex(nextRowIndex); return nextRowInfo == null || nextRowInfo.isClipped; } @@ -497,7 +572,9 @@ bool needToScrollDown( /// If previous row index not present in view it will return true, else it will /// return false bool needToScrollUp( - DataGridConfiguration dataGridConfiguration, int previousRowIndex) { + DataGridConfiguration dataGridConfiguration, + int previousRowIndex, +) { final VisibleLinesCollection visibleLineCollection = dataGridConfiguration.container.scrollRows.getVisibleLines(); if (visibleLineCollection.isEmpty) { @@ -505,7 +582,8 @@ bool needToScrollUp( } final VisibleLineInfo? previousRowLineInfo = dataGridConfiguration - .container.scrollRows + .container + .scrollRows .getVisibleLineAtLineIndex(previousRowIndex); return previousRowLineInfo == null || previousRowLineInfo.isClipped; } @@ -513,10 +591,12 @@ bool needToScrollUp( /// Decide to scroll toward left or not based on previous cell index /// If previous cell index not present in view it will return true, else it will /// return false -bool needToScrollLeft(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { - final VisibleLinesCollection visibleLineCollection = - grid_helper.getVisibleLines(dataGridConfiguration); +bool needToScrollLeft( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, +) { + final VisibleLinesCollection visibleLineCollection = grid_helper + .getVisibleLines(dataGridConfiguration); if (visibleLineCollection.isEmpty) { return false; } @@ -529,10 +609,12 @@ bool needToScrollLeft(DataGridConfiguration dataGridConfiguration, /// Decide to scroll toward right or not based on previous cell index /// If next cell index not present in view it will return true, else it will /// return false -bool needToScrollRight(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { - final VisibleLinesCollection visibleLineCollection = - grid_helper.getVisibleLines(dataGridConfiguration); +bool needToScrollRight( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, +) { + final VisibleLinesCollection visibleLineCollection = grid_helper + .getVisibleLines(dataGridConfiguration); if (visibleLineCollection.isEmpty) { return false; } @@ -542,18 +624,22 @@ bool needToScrollRight(DataGridConfiguration dataGridConfiguration, } /// Perform to scroll the view to left -void scrollInViewFromLeft(DataGridConfiguration dataGridConfiguration, - {int nextCellIndex = -1, bool needToScrollMaxExtent = false}) { +void scrollInViewFromLeft( + DataGridConfiguration dataGridConfiguration, { + int nextCellIndex = -1, + bool needToScrollMaxExtent = false, +}) { if (dataGridConfiguration.horizontalScrollController != null) { final ScrollController horizontalController = dataGridConfiguration.horizontalScrollController!; double measuredHorizontalOffset = 0.0; - final int lastFrozenColumnIndex = - grid_helper.getLastFrozenColumnIndex(dataGridConfiguration); + final int lastFrozenColumnIndex = grid_helper.getLastFrozenColumnIndex( + dataGridConfiguration, + ); - final int firstFooterFrozenColumnIndex = - grid_helper.getStartFooterFrozenColumnIndex(dataGridConfiguration); + final int firstFooterFrozenColumnIndex = grid_helper + .getStartFooterFrozenColumnIndex(dataGridConfiguration); if (dataGridConfiguration.frozenColumnsCount > 0 && lastFrozenColumnIndex + 1 == nextCellIndex) { @@ -566,38 +652,47 @@ void scrollInViewFromLeft(DataGridConfiguration dataGridConfiguration, if (dataGridConfiguration.currentCell.columnIndex != -1 && nextCellIndex == dataGridConfiguration.currentCell.columnIndex + 1) { final List nextCellIndexHeight = dataGridConfiguration - .container.columnWidthsProvider + .container + .columnWidthsProvider .getSize(nextCellIndex, 0); - final VisibleLinesCollection visibleInfoCollection = - grid_helper.getVisibleLines(dataGridConfiguration); - final VisibleLineInfo? nextCellInfo = - visibleInfoCollection.getVisibleLineAtLineIndex(nextCellIndex); - measuredHorizontalOffset = nextCellInfo != null - ? dataGridConfiguration.textDirection == TextDirection.rtl - ? nextCellInfo.clippedSize - - (~nextCellInfo.clippedOrigin.toInt()) - : nextCellInfo.size - - (nextCellInfo.size - nextCellInfo.clippedCornerExtent) - : nextCellIndexHeight.first as double; + final VisibleLinesCollection visibleInfoCollection = grid_helper + .getVisibleLines(dataGridConfiguration); + final VisibleLineInfo? nextCellInfo = visibleInfoCollection + .getVisibleLineAtLineIndex(nextCellIndex); + measuredHorizontalOffset = + nextCellInfo != null + ? dataGridConfiguration.textDirection == TextDirection.rtl + ? nextCellInfo.clippedSize - + (~nextCellInfo.clippedOrigin.toInt()) + : nextCellInfo.size - + (nextCellInfo.size - nextCellInfo.clippedCornerExtent) + : nextCellIndexHeight.first as double; measuredHorizontalOffset = horizontalController.offset + measuredHorizontalOffset; } else { - final VisibleLinesCollection visibleInfoCollection = - grid_helper.getVisibleLines(dataGridConfiguration); - final int firstBodyVisibleLineIndex = visibleInfoCollection - .firstBodyVisibleIndex < - visibleInfoCollection.length - ? visibleInfoCollection[visibleInfoCollection.firstBodyVisibleIndex] - .lineIndex - : 0; + final VisibleLinesCollection visibleInfoCollection = grid_helper + .getVisibleLines(dataGridConfiguration); + final int firstBodyVisibleLineIndex = + visibleInfoCollection.firstBodyVisibleIndex < + visibleInfoCollection.length + ? visibleInfoCollection[visibleInfoCollection + .firstBodyVisibleIndex] + .lineIndex + : 0; if (nextCellIndex < firstBodyVisibleLineIndex) { - scrollInViewFromRight(dataGridConfiguration, - previousCellIndex: nextCellIndex); + scrollInViewFromRight( + dataGridConfiguration, + previousCellIndex: nextCellIndex, + ); } else { measuredHorizontalOffset = getHorizontalCumulativeDistance( - dataGridConfiguration, nextCellIndex); + dataGridConfiguration, + nextCellIndex, + ); measuredHorizontalOffset = grid_helper.resolveHorizontalScrollOffset( - dataGridConfiguration, measuredHorizontalOffset); + dataGridConfiguration, + measuredHorizontalOffset, + ); measuredHorizontalOffset = horizontalController.offset + measuredHorizontalOffset; } @@ -605,23 +700,29 @@ void scrollInViewFromLeft(DataGridConfiguration dataGridConfiguration, } grid_helper.scrollHorizontal( - dataGridConfiguration, measuredHorizontalOffset); + dataGridConfiguration, + measuredHorizontalOffset, + ); } } /// Perform to scroll the view to right -void scrollInViewFromRight(DataGridConfiguration dataGridConfiguration, - {int previousCellIndex = -1, bool needToScrollToMinExtent = false}) { +void scrollInViewFromRight( + DataGridConfiguration dataGridConfiguration, { + int previousCellIndex = -1, + bool needToScrollToMinExtent = false, +}) { double measuredHorizontalOffset = 0.0; if (dataGridConfiguration.horizontalScrollController != null) { final ScrollController horizontalController = dataGridConfiguration.horizontalScrollController!; - final int startingFooterFrozenColumnIndex = - grid_helper.getStartFooterFrozenColumnIndex(dataGridConfiguration); - final int lastFrozenColumnIndex = - grid_helper.getLastFrozenColumnIndex(dataGridConfiguration); + final int startingFooterFrozenColumnIndex = grid_helper + .getStartFooterFrozenColumnIndex(dataGridConfiguration); + final int lastFrozenColumnIndex = grid_helper.getLastFrozenColumnIndex( + dataGridConfiguration, + ); if (dataGridConfiguration.footerFrozenColumnsCount > 0 && startingFooterFrozenColumnIndex - 1 == previousCellIndex) { @@ -635,37 +736,49 @@ void scrollInViewFromRight(DataGridConfiguration dataGridConfiguration, previousCellIndex == dataGridConfiguration.currentCell.columnIndex - 1) { final List previousCellIndexWidth = dataGridConfiguration - .container.columnWidthsProvider + .container + .columnWidthsProvider .getSize(previousCellIndex, 0); - final VisibleLinesCollection visibleInfoCollection = - grid_helper.getVisibleLines(dataGridConfiguration); - final VisibleLineInfo? previousCellInfo = - visibleInfoCollection.getVisibleLineAtLineIndex(previousCellIndex); - measuredHorizontalOffset = previousCellInfo != null - ? previousCellInfo.size - - (previousCellInfo.clippedSize - - previousCellInfo.clippedCornerExtent) - : previousCellIndexWidth.first as double; + final VisibleLinesCollection visibleInfoCollection = grid_helper + .getVisibleLines(dataGridConfiguration); + final VisibleLineInfo? previousCellInfo = visibleInfoCollection + .getVisibleLineAtLineIndex(previousCellIndex); + measuredHorizontalOffset = + previousCellInfo != null + ? previousCellInfo.size - + (previousCellInfo.clippedSize - + previousCellInfo.clippedCornerExtent) + : previousCellIndexWidth.first as double; measuredHorizontalOffset = horizontalController.offset - measuredHorizontalOffset; } else { measuredHorizontalOffset = getHorizontalCumulativeDistance( - dataGridConfiguration, previousCellIndex); + dataGridConfiguration, + previousCellIndex, + ); measuredHorizontalOffset = grid_helper.resolveHorizontalScrollOffset( - dataGridConfiguration, measuredHorizontalOffset); - measuredHorizontalOffset = horizontalController.offset - + dataGridConfiguration, + measuredHorizontalOffset, + ); + measuredHorizontalOffset = + horizontalController.offset - (horizontalController.offset - measuredHorizontalOffset); } } grid_helper.scrollHorizontal( - dataGridConfiguration, measuredHorizontalOffset); + dataGridConfiguration, + measuredHorizontalOffset, + ); } } /// Perform to scroll the view to top -void scrollInViewFromTop(DataGridConfiguration dataGridConfiguration, - {int nextRowIndex = -1, bool needToScrollToMaxExtent = false}) { +void scrollInViewFromTop( + DataGridConfiguration dataGridConfiguration, { + int nextRowIndex = -1, + bool needToScrollToMaxExtent = false, +}) { double measuredVerticalOffset = 0.0; if (dataGridConfiguration.verticalScrollController != null) { @@ -682,34 +795,44 @@ void scrollInViewFromTop(DataGridConfiguration dataGridConfiguration, if (dataGridConfiguration.currentCell.rowIndex != -1 && nextRowIndex == dataGridConfiguration.currentCell.rowIndex + 1) { final List nextRowIndexHeight = dataGridConfiguration - .container.rowHeightsProvider + .container + .rowHeightsProvider .getSize(nextRowIndex, 0); final VisibleLineInfo? nextRowInfo = dataGridConfiguration - .container.scrollRows + .container + .scrollRows .getVisibleLineAtLineIndex(nextRowIndex); - measuredVerticalOffset = nextRowInfo != null - ? nextRowInfo.size - - (nextRowInfo.size - nextRowInfo.clippedCornerExtent) - : nextRowIndexHeight.first as double; + measuredVerticalOffset = + nextRowInfo != null + ? nextRowInfo.size - + (nextRowInfo.size - nextRowInfo.clippedCornerExtent) + : nextRowIndexHeight.first as double; measuredVerticalOffset = verticalController.offset + measuredVerticalOffset; } else { final VisibleLinesCollection visibleInfoCollection = dataGridConfiguration.container.scrollRows.getVisibleLines(); - final int firstBodyVisibleLineIndex = visibleInfoCollection - .firstBodyVisibleIndex < - visibleInfoCollection.length - ? visibleInfoCollection[visibleInfoCollection.firstBodyVisibleIndex] - .lineIndex - : 0; + final int firstBodyVisibleLineIndex = + visibleInfoCollection.firstBodyVisibleIndex < + visibleInfoCollection.length + ? visibleInfoCollection[visibleInfoCollection + .firstBodyVisibleIndex] + .lineIndex + : 0; if (nextRowIndex < firstBodyVisibleLineIndex) { - scrollInViewFromDown(dataGridConfiguration, - previousRowIndex: nextRowIndex); + scrollInViewFromDown( + dataGridConfiguration, + previousRowIndex: nextRowIndex, + ); } else { measuredVerticalOffset = getVerticalCumulativeDistance( - dataGridConfiguration, nextRowIndex); + dataGridConfiguration, + nextRowIndex, + ); measuredVerticalOffset = grid_helper.resolveVerticalScrollOffset( - dataGridConfiguration, measuredVerticalOffset); + dataGridConfiguration, + measuredVerticalOffset, + ); } } } @@ -719,8 +842,11 @@ void scrollInViewFromTop(DataGridConfiguration dataGridConfiguration, } /// Perform to scroll the view to down -void scrollInViewFromDown(DataGridConfiguration dataGridConfiguration, - {int previousRowIndex = -1, bool needToScrollToMinExtent = false}) { +void scrollInViewFromDown( + DataGridConfiguration dataGridConfiguration, { + int previousRowIndex = -1, + bool needToScrollToMinExtent = false, +}) { double measuredVerticalOffset = 0.0; if (dataGridConfiguration.verticalScrollController != null) { @@ -737,24 +863,32 @@ void scrollInViewFromDown(DataGridConfiguration dataGridConfiguration, if (dataGridConfiguration.currentCell.rowIndex != -1 && previousRowIndex == dataGridConfiguration.currentCell.rowIndex - 1) { final List previousRowIndexHeight = dataGridConfiguration - .container.rowHeightsProvider + .container + .rowHeightsProvider .getSize(previousRowIndex, 0); final VisibleLineInfo? previousRowInfo = dataGridConfiguration - .container.scrollRows + .container + .scrollRows .getVisibleLineAtLineIndex(previousRowIndex); - measuredVerticalOffset = previousRowInfo != null - ? previousRowInfo.size - - (previousRowInfo.clippedSize - - previousRowInfo.clippedCornerExtent) - : previousRowIndexHeight.first as double; + measuredVerticalOffset = + previousRowInfo != null + ? previousRowInfo.size - + (previousRowInfo.clippedSize - + previousRowInfo.clippedCornerExtent) + : previousRowIndexHeight.first as double; measuredVerticalOffset = verticalController.offset - measuredVerticalOffset; } else { measuredVerticalOffset = getVerticalCumulativeDistance( - dataGridConfiguration, previousRowIndex); + dataGridConfiguration, + previousRowIndex, + ); measuredVerticalOffset = grid_helper.resolveVerticalScrollOffset( - dataGridConfiguration, measuredVerticalOffset); - measuredVerticalOffset = verticalController.offset - + dataGridConfiguration, + measuredVerticalOffset, + ); + measuredVerticalOffset = + verticalController.offset - (verticalController.offset - measuredVerticalOffset); } } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/cell_renderers.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/cell_renderers.dart index c14fd0e4b..42c533b6e 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/cell_renderers.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/cell_renderers.dart @@ -34,12 +34,14 @@ class GridStackedHeaderCellRenderer final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); Widget? label = DefaultTextStyle( - style: TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w500, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]), - child: dataCell.stackedHeaderCell!.child); + style: TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w500, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ), + child: dataCell.stackedHeaderCell!.child, + ); dataCell.columnElement = GridCell( key: dataCell.key!, @@ -70,24 +72,28 @@ class GridCellTextFieldRenderer } TextStyle _getCellTextStyle( - DataGridConfiguration dataGridConfiguration, DataCellBase dataCell) { + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, + ) { final DataRowBase? dataRow = dataCell.dataRow; if (dataRow != null && dataRow.isSelectedRow) { return dataRow.isHoveredRow ? dataGridConfiguration.dataGridThemeHelper!.rowHoverTextStyle! : TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ); } else { return dataRow!.isHoveredRow ? dataGridConfiguration.dataGridThemeHelper!.rowHoverTextStyle! : TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ); } } } @@ -104,32 +110,36 @@ class GridHeaderCellRenderer void onInitializeDisplayWidget(DataCellBase dataCell) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); final Widget child = DefaultTextStyle( - key: dataCell.key, - style: dataCell.textStyle!, - child: dataCell.gridColumn!.label); + key: dataCell.key, + style: dataCell.textStyle!, + child: dataCell.gridColumn!.label, + ); if (dataGridConfiguration.showCheckboxColumn && dataCell.columnIndex == dataGridConfiguration.source.groupedColumns.length) { dataCell.columnElement = GridCell( - key: dataCell.key!, - dataCell: dataCell, - backgroundColor: dataGridConfiguration.colorScheme!.transparent, - isDirty: dataGridConfiguration.container.isDirty || - dataCell.isDirty || - dataCell.dataRow!.isDirty, - dataGridStateDetails: _dataGridStateDetails, - child: - _getCheckboxHeaderWidget(dataGridConfiguration, dataCell, child)); + key: dataCell.key!, + dataCell: dataCell, + backgroundColor: dataGridConfiguration.colorScheme!.transparent, + isDirty: + dataGridConfiguration.container.isDirty || + dataCell.isDirty || + dataCell.dataRow!.isDirty, + dataGridStateDetails: _dataGridStateDetails, + child: _getCheckboxHeaderWidget(dataGridConfiguration, dataCell, child), + ); } else { dataCell.columnElement = GridHeaderCell( - key: dataCell.key!, - dataCell: dataCell, - backgroundColor: Colors.transparent, - isDirty: dataGridConfiguration.container.isDirty || - dataCell.isDirty || - dataCell.dataRow!.isDirty, - dataGridStateDetails: _dataGridStateDetails, - child: child); + key: dataCell.key!, + dataCell: dataCell, + backgroundColor: Colors.transparent, + isDirty: + dataGridConfiguration.container.isDirty || + dataCell.isDirty || + dataCell.dataRow!.isDirty, + dataGridStateDetails: _dataGridStateDetails, + child: child, + ); } } @@ -137,10 +147,11 @@ class GridHeaderCellRenderer void setCellStyle(DataCellBase dataCell) { TextStyle getDefaultHeaderTextStyle() { return TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w500, - fontSize: 14, - color: _dataGridStateDetails().colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w500, + fontSize: 14, + color: _dataGridStateDetails().colorScheme!.onSurface[222], + ); } dataCell.textStyle = getDefaultHeaderTextStyle(); @@ -148,46 +159,60 @@ class GridHeaderCellRenderer /// Creates a widget which displays label by default. Also, it creates with Checkbox, /// only when the [DataGridConfiguration.showCheckboxOnHeader] is true. - Widget _getCheckboxHeaderWidget(DataGridConfiguration dataGridConfiguration, - DataCellBase dataCell, Widget child) { + Widget _getCheckboxHeaderWidget( + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, + Widget child, + ) { final Widget label = Flexible( - child: DefaultTextStyle( - overflow: TextOverflow.ellipsis, - key: dataCell.key, - style: dataCell.textStyle!, - child: child)); + child: DefaultTextStyle( + overflow: TextOverflow.ellipsis, + key: dataCell.key, + style: dataCell.textStyle!, + child: child, + ), + ); return Center( - child: Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Visibility( - visible: dataGridConfiguration - .checkboxColumnSettings.showCheckboxOnHeader, + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Visibility( + visible: + dataGridConfiguration + .checkboxColumnSettings + .showCheckboxOnHeader, child: Checkbox( - shape: dataGridConfiguration.checkboxShape, - tristate: true, - value: dataGridConfiguration.headerCheckboxState, - onChanged: (bool? newValue) { - if (dataGridConfiguration.selectionMode == - SelectionMode.multiple) { - _requestFocus(dataGridConfiguration); - selection_manager.handleSelectionFromCheckbox( - dataGridConfiguration, - dataCell, - dataGridConfiguration.headerCheckboxState, - newValue); - } - })), - label - ], - )); + shape: dataGridConfiguration.checkboxShape, + tristate: true, + value: dataGridConfiguration.headerCheckboxState, + onChanged: (bool? newValue) { + if (dataGridConfiguration.selectionMode == + SelectionMode.multiple) { + _requestFocus(dataGridConfiguration); + selection_manager.handleSelectionFromCheckbox( + dataGridConfiguration, + dataCell, + dataGridConfiguration.headerCheckboxState, + newValue, + ); + } + }, + ), + ), + label, + ], + ), + ); } } /// A base class for cell renderer classes which displays widget in a cell. -abstract class GridVirtualizingCellRendererBase extends GridCellRendererBase { +abstract class GridVirtualizingCellRendererBase< + T1 extends Widget, + T2 extends Widget +> + extends GridCellRendererBase { /// Creates the [GridVirtualizingCellRendererBase] for [SfDataGrid] widget. GridVirtualizingCellRendererBase(); @@ -205,7 +230,9 @@ abstract class GridVirtualizingCellRendererBase 0 && dataCell.columnIndex < titleColumnSpan)) { final GridSummaryColumn? summaryColumn = dataCell.summaryColumn; - final RowColumnIndex rowColumnIndex = - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex); + final RowColumnIndex rowColumnIndex = RowColumnIndex( + dataCell.rowIndex, + dataCell.columnIndex, + ); final String title = dataGridConfiguration.source .calculateSummaryValue( - tableSummaryRow, summaryColumn, rowColumnIndex); + tableSummaryRow, + summaryColumn, + rowColumnIndex, + ); cell = dataGridConfiguration.source.buildTableSummaryCellWidget( - tableSummaryRow, summaryColumn, rowColumnIndex, title); + tableSummaryRow, + summaryColumn, + rowColumnIndex, + title, + ); } } cell ??= Container(); @@ -321,12 +370,14 @@ class GridTableSummaryCellRenderer } Widget? label = DefaultTextStyle( - style: TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w500, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]), - child: getSummaryCell()); + style: TextStyle( + fontFamily: 'Roboto', + fontWeight: FontWeight.w500, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ), + child: getSummaryCell(), + ); dataCell.columnElement = GridCell( key: dataCell.key!, @@ -352,12 +403,16 @@ class GridCaptionSummaryCellRenderer Widget? result; if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - final int rowIndex = - resolveStartRecordIndex(dataGridConfiguration, dataCell.rowIndex); + final int rowIndex = resolveStartRecordIndex( + dataGridConfiguration, + dataCell.rowIndex, + ); if (rowIndex >= 0) { - final dynamic groupItems = - getGroupElement(dataGridConfiguration, rowIndex); + final dynamic groupItems = getGroupElement( + dataGridConfiguration, + rowIndex, + ); if (groupItems is Group) { final int level = groupItems.level; @@ -374,11 +429,15 @@ class GridCaptionSummaryCellRenderer .replaceAll('{ColumnName}', groupedColumn) .replaceAll('{Key}', '${groupItems.key}') .replaceAll('{ItemsCount}', '${groupItems.rows.length}'); - final RowColumnIndex rowColumnIndex = - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex); + final RowColumnIndex rowColumnIndex = RowColumnIndex( + dataCell.rowIndex, + dataCell.columnIndex, + ); final Widget? cell = dataGridConfiguration.source .buildGroupCaptionCellWidget( - rowColumnIndex, groupCaptionTitleFormat); + rowColumnIndex, + groupCaptionTitleFormat, + ); result = cell; } @@ -420,31 +479,36 @@ class GridIndentCellRenderer if (dataGridConfiguration.source.groupedColumns.isNotEmpty && dataCell.dataRow!.rowType == RowType.captionSummaryCoveredRow && dataGridConfiguration.allowExpandCollapseGroup) { - final int rowIndex = - resolveStartRecordIndex(dataGridConfiguration, dataCell.rowIndex); + final int rowIndex = resolveStartRecordIndex( + dataGridConfiguration, + dataCell.rowIndex, + ); if (rowIndex >= 0) { - final dynamic groupItem = - getGroupElement(dataGridConfiguration, rowIndex); + final dynamic groupItem = getGroupElement( + dataGridConfiguration, + rowIndex, + ); if (groupItem is Group) { final int iconIndex = groupItem.level - 1; - newIcon = (iconIndex == dataCell.columnIndex) - ? Center( - child: GroupExpanderIcon( - // Issue: - // When sorting or navigating through pages with grouping, the group icon's state (expanded/collapsed) was incorrect. - // - // Fix: - // The issue occurred because the widget’s state persisted due to unchanged rowIndex during actions like sorting. - // To resolve this, the key is updated to combine both the rowIndex and isExpanded state, - // ensuring uniqueness and preventing old state from being reused. - key: ObjectKey('${rowIndex}_${groupItem.isExpanded}'), - isExpanded: groupItem.isExpanded, - dataGridConfiguration: dataGridConfiguration, - rowIndex: dataCell.rowIndex, - ), - ) - : const SizedBox(); + newIcon = + (iconIndex == dataCell.columnIndex) + ? Center( + child: GroupExpanderIcon( + // Issue: + // When sorting or navigating through pages with grouping, the group icon's state (expanded/collapsed) was incorrect. + // + // Fix: + // The issue occurred because the widget’s state persisted due to unchanged rowIndex during actions like sorting. + // To resolve this, the key is updated to combine both the rowIndex and isExpanded state, + // ensuring uniqueness and preventing old state from being reused. + key: ObjectKey('${rowIndex}_${groupItem.isExpanded}'), + isExpanded: groupItem.isExpanded, + dataGridConfiguration: dataGridConfiguration, + rowIndex: dataCell.rowIndex, + ), + ) + : const SizedBox(); } } } @@ -452,11 +516,13 @@ class GridIndentCellRenderer dataCell.columnElement = GridCell( key: dataCell.key!, dataCell: dataCell, - backgroundColor: dataCell.rowIndex >= - grid_helper - .resolveStartIndexBasedOnPosition(dataGridConfiguration) - ? dataGridConfiguration.dataGridThemeHelper!.indentColumnColor! - : dataGridConfiguration.colorScheme!.transparent, + backgroundColor: + dataCell.rowIndex >= + grid_helper.resolveStartIndexBasedOnPosition( + dataGridConfiguration, + ) + ? dataGridConfiguration.dataGridThemeHelper!.indentColumnColor! + : dataGridConfiguration.colorScheme!.transparent, dataGridStateDetails: _dataGridStateDetails, isDirty: dataGridConfiguration.container.isDirty || dataCell.isDirty, child: newIcon, @@ -521,10 +587,10 @@ class GroupExpanderIconState extends State turns: Tween(begin: 0.0, end: 0.5).animate(_controller), child: widget.dataGridConfiguration.dataGridThemeHelper?.groupExpanderIcon ?? - Icon( - Icons.expand_less, - color: widget.dataGridConfiguration.colorScheme!.onSurface[153], - ), + Icon( + Icons.expand_less, + color: widget.dataGridConfiguration.colorScheme!.onSurface[153], + ), ); } @@ -536,7 +602,9 @@ class GroupExpanderIconState extends State } /// Sets the `dataGridConfiguration` to the cell renderers. -void setStateDetailsInCellRendererBase(GridCellRendererBase cellRendererBase, - DataGridStateDetails dataGridStateDetails) { +void setStateDetailsInCellRendererBase( + GridCellRendererBase cellRendererBase, + DataGridStateDetails dataGridStateDetails, +) { cellRendererBase._dataGridStateDetails = dataGridStateDetails; } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/column.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/column.dart index 79b4f8161..427c18445 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/column.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/column.dart @@ -23,22 +23,23 @@ import 'generator.dart'; /// Provides the base functionalities for all the column types in [SfDataGrid]. class GridColumn { /// Creates the [GridColumn] for [SfDataGrid] widget. - GridColumn( - {required this.columnName, - required this.label, - this.columnWidthMode = ColumnWidthMode.none, - this.visible = true, - this.allowSorting = true, - this.sortIconPosition = ColumnHeaderIconPosition.end, - this.filterIconPosition = ColumnHeaderIconPosition.end, - this.autoFitPadding = const EdgeInsets.all(16.0), - this.minimumWidth = double.nan, - this.maximumWidth = double.nan, - this.width = double.nan, - this.allowEditing = true, - this.allowFiltering = true, - this.filterPopupMenuOptions, - this.filterIconPadding = const EdgeInsets.symmetric(horizontal: 8.0)}) { + GridColumn({ + required this.columnName, + required this.label, + this.columnWidthMode = ColumnWidthMode.none, + this.visible = true, + this.allowSorting = true, + this.sortIconPosition = ColumnHeaderIconPosition.end, + this.filterIconPosition = ColumnHeaderIconPosition.end, + this.autoFitPadding = const EdgeInsets.all(16.0), + this.minimumWidth = double.nan, + this.maximumWidth = double.nan, + this.width = double.nan, + this.allowEditing = true, + this.allowFiltering = true, + this.filterPopupMenuOptions, + this.filterIconPadding = const EdgeInsets.symmetric(horizontal: 8.0), + }) { _actualWidth = double.nan; _autoWidth = double.nan; } @@ -186,11 +187,7 @@ class GridCheckboxColumn extends GridColumn { required String columnName, required Widget label, double width = double.nan, - }) : super( - columnName: columnName, - label: label, - width: width, - ); + }) : super(columnName: columnName, label: label, width: width); } /// Contains all the properties of the checkbox column. @@ -297,8 +294,9 @@ class ColumnSizer { /// Defines the outer padding of the sort and filter icon's container. We need /// to consider this padding to measure the auto-width and height calculation. - EdgeInsetsGeometry iconsOuterPadding = - const EdgeInsets.symmetric(horizontal: 4.0); + EdgeInsetsGeometry iconsOuterPadding = const EdgeInsets.symmetric( + horizontal: 4.0, + ); void _initialRefresh(double availableWidth) { final LineSizeCollection lineSizeCollection = @@ -313,10 +311,11 @@ class ColumnSizer { _dataGridStateDetails!(); final bool hasAnySizerColumn = dataGridConfiguration.columns.any( - (GridColumn column) => - (column.columnWidthMode != ColumnWidthMode.none) || - (!column.width.isNaN) || - !column.visible); + (GridColumn column) => + (column.columnWidthMode != ColumnWidthMode.none) || + (!column.width.isNaN) || + !column.visible, + ); final PaddedEditableLineSizeHostBase paddedEditableLineSizeHostBase = dataGridConfiguration.container.columnWidths; @@ -345,10 +344,15 @@ class ColumnSizer { int index = dataGridConfiguration.columns.indexOf(column); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { index = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, index); + dataGridConfiguration, + index, + ); } - dataGridConfiguration.container.columnWidths - .setHidden(index, index, !column.visible); + dataGridConfiguration.container.columnWidths.setHidden( + index, + index, + !column.visible, + ); } // Columns will be auto sized only if Columns doesn't have explicit width // defined. @@ -356,84 +360,115 @@ class ColumnSizer { } void _sizerColumnWidth( - DataGridConfiguration dataGridConfiguration, double viewPortWidth) { + DataGridConfiguration dataGridConfiguration, + double viewPortWidth, + ) { double totalColumnSize = 0.0; final List calculatedColumns = []; _autoFillColumn = _getColumnToFill(dataGridConfiguration); // Hide Hidden columns - final List hiddenColumns = dataGridConfiguration.columns - .where((GridColumn column) => !column.visible) - .toList(); + final List hiddenColumns = + dataGridConfiguration.columns + .where((GridColumn column) => !column.visible) + .toList(); for (final GridColumn column in hiddenColumns) { final int index = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, dataGridConfiguration.columns.indexOf(column)); - dataGridConfiguration.container.columnWidths - .setHidden(index, index, true); + dataGridConfiguration, + dataGridConfiguration.columns.indexOf(column), + ); + dataGridConfiguration.container.columnWidths.setHidden( + index, + index, + true, + ); calculatedColumns.add(column); } // Set width based on Column.Width - final List widthColumns = dataGridConfiguration.columns - .where((GridColumn column) => column.visible && !column.width.isNaN) - .toList(); + final List widthColumns = + dataGridConfiguration.columns + .where((GridColumn column) => column.visible && !column.width.isNaN) + .toList(); for (final GridColumn column in widthColumns) { - totalColumnSize += - _setColumnWidth(dataGridConfiguration, column, column.width); + totalColumnSize += _setColumnWidth( + dataGridConfiguration, + column, + column.width, + ); calculatedColumns.add(column); } // Set width based on fitByCellValue mode - final List fitByCellValueColumns = dataGridConfiguration.columns - .where((GridColumn column) => - column.visible && - column.columnWidthMode == ColumnWidthMode.fitByCellValue && - column.width.isNaN) - .toList(); + final List fitByCellValueColumns = + dataGridConfiguration.columns + .where( + (GridColumn column) => + column.visible && + column.columnWidthMode == ColumnWidthMode.fitByCellValue && + column.width.isNaN, + ) + .toList(); for (final GridColumn column in fitByCellValueColumns) { if (column._autoWidth.isNaN) { final double columnWidth = _getWidthBasedOnColumn( - dataGridConfiguration, column, ColumnWidthMode.fitByCellValue); + dataGridConfiguration, + column, + ColumnWidthMode.fitByCellValue, + ); totalColumnSize += columnWidth; _setAutoWidth(column, columnWidth); } else { - totalColumnSize += - _setColumnWidth(dataGridConfiguration, column, column._autoWidth); + totalColumnSize += _setColumnWidth( + dataGridConfiguration, + column, + column._autoWidth, + ); } calculatedColumns.add(column); } // Set width based on fitByColumnName mode - final List fitByColumnNameColumns = dataGridConfiguration - .columns - .where((GridColumn column) => - column.visible && - column.columnWidthMode == ColumnWidthMode.fitByColumnName && - column.width.isNaN) - .toList(); + final List fitByColumnNameColumns = + dataGridConfiguration.columns + .where( + (GridColumn column) => + column.visible && + column.columnWidthMode == ColumnWidthMode.fitByColumnName && + column.width.isNaN, + ) + .toList(); for (final GridColumn column in fitByColumnNameColumns) { totalColumnSize += _getWidthBasedOnColumn( - dataGridConfiguration, column, ColumnWidthMode.fitByColumnName); + dataGridConfiguration, + column, + ColumnWidthMode.fitByColumnName, + ); calculatedColumns.add(column); } // Set width based on auto and lastColumnFill - List autoColumns = dataGridConfiguration.columns - .where((GridColumn column) => - column.columnWidthMode == ColumnWidthMode.auto && - column.visible && - column.width.isNaN) - .toList(); + List autoColumns = + dataGridConfiguration.columns + .where( + (GridColumn column) => + column.columnWidthMode == ColumnWidthMode.auto && + column.visible && + column.width.isNaN, + ) + .toList(); final List lastColumnFill = dataGridConfiguration.shrinkWrapColumns ? [] : dataGridConfiguration.columns - .where((GridColumn col) => - !calculatedColumns.contains(col) && - col.columnWidthMode == ColumnWidthMode.lastColumnFill && - !_isLastFillColum(col)) + .where( + (GridColumn col) => + !calculatedColumns.contains(col) && + col.columnWidthMode == ColumnWidthMode.lastColumnFill && + !_isLastFillColum(col), + ) .toList(); autoColumns = (autoColumns + lastColumnFill).toSet().toList(); @@ -441,12 +476,18 @@ class ColumnSizer { for (final GridColumn column in autoColumns) { if (column._autoWidth.isNaN) { final double columnWidth = _getWidthBasedOnColumn( - dataGridConfiguration, column, ColumnWidthMode.auto); + dataGridConfiguration, + column, + ColumnWidthMode.auto, + ); totalColumnSize += columnWidth; _setAutoWidth(column, columnWidth); } else { - totalColumnSize += - _setColumnWidth(dataGridConfiguration, column, column._autoWidth); + totalColumnSize += _setColumnWidth( + dataGridConfiguration, + column, + column._autoWidth, + ); } calculatedColumns.add(column); } @@ -454,19 +495,24 @@ class ColumnSizer { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { totalColumnSize += dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth * - dataGridConfiguration.source.groupedColumns.length; + dataGridConfiguration.source.groupedColumns.length; } - _setWidthBasedOnGrid(dataGridConfiguration, totalColumnSize, - calculatedColumns, viewPortWidth); + _setWidthBasedOnGrid( + dataGridConfiguration, + totalColumnSize, + calculatedColumns, + viewPortWidth, + ); _autoFillColumn = null; } GridColumn? _getColumnToFill(DataGridConfiguration dataGridConfiguration) { final GridColumn? column = dataGridConfiguration.columns.lastWhereOrNull( - (GridColumn c) => - c.visible && - c.width.isNaN && - c.columnWidthMode == ColumnWidthMode.lastColumnFill); + (GridColumn c) => + c.visible && + c.width.isNaN && + c.columnWidthMode == ColumnWidthMode.lastColumnFill, + ); if (column != null) { return column; } else { @@ -487,10 +533,11 @@ class ColumnSizer { } void _setWidthBasedOnGrid( - DataGridConfiguration dataGridConfiguration, - double totalColumnSize, - List calculatedColumns, - double viewPortWidth) { + DataGridConfiguration dataGridConfiguration, + double totalColumnSize, + List calculatedColumns, + double viewPortWidth, + ) { for (final GridColumn column in dataGridConfiguration.columns) { if (calculatedColumns.contains(column) || column.columnWidthMode == ColumnWidthMode.fill || @@ -502,18 +549,27 @@ class ColumnSizer { case ColumnWidthMode.fitByCellValue: if (column._autoWidth.isNaN) { final double columnWidth = _getWidthBasedOnColumn( - dataGridConfiguration, column, ColumnWidthMode.fitByCellValue); + dataGridConfiguration, + column, + ColumnWidthMode.fitByCellValue, + ); totalColumnSize += columnWidth; _setAutoWidth(column, columnWidth); } else { totalColumnSize += _setColumnWidth( - dataGridConfiguration, column, column._autoWidth); + dataGridConfiguration, + column, + column._autoWidth, + ); } calculatedColumns.add(column); break; case ColumnWidthMode.fitByColumnName: totalColumnSize += _getWidthBasedOnColumn( - dataGridConfiguration, column, ColumnWidthMode.fitByColumnName); + dataGridConfiguration, + column, + ColumnWidthMode.fitByColumnName, + ); calculatedColumns.add(column); break; case ColumnWidthMode.auto: @@ -523,19 +579,28 @@ class ColumnSizer { } if (column._autoWidth.isNaN) { final double columnWidth = _getWidthBasedOnColumn( - dataGridConfiguration, column, ColumnWidthMode.auto); + dataGridConfiguration, + column, + ColumnWidthMode.auto, + ); totalColumnSize += columnWidth; _setAutoWidth(column, columnWidth); } else { totalColumnSize += _setColumnWidth( - dataGridConfiguration, column, column._autoWidth); + dataGridConfiguration, + column, + column._autoWidth, + ); } calculatedColumns.add(column); break; case ColumnWidthMode.none: if (column.visible) { - totalColumnSize += _setColumnWidth(dataGridConfiguration, column, - dataGridConfiguration.container.columnWidths.defaultLineSize); + totalColumnSize += _setColumnWidth( + dataGridConfiguration, + column, + dataGridConfiguration.container.columnWidths.defaultLineSize, + ); calculatedColumns.add(column); } break; @@ -558,19 +623,27 @@ class ColumnSizer { !dataGridConfiguration.shrinkWrapColumns && (totalColumnSize != 0 || (totalColumnSize == 0 && remainingColumns.length == 1) || - (dataGridConfiguration.columns.any((GridColumn col) => - col.columnWidthMode == ColumnWidthMode.fill) || + (dataGridConfiguration.columns.any( + (GridColumn col) => + col.columnWidthMode == ColumnWidthMode.fill, + ) || dataGridConfiguration.columnWidthMode == ColumnWidthMode.fill))) { _setFillWidth( - dataGridConfiguration, remainingColumnWidths, remainingColumns); + dataGridConfiguration, + remainingColumnWidths, + remainingColumns, + ); } else { _setRemainingColumnsWidth(dataGridConfiguration, remainingColumns); } } - double _getWidthBasedOnColumn(DataGridConfiguration dataGridConfiguration, - GridColumn column, ColumnWidthMode columnWidthMode) { + double _getWidthBasedOnColumn( + DataGridConfiguration dataGridConfiguration, + GridColumn column, + ColumnWidthMode columnWidthMode, + ) { double width = 0.0; switch (columnWidthMode) { case ColumnWidthMode.fitByCellValue: @@ -589,15 +662,21 @@ class ColumnSizer { } double _calculateAllCellsWidth(GridColumn column) { - final double headerWidth = - _calculateColumnHeaderWidth(column, setWidth: false); - final double cellWidth = - _calculateAllCellsExceptHeaderWidth(column, setWidth: false); + final double headerWidth = _calculateColumnHeaderWidth( + column, + setWidth: false, + ); + final double cellWidth = _calculateAllCellsExceptHeaderWidth( + column, + setWidth: false, + ); return _getColumnWidth(column, max(cellWidth, headerWidth)); } - double _calculateColumnHeaderWidth(GridColumn column, - {bool setWidth = true}) { + double _calculateColumnHeaderWidth( + GridColumn column, { + bool setWidth = true, + }) { double iconsWidth = _getSortIconWidth(column) + _getFilterIconWidth(column); if (iconsWidth > 0) { @@ -609,8 +688,10 @@ class ColumnSizer { return width; } - double _calculateAllCellsExceptHeaderWidth(GridColumn column, - {bool setWidth = true}) { + double _calculateAllCellsExceptHeaderWidth( + GridColumn column, { + bool setWidth = true, + }) { final double width = _calculateCellWidth(column); _updateSetWidth(setWidth, column, width); return width; @@ -638,16 +719,23 @@ class ColumnSizer { endRowIndex = dataGridConfiguration.source.rows.length - 1; break; case ColumnWidthCalculationRange.visibleRows: - final VisibleLinesCollection visibleLines = - dataGridConfiguration.container.scrollRows.getVisibleLines( - dataGridConfiguration.textDirection == TextDirection.rtl); + final VisibleLinesCollection visibleLines = dataGridConfiguration + .container + .scrollRows + .getVisibleLines( + dataGridConfiguration.textDirection == TextDirection.rtl, + ); startRowIndex = visibleLines.firstBodyVisibleIndex <= visibleLines.length - 1 ? grid_helper.resolveToRecordIndex( - dataGridConfiguration, visibleLines.firstBodyVisibleIndex) + dataGridConfiguration, + visibleLines.firstBodyVisibleIndex, + ) : 0; endRowIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, visibleLines.lastBodyVisibleIndex); + dataGridConfiguration, + visibleLines.lastBodyVisibleIndex, + ); break; } if (getFirstRowIndex(dataGridConfiguration) < 0) { @@ -663,7 +751,9 @@ class ColumnSizer { double _getHeaderCellWidth(GridColumn column) { return computeHeaderCellWidth( - column, _getDefaultTextStyle(_dataGridStateDetails!(), true)); + column, + _getDefaultTextStyle(_dataGridStateDetails!(), true), + ); } double _getCellWidth(GridColumn column, int rowIndex) { @@ -673,7 +763,10 @@ class ColumnSizer { ColumnWidthCalculationRange.visibleRows && (grid_helper.isFooterWidgetRow(rowIndex, dataGridConfiguration) || grid_helper.isCaptionSummaryRow( - dataGridConfiguration, rowIndex, false))) { + dataGridConfiguration, + rowIndex, + false, + ))) { return 0.0; } @@ -700,19 +793,26 @@ class ColumnSizer { break; } return _measureCellWidth( - _getCellValue(dataGridRow, column), column, dataGridRow); + _getCellValue(dataGridRow, column), + column, + dataGridRow, + ); } Object? _getCellValue(DataGridRow dataGridRow, GridColumn column) { return dataGridRow .getCells() .firstWhereOrNull( - (DataGridCell cell) => cell.columnName == column.columnName) + (DataGridCell cell) => cell.columnName == column.columnName, + ) ?.value; } - void _setFillWidth(DataGridConfiguration dataGridConfiguration, - double remainingColumnWidth, List remainingColumns) { + void _setFillWidth( + DataGridConfiguration dataGridConfiguration, + double remainingColumnWidth, + List remainingColumns, + ) { final List removedColumns = []; final List columns = remainingColumns; double totalRemainingFillValue = remainingColumnWidth; @@ -735,8 +835,11 @@ class ColumnSizer { continue; } - final double computedWidth = - _setColumnWidth(dataGridConfiguration, column, fillWidth); + final double computedWidth = _setColumnWidth( + dataGridConfiguration, + column, + fillWidth, + ); if (fillWidth != computedWidth && fillWidth > 0) { isRemoved = true; columns.remove(column); @@ -768,24 +871,34 @@ class ColumnSizer { columnWidth = fillColumn._autoWidth; } - _setColumnWidth(dataGridConfiguration, fillColumn, - max(totalRemainingFillValue, columnWidth)); + _setColumnWidth( + dataGridConfiguration, + fillColumn, + max(totalRemainingFillValue, columnWidth), + ); } } - void _setRemainingColumnsWidth(DataGridConfiguration dataGridConfiguration, - List remainingColumns) { + void _setRemainingColumnsWidth( + DataGridConfiguration dataGridConfiguration, + List remainingColumns, + ) { for (final GridColumn column in remainingColumns) { if (_isLastFillColum(column) || !_isFillColumn(dataGridConfiguration, column)) { - _setColumnWidth(dataGridConfiguration, column, - dataGridConfiguration.container.columnWidths.defaultLineSize); + _setColumnWidth( + dataGridConfiguration, + column, + dataGridConfiguration.container.columnWidths.defaultLineSize, + ); } } } bool _isFillColumn( - DataGridConfiguration dataGridConfiguration, GridColumn column) { + DataGridConfiguration dataGridConfiguration, + GridColumn column, + ) { if (!column.width.isNaN) { return false; } else { @@ -821,8 +934,9 @@ class ColumnSizer { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); double width = 0.0; - final bool isSortedColumn = dataGridConfiguration.source.sortedColumns - .any((SortColumnDetails element) => element.name == column.columnName); + final bool isSortedColumn = dataGridConfiguration.source.sortedColumns.any( + (SortColumnDetails element) => element.name == column.columnName, + ); if (isSortedColumn || (column.allowSorting && dataGridConfiguration.allowSorting)) { width += _sortIconWidth; @@ -841,13 +955,18 @@ class ColumnSizer { return 0.0; } - double _setColumnWidth(DataGridConfiguration dataGridConfiguration, - GridColumn column, double columnWidth) { + double _setColumnWidth( + DataGridConfiguration dataGridConfiguration, + GridColumn column, + double columnWidth, + ) { final int columnIndex = dataGridConfiguration.columns.indexOf(column); final double width = _getColumnWidth(column, columnWidth); column._actualWidth = width; final int index = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, columnIndex); + dataGridConfiguration, + columnIndex, + ); dataGridConfiguration.container.columnWidths[index] = column._actualWidth; return width; } @@ -857,7 +976,9 @@ class ColumnSizer { _dataGridStateDetails!(); final int columnIndex = dataGridConfiguration.columns.indexOf(column); final int index = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, columnIndex); + dataGridConfiguration, + columnIndex, + ); if (column.width < column._actualWidth) { return columnWidth; } @@ -867,7 +988,10 @@ class ColumnSizer { } double _checkWidthConstraints( - GridColumn column, double width, double columnWidth) { + GridColumn column, + double width, + double columnWidth, + ) { if (!column.minimumWidth.isNaN || !column.maximumWidth.isNaN) { if (!column.maximumWidth.isNaN) { if (!width.isNaN && column.maximumWidth > width) { @@ -897,7 +1021,9 @@ class ColumnSizer { } int _resolveRowIndex( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, + ) { if (dataGridConfiguration.source.groupedColumns.isEmpty || dataGridConfiguration.columnWidthCalculationRange == ColumnWidthCalculationRange.allRows) { @@ -911,8 +1037,9 @@ class ColumnSizer { return -1; } - final int recordIndex = - effectiveRows(dataGridConfiguration.source).indexOf(row); + final int recordIndex = effectiveRows( + dataGridConfiguration.source, + ).indexOf(row); return recordIndex; } @@ -973,21 +1100,26 @@ class ColumnSizer { /// /// The auto size is calculated based on default [TextStyle] of the datagrid. @protected - double computeCellWidth(GridColumn column, DataGridRow row, Object? cellValue, - TextStyle textStyle) { + double computeCellWidth( + GridColumn column, + DataGridRow row, + Object? cellValue, + TextStyle textStyle, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); - final int rowIndex = grid_helper.resolveToRowIndex(dataGridConfiguration, - effectiveRows(dataGridConfiguration.source).indexOf(row)); + final int rowIndex = grid_helper.resolveToRowIndex( + dataGridConfiguration, + effectiveRows(dataGridConfiguration.source).indexOf(row), + ); return _calculateTextSize( - column: column, - value: cellValue, - rowIndex: rowIndex, - textStyle: textStyle, - width: double.infinity) - .width - .ceilToDouble(); + column: column, + value: cellValue, + rowIndex: rowIndex, + textStyle: textStyle, + width: double.infinity, + ).width.ceilToDouble(); } /// Calculates the height of the header cell based on the [GridColumn.columnName]. @@ -1009,11 +1141,12 @@ class ColumnSizer { @protected double computeHeaderCellHeight(GridColumn column, TextStyle textStyle) { return _measureCellHeight( - column, - grid_helper.getHeaderIndex(_dataGridStateDetails!()), - column.columnName, - textStyle, - isHeaderCell: true); + column, + grid_helper.getHeaderIndex(_dataGridStateDetails!()), + column.columnName, + textStyle, + isHeaderCell: true, + ); } /// Calculates the height of the cell based on the [DataGridCell.value]. @@ -1038,18 +1171,26 @@ class ColumnSizer { /// /// The auto size is calculated based on default [TextStyle] of the datagrid. @protected - double computeCellHeight(GridColumn column, DataGridRow row, - Object? cellValue, TextStyle textStyle) { + double computeCellHeight( + GridColumn column, + DataGridRow row, + Object? cellValue, + TextStyle textStyle, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); - final int rowIndex = grid_helper.resolveToRowIndex(dataGridConfiguration, - effectiveRows(dataGridConfiguration.source).indexOf(row)); + final int rowIndex = grid_helper.resolveToRowIndex( + dataGridConfiguration, + effectiveRows(dataGridConfiguration.source).indexOf(row), + ); return _measureCellHeight(column, rowIndex, cellValue, textStyle); } - double _getAutoFitRowHeight(int rowIndex, - {bool canIncludeHiddenColumns = false, - List excludedColumns = const []}) { + double _getAutoFitRowHeight( + int rowIndex, { + bool canIncludeHiddenColumns = false, + List excludedColumns = const [], + }) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); double autoFitHeight = 0.0; @@ -1066,7 +1207,10 @@ class ColumnSizer { if (grid_helper.isTableSummaryIndex(dataGridConfiguration, rowIndex) || grid_helper.isCaptionSummaryRow( - dataGridConfiguration, rowIndex, true)) { + dataGridConfiguration, + rowIndex, + true, + )) { return dataGridConfiguration.rowHeight; } @@ -1087,54 +1231,85 @@ class ColumnSizer { _dataGridStateDetails!(); if (rowIndex == grid_helper.getHeaderIndex(dataGridConfiguration)) { return computeHeaderCellHeight( - column, _getDefaultTextStyle(dataGridConfiguration, true)); + column, + _getDefaultTextStyle(dataGridConfiguration, true), + ); } else { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - rowIndex = - grid_helper.resolveToRecordIndex(dataGridConfiguration, rowIndex); + rowIndex = grid_helper.resolveToRecordIndex( + dataGridConfiguration, + rowIndex, + ); if (rowIndex < 0) { return dataGridConfiguration.rowHeight; } - final dynamic row = - grid_helper.getGroupElement(dataGridConfiguration, rowIndex); + final dynamic row = grid_helper.getGroupElement( + dataGridConfiguration, + rowIndex, + ); if (row is! DataGridRow) { return dataGridConfiguration.rowHeight; } - return computeCellHeight(column, row, _getCellValue(row, column), - _getDefaultTextStyle(dataGridConfiguration, false)); + return computeCellHeight( + column, + row, + _getCellValue(row, column), + _getDefaultTextStyle(dataGridConfiguration, false), + ); } else { - final DataGridRow row = - grid_helper.getDataGridRow(dataGridConfiguration, rowIndex); - return computeCellHeight(column, row, _getCellValue(row, column), - _getDefaultTextStyle(dataGridConfiguration, false)); + final DataGridRow row = grid_helper.getDataGridRow( + dataGridConfiguration, + rowIndex, + ); + return computeCellHeight( + column, + row, + _getCellValue(row, column), + _getDefaultTextStyle(dataGridConfiguration, false), + ); } } } double _measureCellWidth( - Object? cellValue, GridColumn column, DataGridRow dataGridRow) { - return computeCellWidth(column, dataGridRow, cellValue, - _getDefaultTextStyle(_dataGridStateDetails!(), false)); + Object? cellValue, + GridColumn column, + DataGridRow dataGridRow, + ) { + return computeCellWidth( + column, + dataGridRow, + cellValue, + _getDefaultTextStyle(_dataGridStateDetails!(), false), + ); } double _measureCellHeight( - GridColumn column, int rowIndex, Object? cellValue, TextStyle textStyle, - {bool isHeaderCell = false}) { + GridColumn column, + int rowIndex, + Object? cellValue, + TextStyle textStyle, { + bool isHeaderCell = false, + }) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); final int columnIndex = resolveToScrollColumnIndex( - dataGridConfiguration, dataGridConfiguration.columns.indexOf(column)); - double columnWidth = !column.visible || column.width == 0.0 - ? dataGridConfiguration.defaultColumnWidth - : dataGridConfiguration.container.columnWidths[columnIndex]; + dataGridConfiguration, + dataGridConfiguration.columns.indexOf(column), + ); + double columnWidth = + !column.visible || column.width == 0.0 + ? dataGridConfiguration.defaultColumnWidth + : dataGridConfiguration.container.columnWidths[columnIndex]; - final double strokeWidth = _getGridLineStrokeWidth( - rowIndex: rowIndex, - dataGridConfiguration: dataGridConfiguration, - column: column) - .width; + final double strokeWidth = + _getGridLineStrokeWidth( + rowIndex: rowIndex, + dataGridConfiguration: dataGridConfiguration, + column: column, + ).width; final double horizontalPadding = column.autoFitPadding.horizontal; @@ -1160,26 +1335,31 @@ class ColumnSizer { } TextStyle _getDefaultTextStyle( - DataGridConfiguration dataGridConfiguration, bool isHeader) { + DataGridConfiguration dataGridConfiguration, + bool isHeader, + ) { if (isHeader) { return TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w500, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w500, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ); } else { return TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ); } } - Size _getGridLineStrokeWidth( - {required int rowIndex, - required DataGridConfiguration dataGridConfiguration, - required GridColumn column}) { + Size _getGridLineStrokeWidth({ + required int rowIndex, + required DataGridConfiguration dataGridConfiguration, + required GridColumn column, + }) { final double strokeWidth = dataGridConfiguration.dataGridThemeHelper!.gridLineStrokeWidth!; @@ -1190,14 +1370,17 @@ class ColumnSizer { final GridColumn firstVisibleColumn = dataGridConfiguration.columns .firstWhere( - (GridColumn column) => column.visible && column.width != 0.0); + (GridColumn column) => column.visible && column.width != 0.0, + ); final GridColumn lastVisibleColumn = dataGridConfiguration.columns .lastWhere( - (GridColumn column) => column.visible && column.width != 0.0); + (GridColumn column) => column.visible && column.width != 0.0, + ); bool isFirstColumn = firstVisibleColumn.columnName == column.columnName; final bool isLastColumn = lastVisibleColumn.columnName == column.columnName; - isFirstColumn = isFirstColumn && + isFirstColumn = + isFirstColumn && (dataGridConfiguration.source.groupedColumns.isEmpty || (dataGridConfiguration.source.groupedColumns.isNotEmpty && dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth <= @@ -1207,14 +1390,20 @@ class ColumnSizer { case GridLinesVisibility.none: return Size.zero; case GridLinesVisibility.both: - return Size(isFirstColumn ? (strokeWidth + strokeWidth) : strokeWidth, - rowIndex == 0 ? (strokeWidth + strokeWidth) : strokeWidth); + return Size( + isFirstColumn ? (strokeWidth + strokeWidth) : strokeWidth, + rowIndex == 0 ? (strokeWidth + strokeWidth) : strokeWidth, + ); case GridLinesVisibility.vertical: - return Size(isFirstColumn ? (strokeWidth + strokeWidth) : strokeWidth, - rowIndex == 0 ? strokeWidth : 0); + return Size( + isFirstColumn ? (strokeWidth + strokeWidth) : strokeWidth, + rowIndex == 0 ? strokeWidth : 0, + ); case GridLinesVisibility.horizontal: - return Size((isFirstColumn || isLastColumn) ? strokeWidth : 0, - rowIndex == 0 ? (strokeWidth + strokeWidth) : strokeWidth); + return Size( + (isFirstColumn || isLastColumn) ? strokeWidth : 0, + rowIndex == 0 ? (strokeWidth + strokeWidth) : strokeWidth, + ); } } @@ -1235,23 +1424,25 @@ class ColumnSizer { _dataGridStateDetails!(); final Size strokeWidthSize = _getGridLineStrokeWidth( - rowIndex: rowIndex, - dataGridConfiguration: dataGridConfiguration, - column: column); + rowIndex: rowIndex, + dataGridConfiguration: dataGridConfiguration, + column: column, + ); final TextPainter textPainter = TextPainter( - text: TextSpan(text: value?.toString() ?? '', style: textStyle), - textScaler: TextScaler.linear(dataGridConfiguration.textScaleFactor), - textDirection: dataGridConfiguration.textDirection) - ..layout(maxWidth: width); + text: TextSpan(text: value?.toString() ?? '', style: textStyle), + textScaler: TextScaler.linear(dataGridConfiguration.textScaleFactor), + textDirection: dataGridConfiguration.textDirection, + )..layout(maxWidth: width); textSize = Size( - textPainter.size.width + - strokeWidthSize.width + - column.autoFitPadding.horizontal, - textPainter.size.height + - strokeWidthSize.height + - column.autoFitPadding.vertical); + textPainter.size.width + + strokeWidthSize.width + + column.autoFitPadding.horizontal, + textPainter.size.height + + strokeWidthSize.height + + column.autoFitPadding.vertical, + ); return textSize; } @@ -1274,7 +1465,9 @@ void resetAutoCalculation(ColumnSizer columnSizer) { /// Updates the column sizer's state whether its loaded or not initially. void updateColumnSizerLoadedInitiallyFlag( - ColumnSizer columnSizer, bool isLoaded) { + ColumnSizer columnSizer, + bool isLoaded, +) { columnSizer._isColumnSizerLoadedInitially = isLoaded; } @@ -1289,17 +1482,24 @@ double getFilterIconWidth(ColumnSizer columnSizer, GridColumn column) { } /// Returns the auto fit row height of the given row based on index. -double getAutoFitRowHeight(ColumnSizer columnSizer, int rowIndex, - {bool canIncludeHiddenColumns = false, - List excludedColumns = const []}) { - return columnSizer._getAutoFitRowHeight(rowIndex, - canIncludeHiddenColumns: canIncludeHiddenColumns, - excludedColumns: excludedColumns); +double getAutoFitRowHeight( + ColumnSizer columnSizer, + int rowIndex, { + bool canIncludeHiddenColumns = false, + List excludedColumns = const [], +}) { + return columnSizer._getAutoFitRowHeight( + rowIndex, + canIncludeHiddenColumns: canIncludeHiddenColumns, + excludedColumns: excludedColumns, + ); } /// Sets `dataGridConfiguration` to the [ColumnSizer]. void setStateDetailsInColumnSizer( - ColumnSizer columnSizer, DataGridStateDetails dataGridCellDetails) { + ColumnSizer columnSizer, + DataGridStateDetails dataGridCellDetails, +) { columnSizer._dataGridStateDetails = dataGridCellDetails; } @@ -1367,8 +1567,11 @@ class ColumnResizeController { dataRow.rowType == RowType.headerRow || dataRow.rowType == RowType.stackedHeaderRow; - VisibleLineInfo? _getHitTestResult(double dx, - {bool isPressed = false, bool canAllowBuffer = true}) { + VisibleLineInfo? _getHitTestResult( + double dx, { + bool isPressed = false, + bool canAllowBuffer = true, + }) { if (!isResizing) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); @@ -1378,8 +1581,9 @@ class ColumnResizeController { _resizingLine = _getResizingLine(dx, canAllowBuffer); - int startColumnIndex = - grid_helper.resolveToStartColumnIndex(dataGridConfiguration); + int startColumnIndex = grid_helper.resolveToStartColumnIndex( + dataGridConfiguration, + ); // Need to disable column resizing for the indent columns. if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { startColumnIndex += dataGridConfiguration.source.groupedColumns.length; @@ -1389,8 +1593,11 @@ class ColumnResizeController { _resizingLine!.lineIndex >= startColumnIndex) { // To ensure the resizing line for the stacked header row. if (dataGridConfiguration.stackedHeaderRows.isNotEmpty) { - if (!_canAllowResizing(dx, resizingDataCell, - canAllowBuffer: canAllowBuffer)) { + if (!_canAllowResizing( + dx, + resizingDataCell, + canAllowBuffer: canAllowBuffer, + )) { return null; } } @@ -1427,7 +1634,9 @@ class ColumnResizeController { _resizingLine!.lineIndex < dataGridConfiguration.container.columnCount) { final int lineIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, _resizingLine!.lineIndex); + dataGridConfiguration, + _resizingLine!.lineIndex, + ); _currentResizingColumn = dataGridConfiguration.columns[lineIndex]; } } else { @@ -1436,9 +1645,11 @@ class ColumnResizeController { } if (_raiseColumnResizeStart()) { isResizeIndicatorVisible = true; - indicatorPosition = _getIndicatorPosition(_resizingLine!, - dataGridConfiguration.textDirection == TextDirection.ltr, - isDefault: true); + indicatorPosition = _getIndicatorPosition( + _resizingLine!, + dataGridConfiguration.textDirection == TextDirection.ltr, + isDefault: true, + ); _resizingColumnWidth = _resizingLine!.size; @@ -1460,9 +1671,11 @@ class ColumnResizeController { // Need to update the resizing line to get the line's updated details after // resizing it. _resizingLine = dataGridConfiguration.container.scrollColumns - .getVisibleLineAtLineIndex(_resizingLine!.lineIndex, - isRightToLeft: - dataGridConfiguration.textDirection == TextDirection.rtl); + .getVisibleLineAtLineIndex( + _resizingLine!.lineIndex, + isRightToLeft: + dataGridConfiguration.textDirection == TextDirection.rtl, + ); if (dataGridConfiguration.columnResizeMode == ColumnResizeMode.onResize) { dataGridConfiguration.container.isDirty = true; @@ -1487,8 +1700,11 @@ class ColumnResizeController { // * Helper methods - bool _canAllowResizing(double downX, DataCellBase? dataColumn, - {bool canAllowBuffer = true}) { + bool _canAllowResizing( + double downX, + DataCellBase? dataColumn, { + bool canAllowBuffer = true, + }) { if (dataColumn != null && _resizingLine != null && dataColumn.dataRow!.rowType == RowType.stackedHeaderRow && @@ -1499,14 +1715,14 @@ class ColumnResizeController { final DataCellBase? dataCell = dataColumn.dataRow!.visibleColumns .firstWhereOrNull((DataCellBase dataCell) { - cellLeft = dataCell.columnIndex; - cellRight = dataCell.columnIndex + dataCell.columnSpan; - lineIndex = _resizingLine!.lineIndex; + cellLeft = dataCell.columnIndex; + cellRight = dataCell.columnIndex + dataCell.columnSpan; + lineIndex = _resizingLine!.lineIndex; - return cellLeft == lineIndex || - cellRight == lineIndex || - (lineIndex > cellLeft && lineIndex < cellRight); - }); + return cellLeft == lineIndex || + cellRight == lineIndex || + (lineIndex > cellLeft && lineIndex < cellRight); + }); if (dataCell != null) { final bool isLTR = @@ -1548,12 +1764,14 @@ class ColumnResizeController { final bool isLTR = dataGridConfiguration.textDirection == TextDirection.ltr; final VisibleLineInfo? visibleLine = dataGridConfiguration - .container.scrollColumns + .container + .scrollColumns .getVisibleLineAtLineIndex(dataCell.columnIndex, isRightToLeft: !isLTR); if (visibleLine != null) { - final bool canCheckNearCell = !(visibleLine.isLastLine && - visibleLine.isClippedCorner && - visibleLine.isClippedOrigin); + final bool canCheckNearCell = + !(visibleLine.isLastLine && + visibleLine.isClippedCorner && + visibleLine.isClippedOrigin); final double origin = isLTR ? visibleLine.clippedOrigin : visibleLine.corner; final double corner = @@ -1561,11 +1779,17 @@ class ColumnResizeController { if (canCheckNearCell) { if (_hitTestPrecision! > (corner - x).abs()) { - nearDataCell = _getDataCell(dataGridConfiguration, dataCell.rowIndex, - dataCell.columnIndex + 1); + nearDataCell = _getDataCell( + dataGridConfiguration, + dataCell.rowIndex, + dataCell.columnIndex + 1, + ); } else if (_hitTestPrecision! > (origin - x).abs()) { - nearDataCell = _getDataCell(dataGridConfiguration, dataCell.rowIndex, - dataCell.columnIndex - 1); + nearDataCell = _getDataCell( + dataGridConfiguration, + dataCell.rowIndex, + dataCell.columnIndex - 1, + ); } } @@ -1577,24 +1801,36 @@ class ColumnResizeController { } } - DataCellBase? _getDataCell(DataGridConfiguration dataGridConfiguration, - int rowIndex, int columnIndex) { + DataCellBase? _getDataCell( + DataGridConfiguration dataGridConfiguration, + int rowIndex, + int columnIndex, + ) { final DataRowBase? dataRow = dataGridConfiguration - .container.rowGenerator.items - .firstWhereOrNull((DataRowBase element) => - rowIndex >= 0 && element.rowIndex == rowIndex); + .container + .rowGenerator + .items + .firstWhereOrNull( + (DataRowBase element) => + rowIndex >= 0 && element.rowIndex == rowIndex, + ); if (dataRow == null || dataRow.visibleColumns.isEmpty) { return null; } - return dataRow.visibleColumns.firstWhereOrNull((DataCellBase dataCell) => - columnIndex >= 0 && dataCell.columnIndex == columnIndex); + return dataRow.visibleColumns.firstWhereOrNull( + (DataCellBase dataCell) => + columnIndex >= 0 && dataCell.columnIndex == columnIndex, + ); } - double _getIndicatorPosition(VisibleLineInfo line, bool isLTR, - {bool isDefault = false, - ScrollController? scrollController, - double? currentColumnWidth}) { + double _getIndicatorPosition( + VisibleLineInfo line, + bool isLTR, { + bool isDefault = false, + ScrollController? scrollController, + double? currentColumnWidth, + }) { late double indicatorLeft; final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (isDefault) { @@ -1608,16 +1844,19 @@ class ColumnResizeController { scrollController.position.extentAfter == 0))) { indicatorLeft = isLTR ? line.corner : line.clippedOrigin; } else { - indicatorLeft = isLTR - ? (line.origin + currentColumnWidth!) - : (line.corner + line.scrollOffset - currentColumnWidth!); + indicatorLeft = + isLTR + ? (line.origin + currentColumnWidth!) + : (line.corner + line.scrollOffset - currentColumnWidth!); } } // To remove the half of stroke width to show the indicator to the // center of grid line. - indicatorLeft -= dataGridConfiguration - .dataGridThemeHelper!.columnResizeIndicatorStrokeWidth! / + indicatorLeft -= + dataGridConfiguration + .dataGridThemeHelper! + .columnResizeIndicatorStrokeWidth! / 2; return indicatorLeft; @@ -1649,13 +1888,19 @@ class ColumnResizeController { } } - VisibleLineInfo? _getVisibleLineAtPoint(double position, bool isRTL, - {bool checkNearLine = false}) { + VisibleLineInfo? _getVisibleLineAtPoint( + double position, + bool isRTL, { + bool checkNearLine = false, + }) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (checkNearLine) { return dataGridConfiguration.container.scrollColumns.getLineNearCorner( - position, _hitTestPrecision!, CornerSide.both, - isRightToLeft: isRTL); + position, + _hitTestPrecision!, + CornerSide.both, + isRightToLeft: isRTL, + ); } else { return dataGridConfiguration.container.scrollColumns .getVisibleLineAtPoint(position, true, isRTL); @@ -1664,7 +1909,9 @@ class ColumnResizeController { /// Resolves the point of the current local position to get the visibleLine. double getXPosition( - DataGridConfiguration dataGridConfiguration, double localPosition) { + DataGridConfiguration dataGridConfiguration, + double localPosition, + ) { final ScrollController scrollController = dataGridConfiguration.horizontalScrollController!; if (dataGridConfiguration.textDirection == TextDirection.ltr) { @@ -1704,12 +1951,15 @@ class ColumnResizeController { /// As a result, the indexOf method returns -1. To obtain the correct currentResizing column index, the indexWhere method is employed instead. if (dataGridConfiguration.onColumnResizeStart != null) { return dataGridConfiguration.onColumnResizeStart!( - ColumnResizeStartDetails( - columnIndex: dataGridConfiguration.columns.indexWhere( - (GridColumn element) => - element.columnName == _currentResizingColumn!.columnName), - column: _currentResizingColumn!, - width: _resizingColumnWidth)); + ColumnResizeStartDetails( + columnIndex: dataGridConfiguration.columns.indexWhere( + (GridColumn element) => + element.columnName == _currentResizingColumn!.columnName, + ), + column: _currentResizingColumn!, + width: _resizingColumnWidth, + ), + ); } return true; } @@ -1718,12 +1968,15 @@ class ColumnResizeController { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (dataGridConfiguration.onColumnResizeUpdate != null) { return dataGridConfiguration.onColumnResizeUpdate!( - ColumnResizeUpdateDetails( - columnIndex: dataGridConfiguration.columns.indexWhere( - (GridColumn element) => - element.columnName == _currentResizingColumn!.columnName), - column: _currentResizingColumn!, - width: currentColumnWidth)); + ColumnResizeUpdateDetails( + columnIndex: dataGridConfiguration.columns.indexWhere( + (GridColumn element) => + element.columnName == _currentResizingColumn!.columnName, + ), + column: _currentResizingColumn!, + width: currentColumnWidth, + ), + ); } return true; } @@ -1731,12 +1984,16 @@ class ColumnResizeController { void _raiseColumnResizeEnd(double currentColumnWidth) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (dataGridConfiguration.onColumnResizeEnd != null) { - dataGridConfiguration.onColumnResizeEnd!(ColumnResizeEndDetails( + dataGridConfiguration.onColumnResizeEnd!( + ColumnResizeEndDetails( columnIndex: dataGridConfiguration.columns.indexWhere( - (GridColumn element) => - element.columnName == _currentResizingColumn!.columnName), + (GridColumn element) => + element.columnName == _currentResizingColumn!.columnName, + ), column: _currentResizingColumn!, - width: currentColumnWidth)); + width: currentColumnWidth, + ), + ); } } @@ -1744,18 +2001,23 @@ class ColumnResizeController { /// Handles the pointer down event for the column resizing. Future onPointerDown( - PointerDownEvent event, DataRowBase dataRow) async { + PointerDownEvent event, + DataRowBase dataRow, + ) async { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (dataGridConfiguration.isDesktop || _canStartResizeInMobile) { if (_isHeaderRow(dataRow)) { // Clears the editing before start resizing a column. if (dataGridConfiguration.currentCell.isEditing) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + ); } - final VisibleLineInfo? resizingLine = - _getHitTestResult(event.localPosition.dx, isPressed: true); + final VisibleLineInfo? resizingLine = _getHitTestResult( + event.localPosition.dx, + isPressed: true, + ); _canStartResizeInMobile = false; @@ -1809,16 +2071,21 @@ class ColumnResizeController { // To restricts the width of current resizing column from its minimum and // maximum width. _resizingColumnWidth = dataGridConfiguration.columnSizer - ._checkWidthConstraints(_currentResizingColumn!, - _resizingColumnWidth, currentColumnWidth); + ._checkWidthConstraints( + _currentResizingColumn!, + _resizingColumnWidth, + currentColumnWidth, + ); // To avoid resizing of column width after reached zero; _resizingColumnWidth = max(0.0, _resizingColumnWidth); final double indicatorPosition = _getIndicatorPosition( - _resizingLine!, isLTR, - scrollController: scrollController, - currentColumnWidth: _resizingColumnWidth); + _resizingLine!, + isLTR, + scrollController: scrollController, + currentColumnWidth: _resizingColumnWidth, + ); _onResizing(_resizingColumnWidth, indicatorPosition); } @@ -1867,9 +2134,10 @@ class ColumnResizeController { !dataGridConfiguration.isDesktop) { if (_isHeaderRow(dataRow)) { final VisibleLineInfo? resizingLine = _getHitTestResult( - details.localPosition.dx, - isPressed: true, - canAllowBuffer: false); + details.localPosition.dx, + isPressed: true, + canAllowBuffer: false, + ); if (resizingLine != null && isResizeIndicatorVisible) { _isLongPressEnabled = true; @@ -1897,8 +2165,10 @@ class ColumnResizeController { if (canSwitchResizeColumnCursor && dataGridConfiguration.columnDragAndDropController .canAllowColumnDragAndDrop()) { - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'columnDragAndDrop'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'columnDragAndDrop', + ); } } @@ -1914,8 +2184,10 @@ class ColumnResizeController { void _rebuild() { dataGridStateDetails().container.isDirty = true; - notifyDataGridPropertyChangeListeners(dataGridStateDetails().source, - propertyName: 'columnResizing'); + notifyDataGridPropertyChangeListeners( + dataGridStateDetails().source, + propertyName: 'columnResizing', + ); } } @@ -1923,12 +2195,13 @@ class ColumnResizeController { @immutable class FilterCondition { /// Creates the [FilterCondition] for [SfDataGrid]. - const FilterCondition( - {required this.type, - required this.value, - this.isCaseSensitive = false, - this.filterOperator = FilterOperator.or, - this.filterBehavior = FilterBehavior.strongDataType}); + const FilterCondition({ + required this.type, + required this.value, + this.isCaseSensitive = false, + this.filterOperator = FilterOperator.or, + this.filterBehavior = FilterBehavior.strongDataType, + }); /// The type of the filter should be applied for filter condition. final FilterType type; @@ -1962,7 +2235,7 @@ class FilterCondition { value, isCaseSensitive, filterOperator, - filterBehavior + filterBehavior, ]; return Object.hashAll(values); } @@ -1999,17 +2272,18 @@ class DataGridFilterHelper { late DataGridAdvancedFilterHelper advancedFilterHelper; /// Provides the height of the popup menu tile. - double get tileHeight => _dataGridStateDetails().isDesktop - ? _dataGridStateDetails() - .dataGridThemeHelper! - .filterPopupTextStyle! - .fontSize! + - 26 - : _dataGridStateDetails() - .dataGridThemeHelper! - .filterPopupTextStyle! - .fontSize! + - 38; + double get tileHeight => + _dataGridStateDetails().isDesktop + ? _dataGridStateDetails() + .dataGridThemeHelper! + .filterPopupTextStyle! + .fontSize! + + 26 + : _dataGridStateDetails() + .dataGridThemeHelper! + .filterPopupTextStyle! + .fontSize! + + 38; /// Provides the primary color. Color get primaryColor => _dataGridStateDetails().colorScheme!.primary; @@ -2019,9 +2293,10 @@ class DataGridFilterHelper { _dataGridStateDetails().dataGridThemeHelper!.filterPopupTextStyle!; /// Provides the text style to the disabled tiles. - TextStyle get disableTextStyle => _dataGridStateDetails() - .dataGridThemeHelper! - .filterPopupDisabledTextStyle!; + TextStyle get disableTextStyle => + _dataGridStateDetails() + .dataGridThemeHelper! + .filterPopupDisabledTextStyle!; /// Apply filter to the effective rows based on `filterConditions`. void applyFilter() { @@ -2034,9 +2309,10 @@ class DataGridFilterHelper { void createFilterConditions(bool isCheckboxFilter, GridColumn column) { // Creates filter conditions if it's a checkbox filter. if (isCheckboxFilter) { - _checkedItemsCount = checkboxFilterHelper.items - .where((FilterElement element) => element.isSelected) - .length; + _checkedItemsCount = + checkboxFilterHelper.items + .where((FilterElement element) => element.isSelected) + .length; _unCheckedItemsCount = checkboxFilterHelper.items.length - _checkedItemsCount; @@ -2061,8 +2337,9 @@ class DataGridFilterHelper { } } } else { - final bool useSelected = !(_checkedItemsCount > _unCheckedItemsCount && - _unCheckedItemsCount > 0); + final bool useSelected = + !(_checkedItemsCount > _unCheckedItemsCount && + _unCheckedItemsCount > 0); final List conditions = []; for (final FilterElement value in checkboxFilterHelper.items) { if (value.isSelected == useSelected) { @@ -2079,12 +2356,15 @@ class DataGridFilterHelper { filterOperator = FilterOperator.and; } - conditions.add(FilterCondition( + conditions.add( + FilterCondition( type: filterType, isCaseSensitive: true, value: filterValue, filterBehavior: FilterBehavior.stringDataType, - filterOperator: filterOperator)); + filterOperator: filterOperator, + ), + ); } } @@ -2193,15 +2473,19 @@ class DataGridFilterHelper { for (final String columnName in source.filterConditions.keys) { final GridColumn? column = dataGridConfiguration.columns .firstWhereOrNull( - (GridColumn column) => column.columnName == columnName); + (GridColumn column) => column.columnName == columnName, + ); if (column == null) { throwAssertFailure( - "The $columnName doesn't exist in the SfDataGrid.columns collection"); + "The $columnName doesn't exist in the SfDataGrid.columns collection", + ); continue; } - final Object? cellValue = - getFirstCellValue(source.effectiveRows, columnName); + final Object? cellValue = getFirstCellValue( + source.effectiveRows, + columnName, + ); for (final FilterCondition condition in source.filterConditions[columnName]!) { assert(() { @@ -2222,7 +2506,8 @@ class DataGridFilterHelper { if (cellValue?.runtimeType != condition.value?.runtimeType && (cellValue is! num && condition.value is! num)) { throwAssertFailure( - '${condition.value?.runtimeType} and ${cellValue.runtimeType} are not the same data type'); + '${condition.value?.runtimeType} and ${cellValue.runtimeType} are not the same data type', + ); } else if (condition.type == FilterType.contains || condition.type == FilterType.doesNotContain || condition.type == FilterType.beginsWith || @@ -2230,7 +2515,8 @@ class DataGridFilterHelper { condition.type == FilterType.endsWith || condition.type == FilterType.doesNotEndsWith) { throwAssertFailure( - 'FilterBehaviour and FilterType are not correct'); + 'FilterBehaviour and FilterType are not correct', + ); } else if (condition.type == FilterType.greaterThan || condition.type == FilterType.greaterThanOrEqual || condition.type == FilterType.lessThan || @@ -2239,7 +2525,8 @@ class DataGridFilterHelper { final String filterType = condition.type.toString().split('.').last; throwAssertFailure( - "The filter type $filterType can't check with the String type"); + "The filter type $filterType can't check with the String type", + ); } } } @@ -2249,7 +2536,8 @@ class DataGridFilterHelper { condition.type == FilterType.lessThan || condition.type == FilterType.lessThanOrEqual) { throwAssertFailure( - 'FilterBehaviour and FilterType are not correct'); + 'FilterBehaviour and FilterType are not correct', + ); } } return true; @@ -2267,8 +2555,10 @@ class DataGridFilterHelper { if (dataGridConfiguration.source.filterConditions.isNotEmpty) { final DataGridSource source = dataGridConfiguration.source; - final List filteredRows = - _getFilterRows(source.rows, source.filterConditions); + final List filteredRows = _getFilterRows( + source.rows, + source.filterConditions, + ); refreshEffectiveRows(source, filteredRows); } } @@ -2287,9 +2577,9 @@ class DataGridFilterHelper { List filteredRows = []; if (_previousDataRows.isNotEmpty) { filteredRows = _getFilterRows( - _previousDataRows, >{ - column.columnName: filterConditions - }); + _previousDataRows, + >{column.columnName: filterConditions}, + ); } else { filteredRows = _getFilterRows(source.rows, source.filterConditions); } @@ -2325,9 +2615,10 @@ class DataGridFilterHelper { if (conditions != null && conditions.isNotEmpty) { removeFilterConditions(source, columnName); - items = source.filterConditions.isEmpty - ? source.rows - : _getFilterRows(source.rows, source.filterConditions); + items = + source.filterConditions.isEmpty + ? source.rows + : _getFilterRows(source.rows, source.filterConditions); _previousDataRows = items.toList(); addFilterConditions(source, columnName, conditions); } else { @@ -2338,7 +2629,9 @@ class DataGridFilterHelper { } List _getCellValues( - GridColumn column, List items) { + GridColumn column, + List items, + ) { bool hasBlankValues = false; final DataGridSource source = _dataGridStateDetails().source; final List conditions = @@ -2350,8 +2643,8 @@ class DataGridFilterHelper { // find selected and unselected items in the checkbox list view. for (final DataGridRow row in source.effectiveRows) { final DataGridCell? cell = row.getCells().firstWhereOrNull( - (DataGridCell element) => - element.columnName == column.columnName); + (DataGridCell element) => element.columnName == column.columnName, + ); if (cell?.value?.toString() == value?.toString()) { return true; } @@ -2365,7 +2658,8 @@ class DataGridFilterHelper { final List filterElements = []; for (final DataGridRow row in items) { final DataGridCell? cell = row.getCells().firstWhereOrNull( - (DataGridCell element) => element.columnName == column.columnName); + (DataGridCell element) => element.columnName == column.columnName, + ); if (cell != null) { if (cell.value != null) { cellValues.add(cell.value); @@ -2376,8 +2670,9 @@ class DataGridFilterHelper { } if (hasBlankValues) { - filterElements - .add(FilterElement(value: '(Blanks)', isSelected: isSelected(null))); + filterElements.add( + FilterElement(value: '(Blanks)', isSelected: isSelected(null)), + ); } if (cellValues.isNotEmpty) { @@ -2393,11 +2688,14 @@ class DataGridFilterHelper { return value1.compareTo(value2); }); - filterElements.addAll(cellValues - .toSet() - .map( - (Object e) => FilterElement(value: e, isSelected: isSelected(e))) - .toList()); + filterElements.addAll( + cellValues + .toSet() + .map( + (Object e) => FilterElement(value: e, isSelected: isSelected(e)), + ) + .toList(), + ); } return filterElements; @@ -2407,16 +2705,20 @@ class DataGridFilterHelper { void endEdit() { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); if (dataGridConfiguration.currentCell.isEditing) { - dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, canRefresh: false); + dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + canRefresh: false, + ); } } /// Sets all the cell values to the check box filter. void setDataGridSource(GridColumn column) { final List items = _getPreviousFilteredRows(column.columnName); - final List distinctCollection = - _getCellValues(column, items); + final List distinctCollection = _getCellValues( + column, + items, + ); checkboxFilterHelper._previousDataGridSource = []; @@ -2436,25 +2738,30 @@ class DataGridFilterHelper { // Remove null and empty values from the items collection since it's not // applicable for the AdvancedFilter. advancedFilterHelper.items.removeWhere( - (FilterElement element) => isNullOrEmpty(element.value.toString())); + (FilterElement element) => isNullOrEmpty(element.value.toString()), + ); } checkboxFilterHelper.ensureSelectAllCheckboxState(); } List _getFilterRows( - List rows, Map> conditions) { + List rows, + Map> conditions, + ) { return rows .where((DataGridRow row) => _filterRow(row, conditions)) .toList(); } void _setPreviousDataGridSource() { - final bool useSelected = !(_checkedItemsCount > _unCheckedItemsCount && - _unCheckedItemsCount > 0); - final List items = checkboxFilterHelper.filterCheckboxItems - .where((FilterElement i) => useSelected) - .toList(); + final bool useSelected = + !(_checkedItemsCount > _unCheckedItemsCount && + _unCheckedItemsCount > 0); + final List items = + checkboxFilterHelper.filterCheckboxItems + .where((FilterElement i) => useSelected) + .toList(); checkboxFilterHelper._previousDataGridSource.addAll(items); } @@ -2467,7 +2774,8 @@ class DataGridFilterHelper { } dataGridConfiguration.source.sortedColumns.add( - SortColumnDetails(name: column.columnName, sortDirection: direction)); + SortColumnDetails(name: column.columnName, sortDirection: direction), + ); dataGridConfiguration.source.sort(); } @@ -2482,42 +2790,50 @@ class DataGridFilterHelper { } updateDataSource(dataGridConfiguration.source); selection_manager.refreshSelectedRows(dataGridConfiguration); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'Filtering'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'Filtering', + ); _invokeFilterChangedCallback(column, []); } bool _invokeFilterChangingCallback( - GridColumn column, List filterConditions) { + GridColumn column, + List filterConditions, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); if (dataGridConfiguration.onFilterChanging != null) { final DataGridFilterChangeDetails details = DataGridFilterChangeDetails( - column: column, - filterConditions: - List.unmodifiable(filterConditions)); + column: column, + filterConditions: List.unmodifiable(filterConditions), + ); return dataGridConfiguration.onFilterChanging!(details); } return true; } void _invokeFilterChangedCallback( - GridColumn column, List filterConditions) { + GridColumn column, + List filterConditions, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); if (dataGridConfiguration.onFilterChanged != null) { final DataGridFilterChangeDetails details = DataGridFilterChangeDetails( - column: column, - filterConditions: - List.unmodifiable(filterConditions)); + column: column, + filterConditions: List.unmodifiable(filterConditions), + ); dataGridConfiguration.onFilterChanged!(details); } } Object? _getCellValue(DataGridRow row, String columnName) { final GridColumn? column = _dataGridStateDetails().columns.firstWhereOrNull( - (GridColumn column) => column.columnName == columnName); + (GridColumn column) => column.columnName == columnName, + ); if (column != null) { final DataGridCell? cellValue = row.getCells().firstWhereOrNull( - (DataGridCell element) => element.columnName == column.columnName); + (DataGridCell element) => element.columnName == column.columnName, + ); if (cellValue != null && cellValue.value != null) { return cellValue.value; } @@ -2526,7 +2842,9 @@ class DataGridFilterHelper { } bool _filterRow( - DataGridRow row, Map> filterConditions) { + DataGridRow row, + Map> filterConditions, + ) { bool? isEqual; // Holds the previous column's comparer value of the current row to help to // perform multi-column filtering. @@ -2571,25 +2889,37 @@ class DataGridFilterHelper { comparerValue = !grid_helper.compareEndsWith(condition, cellValue); break; case FilterType.greaterThan: - comparerValue = - grid_helper.compareGreaterThan(condition, cellValue); + comparerValue = grid_helper.compareGreaterThan( + condition, + cellValue, + ); break; case FilterType.greaterThanOrEqual: - comparerValue = - grid_helper.compareGreaterThan(condition, cellValue, true); + comparerValue = grid_helper.compareGreaterThan( + condition, + cellValue, + true, + ); break; case FilterType.lessThan: comparerValue = grid_helper.compareLessThan(condition, cellValue); break; case FilterType.lessThanOrEqual: - comparerValue = - grid_helper.compareLessThan(condition, cellValue, true); + comparerValue = grid_helper.compareLessThan( + condition, + cellValue, + true, + ); break; } - isEqual = previousComparer && + isEqual = + previousComparer && grid_helper.compare( - isEqual, comparerValue, condition.filterOperator); + isEqual, + comparerValue, + condition.filterOperator, + ); } previousComparer = isEqual != null && isEqual; } @@ -2599,29 +2929,37 @@ class DataGridFilterHelper { void _createAdvancedFilterConditions(GridColumn column) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); final SfLocalizations localizations = dataGridConfiguration.localizations; - final FilterOperator filterOperator = advancedFilterHelper.isOrPredicate - ? FilterOperator.or - : FilterOperator.and; + final FilterOperator filterOperator = + advancedFilterHelper.isOrPredicate + ? FilterOperator.or + : FilterOperator.and; final List filterConditions = dataGridConfiguration.source.filterConditions[column.columnName] ?? - []; + []; final Object? filterValue1 = advancedFilterHelper.filterValue1; final Object? filterValue2 = advancedFilterHelper.filterValue2; final String? filterType1 = advancedFilterHelper.filterType1; final String? filterType2 = advancedFilterHelper.filterType2; - final FilterType type1 = - grid_helper.getFilterType(dataGridConfiguration, filterType1 ?? ''); - final FilterType type2 = - grid_helper.getFilterType(dataGridConfiguration, filterType2 ?? ''); + final FilterType type1 = grid_helper.getFilterType( + dataGridConfiguration, + filterType1 ?? '', + ); + final FilterType type2 = grid_helper.getFilterType( + dataGridConfiguration, + filterType2 ?? '', + ); if (filterConditions.isNotEmpty) { filterConditions.clear(); } bool canCreateFilterCondition( - Object? filterValue, String? filterType, bool isFirstCondition) { + Object? filterValue, + String? filterType, + bool isFirstCondition, + ) { void setFilterValue(String? value) { if (isFirstCondition) { advancedFilterHelper.filterValue1 = value; @@ -2660,22 +2998,24 @@ class DataGridFilterHelper { // Condition 1 if (canCreateFilterCondition(filterValue1, filterType1, true)) { final FilterCondition condition = FilterCondition( - type: type1, - filterOperator: getFilterOperator(), - value: advancedFilterHelper.filterValue1, - filterBehavior: FilterBehavior.stringDataType, - isCaseSensitive: advancedFilterHelper.isCaseSensitive1); + type: type1, + filterOperator: getFilterOperator(), + value: advancedFilterHelper.filterValue1, + filterBehavior: FilterBehavior.stringDataType, + isCaseSensitive: advancedFilterHelper.isCaseSensitive1, + ); filterConditions.add(condition); } // Condition 2 if (canCreateFilterCondition(filterValue2, filterType2, false)) { final FilterCondition condition = FilterCondition( - type: type2, - filterOperator: getFilterOperator(), - value: advancedFilterHelper.filterValue2, - filterBehavior: FilterBehavior.stringDataType, - isCaseSensitive: advancedFilterHelper.isCaseSensitive2); + type: type2, + filterOperator: getFilterOperator(), + value: advancedFilterHelper.filterValue2, + filterBehavior: FilterBehavior.stringDataType, + isCaseSensitive: advancedFilterHelper.isCaseSensitive2, + ); filterConditions.add(condition); } } @@ -2685,18 +3025,20 @@ class DataGridFilterHelper { // Condition 1 if (canCreateFilterCondition(filterValue1, filterType1, true)) { final FilterCondition condition = FilterCondition( - type: type1, - filterOperator: getFilterOperator(), - value: advancedFilterHelper.filterValue1); + type: type1, + filterOperator: getFilterOperator(), + value: advancedFilterHelper.filterValue1, + ); filterConditions.add(condition); } // Condition 2 if (canCreateFilterCondition(filterValue2, filterType2, false)) { final FilterCondition condition = FilterCondition( - type: type2, - filterOperator: getFilterOperator(), - value: advancedFilterHelper.filterValue2); + type: type2, + filterOperator: getFilterOperator(), + value: advancedFilterHelper.filterValue2, + ); filterConditions.add(condition); } } @@ -2706,18 +3048,20 @@ class DataGridFilterHelper { // Condition 1 if (canCreateFilterCondition(filterValue1, filterType1, true)) { final FilterCondition condition = FilterCondition( - type: type1, - filterOperator: getFilterOperator(), - value: advancedFilterHelper.filterValue1); + type: type1, + filterOperator: getFilterOperator(), + value: advancedFilterHelper.filterValue1, + ); filterConditions.add(condition); } // Condition 2 if (canCreateFilterCondition(filterValue2, filterType2, false)) { final FilterCondition condition = FilterCondition( - type: type2, - filterOperator: getFilterOperator(), - value: advancedFilterHelper.filterValue2); + type: type2, + filterOperator: getFilterOperator(), + value: advancedFilterHelper.filterValue2, + ); filterConditions.add(condition); } } @@ -2727,7 +3071,10 @@ class DataGridFilterHelper { if (filterConditions.isNotEmpty) { setFilterFrom(column, FilteredFrom.advancedFilter); addFilterConditions( - dataGridConfiguration.source, column.columnName, filterConditions); + dataGridConfiguration.source, + column.columnName, + filterConditions, + ); _applyViewFilter(column); } } @@ -2785,9 +3132,10 @@ class DataGridCheckboxFilterHelper { if (searchText.isEmpty) { _searchedItems = []; if (_previousDataGridSource.isNotEmpty) { - final int checkedCount = _previousDataGridSource - .where((FilterElement element) => element.isSelected) - .length; + final int checkedCount = + _previousDataGridSource + .where((FilterElement element) => element.isSelected) + .length; final bool isSelected = checkedCount > 0; for (final FilterElement item in filterCheckboxItems) { final FilterElement? filterElement = _previousDataGridSource @@ -2801,12 +3149,15 @@ class DataGridCheckboxFilterHelper { return; } - _searchedItems = filterCheckboxItems - .where((FilterElement element) => element.value - .toString() - .toLowerCase() - .contains(searchText.toLowerCase())) - .toList(); + _searchedItems = + filterCheckboxItems + .where( + (FilterElement element) => element.value + .toString() + .toLowerCase() + .contains(searchText.toLowerCase()), + ) + .toList(); for (final FilterElement element in _searchedItems) { element.isSelected = true; @@ -2876,7 +3227,7 @@ class DataGridAdvancedFilterHelper { localizations.nullDataGridFilteringLabel, localizations.notNullDataGridFilteringLabel, localizations.emptyDataGridFilteringLabel, - localizations.notEmptyDataGridFilteringLabel + localizations.notEmptyDataGridFilteringLabel, ]; textFieldFilterTypes = [ @@ -2947,11 +3298,14 @@ class DataGridAdvancedFilterHelper { /// Sets the advanced filter type based on the column type. void setAdvancedFilterType( - DataGridConfiguration dataGridConfiguration, GridColumn column) { + DataGridConfiguration dataGridConfiguration, + GridColumn column, + ) { Object? value; for (final DataGridRow row in dataGridConfiguration.source.rows) { final DataGridCell? cellValue = row.getCells().firstWhereOrNull( - (DataGridCell element) => element.columnName == column.columnName); + (DataGridCell element) => element.columnName == column.columnName, + ); if (cellValue != null && cellValue.value != null) { value = cellValue.value; break; @@ -2968,8 +3322,11 @@ class DataGridAdvancedFilterHelper { } /// Sets the advanced filter values. - void setAdvancedFilterValues(DataGridConfiguration dataGridConfiguration, - List filterConditions, DataGridFilterHelper helper) { + void setAdvancedFilterValues( + DataGridConfiguration dataGridConfiguration, + List filterConditions, + DataGridFilterHelper helper, + ) { Object? getValue(Object? value, String? filterType) { if (items.any((FilterElement element) => element.value == value) || (filterType != null && textFieldFilterTypes.contains(filterType))) { @@ -2981,7 +3338,10 @@ class DataGridAdvancedFilterHelper { if (filterConditions.isNotEmpty) { final FilterCondition condition = filterConditions.first; filterType1 = grid_helper.getFilterName( - dataGridConfiguration, condition.type, condition.value); + dataGridConfiguration, + condition.type, + condition.value, + ); filterValue1 = getValue(condition.value, filterType1); isCaseSensitive1 = condition.isCaseSensitive; isOrPredicate = condition.filterOperator == FilterOperator.or; @@ -2995,7 +3355,10 @@ class DataGridAdvancedFilterHelper { if (filterConditions.length == 2) { final FilterCondition condition = filterConditions.last; filterType2 = grid_helper.getFilterName( - dataGridConfiguration, condition.type, condition.value); + dataGridConfiguration, + condition.type, + condition.value, + ); filterValue2 = getValue(condition.value, filterType2); isCaseSensitive2 = condition.isCaseSensitive; isOrPredicate = condition.filterOperator == FilterOperator.or; @@ -3009,8 +3372,9 @@ class DataGridAdvancedFilterHelper { /// Resets the advanced filter values. void resetAdvancedFilterValues(DataGridConfiguration dataGridConfiguration) { - filterType1 = filterType2 = - dataGridConfiguration.localizations.equalsDataGridFilteringLabel; + filterType1 = + filterType2 = + dataGridConfiguration.localizations.equalsDataGridFilteringLabel; filterValue1 = filterValue2 = null; isCaseSensitive1 = isCaseSensitive2 = false; isOrPredicate = true; @@ -3036,11 +3400,12 @@ class FilterElement { @immutable class FilterPopupMenuOptions { /// - const FilterPopupMenuOptions( - {this.filterMode = FilterMode.both, - this.canShowClearFilterOption = true, - this.canShowSortingOptions = true, - this.showColumnName = true}); + const FilterPopupMenuOptions({ + this.filterMode = FilterMode.both, + this.canShowClearFilterOption = true, + this.canShowSortingOptions = true, + this.showColumnName = true, + }); /// Decides how the checked listbox and advanced filter options should be shown in filter popup. final FilterMode filterMode; @@ -3155,13 +3520,16 @@ class ColumnDragAndDropController { double indicatorPositionThreshold = 10; void _rebuild(DataGridConfiguration dataGridConfiguration) { - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'columnDragAndDrop'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'columnDragAndDrop', + ); } Future _autoScrollIfNecessary( - DataGridConfiguration dataGridConfiguration, - PointerMoveEvent details) async { + DataGridConfiguration dataGridConfiguration, + PointerMoveEvent details, + ) async { if (!autoScrolling && !disableScrolling) { final ScrollPosition position = dataGridConfiguration.horizontalScrollController!.position; @@ -3181,40 +3549,52 @@ class ColumnDragAndDropController { if (dragDelta > scrollEnd && position.pixels > position.minScrollExtent) { final double overDrag = max(dragDelta - scrollEnd, overDragMax); - newOffset = max(position.minScrollExtent, - position.pixels - step * overDrag / overDragCoef); + newOffset = max( + position.minScrollExtent, + position.pixels - step * overDrag / overDragCoef, + ); } else if (dragDelta < scrollStart && position.pixels < position.maxScrollExtent) { final double overDrag = max(scrollStart - dragDelta, overDragMax); - newOffset = min(position.maxScrollExtent, - position.pixels + step * overDrag / overDragCoef); + newOffset = min( + position.maxScrollExtent, + position.pixels + step * overDrag / overDragCoef, + ); } } else { if (dragDelta < scrollStart && position.pixels > position.minScrollExtent) { final double overDrag = max(scrollStart - dragDelta, overDragMax); - newOffset = max(position.minScrollExtent, - position.pixels - step * overDrag / overDragCoef); + newOffset = max( + position.minScrollExtent, + position.pixels - step * overDrag / overDragCoef, + ); } else if (dragDelta > scrollEnd && position.pixels < position.maxScrollExtent) { final double overDrag = max(dragDelta - scrollEnd, overDragMax); - newOffset = min(position.maxScrollExtent, - position.pixels + step * overDrag / overDragCoef); + newOffset = min( + position.maxScrollExtent, + position.pixels + step * overDrag / overDragCoef, + ); } } if (newOffset != null && (newOffset - position.pixels).abs() >= 1.0) { autoScrolling = true; - await position.animateTo(newOffset, - duration: duration, curve: Curves.linear); + await position.animateTo( + newOffset, + duration: duration, + curve: Curves.linear, + ); dataGridConfiguration.container.scrollColumns ..markDirty() ..updateScrollbar(); autoScrolling = false; - columnIndex = getColumnLineInfo( - dataGridConfiguration, - details.position.dx, - )?.lineIndex; + columnIndex = + getColumnLineInfo( + dataGridConfiguration, + details.position.dx, + )?.lineIndex; _autoScrollIfNecessary(dataGridConfiguration, details); @@ -3234,7 +3614,9 @@ class ColumnDragAndDropController { /// The [getVisibleLineAtPoint] method of the [scrollColumns] object is called with the resolved [TextDirection] and the [position] to get the [VisibleLineInfo]. /// VisibleLineInfo? getColumnLineInfo( - DataGridConfiguration dataGridConfiguration, double position) { + DataGridConfiguration dataGridConfiguration, + double position, + ) { final bool isRTL = dataGridConfiguration.textDirection == TextDirection.rtl; if (isRTL) { dataGridConfiguration.container.scrollColumns.resetVisibleLines(); @@ -3243,9 +3625,10 @@ class ColumnDragAndDropController { // This code retrieves the visible line at the given position within the SfDataGrid container. // The position is adjusted for the data grid's origin position, and the function checks for RTL layout. return dataGridConfiguration.container.scrollColumns.getVisibleLineAtPoint( - position - getDataGridOriginPosition(dataGridConfiguration).dx, - false, - isRTL); + position - getDataGridOriginPosition(dataGridConfiguration).dx, + false, + isRTL, + ); } /// Returns the visible line information for a given vertical position in the data grid. @@ -3255,17 +3638,23 @@ class ColumnDragAndDropController { /// The [getVisibleLineAtPoint] method of the [scrollRows] object of the [configuration] is used to obtain the [VisibleLineInfo]. /// VisibleLineInfo? getRowLineInfo( - DataGridConfiguration dataGridConfiguration, double position) { - return dataGridConfiguration.container.scrollRows - .getVisibleLineAtPoint(position); + DataGridConfiguration dataGridConfiguration, + double position, + ) { + return dataGridConfiguration.container.scrollRows.getVisibleLineAtPoint( + position, + ); } /// Returns the start index adjusted for a checkbox column. /// /// If [showCheckboxColumn] is true, subtracts 1 from [startIndex] to account for the checkbox column. /// Returns the adjusted start index as an int value. - int? getStartIndex(int startIndex, bool showCheckboxColumn, - DataGridConfiguration dataGridConfiguration) { + int? getStartIndex( + int startIndex, + bool showCheckboxColumn, + DataGridConfiguration dataGridConfiguration, + ) { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { startIndex -= dataGridConfiguration.source.groupedColumns.length; } @@ -3276,8 +3665,12 @@ class ColumnDragAndDropController { /// /// If the [showCheckboxColumn] is true, then decrement the [endIndex] by 1. /// If [startIndex] is equal to [endIndex], then return null. - int? getEndIndex(int startIndex, int endIndex, bool showCheckboxColumn, - DataGridConfiguration dataGridConfiguration) { + int? getEndIndex( + int startIndex, + int endIndex, + bool showCheckboxColumn, + DataGridConfiguration dataGridConfiguration, + ) { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { endIndex -= dataGridConfiguration.source.groupedColumns.length; } @@ -3287,8 +3680,8 @@ class ColumnDragAndDropController { return startIndex == endIndex || endIndex < 0 ? null : showCheckboxColumn && endIndex == -1 - ? null - : endIndex; + ? null + : endIndex; } /// Returns the origin position of the data grid within the screen coordinates. @@ -3299,7 +3692,8 @@ class ColumnDragAndDropController { /// The [RenderBox.localToGlobal] method is then called on the [scrollRenderBox] to get its global position. /// Offset getDataGridOriginPosition( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, + ) { final RenderBox scrollRenderBox = dataGridConfiguration.dataGridKey.currentContext!.findRenderObject()! as RenderBox; @@ -3321,12 +3715,17 @@ class ColumnDragAndDropController { canResetColumnWidthCalculation = false; if (dataCell != null && dataCell.cellType == CellType.headerCell) { - dragColumnStartIndex = getStartIndex(dataCell.columnIndex, - dataGridConfiguration.showCheckboxColumn, dataGridConfiguration); - dragColumnEndIndex = dataCell.columnIndex - + dragColumnStartIndex = getStartIndex( + dataCell.columnIndex, + dataGridConfiguration.showCheckboxColumn, + dataGridConfiguration, + ); + dragColumnEndIndex = + dataCell.columnIndex - dataGridConfiguration.source.groupedColumns.length; canWrapDraggableView = dataGridConfiguration.onColumnDragging!( - _invokeOnColumnDragging(action: DataGridColumnDragAction.starting)); + _invokeOnColumnDragging(action: DataGridColumnDragAction.starting), + ); if (!canWrapDraggableView) { // need to remove draggableView when the onColumnDragging returns false. @@ -3335,7 +3734,8 @@ class ColumnDragAndDropController { if (canWrapDraggableView && dragColumnStartIndex != null) { canWrapDraggableView = dataGridConfiguration.onColumnDragging!( - _invokeOnColumnDragging(action: DataGridColumnDragAction.started)); + _invokeOnColumnDragging(action: DataGridColumnDragAction.started), + ); if (!canWrapDraggableView) { _rebuild(dataGridConfiguration); } @@ -3349,17 +3749,22 @@ class ColumnDragAndDropController { if (canWrapDraggableView && dragColumnStartIndex != null) { offset = event.localPosition; dragDelta = dragDelta + event.delta.dx; - columnIndex = getColumnLineInfo(dataGridConfiguration, event.position.dx) - ?.lineIndex; - final int? rowIndex = getRowLineInfo( - dataGridConfiguration, - event.position.dy - - getDataGridOriginPosition(dataGridConfiguration).dy) - ?.lineIndex; + columnIndex = + getColumnLineInfo( + dataGridConfiguration, + event.position.dx, + )?.lineIndex; + final int? rowIndex = + getRowLineInfo( + dataGridConfiguration, + event.position.dy - + getDataGridOriginPosition(dataGridConfiguration).dy, + )?.lineIndex; if (columnIndex != null && rowIndex != null) { - final int headerIndex = - grid_helper.getHeaderIndex(dataGridConfiguration); + final int headerIndex = grid_helper.getHeaderIndex( + dataGridConfiguration, + ); isHoverDisabled = true; scrollOrigin = getDataGridOriginPosition(dataGridConfiguration); @@ -3371,7 +3776,8 @@ class ColumnDragAndDropController { offset = event.localPosition; columnIndex = columnIndex; - final bool isLeftToRightDrag = _isLeftToRightDrag != null && + final bool isLeftToRightDrag = + _isLeftToRightDrag != null && (dataGridConfiguration.textDirection == TextDirection.ltr ? _isLeftToRightDrag! : !_isLeftToRightDrag!); @@ -3408,10 +3814,11 @@ class ColumnDragAndDropController { _autoScrollIfNecessary(dataGridConfiguration, event); allowColumnDrag = dataGridConfiguration.onColumnDragging!( - _invokeOnColumnDragging( - action: DataGridColumnDragAction.update, - showCheckboxColumn: - dataGridConfiguration.showCheckboxColumn)); + _invokeOnColumnDragging( + action: DataGridColumnDragAction.update, + showCheckboxColumn: dataGridConfiguration.showCheckboxColumn, + ), + ); } else { disableScrolling = true; canDrawRightIndicator = null; @@ -3435,31 +3842,40 @@ class ColumnDragAndDropController { if (allowColumnDrag && scrollOrigin != null && event.position.dy >= scrollOrigin!.dy) { - columnIndex = getColumnLineInfo(dataGridConfiguration, event.position.dx) - ?.lineIndex; - final int? rowIndex = getRowLineInfo( - dataGridConfiguration, - event.position.dy - - getDataGridOriginPosition(dataGridConfiguration).dy) - ?.lineIndex; + columnIndex = + getColumnLineInfo( + dataGridConfiguration, + event.position.dx, + )?.lineIndex; + final int? rowIndex = + getRowLineInfo( + dataGridConfiguration, + event.position.dy - + getDataGridOriginPosition(dataGridConfiguration).dy, + )?.lineIndex; final int headerIndex = grid_helper.getHeaderIndex(dataGridConfiguration); if (columnIndex != null && rowIndex == headerIndex && dataGridConfiguration.onColumnDragging != null) { - dragColumnEndIndex = getEndIndex(dragColumnStartIndex!, columnIndex!, - dataGridConfiguration.showCheckboxColumn, dataGridConfiguration); + dragColumnEndIndex = getEndIndex( + dragColumnStartIndex!, + columnIndex!, + dataGridConfiguration.showCheckboxColumn, + dataGridConfiguration, + ); columnIndex = columnIndex! - dataGridConfiguration.source.groupedColumns.length; offset = event.localPosition; allowColumnDrag = dataGridConfiguration.onColumnDragging!( - _invokeOnColumnDragging(action: DataGridColumnDragAction.dropping)); + _invokeOnColumnDragging(action: DataGridColumnDragAction.dropping), + ); if (allowColumnDrag) { allowColumnDrag = dataGridConfiguration.onColumnDragging!( - _invokeOnColumnDragging( - action: DataGridColumnDragAction.dropped)); + _invokeOnColumnDragging(action: DataGridColumnDragAction.dropped), + ); } } } @@ -3479,9 +3895,10 @@ class ColumnDragAndDropController { _rebuild(dataGridConfiguration); } - DataGridColumnDragDetails _invokeOnColumnDragging( - {required DataGridColumnDragAction action, - bool showCheckboxColumn = false}) { + DataGridColumnDragDetails _invokeOnColumnDragging({ + required DataGridColumnDragAction action, + bool showCheckboxColumn = false, + }) { int? to; if (action == DataGridColumnDragAction.update && columnIndex != null) { to = showCheckboxColumn ? (columnIndex! - 1) : columnIndex; @@ -3505,6 +3922,10 @@ class ColumnDragAndDropController { } } return DataGridColumnDragDetails( - from: dragColumnStartIndex!, to: to, offset: offset!, action: action); + from: dragColumnStartIndex!, + to: to, + offset: offset!, + action: action, + ); } } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/generator.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/generator.dart index e1d6c2477..344eb56b2 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/generator.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/runtime/generator.dart @@ -100,10 +100,13 @@ abstract class DataCellBase { return; } - final RowColumnIndex currentRowColumnIndex = - RowColumnIndex(rowIndex, columnIndex); - dataGridConfiguration.rowSelectionManager - .handleTap(currentRowColumnIndex); + final RowColumnIndex currentRowColumnIndex = RowColumnIndex( + rowIndex, + columnIndex, + ); + dataGridConfiguration.rowSelectionManager.handleTap( + currentRowColumnIndex, + ); } } } @@ -216,10 +219,9 @@ abstract class DataRowBase { /// Returns the `VisibleLineInfo` for the given column index. VisibleLineInfo? getColumnVisibleLineInfo(int index) => - dataGridStateDetails!() - .container - .scrollColumns - .getVisibleLineAtLineIndex(index); + dataGridStateDetails!().container.scrollColumns.getVisibleLineAtLineIndex( + index, + ); /// Returns the `VisibleLineInfo` for the given row index. VisibleLineInfo? getRowVisibleLineInfo(int index) => dataGridStateDetails!() @@ -421,7 +423,8 @@ class DataRow extends DataRowBase { } else { _updateColumn(dc, index); dc ??= visibleColumns.firstWhereOrNull( - (DataCellBase col) => col.columnIndex == index); + (DataCellBase col) => col.columnIndex == index, + ); if (dc != null) { if (!dc.isVisible) { @@ -441,15 +444,18 @@ class DataRow extends DataRowBase { if (dc == null) { DataCellBase? dataCell; dataCell = _reUseCell(startColumnIndex, endColumnIndex); - dataCell ??= visibleColumns.firstWhereOrNull((DataCellBase col) => - col.columnIndex == -1 && col.cellType != CellType.indentCell); + dataCell ??= visibleColumns.firstWhereOrNull( + (DataCellBase col) => + col.columnIndex == -1 && col.cellType != CellType.indentCell, + ); _updateColumn(dataCell, index); dataCell = null; } - dc ??= visibleColumns - .firstWhereOrNull((DataCellBase col) => col.columnIndex == index); + dc ??= visibleColumns.firstWhereOrNull( + (DataCellBase col) => col.columnIndex == index, + ); if (dc != null) { if (!dc.isVisible) { @@ -492,15 +498,19 @@ class DataRow extends DataRowBase { DataCellBase _createColumn(int index) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails!(); - final bool canIncrementHeight = rowType == RowType.headerRow && + final bool canIncrementHeight = + rowType == RowType.headerRow && dataGridConfiguration.stackedHeaderRows.isNotEmpty; - final DataCellBase dc = DataCell() - ..dataRow = this - ..columnIndex = index - ..rowIndex = rowIndex; + final DataCellBase dc = + DataCell() + ..dataRow = this + ..columnIndex = index + ..rowIndex = rowIndex; dc.key = ObjectKey(dc); final int columnIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, index); + dataGridConfiguration, + index, + ); dc.gridColumn = dataGridConfiguration.columns[columnIndex]; _checkForCurrentCell(dataGridConfiguration, dc); if (rowIndex == grid_helper.getHeaderIndex(dataGridConfiguration) && @@ -523,8 +533,12 @@ class DataRow extends DataRowBase { } if (canIncrementHeight) { final int rowSpan = grid_helper.getRowSpan( - dataGridConfiguration, dc.dataRow!.rowIndex - 1, index, false, - mappingName: dc.gridColumn!.columnName); + dataGridConfiguration, + dc.dataRow!.rowIndex - 1, + index, + false, + mappingName: dc.gridColumn!.columnName, + ); dc.rowSpan = rowSpan; } @@ -551,17 +565,20 @@ class DataRow extends DataRowBase { } DataCellBase? _reUseCell(int startColumnIndex, int endColumnIndex) => - visibleColumns.firstWhereOrNull((DataCellBase cell) => - cell.gridColumn != null && - (cell.columnIndex < 0 || - cell.columnIndex < startColumnIndex || - cell.columnIndex > endColumnIndex) && - !cell.isEnsured && - !cell.isEditing); + visibleColumns.firstWhereOrNull( + (DataCellBase cell) => + cell.gridColumn != null && + (cell.columnIndex < 0 || + cell.columnIndex < startColumnIndex || + cell.columnIndex > endColumnIndex) && + !cell.isEnsured && + !cell.isEditing, + ); void _updateColumn(DataCellBase? dc, int index) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails!(); - final bool canIncrementHeight = rowType == RowType.headerRow && + final bool canIncrementHeight = + rowType == RowType.headerRow && dataGridConfiguration.stackedHeaderRows.isNotEmpty; if (dc != null) { if (index < 0 || index >= dataGridConfiguration.container.columnCount) { @@ -573,14 +590,20 @@ class DataRow extends DataRowBase { ..key = dc.key ..isVisible = true; final int columnIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, index); + dataGridConfiguration, + index, + ); dc.gridColumn = dataGridConfiguration.columns[columnIndex]; _checkForCurrentCell(dataGridConfiguration, dc); _updateRenderer(dataGridConfiguration, dc, dc.gridColumn); if (canIncrementHeight) { final int rowSpan = grid_helper.getRowSpan( - dataGridConfiguration, dc.dataRow!.rowIndex - 1, index, false, - mappingName: dc.gridColumn!.columnName); + dataGridConfiguration, + dc.dataRow!.rowIndex - 1, + index, + false, + mappingName: dc.gridColumn!.columnName, + ); dc.rowSpan = rowSpan; } else { dc.rowSpan = 0; @@ -605,8 +628,11 @@ class DataRow extends DataRowBase { } } - void _updateRenderer(DataGridConfiguration dataGridConfiguration, - DataCellBase dataCell, GridColumn? column) { + void _updateRenderer( + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, + GridColumn? column, + ) { GridCellRendererBase? newRenderer; if (rowRegion == RowRegion.header && rowType == RowType.headerRow) { newRenderer = dataGridConfiguration.cellRenderers['ColumnHeader']; @@ -629,7 +655,9 @@ class DataRow extends DataRowBase { } void _checkForCurrentCell( - DataGridConfiguration dataGridConfiguration, DataCellBase dc) { + DataGridConfiguration dataGridConfiguration, + DataCellBase dc, + ) { if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { final CurrentCellManager currentCellManager = dataGridConfiguration.currentCell; @@ -662,8 +690,10 @@ class RowGenerator { /// Generates the rows for the [SfDataGrid] by using [DataGridSource]. /// It's generating rows for the data grid initially. - void preGenerateRows(VisibleLinesCollection? visibleRows, - VisibleLinesCollection? visibleColumns) { + void preGenerateRows( + VisibleLinesCollection? visibleRows, + VisibleLinesCollection? visibleColumns, + ) { if (items.isNotEmpty || _dataGridConfiguration.container.rowCount <= 0) { return; } @@ -692,18 +722,22 @@ class RowGenerator { } /// Ensures the data grid rows based on current visible rows. - void ensureRows(VisibleLinesCollection visibleRows, - VisibleLinesCollection visibleColumns) { + void ensureRows( + VisibleLinesCollection visibleRows, + VisibleLinesCollection visibleColumns, + ) { List? actualStartAndEndIndex = []; RowRegion? region = RowRegion.header; List reUseRows() => items - .where((DataRowBase row) => - (row.rowIndex < 0 || - row.rowIndex < actualStartAndEndIndex![0] || - row.rowIndex > actualStartAndEndIndex[1]) && - !row.isEnsured && - !row.isEditing) + .where( + (DataRowBase row) => + (row.rowIndex < 0 || + row.rowIndex < actualStartAndEndIndex![0] || + row.rowIndex > actualStartAndEndIndex[1]) && + !row.isEnsured && + !row.isEditing, + ) .toList(growable: false); void reuseRow(int rowIndex, RowRegion rowRegion) { @@ -730,9 +764,11 @@ class RowGenerator { actualStartAndEndIndex = _container.getStartEndIndex(visibleRows, i); } - for (int index = actualStartAndEndIndex[0]; - index <= actualStartAndEndIndex[1]; - index++) { + for ( + int index = actualStartAndEndIndex[0]; + index <= actualStartAndEndIndex[1]; + index++ + ) { DataRowBase? dr = _indexer(index); if (dr == null) { final DataGridConfiguration dataGridConfiguration = @@ -755,8 +791,9 @@ class RowGenerator { } } - dr ??= - items.firstWhereOrNull((DataRowBase row) => row.rowIndex == index); + dr ??= items.firstWhereOrNull( + (DataRowBase row) => row.rowIndex == index, + ); if (dr != null) { if (!dr.isVisible) { @@ -803,16 +840,19 @@ class RowGenerator { } DataRowBase _createDataRow( - int rowIndex, VisibleLinesCollection visibleColumns, - {RowRegion rowRegion = RowRegion.body}) { + int rowIndex, + VisibleLinesCollection visibleColumns, { + RowRegion rowRegion = RowRegion.body, + }) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); DataRowBase dr; if (grid_helper.isFooterWidgetRow(rowIndex, dataGridConfiguration)) { - dr = DataRow() - ..rowIndex = rowIndex - ..rowRegion = rowRegion - ..rowType = RowType.footerRow - ..dataGridStateDetails = dataGridStateDetails; + dr = + DataRow() + ..rowIndex = rowIndex + ..rowRegion = rowRegion + ..rowType = RowType.footerRow + ..dataGridStateDetails = dataGridStateDetails; dr.key = ObjectKey(dr); dr.footerView = _buildFooterWidget(dataGridConfiguration, rowIndex); return dr; @@ -820,33 +860,42 @@ class RowGenerator { dynamic displayElement; if (dataGridConfiguration.source.groupedColumns.isNotEmpty && rowIndex >= 0) { - final int index = - resolveStartRecordIndex(dataGridConfiguration, rowIndex); + final int index = resolveStartRecordIndex( + dataGridConfiguration, + rowIndex, + ); displayElement = (index >= 0) ? getGroupElement(dataGridConfiguration, index) : null; } else { displayElement = null; } if (displayElement == null || displayElement is DataGridRow) { - dr = DataRow() - ..rowIndex = rowIndex - ..rowRegion = rowRegion - ..rowType = RowType.dataRow - ..rowData = displayElement - ..dataGridStateDetails = dataGridStateDetails; + dr = + DataRow() + ..rowIndex = rowIndex + ..rowRegion = rowRegion + ..rowType = RowType.dataRow + ..rowData = displayElement + ..dataGridStateDetails = dataGridStateDetails; dr - ..dataGridRow = displayElement ?? + ..dataGridRow = + displayElement ?? grid_helper.getDataGridRow(dataGridConfiguration, rowIndex) ..dataGridRowAdapter = grid_helper.getDataGridRowAdapter( - dataGridConfiguration, dr.dataGridRow!); + dataGridConfiguration, + dr.dataGridRow!, + ); dr.key = dr.dataGridRowAdapter?.key; - assert(grid_helper.debugCheckTheLength( + assert( + grid_helper.debugCheckTheLength( dataGridConfiguration, dataGridConfiguration.columns.length, dr.dataGridRowAdapter!.cells.length, - 'SfDataGrid.columns.length == DataGridRowAdapter.cells.length')); + 'SfDataGrid.columns.length == DataGridRowAdapter.cells.length', + ), + ); _checkForCurrentRow(dr); _checkForSelection(dr); @@ -870,15 +919,18 @@ class RowGenerator { } DataRowBase _createHeaderRow( - int rowIndex, VisibleLinesCollection visibleColumns) { + int rowIndex, + VisibleLinesCollection visibleColumns, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridConfiguration; DataRowBase dr; if (rowIndex == grid_helper.getHeaderIndex(dataGridConfiguration)) { - dr = DataRow() - ..rowIndex = rowIndex - ..rowRegion = RowRegion.header - ..rowType = RowType.headerRow - ..dataGridStateDetails = dataGridStateDetails; + dr = + DataRow() + ..rowIndex = rowIndex + ..rowRegion = RowRegion.header + ..rowType = RowType.headerRow + ..dataGridStateDetails = dataGridStateDetails; dr ..key = ObjectKey(dr) .._initializeDataRow(visibleColumns); @@ -891,11 +943,15 @@ class RowGenerator { dr.rowType = RowType.stackedHeaderRow; dr.dataGridStateDetails = dataGridStateDetails; _createStackedHeaderCell( - dataGridConfiguration.stackedHeaderRows[rowIndex], rowIndex); + dataGridConfiguration.stackedHeaderRows[rowIndex], + rowIndex, + ); dr._initializeDataRow(visibleColumns); return dr; } else if (grid_helper.isTopTableSummaryRow( - dataGridConfiguration, rowIndex)) { + dataGridConfiguration, + rowIndex, + )) { dr = _createTableSummaryRow(rowIndex, GridTableSummaryRowPosition.top); dr ..key = ObjectKey(dr) @@ -904,23 +960,31 @@ class RowGenerator { .._initializeDataRow(visibleColumns); return dr; } else { - return _createDataRow(rowIndex, visibleColumns, - rowRegion: RowRegion.header); + return _createDataRow( + rowIndex, + visibleColumns, + rowRegion: RowRegion.header, + ); } } void _createStackedHeaderCell(StackedHeaderRow header, int rowIndex) { final DataGridConfiguration dataGridConfiguration = _dataGridConfiguration; for (final StackedHeaderCell column in header.cells) { - final List childSequence = - grid_helper.getChildSequence(dataGridConfiguration, column, rowIndex); + final List childSequence = grid_helper.getChildSequence( + dataGridConfiguration, + column, + rowIndex, + ); childSequence.sort(); setChildColumnIndexes(column, childSequence); } } DataRowBase _createFooterRow( - int rowIndex, VisibleLinesCollection visibleColumns) { + int rowIndex, + VisibleLinesCollection visibleColumns, + ) { DataRowBase dr; final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (grid_helper.isBottomTableSummaryRow(dataGridConfiguration, rowIndex)) { @@ -931,14 +995,19 @@ class RowGenerator { ..rowRegion = RowRegion.footer .._initializeDataRow(visibleColumns); } else { - dr = - _createDataRow(rowIndex, visibleColumns, rowRegion: RowRegion.footer); + dr = _createDataRow( + rowIndex, + visibleColumns, + rowRegion: RowRegion.footer, + ); } return dr; } Widget? _buildFooterWidget( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, + ) { if (dataGridConfiguration.footer == null) { return null; } @@ -949,47 +1018,56 @@ class RowGenerator { final GridLinesVisibility gridLinesVisibility = dataGridConfiguration.gridLinesVisibility; - final bool canDrawHorizontalBorder = (gridLinesVisibility == - GridLinesVisibility.horizontal || + final bool canDrawHorizontalBorder = + (gridLinesVisibility == GridLinesVisibility.horizontal || gridLinesVisibility == GridLinesVisibility.both) && grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom) <= + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ) <= 0; final bool canDrawVerticalBorder = gridLinesVisibility == GridLinesVisibility.vertical || - gridLinesVisibility == GridLinesVisibility.both; + gridLinesVisibility == GridLinesVisibility.both; final bool canDrawTopFrozenBorder = dataGridConfiguration.footerFrozenRowsCount.isFinite && - dataGridConfiguration.footerFrozenRowsCount > 0 && - grid_helper.getStartFooterFrozenRowIndex(dataGridConfiguration) == - rowIndex; + dataGridConfiguration.footerFrozenRowsCount > 0 && + grid_helper.getStartFooterFrozenRowIndex(dataGridConfiguration) == + rowIndex; return BoxDecoration( border: BorderDirectional( - top: canDrawTopFrozenBorder && themeData.frozenPaneElevation! <= 0.0 - ? BorderSide( - color: themeData.frozenPaneLineColor!, - width: themeData.frozenPaneLineWidth!) - : BorderSide.none, - bottom: canDrawHorizontalBorder - ? BorderSide( - color: themeData.gridLineColor!, - width: themeData.gridLineStrokeWidth!) - : BorderSide.none, - end: canDrawVerticalBorder - ? BorderSide( - color: themeData.gridLineColor!, - width: themeData.gridLineStrokeWidth!) - : BorderSide.none, + top: + canDrawTopFrozenBorder && themeData.frozenPaneElevation! <= 0.0 + ? BorderSide( + color: themeData.frozenPaneLineColor!, + width: themeData.frozenPaneLineWidth!, + ) + : BorderSide.none, + bottom: + canDrawHorizontalBorder + ? BorderSide( + color: themeData.gridLineColor!, + width: themeData.gridLineStrokeWidth!, + ) + : BorderSide.none, + end: + canDrawVerticalBorder + ? BorderSide( + color: themeData.gridLineColor!, + width: themeData.gridLineStrokeWidth!, + ) + : BorderSide.none, ), ); } return Container( - decoration: drawBorder(), - clipBehavior: Clip.antiAlias, - child: dataGridConfiguration.footer); + decoration: drawBorder(), + clipBehavior: Clip.antiAlias, + child: dataGridConfiguration.footer, + ); } DataRowBase? _indexer(int index) { @@ -1004,46 +1082,70 @@ class RowGenerator { void _updateRow(List rows, int index, RowRegion region) { final DataGridConfiguration dataGridConfiguration = _dataGridConfiguration; - final VisibleLinesCollection visibleColumns = - grid_helper.getVisibleLines(dataGridConfiguration); + final VisibleLinesCollection visibleColumns = grid_helper.getVisibleLines( + dataGridConfiguration, + ); switch (region) { case RowRegion.header: _updateHeaderRow( - rows, index, region, visibleColumns, dataGridConfiguration); + rows, + index, + region, + visibleColumns, + dataGridConfiguration, + ); break; case RowRegion.body: _updateDataRow( - rows, index, region, visibleColumns, dataGridConfiguration); + rows, + index, + region, + visibleColumns, + dataGridConfiguration, + ); break; case RowRegion.footer: _updateFooterRow( - rows, index, region, visibleColumns, dataGridConfiguration); + rows, + index, + region, + visibleColumns, + dataGridConfiguration, + ); break; } } DataRowBase _createTableSummaryRow( - int rowIndex, GridTableSummaryRowPosition position) { + int rowIndex, + GridTableSummaryRowPosition position, + ) { final GridTableSummaryRow? tableSummaryRow = grid_helper.getTableSummaryRow( - _dataGridConfiguration, rowIndex, position); - final _SpannedDataRow spannedDataRow = _SpannedDataRow() - ..rowIndex = rowIndex - ..tableSummaryRow = tableSummaryRow; + _dataGridConfiguration, + rowIndex, + position, + ); + final _SpannedDataRow spannedDataRow = + _SpannedDataRow() + ..rowIndex = rowIndex + ..tableSummaryRow = tableSummaryRow; if (tableSummaryRow != null) { - spannedDataRow.rowType = tableSummaryRow.showSummaryInRow - ? RowType.tableSummaryCoveredRow - : RowType.tableSummaryRow; + spannedDataRow.rowType = + tableSummaryRow.showSummaryInRow + ? RowType.tableSummaryCoveredRow + : RowType.tableSummaryRow; } return spannedDataRow; } void _updateHeaderRow( - List rows, - int index, - RowRegion region, - VisibleLinesCollection visibleColumns, - DataGridConfiguration dataGridConfiguration) { + List rows, + int index, + RowRegion region, + VisibleLinesCollection visibleColumns, + DataGridConfiguration dataGridConfiguration, + ) { DataRowBase? dr; void createHeaderRow() { dr = _createHeaderRow(index, visibleColumns); @@ -1053,7 +1155,8 @@ class RowGenerator { if (index == grid_helper.getHeaderIndex(dataGridConfiguration)) { dr = rows.firstWhereOrNull( - (DataRowBase row) => row.rowType == RowType.headerRow); + (DataRowBase row) => row.rowType == RowType.headerRow, + ); if (dr != null) { dr! ..key = dr!.key @@ -1067,7 +1170,8 @@ class RowGenerator { } } else if (index < dataGridConfiguration.stackedHeaderRows.length) { dr = rows.firstWhereOrNull( - (DataRowBase r) => r.rowType == RowType.stackedHeaderRow); + (DataRowBase r) => r.rowType == RowType.stackedHeaderRow, + ); if (dr != null) { dr! ..key = dr!.key @@ -1076,17 +1180,22 @@ class RowGenerator { ..rowType = RowType.stackedHeaderRow ..rowIndexChanged(); _createStackedHeaderCell( - dataGridConfiguration.stackedHeaderRows[index], index); + dataGridConfiguration.stackedHeaderRows[index], + index, + ); dr!._initializeDataRow( - dataGridConfiguration.container.scrollRows.getVisibleLines()); + dataGridConfiguration.container.scrollRows.getVisibleLines(), + ); } else { createHeaderRow(); } } else if (grid_helper.isTopTableSummaryRow(dataGridConfiguration, index)) { - dr = rows.firstWhereOrNull((DataRowBase r) => - r.rowRegion == region && - (r.rowType == RowType.tableSummaryRow || - r.rowType == RowType.tableSummaryCoveredRow)); + dr = rows.firstWhereOrNull( + (DataRowBase r) => + r.rowRegion == region && + (r.rowType == RowType.tableSummaryRow || + r.rowType == RowType.tableSummaryCoveredRow), + ); if (dr != null) { dr! ..key = dr!.key @@ -1100,13 +1209,15 @@ class RowGenerator { } void _updateDataRow( - List rows, - int index, - RowRegion region, - VisibleLinesCollection visibleColumns, - DataGridConfiguration dataGridConfiguration) { + List rows, + int index, + RowRegion region, + VisibleLinesCollection visibleColumns, + DataGridConfiguration dataGridConfiguration, + ) { DataRowBase? row = rows.firstWhereOrNull( - (DataRowBase row) => row is DataRow && row.rowType == RowType.dataRow); + (DataRowBase row) => row is DataRow && row.rowType == RowType.dataRow, + ); void createDataRow() { row = _createDataRow(index, visibleColumns); items.add(row!); @@ -1114,8 +1225,9 @@ class RowGenerator { } if (grid_helper.isFooterWidgetRow(index, dataGridConfiguration)) { - row = rows - .firstWhereOrNull((DataRowBase r) => r.rowType == RowType.footerRow); + row = rows.firstWhereOrNull( + (DataRowBase r) => r.rowType == RowType.footerRow, + ); if (row != null) { row! ..key = row!.key @@ -1133,34 +1245,47 @@ class RowGenerator { dynamic displayElement; if (dataGridConfiguration.source.groupedColumns.isNotEmpty && index >= 0) { - final int rowIndex = - resolveStartRecordIndex(dataGridConfiguration, index); - displayElement = (index >= 0) - ? getGroupElement(dataGridConfiguration, rowIndex) - : null; + final int rowIndex = resolveStartRecordIndex( + dataGridConfiguration, + index, + ); + displayElement = + (index >= 0) + ? getGroupElement(dataGridConfiguration, rowIndex) + : null; } else { displayElement = null; } if (displayElement == null || displayElement is DataGridRow) { - if (rows.any((DataRowBase row) => - row is DataRow && row.rowType == RowType.dataRow)) { - final DataRowBase? row = rows.firstWhereOrNull((DataRowBase row) => - row is DataRow && row.rowType == RowType.dataRow); + if (rows.any( + (DataRowBase row) => + row is DataRow && row.rowType == RowType.dataRow, + )) { + final DataRowBase? row = rows.firstWhereOrNull( + (DataRowBase row) => + row is DataRow && row.rowType == RowType.dataRow, + ); row! ..key = row.key ..rowIndex = index ..rowRegion = region ..rowData = displayElement - ..dataGridRow = displayElement ?? + ..dataGridRow = + displayElement ?? grid_helper.getDataGridRow(dataGridConfiguration, index) ..dataGridRowAdapter = grid_helper.getDataGridRowAdapter( - dataGridConfiguration, row.dataGridRow!); - assert(grid_helper.debugCheckTheLength( + dataGridConfiguration, + row.dataGridRow!, + ); + assert( + grid_helper.debugCheckTheLength( dataGridConfiguration, dataGridConfiguration.columns.length, row.dataGridRowAdapter!.cells.length, - 'SfDataGrid.columns.length == DataGridRowAdapter.cells.length')); + 'SfDataGrid.columns.length == DataGridRowAdapter.cells.length', + ), + ); _checkForCurrentRow(row); _checkForSelection(row); row.rowIndexChanged(); @@ -1168,13 +1293,17 @@ class RowGenerator { createDataRow(); } } else { - if (rows.any((DataRowBase row) => - row is _SpannedDataRow && - row.rowType == RowType.captionSummaryCoveredRow)) { - final _SpannedDataRow spanDataRow = rows.firstWhereOrNull( - (DataRowBase row) => - row.rowType == RowType.captionSummaryCoveredRow)! - as _SpannedDataRow; + if (rows.any( + (DataRowBase row) => + row is _SpannedDataRow && + row.rowType == RowType.captionSummaryCoveredRow, + )) { + final _SpannedDataRow spanDataRow = + rows.firstWhereOrNull( + (DataRowBase row) => + row.rowType == RowType.captionSummaryCoveredRow, + )! + as _SpannedDataRow; final dynamic rowData = spanDataRow.rowData; spanDataRow ..key = ObjectKey(spanDataRow) @@ -1186,11 +1315,12 @@ class RowGenerator { ..dataGridStateDetails = dataGridStateDetails ..rowIndexChanged(); final int columnSpan = grid_helper.getSummaryColumnSpan( - dataGridConfiguration, - 0, - spanDataRow.rowType, - null, - spanDataRow.rowLevel); + dataGridConfiguration, + 0, + spanDataRow.rowType, + null, + spanDataRow.rowLevel, + ); _updataSpannedRow(spanDataRow, displayElement, columnSpan); if (rowData.level > displayElement.level) { for (int i = displayElement.level; i < rowData.level; i++) { @@ -1221,17 +1351,20 @@ class RowGenerator { } void _updateFooterRow( - List rows, - int index, - RowRegion region, - VisibleLinesCollection visibleColumns, - DataGridConfiguration dataGridConfiguration) { + List rows, + int index, + RowRegion region, + VisibleLinesCollection visibleColumns, + DataGridConfiguration dataGridConfiguration, + ) { DataRowBase? dr; if (grid_helper.isBottomTableSummaryRow(dataGridConfiguration, index)) { - dr = rows.firstWhereOrNull((DataRowBase r) => - r.rowRegion == region && - (r.rowType == RowType.tableSummaryRow || - r.rowType == RowType.tableSummaryCoveredRow)); + dr = rows.firstWhereOrNull( + (DataRowBase r) => + r.rowRegion == region && + (r.rowType == RowType.tableSummaryRow || + r.rowType == RowType.tableSummaryCoveredRow), + ); if (dr != null) { dr ..key = dr.key @@ -1245,7 +1378,12 @@ class RowGenerator { } } else { _updateDataRow( - rows, index, region, visibleColumns, dataGridConfiguration); + rows, + index, + region, + visibleColumns, + dataGridConfiguration, + ); } } @@ -1256,7 +1394,9 @@ class RowGenerator { if (dataGridConfiguration.onQueryRowHeight != null) { final RowHeightDetails details = RowHeightDetails(rowIndex, height); setColumnSizerInRowHeightDetailsArgs( - details, dataGridConfiguration.columnSizer); + details, + dataGridConfiguration.columnSizer, + ); rowHeight = dataGridConfiguration.onQueryRowHeight!(details); } @@ -1268,21 +1408,29 @@ class RowGenerator { if (dataGridConfiguration.selectionMode != SelectionMode.none) { final DataGridRow record; if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - final int rowIndex = - resolveStartRecordIndex(dataGridConfiguration, row.rowIndex); - final dynamic element = - getGroupElement(dataGridConfiguration, rowIndex); + final int rowIndex = resolveStartRecordIndex( + dataGridConfiguration, + row.rowIndex, + ); + final dynamic element = getGroupElement( + dataGridConfiguration, + rowIndex, + ); if (element is! DataGridRow) { return; } record = element; } else { final int recordIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, row.rowIndex); + dataGridConfiguration, + row.rowIndex, + ); record = effectiveRows(dataGridConfiguration.source)[recordIndex]; } - row._isSelectedRow = - selection_manager.isSelectedRow(dataGridConfiguration, record); + row._isSelectedRow = selection_manager.isSelectedRow( + dataGridConfiguration, + record, + ); } } @@ -1298,8 +1446,9 @@ class RowGenerator { } final DataCellBase? dc = dr.visibleColumns.firstWhereOrNull( - (DataCellBase dataCell) => - dataCell.columnIndex == currentCellManager.columnIndex); + (DataCellBase dataCell) => + dataCell.columnIndex == currentCellManager.columnIndex, + ); return dc; } @@ -1342,26 +1491,37 @@ class _SpannedDataRow extends DataRow { } if (!_isEnsuredSpannedCell(i)) { final int columnSpan = grid_helper.getSummaryColumnSpan( - dataGridConfiguration, i, rowType, tableSummaryRow); + dataGridConfiguration, + i, + rowType, + tableSummaryRow, + ); dc = _createSpannedColumn(i, columnSpan, null); visibleColumns.add(dc); } } } else { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - for (int i = 0; - i < dataGridConfiguration.source.groupedColumns.length; - i++) { + for ( + int i = 0; + i < dataGridConfiguration.source.groupedColumns.length; + i++ + ) { final DataCellBase dr = _createIndentColumns(i); visibleColumns.add(dr); } } final int columnSpan = grid_helper.getSummaryColumnSpan( - dataGridConfiguration, 0, rowType, tableSummaryRow); + dataGridConfiguration, + 0, + rowType, + tableSummaryRow, + ); dc = _createSpannedColumn( - dataGridConfiguration.source.groupedColumns.length, - columnSpan, - null); + dataGridConfiguration.source.groupedColumns.length, + columnSpan, + null, + ); visibleColumns.add(dc); } } else if (rowType == RowType.stackedHeaderRow) { @@ -1370,19 +1530,24 @@ class _SpannedDataRow extends DataRow { final List stackedColumns = dataGridConfiguration.stackedHeaderRows[rowIndex].cells; if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - for (int i = 0; - i < dataGridConfiguration.source.groupedColumns.length; - i++) { + for ( + int i = 0; + i < dataGridConfiguration.source.groupedColumns.length; + i++ + ) { final DataCellBase dr = _createIndentColumns(i); visibleColumns.add(dr); } } for (final StackedHeaderCell column in stackedColumns) { - final List> columnsSequence = - grid_helper.getConsecutiveRanges(getChildColumnIndexes(column)); + final List> columnsSequence = grid_helper + .getConsecutiveRanges(getChildColumnIndexes(column)); for (final List columns in columnsSequence) { dc = _createSpannedColumn( - columns.reduce(min), columns.length - 1, column); + columns.reduce(min), + columns.length - 1, + column, + ); visibleColumns.add(dc); } } @@ -1390,7 +1555,12 @@ class _SpannedDataRow extends DataRow { } } else if (rowType == RowType.captionSummaryCoveredRow) { final int columnSpan = grid_helper.getSummaryColumnSpan( - dataGridConfiguration, 0, rowType, null, rowLevel); + dataGridConfiguration, + 0, + rowType, + null, + rowLevel, + ); for (int i = 0; i < rowLevel; i++) { final DataCellBase dr = _createIndentColumns(i); visibleColumns.add(dr); @@ -1400,24 +1570,40 @@ class _SpannedDataRow extends DataRow { } } - int _getRowSpan(int columnIndex, StackedHeaderCell? stackedHeaderCell, - String mappingName) { + int _getRowSpan( + int columnIndex, + StackedHeaderCell? stackedHeaderCell, + String mappingName, + ) { int rowSpan = 0; final DataGridConfiguration dataGridConfiguration = dataGridStateDetails!(); if (rowType == RowType.stackedHeaderRow) { rowSpan = grid_helper.getRowSpan( - dataGridConfiguration, rowIndex, columnIndex, true, - stackedHeaderCell: stackedHeaderCell); + dataGridConfiguration, + rowIndex, + columnIndex, + true, + stackedHeaderCell: stackedHeaderCell, + ); } else if (rowType == RowType.headerRow) { rowSpan = grid_helper.getRowSpan( - dataGridConfiguration, rowIndex - 1, columnIndex, false, - mappingName: mappingName); + dataGridConfiguration, + rowIndex - 1, + columnIndex, + false, + mappingName: mappingName, + ); } return rowSpan; } - _SpannedDataColumn _createSpannedCell(_SpannedDataColumn dc, int columnIndex, - int columnSpan, int rowSpan, GridColumn? gridColumn) { + _SpannedDataColumn _createSpannedCell( + _SpannedDataColumn dc, + int columnIndex, + int columnSpan, + int rowSpan, + GridColumn? gridColumn, + ) { dc ..dataRow = this ..columnIndex = columnIndex @@ -1432,18 +1618,25 @@ class _SpannedDataRow extends DataRow { } _SpannedDataColumn _createSpannedColumn( - int index, int columnSpan, StackedHeaderCell? stackedHeaderCell) { + int index, + int columnSpan, + StackedHeaderCell? stackedHeaderCell, + ) { _SpannedDataColumn dc = _SpannedDataColumn(); final DataGridConfiguration dataGridConfiguration = dataGridStateDetails!(); if (index >= grid_helper.resolveToStartColumnIndex(dataGridConfiguration)) { - int startColumnIndex = - grid_helper.resolveToScrollColumnIndex(dataGridConfiguration, index); + int startColumnIndex = grid_helper.resolveToScrollColumnIndex( + dataGridConfiguration, + index, + ); if (dataGridConfiguration.source.groupedColumns.isNotEmpty && (rowType == RowType.tableSummaryRow || rowType == RowType.tableSummaryCoveredRow)) { - startColumnIndex = - resolveToGridVisibleColumnIndex(dataGridConfiguration, index); + startColumnIndex = resolveToGridVisibleColumnIndex( + dataGridConfiguration, + index, + ); } final int indentColumnCount = @@ -1454,10 +1647,18 @@ class _SpannedDataRow extends DataRow { } final GridColumn gridColumn = dataGridConfiguration.columns[startColumnIndex]; - final int rowSpan = - _getRowSpan(index, stackedHeaderCell, gridColumn.columnName); + final int rowSpan = _getRowSpan( + index, + stackedHeaderCell, + gridColumn.columnName, + ); dc = _createSpannedCell( - dc, index + indentColumnCount, columnSpan, rowSpan, gridColumn); + dc, + index + indentColumnCount, + columnSpan, + rowSpan, + gridColumn, + ); dc ..renderer = dataGridConfiguration.cellRenderers['StackedHeader'] ..stackedHeaderCell = stackedHeaderCell @@ -1466,8 +1667,11 @@ class _SpannedDataRow extends DataRow { rowType == RowType.tableSummaryCoveredRow) { final GridColumn gridColumn = dataGridConfiguration.columns[startColumnIndex]; - final int rowSpan = - _getRowSpan(index, stackedHeaderCell, gridColumn.columnName); + final int rowSpan = _getRowSpan( + index, + stackedHeaderCell, + gridColumn.columnName, + ); dc = _createSpannedCell(dc, index, columnSpan, rowSpan, gridColumn); dc ..renderer = dataGridConfiguration.cellRenderers['TableSummary'] @@ -1477,11 +1681,14 @@ class _SpannedDataRow extends DataRow { if (tableSummaryRow != null && tableSummaryRow!.columns.isNotEmpty) { if (rowType == RowType.tableSummaryRow) { final int titleColumnSpan = grid_helper.getSummaryTitleColumnSpan( - dataGridConfiguration, tableSummaryRow!); + dataGridConfiguration, + tableSummaryRow!, + ); if (dc.columnIndex >= titleColumnSpan) { dc.summaryColumn = tableSummaryRow!.columns.firstWhereOrNull( - (GridSummaryColumn element) => - element.columnName == gridColumn.columnName); + (GridSummaryColumn element) => + element.columnName == gridColumn.columnName, + ); } } } @@ -1500,25 +1707,35 @@ class _SpannedDataRow extends DataRow { return dc; } - void _ensureSpannedColumn( - {required int columnIndex, - required int columnSpan, - StackedHeaderCell? stackedHeaderCell}) { + void _ensureSpannedColumn({ + required int columnIndex, + required int columnSpan, + StackedHeaderCell? stackedHeaderCell, + }) { DataCellBase? dc = _indexer(columnIndex); if (dc == null) { - DataCellBase? dataCell = - _reUseCell(columnIndex, columnIndex + columnSpan); - dataCell ??= visibleColumns.firstWhereOrNull((DataCellBase col) => - col.columnIndex == -1 && col.cellType != CellType.indentCell); + DataCellBase? dataCell = _reUseCell( + columnIndex, + columnIndex + columnSpan, + ); + dataCell ??= visibleColumns.firstWhereOrNull( + (DataCellBase col) => + col.columnIndex == -1 && col.cellType != CellType.indentCell, + ); _updateSpannedColumn( - dataCell, columnIndex, columnSpan, stackedHeaderCell); + dataCell, + columnIndex, + columnSpan, + stackedHeaderCell, + ); dataCell = null; } - dc ??= visibleColumns - .firstWhereOrNull((DataCellBase col) => col.columnIndex == columnIndex); + dc ??= visibleColumns.firstWhereOrNull( + (DataCellBase col) => col.columnIndex == columnIndex, + ); if (dc != null) { if (!dc.isVisible) { @@ -1545,21 +1762,24 @@ class _SpannedDataRow extends DataRow { final StackedHeaderRow stackedHeaderRow = dataGridConfiguration.stackedHeaderRows[rowIndex]; final List stackedColumns = stackedHeaderRow.cells; - dataGridConfiguration.rowGenerator - ._createStackedHeaderCell(stackedHeaderRow, rowIndex); + dataGridConfiguration.rowGenerator._createStackedHeaderCell( + stackedHeaderRow, + rowIndex, + ); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { ensureIndentCell(visibleColumnLines); } for (final StackedHeaderCell column in stackedColumns) { - final List> columnsSequence = - grid_helper.getConsecutiveRanges(getChildColumnIndexes(column)); + final List> columnsSequence = grid_helper + .getConsecutiveRanges(getChildColumnIndexes(column)); for (final List columns in columnsSequence) { final int columnIndex = columns.reduce(min); final int columnSpan = columns.length - 1; _ensureSpannedColumn( - columnSpan: columnSpan, - columnIndex: columnIndex, - stackedHeaderCell: column); + columnSpan: columnSpan, + columnIndex: columnIndex, + stackedHeaderCell: column, + ); } } } else { @@ -1571,9 +1791,11 @@ class _SpannedDataRow extends DataRow { final List startAndEndIndex = dataGridConfiguration.container .getStartEndIndex(visibleColumnLines, i); - for (int index = startAndEndIndex[0]; - index <= startAndEndIndex[1]; - index++) { + for ( + int index = startAndEndIndex[0]; + index <= startAndEndIndex[1]; + index++ + ) { if (!_isEnsuredSpannedCell(index)) { if (dataGridConfiguration.source.groupedColumns.isNotEmpty && (rowType == RowType.tableSummaryRow || @@ -1581,11 +1803,19 @@ class _SpannedDataRow extends DataRow { index >= dataGridConfiguration.source.groupedColumns.length) { ensureIndentCell(visibleColumnLines); final int columnSpan = grid_helper.getSummaryColumnSpan( - dataGridConfiguration, index, rowType, tableSummaryRow); + dataGridConfiguration, + index, + rowType, + tableSummaryRow, + ); _ensureSpannedColumn(columnIndex: index, columnSpan: columnSpan); } else { final int columnSpan = grid_helper.getSummaryColumnSpan( - dataGridConfiguration, index, rowType, tableSummaryRow); + dataGridConfiguration, + index, + rowType, + tableSummaryRow, + ); _ensureSpannedColumn(columnIndex: index, columnSpan: columnSpan); } } @@ -1603,15 +1833,17 @@ class _SpannedDataRow extends DataRow { void ensureIndentCell(VisibleLinesCollection visibleColumnLines) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails!(); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - final int length = (rowType == RowType.stackedHeaderRow || - rowType == RowType.tableSummaryRow || - rowType == RowType.tableSummaryCoveredRow) - ? dataGridConfiguration.source.groupedColumns.length - : rowLevel; + final int length = + (rowType == RowType.stackedHeaderRow || + rowType == RowType.tableSummaryRow || + rowType == RowType.tableSummaryCoveredRow) + ? dataGridConfiguration.source.groupedColumns.length + : rowLevel; for (int i = 0; i < length; i++) { if (i < length) { final DataCellBase? ic = visibleColumns.firstWhereOrNull( - (DataCellBase column) => column.columnIndex == i); + (DataCellBase column) => column.columnIndex == i, + ); if (ic != null) { if (!ic.isVisible) { ic.isVisible = true; @@ -1625,31 +1857,45 @@ class _SpannedDataRow extends DataRow { } continue; } - visibleColumns - .removeWhere((DataCellBase column) => column.columnIndex < 0); - visibleColumns.sort((DataCellBase a, DataCellBase b) => - a.columnIndex.compareTo(b.columnIndex)); + visibleColumns.removeWhere( + (DataCellBase column) => column.columnIndex < 0, + ); + visibleColumns.sort( + (DataCellBase a, DataCellBase b) => + a.columnIndex.compareTo(b.columnIndex), + ); } } - void _updateSpannedColumn(DataCellBase? dc, int index, int columnSpan, - StackedHeaderCell? stackedHeaderCell) { + void _updateSpannedColumn( + DataCellBase? dc, + int index, + int columnSpan, + StackedHeaderCell? stackedHeaderCell, + ) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails!(); if (dc != null) { if (index < 0 || index >= dataGridConfiguration.container.columnCount) { dc.isVisible = false; } else { int columnIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, index); + dataGridConfiguration, + index, + ); if (dataGridConfiguration.source.groupedColumns.isNotEmpty && (rowType == RowType.tableSummaryRow)) { - columnIndex = - resolveToGridVisibleColumnIndex(dataGridConfiguration, index); + columnIndex = resolveToGridVisibleColumnIndex( + dataGridConfiguration, + index, + ); } final GridColumn gridColumn = dataGridConfiguration.columns[columnIndex]; - final int rowSpan = - _getRowSpan(index, stackedHeaderCell, gridColumn.columnName); + final int rowSpan = _getRowSpan( + index, + stackedHeaderCell, + gridColumn.columnName, + ); dc ..columnIndex = index @@ -1687,10 +1933,12 @@ class _SpannedDataRow extends DataRow { } bool _isEnsuredSpannedCell(int index) { - return visibleColumns.any((DataCellBase cell) => - cell.isEnsured && - (index >= cell.columnIndex && - index <= cell.columnIndex + cell.columnSpan)); + return visibleColumns.any( + (DataCellBase cell) => + cell.isEnsured && + (index >= cell.columnIndex && + index <= cell.columnIndex + cell.columnSpan), + ); } } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/selection/selection_manager.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/selection/selection_manager.dart index 3b57e780d..53a8bceed 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/selection/selection_manager.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/selection/selection_manager.dart @@ -103,9 +103,13 @@ class RowSelectionManager extends SelectionManagerBase { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); final int recordIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, rowColumnIndex.rowIndex); - DataGridRow? record = - selection_helper.getRecord(dataGridConfiguration, recordIndex); + dataGridConfiguration, + rowColumnIndex.rowIndex, + ); + DataGridRow? record = selection_helper.getRecord( + dataGridConfiguration, + recordIndex, + ); final List addedItems = []; final List removeItems = []; @@ -123,11 +127,16 @@ class RowSelectionManager extends SelectionManagerBase { } if (_raiseSelectionChanging( - newItems: addedItems, oldItems: removeItems)) { + newItems: addedItems, + oldItems: removeItems, + )) { _clearSelectedRow(dataGridConfiguration); _addSelection(record, dataGridConfiguration); _raiseCheckboxValueChanged( - value: true, row: record, rowType: RowType.dataRow); + value: true, + row: record, + rowType: RowType.dataRow, + ); notifyListeners(); _raiseSelectionChanged(newItems: addedItems, oldItems: removeItems); } @@ -151,19 +160,27 @@ class RowSelectionManager extends SelectionManagerBase { } if (_raiseSelectionChanging( - newItems: addedItems, oldItems: removeItems)) { + newItems: addedItems, + oldItems: removeItems, + )) { if (record != null && !_selectedRows.contains(record)) { _clearSelectedRow(dataGridConfiguration); _addSelection(record, dataGridConfiguration); _raiseCheckboxValueChanged( - value: true, row: record, rowType: RowType.dataRow); + value: true, + row: record, + rowType: RowType.dataRow, + ); } else { _clearSelectedRow(dataGridConfiguration); if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { _clearCurrentCell(dataGridConfiguration); } _raiseCheckboxValueChanged( - value: false, row: record, rowType: RowType.dataRow); + value: false, + row: record, + rowType: RowType.dataRow, + ); } notifyListeners(); @@ -188,16 +205,24 @@ class RowSelectionManager extends SelectionManagerBase { } if (_raiseSelectionChanging( - newItems: addedItems, oldItems: removeItems) && + newItems: addedItems, + oldItems: removeItems, + ) && record != null) { if (!_selectedRows.contains(record)) { _addSelection(record, dataGridConfiguration); _raiseCheckboxValueChanged( - value: true, row: record, rowType: RowType.dataRow); + value: true, + row: record, + rowType: RowType.dataRow, + ); } else { _removeSelection(record, dataGridConfiguration); _raiseCheckboxValueChanged( - value: false, row: record, rowType: RowType.dataRow); + value: false, + row: record, + rowType: RowType.dataRow, + ); } notifyListeners(); _raiseSelectionChanged(newItems: addedItems, oldItems: removeItems); @@ -214,7 +239,10 @@ class RowSelectionManager extends SelectionManagerBase { /// Check whether the index is outside the shift selected rows range. bool isIndexOutsideRange( - int pressedRowIndex, int currentRecordIndex, int index) { + int pressedRowIndex, + int currentRecordIndex, + int index, + ) { if (pressedRowIndex < currentRecordIndex) { return index < pressedRowIndex || index > currentRecordIndex; } else { @@ -223,42 +251,62 @@ class RowSelectionManager extends SelectionManagerBase { } void _processShiftKeySelection( - RowColumnIndex rowColumnIndex, int currentRecordIndex) { + RowColumnIndex rowColumnIndex, + int currentRecordIndex, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); List addedItems = []; List removedItems = []; removedItems = _shiftSelectedRows.toList(); - for (final DataGridRow selectedRow - in List.from(_selectedRows)) { - final int selectedIndex = - dataGridConfiguration.source.effectiveRows.indexOf(selectedRow); + for (final DataGridRow selectedRow in List.from( + _selectedRows, + )) { + final int selectedIndex = dataGridConfiguration.source.effectiveRows + .indexOf(selectedRow); if (isIndexOutsideRange( - _pressedRowIndex, currentRecordIndex, selectedIndex)) { + _pressedRowIndex, + currentRecordIndex, + selectedIndex, + )) { _removeSelection(selectedRow, dataGridConfiguration); _raiseCheckboxValueChanged( - value: false, row: selectedRow, rowType: RowType.dataRow); + value: false, + row: selectedRow, + rowType: RowType.dataRow, + ); } } if (dataGridConfiguration.onSelectionChanging != null || dataGridConfiguration.onSelectionChanged != null) { addedItems = _getAddedItems( - _pressedRowIndex, currentRecordIndex, dataGridConfiguration); - final List commonItemsList = addedItems - .toSet() - .where((DataGridRow record) => removedItems.toSet().contains(record)) - .toList(); - addedItems = addedItems - .toSet() - .where( - (DataGridRow record) => !_selectedRows.toSet().contains(record)) - .toList(); - removedItems = removedItems - .toSet() - .where( - (DataGridRow record) => !commonItemsList.toSet().contains(record)) - .toList(); + _pressedRowIndex, + currentRecordIndex, + dataGridConfiguration, + ); + final List commonItemsList = + addedItems + .toSet() + .where( + (DataGridRow record) => removedItems.toSet().contains(record), + ) + .toList(); + addedItems = + addedItems + .toSet() + .where( + (DataGridRow record) => !_selectedRows.toSet().contains(record), + ) + .toList(); + removedItems = + removedItems + .toSet() + .where( + (DataGridRow record) => + !commonItemsList.toSet().contains(record), + ) + .toList(); } if (_raiseSelectionChanging(newItems: addedItems, oldItems: removedItems)) { _addSelectionForShiftKey(currentRecordIndex, removedItems); @@ -268,16 +316,23 @@ class RowSelectionManager extends SelectionManagerBase { } void _addSelectionForShiftKey( - int currentRecordIndex, List removedItems) { + int currentRecordIndex, + List removedItems, + ) { late DataGridRow? record; final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); - final DataGridRow? pressedRecord = - selection_helper.getRecord(dataGridConfiguration, _pressedRowIndex); + final DataGridRow? pressedRecord = selection_helper.getRecord( + dataGridConfiguration, + _pressedRowIndex, + ); if (!_selectedRows.contains(pressedRecord)) { _addSelection(pressedRecord, dataGridConfiguration); _raiseCheckboxValueChanged( - value: true, row: pressedRecord, rowType: RowType.dataRow); + value: true, + row: pressedRecord, + rowType: RowType.dataRow, + ); } if (removedItems.isNotEmpty) { @@ -285,40 +340,56 @@ class RowSelectionManager extends SelectionManagerBase { if (_selectedRows.contains(items)) { _removeSelection(items, dataGridConfiguration); _raiseCheckboxValueChanged( - value: false, row: items, rowType: RowType.dataRow); + value: false, + row: items, + rowType: RowType.dataRow, + ); } } } if (_pressedRowIndex < currentRecordIndex) { - for (int rowIndex = _pressedRowIndex + 1; - rowIndex <= currentRecordIndex; - rowIndex++) { + for ( + int rowIndex = _pressedRowIndex + 1; + rowIndex <= currentRecordIndex; + rowIndex++ + ) { record = selection_helper.getRecord(dataGridConfiguration, rowIndex); if (record != null) { _shiftSelectedRows.add(record); _addSelection(record, dataGridConfiguration); _raiseCheckboxValueChanged( - value: true, row: record, rowType: RowType.dataRow); + value: true, + row: record, + rowType: RowType.dataRow, + ); } } } else if (_pressedRowIndex > currentRecordIndex) { - for (int rowIndex = _pressedRowIndex - 1; - rowIndex >= currentRecordIndex; - rowIndex--) { + for ( + int rowIndex = _pressedRowIndex - 1; + rowIndex >= currentRecordIndex; + rowIndex-- + ) { record = selection_helper.getRecord(dataGridConfiguration, rowIndex); if (record != null) { _shiftSelectedRows.add(record); _addSelection(record, dataGridConfiguration); _raiseCheckboxValueChanged( - value: true, row: record, rowType: RowType.dataRow); + value: true, + row: record, + rowType: RowType.dataRow, + ); } } } } List _getAddedItems( - int startIndex, int endIndex, DataGridConfiguration configuration) { + int startIndex, + int endIndex, + DataGridConfiguration configuration, + ) { final List addedItems = []; if (startIndex > endIndex) { final int tempIndex = startIndex; @@ -332,10 +403,14 @@ class RowSelectionManager extends SelectionManagerBase { } void _addSelection( - DataGridRow? record, DataGridConfiguration dataGridConfiguration) { + DataGridRow? record, + DataGridConfiguration dataGridConfiguration, + ) { if (record != null && !_selectedRows.contains(record)) { - final int rowIndex = - selection_helper.resolveToRowIndex(dataGridConfiguration, record); + final int rowIndex = selection_helper.resolveToRowIndex( + dataGridConfiguration, + record, + ); if (!_selectedRows.contains(record)) { _selectedRows.add(record); dataGridConfiguration.controller.selectedRows.add(record); @@ -349,10 +424,14 @@ class RowSelectionManager extends SelectionManagerBase { } void _removeSelection( - DataGridRow? record, DataGridConfiguration dataGridConfiguration) { + DataGridRow? record, + DataGridConfiguration dataGridConfiguration, + ) { if (record != null && _selectedRows.contains(record)) { - final int rowIndex = - selection_helper.resolveToRowIndex(dataGridConfiguration, record); + final int rowIndex = selection_helper.resolveToRowIndex( + dataGridConfiguration, + record, + ); _selectedRows.remove(record); dataGridConfiguration.controller.selectedRows.remove(record); _refreshSelection(); @@ -373,7 +452,8 @@ class RowSelectionManager extends SelectionManagerBase { void _clearSelectedRows(DataGridConfiguration dataGridConfiguration) { if (_selectedRows.isNotEmpty) { _selectedRows.removeWhere( - (row) => dataGridConfiguration.source.effectiveRows.contains(row)); + (row) => dataGridConfiguration.source.effectiveRows.contains(row), + ); dataGridConfiguration.controller.selectedRows.clear(); _refreshSelection(); dataGridConfiguration.container.isDirty = true; @@ -390,8 +470,11 @@ class RowSelectionManager extends SelectionManagerBase { _clearSelection(dataGridConfiguration); } - void _setRowSelection(int rowIndex, - DataGridConfiguration dataGridConfiguration, bool isRowSelected) { + void _setRowSelection( + int rowIndex, + DataGridConfiguration dataGridConfiguration, + bool isRowSelected, + ) { if (dataGridConfiguration.rowGenerator.items.isEmpty) { return; } @@ -402,7 +485,9 @@ class RowSelectionManager extends SelectionManagerBase { row ..isDirty = true ..dataGridRowAdapter = grid_helper.getDataGridRowAdapter( - dataGridConfiguration, row.dataGridRow!) + dataGridConfiguration, + row.dataGridRow!, + ) ..isSelectedRow = isRowSelected; } @@ -411,7 +496,8 @@ class RowSelectionManager extends SelectionManagerBase { void _clearSelection(DataGridConfiguration dataGridConfiguration) { _selectedRows.removeWhere( - (row) => dataGridConfiguration.source.effectiveRows.contains(row)); + (row) => dataGridConfiguration.source.effectiveRows.contains(row), + ); dataGridConfiguration.controller.selectedRows.clear(); updateSelectedRow(dataGridConfiguration.controller, null); updateSelectedIndex(dataGridConfiguration.controller, -1); @@ -435,21 +521,27 @@ class RowSelectionManager extends SelectionManagerBase { final DataGridRow? selectedRow = _selectedRows.reversed.firstWhereOrNull( (row) => effectiveRows(dataGridConfiguration.source).contains(row), ); - final int recordIndex = selectedRow == null - ? -1 - : dataGridConfiguration.source.groupedColumns.isNotEmpty - ? dataGridConfiguration.group!.displayElements!.grouped - .indexOf(selectedRow) + final int recordIndex = + selectedRow == null + ? -1 + : dataGridConfiguration.source.groupedColumns.isNotEmpty + ? dataGridConfiguration.group!.displayElements!.grouped.indexOf( + selectedRow, + ) : effectiveRows(dataGridConfiguration.source).indexOf(selectedRow); updateSelectedRow(dataGridConfiguration.controller, selectedRow); updateSelectedIndex(dataGridConfiguration.controller, recordIndex); } void _addCurrentCell( - DataGridRow record, DataGridConfiguration dataGridConfiguration, - {bool isSelectionChanging = false}) { - final int rowIndex = - selection_helper.resolveToRowIndex(dataGridConfiguration, record); + DataGridRow record, + DataGridConfiguration dataGridConfiguration, { + bool isSelectionChanging = false, + }) { + final int rowIndex = selection_helper.resolveToRowIndex( + dataGridConfiguration, + record, + ); if (rowIndex <= grid_helper.getHeaderIndex(dataGridConfiguration)) { return; @@ -457,17 +549,19 @@ class RowSelectionManager extends SelectionManagerBase { if (dataGridConfiguration.currentCell.columnIndex > 0) { dataGridConfiguration.currentCell._moveCurrentCellTo( - dataGridConfiguration, - RowColumnIndex( - rowIndex, dataGridConfiguration.currentCell.columnIndex), - isSelectionChanged: isSelectionChanging); + dataGridConfiguration, + RowColumnIndex(rowIndex, dataGridConfiguration.currentCell.columnIndex), + isSelectionChanged: isSelectionChanging, + ); } else { - final int firstVisibleColumnIndex = - grid_helper.resolveToStartColumnIndex(dataGridConfiguration); + final int firstVisibleColumnIndex = grid_helper.resolveToStartColumnIndex( + dataGridConfiguration, + ); dataGridConfiguration.currentCell._moveCurrentCellTo( - dataGridConfiguration, - RowColumnIndex(rowIndex, firstVisibleColumnIndex), - isSelectionChanged: isSelectionChanging); + dataGridConfiguration, + RowColumnIndex(rowIndex, firstVisibleColumnIndex), + isSelectionChanged: isSelectionChanging, + ); } } @@ -476,12 +570,14 @@ class RowSelectionManager extends SelectionManagerBase { _dataGridStateDetails!(); if (dataGridConfiguration.navigationMode == GridNavigationMode.row) { final RowColumnIndex currentRowColumnIndex = RowColumnIndex( - dataGridConfiguration.currentCell.rowIndex, - dataGridConfiguration.currentCell.columnIndex); + dataGridConfiguration.currentCell.rowIndex, + dataGridConfiguration.currentCell.columnIndex, + ); _clearCurrentCell(dataGridConfiguration); dataGridConfiguration.currentCell._updateBorderForMultipleSelection( - dataGridConfiguration, - nextRowColumnIndex: currentRowColumnIndex); + dataGridConfiguration, + nextRowColumnIndex: currentRowColumnIndex, + ); } else { if (dataGridConfiguration.selectionMode != SelectionMode.none) { final DataGridRow? lastRecord = @@ -512,26 +608,34 @@ class RowSelectionManager extends SelectionManagerBase { ); } else { currentCell._moveCurrentCellTo( - dataGridConfiguration, - RowColumnIndex(currentRowColumnIndex.rowIndex, - currentRowColumnIndex.columnIndex), - isSelectionChanged: true); + dataGridConfiguration, + RowColumnIndex( + currentRowColumnIndex.rowIndex, + currentRowColumnIndex.columnIndex, + ), + isSelectionChanged: true, + ); } } } } RowColumnIndex _getRowColumnIndexOnModeChanged( - DataGridConfiguration dataGridConfiguration, DataGridRow? lastRecord) { + DataGridConfiguration dataGridConfiguration, + DataGridRow? lastRecord, + ) { final int rowIndex = lastRecord == null && _pressedRowColumnIndex.rowIndex > 0 ? _pressedRowColumnIndex.rowIndex : selection_helper.resolveToRowIndex( - dataGridConfiguration, lastRecord!); + dataGridConfiguration, + lastRecord!, + ); - final int columnIndex = _pressedRowColumnIndex.columnIndex != -1 - ? _pressedRowColumnIndex.columnIndex - : grid_helper.resolveToStartColumnIndex(dataGridConfiguration); + final int columnIndex = + _pressedRowColumnIndex.columnIndex != -1 + ? _pressedRowColumnIndex.columnIndex + : grid_helper.resolveToStartColumnIndex(dataGridConfiguration); return RowColumnIndex(rowIndex, columnIndex); } @@ -544,7 +648,8 @@ class RowSelectionManager extends SelectionManagerBase { /// When the selection is applied to a row, we should update the state of the check box also. void _updateCheckboxStateOnHeader( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, + ) { if (!dataGridConfiguration.showCheckboxColumn || !dataGridConfiguration.checkboxColumnSettings.showCheckboxOnHeader || dataGridConfiguration.selectionMode == SelectionMode.none) { @@ -553,10 +658,12 @@ class RowSelectionManager extends SelectionManagerBase { final DataRowBase? headerDataRow = dataGridConfiguration.rowGenerator.items .firstWhereOrNull( - (DataRowBase dataRow) => dataRow.rowType == RowType.headerRow); + (DataRowBase dataRow) => dataRow.rowType == RowType.headerRow, + ); final bool isRowInEffectiveList = _selectedRows.any( - (row) => effectiveRows(dataGridConfiguration.source).contains(row)); + (row) => effectiveRows(dataGridConfiguration.source).contains(row), + ); if (headerDataRow == null) { if (dataGridConfiguration.controller.selectedRows.length == @@ -569,9 +676,11 @@ class RowSelectionManager extends SelectionManagerBase { } final DataCellBase? headerDataCell = headerDataRow.visibleColumns - .firstWhereOrNull((DataCellBase cell) => - cell.columnIndex == - dataGridConfiguration.source.groupedColumns.length); + .firstWhereOrNull( + (DataCellBase cell) => + cell.columnIndex == + dataGridConfiguration.source.groupedColumns.length, + ); // Issue: // FLUT-6617-The null check operator used on the null value exception occurred @@ -606,13 +715,18 @@ class RowSelectionManager extends SelectionManagerBase { return; } final int recordIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, rowColumnIndex.rowIndex); + dataGridConfiguration, + rowColumnIndex.rowIndex, + ); final RowColumnIndex previousRowColumnIndex = RowColumnIndex( - dataGridConfiguration.currentCell.rowIndex, - dataGridConfiguration.currentCell.columnIndex); - if (!dataGridConfiguration.currentCell - ._handlePointerOperation(dataGridConfiguration, rowColumnIndex)) { + dataGridConfiguration.currentCell.rowIndex, + dataGridConfiguration.currentCell.columnIndex, + ); + if (!dataGridConfiguration.currentCell._handlePointerOperation( + dataGridConfiguration, + rowColumnIndex, + )) { return; } final bool isShiftPressed = dataGridConfiguration.isShiftKeyPressed; @@ -633,16 +747,20 @@ class RowSelectionManager extends SelectionManagerBase { if (!isShiftPressed && _raiseSelectionChanging()) { _shiftSelectedRows.clear(); _processSelection( - dataGridConfiguration, rowColumnIndex, previousRowColumnIndex); + dataGridConfiguration, + rowColumnIndex, + previousRowColumnIndex, + ); } else if (dataGridConfiguration.selectionMode == SelectionMode.multiple) { _processShiftKeySelection(rowColumnIndex, recordIndex); } } void _processSelection( - DataGridConfiguration dataGridConfiguration, - RowColumnIndex nextRowColumnIndex, - RowColumnIndex previousRowColumnIndex) { + DataGridConfiguration dataGridConfiguration, + RowColumnIndex nextRowColumnIndex, + RowColumnIndex previousRowColumnIndex, + ) { // If selectionMode is single. next current cell is going to present in the // same selected row. // In this case, we don't update the whole data row. Instead of that @@ -697,10 +815,13 @@ class RowSelectionManager extends SelectionManagerBase { return; } - final int recordIndex = - effectiveRows(dataGridConfiguration.source).indexOf(newValue!); - final int rowIndex = - grid_helper.resolveToRowIndex(dataGridConfiguration, recordIndex); + final int recordIndex = effectiveRows( + dataGridConfiguration.source, + ).indexOf(newValue!); + final int rowIndex = grid_helper.resolveToRowIndex( + dataGridConfiguration, + recordIndex, + ); if (rowIndex < grid_helper.getHeaderIndex(dataGridConfiguration)) { return; @@ -714,15 +835,23 @@ class RowSelectionManager extends SelectionManagerBase { } if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { - _addCurrentCell(newValue, dataGridConfiguration, - isSelectionChanging: true); + _addCurrentCell( + newValue, + dataGridConfiguration, + isSelectionChanging: true, + ); } else { - final int columnIndex = - grid_helper.resolveToStartColumnIndex(dataGridConfiguration); - final int rowIndex = - selection_helper.resolveToRowIndex(dataGridConfiguration, newValue); - dataGridConfiguration.currentCell - ._updateCurrentRowColumnIndex(rowIndex, columnIndex); + final int columnIndex = grid_helper.resolveToStartColumnIndex( + dataGridConfiguration, + ); + final int rowIndex = selection_helper.resolveToRowIndex( + dataGridConfiguration, + newValue, + ); + dataGridConfiguration.currentCell._updateCurrentRowColumnIndex( + rowIndex, + columnIndex, + ); } _addSelection(newValue, dataGridConfiguration); @@ -769,8 +898,10 @@ class RowSelectionManager extends SelectionManagerBase { return; } - final DataGridRow? record = - selection_helper.getRecord(dataGridConfiguration, newValue); + final DataGridRow? record = selection_helper.getRecord( + dataGridConfiguration, + newValue, + ); if (record != null && !_selectedRows.contains(record)) { //In multiple case we shouldn't to clear the collection as // well source properties. @@ -779,15 +910,23 @@ class RowSelectionManager extends SelectionManagerBase { } if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { - _addCurrentCell(record, dataGridConfiguration, - isSelectionChanging: true); + _addCurrentCell( + record, + dataGridConfiguration, + isSelectionChanging: true, + ); } else { - final int rowIndex = - selection_helper.resolveToRowIndex(dataGridConfiguration, record); - final int columnIndex = - grid_helper.resolveToStartColumnIndex(dataGridConfiguration); - dataGridConfiguration.currentCell - ._updateCurrentRowColumnIndex(rowIndex, columnIndex); + final int rowIndex = selection_helper.resolveToRowIndex( + dataGridConfiguration, + record, + ); + final int columnIndex = grid_helper.resolveToStartColumnIndex( + dataGridConfiguration, + ); + dataGridConfiguration.currentCell._updateCurrentRowColumnIndex( + rowIndex, + columnIndex, + ); } _addSelection(record, dataGridConfiguration); @@ -805,8 +944,10 @@ class RowSelectionManager extends SelectionManagerBase { return; } - final List newValue = - dataGridConfiguration.controller.selectedRows.toList(growable: false); + final List newValue = dataGridConfiguration + .controller + .selectedRows + .toList(growable: false); if (newValue.isEmpty) { _clearSelectedRows(dataGridConfiguration); @@ -815,10 +956,13 @@ class RowSelectionManager extends SelectionManagerBase { } _clearSelectedRows(dataGridConfiguration); - final List visibleRows = newValue - .where( - (row) => effectiveRows(dataGridConfiguration.source).contains(row)) - .toList(); + final List visibleRows = + newValue + .where( + (row) => + effectiveRows(dataGridConfiguration.source).contains(row), + ) + .toList(); _selectedRows.addAll(visibleRows); dataGridConfiguration.controller.selectedRows.addAll(visibleRows); _refreshSelection(); @@ -830,16 +974,22 @@ class RowSelectionManager extends SelectionManagerBase { if (dataGridConfiguration.navigationMode == GridNavigationMode.cell && _selectedRows.isNotEmpty) { final DataGridRow lastRecord = _selectedRows.last; - _addCurrentCell(lastRecord, dataGridConfiguration, - isSelectionChanging: true); + _addCurrentCell( + lastRecord, + dataGridConfiguration, + isSelectionChanging: true, + ); } else if (dataGridConfiguration.isDesktop && dataGridConfiguration.navigationMode == GridNavigationMode.row) { final DataGridRow lastRecord = _selectedRows.last; - final int rowIndex = - selection_helper.resolveToRowIndex(dataGridConfiguration, lastRecord); + final int rowIndex = selection_helper.resolveToRowIndex( + dataGridConfiguration, + lastRecord, + ); dataGridConfiguration.currentCell._updateBorderForMultipleSelection( - dataGridConfiguration, - nextRowColumnIndex: RowColumnIndex(rowIndex, -1)); + dataGridConfiguration, + nextRowColumnIndex: RowColumnIndex(rowIndex, -1), + ); } notifyListeners(); @@ -866,18 +1016,25 @@ class RowSelectionManager extends SelectionManagerBase { return; } - lastRecord = dataGridConfiguration.selectionMode == SelectionMode.single - ? selection_helper.getRecord( - dataGridConfiguration, - grid_helper.resolveToRecordIndex( - dataGridConfiguration, currentRowColumnIndex.rowIndex)) - : lastRecord; + lastRecord = + dataGridConfiguration.selectionMode == SelectionMode.single + ? selection_helper.getRecord( + dataGridConfiguration, + grid_helper.resolveToRecordIndex( + dataGridConfiguration, + currentRowColumnIndex.rowIndex, + ), + ) + : lastRecord; dataGridConfiguration.currentCell._moveCurrentCellTo( - dataGridConfiguration, - RowColumnIndex(currentRowColumnIndex.rowIndex, - currentRowColumnIndex.columnIndex), - isSelectionChanged: true); + dataGridConfiguration, + RowColumnIndex( + currentRowColumnIndex.rowIndex, + currentRowColumnIndex.columnIndex, + ), + isSelectionChanged: true, + ); } if (lastRecord != null) { @@ -885,11 +1042,14 @@ class RowSelectionManager extends SelectionManagerBase { } } else if (dataGridConfiguration.isDesktop && dataGridConfiguration.selectionMode == SelectionMode.multiple) { - final RowColumnIndex currentRowColumnIndex = - RowColumnIndex(dataGridConfiguration.currentCell.rowIndex, -1); + final RowColumnIndex currentRowColumnIndex = RowColumnIndex( + dataGridConfiguration.currentCell.rowIndex, + -1, + ); dataGridConfiguration.currentCell._updateBorderForMultipleSelection( - dataGridConfiguration, - nextRowColumnIndex: currentRowColumnIndex); + dataGridConfiguration, + nextRowColumnIndex: currentRowColumnIndex, + ); } } @@ -903,35 +1063,48 @@ class RowSelectionManager extends SelectionManagerBase { } final int rowIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, currentCell.rowIndex); + dataGridConfiguration, + currentCell.rowIndex, + ); if (recordLength > 0 && rowIndex >= recordLength && currentCell.rowIndex != -1) { final int startRowIndex = selection_helper.getPreviousRowIndex( - dataGridConfiguration, currentCell.rowIndex); - currentCell._moveCurrentCellTo(dataGridConfiguration, - RowColumnIndex(startRowIndex, currentCell.columnIndex), - needToUpdateColumn: false); + dataGridConfiguration, + currentCell.rowIndex, + ); + currentCell._moveCurrentCellTo( + dataGridConfiguration, + RowColumnIndex(startRowIndex, currentCell.columnIndex), + needToUpdateColumn: false, + ); _refreshSelection(); } final int columnIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, currentCell.columnIndex); + dataGridConfiguration, + currentCell.columnIndex, + ); if (columnLength > 0 && columnIndex >= columnLength && currentCell.columnIndex != -1) { final int startColumnIndex = selection_helper.getPreviousColumnIndex( - dataGridConfiguration, currentCell.columnIndex); - currentCell._moveCurrentCellTo(dataGridConfiguration, - RowColumnIndex(currentCell.rowIndex, startColumnIndex), - needToUpdateColumn: false); + dataGridConfiguration, + currentCell.columnIndex, + ); + currentCell._moveCurrentCellTo( + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, startColumnIndex), + needToUpdateColumn: false, + ); } } - void _updateSelectionController( - {bool isSelectionModeChanged = false, - bool isNavigationModeChanged = false, - bool isDataSourceChanged = false}) { + void _updateSelectionController({ + bool isSelectionModeChanged = false, + bool isNavigationModeChanged = false, + bool isDataSourceChanged = false, + }) { if (isDataSourceChanged) { _onDataSourceChanged(); } @@ -945,10 +1118,11 @@ class RowSelectionManager extends SelectionManagerBase { } } - void _handleSelectionPropertyChanged( - {RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight = false}) { + void _handleSelectionPropertyChanged({ + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight = false, + }) { switch (propertyName) { case 'selectedIndex': onSelectedIndexChanged(); @@ -971,13 +1145,16 @@ class RowSelectionManager extends SelectionManagerBase { _dataGridStateDetails!(); if (dataGridConfiguration.currentCell.isEditing && keyEvent.logicalKey != LogicalKeyboardKey.escape) { - if (!await dataGridConfiguration.currentCell - .canSubmitCell(dataGridConfiguration)) { + if (!await dataGridConfiguration.currentCell.canSubmitCell( + dataGridConfiguration, + )) { return; } - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, cancelCanSubmitCell: true); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + cancelCanSubmitCell: true, + ); } if (keyEvent.logicalKey == LogicalKeyboardKey.tab) { @@ -1042,12 +1219,14 @@ class RowSelectionManager extends SelectionManagerBase { if (dataGridConfiguration.allowEditing && dataGridConfiguration.navigationMode == GridNavigationMode.cell) { final RowColumnIndex rowColumnIndex = RowColumnIndex( - dataGridConfiguration.currentCell.rowIndex, - dataGridConfiguration.currentCell.columnIndex); + dataGridConfiguration.currentCell.rowIndex, + dataGridConfiguration.currentCell.columnIndex, + ); dataGridConfiguration.currentCell.onCellBeginEdit( - editingRowColumnIndex: rowColumnIndex, - isProgrammatic: true, - needToResolveIndex: false); + editingRowColumnIndex: rowColumnIndex, + isProgrammatic: true, + needToResolveIndex: false, + ); } } @@ -1055,69 +1234,95 @@ class RowSelectionManager extends SelectionManagerBase { if (dataGridConfiguration.allowEditing && dataGridConfiguration.navigationMode == GridNavigationMode.cell && dataGridConfiguration.currentCell.isEditing) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, isCellCancelEdit: true); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + isCellCancelEdit: true, + ); } } } void _processEndKey( - DataGridConfiguration dataGridConfiguration, KeyEvent keyEvent) { + DataGridConfiguration dataGridConfiguration, + KeyEvent keyEvent, + ) { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; - final int lastCellIndex = - selection_helper.getLastCellIndex(dataGridConfiguration); + final int lastCellIndex = selection_helper.getLastCellIndex( + dataGridConfiguration, + ); final bool needToScrollToMinOrMaxExtent = dataGridConfiguration.container.extentWidth > - dataGridConfiguration.viewWidth; + dataGridConfiguration.viewWidth; if (needToScrollToMinOrMaxExtent) { - selection_helper.scrollInViewFromLeft(dataGridConfiguration, - needToScrollMaxExtent: true); + selection_helper.scrollInViewFromLeft( + dataGridConfiguration, + needToScrollMaxExtent: true, + ); } if ((dataGridConfiguration.isMacPlatform ? HardwareKeyboard.instance.isMetaPressed : HardwareKeyboard.instance.isControlPressed) && keyEvent.logicalKey != LogicalKeyboardKey.arrowRight) { - final int lastRowIndex = - selection_helper.getLastNavigatingRowIndex(dataGridConfiguration); - selection_helper.scrollInViewFromTop(dataGridConfiguration, - needToScrollToMaxExtent: true); + final int lastRowIndex = selection_helper.getLastNavigatingRowIndex( + dataGridConfiguration, + ); + selection_helper.scrollInViewFromTop( + dataGridConfiguration, + needToScrollToMaxExtent: true, + ); _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(lastRowIndex, lastCellIndex)); + dataGridConfiguration, + RowColumnIndex(lastRowIndex, lastCellIndex), + ); } else { - _processSelectionAndCurrentCell(dataGridConfiguration, - RowColumnIndex(currentCell.rowIndex, lastCellIndex)); + _processSelectionAndCurrentCell( + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, lastCellIndex), + ); } } void _processHomeKey( - DataGridConfiguration dataGridConfiguration, KeyEvent keyEvent) { + DataGridConfiguration dataGridConfiguration, + KeyEvent keyEvent, + ) { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; - final int firstCellIndex = - selection_helper.getFirstCellIndex(dataGridConfiguration); + final int firstCellIndex = selection_helper.getFirstCellIndex( + dataGridConfiguration, + ); final bool needToScrollToMinOrMaxExtend = dataGridConfiguration.container.extentWidth > - dataGridConfiguration.viewWidth; + dataGridConfiguration.viewWidth; if (needToScrollToMinOrMaxExtend) { - selection_helper.scrollInViewFromRight(dataGridConfiguration, - needToScrollToMinExtent: true); + selection_helper.scrollInViewFromRight( + dataGridConfiguration, + needToScrollToMinExtent: true, + ); } if ((dataGridConfiguration.isMacPlatform ? HardwareKeyboard.instance.isMetaPressed : HardwareKeyboard.instance.isControlPressed) && keyEvent.logicalKey != LogicalKeyboardKey.arrowLeft) { - final int firstRowIndex = - selection_helper.getFirstNavigatingRowIndex(dataGridConfiguration); - selection_helper.scrollInViewFromDown(dataGridConfiguration, - needToScrollToMinExtent: true); + final int firstRowIndex = selection_helper.getFirstNavigatingRowIndex( + dataGridConfiguration, + ); + selection_helper.scrollInViewFromDown( + dataGridConfiguration, + needToScrollToMinExtent: true, + ); _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(firstRowIndex, firstCellIndex)); + dataGridConfiguration, + RowColumnIndex(firstRowIndex, firstCellIndex), + ); } else { - _processSelectionAndCurrentCell(dataGridConfiguration, - RowColumnIndex(currentCell.rowIndex, firstCellIndex)); + _processSelectionAndCurrentCell( + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, firstCellIndex), + ); } } @@ -1127,8 +1332,10 @@ class RowSelectionManager extends SelectionManagerBase { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; final int index = selection_helper.getNextPageIndex(dataGridConfiguration); if (currentCell.rowIndex != index && index != -1) { - _processSelectionAndCurrentCell(dataGridConfiguration, - RowColumnIndex(index, currentCell.columnIndex)); + _processSelectionAndCurrentCell( + dataGridConfiguration, + RowColumnIndex(index, currentCell.columnIndex), + ); } } @@ -1136,11 +1343,14 @@ class RowSelectionManager extends SelectionManagerBase { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); final CurrentCellManager currentCell = dataGridConfiguration.currentCell; - final int index = - selection_helper.getPreviousPageIndex(dataGridConfiguration); + final int index = selection_helper.getPreviousPageIndex( + dataGridConfiguration, + ); if (currentCell.rowIndex != index) { - _processSelectionAndCurrentCell(dataGridConfiguration, - RowColumnIndex(index, currentCell.columnIndex)); + _processSelectionAndCurrentCell( + dataGridConfiguration, + RowColumnIndex(index, currentCell.columnIndex), + ); } } @@ -1149,14 +1359,20 @@ class RowSelectionManager extends SelectionManagerBase { _dataGridStateDetails!(); final CurrentCellManager currentCell = dataGridConfiguration.currentCell; final int nextRowIndex = selection_helper.getNextRowIndex( - dataGridConfiguration, currentCell.rowIndex); - final int lastRowIndex = - selection_helper.getLastNavigatingRowIndex(dataGridConfiguration); + dataGridConfiguration, + currentCell.rowIndex, + ); + final int lastRowIndex = selection_helper.getLastNavigatingRowIndex( + dataGridConfiguration, + ); int nextColumnIndex = selection_helper.getDownKeyColumnIndex( - dataGridConfiguration, currentCell); + dataGridConfiguration, + currentCell, + ); if (nextColumnIndex <= 0) { - nextColumnIndex = - selection_helper.getFirstCellIndex(dataGridConfiguration); + nextColumnIndex = selection_helper.getFirstCellIndex( + dataGridConfiguration, + ); } if (nextRowIndex > lastRowIndex || currentCell.rowIndex == nextRowIndex) { @@ -1166,15 +1382,21 @@ class RowSelectionManager extends SelectionManagerBase { if (dataGridConfiguration.isMacPlatform ? HardwareKeyboard.instance.isMetaPressed : HardwareKeyboard.instance.isControlPressed) { - selection_helper.scrollInViewFromTop(dataGridConfiguration, - needToScrollToMaxExtent: true); + selection_helper.scrollInViewFromTop( + dataGridConfiguration, + needToScrollToMaxExtent: true, + ); _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(lastRowIndex, nextColumnIndex), - isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed); + dataGridConfiguration, + RowColumnIndex(lastRowIndex, nextColumnIndex), + isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed, + ); } else { _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(nextRowIndex, nextColumnIndex), - isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed); + dataGridConfiguration, + RowColumnIndex(nextRowIndex, nextColumnIndex), + isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed, + ); } } @@ -1183,9 +1405,13 @@ class RowSelectionManager extends SelectionManagerBase { _dataGridStateDetails!(); final CurrentCellManager currentCell = dataGridConfiguration.currentCell; final int previousRowIndex = selection_helper.getPreviousRowIndex( - dataGridConfiguration, currentCell.rowIndex); + dataGridConfiguration, + currentCell.rowIndex, + ); final int columnIndex = selection_helper.getUpKeyColumnIndex( - dataGridConfiguration, currentCell); + dataGridConfiguration, + currentCell, + ); if (previousRowIndex == currentCell.rowIndex) { return; @@ -1194,22 +1420,31 @@ class RowSelectionManager extends SelectionManagerBase { if (dataGridConfiguration.isMacPlatform ? HardwareKeyboard.instance.isMetaPressed : HardwareKeyboard.instance.isControlPressed) { - final int firstRowIndex = - selection_helper.getFirstRowIndex(dataGridConfiguration); - selection_helper.scrollInViewFromDown(dataGridConfiguration, - needToScrollToMinExtent: true); + final int firstRowIndex = selection_helper.getFirstRowIndex( + dataGridConfiguration, + ); + selection_helper.scrollInViewFromDown( + dataGridConfiguration, + needToScrollToMinExtent: true, + ); _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(firstRowIndex, columnIndex), - isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed); + dataGridConfiguration, + RowColumnIndex(firstRowIndex, columnIndex), + isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed, + ); } else { _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(previousRowIndex, columnIndex), - isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed); + dataGridConfiguration, + RowColumnIndex(previousRowIndex, columnIndex), + isShiftKeyPressed: HardwareKeyboard.instance.isShiftPressed, + ); } } void _processKeyRight( - DataGridConfiguration dataGridConfiguration, KeyEvent keyEvent) { + DataGridConfiguration dataGridConfiguration, + KeyEvent keyEvent, + ) { if (dataGridConfiguration.navigationMode == GridNavigationMode.row) { return; } @@ -1223,8 +1458,9 @@ class RowSelectionManager extends SelectionManagerBase { return; } - final int lastCellIndex = - selection_helper.getLastCellIndex(dataGridConfiguration); + final int lastCellIndex = selection_helper.getLastCellIndex( + dataGridConfiguration, + ); int nextCellIndex; // Need to get previous column index only if the control key is // pressed in RTL mode since it will perform the home key event. @@ -1233,10 +1469,14 @@ class RowSelectionManager extends SelectionManagerBase { : HardwareKeyboard.instance.isControlPressed) && dataGridConfiguration.textDirection == TextDirection.rtl) { nextCellIndex = selection_helper.getPreviousColumnIndex( - dataGridConfiguration, currentCell.columnIndex); + dataGridConfiguration, + currentCell.columnIndex, + ); } else { nextCellIndex = selection_helper.getNextColumnIndex( - dataGridConfiguration, currentCell.columnIndex); + dataGridConfiguration, + currentCell.columnIndex, + ); } if (currentCell.rowIndex <= @@ -1255,9 +1495,11 @@ class RowSelectionManager extends SelectionManagerBase { _processEndKey(dataGridConfiguration, keyEvent); } } else { - currentCell._processCurrentCell(dataGridConfiguration, - RowColumnIndex(currentCell.rowIndex, nextCellIndex), - isSelectionChanged: true); + currentCell._processCurrentCell( + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, nextCellIndex), + isSelectionChanged: true, + ); if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { notifyListeners(); } @@ -1265,7 +1507,9 @@ class RowSelectionManager extends SelectionManagerBase { } void _processKeyLeft( - DataGridConfiguration dataGridConfiguration, KeyEvent keyEvent) { + DataGridConfiguration dataGridConfiguration, + KeyEvent keyEvent, + ) { if (dataGridConfiguration.navigationMode == GridNavigationMode.row) { return; } @@ -1287,10 +1531,14 @@ class RowSelectionManager extends SelectionManagerBase { : HardwareKeyboard.instance.isControlPressed) && dataGridConfiguration.textDirection == TextDirection.rtl) { previousCellIndex = selection_helper.getNextColumnIndex( - dataGridConfiguration, currentCell.columnIndex); + dataGridConfiguration, + currentCell.columnIndex, + ); } else { previousCellIndex = selection_helper.getPreviousColumnIndex( - dataGridConfiguration, currentCell.columnIndex); + dataGridConfiguration, + currentCell.columnIndex, + ); } if (currentCell.rowIndex <= @@ -1309,9 +1557,11 @@ class RowSelectionManager extends SelectionManagerBase { _processHomeKey(dataGridConfiguration, keyEvent); } } else { - currentCell._processCurrentCell(dataGridConfiguration, - RowColumnIndex(currentCell.rowIndex, previousCellIndex), - isSelectionChanged: true); + currentCell._processCurrentCell( + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, previousCellIndex), + isSelectionChanged: true, + ); if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { notifyListeners(); } @@ -1322,30 +1572,35 @@ class RowSelectionManager extends SelectionManagerBase { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); final CurrentCellManager currentCell = dataGridConfiguration.currentCell; - final int lastCellIndex = - selection_helper.getLastCellIndex(dataGridConfiguration); - int firstCellIndex = - selection_helper.getFirstCellIndex(dataGridConfiguration); + final int lastCellIndex = selection_helper.getLastCellIndex( + dataGridConfiguration, + ); + int firstCellIndex = selection_helper.getFirstCellIndex( + dataGridConfiguration, + ); - final int firstRowIndex = - selection_helper.getFirstRowIndex(dataGridConfiguration); + final int firstRowIndex = selection_helper.getFirstRowIndex( + dataGridConfiguration, + ); final bool isCaptionSummaryCoveredRow = currentCell.dataCell?.dataRow != null && - currentCell.dataCell!.dataRow!.rowType == - RowType.captionSummaryCoveredRow; + currentCell.dataCell!.dataRow!.rowType == + RowType.captionSummaryCoveredRow; if (dataGridConfiguration.navigationMode == GridNavigationMode.row || (currentCell.rowIndex < 0 && currentCell.columnIndex < 0)) { _processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(firstRowIndex, firstCellIndex)); + dataGridConfiguration, + RowColumnIndex(firstRowIndex, firstCellIndex), + ); notifyListeners(); return; } final bool needToScrollToMinOrMaxExtend = dataGridConfiguration.container.extentWidth > - dataGridConfiguration.viewWidth; + dataGridConfiguration.viewWidth; if (HardwareKeyboard.instance.isShiftPressed) { if (currentCell.columnIndex == firstCellIndex && @@ -1356,13 +1611,19 @@ class RowSelectionManager extends SelectionManagerBase { if (currentCell.columnIndex == firstCellIndex || isCaptionSummaryCoveredRow) { final int previousRowIndex = selection_helper.getPreviousRowIndex( - dataGridConfiguration, currentCell.rowIndex); + dataGridConfiguration, + currentCell.rowIndex, + ); if (needToScrollToMinOrMaxExtend) { - selection_helper.scrollInViewFromLeft(dataGridConfiguration, - needToScrollMaxExtent: needToScrollToMinOrMaxExtend); + selection_helper.scrollInViewFromLeft( + dataGridConfiguration, + needToScrollMaxExtent: needToScrollToMinOrMaxExtend, + ); } - _processSelectionAndCurrentCell(dataGridConfiguration, - RowColumnIndex(previousRowIndex, lastCellIndex)); + _processSelectionAndCurrentCell( + dataGridConfiguration, + RowColumnIndex(previousRowIndex, lastCellIndex), + ); } else { _processKeyLeft(dataGridConfiguration, keyEvent); } @@ -1371,20 +1632,27 @@ class RowSelectionManager extends SelectionManagerBase { (dataGridConfiguration.source.groupedColumns.isNotEmpty && isCaptionSummaryCoveredRow)) { final int nextRowIndex = selection_helper.getNextRowIndex( - dataGridConfiguration, currentCell.rowIndex); + dataGridConfiguration, + currentCell.rowIndex, + ); if (needToScrollToMinOrMaxExtend) { - selection_helper.scrollInViewFromRight(dataGridConfiguration, - needToScrollToMinExtent: needToScrollToMinOrMaxExtend); + selection_helper.scrollInViewFromRight( + dataGridConfiguration, + needToScrollToMinExtent: needToScrollToMinOrMaxExtend, + ); } if (dataGridConfiguration.source.groupedColumns.isEmpty) { - firstCellIndex = (nextRowIndex == currentCell.rowIndex && - lastCellIndex == currentCell.columnIndex) - ? currentCell.columnIndex - : firstCellIndex; + firstCellIndex = + (nextRowIndex == currentCell.rowIndex && + lastCellIndex == currentCell.columnIndex) + ? currentCell.columnIndex + : firstCellIndex; } - _processSelectionAndCurrentCell(dataGridConfiguration, - RowColumnIndex(nextRowIndex, firstCellIndex)); + _processSelectionAndCurrentCell( + dataGridConfiguration, + RowColumnIndex(nextRowIndex, firstCellIndex), + ); } else { _processKeyRight(dataGridConfiguration, keyEvent); } @@ -1408,14 +1676,19 @@ class RowSelectionManager extends SelectionManagerBase { if (_raiseSelectionChanging(oldItems: removeItems, newItems: addedItems)) { dataGridConfiguration.controller.selectedRows.clear(); _selectedRows.addAll( - effectiveRows(dataGridConfiguration.source) - .where((row) => !_selectedRows.contains(row)), + effectiveRows( + dataGridConfiguration.source, + ).where((row) => !_selectedRows.contains(row)), + ); + dataGridConfiguration.controller.selectedRows.addAll( + effectiveRows(dataGridConfiguration.source), ); - dataGridConfiguration.controller.selectedRows - .addAll(effectiveRows(dataGridConfiguration.source)); _raiseCheckboxValueChanged( - value: true, row: null, rowType: RowType.headerRow); + value: true, + row: null, + rowType: RowType.headerRow, + ); _refreshSelection(); dataGridConfiguration.container @@ -1437,39 +1710,52 @@ class RowSelectionManager extends SelectionManagerBase { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; final int recordIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, currentCell.rowIndex); + dataGridConfiguration, + currentCell.rowIndex, + ); _shiftSelectedRows.clear(); _pressedRowIndex = recordIndex; _applySelection( - RowColumnIndex(currentCell.rowIndex, currentCell.columnIndex)); + RowColumnIndex(currentCell.rowIndex, currentCell.columnIndex), + ); } void _processSelectionAndCurrentCell( - DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex, - {bool isShiftKeyPressed = false, - bool isProgrammatic = false}) { + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, { + bool isShiftKeyPressed = false, + bool isProgrammatic = false, + }) { final RowColumnIndex previousRowColumnIndex = RowColumnIndex( - dataGridConfiguration.currentCell.rowIndex, - dataGridConfiguration.currentCell.columnIndex); + dataGridConfiguration.currentCell.rowIndex, + dataGridConfiguration.currentCell.columnIndex, + ); if (isProgrammatic) { - dataGridConfiguration.currentCell - ._moveCurrentCellTo(dataGridConfiguration, rowColumnIndex); + dataGridConfiguration.currentCell._moveCurrentCellTo( + dataGridConfiguration, + rowColumnIndex, + ); } else { - dataGridConfiguration.currentCell - ._processCurrentCell(dataGridConfiguration, rowColumnIndex); + dataGridConfiguration.currentCell._processCurrentCell( + dataGridConfiguration, + rowColumnIndex, + ); } if (dataGridConfiguration.selectionMode == SelectionMode.multiple) { dataGridConfiguration.currentCell._updateBorderForMultipleSelection( - dataGridConfiguration, - nextRowColumnIndex: rowColumnIndex, - previousRowColumnIndex: previousRowColumnIndex); + dataGridConfiguration, + nextRowColumnIndex: rowColumnIndex, + previousRowColumnIndex: previousRowColumnIndex, + ); if (isShiftKeyPressed) { _processShiftKeySelection( - rowColumnIndex, - grid_helper.resolveToRecordIndex( - dataGridConfiguration, rowColumnIndex.rowIndex)); + rowColumnIndex, + grid_helper.resolveToRecordIndex( + dataGridConfiguration, + rowColumnIndex.rowIndex, + ), + ); } else { notifyListeners(); } @@ -1478,9 +1764,10 @@ class RowSelectionManager extends SelectionManagerBase { _pressedRowColumnIndex = rowColumnIndex; } - bool _raiseSelectionChanging( - {List oldItems = const [], - List newItems = const []}) { + bool _raiseSelectionChanging({ + List oldItems = const [], + List newItems = const [], + }) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); if (dataGridConfiguration.onSelectionChanging == null) { @@ -1490,9 +1777,10 @@ class RowSelectionManager extends SelectionManagerBase { return dataGridConfiguration.onSelectionChanging!(newItems, oldItems); } - void _raiseSelectionChanged( - {List oldItems = const [], - List newItems = const []}) { + void _raiseSelectionChanged({ + List oldItems = const [], + List newItems = const [], + }) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); if (dataGridConfiguration.onSelectionChanged == null) { @@ -1553,28 +1841,39 @@ class CurrentCellManager { /// Indicate the any [DataGridCell] is in editing state. bool isEditing = false; - bool _handlePointerOperation(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { + bool _handlePointerOperation( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, + ) { if (dataGridConfiguration.allowSwiping) { dataGridConfiguration.container.resetSwipeOffset(); } - final RowColumnIndex previousRowColumnIndex = - RowColumnIndex(rowIndex, columnIndex); + final RowColumnIndex previousRowColumnIndex = RowColumnIndex( + rowIndex, + columnIndex, + ); if (!rowColumnIndex.equals(previousRowColumnIndex) && dataGridConfiguration.navigationMode != GridNavigationMode.row) { if (!_raiseCurrentCellActivating(rowColumnIndex)) { return false; } - _setCurrentCell(dataGridConfiguration, rowColumnIndex.rowIndex, - rowColumnIndex.columnIndex); + _setCurrentCell( + dataGridConfiguration, + rowColumnIndex.rowIndex, + rowColumnIndex.columnIndex, + ); _raiseCurrentCellActivated(previousRowColumnIndex); } else if (dataGridConfiguration.navigationMode == GridNavigationMode.row && rowIndex != rowColumnIndex.rowIndex) { _updateCurrentRowColumnIndex( - rowColumnIndex.rowIndex, rowColumnIndex.columnIndex); - _updateBorderForMultipleSelection(dataGridConfiguration, - previousRowColumnIndex: previousRowColumnIndex, - nextRowColumnIndex: rowColumnIndex); + rowColumnIndex.rowIndex, + rowColumnIndex.columnIndex, + ); + _updateBorderForMultipleSelection( + dataGridConfiguration, + previousRowColumnIndex: previousRowColumnIndex, + nextRowColumnIndex: rowColumnIndex, + ); } else if (dataGridConfiguration.navigationMode == GridNavigationMode.row && dataGridConfiguration.selectionMode == SelectionMode.singleDeselect) { // Issue: FLUT-858176-The current row gets removed while selecting a row and then deselecting it. @@ -1587,9 +1886,12 @@ class CurrentCellManager { return true; } - void _setCurrentCell(DataGridConfiguration dataGridConfiguration, - int rowIndex, int columnIndex, - [bool needToUpdateColumn = true]) { + void _setCurrentCell( + DataGridConfiguration dataGridConfiguration, + int rowIndex, + int columnIndex, [ + bool needToUpdateColumn = true, + ]) { if (this.rowIndex == rowIndex && this.columnIndex == columnIndex) { return; } @@ -1597,14 +1899,23 @@ class CurrentCellManager { _removeCurrentCell(dataGridConfiguration, needToUpdateColumn); _updateCurrentRowColumnIndex(rowIndex, columnIndex); _updateCurrentCell( - dataGridConfiguration, rowIndex, columnIndex, needToUpdateColumn); + dataGridConfiguration, + rowIndex, + columnIndex, + needToUpdateColumn, + ); } - void _updateCurrentCell(DataGridConfiguration dataGridConfiguration, - int rowIndex, int columnIndex, - [bool needToUpdateColumn = true]) { - final DataRowBase? dataRowBase = - _getDataRow(dataGridConfiguration, rowIndex); + void _updateCurrentCell( + DataGridConfiguration dataGridConfiguration, + int rowIndex, + int columnIndex, [ + bool needToUpdateColumn = true, + ]) { + final DataRowBase? dataRowBase = _getDataRow( + dataGridConfiguration, + rowIndex, + ); if (dataRowBase != null && needToUpdateColumn) { final DataCellBase? dataCellBase = _getDataCell(dataRowBase, columnIndex); if (dataCellBase != null) { @@ -1615,8 +1926,10 @@ class CurrentCellManager { } } - void _removeCurrentCell(DataGridConfiguration dataGridConfiguration, - [bool needToUpdateColumn = true]) { + void _removeCurrentCell( + DataGridConfiguration dataGridConfiguration, [ + bool needToUpdateColumn = true, + ]) { if (rowIndex == -1 && columnIndex == -1) { return; } @@ -1639,7 +1952,9 @@ class CurrentCellManager { } DataRowBase? _getDataRow( - DataGridConfiguration dataGridConfiguration, int rowIndex) { + DataGridConfiguration dataGridConfiguration, + int rowIndex, + ) { final List dataRows = dataGridConfiguration.rowGenerator.items; if (dataRows.isEmpty) { return null; @@ -1649,7 +1964,8 @@ class CurrentCellManager { // all the row indexes will be -1 in the `items` collection. So, need to // consider the `isCurrentRow` property additionally to get the current row. return dataRows.firstWhereOrNull( - (DataRowBase row) => row.rowIndex == rowIndex || row.isCurrentRow); + (DataRowBase row) => row.rowIndex == rowIndex || row.isCurrentRow, + ); } DataCellBase? _getDataCell(DataRowBase dataRow, int columnIndex) { @@ -1658,13 +1974,16 @@ class CurrentCellManager { } if (dataRow.rowType == RowType.captionSummaryCoveredRow) { - return dataRow.visibleColumns.firstWhereOrNull((DataCellBase dataCell) => - columnIndex >= dataCell.columnIndex && - dataCell.columnIndex + dataCell.columnSpan <= columnIndex); + return dataRow.visibleColumns.firstWhereOrNull( + (DataCellBase dataCell) => + columnIndex >= dataCell.columnIndex && + dataCell.columnIndex + dataCell.columnSpan <= columnIndex, + ); } return dataRow.visibleColumns.firstWhereOrNull( - (DataCellBase dataCell) => dataCell.columnIndex == columnIndex); + (DataCellBase dataCell) => dataCell.columnIndex == columnIndex, + ); } void _updateCurrentRowColumnIndex(int rowIndex, int columnIndex) { @@ -1674,7 +1993,10 @@ class CurrentCellManager { /// Sets the current data cell as dirty to refresh the cell. void setCurrentCellDirty( - DataRowBase? dataRow, DataCellBase? dataCell, bool enableCurrentCell) { + DataRowBase? dataRow, + DataCellBase? dataCell, + bool enableCurrentCell, + ) { dataCell?.isCurrentCell = enableCurrentCell; dataCell?.isDirty = true; dataRow?.isCurrentRow = enableCurrentCell; @@ -1689,11 +2011,15 @@ class CurrentCellManager { final RowColumnIndex newRowColumnIndex = grid_helper .resolveToRecordRowColumnIndex(dataGridConfiguration, rowColumnIndex); - final RowColumnIndex oldRowColumnIndex = - grid_helper.resolveToRecordRowColumnIndex( - dataGridConfiguration, RowColumnIndex(rowIndex, columnIndex)); + final RowColumnIndex oldRowColumnIndex = grid_helper + .resolveToRecordRowColumnIndex( + dataGridConfiguration, + RowColumnIndex(rowIndex, columnIndex), + ); return dataGridConfiguration.onCurrentCellActivating!( - newRowColumnIndex, oldRowColumnIndex); + newRowColumnIndex, + oldRowColumnIndex, + ); } void _raiseCurrentCellActivated(RowColumnIndex previousRowColumnIndex) { @@ -1702,32 +2028,48 @@ class CurrentCellManager { return; } - final RowColumnIndex newRowColumnIndex = - grid_helper.resolveToRecordRowColumnIndex( - dataGridConfiguration, RowColumnIndex(rowIndex, columnIndex)); - final RowColumnIndex oldRowColumnIndex = - grid_helper.resolveToRecordRowColumnIndex( - dataGridConfiguration, previousRowColumnIndex); + final RowColumnIndex newRowColumnIndex = grid_helper + .resolveToRecordRowColumnIndex( + dataGridConfiguration, + RowColumnIndex(rowIndex, columnIndex), + ); + final RowColumnIndex oldRowColumnIndex = grid_helper + .resolveToRecordRowColumnIndex( + dataGridConfiguration, + previousRowColumnIndex, + ); dataGridConfiguration.onCurrentCellActivated!( - newRowColumnIndex, oldRowColumnIndex); + newRowColumnIndex, + oldRowColumnIndex, + ); } - void _moveCurrentCellTo(DataGridConfiguration dataGridConfiguration, - RowColumnIndex nextRowColumnIndex, - {bool isSelectionChanged = false, bool needToUpdateColumn = true}) { + void _moveCurrentCellTo( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex nextRowColumnIndex, { + bool isSelectionChanged = false, + bool needToUpdateColumn = true, + }) { final RowColumnIndex previousRowColumnIndex = RowColumnIndex( - dataGridConfiguration.currentCell.rowIndex, - dataGridConfiguration.currentCell.columnIndex); + dataGridConfiguration.currentCell.rowIndex, + dataGridConfiguration.currentCell.columnIndex, + ); _scrollVertical(dataGridConfiguration, nextRowColumnIndex); _scrollHorizontal(dataGridConfiguration, nextRowColumnIndex); if (dataGridConfiguration.navigationMode == GridNavigationMode.cell) { - _setCurrentCell(dataGridConfiguration, nextRowColumnIndex.rowIndex, - nextRowColumnIndex.columnIndex, needToUpdateColumn); + _setCurrentCell( + dataGridConfiguration, + nextRowColumnIndex.rowIndex, + nextRowColumnIndex.columnIndex, + needToUpdateColumn, + ); } else { _updateCurrentRowColumnIndex( - nextRowColumnIndex.rowIndex, nextRowColumnIndex.columnIndex); + nextRowColumnIndex.rowIndex, + nextRowColumnIndex.columnIndex, + ); } if (dataGridConfiguration.selectionMode != SelectionMode.none && @@ -1738,95 +2080,131 @@ class CurrentCellManager { if (rowSelectionController is RowSelectionManager) { rowSelectionController .._processSelection( - dataGridConfiguration, nextRowColumnIndex, previousRowColumnIndex) + dataGridConfiguration, + nextRowColumnIndex, + previousRowColumnIndex, + ) .._pressedRowColumnIndex = nextRowColumnIndex; } } } - void _processCurrentCell(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex, - {bool isSelectionChanged = false}) { + void _processCurrentCell( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, { + bool isSelectionChanged = false, + }) { if (dataGridConfiguration.navigationMode == GridNavigationMode.row) { - _moveCurrentCellTo(dataGridConfiguration, rowColumnIndex, - isSelectionChanged: isSelectionChanged); + _moveCurrentCellTo( + dataGridConfiguration, + rowColumnIndex, + isSelectionChanged: isSelectionChanged, + ); return; } if (_raiseCurrentCellActivating(rowColumnIndex)) { - _moveCurrentCellTo(dataGridConfiguration, rowColumnIndex, - isSelectionChanged: isSelectionChanged); + _moveCurrentCellTo( + dataGridConfiguration, + rowColumnIndex, + isSelectionChanged: isSelectionChanged, + ); _raiseCurrentCellActivated(rowColumnIndex); } } - void _scrollHorizontal(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { + void _scrollHorizontal( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, + ) { if (rowColumnIndex.columnIndex < columnIndex) { if (selection_helper.needToScrollLeft( - dataGridConfiguration, rowColumnIndex)) { - selection_helper.scrollInViewFromRight(dataGridConfiguration, - previousCellIndex: rowColumnIndex.columnIndex); + dataGridConfiguration, + rowColumnIndex, + )) { + selection_helper.scrollInViewFromRight( + dataGridConfiguration, + previousCellIndex: rowColumnIndex.columnIndex, + ); } } if (rowColumnIndex.columnIndex > columnIndex) { if (selection_helper.needToScrollRight( - dataGridConfiguration, rowColumnIndex)) { - selection_helper.scrollInViewFromLeft(dataGridConfiguration, - nextCellIndex: rowColumnIndex.columnIndex); + dataGridConfiguration, + rowColumnIndex, + )) { + selection_helper.scrollInViewFromLeft( + dataGridConfiguration, + nextCellIndex: rowColumnIndex.columnIndex, + ); } } } - void _scrollVertical(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex) { + void _scrollVertical( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, + ) { if (rowColumnIndex.rowIndex < rowIndex) { if (selection_helper.needToScrollUp( - dataGridConfiguration, rowColumnIndex.rowIndex)) { - selection_helper.scrollInViewFromDown(dataGridConfiguration, - previousRowIndex: rowColumnIndex.rowIndex); + dataGridConfiguration, + rowColumnIndex.rowIndex, + )) { + selection_helper.scrollInViewFromDown( + dataGridConfiguration, + previousRowIndex: rowColumnIndex.rowIndex, + ); } } if (rowColumnIndex.rowIndex > rowIndex) { if (selection_helper.needToScrollDown( - dataGridConfiguration, rowColumnIndex.rowIndex)) { - selection_helper.scrollInViewFromTop(dataGridConfiguration, - nextRowIndex: rowColumnIndex.rowIndex); + dataGridConfiguration, + rowColumnIndex.rowIndex, + )) { + selection_helper.scrollInViewFromTop( + dataGridConfiguration, + nextRowIndex: rowColumnIndex.rowIndex, + ); } } } void _updateBorderForMultipleSelection( - DataGridConfiguration dataGridConfiguration, - {RowColumnIndex? previousRowColumnIndex, - RowColumnIndex? nextRowColumnIndex}) { + DataGridConfiguration dataGridConfiguration, { + RowColumnIndex? previousRowColumnIndex, + RowColumnIndex? nextRowColumnIndex, + }) { if (dataGridConfiguration.isDesktop && dataGridConfiguration.navigationMode == GridNavigationMode.row && dataGridConfiguration.selectionMode == SelectionMode.multiple) { if (previousRowColumnIndex != null) { - dataGridConfiguration.currentCell + dataGridConfiguration + .currentCell ._getDataRow(dataGridConfiguration, previousRowColumnIndex.rowIndex) ?.isDirty = true; } if (nextRowColumnIndex != null) { - final int firstVisibleColumnIndex = - grid_helper.resolveToStartColumnIndex(dataGridConfiguration); + final int firstVisibleColumnIndex = grid_helper + .resolveToStartColumnIndex(dataGridConfiguration); _updateCurrentRowColumnIndex( - nextRowColumnIndex.rowIndex >= 0 - ? nextRowColumnIndex.rowIndex - : rowIndex, - nextRowColumnIndex.columnIndex >= 0 - ? nextRowColumnIndex.columnIndex - : firstVisibleColumnIndex); - dataGridConfiguration.currentCell + nextRowColumnIndex.rowIndex >= 0 + ? nextRowColumnIndex.rowIndex + : rowIndex, + nextRowColumnIndex.columnIndex >= 0 + ? nextRowColumnIndex.columnIndex + : firstVisibleColumnIndex, + ); + dataGridConfiguration + .currentCell ._getDataRow( - dataGridConfiguration, - nextRowColumnIndex.rowIndex >= 0 - ? nextRowColumnIndex.rowIndex - : rowIndex) + dataGridConfiguration, + nextRowColumnIndex.rowIndex >= 0 + ? nextRowColumnIndex.rowIndex + : rowIndex, + ) ?.isDirty = true; } } @@ -1834,14 +2212,16 @@ class CurrentCellManager { // ------------------------------Editing------------------------------------- /// Called when the editing is begin to the data cell. - void onCellBeginEdit( - {DataCellBase? editingDataCell, - RowColumnIndex? editingRowColumnIndex, - bool isProgrammatic = false, - bool needToResolveIndex = true}) { + void onCellBeginEdit({ + DataCellBase? editingDataCell, + RowColumnIndex? editingRowColumnIndex, + bool isProgrammatic = false, + bool needToResolveIndex = true, + }) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); - final bool checkEditingIsEnabled = dataGridConfiguration.allowEditing && + final bool checkEditingIsEnabled = + dataGridConfiguration.allowEditing && dataGridConfiguration.selectionMode != SelectionMode.none && dataGridConfiguration.navigationMode != GridNavigationMode.row; @@ -1872,10 +2252,13 @@ class CurrentCellManager { // When editing is initiate from the f2 key, we need not to to resolve // the editing row column index because its already resolved based on the // SfDataGrid. - editingRowColumnIndex = needToResolveIndex - ? grid_helper.resolveToRowColumnIndex( - dataGridConfiguration, editingRowColumnIndex) - : editingRowColumnIndex; + editingRowColumnIndex = + needToResolveIndex + ? grid_helper.resolveToRowColumnIndex( + dataGridConfiguration, + editingRowColumnIndex, + ) + : editingRowColumnIndex; if (editingRowColumnIndex.rowIndex.isNegative || editingRowColumnIndex.columnIndex.isNegative || @@ -1891,13 +2274,18 @@ class CurrentCellManager { // update the current cell here for programmatic and F2 key to begin edit // the cell. void setCurrentCell() { - final DataRowBase? dataRow = - _getDataRow(dataGridConfiguration, editingRowColumnIndex!.rowIndex); + final DataRowBase? dataRow = _getDataRow( + dataGridConfiguration, + editingRowColumnIndex!.rowIndex, + ); if (dataRow != null) { dataCell = _getDataCell( - dataRow, - grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, editingRowColumnIndex.columnIndex)); + dataRow, + grid_helper.resolveToScrollColumnIndex( + dataGridConfiguration, + editingRowColumnIndex.columnIndex, + ), + ); } else { return; } @@ -1907,12 +2295,15 @@ class CurrentCellManager { // handleTap. if (needToResolveIndex) { if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - editingRowColumnIndex.columnIndex = - grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, editingRowColumnIndex.columnIndex); + editingRowColumnIndex.columnIndex = grid_helper + .resolveToScrollColumnIndex( + dataGridConfiguration, + editingRowColumnIndex.columnIndex, + ); } - dataGridConfiguration.rowSelectionManager - .handleTap(editingRowColumnIndex); + dataGridConfiguration.rowSelectionManager.handleTap( + editingRowColumnIndex, + ); // In programmatic begin edit, if the `editingRowColumnIndex` has valid // row and column index and the current cell has a previous current cell @@ -1920,7 +2311,8 @@ class CurrentCellManager { // `editingRowColumnIndex` property. if (dataCell != null && !editingRowColumnIndex.equals( - RowColumnIndex(dataCell!.rowIndex, dataCell!.columnIndex))) { + RowColumnIndex(dataCell!.rowIndex, dataCell!.columnIndex), + )) { setCurrentCell(); } } else { @@ -1937,8 +2329,9 @@ class CurrentCellManager { } editingRowColumnIndex = grid_helper.resolveToRecordRowColumnIndex( - dataGridConfiguration, - RowColumnIndex(editingDataCell!.rowIndex, editingDataCell.columnIndex)); + dataGridConfiguration, + RowColumnIndex(editingDataCell!.rowIndex, editingDataCell.columnIndex), + ); if (editingRowColumnIndex.rowIndex.isNegative || editingRowColumnIndex.columnIndex.isNegative) { @@ -1946,7 +2339,10 @@ class CurrentCellManager { } final bool beginEdit = _raiseCellBeginEdit( - dataGridConfiguration, editingRowColumnIndex, editingDataCell); + dataGridConfiguration, + editingRowColumnIndex, + editingDataCell, + ); if (beginEdit) { Future submitCell() async { @@ -1954,10 +2350,11 @@ class CurrentCellManager { } final Widget? child = dataGridConfiguration.source.buildEditWidget( - editingDataCell.dataRow!.dataGridRow!, - editingRowColumnIndex, - editingDataCell.gridColumn!, - submitCell); + editingDataCell.dataRow!.dataGridRow!, + editingRowColumnIndex, + editingDataCell.gridColumn!, + submitCell, + ); /// If child is null, we will not initiate the editing if (child != null) { @@ -1966,39 +2363,49 @@ class CurrentCellManager { /// canRequestFocus need to set true to auto detect the focus /// User need to set the autoFocus to true in their editable widget. editingDataCell.editingWidget = FocusScope( - canRequestFocus: true, - node: _focusScopeNode, - onFocusChange: (bool details) async { - /// We should not allow the focus to the other widgets - /// when the cell is in the edit mode and return false from the canSubmitCell - /// So, we need to request the focus here. - /// Also, if we return false from the canSubmitCell method and tap other cells - /// We need to retain the focus on the text field instead of losing focus. - /// - // Issue: - // FLUT-7120-The focus did not go to the other widgets when DataGrid's current cell is in edit mode. - // We have checked whether the current cell is editing or not based on the `isCurrentCellInEditing` property. - // In this case, it is true. So we fixed it by checking the value of the `canCellSubmit` method. - if (!_focusScopeNode.hasFocus && - !dataGridConfiguration.dataGridFocusNode!.hasFocus && - !await canSubmitCell(dataGridConfiguration)) { - _focusScopeNode.requestFocus(); - } - }, - child: child); + canRequestFocus: true, + node: _focusScopeNode, + onFocusChange: (bool details) async { + /// We should not allow the focus to the other widgets + /// when the cell is in the edit mode and return false from the canSubmitCell + /// So, we need to request the focus here. + /// Also, if we return false from the canSubmitCell method and tap other cells + /// We need to retain the focus on the text field instead of losing focus. + /// + // Issue: + // FLUT-7120-The focus did not go to the other widgets when DataGrid's current cell is in edit mode. + // We have checked whether the current cell is editing or not based on the `isCurrentCellInEditing` property. + // In this case, it is true. So we fixed it by checking the value of the `canCellSubmit` method. + if (!_focusScopeNode.hasFocus && + !dataGridConfiguration.dataGridFocusNode!.hasFocus && + !await canSubmitCell(dataGridConfiguration)) { + _focusScopeNode.requestFocus(); + } + }, + child: child, + ); editingDataCell.isEditing = editingDataCell.dataRow!.isEditing = isEditing = true; - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - rowColumnIndex: editingRowColumnIndex, propertyName: 'editing'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + rowColumnIndex: editingRowColumnIndex, + propertyName: 'editing', + ); } } } - bool _raiseCellBeginEdit(DataGridConfiguration dataGridConfiguration, - RowColumnIndex rowColumnIndex, DataCellBase dataCell) { + bool _raiseCellBeginEdit( + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, + DataCellBase dataCell, + ) { return dataGridConfiguration.source.onCellBeginEdit( - dataCell.dataRow!.dataGridRow!, rowColumnIndex, dataCell.gridColumn!); + dataCell.dataRow!.dataGridRow!, + rowColumnIndex, + dataCell.gridColumn!, + ); } /// Help to end-edit editable widget and refresh the [DataGridCell]. @@ -2022,10 +2429,12 @@ class CurrentCellManager { /// 1) _onCellSubmit is call from handleDataGridSource we no need to call the /// _notifyDataGridPropertyChangeListeners to refresh twice.By, set value false /// it will skip the refreshing. - Future onCellSubmit(DataGridConfiguration dataGridConfiguration, - {bool isCellCancelEdit = false, - bool cancelCanSubmitCell = false, - bool canRefresh = true}) async { + Future onCellSubmit( + DataGridConfiguration dataGridConfiguration, { + bool isCellCancelEdit = false, + bool cancelCanSubmitCell = false, + bool canRefresh = true, + }) async { if (!isEditing) { return; } @@ -2044,8 +2453,9 @@ class CurrentCellManager { if (isEditing) { RowColumnIndex rowColumnIndex = grid_helper.resolveToRecordRowColumnIndex( - dataGridConfiguration, - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex)); + dataGridConfiguration, + RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + ); if (rowColumnIndex.rowIndex.isNegative || rowColumnIndex.columnIndex.isNegative) { @@ -2067,28 +2477,42 @@ class CurrentCellManager { /// moving to other cell or another row. so we need to skip the /// canCellSubmit method calling once again if (!cancelCanSubmitCell) { - canSubmitCell = await dataGridConfiguration.source - .canSubmitCell(dataGridRow, rowColumnIndex, dataCell.gridColumn!); + canSubmitCell = await dataGridConfiguration.source.canSubmitCell( + dataGridRow, + rowColumnIndex, + dataCell.gridColumn!, + ); } else { canSubmitCell = true; } if (canSubmitCell) { resetEditing(); - await dataGridConfiguration.source - .onCellSubmit(dataGridRow, rowColumnIndex, dataCell.gridColumn!); + await dataGridConfiguration.source.onCellSubmit( + dataGridRow, + rowColumnIndex, + dataCell.gridColumn!, + ); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - rowColumnIndex: rowColumnIndex, propertyName: 'editing'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + rowColumnIndex: rowColumnIndex, + propertyName: 'editing', + ); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { updateDataSource(dataGridConfiguration.source, true); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } } else { resetEditing(); dataGridConfiguration.source.onCellCancelEdit( - dataGridRow, rowColumnIndex, dataCell.gridColumn!); + dataGridRow, + rowColumnIndex, + dataCell.gridColumn!, + ); } if (canRefresh) { @@ -2097,13 +2521,16 @@ class CurrentCellManager { if (dataGridConfiguration.allowSorting || dataGridConfiguration.allowFiltering) { final DataGridRow? row = grid_helper.getDataRow( - dataGridConfiguration, rowColumnIndex.rowIndex); + dataGridConfiguration, + rowColumnIndex.rowIndex, + ); if (row == null) { return; } updateDataSource(dataGridConfiguration.source); - final int rowIndex = - effectiveRows(dataGridConfiguration.source).indexOf(row); + final int rowIndex = effectiveRows( + dataGridConfiguration.source, + ).indexOf(row); rowColumnIndex = RowColumnIndex(rowIndex, rowColumnIndex.columnIndex); if (dataGridConfiguration.source.filterConditions.isNotEmpty) { dataGridConfiguration.container.updateRowAndColumnCount(); @@ -2113,8 +2540,11 @@ class CurrentCellManager { ..isDirty = true; } - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - rowColumnIndex: rowColumnIndex, propertyName: 'editing'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + rowColumnIndex: rowColumnIndex, + propertyName: 'editing', + ); } // Allow focus only if any data cell is in editing state and the @@ -2128,18 +2558,21 @@ class CurrentCellManager { } DataRowBase? _getEditingRow(DataGridConfiguration dataGridConfiguration) { - return dataGridConfiguration.rowGenerator.items - .firstWhereOrNull((DataRowBase dataRow) => dataRow.isEditing); + return dataGridConfiguration.rowGenerator.items.firstWhereOrNull( + (DataRowBase dataRow) => dataRow.isEditing, + ); } DataCellBase? _getEditingCell(DataRowBase dataRow) { - return dataRow.visibleColumns - .firstWhereOrNull((DataCellBase dataCell) => dataCell.isEditing); + return dataRow.visibleColumns.firstWhereOrNull( + (DataCellBase dataCell) => dataCell.isEditing, + ); } /// Called when the editing is submitted in the data cell. Future canSubmitCell( - DataGridConfiguration dataGridConfiguration) async { + DataGridConfiguration dataGridConfiguration, + ) async { final DataRowBase? dataRow = _getEditingRow(dataGridConfiguration); if (dataRow == null) { @@ -2152,9 +2585,11 @@ class CurrentCellManager { return false; } - final RowColumnIndex rowColumnIndex = - grid_helper.resolveToRecordRowColumnIndex(dataGridConfiguration, - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex)); + final RowColumnIndex rowColumnIndex = grid_helper + .resolveToRecordRowColumnIndex( + dataGridConfiguration, + RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + ); if (rowColumnIndex.rowIndex.isNegative || rowColumnIndex.columnIndex.isNegative) { @@ -2163,14 +2598,20 @@ class CurrentCellManager { final DataGridRow dataGridRow = dataCell.dataRow!.dataGridRow!; - return dataGridConfiguration.source - .canSubmitCell(dataGridRow, rowColumnIndex, dataCell.gridColumn!); + return dataGridConfiguration.source.canSubmitCell( + dataGridRow, + rowColumnIndex, + dataCell.gridColumn!, + ); } } /// -void onRowColumnChanged(DataGridConfiguration dataGridConfiguration, - int recordLength, int columnLength) { +void onRowColumnChanged( + DataGridConfiguration dataGridConfiguration, + int recordLength, + int columnLength, +) { if (dataGridConfiguration.rowSelectionManager is RowSelectionManager) { final RowSelectionManager rowSelectionManager = dataGridConfiguration.rowSelectionManager as RowSelectionManager; @@ -2185,8 +2626,9 @@ void removeUnWantedDataGridRows(DataGridConfiguration dataGridConfiguration) { final List duplicateSelectedRows = rowSelectionManager._selectedRows.toList(); for (final DataGridRow selectedRow in duplicateSelectedRows) { - final int rowIndex = - effectiveRows(dataGridConfiguration.source).indexOf(selectedRow); + final int rowIndex = effectiveRows( + dataGridConfiguration.source, + ).indexOf(selectedRow); if (rowIndex.isNegative) { rowSelectionManager._selectedRows.remove(selectedRow); dataGridConfiguration.controller.selectedRows.remove(selectedRow); @@ -2195,53 +2637,65 @@ void removeUnWantedDataGridRows(DataGridConfiguration dataGridConfiguration) { } /// -void handleSelectionPropertyChanged( - {required DataGridConfiguration dataGridConfiguration, - RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight = false}) { +void handleSelectionPropertyChanged({ + required DataGridConfiguration dataGridConfiguration, + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight = false, +}) { if (dataGridConfiguration.rowSelectionManager is RowSelectionManager) { final RowSelectionManager rowSelectionManager = dataGridConfiguration.rowSelectionManager as RowSelectionManager; rowSelectionManager._handleSelectionPropertyChanged( - propertyName: propertyName, - rowColumnIndex: rowColumnIndex, - recalculateRowHeight: recalculateRowHeight); + propertyName: propertyName, + rowColumnIndex: rowColumnIndex, + recalculateRowHeight: recalculateRowHeight, + ); } } /// -void updateSelectionController( - {required DataGridConfiguration dataGridConfiguration, - bool isSelectionModeChanged = false, - bool isNavigationModeChanged = false, - bool isDataSourceChanged = false}) { +void updateSelectionController({ + required DataGridConfiguration dataGridConfiguration, + bool isSelectionModeChanged = false, + bool isNavigationModeChanged = false, + bool isDataSourceChanged = false, +}) { if (dataGridConfiguration.rowSelectionManager is RowSelectionManager) { final RowSelectionManager rowSelectionManager = dataGridConfiguration.rowSelectionManager as RowSelectionManager; rowSelectionManager._updateSelectionController( - isDataSourceChanged: isDataSourceChanged, - isNavigationModeChanged: isNavigationModeChanged, - isSelectionModeChanged: isSelectionModeChanged); + isDataSourceChanged: isDataSourceChanged, + isNavigationModeChanged: isNavigationModeChanged, + isSelectionModeChanged: isSelectionModeChanged, + ); } } /// Ensures the selection and current cell update in the [RowSelectionManager]. void processSelectionAndCurrentCell( - DataGridConfiguration dataGridConfiguration, RowColumnIndex rowColumnIndex, - {bool isShiftKeyPressed = false, bool isProgrammatic = false}) { + DataGridConfiguration dataGridConfiguration, + RowColumnIndex rowColumnIndex, { + bool isShiftKeyPressed = false, + bool isProgrammatic = false, +}) { if (dataGridConfiguration.rowSelectionManager is RowSelectionManager) { final RowSelectionManager rowSelectionManager = dataGridConfiguration.rowSelectionManager as RowSelectionManager; rowSelectionManager._processSelectionAndCurrentCell( - dataGridConfiguration, rowColumnIndex, - isShiftKeyPressed: isShiftKeyPressed, isProgrammatic: isProgrammatic); + dataGridConfiguration, + rowColumnIndex, + isShiftKeyPressed: isShiftKeyPressed, + isProgrammatic: isProgrammatic, + ); } } /// Need to clarify bool isSelectedRow( - DataGridConfiguration dataGridConfiguration, DataGridRow dataGridRow) { + DataGridConfiguration dataGridConfiguration, + DataGridRow dataGridRow, +) { if (dataGridConfiguration.rowSelectionManager is RowSelectionManager) { final RowSelectionManager rowSelectionManager = dataGridConfiguration.rowSelectionManager as RowSelectionManager; @@ -2253,15 +2707,20 @@ bool isSelectedRow( /// Set the DataGridStateDetails in SelectionManagerBase void setStateDetailsInSelectionManagerBase( - SelectionManagerBase selectionManagerBase, - DataGridStateDetails dataGridStateDetails) { + SelectionManagerBase selectionManagerBase, + DataGridStateDetails dataGridStateDetails, +) { selectionManagerBase._dataGridStateDetails = dataGridStateDetails; } /// Helps to handle the selection from header and grid cell check box /// interaction. -void handleSelectionFromCheckbox(DataGridConfiguration dataGridConfiguration, - DataCellBase dataCell, bool? oldValue, bool? newValue) { +void handleSelectionFromCheckbox( + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, + bool? oldValue, + bool? newValue, +) { if (dataGridConfiguration.rowSelectionManager is RowSelectionManager && dataGridConfiguration.selectionMode != SelectionMode.none) { final RowSelectionManager rowSelectionManager = @@ -2294,7 +2753,9 @@ void handleSelectionFromCheckbox(DataGridConfiguration dataGridConfiguration, final List oldSelectedItems = rowSelectionManager._selectedRows.toList(); if (rowSelectionManager._raiseSelectionChanging( - newItems: [], oldItems: oldSelectedItems)) { + newItems: [], + oldItems: oldSelectedItems, + )) { rowSelectionManager._shiftSelectedRows.clear(); rowSelectionManager._pressedRowIndex = -1; rowSelectionManager._clearSelectedRows(dataGridConfiguration); @@ -2305,7 +2766,9 @@ void handleSelectionFromCheckbox(DataGridConfiguration dataGridConfiguration, ); rowSelectionManager._refreshCheckboxSelection(); rowSelectionManager._raiseSelectionChanged( - oldItems: oldSelectedItems, newItems: []); + oldItems: oldSelectedItems, + newItems: [], + ); } // Cleared the oldSelectedItems list after the callback is called. oldSelectedItems.clear(); @@ -2324,9 +2787,10 @@ void refreshSelectedRows(DataGridConfiguration dataGridConfiguration) { if (dataGridConfiguration.selectionMode != SelectionMode.none && rowSelectionManager._selectedRows.isNotEmpty) { // Filter selected rows to include only those that exist in effectiveRows. - List selectedRows = rowSelectionManager._selectedRows - .where(dataGridConfiguration.source.effectiveRows.contains) - .toList(); + List selectedRows = + rowSelectionManager._selectedRows + .where(dataGridConfiguration.source.effectiveRows.contains) + .toList(); /// When changing the selection mode to single-row selection after filtering, /// we need to retain only the last selected row. diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/sfdatagrid.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/sfdatagrid.dart index 43f3cd561..46ee012b7 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/sfdatagrid.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/sfdatagrid.dart @@ -22,112 +22,130 @@ import 'widgets/scrollview_widget.dart'; typedef QueryRowHeightCallback = double Function(RowHeightDetails details); /// Signature for [SfDataGrid.onSelectionChanging] callback. -typedef SelectionChangingCallback = bool Function( - List addedRows, List removedRows); +typedef SelectionChangingCallback = + bool Function(List addedRows, List removedRows); /// Signature for [SfDataGrid.onSelectionChanged] callback. -typedef SelectionChangedCallback = void Function( - List addedRows, List removedRows); +typedef SelectionChangedCallback = + void Function(List addedRows, List removedRows); /// Signature for [SfDataGrid.onCheckboxValueChanged] callback. -typedef DataGridCheckboxValueChangedCallback = void Function( - DataGridCheckboxValueChangedDetails details); +typedef DataGridCheckboxValueChangedCallback = + void Function(DataGridCheckboxValueChangedDetails details); /// Signature for [SfDataGrid.onColumnSortChanging] callback. -typedef DataGridColumnSortChangingCallback = bool Function( - SortColumnDetails? newSortedColumn, SortColumnDetails? oldSortedColumn); +typedef DataGridColumnSortChangingCallback = + bool Function( + SortColumnDetails? newSortedColumn, + SortColumnDetails? oldSortedColumn, + ); /// Signature for [SfDataGrid.onColumnSortChanged] callback. -typedef DataGridColumnSortChangedCallback = void Function( - SortColumnDetails? newSortedColumn, SortColumnDetails? oldSortedColumn); +typedef DataGridColumnSortChangedCallback = + void Function( + SortColumnDetails? newSortedColumn, + SortColumnDetails? oldSortedColumn, + ); /// Signature for [SfDataGrid.onCurrentCellActivating] callback. -typedef CurrentCellActivatingCallback = bool Function( - RowColumnIndex newRowColumnIndex, RowColumnIndex oldRowColumnIndex); +typedef CurrentCellActivatingCallback = + bool Function( + RowColumnIndex newRowColumnIndex, + RowColumnIndex oldRowColumnIndex, + ); /// Signature for [SfDataGrid.onCurrentCellActivated] callback. -typedef CurrentCellActivatedCallback = void Function( - RowColumnIndex newRowColumnIndex, RowColumnIndex oldRowColumnIndex); +typedef CurrentCellActivatedCallback = + void Function( + RowColumnIndex newRowColumnIndex, + RowColumnIndex oldRowColumnIndex, + ); /// Signature for [SfDataGrid.onCellTap] and [SfDataGrid.onCellSecondaryTap] /// callbacks. typedef DataGridCellTapCallback = void Function(DataGridCellTapDetails details); /// Signature for [SfDataGrid.onCellDoubleTap] callback. -typedef DataGridCellDoubleTapCallback = void Function( - DataGridCellDoubleTapDetails details); +typedef DataGridCellDoubleTapCallback = + void Function(DataGridCellDoubleTapDetails details); /// Signature for [SfDataGrid.onCellLongPress] callback. -typedef DataGridCellLongPressCallback = void Function( - DataGridCellLongPressDetails details); +typedef DataGridCellLongPressCallback = + void Function(DataGridCellLongPressDetails details); /// The signature of [DataGridSource.handleLoadMoreRows] function. typedef LoadMoreRows = Future Function(); /// Signature for the [SfDataGrid.loadMoreViewBuilder] function. -typedef LoadMoreViewBuilder = Widget? Function( - BuildContext context, LoadMoreRows loadMoreRows); +typedef LoadMoreViewBuilder = + Widget? Function(BuildContext context, LoadMoreRows loadMoreRows); /// Signature for the [SfDataGrid.onSwipeStart] callback. -typedef DataGridSwipeStartCallback = bool Function( - DataGridSwipeStartDetails swipeStartDetails); +typedef DataGridSwipeStartCallback = + bool Function(DataGridSwipeStartDetails swipeStartDetails); /// Signature for the [SfDataGrid.onSwipeUpdate] callback. -typedef DataGridSwipeUpdateCallback = bool Function( - DataGridSwipeUpdateDetails swipeUpdateDetails); +typedef DataGridSwipeUpdateCallback = + bool Function(DataGridSwipeUpdateDetails swipeUpdateDetails); /// Signature for the [SfDataGrid.onSwipeEnd] callback. -typedef DataGridSwipeEndCallback = void Function( - DataGridSwipeEndDetails swipeEndDetails); +typedef DataGridSwipeEndCallback = + void Function(DataGridSwipeEndDetails swipeEndDetails); /// Holds the arguments for the [SfDataGrid.startSwipeActionsBuilder] callback. -typedef DataGridSwipeActionsBuilder = Widget? Function( - BuildContext context, DataGridRow dataGridRow, int rowIndex); +typedef DataGridSwipeActionsBuilder = + Widget? Function( + BuildContext context, + DataGridRow dataGridRow, + int rowIndex, + ); /// The signature of [DataGridSource.canSubmitCell] and /// [DataGridSource.onCellSubmit] methods. typedef CellSubmit = void Function(); /// Signature for the [SfDataGrid.onColumnResizeStart] callback. -typedef ColumnResizeStartCallback = bool Function( - ColumnResizeStartDetails details); +typedef ColumnResizeStartCallback = + bool Function(ColumnResizeStartDetails details); /// Signature for the [SfDataGrid.onColumnResizeUpdate] callback. -typedef ColumnResizeUpdateCallback = bool Function( - ColumnResizeUpdateDetails details); +typedef ColumnResizeUpdateCallback = + bool Function(ColumnResizeUpdateDetails details); /// Signature for the [SfDataGrid.onColumnResizeEnd] callback. typedef ColumnResizeEndCallback = void Function(ColumnResizeEndDetails details); /// Signature for the [SfDataGrid.onFilterChanging] callback. -typedef DataGridFilterChangingCallback = bool Function( - DataGridFilterChangeDetails details); +typedef DataGridFilterChangingCallback = + bool Function(DataGridFilterChangeDetails details); /// Signature for the [SfDataGrid.onFilterChanged] callback. -typedef DataGridFilterChangedCallback = void Function( - DataGridFilterChangeDetails details); +typedef DataGridFilterChangedCallback = + void Function(DataGridFilterChangeDetails details); /// Signature for the [DataGridSourceChangeNotifier] listener. -typedef _DataGridSourceListener = void Function( - {RowColumnIndex? rowColumnIndex}); +typedef _DataGridSourceListener = + void Function({RowColumnIndex? rowColumnIndex}); /// Signature for the [DataGridSourceChangeNotifier] listener. -typedef _DataGridPropertyChangeListener = void Function( - {RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight}); +typedef _DataGridPropertyChangeListener = + void Function({ + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight, + }); /// Signature for [SfDataGrid.onColumnDragging] callback. -typedef DataGridColumnDraggingCallback = bool Function( - DataGridColumnDragDetails details); +typedef DataGridColumnDraggingCallback = + bool Function(DataGridColumnDragDetails details); /// Signature for [SfDataGrid. columnDragFeedbackBuilder] callback. -typedef ColumnDragFeedbackBuilderCallback = Widget Function( - BuildContext context, GridColumn column); +typedef ColumnDragFeedbackBuilderCallback = + Widget Function(BuildContext context, GridColumn column); /// Signature for [SfDataGrid.groupExpanding], [SfDataGrid.groupCollapsing], callbacks. -typedef GroupChangingCallback = bool Function( - DataGridGroupChangingDetails group); +typedef GroupChangingCallback = + bool Function(DataGridGroupChangingDetails group); /// Signature for [SfDataGrid.groupExpanded], [SfDataGrid.groupCollapsed] callbacks. typedef GroupChangedCallback = void Function(DataGridGroupChangedDetails group); @@ -218,8 +236,11 @@ class StackedHeaderRow { /// [StackedHeaderRow] – which provides configuration for stacked header row. class StackedHeaderCell { /// Creates the [StackedHeaderCell] for [StackedHeaderRow]. - StackedHeaderCell( - {this.text, required this.columnNames, required this.child}) { + StackedHeaderCell({ + this.text, + required this.columnNames, + required this.child, + }) { _childColumnIndexes = []; } @@ -264,14 +285,14 @@ class StackedHeaderCell { /// to DataGrid. class GridTableSummaryRow { /// Creates the [GridTableSummaryRow] to the [SfDataGrid]. - GridTableSummaryRow( - {this.title, - this.color, - required this.columns, - required this.position, - this.titleColumnSpan = 0, - this.showSummaryInRow = true}) - : assert(titleColumnSpan >= 0); + GridTableSummaryRow({ + this.title, + this.color, + required this.columns, + required this.position, + this.titleColumnSpan = 0, + this.showSummaryInRow = true, + }) : assert(titleColumnSpan >= 0); /// A string that has the format and summary column information to be /// displayed in row. @@ -311,10 +332,11 @@ class GridTableSummaryRow { /// * [GridTableSummaryRow] – Which provides configuration for table summary row. class GridSummaryColumn { /// Creates the [GridSummaryColumn] to the [GridTableSummaryRow]. - const GridSummaryColumn( - {required this.name, - required this.columnName, - required this.summaryType}); + const GridSummaryColumn({ + required this.name, + required this.columnName, + required this.summaryType, + }); /// Indicates the name of the summary column. final String name; @@ -507,11 +529,11 @@ class SfDataGrid extends StatefulWidget { this.groupCollapsing, this.groupCollapsed, this.groupCaptionTitleFormat = '{ColumnName} : {Key} - {ItemsCount} Items', - }) : assert(frozenColumnsCount >= 0), - assert(footerFrozenColumnsCount >= 0), - assert(frozenRowsCount >= 0), - assert(footerFrozenRowsCount >= 0), - super(key: key); + }) : assert(frozenColumnsCount >= 0), + assert(footerFrozenColumnsCount >= 0), + assert(frozenRowsCount >= 0), + assert(footerFrozenRowsCount >= 0), + super(key: key); /// The height of each row except the column header. /// @@ -1812,10 +1834,13 @@ class SfDataGridState extends State _rowGenerator = RowGenerator(dataGridStateDetails: _dataGridStateDetails!); _container = VisualContainerHelper( - rowGenerator: _rowGenerator, - dataGridStateDetails: _dataGridStateDetails!); + rowGenerator: _rowGenerator, + dataGridStateDetails: _dataGridStateDetails!, + ); _swipingAnimationController = AnimationController( - duration: const Duration(milliseconds: 200), vsync: this); + duration: const Duration(milliseconds: 200), + vsync: this, + ); _setUp(); _updateDataGridStateDetails(); @@ -1835,7 +1860,9 @@ class SfDataGridState extends State } void _onDataGridThemeDataChanged( - SfDataGridThemeData? newThemeData, SfColorScheme? newColorScheme) { + SfDataGridThemeData? newThemeData, + SfColorScheme? newColorScheme, + ) { // Refreshes the data grid rows when the `SfDataGridThemeData` or // `SfColorScheme.colorScheme` is changed at runtime. if (_dataGridThemeData == newThemeData && @@ -1872,16 +1899,18 @@ class SfDataGridState extends State } _dataGridConfiguration.textScaleFactor = textScaleFactor; - _dataGridConfiguration.headerRowHeight = widget.headerRowHeight.isNaN - ? (_dataGridConfiguration.textScaleFactor > 1.0) - ? _headerRowHeight * _dataGridConfiguration.textScaleFactor - : _headerRowHeight - : widget.headerRowHeight; - _dataGridConfiguration.rowHeight = widget.rowHeight.isNaN - ? (_dataGridConfiguration.textScaleFactor > 1.0) - ? _rowHeight * _dataGridConfiguration.textScaleFactor - : _rowHeight - : widget.rowHeight; + _dataGridConfiguration.headerRowHeight = + widget.headerRowHeight.isNaN + ? (_dataGridConfiguration.textScaleFactor > 1.0) + ? _headerRowHeight * _dataGridConfiguration.textScaleFactor + : _headerRowHeight + : widget.headerRowHeight; + _dataGridConfiguration.rowHeight = + widget.rowHeight.isNaN + ? (_dataGridConfiguration.textScaleFactor > 1.0) + ? _rowHeight * _dataGridConfiguration.textScaleFactor + : _rowHeight + : widget.rowHeight; // Refreshes the default line size, column widths and row heights in initial // `SfDataGrid` build. So, restricts the codes in initial loading by using // the `_container.isGridLoaded` property. @@ -1934,12 +1963,14 @@ class SfDataGridState extends State _initializeCellRendererCollection(); //DataGrid Controller - _controller = _dataGridConfiguration.controller = - widget.controller ?? DataGridController() - .._dataGridStateDetails = _dataGridStateDetails; + _controller = + _dataGridConfiguration.controller = + widget.controller ?? DataGridController() + .._dataGridStateDetails = _dataGridStateDetails; _controller!._addDataGridPropertyChangeListener( - _handleDataGridPropertyChangeListeners); + _handleDataGridPropertyChangeListeners, + ); if (widget.verticalScrollController != null) { _dataGridConfiguration.disposeVerticalScrollController = false; } @@ -1955,28 +1986,38 @@ class SfDataGridState extends State //AutoFit controller initializing _dataGridConfiguration.columnSizer = widget.columnSizer ?? ColumnSizer(); setStateDetailsInColumnSizer( - _dataGridConfiguration.columnSizer, _dataGridStateDetails!); + _dataGridConfiguration.columnSizer, + _dataGridStateDetails!, + ); //CurrentCell Manager initializing - _dataGridConfiguration.currentCell = - CurrentCellManager(_dataGridStateDetails!); - _dataGridConfiguration.dataGridFilterHelper = - DataGridFilterHelper(_dataGridStateDetails!); + _dataGridConfiguration.currentCell = CurrentCellManager( + _dataGridStateDetails!, + ); + _dataGridConfiguration.dataGridFilterHelper = DataGridFilterHelper( + _dataGridStateDetails!, + ); //Selection Manager initializing - _rowSelectionManager = _dataGridConfiguration.rowSelectionManager = - widget.selectionManager ?? RowSelectionManager(); + _rowSelectionManager = + _dataGridConfiguration.rowSelectionManager = + widget.selectionManager ?? RowSelectionManager(); selection_manager.setStateDetailsInSelectionManagerBase( - _rowSelectionManager!, _dataGridStateDetails!); + _rowSelectionManager!, + _dataGridStateDetails!, + ); - _controller! - ._addDataGridPropertyChangeListener(_handleSelectionPropertyChanged); + _controller!._addDataGridPropertyChangeListener( + _handleSelectionPropertyChanged, + ); - _dataGridConfiguration.columnResizeController = - ColumnResizeController(dataGridStateDetails: _dataGridStateDetails!); - _dataGridConfiguration.columnDragAndDropController = - ColumnDragAndDropController( - dataGridStateDetails: _dataGridStateDetails!); + _dataGridConfiguration.columnResizeController = ColumnResizeController( + dataGridStateDetails: _dataGridStateDetails!, + ); + _dataGridConfiguration + .columnDragAndDropController = ColumnDragAndDropController( + dataGridStateDetails: _dataGridStateDetails!, + ); // Grouping initializing _dataGridConfiguration.group = Group(); @@ -1994,8 +2035,9 @@ class SfDataGridState extends State void _refreshContainerAndView({bool isDataSourceChanged = false}) { if (isDataSourceChanged) { selection_manager.updateSelectionController( - dataGridConfiguration: _dataGridConfiguration, - isDataSourceChanged: isDataSourceChanged); + dataGridConfiguration: _dataGridConfiguration, + isDataSourceChanged: isDataSourceChanged, + ); } _ensureSelectionProperties(); @@ -2084,46 +2126,72 @@ class SfDataGridState extends State _cellRenderers = {}; _cellRenderers['TextField'] = GridCellTextFieldRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['TextField']!, _dataGridStateDetails!); + _cellRenderers['TextField']!, + _dataGridStateDetails!, + ); _cellRenderers['ColumnHeader'] = GridHeaderCellRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['ColumnHeader']!, _dataGridStateDetails!); + _cellRenderers['ColumnHeader']!, + _dataGridStateDetails!, + ); _cellRenderers['StackedHeader'] = GridStackedHeaderCellRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['StackedHeader']!, _dataGridStateDetails!); + _cellRenderers['StackedHeader']!, + _dataGridStateDetails!, + ); _cellRenderers['Checkbox'] = GridCheckboxRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['Checkbox']!, _dataGridStateDetails!); + _cellRenderers['Checkbox']!, + _dataGridStateDetails!, + ); _cellRenderers['TableSummary'] = GridTableSummaryCellRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['TableSummary']!, _dataGridStateDetails!); + _cellRenderers['TableSummary']!, + _dataGridStateDetails!, + ); _cellRenderers['CaptionSummary'] = GridCaptionSummaryCellRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['CaptionSummary']!, _dataGridStateDetails!); + _cellRenderers['CaptionSummary']!, + _dataGridStateDetails!, + ); _cellRenderers['IndentCell'] = GridIndentCellRenderer(); setStateDetailsInCellRendererBase( - _cellRenderers['IndentCell']!, _dataGridStateDetails!); + _cellRenderers['IndentCell']!, + _dataGridStateDetails!, + ); } - void _processCellUpdate(RowColumnIndex rowColumnIndex, - {bool canRefreshGrouping = false}) { + void _processCellUpdate( + RowColumnIndex rowColumnIndex, { + bool canRefreshGrouping = false, + }) { if (rowColumnIndex != RowColumnIndex(-1, -1)) { final bool isGrouping = _dataGridConfiguration.source.groupedColumns.isNotEmpty; int rowIndex = 0; final int columnIndex = grid_helper.resolveToScrollColumnIndex( - _dataGridConfiguration, rowColumnIndex.columnIndex); + _dataGridConfiguration, + rowColumnIndex.columnIndex, + ); if (isGrouping && canRefreshGrouping) { - final DataGridRow row = _dataGridConfiguration - .source.effectiveRows[rowColumnIndex.rowIndex]; - rowColumnIndex.rowIndex = - _dataGridConfiguration.group!.displayElements!.grouped.indexOf(row); - rowIndex = rowColumnIndex.rowIndex + - grid_helper - .resolveStartIndexBasedOnPosition(_dataGridConfiguration); + final DataGridRow row = + _dataGridConfiguration.source.effectiveRows[rowColumnIndex + .rowIndex]; + rowColumnIndex.rowIndex = _dataGridConfiguration + .group! + .displayElements! + .grouped + .indexOf(row); + rowIndex = + rowColumnIndex.rowIndex + + grid_helper.resolveStartIndexBasedOnPosition( + _dataGridConfiguration, + ); } else { rowIndex = grid_helper.resolveToRowIndex( - _dataGridConfiguration, rowColumnIndex.rowIndex); + _dataGridConfiguration, + rowColumnIndex.rowIndex, + ); } // Issue: @@ -2142,14 +2210,16 @@ class SfDataGridState extends State } final DataRowBase? dataRow = _rowGenerator.items.firstWhereOrNull( - (DataRowBase dataRow) => dataRow.rowIndex == rowIndex); + (DataRowBase dataRow) => dataRow.rowIndex == rowIndex, + ); if (dataRow == null) { return; } final DataCellBase? dataCell = dataRow.visibleColumns.firstWhereOrNull( - (DataCellBase dataCell) => dataCell.columnIndex == columnIndex); + (DataCellBase dataCell) => dataCell.columnIndex == columnIndex, + ); if (dataCell == null) { return; @@ -2168,13 +2238,17 @@ class SfDataGridState extends State // and we now retrieve the data grid row from the paginated effective rows // instead of the entire set of effective rows in the data grid final DataGridRow? row = grid_helper.getDataRow( - _dataGridConfiguration, rowColumnIndex.rowIndex); + _dataGridConfiguration, + rowColumnIndex.rowIndex, + ); if (row == null) { return; } dataRow.dataGridRow = row; dataRow.dataGridRowAdapter = grid_helper.getDataGridRowAdapter( - _dataGridConfiguration, dataRow.dataGridRow!); + _dataGridConfiguration, + dataRow.dataGridRow!, + ); if (mounted) { setState(() { @@ -2186,8 +2260,10 @@ class SfDataGridState extends State if (canRefreshGrouping && _dataGridConfiguration.source.groupedColumns.isNotEmpty) { updateDataSource(_dataGridConfiguration.source, true); - notifyDataGridPropertyChangeListeners(_dataGridStateDetails!().source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + _dataGridStateDetails!().source, + propertyName: 'grouping', + ); } } } @@ -2209,8 +2285,9 @@ class SfDataGridState extends State for (final GridTableSummaryRow tableSummaryRow in _dataGridConfiguration.tableSummaryRows) { final GridSummaryColumn? summaryColumn = tableSummaryRow.columns - .firstWhereOrNull((GridSummaryColumn column) => - column.columnName == columnName); + .firstWhereOrNull( + (GridSummaryColumn column) => column.columnName == columnName, + ); // Returns if the updated cell doesn't exist in the table summary row. if (summaryColumn == null) { return; @@ -2218,11 +2295,14 @@ class SfDataGridState extends State final DataRowBase? summaryDataRow = _rowGenerator.items .firstWhereOrNull( - (DataRowBase row) => row.tableSummaryRow == tableSummaryRow); + (DataRowBase row) => row.tableSummaryRow == tableSummaryRow, + ); if (summaryDataRow != null) { for (final DataCellBase column in summaryDataRow.visibleColumns) { final int titleColumnSpan = grid_helper.getSummaryTitleColumnSpan( - _dataGridConfiguration, tableSummaryRow); + _dataGridConfiguration, + tableSummaryRow, + ); if (tableSummaryRow.showSummaryInRow || (titleColumnSpan > 0 && column.columnIndex < titleColumnSpan)) { @@ -2252,7 +2332,9 @@ class SfDataGridState extends State if (_dataGridConfiguration.source.groupedColumns.isNotEmpty && _dataGridConfiguration.group!.displayElements == null) { _dataGridConfiguration.group?.initializeTopLevelGroup( - _dataGridConfiguration, _dataGridConfiguration.autoExpandGroups); + _dataGridConfiguration, + _dataGridConfiguration.autoExpandGroups, + ); } return; } @@ -2261,8 +2343,10 @@ class SfDataGridState extends State // Need to endEdit the editing [DataGridCell] before perform refreshing. if (_dataGridConfiguration.currentCell.isEditing) { - await _dataGridConfiguration.currentCell - .onCellSubmit(_dataGridConfiguration, canRefresh: false); + await _dataGridConfiguration.currentCell.onCellSubmit( + _dataGridConfiguration, + canRefresh: false, + ); } _initializeDataGridDataSource(); @@ -2275,7 +2359,10 @@ class SfDataGridState extends State widget.navigationMode == GridNavigationMode.cell && _rowSelectionManager != null) { selection_manager.onRowColumnChanged( - _dataGridConfiguration, widget.source._effectiveRows.length, -1); + _dataGridConfiguration, + widget.source._effectiveRows.length, + -1, + ); } if (!listEquals(_columns, widget.columns)) { @@ -2283,7 +2370,10 @@ class SfDataGridState extends State widget.navigationMode == GridNavigationMode.cell && _rowSelectionManager != null) { selection_manager.onRowColumnChanged( - _dataGridConfiguration, -1, widget.columns.length); + _dataGridConfiguration, + -1, + widget.columns.length, + ); } if (_dataGridConfiguration.showCheckboxColumn && _dataGridConfiguration.checkboxColumnSettings.showCheckboxOnHeader && @@ -2307,8 +2397,9 @@ class SfDataGridState extends State if (widget.footer != null) { final DataRowBase? footerRow = _rowGenerator.items.firstWhereOrNull( - (DataRowBase row) => - row.rowType == RowType.footerRow && row.rowIndex >= 0); + (DataRowBase row) => + row.rowType == RowType.footerRow && row.rowIndex >= 0, + ); if (footerRow != null) { // Need to reset the old footer row height in rowHeights collection. _container.rowHeights[footerRow.rowIndex] = @@ -2357,8 +2448,11 @@ class SfDataGridState extends State if (_dataGridConfiguration.horizontalScrollController != null && _dataGridConfiguration.horizontalScrollController!.hasClients && _dataGridConfiguration.horizontalScrollController!.offset == 0) { - final double maxScrollExtent = _dataGridConfiguration - .horizontalScrollController!.position.maxScrollExtent; + final double maxScrollExtent = + _dataGridConfiguration + .horizontalScrollController! + .position + .maxScrollExtent; if (_dataGridConfiguration.textDirection == TextDirection.ltr && _dataGridConfiguration.container.horizontalOffset > 0.0) { _dataGridConfiguration.container @@ -2398,16 +2492,19 @@ class SfDataGridState extends State return; } - final DataCellBase? dataCell = dataRow.visibleColumns - .firstWhereOrNull((DataCellBase dataCell) => dataCell.isEditing); + final DataCellBase? dataCell = dataRow.visibleColumns.firstWhereOrNull( + (DataCellBase dataCell) => dataCell.isEditing, + ); if (dataCell == null || !dataCell.isEditing) { return; } - final RowColumnIndex rowColumnIndex = - grid_helper.resolveToRecordRowColumnIndex(_dataGridConfiguration, - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex)); + final RowColumnIndex rowColumnIndex = grid_helper + .resolveToRecordRowColumnIndex( + _dataGridConfiguration, + RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + ); /// Issue: /// FLUT-6409 - Other cells are not moving into edit mode when removing @@ -2468,8 +2565,9 @@ class SfDataGridState extends State void _handleListeners() { // We have cleared the display elements to reinitialize the grouping and update the rows in the UI. if (_dataGridConfiguration.source.groupedColumns.isNotEmpty) { - _dataGridConfiguration.group! - .clearDisplayElements(_dataGridConfiguration); + _dataGridConfiguration.group!.clearDisplayElements( + _dataGridConfiguration, + ); } _processUpdateDataSource(); } @@ -2483,20 +2581,26 @@ class SfDataGridState extends State } } - Future _handleDataGridPropertyChangeListeners( - {RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight = false}) async { + Future _handleDataGridPropertyChangeListeners({ + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight = false, + }) async { if (propertyName == 'refreshRow') { if (rowColumnIndex != null) { // Need to endEdit before refreshing the row. - await _dataGridConfiguration.currentCell - .onCellSubmit(_dataGridConfiguration, canRefresh: false); + await _dataGridConfiguration.currentCell.onCellSubmit( + _dataGridConfiguration, + canRefresh: false, + ); final int rowIndex = grid_helper.resolveToRowIndex( - _dataGridConfiguration, rowColumnIndex.rowIndex); + _dataGridConfiguration, + rowColumnIndex.rowIndex, + ); final DataRowBase? dataRow = _rowGenerator.items.firstWhereOrNull( - (DataRowBase dataRow) => dataRow.rowIndex == rowIndex); + (DataRowBase dataRow) => dataRow.rowIndex == rowIndex, + ); if (dataRow == null) { return; @@ -2507,8 +2611,9 @@ class SfDataGridState extends State ..isDirty = true ..rowIndexChanged(); if (recalculateRowHeight) { - _dataGridConfiguration.container.rowHeightManager - .setDirty(rowIndex); + _dataGridConfiguration.container.rowHeightManager.setDirty( + rowIndex, + ); _dataGridConfiguration.container ..needToRefreshColumn = true ..setRowHeights(); @@ -2534,8 +2639,10 @@ class SfDataGridState extends State if (propertyName == 'Swiping') { // Need to end-edit the editing [DataGridCell] before swiping a // [DataGridRow] or refreshing - await _dataGridConfiguration.currentCell - .onCellSubmit(_dataGridConfiguration, canRefresh: false); + await _dataGridConfiguration.currentCell.onCellSubmit( + _dataGridConfiguration, + canRefresh: false, + ); _container.isDirty = true; if (mounted) { setState(() {}); @@ -2570,20 +2677,22 @@ class SfDataGridState extends State if (propertyName == 'columnDragAndDrop') { final DataRowBase? dataRow = _rowGenerator.items.firstWhereOrNull( - (DataRowBase dataRow) => dataRow.rowType == RowType.headerRow); + (DataRowBase dataRow) => dataRow.rowType == RowType.headerRow, + ); if (dataRow == null) { return; } if (_dataGridConfiguration - .columnDragAndDropController.canResetColumnWidthCalculation) { + .columnDragAndDropController + .canResetColumnWidthCalculation) { if (_dataGridConfiguration.columnWidthMode == ColumnWidthMode.lastColumnFill || _dataGridConfiguration.columns.firstWhereOrNull( - (GridColumn element) => - element.columnWidthMode == - ColumnWidthMode.lastColumnFill) != + (GridColumn element) => + element.columnWidthMode == ColumnWidthMode.lastColumnFill, + ) != null) { resetAutoCalculation(_dataGridConfiguration.columnSizer); } @@ -2673,19 +2782,22 @@ class SfDataGridState extends State ..onColumnResizeEnd = widget.onColumnResizeEnd ..editingGestureType = widget.editingGestureType ..allowEditing = widget.allowEditing - ..rowHeight = (widget.rowHeight.isNaN - ? _dataGridConfiguration.rowHeight.isNaN - ? _rowHeight - : _dataGridConfiguration.rowHeight - : widget.rowHeight) - ..headerRowHeight = (widget.headerRowHeight.isNaN - ? _dataGridConfiguration.headerRowHeight.isNaN - ? _headerRowHeight - : _dataGridConfiguration.headerRowHeight - : widget.headerRowHeight) - ..defaultColumnWidth = (widget.defaultColumnWidth.isNaN - ? _dataGridConfiguration.defaultColumnWidth - : widget.defaultColumnWidth) + ..rowHeight = + (widget.rowHeight.isNaN + ? _dataGridConfiguration.rowHeight.isNaN + ? _rowHeight + : _dataGridConfiguration.rowHeight + : widget.rowHeight) + ..headerRowHeight = + (widget.headerRowHeight.isNaN + ? _dataGridConfiguration.headerRowHeight.isNaN + ? _headerRowHeight + : _dataGridConfiguration.headerRowHeight + : widget.headerRowHeight) + ..defaultColumnWidth = + (widget.defaultColumnWidth.isNaN + ? _dataGridConfiguration.defaultColumnWidth + : widget.defaultColumnWidth) ..footer = widget.footer ..footerHeight = widget.footerHeight ..placeholder = widget.placeholder @@ -2747,44 +2859,49 @@ class SfDataGridState extends State // Fix: // we've taken out the count of checkboxes from the collection of internal columns. // This is done to prevent updating paginated rows before initializing the number of rows per page. - final int columnLength = _dataGridConfiguration.showCheckboxColumn - ? _columns!.length - 1 - : _columns!.length; + final int columnLength = + _dataGridConfiguration.showCheckboxColumn + ? _columns!.length - 1 + : _columns!.length; final bool isColumnsCollectionChanged = columnLength != widget.columns.length; final bool isSelectionManagerChanged = oldWidget.selectionManager != widget.selectionManager || - oldWidget.selectionMode != widget.selectionMode; + oldWidget.selectionMode != widget.selectionMode; final bool isColumnSizerChanged = oldWidget.columnSizer != widget.columnSizer || - oldWidget.columnWidthMode != widget.columnWidthMode || - oldWidget.columnWidthCalculationRange != - widget.columnWidthCalculationRange; + oldWidget.columnWidthMode != widget.columnWidthMode || + oldWidget.columnWidthCalculationRange != + widget.columnWidthCalculationRange; final bool isDataGridControllerChanged = oldWidget.controller != widget.controller; - final bool isFrozenColumnPaneChanged = oldWidget.frozenColumnsCount != - widget.frozenColumnsCount || + final bool isFrozenColumnPaneChanged = + oldWidget.frozenColumnsCount != widget.frozenColumnsCount || oldWidget.footerFrozenColumnsCount != widget.footerFrozenColumnsCount; final bool isFrozenRowPaneChanged = oldWidget.frozenRowsCount != widget.frozenRowsCount || - oldWidget.footerFrozenRowsCount != widget.footerFrozenRowsCount; + oldWidget.footerFrozenRowsCount != widget.footerFrozenRowsCount; final bool isSortingChanged = oldWidget.allowSorting != widget.allowSorting; final bool isMultiColumnSortingChanged = oldWidget.allowMultiColumnSorting != widget.allowMultiColumnSorting; final bool isShowSortNumbersChanged = oldWidget.showSortNumbers != widget.showSortNumbers; - final bool isStackedHeaderRowsChanged = !listEquals( - oldWidget.stackedHeaderRows, widget.stackedHeaderRows); + final bool isStackedHeaderRowsChanged = + !listEquals( + oldWidget.stackedHeaderRows, + widget.stackedHeaderRows, + ); final bool isPullToRefreshPropertiesChanged = oldWidget.allowPullToRefresh != widget.allowPullToRefresh || - oldWidget.refreshIndicatorDisplacement != - widget.refreshIndicatorDisplacement || - oldWidget.refreshIndicatorStrokeWidth != - widget.refreshIndicatorStrokeWidth; + oldWidget.refreshIndicatorDisplacement != + widget.refreshIndicatorDisplacement || + oldWidget.refreshIndicatorStrokeWidth != + widget.refreshIndicatorStrokeWidth; final bool isSwipingChanged = widget.allowSwiping != oldWidget.allowSwiping; final bool isMaxSwipeOffsetChanged = widget.swipeMaxOffset != oldWidget.swipeMaxOffset; - final bool isFooterRowChanged = widget.footer != oldWidget.footer || + final bool isFooterRowChanged = + widget.footer != oldWidget.footer || widget.footerHeight != oldWidget.footerHeight; final bool isTableSummaryRowsChanged = widget.tableSummaryRows != oldWidget.tableSummaryRows; @@ -2819,10 +2936,11 @@ class SfDataGridState extends State final bool isEditingChanged = oldWidget.allowEditing != widget.allowEditing || - oldWidget.editingGestureType != widget.editingGestureType; + oldWidget.editingGestureType != widget.editingGestureType; Future refreshEditing() async { - bool isEditingImpactAPIsChanged = isSourceChanged || + bool isEditingImpactAPIsChanged = + isSourceChanged || isDataSourceChanged || oldWidget.stackedHeaderRows.length != widget.stackedHeaderRows.length; @@ -2830,23 +2948,25 @@ class SfDataGridState extends State /// refreshing isEditingImpactAPIsChanged = (isSortingChanged || isMultiColumnSortingChanged) && - (oldWidget.source.sortedColumns.isNotEmpty || - widget.source.sortedColumns.isNotEmpty || - oldWidget.source.sortedColumns.length != - widget.source.sortedColumns.length); + (oldWidget.source.sortedColumns.isNotEmpty || + widget.source.sortedColumns.isNotEmpty || + oldWidget.source.sortedColumns.length != + widget.source.sortedColumns.length); if (isEditingChanged || isEditingImpactAPIsChanged || isSelectionManagerChanged || oldWidget.navigationMode != widget.navigationMode) { - isEditingImpactAPIsChanged = isEditingImpactAPIsChanged || + isEditingImpactAPIsChanged = + isEditingImpactAPIsChanged || isColumnsChanged || isStackedHeaderRowsChanged; if (_dataGridConfiguration.currentCell.isEditing) { await _dataGridConfiguration.currentCell.onCellSubmit( - _dataGridConfiguration, - canRefresh: !isEditingImpactAPIsChanged); + _dataGridConfiguration, + canRefresh: !isEditingImpactAPIsChanged, + ); } } } @@ -2854,8 +2974,9 @@ class SfDataGridState extends State void refreshFooterView() { if (oldWidget.footer != null) { final DataRowBase? footerRow = _rowGenerator.items.firstWhereOrNull( - (DataRowBase row) => - row.rowType == RowType.footerRow && row.rowIndex >= 0); + (DataRowBase row) => + row.rowType == RowType.footerRow && row.rowIndex >= 0, + ); if (footerRow != null) { if (isFooterRowChanged) { // Need to reset the old footer row height in rowHeights collection. @@ -2878,9 +2999,11 @@ class SfDataGridState extends State void refreshTableSummaryRows() { if (isTableSummaryRowsChanged) { if (oldWidget.tableSummaryRows.isNotEmpty) { - _container.rowGenerator.items.removeWhere((DataRowBase row) => - row.rowType == RowType.tableSummaryRow || - row.rowType == RowType.tableSummaryCoveredRow); + _container.rowGenerator.items.removeWhere( + (DataRowBase row) => + row.rowType == RowType.tableSummaryRow || + row.rowType == RowType.tableSummaryCoveredRow, + ); } _container.refreshHeaderLineCount(); } @@ -2944,21 +3067,26 @@ class SfDataGridState extends State if (isDataGridControllerChanged) { oldWidget.controller?._removeDataGridPropertyChangeListener( - _handleDataGridPropertyChangeListeners); + _handleDataGridPropertyChangeListeners, + ); - _controller = _dataGridConfiguration.controller = - widget.controller ?? _controller!; + _controller = + _dataGridConfiguration.controller = + widget.controller ?? _controller!; _controller!._dataGridStateDetails = _dataGridStateDetails; _controller?._addDataGridPropertyChangeListener( - _handleDataGridPropertyChangeListeners); + _handleDataGridPropertyChangeListeners, + ); } if (oldWidget.columnSizer != widget.columnSizer) { _dataGridConfiguration.columnSizer = widget.columnSizer ?? ColumnSizer(); setStateDetailsInColumnSizer( - _dataGridConfiguration.columnSizer, _dataGridStateDetails!); + _dataGridConfiguration.columnSizer, + _dataGridStateDetails!, + ); } _initializeProperties(); @@ -2979,11 +3107,13 @@ class SfDataGridState extends State _container.updateRowAndColumnCount(); - _updateSelectionController(oldWidget, - isDataGridControlChanged: isDataGridControllerChanged, - isSelectionManagerChanged: isSelectionManagerChanged, - isSourceChanged: isSourceChanged, - isDataSourceChanged: isDataSourceChanged); + _updateSelectionController( + oldWidget, + isDataGridControlChanged: isDataGridControllerChanged, + isSelectionManagerChanged: isSelectionManagerChanged, + isSourceChanged: isSourceChanged, + isDataSourceChanged: isDataSourceChanged, + ); if (isSourceChanged || isColumnsChanged || @@ -3012,7 +3142,8 @@ class SfDataGridState extends State resetAutoCalculation(_dataGridConfiguration.columnSizer); final DataRowBase? dataRow = _rowGenerator.items.firstWhereOrNull( - (DataRowBase element) => element.rowType == RowType.headerRow); + (DataRowBase element) => element.rowType == RowType.headerRow, + ); // To refresh the header row to update the sort and filter icon changes // in the header cells. if (dataRow != null) { @@ -3076,8 +3207,10 @@ class SfDataGridState extends State isEditingChanged) { // Need to endEdit before refreshing if (isEditingChanged && _dataGridConfiguration.currentCell.isEditing) { - await _dataGridConfiguration.currentCell - .onCellSubmit(_dataGridConfiguration, canRefresh: false); + await _dataGridConfiguration.currentCell.onCellSubmit( + _dataGridConfiguration, + canRefresh: false, + ); } _initializeProperties(); _container.isDirty = true; @@ -3105,9 +3238,12 @@ class SfDataGridState extends State isColumnSizerChanged) { if (isColumnsChanged || isColumnsCollectionChanged) { _dataGridConfiguration.source.sortedColumns.removeWhere( - (SortColumnDetails sortColumn) => !_dataGridConfiguration.columns - .any((GridColumn dataGridColumn) => - dataGridColumn.columnName == sortColumn.name)); + (SortColumnDetails sortColumn) => + !_dataGridConfiguration.columns.any( + (GridColumn dataGridColumn) => + dataGridColumn.columnName == sortColumn.name, + ), + ); } updateDataSource(_dataGridConfiguration.source, true); _dataGridConfiguration.container @@ -3117,34 +3253,43 @@ class SfDataGridState extends State } } - void _handleSelectionPropertyChanged( - {RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight = false}) { + void _handleSelectionPropertyChanged({ + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight = false, + }) { selection_manager.handleSelectionPropertyChanged( - dataGridConfiguration: _dataGridStateDetails!(), - propertyName: propertyName, - rowColumnIndex: rowColumnIndex, - recalculateRowHeight: recalculateRowHeight); + dataGridConfiguration: _dataGridStateDetails!(), + propertyName: propertyName, + rowColumnIndex: rowColumnIndex, + recalculateRowHeight: recalculateRowHeight, + ); } - void _updateSelectionController(SfDataGrid oldWidget, - {bool isSelectionManagerChanged = false, - bool isDataGridControlChanged = false, - bool isSourceChanged = false, - bool isDataSourceChanged = false}) { + void _updateSelectionController( + SfDataGrid oldWidget, { + bool isSelectionManagerChanged = false, + bool isDataGridControlChanged = false, + bool isSourceChanged = false, + bool isDataSourceChanged = false, + }) { if (isSourceChanged) { oldWidget.controller?._removeDataGridPropertyChangeListener( - _handleSelectionPropertyChanged); - widget.controller - ?._addDataGridPropertyChangeListener(_handleSelectionPropertyChanged); + _handleSelectionPropertyChanged, + ); + widget.controller?._addDataGridPropertyChangeListener( + _handleSelectionPropertyChanged, + ); } if (isSelectionManagerChanged) { - _rowSelectionManager = _dataGridConfiguration.rowSelectionManager = - widget.selectionManager ?? _rowSelectionManager!; + _rowSelectionManager = + _dataGridConfiguration.rowSelectionManager = + widget.selectionManager ?? _rowSelectionManager!; selection_manager.setStateDetailsInSelectionManagerBase( - _rowSelectionManager!, _dataGridStateDetails!); + _rowSelectionManager!, + _dataGridStateDetails!, + ); } if (isSourceChanged) { @@ -3152,11 +3297,12 @@ class SfDataGridState extends State } selection_manager.updateSelectionController( - dataGridConfiguration: _dataGridConfiguration, - isSelectionModeChanged: oldWidget.selectionMode != widget.selectionMode, - isNavigationModeChanged: - oldWidget.navigationMode != widget.navigationMode, - isDataSourceChanged: isDataSourceChanged); + dataGridConfiguration: _dataGridConfiguration, + isSelectionModeChanged: oldWidget.selectionMode != widget.selectionMode, + isNavigationModeChanged: + oldWidget.navigationMode != widget.navigationMode, + isDataSourceChanged: isDataSourceChanged, + ); if (isDataGridControlChanged) { _ensureSelectionProperties(); @@ -3164,11 +3310,14 @@ class SfDataGridState extends State } void _onStackedHeaderRowsPropertyChanged( - SfDataGrid oldWidget, SfDataGrid widget) { + SfDataGrid oldWidget, + SfDataGrid widget, + ) { _container.refreshHeaderLineCount(); if (oldWidget.stackedHeaderRows.isNotEmpty) { _rowGenerator.items.removeWhere( - (DataRowBase row) => row.rowType == RowType.stackedHeaderRow); + (DataRowBase row) => row.rowType == RowType.stackedHeaderRow, + ); } if (widget.onQueryRowHeight != null) { _container.rowHeightManager.reset(); @@ -3212,8 +3361,9 @@ class SfDataGridState extends State (widget.navigationMode == GridNavigationMode.row) || (_dataGridConfiguration.source.groupedColumns.isNotEmpty && widget.navigationMode == GridNavigationMode.cell)) { - _dataGridConfiguration.configuration ??= - createLocalImageConfiguration(context); + _dataGridConfiguration.configuration ??= createLocalImageConfiguration( + context, + ); if (_dataGridConfiguration.boxPainter == null) { _updateDecoration(); } @@ -3222,28 +3372,36 @@ class SfDataGridState extends State void _updateDecoration() { final BorderSide borderSide = BorderSide( - color: _dataGridConfiguration - .dataGridThemeHelper!.currentCellStyle!.borderColor); + color: + _dataGridConfiguration + .dataGridThemeHelper! + .currentCellStyle! + .borderColor, + ); final BoxDecoration decoration = BoxDecoration( - border: Border( - bottom: borderSide, - top: borderSide, - left: borderSide, - right: borderSide)); + border: Border( + bottom: borderSide, + top: borderSide, + left: borderSide, + right: borderSide, + ), + ); _dataGridConfiguration.boxPainter = decoration.createBoxPainter(); } void _addDataGridSourceListeners() { _source?._addDataGridPropertyChangeListener( - _handleDataGridPropertyChangeListeners); + _handleDataGridPropertyChangeListeners, + ); _source?._addDataGridSourceListener(_handleNotifyListeners); _source?.addListener(_handleListeners); } void _removeDataGridSourceListeners() { _source?._removeDataGridPropertyChangeListener( - _handleDataGridPropertyChangeListeners); + _handleDataGridPropertyChangeListeners, + ); _source?._removeDataGridSourceListener(_handleNotifyListeners); _source?.removeListener(_handleListeners); } @@ -3252,11 +3410,13 @@ class SfDataGridState extends State void _addCheckboxColumn(DataGridConfiguration dataGridConfiguration) { if (widget.showCheckboxColumn) { dataGridConfiguration.columns.insert( - 0, - GridCheckboxColumn( - columnName: '', - label: widget.checkboxColumnSettings.label ?? const SizedBox(), - width: widget.checkboxColumnSettings.width)); + 0, + GridCheckboxColumn( + columnName: '', + label: widget.checkboxColumnSettings.label ?? const SizedBox(), + width: widget.checkboxColumnSettings.width, + ), + ); } } @@ -3289,7 +3449,8 @@ class SfDataGridState extends State final ThemeData themeData = Theme.of(context); final SfColorScheme colorScheme = SfTheme.colorScheme(context); - _dataGridConfiguration.isDesktop = kIsWeb || + _dataGridConfiguration.isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -3308,13 +3469,15 @@ class SfDataGridState extends State _onDataGridThemeDataChanged(SfDataGridTheme.of(context), colorScheme); _onDataGridTextScaleFactorChanged( - MediaQuery.textScalerOf(context).scale(1)); + MediaQuery.textScalerOf(context).scale(1), + ); _updateVisualDensity(themeData.visualDensity); - _dataGridConfiguration.defaultColumnWidth = widget.defaultColumnWidth.isNaN - ? _dataGridConfiguration.isDesktop - ? 100 - : 90 - : widget.defaultColumnWidth; + _dataGridConfiguration.defaultColumnWidth = + widget.defaultColumnWidth.isNaN + ? _dataGridConfiguration.isDesktop + ? 100 + : 90 + : widget.defaultColumnWidth; _onDataGridLocalizationsChanged(SfLocalizations.of(context)); // This is used to dismiss the filtering popup menu manually when resizing @@ -3326,7 +3489,8 @@ class SfDataGridState extends State _screenSize ??= currentScreenSize; if (_screenSize != currentScreenSize && _dataGridConfiguration - .dataGridFilterHelper!.isFilterPopupMenuShowing) { + .dataGridFilterHelper! + .isFilterPopupMenuShowing) { Navigator.pop(context); _dataGridConfiguration.dataGridFilterHelper!.isFilterPopupMenuShowing = false; @@ -3350,34 +3514,44 @@ class SfDataGridState extends State } return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - final double measuredHeight = _dataGridConfiguration.viewHeight = - constraints.maxHeight.isInfinite ? _minHeight : constraints.maxHeight; - double measuredWidth = _dataGridConfiguration.viewWidth = - constraints.maxWidth.isInfinite ? _minWidth : constraints.maxWidth; - - // FLUT-6545 if shrinkWrapColumns is true, we need to set the container extended width value to the viewWidth - // because the row selection colors are applied based on this size while cell is in editing - if (_dataGridConfiguration.shrinkWrapColumns) { - measuredWidth = _dataGridConfiguration.viewWidth = - _dataGridConfiguration.container.extentWidth; - } - if (!_container.isGridLoaded) { - _gridLoaded(); - if (_textDirection == TextDirection.rtl) { - _container.needToSetHorizontalOffset = true; + builder: (BuildContext context, BoxConstraints constraints) { + final double measuredHeight = + _dataGridConfiguration.viewHeight = + constraints.maxHeight.isInfinite + ? _minHeight + : constraints.maxHeight; + double measuredWidth = + _dataGridConfiguration.viewWidth = + constraints.maxWidth.isInfinite + ? _minWidth + : constraints.maxWidth; + + // FLUT-6545 if shrinkWrapColumns is true, we need to set the container extended width value to the viewWidth + // because the row selection colors are applied based on this size while cell is in editing + if (_dataGridConfiguration.shrinkWrapColumns) { + measuredWidth = + _dataGridConfiguration.viewWidth = + _dataGridConfiguration.container.extentWidth; + } + if (!_container.isGridLoaded) { + _gridLoaded(); + if (_textDirection == TextDirection.rtl) { + _container.needToSetHorizontalOffset = true; + } + _container.isDirty = true; + updateColumnSizerLoadedInitiallyFlag( + _dataGridConfiguration.columnSizer, + true, + ); } - _container.isDirty = true; - updateColumnSizerLoadedInitiallyFlag( - _dataGridConfiguration.columnSizer, true); - } - return ScrollViewWidget( - width: measuredWidth, - height: measuredHeight, - dataGridStateDetails: _dataGridStateDetails!, - ); - }); + return ScrollViewWidget( + width: measuredWidth, + height: measuredHeight, + dataGridStateDetails: _dataGridStateDetails!, + ); + }, + ); } @override @@ -3394,9 +3568,11 @@ class SfDataGridState extends State // We have fixed the issue by removing the respective listener from the_dataGridPropertyChangeListeners // through the _removeDataGridPropertyChangeListener method. _controller?._removeDataGridPropertyChangeListener( - _handleDataGridPropertyChangeListeners); + _handleDataGridPropertyChangeListeners, + ); _controller?._removeDataGridPropertyChangeListener( - _handleSelectionPropertyChanged); + _handleSelectionPropertyChanged, + ); _dataGridConfiguration ..gridPaint = null ..boxPainter = null @@ -3422,8 +3598,9 @@ class SfDataGridState extends State // Therefore, it does not reset to "FilteredFrom.none" when the DataGrid is dispose. // We have now implemented a reset of the "filterFrom" property // when the DataGrid is dispose - _dataGridConfiguration.dataGridFilterHelper! - .resetColumnProperties(_dataGridConfiguration); + _dataGridConfiguration.dataGridFilterHelper!.resetColumnProperties( + _dataGridConfiguration, + ); super.dispose(); } } @@ -3670,7 +3847,8 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier return row .getCells() .firstWhereOrNull( - (DataGridCell cell) => cell.columnName == columnName) + (DataGridCell cell) => cell.columnName == columnName, + ) ?.value ?.toString() ?? ''; @@ -3698,7 +3876,10 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier } int _compareValues( - List sortedColumns, DataGridRow a, DataGridRow b) { + List sortedColumns, + DataGridRow a, + DataGridRow b, + ) { if (sortedColumns.length > 1) { for (final int i = 0; i < sortedColumns.length;) { final SortColumnDetails sortColumn = sortedColumns[i]; @@ -3788,7 +3969,8 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier Object? getCellValue(List? cells, String columnName) { return cells ?.firstWhereOrNull( - (DataGridCell element) => element.columnName == columnName) + (DataGridCell element) => element.columnName == columnName, + ) ?.value; } @@ -3798,7 +3980,10 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier } int _compareTo( - dynamic value1, dynamic value2, DataGridSortDirection sortDirection) { + dynamic value1, + dynamic value2, + DataGridSortDirection sortDirection, + ) { if (sortDirection == DataGridSortDirection.ascending) { if (value1 == null) { return -1; @@ -3849,7 +4034,9 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier if (dataGridStateDetails.source.groupedColumns.isNotEmpty && dataGridStateDetails.group!.displayElements == null) { dataGridStateDetails.group?.initializeTopLevelGroup( - dataGridStateDetails, dataGridStateDetails.autoExpandGroups); + dataGridStateDetails, + dataGridStateDetails.autoExpandGroups, + ); } } @@ -3955,7 +4142,7 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier final List conditions = [ if (_filterConditions.containsKey(columnName)) ..._filterConditions[columnName]!, - filterCondition + filterCondition, ]; _filterConditions[columnName] = conditions; @@ -3996,8 +4183,8 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier return; } - final List conditions = _filterConditions[columnName]! - ..remove(filterCondition); + final List conditions = + _filterConditions[columnName]!..remove(filterCondition); if (conditions.isEmpty) { _filterConditions.remove(columnName); @@ -4056,19 +4243,25 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier void _refreshFilter(DataGridConfiguration dataGridConfiguration) { if (dataGridConfiguration.currentCell.isEditing) { - dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, canRefresh: false); + dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + canRefresh: false, + ); } if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { dataGridConfiguration.group!.clearDisplayElements(dataGridConfiguration); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } _updateDataSource(); selection_manager.refreshSelectedRows(dataGridConfiguration); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'Filtering'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'Filtering', + ); } /// Called to obtain the widget when a cell is moved into edit mode. @@ -4132,8 +4325,12 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier /// values. When you call this method, it will call [canSubmitCell] and /// [onCellSubmit] methods. So, your usual cell value updation will be done /// in single place. - Widget? buildEditWidget(DataGridRow dataGridRow, - RowColumnIndex rowColumnIndex, GridColumn column, CellSubmit submitCell) { + Widget? buildEditWidget( + DataGridRow dataGridRow, + RowColumnIndex rowColumnIndex, + GridColumn column, + CellSubmit submitCell, + ) { return null; } @@ -4147,8 +4344,11 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier /// actual row index even after sorting is applied, you can use /// `DataGridSource.rows.indexOf` method and pass the [dataGridRow]. It will /// provide the actual row index from unsorted [DataGridRow] collection. - bool onCellBeginEdit(DataGridRow dataGridRow, RowColumnIndex rowColumnIndex, - GridColumn column) { + bool onCellBeginEdit( + DataGridRow dataGridRow, + RowColumnIndex rowColumnIndex, + GridColumn column, + ) { return true; } @@ -4193,8 +4393,11 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier /// } ///``` /// This method will never be called when you return false from [onCellBeginEdit]. - Future onCellSubmit(DataGridRow dataGridRow, - RowColumnIndex rowColumnIndex, GridColumn column) async {} + Future onCellSubmit( + DataGridRow dataGridRow, + RowColumnIndex rowColumnIndex, + GridColumn column, + ) async {} /// Called whenever the cell’s editing is completed i.e. prior to /// [onCellSubmit] method. @@ -4202,15 +4405,21 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier /// If you want to restrict the cell from being end its editing, you can /// return false. Otherwise, return true. [onCellSubmit] will be called only /// if the [canSubmitCell] returns true. - Future canSubmitCell(DataGridRow dataGridRow, - RowColumnIndex rowColumnIndex, GridColumn column) async { + Future canSubmitCell( + DataGridRow dataGridRow, + RowColumnIndex rowColumnIndex, + GridColumn column, + ) async { return true; } /// Called when you press the [LogicalKeyboardKey.escape] key when /// the [DataGridCell] on editing to cancel the editing. - void onCellCancelEdit(DataGridRow dataGridRow, RowColumnIndex rowColumnIndex, - GridColumn column) {} + void onCellCancelEdit( + DataGridRow dataGridRow, + RowColumnIndex rowColumnIndex, + GridColumn column, + ) {} @override Future handlePageChange(int oldPageIndex, int newPageIndex) { @@ -4222,7 +4431,8 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); - final int rowsPerPage = dataGridConfiguration.rowsPerPage ?? + final int rowsPerPage = + dataGridConfiguration.rowsPerPage ?? (effectiveRows.length / _pageCount).ceil(); final int startIndex = newPageIndex * rowsPerPage; int endIndex = startIndex + rowsPerPage; @@ -4252,10 +4462,15 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier /// summary. /// /// The `summaryColumn` will be null for the spanned table summary columns. - String calculateSummaryValue(GridTableSummaryRow summaryRow, - GridSummaryColumn? summaryColumn, RowColumnIndex rowColumnIndex) { + String calculateSummaryValue( + GridTableSummaryRow summaryRow, + GridSummaryColumn? summaryColumn, + RowColumnIndex rowColumnIndex, + ) { final int titleColumnSpan = grid_helper.getSummaryTitleColumnSpan( - _dataGridStateDetails!(), summaryRow); + _dataGridStateDetails!(), + summaryRow, + ); if (summaryRow.showSummaryInRow || (!summaryRow.showSummaryInRow && @@ -4265,8 +4480,10 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier if (summaryRow.title != null) { for (final GridSummaryColumn cell in summaryRow.columns) { if (title.contains(cell.name)) { - final String summaryValue = - grid_helper.getSummaryValue(cell, _effectiveRows); + final String summaryValue = grid_helper.getSummaryValue( + cell, + _effectiveRows, + ); title = title.replaceAll('{${cell.name}}', summaryValue); } } @@ -4287,10 +4504,11 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier /// /// The `summaryColumn` will be null for the spanned table summary columns. Widget? buildTableSummaryCellWidget( - GridTableSummaryRow summaryRow, - GridSummaryColumn? summaryColumn, - RowColumnIndex rowColumnIndex, - String summaryValue) { + GridTableSummaryRow summaryRow, + GridSummaryColumn? summaryColumn, + RowColumnIndex rowColumnIndex, + String summaryValue, + ) { return null; } @@ -4300,11 +4518,14 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier if (columnGroup.sortGroupRows) { if (!sortedColumns.any( - (SortColumnDetails element) => element.name == columnGroup.name)) { - sortedColumns.add(SortColumnDetails( - name: columnGroup.name, - sortDirection: DataGridSortDirection.ascending, - )); + (SortColumnDetails element) => element.name == columnGroup.name, + )) { + sortedColumns.add( + SortColumnDetails( + name: columnGroup.name, + sortDirection: DataGridSortDirection.ascending, + ), + ); } } @@ -4319,12 +4540,15 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier _dataGridStateDetails!(); if (_groupedColumns.isNotEmpty && _groupedColumns.contains(columnGroup)) { if (dataGridConfiguration.currentCell.isEditing) { - dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, canRefresh: false); + dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + canRefresh: false, + ); } if (columnGroup.sortGroupRows) { final SortColumnDetails? sortedColumn = sortedColumns.firstWhereOrNull( - (SortColumnDetails element) => element.name == columnGroup.name); + (SortColumnDetails element) => element.name == columnGroup.name, + ); if (sortedColumn != null) { sortedColumns.remove(sortedColumn); } @@ -4342,14 +4566,19 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); if (dataGridConfiguration.currentCell.isEditing) { - dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, canRefresh: false); + dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + canRefresh: false, + ); } for (final ColumnGroup column in _groupedColumns) { if (column.sortGroupRows) { - final SortColumnDetails? sortedColumn = - dataGridConfiguration.source.sortedColumns.firstWhereOrNull( - (SortColumnDetails element) => element.name == column.name); + final SortColumnDetails? sortedColumn = dataGridConfiguration + .source + .sortedColumns + .firstWhereOrNull( + (SortColumnDetails element) => element.name == column.name, + ); if (sortedColumn != null) { sortedColumns.remove(sortedColumn); } @@ -4364,13 +4593,17 @@ abstract class DataGridSource extends DataGridSourceChangeNotifier void _refreshGrouping(DataGridConfiguration dataGridConfiguration) { _updateDataSource(true); - notifyDataGridPropertyChangeListeners(_dataGridStateDetails!().source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + _dataGridStateDetails!().source, + propertyName: 'grouping', + ); } /// Called to obtain each cell in the caption summary row. Widget? buildGroupCaptionCellWidget( - RowColumnIndex rowColumnIndex, String summaryValue) { + RowColumnIndex rowColumnIndex, + String summaryValue, + ) { return null; } } @@ -4402,13 +4635,13 @@ void updateDataPager(DataGridSource source) { class DataGridController extends DataGridSourceChangeNotifier { /// Creates the [DataGridController] with the [selectedIndex], [selectedRow] /// and [selectedRows]. - DataGridController( - {int selectedIndex = -1, - DataGridRow? selectedRow, - List selectedRows = const []}) - : _selectedRow = selectedRow, - _selectedIndex = selectedIndex, - _selectedRows = selectedRows.toList() { + DataGridController({ + int selectedIndex = -1, + DataGridRow? selectedRow, + List selectedRows = const [], + }) : _selectedRow = selectedRow, + _selectedIndex = selectedIndex, + _selectedRows = selectedRows.toList() { _horizontalOffset = 0.0; _verticalOffset = 0.0; } @@ -4498,9 +4731,10 @@ class DataGridController extends DataGridSourceChangeNotifier { /// using [SfDataGrid.onQueryRowHeight] callback. void refreshRow(int rowIndex, {bool recalculateRowHeight = false}) { _notifyDataGridPropertyChangeListeners( - rowColumnIndex: RowColumnIndex(rowIndex, -1), - propertyName: 'refreshRow', - recalculateRowHeight: recalculateRowHeight); + rowColumnIndex: RowColumnIndex(rowIndex, -1), + propertyName: 'refreshRow', + recalculateRowHeight: recalculateRowHeight, + ); } /// A cell which is currently active. @@ -4513,10 +4747,14 @@ class DataGridController extends DataGridSourceChangeNotifier { final CurrentCellManager currentCell = dataGridConfiguration.currentCell; if (dataGridConfiguration.navigationMode == GridNavigationMode.row) { return grid_helper.resolveToRecordRowColumnIndex( - dataGridConfiguration, RowColumnIndex(currentCell.rowIndex, -1)); + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, -1), + ); } else { - return grid_helper.resolveToRecordRowColumnIndex(dataGridConfiguration, - RowColumnIndex(currentCell.rowIndex, currentCell.columnIndex)); + return grid_helper.resolveToRecordRowColumnIndex( + dataGridConfiguration, + RowColumnIndex(currentCell.rowIndex, currentCell.columnIndex), + ); } } @@ -4529,13 +4767,19 @@ class DataGridController extends DataGridSourceChangeNotifier { dataGridConfiguration.selectionMode != SelectionMode.none && dataGridConfiguration.navigationMode != GridNavigationMode.row) { final int rowIndex = grid_helper.resolveToRowIndex( - dataGridConfiguration, rowColumnIndex.rowIndex); + dataGridConfiguration, + rowColumnIndex.rowIndex, + ); final int columnIndex = dataGridConfiguration.source.groupedColumns.isNotEmpty ? grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, rowColumnIndex.columnIndex) + dataGridConfiguration, + rowColumnIndex.columnIndex, + ) : grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, rowColumnIndex.columnIndex); + dataGridConfiguration, + rowColumnIndex.columnIndex, + ); // Ignore the scrolling when the row index or column index are in negative // or invalid. if (rowIndex.isNegative || columnIndex.isNegative) { @@ -4545,8 +4789,10 @@ class DataGridController extends DataGridSourceChangeNotifier { dataGridConfiguration.rowSelectionManager; if (rowSelectionController is RowSelectionManager) { selection_manager.processSelectionAndCurrentCell( - dataGridConfiguration, RowColumnIndex(rowIndex, columnIndex), - isProgrammatic: true); + dataGridConfiguration, + RowColumnIndex(rowIndex, columnIndex), + isProgrammatic: true, + ); } } } @@ -4560,11 +4806,13 @@ class DataGridController extends DataGridSourceChangeNotifier { /// passing the [DataGridScrollPosition] as an argument for rowPosition where /// as you can pass [DataGridScrollPosition] as an argument for columnPosition /// to control the position of a column. - Future scrollToCell(double rowIndex, double columnIndex, - {bool canAnimate = false, - DataGridScrollPosition rowPosition = DataGridScrollPosition.start, - DataGridScrollPosition columnPosition = - DataGridScrollPosition.start}) async { + Future scrollToCell( + double rowIndex, + double columnIndex, { + bool canAnimate = false, + DataGridScrollPosition rowPosition = DataGridScrollPosition.start, + DataGridScrollPosition columnPosition = DataGridScrollPosition.start, + }) async { if (_dataGridStateDetails != null) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails!(); @@ -4580,53 +4828,70 @@ class DataGridController extends DataGridSourceChangeNotifier { } final int getRowIndex = grid_helper.resolveToRowIndex( - dataGridConfiguration, rowIndex.toInt()); + dataGridConfiguration, + rowIndex.toInt(), + ); final int getColumnIndex = grid_helper.resolveToGridVisibleColumnIndex( - dataGridConfiguration, columnIndex.toInt()); - double verticalOffset = - grid_helper.getVerticalOffset(dataGridConfiguration, getRowIndex); + dataGridConfiguration, + columnIndex.toInt(), + ); + double verticalOffset = grid_helper.getVerticalOffset( + dataGridConfiguration, + getRowIndex, + ); double horizontalOffset = grid_helper.getHorizontalOffset( - dataGridConfiguration, getColumnIndex); + dataGridConfiguration, + getColumnIndex, + ); if (dataGridConfiguration.textDirection == TextDirection.rtl && columnIndex == -1) { - horizontalOffset = dataGridConfiguration.container.extentWidth - + horizontalOffset = + dataGridConfiguration.container.extentWidth - + dataGridConfiguration.viewWidth - + horizontalOffset > + 0 + ? dataGridConfiguration.container.extentWidth - dataGridConfiguration.viewWidth - - horizontalOffset > - 0 - ? dataGridConfiguration.container.extentWidth - - dataGridConfiguration.viewWidth - - horizontalOffset - : 0; + horizontalOffset + : 0; } verticalOffset = grid_helper.resolveScrollOffsetToPosition( - rowPosition, - scrollRows, - verticalOffset, - dataGridConfiguration.viewHeight, - scrollRows.headerExtent, - scrollRows.footerExtent, - dataGridConfiguration.rowHeight, - dataGridConfiguration.container.verticalOffset, - getRowIndex); + rowPosition, + scrollRows, + verticalOffset, + dataGridConfiguration.viewHeight, + scrollRows.headerExtent, + scrollRows.footerExtent, + dataGridConfiguration.rowHeight, + dataGridConfiguration.container.verticalOffset, + getRowIndex, + ); horizontalOffset = grid_helper.resolveScrollOffsetToPosition( - columnPosition, - scrollColumns, - horizontalOffset, - dataGridConfiguration.viewWidth, - scrollColumns.headerExtent, - scrollColumns.footerExtent, - dataGridConfiguration.defaultColumnWidth, - dataGridConfiguration.container.horizontalOffset, - getColumnIndex); + columnPosition, + scrollColumns, + horizontalOffset, + dataGridConfiguration.viewWidth, + scrollColumns.headerExtent, + scrollColumns.footerExtent, + dataGridConfiguration.defaultColumnWidth, + dataGridConfiguration.container.horizontalOffset, + getColumnIndex, + ); grid_helper.scrollVertical( - dataGridConfiguration, verticalOffset, canAnimate); + dataGridConfiguration, + verticalOffset, + canAnimate, + ); // Need to add await for the horizontal scrolling alone, to avoid the delay time between vertical and horizontal scrolling. await grid_helper.scrollHorizontal( - dataGridConfiguration, horizontalOffset, canAnimate); + dataGridConfiguration, + horizontalOffset, + canAnimate, + ); } } @@ -4636,11 +4901,17 @@ class DataGridController extends DataGridSourceChangeNotifier { /// /// Also, you can control the position of a row when it comes to view by passing /// the [DataGridScrollPosition] as an argument for position. - Future scrollToRow(double rowIndex, - {bool canAnimate = false, - DataGridScrollPosition position = DataGridScrollPosition.start}) async { - return scrollToCell(rowIndex, -1, - canAnimate: canAnimate, rowPosition: position); + Future scrollToRow( + double rowIndex, { + bool canAnimate = false, + DataGridScrollPosition position = DataGridScrollPosition.start, + }) async { + return scrollToCell( + rowIndex, + -1, + canAnimate: canAnimate, + rowPosition: position, + ); } /// Scrolls the [SfDataGrid] to the given column index. @@ -4649,18 +4920,26 @@ class DataGridController extends DataGridSourceChangeNotifier { /// /// Also, you can control the position of a row when it comes to view by passing /// the [DataGridScrollPosition] as an argument for position. - Future scrollToColumn(double columnIndex, - {bool canAnimate = false, - DataGridScrollPosition position = DataGridScrollPosition.start}) async { - return scrollToCell(-1, columnIndex, - canAnimate: canAnimate, columnPosition: position); + Future scrollToColumn( + double columnIndex, { + bool canAnimate = false, + DataGridScrollPosition position = DataGridScrollPosition.start, + }) async { + return scrollToCell( + -1, + columnIndex, + canAnimate: canAnimate, + columnPosition: position, + ); } /// Scroll the vertical scrollbar from current position to the given value. /// /// If you want animation on scrolling, you can pass true as canAnimate argument. - Future scrollToVerticalOffset(double offset, - {bool canAnimate = false}) async { + Future scrollToVerticalOffset( + double offset, { + bool canAnimate = false, + }) async { if (_dataGridStateDetails != null) { final DataGridConfiguration dataGridSettings = _dataGridStateDetails!(); return grid_helper.scrollVertical(dataGridSettings, offset, canAnimate); @@ -4670,8 +4949,10 @@ class DataGridController extends DataGridSourceChangeNotifier { /// Scroll the horizontal scrollbar from current value to the given value. /// /// If you want animation on scrolling, you can pass true as canAnimate argument. - Future scrollToHorizontalOffset(double offset, - {bool canAnimate = false}) async { + Future scrollToHorizontalOffset( + double offset, { + bool canAnimate = false, + }) async { if (_dataGridStateDetails != null) { final DataGridConfiguration dataGridSettings = _dataGridStateDetails!(); return grid_helper.scrollHorizontal(dataGridSettings, offset, canAnimate); @@ -4689,16 +4970,21 @@ class DataGridController extends DataGridSourceChangeNotifier { return; } if (isCurrentCellInEditing) { - if (!await dataGridConfiguration.currentCell - .canSubmitCell(dataGridConfiguration)) { + if (!await dataGridConfiguration.currentCell.canSubmitCell( + dataGridConfiguration, + )) { return; } - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, cancelCanSubmitCell: true); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + cancelCanSubmitCell: true, + ); } dataGridConfiguration.currentCell.onCellBeginEdit( - editingRowColumnIndex: rowColumnIndex, isProgrammatic: true); + editingRowColumnIndex: rowColumnIndex, + isProgrammatic: true, + ); } } @@ -4713,8 +4999,9 @@ class DataGridController extends DataGridSourceChangeNotifier { return; } - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + ); } } @@ -4725,8 +5012,10 @@ class DataGridController extends DataGridSourceChangeNotifier { _dataGridStateDetails!(); final Group grouping = dataGridConfiguration.group!; grouping.expandAll(grouping); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } @@ -4737,8 +5026,10 @@ class DataGridController extends DataGridSourceChangeNotifier { _dataGridStateDetails!(); final Group grouping = dataGridConfiguration.group!; grouping.collapseAll(grouping); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } @@ -4752,8 +5043,10 @@ class DataGridController extends DataGridSourceChangeNotifier { if (level > 0 && level <= length) { grouping.collapseGroupAtLevel(level, grouping); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } } @@ -4767,8 +5060,10 @@ class DataGridController extends DataGridSourceChangeNotifier { final int length = dataGridConfiguration.source.groupedColumns.length; if (level > 0 && level <= length) { grouping.expandGroupsAtLevel(level, grouping); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } } @@ -4843,6 +5138,138 @@ class DataGridController extends DataGridSourceChangeNotifier { return ScrollAxisRegion.footer; } } + + /// Returns the details of the row at the given [rowIndex]. + /// + /// The returned [DataGridRowDetails] object contains: + /// - [DataGridRowDetails.dataGridRow]: The data associated with the row, or `null` if the row is not a default row. + /// - [DataGridRowDetails.isSelected]: Indicates whether the row is currently selected. + /// - [DataGridRowDetails.rowType]: Specifies the type of the row. + /// + /// Returns `null` if the [rowIndex] is not within the valid range of the data grid. + DataGridRowDetails? getRowDetails(int rowIndex) { + if (_dataGridStateDetails == null) { + return null; + } + + final DataGridConfiguration dataGridConfiguration = + _dataGridStateDetails!(); + final RowType? rowType = _getRowType(dataGridConfiguration, rowIndex); + + if (rowType == null) { + return null; + } + + if (rowType != RowType.dataRow) { + return DataGridRowDetails( + rowType: rowType, + dataGridRow: null, + isSelected: false, + ); + } + + final int recordIndex = grid_helper.resolveToRecordIndex( + dataGridConfiguration, + rowIndex, + ); + + final DataGridRow? dataGridRow = + (recordIndex >= 0) + ? grid_helper.getDataRow(dataGridConfiguration, recordIndex) + : null; + + final bool isSelected = + dataGridRow != null && + selection_manager.isSelectedRow(dataGridConfiguration, dataGridRow); + + return DataGridRowDetails( + rowType: rowType, + dataGridRow: dataGridRow, + isSelected: isSelected, + ); + } + + /// Determines the row type based on the given row index. + /// Returns a [RowType] that represents different types of rows such as + /// header, footer, summary, or dataRows. + RowType? _getRowType(dataGridConfiguration, rowIndex) { + if (rowIndex < dataGridConfiguration.stackedHeaderRows.length) { + return RowType.stackedHeaderRow; + } + + if (rowIndex == grid_helper.getHeaderIndex(dataGridConfiguration)) { + return RowType.headerRow; + } + + if (grid_helper.isTableSummaryIndex(dataGridConfiguration, rowIndex)) { + return _getTableSummaryRowType(dataGridConfiguration, rowIndex); + } + + if (dataGridConfiguration.source.groupedColumns.isNotEmpty && + grid_helper.isCaptionSummaryRow( + dataGridConfiguration, + rowIndex, + true, + )) { + return RowType.captionSummaryCoveredRow; + } + if (grid_helper.isFooterWidgetRow(rowIndex, dataGridConfiguration)) { + return RowType.footerRow; + } + + final int recordIndex = grid_helper.resolveToRecordIndex( + dataGridConfiguration, + rowIndex, + ); + + final int rowCount = grid_helper.resolveEffectiveRowCount( + dataGridConfiguration, + ); + + if (recordIndex >= 0 && recordIndex < rowCount) { + return RowType.dataRow; + } + + return null; + } + + /// Determines the row type for a table summary row based on its position. + /// Returns [RowType.tableSummaryCoveredRow] if the summary should be covered, + /// otherwise returns [RowType.tableSummaryRow]. + RowType _getTableSummaryRowType( + DataGridConfiguration dataGridConfiguration, + int rowIndex, + ) { + final GridTableSummaryRow? tableSummaryRow = grid_helper.getTableSummaryRow( + dataGridConfiguration, + rowIndex, + grid_helper.isTopTableSummaryRow(dataGridConfiguration, rowIndex) + ? GridTableSummaryRowPosition.top + : GridTableSummaryRowPosition.bottom, + ); + + return tableSummaryRow != null && tableSummaryRow.showSummaryInRow + ? RowType.tableSummaryCoveredRow + : RowType.tableSummaryRow; + } +} + +/// Returns the row details for the specified row index. +class DataGridRowDetails { + DataGridRowDetails({ + required this.rowType, + required this.dataGridRow, + required this.isSelected, + }); + + /// The instance of [DataGridRow] that associated with the row. + final RowType rowType; + + /// Specifies whether the row is selected. + final DataGridRow? dataGridRow; + + /// The type of the row. + final bool isSelected; } /// A delegate that provides the row count details and method to listen the @@ -4898,16 +5325,18 @@ class DataGridSourceChangeNotifier extends ChangeNotifier { } final ObserverList<_DataGridPropertyChangeListener> - _dataGridPropertyChangeListeners = + _dataGridPropertyChangeListeners = ObserverList<_DataGridPropertyChangeListener>(); void _addDataGridPropertyChangeListener( - _DataGridPropertyChangeListener listener) { + _DataGridPropertyChangeListener listener, + ) { _dataGridPropertyChangeListeners.add(listener); } void _removeDataGridPropertyChangeListener( - _DataGridPropertyChangeListener listener) { + _DataGridPropertyChangeListener listener, + ) { _dataGridPropertyChangeListeners.remove(listener); } @@ -4926,29 +5355,34 @@ class DataGridSourceChangeNotifier extends ChangeNotifier { } /// Call this method whenever the rowColumnIndex, propertyName and recalculateRowHeight of the underlying data are updated internally. - void _notifyDataGridPropertyChangeListeners( - {RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight = false}) { + void _notifyDataGridPropertyChangeListeners({ + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight = false, + }) { for (final Function listener in _dataGridPropertyChangeListeners) { listener( - rowColumnIndex: rowColumnIndex, - propertyName: propertyName, - recalculateRowHeight: recalculateRowHeight); + rowColumnIndex: rowColumnIndex, + propertyName: propertyName, + recalculateRowHeight: recalculateRowHeight, + ); } } } /// Call this method whenever the rowColumnIndex, propertyName and recalculateRowHeight of the /// underlying data are updated internally. -void notifyDataGridPropertyChangeListeners(DataGridSource source, - {RowColumnIndex? rowColumnIndex, - String? propertyName, - bool recalculateRowHeight = false}) { +void notifyDataGridPropertyChangeListeners( + DataGridSource source, { + RowColumnIndex? rowColumnIndex, + String? propertyName, + bool recalculateRowHeight = false, +}) { source._notifyDataGridPropertyChangeListeners( - rowColumnIndex: rowColumnIndex, - recalculateRowHeight: recalculateRowHeight, - propertyName: propertyName); + rowColumnIndex: rowColumnIndex, + recalculateRowHeight: recalculateRowHeight, + propertyName: propertyName, + ); } /// Invokes the `handleLoadMoreRows` method in [DataGridSource]. @@ -4977,7 +5411,10 @@ List effectiveRows(DataGridSource source) { /// Called when grouping is applied to the columns. String performGrouping( - DataGridSource? source, String columnNames, DataGridRow row) { + DataGridSource? source, + String columnNames, + DataGridRow row, +) { return source!.performGrouping(columnNames, row); } @@ -5016,7 +5453,9 @@ void updateSelectedIndex(DataGridController controller, int newSelectedIndex) { /// Updates the given [DataGridRow] to the controller's `selectedRow` property. void updateSelectedRow( - DataGridController controller, DataGridRow? newSelectedRow) { + DataGridController controller, + DataGridRow? newSelectedRow, +) { controller._selectedRow = newSelectedRow; } @@ -5032,7 +5471,9 @@ void updateHorizontalOffset(DataGridController controller, double offset) { /// Sets the `childColumnIndexes` property in the [StackedHeaderCell]. void setChildColumnIndexes( - StackedHeaderCell stackedHeaderCell, List childSequence) { + StackedHeaderCell stackedHeaderCell, + List childSequence, +) { stackedHeaderCell._childColumnIndexes = childSequence; } @@ -5042,8 +5483,11 @@ List getChildColumnIndexes(StackedHeaderCell stackedHeaderCell) { } /// Call this method to add the [FilterCondition] in the UI filtering. -void addFilterConditions(DataGridSource source, String columnName, - List conditions) { +void addFilterConditions( + DataGridSource source, + String columnName, + List conditions, +) { source._filterConditions[columnName] = conditions; } @@ -5062,10 +5506,14 @@ class DataGridThemeHelper { /// To Do DataGridThemeHelper( - SfDataGridThemeData dataGridThemeData, BuildContext context) { + SfDataGridThemeData dataGridThemeData, + BuildContext context, + ) { final SfDataGridThemeData defaults = SfDataGridTheme.of(context); - final _SfDataGridThemeData sfDataGridThemeData = - _SfDataGridThemeData(context, dataGridThemeData); + final _SfDataGridThemeData sfDataGridThemeData = _SfDataGridThemeData( + context, + dataGridThemeData, + ); headerColor = defaults.headerColor ?? sfDataGridThemeData.headerColor; gridLineColor = defaults.gridLineColor ?? sfDataGridThemeData.gridLineColor; @@ -5083,11 +5531,12 @@ class DataGridThemeHelper { sortIconColor = defaults.sortIconColor ?? sfDataGridThemeData.sortIconColor; frozenPaneLineColor = defaults.frozenPaneLineColor ?? sfDataGridThemeData.frozenPaneLineColor; - columnResizeIndicatorColor = defaults.columnResizeIndicatorColor ?? + columnResizeIndicatorColor = + defaults.columnResizeIndicatorColor ?? sfDataGridThemeData.columnResizeIndicatorColor; columnResizeIndicatorStrokeWidth = defaults.columnResizeIndicatorStrokeWidth ?? - sfDataGridThemeData.columnResizeIndicatorStrokeWidth; + sfDataGridThemeData.columnResizeIndicatorStrokeWidth; currentCellStyle = defaults.currentCellStyle ?? sfDataGridThemeData.currentCellStyle; @@ -5097,11 +5546,14 @@ class DataGridThemeHelper { filterIcon = defaults.filterIcon ?? sfDataGridThemeData.filterIcon; filterIconColor = defaults.filterIconColor ?? sfDataGridThemeData.filterIconColor; - filterIconHoverColor = defaults.filterIconHoverColor ?? + filterIconHoverColor = + defaults.filterIconHoverColor ?? sfDataGridThemeData.filterIconHoverColor; - sortOrderNumberColor = defaults.sortOrderNumberColor ?? + sortOrderNumberColor = + defaults.sortOrderNumberColor ?? sfDataGridThemeData.sortOrderNumberColor; - sortOrderNumberBackgroundColor = defaults.sortOrderNumberBackgroundColor ?? + sortOrderNumberBackgroundColor = + defaults.sortOrderNumberBackgroundColor ?? sfDataGridThemeData.sortOrderNumberBackgroundColor; _filterPopupTextStyle = sfDataGridThemeData.filterPopupTextStyle; @@ -5109,35 +5561,128 @@ class DataGridThemeHelper { sfDataGridThemeData.filterPopupDisabledTextStyle; filterPopupTextStyle = _filterPopupTextStyle!.merge( - defaults.filterPopupTextStyle ?? - sfDataGridThemeData.filterPopupTextStyle); - filterPopupDisabledTextStyle = _filterPopupDisabledTextStyle! - .merge(defaults.filterPopupDisabledTextStyle); - - columnDragIndicatorColor = defaults.columnDragIndicatorColor ?? + defaults.filterPopupTextStyle ?? sfDataGridThemeData.filterPopupTextStyle, + ); + filterPopupDisabledTextStyle = _filterPopupDisabledTextStyle!.merge( + defaults.filterPopupDisabledTextStyle, + ); + + columnDragIndicatorColor = + defaults.columnDragIndicatorColor ?? sfDataGridThemeData.columnDragIndicatorColor; - columnDragIndicatorStrokeWidth = defaults.columnDragIndicatorStrokeWidth ?? + columnDragIndicatorStrokeWidth = + defaults.columnDragIndicatorStrokeWidth ?? sfDataGridThemeData.columnDragIndicatorStrokeWidth; groupExpanderIcon = defaults.groupExpanderIcon; indentColumnWidth = defaults.indentColumnWidth ?? sfDataGridThemeData.indentColumnWidth; indentColumnColor = defaults.indentColumnColor ?? sfDataGridThemeData.indentColumnColor; - filterPopupIconColor = sfDataGridThemeData.filterPopupIconColor; - filterPopupDisableIconColor = - sfDataGridThemeData.filterPopupDisableIconColor; + filterPopupIconColor = + defaults.filterPopupIconColor ?? + sfDataGridThemeData.filterPopupIconColor; + filterPopupDisabledIconColor = + defaults.filterPopupDisabledIconColor ?? + sfDataGridThemeData.filterPopupDisabledIconColor; filterPopupBorderColor = sfDataGridThemeData.filterPopupBorderColor; - filterPopupBackgroundColor = sfDataGridThemeData.filterPopupBackgroundColor; + filterPopupBackgroundColor = + defaults.filterPopupBackgroundColor ?? + sfDataGridThemeData.filterPopupBackgroundColor; filterPopupTextColor = sfDataGridThemeData.filterPopupTextColor; filterPopupOuterColor = sfDataGridThemeData.filterPopupOuterColor; feedBackWidgetColor = sfDataGridThemeData.feedBackWidgetColor; - captionSummaryRowColor = sfDataGridThemeData.captionSummaryRowColor!; + captionSummaryRowColor = + defaults.captionSummaryRowColor ?? + sfDataGridThemeData.captionSummaryRowColor!; captionSummaryRowHoverColor = sfDataGridThemeData.captionSummaryRowHoverColor!; tableSummaryRowColor = sfDataGridThemeData.tableSummaryRowColor; + filterPopupCheckColor = + defaults.filterPopupCheckColor ?? + sfDataGridThemeData.filterPopupCheckColor; + filterPopupCheckboxFillColor = + defaults.filterPopupCheckboxFillColor ?? + sfDataGridThemeData.filterPopupCheckboxFillColor; + noMatchesFilteringLabelColor = + defaults.noMatchesFilteringLabelColor ?? + sfDataGridThemeData.noMatchesFilteringLabelColor; + okFilteringLabelColor = + defaults.okFilteringLabelColor ?? + sfDataGridThemeData.okFilteringLabelColor; + okFilteringLabelButtonColor = + defaults.okFilteringLabelButtonColor ?? + sfDataGridThemeData.okFilteringLabelButtonColor; + cancelFilteringLabelColor = + defaults.cancelFilteringLabelColor ?? + sfDataGridThemeData.cancelFilteringLabelColor; + cancelFilteringLabelButtonColor = + defaults.cancelFilteringLabelButtonColor ?? + sfDataGridThemeData.cancelFilteringLabelButtonColor; + searchAreaFocusedBorderColor = + defaults.searchAreaFocusedBorderColor ?? + sfDataGridThemeData.searchAreaFocusedBorderColor; + searchAreaCursorColor = + defaults.searchAreaCursorColor ?? + sfDataGridThemeData.searchAreaCursorColor; + andRadioActiveColor = + defaults.andRadioActiveColor ?? sfDataGridThemeData.andRadioActiveColor; + andRadioFillColor = + defaults.andRadioFillColor ?? sfDataGridThemeData.andRadioFillColor; + orRadioActiveColor = + defaults.orRadioActiveColor ?? sfDataGridThemeData.orRadioActiveColor; + orRadioFillColor = + defaults.orRadioFillColor ?? sfDataGridThemeData.orRadioFillColor; + calendarIconColor = + defaults.calendarIconColor ?? sfDataGridThemeData.calendarIconColor; + advancedFilterValueDropdownFocusedBorderColor = + defaults.advancedFilterValueDropdownFocusedBorderColor ?? + sfDataGridThemeData.advancedFilterValueDropdownFocusedBorderColor; + advancedFilterTypeDropdownFocusedBorderColor = + defaults.advancedFilterTypeDropdownFocusedBorderColor ?? + sfDataGridThemeData.advancedFilterTypeDropdownFocusedBorderColor; + advancedFilterValueTextAreaCursorColor = + defaults.advancedFilterValueTextAreaCursorColor ?? + sfDataGridThemeData.advancedFilterValueTextAreaCursorColor; + searchIconColor = + defaults.searchIconColor ?? sfDataGridThemeData.searchIconColor; + closeIconColor = + defaults.closeIconColor ?? sfDataGridThemeData.closeIconColor; + advancedFilterPopupDropdownIconColor = + defaults.advancedFilterPopupDropdownIconColor ?? + sfDataGridThemeData.advancedFilterPopupDropdownIconColor; + caseSensitiveIconActiveColor = + defaults.caseSensitiveIconActiveColor ?? + sfDataGridThemeData.caseSensitiveIconActiveColor; + caseSensitiveIconColor = + defaults.caseSensitiveIconColor ?? + sfDataGridThemeData.caseSensitiveIconColor; + advancedFilterValueDropdownIconColor = + defaults.advancedFilterValueDropdownIconColor ?? + sfDataGridThemeData.advancedFilterValueDropdownIconColor; + advancedFilterTypeDropdownIconColor = + defaults.advancedFilterTypeDropdownIconColor ?? + sfDataGridThemeData.advancedFilterTypeDropdownIconColor; + filterPopupBottomDividerColor = + defaults.filterPopupBottomDividerColor ?? + sfDataGridThemeData.filterPopupBottomDividerColor; + filterPopupTopDividerColor = + defaults.filterPopupTopDividerColor ?? + sfDataGridThemeData.filterPopupTopDividerColor; + okFilteringLabelDisabledButtonColor = + defaults.okFilteringLabelDisabledButtonColor ?? + sfDataGridThemeData.okFilteringLabelDisabledButtonColor; + appBarBottomBorderColor = + defaults.appBarBottomBorderColor ?? + sfDataGridThemeData.appBarBottomBorderColor; + filterPopupInputBorderColor = + defaults.filterPopupInputBorderColor ?? + sfDataGridThemeData.filterPopupInputBorderColor; + advancedFilterPopupDropdownColor = + defaults.advancedFilterPopupDropdownColor ?? + sfDataGridThemeData.advancedFilterPopupDropdownColor; } -// ignore: public_member_api_docs + // ignore: public_member_api_docs late final Color? headerColor; /// To do @@ -5301,22 +5846,22 @@ class DataGridThemeHelper { /// The color of an indent column. late final Color? indentColumnColor; - /// Provides the icon color. + /// The color of icons displayed in the filter popup. late final Color? filterPopupIconColor; - /// Provides the disable icon color. - late final Color? filterPopupDisableIconColor; + /// The color of disabled icons in the filter popup. + late final Color? filterPopupDisabledIconColor; /// Provides the border color. late final Color? filterPopupBorderColor; - /// Provides the background color. + /// The background color of the filter popup. late final Color? filterPopupBackgroundColor; /// Provides the text color. late final Color? filterPopupTextColor; - /// Provides the text color. + /// Provides the filter popup outer widgetcolor. late final Color? filterPopupOuterColor; /// Provides the feedBack widgetcolor. @@ -5330,6 +5875,96 @@ class DataGridThemeHelper { /// Provides the table summary row color. late final Color tableSummaryRowColor; + + /// The checkmark color of the checkbox in the filter popup. + late final Color? filterPopupCheckColor; + + /// The fill color of the checkbox in the filter popup. + late final WidgetStateProperty? filterPopupCheckboxFillColor; + + /// The color of the "No Matches" filtering label when no results are found. + late final Color? noMatchesFilteringLabelColor; + + /// The color of the OK label in the filtering popup. + late final Color? okFilteringLabelColor; + + /// The color of the OK button in the filtering popup. + late final Color? okFilteringLabelButtonColor; + + /// The color of the cancel label in the filtering popup. + late final Color? cancelFilteringLabelColor; + + /// The color of the cancel button in the filtering popup. + late final Color? cancelFilteringLabelButtonColor; + + /// The cursor color in the search area. + late final Color? searchAreaCursorColor; + + /// The focused border color of the search area. + late final Color? searchAreaFocusedBorderColor; + + /// The active (selected) color of the "AND" radio button. + late final Color? andRadioActiveColor; + + /// The fill color of the "AND" radio button. + late final WidgetStateProperty? andRadioFillColor; + + /// The active (selected) color of the "OR" radio button. + late final Color? orRadioActiveColor; + + /// The fill color of the "OR" radio button. + late final WidgetStateProperty? orRadioFillColor; + + /// The color of the calendar icon. + late final Color? calendarIconColor; + + /// The focused border color of the advanced filter type dropdown. + late final Color? advancedFilterTypeDropdownFocusedBorderColor; + + /// The focused border color of the advanced filter value dropdown. + late final Color? advancedFilterValueDropdownFocusedBorderColor; + + /// The cursor color in the advanced filter value text area. + late final Color? advancedFilterValueTextAreaCursorColor; + + /// The color of the search icon. + late final Color? searchIconColor; + + /// The color of the close icon. + late final Color? closeIconColor; + + /// The color of the dropdown icon of the advanced filter popup. + late final Color? advancedFilterPopupDropdownIconColor; + + /// The active color of the case-sensitive icon. + late final Color? caseSensitiveIconActiveColor; + + /// The default color of the case-sensitive icon. + late final Color? caseSensitiveIconColor; + + /// The background color of the advanced filter type dropdown icon. + late final Color? advancedFilterTypeDropdownIconColor; + + /// The background color of the advanced filter value dropdown icon. + late final Color? advancedFilterValueDropdownIconColor; + + /// The color of the bottom divider in the filter popup. + late final Color? filterPopupBottomDividerColor; + + /// The color of the top divider in the filter popup. + late final Color? filterPopupTopDividerColor; + + /// The color of the disabled OK button in the filtering popup. + late final Color? okFilteringLabelDisabledButtonColor; + + /// The color of the bottom border of the app bar. + late final Color? appBarBottomBorderColor; + + /// The border color of the text field (input box) inside the filter popup. + late final Color? filterPopupInputBorderColor; + + /// The background color of the dropdown in the advanced filter popup. + late final Color? advancedFilterPopupDropdownColor; } /// @@ -5359,7 +5994,9 @@ class _SfDataGridThemeData extends SfDataGridThemeData { @override DataGridCurrentCellStyle get currentCellStyle => DataGridCurrentCellStyle( - borderColor: colorScheme.onSurface[66]!, borderWidth: 1.0); + borderColor: colorScheme.onSurface[66]!, + borderWidth: 1.0, + ); @override double get frozenPaneLineWidth => 2; @@ -5390,10 +6027,11 @@ class _SfDataGridThemeData extends SfDataGridThemeData { @override TextStyle get rowHoverTextStyle => TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: colorScheme.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: colorScheme.onSurface[222], + ); @override Widget? get sortIcon => dataGridThemeData.sortIcon; @@ -5416,17 +6054,19 @@ class _SfDataGridThemeData extends SfDataGridThemeData { @override TextStyle get filterPopupTextStyle => TextStyle( - fontSize: 14.0, - color: colorScheme.onSurface[227], - fontFamily: 'Roboto', - fontWeight: FontWeight.normal); + fontSize: 14.0, + color: colorScheme.onSurface[227], + fontFamily: 'Roboto', + fontWeight: FontWeight.normal, + ); @override TextStyle get filterPopupDisabledTextStyle => TextStyle( - fontSize: 14.0, - color: colorScheme.onSurface[97], - fontFamily: 'Roboto', - fontWeight: FontWeight.normal); + fontSize: 14.0, + color: colorScheme.onSurface[97], + fontFamily: 'Roboto', + fontWeight: FontWeight.normal, + ); @override Color? get columnDragIndicatorColor => colorScheme.primary; @@ -5443,22 +6083,26 @@ class _SfDataGridThemeData extends SfDataGridThemeData { @override Color? get indentColumnColor => colorScheme.onSurface[10]; - /// Provides the icon color. + /// The color of icons displayed in the filter popup. + @override Color? get filterPopupIconColor => colorScheme.onSurface[154]; - /// Provides the disable icon color. - Color? get filterPopupDisableIconColor => colorScheme.onSurface[97]; + /// The color of disabled icons in the filter popup. + @override + Color? get filterPopupDisabledIconColor => colorScheme.onSurface[97]; /// Provides the border color. Color? get filterPopupBorderColor => colorScheme.onSurface[31]; - /// Provides the background color. + /// The background color of the filter popup. + @override Color? get filterPopupBackgroundColor => colorScheme.onSurface[0]; /// Provides the text color. Color? get filterPopupTextColor => colorScheme.onSurface[228]; /// Provides the caption summaryrow color. + @override Color? get captionSummaryRowColor => colorScheme.onSurface[10]; /// Provides the caption summary row hover color. @@ -5472,4 +6116,145 @@ class _SfDataGridThemeData extends SfDataGridThemeData { /// Provides the feedBack widgetcolor. Color get feedBackWidgetColor => colorScheme.surface[250]!; + + /// The checkmark color of the checkbox in the filter popup. + @override + Color? get filterPopupCheckColor => dataGridThemeData.filterPopupCheckColor; + + /// The fill color of the checkbox in the filter popup. + @override + WidgetStateProperty? get filterPopupCheckboxFillColor => + dataGridThemeData.filterPopupCheckboxFillColor; + + /// The color of the "No Matches" filtering label when no results are found. + @override + Color? get noMatchesFilteringLabelColor => + dataGridThemeData.noMatchesFilteringLabelColor; + + /// The color of the OK label in the filtering popup. + @override + Color? get okFilteringLabelColor => dataGridThemeData.okFilteringLabelColor; + + /// The color of the OK button in the filtering popup. + @override + Color? get okFilteringLabelButtonColor => + dataGridThemeData.okFilteringLabelButtonColor; + + /// The color of the cancel label in the filtering popup. + @override + Color? get cancelFilteringLabelColor => + dataGridThemeData.cancelFilteringLabelColor; + + /// The color of the cancel button in the filtering popup. + @override + Color? get cancelFilteringLabelButtonColor => + dataGridThemeData.cancelFilteringLabelButtonColor; + + /// The focused border color of the search area. + @override + Color? get searchAreaFocusedBorderColor => + dataGridThemeData.searchAreaFocusedBorderColor; + + /// The cursor color in the search area. + @override + Color? get searchAreaCursorColor => dataGridThemeData.searchAreaCursorColor; + + /// The active (selected) color of the "AND" radio button. + @override + Color? get andRadioActiveColor => dataGridThemeData.andRadioActiveColor; + + /// The fill color of the "AND" radio button. + @override + WidgetStateProperty? get andRadioFillColor => + dataGridThemeData.andRadioFillColor; + + /// The active (selected) color of the "OR" radio button. + @override + Color? get orRadioActiveColor => dataGridThemeData.orRadioActiveColor; + + /// The fill color of the "OR" radio button. + @override + WidgetStateProperty? get orRadioFillColor => + dataGridThemeData.orRadioFillColor; + + /// The color of the calendar icon. + @override + Color? get calendarIconColor => dataGridThemeData.calendarIconColor; + + /// Provides the border color of the advanced filter type dropdown when focused. + @override + Color? get advancedFilterValueDropdownFocusedBorderColor => + dataGridThemeData.advancedFilterValueDropdownFocusedBorderColor; + + /// The focused border color of the advanced filter type dropdown. + @override + Color? get advancedFilterTypeDropdownFocusedBorderColor => + dataGridThemeData.advancedFilterTypeDropdownFocusedBorderColor; + + /// The cursor color in the advanced filter value text area. + @override + Color? get advancedFilterValueTextAreaCursorColor => + dataGridThemeData.advancedFilterValueTextAreaCursorColor; + + /// The color of the search icon. + @override + Color? get searchIconColor => dataGridThemeData.searchIconColor; + + /// The color of the close icon. + @override + Color? get closeIconColor => dataGridThemeData.closeIconColor; + + /// The color of the dropdown icon of the advanced filter popup. + @override + Color? get advancedFilterPopupDropdownIconColor => + dataGridThemeData.advancedFilterPopupDropdownIconColor; + + /// The active color of the case-sensitive icon. + @override + Color? get caseSensitiveIconActiveColor => + dataGridThemeData.caseSensitiveIconActiveColor; + + /// The default color of the case-sensitive icon. + @override + Color? get caseSensitiveIconColor => dataGridThemeData.caseSensitiveIconColor; + + /// The background color of the advanced filter type dropdown icon. + @override + Color? get advancedFilterTypeDropdownIconColor => + dataGridThemeData.advancedFilterTypeDropdownIconColor; + + /// The background color of the advanced filter value dropdown icon. + @override + Color? get advancedFilterValueDropdownIconColor => + dataGridThemeData.advancedFilterValueDropdownIconColor; + + /// The color of the bottom divider in the filter popup. + @override + Color? get filterPopupBottomDividerColor => + dataGridThemeData.filterPopupBottomDividerColor; + + /// The color of the top divider in the filter popup. + @override + Color? get filterPopupTopDividerColor => + dataGridThemeData.filterPopupTopDividerColor; + + /// The color of the disabled OK button in the filtering popup. + @override + Color? get okFilteringLabelDisabledButtonColor => + dataGridThemeData.okFilteringLabelDisabledButtonColor; + + /// The color of the bottom border of the app bar. + @override + Color? get appBarBottomBorderColor => + dataGridThemeData.appBarBottomBorderColor; + + /// The border color of the text field (input box) inside the filter popup. + @override + Color? get filterPopupInputBorderColor => + dataGridThemeData.filterPopupInputBorderColor; + + /// The background color of the dropdown in the advanced filter popup. + @override + Color? get advancedFilterPopupDropdownColor => + dataGridThemeData.advancedFilterPopupDropdownColor; } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/cell_widget.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/cell_widget.dart index 471158ee5..d3c30502d 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/cell_widget.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/cell_widget.dart @@ -24,14 +24,14 @@ import 'rendering_widget.dart'; /// A widget which displays in the cells. class GridCell extends StatefulWidget { /// Creates the [GridCell] for [SfDataGrid] widget. - const GridCell( - {required Key key, - required this.dataCell, - required this.isDirty, - required this.backgroundColor, - required this.child, - required this.dataGridStateDetails}) - : super(key: key); + const GridCell({ + required Key key, + required this.dataCell, + required this.isDirty, + required this.backgroundColor, + required this.child, + required this.dataGridStateDetails, + }) : super(key: key); /// Holds the information required to display the cell. final DataCellBase dataCell; @@ -66,7 +66,9 @@ class _GridCellState extends State { EditingGestureType.doubleTap); Future _handleOnTapDown( - TapDownDetails details, bool isSecondaryTapDown) async { + TapDownDetails details, + bool isSecondaryTapDown, + ) async { _kind = details.kind!; final DataCellBase dataCell = widget.dataCell; final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); @@ -74,8 +76,9 @@ class _GridCellState extends State { // Clear editing when tap on the stacked header cell. if (widget.dataCell.cellType == CellType.stackedHeaderCell && dataGridConfiguration.currentCell.isEditing) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + ); } if (_isDoubleTapEnabled(dataGridConfiguration) && !isSecondaryTapDown) { @@ -83,8 +86,11 @@ class _GridCellState extends State { } } - void _handleDoubleTapOnEditing(DataGridConfiguration dataGridConfiguration, - DataCellBase dataCell, TapDownDetails details) { + void _handleDoubleTapOnEditing( + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, + TapDownDetails details, + ) { if (tapTimer != null && tapTimer!.isActive) { tapTimer!.cancel(); } else { @@ -97,11 +103,12 @@ class _GridCellState extends State { return; } _handleOnTapUp( - tapDownDetails: details, - tapUpDetails: null, - dataGridConfiguration: dataGridConfiguration, - dataCell: dataCell, - kind: _kind); + tapDownDetails: details, + tapUpDetails: null, + dataGridConfiguration: dataGridConfiguration, + dataCell: dataCell, + kind: _kind, + ); tapTimer?.cancel(); }); } @@ -116,26 +123,30 @@ class _GridCellState extends State { // callback final bool isDoubleTapEnabled = _isDoubleTapEnabled(dataGridConfiguration); return GestureDetector( - onTapUp: isDoubleTapEnabled - ? null - : (TapUpDetails details) { - _handleOnTapUp( + onTapUp: + isDoubleTapEnabled + ? null + : (TapUpDetails details) { + _handleOnTapUp( tapUpDetails: details, tapDownDetails: null, dataGridConfiguration: dataGridConfiguration, dataCell: dataCell, - kind: _kind); - }, + kind: _kind, + ); + }, onTapDown: (TapDownDetails details) => _handleOnTapDown(details, false), - onTap: isDoubleTapEnabled - ? () { - if (tapTimer != null && !tapTimer!.isActive) { - _handleOnDoubleTap( + onTap: + isDoubleTapEnabled + ? () { + if (tapTimer != null && !tapTimer!.isActive) { + _handleOnDoubleTap( dataCell: dataCell, - dataGridConfiguration: dataGridConfiguration); + dataGridConfiguration: dataGridConfiguration, + ); + } } - } - : null, + : null, onTapCancel: () { if (tapTimer != null && tapTimer!.isActive) { tapTimer?.cancel(); @@ -143,30 +154,33 @@ class _GridCellState extends State { }, onSecondaryTapUp: (TapUpDetails details) { _handleOnSecondaryTapUp( - tapUpDetails: details, - dataGridConfiguration: dataGridConfiguration, - dataCell: dataCell, - kind: _kind); + tapUpDetails: details, + dataGridConfiguration: dataGridConfiguration, + dataCell: dataCell, + kind: _kind, + ); }, - onSecondaryTapDown: (TapDownDetails details) => - _handleOnTapDown(details, true), + onSecondaryTapDown: + (TapDownDetails details) => _handleOnTapDown(details, true), child: _wrapInsideContainer(), ); } Widget _wrapInsideContainer() => Container( - key: widget.key, - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration( - border: _getCellBorder(dataGridStateDetails(), widget.dataCell)), - alignment: Alignment.center, - child: _wrapInsideCellContainer( - dataGridConfiguration: dataGridStateDetails(), - child: widget.child, - dataCell: widget.dataCell, - key: widget.key!, - backgroundColor: widget.backgroundColor, - )); + key: widget.key, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + border: _getCellBorder(dataGridStateDetails(), widget.dataCell), + ), + alignment: Alignment.center, + child: _wrapInsideCellContainer( + dataGridConfiguration: dataGridStateDetails(), + child: widget.child, + dataCell: widget.dataCell, + key: widget.key!, + backgroundColor: widget.backgroundColor, + ), + ); @override Widget build(BuildContext context) { @@ -191,14 +205,14 @@ class _GridCellState extends State { /// A widget which displays in the header cells. class GridHeaderCell extends StatefulWidget { /// Creates the [GridHeaderCell] for [SfDataGrid] widget. - const GridHeaderCell( - {required Key key, - required this.dataCell, - required this.backgroundColor, - required this.isDirty, - required this.child, - required this.dataGridStateDetails}) - : super(key: key); + const GridHeaderCell({ + required Key key, + required this.dataCell, + required this.backgroundColor, + required this.isDirty, + required this.child, + required this.dataGridStateDetails, + }) : super(key: key); /// Holds the information required to display the cell. final DataCellBase dataCell; @@ -229,7 +243,7 @@ class GridHeaderCell extends StatefulWidget { class GridHeaderCellElement extends StatefulElement { /// Creates the [GridHeaderCellElement] for [GridHeaderCell] widget. GridHeaderCellElement(GridHeaderCell gridHeaderCell, this.column) - : super(gridHeaderCell); + : super(gridHeaderCell); /// A GridColumn which displays in the header cells. GridColumn column; @@ -260,21 +274,21 @@ class _GridHeaderCellState extends State { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); // Clear editing when tap on the header cell _clearEditing(dataGridConfiguration); - if (dataGridConfiguration.onCellTap != null) { - final DataGridCellTapDetails details = DataGridCellTapDetails( - rowColumnIndex: - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), - column: dataCell.gridColumn!, - globalPosition: tapUpDetails.globalPosition, - localPosition: tapUpDetails.localPosition, - kind: _kind); - dataGridConfiguration.onCellTap!(details); - } - dataGridConfiguration.dataGridFocusNode?.requestFocus(); if (dataGridConfiguration.sortingGestureType == SortingGestureType.tap) { _sort(dataCell); } + + if (dataGridConfiguration.onCellTap != null) { + final DataGridCellTapDetails details = DataGridCellTapDetails( + rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + column: dataCell.gridColumn!, + globalPosition: tapUpDetails.globalPosition, + localPosition: tapUpDetails.localPosition, + kind: _kind, + ); + dataGridConfiguration.onCellTap!(details); + } } void _handleOnDoubleTap() { @@ -282,19 +296,19 @@ class _GridHeaderCellState extends State { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); // Clear editing when tap on the header cell _clearEditing(dataGridConfiguration); - if (dataGridConfiguration.onCellDoubleTap != null) { - final DataGridCellDoubleTapDetails details = DataGridCellDoubleTapDetails( - rowColumnIndex: - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), - column: dataCell.gridColumn!); - dataGridConfiguration.onCellDoubleTap!(details); - } - dataGridConfiguration.dataGridFocusNode?.requestFocus(); if (dataGridConfiguration.sortingGestureType == SortingGestureType.doubleTap) { _sort(dataCell); } + + if (dataGridConfiguration.onCellDoubleTap != null) { + final DataGridCellDoubleTapDetails details = DataGridCellDoubleTapDetails( + rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + column: dataCell.gridColumn!, + ); + dataGridConfiguration.onCellDoubleTap!(details); + } } void _handleOnSecondaryTapUp(TapUpDetails tapUpDetails) { @@ -304,12 +318,12 @@ class _GridHeaderCellState extends State { _clearEditing(dataGridConfiguration); if (dataGridConfiguration.onCellSecondaryTap != null) { final DataGridCellTapDetails details = DataGridCellTapDetails( - rowColumnIndex: - RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), - column: dataCell.gridColumn!, - globalPosition: tapUpDetails.globalPosition, - localPosition: tapUpDetails.localPosition, - kind: _kind); + rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + column: dataCell.gridColumn!, + globalPosition: tapUpDetails.globalPosition, + localPosition: tapUpDetails.localPosition, + kind: _kind, + ); dataGridConfiguration.onCellSecondaryTap!(details); } } @@ -323,29 +337,35 @@ class _GridHeaderCellState extends State { /// Helps to clear the editing cell when tap on header cells Future _clearEditing( - DataGridConfiguration dataGridConfiguration) async { + DataGridConfiguration dataGridConfiguration, + ) async { if (dataGridConfiguration.currentCell.isEditing) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + ); } } Widget _wrapInsideGestureDetector() { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); return GestureDetector( - onTapUp: dataGridConfiguration.onCellTap != null || - dataGridConfiguration.sortingGestureType == SortingGestureType.tap - ? _handleOnTapUp - : null, + onTapUp: + dataGridConfiguration.onCellTap != null || + dataGridConfiguration.sortingGestureType == + SortingGestureType.tap + ? _handleOnTapUp + : null, onTapDown: _handleOnTapDown, - onDoubleTap: dataGridConfiguration.onCellDoubleTap != null || - dataGridConfiguration.sortingGestureType == - SortingGestureType.doubleTap - ? _handleOnDoubleTap - : null, - onSecondaryTapUp: dataGridConfiguration.onCellSecondaryTap != null - ? _handleOnSecondaryTapUp - : null, + onDoubleTap: + dataGridConfiguration.onCellDoubleTap != null || + dataGridConfiguration.sortingGestureType == + SortingGestureType.doubleTap + ? _handleOnDoubleTap + : null, + onSecondaryTapUp: + dataGridConfiguration.onCellSecondaryTap != null + ? _handleOnSecondaryTapUp + : null, onSecondaryTapDown: _handleOnTapDown, child: _wrapInsideContainer(), ); @@ -357,36 +377,47 @@ class _GridHeaderCellState extends State { Widget checkHeaderCellConstraints(Widget child) { return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return _buildHeaderCell(child, _sortDirection, constraints.maxWidth); - }); + builder: (BuildContext context, BoxConstraints constraints) { + return _buildHeaderCell(child, _sortDirection, constraints.maxWidth); + }, + ); } _ensureSortIconVisibility(column!, dataGridConfiguration); Widget child = _wrapInsideCellContainer( - dataGridConfiguration: dataGridConfiguration, - child: checkHeaderCellConstraints(widget.child), - dataCell: widget.dataCell, - key: widget.key!, - backgroundColor: widget.backgroundColor); + dataGridConfiguration: dataGridConfiguration, + child: checkHeaderCellConstraints(widget.child), + dataCell: widget.dataCell, + key: widget.key!, + backgroundColor: widget.backgroundColor, + ); Widget getFeedbackWidget(DataGridConfiguration configuration) { return dataGridConfiguration.columnDragFeedbackBuilder != null ? dataGridConfiguration.columnDragFeedbackBuilder!( - context, widget.dataCell.gridColumn!) + context, + widget.dataCell.gridColumn!, + ) : Container( - width: widget.dataCell.gridColumn!.actualWidth, - height: dataGridConfiguration.headerRowHeight, - decoration: BoxDecoration( - color: dataGridConfiguration - .dataGridThemeHelper!.feedBackWidgetColor, - border: Border.all( - color: dataGridConfiguration - .dataGridThemeHelper!.gridLineColor!, - width: dataGridConfiguration - .dataGridThemeHelper!.gridLineStrokeWidth!)), - child: widget.child); + width: widget.dataCell.gridColumn!.actualWidth, + height: dataGridConfiguration.headerRowHeight, + decoration: BoxDecoration( + color: + dataGridConfiguration + .dataGridThemeHelper! + .feedBackWidgetColor, + border: Border.all( + color: + dataGridConfiguration.dataGridThemeHelper!.gridLineColor!, + width: + dataGridConfiguration + .dataGridThemeHelper! + .gridLineStrokeWidth!, + ), + ), + child: widget.child, + ); } Widget buildDraggableHeaderCell(Widget child) { @@ -396,18 +427,21 @@ class _GridHeaderCellState extends State { return Draggable( onDragStarted: () { if (widget.dataCell.cellType != CellType.indentCell) { - configuration.columnDragAndDropController - .onPointerDown(widget.dataCell); + configuration.columnDragAndDropController.onPointerDown( + widget.dataCell, + ); } }, ignoringFeedbackPointer: isWindowsPlatform, feedback: MouseRegion( - cursor: isWindowsPlatform - ? MouseCursor.defer - : (dataGridConfiguration.isMacPlatform && !kIsWeb) - ? SystemMouseCursors.grabbing - : SystemMouseCursors.move, - child: getFeedbackWidget(configuration)), + cursor: + isWindowsPlatform + ? MouseCursor.defer + : (dataGridConfiguration.isMacPlatform && !kIsWeb) + ? SystemMouseCursors.grabbing + : SystemMouseCursors.move, + child: getFeedbackWidget(configuration), + ), child: child, ); } @@ -415,21 +449,22 @@ class _GridHeaderCellState extends State { if (dataGridConfiguration.columnDragAndDropController .canAllowColumnDragAndDrop() && dataGridConfiguration - .columnDragAndDropController.canWrapDraggableView && + .columnDragAndDropController + .canWrapDraggableView && !dataGridConfiguration - .columnResizeController.canSwitchResizeColumnCursor) { + .columnResizeController + .canSwitchResizeColumnCursor) { child = buildDraggableHeaderCell(child); } return Container( - key: widget.key, - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration( - border: _getCellBorder( - dataGridConfiguration, - widget.dataCell, - )), - child: child); + key: widget.key, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + border: _getCellBorder(dataGridConfiguration, widget.dataCell), + ), + child: child, + ); } @override @@ -444,19 +479,26 @@ class _GridHeaderCellState extends State { } void _ensureSortIconVisibility( - GridColumn column, DataGridConfiguration? dataGridConfiguration) { + GridColumn column, + DataGridConfiguration? dataGridConfiguration, + ) { if (dataGridConfiguration != null) { final SortColumnDetails? sortColumn = dataGridConfiguration - .source.sortedColumns - .firstWhereOrNull((SortColumnDetails sortColumn) => - sortColumn.name == column.columnName); + .source + .sortedColumns + .firstWhereOrNull( + (SortColumnDetails sortColumn) => + sortColumn.name == column.columnName, + ); if (dataGridConfiguration.source.sortedColumns.isNotEmpty && sortColumn != null) { final int sortNumber = dataGridConfiguration.source.sortedColumns.indexOf(sortColumn) + 1; _sortDirection = sortColumn.sortDirection; - _sortNumberBackgroundColor = dataGridConfiguration - .dataGridThemeHelper!.sortOrderNumberBackgroundColor ?? + _sortNumberBackgroundColor = + dataGridConfiguration + .dataGridThemeHelper! + .sortOrderNumberBackgroundColor ?? dataGridConfiguration.colorScheme!.onSurface[31]!; _sortNumberTextColor = (dataGridConfiguration.dataGridThemeHelper!.sortOrderNumberColor ?? @@ -474,21 +516,29 @@ class _GridHeaderCellState extends State { } } - Widget _buildHeaderCell(Widget child, DataGridSortDirection? sortDirection, - double availableWidth) { + Widget _buildHeaderCell( + Widget child, + DataGridSortDirection? sortDirection, + double availableWidth, + ) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); final GridColumn gridColumn = widget.dataCell.gridColumn!; final bool isSortedColumn = dataGridConfiguration.source.sortedColumns.any( - (SortColumnDetails element) => element.name == gridColumn.columnName); + (SortColumnDetails element) => element.name == gridColumn.columnName, + ); final bool isSortNumberVisible = _sortNumber != -1; if ((isSortedColumn || (gridColumn.allowSorting && dataGridConfiguration.allowSorting)) || (gridColumn.allowFiltering && dataGridConfiguration.allowFiltering)) { - final double sortIconWidth = - getSortIconWidth(dataGridConfiguration.columnSizer, gridColumn); - final double filterIconWidth = - getFilterIconWidth(dataGridConfiguration.columnSizer, gridColumn); + final double sortIconWidth = getSortIconWidth( + dataGridConfiguration.columnSizer, + gridColumn, + ); + final double filterIconWidth = getFilterIconWidth( + dataGridConfiguration.columnSizer, + gridColumn, + ); if ((sortIconWidth > 0 && sortIconWidth < availableWidth) || (filterIconWidth > 0 && filterIconWidth < availableWidth)) { @@ -509,11 +559,13 @@ class _GridHeaderCellState extends State { ); } else { if (sortDirection == DataGridSortDirection.ascending) { - children['sortIcon'] = - _BuilderSortIconAscending(sortIcon: _sortIcon); + children['sortIcon'] = _BuilderSortIconAscending( + sortIcon: _sortIcon, + ); } else if (sortDirection == DataGridSortDirection.descending) { - children['sortIcon'] = - _BuilderSortIconDescending(sortIcon: _sortIcon); + children['sortIcon'] = _BuilderSortIconDescending( + sortIcon: _sortIcon, + ); } } if (_sortNumber != -1) { @@ -527,7 +579,8 @@ class _GridHeaderCellState extends State { fontPackage: 'syncfusion_flutter_datagrid', ); - children['sortIcon'] = _sortIcon ?? + children['sortIcon'] = + _sortIcon ?? Icon(unsortIconData, color: _sortIconColor, size: 16); } } @@ -541,13 +594,15 @@ class _GridHeaderCellState extends State { bool canShowColumnHeaderIcon() { final bool isFilteredColumn = dataGridConfiguration - .source.filterConditions + .source + .filterConditions .containsKey(gridColumn.columnName); if (dataGridConfiguration.showColumnHeaderIconOnHover && dataGridConfiguration.isDesktop) { return isHovered || dataGridConfiguration - .dataGridFilterHelper!.isFilterPopupMenuShowing || + .dataGridFilterHelper! + .isFilterPopupMenuShowing || isFilteredColumn || isSortedColumn; } else { @@ -559,18 +614,19 @@ class _GridHeaderCellState extends State { return Container( padding: dataGridConfiguration.columnSizer.iconsOuterPadding, child: Center( - child: isColumnHeaderIconVisible - ? Row( - children: [ - if (children.containsKey('sortIcon')) - children['sortIcon']!, - if (children.containsKey('sortNumber')) - children['sortNumber']!, - if (children.containsKey('filterIcon')) - children['filterIcon']!, - ], - ) - : const SizedBox(), + child: + isColumnHeaderIconVisible + ? Row( + children: [ + if (children.containsKey('sortIcon')) + children['sortIcon']!, + if (children.containsKey('sortNumber')) + children['sortNumber']!, + if (children.containsKey('filterIcon')) + children['filterIcon']!, + ], + ) + : const SizedBox(), ), ); } @@ -582,7 +638,7 @@ class _GridHeaderCellState extends State { headerCell = Row( children: [ Flexible(child: Container(child: child)), - buildHeaderCellIcons(isColumnHeaderIconVisible) + buildHeaderCellIcons(isColumnHeaderIconVisible), ], ); } else if (gridColumn.sortIconPosition == @@ -600,20 +656,14 @@ class _GridHeaderCellState extends State { headerCell = Row( children: [ if (isColumnHeaderIconVisible) - Center( - child: children['filterIcon'] ?? const SizedBox(), - ), - Flexible( - child: Container(child: child), - ), + Center(child: children['filterIcon'] ?? const SizedBox()), + Flexible(child: Container(child: child)), if (isColumnHeaderIconVisible) Container( padding: dataGridConfiguration.columnSizer.iconsOuterPadding, child: Row( children: [ - Center( - child: children['sortIcon'] ?? const SizedBox(), - ), + Center(child: children['sortIcon'] ?? const SizedBox()), if (isSortNumberVisible) Center(child: children['sortNumber']), ], @@ -629,21 +679,15 @@ class _GridHeaderCellState extends State { padding: dataGridConfiguration.columnSizer.iconsOuterPadding, child: Row( children: [ - Center( - child: children['sortIcon'] ?? const SizedBox(), - ), + Center(child: children['sortIcon'] ?? const SizedBox()), if (isSortNumberVisible) Center(child: children['sortNumber']), ], ), ), - Flexible( - child: Container(child: child), - ), + Flexible(child: Container(child: child)), if (isColumnHeaderIconVisible) - Center( - child: children['filterIcon'] ?? const SizedBox(), - ), + Center(child: children['filterIcon'] ?? const SizedBox()), ], ); } @@ -666,30 +710,40 @@ class _GridHeaderCellState extends State { color: _sortNumberBackgroundColor, ), child: Center( - child: Text(_sortNumber.toString(), - style: TextStyle(fontSize: 12, color: _sortNumberTextColor)), + child: Text( + _sortNumber.toString(), + style: TextStyle(fontSize: 12, color: _sortNumberTextColor), + ), ), ); } bool _raiseColumnSortChanging( - SortColumnDetails? newSortedColumn, SortColumnDetails? oldSortedColumn) { + SortColumnDetails? newSortedColumn, + SortColumnDetails? oldSortedColumn, + ) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (dataGridConfiguration.onColumnSortChanging == null) { return true; } return dataGridConfiguration.onColumnSortChanging!( - newSortedColumn, oldSortedColumn); + newSortedColumn, + oldSortedColumn, + ); } void _raiseColumnSortChanged( - SortColumnDetails? newSortedColumn, SortColumnDetails? oldSortedColumn) { + SortColumnDetails? newSortedColumn, + SortColumnDetails? oldSortedColumn, + ) { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); if (dataGridConfiguration.onColumnSortChanged == null) { return; } dataGridConfiguration.onColumnSortChanged!( - newSortedColumn, oldSortedColumn); + newSortedColumn, + oldSortedColumn, + ); } void _sort(DataCellBase dataCell) { @@ -706,18 +760,21 @@ class _GridHeaderCellState extends State { //End-edit before perform sorting if (dataGridConfiguration.currentCell.isEditing) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, canRefresh: false); + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + canRefresh: false, + ); } final GridColumn column = dataCell.gridColumn!; if (column.allowSorting && dataGridConfiguration.allowSorting) { final String sortColumnName = column.columnName; - final bool allowMultiSort = dataGridConfiguration.isMacPlatform - ? (dataGridConfiguration.isCommandKeyPressed && - dataGridConfiguration.allowMultiColumnSorting) - : dataGridConfiguration.isDesktop + final bool allowMultiSort = + dataGridConfiguration.isMacPlatform + ? (dataGridConfiguration.isCommandKeyPressed && + dataGridConfiguration.allowMultiColumnSorting) + : dataGridConfiguration.isDesktop ? (dataGridConfiguration.isControlKeyPressed && dataGridConfiguration.allowMultiColumnSorting) : dataGridConfiguration.allowMultiColumnSorting; @@ -726,12 +783,13 @@ class _GridHeaderCellState extends State { final List sortedColumns = source.sortedColumns; if (sortedColumns.isNotEmpty && allowMultiSort) { SortColumnDetails? sortedColumn = sortedColumns.firstWhereOrNull( - (SortColumnDetails sortColumn) => - sortColumn.name == sortColumnName); + (SortColumnDetails sortColumn) => sortColumn.name == sortColumnName, + ); if (sortedColumn == null) { final SortColumnDetails newSortColumn = SortColumnDetails( - name: sortColumnName, - sortDirection: DataGridSortDirection.ascending); + name: sortColumnName, + sortDirection: DataGridSortDirection.ascending, + ); if (_raiseColumnSortChanging(newSortColumn, sortedColumn)) { sortedColumns.add(newSortColumn); _raiseColumnSortChanged(newSortColumn, sortedColumn); @@ -739,23 +797,28 @@ class _GridHeaderCellState extends State { } else { if (sortedColumn.sortDirection == DataGridSortDirection.descending && dataGridConfiguration.allowTriStateSorting) { - final SortColumnDetails? removedSortColumn = - sortedColumns.firstWhereOrNull((SortColumnDetails sortColumn) => - sortColumn.name == sortColumnName); + final SortColumnDetails? removedSortColumn = sortedColumns + .firstWhereOrNull( + (SortColumnDetails sortColumn) => + sortColumn.name == sortColumnName, + ); if (_raiseColumnSortChanging(null, removedSortColumn)) { sortedColumns.remove(removedSortColumn); _raiseColumnSortChanged(null, removedSortColumn); } } else { sortedColumn = SortColumnDetails( - name: sortedColumn.name, - sortDirection: sortedColumn.sortDirection == - DataGridSortDirection.ascending - ? DataGridSortDirection.descending - : DataGridSortDirection.ascending); - final SortColumnDetails? removedSortColumn = - sortedColumns.firstWhereOrNull((SortColumnDetails sortColumn) => - sortColumn.name == sortedColumn!.name); + name: sortedColumn.name, + sortDirection: + sortedColumn.sortDirection == DataGridSortDirection.ascending + ? DataGridSortDirection.descending + : DataGridSortDirection.ascending, + ); + final SortColumnDetails? removedSortColumn = sortedColumns + .firstWhereOrNull( + (SortColumnDetails sortColumn) => + sortColumn.name == sortedColumn!.name, + ); if (_raiseColumnSortChanging(sortedColumn, removedSortColumn)) { sortedColumns ..remove(removedSortColumn) @@ -766,8 +829,8 @@ class _GridHeaderCellState extends State { } } else { SortColumnDetails? currentSortColumn = sortedColumns.firstWhereOrNull( - (SortColumnDetails sortColumn) => - sortColumn.name == sortColumnName); + (SortColumnDetails sortColumn) => sortColumn.name == sortColumnName, + ); if (sortedColumns.isNotEmpty && currentSortColumn != null) { if (currentSortColumn.sortDirection == DataGridSortDirection.descending && @@ -778,17 +841,21 @@ class _GridHeaderCellState extends State { } } else { currentSortColumn = SortColumnDetails( - name: currentSortColumn.name, - sortDirection: currentSortColumn.sortDirection == - DataGridSortDirection.ascending - ? DataGridSortDirection.descending - : DataGridSortDirection.ascending); + name: currentSortColumn.name, + sortDirection: + currentSortColumn.sortDirection == + DataGridSortDirection.ascending + ? DataGridSortDirection.descending + : DataGridSortDirection.ascending, + ); final SortColumnDetails oldSortColumn = SortColumnDetails( - name: currentSortColumn.name, - sortDirection: currentSortColumn.sortDirection == - DataGridSortDirection.ascending - ? DataGridSortDirection.descending - : DataGridSortDirection.ascending); + name: currentSortColumn.name, + sortDirection: + currentSortColumn.sortDirection == + DataGridSortDirection.ascending + ? DataGridSortDirection.descending + : DataGridSortDirection.ascending, + ); if (_raiseColumnSortChanging(currentSortColumn, oldSortColumn)) { sortedColumns ..clear() @@ -798,12 +865,14 @@ class _GridHeaderCellState extends State { } } else { final SortColumnDetails sortColumn = SortColumnDetails( - name: sortColumnName, - sortDirection: DataGridSortDirection.ascending); + name: sortColumnName, + sortDirection: DataGridSortDirection.ascending, + ); if (sortedColumns.isNotEmpty) { final SortColumnDetails oldSortColumn = SortColumnDetails( - name: sortedColumns.last.name, - sortDirection: sortedColumns.last.sortDirection); + name: sortedColumns.last.name, + sortDirection: sortedColumns.last.sortDirection, + ); if (_raiseColumnSortChanging(sortColumn, oldSortColumn)) { sortedColumns ..clear() @@ -848,10 +917,11 @@ class _BuilderSortIconDescending extends StatelessWidget { } class _SortIcon extends StatefulWidget { - const _SortIcon( - {required this.sortDirection, - required this.sortIconColor, - required this.sortIcon}); + const _SortIcon({ + required this.sortDirection, + required this.sortIconColor, + required this.sortIcon, + }); final DataGridSortDirection sortDirection; final Color sortIconColor; final Widget? sortIcon; @@ -892,12 +962,9 @@ class _SortIconState extends State<_SortIcon> Widget build(BuildContext context) { return RotationTransition( turns: Tween(begin: 0.0, end: 0.5).animate(_animationController), - child: widget.sortIcon ?? - Icon( - Icons.arrow_upward, - color: widget.sortIconColor, - size: 16, - ), + child: + widget.sortIcon ?? + Icon(Icons.arrow_upward, color: widget.sortIconColor, size: 16), ); } @@ -909,9 +976,11 @@ class _SortIconState extends State<_SortIcon> } class _FilterIcon extends StatelessWidget { - const _FilterIcon( - {Key? key, required this.column, required this.dataGridConfiguration}) - : super(key: key); + const _FilterIcon({ + Key? key, + required this.column, + required this.dataGridConfiguration, + }) : super(key: key); final GridColumn column; final DataGridConfiguration dataGridConfiguration; @@ -930,22 +999,31 @@ class _FilterIcon extends StatelessWidget { final Offset newOffset = renderBox.globalToLocal(details.globalPosition); final Size viewSize = renderBox.size; showMenu( - surfaceTintColor: Colors.transparent, - context: context, - color: - dataGridConfiguration.dataGridThemeHelper!.filterPopupOuterColor, - constraints: const BoxConstraints(maxWidth: 274.0), - position: RelativeRect.fromSize(newOffset & Size.zero, viewSize), - items: >[ - _FilterPopupMenuItem( - column: column, dataGridConfiguration: dataGridConfiguration), - ]).then((_) { + surfaceTintColor: Colors.transparent, + context: context, + color: + dataGridConfiguration + .dataGridThemeHelper! + .filterPopupBackgroundColor, + constraints: const BoxConstraints(maxWidth: 274.0), + position: RelativeRect.fromSize(newOffset & Size.zero, viewSize), + items: >[ + _FilterPopupMenuItem( + column: column, + dataGridConfiguration: dataGridConfiguration, + ), + ], + ).then((_) { if (dataGridConfiguration.isDesktop) { - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'Filtering'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'Filtering', + ); if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } dataGridConfiguration.dataGridFilterHelper!.isFilterPopupMenuShowing = false; @@ -953,11 +1031,15 @@ class _FilterIcon extends StatelessWidget { }); } else { Navigator.push<_FilterPopup>( - context, - MaterialPageRoute<_FilterPopup>( - builder: (BuildContext context) => _FilterPopup( - column: column, - dataGridConfiguration: dataGridConfiguration))); + context, + MaterialPageRoute<_FilterPopup>( + builder: + (BuildContext context) => _FilterPopup( + column: column, + dataGridConfiguration: dataGridConfiguration, + ), + ), + ); } } @@ -972,59 +1054,77 @@ class _FilterIcon extends StatelessWidget { child: Padding( padding: column.filterIconPadding, child: StatefulBuilder( - builder: (BuildContext context, StateSetter setState) { - return MouseRegion( - onEnter: (_) { - setState(() { - isHovered = true; - }); - }, - onExit: (_) { - setState(() { - isHovered = false; - }); - }, - child: isFiltered - ? _FilteredIcon( - iconColor: isHovered - ? (dataGridConfiguration - .dataGridThemeHelper!.filterIconHoverColor ?? - dataGridConfiguration.colorScheme!.onSurface[222]!) - : (dataGridConfiguration - .dataGridThemeHelper!.filterIconColor ?? + builder: (BuildContext context, StateSetter setState) { + return MouseRegion( + onEnter: (_) { + setState(() { + isHovered = true; + }); + }, + onExit: (_) { + setState(() { + isHovered = false; + }); + }, + child: + isFiltered + ? _FilteredIcon( + iconColor: + isHovered + ? (dataGridConfiguration + .dataGridThemeHelper! + .filterIconHoverColor ?? + dataGridConfiguration + .colorScheme! + .onSurface[222]!) + : (dataGridConfiguration + .dataGridThemeHelper! + .filterIconColor ?? + dataGridConfiguration + .dataGridThemeHelper! + .filterPopupIconColor!), + filterIcon: dataGridConfiguration - .dataGridThemeHelper!.filterPopupIconColor!), - filterIcon: - dataGridConfiguration.dataGridThemeHelper!.filterIcon, - gridColumnName: column.columnName, - ) - : _UnfilteredIcon( - iconColor: isHovered - ? (dataGridConfiguration - .dataGridThemeHelper!.filterIconHoverColor ?? - dataGridConfiguration.colorScheme!.onSurface[222]!) - : (dataGridConfiguration - .dataGridThemeHelper!.filterIconColor ?? + .dataGridThemeHelper! + .filterIcon, + gridColumnName: column.columnName, + ) + : _UnfilteredIcon( + iconColor: + isHovered + ? (dataGridConfiguration + .dataGridThemeHelper! + .filterIconHoverColor ?? + dataGridConfiguration + .colorScheme! + .onSurface[222]!) + : (dataGridConfiguration + .dataGridThemeHelper! + .filterIconColor ?? + dataGridConfiguration + .dataGridThemeHelper! + .filterPopupIconColor!), + filterIcon: dataGridConfiguration - .dataGridThemeHelper!.filterPopupIconColor!), - filterIcon: - dataGridConfiguration.dataGridThemeHelper!.filterIcon, - gridColumnName: column.columnName, - ), - ); - }), + .dataGridThemeHelper! + .filterIcon, + gridColumnName: column.columnName, + ), + ); + }, + ), ), ); } } class _UnfilteredIcon extends StatelessWidget { - const _UnfilteredIcon( - {Key? key, - required this.iconColor, - required this.filterIcon, - required this.gridColumnName}) - : super(key: key); + const _UnfilteredIcon({ + Key? key, + required this.iconColor, + required this.filterIcon, + required this.gridColumnName, + }) : super(key: key); final Color iconColor; final Widget? filterIcon; @@ -1034,24 +1134,27 @@ class _UnfilteredIcon extends StatelessWidget { Widget build(BuildContext context) { return filterIcon ?? Icon( - const IconData(0xe702, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid'), + const IconData( + 0xe702, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ), size: 18.0, color: iconColor, key: ValueKey( - 'datagrid_filtering_${gridColumnName}_filterIcon'), + 'datagrid_filtering_${gridColumnName}_filterIcon', + ), ); } } class _FilteredIcon extends StatelessWidget { - const _FilteredIcon( - {Key? key, - required this.iconColor, - required this.filterIcon, - required this.gridColumnName}) - : super(key: key); + const _FilteredIcon({ + Key? key, + required this.iconColor, + required this.filterIcon, + required this.gridColumnName, + }) : super(key: key); final Color iconColor; final Widget? filterIcon; @@ -1061,21 +1164,25 @@ class _FilteredIcon extends StatelessWidget { Widget build(BuildContext context) { return filterIcon ?? Icon( - const IconData(0xe704, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid'), + const IconData( + 0xe704, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ), size: 18.0, color: iconColor, key: ValueKey( - 'datagrid_filtering_${gridColumnName}_filterIcon'), + 'datagrid_filtering_${gridColumnName}_filterIcon', + ), ); } } class _FilterPopupMenuItem extends PopupMenuItem { - const _FilterPopupMenuItem( - {required this.column, required this.dataGridConfiguration}) - : super(child: null); + const _FilterPopupMenuItem({ + required this.column, + required this.dataGridConfiguration, + }) : super(child: null); final GridColumn column; @@ -1089,15 +1196,18 @@ class _FilterPopupMenuItemState @override Widget build(BuildContext context) { return _FilterPopup( - column: widget.column, - dataGridConfiguration: widget.dataGridConfiguration); + column: widget.column, + dataGridConfiguration: widget.dataGridConfiguration, + ); } } class _FilterPopup extends StatefulWidget { - const _FilterPopup( - {Key? key, required this.column, required this.dataGridConfiguration}) - : super(key: key); + const _FilterPopup({ + Key? key, + required this.column, + required this.dataGridConfiguration, + }) : super(key: key); final GridColumn column; @@ -1126,17 +1236,16 @@ class _FilterPopupState extends State<_FilterPopup> { Widget build(BuildContext context) { return Visibility( visible: isMobile, - replacement: Material( - child: _buildPopupView(), - ), + replacement: Material(child: _buildPopupView()), child: Theme( data: ThemeData( - colorScheme: Theme.of(context).colorScheme, - // Issue: FLUT-869897-The color of the filter pop-up menu was not working properly - // on the Mobile platform when using the Material 2. - // - // Fix: We have to set the useMaterial3 property to the theme data to resolve the above issue. - useMaterial3: Theme.of(context).useMaterial3), + colorScheme: Theme.of(context).colorScheme, + // Issue: FLUT-869897-The color of the filter pop-up menu was not working properly + // on the Mobile platform when using the Material 2. + // + // Fix: We have to set the useMaterial3 property to the theme data to resolve the above issue. + useMaterial3: Theme.of(context).useMaterial3, + ), child: SafeArea( child: Scaffold( backgroundColor: dataGridThemeHelper.filterPopupOuterColor, @@ -1175,8 +1284,10 @@ class _FilterPopupState extends State<_FilterPopup> { final DataGridAdvancedFilterHelper advancedFilterHelper = filterHelper.advancedFilterHelper; - final List? filterConditions = widget.dataGridConfiguration - .source.filterConditions[widget.column.columnName]; + final List? filterConditions = + widget.dataGridConfiguration.source.filterConditions[widget + .column + .columnName]; if (filterConditions == null) { filterHelper.setFilterFrom(widget.column, FilteredFrom.none); @@ -1193,10 +1304,14 @@ class _FilterPopupState extends State<_FilterPopup> { /// Initializes the advanced filter properties. if (filterConditions != null && isAdvancedFilter) { advancedFilterHelper.setAdvancedFilterValues( - widget.dataGridConfiguration, filterConditions, filterHelper); + widget.dataGridConfiguration, + filterConditions, + filterHelper, + ); } else { - advancedFilterHelper - .resetAdvancedFilterValues(widget.dataGridConfiguration); + advancedFilterHelper.resetAdvancedFilterValues( + widget.dataGridConfiguration, + ); } } @@ -1206,31 +1321,53 @@ class _FilterPopupState extends State<_FilterPopup> { child: AppBar( elevation: 0.0, bottom: PreferredSize( - preferredSize: const Size.fromHeight(1.0), - child: Container( - height: 1.0, - color: dataGridThemeHelper.filterPopupBorderColor)), + preferredSize: const Size.fromHeight(1.0), + child: Container( + height: 1.0, + color: + dataGridThemeHelper.appBarBottomBorderColor ?? + dataGridThemeHelper.filterPopupBorderColor, + ), + ), backgroundColor: dataGridThemeHelper.filterPopupBackgroundColor, leading: IconButton( - key: const ValueKey('datagrid_filtering_cancelFilter_icon'), - onPressed: closePage, - icon: Icon(Icons.close, - size: 22.0, color: dataGridThemeHelper.filterPopupIconColor)), + key: const ValueKey('datagrid_filtering_cancelFilter_icon'), + onPressed: closePage, + icon: Icon( + Icons.close, + size: 22.0, + color: + dataGridThemeHelper.cancelFilteringLabelButtonColor ?? + dataGridThemeHelper.filterPopupIconColor, + ), + ), centerTitle: false, titleSpacing: 0, title: Text( - widget.dataGridConfiguration.localizations - .sortAndFilterDataGridFilteringLabel, - style: filterHelper.textStyle), + widget + .dataGridConfiguration + .localizations + .sortAndFilterDataGridFilteringLabel, + style: filterHelper.textStyle, + ), actions: [ IconButton( key: const ValueKey('datagrid_filtering_applyFilter_icon'), onPressed: canDisableOkButton() ? null : onHandleOkButtonTap, - icon: Icon(Icons.check, - size: 22.0, - color: canDisableOkButton() - ? widget.dataGridConfiguration.colorScheme!.onSurface[97] - : filterHelper.primaryColor), + icon: Icon( + Icons.check, + size: 22.0, + color: + canDisableOkButton() + ? dataGridThemeHelper + .okFilteringLabelDisabledButtonColor ?? + widget + .dataGridConfiguration + .colorScheme! + .onSurface[97] + : dataGridThemeHelper.okFilteringLabelButtonColor ?? + filterHelper.primaryColor, + ), ), ], ), @@ -1243,10 +1380,12 @@ class _FilterPopupState extends State<_FilterPopup> { filterHelper.advancedFilterHelper.advancedFilterType; final SfLocalizations localizations = widget.dataGridConfiguration.localizations; - final bool isSortAscendingEnabled = - canEnableSortButton(DataGridSortDirection.ascending); - final bool isSortDescendingEnabled = - canEnableSortButton(DataGridSortDirection.descending); + final bool isSortAscendingEnabled = canEnableSortButton( + DataGridSortDirection.ascending, + ); + final bool isSortDescendingEnabled = canEnableSortButton( + DataGridSortDirection.descending, + ); final bool isClearFilterEnabled = hasFilterConditions(); const FilterPopupMenuOptions filterPopupMenuOptions = FilterPopupMenuOptions(); @@ -1265,10 +1404,10 @@ class _FilterPopupState extends State<_FilterPopup> { if (widget.column.filterPopupMenuOptions != null) { isCheckboxFilterEnabled = widget.column.filterPopupMenuOptions!.filterMode == - FilterMode.checkboxFilter; + FilterMode.checkboxFilter; isAdvancedFilterEnabled = widget.column.filterPopupMenuOptions!.filterMode == - FilterMode.advancedFilter; + FilterMode.advancedFilter; isBothFilterEnabled = widget.column.filterPopupMenuOptions!.filterMode == FilterMode.both; canShowSortingOptions = @@ -1278,6 +1417,12 @@ class _FilterPopupState extends State<_FilterPopup> { showColumnName = widget.column.filterPopupMenuOptions!.showColumnName; } Widget buildPopup({Size? viewSize}) { + widget.dataGridConfiguration.dataGridFocusNode!.requestFocus(); + final Widget advanceFilterPopupMenu = _AdvancedFilterPopupMenu( + setState: setState, + dataGridConfiguration: widget.dataGridConfiguration, + advanceFilterTopPadding: advanceFilterTopPadding, + ); return SingleChildScrollView( key: const ValueKey('datagrid_filtering_scrollView'), child: Container( @@ -1287,56 +1432,73 @@ class _FilterPopupState extends State<_FilterPopup> { children: [ if (canShowSortingOptions) _FilterPopupMenuTile( - style: isSortAscendingEnabled - ? filterHelper.textStyle - : filterHelper.disableTextStyle, - height: filterHelper.tileHeight, - prefix: Icon( - const IconData(0xe700, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid'), - color: isSortAscendingEnabled - ? iconColor - : dataGridThemeHelper.filterPopupDisableIconColor, - size: filterHelper.textStyle.fontSize! + 10, + style: + isSortAscendingEnabled + ? filterHelper.textStyle + : filterHelper.disableTextStyle, + height: filterHelper.tileHeight, + prefix: Icon( + const IconData( + 0xe700, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', ), - prefixPadding: EdgeInsets.only( - left: 4.0, - right: filterHelper.textStyle.fontSize!, - bottom: filterHelper.textStyle.fontSize! > 14 + color: + isSortAscendingEnabled + ? iconColor + : dataGridThemeHelper.filterPopupDisabledIconColor, + size: filterHelper.textStyle.fontSize! + 10, + ), + prefixPadding: EdgeInsets.only( + left: 4.0, + right: filterHelper.textStyle.fontSize!, + bottom: + filterHelper.textStyle.fontSize! > 14 ? filterHelper.textStyle.fontSize! - 14 - : 0), - onTap: isSortAscendingEnabled - ? onHandleSortAscendingTap - : null, - child: Text( - grid_helper.getSortButtonText( - localizations, true, filterType), - overflow: TextOverflow.ellipsis)), + : 0, + ), + onTap: + isSortAscendingEnabled ? onHandleSortAscendingTap : null, + child: Text( + grid_helper.getSortButtonText( + localizations, + true, + filterType, + ), + overflow: TextOverflow.ellipsis, + ), + ), if (canShowSortingOptions) _FilterPopupMenuTile( - style: isSortDescendingEnabled - ? filterHelper.textStyle - : filterHelper.disableTextStyle, + style: + isSortDescendingEnabled + ? filterHelper.textStyle + : filterHelper.disableTextStyle, height: filterHelper.tileHeight, prefix: Icon( - const IconData(0xe701, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid'), - color: isSortDescendingEnabled - ? iconColor - : dataGridThemeHelper.filterPopupDisableIconColor, + const IconData( + 0xe701, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ), + color: + isSortDescendingEnabled + ? iconColor + : dataGridThemeHelper.filterPopupDisabledIconColor, size: filterHelper.textStyle.fontSize! + 10, ), prefixPadding: EdgeInsets.only( - left: 4.0, - right: filterHelper.textStyle.fontSize!, - bottom: filterHelper.textStyle.fontSize! > 14 - ? filterHelper.textStyle.fontSize! - 14 - : 0), - onTap: isSortDescendingEnabled - ? onHandleSortDescendingTap - : null, + left: 4.0, + right: filterHelper.textStyle.fontSize!, + bottom: + filterHelper.textStyle.fontSize! > 14 + ? filterHelper.textStyle.fontSize! - 14 + : 0, + ), + onTap: + isSortDescendingEnabled + ? onHandleSortDescendingTap + : null, child: Text( grid_helper.getSortButtonText( localizations, @@ -1347,30 +1509,43 @@ class _FilterPopupState extends State<_FilterPopup> { ), ), if (canShowSortingOptions) - const Divider(indent: 8.0, endIndent: 8.0), + Divider( + indent: 8.0, + endIndent: 8.0, + color: dataGridThemeHelper.filterPopupTopDividerColor, + ), if (canShowClearFilterOption) _FilterPopupMenuTile( - style: isClearFilterEnabled - ? filterHelper.textStyle - : filterHelper.disableTextStyle, + style: + isClearFilterEnabled + ? filterHelper.textStyle + : filterHelper.disableTextStyle, height: filterHelper.tileHeight, prefix: Icon( - const IconData(0xe703, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid'), - size: filterHelper.textStyle.fontSize! + 8, - color: isClearFilterEnabled - ? iconColor - : dataGridThemeHelper.filterPopupDisableIconColor), + const IconData( + 0xe703, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ), + size: filterHelper.textStyle.fontSize! + 8, + color: + isClearFilterEnabled + ? iconColor + : dataGridThemeHelper.filterPopupDisabledIconColor, + ), prefixPadding: EdgeInsets.only( - left: 4.0, - right: filterHelper.textStyle.fontSize!, - bottom: filterHelper.textStyle.fontSize! > 14 - ? filterHelper.textStyle.fontSize! - 14 - : 0), + left: 4.0, + right: filterHelper.textStyle.fontSize!, + bottom: + filterHelper.textStyle.fontSize! > 14 + ? filterHelper.textStyle.fontSize! - 14 + : 0, + ), onTap: isClearFilterEnabled ? onHandleClearFilterTap : null, - child: Text(getClearFilterText(localizations, showColumnName), - overflow: TextOverflow.ellipsis), + child: Text( + getClearFilterText(localizations, showColumnName), + overflow: TextOverflow.ellipsis, + ), ), if (isAdvancedFilterEnabled) _AdvancedFilterPopupMenu( @@ -1384,28 +1559,39 @@ class _FilterPopupState extends State<_FilterPopup> { height: filterHelper.tileHeight, onTap: onHandleExpansionTileTap, prefix: Icon( - filterHelper.getFilterForm(widget.column) == - FilteredFrom.advancedFilter - ? const IconData(0xe704, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid') - : const IconData(0xe702, - fontFamily: 'FilterIcon', - fontPackage: 'syncfusion_flutter_datagrid'), - size: filterHelper.textStyle.fontSize! + 6, - color: iconColor), + filterHelper.getFilterForm(widget.column) == + FilteredFrom.advancedFilter + ? const IconData( + 0xe704, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ) + : const IconData( + 0xe702, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ), + size: filterHelper.textStyle.fontSize! + 6, + color: iconColor, + ), suffix: Icon( - isAdvancedFilter - ? Icons.keyboard_arrow_down - : Icons.keyboard_arrow_right, - size: filterHelper.textStyle.fontSize! + 6, - color: iconColor), + isAdvancedFilter + ? Icons.keyboard_arrow_down + : Icons.keyboard_arrow_right, + size: filterHelper.textStyle.fontSize! + 6, + color: + dataGridThemeHelper + .advancedFilterPopupDropdownIconColor ?? + iconColor, + ), prefixPadding: EdgeInsets.only( - left: 4.0, - right: filterHelper.textStyle.fontSize!, - bottom: filterHelper.textStyle.fontSize! > 14 - ? filterHelper.textStyle.fontSize! - 14 - : 0), + left: 4.0, + right: filterHelper.textStyle.fontSize!, + bottom: + filterHelper.textStyle.fontSize! > 14 + ? filterHelper.textStyle.fontSize! - 14 + : 0, + ), child: Text( grid_helper.getFilterTileText(localizations, filterType), overflow: TextOverflow.ellipsis, @@ -1420,13 +1606,21 @@ class _FilterPopupState extends State<_FilterPopup> { viewSize: viewSize, dataGridConfiguration: widget.dataGridConfiguration, ), - child: _AdvancedFilterPopupMenu( - setState: setState, - dataGridConfiguration: widget.dataGridConfiguration, - advanceFilterTopPadding: advanceFilterTopPadding, - ), + child: + isMobile + ? ConstrainedBox( + constraints: BoxConstraints( + minHeight: viewSize!.height, + ), + child: advanceFilterPopupMenu, + ) + : advanceFilterPopupMenu, + ), + if (!isMobile) + Divider( + height: 10, + color: dataGridThemeHelper.filterPopupBottomDividerColor, ), - if (!isMobile) const Divider(height: 10), if (!isMobile) Padding( padding: const EdgeInsets.symmetric(vertical: 6.0), @@ -1437,54 +1631,69 @@ class _FilterPopupState extends State<_FilterPopup> { width: 120.0, height: filterHelper.tileHeight - 8, child: ElevatedButton( - style: ButtonStyle( - backgroundColor: - WidgetStateProperty.resolveWith( - (Set states) { - // Issue: - // FLUT-7487-The buttons UX in the filter popup menu is not very intuitive when using Material 3 design. - // - // Fix: - // There is an issue with the button user experience (UX) in the filter popup menu, - // which is caused by the default background color of the "ElevatedButton" widget - // being set to the surface color in the Material 3 design. To address this issue, - // we set the background color of the button to the primary color if it is not disabled. - // This means that the default value is ignored, and the given color is used instead. - if (states.contains(WidgetState.disabled)) { - return null; - } else { - return filterHelper.primaryColor; - } - }, - ), + style: ButtonStyle( + backgroundColor: WidgetStateProperty.resolveWith< + Color? + >((Set states) { + // Issue: + // FLUT-7487-The buttons UX in the filter popup menu is not very intuitive when using Material 3 design. + // + // Fix: + // There is an issue with the button user experience (UX) in the filter popup menu, + // which is caused by the default background color of the "ElevatedButton" widget + // being set to the surface color in the Material 3 design. To address this issue, + // we set the background color of the button to the primary color if it is not disabled. + // This means that the default value is ignored, and the given color is used instead. + if (states.contains(WidgetState.disabled)) { + return dataGridThemeHelper + .okFilteringLabelDisabledButtonColor; + } else { + return dataGridThemeHelper + .okFilteringLabelButtonColor ?? + filterHelper.primaryColor; + } + }), + ), + onPressed: + canDisableOkButton() ? null : onHandleOkButtonTap, + child: Text( + localizations.okDataGridFilteringLabel, + style: TextStyle( + color: + dataGridThemeHelper.okFilteringLabelColor ?? + const Color(0xFFFFFFFF), + fontSize: filterHelper.textStyle.fontSize, + fontFamily: filterHelper.textStyle.fontFamily, ), - onPressed: canDisableOkButton() - ? null - : onHandleOkButtonTap, - child: Text(localizations.okDataGridFilteringLabel, - style: TextStyle( - color: const Color(0xFFFFFFFF), - fontSize: filterHelper.textStyle.fontSize, - fontFamily: - filterHelper.textStyle.fontFamily))), + ), + ), ), SizedBox( width: 120.0, height: filterHelper.tileHeight - 8, child: OutlinedButton( - onPressed: closePage, - child: Text( - localizations.cancelDataGridFilteringLabel, - style: TextStyle( - color: filterHelper.primaryColor, - fontSize: filterHelper.textStyle.fontSize, - fontFamily: - filterHelper.textStyle.fontFamily), - )), + style: OutlinedButton.styleFrom( + backgroundColor: + dataGridThemeHelper + .cancelFilteringLabelButtonColor, + ), + onPressed: closePage, + child: Text( + localizations.cancelDataGridFilteringLabel, + style: TextStyle( + color: + dataGridThemeHelper + .cancelFilteringLabelColor ?? + filterHelper.primaryColor, + fontSize: filterHelper.textStyle.fontSize, + fontFamily: filterHelper.textStyle.fontFamily, + ), + ), + ), ), ], ), - ) + ), ], ), ), @@ -1502,27 +1711,55 @@ class _FilterPopupState extends State<_FilterPopup> { if (isMobile) { return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) => - buildPopup(viewSize: constraints.biggest)); + builder: + (BuildContext context, BoxConstraints constraints) => + buildPopup(viewSize: constraints.biggest), + ); } else { return buildPopup(); } } - void onHandleSortAscendingTap() { - if (widget.dataGridConfiguration.allowSorting) { - filterHelper.onSortButtonClick( - widget.column, DataGridSortDirection.ascending); + void onHandleSortTap(DataGridSortDirection direction) { + if (!widget.dataGridConfiguration.allowSorting) { + return; + } + + final sortedColumns = widget.dataGridConfiguration.source.sortedColumns; + + final oldSortedColumn = + sortedColumns.isNotEmpty + ? SortColumnDetails( + name: sortedColumns.last.name, + sortDirection: sortedColumns.last.sortDirection, + ) + : null; + + final newSortedColumn = SortColumnDetails( + name: widget.column.columnName, + sortDirection: direction, + ); + + final onColumnSortChangingHandler = + widget.dataGridConfiguration.onColumnSortChanging; + + if (onColumnSortChangingHandler?.call(newSortedColumn, oldSortedColumn) ?? + true) { + filterHelper.onSortButtonClick(widget.column, direction); + widget.dataGridConfiguration.onColumnSortChanged?.call( + newSortedColumn, + oldSortedColumn, + ); } Navigator.pop(context); } + void onHandleSortAscendingTap() { + onHandleSortTap(DataGridSortDirection.ascending); + } + void onHandleSortDescendingTap() { - if (widget.dataGridConfiguration.allowSorting) { - filterHelper.onSortButtonClick( - widget.column, DataGridSortDirection.descending); - } - Navigator.pop(context); + onHandleSortTap(DataGridSortDirection.descending); } void onHandleClearFilterTap() { @@ -1546,8 +1783,9 @@ class _FilterPopupState extends State<_FilterPopup> { } bool hasFilterConditions() { - return widget.dataGridConfiguration.source.filterConditions - .containsKey(widget.column.columnName); + return widget.dataGridConfiguration.source.filterConditions.containsKey( + widget.column.columnName, + ); } bool canDisableOkButton() { @@ -1569,9 +1807,11 @@ class _FilterPopupState extends State<_FilterPopup> { final DataGridConfiguration configuration = widget.dataGridConfiguration; if (configuration.allowSorting && widget.column.allowSorting) { return configuration.source.sortedColumns.isEmpty || - !configuration.source.sortedColumns.any((SortColumnDetails column) => - column.name == widget.column.columnName && - column.sortDirection == sortDirection); + !configuration.source.sortedColumns.any( + (SortColumnDetails column) => + column.name == widget.column.columnName && + column.sortDirection == sortDirection, + ); } return false; } @@ -1586,16 +1826,16 @@ class _FilterPopupState extends State<_FilterPopup> { } class _FilterPopupMenuTile extends StatelessWidget { - const _FilterPopupMenuTile( - {Key? key, - required this.child, - this.onTap, - this.prefix, - this.suffix, - this.height, - required this.style, - this.prefixPadding = EdgeInsets.zero}) - : super(key: key); + const _FilterPopupMenuTile({ + Key? key, + required this.child, + this.onTap, + this.prefix, + this.suffix, + this.height, + required this.style, + this.prefixPadding = EdgeInsets.zero, + }) : super(key: key); final Widget child; @@ -1621,16 +1861,10 @@ class _FilterPopupMenuTile extends StatelessWidget { children: [ Padding( padding: prefixPadding, - child: SizedBox( - width: 24.0, - height: 24.0, - child: prefix, - ), - ), - Expanded( - child: DefaultTextStyle(style: style, child: child), + child: SizedBox(width: 24.0, height: 24.0, child: prefix), ), - if (suffix != null) SizedBox(width: 40.0, child: suffix) + Expanded(child: DefaultTextStyle(style: style, child: child)), + if (suffix != null) SizedBox(width: 40.0, child: suffix), ], ), ), @@ -1639,13 +1873,13 @@ class _FilterPopupMenuTile extends StatelessWidget { } class _FilterMenuDropdown extends StatelessWidget { - const _FilterMenuDropdown( - {required this.child, - required this.padding, - required this.height, - this.suffix, - Key? key}) - : super(key: key); + const _FilterMenuDropdown({ + required this.child, + required this.padding, + required this.height, + this.suffix, + Key? key, + }) : super(key: key); final Widget child; @@ -1663,14 +1897,9 @@ class _FilterMenuDropdown extends StatelessWidget { height: height, child: Row( children: [ - Expanded( - child: child, - ), + Expanded(child: child), if (suffix != null) - Padding( - padding: const EdgeInsets.only(left: 10), - child: suffix, - ) + Padding(padding: const EdgeInsets.only(left: 10), child: suffix), ], ), ), @@ -1679,13 +1908,13 @@ class _FilterMenuDropdown extends StatelessWidget { } class _CheckboxFilterMenu extends StatelessWidget { - _CheckboxFilterMenu( - {Key? key, - required this.setState, - required this.column, - required this.viewSize, - required this.dataGridConfiguration}) - : super(key: key); + _CheckboxFilterMenu({ + Key? key, + required this.setState, + required this.column, + required this.viewSize, + required this.dataGridConfiguration, + }) : super(key: key); final StateSetter setState; @@ -1746,6 +1975,8 @@ class _CheckboxFilterMenu extends StatelessWidget { isMobile ? max(viewSize!.height - occupiedHeight, 120.0) : 200.0; final double selectAllButtonHeight = isMobile ? helper.tileHeight - 4 : helper.tileHeight; + final DataGridThemeHelper dataGridThemeHelper = + dataGridConfiguration.dataGridThemeHelper!; return Padding( padding: const EdgeInsets.only(left: 4.0), @@ -1754,14 +1985,22 @@ class _CheckboxFilterMenu extends StatelessWidget { replacement: SizedBox( height: checkboxHeight + selectAllButtonHeight, child: Center( - child: Text(dataGridConfiguration - .localizations.noMatchesDataGridFilteringLabel)), + child: Text( + dataGridConfiguration + .localizations + .noMatchesDataGridFilteringLabel, + style: TextStyle( + color: dataGridThemeHelper.noMatchesFilteringLabelColor, + ), + ), + ), ), child: CheckboxTheme( data: CheckboxThemeData( side: BorderSide( - width: 2.0, - color: dataGridConfiguration.colorScheme!.onSurface[153]!), + width: 2.0, + color: dataGridConfiguration.colorScheme!.onSurface[153]!, + ), // Issue: The checkbox fill color is applied even when the checkbox is not selected. // The framework changed this behavior in Flutter 3.13.0 onwards. @@ -1769,44 +2008,55 @@ class _CheckboxFilterMenu extends StatelessWidget { // Guide: https://github.com/flutter/website/commit/224bdc9cc3e8dfb8af94d76f275824cdcf76ba4d // Fix: As per the framework guide, we have to set the fillColor property to transparent // when the checkbox is not selected. - fillColor: - WidgetStateProperty.resolveWith((Set states) { + fillColor: WidgetStateProperty.resolveWith(( + Set states, + ) { if (!states.contains(WidgetState.selected)) { return dataGridConfiguration.colorScheme!.transparent; } return helper.primaryColor; }), ), - child: Column(children: [ - _FilterPopupMenuTile( - style: helper.textStyle, - height: selectAllButtonHeight, - prefixPadding: const EdgeInsets.only(left: 4.0, right: 10.0), - prefix: Checkbox( - focusNode: checkboxFocusNode, - tristate: filterHelper.isSelectAllInTriState, - value: filterHelper.isSelectAllChecked, - onChanged: (_) => onHandleSelectAllCheckboxTap(), - ), - onTap: onHandleSelectAllCheckboxTap, - child: Text( - dataGridConfiguration - .localizations.selectAllDataGridFilteringLabel, - overflow: TextOverflow.ellipsis, + child: Column( + children: [ + _FilterPopupMenuTile( + style: helper.textStyle, + height: selectAllButtonHeight, + prefixPadding: const EdgeInsets.only(left: 4.0, right: 10.0), + prefix: Checkbox( + checkColor: dataGridThemeHelper.filterPopupCheckColor, + fillColor: dataGridThemeHelper.filterPopupCheckboxFillColor, + focusNode: checkboxFocusNode, + tristate: filterHelper.isSelectAllInTriState, + value: filterHelper.isSelectAllChecked, + onChanged: (_) => onHandleSelectAllCheckboxTap(), + ), + onTap: onHandleSelectAllCheckboxTap, + child: Text( + dataGridConfiguration + .localizations + .selectAllDataGridFilteringLabel, + overflow: TextOverflow.ellipsis, + ), ), - ), - SizedBox( - height: checkboxHeight, - child: ListView.builder( + SizedBox( + height: checkboxHeight, + child: ListView.builder( key: const ValueKey( - 'datagrid_filtering_checkbox_listView'), + 'datagrid_filtering_checkbox_listView', + ), prototypeItem: buildCheckboxTile( - filterHelper.items.length - 1, helper.textStyle), + filterHelper.items.length - 1, + helper.textStyle, + ), itemCount: filterHelper.items.length, - itemBuilder: (BuildContext context, int index) => - buildCheckboxTile(index, helper.textStyle)), - ), - ]), + itemBuilder: + (BuildContext context, int index) => + buildCheckboxTile(index, helper.textStyle), + ), + ), + ], + ), ), ), ); @@ -1832,6 +2082,7 @@ class _CheckboxFilterMenu extends StatelessWidget { child: SizedBox( height: isMobile ? helper.tileHeight : helper.tileHeight - 4, child: TextField( + cursorColor: dataGridThemeHelper.searchAreaCursorColor, style: helper.textStyle, key: const ValueKey('datagrid_filtering_search_textfield'), focusNode: filterHelper.searchboxFocusNode, @@ -1839,34 +2090,64 @@ class _CheckboxFilterMenu extends StatelessWidget { onChanged: onHandleSearchTextFieldChanged, onSubmitted: onSearchboxSubmitted, decoration: InputDecoration( - enabledBorder: OutlineInputBorder( - borderSide: BorderSide( - color: dataGridThemeHelper.filterPopupBorderColor!)), - suffixIcon: Visibility( - visible: filterHelper.textController.text.isEmpty, - replacement: IconButton( - key: const ValueKey( - 'datagrid_filtering_clearSearch_icon'), - iconSize: helper.textStyle.fontSize! + 8, - padding: EdgeInsets.zero, - constraints: const BoxConstraints.tightFor( - width: 22.0, height: 22.0), - onPressed: () { - filterHelper.textController.clear(); - onHandleSearchTextFieldChanged(''); - }, - icon: Icon(Icons.close, - color: dataGridThemeHelper.filterPopupIconColor)), - child: Icon(Icons.search, - size: helper.textStyle.fontSize! + 8, - color: dataGridThemeHelper.filterPopupIconColor)), - contentPadding: isMobile - ? const EdgeInsets.all(16.0) - : const EdgeInsets.all(8.0), - border: const OutlineInputBorder(), - hintStyle: helper.textStyle, - hintText: dataGridConfiguration - .localizations.searchDataGridFilteringLabel), + focusedBorder: + dataGridThemeHelper.searchAreaFocusedBorderColor == null + ? null + : OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper.searchAreaFocusedBorderColor!, + ), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper.filterPopupInputBorderColor ?? + dataGridThemeHelper.filterPopupBorderColor!, + ), + ), + suffixIcon: Visibility( + visible: filterHelper.textController.text.isEmpty, + replacement: IconButton( + key: const ValueKey( + 'datagrid_filtering_clearSearch_icon', + ), + iconSize: helper.textStyle.fontSize! + 8, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor( + width: 22.0, + height: 22.0, + ), + onPressed: () { + filterHelper.textController.clear(); + onHandleSearchTextFieldChanged(''); + }, + icon: Icon( + Icons.close, + color: + dataGridThemeHelper.closeIconColor ?? + dataGridThemeHelper.filterPopupIconColor, + ), + ), + child: Icon( + Icons.search, + size: helper.textStyle.fontSize! + 8, + color: + dataGridThemeHelper.searchIconColor ?? + dataGridThemeHelper.filterPopupIconColor, + ), + ), + contentPadding: + isMobile + ? const EdgeInsets.all(16.0) + : const EdgeInsets.all(8.0), + border: const OutlineInputBorder(), + hintStyle: helper.textStyle, + hintText: + dataGridConfiguration + .localizations + .searchDataGridFilteringLabel, + ), ), ), ); @@ -1877,16 +2158,22 @@ class _CheckboxFilterMenu extends StatelessWidget { final FilterElement element = filterHelper.items[index]; final String displayText = dataGridConfiguration.dataGridFilterHelper! .getDisplayValue(element.value); + final DataGridThemeHelper dataGridThemeHelper = + dataGridConfiguration.dataGridThemeHelper!; return _FilterPopupMenuTile( - style: style, - height: isMobile ? style.fontSize! + 34 : style.fontSize! + 26, - prefixPadding: const EdgeInsets.only(left: 4.0, right: 10.0), - prefix: Checkbox( - focusNode: checkboxFocusNode, - value: element.isSelected, - onChanged: (_) => onHandleCheckboxTap(element)), - onTap: () => onHandleCheckboxTap(element), - child: Text(displayText, overflow: TextOverflow.ellipsis)); + style: style, + height: isMobile ? style.fontSize! + 34 : style.fontSize! + 26, + prefixPadding: const EdgeInsets.only(left: 4.0, right: 10.0), + prefix: Checkbox( + checkColor: dataGridThemeHelper.filterPopupCheckColor, + fillColor: dataGridThemeHelper.filterPopupCheckboxFillColor, + focusNode: checkboxFocusNode, + value: element.isSelected, + onChanged: (_) => onHandleCheckboxTap(element), + ), + onTap: () => onHandleCheckboxTap(element), + child: Text(displayText, overflow: TextOverflow.ellipsis), + ); } return null; } @@ -1898,7 +2185,8 @@ class _CheckboxFilterMenu extends StatelessWidget { } void onHandleSelectAllCheckboxTap() { - final bool useSelected = filterHelper.isSelectAllInTriState || + final bool useSelected = + filterHelper.isSelectAllInTriState || (filterHelper.isSelectAllChecked != null && filterHelper.isSelectAllChecked!); for (final FilterElement item in filterHelper.filterCheckboxItems) { @@ -1916,12 +2204,12 @@ class _CheckboxFilterMenu extends StatelessWidget { } class _AdvancedFilterPopupMenu extends StatelessWidget { - const _AdvancedFilterPopupMenu( - {Key? key, - required this.setState, - required this.dataGridConfiguration, - required this.advanceFilterTopPadding}) - : super(key: key); + const _AdvancedFilterPopupMenu({ + Key? key, + required this.setState, + required this.dataGridConfiguration, + required this.advanceFilterTopPadding, + }) : super(key: key); final StateSetter setState; @@ -1952,10 +2240,11 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { child: Text( '${dataGridConfiguration.localizations.showRowsWhereDataGridFilteringLabel}:', style: TextStyle( - fontFamily: helper.textStyle.fontFamily, - fontSize: helper.textStyle.fontSize, - color: helper.textStyle.color, - fontWeight: FontWeight.bold), + fontFamily: helper.textStyle.fontFamily, + fontSize: helper.textStyle.fontSize, + color: helper.textStyle.color, + fontWeight: FontWeight.bold, + ), overflow: TextOverflow.ellipsis, ), ), @@ -1991,6 +2280,8 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { final DataGridFilterHelper helper = dataGridConfiguration.dataGridFilterHelper!; final SfLocalizations localizations = dataGridConfiguration.localizations; + final DataGridThemeHelper dataGridThemeHelper = + dataGridConfiguration.dataGridThemeHelper!; void handleChanged(bool? value) { setState(() { @@ -2000,39 +2291,51 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { return Row( children: [ - Row(children: [ - SizedBox.fromSize( - size: const Size(24.0, 24.0), - child: Radio( + Row( + children: [ + SizedBox.fromSize( + size: const Size(24.0, 24.0), + child: Radio( key: const ValueKey('datagrid_filtering_and_button'), value: false, - activeColor: helper.primaryColor, + activeColor: + dataGridThemeHelper.andRadioActiveColor ?? + helper.primaryColor, + fillColor: dataGridThemeHelper.andRadioFillColor, onChanged: handleChanged, - groupValue: filterHelper.isOrPredicate), - ), - const SizedBox(width: 8.0), - Text( - localizations.andDataGridFilteringLabel, - style: helper.textStyle, - ), - ]), + groupValue: filterHelper.isOrPredicate, + ), + ), + const SizedBox(width: 8.0), + Text( + localizations.andDataGridFilteringLabel, + style: helper.textStyle, + ), + ], + ), const SizedBox(width: 16.0), - Row(children: [ - SizedBox.fromSize( - size: const Size(24.0, 24.0), - child: Radio( + Row( + children: [ + SizedBox.fromSize( + size: const Size(24.0, 24.0), + child: Radio( key: const ValueKey('datagrid_filtering_or_button'), value: true, - activeColor: helper.primaryColor, + activeColor: + dataGridThemeHelper.orRadioActiveColor ?? + helper.primaryColor, + fillColor: dataGridThemeHelper.orRadioFillColor, onChanged: handleChanged, - groupValue: filterHelper.isOrPredicate), - ), - const SizedBox(width: 8.0), - Text( - localizations.orDataGridFilteringLabel, - style: helper.textStyle, - ), - ]), + groupValue: filterHelper.isOrPredicate, + ), + ), + const SizedBox(width: 8.0), + Text( + localizations.orDataGridFilteringLabel, + style: helper.textStyle, + ), + ], + ), ], ); } @@ -2077,36 +2380,69 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { Widget buildDropdownFormField() { return DropdownButtonHideUnderline( child: DropdownButtonFormField( - dropdownColor: dataGridThemeHelper.filterPopupOuterColor, - key: isTopButton - ? const ValueKey( - 'datagrid_filtering_filterValue_first_button') - : const ValueKey( - 'datagrid_filtering_filterValue_second_button'), + dropdownColor: + dataGridThemeHelper.advancedFilterPopupDropdownColor ?? + dataGridThemeHelper.filterPopupOuterColor, + key: + isTopButton + ? const ValueKey( + 'datagrid_filtering_filterValue_first_button', + ) + : const ValueKey( + 'datagrid_filtering_filterValue_second_button', + ), decoration: InputDecoration( - enabledBorder: OutlineInputBorder( - borderSide: BorderSide( - color: dataGridThemeHelper.filterPopupBorderColor!), + focusedBorder: + dataGridThemeHelper + .advancedFilterValueDropdownFocusedBorderColor == + null + ? null + : OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper + .advancedFilterValueDropdownFocusedBorderColor!, + ), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper.filterPopupInputBorderColor ?? + dataGridThemeHelper.filterPopupBorderColor!, + ), + ), + contentPadding: const EdgeInsets.symmetric( + vertical: 8.0, + horizontal: 12.0, + ), + border: OutlineInputBorder( + borderSide: BorderSide( + color: dataGridThemeHelper.filterPopupBorderColor!, ), - contentPadding: - const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0), - border: OutlineInputBorder( - borderSide: BorderSide( - color: dataGridThemeHelper.filterPopupBorderColor!))), - icon: Icon(Icons.keyboard_arrow_down, - size: helper.textStyle.fontSize! + 8, - color: dataGridThemeHelper.filterPopupIconColor), + ), + ), + icon: Icon( + Icons.keyboard_arrow_down, + size: helper.textStyle.fontSize! + 8, + color: + dataGridThemeHelper.advancedFilterValueDropdownIconColor ?? + dataGridThemeHelper.filterPopupIconColor, + ), isExpanded: true, - value: isTopButton - ? filterHelper.filterValue1 - : filterHelper.filterValue2, + value: + isTopButton + ? filterHelper.filterValue1 + : filterHelper.filterValue2, style: helper.textStyle, - items: filterHelper.items - .map>((FilterElement value) => - DropdownMenuItem( + items: + filterHelper.items + .map>( + (FilterElement value) => DropdownMenuItem( value: value.value, - child: Text(helper.getDisplayValue(value.value)))) - .toList(), + child: Text(helper.getDisplayValue(value.value)), + ), + ) + .toList(), onChanged: enableDropdownButton(isTopButton) ? setValue : null, ), ); @@ -2114,15 +2450,20 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { Widget buildTextField() { return TextField( + cursorColor: dataGridThemeHelper.advancedFilterValueTextAreaCursorColor, style: helper.textStyle, - key: isTopButton - ? const ValueKey( - 'datagrid_filtering_filterValue_first_button') - : const ValueKey( - 'datagrid_filtering_filterValue_second_button'), - controller: isTopButton - ? filterHelper.firstValueTextController - : filterHelper.secondValueTextController, + key: + isTopButton + ? const ValueKey( + 'datagrid_filtering_filterValue_first_button', + ) + : const ValueKey( + 'datagrid_filtering_filterValue_second_button', + ), + controller: + isTopButton + ? filterHelper.firstValueTextController + : filterHelper.secondValueTextController, maxLengthEnforcement: MaxLengthEnforcement.enforced, keyboardType: getTextInputType(), inputFormatters: getInputFormatters(), @@ -2131,14 +2472,30 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { setValue(helper.getActualValue(value)); }, decoration: InputDecoration( - enabledBorder: OutlineInputBorder( - borderSide: BorderSide( - color: dataGridThemeHelper.filterPopupBorderColor!)), - contentPadding: isMobile - ? const EdgeInsets.all(16.0) - : const EdgeInsets.all(8.0), - border: const OutlineInputBorder(), - hintStyle: const TextStyle(fontSize: 14.0)), + focusedBorder: + dataGridThemeHelper + .advancedFilterValueDropdownFocusedBorderColor == + null + ? null + : OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper + .advancedFilterValueDropdownFocusedBorderColor!, + ), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper.filterPopupInputBorderColor ?? + dataGridThemeHelper.filterPopupBorderColor!, + ), + ), + contentPadding: + isMobile ? const EdgeInsets.all(16.0) : const EdgeInsets.all(8.0), + border: const OutlineInputBorder(), + hintStyle: const TextStyle(fontSize: 14.0), + ), ); } @@ -2174,18 +2531,22 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { // the same value in the text field itself. if (filterHelper.textFieldFilterTypes.contains(value)) { if (isFirstButton) { - filterHelper.firstValueTextController.text = - helper.getDisplayValue(filterHelper.filterValue1); + filterHelper.firstValueTextController.text = helper.getDisplayValue( + filterHelper.filterValue1, + ); } else { - filterHelper.secondValueTextController.text = - helper.getDisplayValue(filterHelper.filterValue2); + filterHelper.secondValueTextController.text = helper.getDisplayValue( + filterHelper.filterValue2, + ); } } else { // Need to set the filter values to null if that value doesn't exist in // the data source when the filter type switching from the text field to // dropdown. - bool isInValidText(Object? filterValue) => !filterHelper.items - .any((FilterElement element) => element.value == filterValue); + bool isInValidText(Object? filterValue) => + !filterHelper.items.any( + (FilterElement element) => element.value == filterValue, + ); if (isFirstButton) { if (isInValidText(filterHelper.filterValue1)) { filterHelper.filterValue1 = null; @@ -2201,32 +2562,67 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { return DropdownButtonHideUnderline( child: DropdownButtonFormField( - dropdownColor: dataGridThemeHelper.filterPopupOuterColor, - key: isFirstButton - ? const ValueKey( - 'datagrid_filtering_filterType_first_button') - : const ValueKey( - 'datagrid_filtering_filterType_second_button'), + dropdownColor: + dataGridThemeHelper.advancedFilterPopupDropdownColor ?? + dataGridThemeHelper.filterPopupOuterColor, + key: + isFirstButton + ? const ValueKey( + 'datagrid_filtering_filterType_first_button', + ) + : const ValueKey( + 'datagrid_filtering_filterType_second_button', + ), decoration: InputDecoration( - enabledBorder: OutlineInputBorder( - borderSide: BorderSide( - color: dataGridThemeHelper.filterPopupBorderColor!)), - contentPadding: - const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0), - border: OutlineInputBorder( - borderSide: BorderSide( - color: dataGridThemeHelper.filterPopupBorderColor!))), - icon: Icon(Icons.keyboard_arrow_down, - size: helper.textStyle.fontSize! + 8, - color: dataGridThemeHelper.filterPopupIconColor), + focusedBorder: + dataGridThemeHelper + .advancedFilterTypeDropdownFocusedBorderColor == + null + ? null + : OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper + .advancedFilterTypeDropdownFocusedBorderColor!, + ), + ), + enabledBorder: OutlineInputBorder( + borderSide: BorderSide( + color: + dataGridThemeHelper.filterPopupInputBorderColor ?? + dataGridThemeHelper.filterPopupBorderColor!, + ), + ), + contentPadding: const EdgeInsets.symmetric( + vertical: 8.0, + horizontal: 12.0, + ), + border: OutlineInputBorder( + borderSide: BorderSide( + color: dataGridThemeHelper.filterPopupBorderColor!, + ), + ), + ), + icon: Icon( + Icons.keyboard_arrow_down, + size: helper.textStyle.fontSize! + 8, + color: + dataGridThemeHelper.advancedFilterTypeDropdownIconColor ?? + dataGridThemeHelper.filterPopupIconColor, + ), isExpanded: true, value: isFirstButton ? filterHelper.filterType1 : filterHelper.filterType2, style: helper.textStyle, - items: filterHelper.filterTypeItems - .map>((String value) => - DropdownMenuItem(value: value, child: Text(value))) - .toList(), + items: + filterHelper.filterTypeItems + .map>( + (String value) => DropdownMenuItem( + value: value, + child: Text(value), + ), + ) + .toList(), onChanged: handleChanged, ), ); @@ -2267,11 +2663,13 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { return; } - final bool isVaildDate = filterHelper.items - .any((FilterElement element) => element.value == selectedDate); + final bool isVaildDate = filterHelper.items.any( + (FilterElement element) => element.value == selectedDate, + ); final String? filterType = isFirstButton ? filterHelper.filterType1 : filterHelper.filterType2; - final bool isValidType = filterType != null && + final bool isValidType = + filterType != null && filterHelper.textFieldFilterTypes.contains(filterType); selectedDate = isVaildDate || isValidType ? selectedDate : null; @@ -2297,13 +2695,16 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { }); } - Color getColor() { - final bool isSelected = isFirstButton - ? filterHelper.isCaseSensitive1 - : filterHelper.isCaseSensitive2; + Color? getColor() { + final bool isSelected = + isFirstButton + ? filterHelper.isCaseSensitive1 + : filterHelper.isCaseSensitive2; return isSelected - ? helper.primaryColor - : dataGridThemeHelper.filterPopupIconColor!; + ? dataGridThemeHelper.caseSensitiveIconActiveColor ?? + helper.primaryColor + : dataGridThemeHelper.caseSensitiveIconColor ?? + dataGridThemeHelper.filterPopupIconColor!; } bool canEnableButton() { @@ -2313,41 +2714,57 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { } if (filterHelper.advancedFilterType == AdvancedFilterType.text) { - const IconData caseSensitiveIcon = IconData(0xe705, - fontFamily: 'FilterIcon', fontPackage: 'syncfusion_flutter_datagrid'); + const IconData caseSensitiveIcon = IconData( + 0xe705, + fontFamily: 'FilterIcon', + fontPackage: 'syncfusion_flutter_datagrid', + ); return IconButton( - key: isFirstButton - ? const ValueKey( - 'datagrid_filtering_case_sensitive_first_button') - : const ValueKey( - 'datagrid_filtering_case_sensitive_second_button'), - iconSize: 22.0, - splashRadius: 20.0, - padding: EdgeInsets.zero, - constraints: const BoxConstraints.tightFor(width: 22.0, height: 22.0), - onPressed: canEnableButton() ? handleCaseSensitiveTap : null, - icon: Icon(caseSensitiveIcon, size: 22.0, color: getColor())); + key: + isFirstButton + ? const ValueKey( + 'datagrid_filtering_case_sensitive_first_button', + ) + : const ValueKey( + 'datagrid_filtering_case_sensitive_second_button', + ), + iconSize: 22.0, + splashRadius: 20.0, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor(width: 22.0, height: 22.0), + onPressed: canEnableButton() ? handleCaseSensitiveTap : null, + icon: Icon(caseSensitiveIcon, size: 22.0, color: getColor()), + ); } else { return IconButton( - key: isFirstButton - ? const ValueKey( - 'datagrid_filtering_date_picker_first_button') - : const ValueKey( - 'datagrid_filtering_date_picker_second_button'), - iconSize: 22.0, - splashRadius: 20.0, - padding: EdgeInsets.zero, - constraints: const BoxConstraints.tightFor(width: 22.0, height: 22.0), - onPressed: canEnableButton() ? handleDatePickerTap : null, - icon: Icon(Icons.calendar_today_outlined, - size: 22.0, - color: dataGridConfiguration.colorScheme!.onSurface[153])); + key: + isFirstButton + ? const ValueKey( + 'datagrid_filtering_date_picker_first_button', + ) + : const ValueKey( + 'datagrid_filtering_date_picker_second_button', + ), + iconSize: 22.0, + splashRadius: 20.0, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor(width: 22.0, height: 22.0), + onPressed: canEnableButton() ? handleDatePickerTap : null, + icon: Icon( + Icons.calendar_today_outlined, + size: 22.0, + color: + dataGridThemeHelper.calendarIconColor ?? + dataGridConfiguration.colorScheme!.onSurface[153], + ), + ); } } bool enableDropdownButton(bool isTopButton) { return !filterHelper.disableFilterTypes.contains( - isTopButton ? filterHelper.filterType1 : filterHelper.filterType2); + isTopButton ? filterHelper.filterType1 : filterHelper.filterType2, + ); } bool canBuildTextField(bool isTopButton) { @@ -2361,15 +2778,18 @@ class _AdvancedFilterPopupMenu extends StatelessWidget { } BorderDirectional _getCellBorder( - DataGridConfiguration dataGridConfiguration, DataCellBase dataCell) { + DataGridConfiguration dataGridConfiguration, + DataCellBase dataCell, +) { final Color borderColor = dataGridConfiguration.dataGridThemeHelper!.gridLineColor!; final double borderWidth = dataGridConfiguration.dataGridThemeHelper!.gridLineStrokeWidth!; - final int rowIndex = (dataCell.rowSpan > 0) - ? dataCell.rowIndex - dataCell.rowSpan - : dataCell.rowIndex; + final int rowIndex = + (dataCell.rowSpan > 0) + ? dataCell.rowIndex - dataCell.rowSpan + : dataCell.rowIndex; final int columnIndex = dataCell.columnIndex; final bool isStackedHeaderCell = dataCell.cellType == CellType.stackedHeaderCell; @@ -2393,14 +2813,18 @@ BorderDirectional _getCellBorder( // To skip bottom border for the top data row of the starting row of bottom table // summary rows and draw top border for the bottom summary start row instead. - final bool canSkipBottomBorder = grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom) > + final bool canSkipBottomBorder = + grid_helper.getTableSummaryCount( + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ) > 0 && dataCell.rowIndex == grid_helper.getStartBottomSummaryRowIndex(dataGridConfiguration) - 1; // To draw the top border for the starting row of the bottom table summary row. - final bool canDrawStartBottomSummaryRowTopBorder = isTableSummaryCell && + final bool canDrawStartBottomSummaryRowTopBorder = + isTableSummaryCell && dataCell.rowIndex == grid_helper.getStartBottomSummaryRowIndex(dataGridConfiguration); @@ -2412,21 +2836,21 @@ BorderDirectional _getCellBorder( final bool canDrawHeaderHorizontalBorder = (dataGridConfiguration.headerGridLinesVisibility == - GridLinesVisibility.horizontal || - dataGridConfiguration.headerGridLinesVisibility == - GridLinesVisibility.both) && - (isHeaderCell || - isStackedHeaderCell || - (isIndentCell && (isHeaderRow || isStackedHeaderRow))); + GridLinesVisibility.horizontal || + dataGridConfiguration.headerGridLinesVisibility == + GridLinesVisibility.both) && + (isHeaderCell || + isStackedHeaderCell || + (isIndentCell && (isHeaderRow || isStackedHeaderRow))); final bool canDrawHeaderVerticalBorder = (dataGridConfiguration.headerGridLinesVisibility == - GridLinesVisibility.vertical || - dataGridConfiguration.headerGridLinesVisibility == - GridLinesVisibility.both) && - (isHeaderCell || - isStackedHeaderCell || - (isIndentCell && (isHeaderRow || isStackedHeaderRow))); + GridLinesVisibility.vertical || + dataGridConfiguration.headerGridLinesVisibility == + GridLinesVisibility.both) && + (isHeaderCell || + isStackedHeaderCell || + (isIndentCell && (isHeaderRow || isStackedHeaderRow))); final ColumnDragAndDropController dragAndDropController = dataGridConfiguration.columnDragAndDropController; @@ -2435,147 +2859,157 @@ BorderDirectional _getCellBorder( final bool canDrawLeftColumnDragAndDropIndicator = dataGridConfiguration.allowColumnsDragging && - dragAndDropController.canDrawRightIndicator != null && - !dragAndDropController.canDrawRightIndicator! && - dragAndDropController.columnIndex == dataCell.columnIndex && - (dragAndDropController.dragColumnStartIndex! + - indentCount + - (dataGridConfiguration.showCheckboxColumn ? 1 : 0)) != - dataCell.columnIndex && - isHeaderCell; + dragAndDropController.canDrawRightIndicator != null && + !dragAndDropController.canDrawRightIndicator! && + dragAndDropController.columnIndex == dataCell.columnIndex && + (dragAndDropController.dragColumnStartIndex! + + indentCount + + (dataGridConfiguration.showCheckboxColumn ? 1 : 0)) != + dataCell.columnIndex && + isHeaderCell; final bool canDrawRightColumnDragAndDropIndicator = dataGridConfiguration.allowColumnsDragging && - dragAndDropController.canDrawRightIndicator != null && - dragAndDropController.canDrawRightIndicator! && - dragAndDropController.columnIndex == dataCell.columnIndex && - (dragAndDropController.dragColumnStartIndex! + - indentCount + - (dataGridConfiguration.showCheckboxColumn ? 1 : 0)) != - dataCell.columnIndex && - isHeaderCell; + dragAndDropController.canDrawRightIndicator != null && + dragAndDropController.canDrawRightIndicator! && + dragAndDropController.columnIndex == dataCell.columnIndex && + (dragAndDropController.dragColumnStartIndex! + + indentCount + + (dataGridConfiguration.showCheckboxColumn ? 1 : 0)) != + dataCell.columnIndex && + isHeaderCell; final bool canSkipLeftColumnDragAndDropIndicator = canDrawLeftColumnDragAndDropIndicator && - (dragAndDropController.dragColumnStartIndex! + - indentCount + - (dataGridConfiguration.showCheckboxColumn ? 2 : 1) == - dataCell.columnIndex || - (dataGridConfiguration.showCheckboxColumn && - dragAndDropController.columnIndex == 0)); + (dragAndDropController.dragColumnStartIndex! + + indentCount + + (dataGridConfiguration.showCheckboxColumn ? 2 : 1) == + dataCell.columnIndex || + (dataGridConfiguration.showCheckboxColumn && + dragAndDropController.columnIndex == 0)); final bool canSkipRightColumnDragAndDropIndicator = canDrawRightColumnDragAndDropIndicator && - (dragAndDropController.dragColumnStartIndex! + - indentCount - - (dataGridConfiguration.showCheckboxColumn ? 0 : 1) == - dataCell.columnIndex || - (dataGridConfiguration.showCheckboxColumn && - dragAndDropController.columnIndex == 0)); + (dragAndDropController.dragColumnStartIndex! + + indentCount - + (dataGridConfiguration.showCheckboxColumn ? 0 : 1) == + dataCell.columnIndex || + (dataGridConfiguration.showCheckboxColumn && + dragAndDropController.columnIndex == 0)); final bool canDrawHorizontalBorder = (dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.horizontal || - dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.both) && - !isHeaderCell && - !isStackedHeaderCell; + GridLinesVisibility.horizontal || + dataGridConfiguration.gridLinesVisibility == + GridLinesVisibility.both) && + !isHeaderCell && + !isStackedHeaderCell; final bool canDrawVerticalBorder = (dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.vertical || - dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.both) && - !isStackedHeaderCell && - !isTableSummaryCell && - !isHeaderCell; + GridLinesVisibility.vertical || + dataGridConfiguration.gridLinesVisibility == + GridLinesVisibility.both) && + !isStackedHeaderCell && + !isTableSummaryCell && + !isHeaderCell; final GridColumn firstVisibleColumn = dataGridConfiguration.columns .firstWhere((GridColumn column) => column.visible && column.width != 0.0); - final GridColumn lastVisibleColumn = dataGridConfiguration.columns - .lastWhere((GridColumn column) => column.visible && column.width != 0.0); + final GridColumn lastVisibleColumn = dataGridConfiguration.columns.lastWhere( + (GridColumn column) => column.visible && column.width != 0.0, + ); - final int firstVisibleColumnIndex = (isGrouping && - dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth > 0) - ? 0 - : grid_helper.resolveToScrollColumnIndex(dataGridConfiguration, - dataGridConfiguration.columns.indexOf(firstVisibleColumn)); + final int firstVisibleColumnIndex = + (isGrouping && + dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth > 0) + ? 0 + : grid_helper.resolveToScrollColumnIndex( + dataGridConfiguration, + dataGridConfiguration.columns.indexOf(firstVisibleColumn), + ); final int lastVisibleColumnIndex = grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, - dataGridConfiguration.columns.indexOf(lastVisibleColumn)); + dataGridConfiguration, + dataGridConfiguration.columns.indexOf(lastVisibleColumn), + ); - final int lastRowIndex = - selection_helper.getLastRowIndex(dataGridConfiguration, true); + final int lastRowIndex = selection_helper.getLastRowIndex( + dataGridConfiguration, + true, + ); - final bool isLastStackedHeaderCell = isStackedHeaderCell && + final bool isLastStackedHeaderCell = + isStackedHeaderCell && (columnIndex == 0 || columnIndex > firstVisibleColumnIndex) && ((dataCell.columnSpan + columnIndex) >= lastVisibleColumnIndex); // To draw the top outer border for the DataGrid. - final bool canDrawGridTopOuterBorder = rowIndex == 0 && + final bool canDrawGridTopOuterBorder = + rowIndex == 0 && dataGridConfiguration.headerGridLinesVisibility != GridLinesVisibility.none; // To draw the bottom outer border for the DataGrid. - final bool canDrawGridBottomOuterBorder = rowIndex == lastRowIndex && + final bool canDrawGridBottomOuterBorder = + rowIndex == lastRowIndex && dataGridConfiguration.gridLinesVisibility != GridLinesVisibility.none; // To draw the right outer border for the DataGrid Headers. final bool canDrawGridHeaderRightOuterBorder = dataGridConfiguration.headerGridLinesVisibility != - GridLinesVisibility.none && - ((isHeaderRow && columnIndex == lastVisibleColumnIndex) || - isLastStackedHeaderCell); + GridLinesVisibility.none && + ((isHeaderRow && columnIndex == lastVisibleColumnIndex) || + isLastStackedHeaderCell); // To draw the right outer border for the DataGrid Rows. final bool canDrawGridRightOuterBorder = dataGridConfiguration.gridLinesVisibility != GridLinesVisibility.none && - (((isRowCell || isTableSummaryCell) && - columnIndex == lastVisibleColumnIndex) || - isCaptionSummaryCoveredRow || - isTableSummaryCoveredRow); + (((isRowCell || isTableSummaryCell) && + columnIndex == lastVisibleColumnIndex) || + isCaptionSummaryCoveredRow || + isTableSummaryCoveredRow); // To draw the left outer border for the DataGrid Headers. final bool canDrawGridHeaderLeftOuterBorder = dataGridConfiguration.headerGridLinesVisibility != - GridLinesVisibility.none && - (isHeaderCell || - isStackedHeaderCell || - (isIndentCell && (isHeaderRow || isStackedHeaderRow))) && - (columnIndex <= firstVisibleColumnIndex); + GridLinesVisibility.none && + (isHeaderCell || + isStackedHeaderCell || + (isIndentCell && (isHeaderRow || isStackedHeaderRow))) && + (columnIndex <= firstVisibleColumnIndex); // To draw the left outer border for the DataGrid Rows. final bool canDrawGridLeftOuterBorder = dataGridConfiguration.gridLinesVisibility != GridLinesVisibility.none && - columnIndex <= firstVisibleColumnIndex && - (!isHeaderRow && !isStackedHeaderRow); + columnIndex <= firstVisibleColumnIndex && + (!isHeaderRow && !isStackedHeaderRow); // Frozen column and row checking final bool canDrawBottomFrozenBorder = dataGridConfiguration.frozenRowsCount.isFinite && - dataGridConfiguration.frozenRowsCount > 0 && - grid_helper.getLastFrozenRowIndex(dataGridConfiguration) == rowIndex; + dataGridConfiguration.frozenRowsCount > 0 && + grid_helper.getLastFrozenRowIndex(dataGridConfiguration) == rowIndex; final bool canDrawTopFrozenBorder = dataGridConfiguration.footerFrozenRowsCount.isFinite && - dataGridConfiguration.footerFrozenRowsCount > 0 && - grid_helper.getStartFooterFrozenRowIndex(dataGridConfiguration) == - rowIndex; + dataGridConfiguration.footerFrozenRowsCount > 0 && + grid_helper.getStartFooterFrozenRowIndex(dataGridConfiguration) == + rowIndex; final bool canDrawRightFrozenBorder = dataGridConfiguration.frozenColumnsCount.isFinite && - dataGridConfiguration.frozenColumnsCount > 0 && - grid_helper.getLastFrozenColumnIndex(dataGridConfiguration) == - columnIndex && - !isStackedHeaderCell; + dataGridConfiguration.frozenColumnsCount > 0 && + grid_helper.getLastFrozenColumnIndex(dataGridConfiguration) == + columnIndex && + !isStackedHeaderCell; final bool canDrawLeftFrozenBorder = dataGridConfiguration.footerFrozenColumnsCount.isFinite && - dataGridConfiguration.footerFrozenColumnsCount > 0 && - grid_helper.getStartFooterFrozenColumnIndex(dataGridConfiguration) == - columnIndex; + dataGridConfiguration.footerFrozenColumnsCount > 0 && + grid_helper.getStartFooterFrozenColumnIndex(dataGridConfiguration) == + columnIndex; final bool isFrozenPaneElevationApplied = dataGridConfiguration.dataGridThemeHelper!.frozenPaneElevation! > 0.0; @@ -2586,7 +3020,8 @@ BorderDirectional _getCellBorder( final double frozenPaneLineWidth = dataGridConfiguration.dataGridThemeHelper!.frozenPaneLineWidth!; - final bool canDrawIndentRightBorder = canDrawVerticalBorder && + final bool canDrawIndentRightBorder = + canDrawVerticalBorder && (dataGridConfiguration.source.groupedColumns.isNotEmpty && (columnIndex >= 0 && columnIndex < groupedColumnsLength && @@ -2597,10 +3032,10 @@ BorderDirectional _getCellBorder( final bool canDrawTableSummaryRowIndentBorder = (dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.horizontal || - dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.both) && - (isIndentCell && isTableSummaryRow); + GridLinesVisibility.horizontal || + dataGridConfiguration.gridLinesVisibility == + GridLinesVisibility.both) && + (isIndentCell && isTableSummaryRow); BorderSide getLeftBorder() { if ((columnIndex == 0 && @@ -2613,16 +3048,23 @@ BorderDirectional _getCellBorder( if (canDrawLeftColumnDragAndDropIndicator && !canSkipLeftColumnDragAndDropIndicator) { return BorderSide( - width: dataGridConfiguration - .dataGridThemeHelper!.columnDragIndicatorStrokeWidth!, - color: dataGridConfiguration - .dataGridThemeHelper!.columnDragIndicatorColor!); + width: + dataGridConfiguration + .dataGridThemeHelper! + .columnDragIndicatorStrokeWidth!, + color: + dataGridConfiguration + .dataGridThemeHelper! + .columnDragIndicatorColor!, + ); } if (canDrawLeftFrozenBorder && !isStackedHeaderCell && !isFrozenPaneElevationApplied) { return BorderSide( - width: frozenPaneLineWidth, color: frozenPaneLineColor); + width: frozenPaneLineWidth, + color: frozenPaneLineColor, + ); } else if ((columnIndex > 0 && ((canDrawVerticalBorder || canDrawHeaderVerticalBorder) && !canDrawLeftFrozenBorder)) || @@ -2634,10 +3076,15 @@ BorderDirectional _getCellBorder( } else if (canDrawLeftColumnDragAndDropIndicator && !canSkipLeftColumnDragAndDropIndicator) { return BorderSide( - width: dataGridConfiguration - .dataGridThemeHelper!.columnDragIndicatorStrokeWidth!, - color: dataGridConfiguration - .dataGridThemeHelper!.columnDragIndicatorColor!); + width: + dataGridConfiguration + .dataGridThemeHelper! + .columnDragIndicatorStrokeWidth!, + color: + dataGridConfiguration + .dataGridThemeHelper! + .columnDragIndicatorColor!, + ); } else { return BorderSide.none; } @@ -2653,7 +3100,9 @@ BorderDirectional _getCellBorder( !isStackedHeaderCell && !isFrozenPaneElevationApplied) { return BorderSide( - width: frozenPaneLineWidth, color: frozenPaneLineColor); + width: frozenPaneLineWidth, + color: frozenPaneLineColor, + ); } else if ((canDrawHorizontalBorder && canDrawStartBottomSummaryRowTopBorder) || canDrawGridTopOuterBorder) { @@ -2678,14 +3127,21 @@ BorderDirectional _getCellBorder( !isStackedHeaderCell && !isFrozenPaneElevationApplied) { return BorderSide( - width: frozenPaneLineWidth, color: frozenPaneLineColor); + width: frozenPaneLineWidth, + color: frozenPaneLineColor, + ); } else if (canDrawRightColumnDragAndDropIndicator && !canSkipRightColumnDragAndDropIndicator) { return BorderSide( - width: dataGridConfiguration - .dataGridThemeHelper!.columnDragIndicatorStrokeWidth!, - color: dataGridConfiguration - .dataGridThemeHelper!.columnDragIndicatorColor!); + width: + dataGridConfiguration + .dataGridThemeHelper! + .columnDragIndicatorStrokeWidth!, + color: + dataGridConfiguration + .dataGridThemeHelper! + .columnDragIndicatorColor!, + ); } else if ((canDrawVerticalBorder || canDrawHeaderVerticalBorder || canDrawGridHeaderRightOuterBorder || @@ -2716,7 +3172,9 @@ BorderDirectional _getCellBorder( !isStackedHeaderCell && !isFrozenPaneElevationApplied) { return BorderSide( - width: frozenPaneLineWidth, color: frozenPaneLineColor); + width: frozenPaneLineWidth, + color: frozenPaneLineColor, + ); } else if ((!canDrawBottomFrozenBorder && !canSkipBottomBorder && !isIndentCell) || @@ -2752,12 +3210,13 @@ BorderDirectional _getCellBorder( ); } -Widget _wrapInsideCellContainer( - {required DataGridConfiguration dataGridConfiguration, - required DataCellBase dataCell, - required Key key, - required Color backgroundColor, - required Widget child}) { +Widget _wrapInsideCellContainer({ + required DataGridConfiguration dataGridConfiguration, + required DataCellBase dataCell, + required Key key, + required Color backgroundColor, + required Widget child, +}) { final Color color = dataGridConfiguration.dataGridThemeHelper!.currentCellStyle!.borderColor; final double borderWidth = @@ -2766,18 +3225,22 @@ Widget _wrapInsideCellContainer( Border getBorder() { final bool isCurrentCell = dataCell.isCurrentCell; return Border( - bottom: isCurrentCell - ? BorderSide(color: color, width: borderWidth) - : BorderSide.none, - left: isCurrentCell - ? BorderSide(color: color, width: borderWidth) - : BorderSide.none, - top: isCurrentCell - ? BorderSide(color: color, width: borderWidth) - : BorderSide.none, - right: isCurrentCell - ? BorderSide(color: color, width: borderWidth) - : BorderSide.none, + bottom: + isCurrentCell + ? BorderSide(color: color, width: borderWidth) + : BorderSide.none, + left: + isCurrentCell + ? BorderSide(color: color, width: borderWidth) + : BorderSide.none, + top: + isCurrentCell + ? BorderSide(color: color, width: borderWidth) + : BorderSide.none, + right: + isCurrentCell + ? BorderSide(color: color, width: borderWidth) + : BorderSide.none, ); } @@ -2790,7 +3253,9 @@ Widget _wrapInsideCellContainer( double height; if (dataCell.rowSpan > 0) { height = dataCell.dataRow!.getRowHeight( - dataCell.rowIndex - dataCell.rowSpan, dataCell.rowIndex); + dataCell.rowIndex - dataCell.rowSpan, + dataCell.rowIndex, + ); } else { height = defaultHeight; } @@ -2806,10 +3271,13 @@ Widget _wrapInsideCellContainer( double width; if (dataCell.columnSpan > 0) { width = dataCell.dataRow!.getColumnWidth( - dataCell.columnIndex, dataCell.columnIndex + dataCell.columnSpan); + dataCell.columnIndex, + dataCell.columnIndex + dataCell.columnSpan, + ); if (dataGridConfiguration.source.groupedColumns.isNotEmpty && dataCell.dataRow!.rowType == RowType.tableSummaryCoveredRow) { - width += dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth * + width += + dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth * dataGridConfiguration.source.groupedColumns.length; } } else { @@ -2828,39 +3296,52 @@ Widget _wrapInsideCellContainer( return Stack( children: [ Container( - width: width, - height: height, - color: backgroundColor, - child: child), + width: width, + height: height, + color: backgroundColor, + child: child, + ), Positioned( - left: 0, - top: 0, - width: width, - height: height, - child: IgnorePointer( - child: Container( - key: key, - clipBehavior: Clip.antiAlias, - decoration: BoxDecoration(border: getBorder())), - )), + left: 0, + top: 0, + width: width, + height: height, + child: IgnorePointer( + child: Container( + key: key, + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration(border: getBorder()), + ), + ), + ), ], ); } else { return Container( - width: width, height: height, color: backgroundColor, child: child); + width: width, + height: height, + color: backgroundColor, + child: child, + ); } } return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraint) { - return getChild(constraint); - }); + builder: (BuildContext context, BoxConstraints constraint) { + return getChild(constraint); + }, + ); } bool _invokeGroupChangingCallback( - DataGridConfiguration dataGridConfiguration, Group group) { + DataGridConfiguration dataGridConfiguration, + Group group, +) { final DataGridGroupChangingDetails details = DataGridGroupChangingDetails( - key: group.key, groupLevel: group.level, isExpanded: group.isExpanded); + key: group.key, + groupLevel: group.level, + isExpanded: group.isExpanded, + ); if (group.isExpanded) { if (dataGridConfiguration.groupCollapsing != null) { return dataGridConfiguration.groupCollapsing!(details); @@ -2875,9 +3356,15 @@ bool _invokeGroupChangingCallback( } void _invokeGroupChangedCallback( - DataGridConfiguration dataGridConfiguration, Group group, bool isExpanded) { + DataGridConfiguration dataGridConfiguration, + Group group, + bool isExpanded, +) { final DataGridGroupChangedDetails details = DataGridGroupChangedDetails( - key: group.key, groupLevel: group.level, isExpanded: isExpanded); + key: group.key, + groupLevel: group.level, + isExpanded: isExpanded, + ); if (dataGridConfiguration.groupCollapsed != null && !isExpanded) { dataGridConfiguration.groupCollapsed!(details); } else if (dataGridConfiguration.groupExpanded != null && isExpanded) { @@ -2887,23 +3374,76 @@ void _invokeGroupChangedCallback( // Gesture Events -Future _handleOnTapUp( - {required TapUpDetails? tapUpDetails, - required TapDownDetails? tapDownDetails, - required DataCellBase dataCell, - required DataGridConfiguration dataGridConfiguration, - required PointerDeviceKind kind}) async { +Future _handleOnTapUp({ + required TapUpDetails? tapUpDetails, + required TapDownDetails? tapDownDetails, + required DataCellBase dataCell, + required DataGridConfiguration dataGridConfiguration, + required PointerDeviceKind kind, +}) async { // End edit the current editing cell if its editing mode is differed if (dataGridConfiguration.currentCell.isEditing) { - if (await dataGridConfiguration.currentCell - .canSubmitCell(dataGridConfiguration)) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, cancelCanSubmitCell: true); + if (await dataGridConfiguration.currentCell.canSubmitCell( + dataGridConfiguration, + )) { + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + cancelCanSubmitCell: true, + ); } else { return; } } + dataGridConfiguration.dataGridFocusNode?.requestFocus(); + dataCell.onTouchUp(); + + // Expand or collpase the individual group by tap. + if (dataGridConfiguration.source.groupedColumns.isNotEmpty && + dataGridConfiguration.allowExpandCollapseGroup && + dataCell.dataRow!.rowType == RowType.captionSummaryCoveredRow) { + final int rowIndex = resolveStartRecordIndex( + dataGridConfiguration, + dataCell.dataRow!.rowIndex, + ); + if (rowIndex >= 0) { + final dynamic group = getGroupElement(dataGridConfiguration, rowIndex); + if (group is Group) { + if (group.isExpanded) { + if (_invokeGroupChangingCallback(dataGridConfiguration, group)) { + dataGridConfiguration.group!.collapseGroups( + group, + dataGridConfiguration.group, + rowIndex, + ); + dataGridConfiguration.groupExpandCollapseRowIndex = + dataCell.dataRow!.rowIndex; + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); + _invokeGroupChangedCallback(dataGridConfiguration, group, false); + } + } else { + if (_invokeGroupChangingCallback(dataGridConfiguration, group)) { + dataGridConfiguration.group!.expandGroups( + group, + dataGridConfiguration.group, + rowIndex, + ); + dataGridConfiguration.groupExpandCollapseRowIndex = + dataCell.dataRow!.rowIndex; + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); + _invokeGroupChangedCallback(dataGridConfiguration, group, true); + } + } + } + } + } + if (dataGridConfiguration.onCellTap != null) { // Issue: // FLUT-865739-A null exception occurred when expanding the group alongside the onCellTap callback. @@ -2912,140 +3452,123 @@ Future _handleOnTapUp( // // Fix: We need to check the gridcolumn is null or not before invoking the onCellDoubleTap callback. // For the caption summary cell, we need to get the first visible column from the columns collection. - final GridColumn? column = - grid_helper.getGridColumn(dataGridConfiguration, dataCell); + final GridColumn? column = grid_helper.getGridColumn( + dataGridConfiguration, + dataCell, + ); if (column == null) { return; } final DataGridCellTapDetails details = DataGridCellTapDetails( - rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), - column: column, - globalPosition: tapDownDetails != null - ? tapDownDetails.globalPosition - : tapUpDetails!.globalPosition, - localPosition: tapDownDetails != null - ? tapDownDetails.localPosition - : tapUpDetails!.localPosition, - kind: kind); + rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + column: column, + globalPosition: + tapDownDetails != null + ? tapDownDetails.globalPosition + : tapUpDetails!.globalPosition, + localPosition: + tapDownDetails != null + ? tapDownDetails.localPosition + : tapUpDetails!.localPosition, + kind: kind, + ); dataGridConfiguration.onCellTap!(details); } - dataGridConfiguration.dataGridFocusNode?.requestFocus(); - dataCell.onTouchUp(); - - // Expand or collpase the individual group by tap. - if (dataGridConfiguration.source.groupedColumns.isNotEmpty && - dataGridConfiguration.allowExpandCollapseGroup && - dataCell.dataRow!.rowType == RowType.captionSummaryCoveredRow) { - final int rowIndex = resolveStartRecordIndex( - dataGridConfiguration, dataCell.dataRow!.rowIndex); - if (rowIndex >= 0) { - final dynamic group = getGroupElement(dataGridConfiguration, rowIndex); - if (group is! Group) { - return; - } - if (group.isExpanded) { - if (_invokeGroupChangingCallback(dataGridConfiguration, group)) { - dataGridConfiguration.group! - .collapseGroups(group, dataGridConfiguration.group, rowIndex); - dataGridConfiguration.groupExpandCollapseRowIndex = - dataCell.dataRow!.rowIndex; - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); - _invokeGroupChangedCallback(dataGridConfiguration, group, false); - } - } else { - if (_invokeGroupChangingCallback(dataGridConfiguration, group)) { - dataGridConfiguration.group! - .expandGroups(group, dataGridConfiguration.group, rowIndex); - dataGridConfiguration.groupExpandCollapseRowIndex = - dataCell.dataRow!.rowIndex; - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); - _invokeGroupChangedCallback(dataGridConfiguration, group, true); - } - } - } - } - // Init the editing based on the editing mode if (dataGridConfiguration.editingGestureType == EditingGestureType.tap) { - dataGridConfiguration.currentCell - .onCellBeginEdit(editingDataCell: dataCell); + dataGridConfiguration.currentCell.onCellBeginEdit( + editingDataCell: dataCell, + ); } } -Future _handleOnDoubleTap( - {required DataCellBase dataCell, - required DataGridConfiguration dataGridConfiguration}) async { +Future _handleOnDoubleTap({ + required DataCellBase dataCell, + required DataGridConfiguration dataGridConfiguration, +}) async { // End edit the current editing cell if its editing mode is differed if (dataGridConfiguration.currentCell.isEditing) { - if (await dataGridConfiguration.currentCell - .canSubmitCell(dataGridConfiguration)) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, cancelCanSubmitCell: true); + if (await dataGridConfiguration.currentCell.canSubmitCell( + dataGridConfiguration, + )) { + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + cancelCanSubmitCell: true, + ); } else { return; } } + dataGridConfiguration.dataGridFocusNode?.requestFocus(); + dataCell.onTouchUp(); + if (dataGridConfiguration.onCellDoubleTap != null) { - final GridColumn? column = - grid_helper.getGridColumn(dataGridConfiguration, dataCell); + final GridColumn? column = grid_helper.getGridColumn( + dataGridConfiguration, + dataCell, + ); if (column == null) { return; } final DataGridCellDoubleTapDetails details = DataGridCellDoubleTapDetails( - rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), - column: column); + rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + column: column, + ); dataGridConfiguration.onCellDoubleTap!(details); } - dataGridConfiguration.dataGridFocusNode?.requestFocus(); - dataCell.onTouchUp(); - // Init the editing based on the editing mode if (dataGridConfiguration.editingGestureType == EditingGestureType.doubleTap) { - dataGridConfiguration.currentCell - .onCellBeginEdit(editingDataCell: dataCell); + dataGridConfiguration.currentCell.onCellBeginEdit( + editingDataCell: dataCell, + ); } } -Future _handleOnSecondaryTapUp( - {required TapUpDetails tapUpDetails, - required DataCellBase dataCell, - required DataGridConfiguration dataGridConfiguration, - required PointerDeviceKind kind}) async { +Future _handleOnSecondaryTapUp({ + required TapUpDetails tapUpDetails, + required DataCellBase dataCell, + required DataGridConfiguration dataGridConfiguration, + required PointerDeviceKind kind, +}) async { // Need to end the editing cell when interacting with other tap gesture if (dataGridConfiguration.currentCell.isEditing) { - if (await dataGridConfiguration.currentCell - .canSubmitCell(dataGridConfiguration)) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, cancelCanSubmitCell: true); + if (await dataGridConfiguration.currentCell.canSubmitCell( + dataGridConfiguration, + )) { + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + cancelCanSubmitCell: true, + ); } else { return; } } if (dataGridConfiguration.onCellSecondaryTap != null) { - final GridColumn? column = - grid_helper.getGridColumn(dataGridConfiguration, dataCell); + final GridColumn? column = grid_helper.getGridColumn( + dataGridConfiguration, + dataCell, + ); if (column == null) { return; } final DataGridCellTapDetails details = DataGridCellTapDetails( - rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), - column: column, - globalPosition: tapUpDetails.globalPosition, - localPosition: tapUpDetails.localPosition, - kind: kind); + rowColumnIndex: RowColumnIndex(dataCell.rowIndex, dataCell.columnIndex), + column: column, + globalPosition: tapUpDetails.globalPosition, + localPosition: tapUpDetails.localPosition, + kind: kind, + ); dataGridConfiguration.onCellSecondaryTap!(details); } } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/rendering_widget.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/rendering_widget.dart index 97d4b35dc..16fe46314 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/rendering_widget.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/rendering_widget.dart @@ -31,8 +31,9 @@ class VisualContainerRenderObjectWidget extends MultiChildRenderObjectWidget { required this.dataGridStateDetails, required this.children, }) : super( - key: key, - children: RepaintBoundary.wrapAll(List.from(children))); + key: key, + children: RepaintBoundary.wrapAll(List.from(children)), + ); @override final List children; @@ -50,13 +51,16 @@ class VisualContainerRenderObjectWidget extends MultiChildRenderObjectWidget { @override RenderVisualContainer createRenderObject(BuildContext context) => RenderVisualContainer( - containerSize: containerSize, - isDirty: isDirty, - dataGridStateDetails: dataGridStateDetails); + containerSize: containerSize, + isDirty: isDirty, + dataGridStateDetails: dataGridStateDetails, + ); @override void updateRenderObject( - BuildContext context, RenderVisualContainer renderObject) { + BuildContext context, + RenderVisualContainer renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..containerSize = containerSize @@ -86,20 +90,21 @@ class RenderVisualContainer extends RenderBox ContainerRenderObjectMixin, RenderBoxContainerDefaultsMixin { /// Creates a [RenderVisualContainer] for `SfDataGrid`. - RenderVisualContainer( - {List? children, - required Size containerSize, - required bool isDirty, - required DataGridStateDetails? dataGridStateDetails}) - : _containerSize = containerSize, - _isDirty = isDirty, - _dataGridStateDetails = dataGridStateDetails! { + RenderVisualContainer({ + List? children, + required Size containerSize, + required bool isDirty, + required DataGridStateDetails? dataGridStateDetails, + }) : _containerSize = containerSize, + _isDirty = isDirty, + _dataGridStateDetails = dataGridStateDetails! { addAll(children); _gestureArenaTeam = GestureArenaTeam(); - _panGestureRecognizer = PanGestureRecognizer() - ..team = _gestureArenaTeam - ..onStart = ((DragStartDetails details) {}) - ..dragStartBehavior = DragStartBehavior.down; + _panGestureRecognizer = + PanGestureRecognizer() + ..team = _gestureArenaTeam + ..onStart = ((DragStartDetails details) {}) + ..dragStartBehavior = DragStartBehavior.down; _gestureArenaTeam.captain = _panGestureRecognizer; } @@ -206,13 +211,15 @@ class RenderVisualContainer extends RenderBox if (dataGridConfiguration.textDirection == TextDirection.rtl && viewWidth > extentWidth) { - dxPosition = (dataGridConfiguration.swipingOffset >= 0) - ? viewWidth - extentWidth - : viewWidth - maxSwipeOffset; + dxPosition = + (dataGridConfiguration.swipingOffset >= 0) + ? viewWidth - extentWidth + : viewWidth - maxSwipeOffset; } else { - dxPosition = (dataGridConfiguration.swipingOffset >= 0) - ? 0.0 - : extentWidth - maxSwipeOffset; + dxPosition = + (dataGridConfiguration.swipingOffset >= 0) + ? 0.0 + : extentWidth - maxSwipeOffset; } return Offset(dxPosition, swipeRowRect.top); @@ -221,8 +228,9 @@ class RenderVisualContainer extends RenderBox // Provides the `Rect` to clip outside bounds of a swipe widget. Rect _getSwipeWidgetClipRect() { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); - final Rect swipeRowRect = - _swipeWholeRowElement!._measureRowRect(size.width); + final Rect swipeRowRect = _swipeWholeRowElement!._measureRowRect( + size.width, + ); final double swipeValue = dataGridConfiguration.swipingAnimation!.value; final VisibleLineInfo? lineInfo = _swipeWholeRowElement!._dataRow .getRowVisibleLineInfo(_swipeWholeRowElement!._dataRow.rowIndex); @@ -243,7 +251,11 @@ class RenderVisualContainer extends RenderBox if (dataGridConfiguration.swipingOffset.isNegative) { final double maxOffset = getSwipeMaxOffset(dataGridConfiguration); return Rect.fromLTWH( - maxOffset - swipeValue.abs(), top, maxOffset, height); + maxOffset - swipeValue.abs(), + top, + maxOffset, + height, + ); } else { return Rect.fromLTWH(0.0, top, swipeValue, height); } @@ -251,15 +263,19 @@ class RenderVisualContainer extends RenderBox @override void performLayout() { - size = - constraints.constrain(Size(containerSize.width, containerSize.height)); - - void layout( - {required RenderBox child, - required double width, - required double height}) { - child.layout(BoxConstraints.tightFor(width: width, height: height), - parentUsesSize: true); + size = constraints.constrain( + Size(containerSize.width, containerSize.height), + ); + + void layout({ + required RenderBox child, + required double width, + required double height, + }) { + child.layout( + BoxConstraints.tightFor(width: width, height: height), + parentUsesSize: true, + ); } RenderBox? child = firstChild; @@ -281,13 +297,13 @@ class RenderVisualContainer extends RenderBox ..height = rowRect.height ..rowClipRect = wholeRowElement._rowClipRect ..offset = Offset( - (wholeRowElement.dataRow.isSwipingRow && - dataGridConfiguration.swipingOffset != 0.0 && - dataGridConfiguration.swipingAnimation != null) - ? rowRect.left + - dataGridConfiguration.swipingAnimation!.value - : rowRect.left, - rowRect.top); + (wholeRowElement.dataRow.isSwipingRow && + dataGridConfiguration.swipingOffset != 0.0 && + dataGridConfiguration.swipingAnimation != null) + ? rowRect.left + dataGridConfiguration.swipingAnimation!.value + : rowRect.left, + rowRect.top, + ); if (wholeRowElement.dataRow.isSwipingRow && dataGridConfiguration.swipingOffset.abs() > 0.0) { @@ -295,7 +311,10 @@ class RenderVisualContainer extends RenderBox } layout( - child: child, width: parentData.width, height: parentData.height); + child: child, + width: parentData.width, + height: parentData.height, + ); } else { child.layout(const BoxConstraints.tightFor(width: 0.0, height: 0.0)); parentData.reset(); @@ -305,8 +324,9 @@ class RenderVisualContainer extends RenderBox // So, we can get it directly from lastChild property. final RenderBox? swipingWidget = lastChild; if (swipingWidget != null && _swipeWholeRowElement != null) { - final Rect swipeRowRect = - _swipeWholeRowElement!._measureRowRect(size.width); + final Rect swipeRowRect = _swipeWholeRowElement!._measureRowRect( + size.width, + ); parentData ..width = getSwipeMaxOffset(dataGridConfiguration) @@ -314,9 +334,10 @@ class RenderVisualContainer extends RenderBox ..offset = _getSwipingChildOffset(swipeRowRect); layout( - child: swipingWidget, - width: parentData.width, - height: parentData.height); + child: swipingWidget, + width: parentData.width, + height: parentData.height, + ); } } @@ -344,11 +365,14 @@ class RenderVisualContainer extends RenderBox if (swipeWidget != null) { final _VisualContainerParentData childParentData = swipeWidget.parentData! as _VisualContainerParentData; - context.pushClipRect(needsCompositing, - childParentData.offset + offset, _getSwipeWidgetClipRect(), - (PaintingContext context, Offset offset) { - context.paintChild(swipeWidget, offset); - }); + context.pushClipRect( + needsCompositing, + childParentData.offset + offset, + _getSwipeWidgetClipRect(), + (PaintingContext context, Offset offset) { + context.paintChild(swipeWidget, offset); + }, + ); } } @@ -376,13 +400,13 @@ class RenderVisualContainer extends RenderBox class VirtualizingCellsRenderObjectWidget extends MultiChildRenderObjectWidget { /// Creates the [VirtualizingCellsRenderObjectWidget] for the /// [RenderVirtualizingCellsWidget]. - VirtualizingCellsRenderObjectWidget( - {super.key, - required this.dataRow, - required this.isDirty, - required this.children, - required this.dataGridStateDetails}) - : super(children: RepaintBoundary.wrapAll(List.from(children))); + VirtualizingCellsRenderObjectWidget({ + super.key, + required this.dataRow, + required this.isDirty, + required this.children, + required this.dataGridStateDetails, + }) : super(children: RepaintBoundary.wrapAll(List.from(children))); @override final List children; @@ -400,13 +424,16 @@ class VirtualizingCellsRenderObjectWidget extends MultiChildRenderObjectWidget { @override RenderVirtualizingCellsWidget createRenderObject(BuildContext context) => RenderVirtualizingCellsWidget( - dataRow: dataRow, - isDirty: isDirty, - dataGridStateDetails: dataGridStateDetails); + dataRow: dataRow, + isDirty: isDirty, + dataGridStateDetails: dataGridStateDetails, + ); @override void updateRenderObject( - BuildContext context, RenderVirtualizingCellsWidget renderObject) { + BuildContext context, + RenderVirtualizingCellsWidget renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..dataRow = dataRow @@ -434,21 +461,24 @@ class _VirtualizingCellWidgetParentData /// virtualizing cells in the data grid. class RenderVirtualizingCellsWidget extends RenderBox with - ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin - implements - MouseTrackerAnnotation { + ContainerRenderObjectMixin< + RenderBox, + _VirtualizingCellWidgetParentData + >, + RenderBoxContainerDefaultsMixin< + RenderBox, + _VirtualizingCellWidgetParentData + > + implements MouseTrackerAnnotation { /// Creates a [RenderVirtualizingCellsWidget] for `SfDataGrid`. RenderVirtualizingCellsWidget({ List? children, required DataRowBase dataRow, required bool isDirty, required DataGridStateDetails? dataGridStateDetails, - }) : _dataRow = dataRow, - _isDirty = isDirty, - _dataGridStateDetails = dataGridStateDetails! { + }) : _dataRow = dataRow, + _isDirty = isDirty, + _dataGridStateDetails = dataGridStateDetails! { addAll(children); // Provides the `postAcceptSlopTolerance` to restrict the call of // long press event from the framework when executing the PointerMoveEvent. @@ -516,8 +546,8 @@ class RenderVirtualizingCellsWidget extends RenderBox _dataGridStateDetails(); final VisualContainerHelper container = dataGridConfiguration.container; - final VisibleLineInfo? lineInfo = - container.scrollRows.getVisibleLineAtLineIndex(dataRow.rowIndex); + final VisibleLineInfo? lineInfo = container.scrollRows + .getVisibleLineAtLineIndex(dataRow.rowIndex); final double lineSize = lineInfo != null ? lineInfo.size : 0.0; double origin = (lineInfo != null) ? lineInfo.origin : 0.0; @@ -526,10 +556,14 @@ class RenderVirtualizingCellsWidget extends RenderBox if (dataRow.rowIndex > grid_helper.getHeaderIndex(dataGridConfiguration)) { - final double headerRowsHeight = container.scrollRows - .rangeToRegionPoints( - 0, grid_helper.getHeaderIndex(dataGridConfiguration), true)[1] - .length; + final double headerRowsHeight = + container.scrollRows + .rangeToRegionPoints( + 0, + grid_helper.getHeaderIndex(dataGridConfiguration), + true, + )[1] + .length; origin -= headerRowsHeight; } @@ -543,7 +577,10 @@ class RenderVirtualizingCellsWidget extends RenderBox } Rect? _getRowClipRect( - VisibleLineInfo? lineInfo, double lineHeight, double width) { + VisibleLineInfo? lineInfo, + double lineHeight, + double width, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); // Clipping the row when the frozen rows are applied. @@ -559,41 +596,46 @@ class RenderVirtualizingCellsWidget extends RenderBox if (dataGridConfiguration.allowSwiping && dataRow.isSwipingRow) { return _getSwipingRowClipRect( - top: top, - height: height, - dataGridConfiguration: dataGridConfiguration); + top: top, + height: height, + dataGridConfiguration: dataGridConfiguration, + ); } else { return Rect.fromLTWH(0.0, top, width, height); } } else if (dataGridConfiguration.allowSwiping && dataRow.isSwipingRow) { return _getSwipingRowClipRect( - top: 0.0, - height: lineHeight, - dataGridConfiguration: dataGridConfiguration); + top: 0.0, + height: lineHeight, + dataGridConfiguration: dataGridConfiguration, + ); } else { return null; } } - Rect? _getSwipingRowClipRect( - {required DataGridConfiguration dataGridConfiguration, - required double top, - required double height}) { + Rect? _getSwipingRowClipRect({ + required DataGridConfiguration dataGridConfiguration, + required double top, + required double height, + }) { if (dataGridConfiguration.swipingAnimation == null) { return null; } double leftPosition = 0.0; final double viewWidth = dataGridConfiguration.viewWidth; final double extentWidth = dataGridConfiguration.container.extentWidth; - final double swipingDelta = dataGridConfiguration.swipingOffset >= 0 - ? dataGridConfiguration.swipingAnimation!.value - : -dataGridConfiguration.swipingAnimation!.value; + final double swipingDelta = + dataGridConfiguration.swipingOffset >= 0 + ? dataGridConfiguration.swipingAnimation!.value + : -dataGridConfiguration.swipingAnimation!.value; if (dataGridConfiguration.textDirection == TextDirection.rtl && viewWidth > extentWidth) { - leftPosition = dataGridConfiguration.swipingOffset >= 0 - ? viewWidth - extentWidth - : (viewWidth - extentWidth) + swipingDelta; + leftPosition = + dataGridConfiguration.swipingOffset >= 0 + ? viewWidth - extentWidth + : (viewWidth - extentWidth) + swipingDelta; } else { leftPosition = dataGridConfiguration.swipingOffset >= 0 ? 0 : swipingDelta; @@ -601,8 +643,12 @@ class RenderVirtualizingCellsWidget extends RenderBox return Rect.fromLTWH(leftPosition, top, extentWidth - swipingDelta, height); } - Rect _getRowRect(DataGridConfiguration dataGridConfiguration, Offset offset, - {bool isHoveredLayer = false, bool isCurrentRowBorderLayer = false}) { + Rect _getRowRect( + DataGridConfiguration dataGridConfiguration, + Offset offset, { + bool isHoveredLayer = false, + bool isCurrentRowBorderLayer = false, + }) { bool needToSetMaxConstraint() => dataGridConfiguration.container.extentWidth < dataGridConfiguration.viewWidth && @@ -610,10 +656,11 @@ class RenderVirtualizingCellsWidget extends RenderBox if (dataRow.rowType == RowType.footerRow) { return Rect.fromLTWH( - offset.dx + dataGridConfiguration.container.horizontalOffset, - offset.dy, - dataGridConfiguration.viewWidth, - dataGridConfiguration.footerHeight); + offset.dx + dataGridConfiguration.container.horizontalOffset, + offset.dy, + dataGridConfiguration.viewWidth, + dataGridConfiguration.footerHeight, + ); } else { late int indentCount; final bool isRTLDirection = @@ -621,7 +668,8 @@ class RenderVirtualizingCellsWidget extends RenderBox // Current row border is applicable for both data row and caption summary covered row // So, considered the row type with this `isCurrentRowBorderLayer` flag itself. - isCurrentRowBorderLayer = isCurrentRowBorderLayer && + isCurrentRowBorderLayer = + isCurrentRowBorderLayer && (dataRow.rowType == RowType.dataRow || dataRow.rowType == RowType.captionSummaryCoveredRow); @@ -637,14 +685,17 @@ class RenderVirtualizingCellsWidget extends RenderBox final double indentColumnsWidth = dataGridConfiguration.dataGridThemeHelper!.indentColumnWidth * - indentCount; - - double dx = needToSetMaxConstraint() - ? constraints.maxWidth - - min(dataGridConfiguration.container.extentWidth, - dataGridConfiguration.viewWidth) - - dataGridConfiguration.container.horizontalOffset - : dataGridConfiguration.container.horizontalOffset; + indentCount; + + double dx = + needToSetMaxConstraint() + ? constraints.maxWidth - + min( + dataGridConfiguration.container.extentWidth, + dataGridConfiguration.viewWidth, + ) - + dataGridConfiguration.container.horizontalOffset + : dataGridConfiguration.container.horizontalOffset; if (isCurrentRowBorderLayer || (isHoveredLayer && dataRow.rowType == RowType.dataRow)) { @@ -655,10 +706,13 @@ class RenderVirtualizingCellsWidget extends RenderBox } } - double width = needToSetMaxConstraint() - ? constraints.maxWidth - : min(dataGridConfiguration.container.extentWidth, - dataGridConfiguration.viewWidth); + double width = + needToSetMaxConstraint() + ? constraints.maxWidth + : min( + dataGridConfiguration.container.extentWidth, + dataGridConfiguration.viewWidth, + ); if (isCurrentRowBorderLayer || (isHoveredLayer && dataRow.rowType == RowType.dataRow)) { @@ -667,7 +721,8 @@ class RenderVirtualizingCellsWidget extends RenderBox // the datagrid is unscrollable. if (needToSetMaxConstraint() && (isHoveredLayer && dataRow.rowType == RowType.dataRow)) { - width -= dataGridConfiguration.viewWidth - + width -= + dataGridConfiguration.viewWidth - dataGridConfiguration.container.extentWidth; } @@ -675,7 +730,8 @@ class RenderVirtualizingCellsWidget extends RenderBox if (isRTLDirection) { if (dataGridConfiguration.container.extentWidth > dataGridConfiguration.viewWidth) { - scrollOffset = (dataGridConfiguration.container.extentWidth - + scrollOffset = + (dataGridConfiguration.container.extentWidth - dataGridConfiguration.viewWidth) - dataGridConfiguration.container.horizontalOffset; } @@ -689,26 +745,35 @@ class RenderVirtualizingCellsWidget extends RenderBox } } - final double height = (isHoveredLayer && - dataRow.isHoveredRow && - (dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.horizontal || - dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.both)) - ? constraints.maxHeight - - dataGridConfiguration.dataGridThemeHelper!.gridLineStrokeWidth! - : constraints.maxHeight; + final double height = + (isHoveredLayer && + dataRow.isHoveredRow && + (dataGridConfiguration.gridLinesVisibility == + GridLinesVisibility.horizontal || + dataGridConfiguration.gridLinesVisibility == + GridLinesVisibility.both)) + ? constraints.maxHeight - + dataGridConfiguration + .dataGridThemeHelper! + .gridLineStrokeWidth! + : constraints.maxHeight; return Rect.fromLTWH(offset.dx + dx, offset.dy, width, height); } } - void _drawRowBackground(DataGridConfiguration dataGridConfiguration, - PaintingContext context, Offset offset) { + void _drawRowBackground( + DataGridConfiguration dataGridConfiguration, + PaintingContext context, + Offset offset, + ) { // Need to consider the selected row as hovered layer to avoid apply // selection for the indent columns. - final Rect rect = _getRowRect(dataGridConfiguration, offset, - isHoveredLayer: dataRow.isSelectedRow); + final Rect rect = _getRowRect( + dataGridConfiguration, + offset, + isHoveredLayer: dataRow.isSelectedRow, + ); Color? backgroundColor; @@ -717,8 +782,9 @@ class RenderVirtualizingCellsWidget extends RenderBox } void drawSpannedRowBackgroundColor(Color backgroundColor) { - final bool isRowSpanned = dataRow.visibleColumns - .any((DataCellBase dataCell) => dataCell.rowSpan > 0); + final bool isRowSpanned = dataRow.visibleColumns.any( + (DataCellBase dataCell) => dataCell.rowSpan > 0, + ); final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); @@ -728,13 +794,16 @@ class RenderVirtualizingCellsWidget extends RenderBox final _VirtualizingCellWidgetParentData childParentData = child.parentData! as _VirtualizingCellWidgetParentData; final DataCellBase dataCell = child.dataCell; - final VisibleLineInfo? lineInfo = - dataRow.getColumnVisibleLineInfo(dataCell.columnIndex); + final VisibleLineInfo? lineInfo = dataRow.getColumnVisibleLineInfo( + dataCell.columnIndex, + ); if (dataCell.rowSpan > 0 && lineInfo != null) { final Rect? columnRect = child._columnRect; final Rect? cellClipRect = child._cellClipRect; final double height = dataRow.getRowHeight( - dataCell.rowIndex - dataCell.rowSpan, dataCell.rowIndex); + dataCell.rowIndex - dataCell.rowSpan, + dataCell.rowIndex, + ); Rect cellRect = Rect.zero; if (cellClipRect != null) { double left = columnRect!.left; @@ -749,7 +818,11 @@ class RenderVirtualizingCellsWidget extends RenderBox cellRect = Rect.fromLTWH(left, columnRect.top, width, height); } else { cellRect = Rect.fromLTWH( - columnRect!.left, columnRect.top, columnRect.width, height); + columnRect!.left, + columnRect.top, + columnRect.width, + height, + ); } dataGridConfiguration.gridPaint?.color = backgroundColor; context.canvas.drawRect(cellRect, dataGridConfiguration.gridPaint!); @@ -772,16 +845,18 @@ class RenderVirtualizingCellsWidget extends RenderBox backgroundColor = getDefaultRowBackgroundColor(); } else if (dataRow.rowType == RowType.tableSummaryRow || dataRow.rowType == RowType.tableSummaryCoveredRow) { - backgroundColor = dataRow.tableSummaryRow?.color ?? + backgroundColor = + dataRow.tableSummaryRow?.color ?? dataGridConfiguration.dataGridThemeHelper!.tableSummaryRowColor; } else if (dataRow.rowType == RowType.captionSummaryCoveredRow) { backgroundColor = getDefaultRowBackgroundColor(); } else { /// Need to check the rowStyle Please look the previous version and /// selection preference - backgroundColor = dataRow.isSelectedRow - ? dataGridConfiguration.dataGridThemeHelper!.selectionColor - : dataRow.dataGridRowAdapter!.color; + backgroundColor = + dataRow.isSelectedRow + ? dataGridConfiguration.dataGridThemeHelper!.selectionColor + : dataRow.dataGridRowAdapter!.color; } // Default theme color are common for both the HeaderBackgroundColor and @@ -809,31 +884,41 @@ class RenderVirtualizingCellsWidget extends RenderBox dataGridConfiguration.textDirection == TextDirection.rtl; const double stokeWidth = 1; - final int origin = (stokeWidth / 2 + - dataGridConfiguration.dataGridThemeHelper!.gridLineStrokeWidth!) - .ceil(); - - final Rect rowRect = _getRowRect(dataGridConfiguration, offset, - isCurrentRowBorderLayer: true); + final int origin = + (stokeWidth / 2 + + dataGridConfiguration + .dataGridThemeHelper! + .gridLineStrokeWidth!) + .ceil(); + + final Rect rowRect = _getRowRect( + dataGridConfiguration, + offset, + isCurrentRowBorderLayer: true, + ); - final double maxWidth = needToSetMaxConstraint() - ? rowRect.width - rowRect.left - : rowRect.right - rowRect.left; + final double maxWidth = + needToSetMaxConstraint() + ? rowRect.width - rowRect.left + : rowRect.right - rowRect.left; final bool isHorizontalGridLinesEnabled = dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.both || - dataGridConfiguration.gridLinesVisibility == - GridLinesVisibility.horizontal; + GridLinesVisibility.both || + dataGridConfiguration.gridLinesVisibility == + GridLinesVisibility.horizontal; dataGridConfiguration.boxPainter!.paint( - context.canvas, - Offset(rowRect.left + origin, rowRect.top + (origin / 2)), - dataGridConfiguration.configuration!.copyWith( - size: Size( - maxWidth - (origin * 2), - constraints.maxHeight - - (origin * (isHorizontalGridLinesEnabled ? 1.5 : 1))))); + context.canvas, + Offset(rowRect.left + origin, rowRect.top + (origin / 2)), + dataGridConfiguration.configuration!.copyWith( + size: Size( + maxWidth - (origin * 2), + constraints.maxHeight - + (origin * (isHorizontalGridLinesEnabled ? 1.5 : 1)), + ), + ), + ); } } @@ -848,23 +933,27 @@ class RenderVirtualizingCellsWidget extends RenderBox void _handleSwipingListener() { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'Swiping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'Swiping', + ); } @override void attach(PipelineOwner owner) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); - dataGridConfiguration.swipingAnimationController - ?.addListener(_handleSwipingListener); + dataGridConfiguration.swipingAnimationController?.addListener( + _handleSwipingListener, + ); super.attach(owner); } @override void detach() { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); - dataGridConfiguration.swipingAnimationController - ?.removeListener(_handleSwipingListener); + dataGridConfiguration.swipingAnimationController?.removeListener( + _handleSwipingListener, + ); super.detach(); } @@ -902,8 +991,9 @@ class RenderVirtualizingCellsWidget extends RenderBox @override bool hitTest(BoxHitTestResult result, {required Offset position}) { - final bool isRowSpanned = dataRow.visibleColumns - .any((DataCellBase dataCell) => dataCell.rowSpan > 0); + final bool isRowSpanned = dataRow.visibleColumns.any( + (DataCellBase dataCell) => dataCell.rowSpan > 0, + ); if (isRowSpanned) { RenderBox? child = lastChild; @@ -936,17 +1026,22 @@ class RenderVirtualizingCellsWidget extends RenderBox } void _updateSwipingAnimation( - DataGridConfiguration dataGridConfiguration, double swipeMaxOffset) { + DataGridConfiguration dataGridConfiguration, + double swipeMaxOffset, + ) { dataGridConfiguration.swipingAnimation = Tween( - begin: 0.0, - end: dataGridConfiguration.swipingOffset.sign >= 0 - ? swipeMaxOffset - : -swipeMaxOffset) - .animate(dataGridConfiguration.swipingAnimationController!); + begin: 0.0, + end: + dataGridConfiguration.swipingOffset.sign >= 0 + ? swipeMaxOffset + : -swipeMaxOffset, + ).animate(dataGridConfiguration.swipingAnimationController!); } void _handleSwipeStart( - PointerDownEvent event, DataGridConfiguration dataGridConfiguration) { + PointerDownEvent event, + DataGridConfiguration dataGridConfiguration, + ) { // Need to reset the swiping and scrolling state to default when pointer // up and touch again dataGridConfiguration.isSwipingApplied = false; @@ -960,31 +1055,42 @@ class RenderVirtualizingCellsWidget extends RenderBox // If it's tapped on different [DataGridRow] or scrolled, we need to end // the swiping. final DataRowBase? swipedRow = dataGridConfiguration.rowGenerator.items - .firstWhereOrNull((DataRowBase row) => - row.isSwipingRow && dataGridConfiguration.swipingOffset.abs() > 0); + .firstWhereOrNull( + (DataRowBase row) => + row.isSwipingRow && dataGridConfiguration.swipingOffset.abs() > 0, + ); if (swipedRow != null && swipedRow.rowIndex != dataRow.rowIndex) { - dataGridConfiguration.container - .resetSwipeOffset(swipedRow: swipedRow, canUpdate: true); + dataGridConfiguration.container.resetSwipeOffset( + swipedRow: swipedRow, + canUpdate: true, + ); dataGridConfiguration.swipingOffset = event.localDelta.dx; dy = event.localDelta.dy; } } void _handleSwipeUpdate( - PointerMoveEvent event, DataGridConfiguration dataGridConfiguration) { + PointerMoveEvent event, + DataGridConfiguration dataGridConfiguration, + ) { bool canUpdateSwiping = true; void onSwipeStart(int rowIndex) { if (_swipeDirection != null && dataGridConfiguration.onSwipeStart != null) { final DataGridSwipeStartDetails swipeStartDetails = DataGridSwipeStartDetails( - rowIndex: rowIndex, swipeDirection: _swipeDirection!); + rowIndex: rowIndex, + swipeDirection: _swipeDirection!, + ); setSwipeOffsetInDataGridSwipeStartDetailsArgs( - dataGridConfiguration, swipeStartDetails); + dataGridConfiguration, + swipeStartDetails, + ); dataGridConfiguration.effectiveSwipeMaxOffset = null; - _canStartSwiping = - dataGridConfiguration.onSwipeStart!(swipeStartDetails); + _canStartSwiping = dataGridConfiguration.onSwipeStart!( + swipeStartDetails, + ); } } @@ -1001,7 +1107,9 @@ class RenderVirtualizingCellsWidget extends RenderBox final ScrollController horizontalController = dataGridConfiguration.horizontalScrollController!; final int rowIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, dataRow.rowIndex); + dataGridConfiguration, + dataRow.rowIndex, + ); // Sets `swipeDirection` to null when the swipe offset is changed the // dragging direction to update the `swipeDirection` property. @@ -1015,7 +1123,9 @@ class RenderVirtualizingCellsWidget extends RenderBox horizontalController.position.minScrollExtent && _swipeDirection == null) { _swipeDirection = grid_helper.getSwipeDirection( - dataGridConfiguration, currentSwipingDelta); + dataGridConfiguration, + currentSwipingDelta, + ); onSwipeStart(rowIndex); } } else if (currentSwipingDelta < -2) { @@ -1023,24 +1133,31 @@ class RenderVirtualizingCellsWidget extends RenderBox horizontalController.position.maxScrollExtent && _swipeDirection == null) { _swipeDirection = grid_helper.getSwipeDirection( - dataGridConfiguration, currentSwipingDelta); + dataGridConfiguration, + currentSwipingDelta, + ); onSwipeStart(rowIndex); } } if (_swipeDirection != null && grid_helper.canSwipeRow( - dataGridConfiguration, _swipeDirection!, currentSwipingDelta)) { + dataGridConfiguration, + _swipeDirection!, + currentSwipingDelta, + )) { final double oldSwipingDelta = dataGridConfiguration.swipingOffset; if (_canStartSwiping) { dataGridConfiguration.isSwipingApplied = true; if (dataGridConfiguration.onSwipeUpdate != null) { final DataGridSwipeUpdateDetails swipeUpdateDetails = DataGridSwipeUpdateDetails( - rowIndex: rowIndex, - swipeDirection: _swipeDirection!, - swipeOffset: currentSwipingDelta); - canUpdateSwiping = - dataGridConfiguration.onSwipeUpdate!(swipeUpdateDetails); + rowIndex: rowIndex, + swipeDirection: _swipeDirection!, + swipeOffset: currentSwipingDelta, + ); + canUpdateSwiping = dataGridConfiguration.onSwipeUpdate!( + swipeUpdateDetails, + ); } if (!canUpdateSwiping || @@ -1074,16 +1191,24 @@ class RenderVirtualizingCellsWidget extends RenderBox } void _handleSwipeEnd( - PointerUpEvent event, DataGridConfiguration dataGridConfiguration) { + PointerUpEvent event, + DataGridConfiguration dataGridConfiguration, + ) { void onSwipeEnd() { if (dataGridConfiguration.onSwipeEnd != null) { final int rowIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, dataRow.rowIndex); - final DataGridRowSwipeDirection swipeDirection = - grid_helper.getSwipeDirection( - dataGridConfiguration, dataGridConfiguration.swipingOffset); + dataGridConfiguration, + dataRow.rowIndex, + ); + final DataGridRowSwipeDirection swipeDirection = grid_helper + .getSwipeDirection( + dataGridConfiguration, + dataGridConfiguration.swipingOffset, + ); final DataGridSwipeEndDetails swipeEndDetails = DataGridSwipeEndDetails( - rowIndex: rowIndex, swipeDirection: swipeDirection); + rowIndex: rowIndex, + swipeDirection: swipeDirection, + ); dataGridConfiguration.onSwipeEnd!(swipeEndDetails); } } @@ -1098,9 +1223,9 @@ class RenderVirtualizingCellsWidget extends RenderBox if (dataGridConfiguration.swipingOffset.abs() > maxOffset / 2) { dataGridConfiguration.swipingOffset = dataGridConfiguration.swipingOffset >= 0 ? maxOffset : -maxOffset; - dataGridConfiguration.swipingAnimationController! - .forward() - .then((_) => onSwipeEnd()); + dataGridConfiguration.swipingAnimationController!.forward().then( + (_) => onSwipeEnd(), + ); } else { dataGridConfiguration.swipingAnimationController!.reverse().then((_) { onSwipeEnd(); @@ -1190,32 +1315,43 @@ class RenderVirtualizingCellsWidget extends RenderBox final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); if (dataGridConfiguration.allowColumnsResizing) { if (event is PointerHoverEvent) { - dataGridConfiguration.columnResizeController - .onPointerHover(event, dataRow); + dataGridConfiguration.columnResizeController.onPointerHover( + event, + dataRow, + ); } if (event is PointerDownEvent) { - dataGridConfiguration.columnResizeController - .onPointerDown(event, dataRow); + dataGridConfiguration.columnResizeController.onPointerDown( + event, + dataRow, + ); } if (event is PointerMoveEvent) { - dataGridConfiguration.columnResizeController - .onPointerMove(event, dataRow); + dataGridConfiguration.columnResizeController.onPointerMove( + event, + dataRow, + ); } if (event is PointerUpEvent) { - dataGridConfiguration.columnResizeController - .onPointerUp(event, dataRow); + dataGridConfiguration.columnResizeController.onPointerUp( + event, + dataRow, + ); } } } @override void performLayout() { - void layout( - {required RenderBox child, - required double width, - required double height}) { - child.layout(BoxConstraints.tightFor(width: width, height: height), - parentUsesSize: true); + void layout({ + required RenderBox child, + required double width, + required double height, + }) { + child.layout( + BoxConstraints.tightFor(width: width, height: height), + parentUsesSize: true, + ); } RenderBox? child = firstChild; @@ -1233,17 +1369,21 @@ class RenderVirtualizingCellsWidget extends RenderBox ..height = columnRect.height ..cellClipRect = child._cellClipRect; layout( - child: child, width: parentData.width, height: parentData.height); + child: child, + width: parentData.width, + height: parentData.height, + ); parentData.offset = Offset(columnRect.left, columnRect.top); } else { if (dataRow.rowType == RowType.footerRow) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); final Rect cellRect = Rect.fromLTWH( - dataGridConfiguration.container.horizontalOffset, - 0.0, - dataGridConfiguration.viewWidth, - dataGridConfiguration.footerHeight); + dataGridConfiguration.container.horizontalOffset, + 0.0, + dataGridConfiguration.viewWidth, + dataGridConfiguration.footerHeight, + ); size = constraints.constrain(Size(cellRect.width, cellRect.height)); parentData @@ -1251,7 +1391,10 @@ class RenderVirtualizingCellsWidget extends RenderBox ..height = cellRect.height ..offset = Offset(cellRect.left, cellRect.top); layout( - child: child, width: parentData.width, height: parentData.height); + child: child, + width: parentData.width, + height: parentData.height, + ); } else { size = constraints.constrain(Size.zero); child.layout(const BoxConstraints.tightFor(width: 0, height: 0)); @@ -1262,20 +1405,26 @@ class RenderVirtualizingCellsWidget extends RenderBox } } - void _drawRowHoverBackground(DataGridConfiguration dataGridConfiguration, - PaintingContext context, Offset offset) { + void _drawRowHoverBackground( + DataGridConfiguration dataGridConfiguration, + PaintingContext context, + Offset offset, + ) { if (dataGridConfiguration.isDesktop && dataGridConfiguration.highlightRowOnHover && dataRow.isHoveredRow) { dataGridConfiguration.gridPaint?.color = dataGridConfiguration.dataGridThemeHelper!.rowHoverColor!; if (dataRow.rowType == RowType.captionSummaryCoveredRow) { - dataGridConfiguration.gridPaint?.color = dataGridConfiguration - .dataGridThemeHelper!.captionSummaryRowHoverColor; + dataGridConfiguration.gridPaint?.color = + dataGridConfiguration + .dataGridThemeHelper! + .captionSummaryRowHoverColor; } context.canvas.drawRect( - _getRowRect(dataGridConfiguration, offset, isHoveredLayer: true), - dataGridConfiguration.gridPaint!); + _getRowRect(dataGridConfiguration, offset, isHoveredLayer: true), + dataGridConfiguration.gridPaint!, + ); } } @@ -1321,7 +1470,8 @@ class RenderVirtualizingCellsWidget extends RenderBox MouseCursor get cursor { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); return dataGridConfiguration - .columnResizeController.canSwitchResizeColumnCursor + .columnResizeController + .canSwitchResizeColumnCursor ? SystemMouseCursors.resizeColumn : SystemMouseCursors.basic; } @@ -1343,10 +1493,7 @@ class RenderVirtualizingCellsWidget extends RenderBox dataRow.rowType == RowType.captionSummaryCoveredRow; } - DataCellBase? _getDataCellBase( - DataRowBase dataRow, - dynamic details, - ) { + DataCellBase? _getDataCellBase(DataRowBase dataRow, dynamic details) { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); DataCellBase? dataCell; @@ -1362,18 +1509,22 @@ class RenderVirtualizingCellsWidget extends RenderBox if (dataRow.rowType != RowType.footerRow) { final double position = dataGridConfiguration.columnResizeController .getXPosition(dataGridConfiguration, details.localPosition.dx); - final VisibleLineInfo? resizingLine = - dataGridConfiguration.container.scrollColumns.getVisibleLineAtPoint( - position, - false, - dataGridConfiguration.textDirection == TextDirection.rtl); + final VisibleLineInfo? resizingLine = dataGridConfiguration + .container + .scrollColumns + .getVisibleLineAtPoint( + position, + false, + dataGridConfiguration.textDirection == TextDirection.rtl, + ); if (dataRow.rowType == RowType.stackedHeaderRow || dataRow.rowType == RowType.tableSummaryRow || dataRow.rowType == RowType.captionSummaryCoveredRow || dataRow.rowType == RowType.tableSummaryCoveredRow) { - dataCell = - dataRow.visibleColumns.firstWhereOrNull((DataCellBase dataCell) { + dataCell = dataRow.visibleColumns.firstWhereOrNull(( + DataCellBase dataCell, + ) { final int cellLeft = dataCell.columnIndex; final int cellRight = dataCell.columnIndex + dataCell.columnSpan; @@ -1384,8 +1535,9 @@ class RenderVirtualizingCellsWidget extends RenderBox }); } else { dataCell = dataRow.visibleColumns.firstWhereOrNull( - (DataCellBase element) => - element.columnIndex == resizingLine!.lineIndex); + (DataCellBase element) => + element.columnIndex == resizingLine!.lineIndex, + ); } } return dataCell; @@ -1399,8 +1551,10 @@ class RenderVirtualizingCellsWidget extends RenderBox // Issue: FLUT-865739-A null exception occurred when expanding the group alongside the onCellTap callback. // Reason: The grid column is null when the row type is caption summary covered row. // Fix: Check the grid column is null or not before invoking the onCellLongPress callback. - final GridColumn? column = - grid_helper.getGridColumn(dataGridConfiguration, _dataCellBase!); + final GridColumn? column = grid_helper.getGridColumn( + dataGridConfiguration, + _dataCellBase!, + ); if (column == null) { return; @@ -1408,11 +1562,14 @@ class RenderVirtualizingCellsWidget extends RenderBox final DataGridCellLongPressDetails longPressDetails = DataGridCellLongPressDetails( - rowColumnIndex: RowColumnIndex( - _dataCellBase!.rowIndex, _dataCellBase!.columnIndex), - column: column, - globalPosition: _longPressStartDetails!.globalPosition, - localPosition: _longPressStartDetails!.localPosition); + rowColumnIndex: RowColumnIndex( + _dataCellBase!.rowIndex, + _dataCellBase!.columnIndex, + ), + column: column, + globalPosition: _longPressStartDetails!.globalPosition, + localPosition: _longPressStartDetails!.localPosition, + ); dataGridConfiguration.onCellLongPress!(longPressDetails); } } @@ -1429,8 +1586,10 @@ class RenderVirtualizingCellsWidget extends RenderBox _dataCellBase = dataCell; _longPressStartDetails = details; - dataGridConfiguration.columnResizeController - .onLongPressStart(details, dataRow); + dataGridConfiguration.columnResizeController.onLongPressStart( + details, + dataRow, + ); } // To handle long press end event. @@ -1448,10 +1607,13 @@ class RenderVirtualizingCellsWidget extends RenderBox dataGridConfiguration.currentCell.onCellSubmit(dataGridConfiguration); } else if (dataCell.cellType == CellType.gridCell) { // Clear editing when tap on the grid cell - if (await dataGridConfiguration.currentCell - .canSubmitCell(dataGridConfiguration)) { - await dataGridConfiguration.currentCell - .onCellSubmit(dataGridConfiguration, cancelCanSubmitCell: true); + if (await dataGridConfiguration.currentCell.canSubmitCell( + dataGridConfiguration, + )) { + await dataGridConfiguration.currentCell.onCellSubmit( + dataGridConfiguration, + cancelCanSubmitCell: true, + ); } } } @@ -1464,8 +1626,10 @@ class RenderVirtualizingCellsWidget extends RenderBox final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); if (dataGridConfiguration.allowColumnsResizing) { - dataGridConfiguration.columnResizeController - .onPointerEnter(event, dataRow); + dataGridConfiguration.columnResizeController.onPointerEnter( + event, + dataRow, + ); } // Restricts the row hovering when resizing the column. @@ -1480,16 +1644,19 @@ class RenderVirtualizingCellsWidget extends RenderBox dataRow.isHoveredRow = true; final TextStyle rowStyle = TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ); if (dataGridConfiguration.dataGridThemeHelper!.rowHoverTextStyle != rowStyle && dataRow.rowType != RowType.captionSummaryCoveredRow) { dataRow.rowIndexChanged(); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'hoverOnCell'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'hoverOnCell', + ); } markNeedsPaint(); } @@ -1502,8 +1669,10 @@ class RenderVirtualizingCellsWidget extends RenderBox final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); if (dataGridConfiguration.allowColumnsResizing) { - dataGridConfiguration.columnResizeController - .onPointerExit(event, dataRow); + dataGridConfiguration.columnResizeController.onPointerExit( + event, + dataRow, + ); } if (dataRow.isHoveredRow && @@ -1514,16 +1683,19 @@ class RenderVirtualizingCellsWidget extends RenderBox dataRow.isHoveredRow = false; final TextStyle rowStyle = TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: dataGridConfiguration.colorScheme!.onSurface[222]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: dataGridConfiguration.colorScheme!.onSurface[222], + ); if (dataGridConfiguration.dataGridThemeHelper!.rowHoverTextStyle != rowStyle && dataRow.rowType != RowType.captionSummaryCoveredRow) { dataRow.rowIndexChanged(); - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'hoverOnCell'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'hoverOnCell', + ); } markNeedsPaint(); } @@ -1557,9 +1729,10 @@ class GridCellRenderObjectWidget extends SingleChildRenderObjectWidget { @override RenderGridCell createRenderObject(BuildContext context) => RenderGridCell( - dataCell: dataCell, - isDirty: isDirty, - dataGridStateDetails: dataGridStateDetails); + dataCell: dataCell, + isDirty: isDirty, + dataGridStateDetails: dataGridStateDetails, + ); @override void updateRenderObject(BuildContext context, RenderGridCell renderObject) { @@ -1576,14 +1749,14 @@ class RenderGridCell extends RenderBox with RenderObjectWithChildMixin implements MouseTrackerAnnotation { /// Creates a [RenderGridCell] for `SfDataGrid`. - RenderGridCell( - {RenderBox? child, - required DataCellBase dataCell, - required bool isDirty, - required DataGridStateDetails dataGridStateDetails}) - : _dataCell = dataCell, - _isDirty = isDirty, - _dataGridStateDetails = dataGridStateDetails { + RenderGridCell({ + RenderBox? child, + required DataCellBase dataCell, + required bool isDirty, + required DataGridStateDetails dataGridStateDetails, + }) : _dataCell = dataCell, + _isDirty = isDirty, + _dataGridStateDetails = dataGridStateDetails { this.child = child; } @@ -1631,25 +1804,41 @@ class RenderGridCell extends RenderBox final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); final double lineWidth = dataRow.getColumnWidth( - dataCell.columnIndex, dataCell.columnIndex + dataCell.columnSpan); + dataCell.columnIndex, + dataCell.columnIndex + dataCell.columnSpan, + ); final double lineHeight = dataRow.getRowHeight( - dataCell.rowIndex - dataCell.rowSpan, dataCell.rowIndex); + dataCell.rowIndex - dataCell.rowSpan, + dataCell.rowIndex, + ); if (dataRow.rowType == RowType.stackedHeaderRow) { _columnRect = _getStackedHeaderCellRect( - dataGridConfiguration, lineWidth, lineHeight); + dataGridConfiguration, + lineWidth, + lineHeight, + ); } else if ((dataRow.tableSummaryRow != null && (dataRow.rowType == RowType.tableSummaryRow || dataRow.rowType == RowType.tableSummaryCoveredRow)) || dataRow.rowType == RowType.captionSummaryCoveredRow) { _columnRect = _getTableSummaryCellRect( - dataGridConfiguration, lineWidth, lineHeight); + dataGridConfiguration, + lineWidth, + lineHeight, + ); } else { - final VisibleLineInfo? lineInfo = - dataRow.getColumnVisibleLineInfo(dataCell.columnIndex); + final VisibleLineInfo? lineInfo = dataRow.getColumnVisibleLineInfo( + dataCell.columnIndex, + ); final double origin = lineInfo != null ? lineInfo.origin : 0.0; _columnRect = _getCellRect( - dataGridConfiguration, lineInfo, origin, lineWidth, lineHeight); + dataGridConfiguration, + lineInfo, + origin, + lineWidth, + lineHeight, + ); } } else { _columnRect = Rect.zero; @@ -1659,11 +1848,12 @@ class RenderGridCell extends RenderBox } Rect? _getCellRect( - DataGridConfiguration dataGridConfiguration, - VisibleLineInfo? lineInfo, - double origin, - double lineWidth, - double lineHeight) { + DataGridConfiguration dataGridConfiguration, + VisibleLineInfo? lineInfo, + double origin, + double lineWidth, + double lineHeight, + ) { final DataRowBase dataRow = dataCell.dataRow!; final int rowIndex = dataCell.rowIndex; final int rowSpan = dataCell.rowSpan; @@ -1683,27 +1873,36 @@ class RenderGridCell extends RenderBox if (dataCell.cellType != CellType.stackedHeaderCell) { // Clipping the column when frozen column applied - _cellClipRect = - _getCellClipRect(dataGridConfiguration, lineInfo, lineHeight); + _cellClipRect = _getCellClipRect( + dataGridConfiguration, + lineInfo, + lineHeight, + ); } - final double topPosition = (rowSpan > 0) - ? -dataRow.getRowHeight(rowIndex - rowSpan, rowIndex - 1) - : 0.0; + final double topPosition = + (rowSpan > 0) + ? -dataRow.getRowHeight(rowIndex - rowSpan, rowIndex - 1) + : 0.0; _columnRect = Rect.fromLTWH(origin, topPosition, lineWidth, lineHeight); return _columnRect; } - double _getCellClippedOrigin(DataGridConfiguration dataGridConfiguration, - int startIndex, int endIndex) { + double _getCellClippedOrigin( + DataGridConfiguration dataGridConfiguration, + int startIndex, + int endIndex, + ) { double origin = 0.0; final ScrollAxisBase scrollColumns = dataGridConfiguration.container.scrollColumns; bool updateOrigin(int index, bool isRTL) { - final VisibleLineInfo? newLine = - scrollColumns.getVisibleLineAtLineIndex(index, isRightToLeft: true); + final VisibleLineInfo? newLine = scrollColumns.getVisibleLineAtLineIndex( + index, + isRightToLeft: true, + ); if (newLine != null) { // Set origin to zero when scrolling is disabled in RTL. @@ -1716,15 +1915,19 @@ class RenderGridCell extends RenderBox if (!newLine.isFooter) { // Adjust origin if the line is clipped. if (newLine.isClipped) { - origin += isRTL && newLine.isClippedCorner - ? newLine.clippedSize - : newLine.size - newLine.clippedCorner; + origin += + isRTL && newLine.isClippedCorner + ? newLine.clippedSize + : newLine.size - newLine.clippedCorner; } return false; } } else { - origin += - dataCell.dataRow!.getColumnWidth(index, index, lineNull: true); + origin += dataCell.dataRow!.getColumnWidth( + index, + index, + lineNull: true, + ); } return true; } @@ -1745,20 +1948,25 @@ class RenderGridCell extends RenderBox return origin; } - double _getCellClippedSize(DataGridConfiguration dataGridConfiguration, - int startIndex, int endIndex) { + double _getCellClippedSize( + DataGridConfiguration dataGridConfiguration, + int startIndex, + int endIndex, + ) { double clippedSize = 0; final bool isRTL = dataGridConfiguration.textDirection == TextDirection.rtl; for (int index = startIndex; index <= endIndex; index++) { final VisibleLineInfo? newLine = dataGridConfiguration - .container.scrollColumns + .container + .scrollColumns .getVisibleLineAtLineIndex(index, isRightToLeft: isRTL); if (newLine != null) { - clippedSize += isRTL && newLine.isClippedCorner - ? newLine.clippedCornerExtent - : newLine.clippedSize; + clippedSize += + isRTL && newLine.isClippedCorner + ? newLine.clippedCornerExtent + : newLine.clippedSize; } } return clippedSize; @@ -1773,27 +1981,42 @@ class RenderGridCell extends RenderBox if (!line.isHeader && dataCell.columnSpan > 0) { final int endIndex = dataCell.columnIndex + dataCell.columnSpan; final double lineSize = _getCellClippedSize( - dataGridConfiguration, line.lineIndex, endIndex); + dataGridConfiguration, + line.lineIndex, + endIndex, + ); final double clipOrigin = _getCellClippedOrigin( - dataGridConfiguration, dataCell.columnIndex, endIndex); + dataGridConfiguration, + dataCell.columnIndex, + endIndex, + ); _cellClipRect = Rect.fromLTWH(clipOrigin, 0.0, lineSize, lineHeight); } else { - _cellClipRect = - _getCellClipRect(dataGridConfiguration, line, lineHeight); + _cellClipRect = _getCellClipRect( + dataGridConfiguration, + line, + lineHeight, + ); } } } - Rect _getTableSummaryCellRect(DataGridConfiguration dataGridConfiguration, - double lineWidth, double lineHeight) { + Rect _getTableSummaryCellRect( + DataGridConfiguration dataGridConfiguration, + double lineWidth, + double lineHeight, + ) { if (dataCell.dataRow!.rowType == RowType.tableSummaryCoveredRow) { - lineWidth = min(dataGridConfiguration.viewWidth, - dataGridConfiguration.container.extentWidth); + lineWidth = min( + dataGridConfiguration.viewWidth, + dataGridConfiguration.container.extentWidth, + ); double offset = dataGridConfiguration.container.horizontalOffset; if (dataGridConfiguration.textDirection == TextDirection.rtl && dataGridConfiguration.viewWidth > dataGridConfiguration.container.extentWidth) { - offset += dataGridConfiguration.viewWidth - + offset += + dataGridConfiguration.viewWidth - dataGridConfiguration.container.extentWidth; } return Rect.fromLTWH(offset, 0.0, lineWidth, lineHeight); @@ -1814,17 +2037,22 @@ class RenderGridCell extends RenderBox if (line == null) { // Gets the origin for the first visible line in the spanned cell and // calculates the clipped size. - for (int index = dataCell.columnIndex; - index <= dataCell.columnIndex + dataCell.columnSpan; - index++) { + for ( + int index = dataCell.columnIndex; + index <= dataCell.columnIndex + dataCell.columnSpan; + index++ + ) { final VisibleLineInfo? newLine = getVisibleLineInfo(index); if (newLine != null) { setOrigin(newLine); _setClipRect(newLine, lineHeight); break; } else { - clippedWidth += - dataCell.dataRow!.getColumnWidth(index, index, lineNull: true); + clippedWidth += dataCell.dataRow!.getColumnWidth( + index, + index, + lineNull: true, + ); } } } else { @@ -1834,16 +2062,20 @@ class RenderGridCell extends RenderBox origin += dataGridConfiguration.container.horizontalOffset; - origin = dataGridConfiguration.textDirection == TextDirection.rtl - ? (origin + clippedWidth) - lineWidth - : origin - clippedWidth; + origin = + dataGridConfiguration.textDirection == TextDirection.rtl + ? (origin + clippedWidth) - lineWidth + : origin - clippedWidth; return Rect.fromLTWH(origin, 0.0, lineWidth, lineHeight); } } - Rect? _getStackedHeaderCellRect(DataGridConfiguration dataGridConfiguration, - double lineWidth, double lineHeight) { + Rect? _getStackedHeaderCellRect( + DataGridConfiguration dataGridConfiguration, + double lineWidth, + double lineHeight, + ) { final DataRowBase dataRow = dataCell.dataRow!; final int cellStartIndex = dataCell.columnIndex; final int columnSpan = dataCell.columnSpan; @@ -1863,16 +2095,21 @@ class RenderGridCell extends RenderBox if (frozenColumns > cellStartIndex && frozenColumns <= cellEndIndex) { if (dataGridConfiguration.textDirection == TextDirection.ltr) { - for (int index = cellEndIndex; - index >= frozenColumnsCount - 1; - index--) { + for ( + int index = cellEndIndex; + index >= frozenColumnsCount - 1; + index-- + ) { lineInfo = scrollColumns.getVisibleLineAtLineIndex(index); if (lineInfo != null) { - final VisibleLineInfo? startLineInfo = - scrollColumns.getVisibleLineAtLineIndex(cellStartIndex); + final VisibleLineInfo? startLineInfo = scrollColumns + .getVisibleLineAtLineIndex(cellStartIndex); origin = startLineInfo?.origin; lineWidth = _getClippedWidth( - dataGridConfiguration, cellStartIndex, cellEndIndex); + dataGridConfiguration, + cellStartIndex, + cellEndIndex, + ); break; } } @@ -1882,7 +2119,10 @@ class RenderGridCell extends RenderBox if (lineInfo != null) { origin = lineInfo.origin < 0 ? 0.0 : lineInfo.origin; lineWidth = _getClippedWidth( - dataGridConfiguration, cellStartIndex, cellEndIndex); + dataGridConfiguration, + cellStartIndex, + cellEndIndex, + ); if (lineInfo.origin < 0) { lineWidth += lineInfo.origin; } @@ -1899,13 +2139,18 @@ class RenderGridCell extends RenderBox if (lineInfo != null) { if (index == columnsLength - footerFrozenColumns) { origin = lineInfo.origin; - lineWidth = - dataRow.getColumnWidth(cellStartIndex + span, cellEndIndex); + lineWidth = dataRow.getColumnWidth( + cellStartIndex + span, + cellEndIndex, + ); break; } else { origin = lineInfo.clippedOrigin; lineWidth = _getClippedWidth( - dataGridConfiguration, cellStartIndex, cellEndIndex); + dataGridConfiguration, + cellStartIndex, + cellEndIndex, + ); break; } } @@ -1916,18 +2161,23 @@ class RenderGridCell extends RenderBox for (int index = cellStartIndex; index <= cellEndIndex; index++) { lineInfo = scrollColumns.getVisibleLineAtLineIndex(index); if (lineInfo != null) { - final VisibleLineInfo? line = - scrollColumns.getVisibleLineAtLineIndex(cellEndIndex); + final VisibleLineInfo? line = scrollColumns + .getVisibleLineAtLineIndex(cellEndIndex); if (line != null) { if (index == columnsLength - footerFrozenColumnsCount) { origin = line.origin; - lineWidth = - dataRow.getColumnWidth(cellStartIndex + span, cellEndIndex); + lineWidth = dataRow.getColumnWidth( + cellStartIndex + span, + cellEndIndex, + ); break; } else { origin = line.clippedOrigin - lineInfo.scrollOffset; lineWidth = _getClippedWidth( - dataGridConfiguration, cellStartIndex, cellEndIndex); + dataGridConfiguration, + cellStartIndex, + cellEndIndex, + ); break; } } @@ -1941,12 +2191,18 @@ class RenderGridCell extends RenderBox for (int index = cellStartIndex; index <= cellEndIndex; index++) { lineInfo = dataRow.getColumnVisibleLineInfo(index); if (lineInfo != null) { - origin = lineInfo.origin + + origin = + lineInfo.origin + dataRow.getColumnWidth(index, index + span) - dataRow.getColumnWidth(cellStartIndex, cellEndIndex); - _cellClipRect = _getSpannedCellClipRect(dataGridConfiguration, - dataRow, dataCell, lineHeight, lineWidth); + _cellClipRect = _getSpannedCellClipRect( + dataGridConfiguration, + dataRow, + dataCell, + lineHeight, + lineWidth, + ); break; } span -= 1; @@ -1955,12 +2211,18 @@ class RenderGridCell extends RenderBox for (int index = cellEndIndex; index >= cellStartIndex; index--) { lineInfo = dataRow.getColumnVisibleLineInfo(index); if (lineInfo != null) { - origin = lineInfo.origin + + origin = + lineInfo.origin + dataRow.getColumnWidth(index - span, index) - dataRow.getColumnWidth(cellStartIndex, cellEndIndex); - _cellClipRect = _getSpannedCellClipRect(dataGridConfiguration, - dataRow, dataCell, lineHeight, lineWidth); + _cellClipRect = _getSpannedCellClipRect( + dataGridConfiguration, + dataRow, + dataCell, + lineHeight, + lineWidth, + ); break; } span -= 1; @@ -1971,28 +2233,37 @@ class RenderGridCell extends RenderBox if (lineInfo != null) { // If resizing a column to 0 width the origin value is return null // So We need to set origin value as 0.0 - columnRect = _getCellRect(dataGridConfiguration, lineInfo, origin ?? 0.0, - lineWidth, lineHeight); + columnRect = _getCellRect( + dataGridConfiguration, + lineInfo, + origin ?? 0.0, + lineWidth, + lineHeight, + ); } return columnRect; } - double _getClippedWidth(DataGridConfiguration dataGridConfiguration, - int startIndex, int endIndex) { + double _getClippedWidth( + DataGridConfiguration dataGridConfiguration, + int startIndex, + int endIndex, + ) { double clippedWidth = 0; for (int index = startIndex; index <= endIndex; index++) { - final VisibleLineInfo? newline = - dataCell.dataRow!.getColumnVisibleLineInfo(index); + final VisibleLineInfo? newline = dataCell.dataRow! + .getColumnVisibleLineInfo(index); if (newline != null) { if (dataGridConfiguration.textDirection == TextDirection.ltr) { clippedWidth += newline.isClipped ? newline.clippedSize : newline.size; } else { - clippedWidth += newline.isClipped - ? newline.clippedCornerExtent > 0 - ? newline.clippedCornerExtent - : newline.clippedSize - : newline.size; + clippedWidth += + newline.isClipped + ? newline.clippedCornerExtent > 0 + ? newline.clippedCornerExtent + : newline.clippedSize + : newline.size; } } } @@ -2028,10 +2299,12 @@ class RenderGridCell extends RenderBox final BoxParentData childParentData = child!.parentData! as BoxParentData; final bool isHit = result.addWithPaintOffset( - offset: childParentData.offset, - position: position, - hitTest: (BoxHitTestResult result, Offset transformed) => - child!.hitTest(result, position: transformed)); + offset: childParentData.offset, + position: position, + hitTest: + (BoxHitTestResult result, Offset transformed) => + child!.hitTest(result, position: transformed), + ); if (isHit) { return true; } else { @@ -2047,14 +2320,18 @@ class RenderGridCell extends RenderBox @override void performLayout() { - size = constraints - .constrain(Size(constraints.maxWidth, constraints.maxHeight)); + size = constraints.constrain( + Size(constraints.maxWidth, constraints.maxHeight), + ); if (child != null) { child!.layout( - BoxConstraints.tightFor( - width: constraints.maxWidth, height: constraints.maxHeight), - parentUsesSize: true); + BoxConstraints.tightFor( + width: constraints.maxWidth, + height: constraints.maxHeight, + ), + parentUsesSize: true, + ); } } @@ -2074,7 +2351,8 @@ class RenderGridCell extends RenderBox MouseCursor get cursor { final DataGridConfiguration dataGridConfiguration = _dataGridStateDetails(); return dataGridConfiguration - .columnResizeController.canSwitchResizeColumnCursor + .columnResizeController + .canSwitchResizeColumnCursor ? SystemMouseCursors.resizeColumn : SystemMouseCursors.basic; } @@ -2122,8 +2400,12 @@ class RenderGridCell extends RenderBox _dataGridStateDetails(); dataGridConfiguration.gridPaint!.color = dataGridConfiguration.dataGridThemeHelper!.headerHoverColor!; - final Rect cellRect = - Rect.fromLTRB(0, 0, constraints.maxWidth, constraints.maxHeight); + final Rect cellRect = Rect.fromLTRB( + 0, + 0, + constraints.maxWidth, + constraints.maxHeight, + ); context.canvas.drawRect(cellRect, dataGridConfiguration.gridPaint!); } @@ -2134,8 +2416,11 @@ class RenderGridCell extends RenderBox bool get validForMouseTracker => dataCell.cellType == CellType.headerCell; } -Rect? _getCellClipRect(DataGridConfiguration dataGridConfiguration, - VisibleLineInfo? lineInfo, double rowHeight) { +Rect? _getCellClipRect( + DataGridConfiguration dataGridConfiguration, + VisibleLineInfo? lineInfo, + double rowHeight, +) { // FLUT-1971 Need to check whether the lineInfo is null or not. Because it // will be null when load empty to the columns collection. if (lineInfo == null) { @@ -2144,9 +2429,12 @@ Rect? _getCellClipRect(DataGridConfiguration dataGridConfiguration, if (lineInfo.isClippedBody && lineInfo.isClippedOrigin && lineInfo.isClippedCorner) { - final double left = dataGridConfiguration.textDirection == TextDirection.ltr - ? lineInfo.size - lineInfo.clippedSize - lineInfo.clippedCornerExtent - : lineInfo.clippedSize; + final double left = + dataGridConfiguration.textDirection == TextDirection.ltr + ? lineInfo.size - + lineInfo.clippedSize - + lineInfo.clippedCornerExtent + : lineInfo.clippedSize; final double right = dataGridConfiguration.textDirection == TextDirection.ltr ? lineInfo.clippedSize @@ -2154,9 +2442,12 @@ Rect? _getCellClipRect(DataGridConfiguration dataGridConfiguration, return Rect.fromLTWH(left, 0.0, right, rowHeight); } else if (lineInfo.isClippedBody && lineInfo.isClippedOrigin) { - final double left = dataGridConfiguration.textDirection == TextDirection.ltr - ? lineInfo.size - lineInfo.clippedSize - lineInfo.clippedCornerExtent - : 0.0; + final double left = + dataGridConfiguration.textDirection == TextDirection.ltr + ? lineInfo.size - + lineInfo.clippedSize - + lineInfo.clippedCornerExtent + : 0.0; final double right = dataGridConfiguration.textDirection == TextDirection.ltr ? lineInfo.size @@ -2164,9 +2455,10 @@ Rect? _getCellClipRect(DataGridConfiguration dataGridConfiguration, return Rect.fromLTWH(left, 0.0, right, rowHeight); } else if (lineInfo.isClippedBody && lineInfo.isClippedCorner) { - final double left = dataGridConfiguration.textDirection == TextDirection.ltr - ? 0.0 - : lineInfo.size - (lineInfo.size - lineInfo.clippedSize); + final double left = + dataGridConfiguration.textDirection == TextDirection.ltr + ? 0.0 + : lineInfo.size - (lineInfo.size - lineInfo.clippedSize); final double right = dataGridConfiguration.textDirection == TextDirection.ltr ? lineInfo.clippedSize @@ -2179,19 +2471,24 @@ Rect? _getCellClipRect(DataGridConfiguration dataGridConfiguration, } Rect? _getSpannedCellClipRect( - DataGridConfiguration dataGridConfiguration, - DataRowBase dataRow, - DataCellBase dataCell, - double cellHeight, - double cellWidth) { + DataGridConfiguration dataGridConfiguration, + DataRowBase dataRow, + DataCellBase dataCell, + double cellHeight, + double cellWidth, +) { Rect? clipRect; int firstVisibleStackedColumnIndex = dataCell.columnIndex; double lastCellClippedSize = 0.0; bool isLastCellClippedCorner = false; bool isLastCellClippedBody = false; - double getClippedWidth(DataCellBase dataCell, DataRowBase dataRow, - {bool columnsNotInViewWidth = false, bool allCellsClippedWidth = false}) { + double getClippedWidth( + DataCellBase dataCell, + DataRowBase dataRow, { + bool columnsNotInViewWidth = false, + bool allCellsClippedWidth = false, + }) { final int startIndex = dataCell.columnIndex; final int endIndex = dataCell.columnIndex + dataCell.columnSpan; double clippedWidth = 0; @@ -2199,8 +2496,8 @@ Rect? _getSpannedCellClipRect( final VisibleLineInfo? newline = dataRow.getColumnVisibleLineInfo(index); if (columnsNotInViewWidth) { if (newline == null) { - clippedWidth += - dataGridConfiguration.container.scrollColumns.getLineSize(index); + clippedWidth += dataGridConfiguration.container.scrollColumns + .getLineSize(index); } else { firstVisibleStackedColumnIndex = index; break; @@ -2212,11 +2509,12 @@ Rect? _getSpannedCellClipRect( clippedWidth += newline.isClipped ? newline.clippedSize : newline.size; } else { - clippedWidth += newline.isClipped - ? newline.clippedCornerExtent > 0 - ? newline.clippedCornerExtent - : newline.clippedSize - : newline.size; + clippedWidth += + newline.isClipped + ? newline.clippedCornerExtent > 0 + ? newline.clippedCornerExtent + : newline.clippedSize + : newline.size; } lastCellClippedSize = newline.clippedSize; isLastCellClippedCorner = newline.isClippedCorner; @@ -2233,16 +2531,24 @@ Rect? _getSpannedCellClipRect( } if (dataCell.renderer != null) { - final double columnsNotInViewWidth = - getClippedWidth(dataCell, dataRow, columnsNotInViewWidth: true); - final double clippedWidth = - getClippedWidth(dataCell, dataRow, allCellsClippedWidth: true); - final VisibleLineInfo? visibleLineInfo = - dataRow.getColumnVisibleLineInfo(firstVisibleStackedColumnIndex); + final double columnsNotInViewWidth = getClippedWidth( + dataCell, + dataRow, + columnsNotInViewWidth: true, + ); + final double clippedWidth = getClippedWidth( + dataCell, + dataRow, + allCellsClippedWidth: true, + ); + final VisibleLineInfo? visibleLineInfo = dataRow.getColumnVisibleLineInfo( + firstVisibleStackedColumnIndex, + ); if (visibleLineInfo != null) { if (visibleLineInfo.isClippedOrigin && visibleLineInfo.isClippedCorner) { - final double clippedOrigin = columnsNotInViewWidth + + final double clippedOrigin = + columnsNotInViewWidth + visibleLineInfo.size - (visibleLineInfo.clippedSize + visibleLineInfo.clippedCornerExtent); @@ -2257,7 +2563,8 @@ Rect? _getSpannedCellClipRect( clipRect = Rect.fromLTWH(left, 0.0, right, cellHeight); } else if (visibleLineInfo.isClippedOrigin) { - final double clippedOriginLTR = columnsNotInViewWidth + + final double clippedOriginLTR = + columnsNotInViewWidth + visibleLineInfo.size - visibleLineInfo.clippedSize; final double clippedOriginRTL = @@ -2281,8 +2588,8 @@ Rect? _getSpannedCellClipRect( dataGridConfiguration.textDirection == TextDirection.ltr ? columnsNotInViewWidth : dataCell.columnIndex < firstVisibleStackedColumnIndex - ? 0.0 - : cellWidth - clippedWidth; + ? 0.0 + : cellWidth - clippedWidth; final double right = dataGridConfiguration.textDirection == TextDirection.ltr ? clippedWidth @@ -2293,13 +2600,15 @@ Rect? _getSpannedCellClipRect( if (clippedWidth < cellWidth) { double left; if (dataCell.columnIndex < firstVisibleStackedColumnIndex) { - left = dataGridConfiguration.textDirection == TextDirection.ltr - ? cellWidth - clippedWidth - : 0.0; + left = + dataGridConfiguration.textDirection == TextDirection.ltr + ? cellWidth - clippedWidth + : 0.0; } else { - left = dataGridConfiguration.textDirection == TextDirection.ltr - ? 0.0 - : cellWidth - clippedWidth; + left = + dataGridConfiguration.textDirection == TextDirection.ltr + ? 0.0 + : cellWidth - clippedWidth; } clipRect = Rect.fromLTWH(left, 0.0, clippedWidth, cellHeight); diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/scrollview_widget.dart b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/scrollview_widget.dart index f2ca21614..43cd610aa 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/scrollview_widget.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datagrid_widget/widgets/scrollview_widget.dart @@ -24,11 +24,12 @@ import 'rendering_widget.dart'; /// A [StatefulWidget] that build all the data grid views from the widget level. class ScrollViewWidget extends StatefulWidget { /// Creates a [ScrollViewWidget] for the [SfDataGrid]. - const ScrollViewWidget( - {super.key, - required this.width, - required this.height, - required this.dataGridStateDetails}); + const ScrollViewWidget({ + super.key, + required this.width, + required this.height, + required this.dataGridStateDetails, + }); /// The parent width of the datagrid. final double width; @@ -65,8 +66,9 @@ class _ScrollViewWidgetState extends State { _height = widget.height; _width = widget.width; - dataGridConfiguration.rowSelectionManager - .addListener(_handleSelectionController); + dataGridConfiguration.rowSelectionManager.addListener( + _handleSelectionController, + ); if (_dataGridFocusNode == null) { // [FocusNode.onKey] callback is not firing on key navigation after flutter @@ -122,7 +124,8 @@ class _ScrollViewWidgetState extends State { _container.resetSwipeOffset(); _dataGridConfiguration.scrollingState = ScrollDirection.forward; if (!_dataGridConfiguration - .columnResizeController.isResizeIndicatorVisible) { + .columnResizeController + .isResizeIndicatorVisible) { _isScrolling = true; } _container.isDirty = true; @@ -174,8 +177,9 @@ class _ScrollViewWidgetState extends State { void _ensureItems(bool needToRefresh) { final VisibleLinesCollection visibleRows = _container.scrollRows.getVisibleLines(); - final VisibleLinesCollection visibleColumns = - grid_helper.getVisibleLines(widget.dataGridStateDetails()); + final VisibleLinesCollection visibleColumns = grid_helper.getVisibleLines( + widget.dataGridStateDetails(), + ); if (_container.isGridLoaded && visibleColumns.isNotEmpty) { rowGenerator.ensureRows(visibleRows, visibleColumns); @@ -188,8 +192,12 @@ class _ScrollViewWidgetState extends State { } } - Widget _buildScrollView(double extentWidth, double scrollViewHeight, - double extentHeight, Size containerSize) { + Widget _buildScrollView( + double extentWidth, + double scrollViewHeight, + double extentHeight, + Size containerSize, + ) { final DataGridConfiguration dataGridConfiguration = _dataGridConfiguration; // Issue: @@ -202,7 +210,9 @@ class _ScrollViewWidgetState extends State { // We have fixed it by handling only to the respective scroll direction // based on the scrollbar. bool handleNotificationPredicate( - ScrollNotification notification, Axis direction) { + ScrollNotification notification, + Axis direction, + ) { // Issue: // FLUT-6320 - Horizontal scrollbar is showing when typing the text in // TextField widget more than cell width in editing. @@ -233,56 +243,66 @@ class _ScrollViewWidgetState extends State { thickness: dataGridConfiguration.showVerticalScrollbar ? null : 0, controller: _verticalController, thumbVisibility: dataGridConfiguration.isScrollbarAlwaysShown, - notificationPredicate: (ScrollNotification notification) => - handleNotificationPredicate(notification, Axis.vertical), + notificationPredicate: + (ScrollNotification notification) => + handleNotificationPredicate(notification, Axis.vertical), child: Scrollbar( thickness: dataGridConfiguration.showHorizontalScrollbar ? null : 0, controller: _horizontalController, thumbVisibility: dataGridConfiguration.isScrollbarAlwaysShown, - notificationPredicate: (ScrollNotification notification) => - handleNotificationPredicate(notification, Axis.horizontal), + notificationPredicate: + (ScrollNotification notification) => + handleNotificationPredicate(notification, Axis.horizontal), child: SingleChildScrollView( controller: _verticalController, - physics: dataGridConfiguration.isSwipingApplied - ? const NeverScrollableScrollPhysics() - : dataGridConfiguration.verticalScrollPhysics, + physics: + dataGridConfiguration.isSwipingApplied + ? const NeverScrollableScrollPhysics() + : dataGridConfiguration.verticalScrollPhysics, child: ConstrainedBox( // FLUT-6553-BoxConstraints has a negative minimum height exception has been thrown. // we need to set height as 0 if it's negative value constraints: BoxConstraints( - minHeight: max(0, min(scrollViewHeight, extentHeight))), + minHeight: max(0, min(scrollViewHeight, extentHeight)), + ), child: SingleChildScrollView( controller: _horizontalController, scrollDirection: Axis.horizontal, - physics: dataGridConfiguration.isSwipingApplied - ? const NeverScrollableScrollPhysics() - : dataGridConfiguration.horizontalScrollPhysics, + physics: + dataGridConfiguration.isSwipingApplied + ? const NeverScrollableScrollPhysics() + : dataGridConfiguration.horizontalScrollPhysics, child: ConstrainedBox( // FLUT-6553-BoxConstraints has a negative minimum width exception has been thrown. // we need to set width as 0 if it's negative value - constraints: - BoxConstraints(minWidth: max(0, min(_width, extentWidth))), - child: _canShowPlaceHolder() - ? SizedBox( - width: extentWidth, - child: Transform.translate( - offset: Offset(_container.horizontalOffset, 0), - child: Align( - alignment: Alignment.topLeft, - child: SizedBox( + constraints: BoxConstraints( + minWidth: max(0, min(_width, extentWidth)), + ), + child: + _canShowPlaceHolder() + ? SizedBox( + width: extentWidth, + child: Transform.translate( + offset: Offset(_container.horizontalOffset, 0), + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( height: scrollViewHeight, width: min(_width, extentWidth), - child: dataGridConfiguration.placeholder), + child: dataGridConfiguration.placeholder, + ), + ), + ), + ) + : _VisualContainer( + key: const ValueKey( + 'SfDataGrid-VisualContainer', ), - )) - : _VisualContainer( - key: const ValueKey( - 'SfDataGrid-VisualContainer'), - isDirty: _container.isDirty, - rowGenerator: rowGenerator, - containerSize: containerSize, - dataGridStateDetails: widget.dataGridStateDetails, - ), + isDirty: _container.isDirty, + rowGenerator: rowGenerator, + containerSize: containerSize, + dataGridStateDetails: widget.dataGridStateDetails, + ), ), ), ), @@ -306,25 +326,32 @@ class _ScrollViewWidgetState extends State { void _addScrollView(List children) { final DataGridConfiguration dataGridConfiguration = _dataGridConfiguration; final double extentWidth = _container.extentWidth; - final double headerRowsHeight = _container.scrollRows - .rangeToRegionPoints( - 0, grid_helper.getHeaderIndex(dataGridConfiguration), true)[1] - .length; + final double headerRowsHeight = + _container.scrollRows + .rangeToRegionPoints( + 0, + grid_helper.getHeaderIndex(dataGridConfiguration), + true, + )[1] + .length; final double extentHeight = _container.extentHeight - headerRowsHeight; final double scrollViewHeight = _height - headerRowsHeight; final Size containerSize = Size( - _canDisableHorizontalScrolling(dataGridConfiguration) - ? _width - : max(_width, extentWidth), - _canDisableVerticalScrolling(dataGridConfiguration) - ? scrollViewHeight - : (extentHeight > scrollViewHeight - ? extentHeight - : scrollViewHeight)); + _canDisableHorizontalScrolling(dataGridConfiguration) + ? _width + : max(_width, extentWidth), + _canDisableVerticalScrolling(dataGridConfiguration) + ? scrollViewHeight + : (extentHeight > scrollViewHeight ? extentHeight : scrollViewHeight), + ); final Widget scrollView = _buildScrollView( - extentWidth, scrollViewHeight, extentHeight, containerSize); + extentWidth, + scrollViewHeight, + extentHeight, + containerSize, + ); final Positioned wrapScrollView = Positioned.fill( top: headerRowsHeight, @@ -356,33 +383,45 @@ class _ScrollViewWidgetState extends State { // Adds stacked header rows if (dataGridConfiguration.stackedHeaderRows.isNotEmpty) { - headerRows.addAll(rowGenerator.items - .where((DataRowBase row) => - row.rowIndex >= 0 && - row.rowRegion == RowRegion.header && - row.rowType == RowType.stackedHeaderRow) - .map((DataRowBase dataRow) => _HeaderCellsWidget( + headerRows.addAll( + rowGenerator.items + .where( + (DataRowBase row) => + row.rowIndex >= 0 && + row.rowRegion == RowRegion.header && + row.rowType == RowType.stackedHeaderRow, + ) + .map( + (DataRowBase dataRow) => _HeaderCellsWidget( key: dataRow.key!, dataRow: dataRow, isDirty: _container.isDirty || dataRow.isDirty, dataGridStateDetails: widget.dataGridStateDetails, - )) - .toList(growable: false)); + ), + ) + .toList(growable: false), + ); } // Adds column header row - headerRows.addAll(rowGenerator.items - .where((DataRowBase row) => - row.rowIndex >= 0 && - row.rowRegion == RowRegion.header && - row.rowType == RowType.headerRow) - .map((DataRowBase dataRow) => _HeaderCellsWidget( + headerRows.addAll( + rowGenerator.items + .where( + (DataRowBase row) => + row.rowIndex >= 0 && + row.rowRegion == RowRegion.header && + row.rowType == RowType.headerRow, + ) + .map( + (DataRowBase dataRow) => _HeaderCellsWidget( key: dataRow.key!, dataRow: dataRow, isDirty: _container.isDirty || dataRow.isDirty, dataGridStateDetails: widget.dataGridStateDetails, - )) - .toList(growable: false)); + ), + ) + .toList(growable: false), + ); return headerRows; } @@ -423,18 +462,19 @@ class _ScrollViewWidgetState extends State { if (rowGenerator.items.isNotEmpty) { final List headerRows = buildHeaderRows(); for (int i = 0; i < headerRows.length; i++) { - final VisibleLineInfo? lineInfo = - _container.scrollRows.getVisibleLineAtLineIndex(i); + final VisibleLineInfo? lineInfo = _container.scrollRows + .getVisibleLineAtLineIndex(i); final Positioned header = Positioned.directional( - textDirection: dataGridConfiguration.textDirection, - start: getStartX(), - top: lineInfo?.origin, - height: lineInfo?.size, - // FLUT-1971 Changed the header row widget as extendwidth instead of - // device width to resolved the issue of apply sorting to the - // invisible columns. - width: containerWidth, - child: headerRows[i]); + textDirection: dataGridConfiguration.textDirection, + start: getStartX(), + top: lineInfo?.origin, + height: lineInfo?.size, + // FLUT-1971 Changed the header row widget as extendwidth instead of + // device width to resolved the issue of apply sorting to the + // invisible columns. + width: containerWidth, + child: headerRows[i], + ); children.add(header); } } @@ -456,8 +496,10 @@ class _ScrollViewWidgetState extends State { } if (rowIndex > 0) { - top = columnResizeController.resizingDataCell!.dataRow! - .getRowHeight(0, rowIndex - 1); + top = columnResizeController.resizingDataCell!.dataRow!.getRowHeight( + 0, + rowIndex - 1, + ); } final Widget indicator = Positioned( @@ -466,14 +508,20 @@ class _ScrollViewWidgetState extends State { // Ignores the `hitTest` of the indicator to resolved the update of the // cursor visibility when hovering the column resizing indicator. child: IgnorePointer( - child: _dataGridConfiguration.isDesktop - ? Container( + child: + _dataGridConfiguration.isDesktop + ? Container( width: dataGridThemeHelper!.columnResizeIndicatorStrokeWidth, height: _container.extentHeight - top, - color: dataGridThemeHelper.columnResizeIndicatorColor) - : _getResizingCursor( - _dataGridConfiguration, dataGridThemeHelper!, top)), + color: dataGridThemeHelper.columnResizeIndicatorColor, + ) + : _getResizingCursor( + _dataGridConfiguration, + dataGridThemeHelper!, + top, + ), + ), ); children.add(indicator); } @@ -494,8 +542,10 @@ class _ScrollViewWidgetState extends State { (_verticalController!.offset >= _verticalController!.position.maxScrollExtent) && !_isLoadMoreViewLoaded) { - final Widget? loadMoreView = - dataGridConfiguration.loadMoreViewBuilder!(context, loadMoreRows); + final Widget? loadMoreView = dataGridConfiguration.loadMoreViewBuilder!( + context, + loadMoreRows, + ); if (loadMoreView != null) { final Alignment loadMoreAlignment = @@ -503,14 +553,14 @@ class _ScrollViewWidgetState extends State { ? Alignment.bottomLeft : Alignment.bottomRight; - children.add(Positioned( + children.add( + Positioned( top: 0.0, width: _width, height: _height, - child: Align( - alignment: loadMoreAlignment, - child: loadMoreView, - ))); + child: Align(alignment: loadMoreAlignment, child: loadMoreView), + ), + ); } } } @@ -529,8 +579,9 @@ class _ScrollViewWidgetState extends State { final Color frozenLineColorWithoutOpacity = dataGridThemeHelper.frozenPaneLineColor!; - final Color frozenLineColorWithOpacity = - dataGridThemeHelper.frozenPaneLineColor!.withValues(alpha: 0.14); + final Color frozenLineColorWithOpacity = dataGridThemeHelper + .frozenPaneLineColor! + .withValues(alpha: 0.14); void drawElevation({ EdgeInsets? margin, @@ -544,43 +595,53 @@ class _ScrollViewWidgetState extends State { required double spreadRadiusValue, }) { final Widget elevationLine = ClipRect( - child: Container( - width: axis == Axis.vertical ? 1 : 0, - height: axis == Axis.horizontal ? 1 : 0, - margin: margin, - decoration: BoxDecoration( - color: const Color(0xFF000000), - boxShadow: [ - BoxShadow( - color: frozenLineColor, - spreadRadius: spreadRadiusValue, - blurRadius: blurRadiusValue, - ) - ]))); - - children.add(Positioned.directional( - top: top, - end: end, - start: start, - bottom: bottom, - textDirection: dataGridConfiguration.textDirection, - child: elevationLine, - )); + child: Container( + width: axis == Axis.vertical ? 1 : 0, + height: axis == Axis.horizontal ? 1 : 0, + margin: margin, + decoration: BoxDecoration( + color: const Color(0xFF000000), + boxShadow: [ + BoxShadow( + color: frozenLineColor, + spreadRadius: spreadRadiusValue, + blurRadius: blurRadiusValue, + ), + ], + ), + ), + ); + + children.add( + Positioned.directional( + top: top, + end: end, + start: start, + bottom: bottom, + textDirection: dataGridConfiguration.textDirection, + child: elevationLine, + ), + ); } double getTopPosition(DataRowBase columnHeaderRow, int columnIndex) { double top = 0.0; if (dataGridConfiguration.stackedHeaderRows.isNotEmpty) { top = columnHeaderRow.getRowHeight( - 0, dataGridConfiguration.stackedHeaderRows.length - 1); + 0, + dataGridConfiguration.stackedHeaderRows.length - 1, + ); final DataCellBase? dataCell = columnHeaderRow.visibleColumns .firstWhereOrNull( - (DataCellBase cell) => cell.columnIndex == columnIndex); + (DataCellBase cell) => cell.columnIndex == columnIndex, + ); // Need to ignore header cell spanned height from the total stacked // header rows height if it is spanned. if (dataCell != null && dataCell.rowSpan > 0) { top -= columnHeaderRow.getRowHeight( - dataCell.rowIndex - dataCell.rowSpan, dataCell.rowIndex - 1); + dataCell.rowIndex - dataCell.rowSpan, + dataCell.rowIndex - 1, + ); } } return top; @@ -598,23 +659,30 @@ class _ScrollViewWidgetState extends State { ? _width - dataGridConfiguration.container.extentWidth : 0.0; - final DataRowBase? columnHeaderRow = - dataGridConfiguration.container.rowGenerator.items.firstWhereOrNull( - (DataRowBase row) => row.rowType == RowType.headerRow); + final DataRowBase? columnHeaderRow = dataGridConfiguration + .container + .rowGenerator + .items + .firstWhereOrNull( + (DataRowBase row) => row.rowType == RowType.headerRow, + ); // Provided the margin to allow shadow only to the corresponding side. // In 4.0 pixels, 1.0 pixel defines the size of the container and // 3.0 pixels defines the amount of spreadRadius. final double margin = dataGridConfiguration.dataGridThemeHelper!.frozenPaneElevation! + 4.0; - final int frozenColumnIndex = - grid_helper.getLastFrozenColumnIndex(dataGridConfiguration); - final int footerFrozenColumnIndex = - grid_helper.getStartFooterFrozenColumnIndex(dataGridConfiguration); - final int frozenRowIndex = - grid_helper.getLastFrozenRowIndex(dataGridConfiguration); - final int footerFrozenRowIndex = - grid_helper.getStartFooterFrozenRowIndex(dataGridConfiguration); + final int frozenColumnIndex = grid_helper.getLastFrozenColumnIndex( + dataGridConfiguration, + ); + final int footerFrozenColumnIndex = grid_helper + .getStartFooterFrozenColumnIndex(dataGridConfiguration); + final int frozenRowIndex = grid_helper.getLastFrozenRowIndex( + dataGridConfiguration, + ); + final int footerFrozenRowIndex = grid_helper.getStartFooterFrozenRowIndex( + dataGridConfiguration, + ); final int indentColumnCount = dataGridConfiguration.source.groupedColumns.length; if (columnHeaderRow != null && @@ -624,11 +692,11 @@ class _ScrollViewWidgetState extends State { double blurRadiusValue = 0.0; Color frozenLineColor = frozenLineColorWithoutOpacity; final double top = getTopPosition(columnHeaderRow, frozenColumnIndex); - final double left = (columnHeaderRow.getColumnWidth( - indentColumnCount, - dataGridConfiguration.frozenColumnsCount + - indentColumnCount - - 1)) + + final double left = + (columnHeaderRow.getColumnWidth( + indentColumnCount, + dataGridConfiguration.frozenColumnsCount + indentColumnCount - 1, + )) + (dataGridThemeHelper.indentColumnWidth * indentColumnCount); if (dataGridConfiguration.textDirection == TextDirection.ltr && dataGridConfiguration.container.horizontalOffset > 0) { @@ -640,7 +708,9 @@ class _ScrollViewWidgetState extends State { if (dataGridConfiguration.textDirection == TextDirection.rtl && dataGridConfiguration.horizontalScrollController!.hasClients && dataGridConfiguration - .horizontalScrollController!.position.maxScrollExtent > + .horizontalScrollController! + .position + .maxScrollExtent > dataGridConfiguration.container.horizontalOffset) { spreadRadiusValue = 3.0; blurRadiusValue = @@ -649,16 +719,18 @@ class _ScrollViewWidgetState extends State { } drawElevation( - frozenLineColor: frozenLineColor, - spreadRadiusValue: spreadRadiusValue, - blurRadiusValue: blurRadiusValue, - top: top, - start: left, - bottom: remainingViewPortHeight, - axis: Axis.horizontal, - margin: dataGridConfiguration.textDirection == TextDirection.rtl - ? EdgeInsets.only(left: margin) - : EdgeInsets.only(right: margin)); + frozenLineColor: frozenLineColor, + spreadRadiusValue: spreadRadiusValue, + blurRadiusValue: blurRadiusValue, + top: top, + start: left, + bottom: remainingViewPortHeight, + axis: Axis.horizontal, + margin: + dataGridConfiguration.textDirection == TextDirection.rtl + ? EdgeInsets.only(left: margin) + : EdgeInsets.only(right: margin), + ); } if (columnHeaderRow != null && @@ -668,14 +740,20 @@ class _ScrollViewWidgetState extends State { double blurRadiusValue = dataGridConfiguration.dataGridThemeHelper!.frozenPaneElevation!; Color frozenLineColor = frozenLineColorWithOpacity; - final double top = - getTopPosition(columnHeaderRow, footerFrozenColumnIndex); + final double top = getTopPosition( + columnHeaderRow, + footerFrozenColumnIndex, + ); final double right = columnHeaderRow.getColumnWidth( - footerFrozenColumnIndex, dataGridConfiguration.container.columnCount); + footerFrozenColumnIndex, + dataGridConfiguration.container.columnCount, + ); if (dataGridConfiguration.textDirection == TextDirection.ltr && dataGridConfiguration.horizontalScrollController!.hasClients && dataGridConfiguration - .horizontalScrollController!.position.maxScrollExtent == + .horizontalScrollController! + .position + .maxScrollExtent == dataGridConfiguration.container.horizontalOffset) { spreadRadiusValue = 1.5; blurRadiusValue = 0.0; @@ -689,16 +767,18 @@ class _ScrollViewWidgetState extends State { } drawElevation( - frozenLineColor: frozenLineColor, - spreadRadiusValue: spreadRadiusValue, - blurRadiusValue: blurRadiusValue, - top: top, - bottom: remainingViewPortHeight, - end: right + remainingViewPortWidth, - axis: Axis.horizontal, - margin: dataGridConfiguration.textDirection == TextDirection.rtl - ? EdgeInsets.only(right: margin) - : EdgeInsets.only(left: margin)); + frozenLineColor: frozenLineColor, + spreadRadiusValue: spreadRadiusValue, + blurRadiusValue: blurRadiusValue, + top: top, + bottom: remainingViewPortHeight, + end: right + remainingViewPortWidth, + axis: Axis.horizontal, + margin: + dataGridConfiguration.textDirection == TextDirection.rtl + ? EdgeInsets.only(right: margin) + : EdgeInsets.only(left: margin), + ); } if (columnHeaderRow != null && @@ -717,14 +797,15 @@ class _ScrollViewWidgetState extends State { } drawElevation( - frozenLineColor: frozenLineColor, - spreadRadiusValue: spreadRadiusValue, - blurRadiusValue: blurRadiusValue, - top: top, - start: 0.0, - end: remainingViewPortWidth, - axis: Axis.vertical, - margin: EdgeInsets.only(bottom: margin)); + frozenLineColor: frozenLineColor, + spreadRadiusValue: spreadRadiusValue, + blurRadiusValue: blurRadiusValue, + top: top, + start: 0.0, + end: remainingViewPortWidth, + axis: Axis.vertical, + margin: EdgeInsets.only(bottom: margin), + ); } if (columnHeaderRow != null && @@ -735,11 +816,15 @@ class _ScrollViewWidgetState extends State { dataGridConfiguration.dataGridThemeHelper!.frozenPaneElevation!; Color frozenLineColor = frozenLineColorWithOpacity; final double bottom = columnHeaderRow.getRowHeight( - footerFrozenRowIndex, dataGridConfiguration.container.rowCount); + footerFrozenRowIndex, + dataGridConfiguration.container.rowCount, + ); if (dataGridConfiguration.verticalScrollController!.hasClients && dataGridConfiguration - .verticalScrollController!.position.maxScrollExtent + .verticalScrollController! + .position + .maxScrollExtent .ceilToDouble() == dataGridConfiguration.container.verticalOffset.ceilToDouble()) { spreadRadiusValue = 1.5; @@ -748,14 +833,15 @@ class _ScrollViewWidgetState extends State { } drawElevation( - frozenLineColor: frozenLineColor, - spreadRadiusValue: spreadRadiusValue, - blurRadiusValue: blurRadiusValue, - start: 0.0, - end: remainingViewPortWidth, - axis: Axis.vertical, - bottom: bottom + remainingViewPortHeight, - margin: EdgeInsets.only(top: margin)); + frozenLineColor: frozenLineColor, + spreadRadiusValue: spreadRadiusValue, + blurRadiusValue: blurRadiusValue, + start: 0.0, + end: remainingViewPortWidth, + axis: Axis.vertical, + bottom: bottom + remainingViewPortHeight, + margin: EdgeInsets.only(top: margin), + ); } } @@ -896,32 +982,47 @@ class _ScrollViewWidgetState extends State { // To handle group expansion and collapse the group. void expandCollapseGroup() { final DataRowBase? row = dataGridConfiguration - .container.rowGenerator.items - .firstWhereOrNull((DataRowBase element) => - element.rowIndex == currentCell.rowIndex); + .container + .rowGenerator + .items + .firstWhereOrNull( + (DataRowBase element) => element.rowIndex == currentCell.rowIndex, + ); if (row != null && row.rowType == RowType.captionSummaryCoveredRow && dataGridConfiguration.allowExpandCollapseGroup) { final int rowIndex = resolveStartRecordIndex( - dataGridConfiguration, currentCell.rowIndex); + dataGridConfiguration, + currentCell.rowIndex, + ); final dynamic group = getGroupElement(dataGridConfiguration, rowIndex); if (keyEvent.logicalKey == LogicalKeyboardKey.arrowRight) { if (group is Group && !group.isExpanded) { - dataGridConfiguration.group! - .expandGroups(group, dataGridConfiguration.group, rowIndex); + dataGridConfiguration.group!.expandGroups( + group, + dataGridConfiguration.group, + rowIndex, + ); dataGridConfiguration.groupExpandCollapseRowIndex = currentCell.rowIndex; - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } else if (keyEvent.logicalKey == LogicalKeyboardKey.arrowLeft) { if (group is Group && group.isExpanded) { - dataGridConfiguration.group! - .collapseGroups(group, dataGridConfiguration.group, rowIndex); + dataGridConfiguration.group!.collapseGroups( + group, + dataGridConfiguration.group, + rowIndex, + ); dataGridConfiguration.groupExpandCollapseRowIndex = currentCell.rowIndex; - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'grouping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'grouping', + ); } } } @@ -969,10 +1070,12 @@ class _ScrollViewWidgetState extends State { (!_dataGridFocusNode!.hasPrimaryFocus && currentCell.isEditing); if (HardwareKeyboard.instance.isShiftPressed) { - final int firstRowIndex = - selection_helper.getFirstRowIndex(dataGridConfiguration); - final int firstCellIndex = - selection_helper.getFirstCellIndex(dataGridConfiguration); + final int firstRowIndex = selection_helper.getFirstRowIndex( + dataGridConfiguration, + ); + final int firstCellIndex = selection_helper.getFirstCellIndex( + dataGridConfiguration, + ); if (canAllowToRemoveFocus(firstRowIndex, firstCellIndex)) { return KeyEventResult.ignored; @@ -980,10 +1083,12 @@ class _ScrollViewWidgetState extends State { return KeyEventResult.handled; } } else { - final int lastRowIndex = - selection_helper.getLastNavigatingRowIndex(dataGridConfiguration); - final int lastCellIndex = - selection_helper.getLastCellIndex(dataGridConfiguration); + final int lastRowIndex = selection_helper.getLastNavigatingRowIndex( + dataGridConfiguration, + ); + final int lastCellIndex = selection_helper.getLastCellIndex( + dataGridConfiguration, + ); if (canAllowToRemoveFocus(lastRowIndex, lastCellIndex)) { return KeyEventResult.ignored; @@ -1045,7 +1150,8 @@ class _ScrollViewWidgetState extends State { /// Need not to change the height when onScreenKeyboard appears. /// Cause: If we change the height on editing, editable widget will not move /// above the onScreenKeyboard on mobile platforms. - final bool needToAvoidResizeHeight = !dataGridConfiguration.isDesktop && + final bool needToAvoidResizeHeight = + !dataGridConfiguration.isDesktop && dataGridConfiguration.currentCell.isEditing; if (!needToAvoidResizeHeight) { @@ -1080,7 +1186,7 @@ class _ScrollViewWidgetState extends State { _horizontalController!.removeListener(_horizontalListener); _horizontalController = dataGridConfiguration.horizontalScrollController ?? - ScrollController(); + ScrollController(); _horizontalController!.addListener(_horizontalListener); } } @@ -1094,14 +1200,16 @@ class _ScrollViewWidgetState extends State { _updateColumnSizer(); } - _height = _dataGridConfiguration.viewHeight = - _dataGridConfiguration.shrinkWrapRows - ? (_container.scrollRows as PixelScrollAxis).totalExtent - : widget.height; - _width = _dataGridConfiguration.viewWidth = - _dataGridConfiguration.shrinkWrapColumns - ? (_container.scrollColumns as PixelScrollAxis).totalExtent - : widget.width; + _height = + _dataGridConfiguration.viewHeight = + _dataGridConfiguration.shrinkWrapRows + ? (_container.scrollRows as PixelScrollAxis).totalExtent + : widget.height; + _width = + _dataGridConfiguration.viewWidth = + _dataGridConfiguration.shrinkWrapColumns + ? (_container.scrollColumns as PixelScrollAxis).totalExtent + : widget.width; _updateAxis(); @@ -1127,8 +1235,9 @@ class _ScrollViewWidgetState extends State { // FLUT-6545 if shrinkWrapRows is true, we need to the set the DataGrid maximum height // based on the row value set in the onQueryRowHeight callback if (_dataGridConfiguration.shrinkWrapRows) { - _height = _dataGridConfiguration.viewHeight = - (_container.scrollRows as PixelScrollAxis).totalExtent; + _height = + _dataGridConfiguration.viewHeight = + (_container.scrollRows as PixelScrollAxis).totalExtent; _updateAxis(); } } @@ -1160,13 +1269,12 @@ class _ScrollViewWidgetState extends State { return Container( height: _height, width: _width, - decoration: const BoxDecoration( - color: Colors.transparent, - ), + decoration: const BoxDecoration(color: Colors.transparent), clipBehavior: Clip.antiAlias, child: Stack( - fit: StackFit.passthrough, - children: List.from(children)), + fit: StackFit.passthrough, + children: List.from(children), + ), ); } @@ -1190,10 +1298,11 @@ class _ScrollViewWidgetState extends State { // below mentioned issue is resolved on framework end. // [https://github.com/flutter/flutter/issues/83023] return Focus( - key: _dataGridConfiguration.dataGridKey, - focusNode: _dataGridFocusNode, - onKeyEvent: _handleKeyOperation, - child: addContainer()); + key: _dataGridConfiguration.dataGridKey, + focusNode: _dataGridFocusNode, + onKeyEvent: _handleKeyOperation, + child: addContainer(), + ); } @override @@ -1201,8 +1310,9 @@ class _ScrollViewWidgetState extends State { // Need to dispose the vertical and horizontal scroll listeners when the widget disposed. _verticalController?.removeListener(_verticalListener); _horizontalController?.removeListener(_horizontalListener); - _dataGridConfiguration.rowSelectionManager - .removeListener(_handleSelectionController); + _dataGridConfiguration.rowSelectionManager.removeListener( + _handleSelectionController, + ); // Need to dispose the horizontal scroll controller when it's not set from the sample level. if (_dataGridConfiguration.disposeVerticalScrollController) { @@ -1218,8 +1328,11 @@ class _ScrollViewWidgetState extends State { } /// Return the resizing indicator for mobile platform -Widget _getResizingCursor(DataGridConfiguration dataGridConfiguration, - DataGridThemeHelper themeData, double y) { +Widget _getResizingCursor( + DataGridConfiguration dataGridConfiguration, + DataGridThemeHelper themeData, + double y, +) { const double cursorContainerHeight = 16.0; const double cursorContainerWidth = 16.0; @@ -1234,8 +1347,10 @@ Widget _getResizingCursor(DataGridConfiguration dataGridConfiguration, // Consider the spanned row height to show the indicator at center if (rowSpan > 0) { - rowHeight = columnResizeController.resizingDataCell!.dataRow! - .getRowHeight(rowIndex - rowSpan, rowIndex); + rowHeight = columnResizeController.resizingDataCell!.dataRow!.getRowHeight( + rowIndex - rowSpan, + rowIndex, + ); } return Stack( @@ -1255,11 +1370,15 @@ Widget _getResizingCursor(DataGridConfiguration dataGridConfiguration, height: cursorContainerHeight, width: cursorContainerWidth, padding: const EdgeInsets.all(.2), - decoration: - BoxDecoration(color: indicatorColor, shape: BoxShape.circle), + decoration: BoxDecoration( + color: indicatorColor, + shape: BoxShape.circle, + ), child: CustomPaint( painter: _CustomResizingCursorPainter( - Colors.white, dataGridConfiguration.gridPaint!), + Colors.white, + dataGridConfiguration.gridPaint!, + ), ), ), ), @@ -1295,22 +1414,32 @@ class _CustomResizingCursorPainter extends CustomPainter { /// Drawing left arrow path.moveTo(leftAndRightPadding, verticalCenterPoint); path.lineTo( - horizontalCenterPoint - leftAndRightPadding, leftAndRightPadding); + horizontalCenterPoint - leftAndRightPadding, + leftAndRightPadding, + ); path.moveTo( - horizontalCenterPoint - leftAndRightPadding, topAndBottomPadding); - path.lineTo(horizontalCenterPoint - leftAndRightPadding, - size.height - topAndBottomPadding); + horizontalCenterPoint - leftAndRightPadding, + topAndBottomPadding, + ); + path.lineTo( + horizontalCenterPoint - leftAndRightPadding, + size.height - topAndBottomPadding, + ); path.lineTo(leftAndRightPadding, verticalCenterPoint); path.close(); canvas.drawPath(path, _arrowPaint); /// Drawing right arrow path.moveTo( - horizontalCenterPoint + topAndBottomPadding, leftAndRightPadding); + horizontalCenterPoint + topAndBottomPadding, + leftAndRightPadding, + ); path.lineTo(size.width - leftAndRightPadding, verticalCenterPoint); path.moveTo(size.width - leftAndRightPadding, verticalCenterPoint); - path.lineTo(horizontalCenterPoint + leftAndRightPadding, - size.height - topAndBottomPadding); + path.lineTo( + horizontalCenterPoint + leftAndRightPadding, + size.height - topAndBottomPadding, + ); path.lineTo(verticalCenterPoint + leftAndRightPadding, topAndBottomPadding); path.close(); canvas.drawPath(path, _arrowPaint); @@ -1331,7 +1460,8 @@ bool _canDisableVerticalScrolling(DataGridConfiguration dataGridConfiguration) { } bool _canDisableHorizontalScrolling( - DataGridConfiguration dataGridConfiguration) { + DataGridConfiguration dataGridConfiguration, +) { final VisualContainerHelper container = dataGridConfiguration.container; return (container.scrollColumns.headerExtent + container.scrollColumns.footerExtent) > @@ -1339,13 +1469,13 @@ bool _canDisableHorizontalScrolling( } class _VisualContainer extends StatefulWidget { - const _VisualContainer( - {required Key key, - required this.rowGenerator, - required this.containerSize, - required this.isDirty, - required this.dataGridStateDetails}) - : super(key: key); + const _VisualContainer({ + required Key key, + required this.rowGenerator, + required this.containerSize, + required this.isDirty, + required this.dataGridStateDetails, + }) : super(key: key); final Size containerSize; final RowGenerator rowGenerator; @@ -1363,38 +1493,51 @@ class _VisualContainerState extends State<_VisualContainer> { if (dataGridConfiguration.allowSwiping && dataGridConfiguration.swipingOffset.abs() > 0.0) { final DataRowBase? swipeRow = widget.rowGenerator.items - .where((DataRowBase row) => - (row.rowRegion == RowRegion.body || - row.rowType == RowType.dataRow) && - row.rowIndex >= 0) + .where( + (DataRowBase row) => + (row.rowRegion == RowRegion.body || + row.rowType == RowType.dataRow) && + row.rowIndex >= 0, + ) .firstWhereOrNull((DataRowBase row) => row.isSwipingRow); if (swipeRow != null) { - final DataGridRowSwipeDirection swipeDirection = - grid_helper.getSwipeDirection( - dataGridConfiguration, dataGridConfiguration.swipingOffset); + final DataGridRowSwipeDirection swipeDirection = grid_helper + .getSwipeDirection( + dataGridConfiguration, + dataGridConfiguration.swipingOffset, + ); int rowIndex = 0; if (dataGridConfiguration.source.groupedColumns.isNotEmpty) { - rowIndex = dataGridConfiguration.source.effectiveRows - .indexOf(swipeRow.dataGridRow!); + rowIndex = dataGridConfiguration.source.effectiveRows.indexOf( + swipeRow.dataGridRow!, + ); } else { rowIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, swipeRow.rowIndex); + dataGridConfiguration, + swipeRow.rowIndex, + ); } switch (swipeDirection) { case DataGridRowSwipeDirection.startToEnd: if (dataGridConfiguration.startSwipeActionsBuilder != null) { - final Widget? startSwipeWidget = - dataGridConfiguration.startSwipeActionsBuilder!( - context, swipeRow.dataGridRow!, rowIndex); + final Widget? startSwipeWidget = dataGridConfiguration + .startSwipeActionsBuilder!( + context, + swipeRow.dataGridRow!, + rowIndex, + ); children.add(startSwipeWidget ?? Container()); } break; case DataGridRowSwipeDirection.endToStart: if (dataGridConfiguration.endSwipeActionsBuilder != null) { - final Widget? endSwipeWidget = - dataGridConfiguration.endSwipeActionsBuilder!( - context, swipeRow.dataGridRow!, rowIndex); + final Widget? endSwipeWidget = dataGridConfiguration + .endSwipeActionsBuilder!( + context, + swipeRow.dataGridRow!, + rowIndex, + ); children.add(endSwipeWidget ?? Container()); } break; @@ -1405,40 +1548,52 @@ class _VisualContainerState extends State<_VisualContainer> { void _addRows(List children, RowRegion rowRegion) { if (rowRegion == RowRegion.header) { - children.addAll(widget.rowGenerator.items - .where((DataRowBase row) => - row.rowIndex >= 0 && - row.rowRegion == rowRegion && - (row.rowType == RowType.tableSummaryRow || - row.rowType == RowType.tableSummaryCoveredRow || - row.rowType == RowType.dataRow || - row.rowType == RowType.captionSummaryCoveredRow)) - .map((DataRowBase dataRow) => addWidget(dataRow)) - .toList()); + children.addAll( + widget.rowGenerator.items + .where( + (DataRowBase row) => + row.rowIndex >= 0 && + row.rowRegion == rowRegion && + (row.rowType == RowType.tableSummaryRow || + row.rowType == RowType.tableSummaryCoveredRow || + row.rowType == RowType.dataRow || + row.rowType == RowType.captionSummaryCoveredRow), + ) + .map((DataRowBase dataRow) => addWidget(dataRow)) + .toList(), + ); } else if (rowRegion == RowRegion.body) { // Need to restrict the layout of the currently unused rows that keep the // row index to -1 in the `rowGenerator.items` collection. - children.addAll(widget.rowGenerator.items - .where((DataRowBase row) => - row.rowIndex >= 0 && - row.rowRegion == rowRegion && - (row.rowType == RowType.dataRow || - row.rowType == RowType.footerRow || - row.rowType == RowType.captionSummaryCoveredRow)) - .map((DataRowBase dataRow) => addWidget(dataRow)) - .toList()); + children.addAll( + widget.rowGenerator.items + .where( + (DataRowBase row) => + row.rowIndex >= 0 && + row.rowRegion == rowRegion && + (row.rowType == RowType.dataRow || + row.rowType == RowType.footerRow || + row.rowType == RowType.captionSummaryCoveredRow), + ) + .map((DataRowBase dataRow) => addWidget(dataRow)) + .toList(), + ); } else if (rowRegion == RowRegion.footer) { - children.addAll(widget.rowGenerator.items - .where((DataRowBase row) => - row.rowIndex >= 0 && - row.rowRegion == rowRegion && - (row.rowType == RowType.tableSummaryRow || - row.rowType == RowType.tableSummaryCoveredRow || - row.rowType == RowType.footerRow || - row.rowType == RowType.dataRow || - row.rowType == RowType.captionSummaryCoveredRow)) - .map((DataRowBase dataRow) => addWidget(dataRow)) - .toList()); + children.addAll( + widget.rowGenerator.items + .where( + (DataRowBase row) => + row.rowIndex >= 0 && + row.rowRegion == rowRegion && + (row.rowType == RowType.tableSummaryRow || + row.rowType == RowType.tableSummaryCoveredRow || + row.rowType == RowType.footerRow || + row.rowType == RowType.dataRow || + row.rowType == RowType.captionSummaryCoveredRow), + ) + .map((DataRowBase dataRow) => addWidget(dataRow)) + .toList(), + ); } } @@ -1474,12 +1629,12 @@ class _VisualContainerState extends State<_VisualContainer> { } class _VirtualizingCellsWidget extends StatefulWidget { - const _VirtualizingCellsWidget( - {required Key? key, - required this.dataRow, - required this.isDirty, - required this.dataGridStateDetails}) - : super(key: key); + const _VirtualizingCellsWidget({ + required Key? key, + required this.dataRow, + required this.isDirty, + required this.dataGridStateDetails, + }) : super(key: key); final DataRowBase dataRow; final bool isDirty; @@ -1517,24 +1672,27 @@ class _VirtualizingCellsWidgetState extends State<_VirtualizingCellsWidget> { } class _HeaderCellsWidget extends _VirtualizingCellsWidget { - const _HeaderCellsWidget( - {required Key key, - required DataRowBase dataRow, - bool isDirty = false, - required DataGridStateDetails dataGridStateDetails}) - : super( - key: key, - dataRow: dataRow, - isDirty: isDirty, - dataGridStateDetails: dataGridStateDetails); + const _HeaderCellsWidget({ + required Key key, + required DataRowBase dataRow, + bool isDirty = false, + required DataGridStateDetails dataGridStateDetails, + }) : super( + key: key, + dataRow: dataRow, + isDirty: isDirty, + dataGridStateDetails: dataGridStateDetails, + ); } /// A class [VisualContainerHelper] is used to provide all the information of the /// grid common to build a [SfDataGrid]. class VisualContainerHelper { /// Creates a [VisualContainerHelper] for the [SfDataGrid]. - VisualContainerHelper( - {required this.rowGenerator, required this.dataGridStateDetails}) { + VisualContainerHelper({ + required this.rowGenerator, + required this.dataGridStateDetails, + }) { isDirty = false; isGridLoaded = false; needToSetHorizontalOffset = false; @@ -1587,8 +1745,11 @@ class VisualContainerHelper { /// A class [ScrollAxisBase] that can be used to control the scrolling of rows /// in the [SfDataGrid]. ScrollAxisBase get scrollRows { - _scrollRows ??= - _createScrollAxis(true, verticalScrollBar, rowHeightsProvider); + _scrollRows ??= _createScrollAxis( + true, + verticalScrollBar, + rowHeightsProvider, + ); _scrollRows!.name = 'ScrollRows'; return _scrollRows!; @@ -1601,8 +1762,11 @@ class VisualContainerHelper { /// A class [ScrollAxisBase] that can be used to control the scrolling of columns /// in the [SfDataGrid]. ScrollAxisBase get scrollColumns { - _scrollColumns ??= - _createScrollAxis(true, horizontalScrollBar, columnWidthsProvider); + _scrollColumns ??= _createScrollAxis( + true, + horizontalScrollBar, + columnWidthsProvider, + ); _scrollColumns!.name = 'ScrollColumns'; return _scrollColumns!; } @@ -1700,12 +1864,17 @@ class VisualContainerHelper { if (dataGridConfiguration.textDirection == TextDirection.ltr) { horizontalScrollBar.value = newValue + horizontalScrollBar.minimum; } else { - horizontalScrollBar.value = max(horizontalScrollBar.minimum, - horizontalScrollBar.maximum - horizontalScrollBar.largeChange) - + horizontalScrollBar.value = + max( + horizontalScrollBar.minimum, + horizontalScrollBar.maximum - horizontalScrollBar.largeChange, + ) - newValue; } updateHorizontalOffset( - dataGridConfiguration.controller, horizontalScrollBar.value); + dataGridConfiguration.controller, + horizontalScrollBar.value, + ); needToRefreshColumn = true; } @@ -1720,7 +1889,9 @@ class VisualContainerHelper { dataGridStateDetails(); verticalScrollBar.value = newValue + verticalScrollBar.minimum; updateVerticalOffset( - dataGridConfiguration.controller, verticalScrollBar.value); + dataGridConfiguration.controller, + verticalScrollBar.value, + ); } } @@ -1794,12 +1965,13 @@ class VisualContainerHelper { initialLoading) { lineSizeCollection.suspendUpdates(); } - for (int index = bodyStartLineIndex; - ((current <= bodyEnd || - (current <= dataGridConfiguration.viewHeight)) || - dataGridConfiguration.shrinkWrapRows) && - index < scrollRows.firstFooterLineIndex; - index++) { + for ( + int index = bodyStartLineIndex; + ((current <= bodyEnd || (current <= dataGridConfiguration.viewHeight)) || + dataGridConfiguration.shrinkWrapRows) && + index < scrollRows.firstFooterLineIndex; + index++ + ) { double height = rowHeights[index]; if (!rowHeightManager.contains(index, RowRegion.body) && @@ -1816,7 +1988,10 @@ class VisualContainerHelper { } rowHeightManager.updateRegion( - bodyStartLineIndex, currentEnd, RowRegion.body); + bodyStartLineIndex, + currentEnd, + RowRegion.body, + ); if (rowHeightManager.dirtyRows.isNotEmpty) { for (final int index in rowHeightManager.dirtyRows) { @@ -1871,8 +2046,9 @@ class VisualContainerHelper { void _preGenerateItems() { final VisibleLinesCollection visibleRows = scrollRows.getVisibleLines(); - final VisibleLinesCollection visibleColumns = - grid_helper.getVisibleLines(dataGridStateDetails()); + final VisibleLinesCollection visibleColumns = grid_helper.getVisibleLines( + dataGridStateDetails(), + ); if (visibleRows.isNotEmpty && visibleColumns.isNotEmpty) { rowGenerator.preGenerateRows(visibleRows, visibleColumns); @@ -1923,12 +2099,18 @@ class VisualContainerHelper { } ScrollAxisBase _createScrollAxis( - bool isPixelScroll, ScrollBarBase scrollBar, LineSizeHostBase lineSizes) { + bool isPixelScroll, + ScrollBarBase scrollBar, + LineSizeHostBase lineSizes, + ) { if (isPixelScroll) { final Object lineSize = lineSizes; if (lineSizes is DistancesHostBase) { return PixelScrollAxis.fromPixelScrollAxis( - scrollBar, lineSizes, lineSize as DistancesHostBase); + scrollBar, + lineSizes, + lineSize as DistancesHostBase, + ); } else { return PixelScrollAxis.fromPixelScrollAxis(scrollBar, lineSizes, null); } @@ -1992,7 +2174,9 @@ class VisualContainerHelper { } if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { headerLineCount += grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.top); + dataGridConfiguration, + GridTableSummaryRowPosition.top, + ); } dataGridConfiguration.headerLineCount = headerLineCount; } @@ -2006,7 +2190,9 @@ class VisualContainerHelper { if (dataGridConfiguration.tableSummaryRows.isNotEmpty) { // Add bottom summary rows count footerLineCount += grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); } return footerLineCount; } @@ -2019,14 +2205,6 @@ class VisualContainerHelper { final DataGridConfiguration dataGridConfiguration = dataGridStateDetails(); _updateColumnCount(dataGridConfiguration); _updateRowCount(dataGridConfiguration); - if (rowCount > 0) { - for (int i = 0; - i <= grid_helper.getHeaderIndex(dataGridConfiguration); - i++) { - rowHeights[i] = dataGridConfiguration.headerRowHeight; - } - } - _refreshVerticalScrollbar(); //need to update the indent column width here lineSizeCollection.resumeUpdates(); @@ -2043,7 +2221,7 @@ class VisualContainerHelper { dataGridConfiguration.verticalScrollController!.hasClients) { final double verticalControllerOffset = dataGridConfiguration.verticalScrollController!.offset + - dataGridConfiguration.container.scrollRows.headerExtent; + dataGridConfiguration.container.scrollRows.headerExtent; final double verticalContainerOffset = dataGridConfiguration.container.verticalScrollBar.value; if (verticalControllerOffset != verticalContainerOffset) { @@ -2053,6 +2231,28 @@ class VisualContainerHelper { } } + void _updateRowHeights(DataGridConfiguration dataGridConfiguration) { + // Sets datagrid row height + rowHeights.setRange(0, rowCount - 1, dataGridConfiguration.rowHeight); + + // Sets header row height + if (rowCount > 0) { + for ( + int i = 0; + i <= grid_helper.getHeaderIndex(dataGridConfiguration); + i++ + ) { + rowHeights[i] = dataGridConfiguration.headerRowHeight; + } + } + + // Sets footer row height + if (dataGridConfiguration.footer != null) { + rowHeights[grid_helper.getFooterViewRowIndex(dataGridConfiguration)] = + dataGridConfiguration.footerHeight; + } + } + void _updateColumnCount(DataGridConfiguration dataGridConfiguration) { int columnCount = dataGridConfiguration.columns.length; @@ -2072,9 +2272,10 @@ class VisualContainerHelper { rowsCount = dataGridConfiguration.group?.displayElements?.grouped.length ?? 0; } else { - rowsCount = effectiveRows(dataGridConfiguration.source).isNotEmpty - ? effectiveRows(dataGridConfiguration.source).length - : 0; + rowsCount = + effectiveRows(dataGridConfiguration.source).isNotEmpty + ? effectiveRows(dataGridConfiguration.source).length + : 0; } rowsCount += dataGridConfiguration.headerLineCount; @@ -2082,11 +2283,9 @@ class VisualContainerHelper { rowCount = rowsCount; - // Sets footer row height - if (dataGridConfiguration.footer != null) { - rowHeights[grid_helper.getFooterViewRowIndex(dataGridConfiguration)] = - dataGridConfiguration.footerHeight; - } + // FLUT-958399 Reassign row height after footerIndex changes + // as the previous footerHeight remains in rowHeights[footerViewRowIndex] + _updateRowHeights(dataGridConfiguration); _updateFreezePaneRows(dataGridConfiguration); // FLUT-2047 Need to mark all visible rows height as dirty when @@ -2104,10 +2303,13 @@ class VisualContainerHelper { // We need to consider the indent column along with the frozen columns count. // So, we have added the 1 to the frozen columns count. // We should consider the frozen columns count when the [SfDataGrid.frozenColumnsCount] is greater than 0. - final int frozenColumnCount = dataGridConfiguration.frozenColumnsCount > 0 - ? grid_helper.resolveToScrollColumnIndex( - dataGridConfiguration, dataGridConfiguration.frozenColumnsCount) - : 0; + final int frozenColumnCount = + dataGridConfiguration.frozenColumnsCount > 0 + ? grid_helper.resolveToScrollColumnIndex( + dataGridConfiguration, + dataGridConfiguration.frozenColumnsCount, + ) + : 0; if (frozenColumnCount > 0 && columnCount >= frozenColumnCount) { frozenColumns = frozenColumnCount; } else { @@ -2126,19 +2328,24 @@ class VisualContainerHelper { void _updateFreezePaneRows(DataGridConfiguration dataGridConfiguration) { final int frozenRowCount = grid_helper.resolveToRowIndex( - dataGridConfiguration, dataGridConfiguration.frozenRowsCount); + dataGridConfiguration, + dataGridConfiguration.frozenRowsCount, + ); - frozenRows = (frozenRowCount > 0 && - rowCount >= frozenRowCount && - dataGridConfiguration.frozenRowsCount <= - resolveEffectiveRowCount(dataGridConfiguration)) - ? headerLineCount + dataGridConfiguration.frozenRowsCount - : headerLineCount; + frozenRows = + (frozenRowCount > 0 && + rowCount >= frozenRowCount && + dataGridConfiguration.frozenRowsCount <= + resolveEffectiveRowCount(dataGridConfiguration)) + ? headerLineCount + dataGridConfiguration.frozenRowsCount + : headerLineCount; final int footerFrozenRowsCount = dataGridConfiguration.footerFrozenRowsCount; final int bottomTableSummariesCount = grid_helper.getTableSummaryCount( - dataGridConfiguration, GridTableSummaryRowPosition.bottom); + dataGridConfiguration, + GridTableSummaryRowPosition.bottom, + ); footerFrozenRows = 0; if (footerFrozenRowsCount > 0 && rowCount > frozenRows + footerFrozenRowsCount && @@ -2160,7 +2367,9 @@ class VisualContainerHelper { void resetRowIndex(DataRowBase dataRow) { if (dataRow.rowType == RowType.dataRow) { final int resolvedRowIndex = grid_helper.resolveToRecordIndex( - dataGridConfiguration, dataRow.rowIndex); + dataGridConfiguration, + dataRow.rowIndex, + ); if (resolvedRowIndex.isNegative) { return; } @@ -2168,7 +2377,9 @@ class VisualContainerHelper { dataRow.dataGridRow = effectiveRows(dataGridConfiguration.source)[resolvedRowIndex]; dataRow.dataGridRowAdapter = grid_helper.getDataGridRowAdapter( - dataGridConfiguration, dataRow.dataGridRow!); + dataGridConfiguration, + dataRow.dataGridRow!, + ); dataRow.rowIndexChanged(); } } @@ -2197,7 +2408,8 @@ class VisualContainerHelper { if (dataGridConfiguration.rowsCacheExtent != null && dataGridConfiguration.rowsCacheExtent! > 0) { rowGenerator.items.removeWhere( - (DataRowBase dataRow) => dataRow.rowRegion == RowRegion.body); + (DataRowBase dataRow) => dataRow.rowRegion == RowRegion.body, + ); rowGenerator.items.forEach(resetRowIndex); } else { rowGenerator.items.forEach(resetRowIndex); @@ -2226,9 +2438,11 @@ class VisualContainerHelper { return; } - swipedRow = swipedRow ?? - dataGridConfiguration.rowGenerator.items - .firstWhereOrNull((DataRowBase row) => row.isSwipingRow); + swipedRow = + swipedRow ?? + dataGridConfiguration.rowGenerator.items.firstWhereOrNull( + (DataRowBase row) => row.isSwipingRow, + ); if (swipedRow != null) { swipedRow.isSwipingRow = false; @@ -2238,8 +2452,10 @@ class VisualContainerHelper { dataGridConfiguration.isSwipingApplied = false; if (canUpdate) { - notifyDataGridPropertyChangeListeners(dataGridConfiguration.source, - propertyName: 'Swiping'); + notifyDataGridPropertyChangeListeners( + dataGridConfiguration.source, + propertyName: 'Swiping', + ); } } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/datapager/sfdatapager.dart b/packages/syncfusion_flutter_datagrid/lib/src/datapager/sfdatapager.dart index 220e59ce1..4b6ece54a 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/datapager/sfdatapager.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/datapager/sfdatapager.dart @@ -260,37 +260,39 @@ class SfDataPager extends StatefulWidget { /// /// The [pageCount] and [delegate] argument must be defined and must not /// be null. - const SfDataPager( - {required this.pageCount, - required this.delegate, - Key? key, - this.direction = Axis.horizontal, - this.itemWidth = 50.0, - this.itemHeight = 50.0, - this.itemPadding = const EdgeInsets.all(5), - this.navigationItemHeight = 50.0, - this.navigationItemWidth = 50.0, - this.firstPageItemVisible = true, - this.lastPageItemVisible = true, - this.nextPageItemVisible = true, - this.previousPageItemVisible = true, - this.visibleItemsCount = 5, - this.initialPageIndex = 0, - this.pageItemBuilder, - this.onPageNavigationStart, - this.onPageNavigationEnd, - this.onRowsPerPageChanged, - this.availableRowsPerPage = const [10, 15, 20], - this.controller}) - : assert(pageCount > 0), - assert(itemHeight > 0 && itemWidth > 0), - assert(availableRowsPerPage.length != 0), - assert((firstPageItemVisible || - lastPageItemVisible || - nextPageItemVisible || - previousPageItemVisible) && - (navigationItemHeight > 0 && navigationItemWidth > 0)), - super(key: key); + const SfDataPager({ + required this.pageCount, + required this.delegate, + Key? key, + this.direction = Axis.horizontal, + this.itemWidth = 50.0, + this.itemHeight = 50.0, + this.itemPadding = const EdgeInsets.all(5), + this.navigationItemHeight = 50.0, + this.navigationItemWidth = 50.0, + this.firstPageItemVisible = true, + this.lastPageItemVisible = true, + this.nextPageItemVisible = true, + this.previousPageItemVisible = true, + this.visibleItemsCount = 5, + this.initialPageIndex = 0, + this.pageItemBuilder, + this.onPageNavigationStart, + this.onPageNavigationEnd, + this.onRowsPerPageChanged, + this.availableRowsPerPage = const [10, 15, 20], + this.controller, + }) : assert(pageCount > 0), + assert(itemHeight > 0 && itemWidth > 0), + assert(availableRowsPerPage.length != 0), + assert( + (firstPageItemVisible || + lastPageItemVisible || + nextPageItemVisible || + previousPageItemVisible) && + (navigationItemHeight > 0 && navigationItemWidth > 0), + ), + super(key: key); /// The number of pages required to display in [SfDataPager]. /// Calculate the number of pages by dividing the total number of items @@ -404,21 +406,44 @@ class SfDataPager extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add( - IntProperty('visibleItemsCount', visibleItemsCount, defaultValue: 5)); + IntProperty('visibleItemsCount', visibleItemsCount, defaultValue: 5), + ); properties.add(DoubleProperty('pageCount', pageCount, ifNull: 'null')); properties.add( - IntProperty('initialPageIndex', initialPageIndex, defaultValue: 0.0)); - properties.add(DiagnosticsProperty('direction', direction, - defaultValue: Axis.horizontal)); - properties.add(ObjectFlagProperty('delegate', delegate, - showName: true, ifNull: 'null')); - properties.add(ObjectFlagProperty( - 'controller', controller, - showName: true, ifNull: 'null')); + IntProperty('initialPageIndex', initialPageIndex, defaultValue: 0.0), + ); + properties.add( + DiagnosticsProperty( + 'direction', + direction, + defaultValue: Axis.horizontal, + ), + ); + properties.add( + ObjectFlagProperty( + 'delegate', + delegate, + showName: true, + ifNull: 'null', + ), + ); + properties.add( + ObjectFlagProperty( + 'controller', + controller, + showName: true, + ifNull: 'null', + ), + ); // ignore: strict_raw_type - properties.add(ObjectFlagProperty( - 'pageItemBuilder', pageItemBuilder, - showName: true, ifNull: 'null')); + properties.add( + ObjectFlagProperty>( + 'pageItemBuilder', + pageItemBuilder, + showName: true, + ifNull: 'null', + ), + ); } } @@ -520,11 +545,15 @@ class SfDataPagerState extends State { if ((min(cumulativeSize, maxScrollExtent) != 0.0) && (_scrollController!.offset <= min(cumulativeSize, maxScrollExtent))) { Future.delayed(Duration.zero, () { - final double distance = - min(cumulativeSize, _scrollController!.position.maxScrollExtent); - _scrollController!.animateTo(distance, - duration: const Duration(milliseconds: 1), - curve: Curves.fastOutSlowIn); + final double distance = min( + cumulativeSize, + _scrollController!.position.maxScrollExtent, + ); + _scrollController!.animateTo( + distance, + duration: const Duration(milliseconds: 1), + curve: Curves.fastOutSlowIn, + ); }); } } @@ -549,11 +578,12 @@ class SfDataPagerState extends State { /// Set page count in DataGridSource. _setPageCountInDataGridSource(widget.pageCount); _defaultPagerDimension = Size(300.0, _getDefaultDimensionHeight()); - _scrollController = ScrollController() - ..addListener(_handleScrollPositionChanged); + _scrollController = + ScrollController()..addListener(_handleScrollPositionChanged); _itemGenerator = _DataPagerItemGenerator(); - _controller = widget.controller ?? DataPagerController() - ..addListener(_handleDataPagerControlPropertyChanged); + _controller = + widget.controller ?? DataPagerController() + ..addListener(_handleDataPagerControlPropertyChanged); _addDelegateListener(); } @@ -605,8 +635,7 @@ class SfDataPagerState extends State { final int index = _resolveToItemIndex(widget.initialPageIndex); _handlePageItemTapped(index, _isInitialLoading); WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) { - final double distance = min(_getCumulativeSize(index), - _scrollController!.position.maxScrollExtent); + final double distance = _getCumulativeSize(index); _scrollTo(distance, canUpdate: true); _setCurrentPageIndex(index); }); @@ -618,8 +647,10 @@ class SfDataPagerState extends State { _isRowsPerPageChanged = false; _handlePageItemTapped(_currentPageIndex); WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) { - final double distance = min(_getCumulativeSize(_currentPageIndex), - _scrollController!.position.maxScrollExtent); + final double distance = min( + _getCumulativeSize(_currentPageIndex), + _scrollController!.position.maxScrollExtent, + ); _scrollTo(distance, canUpdate: true); _setCurrentPageIndex(_currentPageIndex); }); @@ -638,8 +669,10 @@ class SfDataPagerState extends State { } } - Future _handlePageItemTapped(int index, - [bool isInitialLoading = false]) async { + Future _handlePageItemTapped( + int index, [ + bool isInitialLoading = false, + ]) async { // Issue: // FLUT-6759 - `handlePageChange` method is called infinite times when switch between pages so fast // @@ -677,8 +710,9 @@ class SfDataPagerState extends State { _suspendDataPagerUpdate = false; } - Future _handleDataPagerControlPropertyChanged( - {String? property}) async { + Future _handleDataPagerControlPropertyChanged({ + String? property, + }) async { _suspendDataPagerUpdate = true; switch (property) { case 'first': @@ -704,7 +738,8 @@ class SfDataPagerState extends State { _setCurrentPageIndex(_lastPageIndex); } _raisePageNavigationEnd( - canChangePage ? _lastPageIndex : _currentPageIndex); + canChangePage ? _lastPageIndex : _currentPageIndex, + ); break; case 'previous': final int previousIndex = _getPreviousPageIndex(); @@ -719,7 +754,8 @@ class SfDataPagerState extends State { _setCurrentPageIndex(previousIndex); } _raisePageNavigationEnd( - canChangePage ? previousIndex : _currentPageIndex); + canChangePage ? previousIndex : _currentPageIndex, + ); break; case 'next': final int nextPageIndex = _getNextPageIndex(); @@ -735,7 +771,8 @@ class SfDataPagerState extends State { _setCurrentPageIndex(nextPageIndex); } _raisePageNavigationEnd( - canChangePage ? nextPageIndex : _currentPageIndex); + canChangePage ? nextPageIndex : _currentPageIndex, + ); break; case 'initialPageIndex': if (widget.initialPageIndex.isNegative) { @@ -761,8 +798,10 @@ class SfDataPagerState extends State { _suspendDataPagerUpdate = false; return; } - final bool canChangePage = - await _canChangePage(selectedPageIndex, true); + final bool canChangePage = await _canChangePage( + selectedPageIndex, + true, + ); if (canChangePage) { final double distance = _getScrollOffset(selectedPageIndex); @@ -770,7 +809,8 @@ class SfDataPagerState extends State { _setCurrentPageIndex(selectedPageIndex); } _raisePageNavigationEnd( - canChangePage ? selectedPageIndex : _currentPageIndex); + canChangePage ? selectedPageIndex : _currentPageIndex, + ); break; default: break; @@ -778,15 +818,19 @@ class SfDataPagerState extends State { _suspendDataPagerUpdate = false; } - Future _canChangePage(int index, - [bool canRaiseNavigationStartCallback = false]) async { + Future _canChangePage( + int index, [ + bool canRaiseNavigationStartCallback = false, + ]) async { if (_controller!.selectedPageIndex != index || canRaiseNavigationStartCallback) { _raisePageNavigationStart(_currentPageIndex); } - final bool canHandle = - await widget.delegate.handlePageChange(_currentPageIndex, index); + final bool canHandle = await widget.delegate.handlePageChange( + _currentPageIndex, + index, + ); return canHandle; } @@ -863,9 +907,11 @@ class SfDataPagerState extends State { } Future.delayed(Duration.zero, () { - _scrollController!.animateTo(offset, - duration: const Duration(milliseconds: 250), - curve: Curves.fastOutSlowIn); + _scrollController!.animateTo( + offset, + duration: const Duration(milliseconds: 250), + curve: Curves.fastOutSlowIn, + ); }); } @@ -885,13 +931,9 @@ class SfDataPagerState extends State { Widget _getChildrenBasedOnDirection(List children) { if (widget.direction == Axis.vertical) { - return Column( - children: List.from(children), - ); + return Column(children: List.from(children)); } else { - return Row( - children: List.from(children), - ); + return Row(children: List.from(children)); } } @@ -922,8 +964,10 @@ class SfDataPagerState extends State { } Size _getScrollViewSize() { - final Size scrollViewSize = - Size(_scrollViewExtent, _defaultPagerDimension.height); + final Size scrollViewSize = Size( + _scrollViewExtent, + _defaultPagerDimension.height, + ); if (widget.direction == Axis.horizontal) { return scrollViewSize; } else { @@ -932,23 +976,33 @@ class SfDataPagerState extends State { } Widget _getIcon( - String type, IconData iconData, bool visible, SfColorScheme colorScheme) { + String type, + IconData iconData, + bool visible, + SfColorScheme colorScheme, + ) { Icon buildIcon() { - return Icon(iconData, - key: ValueKey(type), - size: 20, - color: visible - ? colorScheme.brightness == Brightness.light - ? _dataPagerThemeHelper!.disabledItemTextStyle!.color - ?.withValues(alpha: 0.54) - : _dataPagerThemeHelper!.disabledItemTextStyle!.color - ?.withValues(alpha: 0.65) - : _dataPagerThemeHelper!.disabledItemTextStyle!.color); + return Icon( + iconData, + key: ValueKey(type), + size: 20, + color: + visible + ? colorScheme.brightness == Brightness.light + ? _dataPagerThemeHelper!.disabledItemTextStyle!.color + ?.withValues(alpha: 0.54) + : _dataPagerThemeHelper!.disabledItemTextStyle!.color + ?.withValues(alpha: 0.65) + : _dataPagerThemeHelper!.disabledItemTextStyle!.color, + ); } if (widget.direction == Axis.vertical) { return RotatedBox( - key: ValueKey(type), quarterTurns: 1, child: buildIcon()); + key: ValueKey(type), + quarterTurns: 1, + child: buildIcon(), + ); } else { return buildIcon(); } @@ -978,8 +1032,10 @@ class SfDataPagerState extends State { } } - double _getDataPagerWidth( - {bool canEnableDataPagerLabel = false, bool isDropDown = false}) { + double _getDataPagerWidth({ + bool canEnableDataPagerLabel = false, + bool isDropDown = false, + }) { if (widget.direction == Axis.horizontal) { if (canEnableDataPagerLabel && isDropDown) { return _headerExtent + @@ -1045,7 +1101,9 @@ class SfDataPagerState extends State { void _preGenerateItem(double width) { _itemGenerator.preGenerateItems( - 0, width ~/ _getButtonSize(widget.itemHeight, widget.itemWidth)); + 0, + width ~/ _getButtonSize(widget.itemHeight, widget.itemWidth), + ); } void _ensureItems() { @@ -1053,8 +1111,10 @@ class SfDataPagerState extends State { return; } - final double buttonSize = - _getButtonSize(widget.itemHeight, widget.itemWidth); + final double buttonSize = _getButtonSize( + widget.itemHeight, + widget.itemWidth, + ); final int startIndex = _scrollController!.offset <= _scrollController!.position.minScrollExtent ? 0 @@ -1079,8 +1139,9 @@ class SfDataPagerState extends State { void _arrangeScrollableItems() { _itemGenerator._items.sort( - (_ScrollableDataPagerItem first, _ScrollableDataPagerItem second) => - first.index.compareTo(second.index)); + (_ScrollableDataPagerItem first, _ScrollableDataPagerItem second) => + first.index.compareTo(second.index), + ); double getDifferenceInSize(double itemSize, double navigationItemSize) { if (itemSize > navigationItemSize) { return 0; @@ -1091,27 +1152,35 @@ class SfDataPagerState extends State { for (final _ScrollableDataPagerItem element in _itemGenerator._items) { if (element.visible) { - final double buttonSize = - _getButtonSize(widget.itemHeight, widget.itemWidth); + final double buttonSize = _getButtonSize( + widget.itemHeight, + widget.itemWidth, + ); - double xPos = widget.direction == Axis.horizontal - ? _isRTL - ? _scrollViewExtent - (element.index * buttonSize) - buttonSize - : element.index * buttonSize - : 0.0; + double xPos = + widget.direction == Axis.horizontal + ? _isRTL + ? _scrollViewExtent - + (element.index * buttonSize) - + buttonSize + : element.index * buttonSize + : 0.0; // In vertical direction, If navigationItemWidth>itemWidth, // the items will align from starting position in order of aligning at the center // So we have to align the scrollable item at the center if (widget.direction == Axis.vertical && widget.itemWidth != widget.navigationItemWidth) { - xPos += - getDifferenceInSize(widget.itemWidth, widget.navigationItemWidth); + xPos += getDifferenceInSize( + widget.itemWidth, + widget.navigationItemWidth, + ); } - double yPos = widget.direction == Axis.vertical - ? element.index * buttonSize - : 0.0; + double yPos = + widget.direction == Axis.vertical + ? element.index * buttonSize + : 0.0; // In horizontal direction, If navigationItemHeight>itemHeight, // the items will align from starting position in order of aligning at the center @@ -1119,11 +1188,17 @@ class SfDataPagerState extends State { if (widget.direction == Axis.horizontal && widget.itemHeight != widget.navigationItemHeight) { yPos += getDifferenceInSize( - widget.itemHeight, widget.navigationItemHeight); + widget.itemHeight, + widget.navigationItemHeight, + ); } - element.elementRect = - Rect.fromLTWH(xPos, yPos, widget.itemWidth, widget.itemHeight); + element.elementRect = Rect.fromLTWH( + xPos, + yPos, + widget.itemWidth, + widget.itemHeight, + ); } } } @@ -1131,13 +1206,14 @@ class SfDataPagerState extends State { // PagerItem builders // Item builder - Widget _buildDataPagerItem( - {_ScrollableDataPagerItem? element, - String? type, - IconData? iconData, - double? height, - double? width, - EdgeInsetsGeometry? padding}) { + Widget _buildDataPagerItem({ + _ScrollableDataPagerItem? element, + String? type, + IconData? iconData, + double? height, + double? width, + EdgeInsetsGeometry? padding, + }) { final SfColorScheme colorScheme = SfTheme.colorScheme(context); Widget? pagerItem; Key? pagerItemKey; @@ -1151,20 +1227,23 @@ class SfDataPagerState extends State { } void setBorder() { - border = _dataPagerThemeHelper!.itemBorderWidth != null && - _dataPagerThemeHelper!.itemBorderWidth! > 0.0 - ? Border.all( - width: _dataPagerThemeHelper!.itemBorderWidth!, - color: _dataPagerThemeHelper!.itemBorderColor!) - : Border.all(width: 0.0, color: colorScheme.transparent); + border = + _dataPagerThemeHelper!.itemBorderWidth != null && + _dataPagerThemeHelper!.itemBorderWidth! > 0.0 + ? Border.all( + width: _dataPagerThemeHelper!.itemBorderWidth!, + color: _dataPagerThemeHelper!.itemBorderColor!, + ) + : Border.all(width: 0.0, color: colorScheme.transparent); } if (pagerItem == null) { if (element == null) { visible = !_isNavigatorItemVisible(type!); - itemColor = visible - ? _dataPagerThemeHelper!.itemColor! - : _dataPagerThemeHelper!.disabledItemColor!; + itemColor = + visible + ? _dataPagerThemeHelper!.itemColor! + : _dataPagerThemeHelper!.disabledItemColor!; pagerItem = Semantics( label: '$type Page', @@ -1174,17 +1253,19 @@ class SfDataPagerState extends State { } else { final bool isSelected = _checkIsSelectedIndex(element.index); - itemColor = isSelected - ? _dataPagerThemeHelper!.selectedItemColor! - : _dataPagerThemeHelper!.itemColor!; + itemColor = + isSelected + ? _dataPagerThemeHelper!.selectedItemColor! + : _dataPagerThemeHelper!.itemColor!; final int index = _resolveToItemIndexInView(element.index); pagerItem = Text( index.toString(), key: element.key, - style: isSelected - ? _dataPagerThemeHelper!.selectedItemTextStyle - : _dataPagerThemeHelper!.itemTextStyle, + style: + isSelected + ? _dataPagerThemeHelper!.selectedItemTextStyle + : _dataPagerThemeHelper!.itemTextStyle, ); pagerItemKey = element.key; } @@ -1204,14 +1285,16 @@ class SfDataPagerState extends State { if (element == null) { visible = !_isNavigatorItemVisible(type!); - itemColor = visible - ? _dataPagerThemeHelper!.itemColor! - : _dataPagerThemeHelper!.disabledItemColor!; + itemColor = + visible + ? _dataPagerThemeHelper!.itemColor! + : _dataPagerThemeHelper!.disabledItemColor!; } else { final bool isSelected = _checkIsSelectedIndex(element.index); - itemColor = isSelected - ? _dataPagerThemeHelper!.selectedItemColor! - : _dataPagerThemeHelper!.itemColor!; + itemColor = + isSelected + ? _dataPagerThemeHelper!.selectedItemColor! + : _dataPagerThemeHelper!.itemColor!; } } @@ -1226,11 +1309,13 @@ class SfDataPagerState extends State { child: CustomPaint( key: pagerItemKey, painter: _DataPagerItemBoxPainter( - decoration: BoxDecoration( - color: itemColor, - border: border, - borderRadius: _dataPagerThemeHelper!.itemBorderRadius), - imageConfig: _imageConfiguration!), + decoration: BoxDecoration( + color: itemColor, + border: border, + borderRadius: _dataPagerThemeHelper!.itemBorderRadius, + ), + imageConfig: _imageConfiguration!, + ), child: Material( key: pagerItemKey, color: colorScheme.transparent, @@ -1238,16 +1323,18 @@ class SfDataPagerState extends State { clipBehavior: Clip.antiAlias, child: InkWell( key: pagerItemKey, - mouseCursor: visible - ? WidgetStateMouseCursor.clickable - : SystemMouseCursors.basic, + mouseCursor: + visible + ? WidgetStateMouseCursor.clickable + : SystemMouseCursors.basic, splashColor: visible ? colorScheme.splashColor : colorScheme.transparent, hoverColor: visible ? colorScheme.hoverColor : colorScheme.transparent, - highlightColor: visible - ? colorScheme.highlightColor - : colorScheme.transparent, + highlightColor: + visible + ? colorScheme.highlightColor + : colorScheme.transparent, onTap: () { if (element != null) { if (element.index == _currentPageIndex) { @@ -1260,7 +1347,8 @@ class SfDataPagerState extends State { } _handleDataPagerControlPropertyChanged( - property: type!.toLowerCase()); + property: type!.toLowerCase(), + ); } }, child: Align(key: pagerItemKey, child: pagerItem), @@ -1294,31 +1382,40 @@ class SfDataPagerState extends State { //FirstIcon if (widget.firstPageItemVisible) { - children.add(_buildDataPagerItem( + children.add( + _buildDataPagerItem( type: 'First', iconData: getFirstIcon(), height: widget.navigationItemHeight, width: widget.navigationItemWidth, - padding: widget.itemPadding)); + padding: widget.itemPadding, + ), + ); } //PreviousIcon if (widget.previousPageItemVisible) { - children.add(_buildDataPagerItem( + children.add( + _buildDataPagerItem( type: 'Previous', iconData: getPreviousIcon(), height: widget.navigationItemHeight, width: widget.navigationItemWidth, - padding: widget.itemPadding)); + padding: widget.itemPadding, + ), + ); } //Set headerExtent - _headerExtent = children.isEmpty - ? 0.0 - : children.length * - _getButtonSize( - widget.navigationItemHeight, widget.navigationItemWidth); + _headerExtent = + children.isEmpty + ? 0.0 + : children.length * + _getButtonSize( + widget.navigationItemHeight, + widget.navigationItemWidth, + ); return children.isEmpty ? null : _getChildrenBasedOnDirection(children); } @@ -1328,26 +1425,30 @@ class SfDataPagerState extends State { if (widget.onRowsPerPageChanged != null) { final List availableRowsPerPage = widget.availableRowsPerPage.map>((int? value) { - return DropdownMenuItem( - value: value, - child: Text( - '$value', - style: _dataPagerThemeHelper!.itemTextStyle, - textAlign: _isRTL ? TextAlign.right : TextAlign.left, - )); - }).toList(); + return DropdownMenuItem( + value: value, + child: Text( + '$value', + style: _dataPagerThemeHelper!.itemTextStyle, + textAlign: _isRTL ? TextAlign.right : TextAlign.left, + ), + ); + }).toList(); return Padding( padding: const EdgeInsets.fromLTRB(0, 0, 16, 0), child: Container( width: _dropdownSize.width, height: _dropdownSize.height, - padding: !_isRTL - ? const EdgeInsets.fromLTRB(16, 8, 7, 8) - : const EdgeInsets.fromLTRB(7, 8, 16, 8), + padding: + !_isRTL + ? const EdgeInsets.fromLTRB(16, 8, 7, 8) + : const EdgeInsets.fromLTRB(7, 8, 16, 8), decoration: BoxDecoration( - borderRadius: BorderRadius.circular(3.0), - border: Border.all( - color: _dataPagerThemeHelper!.dropdownButtonBorderColor!)), + borderRadius: BorderRadius.circular(3.0), + border: Border.all( + color: _dataPagerThemeHelper!.dropdownButtonBorderColor!, + ), + ), child: DropdownButtonHideUnderline( child: DropdownButton( focusColor: Colors.transparent, @@ -1391,31 +1492,40 @@ class SfDataPagerState extends State { //NextIcon if (widget.nextPageItemVisible) { - children.add(_buildDataPagerItem( + children.add( + _buildDataPagerItem( type: 'Next', iconData: getNextIcon(), height: widget.navigationItemHeight, width: widget.navigationItemWidth, - padding: widget.itemPadding)); + padding: widget.itemPadding, + ), + ); } //LastIcon if (widget.lastPageItemVisible) { - children.add(_buildDataPagerItem( + children.add( + _buildDataPagerItem( type: 'Last', iconData: getLastIcon(), height: widget.navigationItemHeight, width: widget.navigationItemWidth, - padding: widget.itemPadding)); + padding: widget.itemPadding, + ), + ); } //Set footerExtent - _footerExtent = children.isEmpty - ? 0.0 - : children.length * - _getButtonSize( - widget.navigationItemHeight, widget.navigationItemWidth); + _footerExtent = + children.isEmpty + ? 0.0 + : children.length * + _getButtonSize( + widget.navigationItemHeight, + widget.navigationItemWidth, + ); return children.isEmpty ? null : _getChildrenBasedOnDirection(children); } @@ -1425,12 +1535,15 @@ class SfDataPagerState extends State { final int oldPageCount = _pageCount; _pageCount = widget.pageCount.toInt(); - final double buttonSize = - _getButtonSize(widget.itemHeight, widget.itemWidth); + final double buttonSize = _getButtonSize( + widget.itemHeight, + widget.itemWidth, + ); _scrollViewExtent = buttonSize * _pageCount; final double size = _getSizeConstraint(constraint); - final double visibleItemsSize = size - + final double visibleItemsSize = + size - (_headerExtent + _footerExtent + widget.visibleItemsCount * buttonSize); // Reset the scroll offset @@ -1440,13 +1553,15 @@ class SfDataPagerState extends State { // Need to remove once it fixed final double preScrollViewPortSize = _scrollViewPortSize; - _scrollViewPortSize = visibleItemsSize <= 0 - ? size - _headerExtent - _footerExtent - : widget.visibleItemsCount * buttonSize; + _scrollViewPortSize = + visibleItemsSize <= 0 + ? size - _headerExtent - _footerExtent + : widget.visibleItemsCount * buttonSize; - _scrollViewPortSize = _scrollViewExtent <= _scrollViewPortSize - ? _scrollViewExtent - : _scrollViewPortSize; + _scrollViewPortSize = + _scrollViewExtent <= _scrollViewPortSize + ? _scrollViewExtent + : _scrollViewPortSize; // Reset the scroll offset // Case: VisibleItemsCount get fit into the view on orientation changed @@ -1467,15 +1582,18 @@ class SfDataPagerState extends State { final Widget child = _buildScrollView(); return Container( - width: widget.direction == Axis.horizontal - ? _scrollViewPortSize - : _defaultPagerDimension.height, - height: widget.direction == Axis.horizontal - ? _defaultPagerDimension.height - : _scrollViewPortSize, - clipBehavior: Clip.antiAlias, - decoration: const BoxDecoration(color: Colors.transparent), - child: child); + width: + widget.direction == Axis.horizontal + ? _scrollViewPortSize + : _defaultPagerDimension.height, + height: + widget.direction == Axis.horizontal + ? _defaultPagerDimension.height + : _scrollViewPortSize, + clipBehavior: Clip.antiAlias, + decoration: const BoxDecoration(color: Colors.transparent), + child: child, + ); } // ScrollView Builder @@ -1488,20 +1606,24 @@ class SfDataPagerState extends State { child: _DataPagerItemPanelRenderObject( isDirty: _isDirty, viewSize: _getScrollViewSize(), - children: List<_DataPagerItemRenderObject>.from(_itemGenerator._items - .map<_DataPagerItemRenderObject>( + children: List<_DataPagerItemRenderObject>.from( + _itemGenerator._items + .map<_DataPagerItemRenderObject>( (_ScrollableDataPagerItem element) => _DataPagerItemRenderObject( key: element.key, isDirty: _isDirty, element: element, child: _buildDataPagerItem( - element: element, - height: widget.itemHeight, - width: widget.itemWidth, - padding: widget.itemPadding), - )) - .toList(growable: false)), + element: element, + height: widget.itemHeight, + width: widget.itemWidth, + padding: widget.itemPadding, + ), + ), + ) + .toList(growable: false), + ), ), ); } @@ -1560,14 +1682,18 @@ class SfDataPagerState extends State { final List children = []; final Widget dropDown = _buildDropDownWidget()!; - children.add(Container( - width: _rowsPerPageLabelWidth, - padding: __rowsPerPageLabelPadding, - child: Text(_localization.rowsPerPageDataPagerLabel, + children.add( + Container( + width: _rowsPerPageLabelWidth, + padding: __rowsPerPageLabelPadding, + child: Text( + _localization.rowsPerPageDataPagerLabel, textDirection: _textDirection, style: _dataPagerThemeHelper!.itemTextStyle, - textAlign: _isRTL ? TextAlign.right : TextAlign.left), - )); + textAlign: _isRTL ? TextAlign.right : TextAlign.left, + ), + ), + ); children.add(dropDown); return children; @@ -1584,24 +1710,29 @@ class SfDataPagerState extends State { labelInfo, textDirection: _textDirection, style: TextStyle( - fontSize: _dataPagerThemeHelper!.itemTextStyle!.fontSize, - fontWeight: _dataPagerThemeHelper!.itemTextStyle!.fontWeight, - fontFamily: _dataPagerThemeHelper!.itemTextStyle!.fontFamily, - color: _dataPagerThemeHelper!.itemTextStyle!.color), + fontSize: _dataPagerThemeHelper!.itemTextStyle!.fontSize, + fontWeight: _dataPagerThemeHelper!.itemTextStyle!.fontWeight, + fontFamily: _dataPagerThemeHelper!.itemTextStyle!.fontFamily, + color: _dataPagerThemeHelper!.itemTextStyle!.color, + ), ); final Widget dataPagerLabel = SizedBox( - width: _defaultPagerLabelDimension.width, - height: _defaultPagerLabelDimension.height, - child: Align( - alignment: _isRTL ? Alignment.centerLeft : Alignment.centerRight, - child: Center(child: label))); + width: _defaultPagerLabelDimension.width, + height: _defaultPagerLabelDimension.height, + child: Align( + alignment: _isRTL ? Alignment.centerLeft : Alignment.centerRight, + child: Center(child: label), + ), + ); return dataPagerLabel; } void _buildDataPagerWithLabel( - BoxConstraints constraint, List children) { + BoxConstraints constraint, + List children, + ) { Widget? dataPagerLabel; final bool canEnablePagerLabel = _canEnableDataPagerLabel(constraint); @@ -1617,10 +1748,12 @@ class SfDataPagerState extends State { // DataPager final BoxConstraints dataPagerConstraint = BoxConstraints( - maxWidth: canEnablePagerLabel - ? _getTotalDataPagerWidth(constraint) - getRowsPerPageLabelWidth() - : _getTotalDataPagerWidth(constraint), - maxHeight: _getTotalDataPagerHeight(constraint)); + maxWidth: + canEnablePagerLabel + ? _getTotalDataPagerWidth(constraint) - getRowsPerPageLabelWidth() + : _getTotalDataPagerWidth(constraint), + maxHeight: _getTotalDataPagerHeight(constraint), + ); final Widget pager = _buildDataPager(dataPagerConstraint); @@ -1634,33 +1767,35 @@ class SfDataPagerState extends State { isDropDown = true; } final Widget dataPager = SizedBox( - width: dataPagerConstraint.maxWidth, - height: dataPagerConstraint.maxHeight, - child: Align( - alignment: _isRTL + width: dataPagerConstraint.maxWidth, + height: dataPagerConstraint.maxHeight, + child: Align( + alignment: + _isRTL ? canEnablePagerLabel ? Alignment.centerRight : Alignment.center : canEnablePagerLabel - ? Alignment.centerLeft - : Alignment.center, - child: SizedBox( - width: _getDataPagerWidth( - canEnableDataPagerLabel: canEnablePagerLabel, - isDropDown: isDropDown), - height: _getDataPagerHeight(), - child: dataPagerLabel != null && isDropDown - ? Row( - children: [pager, dataPagerLabel], - ) - : pager))); + ? Alignment.centerLeft + : Alignment.center, + child: SizedBox( + width: _getDataPagerWidth( + canEnableDataPagerLabel: canEnablePagerLabel, + isDropDown: isDropDown, + ), + height: _getDataPagerHeight(), + child: + dataPagerLabel != null && isDropDown + ? Row(children: [pager, dataPagerLabel]) + : pager, + ), + ), + ); children.add(dataPager); if (isDropDown) { - children.add(Row( - children: _buildRowsPerPageLabel()!, - )); + children.add(Row(children: _buildRowsPerPageLabel()!)); } if ((canEnablePagerLabel && dataPagerLabel != null) && !isDropDown) { children.add(dataPagerLabel); @@ -1677,7 +1812,8 @@ class SfDataPagerState extends State { _localization = SfLocalizations.of(context); final ThemeData themeData = Theme.of(context); _dataPagerThemeHelper = DataPagerThemeHelper(context); - _isDesktop = kIsWeb || + _isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -1714,19 +1850,22 @@ class SfDataPagerState extends State { } if (oldWidget.availableRowsPerPage != widget.availableRowsPerPage) { - _rowsPerPage = widget.availableRowsPerPage.contains(_rowsPerPage) - ? _rowsPerPage - : widget.availableRowsPerPage[0]; + _rowsPerPage = + widget.availableRowsPerPage.contains(_rowsPerPage) + ? _rowsPerPage + : widget.availableRowsPerPage[0]; } if (isDataPagerControllerChanged) { if (oldWidget.pageCount != widget.pageCount) { _currentPageIndex = 0; } - oldWidget.controller! - .removeListener(_handleDataPagerControlPropertyChanged); - _controller = widget.controller ?? _controller! - ..addListener(_handleDataPagerControlPropertyChanged); + oldWidget.controller!.removeListener( + _handleDataPagerControlPropertyChanged, + ); + _controller = + widget.controller ?? _controller! + ..addListener(_handleDataPagerControlPropertyChanged); } if (_previousScreenSize != null) { @@ -1746,53 +1885,56 @@ class SfDataPagerState extends State { elevation: 0.0, color: _dataPagerThemeHelper!.backgroundColor, child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraint) { - _previousScreenSize = MediaQuery.of(context).size; - _updateConstraintChanged(constraint); - // Issue: - // - // FLUT-868631-The DataPager did not function correctly when updating the rows per page at runtime - // - // Fix: We have page count value starts from 0. But the current page index starts from 1. - // So, we have to check the current page index is greater than or equal to the page count. - // If it is true, then we have to set the current page index as page count - 1. - if (_currentPageIndex >= _pageCount && _pageCount > 0) { - _currentPageIndex = _pageCount - 1; - } - if (_isDesktop && widget.direction == Axis.horizontal) { - final List children = []; + builder: (BuildContext context, BoxConstraints constraint) { + _previousScreenSize = MediaQuery.of(context).size; + _updateConstraintChanged(constraint); + // Issue: + // + // FLUT-868631-The DataPager did not function correctly when updating the rows per page at runtime + // + // Fix: We have page count value starts from 0. But the current page index starts from 1. + // So, we have to check the current page index is greater than or equal to the page count. + // If it is true, then we have to set the current page index as page count - 1. + if (_currentPageIndex >= _pageCount && _pageCount > 0) { + _currentPageIndex = _pageCount - 1; + } + if (_isDesktop && widget.direction == Axis.horizontal) { + final List children = []; - _buildDataPagerWithLabel(constraint, children); + _buildDataPagerWithLabel(constraint, children); - _isDirty = false; - return constraint.maxWidth >= _kMobileViewWidthOnWeb - ? SizedBox( + _isDirty = false; + return constraint.maxWidth >= _kMobileViewWidthOnWeb + ? SizedBox( width: _getTotalDataPagerWidth(constraint), height: _getTotalDataPagerHeight(constraint), child: _getChildrenBasedOnDirection(children), ) - : SizedBox( + : SizedBox( child: SingleChildScrollView( - scrollDirection: widget.direction, - child: _getChildrenBasedOnDirection(children)), + scrollDirection: widget.direction, + child: _getChildrenBasedOnDirection(children), + ), ); - } else { - final Widget dataPager = _buildDataPager(constraint); - _isDirty = false; - if (widget.onRowsPerPageChanged != null && - widget.direction == Axis.horizontal) { - return SingleChildScrollView( - scrollDirection: widget.direction, - child: dataPager, - ); } else { - return SizedBox( + final Widget dataPager = _buildDataPager(constraint); + _isDirty = false; + if (widget.onRowsPerPageChanged != null && + widget.direction == Axis.horizontal) { + return SingleChildScrollView( + scrollDirection: widget.direction, + child: dataPager, + ); + } else { + return SizedBox( width: _getDataPagerWidth(), height: _getDataPagerHeight(), - child: dataPager); + child: dataPager, + ); + } } - } - }), + }, + ), ); } @@ -1841,16 +1983,19 @@ class _DataPagerItemGenerator { _ScrollableDataPagerItem? indexer(int index) { return _items.firstWhereOrNull( - (_ScrollableDataPagerItem element) => element.index == index); + (_ScrollableDataPagerItem element) => element.index == index, + ); } for (int index = startIndex; index <= endIndex; index++) { _ScrollableDataPagerItem? scrollableElement = indexer(index); if (scrollableElement == null) { - final _ScrollableDataPagerItem? reUseScrollableElement = - _items.firstWhereOrNull((_ScrollableDataPagerItem element) => - element.index == -1 || !element.isEnsured); + final _ScrollableDataPagerItem? reUseScrollableElement = _items + .firstWhereOrNull( + (_ScrollableDataPagerItem element) => + element.index == -1 || !element.isEnsured, + ); updateScrollableItem(reUseScrollableElement, index); } @@ -1904,12 +2049,12 @@ class _ScrollableDataPagerItem { } class _DataPagerItemRenderObject extends SingleChildRenderObjectWidget { - _DataPagerItemRenderObject( - {required Key? key, - required this.isDirty, - required this.element, - required this.child}) - : super(key: key, child: RepaintBoundary.wrap(child, 0)); + _DataPagerItemRenderObject({ + required Key? key, + required this.isDirty, + required this.element, + required this.child, + }) : super(key: key, child: RepaintBoundary.wrap(child, 0)); @override final Widget child; @@ -1920,15 +2065,14 @@ class _DataPagerItemRenderObject extends SingleChildRenderObjectWidget { @override _DataPagerItemRenderBox createRenderObject(BuildContext context) { - return _DataPagerItemRenderBox( - element: element, - isDirty: isDirty, - ); + return _DataPagerItemRenderBox(element: element, isDirty: isDirty); } @override void updateRenderObject( - BuildContext context, _DataPagerItemRenderBox renderObject) { + BuildContext context, + _DataPagerItemRenderBox renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..element = element @@ -1938,7 +2082,7 @@ class _DataPagerItemRenderObject extends SingleChildRenderObjectWidget { class _DataPagerItemRenderBox extends RenderProxyBox { _DataPagerItemRenderBox({required this.element, required bool isDirty}) - : _isDirty = isDirty; + : _isDirty = isDirty; _ScrollableDataPagerItem element; @@ -1961,14 +2105,15 @@ class _DataPagerItemRenderBox extends RenderProxyBox { } class _DataPagerItemPanelRenderObject extends MultiChildRenderObjectWidget { - _DataPagerItemPanelRenderObject( - {Key? key, - required this.isDirty, - required this.viewSize, - required this.children}) - : super( - key: key, - children: RepaintBoundary.wrapAll(List.from(children))); + _DataPagerItemPanelRenderObject({ + Key? key, + required this.isDirty, + required this.viewSize, + required this.children, + }) : super( + key: key, + children: RepaintBoundary.wrapAll(List.from(children)), + ); @override final List<_DataPagerItemRenderObject> children; @@ -1984,7 +2129,9 @@ class _DataPagerItemPanelRenderObject extends MultiChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, _DataPagerItemPanelRenderBox renderObject) { + BuildContext context, + _DataPagerItemPanelRenderBox renderObject, + ) { super.updateRenderObject(context, renderObject); renderObject ..isDirty = isDirty @@ -1997,12 +2144,14 @@ class _DataPagerItemPanelParentData extends ContainerBoxParentData {} class _DataPagerItemPanelRenderBox extends RenderBox with ContainerRenderObjectMixin, - RenderBoxContainerDefaultsMixin, + RenderBoxContainerDefaultsMixin< + RenderBox, + _DataPagerItemPanelParentData + >, DebugOverflowIndicatorMixin { _DataPagerItemPanelRenderBox({required Size viewSize, required bool isDirty}) - : _isDirty = isDirty, - _viewSize = viewSize; + : _isDirty = isDirty, + _viewSize = viewSize; bool get isDirty => _isDirty; bool _isDirty = false; @@ -2056,12 +2205,17 @@ class _DataPagerItemPanelRenderBox extends RenderBox final Rect childRect = child.pageItemRect; childParentData.offset = Offset(childRect.left, childRect.top); child.layout( - BoxConstraints.tightFor( - width: childRect.width, height: childRect.height), - parentUsesSize: true); + BoxConstraints.tightFor( + width: childRect.width, + height: childRect.height, + ), + parentUsesSize: true, + ); } else { - child.layout(const BoxConstraints.tightFor(width: 0.0, height: 0.0), - parentUsesSize: false); + child.layout( + const BoxConstraints.tightFor(width: 0.0, height: 0.0), + parentUsesSize: false, + ); } } child = childParentData.nextSibling; @@ -2088,8 +2242,10 @@ class _DataPagerItemPanelRenderBox extends RenderBox } class _DataPagerItemBoxPainter extends CustomPainter { - const _DataPagerItemBoxPainter( - {required this.decoration, required this.imageConfig}); + const _DataPagerItemBoxPainter({ + required this.decoration, + required this.imageConfig, + }); final ImageConfiguration imageConfig; final BoxDecoration decoration; @@ -2141,8 +2297,9 @@ class DataPagerThemeHelper { /// To Do DataPagerThemeHelper(BuildContext context) { final SfDataPagerThemeData defaults = SfDataPagerTheme.of(context)!; - final SfDataPagerThemeData sfDataPagerThemeData = - _SfDataPagerThemeData(context); + final SfDataPagerThemeData sfDataPagerThemeData = _SfDataPagerThemeData( + context, + ); backgroundColor = defaults.backgroundColor ?? sfDataPagerThemeData.backgroundColor; itemColor = defaults.itemColor ?? sfDataPagerThemeData.itemColor; @@ -2150,11 +2307,13 @@ class DataPagerThemeHelper { defaults.itemTextStyle ?? sfDataPagerThemeData.itemTextStyle; selectedItemColor = defaults.selectedItemColor ?? sfDataPagerThemeData.selectedItemColor; - selectedItemTextStyle = defaults.selectedItemTextStyle ?? + selectedItemTextStyle = + defaults.selectedItemTextStyle ?? sfDataPagerThemeData.selectedItemTextStyle; disabledItemColor = defaults.disabledItemColor ?? sfDataPagerThemeData.disabledItemColor; - disabledItemTextStyle = defaults.disabledItemTextStyle ?? + disabledItemTextStyle = + defaults.disabledItemTextStyle ?? sfDataPagerThemeData.disabledItemTextStyle; itemBorderColor = defaults.itemBorderColor ?? sfDataPagerThemeData.itemBorderColor; @@ -2162,7 +2321,8 @@ class DataPagerThemeHelper { defaults.itemBorderWidth ?? sfDataPagerThemeData.itemBorderWidth; itemBorderRadius = defaults.itemBorderRadius ?? sfDataPagerThemeData.itemBorderRadius; - dropdownButtonBorderColor = defaults.dropdownButtonBorderColor ?? + dropdownButtonBorderColor = + defaults.dropdownButtonBorderColor ?? sfDataPagerThemeData.dropdownButtonBorderColor; } @@ -2227,30 +2387,33 @@ class _SfDataPagerThemeData extends SfDataPagerThemeData { @override TextStyle get itemTextStyle => TextStyle( - color: colorScheme.onSurface[153], - fontSize: 14, - fontFamily: 'Roboto', - fontWeight: FontWeight.w400); + color: colorScheme.onSurface[153], + fontSize: 14, + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + ); @override Color get disabledItemColor => colorScheme.transparent; @override TextStyle get disabledItemTextStyle => TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: colorScheme.onSurface[92]); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: colorScheme.onSurface[92], + ); @override Color? get selectedItemColor => colorScheme.primary[1]; @override TextStyle get selectedItemTextStyle => TextStyle( - fontFamily: 'Roboto', - fontWeight: FontWeight.w400, - fontSize: 14, - color: colorScheme.onPrimary); + fontFamily: 'Roboto', + fontWeight: FontWeight.w400, + fontSize: 14, + color: colorScheme.onPrimary, + ); @override Color get itemBorderColor => colorScheme.transparent; diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/distance_counter.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/distance_counter.dart index c46846a0a..b04643027 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/distance_counter.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/distance_counter.dart @@ -14,11 +14,13 @@ import 'utility_helper.dart'; /// the scrollbars value and the rows or columns associated with that value. abstract class DistanceCounterCollectionBase { /// Create the DistanceCounterCollection Base - DistanceCounterCollectionBase( - {int count = 0, double defaultDistance = 0.0, double totalDistance = 0.0}) - : _count = count, - _defaultDistance = defaultDistance, - _totalDistance = totalDistance; + DistanceCounterCollectionBase({ + int count = 0, + double defaultDistance = 0.0, + double totalDistance = 0.0, + }) : _count = count, + _defaultDistance = defaultDistance, + _totalDistance = totalDistance; /// Gets the raw number of entities (lines, rows or columns). /// @@ -169,7 +171,9 @@ abstract class DistanceCounterCollectionBase { /// * index - _required_ - The index. /// * nestedCollection - _required_ - The nested collection. void setNestedDistances( - int index, DistanceCounterCollectionBase? nestedCollection); + int index, + DistanceCounterCollectionBase? nestedCollection, + ); /// Hides a specified range of entities (lines, rows or columns). /// @@ -206,7 +210,7 @@ class DistanceCounterSubset extends DistanceCounterCollectionBase /// * trackedParentCollection - _required_ - The parent collection for which /// a subset is "tracked". DistanceCounterSubset(DistanceCounterCollectionBase trackedParentCollection) - : super(count: 0) { + : super(count: 0) { _trackDCC = trackedParentCollection; } @@ -284,7 +288,8 @@ class DistanceCounterSubset extends DistanceCounterCollectionBase /// * treeTableCounterSource - _required_ - The nested tree /// table visible counter source. void connectWithParentBase( - TreeTableCounterSourceBase treeTableCounterSource) { + TreeTableCounterSourceBase treeTableCounterSource, + ) { throw Exception('Do not use DistanceCounterSubset as nested collection!'); } @@ -429,7 +434,8 @@ class DistanceCounterSubset extends DistanceCounterCollectionBase } final int n = _trackDCC.indexOfCumulatedDistance( - cumulatedDistance + _trackDCC.getCumulatedDistanceAt(start)); + cumulatedDistance + _trackDCC.getCumulatedDistanceAt(start), + ); if (n > end || n < start) { return -1; } @@ -472,7 +478,9 @@ class DistanceCounterSubset extends DistanceCounterCollectionBase /// * nestedCollection - _required_ - The nested collection. @override void setNestedDistances( - int index, DistanceCounterCollectionBase? nestedCollection) { + int index, + DistanceCounterCollectionBase? nestedCollection, + ) { _trackDCC.setNestedDistances(index + start, nestedCollection); } @@ -520,7 +528,7 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { /// /// * paddingDistance - _required_ - The padding distance. DistanceRangeCounterCollection.fromPaddingDistance(this.paddingDistance) - : super(defaultDistance: 1.0, count: 0) { + : super(defaultDistance: 1.0, count: 0) { final DistanceLineCounter startPos = DistanceLineCounter(0, 0); _rbTree = DistanceLineCounterTree(startPos, false); } @@ -584,9 +592,10 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { /// DistanceLineCounterEntry createTreeTableEntry(double distance, int count) { - final DistanceLineCounterEntry entry = DistanceLineCounterEntry() - ..value = DistanceLineCounterSource(distance, count) - ..tree = _rbTree; + final DistanceLineCounterEntry entry = + DistanceLineCounterEntry() + ..value = DistanceLineCounterSource(distance, count) + ..tree = _rbTree; return entry; } @@ -595,8 +604,10 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { final int treeCount = internalCount; final int insert = count - treeCount; if (insert > 0) { - final DistanceLineCounterEntry entry = - createTreeTableEntry(defaultDistance, insert); + final DistanceLineCounterEntry entry = createTreeTableEntry( + defaultDistance, + insert, + ); _rbTree.add(entry); } } @@ -646,11 +657,16 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { return internalCount + delta; } - final DistanceLineCounter searchPosition = - DistanceLineCounter(cumulatedDistance, 0); - final DistanceLineCounterEntry? rbEntry = - _rbTree.getEntryAtCounterPositionWithThreeArgs( - searchPosition, DistanceLineCounterKind.distance, false); + final DistanceLineCounter searchPosition = DistanceLineCounter( + cumulatedDistance, + 0, + ); + final DistanceLineCounterEntry? rbEntry = _rbTree + .getEntryAtCounterPositionWithThreeArgs( + searchPosition, + DistanceLineCounterKind.distance, + false, + ); final DistanceLineCounterSource? rbValue = rbEntry!.value; final DistanceLineCounter? rbEntryPosition = rbEntry.getCounterPosition; if (rbValue != null && @@ -658,7 +674,7 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { rbValue.singleLineDistance > 0) { final double totalDistance = (cumulatedDistance - rbEntryPosition.distance) / - rbValue.singleLineDistance; + rbValue.singleLineDistance; delta = totalDistance.isFinite ? totalDistance.floor() : 0; } @@ -667,17 +683,23 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { /// LineIndexEntryAt initDistanceLine( - int lineIndex, bool determineEntryPosition) { - final LineIndexEntryAt e = LineIndexEntryAt() - ..searchPosition = DistanceLineCounter(0, lineIndex); + int lineIndex, + bool determineEntryPosition, + ) { + final LineIndexEntryAt e = + LineIndexEntryAt()..searchPosition = DistanceLineCounter(0, lineIndex); e.rbEntry = _rbTree.getEntryAtCounterPositionWithThreeArgs( - e.searchPosition!, DistanceLineCounterKind.lines, false); + e.searchPosition!, + DistanceLineCounterKind.lines, + false, + ); e.rbValue = e.rbEntry!.value; e.rbEntryPosition = null; if (determineEntryPosition) { - e.rbEntryPosition = e.rbValue!.lineCount > 1 - ? e.rbEntry!.getCounterPosition - : e.searchPosition; + e.rbEntryPosition = + e.rbValue!.lineCount > 1 + ? e.rbEntry!.getCounterPosition + : e.searchPosition; } return e; @@ -703,8 +725,10 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { e.rbEntry!.invalidateCounterBottomUp(true); } else { final DistanceLineCounterEntry? rbEntry0 = split(insertAt); - final DistanceLineCounterEntry entry = - createTreeTableEntry(distance, count); + final DistanceLineCounterEntry entry = createTreeTableEntry( + distance, + count, + ); if (rbEntry0 == null) { _rbTree.add(entry); } else { @@ -803,8 +827,10 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { e.rbValue!.lineCount = count1; - final DistanceLineCounterEntry rbEntry2 = - createTreeTableEntry(e.rbValue!.singleLineDistance, count2); + final DistanceLineCounterEntry rbEntry2 = createTreeTableEntry( + e.rbValue!.singleLineDistance, + count2, + ); _rbTree.insert(_rbTree.indexOf(e.rbEntry!) + 1, rbEntry2); e.rbEntry!.invalidateCounterBottomUp(true); return rbEntry2; @@ -842,8 +868,9 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { final double delta = point - nestedStart; if (delta > 0) { - final DistanceCounterCollectionBase? nestedDcc = - getNestedDistances(index); + final DistanceCounterCollectionBase? nestedDcc = getNestedDistances( + index, + ); if (nestedDcc != null) { final double r = nestedDcc.getAlignedScrollValue(delta); if (!r.isNaN && r >= 0 && r < nestedDcc.totalDistance) { @@ -966,8 +993,9 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { double delta = point - nestedStart; if (delta > 0) { - final DistanceCounterCollectionBase? nestedDcc = - getNestedDistances(index); + final DistanceCounterCollectionBase? nestedDcc = getNestedDistances( + index, + ); if (nestedDcc != null) { final double r = nestedDcc.getPreviousScrollValue(delta); if (!r.isNaN && r >= 0 && r < nestedDcc.totalDistance) { @@ -983,8 +1011,9 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { if (index >= 0 && index < count) { nestedStart = getCumulatedDistanceAt(index); - final DistanceCounterCollectionBase? nestedDcc = - getNestedDistances(index); + final DistanceCounterCollectionBase? nestedDcc = getNestedDistances( + index, + ); if (nestedDcc != null) { delta = nestedDcc.totalDistance; final double r = nestedDcc.getPreviousScrollValue(delta); @@ -1130,7 +1159,9 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { /// * nestedCollection - _required_ - The nested collection. @override void setNestedDistances( - int index, DistanceCounterCollectionBase? nestedCollection) { + int index, + DistanceCounterCollectionBase? nestedCollection, + ) { checkRange('index', 0, count - 1, index); if (getNestedDistances(index) != nestedCollection) { @@ -1144,7 +1175,10 @@ class DistanceRangeCounterCollection extends DistanceCounterCollectionBase { if (nestedCollection != null) { final NestedDistanceCounterCollectionSource vcs = NestedDistanceCounterCollectionSource( - this, nestedCollection, entry); + this, + nestedCollection, + entry, + ); entry.value = vcs; } else { entry.value = DistanceLineCounterSource(0, 1); @@ -1220,10 +1254,10 @@ class NestedDistanceCounterCollectionSource extends DistanceLineCounterSource { /// * nestedDistances - _required_ - The nested distances. /// * entry - _required_ - The entry. NestedDistanceCounterCollectionSource( - DistanceCounterCollectionBase parentDistances, - DistanceCounterCollectionBase nestedDistances, - this.entry) - : super(0, 1) { + DistanceCounterCollectionBase parentDistances, + DistanceCounterCollectionBase nestedDistances, + this.entry, + ) : super(0, 1) { _parentDistances = parentDistances; _nestedDistances = nestedDistances; @@ -1262,7 +1296,9 @@ class NestedDistanceCounterCollectionSource extends DistanceLineCounterSource { /// Returns the `_TreeTableVisibleCounter` object with counters. @override TreeTableCounterBase getCounter() => DistanceLineCounter( - _nestedDistances == null ? 0 : _nestedDistances!.totalDistance, 1); + _nestedDistances == null ? 0 : _nestedDistances!.totalDistance, + 1, + ); /// Marks all counters dirty in this object and parent nodes. @override @@ -1491,7 +1527,7 @@ class DistanceLineCounterTree extends TreeTableWithCounter { /// * startPos - _required_ - The start position. /// * sorted - _required_ - A boolean value indicating whether sorted. DistanceLineCounterTree(DistanceLineCounter startPos, bool sorted) - : super(startPos, sorted); + : super(startPos, sorted); /// Appends the given object. /// @@ -1530,7 +1566,9 @@ class DistanceLineCounterTree extends TreeTableWithCounter { /// Returns an entry at the specified counter position. @override DistanceLineCounterEntry? getEntryAtCounterPosition( - Object searchPosition, int cookie) { + Object searchPosition, + int cookie, + ) { if (searchPosition is TreeTableCounterBase && super.getEntryAtCounterPosition(searchPosition, cookie) is DistanceLineCounterEntry) { @@ -1552,13 +1590,23 @@ class DistanceLineCounterTree extends TreeTableWithCounter { /// /// Returns an entry at the specified counter position. DistanceLineCounterEntry? getEntryAtCounterPositionWithThreeArgs( - Object searchPosition, int cookie, bool preferLeftMost) { + Object searchPosition, + int cookie, + bool preferLeftMost, + ) { if (searchPosition is TreeTableCounterBase && super.getEntryAtCounterPositionwithThreeParameter( - searchPosition, cookie, preferLeftMost) + searchPosition, + cookie, + preferLeftMost, + ) is DistanceLineCounterEntry) { return super.getEntryAtCounterPositionwithThreeParameter( - searchPosition, cookie, preferLeftMost)! as DistanceLineCounterEntry; + searchPosition, + cookie, + preferLeftMost, + )! + as DistanceLineCounterEntry; } else { return null; } @@ -1589,7 +1637,9 @@ class DistanceLineCounterTree extends TreeTableWithCounter { /// the specific counter is not empty. @override DistanceLineCounterEntry? getNextNotEmptyCounterEntry( - Object current, int cookie) { + Object current, + int cookie, + ) { if (current is TreeTableEntryBase && super.getNextNotEmptyCounterEntry(current, cookie) is DistanceLineCounterEntry) { @@ -1642,7 +1692,9 @@ class DistanceLineCounterTree extends TreeTableWithCounter { /// specific counter is not empty. @override DistanceLineCounterEntry? getPreviousNotEmptyCounterEntry( - Object current, int cookie) { + Object current, + int cookie, + ) { if (current is TreeTableEntryBase && super.getPreviousNotEmptyCounterEntry(current, cookie) is DistanceLineCounterEntry) { diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/enums.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/enums.dart index 69e871861..51f805e06 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/enums.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/enums.dart @@ -5,7 +5,7 @@ enum TreeTableNodeColor { red, /// TreeTableNodeColoe.black, will represented the Black color. - black + black, } /// Type of scroll axis regions @@ -22,7 +22,7 @@ enum ScrollAxisRegion { /// - ScrollAxisRegion.footer Specifies the footer region /// (at bottom or right side). - footer + footer, } /// Corner side enumeration. @@ -37,5 +37,5 @@ enum CornerSide { right, /// Bottom side alone. - bottom + bottom, } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/event_args.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/event_args.dart index 38b89750f..3ae3a79b2 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/event_args.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/event_args.dart @@ -16,7 +16,11 @@ class RangeChangedArgs { /// * oldSize - _required_ - The old size. /// * newSize - _required_ - The new size. RangeChangedArgs.fromRangeChangedArgs( - int from, int to, double oldSize, double newSize) { + int from, + int to, + double oldSize, + double newSize, + ) { _from = from; _to = to; _oldSize = oldSize; diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/line_size_host.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/line_size_host.dart index f66d8c3d8..50a81e38d 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/line_size_host.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/line_size_host.dart @@ -7,8 +7,8 @@ import 'utility_helper.dart'; /// Returns the DefaultLineSizeChangedArgs used by the /// [onDefaultLineSizeChanged] event. -typedef DefaultLineSizeChangedCallback = void Function( - DefaultLineSizeChangedArgs defaultLineSizeChangedArgs); +typedef DefaultLineSizeChangedCallback = + void Function(DefaultLineSizeChangedArgs defaultLineSizeChangedArgs); /// Returns the LineCountChangedArgs used by the /// [onLineCountChanged][onHeaderLineCountChanged][onFooderLineCountChanged] @@ -16,19 +16,19 @@ typedef DefaultLineSizeChangedCallback = void Function( typedef LineCountChangedCallback = void Function(); /// Returns the HiddenRangeChangedArgs used by the [onLineHiddenChanged] event. -typedef LineHiddenChangedCallback = void Function( - HiddenRangeChangedArgs hiddenRangeChangedArgs); +typedef LineHiddenChangedCallback = + void Function(HiddenRangeChangedArgs hiddenRangeChangedArgs); /// Returns the LinesInsertedArgs used by the [onLinesInserted] event. -typedef LinesInsertedCallback = void Function( - LinesInsertedArgs linesInsertedArgs); +typedef LinesInsertedCallback = + void Function(LinesInsertedArgs linesInsertedArgs); /// Returns the LinesRemovedArgs used by the [onLinesRemoved] event. typedef LinesRemovedCallback = void Function(LinesRemovedArgs linesRemovedArgs); /// Returns the RangeChangedArgs used by the [onLineSizeChanged] event. -typedef LineSizeChangedCallback = void Function( - RangeChangedArgs rangeChangedArgs); +typedef LineSizeChangedCallback = + void Function(RangeChangedArgs rangeChangedArgs); /// A collection that manages lines with varying height and hidden state. /// @@ -135,21 +135,21 @@ mixin NestedDistancesHostBase { /// size of line. abstract class EditableLineSizeHostBase extends LineSizeHostBase { /// - EditableLineSizeHostBase( - {double defaultLineSize = 0.0, - int footerLineCount = 0, - int headerLineCount = 0, - int lineCount = 0, - bool supportsInsertRemove = false, - bool supportsNestedLines = false, - double totalExtent = 0.0}) - : _defaultLineSize = defaultLineSize, - _footerLineCount = footerLineCount, - _headerLineCount = headerLineCount, - _lineCount = lineCount, - _supportsInsertRemove = supportsInsertRemove, - _supportsNestedLines = supportsNestedLines, - _totalExtent = totalExtent; + EditableLineSizeHostBase({ + double defaultLineSize = 0.0, + int footerLineCount = 0, + int headerLineCount = 0, + int lineCount = 0, + bool supportsInsertRemove = false, + bool supportsNestedLines = false, + double totalExtent = 0.0, + }) : _defaultLineSize = defaultLineSize, + _footerLineCount = footerLineCount, + _headerLineCount = headerLineCount, + _lineCount = lineCount, + _supportsInsertRemove = supportsInsertRemove, + _supportsNestedLines = supportsNestedLines, + _totalExtent = totalExtent; /// Gets the default size of lines. /// @@ -277,7 +277,10 @@ abstract class EditableLineSizeHostBase extends LineSizeHostBase { /// `RemoveLines` call when lines should be moved. When it is null, /// empty lines with default size are inserted. void insertLines( - int insertAtLine, int count, EditableLineSizeHostBase? moveLines); + int insertAtLine, + int count, + EditableLineSizeHostBase? moveLines, + ); /// Removes a number of lines at the given index. /// @@ -286,7 +289,10 @@ abstract class EditableLineSizeHostBase extends LineSizeHostBase { /// * moveLines - _required_ - A container to save state for a subsequent /// `InsertLines` call when lines should be moved. void removeLines( - int removeAtLine, int count, EditableLineSizeHostBase? moveLines); + int removeAtLine, + int count, + EditableLineSizeHostBase? moveLines, + ); /// Sets the hidden state for the given range of lines. /// @@ -330,24 +336,25 @@ abstract class EditableLineSizeHostBase extends LineSizeHostBase { /// and `DeferRefresh` method. abstract class PaddedEditableLineSizeHostBase extends EditableLineSizeHostBase { /// - PaddedEditableLineSizeHostBase( - {double paddingDistance = 0.0, - double defaultLineSize = 0.0, - int footerLineCount = 0, - int headerLineCount = 0, - int lineCount = 0, - bool supportsInsertRemove = false, - bool supportsNestedLines = false, - double totalExtent = 0.0}) - : _paddingDistance = paddingDistance, - super( - defaultLineSize: defaultLineSize, - footerLineCount: footerLineCount, - headerLineCount: headerLineCount, - lineCount: lineCount, - supportsInsertRemove: supportsInsertRemove, - supportsNestedLines: supportsNestedLines, - totalExtent: totalExtent); + PaddedEditableLineSizeHostBase({ + double paddingDistance = 0.0, + double defaultLineSize = 0.0, + int footerLineCount = 0, + int headerLineCount = 0, + int lineCount = 0, + bool supportsInsertRemove = false, + bool supportsNestedLines = false, + double totalExtent = 0.0, + }) : _paddingDistance = paddingDistance, + super( + defaultLineSize: defaultLineSize, + footerLineCount: footerLineCount, + headerLineCount: headerLineCount, + lineCount: lineCount, + supportsInsertRemove: supportsInsertRemove, + supportsNestedLines: supportsNestedLines, + totalExtent: totalExtent, + ); /// Gets the padding distance for the line. /// @@ -376,19 +383,21 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase with DistancesHostBase, NestedDistancesHostBase { ///Initializes a new instance of the [LineSizeCollection] class. LineSizeCollection() - : super( - headerLineCount: 0, - footerLineCount: 0, - lineCount: 0, - defaultLineSize: 1.0, - paddingDistance: 0.0); + : super( + headerLineCount: 0, + footerLineCount: 0, + lineCount: 0, + defaultLineSize: 1.0, + paddingDistance: 0.0, + ); final SortedRangeValueList _lineSizes = SortedRangeValueList.from(-1); DistanceCounterCollectionBase? _distances; int _isSuspendUpdates = 0; - SortedRangeValueList _lineHidden = - SortedRangeValueList.from(false); + SortedRangeValueList _lineHidden = SortedRangeValueList.from( + false, + ); Map _lineNested = {}; set distances(DistanceCounterCollectionBase? newValue) { @@ -407,8 +416,9 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase @override DistanceCounterCollectionBase? get distances { if (_distances == null) { - _distances = - DistanceRangeCounterCollection.fromPaddingDistance(paddingDistance); + _distances = DistanceRangeCounterCollection.fromPaddingDistance( + paddingDistance, + ); initializeDistances(); } @@ -489,8 +499,9 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase return; } - _distances = - DistanceRangeCounterCollection.fromPaddingDistance(paddingDistance); + _distances = DistanceRangeCounterCollection.fromPaddingDistance( + paddingDistance, + ); initializeDistances(); } } @@ -620,8 +631,10 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase /// Returns the boolean value indicating the hidden state for a line. @override List getHidden(int index, int repeatValueCount) { - final List rangeValue = - _lineHidden.getRange(index, repeatValueCount); + final List rangeValue = _lineHidden.getRange( + index, + repeatValueCount, + ); return [rangeValue[0], rangeValue[1]]; } @@ -632,16 +645,20 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase if (_lineNested.containsKey(index)) { return [_lineNested[index]?.totalExtent, repeatValueCount]; } - final List hiddenValue = - _lineHidden.getRange(index, repeatValueCount); + final List hiddenValue = _lineHidden.getRange( + index, + repeatValueCount, + ); final bool hide = hiddenValue[0] as bool; repeatValueCount = hiddenValue[1] as int; if (hide) { return [0.0, repeatValueCount]; } - final List rangeValue = - _lineSizes.getRange(index, repeatValueCount); + final List rangeValue = _lineSizes.getRange( + index, + repeatValueCount, + ); final double size = rangeValue[0] as double; repeatValueCount = rangeValue[1] as int; if (size >= 0) { @@ -672,8 +689,11 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase for (final RangeValuePair entry in _lineSizes.rangeValues) { final double entryValue = entry.value as double; if (entryValue != -2) { - _distances!.setRange(entry.start, entry.end, - entryValue < 0.0 ? defaultLineSize : entryValue); + _distances!.setRange( + entry.start, + entry.end, + entryValue < 0.0 ? defaultLineSize : entryValue, + ); } } @@ -704,7 +724,10 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase /// size are inserted. @override void insertLines( - int insertAtLine, int count, EditableLineSizeHostBase? moveLines) { + int insertAtLine, + int count, + EditableLineSizeHostBase? moveLines, + ) { final LineSizeCollection? moveLine = moveLines != null ? moveLines as LineSizeCollection : null; _lineSizes.insertWithThreeArgs(insertAtLine, count, moveLine?._lineSizes); @@ -738,8 +761,10 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase } if (onLinesInserted != null) { - final LinesInsertedArgs linesInsertedArgs = - LinesInsertedArgs.fromArgs(insertAtLine, count); + final LinesInsertedArgs linesInsertedArgs = LinesInsertedArgs.fromArgs( + insertAtLine, + count, + ); onLinesInserted!(linesInsertedArgs); } } @@ -752,7 +777,8 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase final PixelScrollAxis pixelScrollAxis = scrollAxis as PixelScrollAxis; if (_lineNested.isNotEmpty) { throw Exception( - 'When you have nested line collections you need to use PixelScrolling!'); + 'When you have nested line collections you need to use PixelScrolling!', + ); } scrollAxis ..defaultLineSize = defaultLineSize @@ -761,8 +787,11 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase for (final RangeValuePair entry in _lineSizes) { if (entry.value != -2) { final double entryValue = entry.value as double; - scrollAxis.setLineSize(entry.start, entry.end, - entryValue < 0 ? defaultLineSize : entry.value); + scrollAxis.setLineSize( + entry.start, + entry.end, + entryValue < 0 ? defaultLineSize : entry.value, + ); } } @@ -794,13 +823,22 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase /// call when lines should be moved. @override void removeLines( - int removeAtLine, int count, EditableLineSizeHostBase? moveLines) { + int removeAtLine, + int count, + EditableLineSizeHostBase? moveLines, + ) { final LineSizeCollection? removeLines = moveLines != null ? moveLines as LineSizeCollection : null; _lineSizes.removeWithThreeArgs( - removeAtLine, count, removeLines?._lineSizes); + removeAtLine, + count, + removeLines?._lineSizes, + ); _lineHidden.removeWithThreeArgs( - removeAtLine, count, removeLines?._lineHidden); + removeAtLine, + count, + removeLines?._lineHidden, + ); final Map lineNested = _lineNested; _lineNested = {}; @@ -811,8 +849,10 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase if (key >= removeAtLine + count) { _lineNested.putIfAbsent(key - count, () => value); } else if (removeLines != null) { - removeLines._lineNested - .putIfAbsent(key - removeAtLine, () => value); + removeLines._lineNested.putIfAbsent( + key - removeAtLine, + () => value, + ); } } else { _lineNested.putIfAbsent(key, () => value); @@ -831,8 +871,10 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase } if (onLinesRemoved != null) { - final LinesRemovedArgs linesRemovedArgs = - LinesRemovedArgs.fromArgs(removeAtLine, count); + final LinesRemovedArgs linesRemovedArgs = LinesRemovedArgs.fromArgs( + removeAtLine, + count, + ); onLinesRemoved!(linesRemovedArgs); } } @@ -898,8 +940,12 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase } // DistancesLineHiddenChanged checks both hidden state and sizes together... if (_distances != null) { - DistancesUtil.instance - .distancesLineHiddenChanged(distances!, this, from, to); + DistancesUtil.instance.distancesLineHiddenChanged( + distances!, + this, + from, + to, + ); } HiddenRangeChangedArgs hiddenRangeChangedArgs; if (onLineHiddenChanged != null) { @@ -994,8 +1040,12 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase } if (_distances != null) { - DistancesUtil.instance - .distancesLineSizeChanged(distances!, this, index, index); + DistancesUtil.instance.distancesLineSizeChanged( + distances!, + this, + index, + index, + ); } if (onLineSizeChanged != null) { @@ -1023,13 +1073,21 @@ class LineSizeCollection extends PaddedEditableLineSizeHostBase } if (_distances != null) { - DistancesUtil.instance - .distancesLineHiddenChanged(_distances!, this, from, to); + DistancesUtil.instance.distancesLineHiddenChanged( + _distances!, + this, + from, + to, + ); } RangeChangedArgs rangeChangedArgs; if (onLineSizeChanged != null) { - rangeChangedArgs = - RangeChangedArgs.fromRangeChangedArgs(from, to, saveValue, size); + rangeChangedArgs = RangeChangedArgs.fromRangeChangedArgs( + from, + to, + saveValue, + size, + ); onLineSizeChanged!(rangeChangedArgs); } } @@ -1074,8 +1132,12 @@ class DistancesUtil { /// * linesHost - _required_ - The line host. /// * from - _required_ - The start index of the line. /// * to - _required_ - The end index of the line. - void distancesLineHiddenChanged(DistanceCounterCollectionBase distances, - LineSizeHostBase linesHost, int from, int to) { + void distancesLineHiddenChanged( + DistanceCounterCollectionBase distances, + LineSizeHostBase linesHost, + int from, + int to, + ) { final Object ndh = linesHost; for (int n = from; n <= to; n++) { int repeatSizeCount = -1; @@ -1112,8 +1174,12 @@ class DistancesUtil { /// * linesHost - _required_ - The line host. /// * from - _required_ - The start index of the line. /// * to - _required_ - The end index of the line. - void distancesLineSizeChanged(DistanceCounterCollectionBase distances, - LineSizeHostBase linesHost, int from, int to) { + void distancesLineSizeChanged( + DistanceCounterCollectionBase distances, + LineSizeHostBase linesHost, + int from, + int to, + ) { final Object ndh = linesHost; for (int n = from; n <= to; n++) { @@ -1160,8 +1226,12 @@ class DistancesUtil { /// * linesHost - _required_ - The line host. /// * insertAt - _required_ - The index to insert. /// * count - _required_ - The count of the lines inserted. - void onInserted(DistanceCounterCollectionBase distances, - LineSizeHostBase linesHost, int insertAt, int count) { + void onInserted( + DistanceCounterCollectionBase distances, + LineSizeHostBase linesHost, + int insertAt, + int count, + ) { distances.insert(insertAt, count); final int to = insertAt + count - 1; int repeatSizeCount = -1; diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scroll_axis.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scroll_axis.dart index d412ceb98..750ec84b0 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scroll_axis.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scroll_axis.dart @@ -344,7 +344,8 @@ abstract class ScrollAxisBase { /// void defaultLineSizeChangedCallback( - DefaultLineSizeChangedArgs defaultLineSizeChangedArgs) { + DefaultLineSizeChangedArgs defaultLineSizeChangedArgs, + ) { if (scrollLinesHost != null) { defaultLineSize = scrollLinesHost!.getDefaultLineSize(); markDirty(); @@ -378,8 +379,10 @@ abstract class ScrollAxisBase { /// then get temporary value previously set with `SetLineResize`. /// If size is negative then `DefaultLineSize` is returned. List getScrollLinesHostSize(int index, int repeatSizeCount) { - final List lineSize = - scrollLinesHost!.getSize(index, repeatSizeCount); + final List lineSize = scrollLinesHost!.getSize( + index, + repeatSizeCount, + ); double size = lineSize[0] as double; repeatSizeCount = lineSize[1] as int; @@ -410,7 +413,7 @@ abstract class ScrollAxisBase { return [ getScrollLinesHostSize(index, repeatSizeCount)[0], - getScrollLinesHostSize(index, repeatSizeCount)[1] + getScrollLinesHostSize(index, repeatSizeCount)[1], ]; } @@ -436,13 +439,17 @@ abstract class ScrollAxisBase { void getOriginAndCornerOfBodyRegion(double origin, double corner) { int scrollLineIndex = 0; double scrollOffset = 0.0; - final List lineInfo = - getScrollLineIndex(scrollLineIndex, scrollOffset); + final List lineInfo = getScrollLineIndex( + scrollLineIndex, + scrollOffset, + ); scrollLineIndex = lineInfo[0] as int; scrollOffset = lineInfo[1] as double; final double arrangeSize = renderSize; - final double adjustedFooterExtent = - adjustFooterExtentToAvoidGap(footerExtent, arrangeSize); + final double adjustedFooterExtent = adjustFooterExtentToAvoidGap( + footerExtent, + arrangeSize, + ); origin = headerExtent - scrollOffset; corner = arrangeSize - adjustedFooterExtent; } @@ -459,8 +466,11 @@ abstract class ScrollAxisBase { /// * scrollLineOffset The scroll line offset. /// * isRightToLeft The boolean value used to calculate visible columns /// in right to left mode. - List getScrollLineIndex(int scrollLineIndex, double scrollLineOffset, - [bool isRightToLeft = false]); + List getScrollLineIndex( + int scrollLineIndex, + double scrollLineOffset, [ + bool isRightToLeft = false, + ]); /// Gets the maximum range /// @@ -504,8 +514,10 @@ abstract class ScrollAxisBase { int scrollLineIndex = 0; double scrollOffset = 0.0; final int headerLineCount = this.headerLineCount; - final List scrollLineValues = - getScrollLineIndex(scrollLineIndex, scrollOffset); + final List scrollLineValues = getScrollLineIndex( + scrollLineIndex, + scrollOffset, + ); scrollLineIndex = scrollLineValues[0] as int; scrollOffset = scrollLineValues[1] as double; final int firstFooterLine = lineCount - footerLineCount; @@ -515,15 +527,24 @@ abstract class ScrollAxisBase { // Header double point = 0; int lastHeaderLineIndex = -1; - for (index = 0; - index != -1 && - strictlyLessThan(point, headerExtent) && - index < firstFooterLine && - index < headerLineCount; - index = getNextScrollLineIndex(index)) { + for ( + index = 0; + index != -1 && + strictlyLessThan(point, headerExtent) && + index < firstFooterLine && + index < headerLineCount; + index = getNextScrollLineIndex(index) + ) { final double size = getLineSize(index); final VisibleLineInfo line = VisibleLineInfo( - visibleIndex++, index, size, point, 0, true, false); + visibleIndex++, + index, + size, + point, + 0, + true, + false, + ); _visibleLines.add(line); point += size; lastHeaderLineIndex = index; @@ -534,22 +555,29 @@ abstract class ScrollAxisBase { VisibleLineInfo? lastScrollableLine; // Body point = headerExtent; - final int firstBodyLineIndex = - max(scrollLineIndex, lastHeaderLineIndex + 1); - for (index = firstBodyLineIndex; - index != -1 && - strictlyLessThan(point, footerStartPoint) && - index < firstFooterLine; - index = getNextScrollLineIndex(index)) { + final int firstBodyLineIndex = max( + scrollLineIndex, + lastHeaderLineIndex + 1, + ); + for ( + index = firstBodyLineIndex; + index != -1 && + strictlyLessThan(point, footerStartPoint) && + index < firstFooterLine; + index = getNextScrollLineIndex(index) + ) { final double size = getLineSize(index); - _visibleLines.add(lastScrollableLine = VisibleLineInfo( + _visibleLines.add( + lastScrollableLine = VisibleLineInfo( visibleIndex++, index, size, point, scrollOffset, false, - false)); + false, + ), + ); point += size - scrollOffset; scrollOffset = 0; // reset scrollOffset after first line. // Subsequent lines will start at given point. @@ -567,11 +595,13 @@ abstract class ScrollAxisBase { // Footer point = max(headerExtent, viewSize - footerExtent); - for (index = firstFooterLine; - index != -1 && - strictlyLessThan(point, renderSize) && - index < lineCount; - index = getNextScrollLineIndex(index)) { + for ( + index = firstFooterLine; + index != -1 && + strictlyLessThan(point, renderSize) && + index < lineCount; + index = getNextScrollLineIndex(index) + ) { if (lastScrollableLine != null) { lastScrollableLine.clippedCornerExtent = lastScrollableLine.corner - point; @@ -579,8 +609,17 @@ abstract class ScrollAxisBase { } final double size = getLineSize(index); - _visibleLines.add(VisibleLineInfo( - visibleIndex++, index, size, point, 0, false, true)); + _visibleLines.add( + VisibleLineInfo( + visibleIndex++, + index, + size, + point, + 0, + false, + true, + ), + ); point += size; } @@ -635,8 +674,11 @@ abstract class ScrollAxisBase { int scrollLineIndex = 0; double scrollOffset = 0.0; final int headerLineCounts = headerLineCount; - final List scrollLineValues = - getScrollLineIndex(scrollLineIndex, scrollOffset, true); + final List scrollLineValues = getScrollLineIndex( + scrollLineIndex, + scrollOffset, + true, + ); scrollLineIndex = scrollLineValues[0] as int; scrollOffset = scrollLineValues[1] as double; final int firstFooterLine = lineCount - footerLineCount; @@ -646,15 +688,26 @@ abstract class ScrollAxisBase { // Header double point = 0; int lastHeaderLineIndex = -1; - for (index = 0; - index != -1 && - strictlyLessThan(point, headerExtent) && - index < firstFooterLine && - index < headerLineCounts; - index = getNextScrollLineIndex(index)) { + for ( + index = 0; + index != -1 && + strictlyLessThan(point, headerExtent) && + index < firstFooterLine && + index < headerLineCounts; + index = getNextScrollLineIndex(index) + ) { final double size = getLineSize(index); - _visibleLines.add(VisibleLineInfo(visibleIndex++, index, size, - footerStartPoint - size - point, 0, true, false)); + _visibleLines.add( + VisibleLineInfo( + visibleIndex++, + index, + size, + footerStartPoint - size - point, + 0, + true, + false, + ), + ); footerStartPoint -= size; lastHeaderLineIndex = index; } @@ -664,8 +717,10 @@ abstract class ScrollAxisBase { // Body point = headerExtent; - int firstBodyLineIndex = - max(scrollLineIndex, lastHeaderLineIndex + 1); + int firstBodyLineIndex = max( + scrollLineIndex, + lastHeaderLineIndex + 1, + ); point = footerStartPoint - clip.start; @@ -677,22 +732,29 @@ abstract class ScrollAxisBase { } firstBodyLineIndex = max(scrollLineIndex, lastHeaderLineIndex + 1); - for (index = firstBodyLineIndex; - index != -1 && - strictlyLessThan( - point - 1, renderSize + clip.start - headerExtent) && - (point > footerExtent) && - (index < firstFooterLine && index >= headerLineCount); - index = getNextScrollLineIndex(index)) { + for ( + index = firstBodyLineIndex; + index != -1 && + strictlyLessThan( + point - 1, + renderSize + clip.start - headerExtent, + ) && + (point > footerExtent) && + (index < firstFooterLine && index >= headerLineCount); + index = getNextScrollLineIndex(index) + ) { final double size = getLineSize(index); - _visibleLines.add(lastScrollableLine = VisibleLineInfo( + _visibleLines.add( + lastScrollableLine = VisibleLineInfo( visibleIndex++, index, size, point - size + scrollOffset, scrollOffset, false, - false)); + false, + ), + ); point -= size - scrollOffset; scrollOffset = 0; } @@ -709,17 +771,22 @@ abstract class ScrollAxisBase { if (footerLineCount > 0) { if (renderSize < scrollBar!.maximum + footerExtent) { - point = min(renderSize + clip.start - headerExtent, - clip.start + footerExtent); - for (index = firstFooterLine; - index != -1 && - strictlyLessThan( - point - 1, - renderSize < scrollBar!.maximum - ? clip.start + footerExtent - : renderSize - headerExtent) && - index < lineCount; - index = getNextScrollLineIndex(index)) { + point = min( + renderSize + clip.start - headerExtent, + clip.start + footerExtent, + ); + for ( + index = firstFooterLine; + index != -1 && + strictlyLessThan( + point - 1, + renderSize < scrollBar!.maximum + ? clip.start + footerExtent + : renderSize - headerExtent, + ) && + index < lineCount; + index = getNextScrollLineIndex(index) + ) { if (lastScrollableLine != null) { lastScrollableLine.clippedCornerExtent = lastScrollableLine.corner - point; @@ -727,20 +794,32 @@ abstract class ScrollAxisBase { } final double size = getLineSize(index); - _visibleLines.add(VisibleLineInfo( - visibleIndex++, index, size, point - size, 0, false, true)); + _visibleLines.add( + VisibleLineInfo( + visibleIndex++, + index, + size, + point - size, + 0, + false, + true, + ), + ); point -= size; } } else { - for (index = firstFooterLine; - index != -1 && - strictlyLessThan( - point - 1, - renderSize < scrollBar!.maximum - ? clip.start + footerExtent - : renderSize - headerExtent) && - index < lineCount; - index = getNextScrollLineIndex(index)) { + for ( + index = firstFooterLine; + index != -1 && + strictlyLessThan( + point - 1, + renderSize < scrollBar!.maximum + ? clip.start + footerExtent + : renderSize - headerExtent, + ) && + index < lineCount; + index = getNextScrollLineIndex(index) + ) { if (lastScrollableLine != null) { lastScrollableLine.clippedCornerExtent = lastScrollableLine.corner - point; @@ -748,8 +827,17 @@ abstract class ScrollAxisBase { } final double size = getLineSize(index); - _visibleLines.add(VisibleLineInfo( - visibleIndex++, index, size, point - size, 0, false, true)); + _visibleLines.add( + VisibleLineInfo( + visibleIndex++, + index, + size, + point - size, + 0, + false, + true, + ), + ); point -= size; } } @@ -796,15 +884,19 @@ abstract class ScrollAxisBase { /// * isRightToLeft The boolean value used to calculate visible columns /// in right to left mode. /// Returns the visible line for a point in the display. - VisibleLineInfo? getVisibleLineAtPoint(double point, - [bool allowOutSideLines = false, bool isRightToLeft = false]) { + VisibleLineInfo? getVisibleLineAtPoint( + double point, [ + bool allowOutSideLines = false, + bool isRightToLeft = false, + ]) { if (!isRightToLeft) { if (allowOutSideLines) { point = max(point, 0); } - final VisibleLineInfo? lineInfo = - getVisibleLines().getVisibleLineAtPoint(point); + final VisibleLineInfo? lineInfo = getVisibleLines().getVisibleLineAtPoint( + point, + ); if (lineInfo != null && (allowOutSideLines || point <= lineInfo.corner)) { return lineInfo; } @@ -815,8 +907,8 @@ abstract class ScrollAxisBase { final VisibleLinesCollection collection = getVisibleLines(true); final VisibleLinesCollection reversedCollection = collection.reversed; - final VisibleLineInfo? lineInfo = - reversedCollection.getVisibleLineAtPoint(point); + final VisibleLineInfo? lineInfo = reversedCollection + .getVisibleLineAtPoint(point); if (lineInfo != null && (allowOutSideLines || point <= lineInfo.corner)) { return lineInfo; } @@ -832,9 +924,10 @@ abstract class ScrollAxisBase { /// The visible line that displays the line with the given /// absolute line index. - VisibleLineInfo? getVisibleLineAtLineIndex(int lineIndex, - {bool isRightToLeft = false}) => - getVisibleLines(isRightToLeft).getVisibleLineAtLineIndex(lineIndex); + VisibleLineInfo? getVisibleLineAtLineIndex( + int lineIndex, { + bool isRightToLeft = false, + }) => getVisibleLines(isRightToLeft).getVisibleLineAtLineIndex(lineIndex); /// Gets the visible line that displays the line with the given absolute /// line index. If the line is outside the view and you specify @@ -848,12 +941,21 @@ abstract class ScrollAxisBase { /// Returns the visible line that displays the line with the given /// absolute line index. VisibleLineInfo? getVisibleLineAtLineIndexWithTwoArgs( - int lineIndex, bool allowCreateEmptyLineIfNotVisible) { + int lineIndex, + bool allowCreateEmptyLineIfNotVisible, + ) { VisibleLineInfo? line = getVisibleLineAtLineIndex(lineIndex); if (line == null && allowCreateEmptyLineIfNotVisible) { final double size = getLineSize(lineIndex); line = VisibleLineInfo( - maxvalue, lineIndex, size, renderSize + 1, size, false, false); + maxvalue, + lineIndex, + size, + renderSize + 1, + size, + false, + false, + ); } return line; @@ -880,7 +982,9 @@ abstract class ScrollAxisBase { } return Int32Span( - visibleLines[start].lineIndex, visibleLines[end].lineIndex); + visibleLines[start].lineIndex, + visibleLines[end].lineIndex, + ); } return null; } @@ -892,7 +996,10 @@ abstract class ScrollAxisBase { /// * start The start index. /// * end The end index. void getVisibleSectionWithThreeArgs( - ScrollAxisRegion section, int start, int end) { + ScrollAxisRegion section, + int start, + int end, + ) { getVisibleSection(section, start, end); } @@ -931,7 +1038,9 @@ abstract class ScrollAxisBase { /// * lastLine The last visible line. /// Returns the clipping area for the specified visible lines. DoubleSpan getBorderRangeClipPoints( - VisibleLineInfo firstLine, VisibleLineInfo lastLine) { + VisibleLineInfo firstLine, + VisibleLineInfo lastLine, + ) { if (!firstLine.isClippedOrigin && !lastLine.isClippedCorner) { return DoubleSpan(0, renderSize); } @@ -958,10 +1067,16 @@ abstract class ScrollAxisBase { /// in right to left mode. /// Returns the visible line. VisibleLineInfo? getLineNearCorner( - double point, double hitTestPrecision, CornerSide side, - {bool isRightToLeft = false}) => - getLineNearCornerWithFourArgs( - point, hitTestPrecision, CornerSide.both, isRightToLeft); + double point, + double hitTestPrecision, + CornerSide side, { + bool isRightToLeft = false, + }) => getLineNearCornerWithFourArgs( + point, + hitTestPrecision, + CornerSide.both, + isRightToLeft, + ); /// Gets the line near the given corner point. Use this method /// for hit-testing row or column lines for resizing cells. @@ -972,8 +1087,11 @@ abstract class ScrollAxisBase { /// * isRightToLeft The boolean value indicates the right to left mode. /// Returns the visible line. VisibleLineInfo? getLineNearCornerWithFourArgs( - double point, double hitTestPrecision, CornerSide side, - [bool isRightToLeft = false]) { + double point, + double hitTestPrecision, + CornerSide side, [ + bool isRightToLeft = false, + ]) { if (!isRightToLeft) { final VisibleLinesCollection lines = getVisibleLines(); VisibleLineInfo? visibleLine = lines.getVisibleLineAtPoint(point); @@ -1010,8 +1128,11 @@ abstract class ScrollAxisBase { } } else { final VisibleLinesCollection lines = getVisibleLines(true); - VisibleLineInfo? visibleLine = - getVisibleLineAtPoint(point, false, isRightToLeft); + VisibleLineInfo? visibleLine = getVisibleLineAtPoint( + point, + false, + isRightToLeft, + ); if (visibleLine != null) { double d; @@ -1070,13 +1191,14 @@ abstract class ScrollAxisBase { /// * lastLine The last line or null if allowAdjust is false and line /// is not in viewable area. List getLinesAndVisibility( - int firstIndex, - int lastIndex, - bool allowAdjust, - bool firstVisible, - bool lastVisible, - VisibleLineInfo? firstLine, - VisibleLineInfo? lastLine) { + int firstIndex, + int lastIndex, + bool allowAdjust, + bool firstVisible, + bool lastVisible, + VisibleLineInfo? firstLine, + VisibleLineInfo? lastLine, + ) { final VisibleLinesCollection visibleLines = getVisibleLines(); if (firstIndex < 0) { @@ -1088,26 +1210,22 @@ abstract class ScrollAxisBase { firstVisible = false; firstLine = null; } - // Header else if (firstIndex < headerLineCount) { firstVisible = true; firstLine = visibleLines.getVisibleLineNearLineIndex(firstIndex); } - // Footer else if (firstIndex >= firstFooterLineIndex) { firstVisible = true; firstLine = visibleLines.getVisibleLineNearLineIndex(firstIndex); } - // After Header and Before Scroll Position else if (firstIndex < scrollLineIndex) { firstVisible = false; firstLine = allowAdjust ? getVisibleLineAtLineIndex(scrollLineIndex) : null; } - // After Scroll Position and Before Footer else if (firstIndex > lastBodyVisibleLineIndex) { firstVisible = false; @@ -1132,19 +1250,16 @@ abstract class ScrollAxisBase { lastVisible = false; lastLine = null; } - // Header else if (lastIndex < headerLineCount) { lastVisible = true; lastLine = visibleLines.getVisibleLineNearLineIndex(lastIndex); } - // Footer else if (lastIndex >= firstFooterLineIndex) { lastVisible = true; lastLine = visibleLines.getVisibleLineNearLineIndex(lastIndex); } - // After Header and Before Scroll Position else if (lastIndex < scrollLineIndex) { lastVisible = false; @@ -1162,7 +1277,6 @@ abstract class ScrollAxisBase { } } } - // After Scroll Position and Before Footer else if (lastIndex > lastBodyVisibleLineIndex) { lastVisible = false; @@ -1173,7 +1287,6 @@ abstract class ScrollAxisBase { lastLine = allowAdjust ? lastBodyVisibleLine : null; } } - // Regular line (Body) - Visible and not a Header or Footer. else { lastVisible = true; @@ -1198,8 +1311,15 @@ abstract class ScrollAxisBase { const bool lastVisible = false; VisibleLineInfo? firstLine, lastLine; - final List values = getLinesAndVisibility(firstIndex, lastIndex, - true, firstVisible, lastVisible, firstLine, lastLine); + final List values = getLinesAndVisibility( + firstIndex, + lastIndex, + true, + firstVisible, + lastVisible, + firstLine, + lastLine, + ); firstLine = values[2]; lastLine = values[3]; @@ -1216,8 +1336,10 @@ abstract class ScrollAxisBase { /// * isRightToLeft The boolean value used to calculate visible columns /// in right to left mode. /// Returns the clip points for a region. - DoubleSpan getClipPoints(ScrollAxisRegion region, - {bool isRightToLeft = false}) { + DoubleSpan getClipPoints( + ScrollAxisRegion region, { + bool isRightToLeft = false, + }) { final VisibleLinesCollection lines = getVisibleLines(); int start = -1; int end = -1; @@ -1286,17 +1408,25 @@ abstract class ScrollAxisBase { /// void hiddenRangeChangedCallback( - HiddenRangeChangedArgs hiddenRangeChangedArgs) { - for (int n = hiddenRangeChangedArgs.from; - n <= hiddenRangeChangedArgs.to; - n++) { + HiddenRangeChangedArgs hiddenRangeChangedArgs, + ) { + for ( + int n = hiddenRangeChangedArgs.from; + n <= hiddenRangeChangedArgs.to; + n++ + ) { int repeatSizeCount = 0; - final List hiddenValue = - scrollLinesHost!.getHidden(n, repeatSizeCount); + final List hiddenValue = scrollLinesHost!.getHidden( + n, + repeatSizeCount, + ); final bool hide = hiddenValue[0] as bool; repeatSizeCount = hiddenValue[1] as int; - final int rangeTo = - getRangeToHelper(n, hiddenRangeChangedArgs.to, repeatSizeCount); + final int rangeTo = getRangeToHelper( + n, + hiddenRangeChangedArgs.to, + repeatSizeCount, + ); setLineHiddenState(n, rangeTo, hide); n = rangeTo; } @@ -1364,8 +1494,11 @@ abstract class ScrollAxisBase { void resetLineResize() { const int repeatSizeCount = 0; if (_lineResizeIndex >= 0 && _scrollLinesHost != null) { - setLineSize(_lineResizeIndex, _lineResizeIndex, - getScrollLinesHostSize(_lineResizeIndex, repeatSizeCount)[0]); + setLineSize( + _lineResizeIndex, + _lineResizeIndex, + getScrollLinesHostSize(_lineResizeIndex, repeatSizeCount)[0], + ); } _lineResizeIndex = -1; @@ -1381,14 +1514,22 @@ abstract class ScrollAxisBase { final List lineSize = getScrollLinesHostSize(n, repeatSizeCount); final double size = lineSize[0] as double; repeatSizeCount = lineSize[1] as int; - final int rangeTo = - getRangeToHelper(n, rangeChangedArgs.to, repeatSizeCount); + final int rangeTo = getRangeToHelper( + n, + rangeChangedArgs.to, + repeatSizeCount, + ); setLineSize(n, rangeTo, size); n = rangeTo; } // Also check whether I need to re-hide any of the rows. - hiddenRangeChangedCallback(HiddenRangeChangedArgs.fromArgs( - rangeChangedArgs.from, rangeChangedArgs.to, false)); + hiddenRangeChangedCallback( + HiddenRangeChangedArgs.fromArgs( + rangeChangedArgs.from, + rangeChangedArgs.to, + false, + ), + ); markDirty(); raiseChanged(ScrollChangedAction.lineResized); } @@ -1408,7 +1549,10 @@ abstract class ScrollAxisBase { /// Returns An array with 3 ranges indicating the first and last point /// for the given lines in each region. List rangeToRegionPoints( - int first, int last, bool allowEstimatesForOutOfViewLines); + int first, + int last, + bool allowEstimatesForOutOfViewLines, + ); /// Gets the first and last point for the given lines in a region. /// @@ -1418,16 +1562,21 @@ abstract class ScrollAxisBase { /// * allowEstimatesForOutOfViewLines if set to true allow estimates /// for out of view lines. /// Returns the first and last point for the given lines in a region. - DoubleSpan rangeToPoints(ScrollAxisRegion region, int first, int last, - bool allowEstimatesForOutOfViewLines); + DoubleSpan rangeToPoints( + ScrollAxisRegion region, + int first, + int last, + bool allowEstimatesForOutOfViewLines, + ); /// Raises the `Changed` event. /// /// * action scroll action void raiseChanged(ScrollChangedAction action) { if (onChangedCallback != null) { - final ScrollChangedArgs scrollChangedArgs = - ScrollChangedArgs.fromArgs(action); + final ScrollChangedArgs scrollChangedArgs = ScrollChangedArgs.fromArgs( + action, + ); onChangedCallback!(scrollChangedArgs); } } @@ -1553,13 +1702,17 @@ abstract class ScrollAxisBase { double get viewCorner { int scrollLineIndex = 0; double scrollOffset = 0.0; - final List lineSize = - getScrollLineIndex(scrollLineIndex, scrollOffset); + final List lineSize = getScrollLineIndex( + scrollLineIndex, + scrollOffset, + ); scrollLineIndex = lineSize[0] as int; scrollOffset = lineSize[1] as double; final double arrangeSize = renderSize; - final double adjustedFooterExtent = - adjustFooterExtentToAvoidGap(footerExtent, arrangeSize); + final double adjustedFooterExtent = adjustFooterExtentToAvoidGap( + footerExtent, + arrangeSize, + ); return arrangeSize - adjustedFooterExtent; } @@ -1575,8 +1728,9 @@ abstract class ScrollAxisBase { point = max(point, 0); } - final VisibleLineInfo? line = - getVisibleLines().getVisibleLineAtPoint(point); + final VisibleLineInfo? line = getVisibleLines().getVisibleLineAtPoint( + point, + ); if (line != null && (allowOutsideLines || point <= line.corner)) { return line.lineIndex; } @@ -1628,10 +1782,12 @@ class PixelScrollAxis extends ScrollAxisBase { /// * scrollBar - _required_ - The scrollbar state. /// * scrollLinesHost - _required_ - The scroll lines host. /// * distancesHost - _required_ - The distances host. - PixelScrollAxis(ScrollAxisBase parentScrollAxis, ScrollBarBase scrollBar, - LineSizeHostBase scrollLinesHost, DistancesHostBase distancesHost) - : super(scrollBar, scrollLinesHost, - headerExtent: 0.0, footerExtent: 0.0) { + PixelScrollAxis( + ScrollAxisBase parentScrollAxis, + ScrollBarBase scrollBar, + LineSizeHostBase scrollLinesHost, + DistancesHostBase distancesHost, + ) : super(scrollBar, scrollLinesHost, headerExtent: 0.0, footerExtent: 0.0) { // GridCellGridRenderer passes in Distances. LineSizeCollection holds them. // This allows faster construction of grids when they were scrolled // out of view and unloaded. @@ -1647,14 +1803,17 @@ class PixelScrollAxis extends ScrollAxisBase { /// * scrollBar - _required_ - The scrollbar state. /// * scrollLinesHost - _required_ - The scroll lines host. /// * distancesHost - _required_ - The distances host. - PixelScrollAxis.fromPixelScrollAxis(ScrollBarBase scrollBar, - LineSizeHostBase? scrollLinesHost, DistancesHostBase? distancesHost) - : super(scrollBar, scrollLinesHost) { + PixelScrollAxis.fromPixelScrollAxis( + ScrollBarBase scrollBar, + LineSizeHostBase? scrollLinesHost, + DistancesHostBase? distancesHost, + ) : super(scrollBar, scrollLinesHost) { if (distancesHost != null) { _distancesHost = distancesHost; } else if (scrollLinesHost != null) { - _distances = DistanceRangeCounterCollection() - ..defaultDistance = scrollLinesHost.getDefaultLineSize(); + _distances = + DistanceRangeCounterCollection() + ..defaultDistance = scrollLinesHost.getDefaultLineSize(); scrollLinesHost.initializeScrollAxis(this); } @@ -1714,7 +1873,10 @@ class PixelScrollAxis extends ScrollAxisBase { if (_parentScrollAxis != null) { _parentScrollAxis!.setLineSize( - startLineIndex, startLineIndex, distances?.totalDistance ?? 0); + startLineIndex, + startLineIndex, + distances?.totalDistance ?? 0, + ); } } } @@ -1827,21 +1989,28 @@ class PixelScrollAxis extends ScrollAxisBase { /// * isRightToLeft - _optional_ - The boolean value used to calculate /// visible columns in right to left mode. @override - List getScrollLineIndex(int scrollLineIndex, double scrollLineDelta, - [bool isRightToLeft = false]) { + List getScrollLineIndex( + int scrollLineIndex, + double scrollLineDelta, [ + bool isRightToLeft = false, + ]) { if (!isRightToLeft && scrollBar != null && distances != null) { - scrollLineIndex = - max(0, distances!.indexOfCumulatedDistance(scrollBar!.value)); + scrollLineIndex = max( + 0, + distances!.indexOfCumulatedDistance(scrollBar!.value), + ); if (scrollLineIndex >= lineCount) { scrollLineDelta = 0.0; } else { - scrollLineDelta = scrollBar!.value - + scrollLineDelta = + scrollBar!.value - distances!.getCumulatedDistanceAt(scrollLineIndex); } } else { scrollLineIndex = max( - 0, - distances!.indexOfCumulatedDistance(scrollBar!.maximum - + 0, + distances!.indexOfCumulatedDistance( + scrollBar!.maximum - scrollBar!.largeChange - scrollBar!.value + (headerLineCount == 0 ? clip.start : clip.start + headerExtent) + @@ -1850,12 +2019,15 @@ class PixelScrollAxis extends ScrollAxisBase { scrollBar!.maximum - footerExtent - headerExtent - : 0))); + : 0), + ), + ); if (scrollLineIndex >= lineCount) { scrollLineDelta = 0.0; } else { - scrollLineDelta = scrollBar!.maximum - + scrollLineDelta = + scrollBar!.maximum - scrollBar!.largeChange - scrollBar!.value + (headerLineCount == 0 @@ -1944,8 +2116,12 @@ class PixelScrollAxis extends ScrollAxisBase { @override void onLinesInserted(int insertAt, int count) { if (distances != null) { - DistancesUtil.instance - .onInserted(distances!, scrollLinesHost!, insertAt, count); + DistancesUtil.instance.onInserted( + distances!, + scrollLinesHost!, + insertAt, + count, + ); } } @@ -1961,12 +2137,16 @@ class PixelScrollAxis extends ScrollAxisBase { /// the given lines in each region. @override List rangeToRegionPoints( - int first, int last, bool allowEstimatesForOutOfViewLines) { + int first, + int last, + bool allowEstimatesForOutOfViewLines, + ) { double p1, p2; p1 = distances!.getCumulatedDistanceAt(first); - p2 = last >= distances!.count - 1 - ? distances!.totalDistance - : distances!.getCumulatedDistanceAt(last + 1); + p2 = + last >= distances!.count - 1 + ? distances!.totalDistance + : distances!.getCumulatedDistanceAt(last + 1); final List result = []; for (int n = 0; n < 3; n++) { @@ -2005,8 +2185,12 @@ class PixelScrollAxis extends ScrollAxisBase { /// /// Returns the first and last point for the given lines in a region. @override - DoubleSpan rangeToPoints(ScrollAxisRegion region, int first, int last, - bool allowEstimatesForOutOfViewLines) { + DoubleSpan rangeToPoints( + ScrollAxisRegion region, + int first, + int last, + bool allowEstimatesForOutOfViewLines, + ) { final VisibleLinesCollection lines = getVisibleLines(); // If line is visible use already calculated values, @@ -2015,20 +2199,25 @@ class PixelScrollAxis extends ScrollAxisBase { final VisibleLineInfo? line2 = lines.getVisibleLineAtLineIndex(last); double p1, p2; - p1 = line1 == null - ? distances!.getCumulatedDistanceAt(first) - : getCumulatedOrigin(line1); + p1 = + line1 == null + ? distances!.getCumulatedDistanceAt(first) + : getCumulatedOrigin(line1); - p2 = line2 == null - ? distances!.getCumulatedDistanceAt(last + 1) - : getCumulatedCorner(line2); + p2 = + line2 == null + ? distances!.getCumulatedDistanceAt(last + 1) + : getCumulatedCorner(line2); return rangeToPointsHelper(region, p1, p2); } /// DoubleSpan rangeToPointsHelper( - ScrollAxisRegion region, double p1, double p2) { + ScrollAxisRegion region, + double p1, + double p2, + ) { final VisibleLinesCollection lines = getVisibleLines(); DoubleSpan doubleSpan = DoubleSpan.empty(); switch (region) { @@ -2071,8 +2260,10 @@ class PixelScrollAxis extends ScrollAxisBase { /// Scrolls to next page. @override void scrollToNextPage() { - scrollBar!.value += max(scrollBar!.smallChange, - scrollBar!.largeChange - scrollBar!.smallChange); + scrollBar!.value += max( + scrollBar!.smallChange, + scrollBar!.largeChange - scrollBar!.smallChange, + ); scrollToNextLine(); } @@ -2081,9 +2272,10 @@ class PixelScrollAxis extends ScrollAxisBase { void scrollToNextLine() { final double d = distances!.getNextScrollValue(scrollBar!.value); if (!d.isNaN) { - scrollBar!.value = d <= scrollBar!.value - ? distances!.getNextScrollValue(scrollBar!.value + 1) - : d; + scrollBar!.value = + d <= scrollBar!.value + ? distances!.getNextScrollValue(scrollBar!.value + 1) + : d; } else { scrollBar!.value += scrollBar!.smallChange; } @@ -2101,8 +2293,10 @@ class PixelScrollAxis extends ScrollAxisBase { /// Scrolls to previous page. @override void scrollToPreviousPage() { - scrollBar!.value -= max(scrollBar!.smallChange, - scrollBar!.largeChange - scrollBar!.smallChange); + scrollBar!.value -= max( + scrollBar!.smallChange, + scrollBar!.largeChange - scrollBar!.smallChange, + ); alignScrollLine(); } @@ -2176,7 +2370,8 @@ class PixelScrollAxis extends ScrollAxisBase { // DistanceRangeCounterCollection type. final DistanceRangeCounterCollection distance = distances! as DistanceRangeCounterCollection; - super.footerExtent = distances!.totalDistance - + super.footerExtent = + distances!.totalDistance - distance.paddingDistance - distances!.getCumulatedDistanceAt(n); } else { @@ -2191,8 +2386,9 @@ class PixelScrollAxis extends ScrollAxisBase { /// * value - _required_ - The value. @override void setHeaderLineCount(int value) { - super.headerExtent = - distances!.getCumulatedDistanceAt(min(value, distances!.count)); + super.headerExtent = distances!.getCumulatedDistanceAt( + min(value, distances!.count), + ); } /// Sets the hidden state of the lines. @@ -2208,8 +2404,10 @@ class PixelScrollAxis extends ScrollAxisBase { } else { for (int n = from; n <= to; n++) { int repeatSizeCount = -1; - final List lineSize = - getLineSizeWithTwoArgs(n, repeatSizeCount); + final List lineSize = getLineSizeWithTwoArgs( + n, + repeatSizeCount, + ); final double size = lineSize[0] as double; repeatSizeCount = lineSize[1] as int; final int rangeTo = getRangeToHelper(n, to, repeatSizeCount); @@ -2230,7 +2428,6 @@ class PixelScrollAxis extends ScrollAxisBase { if (_distances != null) { _distances!.setRange(from, to, size); } - // special case for SetLineResize when axis is nested. Parent Scroll // Axis relies on Distances.TotalDistance and this only gets updated if // we temporarily set the value in the collection. @@ -2255,8 +2452,10 @@ class PixelScrollAxis extends ScrollAxisBase { } if (_parentScrollAxis != null) { - _parentScrollAxis! - .setLineResize(startLineIndex, distances!.totalDistance); + _parentScrollAxis!.setLineResize( + startLineIndex, + distances!.totalDistance, + ); } inLineResize = false; @@ -2319,11 +2518,14 @@ class LineScrollAxis extends ScrollAxisBase { /// * scrollBar - _required_ - The state of the scrollbar. /// * scrollLinesHost - _required_ - The scroll lines host. LineScrollAxis(ScrollBarBase scrollBar, LineSizeHostBase scrollLinesHost) - : super(scrollBar, scrollLinesHost, - headerExtent: 0.0, - footerExtent: 0.0, - defaultLineSize: 0.0, - viewSize: 0.0) { + : super( + scrollBar, + scrollLinesHost, + headerExtent: 0.0, + footerExtent: 0.0, + defaultLineSize: 0.0, + viewSize: 0.0, + ) { final Object distancesHost = scrollLinesHost; if (distancesHost is DistancesHostBase) { _distances = distancesHost.distances; @@ -2467,13 +2669,18 @@ class LineScrollAxis extends ScrollAxisBase { int repeatSizeCount = -1; for (int index = 0; index < lineCount; index++) { - final List hiddenValue = - scrollLinesHost!.getHidden(index, repeatSizeCount); + final List hiddenValue = scrollLinesHost!.getHidden( + index, + repeatSizeCount, + ); final bool hide = hiddenValue[0] as bool; repeatSizeCount = hiddenValue[1] as int; final double value = hide == true ? 0.0 : 1.0; - final int rangeTo = - getRangeToHelper(index, lineCount - 1, repeatSizeCount); + final int rangeTo = getRangeToHelper( + index, + lineCount - 1, + repeatSizeCount, + ); _distances!.setRange(index, rangeTo, value); index = rangeTo; } @@ -2516,8 +2723,11 @@ class LineScrollAxis extends ScrollAxisBase { /// * isRightToLeft - _required_ - The boolean value used to calculate visible /// columns in right to left mode. @override - List getScrollLineIndex(int scrollLineIndex, double scrollLineDelta, - [bool isRightToLeft = false]) { + List getScrollLineIndex( + int scrollLineIndex, + double scrollLineDelta, [ + bool isRightToLeft = false, + ]) { scrollLineIndex = scrollBarValueToLineIndex(scrollBar!.value); scrollLineDelta = 0.0; return [scrollLineIndex, scrollLineDelta]; @@ -2544,8 +2754,10 @@ class LineScrollAxis extends ScrollAxisBase { final int to = insertAt + count - 1; int repeatSizeCount = -1; for (int index = insertAt; index <= to; index++) { - final List hiddenValue = - scrollLinesHost!.getHidden(index, repeatSizeCount); + final List hiddenValue = scrollLinesHost!.getHidden( + index, + repeatSizeCount, + ); final bool hide = hiddenValue[0] as bool; repeatSizeCount = hiddenValue[1] as int; final double value = hide == true ? 0.0 : 1.0; @@ -2565,14 +2777,25 @@ class LineScrollAxis extends ScrollAxisBase { /// /// Returns the first and last point for the given lines in a region. @override - DoubleSpan rangeToPoints(ScrollAxisRegion region, int first, int last, - bool allowEstimatesForOutOfViewLines) { + DoubleSpan rangeToPoints( + ScrollAxisRegion region, + int first, + int last, + bool allowEstimatesForOutOfViewLines, + ) { bool firstVisible = false; bool lastVisible = false; VisibleLineInfo? firstLine, lastLine; final List lineValues = getLinesAndVisibility( - first, last, true, firstVisible, lastVisible, firstLine, lastLine); + first, + last, + true, + firstVisible, + lastVisible, + firstLine, + lastLine, + ); firstVisible = lineValues[0] as bool; lastVisible = lineValues[1] as bool; firstLine = lineValues[2] as VisibleLineInfo?; @@ -2682,7 +2905,10 @@ class LineScrollAxis extends ScrollAxisBase { /// for the given lines in each region. @override List rangeToRegionPoints( - int first, int last, bool allowEstimatesForOutOfViewLines) { + int first, + int last, + bool allowEstimatesForOutOfViewLines, + ) { final List result = []; for (int n = 0; n < 3; n++) { late ScrollAxisRegion region; @@ -2694,8 +2920,10 @@ class LineScrollAxis extends ScrollAxisBase { region = ScrollAxisRegion.footer; } - result.insert(n, - rangeToPoints(region, first, last, allowEstimatesForOutOfViewLines)); + result.insert( + n, + rangeToPoints(region, first, last, allowEstimatesForOutOfViewLines), + ); } return result; @@ -2734,7 +2962,9 @@ class LineScrollAxis extends ScrollAxisBase { if (visibleScrollIndex > scrollBar!.value) { final int scrollIndexLinex = intPreviousPageLineIndex( - scrollPageSize - getLineSize(lineIndex), lineIndex); + scrollPageSize - getLineSize(lineIndex), + lineIndex, + ); visibleScrollIndex = lineIndexToScrollBarValue(scrollIndexLinex); } @@ -2788,8 +3018,10 @@ class LineScrollAxis extends ScrollAxisBase { /// * scrollLineDelta - _required_ - The scroll line delta. @override void setScrollLineIndex(int scrollLineIndex, double scrollLineDelta) { - scrollLineIndex = - min(max(_distances!.count - 1, 0), max(0, scrollLineIndex)); + scrollLineIndex = min( + max(_distances!.count - 1, 0), + max(0, scrollLineIndex), + ); scrollBar!.value = lineIndexToScrollBarValue(scrollLineIndex); resetVisibleLines(); } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scrollbar.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scrollbar.dart index 1e7b2a4f4..f3ef60523 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scrollbar.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/scrollbar.dart @@ -8,29 +8,29 @@ import 'event_args.dart'; typedef ValueChangedCallback = void Function(); /// Returns the ValueChangingArgs by used the [onValueChanging] event. -typedef ValueChangingCallback = void Function( - ValueChangingArgs valueChangingArgs); +typedef ValueChangingCallback = + void Function(ValueChangingArgs valueChangingArgs); /// Returns the PropertyChangedArgs by used the [onPropertyChanged] event. -typedef PropertyChangedCallback = void Function( - PropertyChangedArgs propertyChangedArgs); +typedef PropertyChangedCallback = + void Function(PropertyChangedArgs propertyChangedArgs); /// Defines an interface that provides all properties to configure a scrollbar. class ScrollBarBase extends ChangeNotifier { /// - ScrollBarBase( - {required bool enabled, - required double maximum, - required double minimum, - required double largeChange, - required double smallChange, - required double value}) - : _enabled = enabled, - _maximum = maximum, - _minimum = minimum, - _largeChange = largeChange, - _smallChange = smallChange, - _value = value; + ScrollBarBase({ + required bool enabled, + required double maximum, + required double minimum, + required double largeChange, + required double smallChange, + required double value, + }) : _enabled = enabled, + _maximum = maximum, + _minimum = minimum, + _largeChange = largeChange, + _smallChange = smallChange, + _value = value; /// Gets a value indicating whether the scroll bar is enabled or not. /// @@ -123,13 +123,14 @@ class ScrollBarBase extends ChangeNotifier { class ScrollInfo extends ScrollBarBase { ///Initializes a new instance of the [ScrollInfo] class. ScrollInfo() - : super( - value: 0, - minimum: 0, - maximum: 100, - smallChange: 1, - enabled: true, - largeChange: 10) { + : super( + value: 0, + minimum: 0, + maximum: 100, + smallChange: 1, + enabled: true, + largeChange: 10, + ) { _proposedLargeChange = 10; } @@ -254,8 +255,9 @@ class ScrollInfo extends ScrollBarBase { /// * propertyName - _required_ - Name of the property. void onPropertyChanged(String propertyName) { if (onPropertyChangedEvent != null) { - final PropertyChangedArgs propertyChangedArgs = - PropertyChangedArgs(propertyName); + final PropertyChangedArgs propertyChangedArgs = PropertyChangedArgs( + propertyName, + ); onPropertyChangedEvent!(propertyChangedArgs); } } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/tree_table.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/tree_table.dart index 7c15a4254..1336a7c0b 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/tree_table.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/tree_table.dart @@ -838,7 +838,9 @@ class TreeTable extends TreeTableBase { /// /// Returns the instance for the tree TreeTableEntryBase? addIfNotExists( - Comparable? key, TreeTableEntryBase? value) { + Comparable? key, + TreeTableEntryBase? value, + ) { if (!sorted) { throw Exception('This tree is not sorted.'); } @@ -1024,7 +1026,10 @@ class TreeTable extends TreeTableBase { /// TreeTableEntryBase? cacheLastFoundEntry( - TreeTableEntryBase? entry, Object? key, bool highestSmallerValue) { + TreeTableEntryBase? entry, + Object? key, + bool highestSmallerValue, + ) { lastIndex = -1; _lastFoundEntry = entry; _lastFoundEntryKey = key; @@ -1256,7 +1261,10 @@ class TreeTable extends TreeTableBase { } return cacheLastFoundEntry( - current as TreeTableEntryBase, key, highestSmallerValue); + current as TreeTableEntryBase, + key, + highestSmallerValue, + ); } else if (cmp < 0) { current = branch.left!; lastLeft = branch.left; @@ -1293,7 +1301,10 @@ class TreeTable extends TreeTableBase { } return cacheLastFoundEntry( - current as TreeTableEntryBase, key, highestSmallerValue); + current as TreeTableEntryBase, + key, + highestSmallerValue, + ); } } @@ -1510,7 +1521,8 @@ class TreeTable extends TreeTableBase { final int treeCount = getCount(); if (index < 0 || index >= treeCount) { throw ArgumentError( - 'index $index must be between 0 and ${treeCount - 1}'); + 'index $index must be between 0 and ${treeCount - 1}', + ); } if (_root == null) { @@ -1569,7 +1581,9 @@ class TreeTable extends TreeTableBase { } TreeTableNodeBase _getSisterNode( - TreeTableBranchBase leafsParent, TreeTableNodeBase node) { + TreeTableBranchBase leafsParent, + TreeTableNodeBase node, + ) { final TreeTableNodeBase? sisterNode = referenceEquals(leafsParent.left, node) ? leafsParent.right @@ -1684,8 +1698,12 @@ class TreeTable extends TreeTableBase { _lastIndexLeaf = null; } - void _replaceNode(TreeTableBranchBase? branch, TreeTableNodeBase? oldNode, - TreeTableNodeBase? newNode, bool inAddMode) { + void _replaceNode( + TreeTableBranchBase? branch, + TreeTableNodeBase? oldNode, + TreeTableNodeBase? newNode, + bool inAddMode, + ) { // also updates node count. if (referenceEquals(branch?.left, oldNode)) { branch?.setLeft(newNode, inAddMode, sorted); @@ -2334,7 +2352,8 @@ class TreeTableEntrySourceCollectionEnumerator implements EnumeratorBase { /// /// * collection - _required_ - Collection value TreeTableEntrySourceCollectionEnumerator( - TreeTableEntrySourceCollection collection) { + TreeTableEntrySourceCollection collection, + ) { inner = TreeTableEnumerator(collection.inner); } @@ -2503,7 +2522,9 @@ class TreeTableWithCounterBranch extends TreeTableWithSummaryBranch if (referenceEquals(node, right)) { return pos.combine( - getLeftNode()?.getCounterTotal(), TreeTableCounterCookies.countAll); + getLeftNode()?.getCounterTotal(), + TreeTableCounterCookies.countAll, + ); } else if (referenceEquals(node, left)) { return pos; } @@ -2768,7 +2789,7 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// * startPosition - _required_ - Sorting position /// * sorted - _required_ - Boolean value TreeTableWithCounter(TreeTableCounterBase startPosition, bool sorted) - : super(sorted) { + : super(sorted) { _startPos = startPosition; } @@ -2813,9 +2834,14 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// /// Returns an entry at the specified counter position. TreeTableWithCounterEntry? getEntryAtCounterPosition( - TreeTableCounterBase searchPosition, int cookie) => - getEntryAtCounterPositionWithForParameter( - getStartCounterPosition(), searchPosition, cookie, false); + TreeTableCounterBase searchPosition, + int cookie, + ) => getEntryAtCounterPositionWithForParameter( + getStartCounterPosition(), + searchPosition, + cookie, + false, + ); /// Gets an entry at the specified counter position. A cookie defines the /// type of counter. @@ -2827,11 +2853,15 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// /// Returns an entry at the specified counter position. TreeTableWithCounterEntry? getEntryAtCounterPositionwithThreeParameter( - TreeTableCounterBase searchPosition, - int cookie, - bool preferLeftMost) => - getEntryAtCounterPositionWithForParameter( - getStartCounterPosition(), searchPosition, cookie, preferLeftMost); + TreeTableCounterBase searchPosition, + int cookie, + bool preferLeftMost, + ) => getEntryAtCounterPositionWithForParameter( + getStartCounterPosition(), + searchPosition, + cookie, + preferLeftMost, + ); /// Gets the entry at counter position. /// @@ -2842,10 +2872,11 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// /// Returns an entry at the specified counter position. TreeTableWithCounterEntry? getEntryAtCounterPositionWithForParameter( - TreeTableCounterBase start, - TreeTableCounterBase searchPosition, - int cookie, - bool preferLeftMost) { + TreeTableCounterBase start, + TreeTableCounterBase searchPosition, + int cookie, + bool preferLeftMost, + ) { if (searchPosition.compare(getStartCounterPosition(), cookie) < 0) { throw Exception('SearchPosition'); } @@ -2860,8 +2891,14 @@ class TreeTableWithCounter extends TreeTableWithSummary { // find node final TreeTableNodeBase? currentNode = root; final TreeTableCounterBase currentNodePosition = start; - return getEntryAtCounterPositionWithSixParameter(currentNode!, start, - searchPosition, cookie, preferLeftMost, currentNodePosition); + return getEntryAtCounterPositionWithSixParameter( + currentNode!, + start, + searchPosition, + cookie, + preferLeftMost, + currentNodePosition, + ); } } @@ -2878,12 +2915,13 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// /// Returns the current node. TreeTableWithCounterEntry getEntryAtCounterPositionWithSixParameter( - TreeTableNodeBase currentNode, - TreeTableCounterBase start, - TreeTableCounterBase searchPosition, - int cookie, - bool preferLeftMost, - TreeTableCounterBase? currentNodePosition) { + TreeTableNodeBase currentNode, + TreeTableCounterBase start, + TreeTableCounterBase searchPosition, + int cookie, + bool preferLeftMost, + TreeTableCounterBase? currentNodePosition, + ) { TreeTableWithCounterBranch? savedBranch; currentNodePosition = start; while (!currentNode.isEntry()) { @@ -2891,8 +2929,8 @@ class TreeTableWithCounter extends TreeTableWithSummary { currentNode as TreeTableWithCounterBranch; final TreeTableCounterNodeBase leftB = branch.left! as TreeTableCounterNodeBase; - final TreeTableCounterBase rightNodePosition = - currentNodePosition!.combine(leftB.getCounterTotal(), cookie); + final TreeTableCounterBase rightNodePosition = currentNodePosition! + .combine(leftB.getCounterTotal(), cookie); if (searchPosition.compare(rightNodePosition, cookie) < 0) { currentNode = branch.left!; @@ -2909,12 +2947,13 @@ class TreeTableWithCounter extends TreeTableWithSummary { TreeTableCounterBase? currentNode2Position; final TreeTableNodeBase currentNode2 = getEntryAtCounterPositionWithSixParameter( - branch.left!, - currentNodePosition, - searchPosition, - cookie, - preferLeftMost, - currentNode2Position); + branch.left!, + currentNodePosition, + searchPosition, + cookie, + preferLeftMost, + currentNode2Position, + ); if (rightNodePosition.compare(currentNode2Position, cookie) == 0) { currentNode = currentNode2; currentNodePosition = currentNode2Position; @@ -2942,7 +2981,9 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// Returns the subsequent entry in the collection for which the /// specific counter is not empty. TreeTableEntryBase? getNextNotEmptyCounterEntry( - TreeTableEntryBase current, int cookie) { + TreeTableEntryBase current, + int cookie, + ) { TreeTableBranchBase? parent = current.parent; TreeTableNodeBase? next; @@ -2988,9 +3029,10 @@ class TreeTableWithCounter extends TreeTableWithSummary { final TreeTableBranchBase branch = next as TreeTableBranchBase; final TreeTableCounterNodeBase left = branch.left! as TreeTableCounterNodeBase; - next = !left.getCounterTotal()!.isEmpty(cookie) - ? branch.left - : branch.right; + next = + !left.getCounterTotal()!.isEmpty(cookie) + ? branch.left + : branch.right; } } @@ -3006,7 +3048,9 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// Returns the previous entry in the collection for which the specific /// counter is not empty. TreeTableEntryBase? getPreviousNotEmptyCounterEntry( - TreeTableEntryBase current, int cookie) { + TreeTableEntryBase current, + int cookie, + ) { TreeTableBranchBase? parent = current.parent; TreeTableNodeBase? next; @@ -3051,9 +3095,10 @@ class TreeTableWithCounter extends TreeTableWithSummary { final TreeTableBranchBase branch = next as TreeTableBranchBase; final TreeTableCounterNodeBase right = branch.right! as TreeTableCounterNodeBase; - next = !right.getCounterTotal()!.isEmpty(cookie) - ? branch.right - : branch.left; + next = + !right.getCounterTotal()!.isEmpty(cookie) + ? branch.right + : branch.left; } } @@ -3068,9 +3113,12 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// Returns the next entry in the collection for which CountVisible counter /// is not empty. TreeTableWithCounterEntry? getNextVisibleEntry( - TreeTableWithCounterEntry current) { + TreeTableWithCounterEntry current, + ) { final TreeTableEntryBase? nextCounterEntry = getNextNotEmptyCounterEntry( - current, TreeTableCounterCookies.countVisible); + current, + TreeTableCounterCookies.countVisible, + ); if (nextCounterEntry != null) { return nextCounterEntry as TreeTableWithCounterEntry; } @@ -3086,10 +3134,13 @@ class TreeTableWithCounter extends TreeTableWithSummary { /// Returns the previous entry in the collection for which CountVisible /// counter is not empty. TreeTableWithCounterEntry? getPreviousVisibleEntry( - TreeTableWithCounterEntry current) { + TreeTableWithCounterEntry current, + ) { final TreeTableEntryBase? previousCounterEntry = getPreviousNotEmptyCounterEntry( - current, TreeTableCounterCookies.countVisible); + current, + TreeTableCounterCookies.countVisible, + ); if (previousCounterEntry != null) { return previousCounterEntry as TreeTableWithCounterEntry; } @@ -3225,7 +3276,8 @@ mixin TreeTableSummaryNodeBase on TreeTableNodeBase { /// /// Returns an array of summary objects. List? getSummaries( - TreeTableEmptySummaryArraySourceBase emptySummaries); + TreeTableEmptySummaryArraySourceBase emptySummaries, + ); /// Marks all summaries dirty in this node and child nodes. /// @@ -3251,7 +3303,9 @@ abstract class TreeTableSummaryArraySourceBase { /// /// Returns An array of summary objects. List getSummaries( - TreeTableEmptySummaryArraySourceBase emptySummaries, bool changed); + TreeTableEmptySummaryArraySourceBase emptySummaries, + bool changed, + ); /// Marks all summaries dirty in this object and parent nodes. void invalidateSummariesBottomUp(); @@ -3322,14 +3376,17 @@ class TreeTableWithSummaryBranch extends TreeTableBranch /// Returns an array of summary objects. @override List? getSummaries( - TreeTableEmptySummaryArraySourceBase emptySummaries) { + TreeTableEmptySummaryArraySourceBase emptySummaries, + ) { if (tree!.isInitializing) { return null; } else if (_summaries == null) { - final List? left = - getLeftNode()?.getSummaries(emptySummaries); - final List? right = - getRightNode()?.getSummaries(emptySummaries); + final List? left = getLeftNode()?.getSummaries( + emptySummaries, + ); + final List? right = getRightNode()?.getSummaries( + emptySummaries, + ); if (left != null && right != null) { int reuseLeft = 0; int reuseRight = 0; @@ -3446,14 +3503,17 @@ class TreeTableWithSummaryEntryBase extends TreeTableEntry /// /// Returns an array of summary objects. List? onGetSummaries( - TreeTableEmptySummaryArraySourceBase emptySummaries) { + TreeTableEmptySummaryArraySourceBase emptySummaries, + ) { List? summaries; final TreeTableSummaryArraySourceBase? summaryArraySource = getSummaryArraySource(); if (summaryArraySource != null) { const bool summaryChanged = false; - summaries = - summaryArraySource.getSummaries(emptySummaries, summaryChanged); + summaries = summaryArraySource.getSummaries( + emptySummaries, + summaryChanged, + ); } return summaries; @@ -3482,8 +3542,8 @@ class TreeTableWithSummaryEntryBase extends TreeTableEntry /// Returns an array of summary objects. @override List getSummaries( - TreeTableEmptySummaryArraySourceBase emptySummaries) => - _summaries ??= onGetSummaries(emptySummaries) ?? emptySummaryArray; + TreeTableEmptySummaryArraySourceBase emptySummaries, + ) => _summaries ??= onGetSummaries(emptySummaries) ?? emptySummaryArray; /// Walks up parent branches and reset summaries. /// @@ -3554,7 +3614,8 @@ class TreeTableWithSummary extends TreeTable { /// /// Returns an array of summary objects. List? getSummaries( - TreeTableEmptySummaryArraySourceBase emptySummaries) { + TreeTableEmptySummaryArraySourceBase emptySummaries, + ) { if (root == null) { return emptySummaries.getEmptySummaries(); } diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/utility_helper.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/utility_helper.dart index 33dbdff30..40062f28e 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/utility_helper.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/utility_helper.dart @@ -61,7 +61,8 @@ class RangeValuePair implements Comparable { /// /// Returns a `string` with state information about this `object`. @override - String toString() => 'RangeValuePair Start = $start ' + String toString() => + 'RangeValuePair Start = $start ' 'Count = $count End = $end Value = $value'; } @@ -139,8 +140,13 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// void ensureCount(num index) { if (index - count > 0) { - rangeValues.add(RangeValuePair.fromRangeValuePair( - count.toInt(), index.toInt() - count.toInt(), defaultValue)); + rangeValues.add( + RangeValuePair.fromRangeValuePair( + count.toInt(), + index.toInt() - count.toInt(), + defaultValue, + ), + ); } } @@ -165,8 +171,10 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// RangeValuePair getRangeValue(int index) { - final int n = - binarySearch>(rangeValues, RangeValuePair(index)); + final int n = binarySearch>( + rangeValues, + RangeValuePair(index), + ); return rangeValues[n]; } @@ -192,8 +200,12 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// * moveRanges - _required_ - Allocate this object before a preceding /// Remove call when moving ranges. /// Otherwise specify null. - void insertWithFourArgs(num insertAt, num count, Object? value, - SortedRangeValueList? moveRanges) { + void insertWithFourArgs( + num insertAt, + num count, + Object? value, + SortedRangeValueList? moveRanges, + ) { if (insertAt >= this.count) { if (value == defaultValue && (moveRanges == null || moveRanges.count == 0)) { @@ -201,14 +213,21 @@ class SortedRangeValueList extends EnumerableGenericBase> { } ensureCount(insertAt); - rangeValues.add(RangeValuePair.fromRangeValuePair( - insertAt.toInt(), count.toInt(), value)); + rangeValues.add( + RangeValuePair.fromRangeValuePair( + insertAt.toInt(), + count.toInt(), + value, + ), + ); if (rangeValues.length >= 2) { merge(rangeValues.length - 2); } } else { int n = binarySearch>( - rangeValues, RangeValuePair(insertAt.toInt())); + rangeValues, + RangeValuePair(insertAt.toInt()), + ); final RangeValuePair rv = rangeValues[n]; if (value == (rv.value)) { rv.count += count.toInt(); @@ -217,7 +236,10 @@ class SortedRangeValueList extends EnumerableGenericBase> { n = splitWithTwoArgs(insertAt, n); split(insertAt + 1); final RangeValuePair rv2 = RangeValuePair.fromRangeValuePair( - insertAt.toInt(), count.toInt(), value); + insertAt.toInt(), + count.toInt(), + value, + ); rangeValues.insert(n, rv2); adjustStart(n + 1, count); merge(n); @@ -246,7 +268,10 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// remove call when moving ranges. /// Otherwise specify null. void insertWithThreeArgs( - num insertAt, num count, SortedRangeValueList? moveRanges) { + num insertAt, + num count, + SortedRangeValueList? moveRanges, + ) { insertWithFourArgs(insertAt, count, defaultValue, moveRanges); } @@ -287,7 +312,10 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// when moving ranges /// and pass it to a subsequent insert call. Otherwise specify null. void removeWithThreeArgs( - num removeAt, num count, SortedRangeValueList? moveRanges) { + num removeAt, + num count, + SortedRangeValueList? moveRanges, + ) { if (removeAt >= this.count) { return; } @@ -301,7 +329,10 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// num removeHelper( - int removeAt, int count, SortedRangeValueList? moveRanges) { + int removeAt, + int count, + SortedRangeValueList? moveRanges, + ) { if (removeAt >= this.count) { return rangeValues.length; } @@ -315,8 +346,13 @@ class SortedRangeValueList extends EnumerableGenericBase> { total += rv.count; deleteCount++; if (moveRanges != null && !(rv.value == defaultValue)) { - moveRanges.rangeValues.add(RangeValuePair.fromRangeValuePair( - rv.start - removeAt, rv.count, rv.value)); + moveRanges.rangeValues.add( + RangeValuePair.fromRangeValuePair( + rv.start - removeAt, + rv.count, + rv.value, + ), + ); } } @@ -337,16 +373,23 @@ class SortedRangeValueList extends EnumerableGenericBase> { /// * index - _required_ - The index for the range to be changed. /// * count - _required_ - The count. /// * value - _required_ - The value. - void setRange(int index, int count, Object value, - [bool canMergeLines = true]) { + void setRange( + int index, + int count, + Object value, [ + bool canMergeLines = true, + ]) { if (index >= this.count && value == defaultValue) { return; } ensureCount(index); final num n = removeHelper(index, count, null); - final RangeValuePair rv = - RangeValuePair.fromRangeValuePair(index, count, value); + final RangeValuePair rv = RangeValuePair.fromRangeValuePair( + index, + count, + value, + ); rangeValues.insert(n.toInt(), rv); merge(n.toInt()); @@ -374,7 +417,9 @@ class SortedRangeValueList extends EnumerableGenericBase> { return rangeValues.length; } final int n = binarySearch>( - rangeValues, RangeValuePair(index.toInt())); + rangeValues, + RangeValuePair(index.toInt()), + ); return splitWithTwoArgs(index, n); } @@ -389,8 +434,11 @@ class SortedRangeValueList extends EnumerableGenericBase> { final int count2 = rangeValues[n].count - count1; rv.count = count1; - final RangeValuePair rv2 = - RangeValuePair.fromRangeValuePair(index.toInt(), count2, rv.value); + final RangeValuePair rv2 = RangeValuePair.fromRangeValuePair( + index.toInt(), + count2, + rv.value, + ); rangeValues.insert(n + 1, rv2); return n + 1; } @@ -448,7 +496,8 @@ class SortedRangeValueList extends EnumerableGenericBase> { rangeValues[n.toInt() - 1].count++; } else { rangeValues.add( - RangeValuePair.fromRangeValuePair(index.toInt(), 1, value)); + RangeValuePair.fromRangeValuePair(index.toInt(), 1, value), + ); } } else { rangeValues[n.toInt()].value = value; diff --git a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/visible_line_info.dart b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/visible_line_info.dart index f4dd2a1b8..9301ed54d 100644 --- a/packages/syncfusion_flutter_datagrid/lib/src/grid_common/visible_line_info.dart +++ b/packages/syncfusion_flutter_datagrid/lib/src/grid_common/visible_line_info.dart @@ -17,8 +17,15 @@ class VisibleLineInfo implements Comparable { /// * scrollOffset - _required_ - The scroll offset. /// * isHeader - _required_ - if set to true line is a header. /// * isFooter - _required_ - if set to true line is a footer. - VisibleLineInfo(int visibleIndex, this.lineIndex, double size, - double clippedOrigin, double scrollOffset, bool isHeader, bool isFooter) { + VisibleLineInfo( + int visibleIndex, + this.lineIndex, + double size, + double clippedOrigin, + double scrollOffset, + bool isHeader, + bool isFooter, + ) { _visibleIndex = visibleIndex; _size = size; _clippedOrigin = clippedOrigin; @@ -200,8 +207,9 @@ class VisibleLineInfo implements Comparable { /// A strong-typed collection of `VisibleLineInfo` items. class VisibleLinesCollection extends ListBase { /// - List visibleLines = - List.empty(growable: true); + List visibleLines = List.empty( + growable: true, + ); /// VisibleLineInfoLineIndexComparer lineIndexComparer = @@ -286,7 +294,9 @@ class VisibleLinesCollection extends ListBase { final List visibleLineInfo = visibleLines as List; int index = binarySearch( - visibleLineInfo, VisibleLineInfo.fromLineIndex(lineIndex)); + visibleLineInfo, + VisibleLineInfo.fromLineIndex(lineIndex), + ); index = (index < 0) ? (~index) - 1 : index; if (index >= 0) { return this[index]; @@ -303,7 +313,9 @@ class VisibleLinesCollection extends ListBase { VisibleLineInfo? getVisibleLineAtPoint(double point) { final List visibleLineInfo = visibleLines.cast(); int index = binarySearch( - visibleLineInfo, VisibleLineInfo.fromClippedOrigin(point)); + visibleLineInfo, + VisibleLineInfo.fromClippedOrigin(point), + ); index = (index < 0) ? (~index) - 1 : index; if (index >= 0) { return this[index]; diff --git a/packages/syncfusion_flutter_datagrid/pubspec.yaml b/packages/syncfusion_flutter_datagrid/pubspec.yaml index 3838ba622..208a759d1 100644 --- a/packages/syncfusion_flutter_datagrid/pubspec.yaml +++ b/packages/syncfusion_flutter_datagrid/pubspec.yaml @@ -1,10 +1,10 @@ name: syncfusion_flutter_datagrid description: The Syncfusion Flutter DataGrid is used to display and manipulate data in a tabular view. Its rich feature set includes different types of columns, selections, column sizing, etc. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_datagrid environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_datagrid_export/CHANGELOG.md b/packages/syncfusion_flutter_datagrid_export/CHANGELOG.md index b1ab7d4d2..7f1491795 100644 --- a/packages/syncfusion_flutter_datagrid_export/CHANGELOG.md +++ b/packages/syncfusion_flutter_datagrid_export/CHANGELOG.md @@ -1,3 +1,9 @@ +## [29.1.39] - 04/22/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + ## [19.3.43-beta] - 09/30/2021 Intial release. diff --git a/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_mobile.dart b/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_mobile.dart index ca3084865..d2edbbbda 100644 --- a/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_mobile.dart +++ b/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_mobile.dart @@ -14,14 +14,14 @@ Future saveAndLaunchFile(List bytes, String fileName) async { Platform.isLinux || Platform.isWindows) { if (Platform.isAndroid) { - final Directory? directory = - await path_provider.getExternalStorageDirectory(); + final Directory? directory = await path_provider + .getExternalStorageDirectory(); if (directory != null) { path = directory.path; } } else { - final Directory directory = - await path_provider.getApplicationSupportDirectory(); + final Directory directory = await path_provider + .getApplicationSupportDirectory(); path = directory.path; } } else { @@ -29,8 +29,9 @@ Future saveAndLaunchFile(List bytes, String fileName) async { .getApplicationSupportPath(); } - final String fileLocation = - Platform.isWindows ? '$path\\$fileName' : '$path/$fileName'; + final String fileLocation = Platform.isWindows + ? '$path\\$fileName' + : '$path/$fileName'; final File file = File(fileLocation); await file.writeAsBytes(bytes, flush: true); diff --git a/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_wasm.dart b/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_wasm.dart index 67f3d9087..a996d8167 100644 --- a/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_wasm.dart +++ b/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_wasm.dart @@ -8,12 +8,12 @@ Future saveAndLaunchFile(List bytes, String fileName) async { ..style.display = 'none' ..download = fileName; -// Insert new elements in the DOM: + // Insert new elements in the DOM: web.document.body!.appendChild(anchor); -// download + // download anchor.click(); -// cleanup + // cleanup web.document.body!.removeChild(anchor); } diff --git a/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_web.dart b/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_web.dart index df1c09553..90d0e90d6 100644 --- a/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_web.dart +++ b/packages/syncfusion_flutter_datagrid_export/example/lib/helper/save_file_web.dart @@ -10,11 +10,11 @@ Future saveAndLaunchFile(List bytes, String fileName) async { ..style.display = 'none' ..download = fileName; -// Insert the new element into the DOM + // Insert the new element into the DOM document.body!.appendChild(anchor); -// Initiate the download + // Initiate the download anchor.click(); -// Clean up the DOM by removing the anchor element + // Clean up the DOM by removing the anchor element document.body!.removeChild(anchor); } diff --git a/packages/syncfusion_flutter_datagrid_export/example/lib/main.dart b/packages/syncfusion_flutter_datagrid_export/example/lib/main.dart index 2994572a1..d8d540c62 100644 --- a/packages/syncfusion_flutter_datagrid_export/example/lib/main.dart +++ b/packages/syncfusion_flutter_datagrid_export/example/lib/main.dart @@ -11,7 +11,8 @@ import 'package:syncfusion_flutter_xlsio/xlsio.dart' hide Column, Row; // Local import import 'helper/save_file_mobile.dart' if (dart.library.html) 'helper/save_file_web.dart' - if (dart.library.js_interop) 'helper/save_file_wasm.dart' as helper; + if (dart.library.js_interop) 'helper/save_file_wasm.dart' + as helper; void main() { runApp(const MyApp()); @@ -64,8 +65,9 @@ class MyHomePageState extends State { } Future _exportDataGridToPdf() async { - final PdfDocument document = - _key.currentState!.exportToPdfDocument(fitAllColumnsInOnePage: true); + final PdfDocument document = _key.currentState!.exportToPdfDocument( + fitAllColumnsInOnePage: true, + ); final List bytes = document.saveSync(); await helper.saveAndLaunchFile(bytes, 'DataGrid.pdf'); @@ -91,26 +93,30 @@ class MyHomePageState extends State { height: 40.0, width: 150.0, child: MaterialButton( - color: Colors.blue, - onPressed: _exportDataGridToExcel, - child: const Center( - child: Text( + color: Colors.blue, + onPressed: _exportDataGridToExcel, + child: const Center( + child: Text( 'Export to Excel', style: TextStyle(color: Colors.white), - ))), + ), + ), + ), ), const Padding(padding: EdgeInsets.all(20)), SizedBox( height: 40.0, width: 150.0, child: MaterialButton( - color: Colors.blue, - onPressed: _exportDataGridToPdf, - child: const Center( - child: Text( + color: Colors.blue, + onPressed: _exportDataGridToPdf, + child: const Center( + child: Text( 'Export to PDF', style: TextStyle(color: Colors.white), - ))), + ), + ), + ), ), ], ), @@ -121,34 +127,40 @@ class MyHomePageState extends State { source: _employeeDataSource, columns: [ GridColumn( - columnName: 'ID', - label: Container( - padding: const EdgeInsets.all(16.0), - alignment: Alignment.center, - child: const Text( - 'ID', - ))), + columnName: 'ID', + label: Container( + padding: const EdgeInsets.all(16.0), + alignment: Alignment.center, + child: const Text('ID'), + ), + ), GridColumn( - columnName: 'Name', - label: Container( - padding: const EdgeInsets.all(8.0), - alignment: Alignment.center, - child: const Text('Name'))), + columnName: 'Name', + label: Container( + padding: const EdgeInsets.all(8.0), + alignment: Alignment.center, + child: const Text('Name'), + ), + ), GridColumn( - columnName: 'Designation', - label: Container( - padding: const EdgeInsets.all(8.0), - alignment: Alignment.center, - child: const Text( - 'Designation', - overflow: TextOverflow.ellipsis, - ))), + columnName: 'Designation', + label: Container( + padding: const EdgeInsets.all(8.0), + alignment: Alignment.center, + child: const Text( + 'Designation', + overflow: TextOverflow.ellipsis, + ), + ), + ), GridColumn( - columnName: 'Salary', - label: Container( - padding: const EdgeInsets.all(8.0), - alignment: Alignment.center, - child: const Text('Salary'))), + columnName: 'Salary', + label: Container( + padding: const EdgeInsets.all(8.0), + alignment: Alignment.center, + child: const Text('Salary'), + ), + ), ], ), ), @@ -168,7 +180,7 @@ class MyHomePageState extends State { Employee(10007, 'Balnc', 'Developer', 15000), Employee(10008, 'Perry', 'Developer', 15000), Employee(10009, 'Gable', 'Developer', 15000), - Employee(10010, 'Grimes', 'Developer', 15000) + Employee(10010, 'Grimes', 'Developer', 15000), ]; } } @@ -198,13 +210,19 @@ class EmployeeDataSource extends DataGridSource { /// Creates the employee data source class with required details. EmployeeDataSource({required List employeeData}) { _employeeData = employeeData - .map((Employee e) => DataGridRow(cells: [ + .map( + (Employee e) => DataGridRow( + cells: [ DataGridCell(columnName: 'ID', value: e.id), DataGridCell(columnName: 'Name', value: e.name), DataGridCell( - columnName: 'Designation', value: e.designation), + columnName: 'Designation', + value: e.designation, + ), DataGridCell(columnName: 'Salary', value: e.salary), - ])) + ], + ), + ) .toList(); } @@ -216,12 +234,13 @@ class EmployeeDataSource extends DataGridSource { @override DataGridRowAdapter buildRow(DataGridRow row) { return DataGridRowAdapter( - cells: row.getCells().map((DataGridCell cell) { - return Container( - alignment: Alignment.center, - padding: const EdgeInsets.all(8.0), - child: Text(cell.value.toString()), - ); - }).toList()); + cells: row.getCells().map((DataGridCell cell) { + return Container( + alignment: Alignment.center, + padding: const EdgeInsets.all(8.0), + child: Text(cell.value.toString()), + ); + }).toList(), + ); } } diff --git a/packages/syncfusion_flutter_datagrid_export/example/pubspec.yaml b/packages/syncfusion_flutter_datagrid_export/example/pubspec.yaml index 2ae045ad5..62035a0ce 100644 --- a/packages/syncfusion_flutter_datagrid_export/example/pubspec.yaml +++ b/packages/syncfusion_flutter_datagrid_export/example/pubspec.yaml @@ -6,7 +6,7 @@ publish_to: "none" version: 1.0.0+1 environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: cupertino_icons: ^1.0.2 diff --git a/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_excel.dart b/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_excel.dart index 783d0da4a..bd5554b78 100644 --- a/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_excel.dart +++ b/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_excel.dart @@ -11,14 +11,18 @@ import 'helper.dart'; /// Signature for `cellExport` callback which is passed as an argument in /// `exportToExcelWorkbook` and `exportToExcelWorksheet` methods. -typedef DataGridCellExcelExportCallback = void Function( - DataGridCellExcelExportDetails details); +typedef DataGridCellExcelExportCallback = + void Function(DataGridCellExcelExportDetails details); /// Details for the callback that use [DataGridCellExcelExportDetails]. class DataGridCellExcelExportDetails { /// Creates the [DataGridCellExcelExportDetails]. const DataGridCellExcelExportDetails( - this.cellValue, this.columnName, this.excelRange, this.cellType); + this.cellValue, + this.columnName, + this.excelRange, + this.cellType, + ); /// The value of the cell. Typically, it is [DataGridCell.value]. final Object? cellValue; @@ -117,23 +121,32 @@ class DataGridToExcelConverter { /// Exports a column header to Excel. @protected - void exportColumnHeader(SfDataGrid dataGrid, GridColumn column, - String columnName, Worksheet worksheet) { + void exportColumnHeader( + SfDataGrid dataGrid, + GridColumn column, + String columnName, + Worksheet worksheet, + ) { Range range; int rowSpan = 0; if (exportStackedHeaders && dataGrid.stackedHeaderRows.isNotEmpty) { rowSpan = getRowSpan( - dataGrid: dataGrid, - isStackedHeader: false, - columnName: column.columnName, - rowIndex: excelRowIndex - startRowIndex - 1, - columnIndex: dataGrid.columns.indexOf(column)); + dataGrid: dataGrid, + isStackedHeader: false, + columnName: column.columnName, + rowIndex: excelRowIndex - startRowIndex - 1, + columnIndex: dataGrid.columns.indexOf(column), + ); } if (rowSpan > 0) { - range = worksheet.getRangeByIndex(excelRowIndex - rowSpan, - excelColumnIndex, excelRowIndex, excelColumnIndex); + range = worksheet.getRangeByIndex( + excelRowIndex - rowSpan, + excelColumnIndex, + excelRowIndex, + excelColumnIndex, + ); range.merge(); } else { range = worksheet.getRangeByIndex(excelRowIndex, excelColumnIndex); @@ -144,14 +157,22 @@ class DataGridToExcelConverter { ..hAlign = HAlignType.center ..vAlign = VAlignType.center; - _exportCellToExcel(worksheet, range, column, - DataGridExportCellType.columnHeader, columnName); + _exportCellToExcel( + worksheet, + range, + column, + DataGridExportCellType.columnHeader, + columnName, + ); } /// Exports all the data rows to Excel. @protected void exportRows( - SfDataGrid dataGrid, List rows, Worksheet worksheet) { + SfDataGrid dataGrid, + List rows, + Worksheet worksheet, + ) { if (rows.isEmpty) { return; } @@ -172,13 +193,24 @@ class DataGridToExcelConverter { /// Exports a [DataGridRow] to Excel. @protected - void exportRow(SfDataGrid dataGrid, DataGridRow row, GridColumn column, - Worksheet worksheet) { + void exportRow( + SfDataGrid dataGrid, + DataGridRow row, + GridColumn column, + Worksheet worksheet, + ) { final Object? cellValue = getCellValue(row, column); - final Range range = - worksheet.getRangeByIndex(excelRowIndex, excelColumnIndex); + final Range range = worksheet.getRangeByIndex( + excelRowIndex, + excelColumnIndex, + ); _exportCellToExcel( - worksheet, range, column, DataGridExportCellType.row, cellValue); + worksheet, + range, + column, + DataGridExportCellType.row, + cellValue, + ); } /// Exports all the stacked header rows to Excel. @@ -196,33 +228,48 @@ class DataGridToExcelConverter { /// Exports a stacked header row to Excel. @protected - void exportStackedHeaderRow(SfDataGrid dataGrid, - StackedHeaderRow stackedHeaderRow, Worksheet worksheet) { + void exportStackedHeaderRow( + SfDataGrid dataGrid, + StackedHeaderRow stackedHeaderRow, + Worksheet worksheet, + ) { _setRowHeight(dataGrid, DataGridExportCellType.stackedHeader, worksheet); for (final StackedHeaderCell column in stackedHeaderRow.cells) { - final List columnSequences = - getColumnSequences(dataGrid.columns, column); + final List columnSequences = getColumnSequences( + dataGrid.columns, + column, + ); for (final List indexes in getConsecutiveRanges(columnSequences)) { final int columnIndex = indexes.reduce(min); final int columnSpan = indexes.length - 1; final int rowSpan = getRowSpan( - dataGrid: dataGrid, - isStackedHeader: true, - columnIndex: columnIndex, - stackedHeaderCell: column, - rowIndex: excelRowIndex - startRowIndex - 1); + dataGrid: dataGrid, + isStackedHeader: true, + columnIndex: columnIndex, + stackedHeaderCell: column, + rowIndex: excelRowIndex - startRowIndex - 1, + ); _exportStackedHeaderCell( - dataGrid, column, columnIndex, columnSpan, rowSpan, worksheet); + dataGrid, + column, + columnIndex, + columnSpan, + rowSpan, + worksheet, + ); } } } /// Export table summary rows to the Excel. @protected - void exportTableSummaryRows(SfDataGrid dataGrid, - GridTableSummaryRowPosition position, Worksheet worksheet) { + void exportTableSummaryRows( + SfDataGrid dataGrid, + GridTableSummaryRowPosition position, + Worksheet worksheet, + ) { if (dataGrid.tableSummaryRows.isEmpty) { return; } @@ -243,8 +290,11 @@ class DataGridToExcelConverter { /// Export table summary row to the Excel. @protected - void exportTableSummaryRow(SfDataGrid dataGrid, - GridTableSummaryRow summaryRow, Worksheet worksheet) { + void exportTableSummaryRow( + SfDataGrid dataGrid, + GridTableSummaryRow summaryRow, + Worksheet worksheet, + ) { // Resets the column index when creating a new row. excelColumnIndex = startColumnIndex; @@ -252,32 +302,41 @@ class DataGridToExcelConverter { if (summaryRow.showSummaryInRow) { _exportTableSummaryCell( - sheet: worksheet, - dataGrid: dataGrid, - summaryRow: summaryRow, - columnSpan: columns.length); + sheet: worksheet, + dataGrid: dataGrid, + summaryRow: summaryRow, + columnSpan: columns.length, + ); } else { int titleColumnCount = summaryRow.titleColumnSpan; if (titleColumnCount > 0) { // To consider the exclude columns in the `titleColumnCount`. - titleColumnCount = - getTitleColumnCount(summaryRow, dataGrid.columns, excludeColumns); + titleColumnCount = getTitleColumnCount( + summaryRow, + dataGrid.columns, + excludeColumns, + ); if (titleColumnCount > 0) { _exportTableSummaryCell( - sheet: worksheet, - dataGrid: dataGrid, - summaryRow: summaryRow, - columnSpan: titleColumnCount); + sheet: worksheet, + dataGrid: dataGrid, + summaryRow: summaryRow, + columnSpan: titleColumnCount, + ); } } for (final GridSummaryColumn summaryColumn in summaryRow.columns) { final GridColumn? column = dataGrid.columns.firstWhereOrNull( - (GridColumn element) => - element.columnName == summaryColumn.columnName); + (GridColumn element) => + element.columnName == summaryColumn.columnName, + ); final int columnIndex = getSummaryColumnIndex( - dataGrid.columns, summaryColumn.columnName, excludeColumns); + dataGrid.columns, + summaryColumn.columnName, + excludeColumns, + ); // Restricts if the column doesn't exist or its column index is less // than the `titleColumnCount`. because the `titleColumn` summary cell @@ -289,12 +348,13 @@ class DataGridToExcelConverter { } _exportTableSummaryCell( - column: column, - sheet: worksheet, - dataGrid: dataGrid, - summaryRow: summaryRow, - columnIndex: columnIndex, - summaryColumn: summaryColumn); + column: column, + sheet: worksheet, + dataGrid: dataGrid, + summaryRow: summaryRow, + columnIndex: columnIndex, + summaryColumn: summaryColumn, + ); } } } @@ -303,16 +363,21 @@ class DataGridToExcelConverter { @protected Object? getCellValue(DataGridRow row, GridColumn column) { final DataGridCell cellValue = row.getCells().firstWhereOrNull( - (DataGridCell cell) => cell.columnName == column.columnName)!; + (DataGridCell cell) => cell.columnName == column.columnName, + )!; return cellValue.value; } /// Exports the [SfDataGrid] to Excel [Worksheet]. void exportToExcelWorksheet( - SfDataGrid dataGrid, List? rows, Worksheet worksheet) { + SfDataGrid dataGrid, + List? rows, + Worksheet worksheet, + ) { _columns = dataGrid.columns .where( - (GridColumn column) => !excludeColumns.contains(column.columnName)) + (GridColumn column) => !excludeColumns.contains(column.columnName), + ) .toList(); // Return if all the columns are `excludeColumns`. @@ -335,7 +400,10 @@ class DataGridToExcelConverter { // Exports the top table summary rows. if (exportTableSummaries) { exportTableSummaryRows( - dataGrid, GridTableSummaryRowPosition.top, worksheet); + dataGrid, + GridTableSummaryRowPosition.top, + worksheet, + ); } // Exports the data rows. @@ -344,7 +412,10 @@ class DataGridToExcelConverter { // Exports the bottom table summary rows. if (exportTableSummaries) { exportTableSummaryRows( - dataGrid, GridTableSummaryRowPosition.bottom, worksheet); + dataGrid, + GridTableSummaryRowPosition.bottom, + worksheet, + ); } } @@ -356,30 +427,46 @@ class DataGridToExcelConverter { return workbook; } - void _exportCellToExcel(Worksheet sheet, Range range, GridColumn column, - DataGridExportCellType cellType, Object? cellValue) { + void _exportCellToExcel( + Worksheet sheet, + Range range, + GridColumn column, + DataGridExportCellType cellType, + Object? cellValue, + ) { range.setValue(cellValue); if (cellExport != null) { final DataGridCellExcelExportDetails details = DataGridCellExcelExportDetails( - cellValue, column.columnName, range, cellType); + cellValue, + column.columnName, + range, + cellType, + ); cellExport!(details); } } - void _exportStackedHeaderCell(SfDataGrid dataGrid, StackedHeaderCell column, - int columnIndex, int columnSpan, int rowSpan, Worksheet sheet) { + void _exportStackedHeaderCell( + SfDataGrid dataGrid, + StackedHeaderCell column, + int columnIndex, + int columnSpan, + int rowSpan, + Worksheet sheet, + ) { Range range; int firstColumnIndex = startColumnIndex + columnIndex; int lastColumnIndex = firstColumnIndex + columnSpan; if (excludeColumns.isNotEmpty) { final List startAndEndIndex = getSpannedCellStartAndEndIndex( - columnSpan: columnSpan, - columnIndex: columnIndex, - columns: dataGrid.columns, - excludeColumns: excludeColumns, - startColumnIndex: startColumnIndex); + columnSpan: columnSpan, + columnIndex: columnIndex, + columns: dataGrid.columns, + excludeColumns: excludeColumns, + startColumnIndex: startColumnIndex, + ); firstColumnIndex = startAndEndIndex[0]; lastColumnIndex = startAndEndIndex[1]; @@ -388,8 +475,12 @@ class DataGridToExcelConverter { if (firstColumnIndex <= lastColumnIndex) { excelColumnIndex = firstColumnIndex; if (rowSpan > 0 || lastColumnIndex > firstColumnIndex) { - range = sheet.getRangeByIndex(excelRowIndex - rowSpan, firstColumnIndex, - excelRowIndex, lastColumnIndex); + range = sheet.getRangeByIndex( + excelRowIndex - rowSpan, + firstColumnIndex, + excelRowIndex, + lastColumnIndex, + ); range.merge(); } else { range = sheet.getRangeByIndex(excelRowIndex, firstColumnIndex); @@ -400,45 +491,68 @@ class DataGridToExcelConverter { ..hAlign = HAlignType.center ..vAlign = VAlignType.center; - _exportCellToExcel(sheet, range, dataGrid.columns[columnIndex], - DataGridExportCellType.stackedHeader, column.text); + _exportCellToExcel( + sheet, + range, + dataGrid.columns[columnIndex], + DataGridExportCellType.stackedHeader, + column.text, + ); } } - void _exportTableSummaryCell( - {int columnSpan = 0, - int columnIndex = 0, - GridColumn? column, - required Worksheet sheet, - required SfDataGrid dataGrid, - GridSummaryColumn? summaryColumn, - required GridTableSummaryRow summaryRow}) { + void _exportTableSummaryCell({ + int columnSpan = 0, + int columnIndex = 0, + GridColumn? column, + required Worksheet sheet, + required SfDataGrid dataGrid, + GridSummaryColumn? summaryColumn, + required GridTableSummaryRow summaryRow, + }) { Range range; final GridColumn? column = dataGrid.columns.firstWhereOrNull( - (GridColumn column) => column.columnName == summaryColumn?.columnName); + (GridColumn column) => column.columnName == summaryColumn?.columnName, + ); final RowColumnIndex rowColumnIndex = RowColumnIndex( - excelRowIndex - startRowIndex, - column != null ? dataGrid.columns.indexOf(column) : 0); + excelRowIndex - startRowIndex, + column != null ? dataGrid.columns.indexOf(column) : 0, + ); final String summaryValue = dataGrid.source.calculateSummaryValue( - summaryRow, summaryColumn ?? summaryRow.columns.first, rowColumnIndex); + summaryRow, + summaryColumn ?? summaryRow.columns.first, + rowColumnIndex, + ); columnIndex += startColumnIndex; excelColumnIndex = columnIndex; if (columnSpan > 0) { - range = sheet.getRangeByIndex(excelRowIndex, excelColumnIndex, - excelRowIndex, excelColumnIndex + columnSpan - 1); + range = sheet.getRangeByIndex( + excelRowIndex, + excelColumnIndex, + excelRowIndex, + excelColumnIndex + columnSpan - 1, + ); range.merge(); } else { range = sheet.getRangeByIndex(excelRowIndex, excelColumnIndex); } - _exportCellToExcel(sheet, range, column ?? dataGrid.columns[0], - DataGridExportCellType.tableSummaryRow, summaryValue); + _exportCellToExcel( + sheet, + range, + column ?? dataGrid.columns[0], + DataGridExportCellType.tableSummaryRow, + summaryValue, + ); } void _setColumnWidths( - bool exportColumnWidth, Worksheet sheet, double columnWidth) { + bool exportColumnWidth, + Worksheet sheet, + double columnWidth, + ) { excelColumnIndex = startColumnIndex; for (final GridColumn column in columns) { if (exportColumnWidth && !column.actualWidth.isNaN) { @@ -451,19 +565,24 @@ class DataGridToExcelConverter { } void _setRowHeight( - SfDataGrid dataGrid, DataGridExportCellType cellType, Worksheet sheet) { + SfDataGrid dataGrid, + DataGridExportCellType cellType, + Worksheet sheet, + ) { if (exportRowHeight) { switch (cellType) { case DataGridExportCellType.columnHeader: case DataGridExportCellType.stackedHeader: - final double height = - dataGrid.headerRowHeight.isNaN ? 56.0 : dataGrid.headerRowHeight; + final double height = dataGrid.headerRowHeight.isNaN + ? 56.0 + : dataGrid.headerRowHeight; sheet.setRowHeightInPixels(excelRowIndex, height); break; case DataGridExportCellType.row: case DataGridExportCellType.tableSummaryRow: - final double height = - dataGrid.rowHeight.isNaN ? 49.0 : dataGrid.rowHeight; + final double height = dataGrid.rowHeight.isNaN + ? 49.0 + : dataGrid.rowHeight; sheet.setRowHeightInPixels(excelRowIndex, height); break; } @@ -477,17 +596,19 @@ class DataGridToExcelConverter { /// [SfDataGrid] to Excel. extension DataGridExcelExportExtensions on SfDataGridState { // Initializes the properties to the converter. - void _initializeProperties(DataGridToExcelConverter converter, - {required int excelStartRowIndex, - required int excelStartColumnIndex, - required bool canExportStackedHeaders, - required bool canExportTableSummaries, - required bool canExportColumnWidth, - required bool canExportRowHeight, - required int columnWidth, - required int rowHeight, - required List excludeColumns, - DataGridCellExcelExportCallback? cellExport}) { + void _initializeProperties( + DataGridToExcelConverter converter, { + required int excelStartRowIndex, + required int excelStartColumnIndex, + required bool canExportStackedHeaders, + required bool canExportTableSummaries, + required bool canExportColumnWidth, + required bool canExportRowHeight, + required int columnWidth, + required int rowHeight, + required List excludeColumns, + DataGridCellExcelExportCallback? cellExport, + }) { converter ..defaultColumnWidth = columnWidth.toDouble() ..defaultRowHeight = rowHeight.toDouble() @@ -593,19 +714,21 @@ extension DataGridExcelExportExtensions on SfDataGridState { /// ); /// } /// ``` - void exportToExcelWorksheet(Worksheet worksheet, - {List? rows, - bool exportStackedHeaders = true, - bool exportTableSummaries = true, - int defaultColumnWidth = 90, - int defaultRowHeight = 49, - bool exportColumnWidth = true, - bool exportRowHeight = true, - int startColumnIndex = 1, - int startRowIndex = 1, - List excludeColumns = const [], - DataGridToExcelConverter? converter, - DataGridCellExcelExportCallback? cellExport}) { + void exportToExcelWorksheet( + Worksheet worksheet, { + List? rows, + bool exportStackedHeaders = true, + bool exportTableSummaries = true, + int defaultColumnWidth = 90, + int defaultRowHeight = 49, + bool exportColumnWidth = true, + bool exportRowHeight = true, + int startColumnIndex = 1, + int startRowIndex = 1, + List excludeColumns = const [], + DataGridToExcelConverter? converter, + DataGridCellExcelExportCallback? cellExport, + }) { converter ??= DataGridToExcelConverter(); _initializeProperties( @@ -724,19 +847,20 @@ extension DataGridExcelExportExtensions on SfDataGridState { /// ); /// } /// ``` - Workbook exportToExcelWorkbook( - {List? rows, - bool exportStackedHeaders = true, - bool exportTableSummaries = true, - int defaultColumnWidth = 90, - int defaultRowHeight = 49, - bool exportRowHeight = true, - bool exportColumnWidth = true, - int startColumnIndex = 1, - int startRowIndex = 1, - List excludeColumns = const [], - DataGridToExcelConverter? converter, - DataGridCellExcelExportCallback? cellExport}) { + Workbook exportToExcelWorkbook({ + List? rows, + bool exportStackedHeaders = true, + bool exportTableSummaries = true, + int defaultColumnWidth = 90, + int defaultRowHeight = 49, + bool exportRowHeight = true, + bool exportColumnWidth = true, + int startColumnIndex = 1, + int startRowIndex = 1, + List excludeColumns = const [], + DataGridToExcelConverter? converter, + DataGridCellExcelExportCallback? cellExport, + }) { converter ??= DataGridToExcelConverter(); _initializeProperties( diff --git a/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_pdf.dart b/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_pdf.dart index 5b1eb5c49..99d4cdfa6 100644 --- a/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_pdf.dart +++ b/packages/syncfusion_flutter_datagrid_export/lib/src/export_to_pdf.dart @@ -14,16 +14,18 @@ import 'helper.dart'; extension DataGridPdfExportExtensions on SfDataGridState { // Initializes the properties to the converter. - void _initializeProperties(DataGridToPdfConverter converter, - {required bool canRepeatHeaders, - required bool exportStackedHeaders, - required bool fitAllColumnsInOnePage, - required List excludeColumns, - required bool autoColumnWidth, - required bool exportTableSummaries, - int rowIndex = 0, - DataGridCellPdfExportCallback? cellExport, - DataGridPdfHeaderFooterExportCallback? headerFooterExport}) { + void _initializeProperties( + DataGridToPdfConverter converter, { + required bool canRepeatHeaders, + required bool exportStackedHeaders, + required bool fitAllColumnsInOnePage, + required List excludeColumns, + required bool autoColumnWidth, + required bool exportTableSummaries, + int rowIndex = 0, + DataGridCellPdfExportCallback? cellExport, + DataGridPdfHeaderFooterExportCallback? headerFooterExport, + }) { converter ..canRepeatHeaders = canRepeatHeaders ..exportStackedHeaders = exportStackedHeaders @@ -133,27 +135,30 @@ extension DataGridPdfExportExtensions on SfDataGridState { /// ); /// } /// ``` - PdfDocument exportToPdfDocument( - {List? rows, - bool exportStackedHeaders = true, - bool canRepeatHeaders = true, - bool fitAllColumnsInOnePage = false, - bool autoColumnWidth = true, - bool exportTableSummaries = true, - List excludeColumns = const [], - DataGridToPdfConverter? converter, - DataGridCellPdfExportCallback? cellExport, - DataGridPdfHeaderFooterExportCallback? headerFooterExport}) { + PdfDocument exportToPdfDocument({ + List? rows, + bool exportStackedHeaders = true, + bool canRepeatHeaders = true, + bool fitAllColumnsInOnePage = false, + bool autoColumnWidth = true, + bool exportTableSummaries = true, + List excludeColumns = const [], + DataGridToPdfConverter? converter, + DataGridCellPdfExportCallback? cellExport, + DataGridPdfHeaderFooterExportCallback? headerFooterExport, + }) { converter ??= DataGridToPdfConverter(); - _initializeProperties(converter, - autoColumnWidth: autoColumnWidth, - fitAllColumnsInOnePage: fitAllColumnsInOnePage, - canRepeatHeaders: canRepeatHeaders, - exportStackedHeaders: exportStackedHeaders, - cellExport: cellExport, - headerFooterExport: headerFooterExport, - excludeColumns: excludeColumns, - exportTableSummaries: exportTableSummaries); + _initializeProperties( + converter, + autoColumnWidth: autoColumnWidth, + fitAllColumnsInOnePage: fitAllColumnsInOnePage, + canRepeatHeaders: canRepeatHeaders, + exportStackedHeaders: exportStackedHeaders, + cellExport: cellExport, + headerFooterExport: headerFooterExport, + excludeColumns: excludeColumns, + exportTableSummaries: exportTableSummaries, + ); return converter.exportToPdfDocument(widget, rows); } @@ -256,25 +261,28 @@ extension DataGridPdfExportExtensions on SfDataGridState { /// ); /// } /// ``` - PdfGrid exportToPdfGrid( - {List? rows, - bool exportStackedHeaders = true, - bool canRepeatHeaders = true, - bool fitAllColumnsInOnePage = false, - bool autoColumnWidth = true, - bool exportTableSummaries = true, - List excludeColumns = const [], - DataGridToPdfConverter? converter, - DataGridCellPdfExportCallback? cellExport}) { + PdfGrid exportToPdfGrid({ + List? rows, + bool exportStackedHeaders = true, + bool canRepeatHeaders = true, + bool fitAllColumnsInOnePage = false, + bool autoColumnWidth = true, + bool exportTableSummaries = true, + List excludeColumns = const [], + DataGridToPdfConverter? converter, + DataGridCellPdfExportCallback? cellExport, + }) { converter ??= DataGridToPdfConverter(); - _initializeProperties(converter, - autoColumnWidth: autoColumnWidth, - fitAllColumnsInOnePage: fitAllColumnsInOnePage, - canRepeatHeaders: canRepeatHeaders, - cellExport: cellExport, - exportStackedHeaders: exportStackedHeaders, - excludeColumns: excludeColumns, - exportTableSummaries: exportTableSummaries); + _initializeProperties( + converter, + autoColumnWidth: autoColumnWidth, + fitAllColumnsInOnePage: fitAllColumnsInOnePage, + canRepeatHeaders: canRepeatHeaders, + cellExport: cellExport, + exportStackedHeaders: exportStackedHeaders, + excludeColumns: excludeColumns, + exportTableSummaries: exportTableSummaries, + ); return converter.exportToPdfGrid(widget, rows); } @@ -335,7 +343,10 @@ class DataGridToPdfConverter { /// Exports the column headers to Pdf. @protected void exportColumnHeaders( - SfDataGrid dataGrid, List columns, PdfGrid pdfGrid) { + SfDataGrid dataGrid, + List columns, + PdfGrid pdfGrid, + ) { if (columns.isEmpty) { return; } @@ -348,19 +359,24 @@ class DataGridToPdfConverter { /// Exports a column header to Pdf @protected - void exportColumnHeader(SfDataGrid dataGrid, GridColumn column, - String columnName, PdfGrid pdfGrid) { + void exportColumnHeader( + SfDataGrid dataGrid, + GridColumn column, + String columnName, + PdfGrid pdfGrid, + ) { int rowSpan = 0; PdfGridRow columnHeader = pdfGrid.headers[rowIndex]; PdfGridCell pdfCell = columnHeader.cells[_columnIndex]; if (dataGrid.stackedHeaderRows.isNotEmpty && exportStackedHeaders) { rowSpan = getRowSpan( - dataGrid: dataGrid, - isStackedHeader: false, - columnName: column.columnName, - rowIndex: rowIndex - 1, - columnIndex: dataGrid.columns.indexOf(column)); + dataGrid: dataGrid, + isStackedHeader: false, + columnName: column.columnName, + rowIndex: rowIndex - 1, + columnIndex: dataGrid.columns.indexOf(column), + ); } if (rowSpan > 0) { // Retrieve the header cell at the given index by subtracting the number of rows @@ -374,13 +390,20 @@ class DataGridToPdfConverter { } pdfCell.style.borders.all = _pdfPen; _exportCellToPdf( - DataGridExportCellType.columnHeader, pdfCell, columnName, column); + DataGridExportCellType.columnHeader, + pdfCell, + columnName, + column, + ); } /// Exports all the data rows to Pdf. @protected void exportRows( - List columns, List rows, PdfGrid pdfGrid) { + List columns, + List rows, + PdfGrid pdfGrid, + ) { for (final DataGridRow row in rows) { exportRow(columns, row, pdfGrid); rowIndex++; @@ -407,7 +430,9 @@ class DataGridToPdfConverter { /// /// If the `rows` is set, the given list of DataGridRow collection is exported. Typically, you can set this property to export PdfDocument exportToPdfDocument( - SfDataGrid dataGrid, List? rows) { + SfDataGrid dataGrid, + List? rows, + ) { final PdfDocument pdfDocument = PdfDocument(); //adding page into pdf document @@ -443,7 +468,8 @@ class DataGridToPdfConverter { //final List columns = dataGrid.columns; _columns = dataGrid.columns .where( - (GridColumn column) => !excludeColumns.contains(column.columnName)) + (GridColumn column) => !excludeColumns.contains(column.columnName), + ) .toList(); //if fit all columns in one page is false then horizontal overflow is true and type is next page @@ -480,7 +506,10 @@ class DataGridToPdfConverter { // Exports the top table summary rows. if (exportTableSummaries) { exportTableSummaryRows( - dataGrid, GridTableSummaryRowPosition.top, pdfGrid); + dataGrid, + GridTableSummaryRowPosition.top, + pdfGrid, + ); } //Export the rows @@ -489,7 +518,10 @@ class DataGridToPdfConverter { // Exports the bottom table summary rows. if (exportTableSummaries) { exportTableSummaryRows( - dataGrid, GridTableSummaryRowPosition.bottom, pdfGrid); + dataGrid, + GridTableSummaryRowPosition.bottom, + pdfGrid, + ); } //Can Repeate header for all pages @@ -520,30 +552,48 @@ class DataGridToPdfConverter { /// Exports a stacked header row to Pdf. @protected void exportStackedHeaderRow( - SfDataGrid dataGrid, StackedHeaderRow stackedHeaderRow, PdfGrid pdfGrid) { + SfDataGrid dataGrid, + StackedHeaderRow stackedHeaderRow, + PdfGrid pdfGrid, + ) { for (final StackedHeaderCell column in stackedHeaderRow.cells) { int columnSpanValue = 0; - final List columnSequences = - getColumnSequences(dataGrid.columns, column); + final List columnSequences = getColumnSequences( + dataGrid.columns, + column, + ); for (final List indexes in getConsecutiveRanges(columnSequences)) { _columnIndex = indexes.reduce(min); columnSpanValue = indexes.length; final int rowSpan = getRowSpan( - dataGrid: dataGrid, - isStackedHeader: true, - columnIndex: _columnIndex, - stackedHeaderCell: column, - rowIndex: rowIndex - 1); + dataGrid: dataGrid, + isStackedHeader: true, + columnIndex: _columnIndex, + stackedHeaderCell: column, + rowIndex: rowIndex - 1, + ); _exportStackedHeaderCell( - dataGrid, column, _columnIndex, columnSpanValue, rowSpan, pdfGrid); + dataGrid, + column, + _columnIndex, + columnSpanValue, + rowSpan, + pdfGrid, + ); } } } /// Exports a stacked header cell to Pdf. - void _exportStackedHeaderCell(SfDataGrid dataGrid, StackedHeaderCell column, - int columnIndex, int columnSpan, int rowSpan, PdfGrid pdfGrid) { + void _exportStackedHeaderCell( + SfDataGrid dataGrid, + StackedHeaderCell column, + int columnIndex, + int columnSpan, + int rowSpan, + PdfGrid pdfGrid, + ) { PdfGridRow stakedHeaderRow = pdfGrid.headers[rowIndex]; int firstColumnIndex = columnIndex; @@ -551,11 +601,12 @@ class DataGridToPdfConverter { if (excludeColumns.isNotEmpty) { final List startAndEndIndex = getSpannedCellStartAndEndIndex( - columnSpan: columnSpan - 1, - columnIndex: columnIndex, - columns: dataGrid.columns, - excludeColumns: excludeColumns, - startColumnIndex: 0); + columnSpan: columnSpan - 1, + columnIndex: columnIndex, + columns: dataGrid.columns, + excludeColumns: excludeColumns, + startColumnIndex: 0, + ); firstColumnIndex = startAndEndIndex[0]; lastColumnIndex = startAndEndIndex[1]; @@ -576,15 +627,20 @@ class DataGridToPdfConverter { } pdfCell.style.borders.all = _pdfPen; - _exportCellToPdf(DataGridExportCellType.stackedHeader, pdfCell, - pdfCell.value, dataGrid.columns[firstColumnIndex]); + _exportCellToPdf( + DataGridExportCellType.stackedHeader, + pdfCell, + pdfCell.value, + dataGrid.columns[firstColumnIndex], + ); } /// Gets the cell value required for data rows. @protected Object? getCellValue(GridColumn column, DataGridRow row) { final DataGridCell cellValue = row.getCells().firstWhereOrNull( - (DataGridCell element) => element.columnName == column.columnName)!; + (DataGridCell element) => element.columnName == column.columnName, + )!; return cellValue.value; } @@ -596,13 +652,19 @@ class DataGridToPdfConverter { ) { if (cellExport != null) { final DataGridCellPdfExportDetails details = DataGridCellPdfExportDetails( - cellType, pdfCell, cellValue, column.columnName); + cellType, + pdfCell, + cellValue, + column.columnName, + ); cellExport!(details); } } void _exportHeaderFooter( - PdfPage pdfPage, PdfDocumentTemplate pdfDocumentTemplate) { + PdfPage pdfPage, + PdfDocumentTemplate pdfDocumentTemplate, + ) { if (headerFooterExport != null) { final DataGridPdfHeaderFooterExportDetails details = DataGridPdfHeaderFooterExportDetails(pdfPage, pdfDocumentTemplate); @@ -612,8 +674,11 @@ class DataGridToPdfConverter { /// Export table summary rows to the Excel. @protected - void exportTableSummaryRows(SfDataGrid dataGrid, - GridTableSummaryRowPosition position, PdfGrid pdfGrid) { + void exportTableSummaryRows( + SfDataGrid dataGrid, + GridTableSummaryRowPosition position, + PdfGrid pdfGrid, + ) { if (dataGrid.tableSummaryRows.isEmpty) { return; } @@ -636,40 +701,52 @@ class DataGridToPdfConverter { /// Export table summary row to the Excel. @protected void exportTableSummaryRow( - SfDataGrid dataGrid, GridTableSummaryRow summaryRow, PdfGrid pdfGrid) { + SfDataGrid dataGrid, + GridTableSummaryRow summaryRow, + PdfGrid pdfGrid, + ) { final PdfGridRow tableSummaryRow = pdfGrid.rows.add(); // Resets the column index when creating a new row. _columnIndex = 0; if (summaryRow.showSummaryInRow) { _exportTableSummaryCell( - pdfGrid: pdfGrid, - dataGrid: dataGrid, - summaryRow: summaryRow, - columnSpan: columns.length, - tableSummaryRow: tableSummaryRow); + pdfGrid: pdfGrid, + dataGrid: dataGrid, + summaryRow: summaryRow, + columnSpan: columns.length, + tableSummaryRow: tableSummaryRow, + ); } else { int titleColumnCount = summaryRow.titleColumnSpan; if (titleColumnCount > 0) { // To consider the exclude columns in the `titleColumnCount`. - titleColumnCount = - getTitleColumnCount(summaryRow, dataGrid.columns, excludeColumns); + titleColumnCount = getTitleColumnCount( + summaryRow, + dataGrid.columns, + excludeColumns, + ); if (titleColumnCount > 0) { _exportTableSummaryCell( - pdfGrid: pdfGrid, - dataGrid: dataGrid, - summaryRow: summaryRow, - columnSpan: titleColumnCount, - tableSummaryRow: tableSummaryRow); + pdfGrid: pdfGrid, + dataGrid: dataGrid, + summaryRow: summaryRow, + columnSpan: titleColumnCount, + tableSummaryRow: tableSummaryRow, + ); } } for (final GridSummaryColumn summaryColumn in summaryRow.columns) { final GridColumn? column = dataGrid.columns.firstWhereOrNull( - (GridColumn element) => - element.columnName == summaryColumn.columnName); + (GridColumn element) => + element.columnName == summaryColumn.columnName, + ); final int summaryColumnIndex = getSummaryColumnIndex( - dataGrid.columns, summaryColumn.columnName, excludeColumns); + dataGrid.columns, + summaryColumn.columnName, + excludeColumns, + ); // Restricts if the column doesn't exist or its column index is less // than the `titleColumnCount`. because the `titleColumn` summary cell @@ -679,33 +756,41 @@ class DataGridToPdfConverter { } _exportTableSummaryCell( - column: column, - pdfGrid: pdfGrid, - dataGrid: dataGrid, - summaryRow: summaryRow, - startColumnIndex: summaryColumnIndex, - summaryColumn: summaryColumn, - tableSummaryRow: tableSummaryRow); + column: column, + pdfGrid: pdfGrid, + dataGrid: dataGrid, + summaryRow: summaryRow, + startColumnIndex: summaryColumnIndex, + summaryColumn: summaryColumn, + tableSummaryRow: tableSummaryRow, + ); } } } - void _exportTableSummaryCell( - {int columnSpan = 0, - int startColumnIndex = 0, - GridColumn? column, - required PdfGrid pdfGrid, - required SfDataGrid dataGrid, - GridSummaryColumn? summaryColumn, - PdfGridRow? tableSummaryRow, - required GridTableSummaryRow summaryRow}) { + void _exportTableSummaryCell({ + int columnSpan = 0, + int startColumnIndex = 0, + GridColumn? column, + required PdfGrid pdfGrid, + required SfDataGrid dataGrid, + GridSummaryColumn? summaryColumn, + PdfGridRow? tableSummaryRow, + required GridTableSummaryRow summaryRow, + }) { final GridColumn? column = dataGrid.columns.firstWhereOrNull( - (GridColumn column) => column.columnName == summaryColumn?.columnName); + (GridColumn column) => column.columnName == summaryColumn?.columnName, + ); final RowColumnIndex rowColumnIndex = RowColumnIndex( - rowIndex, column != null ? dataGrid.columns.indexOf(column) : 0); + rowIndex, + column != null ? dataGrid.columns.indexOf(column) : 0, + ); final String summaryValue = dataGrid.source.calculateSummaryValue( - summaryRow, summaryColumn ?? summaryRow.columns.first, rowColumnIndex); + summaryRow, + summaryColumn ?? summaryRow.columns.first, + rowColumnIndex, + ); PdfGridCell pdfCell = tableSummaryRow!.cells[startColumnIndex]; if (columnSpan > 0) { @@ -720,8 +805,12 @@ class DataGridToPdfConverter { for (int i = 0; i < tableSummaryRow.cells.count; i++) { tableSummaryRow.cells[i].style.borders.all = _pdfPen; } - _exportCellToPdf(DataGridExportCellType.tableSummaryRow, pdfCell, - pdfCell.value, column ?? dataGrid.columns[0]); + _exportCellToPdf( + DataGridExportCellType.tableSummaryRow, + pdfCell, + pdfCell.value, + column ?? dataGrid.columns[0], + ); } } @@ -729,7 +818,11 @@ class DataGridToPdfConverter { class DataGridCellPdfExportDetails { ///the callback event [DataGridCellPdfExportDetails] const DataGridCellPdfExportDetails( - this.cellType, this.pdfCell, this.cellValue, this.columnName); + this.cellType, + this.pdfCell, + this.cellValue, + this.columnName, + ); /// The type of the cell. final DataGridExportCellType cellType; @@ -758,10 +851,10 @@ class DataGridPdfHeaderFooterExportDetails { /// Signature for `cellExport` callback which is passed as an argument in /// `exportToPdfGrid` and `exportToPdfDocument` methods. -typedef DataGridCellPdfExportCallback = void Function( - DataGridCellPdfExportDetails details); +typedef DataGridCellPdfExportCallback = + void Function(DataGridCellPdfExportDetails details); /// Signature for `headerFooterExport` callback which is passed as an argument /// `exportToPdfGrid` and `exportToPdfDocument` methods. -typedef DataGridPdfHeaderFooterExportCallback = void Function( - DataGridPdfHeaderFooterExportDetails details); +typedef DataGridPdfHeaderFooterExportCallback = + void Function(DataGridPdfHeaderFooterExportDetails details); diff --git a/packages/syncfusion_flutter_datagrid_export/lib/src/helper.dart b/packages/syncfusion_flutter_datagrid_export/lib/src/helper.dart index ed214eb91..857a17b1b 100644 --- a/packages/syncfusion_flutter_datagrid_export/lib/src/helper.dart +++ b/packages/syncfusion_flutter_datagrid_export/lib/src/helper.dart @@ -12,7 +12,8 @@ List getColumnSequences(List columns, StackedHeaderCell cell) { if (cell.columnNames.isNotEmpty) { for (final String columnName in cell.columnNames) { final GridColumn? column = columns.firstWhereOrNull( - (GridColumn column) => column.columnName == columnName); + (GridColumn column) => column.columnName == columnName, + ); if (column != null) { childSequences.add(columns.indexOf(column)); } @@ -49,19 +50,22 @@ List> getConsecutiveRanges(List columnIndexes) { } /// Returns the row span to the stacked header and column header row. -int getRowSpan( - {String? columnName, - required int rowIndex, - required int columnIndex, - required bool isStackedHeader, - required SfDataGrid dataGrid, - StackedHeaderCell? stackedHeaderCell}) { +int getRowSpan({ + String? columnName, + required int rowIndex, + required int columnIndex, + required bool isStackedHeader, + required SfDataGrid dataGrid, + StackedHeaderCell? stackedHeaderCell, +}) { int startIndex = 0, endIndex = 0, rowSpan = 0; if (isStackedHeader && stackedHeaderCell != null) { final List> columnIndexes = getConsecutiveRanges( - getColumnSequences(dataGrid.columns, stackedHeaderCell)); - final List? spannedColumn = columnIndexes - .singleWhereOrNull((List column) => column.first == columnIndex); + getColumnSequences(dataGrid.columns, stackedHeaderCell), + ); + final List? spannedColumn = columnIndexes.singleWhereOrNull( + (List column) => column.first == columnIndex, + ); if (spannedColumn != null) { startIndex = spannedColumn.reduce(min); endIndex = startIndex + spannedColumn.length - 1; @@ -78,7 +82,8 @@ int getRowSpan( for (final StackedHeaderCell stackedColumn in stackedHeaderRow.cells) { if (isStackedHeader) { final List> columnIndexes = getConsecutiveRanges( - getColumnSequences(dataGrid.columns, stackedColumn)); + getColumnSequences(dataGrid.columns, stackedColumn), + ); for (final List column in columnIndexes) { if ((startIndex >= column.first && startIndex <= column.last) || (endIndex >= column.first && endIndex <= column.last)) { @@ -104,12 +109,13 @@ int getRowSpan( /// Returns the start and end index of the given spanned columns when the /// exclude columns are applied. -List getSpannedCellStartAndEndIndex( - {required int columnSpan, - required int columnIndex, - required int startColumnIndex, - required List columns, - required List excludeColumns}) { +List getSpannedCellStartAndEndIndex({ + required int columnSpan, + required int columnIndex, + required int startColumnIndex, + required List columns, + required List excludeColumns, +}) { int excludeColumnsCount = 0; int firstColumnIndex = startColumnIndex + columnIndex; int lastColumnIndex = firstColumnIndex + columnSpan; @@ -117,7 +123,8 @@ List getSpannedCellStartAndEndIndex( for (final String columnName in excludeColumns) { final GridColumn? column = columns.firstWhereOrNull( - (GridColumn element) => element.columnName == columnName); + (GridColumn element) => element.columnName == columnName, + ); if (column != null) { excludeColumnIndexes.add(columns.indexOf(column)); } @@ -126,19 +133,26 @@ List getSpannedCellStartAndEndIndex( if (firstColumnIndex > startColumnIndex) { // Updates the first and last column index if any exclude column exists // before the `firstColumnIndex`. - excludeColumnsCount = - excludeColumnIndexes.where((int index) => index < columnIndex).length; - - firstColumnIndex = - max(startColumnIndex, firstColumnIndex - excludeColumnsCount); - lastColumnIndex = - max(startColumnIndex, lastColumnIndex - excludeColumnsCount); + excludeColumnsCount = excludeColumnIndexes + .where((int index) => index < columnIndex) + .length; + + firstColumnIndex = max( + startColumnIndex, + firstColumnIndex - excludeColumnsCount, + ); + lastColumnIndex = max( + startColumnIndex, + lastColumnIndex - excludeColumnsCount, + ); } // To remove the in-between excluded columns from the `lastColumnIndex`. excludeColumnsCount = excludeColumnIndexes - .where((int index) => - index >= columnIndex && index <= columnIndex + columnSpan) + .where( + (int index) => + index >= columnIndex && index <= columnIndex + columnSpan, + ) .length; lastColumnIndex -= excludeColumnsCount; @@ -148,8 +162,11 @@ List getSpannedCellStartAndEndIndex( /// ----------------- Table summary row helper methods -------------------// /// Gets title column count of the given summary column. -int getTitleColumnCount(GridTableSummaryRow summaryRow, - List columns, List excludeColumns) { +int getTitleColumnCount( + GridTableSummaryRow summaryRow, + List columns, + List excludeColumns, +) { int currentColumnSpan = 0; for (int i = 0; i < summaryRow.titleColumnSpan; i++) { if (i <= columns.length) { @@ -163,7 +180,10 @@ int getTitleColumnCount(GridTableSummaryRow summaryRow, /// Returns the column index to the summary column. int getSummaryColumnIndex( - List columns, String columnName, List excludeColumns) { + List columns, + String columnName, + List excludeColumns, +) { if (excludeColumns.contains(columnName)) { return -1; } @@ -172,6 +192,7 @@ int getSummaryColumnIndex( .where((GridColumn column) => !excludeColumns.contains(column.columnName)) .toList(); final GridColumn? column = visibleColumns.firstWhereOrNull( - (GridColumn element) => element.columnName == columnName); + (GridColumn element) => element.columnName == columnName, + ); return column != null ? visibleColumns.indexOf(column) : -1; } diff --git a/packages/syncfusion_flutter_datagrid_export/pubspec.yaml b/packages/syncfusion_flutter_datagrid_export/pubspec.yaml index 8ce138505..79995a53f 100644 --- a/packages/syncfusion_flutter_datagrid_export/pubspec.yaml +++ b/packages/syncfusion_flutter_datagrid_export/pubspec.yaml @@ -1,10 +1,10 @@ name: syncfusion_flutter_datagrid_export description: The Syncfusion Flutter DataGrid Export library is used to export the DataGrid content to Excel and Pdf format with several customization options. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_datagrid_export environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 flutter: ">=1.17.0" dependencies: diff --git a/packages/syncfusion_flutter_datepicker/CHANGELOG.md b/packages/syncfusion_flutter_datepicker/CHANGELOG.md index 68581d4d8..8d3bb272c 100644 --- a/packages/syncfusion_flutter_datepicker/CHANGELOG.md +++ b/packages/syncfusion_flutter_datepicker/CHANGELOG.md @@ -1,4 +1,10 @@ -## Unreleased +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 **General** diff --git a/packages/syncfusion_flutter_datepicker/assets/fonts/Roboto-Medium.ttf b/packages/syncfusion_flutter_datepicker/assets/fonts/Roboto-Medium.ttf new file mode 100644 index 000000000..d629e9848 Binary files /dev/null and b/packages/syncfusion_flutter_datepicker/assets/fonts/Roboto-Medium.ttf differ diff --git a/packages/syncfusion_flutter_datepicker/example/lib/main.dart b/packages/syncfusion_flutter_datepicker/example/lib/main.dart index d03c6d18d..ec86cd975 100644 --- a/packages/syncfusion_flutter_datepicker/example/lib/main.dart +++ b/packages/syncfusion_flutter_datepicker/example/lib/main.dart @@ -39,7 +39,8 @@ class MyAppState extends State { /// multi range. setState(() { if (args.value is PickerDateRange) { - _range = '${DateFormat('dd/MM/yyyy').format(args.value.startDate)} -' + _range = + '${DateFormat('dd/MM/yyyy').format(args.value.startDate)} -' // ignore: lines_longer_than_80_chars ' ${DateFormat('dd/MM/yyyy').format(args.value.endDate ?? args.value.startDate)}'; } else if (args.value is DateTime) { @@ -55,43 +56,44 @@ class MyAppState extends State { @override Widget build(BuildContext context) { return MaterialApp( - home: Scaffold( - appBar: AppBar( - title: const Text('DatePicker demo'), + home: Scaffold( + appBar: AppBar(title: const Text('DatePicker demo')), + body: Stack( + children: [ + Positioned( + left: 0, + right: 0, + top: 0, + height: 80, + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Selected date: $_selectedDate'), + Text('Selected date count: $_dateCount'), + Text('Selected range: $_range'), + Text('Selected ranges count: $_rangeCount'), + ], + ), ), - body: Stack( - children: [ - Positioned( - left: 0, - right: 0, - top: 0, - height: 80, - child: Column( - mainAxisAlignment: MainAxisAlignment.spaceEvenly, - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text('Selected date: $_selectedDate'), - Text('Selected date count: $_dateCount'), - Text('Selected range: $_range'), - Text('Selected ranges count: $_rangeCount') - ], - ), + Positioned( + left: 0, + top: 80, + right: 0, + bottom: 0, + child: SfDateRangePicker( + onSelectionChanged: _onSelectionChanged, + selectionMode: DateRangePickerSelectionMode.range, + initialSelectedRange: PickerDateRange( + DateTime.now().subtract(const Duration(days: 4)), + DateTime.now().add(const Duration(days: 3)), ), - Positioned( - left: 0, - top: 80, - right: 0, - bottom: 0, - child: SfDateRangePicker( - onSelectionChanged: _onSelectionChanged, - selectionMode: DateRangePickerSelectionMode.range, - initialSelectedRange: PickerDateRange( - DateTime.now().subtract(const Duration(days: 4)), - DateTime.now().add(const Duration(days: 3))), - ), - ) - ], - ))); + ), + ), + ], + ), + ), + ); } } diff --git a/packages/syncfusion_flutter_datepicker/example/pubspec.yaml b/packages/syncfusion_flutter_datepicker/example/pubspec.yaml index c8419b953..f38896994 100644 --- a/packages/syncfusion_flutter_datepicker/example/pubspec.yaml +++ b/packages/syncfusion_flutter_datepicker/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Syncfusion date picker example project version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker.dart index 0911429b7..13feb9021 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker.dart @@ -17,8 +17,8 @@ import 'theme.dart'; import 'year_view.dart'; /// Signature for callback that reports that the picker state value changed. -typedef UpdatePickerState = void Function( - PickerStateArgs updatePickerStateDetails); +typedef UpdatePickerState = + void Function(PickerStateArgs updatePickerStateDetails); /// Signature for callback that reports that a current view or current visible /// date range changes. @@ -31,8 +31,10 @@ typedef UpdatePickerState = void Function( /// See also: /// * [SfDateRangePicker.onViewChanged], which matches this signature. /// * [SfDateRangePicker], which uses this signature in one of it's callback. -typedef DateRangePickerViewChangedCallback = void Function( - DateRangePickerViewChangedArgs dateRangePickerViewChangedArgs); +typedef DateRangePickerViewChangedCallback = + void Function( + DateRangePickerViewChangedArgs dateRangePickerViewChangedArgs, + ); /// Signature for callback that reports that a current view or current visible /// date range changes. @@ -46,8 +48,10 @@ typedef DateRangePickerViewChangedCallback = void Function( /// * [SfHijriDateRangePicker.onViewChanged], which matches this signature. /// * [SfHijriDateRangePicker], which uses this signature in one of it's /// callback. -typedef HijriDatePickerViewChangedCallback = void Function( - HijriDatePickerViewChangedArgs hijriDatePickerViewChangedArgs); +typedef HijriDatePickerViewChangedCallback = + void Function( + HijriDatePickerViewChangedArgs hijriDatePickerViewChangedArgs, + ); /// Signature for callback that reports that a new dates or date ranges /// selected. @@ -64,30 +68,39 @@ typedef HijriDatePickerViewChangedCallback = void Function( /// * [SfDateRangePicker], which uses this signature in one of it's callback. /// * [SfHijriDateRangePicker], which uses this signature in one of it's /// callback. -typedef DateRangePickerSelectionChangedCallback = void Function( - DateRangePickerSelectionChangedArgs dateRangePickerSelectionChangedArgs); +typedef DateRangePickerSelectionChangedCallback = + void Function( + DateRangePickerSelectionChangedArgs dateRangePickerSelectionChangedArgs, + ); // method that raise the picker selection changed call back with the given // parameters. -void _raiseSelectionChangedCallback(_SfDateRangePicker picker, - {dynamic value}) { +void _raiseSelectionChangedCallback( + _SfDateRangePicker picker, { + dynamic value, +}) { picker.onSelectionChanged?.call(DateRangePickerSelectionChangedArgs(value)); } // method that raises the visible dates changed call back with the given // parameters. -void _raisePickerViewChangedCallback(_SfDateRangePicker picker, - {dynamic visibleDateRange, dynamic view}) { +void _raisePickerViewChangedCallback( + _SfDateRangePicker picker, { + dynamic visibleDateRange, + dynamic view, +}) { if (picker.onViewChanged == null) { return; } if (picker.isHijri) { - picker - .onViewChanged(HijriDatePickerViewChangedArgs(visibleDateRange, view)); + picker.onViewChanged( + HijriDatePickerViewChangedArgs(visibleDateRange, view), + ); } else { - picker - .onViewChanged(DateRangePickerViewChangedArgs(visibleDateRange, view)); + picker.onViewChanged( + DateRangePickerViewChangedArgs(visibleDateRange, view), + ); } } @@ -199,87 +212,90 @@ class SfDateRangePicker extends StatelessWidget { /// /// When the visible view changes, the widget will call the [onViewChanged] /// callback with the current view and the current view visible dates. - SfDateRangePicker( - {Key? key, - DateRangePickerView view = DateRangePickerView.month, - this.selectionMode = DateRangePickerSelectionMode.single, - this.headerHeight = 40, - this.todayHighlightColor, - this.backgroundColor, - DateTime? initialSelectedDate, - List? initialSelectedDates, - PickerDateRange? initialSelectedRange, - List? initialSelectedRanges, - this.toggleDaySelection = false, - this.enablePastDates = true, - this.showNavigationArrow = false, - this.confirmText = 'OK', - this.cancelText = 'CANCEL', - this.showActionButtons = false, - this.selectionShape = DateRangePickerSelectionShape.circle, - this.navigationDirection = DateRangePickerNavigationDirection.horizontal, - this.allowViewNavigation = true, - this.navigationMode = DateRangePickerNavigationMode.snap, - this.enableMultiView = false, - this.controller, - this.onViewChanged, - this.onSelectionChanged, - this.onCancel, - this.onSubmit, - this.headerStyle = const DateRangePickerHeaderStyle(), - this.yearCellStyle = const DateRangePickerYearCellStyle(), - this.monthViewSettings = const DateRangePickerMonthViewSettings(), - this.monthCellStyle = const DateRangePickerMonthCellStyle(), - DateTime? minDate, - DateTime? maxDate, - DateTime? initialDisplayDate, - double viewSpacing = 20, - this.selectionRadius = -1, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectionTextStyle, - this.rangeTextStyle, - this.monthFormat, - this.cellBuilder, - this.showTodayButton = false, - this.selectableDayPredicate, - this.extendableRangeSelectionDirection = - ExtendableRangeSelectionDirection.both}) - : assert(headerHeight >= -1), - assert(minDate == null || - maxDate == null || - minDate.isBefore(maxDate) || - minDate == maxDate), - assert(viewSpacing >= 0), - initialSelectedDate = - controller != null && controller.selectedDate != null - ? controller.selectedDate - : initialSelectedDate, - initialSelectedDates = - controller != null && controller.selectedDates != null - ? controller.selectedDates - : initialSelectedDates, - initialSelectedRange = - controller != null && controller.selectedRange != null - ? controller.selectedRange - : initialSelectedRange, - initialSelectedRanges = - controller != null && controller.selectedRanges != null - ? controller.selectedRanges - : initialSelectedRanges, - view = controller != null && controller.view != null - ? controller.view! - : view, - initialDisplayDate = - controller != null && controller.displayDate != null - ? controller.displayDate! - : initialDisplayDate ?? DateTime.now(), - minDate = minDate ?? DateTime(1900), - maxDate = maxDate ?? DateTime(2100, 12, 31), - viewSpacing = enableMultiView ? viewSpacing : 0, - super(key: key); + SfDateRangePicker({ + Key? key, + DateRangePickerView view = DateRangePickerView.month, + this.selectionMode = DateRangePickerSelectionMode.single, + this.headerHeight = 40, + this.todayHighlightColor, + this.backgroundColor, + DateTime? initialSelectedDate, + List? initialSelectedDates, + PickerDateRange? initialSelectedRange, + List? initialSelectedRanges, + this.toggleDaySelection = false, + this.enablePastDates = true, + this.showNavigationArrow = false, + this.confirmText = 'OK', + this.cancelText = 'CANCEL', + this.showActionButtons = false, + this.selectionShape = DateRangePickerSelectionShape.circle, + this.navigationDirection = DateRangePickerNavigationDirection.horizontal, + this.allowViewNavigation = true, + this.navigationMode = DateRangePickerNavigationMode.snap, + this.enableMultiView = false, + this.controller, + this.onViewChanged, + this.onSelectionChanged, + this.onCancel, + this.onSubmit, + this.headerStyle = const DateRangePickerHeaderStyle(), + this.yearCellStyle = const DateRangePickerYearCellStyle(), + this.monthViewSettings = const DateRangePickerMonthViewSettings(), + this.monthCellStyle = const DateRangePickerMonthCellStyle(), + DateTime? minDate, + DateTime? maxDate, + DateTime? initialDisplayDate, + double viewSpacing = 20, + this.selectionRadius = -1, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectionTextStyle, + this.rangeTextStyle, + this.monthFormat, + this.cellBuilder, + this.showTodayButton = false, + this.selectableDayPredicate, + this.extendableRangeSelectionDirection = + ExtendableRangeSelectionDirection.both, + }) : assert(headerHeight >= -1), + assert( + minDate == null || + maxDate == null || + minDate.isBefore(maxDate) || + minDate == maxDate, + ), + assert(viewSpacing >= 0), + initialSelectedDate = + controller != null && controller.selectedDate != null + ? controller.selectedDate + : initialSelectedDate, + initialSelectedDates = + controller != null && controller.selectedDates != null + ? controller.selectedDates + : initialSelectedDates, + initialSelectedRange = + controller != null && controller.selectedRange != null + ? controller.selectedRange + : initialSelectedRange, + initialSelectedRanges = + controller != null && controller.selectedRanges != null + ? controller.selectedRanges + : initialSelectedRanges, + view = + controller != null && controller.view != null + ? controller.view! + : view, + initialDisplayDate = + controller != null && controller.displayDate != null + ? controller.displayDate! + : initialDisplayDate ?? DateTime.now(), + minDate = minDate ?? DateTime(1900), + maxDate = maxDate ?? DateTime(2100, 12, 31), + viewSpacing = enableMultiView ? viewSpacing : 0, + super(key: key); /// Defines the view for the [SfDateRangePicker]. /// @@ -2666,14 +2682,30 @@ class SfDateRangePicker extends StatelessWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty('view', view)); - properties.add(EnumProperty( - 'selectionMode', selectionMode)); - properties.add(EnumProperty( - 'selectionShape', selectionShape)); - properties.add(EnumProperty( - 'navigationDirection', navigationDirection)); - properties.add(EnumProperty( - 'navigationMode', navigationMode)); + properties.add( + EnumProperty( + 'selectionMode', + selectionMode, + ), + ); + properties.add( + EnumProperty( + 'selectionShape', + selectionShape, + ), + ); + properties.add( + EnumProperty( + 'navigationDirection', + navigationDirection, + ), + ); + properties.add( + EnumProperty( + 'navigationMode', + navigationMode, + ), + ); properties.add(DoubleProperty('headerHeight', headerHeight)); properties.add(DoubleProperty('viewSpacing', viewSpacing)); properties.add(DoubleProperty('selectionRadius', selectionRadius)); @@ -2681,68 +2713,112 @@ class SfDateRangePicker extends StatelessWidget { properties.add(ColorProperty('backgroundColor', backgroundColor)); properties.add(ColorProperty('selectionColor', selectionColor)); properties.add( - ColorProperty('startRangeSelectionColor', startRangeSelectionColor)); - properties - .add(ColorProperty('endRangeSelectionColor', endRangeSelectionColor)); + ColorProperty('startRangeSelectionColor', startRangeSelectionColor), + ); + properties.add( + ColorProperty('endRangeSelectionColor', endRangeSelectionColor), + ); properties.add(ColorProperty('rangeSelectionColor', rangeSelectionColor)); properties.add(StringProperty('monthFormat', monthFormat)); - properties.add(DiagnosticsProperty( - 'selectionTextStyle', selectionTextStyle)); - properties - .add(DiagnosticsProperty('rangeTextStyle', rangeTextStyle)); - properties.add(DiagnosticsProperty( - 'initialDisplayDate', initialDisplayDate)); - properties.add(DiagnosticsProperty( - 'initialSelectedDate', initialSelectedDate)); - properties.add(IterableDiagnostics(initialSelectedDates) - .toDiagnosticsNode(name: 'initialSelectedDates')); - properties.add(DiagnosticsProperty( - 'initialSelectedRange', initialSelectedRange)); - properties.add(IterableDiagnostics(initialSelectedRanges) - .toDiagnosticsNode(name: 'initialSelectedRanges')); + properties.add( + DiagnosticsProperty('selectionTextStyle', selectionTextStyle), + ); + properties.add( + DiagnosticsProperty('rangeTextStyle', rangeTextStyle), + ); + properties.add( + DiagnosticsProperty('initialDisplayDate', initialDisplayDate), + ); + properties.add( + DiagnosticsProperty('initialSelectedDate', initialSelectedDate), + ); + properties.add( + IterableDiagnostics( + initialSelectedDates, + ).toDiagnosticsNode(name: 'initialSelectedDates'), + ); + properties.add( + DiagnosticsProperty( + 'initialSelectedRange', + initialSelectedRange, + ), + ); + properties.add( + IterableDiagnostics( + initialSelectedRanges, + ).toDiagnosticsNode(name: 'initialSelectedRanges'), + ); properties.add(DiagnosticsProperty('minDate', minDate)); properties.add(DiagnosticsProperty('maxDate', maxDate)); - properties.add(DiagnosticsProperty( - 'cellBuilder', cellBuilder)); properties.add( - DiagnosticsProperty('allowViewNavigation', allowViewNavigation)); + DiagnosticsProperty( + 'cellBuilder', + cellBuilder, + ), + ); + properties.add( + DiagnosticsProperty('allowViewNavigation', allowViewNavigation), + ); + properties.add( + DiagnosticsProperty('toggleDaySelection', toggleDaySelection), + ); + properties.add( + DiagnosticsProperty('enablePastDates', enablePastDates), + ); properties.add( - DiagnosticsProperty('toggleDaySelection', toggleDaySelection)); - properties - .add(DiagnosticsProperty('enablePastDates', enablePastDates)); + DiagnosticsProperty('showNavigationArrow', showNavigationArrow), + ); properties.add( - DiagnosticsProperty('showNavigationArrow', showNavigationArrow)); - properties - .add(DiagnosticsProperty('showActionButtons', showActionButtons)); + DiagnosticsProperty('showActionButtons', showActionButtons), + ); properties.add(StringProperty('cancelText', cancelText)); properties.add(StringProperty('confirmText', confirmText)); - properties - .add(DiagnosticsProperty('enableMultiView', enableMultiView)); - properties.add(DiagnosticsProperty( - 'onViewChanged', onViewChanged)); - properties.add(DiagnosticsProperty( - 'onSelectionChanged', onSelectionChanged)); + properties.add( + DiagnosticsProperty('enableMultiView', enableMultiView), + ); + properties.add( + DiagnosticsProperty( + 'onViewChanged', + onViewChanged, + ), + ); + properties.add( + DiagnosticsProperty( + 'onSelectionChanged', + onSelectionChanged, + ), + ); properties.add(DiagnosticsProperty('onCancel', onCancel)); properties.add(DiagnosticsProperty('onSubmit', onSubmit)); - properties.add(DiagnosticsProperty( - 'controller', controller)); + properties.add( + DiagnosticsProperty('controller', controller), + ); properties.add(headerStyle.toDiagnosticsNode(name: 'headerStyle')); properties.add(yearCellStyle.toDiagnosticsNode(name: 'yearCellStyle')); - properties - .add(monthViewSettings.toDiagnosticsNode(name: 'monthViewSettings')); + properties.add( + monthViewSettings.toDiagnosticsNode(name: 'monthViewSettings'), + ); properties.add(monthCellStyle.toDiagnosticsNode(name: 'monthCellStyle')); - properties - .add(DiagnosticsProperty('showTodayButton', showTodayButton)); - properties.add(DiagnosticsProperty( - 'selectableDayPredicate', selectableDayPredicate)); - properties.add(EnumProperty( + properties.add( + DiagnosticsProperty('showTodayButton', showTodayButton), + ); + properties.add( + DiagnosticsProperty( + 'selectableDayPredicate', + selectableDayPredicate, + ), + ); + properties.add( + EnumProperty( 'extendableRangeSelectionDirection', - extendableRangeSelectionDirection)); + extendableRangeSelectionDirection, + ), + ); } } @@ -2899,33 +2975,34 @@ class SfHijriDateRangePicker extends StatelessWidget { this.selectableDayPredicate, this.extendableRangeSelectionDirection = ExtendableRangeSelectionDirection.both, - }) : initialSelectedDate = - controller != null && controller.selectedDate != null - ? controller.selectedDate - : initialSelectedDate, - initialSelectedDates = - controller != null && controller.selectedDates != null - ? controller.selectedDates - : initialSelectedDates, - initialSelectedRange = - controller != null && controller.selectedRange != null - ? controller.selectedRange - : initialSelectedRange, - initialSelectedRanges = - controller != null && controller.selectedRanges != null - ? controller.selectedRanges - : initialSelectedRanges, - view = controller != null && controller.view != null - ? controller.view! - : view, - initialDisplayDate = - controller != null && controller.displayDate != null - ? controller.displayDate! - : initialDisplayDate ?? HijriDateTime.now(), - minDate = minDate ?? HijriDateTime(1356, 01, 01), - maxDate = maxDate ?? HijriDateTime(1499, 12, 30), - viewSpacing = enableMultiView ? viewSpacing : 0, - super(key: key); + }) : initialSelectedDate = + controller != null && controller.selectedDate != null + ? controller.selectedDate + : initialSelectedDate, + initialSelectedDates = + controller != null && controller.selectedDates != null + ? controller.selectedDates + : initialSelectedDates, + initialSelectedRange = + controller != null && controller.selectedRange != null + ? controller.selectedRange + : initialSelectedRange, + initialSelectedRanges = + controller != null && controller.selectedRanges != null + ? controller.selectedRanges + : initialSelectedRanges, + view = + controller != null && controller.view != null + ? controller.view! + : view, + initialDisplayDate = + controller != null && controller.displayDate != null + ? controller.displayDate! + : initialDisplayDate ?? HijriDateTime.now(), + minDate = minDate ?? HijriDateTime(1356, 01, 01), + maxDate = maxDate ?? HijriDateTime(1499, 12, 30), + viewSpacing = enableMultiView ? viewSpacing : 0, + super(key: key); /// Defines the view for the [SfHijriDateRangePicker]. /// @@ -5307,14 +5384,30 @@ class SfHijriDateRangePicker extends StatelessWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty('view', view)); - properties.add(EnumProperty( - 'selectionMode', selectionMode)); - properties.add(EnumProperty( - 'selectionShape', selectionShape)); - properties.add(EnumProperty( - 'navigationDirection', navigationDirection)); - properties.add(EnumProperty( - 'navigationMode', navigationMode)); + properties.add( + EnumProperty( + 'selectionMode', + selectionMode, + ), + ); + properties.add( + EnumProperty( + 'selectionShape', + selectionShape, + ), + ); + properties.add( + EnumProperty( + 'navigationDirection', + navigationDirection, + ), + ); + properties.add( + EnumProperty( + 'navigationMode', + navigationMode, + ), + ); properties.add(DoubleProperty('headerHeight', headerHeight)); properties.add(DoubleProperty('viewSpacing', viewSpacing)); properties.add(DoubleProperty('selectionRadius', selectionRadius)); @@ -5322,123 +5415,173 @@ class SfHijriDateRangePicker extends StatelessWidget { properties.add(ColorProperty('backgroundColor', backgroundColor)); properties.add(ColorProperty('selectionColor', selectionColor)); properties.add( - ColorProperty('startRangeSelectionColor', startRangeSelectionColor)); - properties - .add(ColorProperty('endRangeSelectionColor', endRangeSelectionColor)); + ColorProperty('startRangeSelectionColor', startRangeSelectionColor), + ); + properties.add( + ColorProperty('endRangeSelectionColor', endRangeSelectionColor), + ); properties.add(ColorProperty('rangeSelectionColor', rangeSelectionColor)); properties.add(StringProperty('monthFormat', monthFormat)); - properties.add(DiagnosticsProperty( - 'selectionTextStyle', selectionTextStyle)); - properties - .add(DiagnosticsProperty('rangeTextStyle', rangeTextStyle)); - properties.add(DiagnosticsProperty( - 'initialDisplayDate', initialDisplayDate)); - properties.add(DiagnosticsProperty( - 'initialSelectedDate', initialSelectedDate)); - properties.add(IterableDiagnostics(initialSelectedDates) - .toDiagnosticsNode(name: 'initialSelectedDates')); - properties.add(DiagnosticsProperty( - 'HijriDateRange', initialSelectedRange)); - properties.add(IterableDiagnostics(initialSelectedRanges) - .toDiagnosticsNode(name: 'initialSelectedRanges')); + properties.add( + DiagnosticsProperty('selectionTextStyle', selectionTextStyle), + ); + properties.add( + DiagnosticsProperty('rangeTextStyle', rangeTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'initialDisplayDate', + initialDisplayDate, + ), + ); + properties.add( + DiagnosticsProperty( + 'initialSelectedDate', + initialSelectedDate, + ), + ); + properties.add( + IterableDiagnostics( + initialSelectedDates, + ).toDiagnosticsNode(name: 'initialSelectedDates'), + ); + properties.add( + DiagnosticsProperty( + 'HijriDateRange', + initialSelectedRange, + ), + ); + properties.add( + IterableDiagnostics( + initialSelectedRanges, + ).toDiagnosticsNode(name: 'initialSelectedRanges'), + ); properties.add(DiagnosticsProperty('minDate', minDate)); properties.add(DiagnosticsProperty('maxDate', maxDate)); - properties.add(DiagnosticsProperty( - 'cellBuilder', cellBuilder)); properties.add( - DiagnosticsProperty('allowViewNavigation', allowViewNavigation)); + DiagnosticsProperty( + 'cellBuilder', + cellBuilder, + ), + ); + properties.add( + DiagnosticsProperty('allowViewNavigation', allowViewNavigation), + ); + properties.add( + DiagnosticsProperty('toggleDaySelection', toggleDaySelection), + ); + properties.add( + DiagnosticsProperty('enablePastDates', enablePastDates), + ); properties.add( - DiagnosticsProperty('toggleDaySelection', toggleDaySelection)); - properties - .add(DiagnosticsProperty('enablePastDates', enablePastDates)); + DiagnosticsProperty('showNavigationArrow', showNavigationArrow), + ); properties.add( - DiagnosticsProperty('showNavigationArrow', showNavigationArrow)); - properties - .add(DiagnosticsProperty('showActionButtons', showActionButtons)); + DiagnosticsProperty('showActionButtons', showActionButtons), + ); properties.add(StringProperty('cancelText', cancelText)); properties.add(StringProperty('confirmText', confirmText)); - properties - .add(DiagnosticsProperty('enableMultiView', enableMultiView)); - properties.add(DiagnosticsProperty( - 'onViewChanged', onViewChanged)); - properties.add(DiagnosticsProperty( - 'onSelectionChanged', onSelectionChanged)); + properties.add( + DiagnosticsProperty('enableMultiView', enableMultiView), + ); + properties.add( + DiagnosticsProperty( + 'onViewChanged', + onViewChanged, + ), + ); + properties.add( + DiagnosticsProperty( + 'onSelectionChanged', + onSelectionChanged, + ), + ); properties.add(DiagnosticsProperty('onCancel', onCancel)); properties.add(DiagnosticsProperty('onSubmit', onSubmit)); - properties.add(DiagnosticsProperty( - 'controller', controller)); + properties.add( + DiagnosticsProperty('controller', controller), + ); properties.add(headerStyle.toDiagnosticsNode(name: 'headerStyle')); properties.add(yearCellStyle.toDiagnosticsNode(name: 'yearCellStyle')); - properties - .add(monthViewSettings.toDiagnosticsNode(name: 'monthViewSettings')); + properties.add( + monthViewSettings.toDiagnosticsNode(name: 'monthViewSettings'), + ); properties.add(monthCellStyle.toDiagnosticsNode(name: 'monthCellStyle')); - properties - .add(DiagnosticsProperty('showTodayButton', showTodayButton)); - properties.add(DiagnosticsProperty( - 'selectableDayPredicate', selectableDayPredicate)); - properties.add(EnumProperty( + properties.add( + DiagnosticsProperty('showTodayButton', showTodayButton), + ); + properties.add( + DiagnosticsProperty( + 'selectableDayPredicate', + selectableDayPredicate, + ), + ); + properties.add( + EnumProperty( 'extendableRangeSelectionDirection', - extendableRangeSelectionDirection)); + extendableRangeSelectionDirection, + ), + ); } } @immutable class _SfDateRangePicker extends StatefulWidget { - const _SfDateRangePicker( - {Key? key, - required this.view, - required this.selectionMode, - this.isHijri = false, - required this.headerHeight, - this.todayHighlightColor, - this.backgroundColor, - this.initialSelectedDate, - this.initialSelectedDates, - this.initialSelectedRange, - this.initialSelectedRanges, - this.toggleDaySelection = false, - this.enablePastDates = true, - this.showNavigationArrow = false, - required this.selectionShape, - required this.navigationDirection, - this.controller, - this.onViewChanged, - this.onSelectionChanged, - this.onCancel, - this.onSubmit, - required this.headerStyle, - required this.yearCellStyle, - required this.monthViewSettings, - required this.initialDisplayDate, - this.confirmText = 'OK', - this.cancelText = 'CANCEL', - this.showActionButtons = false, - required this.minDate, - required this.maxDate, - required this.monthCellStyle, - this.allowViewNavigation = true, - this.enableMultiView = false, - required this.navigationMode, - required this.viewSpacing, - required this.selectionRadius, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectionTextStyle, - this.rangeTextStyle, - this.monthFormat, - this.cellBuilder, - this.showTodayButton = false, - this.selectableDayPredicate, - this.extendableRangeSelectionDirection = - ExtendableRangeSelectionDirection.both}) - : super(key: key); + const _SfDateRangePicker({ + Key? key, + required this.view, + required this.selectionMode, + this.isHijri = false, + required this.headerHeight, + this.todayHighlightColor, + this.backgroundColor, + this.initialSelectedDate, + this.initialSelectedDates, + this.initialSelectedRange, + this.initialSelectedRanges, + this.toggleDaySelection = false, + this.enablePastDates = true, + this.showNavigationArrow = false, + required this.selectionShape, + required this.navigationDirection, + this.controller, + this.onViewChanged, + this.onSelectionChanged, + this.onCancel, + this.onSubmit, + required this.headerStyle, + required this.yearCellStyle, + required this.monthViewSettings, + required this.initialDisplayDate, + this.confirmText = 'OK', + this.cancelText = 'CANCEL', + this.showActionButtons = false, + required this.minDate, + required this.maxDate, + required this.monthCellStyle, + this.allowViewNavigation = true, + this.enableMultiView = false, + required this.navigationMode, + required this.viewSpacing, + required this.selectionRadius, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectionTextStyle, + this.rangeTextStyle, + this.monthFormat, + this.cellBuilder, + this.showTodayButton = false, + this.selectableDayPredicate, + this.extendableRangeSelectionDirection = + ExtendableRangeSelectionDirection.both, + }) : super(key: key); final DateRangePickerView view; @@ -5610,19 +5753,24 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _updateSelectionValues(); _view = DateRangePickerHelper.getPickerView(_controller.view); _updateCurrentVisibleDates(); - _headerVisibleDates = - ValueNotifier>(_currentViewVisibleDates); - _viewHeaderVisibleDates = - ValueNotifier>(_currentViewVisibleDates); + _headerVisibleDates = ValueNotifier>( + _currentViewVisibleDates, + ); + _viewHeaderVisibleDates = ValueNotifier>( + _currentViewVisibleDates, + ); _controller.addPropertyChangedListener(_pickerValueChangedListener); - _previousSelectedValue = PickerStateArgs() - ..selectedDate = _controller.selectedDate - ..selectedDates = - DateRangePickerHelper.cloneList(_controller.selectedDates) - ..selectedRange = _controller.selectedRange - ..selectedRanges = - DateRangePickerHelper.cloneList(_controller.selectedRanges); + _previousSelectedValue = + PickerStateArgs() + ..selectedDate = _controller.selectedDate + ..selectedDates = DateRangePickerHelper.cloneList( + _controller.selectedDates, + ) + ..selectedRange = _controller.selectedRange + ..selectedRanges = DateRangePickerHelper.cloneList( + _controller.selectedRanges, + ); super.initState(); } @@ -5639,52 +5787,57 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _locale = Localizations.localeOf(context); _localizations = SfLocalizations.of(context); _isRtl = direction == TextDirection.rtl; - _isMobilePlatform = - DateRangePickerHelper.isMobileLayout(Theme.of(context).platform); + _isMobilePlatform = DateRangePickerHelper.isMobileLayout( + Theme.of(context).platform, + ); _fadeInController ??= AnimationController( - duration: Duration(milliseconds: _isMobilePlatform ? 500 : 600), - vsync: this) - ..addListener(_updateFadeAnimation); - _fadeIn ??= Tween( - begin: 0.1, - end: 1, - ).animate(CurvedAnimation( - parent: _fadeInController!, - curve: Curves.easeIn, - )); + duration: Duration(milliseconds: _isMobilePlatform ? 500 : 600), + vsync: this, + )..addListener(_updateFadeAnimation); + _fadeIn ??= Tween(begin: 0.1, end: 1).animate( + CurvedAnimation(parent: _fadeInController!, curve: Curves.easeIn), + ); super.didChangeDependencies(); } @override void didUpdateWidget(_SfDateRangePicker oldWidget) { if (oldWidget.controller != widget.controller) { - oldWidget.controller - ?.removePropertyChangedListener(_pickerValueChangedListener); + oldWidget.controller?.removePropertyChangedListener( + _pickerValueChangedListener, + ); _controller.removePropertyChangedListener(_pickerValueChangedListener); if (widget.controller != null) { _controller = widget.controller; _controller.selectedDates = _getSelectedDates( - DateRangePickerHelper.cloneList(widget.controller!.selectedDates)); + DateRangePickerHelper.cloneList(widget.controller!.selectedDates), + ); _controller.selectedRanges = _getSelectedRanges( - DateRangePickerHelper.cloneList(widget.controller!.selectedRanges)); + DateRangePickerHelper.cloneList(widget.controller!.selectedRanges), + ); _controller.displayDate ??= _currentDate; _currentDate = getValidDate( - widget.minDate, widget.maxDate, _controller.displayDate); + widget.minDate, + widget.maxDate, + _controller.displayDate, + ); } else { _initPickerController(); } - _controller.view ??= widget.isHijri - ? DateRangePickerHelper.getHijriPickerView(_view) - : DateRangePickerHelper.getPickerView(_view); + _controller.view ??= + widget.isHijri + ? DateRangePickerHelper.getHijriPickerView(_view) + : DateRangePickerHelper.getPickerView(_view); _controller.addPropertyChangedListener(_pickerValueChangedListener); _initNavigation(); _updateSelectionValues(); _view = DateRangePickerHelper.getPickerView(_controller.view); } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(_controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + _controller.view, + ); if (view == DateRangePickerView.month && oldWidget.monthViewSettings.firstDayOfWeek != widget.monthViewSettings.firstDayOfWeek) { @@ -5733,13 +5886,16 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> /// confirmed value so store the confirmed selected values when show /// action buttons enabled. if (widget.showActionButtons) { - _previousSelectedValue = PickerStateArgs() - ..selectedDate = _controller.selectedDate - ..selectedDates = - DateRangePickerHelper.cloneList(_controller.selectedDates) - ..selectedRange = _controller.selectedRange - ..selectedRanges = - DateRangePickerHelper.cloneList(_controller.selectedRanges); + _previousSelectedValue = + PickerStateArgs() + ..selectedDate = _controller.selectedDate + ..selectedDates = DateRangePickerHelper.cloneList( + _controller.selectedDates, + ) + ..selectedRange = _controller.selectedRange + ..selectedRanges = DateRangePickerHelper.cloneList( + _controller.selectedRanges, + ); } } @@ -5774,9 +5930,13 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> if (!widget.isHijri && DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri) != + widget.monthViewSettings, + widget.isHijri, + ) != DateRangePickerHelper.getNumberOfWeeksInView( - oldWidget.monthViewSettings, oldWidget.isHijri)) { + oldWidget.monthViewSettings, + oldWidget.isHijri, + )) { _currentDate = _updateCurrentDate(oldWidget); _controller.displayDate = _currentDate; } @@ -5793,8 +5953,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> if (oldWidget.controller?.selectedDates != widget.controller?.selectedDates) { - _selectedDates = - DateRangePickerHelper.cloneList(_controller.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _controller.selectedDates, + ); } if (oldWidget.controller?.selectedRange != @@ -5804,8 +5965,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> if (oldWidget.controller?.selectedRanges != widget.controller?.selectedRanges) { - _selectedRanges = - DateRangePickerHelper.cloneList(_controller.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _controller.selectedRanges, + ); } if (oldWidget.controller?.view != widget.controller?.view) { @@ -5816,8 +5978,11 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> if (oldWidget.controller?.displayDate != widget.controller?.displayDate && widget.controller?.displayDate != null) { - _currentDate = - getValidDate(widget.minDate, widget.maxDate, _controller.displayDate); + _currentDate = getValidDate( + widget.minDate, + widget.maxDate, + _controller.displayDate, + ); _controller.displayDate = _currentDate; } @@ -5827,46 +5992,57 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> @override Widget build(BuildContext context) { _datePickerTheme = _getPickerThemeData( - SfDateRangePickerTheme.of(context), Theme.of(context)); + SfDateRangePickerTheme.of(context), + Theme.of(context), + ); double top = 0, height; return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - final double? previousWidth = _minWidth; - final double? previousHeight = _minHeight; - _minWidth = constraints.maxWidth == double.infinity - ? _minPickerWidth - : constraints.maxWidth; - _minHeight = constraints.maxHeight == double.infinity - ? _minPickerHeight - : constraints.maxHeight; - - final double actionButtonsHeight = - (widget.showActionButtons || widget.showTodayButton) - ? _minHeight! * 0.1 < 50 - ? 50 - : _minHeight! * 0.1 - : 0; - _handleScrollViewSizeChanged(_minHeight!, _minWidth!, previousHeight, - previousWidth, actionButtonsHeight); + builder: (BuildContext context, BoxConstraints constraints) { + final double? previousWidth = _minWidth; + final double? previousHeight = _minHeight; + _minWidth = + constraints.maxWidth == double.infinity + ? _minPickerWidth + : constraints.maxWidth; + _minHeight = + constraints.maxHeight == double.infinity + ? _minPickerHeight + : constraints.maxHeight; + + final double actionButtonsHeight = + (widget.showActionButtons || widget.showTodayButton) + ? _minHeight! * 0.1 < 50 + ? 50 + : _minHeight! * 0.1 + : 0; + _handleScrollViewSizeChanged( + _minHeight!, + _minWidth!, + previousHeight, + previousWidth, + actionButtonsHeight, + ); - height = _minHeight! - widget.headerHeight; - top = widget.headerHeight; - if (_view == DateRangePickerView.month && - widget.navigationDirection == - DateRangePickerNavigationDirection.vertical) { - height -= widget.monthViewSettings.viewHeaderHeight; - top += widget.monthViewSettings.viewHeaderHeight; - } + height = _minHeight! - widget.headerHeight; + top = widget.headerHeight; + if (_view == DateRangePickerView.month && + widget.navigationDirection == + DateRangePickerNavigationDirection.vertical) { + height -= widget.monthViewSettings.viewHeaderHeight; + top += widget.monthViewSettings.viewHeaderHeight; + } - return Container( - width: _minWidth, - height: _minHeight, - color: widget.backgroundColor ?? _datePickerTheme.backgroundColor, - child: widget.navigationMode == DateRangePickerNavigationMode.scroll - ? _addScrollView(_minWidth!, _minHeight!, actionButtonsHeight) - : _addChildren(top, height, _minWidth!, actionButtonsHeight), - ); - }); + return Container( + width: _minWidth, + height: _minHeight, + color: widget.backgroundColor ?? _datePickerTheme.backgroundColor, + child: + widget.navigationMode == DateRangePickerNavigationMode.scroll + ? _addScrollView(_minWidth!, _minHeight!, actionButtonsHeight) + : _addChildren(top, height, _minWidth!, actionButtonsHeight), + ); + }, + ); } @override @@ -5886,176 +6062,177 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } SfDateRangePickerThemeData _getPickerThemeData( - SfDateRangePickerThemeData pickerTheme, ThemeData themeData) { + SfDateRangePickerThemeData pickerTheme, + ThemeData themeData, + ) { final ColorScheme colorScheme = themeData.colorScheme; final SfDateRangePickerThemeData effectiveThemeData = SfDateRangePickerThemeKey(context); return pickerTheme.copyWith( - brightness: themeData.brightness, - backgroundColor: - pickerTheme.backgroundColor ?? effectiveThemeData.backgroundColor, - headerBackgroundColor: pickerTheme.headerBackgroundColor ?? - effectiveThemeData.headerBackgroundColor, - viewHeaderBackgroundColor: pickerTheme.viewHeaderBackgroundColor ?? - effectiveThemeData.viewHeaderBackgroundColor, - weekNumberBackgroundColor: pickerTheme.weekNumberBackgroundColor ?? - effectiveThemeData.weekNumberBackgroundColor, - viewHeaderTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 14, - ) - .merge(pickerTheme.viewHeaderTextStyle) - .merge(widget.monthViewSettings.viewHeaderStyle.textStyle), - headerTextStyle: themeData.textTheme.bodyLarge! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 16, - fontWeight: FontWeight.w400, - ) - .merge(pickerTheme.headerTextStyle) - .merge(widget.headerStyle.textStyle), - trailingDatesTextStyle: - (widget.monthCellStyle is DateRangePickerMonthCellStyle) - ? themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: 13, - ) - .merge(pickerTheme.trailingDatesTextStyle) - .merge(widget.monthCellStyle.trailingDatesTextStyle) - : null, - leadingCellTextStyle: - (widget.yearCellStyle is DateRangePickerYearCellStyle) - ? themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: 13, - ) - .merge(pickerTheme.leadingCellTextStyle) - .merge(widget.yearCellStyle.leadingDatesTextStyle) - : null, - activeDatesTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.activeDatesTextStyle) - .merge(widget.monthCellStyle.textStyle), - cellTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.cellTextStyle) - .merge(widget.yearCellStyle.textStyle), - leadingDatesTextStyle: - (widget.monthCellStyle is DateRangePickerMonthCellStyle) - ? themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.54), - fontSize: 13, - ) - .merge(pickerTheme.leadingDatesTextStyle) - .merge(widget.monthCellStyle.leadingDatesTextStyle) - : null, - rangeSelectionTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.rangeSelectionTextStyle) - .merge(widget.rangeTextStyle), - disabledDatesTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.38), - fontSize: 13, - ) - .merge(pickerTheme.disabledDatesTextStyle) - .merge(widget.monthCellStyle.disabledDatesTextStyle), - disabledCellTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.38), - fontSize: 13, - ) - .merge(pickerTheme.disabledCellTextStyle) - .merge(widget.yearCellStyle.disabledDatesTextStyle), - selectionTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onPrimary, - fontSize: 13, - ) - .merge(pickerTheme.selectionTextStyle) - .merge(widget.selectionTextStyle), - weekNumberTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.weekNumberTextStyle) - .merge(widget.monthViewSettings.weekNumberStyle.textStyle), - todayTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.primary, - fontSize: 13, - ) - .merge(pickerTheme.todayTextStyle) - .merge(widget.monthCellStyle.todayTextStyle), - todayCellTextStyle: themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.primary, - fontSize: 13, - ) - .merge(pickerTheme.todayCellTextStyle) - .merge(widget.yearCellStyle.todayTextStyle), - - /// Check the widget property and theme property styles are null. - /// If null assign the picker theme style or - /// If not null then assign the theme data text theme with - /// merge the styles from widget property or theme properties are given. - blackoutDatesTextStyle: - (widget.monthCellStyle.blackoutDateTextStyle == null && - pickerTheme.blackoutDatesTextStyle == null) - ? pickerTheme.blackoutDatesTextStyle - : themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.blackoutDatesTextStyle) - .merge(widget.monthCellStyle.blackoutDateTextStyle), - specialDatesTextStyle: - (widget.monthCellStyle.specialDatesTextStyle == null && - pickerTheme.specialDatesTextStyle == null) - ? pickerTheme.specialDatesTextStyle - : themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.specialDatesTextStyle) - .merge(widget.monthCellStyle.specialDatesTextStyle), - weekendDatesTextStyle: - (widget.monthCellStyle.weekendTextStyle == null && - pickerTheme.weekendDatesTextStyle == null) - ? pickerTheme.weekendDatesTextStyle - : themeData.textTheme.bodyMedium! - .copyWith( - color: colorScheme.onSurface.withValues(alpha: 0.87), - fontSize: 13, - ) - .merge(pickerTheme.weekendDatesTextStyle) - .merge(widget.monthCellStyle.weekendTextStyle), - selectionColor: - pickerTheme.selectionColor ?? effectiveThemeData.selectionColor, - startRangeSelectionColor: pickerTheme.startRangeSelectionColor ?? - effectiveThemeData.startRangeSelectionColor, - rangeSelectionColor: pickerTheme.rangeSelectionColor ?? - effectiveThemeData.rangeSelectionColor, - endRangeSelectionColor: pickerTheme.endRangeSelectionColor ?? - effectiveThemeData.endRangeSelectionColor, - todayHighlightColor: pickerTheme.todayHighlightColor ?? - effectiveThemeData.todayHighlightColor); + brightness: themeData.brightness, + backgroundColor: + pickerTheme.backgroundColor ?? effectiveThemeData.backgroundColor, + headerBackgroundColor: + pickerTheme.headerBackgroundColor ?? + effectiveThemeData.headerBackgroundColor, + viewHeaderBackgroundColor: + pickerTheme.viewHeaderBackgroundColor ?? + effectiveThemeData.viewHeaderBackgroundColor, + weekNumberBackgroundColor: + pickerTheme.weekNumberBackgroundColor ?? + effectiveThemeData.weekNumberBackgroundColor, + viewHeaderTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 14, + ) + .merge(pickerTheme.viewHeaderTextStyle) + .merge(widget.monthViewSettings.viewHeaderStyle.textStyle), + headerTextStyle: themeData.textTheme.bodyLarge! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 16, + fontWeight: FontWeight.w400, + ) + .merge(pickerTheme.headerTextStyle) + .merge(widget.headerStyle.textStyle), + trailingDatesTextStyle: + (widget.monthCellStyle is DateRangePickerMonthCellStyle) + ? themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: 13, + ) + .merge(pickerTheme.trailingDatesTextStyle) + .merge(widget.monthCellStyle.trailingDatesTextStyle) + : null, + leadingCellTextStyle: + (widget.yearCellStyle is DateRangePickerYearCellStyle) + ? themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: 13, + ) + .merge(pickerTheme.leadingCellTextStyle) + .merge(widget.yearCellStyle.leadingDatesTextStyle) + : null, + activeDatesTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.activeDatesTextStyle) + .merge(widget.monthCellStyle.textStyle), + cellTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.cellTextStyle) + .merge(widget.yearCellStyle.textStyle), + leadingDatesTextStyle: + (widget.monthCellStyle is DateRangePickerMonthCellStyle) + ? themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.54), + fontSize: 13, + ) + .merge(pickerTheme.leadingDatesTextStyle) + .merge(widget.monthCellStyle.leadingDatesTextStyle) + : null, + rangeSelectionTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.rangeSelectionTextStyle) + .merge(widget.rangeTextStyle), + disabledDatesTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.38), + fontSize: 13, + ) + .merge(pickerTheme.disabledDatesTextStyle) + .merge(widget.monthCellStyle.disabledDatesTextStyle), + disabledCellTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.38), + fontSize: 13, + ) + .merge(pickerTheme.disabledCellTextStyle) + .merge(widget.yearCellStyle.disabledDatesTextStyle), + selectionTextStyle: themeData.textTheme.bodyMedium! + .copyWith(color: colorScheme.onPrimary, fontSize: 13) + .merge(pickerTheme.selectionTextStyle) + .merge(widget.selectionTextStyle), + weekNumberTextStyle: themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.weekNumberTextStyle) + .merge(widget.monthViewSettings.weekNumberStyle.textStyle), + todayTextStyle: themeData.textTheme.bodyMedium! + .copyWith(color: colorScheme.primary, fontSize: 13) + .merge(pickerTheme.todayTextStyle) + .merge(widget.monthCellStyle.todayTextStyle), + todayCellTextStyle: themeData.textTheme.bodyMedium! + .copyWith(color: colorScheme.primary, fontSize: 13) + .merge(pickerTheme.todayCellTextStyle) + .merge(widget.yearCellStyle.todayTextStyle), + + /// Check the widget property and theme property styles are null. + /// If null assign the picker theme style or + /// If not null then assign the theme data text theme with + /// merge the styles from widget property or theme properties are given. + blackoutDatesTextStyle: + (widget.monthCellStyle.blackoutDateTextStyle == null && + pickerTheme.blackoutDatesTextStyle == null) + ? pickerTheme.blackoutDatesTextStyle + : themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.blackoutDatesTextStyle) + .merge(widget.monthCellStyle.blackoutDateTextStyle), + specialDatesTextStyle: + (widget.monthCellStyle.specialDatesTextStyle == null && + pickerTheme.specialDatesTextStyle == null) + ? pickerTheme.specialDatesTextStyle + : themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.specialDatesTextStyle) + .merge(widget.monthCellStyle.specialDatesTextStyle), + weekendDatesTextStyle: + (widget.monthCellStyle.weekendTextStyle == null && + pickerTheme.weekendDatesTextStyle == null) + ? pickerTheme.weekendDatesTextStyle + : themeData.textTheme.bodyMedium! + .copyWith( + color: colorScheme.onSurface.withValues(alpha: 0.87), + fontSize: 13, + ) + .merge(pickerTheme.weekendDatesTextStyle) + .merge(widget.monthCellStyle.weekendTextStyle), + selectionColor: + pickerTheme.selectionColor ?? effectiveThemeData.selectionColor, + startRangeSelectionColor: + pickerTheme.startRangeSelectionColor ?? + effectiveThemeData.startRangeSelectionColor, + rangeSelectionColor: + pickerTheme.rangeSelectionColor ?? + effectiveThemeData.rangeSelectionColor, + endRangeSelectionColor: + pickerTheme.endRangeSelectionColor ?? + effectiveThemeData.endRangeSelectionColor, + todayHighlightColor: + pickerTheme.todayHighlightColor ?? + effectiveThemeData.todayHighlightColor, + ); } void _updateFadeAnimation() { @@ -6072,30 +6249,38 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } void _initPickerController() { - _controller = widget.controller ?? + _controller = + widget.controller ?? (widget.isHijri ? HijriDatePickerController() : DateRangePickerController()); _controller.selectedDate = widget.initialSelectedDate; _controller.selectedDates = _getSelectedDates( - DateRangePickerHelper.cloneList(widget.initialSelectedDates)); + DateRangePickerHelper.cloneList(widget.initialSelectedDates), + ); _controller.selectedRange = widget.initialSelectedRange; - _controller.selectedRanges = - DateRangePickerHelper.cloneList(widget.initialSelectedRanges); - _controller.view = widget.isHijri - ? DateRangePickerHelper.getHijriPickerView(widget.view) - : DateRangePickerHelper.getPickerView(widget.view); - _currentDate = - getValidDate(widget.minDate, widget.maxDate, widget.initialDisplayDate); - _controller.displayDate = _currentDate; + _controller.selectedRanges = DateRangePickerHelper.cloneList( + widget.initialSelectedRanges, + ); + _controller.view = + widget.isHijri + ? DateRangePickerHelper.getHijriPickerView(widget.view) + : DateRangePickerHelper.getPickerView(widget.view); + _currentDate = getValidDate( + widget.minDate, + widget.maxDate, + widget.initialDisplayDate, + ); + _controller.displayDate = _currentDate; } void _updateSelectionValues() { _selectedDate = _controller.selectedDate; _selectedDates = DateRangePickerHelper.cloneList(_controller.selectedDates); _selectedRange = _controller.selectedRange; - _selectedRanges = - DateRangePickerHelper.cloneList(_controller.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _controller.selectedRanges, + ); } void _pickerValueChangedListener(String value) { @@ -6111,19 +6296,24 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } else if (value == 'selectedDates') { if (!mounted || DateRangePickerHelper.isDateCollectionEquals( - _selectedDates, _controller.selectedDates)) { + _selectedDates, + _controller.selectedDates, + )) { return; } _raiseSelectionChangedCallback(widget, value: _controller.selectedDates); setState(() { - _selectedDates = - DateRangePickerHelper.cloneList(_controller.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _controller.selectedDates, + ); }); } else if (value == 'selectedRange') { if (!mounted || DateRangePickerHelper.isRangeEquals( - _selectedRange, _controller.selectedRange)) { + _selectedRange, + _controller.selectedRange, + )) { return; } @@ -6134,14 +6324,17 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } else if (value == 'selectedRanges') { if (!mounted || DateRangePickerHelper.isDateRangesEquals( - _selectedRanges, _controller.selectedRanges)) { + _selectedRanges, + _controller.selectedRanges, + )) { return; } _raiseSelectionChangedCallback(widget, value: _controller.selectedRanges); setState(() { - _selectedRanges = - DateRangePickerHelper.cloneList(_controller.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _controller.selectedRanges, + ); }); } else if (value == 'view') { if (!mounted || @@ -6161,7 +6354,8 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _scrollViewKey.currentState!._children.clear(); _scrollViewKey.currentState!._updateVisibleDates(); _scrollViewKey.currentState!._triggerSelectableDayPredicates( - _scrollViewKey.currentState!._currentViewVisibleDates); + _scrollViewKey.currentState!._currentViewVisibleDates, + ); _scrollViewKey.currentState!._triggerViewChangedCallback(); } }); @@ -6199,22 +6393,26 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } bool _checkDateWithInVisibleDates(dynamic date) { - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(_controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + _controller.view, + ); switch (view) { case DateRangePickerView.month: { if (!widget.isHijri && DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri) != + widget.monthViewSettings, + widget.isHijri, + ) != 6) { return isDateWithInDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[_currentViewVisibleDates.length - 1], - date); + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + date, + ); } else { - final dynamic currentMonth = _currentViewVisibleDates[ - _currentViewVisibleDates.length ~/ + final dynamic currentMonth = + _currentViewVisibleDates[_currentViewVisibleDates.length ~/ (_isMultiViewEnabled(widget) ? 4 : 2)]; return date.month == currentMonth.month && date.year == currentMonth.year; @@ -6254,10 +6452,13 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> null, widget.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - _view, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri), - widget.isHijri), + _view, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.monthViewSettings, + widget.isHijri, + ), + widget.isHijri, + ), ); } break; @@ -6266,7 +6467,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> case DateRangePickerView.century: { _currentViewVisibleDates = DateRangePickerHelper.getVisibleYearDates( - _currentDate, _view, widget.isHijri); + _currentDate, + _view, + widget.isHijri, + ); } } } @@ -6298,14 +6502,18 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> if (_forwardDateCollection.isEmpty) { return true; } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(_controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + _controller.view, + ); final int numberOfWeekInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri); + widget.monthViewSettings, + widget.isHijri, + ); // ignore: always_specify_types, strict_raw_type - final List startDates = _backwardDateCollection.isNotEmpty - ? _backwardDateCollection[_backwardDateCollection.length - 1] - : _forwardDateCollection[0]; + final List startDates = + _backwardDateCollection.isNotEmpty + ? _backwardDateCollection[_backwardDateCollection.length - 1] + : _forwardDateCollection[0]; // ignore: always_specify_types, strict_raw_type final List endDates = _forwardDateCollection[_forwardDateCollection.length - 1]; @@ -6315,20 +6523,29 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> if (!widget.isHijri && numberOfWeekInView != 6) { final DateTime visibleStartDate = DateRangePickerHelper.getDateTimeValue( - startDates[startDates.length - 1]); + startDates[startDates.length - 1], + ); final DateTime visibleEndDate = DateRangePickerHelper.getDateTimeValue(endDates[0]); return isDateWithInDateRange( - widget.minDate, widget.maxDate, visibleStartDate) && + widget.minDate, + widget.maxDate, + visibleStartDate, + ) && isDateWithInDateRange( - widget.minDate, widget.maxDate, visibleEndDate); + widget.minDate, + widget.maxDate, + visibleEndDate, + ); } else { final DateTime visibleStartDate = DateRangePickerHelper.getDateTimeValue( - startDates[startDates.length ~/ 2]); + startDates[startDates.length ~/ 2], + ); final DateTime visibleEndDate = DateRangePickerHelper.getDateTimeValue( - endDates[endDates.length ~/ 2]); + endDates[endDates.length ~/ 2], + ); return (visibleStartDate.year > widget.minDate.year || (visibleStartDate.year == widget.minDate.year && visibleStartDate.month >= widget.minDate.month)) && @@ -6380,8 +6597,13 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> /// Handle the control size changed related view updates on scroll navigation /// mode. - void _handleScrollViewSizeChanged(double newHeight, double newWidth, - double? oldHeight, double? oldWidth, double actionButtonHeight) { + void _handleScrollViewSizeChanged( + double newHeight, + double newWidth, + double? oldHeight, + double? oldWidth, + double actionButtonHeight, + ) { if (widget.navigationMode != DateRangePickerNavigationMode.scroll || _pickerScrollController == null || !_pickerScrollController!.hasClients) { @@ -6397,16 +6619,17 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _pickerScrollController!.dispose(); _scrollKey = UniqueKey(); _pickerKey = UniqueKey(); - _pickerScrollController = - ScrollController(initialScrollOffset: index * newWidth) - ..addListener(_handleScrollChanged); + _pickerScrollController = ScrollController( + initialScrollOffset: index * newWidth, + )..addListener(_handleScrollChanged); } else if (oldHeight != null && widget.navigationDirection == DateRangePickerNavigationDirection.vertical && oldHeight != newHeight) { - final double viewHeaderHeight = _view == DateRangePickerView.month - ? widget.monthViewSettings.viewHeaderHeight as double - : 0; + final double viewHeaderHeight = + _view == DateRangePickerView.month + ? widget.monthViewSettings.viewHeaderHeight as double + : 0; final double viewSize = oldHeight - viewHeaderHeight - actionButtonHeight; final double index = _pickerScrollController!.position.pixels / viewSize; _pickerScrollController!.removeListener(_handleScrollChanged); @@ -6414,28 +6637,30 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _scrollKey = UniqueKey(); _pickerKey = UniqueKey(); _pickerScrollController = ScrollController( - initialScrollOffset: - index * (newHeight - viewHeaderHeight - actionButtonHeight)) - ..addListener(_handleScrollChanged); + initialScrollOffset: + index * (newHeight - viewHeaderHeight - actionButtonHeight), + )..addListener(_handleScrollChanged); } } /// handle the scroll navigation mode scroll view scroll changed. void _handleScrollChanged() { final double scrolledPosition = _pickerScrollController!.position.pixels; - final double actionButtonsHeight = widget.showActionButtons - ? _minHeight! * 0.1 < 50 - ? 50 - : _minHeight! * 0.1 - : 0; - double widgetSize = widget.navigationDirection == - DateRangePickerNavigationDirection.horizontal - ? _minWidth! - : _minHeight! - - (_view == DateRangePickerView.month - ? widget.monthViewSettings.viewHeaderHeight - : 0) - - actionButtonsHeight; + final double actionButtonsHeight = + widget.showActionButtons + ? _minHeight! * 0.1 < 50 + ? 50 + : _minHeight! * 0.1 + : 0; + double widgetSize = + widget.navigationDirection == + DateRangePickerNavigationDirection.horizontal + ? _minWidth! + : _minHeight! - + (_view == DateRangePickerView.month + ? widget.monthViewSettings.viewHeaderHeight + : 0) - + actionButtonsHeight; if (widget.enableMultiView) { widgetSize /= 2; } @@ -6477,12 +6702,18 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> dynamic currentDate = visibleDates[0]; final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri); + widget.monthViewSettings, + widget.isHijri, + ); if (_view == DateRangePickerView.month && (numberOfWeeksInView == 6 || widget.isHijri)) { final dynamic date = visibleDates[visibleDates.length ~/ 2]; currentDate = DateRangePickerHelper.getDate( - date.year, date.month, 1, widget.isHijri); + date.year, + date.month, + 1, + widget.isHijri, + ); } _currentDate = getValidDate(widget.minDate, widget.maxDate, currentDate); @@ -6494,12 +6725,13 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> /// Calculate and add the visible date collection for scroll view based on /// [isNextView] value. void _addScrollViewDateCollection( - List dateCollection, - bool isNextView, - dynamic startDate, - DateRangePickerView currentView, - int numberOfWeeksInView, - int visibleDatesCount) { + List dateCollection, + bool isNextView, + dynamic startDate, + DateRangePickerView currentView, + int numberOfWeeksInView, + int visibleDatesCount, + ) { int count = 0; dynamic visibleDate = startDate; while (count < 10) { @@ -6551,18 +6783,20 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> dateCollection.add(visibleDates); if (isNextView) { visibleDate = DateRangePickerHelper.getNextViewStartDate( - currentView, - numberOfWeeksInView, - visibleDate, - false, - widget.isHijri); + currentView, + numberOfWeeksInView, + visibleDate, + false, + widget.isHijri, + ); } else { visibleDate = DateRangePickerHelper.getPreviousViewStartDate( - currentView, - numberOfWeeksInView, - visibleDate, - false, - widget.isHijri); + currentView, + numberOfWeeksInView, + visibleDate, + false, + widget.isHijri, + ); } count++; } @@ -6600,18 +6834,20 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> dateCollection.add(visibleDates); if (isNextView) { visibleDate = DateRangePickerHelper.getNextViewStartDate( - currentView, - numberOfWeeksInView, - visibleDate, - false, - widget.isHijri); + currentView, + numberOfWeeksInView, + visibleDate, + false, + widget.isHijri, + ); } else { visibleDate = DateRangePickerHelper.getPreviousViewStartDate( - currentView, - numberOfWeeksInView, - visibleDate, - false, - widget.isHijri); + currentView, + numberOfWeeksInView, + visibleDate, + false, + widget.isHijri, + ); } count++; } @@ -6621,20 +6857,35 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } Widget _addScrollView( - double width, double height, double actionButtonsHeight) { - _pickerScrollController ??= ScrollController() - ..addListener(_handleScrollChanged); - final DateRangePickerView currentView = - DateRangePickerHelper.getPickerView(_view); + double width, + double height, + double actionButtonsHeight, + ) { + _pickerScrollController ??= + ScrollController()..addListener(_handleScrollChanged); + final DateRangePickerView currentView = DateRangePickerHelper.getPickerView( + _view, + ); final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri); + widget.monthViewSettings, + widget.isHijri, + ); final int visibleDatesCount = DateRangePickerHelper.getViewDatesCount( - currentView, numberOfWeeksInView, widget.isHijri); + currentView, + numberOfWeeksInView, + widget.isHijri, + ); final bool isInitialLoading = _forwardDateCollection.isEmpty; if (isInitialLoading) { - _addScrollViewDateCollection(_forwardDateCollection, true, _currentDate, - currentView, numberOfWeeksInView, visibleDatesCount); + _addScrollViewDateCollection( + _forwardDateCollection, + true, + _currentDate, + currentView, + numberOfWeeksInView, + visibleDatesCount, + ); } if (_backwardDateCollection.isEmpty) { @@ -6646,12 +6897,23 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> ? lastViewDates[0] : _currentDate : lastViewDates != null && lastViewDates.isNotEmpty - ? lastViewDates[lastViewDates.length ~/ 2] - : _currentDate; + ? lastViewDates[lastViewDates.length ~/ 2] + : _currentDate; visibleDate = DateRangePickerHelper.getPreviousViewStartDate( - currentView, numberOfWeeksInView, visibleDate, false, widget.isHijri); - _addScrollViewDateCollection(_backwardDateCollection, false, visibleDate, - currentView, numberOfWeeksInView, visibleDatesCount); + currentView, + numberOfWeeksInView, + visibleDate, + false, + widget.isHijri, + ); + _addScrollViewDateCollection( + _backwardDateCollection, + false, + visibleDate, + currentView, + numberOfWeeksInView, + visibleDatesCount, + ); } int forwardCollectionLength = _forwardDateCollection.length; @@ -6673,7 +6935,8 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _notifyCurrentVisibleDatesChanged(); } - final bool isHorizontal = widget.navigationDirection == + final bool isHorizontal = + widget.navigationDirection == DateRangePickerNavigationDirection.horizontal; final double topPosition = _view == DateRangePickerView.month && !isHorizontal @@ -6683,28 +6946,32 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> double scrollViewItemHeight = scrollViewHeight; double scrollViewItemWidth = width; if (isHorizontal) { - scrollViewItemWidth = widget.enableMultiView - ? scrollViewItemWidth / 2 - : scrollViewItemWidth; + scrollViewItemWidth = + widget.enableMultiView + ? scrollViewItemWidth / 2 + : scrollViewItemWidth; } else { - scrollViewItemHeight = widget.enableMultiView - ? scrollViewItemHeight / 2 - : scrollViewItemHeight; + scrollViewItemHeight = + widget.enableMultiView + ? scrollViewItemHeight / 2 + : scrollViewItemHeight; } final Widget scrollView = CustomScrollView( scrollDirection: isHorizontal ? Axis.horizontal : Axis.vertical, key: _scrollKey, physics: const AlwaysScrollableScrollPhysics( - parent: - ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics())), + parent: ClampingScrollPhysics(parent: RangeMaintainingScrollPhysics()), + ), controller: _pickerScrollController, center: _pickerKey, slivers: [ SliverFixedExtentList( itemExtent: isHorizontal ? scrollViewItemWidth : scrollViewItemHeight, - delegate: - SliverChildBuilderDelegate((BuildContext context, int index) { + delegate: SliverChildBuilderDelegate(( + BuildContext context, + int index, + ) { if (_backwardDateCollection.length <= index) { return null; } @@ -6712,27 +6979,31 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> /// Send negative index value to differentiate the /// backward view from forward view. return _getScrollViewItem( - -(index + 1), - scrollViewItemWidth, - scrollViewItemHeight, - _backwardDateCollection[index], - isHorizontal); + -(index + 1), + scrollViewItemWidth, + scrollViewItemHeight, + _backwardDateCollection[index], + isHorizontal, + ); }), ), SliverFixedExtentList( itemExtent: isHorizontal ? scrollViewItemWidth : scrollViewItemHeight, - delegate: - SliverChildBuilderDelegate((BuildContext context, int index) { + delegate: SliverChildBuilderDelegate(( + BuildContext context, + int index, + ) { if (_forwardDateCollection.length <= index) { return null; } return _getScrollViewItem( - index, - scrollViewItemWidth, - scrollViewItemHeight, - _forwardDateCollection[index], - isHorizontal); + index, + scrollViewItemWidth, + scrollViewItemHeight, + _forwardDateCollection[index], + isHorizontal, + ); }), key: _pickerKey, ), @@ -6744,55 +7015,84 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> children: [ scrollView, _getActionsButton( - topPosition + scrollViewHeight, actionButtonsHeight), + topPosition + scrollViewHeight, + actionButtonsHeight, + ), ], ); } else { _viewHeaderVisibleDates.value = _currentViewVisibleDates; - return Stack(children: [ - _getViewHeaderView(0), - Positioned( + return Stack( + children: [ + _getViewHeaderView(0), + Positioned( left: 0, top: topPosition, right: 0, height: scrollViewHeight, - child: scrollView), - _getActionsButton(topPosition + scrollViewHeight, actionButtonsHeight) - ]); + child: scrollView, + ), + _getActionsButton( + topPosition + scrollViewHeight, + actionButtonsHeight, + ), + ], + ); } } /// Return widget that placed on scroll view when navigation mode is scroll. Widget _getScrollViewItem( - int index, - double width, - double height, - // ignore: always_specify_types, strict_raw_type - List dates, - bool isHorizontal) { - final DateRangePickerView currentView = - DateRangePickerHelper.getPickerView(_view); + int index, + double width, + double height, + // ignore: always_specify_types, strict_raw_type + List dates, + bool isHorizontal, + ) { + final DateRangePickerView currentView = DateRangePickerHelper.getPickerView( + _view, + ); final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri); + widget.monthViewSettings, + widget.isHijri, + ); final int visibleDatesCount = DateRangePickerHelper.getViewDatesCount( - currentView, numberOfWeeksInView, widget.isHijri); + currentView, + numberOfWeeksInView, + widget.isHijri, + ); if (index >= 0) { if (_forwardDateCollection.isNotEmpty && index > _forwardDateCollection.length - 2) { // ignore: always_specify_types, strict_raw_type final List lastViewDates = _forwardDateCollection[_forwardDateCollection.length - 1]; - dynamic date = currentView == DateRangePickerView.month && - DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri) != - 6 - ? lastViewDates[0] - : lastViewDates[lastViewDates.length ~/ 2]; + dynamic date = + currentView == DateRangePickerView.month && + DateRangePickerHelper.getNumberOfWeeksInView( + widget.monthViewSettings, + widget.isHijri, + ) != + 6 + ? lastViewDates[0] + : lastViewDates[lastViewDates.length ~/ 2]; date = DateRangePickerHelper.getNextViewStartDate( - currentView, numberOfWeeksInView, date, false, widget.isHijri); - _addScrollViewDateCollection(_forwardDateCollection, true, date, - currentView, numberOfWeeksInView, visibleDatesCount); + currentView, + numberOfWeeksInView, + date, + false, + widget.isHijri, + ); + _addScrollViewDateCollection( + _forwardDateCollection, + true, + date, + currentView, + numberOfWeeksInView, + visibleDatesCount, + ); } } else { if (_backwardDateCollection.isNotEmpty && @@ -6800,16 +7100,30 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> // ignore: always_specify_types, strict_raw_type final List lastViewDates = _backwardDateCollection[_backwardDateCollection.length - 1]; - dynamic date = currentView == DateRangePickerView.month && - DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri) != - 6 - ? lastViewDates[0] - : lastViewDates[lastViewDates.length ~/ 2]; + dynamic date = + currentView == DateRangePickerView.month && + DateRangePickerHelper.getNumberOfWeeksInView( + widget.monthViewSettings, + widget.isHijri, + ) != + 6 + ? lastViewDates[0] + : lastViewDates[lastViewDates.length ~/ 2]; date = DateRangePickerHelper.getPreviousViewStartDate( - currentView, numberOfWeeksInView, date, false, widget.isHijri); - _addScrollViewDateCollection(_backwardDateCollection, false, date, - currentView, numberOfWeeksInView, visibleDatesCount); + currentView, + numberOfWeeksInView, + date, + false, + widget.isHijri, + ); + _addScrollViewDateCollection( + _backwardDateCollection, + false, + date, + currentView, + numberOfWeeksInView, + visibleDatesCount, + ); } } @@ -6818,28 +7132,35 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> double headerWidth = pickerWidth; if (isHorizontal) { final String headerText = _getHeaderText( - dates, - _view, - 0, - widget.isHijri, - numberOfWeeksInView, - widget.monthFormat, - false, - widget.headerStyle, - widget.navigationDirection, - _locale, - _localizations); - headerWidth = _getTextWidgetWidth( - headerText, widget.headerHeight, pickerWidth, context, - style: _datePickerTheme.headerTextStyle!, widthPadding: 20) - .width; + dates, + _view, + 0, + widget.isHijri, + numberOfWeeksInView, + widget.monthFormat, + false, + widget.headerStyle, + widget.navigationDirection, + _locale, + _localizations, + ); + headerWidth = + _getTextWidgetWidth( + headerText, + widget.headerHeight, + pickerWidth, + context, + style: _datePickerTheme.headerTextStyle!, + widthPadding: 20, + ).width; } if (headerWidth > pickerWidth) { headerWidth = pickerWidth; } - final Color? backgroundColor = widget.headerStyle.backgroundColor ?? + final Color? backgroundColor = + widget.headerStyle.backgroundColor ?? _datePickerTheme.headerBackgroundColor; final Widget header = Positioned( top: 0, @@ -6851,37 +7172,40 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> color: backgroundColor, height: widget.headerHeight, child: _PickerHeaderView( - ValueNotifier>(dates), - widget.headerStyle, - widget.selectionMode, - _view, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri), - widget.showNavigationArrow, - widget.navigationDirection, - widget.monthViewSettings.enableSwipeSelection, - widget.navigationMode, - widget.minDate, - widget.maxDate, - widget.monthFormat, - _datePickerTheme, - _locale, - headerWidth, - widget.headerHeight, - widget.allowViewNavigation, - _controller.backward, - _controller.forward, - _isMultiViewEnabled(widget), - widget.viewSpacing, - kIsWeb && - (Theme.of(context).platform == TargetPlatform.android || - Theme.of(context).platform == TargetPlatform.iOS) - ? _datePickerTheme.selectionColor! - : widget.selectionColor ?? _datePickerTheme.selectionColor!, - _isRtl, - _textScaleFactor, + ValueNotifier>(dates), + widget.headerStyle, + widget.selectionMode, + _view, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.monthViewSettings, widget.isHijri, - _localizations), + ), + widget.showNavigationArrow, + widget.navigationDirection, + widget.monthViewSettings.enableSwipeSelection, + widget.navigationMode, + widget.minDate, + widget.maxDate, + widget.monthFormat, + _datePickerTheme, + _locale, + headerWidth, + widget.headerHeight, + widget.allowViewNavigation, + _controller.backward, + _controller.forward, + _isMultiViewEnabled(widget), + widget.viewSpacing, + kIsWeb && + (Theme.of(context).platform == TargetPlatform.android || + Theme.of(context).platform == TargetPlatform.iOS) + ? _datePickerTheme.selectionColor! + : widget.selectionColor ?? _datePickerTheme.selectionColor!, + _isRtl, + _textScaleFactor, + widget.isHijri, + _localizations, + ), ), onTapUp: (TapUpDetails details) { if (_view == DateRangePickerView.century || @@ -6893,16 +7217,25 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> dynamic currentDate = dates[0]; final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri); + widget.monthViewSettings, + widget.isHijri, + ); if (_view == DateRangePickerView.month && (numberOfWeeksInView == 6 || widget.isHijri)) { final dynamic date = dates[dates.length ~/ 2]; currentDate = DateRangePickerHelper.getDate( - date.year, date.month, 1, widget.isHijri); + date.year, + date.month, + 1, + widget.isHijri, + ); } - currentDate = - getValidDate(widget.minDate, widget.maxDate, currentDate); + currentDate = getValidDate( + widget.minDate, + widget.maxDate, + currentDate, + ); /// Check the moved view visible date not contains tapped /// header date @@ -6951,50 +7284,59 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> final List children = [pickerView]; if (isHorizontal) { - children.add(Positioned( - top: 0, - left: pickerWidth, - width: 1, - height: height, - child: const VerticalDivider( - thickness: 1, + children.add( + Positioned( + top: 0, + left: pickerWidth, + width: 1, + height: height, + child: const VerticalDivider(thickness: 1), ), - )); + ); } children.add(header); return SizedBox( - width: width, - height: height, - child: _StickyHeader( - isHorizontal: isHorizontal, - isRTL: _isRtl, - children: children, - )); + width: width, + height: height, + child: _StickyHeader( + isHorizontal: isHorizontal, + isRTL: _isRtl, + children: children, + ), + ); } Widget _addChildren( - double top, double height, double width, double actionButtonsHeight) { + double top, + double height, + double width, + double actionButtonsHeight, + ) { _headerVisibleDates.value = _currentViewVisibleDates; height -= actionButtonsHeight; - return Stack(children: [ - Positioned( - top: 0, - right: 0, - left: 0, - height: widget.headerHeight, - child: GestureDetector( - child: Container( - color: widget.headerStyle.backgroundColor ?? - _datePickerTheme.headerBackgroundColor, - height: widget.headerHeight, - child: _PickerHeaderView( + return Stack( + children: [ + Positioned( + top: 0, + right: 0, + left: 0, + height: widget.headerHeight, + child: GestureDetector( + child: Container( + color: + widget.headerStyle.backgroundColor ?? + _datePickerTheme.headerBackgroundColor, + height: widget.headerHeight, + child: _PickerHeaderView( _headerVisibleDates, widget.headerStyle, widget.selectionMode, _view, DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri), + widget.monthViewSettings, + widget.isHijri, + ), widget.showNavigationArrow, widget.navigationDirection, widget.monthViewSettings.enableSwipeSelection, @@ -7019,42 +7361,44 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _isRtl, _textScaleFactor, widget.isHijri, - _localizations), + _localizations, + ), + ), + onTapUp: (TapUpDetails details) { + _updateCalendarTapCallbackForHeader(); + }, ), - onTapUp: (TapUpDetails details) { - _updateCalendarTapCallbackForHeader(); - }, ), - ), - _getViewHeaderView(widget.headerHeight), - Positioned( - top: top, - left: 0, - right: 0, - height: height, - child: _AnimatedOpacityWidget( - opacity: _opacity, - child: _PickerScrollView( - widget, - _controller, - width, - height, - _isRtl, - _datePickerTheme, - _locale, - _textScaleFactor, - getPickerStateValues: (PickerStateArgs details) { - _getPickerStateValues(details); - }, - updatePickerStateValues: (PickerStateArgs details) { - _updatePickerStateValues(details); - }, - key: _scrollViewKey, + _getViewHeaderView(widget.headerHeight), + Positioned( + top: top, + left: 0, + right: 0, + height: height, + child: _AnimatedOpacityWidget( + opacity: _opacity, + child: _PickerScrollView( + widget, + _controller, + width, + height, + _isRtl, + _datePickerTheme, + _locale, + _textScaleFactor, + getPickerStateValues: (PickerStateArgs details) { + _getPickerStateValues(details); + }, + updatePickerStateValues: (PickerStateArgs details) { + _updatePickerStateValues(details); + }, + key: _scrollViewKey, + ), ), ), - ), - _getActionsButton(top + height, actionButtonsHeight) - ]); + _getActionsButton(top + height, actionButtonsHeight), + ], + ); } Widget _getActionsButton(double top, double actionButtonsHeight) { @@ -7067,68 +7411,73 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> final TextStyle style = _datePickerTheme.todayTextStyle!; textColor = style.color != null ? style.color! : Colors.blue; } - final Widget actionButtons = widget.showActionButtons - ? Container( - alignment: AlignmentDirectional.centerEnd, - constraints: const BoxConstraints(minHeight: 52.0), - padding: const EdgeInsets.symmetric(horizontal: 8), - child: OverflowBar( - spacing: 8, - children: [ - TextButton( - onPressed: _handleCancel, - child: Text( - widget.cancelText, - style: TextStyle(color: textColor), + final Widget actionButtons = + widget.showActionButtons + ? Container( + alignment: AlignmentDirectional.centerEnd, + constraints: const BoxConstraints(minHeight: 52.0), + padding: const EdgeInsets.symmetric(horizontal: 8), + child: OverflowBar( + spacing: 8, + children: [ + TextButton( + onPressed: _handleCancel, + child: Text( + widget.cancelText, + style: TextStyle(color: textColor), + ), ), - ), - TextButton( - onPressed: _handleOk, - child: Text( - widget.confirmText, - style: TextStyle(color: textColor), + TextButton( + onPressed: _handleOk, + child: Text( + widget.confirmText, + style: TextStyle(color: textColor), + ), ), - ), - ], - ), - ) - : const SizedBox(width: 0, height: 0); - final Widget todayButton = widget.showTodayButton - ? Container( - alignment: AlignmentDirectional.centerStart, - constraints: const BoxConstraints(minHeight: 52.0), - padding: const EdgeInsets.symmetric(horizontal: 8), - child: OverflowBar( - spacing: 8, - children: [ - TextButton( - child: Text( - _localizations.todayLabel.toUpperCase(), - style: TextStyle(color: textColor), + ], + ), + ) + : const SizedBox(width: 0, height: 0); + final Widget todayButton = + widget.showTodayButton + ? Container( + alignment: AlignmentDirectional.centerStart, + constraints: const BoxConstraints(minHeight: 52.0), + padding: const EdgeInsets.symmetric(horizontal: 8), + child: OverflowBar( + spacing: 8, + children: [ + TextButton( + child: Text( + _localizations.todayLabel.toUpperCase(), + style: TextStyle(color: textColor), + ), + onPressed: () { + if (widget.allowViewNavigation) { + _controller.view = + widget.isHijri + ? HijriDatePickerView.month + : DateRangePickerView.month; + } + + _controller.displayDate = DateRangePickerHelper.getToday( + widget.isHijri, + ); + }, ), - onPressed: () { - if (widget.allowViewNavigation) { - _controller.view = widget.isHijri - ? HijriDatePickerView.month - : DateRangePickerView.month; - } - - _controller.displayDate = - DateRangePickerHelper.getToday(widget.isHijri); - }, - ), - ], - ), - ) - : const SizedBox(width: 0, height: 0); + ], + ), + ) + : const SizedBox(width: 0, height: 0); return Positioned( top: top, left: 0, right: 0, height: actionButtonsHeight, child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [todayButton, actionButtons]), + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [todayButton, actionButtons], + ), ); } @@ -7146,11 +7495,14 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> break; case DateRangePickerSelectionMode.multiple: { - _selectedDates = _previousSelectedValue.selectedDates != null - ? _getSelectedDates(_previousSelectedValue.selectedDates) - : null; + _selectedDates = + _previousSelectedValue.selectedDates != null + ? _getSelectedDates(_previousSelectedValue.selectedDates) + : null; if (!DateRangePickerHelper.isDateCollectionEquals( - _selectedDates, _controller.selectedDates)) { + _selectedDates, + _controller.selectedDates, + )) { setState(() { _controller.selectedDates = _previousSelectedValue.selectedDates != null @@ -7165,7 +7517,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> { _selectedRange = _previousSelectedValue.selectedRange; if (!DateRangePickerHelper.isRangeEquals( - _selectedRange, _controller.selectedRange)) { + _selectedRange, + _controller.selectedRange, + )) { setState(() { _controller.selectedRange = _selectedRange; }); @@ -7174,17 +7528,21 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> break; case DateRangePickerSelectionMode.multiRange: { - _selectedRanges = _previousSelectedValue.selectedRanges != null - ? _getSelectedRanges(_previousSelectedValue.selectedRanges) - : null; - if (!DateRangePickerHelper.isDateRangesEquals( - _selectedRanges, _controller.selectedRanges)) { - setState(() { - _controller.selectedRanges = _previousSelectedValue - .selectedRanges != - null + _selectedRanges = + _previousSelectedValue.selectedRanges != null ? _getSelectedRanges(_previousSelectedValue.selectedRanges) : null; + if (!DateRangePickerHelper.isDateRangesEquals( + _selectedRanges, + _controller.selectedRanges, + )) { + setState(() { + _controller.selectedRanges = + _previousSelectedValue.selectedRanges != null + ? _getSelectedRanges( + _previousSelectedValue.selectedRanges, + ) + : null; }); } } @@ -7205,8 +7563,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> case DateRangePickerSelectionMode.multiple: { value = _getSelectedDates(_selectedDates); - _previousSelectedValue.selectedDates = - _getSelectedDates(_selectedDates); + _previousSelectedValue.selectedDates = _getSelectedDates( + _selectedDates, + ); } break; case DateRangePickerSelectionMode.range: @@ -7219,8 +7578,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> case DateRangePickerSelectionMode.multiRange: { value = _getSelectedRanges(_selectedRanges); - _previousSelectedValue.selectedRanges = - _getSelectedRanges(_selectedRanges); + _previousSelectedValue.selectedRanges = _getSelectedRanges( + _selectedRanges, + ); } } @@ -7247,29 +7607,31 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> child: _AnimatedOpacityWidget( opacity: _opacity, child: Container( - color: widget.monthViewSettings.viewHeaderStyle.backgroundColor ?? + color: + widget.monthViewSettings.viewHeaderStyle.backgroundColor ?? _datePickerTheme.viewHeaderBackgroundColor, child: RepaintBoundary( child: CustomPaint( painter: _PickerViewHeaderPainter( - _currentViewVisibleDates, - widget.navigationMode, - widget.monthViewSettings.viewHeaderStyle, - widget.monthViewSettings.viewHeaderHeight, - widget.monthViewSettings, - _datePickerTheme, - _locale, - _isRtl, - widget.monthCellStyle, - _isMultiViewEnabled(widget), - widget.viewSpacing, - todayTextColor, - _textScaleFactor, - widget.isHijri, - widget.navigationDirection, - _viewHeaderVisibleDates, - widget.monthViewSettings.showWeekNumber, - _isMobilePlatform), + _currentViewVisibleDates, + widget.navigationMode, + widget.monthViewSettings.viewHeaderStyle, + widget.monthViewSettings.viewHeaderHeight, + widget.monthViewSettings, + _datePickerTheme, + _locale, + _isRtl, + widget.monthCellStyle, + _isMultiViewEnabled(widget), + widget.viewSpacing, + todayTextColor, + _textScaleFactor, + widget.isHijri, + widget.navigationDirection, + _viewHeaderVisibleDates, + widget.monthViewSettings.showWeekNumber, + _isMobilePlatform, + ), ), ), ), @@ -7285,13 +7647,16 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> return; } if (!DateRangePickerHelper.canMoveToNextView( - _view, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri), - widget.maxDate, - _currentViewVisibleDates, - _isMultiViewEnabled(widget), - widget.isHijri)) { + _view, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.monthViewSettings, + widget.isHijri, + ), + widget.maxDate, + _currentViewVisibleDates, + _isMultiViewEnabled(widget), + widget.isHijri, + )) { return; } @@ -7305,13 +7670,16 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> return; } if (!DateRangePickerHelper.canMoveToPreviousView( - _view, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri), - widget.minDate, - _currentViewVisibleDates, - _isMultiViewEnabled(widget), - widget.isHijri)) { + _view, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.monthViewSettings, + widget.isHijri, + ), + widget.minDate, + _currentViewVisibleDates, + _isMultiViewEnabled(widget), + widget.isHijri, + )) { return; } @@ -7351,9 +7719,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } if (_view != details.view) { - _controller.view = widget.isHijri - ? DateRangePickerHelper.getHijriPickerView(details.view) - : DateRangePickerHelper.getPickerView(details.view); + _controller.view = + widget.isHijri + ? DateRangePickerHelper.getHijriPickerView(details.view) + : DateRangePickerHelper.getPickerView(details.view); if (_view == DateRangePickerView.month && widget.navigationDirection == DateRangePickerNavigationDirection.vertical) { @@ -7386,8 +7755,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> case DateRangePickerSelectionMode.single: { _selectedDate = details.selectedDate; - final bool isSameSelectedDate = - isSameDate(_controller.selectedDate, _selectedDate); + final bool isSameSelectedDate = isSameDate( + _controller.selectedDate, + _selectedDate, + ); if (widget.navigationMode == DateRangePickerNavigationMode.scroll && !isSameSelectedDate) { setState(() { @@ -7397,8 +7768,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _controller.selectedDate = _selectedDate; if (!isSameSelectedDate) { - _raiseSelectionChangedCallback(widget, - value: _controller.selectedDate); + _raiseSelectionChangedCallback( + widget, + value: _controller.selectedDate, + ); } } break; @@ -7407,7 +7780,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _selectedDates = details.selectedDates; final bool isSameSelectedDate = DateRangePickerHelper.isDateCollectionEquals( - _selectedDates, _controller.selectedDates); + _selectedDates, + _controller.selectedDates, + ); if (widget.navigationMode == DateRangePickerNavigationMode.scroll && !isSameSelectedDate) { setState(() { @@ -7417,8 +7792,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _controller.selectedDates = _getSelectedDates(_selectedDates); if (!isSameSelectedDate) { - _raiseSelectionChangedCallback(widget, - value: _controller.selectedDates); + _raiseSelectionChangedCallback( + widget, + value: _controller.selectedDates, + ); } } break; @@ -7427,7 +7804,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> { _selectedRange = details.selectedRange; final bool isSameSelectedDate = DateRangePickerHelper.isRangeEquals( - _selectedRange, _controller.selectedRange); + _selectedRange, + _controller.selectedRange, + ); if (widget.navigationMode == DateRangePickerNavigationMode.scroll && !isSameSelectedDate) { setState(() { @@ -7437,8 +7816,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _controller.selectedRange = _selectedRange; if (!isSameSelectedDate) { - _raiseSelectionChangedCallback(widget, - value: _controller.selectedRange); + _raiseSelectionChangedCallback( + widget, + value: _controller.selectedRange, + ); } } break; @@ -7447,7 +7828,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _selectedRanges = details.selectedRanges; final bool isSameSelectedDate = DateRangePickerHelper.isDateRangesEquals( - _selectedRanges, _controller.selectedRanges); + _selectedRanges, + _controller.selectedRanges, + ); if (widget.navigationMode == DateRangePickerNavigationMode.scroll && !isSameSelectedDate) { setState(() { @@ -7457,8 +7840,10 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> _controller.selectedRanges = _getSelectedRanges(_selectedRanges); if (!isSameSelectedDate) { - _raiseSelectionChangedCallback(widget, - value: _controller.selectedRanges); + _raiseSelectionChangedCallback( + widget, + value: _controller.selectedRanges, + ); } } } @@ -7468,8 +7853,9 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> /// Used to call the view changed callback when [_currentViewVisibleDates] /// changed. void _notifyCurrentVisibleDatesChanged() { - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(_controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + _controller.view, + ); dynamic visibleDateRange; switch (view) { case DateRangePickerView.month: @@ -7477,57 +7863,76 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> final bool enableMultiView = _isMultiViewEnabled(widget); if (widget.isHijri || (!DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.monthViewSettings, widget.isHijri) && + widget.monthViewSettings, + widget.isHijri, + ) && DateRangePickerHelper.getNumberOfWeeksInView( - widget.monthViewSettings, widget.isHijri) == + widget.monthViewSettings, + widget.isHijri, + ) == 6)) { - final dynamic visibleDate = _currentViewVisibleDates[ - _currentViewVisibleDates.length ~/ (enableMultiView ? 4 : 2)]; + final dynamic visibleDate = + _currentViewVisibleDates[_currentViewVisibleDates.length ~/ + (enableMultiView ? 4 : 2)]; if (widget.isHijri) { visibleDateRange = HijriDateRange( - DateRangePickerHelper.getMonthStartDate( - visibleDate, widget.isHijri), - enableMultiView - ? DateRangePickerHelper.getMonthEndDate( - DateRangePickerHelper.getNextViewStartDate( - DateRangePickerHelper.getPickerView( - _controller.view), - 6, - visibleDate, - _isRtl, - widget.isHijri)) - : DateRangePickerHelper.getMonthEndDate(visibleDate)); + DateRangePickerHelper.getMonthStartDate( + visibleDate, + widget.isHijri, + ), + enableMultiView + ? DateRangePickerHelper.getMonthEndDate( + DateRangePickerHelper.getNextViewStartDate( + DateRangePickerHelper.getPickerView(_controller.view), + 6, + visibleDate, + _isRtl, + widget.isHijri, + ), + ) + : DateRangePickerHelper.getMonthEndDate(visibleDate), + ); } else { visibleDateRange = PickerDateRange( - DateRangePickerHelper.getMonthStartDate( - visibleDate, widget.isHijri), - enableMultiView - ? DateRangePickerHelper.getMonthEndDate( - DateRangePickerHelper.getNextViewStartDate( - DateRangePickerHelper.getPickerView( - _controller.view), - 6, - visibleDate, - _isRtl, - widget.isHijri)) - : DateRangePickerHelper.getMonthEndDate(visibleDate)); + DateRangePickerHelper.getMonthStartDate( + visibleDate, + widget.isHijri, + ), + enableMultiView + ? DateRangePickerHelper.getMonthEndDate( + DateRangePickerHelper.getNextViewStartDate( + DateRangePickerHelper.getPickerView(_controller.view), + 6, + visibleDate, + _isRtl, + widget.isHijri, + ), + ) + : DateRangePickerHelper.getMonthEndDate(visibleDate), + ); } - _raisePickerViewChangedCallback(widget, - visibleDateRange: visibleDateRange, view: _controller.view); + _raisePickerViewChangedCallback( + widget, + visibleDateRange: visibleDateRange, + view: _controller.view, + ); } else { if (widget.isHijri) { visibleDateRange = HijriDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[ - _currentViewVisibleDates.length - 1]); + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + ); } else { visibleDateRange = PickerDateRange( - _currentViewVisibleDates[0], - _currentViewVisibleDates[ - _currentViewVisibleDates.length - 1]); + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + ); } - _raisePickerViewChangedCallback(widget, - visibleDateRange: visibleDateRange, view: _controller.view); + _raisePickerViewChangedCallback( + widget, + visibleDateRange: visibleDateRange, + view: _controller.view, + ); } } break; @@ -7536,14 +7941,21 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> case DateRangePickerView.century: { if (widget.isHijri) { - visibleDateRange = HijriDateRange(_currentViewVisibleDates[0], - _currentViewVisibleDates[_currentViewVisibleDates.length - 1]); + visibleDateRange = HijriDateRange( + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + ); } else { - visibleDateRange = PickerDateRange(_currentViewVisibleDates[0], - _currentViewVisibleDates[_currentViewVisibleDates.length - 1]); + visibleDateRange = PickerDateRange( + _currentViewVisibleDates[0], + _currentViewVisibleDates[_currentViewVisibleDates.length - 1], + ); } - _raisePickerViewChangedCallback(widget, - visibleDateRange: visibleDateRange, view: _controller.view); + _raisePickerViewChangedCallback( + widget, + visibleDateRange: visibleDateRange, + view: _controller.view, + ); } } } @@ -7599,20 +8011,31 @@ class _SfDateRangePickerState extends State<_SfDateRangePicker> } if (_view == DateRangePickerView.month) { - _controller.view = widget.isHijri - ? DateRangePickerHelper.getHijriPickerView(DateRangePickerView.year) - : DateRangePickerHelper.getPickerView(DateRangePickerView.year); + _controller.view = + widget.isHijri + ? DateRangePickerHelper.getHijriPickerView( + DateRangePickerView.year, + ) + : DateRangePickerHelper.getPickerView(DateRangePickerView.year); } else { if (_view == DateRangePickerView.year) { - _controller.view = widget.isHijri - ? DateRangePickerHelper.getHijriPickerView( - DateRangePickerView.decade) - : DateRangePickerHelper.getPickerView(DateRangePickerView.decade); + _controller.view = + widget.isHijri + ? DateRangePickerHelper.getHijriPickerView( + DateRangePickerView.decade, + ) + : DateRangePickerHelper.getPickerView( + DateRangePickerView.decade, + ); } else if (_view == DateRangePickerView.decade) { - _controller.view = widget.isHijri - ? DateRangePickerHelper.getHijriPickerView( - DateRangePickerView.century) - : DateRangePickerHelper.getPickerView(DateRangePickerView.century); + _controller.view = + widget.isHijri + ? DateRangePickerHelper.getHijriPickerView( + DateRangePickerView.century, + ) + : DateRangePickerHelper.getPickerView( + DateRangePickerView.century, + ); } } } @@ -7671,11 +8094,7 @@ class _StickyHeader extends Stack { this.isHorizontal = false, this.isRTL = false, Key? key, - }) : super( - key: key, - children: children, - alignment: alignment, - ); + }) : super(key: key, children: children, alignment: alignment); final bool isHorizontal; final bool isRTL; @@ -7713,14 +8132,10 @@ class _StickyHeaderRenderObject extends RenderStack { required StackFit fit, required bool isHorizontal, required bool isRTL, - }) : _scrollableState = scrollableState, - _isHorizontal = isHorizontal, - _isRTL = isRTL, - super( - alignment: alignment, - textDirection: textDirection, - fit: fit, - ); + }) : _scrollableState = scrollableState, + _isHorizontal = isHorizontal, + _isRTL = isRTL, + super(alignment: alignment, textDirection: textDirection, fit: fit); /// Used to update the child position when it scroll changed. ScrollableState _scrollableState; @@ -7820,20 +8235,25 @@ class _StickyHeaderRenderObject extends RenderStack { /// Eg., If initially header in position 0 then calculate the offset on RTL /// by content size(total control size) - header size(total header widget /// size) - 0 and the header placed on right side end. - final double headerYOffset = _isRTL && _isHorizontal - ? contentSize - - headerSize - - _getHeaderOffset(contentSize, offset, headerSize) - : _getHeaderOffset(contentSize, offset, headerSize); + final double headerYOffset = + _isRTL && _isHorizontal + ? contentSize - + headerSize - + _getHeaderOffset(contentSize, offset, headerSize) + : _getHeaderOffset(contentSize, offset, headerSize); /// Update the header start y position on vertical direction or update the /// header start x position on horizontal direction. if (!_isHorizontal && headerYOffset != headerParentData?.offset.dy) { - headerParentData?.offset = - Offset(headerParentData.offset.dx, headerYOffset); + headerParentData?.offset = Offset( + headerParentData.offset.dx, + headerYOffset, + ); } else if (_isHorizontal && headerYOffset != headerParentData?.offset.dx) { - headerParentData?.offset = - Offset(headerYOffset, headerParentData.offset.dy); + headerParentData?.offset = Offset( + headerYOffset, + headerParentData.offset.dy, + ); } } @@ -7887,34 +8307,34 @@ class _StickyHeaderRenderObject extends RenderStack { class _PickerHeaderView extends StatefulWidget { /// Constructor to create picker header view instance. const _PickerHeaderView( - this.visibleDates, - this.headerStyle, - this.selectionMode, - this.view, - this.numberOfWeeksInView, - this.showNavigationArrow, - this.navigationDirection, - this.enableSwipeSelection, - this.navigationMode, - this.minDate, - this.maxDate, - this.monthFormat, - this.datePickerTheme, - this.locale, - this.width, - this.height, - this.allowViewNavigation, - this.previousNavigationCallback, - this.nextNavigationCallback, - this.enableMultiView, - this.multiViewSpacing, - this.hoverColor, - this.isRtl, - this.textScaleFactor, - this.isHijri, - this.localizations, - {Key? key}) - : super(key: key); + this.visibleDates, + this.headerStyle, + this.selectionMode, + this.view, + this.numberOfWeeksInView, + this.showNavigationArrow, + this.navigationDirection, + this.enableSwipeSelection, + this.navigationMode, + this.minDate, + this.maxDate, + this.monthFormat, + this.datePickerTheme, + this.locale, + this.width, + this.height, + this.allowViewNavigation, + this.previousNavigationCallback, + this.nextNavigationCallback, + this.enableMultiView, + this.multiViewSpacing, + this.hoverColor, + this.isRtl, + this.textScaleFactor, + this.isHijri, + this.localizations, { + Key? key, + }) : super(key: key); /// Defines the text scale factor of [SfDateRangePicker]. final double textScaleFactor; @@ -8016,21 +8436,26 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { @override Widget build(BuildContext context) { - final bool isMobilePlatform = - DateRangePickerHelper.isMobileLayout(Theme.of(context).platform); + final bool isMobilePlatform = DateRangePickerHelper.isMobileLayout( + Theme.of(context).platform, + ); double arrowWidth = 0; double headerWidth = widget.width; - bool showNavigationArrow = widget.showNavigationArrow || + bool showNavigationArrow = + widget.showNavigationArrow || ((widget.view == DateRangePickerView.month || !widget.allowViewNavigation) && _isSwipeInteractionEnabled( - widget.enableSwipeSelection, widget.navigationMode) && + widget.enableSwipeSelection, + widget.navigationMode, + ) && (widget.selectionMode == DateRangePickerSelectionMode.range || widget.selectionMode == DateRangePickerSelectionMode.multiRange || widget.selectionMode == DateRangePickerSelectionMode.extendableRange)); - showNavigationArrow = showNavigationArrow && + showNavigationArrow = + showNavigationArrow && widget.navigationMode != DateRangePickerNavigationMode.scroll; if (showNavigationArrow) { arrowWidth = widget.width / 6; @@ -8045,23 +8470,25 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { final List dates = widget.visibleDates.value; if (showNavigationArrow && !DateRangePickerHelper.canMoveToNextView( - widget.view, - widget.numberOfWeeksInView, - widget.maxDate, - dates, - widget.enableMultiView, - widget.isHijri)) { + widget.view, + widget.numberOfWeeksInView, + widget.maxDate, + dates, + widget.enableMultiView, + widget.isHijri, + )) { nextArrowColor = nextArrowColor.withValues(alpha: arrowColor.a * 0.5); } if (showNavigationArrow && !DateRangePickerHelper.canMoveToPreviousView( - widget.view, - widget.numberOfWeeksInView, - widget.minDate, - dates, - widget.enableMultiView, - widget.isHijri)) { + widget.view, + widget.numberOfWeeksInView, + widget.minDate, + dates, + widget.enableMultiView, + widget.isHijri, + )) { prevArrowColor = prevArrowColor.withValues(alpha: arrowColor.a * 0.5); } @@ -8075,40 +8502,33 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { double arrowSize = widget.height * 0.5; arrowSize = arrowSize > 25 ? 25 : arrowSize; arrowSize = arrowSize * widget.textScaleFactor; - final Container leftArrow = showNavigationArrow - ? _getLeftArrow(arrowWidth, arrowColor, prevArrowColor, arrowSize) - : Container(); + final Container leftArrow = + showNavigationArrow + ? _getLeftArrow(arrowWidth, arrowColor, prevArrowColor, arrowSize) + : Container(); - final Container rightArrow = showNavigationArrow - ? _getRightArrow(arrowWidth, arrowColor, nextArrowColor, arrowSize) - : Container(); + final Container rightArrow = + showNavigationArrow + ? _getRightArrow(arrowWidth, arrowColor, nextArrowColor, arrowSize) + : Container(); if (widget.headerStyle.textAlign == TextAlign.left || widget.headerStyle.textAlign == TextAlign.start) { return Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - headerText, - leftArrow, - rightArrow, - ]); + mainAxisAlignment: MainAxisAlignment.center, + children: [headerText, leftArrow, rightArrow], + ); } else if (widget.headerStyle.textAlign == TextAlign.right || widget.headerStyle.textAlign == TextAlign.end) { return Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - leftArrow, - rightArrow, - headerText, - ]); + mainAxisAlignment: MainAxisAlignment.center, + children: [leftArrow, rightArrow, headerText], + ); } else { return Row( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - leftArrow, - headerText, - rightArrow, - ]); + mainAxisAlignment: MainAxisAlignment.center, + children: [leftArrow, headerText, rightArrow], + ); } } @@ -8127,7 +8547,9 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { ((widget.view == DateRangePickerView.month || !widget.allowViewNavigation) && _isSwipeInteractionEnabled( - widget.enableSwipeSelection, widget.navigationMode) && + widget.enableSwipeSelection, + widget.navigationMode, + ) && (widget.selectionMode == DateRangePickerSelectionMode.range || widget.selectionMode == DateRangePickerSelectionMode.multiRange || @@ -8147,62 +8569,70 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { Widget _getHeaderText(double headerWidth, bool isMobilePlatform) { return MouseRegion( - onEnter: (PointerEnterEvent event) { - if (widget.view == DateRangePickerView.century || - (widget.isHijri && widget.view == DateRangePickerView.decade) || - isMobilePlatform) { - return; - } + onEnter: (PointerEnterEvent event) { + if (widget.view == DateRangePickerView.century || + (widget.isHijri && widget.view == DateRangePickerView.decade) || + isMobilePlatform) { + return; + } - setState(() { - _hovering = true; - }); - }, - onHover: (PointerHoverEvent event) { - if (widget.view == DateRangePickerView.century || - (widget.isHijri && widget.view == DateRangePickerView.decade) || - isMobilePlatform) { - return; - } + setState(() { + _hovering = true; + }); + }, + onHover: (PointerHoverEvent event) { + if (widget.view == DateRangePickerView.century || + (widget.isHijri && widget.view == DateRangePickerView.decade) || + isMobilePlatform) { + return; + } - setState(() { - _hovering = true; - }); - }, - onExit: (PointerExitEvent event) { - setState(() { - _hovering = false; - }); - }, - child: RepaintBoundary( - child: CustomPaint( + setState(() { + _hovering = true; + }); + }, + onExit: (PointerExitEvent event) { + setState(() { + _hovering = false; + }); + }, + child: RepaintBoundary( + child: CustomPaint( // Returns the header view as a child for the picker. painter: _PickerHeaderPainter( - widget.visibleDates, - widget.headerStyle, - widget.view, - widget.numberOfWeeksInView, - widget.monthFormat, - widget.datePickerTheme, - widget.isRtl, - widget.locale, - widget.enableMultiView, - widget.multiViewSpacing, - widget.hoverColor, - _hovering, - widget.textScaleFactor, - widget.isHijri, - widget.localizations, - widget.navigationDirection), + widget.visibleDates, + widget.headerStyle, + widget.view, + widget.numberOfWeeksInView, + widget.monthFormat, + widget.datePickerTheme, + widget.isRtl, + widget.locale, + widget.enableMultiView, + widget.multiViewSpacing, + widget.hoverColor, + _hovering, + widget.textScaleFactor, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + ), size: Size(headerWidth, widget.height), - ))); + ), + ), + ); } - Container _getLeftArrow(double arrowWidth, Color arrowColor, - Color prevArrowColor, double arrowSize) { + Container _getLeftArrow( + double arrowWidth, + Color arrowColor, + Color prevArrowColor, + double arrowSize, + ) { return Container( alignment: Alignment.center, - color: widget.headerStyle.backgroundColor ?? + color: + widget.headerStyle.backgroundColor ?? widget.datePickerTheme.headerBackgroundColor, width: arrowWidth, padding: EdgeInsets.zero, @@ -8212,7 +8642,8 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { hoverColor: prevArrowColor != arrowColor ? Colors.transparent : null, highlightColor: prevArrowColor != arrowColor ? Colors.transparent : null, - color: widget.headerStyle.backgroundColor ?? + color: + widget.headerStyle.backgroundColor ?? widget.datePickerTheme.headerBackgroundColor, onPressed: widget.previousNavigationCallback, padding: EdgeInsets.zero, @@ -8236,11 +8667,16 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { ); } - Container _getRightArrow(double arrowWidth, Color arrowColor, - Color nextArrowColor, double arrowSize) { + Container _getRightArrow( + double arrowWidth, + Color arrowColor, + Color nextArrowColor, + double arrowSize, + ) { return Container( alignment: Alignment.center, - color: widget.headerStyle.backgroundColor ?? + color: + widget.headerStyle.backgroundColor ?? widget.datePickerTheme.headerBackgroundColor, width: arrowWidth, padding: EdgeInsets.zero, @@ -8250,7 +8686,8 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { hoverColor: nextArrowColor != arrowColor ? Colors.transparent : null, highlightColor: nextArrowColor != arrowColor ? Colors.transparent : null, - color: widget.headerStyle.backgroundColor ?? + color: + widget.headerStyle.backgroundColor ?? widget.datePickerTheme.headerBackgroundColor, onPressed: widget.nextNavigationCallback, padding: EdgeInsets.zero, @@ -8277,23 +8714,23 @@ class _PickerHeaderViewState extends State<_PickerHeaderView> { class _PickerHeaderPainter extends CustomPainter { _PickerHeaderPainter( - this.visibleDates, - this.headerStyle, - this.view, - this.numberOfWeeksInView, - this.monthFormat, - this.datePickerTheme, - this.isRtl, - this.locale, - this.enableMultiView, - this.multiViewSpacing, - this.hoverColor, - this.hovering, - this.textScaleFactor, - this.isHijri, - this.localizations, - this.navigationDirection) - : super(repaint: visibleDates); + this.visibleDates, + this.headerStyle, + this.view, + this.numberOfWeeksInView, + this.monthFormat, + this.datePickerTheme, + this.isRtl, + this.locale, + this.enableMultiView, + this.multiViewSpacing, + this.hoverColor, + this.hovering, + this.textScaleFactor, + this.isHijri, + this.localizations, + this.navigationDirection, + ) : super(repaint: visibleDates); final DateRangePickerHeaderStyle headerStyle; final DateRangePickerView view; @@ -8324,35 +8761,38 @@ class _PickerHeaderPainter extends CustomPainter { _textPainter.maxLines = 1; _headerText = ''; - final double width = (enableMultiView && - navigationDirection == - DateRangePickerNavigationDirection.horizontal) && - headerStyle.textAlign == TextAlign.center - ? (size.width - multiViewSpacing) / 2 - : size.width; - final int count = (enableMultiView && - navigationDirection == - DateRangePickerNavigationDirection.horizontal) && - headerStyle.textAlign == TextAlign.center - ? 2 - : 1; + final double width = + (enableMultiView && + navigationDirection == + DateRangePickerNavigationDirection.horizontal) && + headerStyle.textAlign == TextAlign.center + ? (size.width - multiViewSpacing) / 2 + : size.width; + final int count = + (enableMultiView && + navigationDirection == + DateRangePickerNavigationDirection.horizontal) && + headerStyle.textAlign == TextAlign.center + ? 2 + : 1; for (int j = 0; j < count; j++) { final int currentViewIndex = isRtl ? DateRangePickerHelper.getRtlIndex(count, j) : j; xPosition = (currentViewIndex * width) + 10; final String text = _getHeaderText( - visibleDates.value, - view, - j, - isHijri, - numberOfWeeksInView, - monthFormat, - enableMultiView, - headerStyle, - navigationDirection, - locale, - localizations); + visibleDates.value, + view, + j, + isHijri, + numberOfWeeksInView, + monthFormat, + enableMultiView, + headerStyle, + navigationDirection, + locale, + localizations, + ); _headerText += j == 1 ? ' $text' : text; TextStyle? style = datePickerTheme.headerTextStyle; if (hovering) { @@ -8371,7 +8811,8 @@ class _PickerHeaderPainter extends CustomPainter { _textPainter.layout(maxWidth: textWidth); if (headerStyle.textAlign == TextAlign.center) { - xPosition = (currentViewIndex * width) + + xPosition = + (currentViewIndex * width) + (currentViewIndex * multiViewSpacing) + (width / 2) - (_textPainter.width / 2); @@ -8385,7 +8826,9 @@ class _PickerHeaderPainter extends CustomPainter { ((currentViewIndex + 1) * width) - _textPainter.width - xPosition; } _textPainter.paint( - canvas, Offset(xPosition, size.height / 2 - _textPainter.height / 2)); + canvas, + Offset(xPosition, size.height / 2 - _textPainter.height / 2), + ); } } @@ -8432,25 +8875,25 @@ class _PickerHeaderPainter extends CustomPainter { class _PickerViewHeaderPainter extends CustomPainter { /// Constructor to create picker view header view instance. _PickerViewHeaderPainter( - this.visibleDates, - this.navigationMode, - this.viewHeaderStyle, - this.viewHeaderHeight, - this.monthViewSettings, - this.datePickerTheme, - this.locale, - this.isRtl, - this.monthCellStyle, - this.enableMultiView, - this.multiViewSpacing, - this.todayHighlightColor, - this.textScaleFactor, - this.isHijri, - this.navigationDirection, - this.viewHeaderVisibleDates, - this.showWeekNumber, - this.isMobilePlatform) - : super(repaint: viewHeaderVisibleDates); + this.visibleDates, + this.navigationMode, + this.viewHeaderStyle, + this.viewHeaderHeight, + this.monthViewSettings, + this.datePickerTheme, + this.locale, + this.isRtl, + this.monthCellStyle, + this.enableMultiView, + this.multiViewSpacing, + this.todayHighlightColor, + this.textScaleFactor, + this.isHijri, + this.navigationDirection, + this.viewHeaderVisibleDates, + this.showWeekNumber, + this.isMobilePlatform, + ) : super(repaint: viewHeaderVisibleDates); /// Defines the view header style. final DateRangePickerViewHeaderStyle viewHeaderStyle; @@ -8497,9 +8940,10 @@ class _PickerViewHeaderPainter extends CustomPainter { /// Defines the navigation direction for [SfDateRangePicker]. final DateRangePickerNavigationDirection navigationDirection; final TextPainter _textPainter = TextPainter( - textDirection: TextDirection.ltr, - textAlign: TextAlign.left, - textWidthBasis: TextWidthBasis.longestLine); + textDirection: TextDirection.ltr, + textAlign: TextAlign.left, + textWidthBasis: TextWidthBasis.longestLine, + ); final ValueNotifier>? viewHeaderVisibleDates; @@ -8514,16 +8958,21 @@ class _PickerViewHeaderPainter extends CustomPainter { canvas.clipRect(Rect.fromLTWH(0, 0, size.width, size.height)); final double weekNumberPanelWidth = DateRangePickerHelper.getWeekNumberPanelWidth( - showWeekNumber, size.width, isMobilePlatform); - double width = showWeekNumber - ? (size.width - weekNumberPanelWidth) / DateTime.daysPerWeek - : size.width / DateTime.daysPerWeek; + showWeekNumber, + size.width, + isMobilePlatform, + ); + double width = + showWeekNumber + ? (size.width - weekNumberPanelWidth) / DateTime.daysPerWeek + : size.width / DateTime.daysPerWeek; if (enableMultiView && navigationDirection == DateRangePickerNavigationDirection.horizontal) { - width = showWeekNumber - ? (size.width - multiViewSpacing - (weekNumberPanelWidth * 2)) / - (DateTime.daysPerWeek * 2) - : (size.width - multiViewSpacing) / (DateTime.daysPerWeek * 2); + width = + showWeekNumber + ? (size.width - multiViewSpacing - (weekNumberPanelWidth * 2)) / + (DateTime.daysPerWeek * 2) + : (size.width - multiViewSpacing) / (DateTime.daysPerWeek * 2); } /// Initializes the default text style for the texts in view header of @@ -8533,22 +8982,25 @@ class _PickerViewHeaderPainter extends CustomPainter { TextStyle? dayTextStyle = viewHeaderDayStyle; double xPosition = isRtl ? 0 : weekNumberPanelWidth; double yPosition = 0; - final int count = (enableMultiView && - navigationDirection == - DateRangePickerNavigationDirection.horizontal) - ? 2 - : 1; - final int datesCount = (enableMultiView && - navigationDirection == - DateRangePickerNavigationDirection.horizontal) - ? visibleDates.length ~/ 2 - : visibleDates.length; + final int count = + (enableMultiView && + navigationDirection == + DateRangePickerNavigationDirection.horizontal) + ? 2 + : 1; + final int datesCount = + (enableMultiView && + navigationDirection == + DateRangePickerNavigationDirection.horizontal) + ? visibleDates.length ~/ 2 + : visibleDates.length; final bool isVerticalScroll = navigationDirection == DateRangePickerNavigationDirection.vertical && - navigationMode == DateRangePickerNavigationMode.scroll; - visibleDates = viewHeaderVisibleDates != null - ? viewHeaderVisibleDates!.value - : visibleDates; + navigationMode == DateRangePickerNavigationMode.scroll; + visibleDates = + viewHeaderVisibleDates != null + ? viewHeaderVisibleDates!.value + : visibleDates; for (int j = 0; j < count; j++) { final int currentViewIndex = @@ -8556,7 +9008,8 @@ class _PickerViewHeaderPainter extends CustomPainter { dynamic currentDate; final int month = visibleDates[(currentViewIndex * datesCount) + (datesCount ~/ 2)] - .month as int; + .month + as int; final int year = visibleDates[(currentViewIndex * datesCount) + (datesCount ~/ 2)].year as int; @@ -8565,18 +9018,23 @@ class _PickerViewHeaderPainter extends CustomPainter { final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - monthViewSettings, isHijri); + monthViewSettings, + isHijri, + ); final bool isTodayMonth = isDateWithInDateRange( - visibleDates[(currentViewIndex * datesCount)], - visibleDates[((currentViewIndex + 1) * datesCount) - 1], - today); - final bool hasToday = isVerticalScroll || + visibleDates[(currentViewIndex * datesCount)], + visibleDates[((currentViewIndex + 1) * datesCount) - 1], + today, + ); + final bool hasToday = + isVerticalScroll || (numberOfWeeksInView > 0 && numberOfWeeksInView < 6 || month == currentMonth && year == currentYear); for (int i = 0; i < DateTime.daysPerWeek; i++) { - int index = isRtl - ? DateRangePickerHelper.getRtlIndex(DateTime.daysPerWeek, i) - : i; + int index = + isRtl + ? DateRangePickerHelper.getRtlIndex(DateTime.daysPerWeek, i) + : i; index = index + (currentViewIndex * datesCount); currentDate = visibleDates[index]; String dayText = @@ -8588,10 +9046,11 @@ class _PickerViewHeaderPainter extends CustomPainter { if (hasToday && currentDate.weekday == today.weekday && (isTodayMonth || isVerticalScroll)) { - final Color textColor = monthCellStyle.todayTextStyle != null && - monthCellStyle.todayTextStyle.color != null - ? monthCellStyle.todayTextStyle.color! as Color - : todayHighlightColor ?? datePickerTheme.todayHighlightColor!; + final Color textColor = + monthCellStyle.todayTextStyle != null && + monthCellStyle.todayTextStyle.color != null + ? monthCellStyle.todayTextStyle.color! as Color + : todayHighlightColor ?? datePickerTheme.todayHighlightColor!; dayTextStyle = viewHeaderDayStyle!.copyWith(color: textColor); } else { dayTextStyle = viewHeaderDayStyle; @@ -8607,9 +9066,9 @@ class _PickerViewHeaderPainter extends CustomPainter { _textPainter.layout(maxWidth: width); yPosition = (viewHeaderHeight - _textPainter.height) / 2; _textPainter.paint( - canvas, - Offset( - xPosition + (width / 2 - _textPainter.width / 2), yPosition)); + canvas, + Offset(xPosition + (width / 2 - _textPainter.width / 2), yPosition), + ); xPosition += width; } @@ -8665,17 +9124,22 @@ class _PickerViewHeaderPainter extends CustomPainter { const double top = 0; for (int j = 0; j < count; j++) { for (int i = 0; i < DateTime.daysPerWeek; i++) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(left, top, cellWidth, size.height), - properties: SemanticsProperties( - label: DateFormat('EEEEE') - .format(isHijri - ? visibleDates[(j * datesCount) + i].toDateTime() - : visibleDates[(j * datesCount) + i]) - .toUpperCase(), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH(left, top, cellWidth, size.height), + properties: SemanticsProperties( + label: + DateFormat('EEEEE') + .format( + isHijri + ? visibleDates[(j * datesCount) + i].toDateTime() + : visibleDates[(j * datesCount) + i], + ) + .toUpperCase(), + textDirection: TextDirection.ltr, + ), ), - )); + ); if (isRtl) { left -= cellWidth; } else { @@ -8817,7 +9281,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _triggerSelectableDayPredicates(_currentViewVisibleDates); _triggerViewChangedCallback(); _animationController = AnimationController( - duration: const Duration(milliseconds: 250), vsync: this); + duration: const Duration(milliseconds: 250), + vsync: this, + ); _tween = Tween(begin: 0.0, end: 0.1); _animation = _tween.animate(_animationController) ..addListener(_animationListener); @@ -8858,8 +9324,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _updateSettings(oldWidget); - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView == DateRangePickerView.year && widget.picker.monthFormat != oldWidget.picker.monthFormat) { @@ -8897,26 +9364,37 @@ class _PickerScrollViewState extends State<_PickerScrollView> oldWidget.picker.monthViewSettings.viewHeaderHeight != widget.picker.monthViewSettings.viewHeaderHeight || DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri) != + widget.picker.monthViewSettings, + widget.picker.isHijri, + ) != DateRangePickerHelper.canShowLeadingAndTrailingDates( - oldWidget.picker.monthViewSettings, - oldWidget.picker.isHijri))) { + oldWidget.picker.monthViewSettings, + oldWidget.picker.isHijri, + ))) { _children.clear(); _position = 0; if (DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri) != + widget.picker.monthViewSettings, + widget.picker.isHijri, + ) != DateRangePickerHelper.canShowLeadingAndTrailingDates( - oldWidget.picker.monthViewSettings, oldWidget.picker.isHijri)) { + oldWidget.picker.monthViewSettings, + oldWidget.picker.isHijri, + )) { _disabledDates?.clear(); _triggerSelectableDayPredicates(_currentViewVisibleDates); } } if (DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri) != + widget.picker.monthViewSettings, + widget.picker.isHijri, + ) != DateRangePickerHelper.getNumberOfWeeksInView( - oldWidget.picker.monthViewSettings, oldWidget.picker.isHijri) || + oldWidget.picker.monthViewSettings, + oldWidget.picker.isHijri, + ) || widget.picker.monthViewSettings.firstDayOfWeek != oldWidget.picker.monthViewSettings.firstDayOfWeek) { _updateVisibleDates(); @@ -8938,7 +9416,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } if (!isSameDate( - _pickerStateDetails.currentDate, widget.controller.displayDate)) { + _pickerStateDetails.currentDate, + widget.controller.displayDate, + )) { _pickerStateDetails.currentDate = widget.controller?.displayDate; _updateVisibleDates(); _triggerSelectableDayPredicates(_currentViewVisibleDates); @@ -8985,56 +9465,63 @@ class _PickerScrollViewState extends State<_PickerScrollView> bottom: bottomPosition, top: topPosition, child: GestureDetector( - onHorizontalDragStart: widget.picker.navigationDirection == - DateRangePickerNavigationDirection.horizontal && - widget.picker.navigationMode != - DateRangePickerNavigationMode.none - ? _onHorizontalStart - : null, - onHorizontalDragUpdate: widget.picker.navigationDirection == - DateRangePickerNavigationDirection.horizontal && - widget.picker.navigationMode != - DateRangePickerNavigationMode.none - ? _onHorizontalUpdate - : null, - onHorizontalDragEnd: widget.picker.navigationDirection == - DateRangePickerNavigationDirection.horizontal && - widget.picker.navigationMode != - DateRangePickerNavigationMode.none - ? _onHorizontalEnd - : null, - onVerticalDragStart: widget.picker.navigationDirection == - DateRangePickerNavigationDirection.vertical && - widget.picker.navigationMode != - DateRangePickerNavigationMode.none - ? _onVerticalStart - : null, - onVerticalDragUpdate: widget.picker.navigationDirection == - DateRangePickerNavigationDirection.vertical && - widget.picker.navigationMode != - DateRangePickerNavigationMode.none - ? _onVerticalUpdate - : null, - onVerticalDragEnd: widget.picker.navigationDirection == - DateRangePickerNavigationDirection.vertical && - widget.picker.navigationMode != - DateRangePickerNavigationMode.none - ? _onVerticalEnd - : null, + onHorizontalDragStart: + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.horizontal && + widget.picker.navigationMode != + DateRangePickerNavigationMode.none + ? _onHorizontalStart + : null, + onHorizontalDragUpdate: + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.horizontal && + widget.picker.navigationMode != + DateRangePickerNavigationMode.none + ? _onHorizontalUpdate + : null, + onHorizontalDragEnd: + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.horizontal && + widget.picker.navigationMode != + DateRangePickerNavigationMode.none + ? _onHorizontalEnd + : null, + onVerticalDragStart: + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.vertical && + widget.picker.navigationMode != + DateRangePickerNavigationMode.none + ? _onVerticalStart + : null, + onVerticalDragUpdate: + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.vertical && + widget.picker.navigationMode != + DateRangePickerNavigationMode.none + ? _onVerticalUpdate + : null, + onVerticalDragEnd: + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.vertical && + widget.picker.navigationMode != + DateRangePickerNavigationMode.none + ? _onVerticalEnd + : null, child: FocusScope( node: _focusNode, onKeyEvent: _onKeyDown, child: CustomScrollViewerLayout( - _addViews(context), - widget.picker.navigationDirection == - DateRangePickerNavigationDirection.horizontal - ? CustomScrollDirection.horizontal - : CustomScrollDirection.vertical, - _position, - _currentChildIndex), + _addViews(context), + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.horizontal + ? CustomScrollDirection.horizontal + : CustomScrollDirection.vertical, + _position, + _currentChildIndex, + ), ), ), - ) + ), ], ); } @@ -9054,34 +9541,40 @@ class _PickerScrollViewState extends State<_PickerScrollView> widget.getPickerStateValues(_pickerStateDetails); final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); final dynamic currentDate = _pickerStateDetails.currentDate; final dynamic prevDate = DateRangePickerHelper.getPreviousViewStartDate( - DateRangePickerHelper.getPickerView(widget.controller.view), - numberOfWeeksInView, - _pickerStateDetails.currentDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerHelper.getPickerView(widget.controller.view), + numberOfWeeksInView, + _pickerStateDetails.currentDate, + widget.isRtl, + widget.picker.isHijri, + ); final dynamic nextDate = DateRangePickerHelper.getNextViewStartDate( - DateRangePickerHelper.getPickerView(widget.controller.view), - numberOfWeeksInView, - _pickerStateDetails.currentDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerHelper.getPickerView(widget.controller.view), + numberOfWeeksInView, + _pickerStateDetails.currentDate, + widget.isRtl, + widget.picker.isHijri, + ); dynamic afterNextViewDate; List? afterVisibleDates; if (widget.picker.enableMultiView) { afterNextViewDate = DateRangePickerHelper.getNextViewStartDate( - DateRangePickerHelper.getPickerView(widget.controller.view), - numberOfWeeksInView, - widget.isRtl ? prevDate : nextDate, - false, - widget.picker.isHijri); + DateRangePickerHelper.getPickerView(widget.controller.view), + numberOfWeeksInView, + widget.isRtl ? prevDate : nextDate, + false, + widget.picker.isHijri, + ); } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (view) { case DateRangePickerView.month: @@ -9091,21 +9584,30 @@ class _PickerScrollViewState extends State<_PickerScrollView> null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); _previousViewVisibleDates = getVisibleDates( prevDate, null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); _nextViewVisibleDates = getVisibleDates( nextDate, null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); if (widget.picker.enableMultiView) { afterVisibleDates = getVisibleDates( @@ -9113,7 +9615,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); } } @@ -9123,14 +9628,26 @@ class _PickerScrollViewState extends State<_PickerScrollView> case DateRangePickerView.century: { _visibleDates = DateRangePickerHelper.getVisibleYearDates( - currentDate, view, widget.picker.isHijri); + currentDate, + view, + widget.picker.isHijri, + ); _previousViewVisibleDates = DateRangePickerHelper.getVisibleYearDates( - prevDate, view, widget.picker.isHijri); + prevDate, + view, + widget.picker.isHijri, + ); _nextViewVisibleDates = DateRangePickerHelper.getVisibleYearDates( - nextDate, view, widget.picker.isHijri); + nextDate, + view, + widget.picker.isHijri, + ); if (widget.picker.enableMultiView) { afterVisibleDates = DateRangePickerHelper.getVisibleYearDates( - afterNextViewDate, view, widget.picker.isHijri); + afterNextViewDate, + view, + widget.picker.isHijri, + ); } } } @@ -9186,9 +9703,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _triggerSelectableDayPredicates(_getCurrentVisibleDates(true)); _animationController.duration = const Duration(milliseconds: 500); - _animationController - .forward() - .then((dynamic value) => _updateNextView()); + _animationController.forward().then( + (dynamic value) => _updateNextView(), + ); /// updates the current view visible dates when the view swiped _updateCurrentViewVisibleDates(isNextView: true); @@ -9219,9 +9736,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _triggerSelectableDayPredicates(_getCurrentVisibleDates(false)); _animationController.duration = const Duration(milliseconds: 500); - _animationController - .forward() - .then((dynamic value) => _updatePreviousView()); + _animationController.forward().then( + (dynamic value) => _updatePreviousView(), + ); /// updates the current view visible dates when the view swiped. _updateCurrentViewVisibleDates(); @@ -9252,41 +9769,47 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _updateNextViewVisibleDates() { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); dynamic currentViewDate = _currentViewVisibleDates[0]; if ((pickerView == DateRangePickerView.month && (numberOfWeeksInView == 6 || widget.picker.isHijri)) || pickerView == DateRangePickerView.year || pickerView == DateRangePickerView.decade || pickerView == DateRangePickerView.century) { - currentViewDate = _currentViewVisibleDates[ - (_currentViewVisibleDates.length / + currentViewDate = + _currentViewVisibleDates[(_currentViewVisibleDates.length / (widget.picker.enableMultiView ? 4 : 2)) .truncate()]; } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); currentViewDate = DateRangePickerHelper.getNextViewStartDate( - view, - numberOfWeeksInView, - currentViewDate, - widget.isRtl, - widget.picker.isHijri); + view, + numberOfWeeksInView, + currentViewDate, + widget.isRtl, + widget.picker.isHijri, + ); List? afterVisibleDates; dynamic afterNextViewDate; if (widget.picker.enableMultiView && !widget.isRtl) { afterNextViewDate = DateRangePickerHelper.getNextViewStartDate( - view, - numberOfWeeksInView, - currentViewDate, - widget.isRtl, - widget.picker.isHijri); + view, + numberOfWeeksInView, + currentViewDate, + widget.isRtl, + widget.picker.isHijri, + ); } List dates; switch (view) { @@ -9297,7 +9820,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); if (widget.picker.enableMultiView && !widget.isRtl) { afterVisibleDates = getVisibleDates( @@ -9305,7 +9831,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); } } @@ -9315,10 +9844,16 @@ class _PickerScrollViewState extends State<_PickerScrollView> case DateRangePickerView.century: { dates = DateRangePickerHelper.getVisibleYearDates( - currentViewDate, view, widget.picker.isHijri); + currentViewDate, + view, + widget.picker.isHijri, + ); if (widget.picker.enableMultiView && !widget.isRtl) { afterVisibleDates = DateRangePickerHelper.getVisibleYearDates( - afterNextViewDate, view, widget.picker.isHijri); + afterNextViewDate, + view, + widget.picker.isHijri, + ); } } } @@ -9337,7 +9872,8 @@ class _PickerScrollViewState extends State<_PickerScrollView> } List _updateNextVisibleDateForMultiView( - List? afterVisibleDates) { + List? afterVisibleDates, + ) { List dates; if (widget.picker.isHijri) { dates = []; @@ -9358,42 +9894,48 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _updatePreviousViewVisibleDates() { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); dynamic currentViewDate = _currentViewVisibleDates[0]; if ((pickerView == DateRangePickerView.month && (numberOfWeeksInView == 6 || widget.picker.isHijri)) || pickerView == DateRangePickerView.year || pickerView == DateRangePickerView.decade || pickerView == DateRangePickerView.century) { - currentViewDate = _currentViewVisibleDates[ - (_currentViewVisibleDates.length / + currentViewDate = + _currentViewVisibleDates[(_currentViewVisibleDates.length / (widget.picker.enableMultiView ? 4 : 2)) .truncate()]; } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); currentViewDate = DateRangePickerHelper.getPreviousViewStartDate( - view, - numberOfWeeksInView, - currentViewDate, - widget.isRtl, - widget.picker.isHijri); + view, + numberOfWeeksInView, + currentViewDate, + widget.isRtl, + widget.picker.isHijri, + ); List dates; List? afterVisibleDates; dynamic afterNextViewDate; if (widget.picker.enableMultiView && widget.isRtl) { afterNextViewDate = DateRangePickerHelper.getPreviousViewStartDate( - view, - numberOfWeeksInView, - currentViewDate, - widget.isRtl, - widget.picker.isHijri); + view, + numberOfWeeksInView, + currentViewDate, + widget.isRtl, + widget.picker.isHijri, + ); } switch (view) { @@ -9404,7 +9946,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); if (widget.picker.enableMultiView && widget.isRtl) { afterVisibleDates = getVisibleDates( @@ -9412,7 +9957,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> null, widget.picker.monthViewSettings.firstDayOfWeek, DateRangePickerHelper.getViewDatesCount( - view, numberOfWeeksInView, widget.picker.isHijri), + view, + numberOfWeeksInView, + widget.picker.isHijri, + ), ); } } @@ -9422,10 +9970,16 @@ class _PickerScrollViewState extends State<_PickerScrollView> case DateRangePickerView.century: { dates = DateRangePickerHelper.getVisibleYearDates( - currentViewDate, view, widget.picker.isHijri); + currentViewDate, + view, + widget.picker.isHijri, + ); if (widget.picker.enableMultiView && widget.isRtl) { afterVisibleDates = DateRangePickerHelper.getVisibleYearDates( - afterNextViewDate, view, widget.picker.isHijri); + afterNextViewDate, + view, + widget.picker.isHijri, + ); } } } @@ -9444,7 +9998,8 @@ class _PickerScrollViewState extends State<_PickerScrollView> } List _updatePreviousDatesForMultiView( - List? afterVisibleDates) { + List? afterVisibleDates, + ) { List dates; if (widget.picker.isHijri) { dates = []; @@ -9494,11 +10049,13 @@ class _PickerScrollViewState extends State<_PickerScrollView> widget.datePickerTheme, _focusNode, widget.textScaleFactor, - DateRangePickerHelper.cloneList((_disabledDates != null && - _disabledDates?.values != null && - _disabledDates!.values.isNotEmpty) - ? _disabledDates?.values.first - : null), + DateRangePickerHelper.cloneList( + (_disabledDates != null && + _disabledDates?.values != null && + _disabledDates!.values.isNotEmpty) + ? _disabledDates?.values.first + : null, + ), key: key, getPickerStateDetails: (PickerStateArgs details) { _getPickerViewStateDetails(details); @@ -9523,11 +10080,20 @@ class _PickerScrollViewState extends State<_PickerScrollView> } final _PickerView previousView = _updateViews( - _previousView!, _previousView!.visibleDates, _previousViewVisibleDates); - final _PickerView currentView = - _updateViews(_currentView!, _currentView!.visibleDates, _visibleDates); + _previousView!, + _previousView!.visibleDates, + _previousViewVisibleDates, + ); + final _PickerView currentView = _updateViews( + _currentView!, + _currentView!.visibleDates, + _visibleDates, + ); final _PickerView nextView = _updateViews( - _nextView!, _nextView!.visibleDates, _nextViewVisibleDates); + _nextView!, + _nextView!.visibleDates, + _nextViewVisibleDates, + ); /// Update views while the all day view height differ from original height, /// else repaint the appointment painter while current child visible @@ -9547,7 +10113,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> // method to check and update the views and appointments on the swiping end _PickerView _updateViews( - _PickerView view, List viewDates, List visibleDates) { + _PickerView view, + List viewDates, + List visibleDates, + ) { final int index = _children.indexOf(view); // update the view with the visible dates on swiping end. if (viewDates != visibleDates) { @@ -9560,7 +10129,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _disabledDates!.keys.isNotEmpty && _disabledDates!.keys.first == viewDates && !DateRangePickerHelper.isDateCollectionEquals( - view.disableDatePredicates, _disabledDates!.values.first)) { + view.disableDatePredicates, + _disabledDates!.values.first, + )) { view = _getView(viewDates, view.key!); _children[index] = view; } @@ -9606,13 +10177,18 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _drawSelection( - dynamic oldValue, dynamic newValue, DateRangePickerView pickerView) { + dynamic oldValue, + dynamic newValue, + DateRangePickerView pickerView, + ) { switch (widget.picker.selectionMode) { case DateRangePickerSelectionMode.single: { if (oldValue.selectedDate != newValue.selectedDate || !isSameDate( - _pickerStateDetails.selectedDate, newValue.selectedDate)) { + _pickerStateDetails.selectedDate, + newValue.selectedDate, + )) { _pickerStateDetails.selectedDate = newValue.selectedDate; if (pickerView != DateRangePickerView.month && !widget.picker.allowViewNavigation) { @@ -9629,7 +10205,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> { if (oldValue.selectedDates != newValue.selectedDates || !DateRangePickerHelper.isDateCollectionEquals( - _pickerStateDetails.selectedDates, newValue.selectedDates)) { + _pickerStateDetails.selectedDates, + newValue.selectedDates, + )) { _pickerStateDetails.selectedDates = newValue.selectedDates as List?; if (pickerView != DateRangePickerView.month && @@ -9648,7 +10226,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> { if (oldValue.selectedRange != newValue.selectedRange || !DateRangePickerHelper.isRangeEquals( - _pickerStateDetails.selectedRange, newValue.selectedRange)) { + _pickerStateDetails.selectedRange, + newValue.selectedRange, + )) { _pickerStateDetails.selectedRange = newValue.selectedRange; if (pickerView != DateRangePickerView.month && !widget.picker.allowViewNavigation) { @@ -9665,8 +10245,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> { if (oldValue.selectedRanges != newValue.selectedRanges || !DateRangePickerHelper.isDateRangesEquals( - _pickerStateDetails.selectedRanges, - newValue.selectedRanges)) { + _pickerStateDetails.selectedRanges, + newValue.selectedRanges, + )) { _pickerStateDetails.selectedRanges = newValue.selectedRanges as List?; if (pickerView != DateRangePickerView.month && @@ -9685,8 +10266,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// Update the selection details to scroll view children except current view /// while view navigation. void _updateSelection({dynamic selectedDate}) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); /// Update selection on month view and update selection on year view when /// [allowViewNavigation] property on [SfDateRangePicker] as false @@ -9701,8 +10283,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> continue; } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); final _PickerViewState viewState = _getCurrentViewState(i); switch (view) { @@ -9732,8 +10315,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// Draw the selection on current month view when selected date value /// changed dynamically. void _drawMonthSelection() { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView != DateRangePickerView.month || _children.isEmpty) { return; } @@ -9757,8 +10341,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// Draw the selection on current year, decade, century view when /// selected date value changed dynamically. void _drawYearSelection() { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView == DateRangePickerView.month || _children.isEmpty) { return; } @@ -9813,22 +10398,29 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// Updates the current view visible dates for picker in the swiping end void _updateCurrentViewVisibleDates({bool isNextView = false}) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); _currentViewVisibleDates = _getCurrentVisibleDates(isNextView); _pickerStateDetails.currentViewVisibleDates = _currentViewVisibleDates; _pickerStateDetails.currentDate = _currentViewVisibleDates[0]; final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); if (pickerView == DateRangePickerView.month && (numberOfWeeksInView == 6 || widget.picker.isHijri)) { - final dynamic date = _currentViewVisibleDates[ - _currentViewVisibleDates.length ~/ + final dynamic date = + _currentViewVisibleDates[_currentViewVisibleDates.length ~/ (widget.picker.enableMultiView ? 4 : 2)]; _pickerStateDetails.currentDate = DateRangePickerHelper.getDate( - date.year, date.month, 1, widget.picker.isHijri); + date.year, + date.month, + 1, + widget.picker.isHijri, + ); } widget.updatePickerStateValues(_pickerStateDetails); @@ -9904,15 +10496,23 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// Calculate and return the date time value based on previous selected date, /// keyboard action and current picker view. - dynamic _getYearSelectedDate(dynamic selectedDate, LogicalKeyboardKey key, - _PickerView view, _PickerViewState state) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + dynamic _getYearSelectedDate( + dynamic selectedDate, + LogicalKeyboardKey key, + _PickerView view, + _PickerViewState state, + ) { + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); dynamic date; /// Calculate the index value for previous selected date. int index = DateRangePickerHelper.getDateCellIndex( - view.visibleDates, selectedDate, widget.controller.view); + view.visibleDates, + selectedDate, + widget.controller.view, + ); if (key == LogicalKeyboardKey.arrowRight) { /// If index value as last cell index in current view then /// navigate to next view. Calculate the selected index on navigated view @@ -9978,11 +10578,14 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// Return the next date for year, decade and century view in keyboard /// navigation dynamic _updateNextYearSelectionDate(dynamic selectedDate) { - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); switch (view) { case DateRangePickerView.month: { @@ -9991,29 +10594,32 @@ class _PickerScrollViewState extends State<_PickerScrollView> case DateRangePickerView.year: { return DateRangePickerHelper.getNextViewStartDate( - DateRangePickerView.month, - numberOfWeeksInView, - selectedDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerView.month, + numberOfWeeksInView, + selectedDate, + widget.isRtl, + widget.picker.isHijri, + ); } case DateRangePickerView.decade: { return DateRangePickerHelper.getNextViewStartDate( - DateRangePickerView.year, - numberOfWeeksInView, - selectedDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerView.year, + numberOfWeeksInView, + selectedDate, + widget.isRtl, + widget.picker.isHijri, + ); } case DateRangePickerView.century: { return DateRangePickerHelper.getNextViewStartDate( - DateRangePickerView.decade, - numberOfWeeksInView, - selectedDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerView.decade, + numberOfWeeksInView, + selectedDate, + widget.isRtl, + widget.picker.isHijri, + ); } } @@ -10025,9 +10631,12 @@ class _PickerScrollViewState extends State<_PickerScrollView> dynamic _updatePreviousYearSelectionDate(dynamic selectedDate) { final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (view) { case DateRangePickerView.month: { @@ -10036,29 +10645,32 @@ class _PickerScrollViewState extends State<_PickerScrollView> case DateRangePickerView.year: { return DateRangePickerHelper.getPreviousViewStartDate( - DateRangePickerView.month, - numberOfWeeksInView, - selectedDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerView.month, + numberOfWeeksInView, + selectedDate, + widget.isRtl, + widget.picker.isHijri, + ); } case DateRangePickerView.decade: { return DateRangePickerHelper.getPreviousViewStartDate( - DateRangePickerView.year, - numberOfWeeksInView, - selectedDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerView.year, + numberOfWeeksInView, + selectedDate, + widget.isRtl, + widget.picker.isHijri, + ); } case DateRangePickerView.century: { return DateRangePickerHelper.getPreviousViewStartDate( - DateRangePickerView.decade, - numberOfWeeksInView, - selectedDate, - widget.isRtl, - widget.picker.isHijri); + DateRangePickerView.decade, + numberOfWeeksInView, + selectedDate, + widget.isRtl, + widget.picker.isHijri, + ); } } @@ -10090,23 +10702,29 @@ class _PickerScrollViewState extends State<_PickerScrollView> } KeyEventResult _updateYearSelectionByKeyBoardNavigation( - _PickerViewState currentVisibleViewState, - _PickerView currentVisibleView, - DateRangePickerView pickerView, - KeyEvent event) { + _PickerViewState currentVisibleViewState, + _PickerView currentVisibleView, + DateRangePickerView pickerView, + KeyEvent event, + ) { dynamic selectedDate; if (_pickerStateDetails.selectedDate != null && widget.picker.selectionMode == DateRangePickerSelectionMode.single) { - selectedDate = _getYearSelectedDate(_pickerStateDetails.selectedDate, - event.logicalKey, currentVisibleView, currentVisibleViewState); + selectedDate = _getYearSelectedDate( + _pickerStateDetails.selectedDate, + event.logicalKey, + currentVisibleView, + currentVisibleViewState, + ); if (selectedDate != null && DateRangePickerHelper.isBetweenMinMaxDateCell( - selectedDate, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri)) { + selectedDate, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + )) { _pickerStateDetails.selectedDate = selectedDate; } } else if (widget.picker.selectionMode == @@ -10114,21 +10732,27 @@ class _PickerScrollViewState extends State<_PickerScrollView> _pickerStateDetails.selectedDates != null && _pickerStateDetails.selectedDates!.isNotEmpty && HardwareKeyboard.instance.isShiftPressed) { - final dynamic date = _pickerStateDetails - .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; + final dynamic date = + _pickerStateDetails + .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; selectedDate = _getYearSelectedDate( - date, event.logicalKey, currentVisibleView, currentVisibleViewState); + date, + event.logicalKey, + currentVisibleView, + currentVisibleViewState, + ); if (selectedDate != null && DateRangePickerHelper.isBetweenMinMaxDateCell( - selectedDate, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri)) { - _pickerStateDetails.selectedDates = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedDates) - ?..add(selectedDate); + selectedDate, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + )) { + _pickerStateDetails.selectedDates = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedDates, + )?..add(selectedDate); } } else if ((widget.picker.selectionMode == DateRangePickerSelectionMode.range || @@ -10139,19 +10763,25 @@ class _PickerScrollViewState extends State<_PickerScrollView> HardwareKeyboard.instance.isShiftPressed) { final dynamic date = currentVisibleViewState._lastSelectedDate; selectedDate = _getYearSelectedDate( - date, event.logicalKey, currentVisibleView, currentVisibleViewState); + date, + event.logicalKey, + currentVisibleView, + currentVisibleViewState, + ); if (selectedDate == null || !DateRangePickerHelper.isBetweenMinMaxDateCell( - selectedDate, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri)) { + selectedDate, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + )) { return KeyEventResult.ignored; } - final bool isExtendableRange = widget.picker.selectionMode == + final bool isExtendableRange = + widget.picker.selectionMode == DateRangePickerSelectionMode.extendableRange; /// Ignore the selection date while the extendable range enabled and the @@ -10159,11 +10789,12 @@ class _PickerScrollViewState extends State<_PickerScrollView> /// year view keyboard selection. if (isExtendableRange && DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return KeyEventResult.ignored; } @@ -10199,29 +10830,41 @@ class _PickerScrollViewState extends State<_PickerScrollView> } if (DateRangePickerHelper.isSameCellDates( - startDate, endDate, pickerView)) { + startDate, + endDate, + pickerView, + )) { return KeyEventResult.ignored; } endDate = DateRangePickerHelper.getLastDate( - endDate, widget.controller.view, widget.picker.isHijri); + endDate, + widget.controller.view, + widget.picker.isHijri, + ); if (widget.picker.maxDate != null) { - endDate = endDate.isAfter(widget.picker.maxDate) == true - ? widget.picker.maxDate - : endDate; + endDate = + endDate.isAfter(widget.picker.maxDate) == true + ? widget.picker.maxDate + : endDate; } startDate = DateRangePickerHelper.getFirstDate( - startDate, widget.picker.isHijri, pickerView); + startDate, + widget.picker.isHijri, + pickerView, + ); if (widget.picker.minDate != null) { - startDate = startDate.isBefore(widget.picker.minDate) == true - ? widget.picker.minDate - : startDate; + startDate = + startDate.isBefore(widget.picker.minDate) == true + ? widget.picker.minDate + : startDate; } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); currentVisibleViewState._lastSelectedDate = selectedDate; } else { return KeyEventResult.ignored; @@ -10237,8 +10880,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> if (_pickerStateDetails.selectedRange != null && _pickerStateDetails.selectedRange.startDate != null && (_pickerStateDetails.selectedRange.endDate == null || - isSameDate(_pickerStateDetails.selectedRange.startDate, - _pickerStateDetails.selectedRange.endDate))) { + isSameDate( + _pickerStateDetails.selectedRange.startDate, + _pickerStateDetails.selectedRange.endDate, + ))) { dynamic startDate = _pickerStateDetails.selectedRange.startDate; dynamic endDate = selectedDate; if (startDate.isAfter(endDate) == true) { @@ -10247,13 +10892,15 @@ class _PickerScrollViewState extends State<_PickerScrollView> endDate = temp; } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); } else { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } } @@ -10306,9 +10953,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> } } } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); } else { _updateRangeSelectionByKeyboardNavigation(selectedDate); } @@ -10335,33 +10983,40 @@ class _PickerScrollViewState extends State<_PickerScrollView> return KeyEventResult.handled; } - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); result = _switchViewsByKeyBoardEvent(event); if (HardwareKeyboard.instance.isControlPressed) { final bool canMoveToNextView = DateRangePickerHelper.canMoveToNextViewRtl( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - widget.picker.maxDate, - _currentViewVisibleDates, - widget.isRtl, - widget.picker.enableMultiView, - widget.picker.isHijri); + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + widget.picker.maxDate, + _currentViewVisibleDates, + widget.isRtl, + widget.picker.enableMultiView, + widget.picker.isHijri, + ); final bool canMoveToPreviousView = DateRangePickerHelper.canMoveToPreviousViewRtl( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - widget.picker.maxDate, - _currentViewVisibleDates, - widget.isRtl, - widget.picker.enableMultiView, - widget.picker.isHijri); + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + widget.picker.maxDate, + _currentViewVisibleDates, + widget.isRtl, + widget.picker.enableMultiView, + widget.picker.isHijri, + ); if (event.logicalKey == LogicalKeyboardKey.arrowRight && canMoveToNextView) { widget.isRtl @@ -10407,27 +11062,37 @@ class _PickerScrollViewState extends State<_PickerScrollView> if (pickerView != DateRangePickerView.month) { result = _updateYearSelectionByKeyBoardNavigation( - currentVisibleViewState, currentVisibleView, pickerView, event); + currentVisibleViewState, + currentVisibleView, + pickerView, + event, + ); return result; } - final dynamic selectedDate = - _updateSelectedDate(event, currentVisibleViewState, currentVisibleView); + final dynamic selectedDate = _updateSelectedDate( + event, + currentVisibleViewState, + currentVisibleView, + ); if (DateRangePickerHelper.isDateWithInVisibleDates( - currentVisibleView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate) || + currentVisibleView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - currentVisibleView.visibleDates, - currentVisibleView.disableDatePredicates, - selectedDate) || + currentVisibleView.visibleDates, + currentVisibleView.disableDatePredicates, + selectedDate, + ) || !DateRangePickerHelper.isEnabledDate( - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - selectedDate, - widget.picker.isHijri)) { + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + selectedDate, + widget.picker.isHijri, + )) { return result; } @@ -10438,59 +11103,81 @@ class _PickerScrollViewState extends State<_PickerScrollView> DateRangePickerSelectionMode.extendableRange && _pickerStateDetails.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return result; } final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); final dynamic visibleStartDate = currentVisibleView.visibleDates[0]; - final dynamic visibleEndDate = currentVisibleView - .visibleDates[currentVisibleView.visibleDates.length - 1]; - final int datesCount = currentVisibleView.visibleDates.length ~/ + final dynamic visibleEndDate = + currentVisibleView.visibleDates[currentVisibleView.visibleDates.length - + 1]; + final int datesCount = + currentVisibleView.visibleDates.length ~/ (widget.picker.enableMultiView ? 2 : 1); - // ignore: avoid_bool_literals_in_conditional_expressions - final bool showLeadingTrailingDates = widget.picker.enableMultiView - ? false - : DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri); - final bool isCurrentMonthDate = widget.picker.enableMultiView - ? (DateRangePickerHelper.isDateAsCurrentMonthDate( - currentVisibleView.visibleDates[datesCount ~/ 2], - numberOfWeeksInView, - showLeadingTrailingDates, - selectedDate, - widget.picker.isHijri) || - DateRangePickerHelper.isDateAsCurrentMonthDate( - currentVisibleView.visibleDates[datesCount + (datesCount ~/ 2)], - numberOfWeeksInView, - showLeadingTrailingDates, - selectedDate, - widget.picker.isHijri)) - : DateRangePickerHelper.isDateAsCurrentMonthDate( - currentVisibleView.visibleDates[datesCount ~/ 2], - numberOfWeeksInView, - showLeadingTrailingDates, - selectedDate, - widget.picker.isHijri); + final bool showLeadingTrailingDates = + // ignore: avoid_bool_literals_in_conditional_expressions + widget.picker.enableMultiView + ? false + : DateRangePickerHelper.canShowLeadingAndTrailingDates( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); + final bool isCurrentMonthDate = + widget.picker.enableMultiView + ? (DateRangePickerHelper.isDateAsCurrentMonthDate( + currentVisibleView.visibleDates[datesCount ~/ 2], + numberOfWeeksInView, + showLeadingTrailingDates, + selectedDate, + widget.picker.isHijri, + ) || + DateRangePickerHelper.isDateAsCurrentMonthDate( + currentVisibleView.visibleDates[datesCount + + (datesCount ~/ 2)], + numberOfWeeksInView, + showLeadingTrailingDates, + selectedDate, + widget.picker.isHijri, + )) + : DateRangePickerHelper.isDateAsCurrentMonthDate( + currentVisibleView.visibleDates[datesCount ~/ 2], + numberOfWeeksInView, + showLeadingTrailingDates, + selectedDate, + widget.picker.isHijri, + ); if (!isCurrentMonthDate || !isDateWithInDateRange( - visibleStartDate, visibleEndDate, selectedDate)) { + visibleStartDate, + visibleEndDate, + selectedDate, + )) { final int month = selectedDate.month as int; final dynamic nextMonthDate = getNextMonthDate( - currentVisibleView.visibleDates[ - currentVisibleView.visibleDates.length ~/ - (widget.picker.enableMultiView ? 4 : 2)]); + currentVisibleView.visibleDates[currentVisibleView + .visibleDates + .length ~/ + (widget.picker.enableMultiView ? 4 : 2)], + ); int nextMonth = nextMonthDate.month as int; - final dynamic nextMonthEndDate = - DateRangePickerHelper.getMonthEndDate(nextMonthDate); + final dynamic nextMonthEndDate = DateRangePickerHelper.getMonthEndDate( + nextMonthDate, + ); if (isDateWithInDateRange( - visibleStartDate, visibleEndDate, nextMonthEndDate)) { + visibleStartDate, + visibleEndDate, + nextMonthEndDate, + )) { nextMonth = getNextMonthDate(nextMonthEndDate).month as int; } if (month == nextMonth) { @@ -10517,147 +11204,172 @@ class _PickerScrollViewState extends State<_PickerScrollView> } dynamic _updateSingleSelectionByKeyBoardKeys( - KeyEvent event, _PickerView currentView) { + KeyEvent event, + _PickerView currentView, + ) { dynamic selectedDate = _pickerStateDetails.selectedDate; if (event.logicalKey == LogicalKeyboardKey.arrowRight) { - if (isSameDate(_pickerStateDetails.selectedDate, - currentView.visibleDates[currentView.visibleDates.length - 1])) { + if (isSameDate( + _pickerStateDetails.selectedDate, + currentView.visibleDates[currentView.visibleDates.length - 1], + )) { _moveToNextViewWithAnimation(); } do { selectedDate = addDays(selectedDate, 1); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else if (event.logicalKey == LogicalKeyboardKey.arrowLeft) { if (isSameDate( - _pickerStateDetails.selectedDate, currentView.visibleDates[0])) { + _pickerStateDetails.selectedDate, + currentView.visibleDates[0], + )) { _moveToPreviousViewWithAnimation(); } do { selectedDate = addDays(selectedDate, -1); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else if (event.logicalKey == LogicalKeyboardKey.arrowUp) { do { selectedDate = addDays(selectedDate, -DateTime.daysPerWeek); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) { do { selectedDate = addDays(selectedDate, DateTime.daysPerWeek); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } return null; } dynamic _updateMultiAndRangeSelectionByKeyBoard( - KeyEvent event, _PickerViewState currentState, _PickerView currentView) { + KeyEvent event, + _PickerViewState currentState, + _PickerView currentView, + ) { dynamic selectedDate; if (HardwareKeyboard.instance.isShiftPressed && event.logicalKey == LogicalKeyboardKey.arrowRight) { if (widget.picker.selectionMode == DateRangePickerSelectionMode.multiple) { - selectedDate = _pickerStateDetails - .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; + selectedDate = + _pickerStateDetails + .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; do { selectedDate = addDays(selectedDate, 1); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else { selectedDate = currentState._lastSelectedDate; do { selectedDate = addDays(selectedDate, 1); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } } else if (HardwareKeyboard.instance.isShiftPressed && event.logicalKey == LogicalKeyboardKey.arrowLeft) { if (widget.picker.selectionMode == DateRangePickerSelectionMode.multiple) { - selectedDate = _pickerStateDetails - .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; + selectedDate = + _pickerStateDetails + .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; do { selectedDate = addDays(selectedDate, -1); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else { selectedDate = currentState._lastSelectedDate; do { selectedDate = addDays(selectedDate, -1); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } } else if (HardwareKeyboard.instance.isShiftPressed && event.logicalKey == LogicalKeyboardKey.arrowUp) { if (widget.picker.selectionMode == DateRangePickerSelectionMode.multiple) { - selectedDate = _pickerStateDetails - .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; + selectedDate = + _pickerStateDetails + .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; do { selectedDate = addDays(selectedDate, -DateTime.daysPerWeek); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else { selectedDate = currentState._lastSelectedDate; do { selectedDate = addDays(selectedDate, -DateTime.daysPerWeek); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } } else if (HardwareKeyboard.instance.isShiftPressed && event.logicalKey == LogicalKeyboardKey.arrowDown) { if (widget.picker.selectionMode == DateRangePickerSelectionMode.multiple) { - selectedDate = _pickerStateDetails - .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; + selectedDate = + _pickerStateDetails + .selectedDates![_pickerStateDetails.selectedDates!.length - 1]; do { selectedDate = addDays(selectedDate, DateTime.daysPerWeek); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } else { selectedDate = currentState._lastSelectedDate; do { selectedDate = addDays(selectedDate, DateTime.daysPerWeek); } while (DateRangePickerHelper.isDateWithInVisibleDates( - currentView.visibleDates, - widget.picker.monthViewSettings.blackoutDates, - selectedDate)); + currentView.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + )); return selectedDate; } } @@ -10665,7 +11377,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> } dynamic _updateSelectedDate( - KeyEvent event, _PickerViewState currentState, _PickerView currentView) { + KeyEvent event, + _PickerViewState currentState, + _PickerView currentView, + ) { switch (widget.picker.selectionMode) { case DateRangePickerSelectionMode.single: { @@ -10676,7 +11391,10 @@ class _PickerScrollViewState extends State<_PickerScrollView> case DateRangePickerSelectionMode.extendableRange: { return _updateMultiAndRangeSelectionByKeyBoard( - event, currentState, currentView); + event, + currentState, + currentView, + ); } case DateRangePickerSelectionMode.multiRange: break; @@ -10699,8 +11417,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _onHorizontalUpdate(DragUpdateDetails dragUpdateDetails) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (widget.picker.navigationDirection) { case DateRangePickerNavigationDirection.horizontal: { @@ -10708,27 +11427,33 @@ class _PickerScrollViewState extends State<_PickerScrollView> dragUpdateDetails.globalPosition.dx - _scrollStartPosition!; if (difference < 0 && !DateRangePickerHelper.canMoveToNextViewRtl( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - widget.picker.maxDate, - _currentViewVisibleDates, - widget.isRtl, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + widget.picker.maxDate, + _currentViewVisibleDates, + widget.isRtl, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { return; } else if (difference > 0 && !DateRangePickerHelper.canMoveToPreviousViewRtl( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - widget.picker.maxDate, - _currentViewVisibleDates, - widget.isRtl, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + widget.picker.maxDate, + _currentViewVisibleDates, + widget.isRtl, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { return; } @@ -10748,8 +11473,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _onHorizontalEnd(DragEndDetails dragEndDetails) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (widget.picker.navigationDirection) { case DateRangePickerNavigationDirection.vertical: break; @@ -10768,9 +11494,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } _animationController.duration = const Duration(milliseconds: 250); - _animationController - .forward() - .then((dynamic value) => _updateNextView()); + _animationController.forward().then( + (dynamic value) => _updateNextView(), + ); /// updates the current view visible dates when the view swiped in /// right to left direction @@ -10779,15 +11505,18 @@ class _PickerScrollViewState extends State<_PickerScrollView> // fling the view from right to left else if (-dragEndDetails.velocity.pixelsPerSecond.dx > widget.width) { if (!DateRangePickerHelper.canMoveToNextViewRtl( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - widget.picker.maxDate, - _currentViewVisibleDates, - widget.isRtl, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + widget.picker.maxDate, + _currentViewVisibleDates, + widget.isRtl, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position in @@ -10808,7 +11537,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _animationController.duration = const Duration(milliseconds: 250); _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updateNextView()); /// updates the current view visible dates when fling the view in @@ -10827,9 +11558,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } _animationController.duration = const Duration(milliseconds: 250); - _animationController - .forward() - .then((dynamic value) => _updatePreviousView()); + _animationController.forward().then( + (dynamic value) => _updatePreviousView(), + ); /// updates the current view visible dates when the view swiped in /// left to right direction @@ -10838,15 +11569,18 @@ class _PickerScrollViewState extends State<_PickerScrollView> // fling the view from left to right else if (dragEndDetails.velocity.pixelsPerSecond.dx > widget.width) { if (!DateRangePickerHelper.canMoveToPreviousViewRtl( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - widget.picker.maxDate, - _currentViewVisibleDates, - widget.isRtl, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + widget.picker.maxDate, + _currentViewVisibleDates, + widget.isRtl, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position in @@ -10867,7 +11601,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _animationController.duration = const Duration(milliseconds: 250); _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updatePreviousView()); /// updates the current view visible dates when fling the view in @@ -10907,8 +11643,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _onVerticalUpdate(DragUpdateDetails dragUpdateDetails) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (widget.picker.navigationDirection) { case DateRangePickerNavigationDirection.horizontal: break; @@ -10918,23 +11655,29 @@ class _PickerScrollViewState extends State<_PickerScrollView> dragUpdateDetails.globalPosition.dy - _scrollStartPosition!; if (difference < 0 && !DateRangePickerHelper.canMoveToNextView( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.maxDate, - _currentViewVisibleDates, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.maxDate, + _currentViewVisibleDates, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { return; } else if (difference > 0 && !DateRangePickerHelper.canMoveToPreviousView( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - _currentViewVisibleDates, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + _currentViewVisibleDates, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { return; } @@ -10951,8 +11694,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } void _onVerticalEnd(DragEndDetails dragEndDetails) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (widget.picker.navigationDirection) { case DateRangePickerNavigationDirection.horizontal: break; @@ -10971,9 +11715,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } _animationController.duration = const Duration(milliseconds: 250); - _animationController - .forward() - .then((dynamic value) => _updateNextView()); + _animationController.forward().then( + (dynamic value) => _updateNextView(), + ); /// updates the current view visible dates when the view swiped in /// bottom to top direction @@ -10983,13 +11727,16 @@ class _PickerScrollViewState extends State<_PickerScrollView> else if (-dragEndDetails.velocity.pixelsPerSecond.dy > widget.height) { if (!DateRangePickerHelper.canMoveToNextView( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.maxDate, - _currentViewVisibleDates, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.maxDate, + _currentViewVisibleDates, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position in @@ -11009,7 +11756,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _animationController.duration = const Duration(milliseconds: 250); _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updateNextView()); /// updates the current view visible dates when fling the view in @@ -11028,9 +11777,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> } _animationController.duration = const Duration(milliseconds: 250); - _animationController - .forward() - .then((dynamic value) => _updatePreviousView()); + _animationController.forward().then( + (dynamic value) => _updatePreviousView(), + ); /// updates the current view visible dates when the view swiped in /// top to bottom direction @@ -11039,13 +11788,16 @@ class _PickerScrollViewState extends State<_PickerScrollView> // fling the view to top to bottom else if (dragEndDetails.velocity.pixelsPerSecond.dy > widget.height) { if (!DateRangePickerHelper.canMoveToPreviousView( - pickerView, - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - widget.picker.minDate, - _currentViewVisibleDates, - widget.picker.enableMultiView, - widget.picker.isHijri)) { + pickerView, + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + widget.picker.minDate, + _currentViewVisibleDates, + widget.picker.enableMultiView, + widget.picker.isHijri, + )) { _position = 0; setState(() { /* Completes the swiping and rearrange the children position in @@ -11066,7 +11818,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> _animationController.duration = const Duration(milliseconds: 250); _animationController .fling( - velocity: 5.0, animationBehavior: AnimationBehavior.normal) + velocity: 5.0, + animationBehavior: AnimationBehavior.normal, + ) .then((dynamic value) => _updatePreviousView()); /// updates the current view visible dates when fling the view in @@ -11106,8 +11860,9 @@ class _PickerScrollViewState extends State<_PickerScrollView> return; } - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); final int viewCount = _isMultiViewEnabled(widget.picker) ? 2 : 1; _disabledDates ??= , List>{}; @@ -11127,17 +11882,22 @@ class _PickerScrollViewState extends State<_PickerScrollView> for (int j = i * datesCount; j < ((i + 1) * datesCount); j++) { final int numberOfWeeksInView = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); final bool showLeadingTrailingDates = DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); final bool isCurrentMonthDate = DateRangePickerHelper.isDateAsCurrentMonthDate( - visibleDates[midDateIndex], - numberOfWeeksInView, - showLeadingTrailingDates, - visibleDates[j], - widget.picker.isHijri); + visibleDates[midDateIndex], + numberOfWeeksInView, + showLeadingTrailingDates, + visibleDates[j], + widget.picker.isHijri, + ); if (isCurrentMonthDate) { final bool isSelectedDayPredicate = widget.picker.selectableDayPredicate(visibleDates[j]) as bool; @@ -11269,11 +12029,13 @@ class _PickerViewState extends State<_PickerView> Widget build(BuildContext context) { final Locale locale = Localizations.localeOf(context); final SfLocalizations localizations = SfLocalizations.of(context); - _isMobilePlatform = - DateRangePickerHelper.isMobileLayout(Theme.of(context).platform); + _isMobilePlatform = DateRangePickerHelper.isMobileLayout( + Theme.of(context).platform, + ); widget.getPickerStateDetails(_pickerStateDetails); - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (pickerView) { case DateRangePickerView.month: @@ -11285,15 +12047,19 @@ class _PickerViewState extends State<_PickerView> onHorizontalDragUpdate: _getDragUpdateCallback(), onVerticalDragUpdate: _getDragUpdateCallback(), child: MouseRegion( - onEnter: _pointerEnterEvent, - onHover: _pointerHoverEvent, - onExit: _pointerExitEvent, - child: SizedBox( - width: widget.width, - height: widget.height, - child: _addMonthView( - locale, widget.datePickerTheme, localizations), - )), + onEnter: _pointerEnterEvent, + onHover: _pointerHoverEvent, + onExit: _pointerExitEvent, + child: SizedBox( + width: widget.width, + height: widget.height, + child: _addMonthView( + locale, + widget.datePickerTheme, + localizations, + ), + ), + ), ); } case DateRangePickerView.year: @@ -11339,11 +12105,13 @@ class _PickerViewState extends State<_PickerView> // Returns the month view as a child for the picker view. Widget _addMonthView( - Locale locale, - SfDateRangePickerThemeData datePickerTheme, - SfLocalizations localizations) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + Locale locale, + SfDateRangePickerThemeData datePickerTheme, + SfLocalizations localizations, + ) { + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); double viewHeaderHeight = widget.picker.monthViewSettings.viewHeaderHeight as double; if (pickerView == DateRangePickerView.month && @@ -11353,8 +12121,14 @@ class _PickerViewState extends State<_PickerView> } final double height = widget.height - viewHeaderHeight; - _monthView = _getMonthView(locale, widget.datePickerTheme, localizations, - widget.width, height, pickerView); + _monthView = _getMonthView( + locale, + widget.datePickerTheme, + localizations, + widget.width, + height, + pickerView, + ); return Stack( children: [ _getViewHeader(viewHeaderHeight, locale, datePickerTheme), @@ -11363,23 +12137,24 @@ class _PickerViewState extends State<_PickerView> top: viewHeaderHeight, right: 0, height: height, - child: RepaintBoundary( - child: _monthView, - ), + child: RepaintBoundary(child: _monthView), ), ], ); } MonthView _getMonthView( - Locale locale, - SfDateRangePickerThemeData datePickerTheme, - SfLocalizations localizations, - double width, - double height, - DateRangePickerView pickerView) { + Locale locale, + SfDateRangePickerThemeData datePickerTheme, + SfLocalizations localizations, + double width, + double height, + DateRangePickerView pickerView, + ) { final int rowCount = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); return MonthView( widget.visibleDates, rowCount, @@ -11397,7 +12172,9 @@ class _PickerViewState extends State<_PickerView> widget.picker.maxDate, widget.picker.enablePastDates, DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri), + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), widget.picker.monthViewSettings.blackoutDates, widget.picker.monthViewSettings.specialDates, widget.picker.monthViewSettings.weekendDays, @@ -11424,15 +12201,19 @@ class _PickerViewState extends State<_PickerView> ); } - Widget _getViewHeader(double viewHeaderHeight, Locale locale, - SfDateRangePickerThemeData datePickerTheme) { + Widget _getViewHeader( + double viewHeaderHeight, + Locale locale, + SfDateRangePickerThemeData datePickerTheme, + ) { if (viewHeaderHeight == 0) { return Positioned( - left: 0, - top: 0, - right: 0, - height: viewHeaderHeight, - child: Container()); + left: 0, + top: 0, + right: 0, + height: viewHeaderHeight, + child: Container(), + ); } final Color todayTextColor = @@ -11452,28 +12233,29 @@ class _PickerViewState extends State<_PickerView> child: Container( color: widget.picker.monthViewSettings.viewHeaderStyle.backgroundColor ?? - widget.datePickerTheme.viewHeaderBackgroundColor, + widget.datePickerTheme.viewHeaderBackgroundColor, child: RepaintBoundary( child: CustomPaint( painter: _PickerViewHeaderPainter( - widget.visibleDates, - widget.picker.navigationMode, - widget.picker.monthViewSettings.viewHeaderStyle, - viewHeaderHeight, - widget.picker.monthViewSettings, - widget.datePickerTheme, - locale, - widget.isRtl, - widget.picker.monthCellStyle, - widget.enableMultiView, - widget.picker.viewSpacing, - todayTextColor, - widget.textScaleFactor, - widget.picker.isHijri, - widget.picker.navigationDirection, - null, - widget.picker.monthViewSettings.showWeekNumber, - _isMobilePlatform), + widget.visibleDates, + widget.picker.navigationMode, + widget.picker.monthViewSettings.viewHeaderStyle, + viewHeaderHeight, + widget.picker.monthViewSettings, + widget.datePickerTheme, + locale, + widget.isRtl, + widget.picker.monthCellStyle, + widget.enableMultiView, + widget.picker.viewSpacing, + todayTextColor, + widget.textScaleFactor, + widget.picker.isHijri, + widget.picker.navigationDirection, + null, + widget.picker.monthViewSettings.showWeekNumber, + _isMobilePlatform, + ), ), ), ), @@ -11481,8 +12263,9 @@ class _PickerViewState extends State<_PickerView> } void _updateTapCallback(TapUpDetails details) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); switch (pickerView) { case DateRangePickerView.month: { @@ -11495,9 +12278,10 @@ class _PickerViewState extends State<_PickerView> final double weekNumberPanelWidth = DateRangePickerHelper.getWeekNumberPanelWidth( - widget.picker.monthViewSettings.showWeekNumber, - widget.width, - _isMobilePlatform); + widget.picker.monthViewSettings.showWeekNumber, + widget.width, + _isMobilePlatform, + ); if (details.localPosition.dy < viewHeaderHeight || ((!widget.isRtl && @@ -11510,9 +12294,12 @@ class _PickerViewState extends State<_PickerView> if (details.localPosition.dy > viewHeaderHeight) { _handleTouch( - Offset(details.localPosition.dx, - details.localPosition.dy - viewHeaderHeight), - details); + Offset( + details.localPosition.dx, + details.localPosition.dy - viewHeaderHeight, + ), + details, + ); } } break; @@ -11521,7 +12308,8 @@ class _PickerViewState extends State<_PickerView> case DateRangePickerView.century: { _handleYearPanelSelection( - Offset(details.localPosition.dx, details.localPosition.dy)); + Offset(details.localPosition.dx, details.localPosition.dy), + ); } } @@ -11536,16 +12324,18 @@ class _PickerViewState extends State<_PickerView> } widget.getPickerStateDetails(_pickerStateDetails); - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); final RenderObject renderObject = context.findRenderObject()!; final RenderBox? box = renderObject is RenderBox ? renderObject : null; final Offset localPosition = box!.globalToLocal(globalPosition); - final double viewHeaderHeight = pickerView == DateRangePickerView.month && - widget.picker.navigationDirection == - DateRangePickerNavigationDirection.horizontal - ? widget.picker.monthViewSettings.viewHeaderHeight as double - : 0; + final double viewHeaderHeight = + pickerView == DateRangePickerView.month && + widget.picker.navigationDirection == + DateRangePickerNavigationDirection.horizontal + ? widget.picker.monthViewSettings.viewHeaderHeight as double + : 0; final double xPosition = localPosition.dx; final double yPosition = localPosition.dy - viewHeaderHeight; @@ -11577,24 +12367,30 @@ class _PickerViewState extends State<_PickerView> date = widget.visibleDates[index]; if (!DateRangePickerHelper.isEnabledDate( - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - date, - widget.picker.isHijri)) { + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + date, + widget.picker.isHijri, + )) { _mouseHoverPosition.value = null; return; } final int currentMonthIndex = _getCurrentDateIndex(index); if (!DateRangePickerHelper.isDateAsCurrentMonthDate( - widget.visibleDates[currentMonthIndex], - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri), - date, - widget.picker.isHijri)) { + widget.visibleDates[currentMonthIndex], + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + DateRangePickerHelper.canShowLeadingAndTrailingDates( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + date, + widget.picker.isHijri, + )) { _mouseHoverPosition.value = null; return; } @@ -11605,8 +12401,10 @@ class _PickerViewState extends State<_PickerView> case DateRangePickerView.century: { if (widget.picker.allowViewNavigation) { - _mouseHoverPosition.value = - HoveringDetails(range, Offset(xPosition, yPosition)); + _mouseHoverPosition.value = HoveringDetails( + range, + Offset(xPosition, yPosition), + ); return; } @@ -11618,12 +12416,13 @@ class _PickerViewState extends State<_PickerView> date = widget.visibleDates[index]; if (!DateRangePickerHelper.isBetweenMinMaxDateCell( - date, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri)) { + date, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + )) { _mouseHoverPosition.value = null; return; } @@ -11634,11 +12433,12 @@ class _PickerViewState extends State<_PickerView> /// selection value is disabled based on extendable direction on /// mouse hovering. if (DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - date, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + date, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { _mouseHoverPosition.value = null; return; } @@ -11659,13 +12459,16 @@ class _PickerViewState extends State<_PickerView> rangeStartDate = date; } - range = widget.picker.isHijri - ? HijriDateRange(rangeStartDate, rangeEndDate) - : PickerDateRange(rangeStartDate, rangeEndDate); + range = + widget.picker.isHijri + ? HijriDateRange(rangeStartDate, rangeEndDate) + : PickerDateRange(rangeStartDate, rangeEndDate); } - _mouseHoverPosition.value = - HoveringDetails(range, Offset(xPosition, yPosition)); + _mouseHoverPosition.value = HoveringDetails( + range, + Offset(xPosition, yPosition), + ); } void _pointerEnterEvent(PointerEnterEvent event) { @@ -11682,59 +12485,60 @@ class _PickerViewState extends State<_PickerView> Widget _addYearView(Locale locale, SfLocalizations localizations) { _yearView = _getYearView(locale, localizations); - return RepaintBoundary( - child: _yearView, + return RepaintBoundary(child: _yearView); + } + + YearView _getYearView(Locale locale, SfLocalizations localizations) { + return YearView( + widget.visibleDates, + widget.picker.yearCellStyle, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.picker.todayHighlightColor, + widget.picker.selectionShape, + widget.picker.monthFormat, + widget.isRtl, + widget.datePickerTheme, + locale, + _mouseHoverPosition, + widget.enableMultiView, + widget.picker.viewSpacing, + widget.picker.selectionTextStyle, + widget.picker.rangeTextStyle, + widget.picker.selectionColor, + widget.picker.startRangeSelectionColor, + widget.picker.endRangeSelectionColor, + widget.picker.rangeSelectionColor, + widget.picker.selectionMode, + widget.picker.selectionRadius, + ValueNotifier(false), + widget.textScaleFactor, + widget.picker.allowViewNavigation, + widget.picker.cellBuilder, + widget.getPickerStateDetails, + DateRangePickerHelper.getPickerView(widget.controller.view), + widget.picker.isHijri, + localizations, + widget.picker.navigationDirection, + widget.width, + widget.height, + widget.disableDatePredicates, + widget.picker.extendableRangeSelectionDirection, ); } - YearView _getYearView(Locale locale, SfLocalizations localizations) { - return YearView( - widget.visibleDates, - widget.picker.yearCellStyle, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.picker.todayHighlightColor, - widget.picker.selectionShape, - widget.picker.monthFormat, - widget.isRtl, - widget.datePickerTheme, - locale, - _mouseHoverPosition, - widget.enableMultiView, - widget.picker.viewSpacing, - widget.picker.selectionTextStyle, - widget.picker.rangeTextStyle, - widget.picker.selectionColor, - widget.picker.startRangeSelectionColor, - widget.picker.endRangeSelectionColor, - widget.picker.rangeSelectionColor, - widget.picker.selectionMode, - widget.picker.selectionRadius, - ValueNotifier(false), - widget.textScaleFactor, - widget.picker.allowViewNavigation, - widget.picker.cellBuilder, - widget.getPickerStateDetails, - DateRangePickerHelper.getPickerView(widget.controller.view), - widget.picker.isHijri, - localizations, - widget.picker.navigationDirection, - widget.width, - widget.height, - widget.disableDatePredicates, - widget.picker.extendableRangeSelectionDirection); - } - GestureDragStartCallback? _getDragStartCallback() { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); //// return drag start start event when selection mode as range or multi range. if ((pickerView != DateRangePickerView.month && widget.picker.allowViewNavigation) || !_isSwipeInteractionEnabled( - widget.picker.monthViewSettings.enableSwipeSelection, - widget.picker.navigationMode)) { + widget.picker.monthViewSettings.enableSwipeSelection, + widget.picker.navigationMode, + )) { return null; } @@ -11759,14 +12563,16 @@ class _PickerViewState extends State<_PickerView> } GestureDragUpdateCallback? _getDragUpdateCallback() { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); //// return drag update start event when selection mode as range or multi range. if ((pickerView != DateRangePickerView.month && widget.picker.allowViewNavigation) || !_isSwipeInteractionEnabled( - widget.picker.monthViewSettings.enableSwipeSelection, - widget.picker.navigationMode)) { + widget.picker.monthViewSettings.enableSwipeSelection, + widget.picker.navigationMode, + )) { return null; } @@ -11861,15 +12667,17 @@ class _PickerViewState extends State<_PickerView> } const int totalDatesCount = YearView.maxRowCount * YearView.maxColumnCount; - index = (columnIndex * YearView.maxColumnCount) + + index = + (columnIndex * YearView.maxColumnCount) + ((rowIndex ~/ YearView.maxColumnCount) * totalDatesCount) + (rowIndex % YearView.maxColumnCount); return widget.enableMultiView && DateRangePickerHelper.isLeadingCellDate( - index, - (index ~/ totalDatesCount) * totalDatesCount, - widget.visibleDates, - widget.controller.view) + index, + (index ~/ totalDatesCount) * totalDatesCount, + widget.visibleDates, + widget.controller.view, + ) ? -1 : index; } @@ -11877,16 +12685,19 @@ class _PickerViewState extends State<_PickerView> int _getSelectedIndex(double xPosition, double yPosition) { final double weekNumberPanelWidth = DateRangePickerHelper.getWeekNumberPanelWidth( - widget.picker.monthViewSettings.showWeekNumber, - widget.width, - _isMobilePlatform); + widget.picker.monthViewSettings.showWeekNumber, + widget.width, + _isMobilePlatform, + ); int rowIndex, columnIndex; double width = widget.width - weekNumberPanelWidth; double height = widget.height; int index = -1; int totalColumnCount = DateTime.daysPerWeek; final int rowCount = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri); + widget.picker.monthViewSettings, + widget.picker.isHijri, + ); int totalRowCount = rowCount; if (widget.enableMultiView) { switch (widget.picker.navigationDirection) { @@ -11939,8 +12750,9 @@ class _PickerViewState extends State<_PickerView> xPosition -= weekNumberPanelWidth; } - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); double viewHeaderHeight = widget.picker.monthViewSettings.viewHeaderHeight as double; @@ -11979,7 +12791,8 @@ class _PickerViewState extends State<_PickerView> } } - index = (columnIndex * DateTime.daysPerWeek) + + index = + (columnIndex * DateTime.daysPerWeek) + ((rowIndex ~/ DateTime.daysPerWeek) * (totalRowCount * DateTime.daysPerWeek)) + (rowIndex % DateTime.daysPerWeek); @@ -11991,13 +12804,15 @@ class _PickerViewState extends State<_PickerView> _isDragStart = false; widget.getPickerStateDetails(_pickerStateDetails); final double xPosition = details.localPosition.dx; - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); double yPosition = details.localPosition.dy; if (pickerView == DateRangePickerView.month && widget.picker.navigationDirection == DateRangePickerNavigationDirection.horizontal) { - yPosition = details.localPosition.dy - + yPosition = + details.localPosition.dy - widget.picker.monthViewSettings.viewHeaderHeight; } @@ -12008,30 +12823,42 @@ class _PickerViewState extends State<_PickerView> final dynamic selectedDate = widget.visibleDates[index]; if (!DateRangePickerHelper.isEnabledDate( - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - selectedDate, - widget.picker.isHijri)) { + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + selectedDate, + widget.picker.isHijri, + )) { return; } final int currentMonthIndex = _getCurrentDateIndex(index); if (!DateRangePickerHelper.isDateAsCurrentMonthDate( - widget.visibleDates[currentMonthIndex], - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri), - selectedDate, - widget.picker.isHijri)) { + widget.visibleDates[currentMonthIndex], + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + DateRangePickerHelper.canShowLeadingAndTrailingDates( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + selectedDate, + widget.picker.isHijri, + )) { return; } - if (DateRangePickerHelper.isDateWithInVisibleDates(widget.visibleDates, - widget.picker.monthViewSettings.blackoutDates, selectedDate) || + if (DateRangePickerHelper.isDateWithInVisibleDates( + widget.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - widget.visibleDates, widget.disableDatePredicates, selectedDate)) { + widget.visibleDates, + widget.disableDatePredicates, + selectedDate, + )) { return; } @@ -12042,11 +12869,12 @@ class _PickerViewState extends State<_PickerView> DateRangePickerSelectionMode.extendableRange && _pickerStateDetails.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return; } @@ -12065,12 +12893,14 @@ class _PickerViewState extends State<_PickerView> widget.getPickerStateDetails(_pickerStateDetails); final double xPosition = details.localPosition.dx; double yPosition = details.localPosition.dy; - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView == DateRangePickerView.month && widget.picker.navigationDirection == DateRangePickerNavigationDirection.horizontal) { - yPosition = details.localPosition.dy - + yPosition = + details.localPosition.dy - widget.picker.monthViewSettings.viewHeaderHeight; } @@ -12081,30 +12911,42 @@ class _PickerViewState extends State<_PickerView> final dynamic selectedDate = widget.visibleDates[index]; if (!DateRangePickerHelper.isEnabledDate( - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - selectedDate, - widget.picker.isHijri)) { + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + selectedDate, + widget.picker.isHijri, + )) { return; } final int currentMonthIndex = _getCurrentDateIndex(index); if (!DateRangePickerHelper.isDateAsCurrentMonthDate( - widget.visibleDates[currentMonthIndex], - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri), - selectedDate, - widget.picker.isHijri)) { + widget.visibleDates[currentMonthIndex], + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + DateRangePickerHelper.canShowLeadingAndTrailingDates( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + selectedDate, + widget.picker.isHijri, + )) { return; } - if (DateRangePickerHelper.isDateWithInVisibleDates(widget.visibleDates, - widget.picker.monthViewSettings.blackoutDates, selectedDate) || + if (DateRangePickerHelper.isDateWithInVisibleDates( + widget.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - widget.visibleDates, widget.disableDatePredicates, selectedDate)) { + widget.visibleDates, + widget.disableDatePredicates, + selectedDate, + )) { return; } @@ -12115,11 +12957,12 @@ class _PickerViewState extends State<_PickerView> DateRangePickerSelectionMode.extendableRange && _pickerStateDetails.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return; } @@ -12141,21 +12984,27 @@ class _PickerViewState extends State<_PickerView> break; case DateRangePickerSelectionMode.range: { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } break; case DateRangePickerSelectionMode.multiRange: { _pickerStateDetails.selectedRanges ??= []; - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); _removeInterceptRanges( - _pickerStateDetails.selectedRanges, - _pickerStateDetails.selectedRanges![ - _pickerStateDetails.selectedRanges!.length - 1]); + _pickerStateDetails.selectedRanges, + _pickerStateDetails.selectedRanges![_pickerStateDetails + .selectedRanges! + .length - + 1], + ); } break; case DateRangePickerSelectionMode.extendableRange: @@ -12172,24 +13021,30 @@ class _PickerViewState extends State<_PickerView> { //// Check the start date of the range updated or not, if not updated then create the new range. if (!_isDragStart) { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } else { if (_pickerStateDetails.selectedRange != null && _pickerStateDetails.selectedRange.startDate != null) { final dynamic updatedRange = _getSelectedRangeOnDragUpdate( - _pickerStateDetails.selectedRange, selectedDate); + _pickerStateDetails.selectedRange, + selectedDate, + ); if (DateRangePickerHelper.isRangeEquals( - _pickerStateDetails.selectedRange, updatedRange)) { + _pickerStateDetails.selectedRange, + updatedRange, + )) { return; } _pickerStateDetails.selectedRange = updatedRange; } else { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } } } @@ -12205,30 +13060,41 @@ class _PickerViewState extends State<_PickerView> //// Check the start date of the range updated or not, if not updated then create the new range. if (!_isDragStart) { - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); } else { if (lastRange != null && lastRange.startDate != null) { - final dynamic updatedRange = - _getSelectedRangeOnDragUpdate(lastRange, selectedDate); + final dynamic updatedRange = _getSelectedRangeOnDragUpdate( + lastRange, + selectedDate, + ); if (DateRangePickerHelper.isRangeEquals( - lastRange, updatedRange)) { + lastRange, + updatedRange, + )) { return; } _pickerStateDetails.selectedRanges![count - 1] = updatedRange; } else { - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); } } _removeInterceptRanges( - _pickerStateDetails.selectedRanges, - _pickerStateDetails.selectedRanges![ - _pickerStateDetails.selectedRanges!.length - 1]); + _pickerStateDetails.selectedRanges, + _pickerStateDetails.selectedRanges![_pickerStateDetails + .selectedRanges! + .length - + 1], + ); } break; case DateRangePickerSelectionMode.extendableRange: @@ -12238,7 +13104,9 @@ class _PickerViewState extends State<_PickerView> /// Return the range that start date is before of end date in month view. dynamic _getSelectedRangeOnDragUpdate( - dynamic previousRange, dynamic selectedDate) { + dynamic previousRange, + dynamic selectedDate, + ) { final dynamic previousRangeStartDate = previousRange.startDate; final dynamic previousRangeEndDate = previousRange.endDate ?? previousRange.startDate; @@ -12271,14 +13139,19 @@ class _PickerViewState extends State<_PickerView> /// Return the range that start date is before of end date in year view. dynamic _getSelectedRangeOnDragUpdateYear( - dynamic previousRange, dynamic selectedDate) { + dynamic previousRange, + dynamic selectedDate, + ) { final dynamic previousRangeStartDate = previousRange.startDate; final dynamic previousRangeEndDate = previousRange.endDate ?? previousRange.startDate; dynamic rangeStartDate = previousRangeStartDate; dynamic rangeEndDate = selectedDate; - if (DateRangePickerHelper.isSameCellDates(previousRangeStartDate, - _previousSelectedDate, widget.controller.view)) { + if (DateRangePickerHelper.isSameCellDates( + previousRangeStartDate, + _previousSelectedDate, + widget.controller.view, + )) { if (_isSameOrBeforeDateCell(previousRangeEndDate, rangeEndDate)) { rangeStartDate = selectedDate; rangeEndDate = previousRangeEndDate; @@ -12287,7 +13160,10 @@ class _PickerViewState extends State<_PickerView> rangeEndDate = selectedDate; } } else if (DateRangePickerHelper.isSameCellDates( - previousRangeEndDate, _previousSelectedDate, widget.controller.view)) { + previousRangeEndDate, + _previousSelectedDate, + widget.controller.view, + )) { if (_isSameOrAfterDateCell(previousRangeStartDate, rangeEndDate)) { rangeStartDate = previousRangeStartDate; rangeEndDate = selectedDate; @@ -12298,21 +13174,30 @@ class _PickerViewState extends State<_PickerView> } rangeEndDate = DateRangePickerHelper.getLastDate( - rangeEndDate, widget.controller.view, widget.picker.isHijri); + rangeEndDate, + widget.controller.view, + widget.picker.isHijri, + ); if (widget.picker.maxDate != null) { - rangeEndDate = rangeEndDate.isAfter(widget.picker.maxDate) == true - ? widget.picker.maxDate - : rangeEndDate; + rangeEndDate = + rangeEndDate.isAfter(widget.picker.maxDate) == true + ? widget.picker.maxDate + : rangeEndDate; } - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); rangeStartDate = DateRangePickerHelper.getFirstDate( - rangeStartDate, widget.picker.isHijri, pickerView); + rangeStartDate, + widget.picker.isHijri, + pickerView, + ); if (widget.picker.minDate != null) { - rangeStartDate = rangeStartDate.isBefore(widget.picker.minDate) == true - ? widget.picker.minDate - : rangeStartDate; + rangeStartDate = + rangeStartDate.isBefore(widget.picker.minDate) == true + ? widget.picker.minDate + : rangeStartDate; } if (widget.picker.isHijri) { @@ -12328,8 +13213,9 @@ class _PickerViewState extends State<_PickerView> /// consider the month value(max month as 12). /// Note: This method not applicable for month view. bool _isSameOrBeforeDateCell(dynamic currentMaxDate, dynamic currentDate) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView == DateRangePickerView.year) { return (currentDate.month <= currentMaxDate.month == true && currentDate.year == currentMaxDate.year) || @@ -12349,8 +13235,9 @@ class _PickerViewState extends State<_PickerView> /// consider the month value(min month as 12). /// Note: This method not applicable for month view. bool _isSameOrAfterDateCell(dynamic currentMinDate, dynamic currentDate) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView == DateRangePickerView.year) { return (currentDate.month >= currentMinDate.month == true && currentDate.year == currentMinDate.year) || @@ -12373,24 +13260,30 @@ class _PickerViewState extends State<_PickerView> { //// Check the start date of the range updated or not, if not updated then create the new range. if (!_isDragStart) { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } else { if (_pickerStateDetails.selectedRange != null && _pickerStateDetails.selectedRange.startDate != null) { final dynamic updatedRange = _getSelectedRangeOnDragUpdateYear( - _pickerStateDetails.selectedRange, selectedDate); + _pickerStateDetails.selectedRange, + selectedDate, + ); if (DateRangePickerHelper.isRangeEquals( - _pickerStateDetails.selectedRange, updatedRange)) { + _pickerStateDetails.selectedRange, + updatedRange, + )) { return; } _pickerStateDetails.selectedRange = updatedRange; } else { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } } } @@ -12406,30 +13299,41 @@ class _PickerViewState extends State<_PickerView> //// Check the start date of the range updated or not, if not updated then create the new range. if (!_isDragStart) { - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); } else { if (lastRange != null && lastRange.startDate != null) { - final dynamic updatedRange = - _getSelectedRangeOnDragUpdateYear(lastRange, selectedDate); + final dynamic updatedRange = _getSelectedRangeOnDragUpdateYear( + lastRange, + selectedDate, + ); if (DateRangePickerHelper.isRangeEquals( - lastRange, updatedRange)) { + lastRange, + updatedRange, + )) { return; } _pickerStateDetails.selectedRanges![count - 1] = updatedRange; } else { - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); } } _removeInterceptRanges( - _pickerStateDetails.selectedRanges, - _pickerStateDetails.selectedRanges![ - _pickerStateDetails.selectedRanges!.length - 1]); + _pickerStateDetails.selectedRanges, + _pickerStateDetails.selectedRanges![_pickerStateDetails + .selectedRanges! + .length - + 1], + ); } break; case DateRangePickerSelectionMode.extendableRange: @@ -12441,22 +13345,28 @@ class _PickerViewState extends State<_PickerView> //// Set drag start value as false, identifies the start date of the range not updated. _isDragStart = false; widget.getPickerStateDetails(_pickerStateDetails); - final int index = - _getYearViewIndex(details.localPosition.dx, details.localPosition.dy); + final int index = _getYearViewIndex( + details.localPosition.dx, + details.localPosition.dy, + ); if (index == -1) { return; } final dynamic selectedDate = widget.visibleDates[index]; if (!DateRangePickerHelper.isBetweenMinMaxDateCell( - selectedDate, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri) || + selectedDate, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - widget.visibleDates, widget.disableDatePredicates, selectedDate)) { + widget.visibleDates, + widget.disableDatePredicates, + selectedDate, + )) { return; } @@ -12469,11 +13379,12 @@ class _PickerViewState extends State<_PickerView> final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView(widget.controller.view); if (DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return; } } @@ -12489,22 +13400,28 @@ class _PickerViewState extends State<_PickerView> void _dragUpdateOnYear(DragUpdateDetails details) { widget.getPickerStateDetails(_pickerStateDetails); - final int index = - _getYearViewIndex(details.localPosition.dx, details.localPosition.dy); + final int index = _getYearViewIndex( + details.localPosition.dx, + details.localPosition.dy, + ); if (index == -1) { return; } final dynamic selectedDate = widget.visibleDates[index]; if (!DateRangePickerHelper.isBetweenMinMaxDateCell( - selectedDate, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri) || + selectedDate, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - widget.visibleDates, widget.disableDatePredicates, selectedDate)) { + widget.visibleDates, + widget.disableDatePredicates, + selectedDate, + )) { return; } @@ -12517,11 +13434,12 @@ class _PickerViewState extends State<_PickerView> final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView(widget.controller.view); if (DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return; } } @@ -12537,8 +13455,9 @@ class _PickerViewState extends State<_PickerView> void _handleTouch(Offset details, TapUpDetails tapUpDetails) { widget.getPickerStateDetails(_pickerStateDetails); - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (pickerView == DateRangePickerView.month) { final int index = _getSelectedIndex(details.dx, details.dy); if (index == -1) { @@ -12547,30 +13466,42 @@ class _PickerViewState extends State<_PickerView> final dynamic selectedDate = widget.visibleDates[index]; if (!DateRangePickerHelper.isEnabledDate( - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - selectedDate, - widget.picker.isHijri)) { + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + selectedDate, + widget.picker.isHijri, + )) { return; } final int currentMonthIndex = _getCurrentDateIndex(index); if (!DateRangePickerHelper.isDateAsCurrentMonthDate( - widget.visibleDates[currentMonthIndex], - DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri), - DateRangePickerHelper.canShowLeadingAndTrailingDates( - widget.picker.monthViewSettings, widget.picker.isHijri), - selectedDate, - widget.picker.isHijri)) { + widget.visibleDates[currentMonthIndex], + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + DateRangePickerHelper.canShowLeadingAndTrailingDates( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ), + selectedDate, + widget.picker.isHijri, + )) { return; } - if (DateRangePickerHelper.isDateWithInVisibleDates(widget.visibleDates, - widget.picker.monthViewSettings.blackoutDates, selectedDate) || - DateRangePickerHelper.isDateWithInVisibleDates(widget.visibleDates, - widget.disableDatePredicates, selectedDate)) { + if (DateRangePickerHelper.isDateWithInVisibleDates( + widget.visibleDates, + widget.picker.monthViewSettings.blackoutDates, + selectedDate, + ) || + DateRangePickerHelper.isDateWithInVisibleDates( + widget.visibleDates, + widget.disableDatePredicates, + selectedDate, + )) { return; } @@ -12581,11 +13512,12 @@ class _PickerViewState extends State<_PickerView> DateRangePickerSelectionMode.extendableRange && _pickerStateDetails.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - selectedDate, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + selectedDate, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return; } @@ -12597,8 +13529,11 @@ class _PickerViewState extends State<_PickerView> } int _getCurrentDateIndex(int index) { - final int datesCount = DateRangePickerHelper.getNumberOfWeeksInView( - widget.picker.monthViewSettings, widget.picker.isHijri) * + final int datesCount = + DateRangePickerHelper.getNumberOfWeeksInView( + widget.picker.monthViewSettings, + widget.picker.isHijri, + ) * DateTime.daysPerWeek; int currentMonthIndex = datesCount ~/ 2; if (widget.enableMultiView && index >= datesCount) { @@ -12610,8 +13545,11 @@ class _PickerViewState extends State<_PickerView> void _drawSingleSelectionForYear(dynamic selectedDate) { if (widget.picker.toggleDaySelection && - DateRangePickerHelper.isSameCellDates(selectedDate, - _pickerStateDetails.selectedDate, widget.controller.view)) { + DateRangePickerHelper.isSameCellDates( + selectedDate, + _pickerStateDetails.selectedDate, + widget.controller.view, + )) { selectedDate = null; } @@ -12623,9 +13561,10 @@ class _PickerViewState extends State<_PickerView> if (_pickerStateDetails.selectedDates != null && _pickerStateDetails.selectedDates!.isNotEmpty) { selectedIndex = DateRangePickerHelper.getDateCellIndex( - _pickerStateDetails.selectedDates!, - selectedDate, - widget.controller.view); + _pickerStateDetails.selectedDates!, + selectedDate, + widget.controller.view, + ); } if (selectedIndex == -1) { @@ -12641,9 +13580,10 @@ class _PickerViewState extends State<_PickerView> _pickerStateDetails.selectedRange.startDate != null && (_pickerStateDetails.selectedRange.endDate == null || DateRangePickerHelper.isSameCellDates( - _pickerStateDetails.selectedRange.startDate, - _pickerStateDetails.selectedRange.endDate, - widget.controller.view))) { + _pickerStateDetails.selectedRange.startDate, + _pickerStateDetails.selectedRange.endDate, + widget.controller.view, + ))) { dynamic startDate = _pickerStateDetails.selectedRange.startDate; dynamic endDate = selectedDate; if (startDate.isAfter(endDate) == true) { @@ -12653,26 +13593,33 @@ class _PickerViewState extends State<_PickerView> } endDate = DateRangePickerHelper.getLastDate( - endDate, widget.controller.view, widget.picker.isHijri); + endDate, + widget.controller.view, + widget.picker.isHijri, + ); if (widget.picker.maxDate != null) { - endDate = endDate.isAfter(widget.picker.maxDate) == true - ? widget.picker.maxDate - : endDate; + endDate = + endDate.isAfter(widget.picker.maxDate) == true + ? widget.picker.maxDate + : endDate; } if (widget.picker.minDate != null) { - startDate = startDate.isBefore(widget.picker.minDate) == true - ? widget.picker.minDate - : startDate; + startDate = + startDate.isBefore(widget.picker.minDate) == true + ? widget.picker.minDate + : startDate; } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); } else { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } _lastSelectedDate = selectedDate; @@ -12689,8 +13636,11 @@ class _PickerViewState extends State<_PickerView> if (lastRange != null && lastRange.startDate != null && (lastRange.endDate == null || - DateRangePickerHelper.isSameCellDates(lastRange.startDate, - lastRange.endDate, widget.controller.view))) { + DateRangePickerHelper.isSameCellDates( + lastRange.startDate, + lastRange.endDate, + widget.controller.view, + ))) { dynamic startDate = lastRange.startDate; dynamic endDate = selectedDate; if (startDate.isAfter(endDate) == true) { @@ -12700,40 +13650,53 @@ class _PickerViewState extends State<_PickerView> } endDate = DateRangePickerHelper.getLastDate( - endDate, widget.controller.view, widget.picker.isHijri); + endDate, + widget.controller.view, + widget.picker.isHijri, + ); if (widget.picker.maxDate != null) { - endDate = endDate.isAfter(widget.picker.maxDate) == true - ? widget.picker.maxDate - : endDate; + endDate = + endDate.isAfter(widget.picker.maxDate) == true + ? widget.picker.maxDate + : endDate; } if (widget.picker.minDate != null) { - startDate = startDate.isBefore(widget.picker.minDate) == true - ? widget.picker.minDate - : startDate; + startDate = + startDate.isBefore(widget.picker.minDate) == true + ? widget.picker.minDate + : startDate; } - final dynamic newRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + final dynamic newRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); _pickerStateDetails.selectedRanges![count - 1] = newRange; } else { - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); } count = _pickerStateDetails.selectedRanges!.length; _removeInterceptRanges( - _pickerStateDetails.selectedRanges, + _pickerStateDetails.selectedRanges, + _pickerStateDetails + .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1], + ); + lastRange = _pickerStateDetails - .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1]); - lastRange = _pickerStateDetails - .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1]; + .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1]; if (count != _pickerStateDetails.selectedRanges!.length && (lastRange.endDate == null || - DateRangePickerHelper.isSameCellDates(lastRange.endDate, - lastRange.startDate, widget.controller.view))) { + DateRangePickerHelper.isSameCellDates( + lastRange.endDate, + lastRange.startDate, + widget.controller.view, + ))) { _pickerStateDetails.selectedRanges!.removeLast(); } } @@ -12766,18 +13729,23 @@ class _PickerViewState extends State<_PickerView> final dynamic date = widget.visibleDates[selectedIndex]; widget.getPickerStateDetails(_pickerStateDetails); - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (!widget.picker.allowViewNavigation) { if (!DateRangePickerHelper.isBetweenMinMaxDateCell( - date, - widget.picker.minDate, - widget.picker.maxDate, - widget.picker.enablePastDates, - widget.controller.view, - widget.picker.isHijri) || + date, + widget.picker.minDate, + widget.picker.maxDate, + widget.picker.enablePastDates, + widget.controller.view, + widget.picker.isHijri, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - widget.visibleDates, widget.disableDatePredicates, date)) { + widget.visibleDates, + widget.disableDatePredicates, + date, + )) { return; } @@ -12788,11 +13756,12 @@ class _PickerViewState extends State<_PickerView> DateRangePickerSelectionMode.extendableRange && _pickerStateDetails.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - _pickerStateDetails.selectedRange, - date, - widget.picker.extendableRangeSelectionDirection, - pickerView, - widget.picker.isHijri)) { + _pickerStateDetails.selectedRange, + date, + widget.picker.extendableRangeSelectionDirection, + pickerView, + widget.picker.isHijri, + )) { return; } @@ -12862,7 +13831,9 @@ class _PickerViewState extends State<_PickerView> void _drawMultipleSelectionForMonth(dynamic selectedDate) { final int selectedIndex = DateRangePickerHelper.isDateIndexInCollection( - _pickerStateDetails.selectedDates, selectedDate); + _pickerStateDetails.selectedDates, + selectedDate, + ); if (selectedIndex == -1) { _pickerStateDetails.selectedDates ??= []; _pickerStateDetails.selectedDates!.add(selectedDate); @@ -12874,20 +13845,23 @@ class _PickerViewState extends State<_PickerView> /// Draws the extendable selection, by extending the already available range /// selection. void _drawExtendableRangeSelection(dynamic selectedDate) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); if (_pickerStateDetails.selectedRange == null) { dynamic startDate = selectedDate; if (pickerView != DateRangePickerView.month && widget.picker.minDate != null) { - startDate = startDate.isBefore(widget.picker.minDate) == true - ? widget.picker.minDate - : startDate; + startDate = + startDate.isBefore(widget.picker.minDate) == true + ? widget.picker.minDate + : startDate; } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, null) - : PickerDateRange(startDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, null) + : PickerDateRange(startDate, null); _lastSelectedDate = selectedDate; return; } @@ -12931,25 +13905,34 @@ class _PickerViewState extends State<_PickerView> if (pickerView != DateRangePickerView.month) { endDate = DateRangePickerHelper.getLastDate( - endDate, widget.controller.view, widget.picker.isHijri); + endDate, + widget.controller.view, + widget.picker.isHijri, + ); if (widget.picker.maxDate != null) { - endDate = endDate.isAfter(widget.picker.maxDate) == true - ? widget.picker.maxDate - : endDate; + endDate = + endDate.isAfter(widget.picker.maxDate) == true + ? widget.picker.maxDate + : endDate; } startDate = DateRangePickerHelper.getFirstDate( - startDate, widget.picker.isHijri, pickerView); + startDate, + widget.picker.isHijri, + pickerView, + ); if (widget.picker.minDate != null) { - startDate = startDate.isBefore(widget.picker.minDate) == true - ? widget.picker.minDate - : startDate; + startDate = + startDate.isBefore(widget.picker.minDate) == true + ? widget.picker.minDate + : startDate; } } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); _lastSelectedDate = selectedDate; _mouseHoverPosition.value = HoveringDetails(null, null); @@ -12959,8 +13942,10 @@ class _PickerViewState extends State<_PickerView> if (_pickerStateDetails.selectedRange != null && _pickerStateDetails.selectedRange.startDate != null && (_pickerStateDetails.selectedRange.endDate == null || - isSameDate(_pickerStateDetails.selectedRange.startDate, - _pickerStateDetails.selectedRange.endDate))) { + isSameDate( + _pickerStateDetails.selectedRange.startDate, + _pickerStateDetails.selectedRange.endDate, + ))) { dynamic startDate = _pickerStateDetails.selectedRange.startDate; dynamic endDate = selectedDate; if (startDate.isAfter(endDate) == true) { @@ -12969,13 +13954,15 @@ class _PickerViewState extends State<_PickerView> endDate = temp; } - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); } else { - _pickerStateDetails.selectedRange = widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null); + _pickerStateDetails.selectedRange = + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null); } _lastSelectedDate = selectedDate; @@ -13001,23 +13988,28 @@ class _PickerViewState extends State<_PickerView> endDate = temp; } - final dynamic newRange = widget.picker.isHijri - ? HijriDateRange(startDate, endDate) - : PickerDateRange(startDate, endDate); + final dynamic newRange = + widget.picker.isHijri + ? HijriDateRange(startDate, endDate) + : PickerDateRange(startDate, endDate); _pickerStateDetails.selectedRanges![count - 1] = newRange; } else { - _pickerStateDetails.selectedRanges!.add(widget.picker.isHijri - ? HijriDateRange(selectedDate, null) - : PickerDateRange(selectedDate, null)); + _pickerStateDetails.selectedRanges!.add( + widget.picker.isHijri + ? HijriDateRange(selectedDate, null) + : PickerDateRange(selectedDate, null), + ); } count = _pickerStateDetails.selectedRanges!.length; _removeInterceptRanges( - _pickerStateDetails.selectedRanges, + _pickerStateDetails.selectedRanges, + _pickerStateDetails + .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1], + ); + lastRange = _pickerStateDetails - .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1]); - lastRange = _pickerStateDetails - .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1]; + .selectedRanges![_pickerStateDetails.selectedRanges!.length - 1]; if (count != _pickerStateDetails.selectedRanges!.length && (lastRange.endDate == null || isSameDate(lastRange.endDate, lastRange.startDate))) { @@ -13025,8 +14017,13 @@ class _PickerViewState extends State<_PickerView> } } - int? _removeInterceptRangesForMonth(dynamic range, dynamic startDate, - dynamic endDate, int i, dynamic selectedRangeValue) { + int? _removeInterceptRangesForMonth( + dynamic range, + dynamic startDate, + dynamic endDate, + int i, + dynamic selectedRangeValue, + ) { if (range != null && !DateRangePickerHelper.isRangeEquals(range, selectedRangeValue) && ((range.startDate != null && @@ -13041,18 +14038,30 @@ class _PickerViewState extends State<_PickerView> range.endDate != null && ((startDate != null && isDateWithInDateRange( - range.startDate, range.endDate, startDate)) || + range.startDate, + range.endDate, + startDate, + )) || (endDate != null && isDateWithInDateRange( - range.startDate, range.endDate, endDate)))) || + range.startDate, + range.endDate, + endDate, + )))) || (startDate != null && endDate != null && ((range.startDate != null && isDateWithInDateRange( - startDate, endDate, range.startDate)) || + startDate, + endDate, + range.startDate, + )) || (range.endDate != null && isDateWithInDateRange( - startDate, endDate, range.endDate)))) || + startDate, + endDate, + range.endDate, + )))) || (range.startDate != null && range.endDate != null && startDate != null && @@ -13067,8 +14076,13 @@ class _PickerViewState extends State<_PickerView> return null; } - int? _removeInterceptRangesForYear(dynamic range, dynamic startDate, - dynamic endDate, int i, dynamic selectedRangeValue) { + int? _removeInterceptRangesForYear( + dynamic range, + dynamic startDate, + dynamic endDate, + int i, + dynamic selectedRangeValue, + ) { if (range == null || DateRangePickerHelper.isRangeEquals(range, selectedRangeValue)) { return null; @@ -13078,10 +14092,16 @@ class _PickerViewState extends State<_PickerView> if (range.startDate != null && ((startDate != null && DateRangePickerHelper.isSameCellDates( - range.startDate, startDate, widget.controller.view)) || + range.startDate, + startDate, + widget.controller.view, + )) || (endDate != null && DateRangePickerHelper.isSameCellDates( - range.startDate, endDate, widget.controller.view)))) { + range.startDate, + endDate, + widget.controller.view, + )))) { return i; } @@ -13089,10 +14109,16 @@ class _PickerViewState extends State<_PickerView> if (range.endDate != null && ((startDate != null && DateRangePickerHelper.isSameCellDates( - range.endDate, startDate, widget.controller.view)) || + range.endDate, + startDate, + widget.controller.view, + )) || (endDate != null && DateRangePickerHelper.isSameCellDates( - range.endDate, endDate, widget.controller.view)))) { + range.endDate, + endDate, + widget.controller.view, + )))) { return i; } @@ -13101,10 +14127,16 @@ class _PickerViewState extends State<_PickerView> range.endDate != null && ((startDate != null && _isDateWithInYearRange( - range.startDate, range.endDate, startDate)) || + range.startDate, + range.endDate, + startDate, + )) || (endDate != null && _isDateWithInYearRange( - range.startDate, range.endDate, endDate)))) { + range.startDate, + range.endDate, + endDate, + )))) { return i; } @@ -13137,13 +14169,17 @@ class _PickerViewState extends State<_PickerView> /// Check whether the date is in between the start and end date value. bool _isDateWithInYearRange( - dynamic startDate, dynamic endDate, dynamic date) { + dynamic startDate, + dynamic endDate, + dynamic date, + ) { if (startDate == null || endDate == null || date == null) { return false; } - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(widget.controller.view); + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + widget.controller.view, + ); /// Check the start date as before of end date, if not then swap /// the start and end date values. @@ -13166,7 +14202,9 @@ class _PickerViewState extends State<_PickerView> } void _removeInterceptRanges( - List? selectedRanges, dynamic selectedRangeValue) { + List? selectedRanges, + dynamic selectedRangeValue, + ) { if (selectedRanges == null || selectedRanges.isEmpty || selectedRangeValue == null) { @@ -13198,7 +14236,12 @@ class _PickerViewState extends State<_PickerView> case DateRangePickerView.month: { index = _removeInterceptRangesForMonth( - range, startDate, endDate, i, selectedRangeValue); + range, + startDate, + endDate, + i, + selectedRangeValue, + ); } break; case DateRangePickerView.year: @@ -13206,7 +14249,12 @@ class _PickerViewState extends State<_PickerView> case DateRangePickerView.century: { index = _removeInterceptRangesForYear( - range, startDate, endDate, i, selectedRangeValue); + range, + startDate, + endDate, + i, + selectedRangeValue, + ); } } if (index != null) { @@ -13222,19 +14270,20 @@ class _PickerViewState extends State<_PickerView> } String _getMonthHeaderText( - int startIndex, - int endIndex, - List dates, - int middleIndex, - int datesCount, - bool isHijri, - int numberOfWeeksInView, - String? monthFormat, - bool enableMultiView, - DateRangePickerHeaderStyle headerStyle, - DateRangePickerNavigationDirection navigationDirection, - Locale locale, - SfLocalizations localizations) { + int startIndex, + int endIndex, + List dates, + int middleIndex, + int datesCount, + bool isHijri, + int numberOfWeeksInView, + String? monthFormat, + bool enableMultiView, + DateRangePickerHeaderStyle headerStyle, + DateRangePickerNavigationDirection navigationDirection, + Locale locale, + SfLocalizations localizations, +) { if ((!isHijri && numberOfWeeksInView != 6) && dates[startIndex].month != dates[endIndex].month) { final String monthTextFormat = @@ -13255,13 +14304,14 @@ String _getMonthHeaderText( return '$startText - $endText'; } else { - final String monthTextFormat = monthFormat == null || monthFormat.isEmpty - ? enableMultiView && - navigationDirection == - DateRangePickerNavigationDirection.vertical - ? 'MMM' - : 'MMMM' - : monthFormat; + final String monthTextFormat = + monthFormat == null || monthFormat.isEmpty + ? enableMultiView && + navigationDirection == + DateRangePickerNavigationDirection.vertical + ? 'MMM' + : 'MMMM' + : monthFormat; String text; dynamic middleDate = dates[middleIndex]; if (isHijri) { @@ -13302,17 +14352,18 @@ String _getMonthHeaderText( } String _getHeaderText( - List dates, - DateRangePickerView view, - int index, - bool isHijri, - int numberOfWeeksInView, - String? monthFormat, - bool enableMultiView, - DateRangePickerHeaderStyle headerStyle, - DateRangePickerNavigationDirection navigationDirection, - Locale locale, - SfLocalizations localizations) { + List dates, + DateRangePickerView view, + int index, + bool isHijri, + int numberOfWeeksInView, + String? monthFormat, + bool enableMultiView, + DateRangePickerHeaderStyle headerStyle, + DateRangePickerNavigationDirection navigationDirection, + Locale locale, + SfLocalizations localizations, +) { final int count = enableMultiView ? 2 : 1; final int datesCount = dates.length ~/ count; final int startIndex = index * datesCount; @@ -13322,19 +14373,20 @@ String _getHeaderText( case DateRangePickerView.month: { return _getMonthHeaderText( - startIndex, - endIndex, - dates, - middleIndex, - datesCount, - isHijri, - numberOfWeeksInView, - monthFormat, - enableMultiView, - headerStyle, - navigationDirection, - locale, - localizations); + startIndex, + endIndex, + dates, + middleIndex, + datesCount, + isHijri, + numberOfWeeksInView, + monthFormat, + enableMultiView, + headerStyle, + navigationDirection, + locale, + localizations, + ); } case DateRangePickerView.year: { @@ -13378,10 +14430,14 @@ String _getHeaderText( } Size _getTextWidgetWidth( - String text, double height, double width, BuildContext context, - {required TextStyle style, - double widthPadding = 10, - double heightPadding = 10}) { + String text, + double height, + double width, + BuildContext context, { + required TextStyle style, + double widthPadding = 10, + double heightPadding = 10, +}) { /// Create new text with it style. final Widget textWidget = Text( text, @@ -13396,18 +14452,22 @@ Size _getTextWidgetWidth( /// Create and layout the render object based on /// allocated width and height. - final RenderParagraph renderObject = - richTextWidget!.createRenderObject(context); - renderObject.layout(BoxConstraints( - minWidth: width, - maxWidth: width, - minHeight: height, - maxHeight: height, - )); + final RenderParagraph renderObject = richTextWidget!.createRenderObject( + context, + ); + renderObject.layout( + BoxConstraints( + minWidth: width, + maxWidth: width, + minHeight: height, + maxHeight: height, + ), + ); /// Get the size of text by using render object. final List textBox = renderObject.getBoxesForSelection( - TextSelection(baseOffset: 0, extentOffset: text.length)); + TextSelection(baseOffset: 0, extentOffset: text.length), + ); double textWidth = 0; double textHeight = 0; for (final TextBox box in textBox) { @@ -13420,7 +14480,9 @@ Size _getTextWidgetWidth( } bool _isSwipeInteractionEnabled( - bool enableSwipeSelection, DateRangePickerNavigationMode navigationMode) { + bool enableSwipeSelection, + DateRangePickerNavigationMode navigationMode, +) { return enableSwipeSelection && navigationMode != DateRangePickerNavigationMode.scroll; } diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker_manager.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker_manager.dart index b80f6ceaa..c4f225957 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker_manager.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/date_picker_manager.dart @@ -48,8 +48,11 @@ import 'picker_helper.dart'; @immutable class DateRangePickerHeaderStyle with Diagnosticable { /// Creates a header style for date range picker. - const DateRangePickerHeaderStyle( - {this.textAlign = TextAlign.left, this.backgroundColor, this.textStyle}); + const DateRangePickerHeaderStyle({ + this.textAlign = TextAlign.left, + this.backgroundColor, + this.textStyle, + }); /// The text style for the text in the [SfDateRangePicker] header view. /// @@ -191,11 +194,7 @@ class DateRangePickerHeaderStyle with Diagnosticable { @override int get hashCode { - return Object.hash( - textStyle, - textAlign, - backgroundColor, - ); + return Object.hash(textStyle, textAlign, backgroundColor); } } @@ -346,10 +345,7 @@ class DateRangePickerViewHeaderStyle with Diagnosticable { @override int get hashCode { - return Object.hash( - backgroundColor, - textStyle, - ); + return Object.hash(backgroundColor, textStyle); } } @@ -473,10 +469,7 @@ class DateRangePickerWeekNumberStyle with Diagnosticable { @override int get hashCode { - return Object.hash( - textStyle, - backgroundColor, - ); + return Object.hash(textStyle, backgroundColor); } } @@ -558,25 +551,25 @@ class DateRangePickerMonthViewSettings with Diagnosticable { /// Creates a date range picker month view settings for date range picker. /// /// The properties allows to customize the month view of [SfDateRangePicker]. - const DateRangePickerMonthViewSettings( - {this.numberOfWeeksInView = 6, - this.firstDayOfWeek = 7, - this.dayFormat = 'EE', - this.viewHeaderHeight = 30, - @Deprecated('Use selectionRadius property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.selectionRadius = -1, - this.showTrailingAndLeadingDates = false, - this.viewHeaderStyle = const DateRangePickerViewHeaderStyle(), - this.enableSwipeSelection = true, - this.blackoutDates, - this.specialDates, - this.weekendDays = const [6, 7], - this.showWeekNumber = false, - this.weekNumberStyle = const DateRangePickerWeekNumberStyle()}) - : assert(numberOfWeeksInView >= 1 && numberOfWeeksInView <= 6), - assert(firstDayOfWeek >= 1 && firstDayOfWeek <= 7), - assert(viewHeaderHeight >= -1); + const DateRangePickerMonthViewSettings({ + this.numberOfWeeksInView = 6, + this.firstDayOfWeek = 7, + this.dayFormat = 'EE', + this.viewHeaderHeight = 30, + @Deprecated('Use selectionRadius property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.selectionRadius = -1, + this.showTrailingAndLeadingDates = false, + this.viewHeaderStyle = const DateRangePickerViewHeaderStyle(), + this.enableSwipeSelection = true, + this.blackoutDates, + this.specialDates, + this.weekendDays = const [6, 7], + this.showWeekNumber = false, + this.weekNumberStyle = const DateRangePickerWeekNumberStyle(), + }) : assert(numberOfWeeksInView >= 1 && numberOfWeeksInView <= 6), + assert(firstDayOfWeek >= 1 && firstDayOfWeek <= 7), + assert(viewHeaderHeight >= -1); /// Formats a text in the [SfDateRangePicker] month view view header. /// @@ -1099,18 +1092,29 @@ class DateRangePickerMonthViewSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(IterableDiagnostics(blackoutDates) - .toDiagnosticsNode(name: 'blackoutDates')); - properties.add(IterableDiagnostics(specialDates) - .toDiagnosticsNode(name: 'specialDates')); + properties.add( + IterableDiagnostics( + blackoutDates, + ).toDiagnosticsNode(name: 'blackoutDates'), + ); + properties.add( + IterableDiagnostics( + specialDates, + ).toDiagnosticsNode(name: 'specialDates'), + ); properties.add(IntProperty('numberOfWeeksInView', numberOfWeeksInView)); properties.add(IntProperty('firstDayOfWeek', firstDayOfWeek)); properties.add(DoubleProperty('viewHeaderHeight', viewHeaderHeight)); properties.add(StringProperty('dayFormat', dayFormat)); - properties.add(DiagnosticsProperty( - 'showTrailingAndLeadingDates', showTrailingAndLeadingDates)); - properties.add(DiagnosticsProperty( - 'enableSwipeSelection', enableSwipeSelection)); + properties.add( + DiagnosticsProperty( + 'showTrailingAndLeadingDates', + showTrailingAndLeadingDates, + ), + ); + properties.add( + DiagnosticsProperty('enableSwipeSelection', enableSwipeSelection), + ); properties.add(viewHeaderStyle.toDiagnosticsNode(name: 'viewHeaderStyle')); properties.add(IterableProperty('weekendDays', weekendDays)); properties.add(DiagnosticsProperty('showWeekNumber', showWeekNumber)); @@ -1120,21 +1124,22 @@ class DateRangePickerMonthViewSettings with Diagnosticable { @override int get hashCode { return Object.hash( - dayFormat, - firstDayOfWeek, - viewHeaderStyle, - enableSwipeSelection, - viewHeaderHeight, - showTrailingAndLeadingDates, - numberOfWeeksInView, - showWeekNumber, - weekNumberStyle, - - /// Below condition is referred from text style class - /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html - specialDates == null ? null : Object.hashAll(specialDates!), - blackoutDates == null ? null : Object.hashAll(blackoutDates!), - Object.hashAll(weekendDays)); + dayFormat, + firstDayOfWeek, + viewHeaderStyle, + enableSwipeSelection, + viewHeaderHeight, + showTrailingAndLeadingDates, + numberOfWeeksInView, + showWeekNumber, + weekNumberStyle, + + /// Below condition is referred from text style class + /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html + specialDates == null ? null : Object.hashAll(specialDates!), + blackoutDates == null ? null : Object.hashAll(blackoutDates!), + Object.hashAll(weekendDays), + ); } } @@ -1214,15 +1219,16 @@ class DateRangePickerYearCellStyle with Diagnosticable { /// /// The properties allows to customize the year cells in year view of /// [SfDateRangePicker]. - const DateRangePickerYearCellStyle( - {this.textStyle, - this.todayTextStyle, - this.leadingDatesTextStyle, - this.disabledDatesTextStyle, - this.cellDecoration, - this.todayCellDecoration, - this.disabledDatesDecoration, - this.leadingDatesDecoration}); + const DateRangePickerYearCellStyle({ + this.textStyle, + this.todayTextStyle, + this.leadingDatesTextStyle, + this.disabledDatesTextStyle, + this.cellDecoration, + this.todayCellDecoration, + this.disabledDatesDecoration, + this.leadingDatesDecoration, + }); /// The text style for the text in the [SfDateRangePicker] year, decade and /// century view cells. @@ -1657,33 +1663,56 @@ class DateRangePickerYearCellStyle with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('textStyle', textStyle)); - properties - .add(DiagnosticsProperty('todayTextStyle', todayTextStyle)); - properties.add(DiagnosticsProperty( - 'leadingDatesTextStyle', leadingDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesTextStyle', disabledDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesDecoration', disabledDatesDecoration)); - properties - .add(DiagnosticsProperty('cellDecoration', cellDecoration)); - properties.add(DiagnosticsProperty( - 'todayCellDecoration', todayCellDecoration)); - properties.add(DiagnosticsProperty( - 'leadingDatesDecoration', leadingDatesDecoration)); + properties.add( + DiagnosticsProperty('todayTextStyle', todayTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'leadingDatesTextStyle', + leadingDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesTextStyle', + disabledDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesDecoration', + disabledDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty('cellDecoration', cellDecoration), + ); + properties.add( + DiagnosticsProperty( + 'todayCellDecoration', + todayCellDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'leadingDatesDecoration', + leadingDatesDecoration, + ), + ); } @override int get hashCode { return Object.hash( - textStyle, - todayTextStyle, - leadingDatesTextStyle, - disabledDatesTextStyle, - disabledDatesDecoration, - cellDecoration, - todayCellDecoration, - leadingDatesDecoration); + textStyle, + todayTextStyle, + leadingDatesTextStyle, + disabledDatesTextStyle, + disabledDatesDecoration, + cellDecoration, + todayCellDecoration, + leadingDatesDecoration, + ); } } @@ -1767,41 +1796,42 @@ class DateRangePickerMonthCellStyle with Diagnosticable { /// /// The properties allows to customize the month cells in month view of /// [SfDateRangePicker]. - const DateRangePickerMonthCellStyle( - {@Deprecated('Use selectionColor property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.selectionColor, - @Deprecated('Use startRangeSelectionColor property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.startRangeSelectionColor, - @Deprecated('Use endRangeSelectionColor property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.endRangeSelectionColor, - @Deprecated('Use rangeSelectionColor property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.rangeSelectionColor, - this.textStyle, - this.todayTextStyle, - this.trailingDatesTextStyle, - this.leadingDatesTextStyle, - @Deprecated('Use selectionTextStyle property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.selectionTextStyle, - this.disabledDatesTextStyle, - this.blackoutDateTextStyle, - this.weekendTextStyle, - this.specialDatesTextStyle, - this.specialDatesDecoration, - this.blackoutDatesDecoration, - this.cellDecoration, - this.todayCellDecoration, - this.disabledDatesDecoration, - this.trailingDatesDecoration, - this.leadingDatesDecoration, - @Deprecated('Use rangeTextStyle property in SfDateRangePicker') - // ignore: deprecated_member_use, deprecated_member_use_from_same_package - this.rangeTextStyle, - this.weekendDatesDecoration}); + const DateRangePickerMonthCellStyle({ + @Deprecated('Use selectionColor property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.selectionColor, + @Deprecated('Use startRangeSelectionColor property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.startRangeSelectionColor, + @Deprecated('Use endRangeSelectionColor property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.endRangeSelectionColor, + @Deprecated('Use rangeSelectionColor property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.rangeSelectionColor, + this.textStyle, + this.todayTextStyle, + this.trailingDatesTextStyle, + this.leadingDatesTextStyle, + @Deprecated('Use selectionTextStyle property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.selectionTextStyle, + this.disabledDatesTextStyle, + this.blackoutDateTextStyle, + this.weekendTextStyle, + this.specialDatesTextStyle, + this.specialDatesDecoration, + this.blackoutDatesDecoration, + this.cellDecoration, + this.todayCellDecoration, + this.disabledDatesDecoration, + this.trailingDatesDecoration, + this.leadingDatesDecoration, + @Deprecated('Use rangeTextStyle property in SfDateRangePicker') + // ignore: deprecated_member_use, deprecated_member_use_from_same_package + this.rangeTextStyle, + this.weekendDatesDecoration, + }); /// The text style for the text in the [SfDateRangePicker] month cells. /// @@ -3089,36 +3119,87 @@ class DateRangePickerMonthCellStyle with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('textStyle', textStyle)); - properties - .add(DiagnosticsProperty('todayTextStyle', todayTextStyle)); - properties.add(DiagnosticsProperty( - 'trailingDatesTextStyle', trailingDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'leadingDatesTextStyle', leadingDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'blackoutDateTextStyle', blackoutDateTextStyle)); properties.add( - DiagnosticsProperty('weekendTextStyle', weekendTextStyle)); - properties.add(DiagnosticsProperty( - 'specialDatesTextStyle', specialDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesTextStyle', disabledDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesDecoration', disabledDatesDecoration)); - properties - .add(DiagnosticsProperty('cellDecoration', cellDecoration)); - properties.add(DiagnosticsProperty( - 'todayCellDecoration', todayCellDecoration)); - properties.add(DiagnosticsProperty( - 'trailingDatesDecoration', trailingDatesDecoration)); - properties.add(DiagnosticsProperty( - 'leadingDatesDecoration', leadingDatesDecoration)); - properties.add(DiagnosticsProperty( - 'blackoutDatesDecoration', blackoutDatesDecoration)); - properties.add(DiagnosticsProperty( - 'weekendDatesDecoration', weekendDatesDecoration)); - properties.add(DiagnosticsProperty( - 'specialDatesDecoration', specialDatesDecoration)); + DiagnosticsProperty('todayTextStyle', todayTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'trailingDatesTextStyle', + trailingDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'leadingDatesTextStyle', + leadingDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'blackoutDateTextStyle', + blackoutDateTextStyle, + ), + ); + properties.add( + DiagnosticsProperty('weekendTextStyle', weekendTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'specialDatesTextStyle', + specialDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesTextStyle', + disabledDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesDecoration', + disabledDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty('cellDecoration', cellDecoration), + ); + properties.add( + DiagnosticsProperty( + 'todayCellDecoration', + todayCellDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'trailingDatesDecoration', + trailingDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'leadingDatesDecoration', + leadingDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'blackoutDatesDecoration', + blackoutDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'weekendDatesDecoration', + weekendDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'specialDatesDecoration', + specialDatesDecoration, + ), + ); } @override @@ -3156,7 +3237,8 @@ class DateRangePickerValueChangeNotifier with Diagnosticable { /// /// Listeners can be removed with [removePropertyChangedListener]. void addPropertyChangedListener( - DateRangePickerValueChangedCallback listener) { + DateRangePickerValueChangedCallback listener, + ) { _listeners ??= []; _listeners?.add(listener); } @@ -3170,7 +3252,8 @@ class DateRangePickerValueChangeNotifier with Diagnosticable { /// /// Listeners can be added with [addPropertyChangedListener]. void removePropertyChangedListener( - DateRangePickerValueChangedCallback listener) { + DateRangePickerValueChangedCallback listener, + ) { if (_listeners == null) { return; } @@ -3925,12 +4008,19 @@ class DateRangePickerController extends DateRangePickerValueChangeNotifier { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('displayDate', displayDate)); properties.add(DiagnosticsProperty('selectedDate', selectedDate)); - properties.add(IterableDiagnostics(selectedDates) - .toDiagnosticsNode(name: 'selectedDates')); properties.add( - DiagnosticsProperty('selectedRange', selectedRange)); - properties.add(IterableDiagnostics(selectedRanges) - .toDiagnosticsNode(name: 'selectedRanges')); + IterableDiagnostics( + selectedDates, + ).toDiagnosticsNode(name: 'selectedDates'), + ); + properties.add( + DiagnosticsProperty('selectedRange', selectedRange), + ); + properties.add( + IterableDiagnostics( + selectedRanges, + ).toDiagnosticsNode(name: 'selectedRanges'), + ); properties.add(EnumProperty('view', view)); } } @@ -4006,7 +4096,7 @@ enum DateRangePickerView { /// /// _Note:_ This property not applicable when the /// [SfDateRangePicker.pickerMode] set as [DateRangePickerMode.hijri]. - century + century, } /// The shape for the selection view in [SfDateRangePicker]. @@ -4021,7 +4111,7 @@ enum DateRangePickerSelectionShape { /// - DateRangePickerSelectionShape.rectangle, Draws the date selection in /// rectangle shape. - rectangle + rectangle, } /// A direction in which the [SfDateRangePicker] navigates. @@ -4036,7 +4126,7 @@ enum DateRangePickerNavigationDirection { /// - DateRangePickerNavigationDirection.horizontal, Navigates in right and /// left direction. - horizontal + horizontal, } /// A type specifies how the date picker navigation interaction works. @@ -4073,7 +4163,7 @@ enum DateRangePickerNavigationMode { /// 6. header view background color changed to white on light theme or /// grey[850] on dark theme when [backgroundColor] in /// [DateRangePickerHeaderStyle] is transparent. - scroll + scroll, } /// The direction for extendable range selection in [SfDateRangePicker]. @@ -4092,7 +4182,7 @@ enum ExtendableRangeSelectionDirection { /// Allows to extend the selection only in backward direction. /// The end date will not be changed here. - backward + backward, } /// The dates that visible on the view changes in [SfDateRangePicker]. @@ -4193,8 +4283,11 @@ class PickerDateRange with Diagnosticable { /// See also: /// * [SfDateRangePicker.cellBuilder], which matches this signature. /// * [SfDateRangePicker], which uses this signature in one of it's callback. -typedef DateRangePickerCellBuilder = Widget Function( - BuildContext context, DateRangePickerCellDetails cellDetails); +typedef DateRangePickerCellBuilder = + Widget Function( + BuildContext context, + DateRangePickerCellDetails cellDetails, + ); /// Signature for predicating dates for enabled date selections. /// @@ -4209,8 +4302,11 @@ typedef DateRangePickerSelectableDayPredicate = bool Function(DateTime date); /// * [SfDateRangePicker], which uses this signature in one of it's callback. class DateRangePickerCellDetails { /// Constructor to store the details that needed on calendar cell builder. - DateRangePickerCellDetails( - {required this.date, required this.bounds, required this.visibleDates}); + DateRangePickerCellDetails({ + required this.date, + required this.bounds, + required this.visibleDates, + }); /// Date value associated with the picker cell in month, year, decade and /// century views. @@ -4252,7 +4348,7 @@ class IterableDiagnostics extends DiagnosticableTree { return collection == null ? 'null' : collection!.isNotEmpty - ? '<$T>' - : ''; + ? '<$T>' + : ''; } } diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/hijri_date_picker_manager.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/hijri_date_picker_manager.dart index 02f19627e..5adba3d64 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/hijri_date_picker_manager.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/hijri_date_picker_manager.dart @@ -79,19 +79,19 @@ class HijriDatePickerMonthViewSettings with Diagnosticable { /// /// The properties allows to customize the month view of /// [SfHijriDateRangePicker]. - const HijriDatePickerMonthViewSettings( - {this.firstDayOfWeek = 7, - this.dayFormat = 'EE', - this.viewHeaderHeight = 30, - this.viewHeaderStyle = const DateRangePickerViewHeaderStyle(), - this.enableSwipeSelection = true, - this.blackoutDates, - this.specialDates, - this.showWeekNumber = false, - this.weekNumberStyle = const DateRangePickerWeekNumberStyle(), - this.weekendDays = const [6, 7]}) - : assert(firstDayOfWeek >= 1 && firstDayOfWeek <= 7), - assert(viewHeaderHeight >= -1); + const HijriDatePickerMonthViewSettings({ + this.firstDayOfWeek = 7, + this.dayFormat = 'EE', + this.viewHeaderHeight = 30, + this.viewHeaderStyle = const DateRangePickerViewHeaderStyle(), + this.enableSwipeSelection = true, + this.blackoutDates, + this.specialDates, + this.showWeekNumber = false, + this.weekNumberStyle = const DateRangePickerWeekNumberStyle(), + this.weekendDays = const [6, 7], + }) : assert(firstDayOfWeek >= 1 && firstDayOfWeek <= 7), + assert(viewHeaderHeight >= -1); /// Formats a text in the [SfHijriDateRangePicker] month view view header. /// @@ -490,15 +490,22 @@ class HijriDatePickerMonthViewSettings with Diagnosticable { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(IterableDiagnostics(blackoutDates) - .toDiagnosticsNode(name: 'blackoutDates')); - properties.add(IterableDiagnostics(specialDates) - .toDiagnosticsNode(name: 'specialDates')); + properties.add( + IterableDiagnostics( + blackoutDates, + ).toDiagnosticsNode(name: 'blackoutDates'), + ); + properties.add( + IterableDiagnostics( + specialDates, + ).toDiagnosticsNode(name: 'specialDates'), + ); properties.add(IntProperty('firstDayOfWeek', firstDayOfWeek)); properties.add(DoubleProperty('viewHeaderHeight', viewHeaderHeight)); properties.add(StringProperty('dayFormat', dayFormat)); - properties.add(DiagnosticsProperty( - 'enableSwipeSelection', enableSwipeSelection)); + properties.add( + DiagnosticsProperty('enableSwipeSelection', enableSwipeSelection), + ); properties.add(viewHeaderStyle.toDiagnosticsNode(name: 'viewHeaderStyle')); properties.add(IterableProperty('weekendDays', weekendDays)); properties.add(DiagnosticsProperty('showWeekNumber', showWeekNumber)); @@ -508,19 +515,20 @@ class HijriDatePickerMonthViewSettings with Diagnosticable { @override int get hashCode { return Object.hash( - dayFormat, - firstDayOfWeek, - viewHeaderStyle, - enableSwipeSelection, - viewHeaderHeight, - showWeekNumber, - weekNumberStyle, - - /// Below condition is referred from text style class - /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html - specialDates == null ? null : Object.hashAll(specialDates!), - blackoutDates == null ? null : Object.hashAll(blackoutDates!), - Object.hashAll(weekendDays)); + dayFormat, + firstDayOfWeek, + viewHeaderStyle, + enableSwipeSelection, + viewHeaderHeight, + showWeekNumber, + weekNumberStyle, + + /// Below condition is referred from text style class + /// https://api.flutter.dev/flutter/painting/TextStyle/hashCode.html + specialDates == null ? null : Object.hashAll(specialDates!), + blackoutDates == null ? null : Object.hashAll(blackoutDates!), + Object.hashAll(weekendDays), + ); } } @@ -596,13 +604,14 @@ class HijriDatePickerYearCellStyle with Diagnosticable { /// /// The properties allows to customize the year cells in year view of /// [SfHijriDateRangePicker]. - const HijriDatePickerYearCellStyle( - {this.textStyle, - this.todayTextStyle, - this.disabledDatesTextStyle, - this.cellDecoration, - this.todayCellDecoration, - this.disabledDatesDecoration}); + const HijriDatePickerYearCellStyle({ + this.textStyle, + this.todayTextStyle, + this.disabledDatesTextStyle, + this.cellDecoration, + this.todayCellDecoration, + this.disabledDatesDecoration, + }); /// The text style for the text in the [SfHijriDateRangePicker] year and /// decade view cells. @@ -919,22 +928,42 @@ class HijriDatePickerYearCellStyle with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('textStyle', textStyle)); - properties - .add(DiagnosticsProperty('todayTextStyle', todayTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesTextStyle', disabledDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesDecoration', disabledDatesDecoration)); - properties - .add(DiagnosticsProperty('cellDecoration', cellDecoration)); - properties.add(DiagnosticsProperty( - 'todayCellDecoration', todayCellDecoration)); + properties.add( + DiagnosticsProperty('todayTextStyle', todayTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesTextStyle', + disabledDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesDecoration', + disabledDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty('cellDecoration', cellDecoration), + ); + properties.add( + DiagnosticsProperty( + 'todayCellDecoration', + todayCellDecoration, + ), + ); } @override int get hashCode { - return Object.hash(textStyle, todayTextStyle, disabledDatesTextStyle, - disabledDatesDecoration, cellDecoration, todayCellDecoration); + return Object.hash( + textStyle, + todayTextStyle, + disabledDatesTextStyle, + disabledDatesDecoration, + cellDecoration, + todayCellDecoration, + ); } } @@ -1012,19 +1041,20 @@ class HijriDatePickerMonthCellStyle with Diagnosticable { /// /// The properties allows to customize the month cells in month view of /// [SfHijriDateRangePicker]. - const HijriDatePickerMonthCellStyle( - {this.textStyle, - this.todayTextStyle, - this.disabledDatesTextStyle, - this.blackoutDateTextStyle, - this.weekendTextStyle, - this.specialDatesTextStyle, - this.specialDatesDecoration, - this.blackoutDatesDecoration, - this.cellDecoration, - this.todayCellDecoration, - this.disabledDatesDecoration, - this.weekendDatesDecoration}); + const HijriDatePickerMonthCellStyle({ + this.textStyle, + this.todayTextStyle, + this.disabledDatesTextStyle, + this.blackoutDateTextStyle, + this.weekendTextStyle, + this.specialDatesTextStyle, + this.specialDatesDecoration, + this.blackoutDatesDecoration, + this.cellDecoration, + this.todayCellDecoration, + this.disabledDatesDecoration, + this.weekendDatesDecoration, + }); /// The text style for the text in the [SfHijriDateRangePicker] month cells. /// @@ -1762,28 +1792,63 @@ class HijriDatePickerMonthCellStyle with Diagnosticable { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty('textStyle', textStyle)); - properties - .add(DiagnosticsProperty('todayTextStyle', todayTextStyle)); - properties.add(DiagnosticsProperty( - 'blackoutDateTextStyle', blackoutDateTextStyle)); properties.add( - DiagnosticsProperty('weekendTextStyle', weekendTextStyle)); - properties.add(DiagnosticsProperty( - 'specialDatesTextStyle', specialDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesTextStyle', disabledDatesTextStyle)); - properties.add(DiagnosticsProperty( - 'disabledDatesDecoration', disabledDatesDecoration)); - properties - .add(DiagnosticsProperty('cellDecoration', cellDecoration)); - properties.add(DiagnosticsProperty( - 'todayCellDecoration', todayCellDecoration)); - properties.add(DiagnosticsProperty( - 'blackoutDatesDecoration', blackoutDatesDecoration)); - properties.add(DiagnosticsProperty( - 'weekendDatesDecoration', weekendDatesDecoration)); - properties.add(DiagnosticsProperty( - 'specialDatesDecoration', specialDatesDecoration)); + DiagnosticsProperty('todayTextStyle', todayTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'blackoutDateTextStyle', + blackoutDateTextStyle, + ), + ); + properties.add( + DiagnosticsProperty('weekendTextStyle', weekendTextStyle), + ); + properties.add( + DiagnosticsProperty( + 'specialDatesTextStyle', + specialDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesTextStyle', + disabledDatesTextStyle, + ), + ); + properties.add( + DiagnosticsProperty( + 'disabledDatesDecoration', + disabledDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty('cellDecoration', cellDecoration), + ); + properties.add( + DiagnosticsProperty( + 'todayCellDecoration', + todayCellDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'blackoutDatesDecoration', + blackoutDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'weekendDatesDecoration', + weekendDatesDecoration, + ), + ); + properties.add( + DiagnosticsProperty( + 'specialDatesDecoration', + specialDatesDecoration, + ), + ); } @override @@ -2521,16 +2586,25 @@ class HijriDatePickerController extends DateRangePickerValueChangeNotifier { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(DiagnosticsProperty('displayDate', displayDate)); - properties - .add(DiagnosticsProperty('selectedDate', selectedDate)); - properties.add(IterableDiagnostics(selectedDates) - .toDiagnosticsNode(name: 'selectedDates')); properties.add( - DiagnosticsProperty('selectedRange', selectedRange)); - properties.add(IterableDiagnostics(selectedRanges) - .toDiagnosticsNode(name: 'selectedRanges')); + DiagnosticsProperty('displayDate', displayDate), + ); + properties.add( + DiagnosticsProperty('selectedDate', selectedDate), + ); + properties.add( + IterableDiagnostics( + selectedDates, + ).toDiagnosticsNode(name: 'selectedDates'), + ); + properties.add( + DiagnosticsProperty('selectedRange', selectedRange), + ); + properties.add( + IterableDiagnostics( + selectedRanges, + ).toDiagnosticsNode(name: 'selectedRanges'), + ); properties.add(EnumProperty('view', view)); } } @@ -2620,15 +2694,18 @@ class HijriDateRange with Diagnosticable { /// * [SfHijriDateRangePicker.cellBuilder], which matches this signature. /// * [SfHijriDateRangePicker], which uses this signature in one of it's /// callback. -typedef HijriDateRangePickerCellBuilder = Widget Function( - BuildContext context, HijriDateRangePickerCellDetails cellDetails); +typedef HijriDateRangePickerCellBuilder = + Widget Function( + BuildContext context, + HijriDateRangePickerCellDetails cellDetails, + ); /// Signature for predicating dates for enabled date selections. /// /// [SelectableDayPredicate] parameter used to specify allowable days in the /// SfHijriDateRangePicker. -typedef HijriDatePickerSelectableDayPredicate = bool Function( - HijriDateTime date); +typedef HijriDatePickerSelectableDayPredicate = + bool Function(HijriDateTime date); /// Contains the details that needed on calendar cell builder. /// @@ -2638,8 +2715,11 @@ typedef HijriDatePickerSelectableDayPredicate = bool Function( /// callback. class HijriDateRangePickerCellDetails { /// Constructor to store the details that needed on calendar cell builder. - HijriDateRangePickerCellDetails( - {required this.date, required this.bounds, required this.visibleDates}); + HijriDateRangePickerCellDetails({ + required this.date, + required this.bounds, + required this.visibleDates, + }); /// Date value associated with the picker cell in month, year, decade and /// century views. diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/month_view.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/month_view.dart index 92298ebf8..c0d28b95e 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/month_view.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/month_view.dart @@ -13,46 +13,47 @@ class MonthView extends StatefulWidget { /// Constructor for create the month view widget used to hold the month cell /// widgets. const MonthView( - this.visibleDates, - this.rowCount, - this.cellStyle, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.datePickerTheme, - this.isRtl, - this.todayHighlightColor, - this.minDate, - this.maxDate, - this.enablePastDates, - this.showLeadingAndTailingDates, - this.blackoutDates, - this.specialDates, - this.weekendDays, - this.selectionShape, - this.selectionRadius, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionNotifier, - this.textScaleFactor, - this.selectionMode, - this.isHijri, - this.localizations, - this.navigationDirection, - this.width, - this.height, - this.getPickerStateDetails, - this.cellBuilder, - this.showWeekNumber, - this.weekNumberStyle, - this.isMobilePlatform, - this.disableDatesCollection, - this.extendableRangeSelectionDirection, - {super.key}); + this.visibleDates, + this.rowCount, + this.cellStyle, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.datePickerTheme, + this.isRtl, + this.todayHighlightColor, + this.minDate, + this.maxDate, + this.enablePastDates, + this.showLeadingAndTailingDates, + this.blackoutDates, + this.specialDates, + this.weekendDays, + this.selectionShape, + this.selectionRadius, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionNotifier, + this.textScaleFactor, + this.selectionMode, + this.isHijri, + this.localizations, + this.navigationDirection, + this.width, + this.height, + this.getPickerStateDetails, + this.cellBuilder, + this.showWeekNumber, + this.weekNumberStyle, + this.isMobilePlatform, + this.disableDatesCollection, + this.extendableRangeSelectionDirection, { + super.key, + }); /// Defines the month row count. final int rowCount; @@ -191,11 +192,13 @@ class _MonthViewState extends State { _pickerStateDetails = PickerStateArgs(); widget.getPickerStateDetails(_pickerStateDetails); _selectedDate = _pickerStateDetails.selectedDate; - _selectedDates = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedDates, + ); _selectedRange = _pickerStateDetails.selectedRange; - _selectedRanges = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedRanges, + ); widget.selectionNotifier.addListener(_updateSelection); super.initState(); } @@ -212,9 +215,13 @@ class _MonthViewState extends State { widget.multiViewSpacing != oldWidget.multiViewSpacing || widget.enableMultiView != oldWidget.enableMultiView || !DateRangePickerHelper.isDateCollectionEquals( - widget.blackoutDates, oldWidget.blackoutDates) || + widget.blackoutDates, + oldWidget.blackoutDates, + ) || !DateRangePickerHelper.isDateCollectionEquals( - widget.specialDates, oldWidget.specialDates) || + widget.specialDates, + oldWidget.specialDates, + ) || widget.showLeadingAndTailingDates != oldWidget.showLeadingAndTailingDates || widget.rowCount != oldWidget.rowCount || @@ -247,16 +254,21 @@ class _MonthViewState extends State { @override Widget build(BuildContext context) { weekNumberPanelWidth = DateRangePickerHelper.getWeekNumberPanelWidth( - widget.showWeekNumber, widget.width, widget.isMobilePlatform); + widget.showWeekNumber, + widget.width, + widget.isMobilePlatform, + ); if (widget.cellBuilder != null && _children.isEmpty) { double webUIPadding = 0; double width = widget.width - weekNumberPanelWidth; double height = widget.height; int viewCount = 1; - final bool isHorizontalMultiView = widget.enableMultiView && + final bool isHorizontalMultiView = + widget.enableMultiView && widget.navigationDirection == DateRangePickerNavigationDirection.horizontal; - final bool isVerticalMultiView = widget.enableMultiView && + final bool isVerticalMultiView = + widget.enableMultiView && widget.navigationDirection == DateRangePickerNavigationDirection.vertical; @@ -275,39 +287,48 @@ class _MonthViewState extends State { final double cellHeight = height / widget.rowCount; final bool hideLeadingAndTrailingDates = (widget.rowCount == 6 && !widget.showLeadingAndTailingDates) || - widget.isHijri; + widget.isHijri; for (int j = 0; j < viewCount; j++) { final int currentViewIndex = widget.isRtl ? DateRangePickerHelper.getRtlIndex(viewCount, j) : j; final int viewStartIndex = j * datesCount; - final int currentMonth = widget - .visibleDates[(viewStartIndex + (datesCount / 2)).truncate()] - .month as int; - - double viewStartPosition = isVerticalMultiView - ? weekNumberPanelWidth - : (currentViewIndex * width) + - (currentViewIndex * widget.multiViewSpacing) + - (weekNumberPanelWidth * (viewStartIndex + 1)); + final int currentMonth = + widget + .visibleDates[(viewStartIndex + (datesCount / 2)) + .truncate()] + .month + as int; + + double viewStartPosition = + isVerticalMultiView + ? weekNumberPanelWidth + : (currentViewIndex * width) + + (currentViewIndex * widget.multiViewSpacing) + + (weekNumberPanelWidth * (viewStartIndex + 1)); if (widget.isRtl) { - viewStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * currentViewIndex); + viewStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * currentViewIndex); } final double viewEndPosition = viewStartPosition + width; double xPosition = viewStartPosition; - double yPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + - (currentViewIndex * widget.multiViewSpacing); + double yPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + + (currentViewIndex * widget.multiViewSpacing); for (int i = 0; i < datesCount; i++) { int currentIndex = i; if (widget.isRtl) { final int rowIndex = i ~/ DateTime.daysPerWeek; - currentIndex = DateRangePickerHelper.getRtlIndex( - DateTime.daysPerWeek, i % DateTime.daysPerWeek) + + currentIndex = + DateRangePickerHelper.getRtlIndex( + DateTime.daysPerWeek, + i % DateTime.daysPerWeek, + ) + (rowIndex * DateTime.daysPerWeek); } @@ -330,19 +351,33 @@ class _MonthViewState extends State { continue; } - final Widget child = widget.cellBuilder( - context, - widget.isHijri - ? HijriDateRangePickerCellDetails( - date: date, - visibleDates: widget.visibleDates.cast(), - bounds: Rect.fromLTWH( - xPosition, yPosition, cellWidth, cellHeight)) - : DateRangePickerCellDetails( - date: date, - visibleDates: widget.visibleDates.cast(), - bounds: Rect.fromLTWH(xPosition, yPosition, cellWidth, - cellHeight))) as Widget; + final Widget child = + widget.cellBuilder( + context, + widget.isHijri + ? HijriDateRangePickerCellDetails( + date: date, + visibleDates: + widget.visibleDates.cast(), + bounds: Rect.fromLTWH( + xPosition, + yPosition, + cellWidth, + cellHeight, + ), + ) + : DateRangePickerCellDetails( + date: date, + visibleDates: widget.visibleDates.cast(), + bounds: Rect.fromLTWH( + xPosition, + yPosition, + cellWidth, + cellHeight, + ), + ), + ) + as Widget; _children.add(child); xPosition += cellWidth; } @@ -360,11 +395,13 @@ class _MonthViewState extends State { _children.clear(); _selectedDate = _pickerStateDetails.selectedDate; - _selectedDates = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedDates, + ); _selectedRange = _pickerStateDetails.selectedRange; - _selectedRanges = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedRanges, + ); if (!isNeedSetState) { return; @@ -385,18 +422,24 @@ class _MonthViewState extends State { case DateRangePickerSelectionMode.multiple: { return DateRangePickerHelper.isDateCollectionEquals( - _selectedDates, _pickerStateDetails.selectedDates); + _selectedDates, + _pickerStateDetails.selectedDates, + ); } case DateRangePickerSelectionMode.range: case DateRangePickerSelectionMode.extendableRange: { return DateRangePickerHelper.isRangeEquals( - _selectedRange, _pickerStateDetails.selectedRange); + _selectedRange, + _pickerStateDetails.selectedRange, + ); } case DateRangePickerSelectionMode.multiRange: { return DateRangePickerHelper.isDateRangesEquals( - _selectedRanges, _pickerStateDetails.selectedRanges); + _selectedRanges, + _pickerStateDetails.selectedRanges, + ); } } } @@ -406,87 +449,130 @@ class _MonthViewState extends State { case DateRangePickerSelectionMode.single: { return _MonthViewSingleSelectionRenderWidget( - widget.visibleDates, - widget.rowCount, - widget.cellStyle, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.datePickerTheme, - widget.isRtl, - widget.todayHighlightColor, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.showLeadingAndTailingDates, - widget.blackoutDates, - widget.specialDates, - widget.weekendDays, - widget.selectionShape, - widget.selectionRadius, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionNotifier, - widget.textScaleFactor, - widget.height, - widget.width, - _selectedDate, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.isMobilePlatform, - widget.weekNumberStyle, - weekNumberPanelWidth, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.rowCount, + widget.cellStyle, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.datePickerTheme, + widget.isRtl, + widget.todayHighlightColor, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.showLeadingAndTailingDates, + widget.blackoutDates, + widget.specialDates, + widget.weekendDays, + widget.selectionShape, + widget.selectionRadius, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionNotifier, + widget.textScaleFactor, + widget.height, + widget.width, + _selectedDate, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.isMobilePlatform, + widget.weekNumberStyle, + weekNumberPanelWidth, + widget.disableDatesCollection, + widgets: _children, + ); } case DateRangePickerSelectionMode.multiple: { return _MonthViewMultiSelectionRenderWidget( - widget.visibleDates, - widget.rowCount, - widget.cellStyle, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.datePickerTheme, - widget.isRtl, - widget.todayHighlightColor, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.showLeadingAndTailingDates, - widget.blackoutDates, - widget.specialDates, - widget.weekendDays, - widget.selectionShape, - widget.selectionRadius, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionNotifier, - widget.textScaleFactor, - widget.height, - widget.width, - _selectedDates, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.isMobilePlatform, - widget.weekNumberStyle, - weekNumberPanelWidth, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.rowCount, + widget.cellStyle, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.datePickerTheme, + widget.isRtl, + widget.todayHighlightColor, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.showLeadingAndTailingDates, + widget.blackoutDates, + widget.specialDates, + widget.weekendDays, + widget.selectionShape, + widget.selectionRadius, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionNotifier, + widget.textScaleFactor, + widget.height, + widget.width, + _selectedDates, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.isMobilePlatform, + widget.weekNumberStyle, + weekNumberPanelWidth, + widget.disableDatesCollection, + widgets: _children, + ); } case DateRangePickerSelectionMode.range: return _MonthViewRangeSelectionRenderWidget( + widget.visibleDates, + widget.rowCount, + widget.cellStyle, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.datePickerTheme, + widget.isRtl, + widget.todayHighlightColor, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.showLeadingAndTailingDates, + widget.blackoutDates, + widget.specialDates, + widget.weekendDays, + widget.selectionShape, + widget.selectionRadius, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionNotifier, + widget.textScaleFactor, + widget.height, + widget.width, + _selectedRange, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.isMobilePlatform, + widget.weekNumberStyle, + weekNumberPanelWidth, + widget.disableDatesCollection, + widgets: _children, + ); + case DateRangePickerSelectionMode.extendableRange: + { + return _MonthViewExtendableRangeSelectionRenderWidget( widget.visibleDates, widget.rowCount, widget.cellStyle, @@ -523,89 +609,51 @@ class _MonthViewState extends State { widget.weekNumberStyle, weekNumberPanelWidth, widget.disableDatesCollection, - widgets: _children); - case DateRangePickerSelectionMode.extendableRange: - { - return _MonthViewExtendableRangeSelectionRenderWidget( - widget.visibleDates, - widget.rowCount, - widget.cellStyle, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.datePickerTheme, - widget.isRtl, - widget.todayHighlightColor, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.showLeadingAndTailingDates, - widget.blackoutDates, - widget.specialDates, - widget.weekendDays, - widget.selectionShape, - widget.selectionRadius, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionNotifier, - widget.textScaleFactor, - widget.height, - widget.width, - _selectedRange, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.isMobilePlatform, - widget.weekNumberStyle, - weekNumberPanelWidth, - widget.disableDatesCollection, - widget.extendableRangeSelectionDirection, - widgets: _children); + widget.extendableRangeSelectionDirection, + widgets: _children, + ); } case DateRangePickerSelectionMode.multiRange: { return _MonthViewMultiRangeSelectionRenderWidget( - widget.visibleDates, - widget.rowCount, - widget.cellStyle, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.datePickerTheme, - widget.isRtl, - widget.todayHighlightColor, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.showLeadingAndTailingDates, - widget.blackoutDates, - widget.specialDates, - widget.weekendDays, - widget.selectionShape, - widget.selectionRadius, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionNotifier, - widget.textScaleFactor, - widget.height, - widget.width, - _selectedRanges, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.isMobilePlatform, - widget.weekNumberStyle, - weekNumberPanelWidth, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.rowCount, + widget.cellStyle, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.datePickerTheme, + widget.isRtl, + widget.todayHighlightColor, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.showLeadingAndTailingDates, + widget.blackoutDates, + widget.specialDates, + widget.weekendDays, + widget.selectionShape, + widget.selectionRadius, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionNotifier, + widget.textScaleFactor, + widget.height, + widget.width, + _selectedRanges, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.isMobilePlatform, + widget.weekNumberStyle, + weekNumberPanelWidth, + widget.disableDatesCollection, + widgets: _children, + ); } } } @@ -614,44 +662,44 @@ class _MonthViewState extends State { class _MonthViewSingleSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MonthViewSingleSelectionRenderWidget( - this.visibleDates, - this.rowCount, - this.cellStyle, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.datePickerTheme, - this.isRtl, - this.todayHighlightColor, - this.minDate, - this.maxDate, - this.enablePastDates, - this.showLeadingAndTailingDates, - this.blackoutDates, - this.specialDates, - this.weekendDays, - this.selectionShape, - this.selectionRadius, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionNotifier, - this.textScaleFactor, - this.height, - this.width, - this.selectedDate, - this.isHijri, - this.localizations, - this.navigationDirection, - this.isMobilePlatform, - this.weekNumberStyle, - this.weekNumberPanelWidth, - this.disableDatesCollection, - {List widgets = const []}) - : super(children: widgets); + this.visibleDates, + this.rowCount, + this.cellStyle, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.datePickerTheme, + this.isRtl, + this.todayHighlightColor, + this.minDate, + this.maxDate, + this.enablePastDates, + this.showLeadingAndTailingDates, + this.blackoutDates, + this.specialDates, + this.weekendDays, + this.selectionShape, + this.selectionRadius, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionNotifier, + this.textScaleFactor, + this.height, + this.width, + this.selectedDate, + this.isHijri, + this.localizations, + this.navigationDirection, + this.isMobilePlatform, + this.weekNumberStyle, + this.weekNumberPanelWidth, + this.disableDatesCollection, { + List widgets = const [], + }) : super(children: widgets); final DateRangePickerWeekNumberStyle weekNumberStyle; @@ -727,49 +775,53 @@ class _MonthViewSingleSelectionRenderWidget @override _MonthViewSingleSelectionRenderObject createRenderObject( - BuildContext context) { + BuildContext context, + ) { return _MonthViewSingleSelectionRenderObject( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - selectedDate, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + selectedDate, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); } @override - void updateRenderObject(BuildContext context, - _MonthViewSingleSelectionRenderObject renderObject) { + void updateRenderObject( + BuildContext context, + _MonthViewSingleSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..rowCount = rowCount @@ -813,44 +865,44 @@ class _MonthViewSingleSelectionRenderWidget class _MonthViewMultiSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MonthViewMultiSelectionRenderWidget( - this.visibleDates, - this.rowCount, - this.cellStyle, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.datePickerTheme, - this.isRtl, - this.todayHighlightColor, - this.minDate, - this.maxDate, - this.enablePastDates, - this.showLeadingAndTailingDates, - this.blackoutDates, - this.specialDates, - this.weekendDays, - this.selectionShape, - this.selectionRadius, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionNotifier, - this.textScaleFactor, - this.height, - this.width, - this.selectedDates, - this.isHijri, - this.localizations, - this.navigationDirection, - this.isMobilePlatform, - this.weekNumberStyle, - this.weekNumberPanelWidth, - this.disableDatesCollection, - {List widgets = const []}) - : super(children: widgets); + this.visibleDates, + this.rowCount, + this.cellStyle, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.datePickerTheme, + this.isRtl, + this.todayHighlightColor, + this.minDate, + this.maxDate, + this.enablePastDates, + this.showLeadingAndTailingDates, + this.blackoutDates, + this.specialDates, + this.weekendDays, + this.selectionShape, + this.selectionRadius, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionNotifier, + this.textScaleFactor, + this.height, + this.width, + this.selectedDates, + this.isHijri, + this.localizations, + this.navigationDirection, + this.isMobilePlatform, + this.weekNumberStyle, + this.weekNumberPanelWidth, + this.disableDatesCollection, { + List widgets = const [], + }) : super(children: widgets); final DateRangePickerWeekNumberStyle weekNumberStyle; final int rowCount; @@ -925,49 +977,53 @@ class _MonthViewMultiSelectionRenderWidget @override _MonthViewMultiSelectionRenderObject createRenderObject( - BuildContext context) { + BuildContext context, + ) { return _MonthViewMultiSelectionRenderObject( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - selectedDates, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + selectedDates, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); } @override void updateRenderObject( - BuildContext context, _MonthViewMultiSelectionRenderObject renderObject) { + BuildContext context, + _MonthViewMultiSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..rowCount = rowCount @@ -1011,44 +1067,44 @@ class _MonthViewMultiSelectionRenderWidget class _MonthViewRangeSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MonthViewRangeSelectionRenderWidget( - this.visibleDates, - this.rowCount, - this.cellStyle, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.datePickerTheme, - this.isRtl, - this.todayHighlightColor, - this.minDate, - this.maxDate, - this.enablePastDates, - this.showLeadingAndTailingDates, - this.blackoutDates, - this.specialDates, - this.weekendDays, - this.selectionShape, - this.selectionRadius, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionNotifier, - this.textScaleFactor, - this.height, - this.width, - this.selectedRange, - this.isHijri, - this.localizations, - this.navigationDirection, - this.isMobilePlatform, - this.weekNumberStyle, - this.weekNumberPanelWidth, - this.disableDatesCollection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.rowCount, + this.cellStyle, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.datePickerTheme, + this.isRtl, + this.todayHighlightColor, + this.minDate, + this.maxDate, + this.enablePastDates, + this.showLeadingAndTailingDates, + this.blackoutDates, + this.specialDates, + this.weekendDays, + this.selectionShape, + this.selectionRadius, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionNotifier, + this.textScaleFactor, + this.height, + this.width, + this.selectedRange, + this.isHijri, + this.localizations, + this.navigationDirection, + this.isMobilePlatform, + this.weekNumberStyle, + this.weekNumberPanelWidth, + this.disableDatesCollection, { + required List widgets, + }) : super(children: widgets); final DateRangePickerWeekNumberStyle weekNumberStyle; @@ -1124,49 +1180,53 @@ class _MonthViewRangeSelectionRenderWidget @override _MonthViewRangeSelectionRenderObject createRenderObject( - BuildContext context) { + BuildContext context, + ) { return _MonthViewRangeSelectionRenderObject( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - selectedRange, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + selectedRange, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); } @override void updateRenderObject( - BuildContext context, _MonthViewRangeSelectionRenderObject renderObject) { + BuildContext context, + _MonthViewRangeSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..rowCount = rowCount @@ -1210,45 +1270,45 @@ class _MonthViewRangeSelectionRenderWidget class _MonthViewExtendableRangeSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MonthViewExtendableRangeSelectionRenderWidget( - this.visibleDates, - this.rowCount, - this.cellStyle, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.datePickerTheme, - this.isRtl, - this.todayHighlightColor, - this.minDate, - this.maxDate, - this.enablePastDates, - this.showLeadingAndTailingDates, - this.blackoutDates, - this.specialDates, - this.weekendDays, - this.selectionShape, - this.selectionRadius, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionNotifier, - this.textScaleFactor, - this.height, - this.width, - this.selectedRange, - this.isHijri, - this.localizations, - this.navigationDirection, - this.isMobilePlatform, - this.weekNumberStyle, - this.weekNumberPanelWidth, - this.disableDatesCollection, - this.extendableRangeSelectionDirection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.rowCount, + this.cellStyle, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.datePickerTheme, + this.isRtl, + this.todayHighlightColor, + this.minDate, + this.maxDate, + this.enablePastDates, + this.showLeadingAndTailingDates, + this.blackoutDates, + this.specialDates, + this.weekendDays, + this.selectionShape, + this.selectionRadius, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionNotifier, + this.textScaleFactor, + this.height, + this.width, + this.selectedRange, + this.isHijri, + this.localizations, + this.navigationDirection, + this.isMobilePlatform, + this.weekNumberStyle, + this.weekNumberPanelWidth, + this.disableDatesCollection, + this.extendableRangeSelectionDirection, { + required List widgets, + }) : super(children: widgets); final int rowCount; @@ -1326,50 +1386,54 @@ class _MonthViewExtendableRangeSelectionRenderWidget @override _MonthViewExtendableRangeSelectionRenderObject createRenderObject( - BuildContext context) { + BuildContext context, + ) { return _MonthViewExtendableRangeSelectionRenderObject( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - selectedRange, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection, - extendableRangeSelectionDirection); + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + selectedRange, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + extendableRangeSelectionDirection, + ); } @override - void updateRenderObject(BuildContext context, - _MonthViewExtendableRangeSelectionRenderObject renderObject) { + void updateRenderObject( + BuildContext context, + _MonthViewExtendableRangeSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..rowCount = rowCount @@ -1414,44 +1478,44 @@ class _MonthViewExtendableRangeSelectionRenderWidget class _MonthViewMultiRangeSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MonthViewMultiRangeSelectionRenderWidget( - this.visibleDates, - this.rowCount, - this.cellStyle, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.datePickerTheme, - this.isRtl, - this.todayHighlightColor, - this.minDate, - this.maxDate, - this.enablePastDates, - this.showLeadingAndTailingDates, - this.blackoutDates, - this.specialDates, - this.weekendDays, - this.selectionShape, - this.selectionRadius, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionNotifier, - this.textScaleFactor, - this.height, - this.width, - this.selectedRanges, - this.isHijri, - this.localizations, - this.navigationDirection, - this.isMobilePlatform, - this.weekNumberStyle, - this.weekNumberPanelWidth, - this.disableDatesCollection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.rowCount, + this.cellStyle, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.datePickerTheme, + this.isRtl, + this.todayHighlightColor, + this.minDate, + this.maxDate, + this.enablePastDates, + this.showLeadingAndTailingDates, + this.blackoutDates, + this.specialDates, + this.weekendDays, + this.selectionShape, + this.selectionRadius, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionNotifier, + this.textScaleFactor, + this.height, + this.width, + this.selectedRanges, + this.isHijri, + this.localizations, + this.navigationDirection, + this.isMobilePlatform, + this.weekNumberStyle, + this.weekNumberPanelWidth, + this.disableDatesCollection, { + required List widgets, + }) : super(children: widgets); final DateRangePickerWeekNumberStyle weekNumberStyle; @@ -1519,57 +1583,61 @@ class _MonthViewMultiRangeSelectionRenderWidget final SfLocalizations localizations; - final DateRangePickerNavigationDirection navigationDirection; - - final double weekNumberPanelWidth; - - final List? disableDatesCollection; - - @override - _MonthViewMultiRangeSelectionRenderObject createRenderObject( - BuildContext context) { - return _MonthViewMultiRangeSelectionRenderObject( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - selectedRanges, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + final DateRangePickerNavigationDirection navigationDirection; + + final double weekNumberPanelWidth; + + final List? disableDatesCollection; + + @override + _MonthViewMultiRangeSelectionRenderObject createRenderObject( + BuildContext context, + ) { + return _MonthViewMultiRangeSelectionRenderObject( + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + selectedRanges, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); } @override - void updateRenderObject(BuildContext context, - _MonthViewMultiRangeSelectionRenderObject renderObject) { + void updateRenderObject( + BuildContext context, + _MonthViewMultiRangeSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..rowCount = rowCount @@ -1615,41 +1683,42 @@ class _DatePickerParentData extends ContainerBoxParentData {} abstract class _IMonthView extends RenderBox with ContainerRenderObjectMixin { _IMonthView( - this._visibleDates, - this._rowCount, - this._cellStyle, - this._selectionTextStyle, - this._rangeTextStyle, - this._selectionColor, - this._startRangeSelectionColor, - this._endRangeSelectionColor, - this._rangeSelectionColor, - this._datePickerTheme, - this._isRtl, - this._todayHighlightColor, - this._minDate, - this._maxDate, - this._enablePastDates, - this._showLeadingAndTailingDates, - this._blackoutDates, - this._specialDates, - this._weekendDays, - this._selectionShape, - this._selectionRadius, - this._mouseHoverPosition, - this._enableMultiView, - this._multiViewSpacing, - this.selectionNotifier, - this._textScaleFactor, - this._height, - this._width, - this._isHijri, - this._navigationDirection, - this.localizations, - this.isMobilePlatform, - this._weekNumberStyle, - this._weekNumberPanelWidth, - this._disableDatesCollection); + this._visibleDates, + this._rowCount, + this._cellStyle, + this._selectionTextStyle, + this._rangeTextStyle, + this._selectionColor, + this._startRangeSelectionColor, + this._endRangeSelectionColor, + this._rangeSelectionColor, + this._datePickerTheme, + this._isRtl, + this._todayHighlightColor, + this._minDate, + this._maxDate, + this._enablePastDates, + this._showLeadingAndTailingDates, + this._blackoutDates, + this._specialDates, + this._weekendDays, + this._selectionShape, + this._selectionRadius, + this._mouseHoverPosition, + this._enableMultiView, + this._multiViewSpacing, + this.selectionNotifier, + this._textScaleFactor, + this._height, + this._width, + this._isHijri, + this._navigationDirection, + this.localizations, + this.isMobilePlatform, + this._weekNumberStyle, + this._weekNumberPanelWidth, + this._disableDatesCollection, + ); bool isMobilePlatform; @@ -2219,8 +2288,9 @@ abstract class _IMonthView extends RenderBox /// Used to draw month cell text in month view. final TextPainter _textPainter = TextPainter( - textDirection: TextDirection.ltr, - textWidthBasis: TextWidthBasis.longestLine); + textDirection: TextDirection.ltr, + textWidthBasis: TextWidthBasis.longestLine, + ); static const int _selectionPadding = 2; @@ -2259,8 +2329,10 @@ abstract class _IMonthView extends RenderBox @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; if (child == null) { return; @@ -2281,11 +2353,14 @@ abstract class _IMonthView extends RenderBox final double cellWidth = currentWidth / DateTime.daysPerWeek; final double cellHeight = currentHeight / rowCount; while (child != null) { - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: cellHeight, maxHeight: cellHeight, minWidth: cellWidth, - maxWidth: cellWidth)); + maxWidth: cellWidth, + ), + ); child = childAfter(child); } } @@ -2303,8 +2378,14 @@ abstract class _IMonthView extends RenderBox /// Draw the highlight for selected month cell based on it selection mode /// value(date, dates, range, ranges). - TextStyle drawSelection(Canvas canvas, double x, double y, int index, - TextStyle selectionTextStyle, TextStyle selectionRangeTextStyle); + TextStyle drawSelection( + Canvas canvas, + double x, + double y, + int index, + TextStyle selectionTextStyle, + TextStyle selectionRangeTextStyle, + ); /// Draw the highlight for selected month cell based on it selection mode /// value(date, dates, range, ranges) when the month cell have custom widget. @@ -2330,9 +2411,10 @@ abstract class _IMonthView extends RenderBox final List semanticsNodes = []; for (int i = 0; i < semantics.length; i++) { final CustomPainterSemantics currentSemantics = semantics[i]; - final SemanticsNode newChild = _cacheNodes!.isNotEmpty - ? _cacheNodes!.removeAt(0) - : SemanticsNode(key: currentSemantics.key); + final SemanticsNode newChild = + _cacheNodes!.isNotEmpty + ? _cacheNodes!.removeAt(0) + : SemanticsNode(key: currentSemantics.key); final SemanticsProperties properties = currentSemantics.properties; final SemanticsConfiguration config = SemanticsConfiguration(); @@ -2384,9 +2466,11 @@ abstract class _IMonthView extends RenderBox double width = size.width - weekNumberPanelWidth; double height = size.height; int viewCount = 1; - final bool isHorizontalMultiView = _enableMultiView && + final bool isHorizontalMultiView = + _enableMultiView && _navigationDirection == DateRangePickerNavigationDirection.horizontal; - final bool isVerticalMultiView = _enableMultiView && + final bool isVerticalMultiView = + _enableMultiView && _navigationDirection == DateRangePickerNavigationDirection.vertical; if (isHorizontalMultiView) { @@ -2406,28 +2490,32 @@ abstract class _IMonthView extends RenderBox for (int j = 0; j < viewCount; j++) { final int currentViewIndex = _isRtl ? DateRangePickerHelper.getRtlIndex(viewCount, j) : j; - left = _isRtl - ? width - cellWidth - weekNumberPanelWidth - : weekNumberPanelWidth; + left = + _isRtl + ? width - cellWidth - weekNumberPanelWidth + : weekNumberPanelWidth; top = 0; final dynamic middleDate = _visibleDates[(j * datesCount) + (datesCount ~/ 2)]; - double viewXStartPosition = isVerticalMultiView - ? weekNumberPanelWidth - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * (currentViewIndex + 1)); + double viewXStartPosition = + isVerticalMultiView + ? weekNumberPanelWidth + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * (currentViewIndex + 1)); if (isRtl) { - viewXStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * currentViewIndex); + viewXStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * currentViewIndex); } - final double viewYStartPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + - (currentViewIndex * _multiViewSpacing); + final double viewYStartPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + + (currentViewIndex * _multiViewSpacing); for (int i = 0; i < datesCount; i++) { final dynamic currentDate = _visibleDates[(j * datesCount) + i]; @@ -2437,71 +2525,139 @@ abstract class _IMonthView extends RenderBox double xPosition = _isRtl ? (size.width - left - cellWidth) : 0; if (isHorizontalMultiView || isVerticalMultiView) { xPosition = isRtl ? size.width - weekNumberPanelWidth : 0; - xPosition = isHorizontalMultiView - ? viewXStartPosition - weekNumberPanelWidth - : xPosition; + xPosition = + isHorizontalMultiView + ? viewXStartPosition - weekNumberPanelWidth + : xPosition; } - final int weekNumber = - DateRangePickerHelper.getWeekNumberOfYear(currentDate, isHijri); - semanticsBuilder.add(CustomPainterSemantics( + final int weekNumber = DateRangePickerHelper.getWeekNumberOfYear( + currentDate, + isHijri, + ); + semanticsBuilder.add( + CustomPainterSemantics( rect: Rect.fromLTWH( - xPosition, top, weekNumberPanelWidth, cellHeight), + xPosition, + top, + weekNumberPanelWidth, + cellHeight, + ), properties: SemanticsProperties( label: 'week$weekNumber', textDirection: TextDirection.ltr, - ))); + ), + ), + ); } - if (!DateRangePickerHelper.isDateAsCurrentMonthDate(middleDate, - _rowCount, _showLeadingAndTailingDates, currentDate, _isHijri)) { + if (!DateRangePickerHelper.isDateAsCurrentMonthDate( + middleDate, + _rowCount, + _showLeadingAndTailingDates, + currentDate, + _isHijri, + )) { leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - _isRtl, left, top, cellWidth, cellHeight, width); + _isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; continue; } else if (DateRangePickerHelper.isDateWithInVisibleDates( - _visibleDates, _blackoutDates, currentDate)) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(viewXStartPosition + left, - viewYStartPosition + top, cellWidth, cellHeight), - properties: SemanticsProperties( - label: '${_getSemanticMonthLabel(currentDate)}, Blackout date', - textDirection: TextDirection.ltr, + _visibleDates, + _blackoutDates, + currentDate, + )) { + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + viewXStartPosition + left, + viewYStartPosition + top, + cellWidth, + cellHeight, + ), + properties: SemanticsProperties( + label: '${_getSemanticMonthLabel(currentDate)}, Blackout date', + textDirection: TextDirection.ltr, + ), ), - )); + ); leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - _isRtl, left, top, cellWidth, cellHeight, width); + _isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; continue; } else if (!DateRangePickerHelper.isEnabledDate( - _minDate, _maxDate, _enablePastDates, currentDate, _isHijri) || + _minDate, + _maxDate, + _enablePastDates, + currentDate, + _isHijri, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - visibleDates, disableDatesCollection, currentDate)) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(viewXStartPosition + left, - viewYStartPosition + top, cellWidth, cellHeight), - properties: SemanticsProperties( - label: '${_getSemanticMonthLabel(currentDate)}, Disabled date', - textDirection: TextDirection.ltr, + visibleDates, + disableDatesCollection, + currentDate, + )) { + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + viewXStartPosition + left, + viewYStartPosition + top, + cellWidth, + cellHeight, + ), + properties: SemanticsProperties( + label: '${_getSemanticMonthLabel(currentDate)}, Disabled date', + textDirection: TextDirection.ltr, + ), ), - )); + ); leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - _isRtl, left, top, cellWidth, cellHeight, width); + _isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; continue; } - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(viewXStartPosition + left, - viewYStartPosition + top, cellWidth, cellHeight), - properties: SemanticsProperties( - label: _getSemanticMonthLabel(currentDate), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + viewXStartPosition + left, + viewYStartPosition + top, + cellWidth, + cellHeight, + ), + properties: SemanticsProperties( + label: _getSemanticMonthLabel(currentDate), + textDirection: TextDirection.ltr, + ), ), - )); + ); leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - _isRtl, left, top, cellWidth, cellHeight, width); + _isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; } @@ -2524,78 +2680,79 @@ abstract class _IMonthView extends RenderBox class _MonthViewSingleSelectionRenderObject extends _IMonthView { _MonthViewSingleSelectionRenderObject( - List visibleDates, - int rowCount, - dynamic cellStyle, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - SfDateRangePickerThemeData datePickerTheme, - bool isRtl, - Color? todayHighlightColor, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - bool showLeadingAndTailingDates, - List? blackoutDates, - List? specialDates, - List weekendDays, - DateRangePickerSelectionShape selectionShape, - double selectionRadius, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - ValueNotifier selectionNotifier, - double textScaleFactor, - double height, - double width, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedDate, - bool isMobilePlatform, - DateRangePickerWeekNumberStyle weekNumberStyle, - double weekNumberPanelWidth, - List? disableDatesCollection) - : super( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + List visibleDates, + int rowCount, + dynamic cellStyle, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + SfDateRangePickerThemeData datePickerTheme, + bool isRtl, + Color? todayHighlightColor, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + bool showLeadingAndTailingDates, + List? blackoutDates, + List? specialDates, + List weekendDays, + DateRangePickerSelectionShape selectionShape, + double selectionRadius, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + ValueNotifier selectionNotifier, + double textScaleFactor, + double height, + double width, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedDate, + bool isMobilePlatform, + DateRangePickerWeekNumberStyle weekNumberStyle, + double weekNumberPanelWidth, + List? disableDatesCollection, + ) : super( + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); dynamic _selectedDate; @@ -2624,7 +2781,7 @@ class _MonthViewSingleSelectionRenderObject extends _IMonthView { { _cellWidth = (size.width - _multiViewSpacing - (weekNumberPanelWidth * 2)) / - (DateTime.daysPerWeek * 2); + (DateTime.daysPerWeek * 2); } break; case DateRangePickerNavigationDirection.vertical: @@ -2640,22 +2797,42 @@ class _MonthViewSingleSelectionRenderObject extends _IMonthView { } @override - TextStyle drawSelection(Canvas canvas, double x, double y, int index, - TextStyle selectionTextStyle, TextStyle selectionRangeTextStyle) { + TextStyle drawSelection( + Canvas canvas, + double x, + double y, + int index, + TextStyle selectionTextStyle, + TextStyle selectionRangeTextStyle, + ) { _selectionPainter.isAntiAlias = true; switch (selectionShape) { case DateRangePickerSelectionShape.circle: { final double radius = _getCellRadius( - selectionRadius, _centerXPosition, _centerYPosition); - _drawCircleSelection(canvas, x + _centerXPosition, - y + _centerYPosition, radius, _selectionPainter); + selectionRadius, + _centerXPosition, + _centerYPosition, + ); + _drawCircleSelection( + canvas, + x + _centerXPosition, + y + _centerYPosition, + radius, + _selectionPainter, + ); } break; case DateRangePickerSelectionShape.rectangle: { _drawFillSelection( - canvas, x, y, _cellWidth, _cellHeight, _selectionPainter); + canvas, + x, + y, + _cellWidth, + _cellHeight, + _selectionPainter, + ); } } @@ -2668,18 +2845,26 @@ class _MonthViewSingleSelectionRenderObject extends _IMonthView { _selectionPainter.strokeWidth = 0.0; _selectionPainter.style = PaintingStyle.fill; _selectionPainter.isAntiAlias = true; - canvas.drawRect(Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), - _selectionPainter); + canvas.drawRect( + Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), + _selectionPainter, + ); } @override List getSelectedIndexValues(int viewStartIndex, int viewEndIndex) { final List selectedIndex = []; if (selectedDate != null) { - if (isDateWithInDateRange(visibleDates[viewStartIndex], - visibleDates[viewEndIndex], selectedDate)) { - final int index = _getSelectedIndex(selectedDate, visibleDates, - viewStartIndex: viewStartIndex); + if (isDateWithInDateRange( + visibleDates[viewStartIndex], + visibleDates[viewEndIndex], + selectedDate, + )) { + final int index = _getSelectedIndex( + selectedDate, + visibleDates, + viewStartIndex: viewStartIndex, + ); selectedIndex.add(index); } } @@ -2705,78 +2890,79 @@ class _MonthViewSingleSelectionRenderObject extends _IMonthView { class _MonthViewMultiSelectionRenderObject extends _IMonthView { _MonthViewMultiSelectionRenderObject( - List visibleDates, - int rowCount, - dynamic cellStyle, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - SfDateRangePickerThemeData datePickerTheme, - bool isRtl, - Color? todayHighlightColor, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - bool showLeadingAndTailingDates, - List? blackoutDates, - List? specialDates, - List weekendDays, - DateRangePickerSelectionShape selectionShape, - double selectionRadius, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - ValueNotifier selectionNotifier, - double textScaleFactor, - double height, - double width, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedDates, - bool isMobilePlatform, - DateRangePickerWeekNumberStyle weekNumberStyle, - double weekNumberPanelWidth, - List? disableDatesCollection) - : super( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + List visibleDates, + int rowCount, + dynamic cellStyle, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + SfDateRangePickerThemeData datePickerTheme, + bool isRtl, + Color? todayHighlightColor, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + bool showLeadingAndTailingDates, + List? blackoutDates, + List? specialDates, + List weekendDays, + DateRangePickerSelectionShape selectionShape, + double selectionRadius, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + ValueNotifier selectionNotifier, + double textScaleFactor, + double height, + double width, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedDates, + bool isMobilePlatform, + DateRangePickerWeekNumberStyle weekNumberStyle, + double weekNumberPanelWidth, + List? disableDatesCollection, + ) : super( + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); List? _selectedDates; @@ -2796,22 +2982,42 @@ class _MonthViewMultiSelectionRenderObject extends _IMonthView { } @override - TextStyle drawSelection(Canvas canvas, double x, double y, int index, - TextStyle selectionTextStyle, TextStyle selectionRangeTextStyle) { + TextStyle drawSelection( + Canvas canvas, + double x, + double y, + int index, + TextStyle selectionTextStyle, + TextStyle selectionRangeTextStyle, + ) { _selectionPainter.isAntiAlias = true; switch (selectionShape) { case DateRangePickerSelectionShape.circle: { final double radius = _getCellRadius( - selectionRadius, _centerXPosition, _centerYPosition); - _drawCircleSelection(canvas, x + _centerXPosition, - y + _centerYPosition, radius, _selectionPainter); + selectionRadius, + _centerXPosition, + _centerYPosition, + ); + _drawCircleSelection( + canvas, + x + _centerXPosition, + y + _centerYPosition, + radius, + _selectionPainter, + ); } break; case DateRangePickerSelectionShape.rectangle: { _drawFillSelection( - canvas, x, y, _cellWidth, _cellHeight, _selectionPainter); + canvas, + x, + y, + _cellWidth, + _cellHeight, + _selectionPainter, + ); } } @@ -2824,8 +3030,10 @@ class _MonthViewMultiSelectionRenderObject extends _IMonthView { _selectionPainter.strokeWidth = 0.0; _selectionPainter.style = PaintingStyle.fill; _selectionPainter.isAntiAlias = true; - canvas.drawRect(Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), - _selectionPainter); + canvas.drawRect( + Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), + _selectionPainter, + ); } @override @@ -2835,12 +3043,16 @@ class _MonthViewMultiSelectionRenderObject extends _IMonthView { for (int j = 0; j < selectedDates!.length; j++) { final dynamic date = selectedDates![j]; if (!isDateWithInDateRange( - visibleDates[viewStartIndex], visibleDates[viewEndIndex], date)) { + visibleDates[viewStartIndex], + visibleDates[viewEndIndex], + date, + )) { continue; } - selectedIndex.add(_getSelectedIndex(date, visibleDates, - viewStartIndex: viewStartIndex)); + selectedIndex.add( + _getSelectedIndex(date, visibleDates, viewStartIndex: viewStartIndex), + ); } } @@ -2857,7 +3069,7 @@ class _MonthViewMultiSelectionRenderObject extends _IMonthView { { _cellWidth = (size.width - _multiViewSpacing - (weekNumberPanelWidth * 2)) / - (DateTime.daysPerWeek * 2); + (DateTime.daysPerWeek * 2); } break; case DateRangePickerNavigationDirection.vertical: @@ -2875,7 +3087,9 @@ class _MonthViewMultiSelectionRenderObject extends _IMonthView { @override void updateSelection(PickerStateArgs details) { if (DateRangePickerHelper.isDateCollectionEquals( - details.selectedDates, selectedDates)) { + details.selectedDates, + selectedDates, + )) { return; } @@ -2891,78 +3105,79 @@ class _MonthViewMultiSelectionRenderObject extends _IMonthView { class _MonthViewRangeSelectionRenderObject extends _IMonthView { _MonthViewRangeSelectionRenderObject( - List visibleDates, - int rowCount, - dynamic cellStyle, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - SfDateRangePickerThemeData datePickerTheme, - bool isRtl, - Color? todayHighlightColor, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - bool showLeadingAndTailingDates, - List? blackoutDates, - List? specialDates, - List weekendDays, - DateRangePickerSelectionShape selectionShape, - double selectionRadius, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - ValueNotifier selectionNotifier, - double textScaleFactor, - double height, - double width, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedRange, - bool isMobilePlatform, - DateRangePickerWeekNumberStyle weekNumberStyle, - double weekNumberPanelWidth, - List? disableDatesCollection) - : super( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + List visibleDates, + int rowCount, + dynamic cellStyle, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + SfDateRangePickerThemeData datePickerTheme, + bool isRtl, + Color? todayHighlightColor, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + bool showLeadingAndTailingDates, + List? blackoutDates, + List? specialDates, + List weekendDays, + DateRangePickerSelectionShape selectionShape, + double selectionRadius, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + ValueNotifier selectionNotifier, + double textScaleFactor, + double height, + double width, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedRange, + bool isMobilePlatform, + DateRangePickerWeekNumberStyle weekNumberStyle, + double weekNumberPanelWidth, + List? disableDatesCollection, + ) : super( + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); dynamic _selectedRange; @@ -2984,55 +3199,84 @@ class _MonthViewRangeSelectionRenderObject extends _IMonthView { List _selectedIndex = []; @override - TextStyle drawSelection(Canvas canvas, double x, double y, int index, - TextStyle selectionTextStyle, TextStyle selectionRangeTextStyle) { + TextStyle drawSelection( + Canvas canvas, + double x, + double y, + int index, + TextStyle selectionTextStyle, + TextStyle selectionRangeTextStyle, + ) { final List selectionDetails = _getSelectedRangePosition(index); final bool isSelectedDate = selectionDetails[0]; final bool isStartRange = selectionDetails[1]; final bool isEndRange = selectionDetails[2]; final bool isBetweenRange = selectionDetails[3]; - final double radius = - _getCellRadius(selectionRadius, _centerXPosition, _centerYPosition); + final double radius = _getCellRadius( + selectionRadius, + _centerXPosition, + _centerYPosition, + ); final double heightDifference = _cellHeight / 2 - radius; if (isSelectedDate) { - _drawSelectedDate(canvas, radius, _centerXPosition, _cellWidth, - _cellHeight, x, y, this, _centerYPosition); + _drawSelectedDate( + canvas, + radius, + _centerXPosition, + _cellWidth, + _cellHeight, + x, + y, + this, + _centerYPosition, + ); } else if (isStartRange) { _selectionPainter.color = rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; _drawStartAndEndRange( - canvas, - this, - _cellHeight, - _cellWidth, - radius, - _centerXPosition, - _centerYPosition, - x, - y, - startRangeSelectionColor ?? datePickerTheme.startRangeSelectionColor!, - heightDifference, - isStartRange); + canvas, + this, + _cellHeight, + _cellWidth, + radius, + _centerXPosition, + _centerYPosition, + x, + y, + startRangeSelectionColor ?? datePickerTheme.startRangeSelectionColor!, + heightDifference, + isStartRange, + ); } else if (isEndRange) { _selectionPainter.color = rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; _drawStartAndEndRange( - canvas, - this, - _cellHeight, - _cellWidth, - radius, - _centerXPosition, - _centerYPosition, - x, - y, - endRangeSelectionColor ?? datePickerTheme.endRangeSelectionColor!, - heightDifference, - isStartRange); + canvas, + this, + _cellHeight, + _cellWidth, + radius, + _centerXPosition, + _centerYPosition, + x, + y, + endRangeSelectionColor ?? datePickerTheme.endRangeSelectionColor!, + heightDifference, + isStartRange, + ); } else if (isBetweenRange) { - return _drawBetweenSelection(canvas, this, _cellWidth, _cellHeight, - radius, x, y, heightDifference, selectionRangeTextStyle); + return _drawBetweenSelection( + canvas, + this, + _cellWidth, + _cellHeight, + radius, + x, + y, + heightDifference, + selectionRangeTextStyle, + ); } return selectionTextStyle; @@ -3062,8 +3306,10 @@ class _MonthViewRangeSelectionRenderObject extends _IMonthView { rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; } - canvas.drawRect(Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), - _selectionPainter); + canvas.drawRect( + Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), + _selectionPainter, + ); } List _getSelectedRangePosition(int index) { @@ -3113,8 +3359,13 @@ class _MonthViewRangeSelectionRenderObject extends _IMonthView { final dynamic startDate = selectedRange.startDate; final dynamic endDate = selectedRange.endDate ?? selectedRange.startDate; _selectedIndex = _getSelectedRangeIndex( - startDate, endDate, visibleDates, isHijri, - monthStartIndex: viewStartIndex, monthEndIndex: viewEndIndex); + startDate, + endDate, + visibleDates, + isHijri, + monthStartIndex: viewStartIndex, + monthEndIndex: viewEndIndex, + ); } return _selectedIndex; @@ -3130,7 +3381,7 @@ class _MonthViewRangeSelectionRenderObject extends _IMonthView { { _cellWidth = (size.width - _multiViewSpacing - (weekNumberPanelWidth * 2)) / - (DateTime.daysPerWeek * 2); + (DateTime.daysPerWeek * 2); } break; case DateRangePickerNavigationDirection.vertical: @@ -3148,7 +3399,9 @@ class _MonthViewRangeSelectionRenderObject extends _IMonthView { @override void updateSelection(PickerStateArgs details) { if (DateRangePickerHelper.isRangeEquals( - details.selectedRange, selectedRange)) { + details.selectedRange, + selectedRange, + )) { return; } @@ -3169,79 +3422,80 @@ class _MonthViewRangeSelectionRenderObject extends _IMonthView { class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { _MonthViewExtendableRangeSelectionRenderObject( - List visibleDates, - int rowCount, - dynamic cellStyle, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - SfDateRangePickerThemeData datePickerTheme, - bool isRtl, - Color? todayHighlightColor, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - bool showLeadingAndTailingDates, - List? blackoutDates, - List? specialDates, - List weekendDays, - DateRangePickerSelectionShape selectionShape, - double selectionRadius, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - ValueNotifier selectionNotifier, - double textScaleFactor, - double height, - double width, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedRange, - bool isMobilePlatform, - DateRangePickerWeekNumberStyle weekNumberStyle, - double weekNumberPanelWidth, - List? disableDatesCollection, - this._extendableRangeSelectionDirection) - : super( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + List visibleDates, + int rowCount, + dynamic cellStyle, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + SfDateRangePickerThemeData datePickerTheme, + bool isRtl, + Color? todayHighlightColor, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + bool showLeadingAndTailingDates, + List? blackoutDates, + List? specialDates, + List weekendDays, + DateRangePickerSelectionShape selectionShape, + double selectionRadius, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + ValueNotifier selectionNotifier, + double textScaleFactor, + double height, + double width, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedRange, + bool isMobilePlatform, + DateRangePickerWeekNumberStyle weekNumberStyle, + double weekNumberPanelWidth, + List? disableDatesCollection, + this._extendableRangeSelectionDirection, + ) : super( + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); dynamic _selectedRange; @@ -3266,7 +3520,8 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { _extendableRangeSelectionDirection; set extendableRangeSelectionDirection( - ExtendableRangeSelectionDirection value) { + ExtendableRangeSelectionDirection value, + ) { if (_extendableRangeSelectionDirection == value) { return; } @@ -3282,56 +3537,87 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { List _selectedIndex = []; @override - TextStyle drawSelection(Canvas canvas, double x, double y, int index, - TextStyle selectionTextStyle, TextStyle selectionRangeTextStyle) { - final List selectionDetails = - _getSelectedRangePosition(index, _selectedIndex); + TextStyle drawSelection( + Canvas canvas, + double x, + double y, + int index, + TextStyle selectionTextStyle, + TextStyle selectionRangeTextStyle, + ) { + final List selectionDetails = _getSelectedRangePosition( + index, + _selectedIndex, + ); final bool isSelectedDate = selectionDetails[0]; final bool isStartRange = selectionDetails[1]; final bool isEndRange = selectionDetails[2]; final bool isBetweenRange = selectionDetails[3]; - final double radius = - _getCellRadius(selectionRadius, _centerXPosition, _centerYPosition); + final double radius = _getCellRadius( + selectionRadius, + _centerXPosition, + _centerYPosition, + ); final double heightDifference = _cellHeight / 2 - radius; if (isSelectedDate) { - _drawSelectedDate(canvas, radius, _centerXPosition, _cellWidth, - _cellHeight, x, y, this, _centerYPosition); + _drawSelectedDate( + canvas, + radius, + _centerXPosition, + _cellWidth, + _cellHeight, + x, + y, + this, + _centerYPosition, + ); } else if (isStartRange) { _selectionPainter.color = rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; _drawStartAndEndRange( - canvas, - this, - _cellHeight, - _cellWidth, - radius, - _centerXPosition, - _centerYPosition, - x, - y, - startRangeSelectionColor ?? datePickerTheme.startRangeSelectionColor!, - heightDifference, - isStartRange); + canvas, + this, + _cellHeight, + _cellWidth, + radius, + _centerXPosition, + _centerYPosition, + x, + y, + startRangeSelectionColor ?? datePickerTheme.startRangeSelectionColor!, + heightDifference, + isStartRange, + ); } else if (isEndRange) { _selectionPainter.color = rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; _drawStartAndEndRange( - canvas, - this, - _cellHeight, - _cellWidth, - radius, - _centerXPosition, - _centerYPosition, - x, - y, - endRangeSelectionColor ?? datePickerTheme.endRangeSelectionColor!, - heightDifference, - isStartRange); + canvas, + this, + _cellHeight, + _cellWidth, + radius, + _centerXPosition, + _centerYPosition, + x, + y, + endRangeSelectionColor ?? datePickerTheme.endRangeSelectionColor!, + heightDifference, + isStartRange, + ); } else if (isBetweenRange) { - return _drawBetweenSelection(canvas, this, _cellWidth, _cellHeight, - radius, x, y, heightDifference, selectionRangeTextStyle); + return _drawBetweenSelection( + canvas, + this, + _cellWidth, + _cellHeight, + radius, + x, + y, + heightDifference, + selectionRangeTextStyle, + ); } return selectionTextStyle; @@ -3342,8 +3628,10 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { _selectionPainter.strokeWidth = 0.0; _selectionPainter.style = PaintingStyle.fill; _selectionPainter.isAntiAlias = true; - final List selectionDetails = - _getSelectedRangePosition(index, _selectedIndex); + final List selectionDetails = _getSelectedRangePosition( + index, + _selectedIndex, + ); final bool isSelectedDate = selectionDetails[0]; final bool isStartRange = selectionDetails[1]; final bool isEndRange = selectionDetails[2]; @@ -3362,8 +3650,10 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; } - canvas.drawRect(Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), - _selectionPainter); + canvas.drawRect( + Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), + _selectionPainter, + ); } List _getSelectedRangePosition(int index, List indexList) { @@ -3413,8 +3703,13 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { final dynamic startDate = selectedRange.startDate; final dynamic endDate = selectedRange.endDate ?? selectedRange.startDate; _selectedIndex = _getSelectedRangeIndex( - startDate, endDate, visibleDates, isHijri, - monthStartIndex: viewStartIndex, monthEndIndex: viewEndIndex); + startDate, + endDate, + visibleDates, + isHijri, + monthStartIndex: viewStartIndex, + monthEndIndex: viewEndIndex, + ); } return _selectedIndex; @@ -3430,7 +3725,7 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { { _cellWidth = (size.width - _multiViewSpacing - (weekNumberPanelWidth * 2)) / - (DateTime.daysPerWeek * 2); + (DateTime.daysPerWeek * 2); } break; case DateRangePickerNavigationDirection.vertical: @@ -3448,7 +3743,9 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { @override void updateSelection(PickerStateArgs details) { if (DateRangePickerHelper.isRangeEquals( - details.selectedRange, selectedRange)) { + details.selectedRange, + selectedRange, + )) { return; } @@ -3462,86 +3759,89 @@ class _MonthViewExtendableRangeSelectionRenderObject extends _IMonthView { /// index is either it is start or end range or selected date and is between /// range as a list, in this list the isBetweenRange boolean index is 3, /// hence we used 3 here. - final List selectionDetails = - _getSelectedRangePosition(index, _selectedIndex); + final List selectionDetails = _getSelectedRangePosition( + index, + _selectedIndex, + ); return selectionDetails[3]; } } class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { _MonthViewMultiRangeSelectionRenderObject( - List visibleDates, - int rowCount, - dynamic cellStyle, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - SfDateRangePickerThemeData datePickerTheme, - bool isRtl, - Color? todayHighlightColor, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - bool showLeadingAndTailingDates, - List? blackoutDates, - List? specialDates, - List weekendDays, - DateRangePickerSelectionShape selectionShape, - double selectionRadius, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - ValueNotifier selectionNotifier, - double textScaleFactor, - double height, - double width, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedRanges, - bool isMobilePlatform, - DateRangePickerWeekNumberStyle weekNumberStyle, - double weekNumberPanelWidth, - List? disableDatesCollection) - : super( - visibleDates, - rowCount, - cellStyle, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - datePickerTheme, - isRtl, - todayHighlightColor, - minDate, - maxDate, - enablePastDates, - showLeadingAndTailingDates, - blackoutDates, - specialDates, - weekendDays, - selectionShape, - selectionRadius, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionNotifier, - textScaleFactor, - height, - width, - isHijri, - navigationDirection, - localizations, - isMobilePlatform, - weekNumberStyle, - weekNumberPanelWidth, - disableDatesCollection); + List visibleDates, + int rowCount, + dynamic cellStyle, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + SfDateRangePickerThemeData datePickerTheme, + bool isRtl, + Color? todayHighlightColor, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + bool showLeadingAndTailingDates, + List? blackoutDates, + List? specialDates, + List weekendDays, + DateRangePickerSelectionShape selectionShape, + double selectionRadius, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + ValueNotifier selectionNotifier, + double textScaleFactor, + double height, + double width, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedRanges, + bool isMobilePlatform, + DateRangePickerWeekNumberStyle weekNumberStyle, + double weekNumberPanelWidth, + List? disableDatesCollection, + ) : super( + visibleDates, + rowCount, + cellStyle, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + datePickerTheme, + isRtl, + todayHighlightColor, + minDate, + maxDate, + enablePastDates, + showLeadingAndTailingDates, + blackoutDates, + specialDates, + weekendDays, + selectionShape, + selectionRadius, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionNotifier, + textScaleFactor, + height, + width, + isHijri, + navigationDirection, + localizations, + isMobilePlatform, + weekNumberStyle, + weekNumberPanelWidth, + disableDatesCollection, + ); List? _selectedRanges; @@ -3563,55 +3863,84 @@ class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { List> _selectedRangesIndex = >[]; @override - TextStyle drawSelection(Canvas canvas, double x, double y, int index, - TextStyle selectionTextStyle, TextStyle selectionRangeTextStyle) { + TextStyle drawSelection( + Canvas canvas, + double x, + double y, + int index, + TextStyle selectionTextStyle, + TextStyle selectionRangeTextStyle, + ) { final List selectionDetails = _getSelectedRangePosition(index); final bool isSelectedDate = selectionDetails[0]; final bool isStartRange = selectionDetails[1]; final bool isEndRange = selectionDetails[2]; final bool isBetweenRange = selectionDetails[3]; - final double radius = - _getCellRadius(selectionRadius, _centerXPosition, _centerYPosition); + final double radius = _getCellRadius( + selectionRadius, + _centerXPosition, + _centerYPosition, + ); final double heightDifference = _cellHeight / 2 - radius; if (isSelectedDate) { - _drawSelectedDate(canvas, radius, _centerXPosition, _cellWidth, - _cellHeight, x, y, this, _centerYPosition); + _drawSelectedDate( + canvas, + radius, + _centerXPosition, + _cellWidth, + _cellHeight, + x, + y, + this, + _centerYPosition, + ); } else if (isStartRange) { _selectionPainter.color = rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; _drawStartAndEndRange( - canvas, - this, - _cellHeight, - _cellWidth, - radius, - _centerXPosition, - _centerYPosition, - x, - y, - startRangeSelectionColor ?? datePickerTheme.startRangeSelectionColor!, - heightDifference, - isStartRange); + canvas, + this, + _cellHeight, + _cellWidth, + radius, + _centerXPosition, + _centerYPosition, + x, + y, + startRangeSelectionColor ?? datePickerTheme.startRangeSelectionColor!, + heightDifference, + isStartRange, + ); } else if (isEndRange) { _selectionPainter.color = rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; _drawStartAndEndRange( - canvas, - this, - _cellHeight, - _cellWidth, - radius, - _centerXPosition, - _centerYPosition, - x, - y, - endRangeSelectionColor ?? datePickerTheme.endRangeSelectionColor!, - heightDifference, - isStartRange); + canvas, + this, + _cellHeight, + _cellWidth, + radius, + _centerXPosition, + _centerYPosition, + x, + y, + endRangeSelectionColor ?? datePickerTheme.endRangeSelectionColor!, + heightDifference, + isStartRange, + ); } else if (isBetweenRange) { - return _drawBetweenSelection(canvas, this, _cellWidth, _cellHeight, - radius, x, y, heightDifference, selectionRangeTextStyle); + return _drawBetweenSelection( + canvas, + this, + _cellWidth, + _cellHeight, + radius, + x, + y, + heightDifference, + selectionRangeTextStyle, + ); } return selectionTextStyle; @@ -3641,8 +3970,10 @@ class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { rangeSelectionColor ?? datePickerTheme.rangeSelectionColor!; } - canvas.drawRect(Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), - _selectionPainter); + canvas.drawRect( + Rect.fromLTRB(x, y, x + _cellWidth, y + _cellHeight), + _selectionPainter, + ); } List _getSelectedRangePosition(int index) { @@ -3704,8 +4035,13 @@ class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { final dynamic startDate = range.startDate; final dynamic endDate = range.endDate ?? range.startDate; final List rangeIndex = _getSelectedRangeIndex( - startDate, endDate, visibleDates, isHijri, - monthStartIndex: viewStartIndex, monthEndIndex: viewEndIndex); + startDate, + endDate, + visibleDates, + isHijri, + monthStartIndex: viewStartIndex, + monthEndIndex: viewEndIndex, + ); for (int i = 0; i < rangeIndex.length; i++) { selectedIndex.add(rangeIndex[i]); } @@ -3727,7 +4063,7 @@ class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { { _cellWidth = (size.width - _multiViewSpacing - (weekNumberPanelWidth * 2)) / - (DateTime.daysPerWeek * 2); + (DateTime.daysPerWeek * 2); } break; case DateRangePickerNavigationDirection.vertical: @@ -3745,7 +4081,9 @@ class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { @override void updateSelection(PickerStateArgs details) { if (DateRangePickerHelper.isDateRangesEquals( - details.selectedRanges, selectedRanges)) { + details.selectedRanges, + selectedRanges, + )) { return; } @@ -3765,60 +4103,89 @@ class _MonthViewMultiRangeSelectionRenderObject extends _IMonthView { } void _drawSelectedDate( - Canvas canvas, - double radius, - double centerXPosition, - double cellWidth, - double cellHeight, - double x, - double y, - _IMonthView view, - double centerYPosition) { + Canvas canvas, + double radius, + double centerXPosition, + double cellWidth, + double cellHeight, + double x, + double y, + _IMonthView view, + double centerYPosition, +) { view._selectionPainter.isAntiAlias = true; - view._selectionPainter.color = view.startRangeSelectionColor ?? + view._selectionPainter.color = + view.startRangeSelectionColor ?? view.datePickerTheme.startRangeSelectionColor!; switch (view.selectionShape) { case DateRangePickerSelectionShape.circle: { - _drawCircleSelection(canvas, x + centerXPosition, y + centerYPosition, - radius, view._selectionPainter); + _drawCircleSelection( + canvas, + x + centerXPosition, + y + centerYPosition, + radius, + view._selectionPainter, + ); } break; case DateRangePickerSelectionShape.rectangle: { _drawFillSelection( - canvas, x, y, cellWidth, cellHeight, view._selectionPainter); + canvas, + x, + y, + cellWidth, + cellHeight, + view._selectionPainter, + ); } } } void _drawStartAndEndRange( - Canvas canvas, - _IMonthView view, - double cellHeight, - double cellWidth, - double radius, - double centerXPosition, - double centerYPosition, - double x, - double y, - Color color, - double heightDifference, - bool isStartRange) { + Canvas canvas, + _IMonthView view, + double cellHeight, + double cellWidth, + double radius, + double centerXPosition, + double centerYPosition, + double x, + double y, + Color color, + double heightDifference, + bool isStartRange, +) { switch (view.selectionShape) { case DateRangePickerSelectionShape.circle: { Rect rect; if (isStartRange) { - rect = Rect.fromLTRB(x + centerXPosition, y + heightDifference, - x + cellWidth, y + cellHeight - heightDifference); + rect = Rect.fromLTRB( + x + centerXPosition, + y + heightDifference, + x + cellWidth, + y + cellHeight - heightDifference, + ); } else { - rect = Rect.fromLTRB(x, y + heightDifference, x + centerXPosition, - y + cellHeight - heightDifference); + rect = Rect.fromLTRB( + x, + y + heightDifference, + x + centerXPosition, + y + cellHeight - heightDifference, + ); } - _drawStartEndRangeCircleSelection(canvas, x + centerXPosition, - y + centerYPosition, radius, rect, view._selectionPainter, color); + _drawStartEndRangeCircleSelection( + canvas, + x + centerXPosition, + y + centerYPosition, + radius, + rect, + view._selectionPainter, + color, + ); } break; case DateRangePickerSelectionShape.rectangle: @@ -3827,25 +4194,38 @@ void _drawStartAndEndRange( view._selectionPainter.color = color; if (isStartRange) { _drawStartRangeFillSelection( - canvas, x, y, cellWidth, cellHeight, view._selectionPainter); + canvas, + x, + y, + cellWidth, + cellHeight, + view._selectionPainter, + ); } else { _drawEndRangeFillSelection( - canvas, x, y, cellWidth, cellHeight, view._selectionPainter); + canvas, + x, + y, + cellWidth, + cellHeight, + view._selectionPainter, + ); } } } } TextStyle _drawBetweenSelection( - Canvas canvas, - _IMonthView view, - double cellWidth, - double cellHeight, - double radius, - double x, - double y, - double heightDifference, - TextStyle selectionRangeTextStyle) { + Canvas canvas, + _IMonthView view, + double cellWidth, + double cellHeight, + double radius, + double x, + double y, + double heightDifference, + TextStyle selectionRangeTextStyle, +) { switch (view.selectionShape) { case DateRangePickerSelectionShape.rectangle: heightDifference = 1; @@ -3856,16 +4236,26 @@ TextStyle _drawBetweenSelection( view._selectionPainter.color = view.rangeSelectionColor ?? view.datePickerTheme.rangeSelectionColor!; - _drawRectRangeSelection(canvas, x, y + heightDifference, x + cellWidth, - y + cellHeight - heightDifference, view._selectionPainter); + _drawRectRangeSelection( + canvas, + x, + y + heightDifference, + x + cellWidth, + y + cellHeight - heightDifference, + view._selectionPainter, + ); return selectionRangeTextStyle; } double _getCellRadius( - double selectionRadius, double maxXRadius, double maxYRadius) { - final double radius = maxXRadius > maxYRadius - ? maxYRadius - _IMonthView._selectionPadding - : maxXRadius - _IMonthView._selectionPadding; + double selectionRadius, + double maxXRadius, + double maxYRadius, +) { + final double radius = + maxXRadius > maxYRadius + ? maxYRadius - _IMonthView._selectionPadding + : maxXRadius - _IMonthView._selectionPadding; if (selectionRadius == -1) { return radius; @@ -3874,9 +4264,14 @@ double _getCellRadius( return radius > selectionRadius ? selectionRadius : radius; } -List _getSelectedRangeIndex(dynamic startDate, dynamic endDate, - List visibleDates, bool isHijri, - {int monthStartIndex = -1, int monthEndIndex = -1}) { +List _getSelectedRangeIndex( + dynamic startDate, + dynamic endDate, + List visibleDates, + bool isHijri, { + int monthStartIndex = -1, + int monthEndIndex = -1, +}) { int startIndex = -1; int endIndex = -1; final List selectedIndex = []; @@ -3887,7 +4282,11 @@ List _getSelectedRangeIndex(dynamic startDate, dynamic endDate, dynamic endRangeDate; if (endDate != null) { endRangeDate = DateRangePickerHelper.getDate( - endDate.year, endDate.month, endDate.day, isHijri); + endDate.year, + endDate.month, + endDate.day, + isHijri, + ); } if (startDate != null && startDate.isAfter(endRangeDate) == true) { final dynamic temp = startDate; @@ -3897,16 +4296,20 @@ List _getSelectedRangeIndex(dynamic startDate, dynamic endDate, final dynamic viewStartDate = monthStartIndex != -1 ? visibleDates[monthStartIndex] : visibleDates[0]; - final dynamic viewEndDate = monthEndIndex != -1 - ? visibleDates[monthEndIndex] - : visibleDates[visibleDates.length - 1]; + final dynamic viewEndDate = + monthEndIndex != -1 + ? visibleDates[monthEndIndex] + : visibleDates[visibleDates.length - 1]; if (startDate != null) { if (viewStartDate.isAfter(startDate) == true && viewStartDate.isBefore(endRangeDate) == true) { startIndex = -1; } else { - startIndex = _getSelectedIndex(startDate, visibleDates, - viewStartIndex: monthStartIndex); + startIndex = _getSelectedIndex( + startDate, + visibleDates, + viewStartIndex: monthStartIndex, + ); } } @@ -3915,8 +4318,11 @@ List _getSelectedRangeIndex(dynamic startDate, dynamic endDate, viewEndDate.isBefore(endRangeDate) == true) { endIndex = visibleDates.length; } else { - endIndex = _getSelectedIndex(endRangeDate, visibleDates, - viewStartIndex: monthStartIndex); + endIndex = _getSelectedIndex( + endRangeDate, + visibleDates, + viewStartIndex: monthStartIndex, + ); } } @@ -3938,8 +4344,11 @@ List _getSelectedRangeIndex(dynamic startDate, dynamic endDate, return selectedIndex; } -int _getSelectedIndex(dynamic date, List visibleDates, - {int viewStartIndex = 0}) { +int _getSelectedIndex( + dynamic date, + List visibleDates, { + int viewStartIndex = 0, +}) { if (viewStartIndex == -1) { viewStartIndex = 0; } @@ -3954,62 +4363,111 @@ int _getSelectedIndex(dynamic date, List visibleDates, } void _drawCircleSelection( - Canvas canvas, double x, double y, double radius, Paint selectionPainter) { + Canvas canvas, + double x, + double y, + double radius, + Paint selectionPainter, +) { canvas.drawCircle(Offset(x, y), radius, selectionPainter); } -void _drawFillSelection(Canvas canvas, double x, double y, double width, - double height, Paint selectionPainter) { +void _drawFillSelection( + Canvas canvas, + double x, + double y, + double width, + double height, + Paint selectionPainter, +) { const double padding = 1; canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB(x + padding, y + padding, x + width - padding, - y + height - padding), - Radius.circular(height / 4 > 10 ? 10 : height / 4)), - selectionPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + x + padding, + y + padding, + x + width - padding, + y + height - padding, + ), + Radius.circular(height / 4 > 10 ? 10 : height / 4), + ), + selectionPainter, + ); } -void _drawStartRangeFillSelection(Canvas canvas, double x, double y, - double width, double height, Paint selectionPainter) { +void _drawStartRangeFillSelection( + Canvas canvas, + double x, + double y, + double width, + double height, + Paint selectionPainter, +) { const double padding = 1; final double cornerRadius = height / 4 > 10 ? 10 : height / 4; canvas.drawRRect( - RRect.fromRectAndCorners( - Rect.fromLTRB( - x + padding, y + padding, x + width, y + height - padding), - bottomLeft: Radius.circular(cornerRadius), - topLeft: Radius.circular(cornerRadius)), - selectionPainter); + RRect.fromRectAndCorners( + Rect.fromLTRB(x + padding, y + padding, x + width, y + height - padding), + bottomLeft: Radius.circular(cornerRadius), + topLeft: Radius.circular(cornerRadius), + ), + selectionPainter, + ); } -void _drawEndRangeFillSelection(Canvas canvas, double x, double y, double width, - double height, Paint selectionPainter) { +void _drawEndRangeFillSelection( + Canvas canvas, + double x, + double y, + double width, + double height, + Paint selectionPainter, +) { const double padding = 1; final double cornerRadius = height / 4 > 10 ? 10 : height / 4; canvas.drawRRect( - RRect.fromRectAndCorners( - Rect.fromLTRB( - x, y + padding, x + width - padding, y + height - padding), - bottomRight: Radius.circular(cornerRadius), - topRight: Radius.circular(cornerRadius)), - selectionPainter); + RRect.fromRectAndCorners( + Rect.fromLTRB(x, y + padding, x + width - padding, y + height - padding), + bottomRight: Radius.circular(cornerRadius), + topRight: Radius.circular(cornerRadius), + ), + selectionPainter, + ); } -void _drawStartEndRangeCircleSelection(Canvas canvas, double x, double y, - double radius, Rect rect, Paint selectionPainter, Color color) { +void _drawStartEndRangeCircleSelection( + Canvas canvas, + double x, + double y, + double radius, + Rect rect, + Paint selectionPainter, + Color color, +) { canvas.drawRect(rect, selectionPainter); selectionPainter.isAntiAlias = true; selectionPainter.color = color; canvas.drawCircle(Offset(x, y), radius, selectionPainter); } -void _drawRectRangeSelection(Canvas canvas, double left, double top, - double right, double bottom, Paint selectionPainter) { +void _drawRectRangeSelection( + Canvas canvas, + double left, + double top, + double right, + double bottom, + Paint selectionPainter, +) { canvas.drawRect(Rect.fromLTRB(left, top, right, bottom), selectionPainter); } -void _drawMonthCellsAndSelection(PaintingContext context, Size size, - _IMonthView monthView, double cellWidth, double cellHeight) { +void _drawMonthCellsAndSelection( + PaintingContext context, + Size size, + _IMonthView monthView, + double cellWidth, + double cellHeight, +) { final double weekNumberPanelWidth = monthView.weekNumberPanelWidth; final Canvas canvas = context.canvas; double xPosition = monthView._isRtl ? 0 : weekNumberPanelWidth, yPosition; @@ -4017,10 +4475,12 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, double width = size.width - weekNumberPanelWidth; double height = size.height; int viewCount = 1; - final bool isHorizontalMultiView = monthView.enableMultiView && + final bool isHorizontalMultiView = + monthView.enableMultiView && monthView.navigationDirection == DateRangePickerNavigationDirection.horizontal; - final bool isVerticalMultiView = monthView.enableMultiView && + final bool isVerticalMultiView = + monthView.enableMultiView && monthView.navigationDirection == DateRangePickerNavigationDirection.vertical; @@ -4034,48 +4494,62 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, height = (height - webUIPadding) / viewCount; } - monthView._textPainter.textScaler = - TextScaler.linear(monthView.textScaleFactor); + monthView._textPainter.textScaler = TextScaler.linear( + monthView.textScaleFactor, + ); TextStyle textStyle = monthView.datePickerTheme.activeDatesTextStyle!; final int datesCount = monthView.visibleDates.length ~/ viewCount; final bool isNeedWidgetPaint = monthView.childCount != 0; final bool hideLeadingAndTrailingDates = (monthView.rowCount == 6 && !monthView.showLeadingAndTailingDates) || - monthView.isHijri; + monthView.isHijri; if (isNeedWidgetPaint) { RenderBox? child = monthView.firstChild; if (!isHorizontalMultiView) { _drawWeekNumberPanel( - canvas, size, weekNumberPanelWidth, monthView, isHorizontalMultiView); + canvas, + size, + weekNumberPanelWidth, + monthView, + isHorizontalMultiView, + ); } for (int j = 0; j < viewCount; j++) { final int currentViewIndex = monthView.isRtl ? DateRangePickerHelper.getRtlIndex(viewCount, j) : j; - final int currentMonth = monthView - .visibleDates[((j * datesCount) + (datesCount / 2)).truncate()] - .month as int; + final int currentMonth = + monthView + .visibleDates[((j * datesCount) + (datesCount / 2)) + .truncate()] + .month + as int; final int viewStartIndex = j * datesCount; final int viewEndIndex = ((j + 1) * datesCount) - 1; - final List selectedIndex = - monthView.getSelectedIndexValues(viewStartIndex, viewEndIndex); - double viewStartPosition = isVerticalMultiView - ? weekNumberPanelWidth - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * (currentViewIndex + 1)); + final List selectedIndex = monthView.getSelectedIndexValues( + viewStartIndex, + viewEndIndex, + ); + double viewStartPosition = + isVerticalMultiView + ? weekNumberPanelWidth + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * (currentViewIndex + 1)); if (monthView.isRtl) { - viewStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * currentViewIndex); + viewStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * currentViewIndex); } final double viewEndPosition = viewStartPosition + width; xPosition = viewStartPosition; - yPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + (currentViewIndex * webUIPadding); + yPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + (currentViewIndex * webUIPadding); /// In horizontal multi view we need to add two week number panel in /// different position hence added condition here to add week number @@ -4083,19 +4557,30 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, /// position and if we add here the color applied for two times when /// multi view enabled. if (isHorizontalMultiView) { - _drawWeekNumberPanel(canvas, size, weekNumberPanelWidth, monthView, - isHorizontalMultiView, - viewStartPosition: monthView.isRtl - ? (viewEndPosition + weekNumberPanelWidth + (j * webUIPadding)) - : viewStartPosition); + _drawWeekNumberPanel( + canvas, + size, + weekNumberPanelWidth, + monthView, + isHorizontalMultiView, + viewStartPosition: + monthView.isRtl + ? (viewEndPosition + + weekNumberPanelWidth + + (j * webUIPadding)) + : viewStartPosition, + ); } for (int i = 0; i < datesCount; i++) { int currentIndex = i; if (monthView.isRtl) { final int rowIndex = i ~/ DateTime.daysPerWeek; - currentIndex = DateRangePickerHelper.getRtlIndex( - DateTime.daysPerWeek, i % DateTime.daysPerWeek) + + currentIndex = + DateRangePickerHelper.getRtlIndex( + DateTime.daysPerWeek, + i % DateTime.daysPerWeek, + ) + (rowIndex * DateTime.daysPerWeek); } @@ -4124,34 +4609,35 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, (i > DateTime.daysPerWeek && i <= (DateTime.daysPerWeek * 2) && monthView - .visibleDates[ - viewStartIndex + (DateTime.daysPerWeek * 2)] + .visibleDates[viewStartIndex + + (DateTime.daysPerWeek * 2)] .month == currentMonth) || (i >= datesCount - (DateTime.daysPerWeek * 2) && i < datesCount - DateTime.daysPerWeek && monthView - .visibleDates[ - viewEndIndex - ((DateTime.daysPerWeek * 2) - 1)] + .visibleDates[viewEndIndex - + ((DateTime.daysPerWeek * 2) - 1)] .month == currentMonth) || (i >= datesCount - DateTime.daysPerWeek && (monthView - .visibleDates[ - viewEndIndex - (DateTime.daysPerWeek - 1)] + .visibleDates[viewEndIndex - + (DateTime.daysPerWeek - 1)] .month == currentMonth))) && date.weekday == DateTime.monday) { _drawWeekNumber( - canvas, - size, - date, - cellHeight, - yPosition, - weekNumberPanelWidth, - monthView, - viewStartPosition, - viewEndPosition); + canvas, + size, + date, + cellHeight, + yPosition, + weekNumberPanelWidth, + monthView, + viewStartPosition, + viewEndPosition, + ); } if (hideLeadingAndTrailingDates && currentDateMonth != currentMonth) { @@ -4160,28 +4646,36 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, } final bool isEnableDate = DateRangePickerHelper.isEnabledDate( - monthView.minDate, - monthView.maxDate, - monthView.enablePastDates, - date, - monthView.isHijri); + monthView.minDate, + monthView.maxDate, + monthView.enablePastDates, + date, + monthView.isHijri, + ); final bool isBlackedDate = DateRangePickerHelper.isDateWithInVisibleDates( - monthView.visibleDates, monthView.blackoutDates, date); + monthView.visibleDates, + monthView.blackoutDates, + date, + ); final bool isSelectedDate = selectedIndex.contains(currentIndex); bool isDisabledDate = DateRangePickerHelper.isDateWithInVisibleDates( - monthView.visibleDates, monthView.disableDatesCollection, date); + monthView.visibleDates, + monthView.disableDatesCollection, + date, + ); if (!isDisabledDate && monthView is _MonthViewExtendableRangeSelectionRenderObject && monthView.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - monthView.selectedRange, - date, - monthView.extendableRangeSelectionDirection, - DateRangePickerView.month, - monthView.isHijri, - isInBetweenEnabled: true)) { + monthView.selectedRange, + date, + monthView.extendableRangeSelectionDirection, + DateRangePickerView.month, + monthView.isHijri, + isInBetweenEnabled: true, + )) { isDisabledDate = true; } @@ -4193,7 +4687,11 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, (monthView.rowCount != 6 || (currentMonth == currentDateMonth)))) { monthView.drawCustomCellSelection( - canvas, xPosition, yPosition, currentIndex); + canvas, + xPosition, + yPosition, + currentIndex, + ); } child!.paint(context, Offset(xPosition, yPosition)); @@ -4206,15 +4704,16 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, (i > (DateTime.daysPerWeek * 2)) && (i < datesCount - (DateTime.daysPerWeek * 2))))) { _drawWeekNumber( - canvas, - size, - date, - cellHeight, - yPosition, - weekNumberPanelWidth, - monthView, - viewStartPosition, - viewEndPosition); + canvas, + size, + date, + cellHeight, + yPosition, + weekNumberPanelWidth, + monthView, + viewStartPosition, + viewEndPosition, + ); } if (monthView.mouseHoverPosition.value != null && @@ -4235,15 +4734,19 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, monthView.mouseHoverPosition.value!.offset!.dy) { monthView._selectionPainter.style = PaintingStyle.fill; monthView._selectionPainter.strokeWidth = 2; - monthView._selectionPainter.color = monthView.selectionColor != null - ? monthView.selectionColor!.withValues(alpha: 0.4) - : monthView.datePickerTheme.selectionColor! - .withValues(alpha: 0.4); + monthView._selectionPainter.color = + monthView.selectionColor != null + ? monthView.selectionColor!.withValues(alpha: 0.4) + : monthView.datePickerTheme.selectionColor!.withValues( + alpha: 0.4, + ); canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTWH(xPosition, yPosition, cellWidth, cellHeight), - const Radius.circular(2)), - monthView._selectionPainter); + RRect.fromRectAndRadius( + Rect.fromLTWH(xPosition, yPosition, cellWidth, cellHeight), + const Radius.circular(2), + ), + monthView._selectionPainter, + ); } } @@ -4257,13 +4760,19 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, final dynamic today = DateRangePickerHelper.getToday(monthView.isHijri); if (!isHorizontalMultiView) { _drawWeekNumberPanel( - canvas, size, weekNumberPanelWidth, monthView, isHorizontalMultiView); + canvas, + size, + weekNumberPanelWidth, + monthView, + isHorizontalMultiView, + ); } for (int j = 0; j < viewCount; j++) { final int currentViewIndex = monthView.isRtl ? DateRangePickerHelper.getRtlIndex(viewCount, j) : j; - final dynamic currentMonthDate = monthView - .visibleDates[((j * datesCount) + (datesCount / 2)).truncate()]; + final dynamic currentMonthDate = + monthView.visibleDates[((j * datesCount) + (datesCount / 2)) + .truncate()]; final int nextMonth = getNextMonthDate(currentMonthDate).month as int; final int previousMonth = getPreviousMonthDate(currentMonthDate).month as int; @@ -4278,51 +4787,66 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, final int viewStartIndex = j * datesCount; final int viewEndIndex = ((j + 1) * datesCount) - 1; - final List selectedIndex = - monthView.getSelectedIndexValues(viewStartIndex, viewEndIndex); - double viewStartPosition = isVerticalMultiView - ? weekNumberPanelWidth - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * (currentViewIndex + 1)); + final List selectedIndex = monthView.getSelectedIndexValues( + viewStartIndex, + viewEndIndex, + ); + double viewStartPosition = + isVerticalMultiView + ? weekNumberPanelWidth + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * (currentViewIndex + 1)); if (monthView.isRtl) { - viewStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + - (currentViewIndex * webUIPadding) + - (weekNumberPanelWidth * currentViewIndex); + viewStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + + (currentViewIndex * webUIPadding) + + (weekNumberPanelWidth * currentViewIndex); } List? hoveringIndex; if (monthView.mouseHoverPosition.value != null && monthView.mouseHoverPosition.value!.hoveringRange != null) { hoveringIndex = _getSelectedRangeIndex( - monthView.mouseHoverPosition.value!.hoveringRange.startDate, - monthView.mouseHoverPosition.value!.hoveringRange.endDate, - monthView.visibleDates, - monthView.isHijri, - monthStartIndex: viewStartIndex, - monthEndIndex: viewEndIndex); + monthView.mouseHoverPosition.value!.hoveringRange.startDate, + monthView.mouseHoverPosition.value!.hoveringRange.endDate, + monthView.visibleDates, + monthView.isHijri, + monthStartIndex: viewStartIndex, + monthEndIndex: viewEndIndex, + ); } final double viewEndPosition = viewStartPosition + width; xPosition = viewStartPosition; - yPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + (currentViewIndex * webUIPadding); + yPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + (currentViewIndex * webUIPadding); if (isHorizontalMultiView) { _drawWeekNumberPanel( - canvas, size, weekNumberPanelWidth, monthView, isHorizontalMultiView, - viewStartPosition: monthView.isRtl - ? (viewEndPosition + weekNumberPanelWidth + (j * webUIPadding)) - : viewStartPosition); + canvas, + size, + weekNumberPanelWidth, + monthView, + isHorizontalMultiView, + viewStartPosition: + monthView.isRtl + ? (viewEndPosition + weekNumberPanelWidth + (j * webUIPadding)) + : viewStartPosition, + ); } for (int i = 0; i < datesCount; i++) { int currentIndex = i; if (monthView.isRtl) { final int rowIndex = i ~/ DateTime.daysPerWeek; - currentIndex = DateRangePickerHelper.getRtlIndex( - DateTime.daysPerWeek, i % DateTime.daysPerWeek) + + currentIndex = + DateRangePickerHelper.getRtlIndex( + DateTime.daysPerWeek, + i % DateTime.daysPerWeek, + ) + (rowIndex * DateTime.daysPerWeek); } @@ -4345,40 +4869,42 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, if (weekNumberPanelWidth != 0 && hideLeadingAndTrailingDates && ((i <= DateTime.daysPerWeek && - monthView.visibleDates[viewStartIndex + DateTime.daysPerWeek] + monthView + .visibleDates[viewStartIndex + DateTime.daysPerWeek] .month == currentMonthDate.month) || (i > DateTime.daysPerWeek && i <= (DateTime.daysPerWeek * 2) && monthView - .visibleDates[ - viewStartIndex + (DateTime.daysPerWeek * 2)] + .visibleDates[viewStartIndex + + (DateTime.daysPerWeek * 2)] .month == currentMonthDate.month) || (i >= datesCount - (DateTime.daysPerWeek * 2) && i < datesCount - DateTime.daysPerWeek && monthView - .visibleDates[ - viewEndIndex - ((DateTime.daysPerWeek * 2) - 1)] + .visibleDates[viewEndIndex - + ((DateTime.daysPerWeek * 2) - 1)] .month == currentMonthDate.month) || (i >= datesCount - DateTime.daysPerWeek && (monthView - .visibleDates[ - viewEndIndex - (DateTime.daysPerWeek - 1)] + .visibleDates[viewEndIndex - + (DateTime.daysPerWeek - 1)] .month == currentMonthDate.month))) && date.weekday == DateTime.monday) { _drawWeekNumber( - canvas, - size, - date, - cellHeight, - yPosition, - weekNumberPanelWidth, - monthView, - viewStartPosition, - viewEndPosition); + canvas, + size, + date, + cellHeight, + yPosition, + weekNumberPanelWidth, + monthView, + viewStartPosition, + viewEndPosition, + ); } bool isNextMonth = false; @@ -4406,67 +4932,83 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, (i > (DateTime.daysPerWeek * 2)) && (i < datesCount - (DateTime.daysPerWeek * 2))))) { _drawWeekNumber( - canvas, - size, - date, - cellHeight, - yPosition, - weekNumberPanelWidth, - monthView, - viewStartPosition, - viewEndPosition); + canvas, + size, + date, + cellHeight, + yPosition, + weekNumberPanelWidth, + monthView, + viewStartPosition, + viewEndPosition, + ); } isCurrentDate = isSameDate(date, today); final bool isEnableDate = DateRangePickerHelper.isEnabledDate( - monthView.minDate, - monthView.maxDate, - monthView.enablePastDates, - date, - monthView.isHijri); + monthView.minDate, + monthView.maxDate, + monthView.enablePastDates, + date, + monthView.isHijri, + ); final bool isBlackedDate = DateRangePickerHelper.isDateWithInVisibleDates( - monthView.visibleDates, monthView.blackoutDates, date); - final bool isWeekEnd = - DateRangePickerHelper.isWeekend(monthView.weekendDays, date); + monthView.visibleDates, + monthView.blackoutDates, + date, + ); + final bool isWeekEnd = DateRangePickerHelper.isWeekend( + monthView.weekendDays, + date, + ); final bool isSpecialDate = DateRangePickerHelper.isDateWithInVisibleDates( - monthView.visibleDates, monthView.specialDates, date); + monthView.visibleDates, + monthView.specialDates, + date, + ); bool isDisabledDate = DateRangePickerHelper.isDateWithInVisibleDates( - monthView.visibleDates, monthView.disableDatesCollection, date); + monthView.visibleDates, + monthView.disableDatesCollection, + date, + ); if (!isDisabledDate && monthView is _MonthViewExtendableRangeSelectionRenderObject && monthView.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - monthView.selectedRange, - date, - monthView.extendableRangeSelectionDirection, - DateRangePickerView.month, - monthView.isHijri, - isInBetweenEnabled: true)) { + monthView.selectedRange, + date, + monthView.extendableRangeSelectionDirection, + DateRangePickerView.month, + monthView.isHijri, + isInBetweenEnabled: true, + )) { isDisabledDate = true; } textStyle = _updateTextStyle( - monthView, - isNextMonth, - isPreviousMonth, - isCurrentDate, - isEnableDate, - isBlackedDate, - isWeekEnd, - isSpecialDate, - isDisabledDate); + monthView, + isNextMonth, + isPreviousMonth, + isCurrentDate, + isEnableDate, + isBlackedDate, + isWeekEnd, + isSpecialDate, + isDisabledDate, + ); dateDecoration = _updateDecoration( - isNextMonth, - isPreviousMonth, - monthView, - isEnableDate, - isCurrentDate, - isBlackedDate, - date, - isWeekEnd, - isSpecialDate, - isDisabledDate); + isNextMonth, + isPreviousMonth, + monthView, + isEnableDate, + isCurrentDate, + isBlackedDate, + date, + isWeekEnd, + isSpecialDate, + isDisabledDate, + ); final bool isSelectedDate = selectedIndex.contains(currentIndex); if (isSelectedDate && @@ -4477,19 +5019,35 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, (monthView.rowCount != 6 || (currentMonthDate.month == currentDateMonth)))) { textStyle = _drawCellAndSelection( - canvas, - xPosition, - yPosition, - selectionTextStyle, - selectedRangeTextStyle, - monthView, - currentIndex); + canvas, + xPosition, + yPosition, + selectionTextStyle, + selectedRangeTextStyle, + monthView, + currentIndex, + ); } else if (dateDecoration != null) { - _drawDecoration(canvas, xPosition, yPosition, padding, cellWidth, - cellHeight, dateDecoration, monthView); + _drawDecoration( + canvas, + xPosition, + yPosition, + padding, + cellWidth, + cellHeight, + dateDecoration, + monthView, + ); } else if (isCurrentDate) { - _drawCurrentDate(canvas, monthView, xPosition, yPosition, padding, - cellWidth, cellHeight); + _drawCurrentDate( + canvas, + monthView, + xPosition, + yPosition, + padding, + cellWidth, + cellHeight, + ); } final TextSpan dateText = TextSpan( @@ -4500,17 +5058,26 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, monthView._textPainter.text = dateText; monthView._textPainter.layout(maxWidth: cellWidth); monthView._textPainter.paint( - canvas, - Offset(xPosition + (cellWidth / 2 - monthView._textPainter.width / 2), - yPosition + ((cellHeight - monthView._textPainter.height) / 2))); + canvas, + Offset( + xPosition + (cellWidth / 2 - monthView._textPainter.width / 2), + yPosition + ((cellHeight - monthView._textPainter.height) / 2), + ), + ); if (hoveringIndex != null && hoveringIndex.isNotEmpty && hoveringIndex.contains(currentIndex) && !isBlackedDate && isEnableDate) { - _addRangeHoverEffect(canvas, xPosition, yPosition, monthView, - currentIndex, hoveringIndex); + _addRangeHoverEffect( + canvas, + xPosition, + yPosition, + monthView, + currentIndex, + hoveringIndex, + ); } if (monthView.mouseHoverPosition.value != null) { @@ -4523,8 +5090,15 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, } if (monthView.mouseHoverPosition.value!.offset != null) { - _addHoveringEffect(canvas, monthView, xPosition, yPosition, cellWidth, - cellHeight, size); + _addHoveringEffect( + canvas, + monthView, + xPosition, + yPosition, + cellWidth, + cellHeight, + size, + ); } } @@ -4534,22 +5108,27 @@ void _drawMonthCellsAndSelection(PaintingContext context, Size size, } void _drawWeekNumber( - Canvas canvas, - Size size, - dynamic date, - double cellHeight, - double yPosition, - double weekNumberPanelWidth, - _IMonthView monthView, - double viewStartPosition, - double viewEndPosition) { + Canvas canvas, + Size size, + dynamic date, + double cellHeight, + double yPosition, + double weekNumberPanelWidth, + _IMonthView monthView, + double viewStartPosition, + double viewEndPosition, +) { final String weekNumber = - DateRangePickerHelper.getWeekNumberOfYear(date, monthView.isHijri) - .toString(); + DateRangePickerHelper.getWeekNumberOfYear( + date, + monthView.isHijri, + ).toString(); final TextStyle weekNumberTextStyle = monthView.datePickerTheme.weekNumberTextStyle!; - final TextSpan textSpan = - TextSpan(text: weekNumber, style: weekNumberTextStyle); + final TextSpan textSpan = TextSpan( + text: weekNumber, + style: weekNumberTextStyle, + ); monthView._textPainter.text = textSpan; monthView._textPainter.textAlign = TextAlign.left; @@ -4559,22 +5138,31 @@ void _drawWeekNumber( double weekNumberPosition = (weekNumberPanelWidth - monthView._textPainter.width) / 2; - weekNumberPosition += monthView.isRtl - ? viewStartPosition == 0 && - monthView.navigationDirection == - DateRangePickerNavigationDirection.horizontal - ? viewEndPosition + monthView.multiViewSpacing - : viewEndPosition - : viewStartPosition - weekNumberPanelWidth; + weekNumberPosition += + monthView.isRtl + ? viewStartPosition == 0 && + monthView.navigationDirection == + DateRangePickerNavigationDirection.horizontal + ? viewEndPosition + monthView.multiViewSpacing + : viewEndPosition + : viewStartPosition - weekNumberPanelWidth; monthView._textPainter.paint( - canvas, - Offset(weekNumberPosition, - yPosition + ((cellHeight - monthView._textPainter.height) / 2))); + canvas, + Offset( + weekNumberPosition, + yPosition + ((cellHeight - monthView._textPainter.height) / 2), + ), + ); } -void _drawWeekNumberPanel(Canvas canvas, Size size, double weekNumberPanelWidth, - _IMonthView monthView, bool isHorizontalMultiView, - {double viewStartPosition = 0}) { +void _drawWeekNumberPanel( + Canvas canvas, + Size size, + double weekNumberPanelWidth, + _IMonthView monthView, + bool isHorizontalMultiView, { + double viewStartPosition = 0, +}) { if (weekNumberPanelWidth == 0) { return; } @@ -4585,21 +5173,34 @@ void _drawWeekNumberPanel(Canvas canvas, Size size, double weekNumberPanelWidth, } final double padding = monthView.isMobilePlatform ? 5 : 0; - final Rect rect = Rect.fromLTRB(xPosition + padding, padding, - (xPosition + weekNumberPanelWidth) - padding, size.height - padding); + final Rect rect = Rect.fromLTRB( + xPosition + padding, + padding, + (xPosition + weekNumberPanelWidth) - padding, + size.height - padding, + ); final Paint linePainter = Paint(); linePainter.style = PaintingStyle.fill; - linePainter.color = monthView.weekNumberStyle.backgroundColor ?? + linePainter.color = + monthView.weekNumberStyle.backgroundColor ?? monthView.datePickerTheme.weekNumberBackgroundColor!; - final RRect roundedRect = - RRect.fromRectAndRadius(rect, Radius.circular(padding)); + final RRect roundedRect = RRect.fromRectAndRadius( + rect, + Radius.circular(padding), + ); canvas.drawRRect(roundedRect, linePainter); } /// Add the hovering effect when the selection mode set as extendable and the /// hovering date extends the range. -void _addRangeHoverEffect(Canvas canvas, double xPosition, double yPosition, - _IMonthView monthView, int currentIndex, List? hoveringIndex) { +void _addRangeHoverEffect( + Canvas canvas, + double xPosition, + double yPosition, + _IMonthView monthView, + int currentIndex, + List? hoveringIndex, +) { if (hoveringIndex == null || hoveringIndex.isEmpty) { return; } @@ -4615,9 +5216,10 @@ void _addRangeHoverEffect(Canvas canvas, double xPosition, double yPosition, final bool isBetweenRange = hoveringDetails[3]; final double radius = _getCellRadius( - rangeSelectionMonthView.selectionRadius, - rangeSelectionMonthView._centerXPosition, - rangeSelectionMonthView._centerYPosition); + rangeSelectionMonthView.selectionRadius, + rangeSelectionMonthView._centerXPosition, + rangeSelectionMonthView._centerYPosition, + ); final double cornerRadius = monthView._cellHeight / 4 > 10 ? 10 : monthView._cellHeight / 4; double heightDifference = rangeSelectionMonthView._cellHeight / 2 - radius; @@ -4634,61 +5236,82 @@ void _addRangeHoverEffect(Canvas canvas, double xPosition, double yPosition, switch (monthView.selectionShape) { case DateRangePickerSelectionShape.circle: rect = Rect.fromLTRB( - xPosition + rangeSelectionMonthView._centerXPosition, - yPosition + heightDifference, - xPosition + rangeSelectionMonthView._cellWidth, - yPosition + rangeSelectionMonthView._cellHeight - heightDifference); + xPosition + rangeSelectionMonthView._centerXPosition, + yPosition + heightDifference, + xPosition + rangeSelectionMonthView._cellWidth, + yPosition + rangeSelectionMonthView._cellHeight - heightDifference, + ); break; case DateRangePickerSelectionShape.rectangle: final double rightPosition = xPosition + rangeSelectionMonthView._cellWidth; rect = Rect.fromLTRB( - rightPosition - cornerRadius, - yPosition + heightDifference, - rightPosition, - yPosition + rangeSelectionMonthView._cellHeight - heightDifference); + rightPosition - cornerRadius, + yPosition + heightDifference, + rightPosition, + yPosition + rangeSelectionMonthView._cellHeight - heightDifference, + ); } } else if (isEndRange) { switch (monthView.selectionShape) { case DateRangePickerSelectionShape.circle: rect = Rect.fromLTRB( - xPosition, - yPosition + heightDifference, - xPosition + rangeSelectionMonthView._centerXPosition, - yPosition + rangeSelectionMonthView._cellHeight - heightDifference); + xPosition, + yPosition + heightDifference, + xPosition + rangeSelectionMonthView._centerXPosition, + yPosition + rangeSelectionMonthView._cellHeight - heightDifference, + ); break; case DateRangePickerSelectionShape.rectangle: { rect = Rect.fromLTRB( - xPosition, - yPosition + heightDifference, - xPosition + cornerRadius, - yPosition + - rangeSelectionMonthView._cellHeight - - heightDifference); + xPosition, + yPosition + heightDifference, + xPosition + cornerRadius, + yPosition + rangeSelectionMonthView._cellHeight - heightDifference, + ); } } } else if (isBetweenRange) { rect = Rect.fromLTRB( - xPosition, - yPosition + heightDifference, - xPosition + rangeSelectionMonthView._cellWidth, - yPosition + rangeSelectionMonthView._cellHeight - heightDifference); + xPosition, + yPosition + heightDifference, + xPosition + rangeSelectionMonthView._cellWidth, + yPosition + rangeSelectionMonthView._cellHeight - heightDifference, + ); } monthView._selectionPainter.style = PaintingStyle.stroke; monthView._selectionPainter.strokeWidth = 1.0; - monthView._selectionPainter.color = monthView.selectionColor != null - ? monthView.selectionColor!.withValues(alpha: 0.4) - : monthView.datePickerTheme.selectionColor!.withValues(alpha: 0.4); + monthView._selectionPainter.color = + monthView.selectionColor != null + ? monthView.selectionColor!.withValues(alpha: 0.4) + : monthView.datePickerTheme.selectionColor!.withValues(alpha: 0.4); DateRangePickerHelper.drawDashedLine( - rect.left, rect.top, rect.right, canvas, monthView._selectionPainter); + rect.left, + rect.top, + rect.right, + canvas, + monthView._selectionPainter, + ); DateRangePickerHelper.drawDashedLine( - rect.left, rect.bottom, rect.right, canvas, monthView._selectionPainter); + rect.left, + rect.bottom, + rect.right, + canvas, + monthView._selectionPainter, + ); } -void _addHoveringEffect(Canvas canvas, _IMonthView monthView, double xPosition, - double yPosition, double cellWidth, double cellHeight, Size size) { +void _addHoveringEffect( + Canvas canvas, + _IMonthView monthView, + double xPosition, + double yPosition, + double cellWidth, + double cellHeight, + Size size, +) { if (xPosition <= monthView.mouseHoverPosition.value!.offset!.dx && xPosition + cellWidth >= monthView.mouseHoverPosition.value!.offset!.dx && yPosition <= monthView.mouseHoverPosition.value!.offset!.dy && @@ -4696,74 +5319,104 @@ void _addHoveringEffect(Canvas canvas, _IMonthView monthView, double xPosition, monthView.mouseHoverPosition.value!.offset!.dy) { monthView._selectionPainter.style = PaintingStyle.fill; monthView._selectionPainter.strokeWidth = 2; - monthView._selectionPainter.color = monthView.selectionColor != null - ? monthView.selectionColor!.withValues(alpha: 0.4) - : monthView.datePickerTheme.selectionColor!.withValues(alpha: 0.4); + monthView._selectionPainter.color = + monthView.selectionColor != null + ? monthView.selectionColor!.withValues(alpha: 0.4) + : monthView.datePickerTheme.selectionColor!.withValues(alpha: 0.4); switch (monthView.selectionShape) { case DateRangePickerSelectionShape.circle: { final double centerXPosition = cellWidth / 2; final double centerYPosition = cellHeight / 2; final double radius = _getCellRadius( - monthView.selectionRadius, centerXPosition, centerYPosition); + monthView.selectionRadius, + centerXPosition, + centerYPosition, + ); canvas.drawCircle( - Offset(xPosition + centerXPosition, yPosition + centerYPosition), - radius, - monthView._selectionPainter); + Offset(xPosition + centerXPosition, yPosition + centerYPosition), + radius, + monthView._selectionPainter, + ); } break; case DateRangePickerSelectionShape.rectangle: { canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTWH(xPosition + 1, yPosition + 1, cellWidth - 1, - cellHeight - 1), - Radius.circular(cellHeight / 4 > 10 ? 10 : cellHeight / 4)), - monthView._selectionPainter); + RRect.fromRectAndRadius( + Rect.fromLTWH( + xPosition + 1, + yPosition + 1, + cellWidth - 1, + cellHeight - 1, + ), + Radius.circular(cellHeight / 4 > 10 ? 10 : cellHeight / 4), + ), + monthView._selectionPainter, + ); } } } } TextStyle _drawCellAndSelection( - Canvas canvas, - double xPosition, - double yPosition, - TextStyle selectionTextStyle, - TextStyle selectedRangeTextStyle, - _IMonthView monthView, - int currentIndex) { + Canvas canvas, + double xPosition, + double yPosition, + TextStyle selectionTextStyle, + TextStyle selectedRangeTextStyle, + _IMonthView monthView, + int currentIndex, +) { monthView._selectionPainter.color = monthView.selectionColor ?? monthView.datePickerTheme.selectionColor!; //// Unwanted space shown at end of the rectangle while enable anti aliasing property. monthView._selectionPainter.isAntiAlias = false; monthView._selectionPainter.strokeWidth = 0.0; monthView._selectionPainter.style = PaintingStyle.fill; - return monthView.drawSelection(canvas, xPosition, yPosition, currentIndex, - selectionTextStyle, selectedRangeTextStyle); + return monthView.drawSelection( + canvas, + xPosition, + yPosition, + currentIndex, + selectionTextStyle, + selectedRangeTextStyle, + ); } void _drawDecoration( - Canvas canvas, - double xPosition, - double yPosition, - double padding, - double cellWidth, - double cellHeight, - Decoration dateDecoration, - _IMonthView monthView) { - final BoxPainter boxPainter = - dateDecoration.createBoxPainter(monthView.markNeedsPaint); + Canvas canvas, + double xPosition, + double yPosition, + double padding, + double cellWidth, + double cellHeight, + Decoration dateDecoration, + _IMonthView monthView, +) { + final BoxPainter boxPainter = dateDecoration.createBoxPainter( + monthView.markNeedsPaint, + ); boxPainter.paint( - canvas, - Offset(xPosition + padding, yPosition + padding), - ImageConfiguration( - size: Size(cellWidth - (2 * padding), cellHeight - (2 * padding)))); + canvas, + Offset(xPosition + padding, yPosition + padding), + ImageConfiguration( + size: Size(cellWidth - (2 * padding), cellHeight - (2 * padding)), + ), + ); } -void _drawCurrentDate(Canvas canvas, _IMonthView monthView, double xPosition, - double yPosition, double padding, double cellWidth, double cellHeight) { - monthView._selectionPainter.color = monthView.todayHighlightColor ?? +void _drawCurrentDate( + Canvas canvas, + _IMonthView monthView, + double xPosition, + double yPosition, + double padding, + double cellWidth, + double cellHeight, +) { + monthView._selectionPainter.color = + monthView.todayHighlightColor ?? monthView.datePickerTheme.todayHighlightColor!; monthView._selectionPainter.isAntiAlias = true; monthView._selectionPainter.strokeWidth = 1.0; @@ -4775,38 +5428,46 @@ void _drawCurrentDate(Canvas canvas, _IMonthView monthView, double xPosition, final double centerXPosition = cellWidth / 2; final double centerYPosition = cellHeight / 2; final double radius = _getCellRadius( - monthView.selectionRadius, centerXPosition, centerYPosition); + monthView.selectionRadius, + centerXPosition, + centerYPosition, + ); canvas.drawCircle( - Offset(xPosition + centerXPosition, yPosition + centerYPosition), - radius, - monthView._selectionPainter); + Offset(xPosition + centerXPosition, yPosition + centerYPosition), + radius, + monthView._selectionPainter, + ); } break; case DateRangePickerSelectionShape.rectangle: { canvas.drawRRect( - RRect.fromRectAndRadius( - Rect.fromLTRB( - xPosition + padding, - yPosition + padding, - xPosition + cellWidth - padding, - yPosition + cellHeight - padding), - Radius.circular(cellHeight / 4 > 10 ? 10 : cellHeight / 4)), - monthView._selectionPainter); + RRect.fromRectAndRadius( + Rect.fromLTRB( + xPosition + padding, + yPosition + padding, + xPosition + cellWidth - padding, + yPosition + cellHeight - padding, + ), + Radius.circular(cellHeight / 4 > 10 ? 10 : cellHeight / 4), + ), + monthView._selectionPainter, + ); } } } TextStyle _updateTextStyle( - _IMonthView monthView, - bool isNextMonth, - bool isPreviousMonth, - bool isCurrentDate, - bool isEnableDate, - bool isBlackedDate, - bool isWeekEnd, - bool isSpecialDate, - bool isDisabledDate) { + _IMonthView monthView, + bool isNextMonth, + bool isPreviousMonth, + bool isCurrentDate, + bool isEnableDate, + bool isBlackedDate, + bool isWeekEnd, + bool isSpecialDate, + bool isDisabledDate, +) { final TextStyle currentDatesTextStyle = monthView.datePickerTheme.activeDatesTextStyle!; if (isBlackedDate) { @@ -4844,16 +5505,17 @@ TextStyle _updateTextStyle( } Decoration? _updateDecoration( - bool isNextMonth, - bool isPreviousMonth, - _IMonthView monthView, - bool isEnableDate, - bool isCurrentDate, - bool isBlackedDate, - dynamic date, - bool isWeekEnd, - bool isSpecialDate, - bool isDisabledDate) { + bool isNextMonth, + bool isPreviousMonth, + _IMonthView monthView, + bool isEnableDate, + bool isCurrentDate, + bool isBlackedDate, + dynamic date, + bool isWeekEnd, + bool isSpecialDate, + bool isDisabledDate, +) { final Decoration? dateDecoration = monthView.cellStyle.cellDecoration as Decoration?; diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/picker_helper.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/picker_helper.dart index 343ba1915..f4899fd82 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/picker_helper.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/picker_helper.dart @@ -16,7 +16,10 @@ class DateRangePickerHelper { /// Calculate the visible dates count based on picker view static int getViewDatesCount( - DateRangePickerView pickerView, int numberOfWeeks, bool isHijri) { + DateRangePickerView pickerView, + int numberOfWeeks, + bool isHijri, + ) { if (pickerView == DateRangePickerView.month) { if (isHijri) { /// 6 used to render the default number of weeks, since, Hijri type @@ -48,7 +51,9 @@ class DateRangePickerHelper { /// Checks both the range collections are equal or not. static bool isDateRangesEquals( - List? rangeCollection1, List? rangeCollection2) { + List? rangeCollection1, + List? rangeCollection2, + ) { if (rangeCollection1 == rangeCollection2) { return true; } @@ -78,11 +83,21 @@ class DateRangePickerHelper { } /// Calculate the next view visible start date based on picker view. - static dynamic getNextViewStartDate(DateRangePickerView pickerView, - int numberOfWeeksInView, dynamic date, bool isRtl, bool isHijri) { + static dynamic getNextViewStartDate( + DateRangePickerView pickerView, + int numberOfWeeksInView, + dynamic date, + bool isRtl, + bool isHijri, + ) { if (isRtl) { return getPreviousViewStartDate( - pickerView, numberOfWeeksInView, date, false, isHijri); + pickerView, + numberOfWeeksInView, + date, + false, + isHijri, + ); } switch (pickerView) { @@ -108,11 +123,21 @@ class DateRangePickerHelper { } /// Calculate the previous view visible start date based on calendar view. - static dynamic getPreviousViewStartDate(DateRangePickerView pickerView, - int numberOfWeeksInView, dynamic date, bool isRtl, bool isHijri) { + static dynamic getPreviousViewStartDate( + DateRangePickerView pickerView, + int numberOfWeeksInView, + dynamic date, + bool isRtl, + bool isHijri, + ) { if (isRtl) { return getNextViewStartDate( - pickerView, numberOfWeeksInView, date, false, isHijri); + pickerView, + numberOfWeeksInView, + date, + false, + isHijri, + ); } switch (pickerView) { @@ -179,7 +204,9 @@ class DateRangePickerHelper { /// Checks both the date collection are equal or not. static bool isDateCollectionEquals( - List? datesCollection1, List? datesCollection2) { + List? datesCollection1, + List? datesCollection2, + ) { if (datesCollection1 == datesCollection2) { return true; } @@ -210,8 +237,13 @@ class DateRangePickerHelper { /// Check the date as enable date or disable date based on min date, max date /// and enable past dates values. - static bool isEnabledDate(dynamic startDate, dynamic endDate, - bool enablePastDates, dynamic date, bool isHijri) { + static bool isEnabledDate( + dynamic startDate, + dynamic endDate, + bool enablePastDates, + dynamic date, + bool isHijri, + ) { return isDateWithInDateRange(startDate, endDate, date) && (enablePastDates || (!enablePastDates && @@ -221,7 +253,10 @@ class DateRangePickerHelper { /// Return the first date of the month, year and decade based on view. /// Note: This method not applicable for month view. static dynamic getFirstDate( - dynamic date, bool isHijri, DateRangePickerView pickerView) { + dynamic date, + bool isHijri, + DateRangePickerView pickerView, + ) { if (pickerView == DateRangePickerView.month) { return date; } @@ -232,7 +267,11 @@ class DateRangePickerHelper { return DateRangePickerHelper.getDate(date.year, 1, 1, isHijri); } else if (pickerView == DateRangePickerView.century) { return DateRangePickerHelper.getDate( - (date.year ~/ 10) * 10, 1, 1, isHijri); + (date.year ~/ 10) * 10, + 1, + 1, + isHijri, + ); } return date; @@ -243,12 +282,13 @@ class DateRangePickerHelper { /// is in between enabled used to enable the in between dates on selected /// range while draw the cell. static bool isDisableDirectionDate( - dynamic range, - dynamic currentDate, - ExtendableRangeSelectionDirection extendableRangeSelectionDirection, - DateRangePickerView view, - bool isHijri, - {bool isInBetweenEnabled = false}) { + dynamic range, + dynamic currentDate, + ExtendableRangeSelectionDirection extendableRangeSelectionDirection, + DateRangePickerView view, + bool isHijri, { + bool isInBetweenEnabled = false, + }) { if (range == null) { return false; } @@ -258,9 +298,10 @@ class DateRangePickerHelper { } final dynamic startDate = getFirstDate(range.startDate, isHijri, view); - final dynamic endDate = range.endDate != null - ? getFirstDate(range.endDate, isHijri, view) - : startDate; + final dynamic endDate = + range.endDate != null + ? getFirstDate(range.endDate, isHijri, view) + : startDate; final dynamic currentDateValue = getFirstDate(currentDate, isHijri, view); switch (extendableRangeSelectionDirection) { case ExtendableRangeSelectionDirection.none: @@ -269,10 +310,16 @@ class DateRangePickerHelper { (isInBetweenEnabled && ((startDate.isAfter(currentDateValue) == true && !isSameCellDates( - startDate, currentDateValue, view)) || + startDate, + currentDateValue, + view, + )) || (endDate.isBefore(currentDateValue) == true && !isSameCellDates( - endDate, currentDateValue, view))))); + endDate, + currentDateValue, + view, + ))))); case ExtendableRangeSelectionDirection.forward: return startDate.isAfter(currentDateValue) == true && !isSameCellDates(startDate, currentDateValue, view); @@ -285,8 +332,13 @@ class DateRangePickerHelper { } /// Check the date as current month date. - static bool isDateAsCurrentMonthDate(dynamic visibleDate, int rowCount, - bool showLeadingAndTrialingDates, dynamic date, bool isHijri) { + static bool isDateAsCurrentMonthDate( + dynamic visibleDate, + int rowCount, + bool showLeadingAndTrialingDates, + dynamic date, + bool isHijri, + ) { if ((rowCount == 6 && !showLeadingAndTrialingDates || isHijri) && date.month != visibleDate.month) { return false; @@ -297,11 +349,17 @@ class DateRangePickerHelper { /// Return the updated left and top value based cell width and height and /// total width and height. - static Map getTopAndLeftValues(bool isRtl, double left, - double top, double cellWidth, double cellHeight, double width) { + static Map getTopAndLeftValues( + bool isRtl, + double left, + double top, + double cellWidth, + double cellHeight, + double width, + ) { final Map topAndLeft = { 'left': left, - 'top': top + 'top': top, }; if (isRtl) { if (left.round() == cellWidth.round()) { @@ -328,7 +386,10 @@ class DateRangePickerHelper { /// Check the date placed in dates collection based on visible dates. static bool isDateWithInVisibleDates( - List visibleDates, List? dates, dynamic date) { + List visibleDates, + List? dates, + dynamic date, + ) { if (dates == null || dates.isEmpty) { return false; } @@ -337,7 +398,10 @@ class DateRangePickerHelper { final dynamic visibleEndDate = visibleDates[visibleDates.length - 1]; for (final dynamic currentDate in dates) { if (!isDateWithInDateRange( - visibleStartDate, visibleEndDate, currentDate)) { + visibleStartDate, + visibleEndDate, + currentDate, + )) { continue; } @@ -360,58 +424,87 @@ class DateRangePickerHelper { /// Check the left side view have valid dates based on widget direction. static bool canMoveToPreviousViewRtl( - DateRangePickerView view, - int numberOfWeeksInView, - dynamic minDate, - dynamic maxDate, - List visibleDates, - bool isRtl, - bool enableMultiView, - bool isHijri) { + DateRangePickerView view, + int numberOfWeeksInView, + dynamic minDate, + dynamic maxDate, + List visibleDates, + bool isRtl, + bool enableMultiView, + bool isHijri, + ) { if (isRtl) { - return canMoveToNextView(view, numberOfWeeksInView, maxDate, visibleDates, - enableMultiView, isHijri); + return canMoveToNextView( + view, + numberOfWeeksInView, + maxDate, + visibleDates, + enableMultiView, + isHijri, + ); } else { - return canMoveToPreviousView(view, numberOfWeeksInView, minDate, - visibleDates, enableMultiView, isHijri); + return canMoveToPreviousView( + view, + numberOfWeeksInView, + minDate, + visibleDates, + enableMultiView, + isHijri, + ); } } /// Check the right side view have valid dates based on widget direction. static bool canMoveToNextViewRtl( - DateRangePickerView view, - int numberOfWeeksInView, - dynamic minDate, - dynamic maxDate, - List visibleDates, - bool isRtl, - bool enableMultiView, - bool isHijri) { + DateRangePickerView view, + int numberOfWeeksInView, + dynamic minDate, + dynamic maxDate, + List visibleDates, + bool isRtl, + bool enableMultiView, + bool isHijri, + ) { if (isRtl) { - return canMoveToPreviousView(view, numberOfWeeksInView, minDate, - visibleDates, enableMultiView, isHijri); + return canMoveToPreviousView( + view, + numberOfWeeksInView, + minDate, + visibleDates, + enableMultiView, + isHijri, + ); } else { - return canMoveToNextView(view, numberOfWeeksInView, maxDate, visibleDates, - enableMultiView, isHijri); + return canMoveToNextView( + view, + numberOfWeeksInView, + maxDate, + visibleDates, + enableMultiView, + isHijri, + ); } } /// Check the previous view have enabled dates or not. static bool canMoveToPreviousView( - DateRangePickerView view, - int numberOfWeeksInView, - dynamic minDate, - List visibleDates, - bool enableMultiView, - bool isHijri) { + DateRangePickerView view, + int numberOfWeeksInView, + dynamic minDate, + List visibleDates, + bool enableMultiView, + bool isHijri, + ) { switch (view) { case DateRangePickerView.month: { if (numberOfWeeksInView != 6 && !isHijri) { - DateTime prevViewDate = - DateRangePickerHelper.getDateTimeValue(visibleDates[0]); + DateTime prevViewDate = DateRangePickerHelper.getDateTimeValue( + visibleDates[0], + ); prevViewDate = DateRangePickerHelper.getDateTimeValue( - addDays(prevViewDate, -1)); + addDays(prevViewDate, -1), + ); if (!isSameOrAfterDate(minDate, prevViewDate)) { return false; } @@ -433,7 +526,8 @@ class DateRangePickerHelper { { final int currentYear = visibleDates[visibleDates.length ~/ (enableMultiView ? 4 : 2)] - .year as int; + .year + as int; final int minYear = minDate.year as int; final int offset = getOffset(view); @@ -466,7 +560,10 @@ class DateRangePickerHelper { /// Get the visible dates based on the date value and visible dates count. // ignore: always_specify_types, strict_raw_type static List getVisibleYearDates( - dynamic date, DateRangePickerView view, bool isHijri) { + dynamic date, + DateRangePickerView view, + bool isHijri, + ) { // ignore: always_specify_types, strict_raw_type List datesCollection; if (isHijri) { @@ -514,20 +611,23 @@ class DateRangePickerHelper { /// Check the next view have enabled dates or not. static bool canMoveToNextView( - DateRangePickerView view, - int numberOfWeeksInView, - dynamic maxDate, - List visibleDates, - bool enableMultiView, - bool isHijri) { + DateRangePickerView view, + int numberOfWeeksInView, + dynamic maxDate, + List visibleDates, + bool enableMultiView, + bool isHijri, + ) { switch (view) { case DateRangePickerView.month: { if (!isHijri && numberOfWeeksInView != 6) { DateTime nextViewDate = DateRangePickerHelper.getDateTimeValue( - visibleDates[visibleDates.length - 1]); + visibleDates[visibleDates.length - 1], + ); nextViewDate = DateRangePickerHelper.getDateTimeValue( - addDays(nextViewDate, 1)); + addDays(nextViewDate, 1), + ); if (!isSameOrBeforeDate(maxDate, nextViewDate)) { return false; } @@ -549,7 +649,8 @@ class DateRangePickerHelper { { final int currentYear = visibleDates[visibleDates.length ~/ (enableMultiView ? 4 : 2)] - .year as int; + .year + as int; final int maxYear = maxDate.year as int; final int offset = getOffset(view); if (((currentYear ~/ offset) * offset) + offset > @@ -582,7 +683,10 @@ class DateRangePickerHelper { /// Returns the corresponding hijri month date, for the date passed with the /// given month format and localization. static String getHijriMonthText( - dynamic date, SfLocalizations localizations, String format) { + dynamic date, + SfLocalizations localizations, + String format, + ) { if (date.month == 1) { if (format == 'M' || format == 'MM') { return date.month.toString(); @@ -735,7 +839,9 @@ class DateRangePickerHelper { /// Determines whether the leading and trailing dates can be shown or not. static bool canShowLeadingAndTrailingDates( - dynamic monthViewSettings, bool isHijri) { + dynamic monthViewSettings, + bool isHijri, + ) { if (isHijri) { return false; } @@ -792,7 +898,11 @@ class DateRangePickerHelper { /// as leading date or not. /// Note: This method not applicable for month view. static bool isLeadingCellDate( - int index, int viewStartIndex, List visibleDates, dynamic view) { + int index, + int viewStartIndex, + List visibleDates, + dynamic view, + ) { final DateRangePickerView pickerView = getPickerView(view); if (pickerView == DateRangePickerView.month || pickerView == DateRangePickerView.year) { @@ -816,8 +926,14 @@ class DateRangePickerHelper { /// then the year view need to highlight selection because year view only /// consider the month value(max month as 12). /// Note: This method not applicable for month view. - static bool isBetweenMinMaxDateCell(dynamic date, dynamic minDate, - dynamic maxDate, bool enablePastDates, dynamic view, bool isHijri) { + static bool isBetweenMinMaxDateCell( + dynamic date, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + dynamic view, + bool isHijri, + ) { if (date == null || minDate == null || maxDate == null) { return true; } @@ -866,15 +982,23 @@ class DateRangePickerHelper { } if (pickerView == DateRangePickerView.year) { - final dynamic currentDate = - getDate(date.year, date.month + 1, 1, isHijri); + final dynamic currentDate = getDate( + date.year, + date.month + 1, + 1, + isHijri, + ); return addDays(currentDate, -1); } else if (pickerView == DateRangePickerView.decade) { final dynamic currentDate = getDate(date.year + 1, 1, 1, isHijri); return addDays(currentDate, -1); } else if (pickerView == DateRangePickerView.century) { - final dynamic currentDate = - getDate(((date.year ~/ 10) * 10) + 10, 1, 1, isHijri); + final dynamic currentDate = getDate( + ((date.year ~/ 10) * 10) + 10, + 1, + 1, + isHijri, + ); return addDays(currentDate, -1); } @@ -883,8 +1007,13 @@ class DateRangePickerHelper { /// Return index of the date value in dates collection. /// Return -1 when the date does not exist in dates collection. - static int getDateCellIndex(List dates, dynamic date, dynamic view, - {int viewStartIndex = -1, int viewEndIndex = -1}) { + static int getDateCellIndex( + List dates, + dynamic date, + dynamic view, { + int viewStartIndex = -1, + int viewEndIndex = -1, + }) { if (date == null) { return -1; } @@ -914,7 +1043,10 @@ class DateRangePickerHelper { /// Check the showWeekNumber is true or not and returns the position. static double getWeekNumberPanelWidth( - bool showWeekNumber, double width, bool isMobilePlatform) { + bool showWeekNumber, + double width, + bool isMobilePlatform, + ) { return showWeekNumber ? (width / (DateTime.daysPerWeek + 1)) / (isMobilePlatform ? 1.3 : 4) : 0; @@ -922,9 +1054,10 @@ class DateRangePickerHelper { /// Returns week number for the given date. static int getWeekNumberOfYear(dynamic date, bool isHijri) { - final dynamic yearEndDate = isHijri - ? HijriDateTime(date.year - 1, 12, 31) - : DateTime(date.year - 1, 12, 31); + final dynamic yearEndDate = + isHijri + ? HijriDateTime(date.year - 1, 12, 31) + : DateTime(date.year - 1, 12, 31); final int dayOfYear = date.difference(yearEndDate).inDays as int; int weekNumber = (dayOfYear - date.weekday + 10) ~/ 7; if (weekNumber < 1) { @@ -945,28 +1078,41 @@ class DateRangePickerHelper { } /// Draws the dashed line between given x positions. - static void drawDashedLine(double xPosition, double yPosition, - double endXPosition, Canvas canvas, Paint painter) { + static void drawDashedLine( + double xPosition, + double yPosition, + double endXPosition, + Canvas canvas, + Paint painter, + ) { const double dashWidth = 4, dashSpace = 5; while (xPosition < endXPosition) { - canvas.drawLine(Offset(xPosition, yPosition), - Offset(xPosition + dashWidth, yPosition), painter); + canvas.drawLine( + Offset(xPosition, yPosition), + Offset(xPosition + dashWidth, yPosition), + painter, + ); xPosition += dashWidth + dashSpace; } } /// Returns the dashed path for teh given path - static Path getDashedPath(Path sourcePath, bool isStartRange, bool isEndRange, - bool isRectSelection) { + static Path getDashedPath( + Path sourcePath, + bool isStartRange, + bool isEndRange, + bool isRectSelection, + ) { final Path dashedPath = Path(); final List array = [6, 5]; final List sourceMetrics = sourcePath.computeMetrics().toList(); final Rect sourceRect = sourcePath.getBounds(); - final double restrictXPosition = isRectSelection - ? isStartRange - ? sourceRect.right - : sourceRect.left - : -1; + final double restrictXPosition = + isRectSelection + ? isStartRange + ? sourceRect.right + : sourceRect.left + : -1; for (int i = 0; i < sourceMetrics.length; i++) { final PathMetric metric = sourceMetrics[i]; double distance = 0; @@ -975,8 +1121,10 @@ class DateRangePickerHelper { while (distance < metric.length) { final double length = array[j]; if (canDrawPath) { - final Path extractedPath = - metric.extractPath(distance, distance + length); + final Path extractedPath = metric.extractPath( + distance, + distance + length, + ); final Rect extractedRect = extractedPath.getBounds(); if ((isStartRange && extractedRect.right != restrictXPosition) || (isEndRange && extractedRect.left != restrictXPosition)) { diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/theme.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/theme.dart index 484162ec9..bdc18a303 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/theme.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/theme.dart @@ -20,18 +20,20 @@ class SfDateRangePickerThemeKey extends SfDateRangePickerThemeData { late final SfColorScheme colorScheme = SfTheme.colorScheme(context); @override - Color? get backgroundColor => Theme.of(context).useMaterial3 - ? (Theme.of(context).brightness == Brightness.light - ? const Color.fromRGBO(238, 232, 244, 1) - : const Color.fromRGBO(48, 45, 56, 1)) - : Colors.transparent; - - @override - Color? get headerBackgroundColor => Theme.of(context).useMaterial3 - ? (Theme.of(context).brightness == Brightness.light - ? const Color.fromRGBO(238, 232, 244, 1) - : const Color.fromRGBO(48, 45, 56, 1)) - : Theme.of(context).brightness == Brightness.light + Color? get backgroundColor => + Theme.of(context).useMaterial3 + ? (Theme.of(context).brightness == Brightness.light + ? const Color.fromRGBO(238, 232, 244, 1) + : const Color.fromRGBO(48, 45, 56, 1)) + : Colors.transparent; + + @override + Color? get headerBackgroundColor => + Theme.of(context).useMaterial3 + ? (Theme.of(context).brightness == Brightness.light + ? const Color.fromRGBO(238, 232, 244, 1) + : const Color.fromRGBO(48, 45, 56, 1)) + : Theme.of(context).brightness == Brightness.light ? Colors.white : Colors.grey[850]; diff --git a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/year_view.dart b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/year_view.dart index 34b88412e..2f0a4a2d6 100644 --- a/packages/syncfusion_flutter_datepicker/lib/src/date_picker/year_view.dart +++ b/packages/syncfusion_flutter_datepicker/lib/src/date_picker/year_view.dart @@ -12,42 +12,43 @@ class YearView extends StatefulWidget { /// Constructor for create the year view widget used to hold the year cell /// widgets. const YearView( - this.visibleDates, - this.cellStyle, - this.minDate, - this.maxDate, - this.enablePastDates, - this.todayHighlightColor, - this.selectionShape, - this.monthFormat, - this.isRtl, - this.datePickerTheme, - this.locale, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectionMode, - this.selectionRadius, - this.selectionNotifier, - this.textScaleFactor, - this.allowViewNavigation, - this.cellBuilder, - this.getPickerStateDetails, - this.view, - this.isHijri, - this.localizations, - this.navigationDirection, - this.width, - this.height, - this.disableDatesCollection, - this.extendableRangeSelectionDirection, - {super.key}); + this.visibleDates, + this.cellStyle, + this.minDate, + this.maxDate, + this.enablePastDates, + this.todayHighlightColor, + this.selectionShape, + this.monthFormat, + this.isRtl, + this.datePickerTheme, + this.locale, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectionMode, + this.selectionRadius, + this.selectionNotifier, + this.textScaleFactor, + this.allowViewNavigation, + this.cellBuilder, + this.getPickerStateDetails, + this.view, + this.isHijri, + this.localizations, + this.navigationDirection, + this.width, + this.height, + this.disableDatesCollection, + this.extendableRangeSelectionDirection, { + super.key, + }); /// Defines the year cell style. final dynamic cellStyle; @@ -180,11 +181,13 @@ class _YearViewState extends State { _children = []; widget.getPickerStateDetails(_pickerStateDetails); _selectedDate = _pickerStateDetails.selectedDate; - _selectedDates = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedDates, + ); _selectedRange = _pickerStateDetails.selectedRange; - _selectedRanges = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedRanges, + ); widget.selectionNotifier.addListener(_updateSelection); super.initState(); } @@ -231,10 +234,12 @@ class _YearViewState extends State { double width = widget.width; double height = widget.height; int viewCount = 1; - final bool isHorizontalMultiView = widget.enableMultiView && + final bool isHorizontalMultiView = + widget.enableMultiView && widget.navigationDirection == DateRangePickerNavigationDirection.horizontal; - final bool isVerticalMultiView = widget.enableMultiView && + final bool isVerticalMultiView = + widget.enableMultiView && widget.navigationDirection == DateRangePickerNavigationDirection.vertical; @@ -257,22 +262,27 @@ class _YearViewState extends State { final int viewStartIndex = j * visibleDatesCount; - final double viewStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + - (currentViewIndex * widget.multiViewSpacing); + final double viewStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + + (currentViewIndex * widget.multiViewSpacing); final double viewEndPosition = viewStartPosition + width; double xPosition = viewStartPosition; - double yPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + - (currentViewIndex * widget.multiViewSpacing); + double yPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + + (currentViewIndex * widget.multiViewSpacing); for (int i = 0; i < visibleDatesCount; i++) { int currentIndex = i; if (widget.isRtl) { final int rowIndex = i ~/ YearView.maxColumnCount; - currentIndex = DateRangePickerHelper.getRtlIndex( - YearView.maxColumnCount, i % YearView.maxColumnCount) + + currentIndex = + DateRangePickerHelper.getRtlIndex( + YearView.maxColumnCount, + i % YearView.maxColumnCount, + ) + (rowIndex * YearView.maxColumnCount); } @@ -283,26 +293,44 @@ class _YearViewState extends State { } if ((widget.enableMultiView || widget.isHijri) && - DateRangePickerHelper.isLeadingCellDate(currentIndex, - viewStartIndex, widget.visibleDates, widget.view)) { + DateRangePickerHelper.isLeadingCellDate( + currentIndex, + viewStartIndex, + widget.visibleDates, + widget.view, + )) { xPosition += cellWidth; continue; } final dynamic date = widget.visibleDates[currentIndex]; - final Widget child = widget.cellBuilder( - context, - widget.isHijri - ? HijriDateRangePickerCellDetails( - date: date, - visibleDates: widget.visibleDates.cast(), - bounds: Rect.fromLTWH( - xPosition, yPosition, cellWidth, cellHeight)) - : DateRangePickerCellDetails( - date: date, - visibleDates: widget.visibleDates.cast(), - bounds: Rect.fromLTWH(xPosition, yPosition, cellWidth, - cellHeight))) as Widget; + final Widget child = + widget.cellBuilder( + context, + widget.isHijri + ? HijriDateRangePickerCellDetails( + date: date, + visibleDates: + widget.visibleDates.cast(), + bounds: Rect.fromLTWH( + xPosition, + yPosition, + cellWidth, + cellHeight, + ), + ) + : DateRangePickerCellDetails( + date: date, + visibleDates: widget.visibleDates.cast(), + bounds: Rect.fromLTWH( + xPosition, + yPosition, + cellWidth, + cellHeight, + ), + ), + ) + as Widget; _children.add(child); xPosition += cellWidth; } @@ -317,183 +345,188 @@ class _YearViewState extends State { case DateRangePickerSelectionMode.single: { return _SingleSelectionRenderWidget( - widget.visibleDates, - widget.cellStyle, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.todayHighlightColor, - widget.selectionShape, - widget.monthFormat, - widget.isRtl, - widget.datePickerTheme, - widget.locale, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.allowViewNavigation ? null : _getSelectedDateValue(), - widget.selectionRadius, - widget.selectionNotifier, - widget.textScaleFactor, - widget.width, - widget.height, - widget.view, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.cellStyle, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.todayHighlightColor, + widget.selectionShape, + widget.monthFormat, + widget.isRtl, + widget.datePickerTheme, + widget.locale, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.allowViewNavigation ? null : _getSelectedDateValue(), + widget.selectionRadius, + widget.selectionNotifier, + widget.textScaleFactor, + widget.width, + widget.height, + widget.view, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.disableDatesCollection, + widgets: _children, + ); } case DateRangePickerSelectionMode.multiple: { return _MultiSelectionRenderWidget( - widget.visibleDates, - widget.cellStyle, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.todayHighlightColor, - widget.selectionShape, - widget.monthFormat, - widget.isRtl, - widget.datePickerTheme, - widget.locale, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.allowViewNavigation ? null : _getSelectedDateValue(), - widget.selectionRadius, - widget.selectionNotifier, - widget.textScaleFactor, - widget.width, - widget.height, - widget.view, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.cellStyle, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.todayHighlightColor, + widget.selectionShape, + widget.monthFormat, + widget.isRtl, + widget.datePickerTheme, + widget.locale, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.allowViewNavigation ? null : _getSelectedDateValue(), + widget.selectionRadius, + widget.selectionNotifier, + widget.textScaleFactor, + widget.width, + widget.height, + widget.view, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.disableDatesCollection, + widgets: _children, + ); } case DateRangePickerSelectionMode.range: { return _RangeSelectionRenderWidget( - widget.visibleDates, - widget.cellStyle, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.todayHighlightColor, - widget.selectionShape, - widget.monthFormat, - widget.isRtl, - widget.datePickerTheme, - widget.locale, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.allowViewNavigation ? null : _getSelectedDateValue(), - widget.selectionRadius, - widget.selectionNotifier, - widget.textScaleFactor, - widget.width, - widget.height, - widget.view, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.cellStyle, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.todayHighlightColor, + widget.selectionShape, + widget.monthFormat, + widget.isRtl, + widget.datePickerTheme, + widget.locale, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.allowViewNavigation ? null : _getSelectedDateValue(), + widget.selectionRadius, + widget.selectionNotifier, + widget.textScaleFactor, + widget.width, + widget.height, + widget.view, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.disableDatesCollection, + widgets: _children, + ); } case DateRangePickerSelectionMode.extendableRange: { return _ExtendableRangeSelectionRenderWidget( - widget.visibleDates, - widget.cellStyle, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.todayHighlightColor, - widget.selectionShape, - widget.monthFormat, - widget.isRtl, - widget.datePickerTheme, - widget.locale, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.allowViewNavigation ? null : _getSelectedDateValue(), - widget.selectionRadius, - widget.selectionNotifier, - widget.textScaleFactor, - widget.width, - widget.height, - widget.view, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.disableDatesCollection, - widget.extendableRangeSelectionDirection, - widgets: _children); + widget.visibleDates, + widget.cellStyle, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.todayHighlightColor, + widget.selectionShape, + widget.monthFormat, + widget.isRtl, + widget.datePickerTheme, + widget.locale, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.allowViewNavigation ? null : _getSelectedDateValue(), + widget.selectionRadius, + widget.selectionNotifier, + widget.textScaleFactor, + widget.width, + widget.height, + widget.view, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.disableDatesCollection, + widget.extendableRangeSelectionDirection, + widgets: _children, + ); } case DateRangePickerSelectionMode.multiRange: { return _MultiRangeSelectionRenderWidget( - widget.visibleDates, - widget.cellStyle, - widget.minDate, - widget.maxDate, - widget.enablePastDates, - widget.todayHighlightColor, - widget.selectionShape, - widget.monthFormat, - widget.isRtl, - widget.datePickerTheme, - widget.locale, - widget.mouseHoverPosition, - widget.enableMultiView, - widget.multiViewSpacing, - widget.selectionTextStyle, - widget.rangeTextStyle, - widget.selectionColor, - widget.startRangeSelectionColor, - widget.endRangeSelectionColor, - widget.rangeSelectionColor, - widget.allowViewNavigation ? null : _getSelectedDateValue(), - widget.selectionRadius, - widget.selectionNotifier, - widget.textScaleFactor, - widget.width, - widget.height, - widget.view, - widget.isHijri, - widget.localizations, - widget.navigationDirection, - widget.disableDatesCollection, - widgets: _children); + widget.visibleDates, + widget.cellStyle, + widget.minDate, + widget.maxDate, + widget.enablePastDates, + widget.todayHighlightColor, + widget.selectionShape, + widget.monthFormat, + widget.isRtl, + widget.datePickerTheme, + widget.locale, + widget.mouseHoverPosition, + widget.enableMultiView, + widget.multiViewSpacing, + widget.selectionTextStyle, + widget.rangeTextStyle, + widget.selectionColor, + widget.startRangeSelectionColor, + widget.endRangeSelectionColor, + widget.rangeSelectionColor, + widget.allowViewNavigation ? null : _getSelectedDateValue(), + widget.selectionRadius, + widget.selectionNotifier, + widget.textScaleFactor, + widget.width, + widget.height, + widget.view, + widget.isHijri, + widget.localizations, + widget.navigationDirection, + widget.disableDatesCollection, + widgets: _children, + ); } } } @@ -502,11 +535,13 @@ class _YearViewState extends State { widget.getPickerStateDetails(_pickerStateDetails); if (widget.allowViewNavigation) { _selectedDate = _pickerStateDetails.selectedDate; - _selectedDates = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedDates, + ); _selectedRange = _pickerStateDetails.selectedRange; - _selectedRanges = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedRanges, + ); return; } @@ -516,11 +551,13 @@ class _YearViewState extends State { _children.clear(); _selectedDate = _pickerStateDetails.selectedDate; - _selectedDates = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedDates); + _selectedDates = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedDates, + ); _selectedRange = _pickerStateDetails.selectedRange; - _selectedRanges = - DateRangePickerHelper.cloneList(_pickerStateDetails.selectedRanges); + _selectedRanges = DateRangePickerHelper.cloneList( + _pickerStateDetails.selectedRanges, + ); if (!isNeedSetState) { return; @@ -563,18 +600,24 @@ class _YearViewState extends State { case DateRangePickerSelectionMode.multiple: { return DateRangePickerHelper.isDateCollectionEquals( - _selectedDates, _pickerStateDetails.selectedDates); + _selectedDates, + _pickerStateDetails.selectedDates, + ); } case DateRangePickerSelectionMode.range: case DateRangePickerSelectionMode.extendableRange: { return DateRangePickerHelper.isRangeEquals( - _selectedRange, _pickerStateDetails.selectedRange); + _selectedRange, + _pickerStateDetails.selectedRange, + ); } case DateRangePickerSelectionMode.multiRange: { return DateRangePickerHelper.isDateRangesEquals( - _selectedRanges, _pickerStateDetails.selectedRanges); + _selectedRanges, + _pickerStateDetails.selectedRanges, + ); } } } @@ -582,39 +625,39 @@ class _YearViewState extends State { class _SingleSelectionRenderWidget extends MultiChildRenderObjectWidget { const _SingleSelectionRenderWidget( - this.visibleDates, - this.cellStyle, - this.minDate, - this.maxDate, - this.enablePastDates, - this.todayHighlightColor, - this.selectionShape, - this.monthFormat, - this.isRtl, - this.datePickerTheme, - this.locale, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectedDate, - this.selectionRadius, - this.selectionNotifier, - this.textScaleFactor, - this.width, - this.height, - this.view, - this.isHijri, - this.localizations, - this.navigationDirection, - this.disableDatesCollection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.cellStyle, + this.minDate, + this.maxDate, + this.enablePastDates, + this.todayHighlightColor, + this.selectionShape, + this.monthFormat, + this.isRtl, + this.datePickerTheme, + this.locale, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectedDate, + this.selectionRadius, + this.selectionNotifier, + this.textScaleFactor, + this.width, + this.height, + this.view, + this.isHijri, + this.localizations, + this.navigationDirection, + this.disableDatesCollection, { + required List widgets, + }) : super(children: widgets); /// Defines the year cell style. final dynamic cellStyle; @@ -705,41 +748,44 @@ class _SingleSelectionRenderWidget extends MultiChildRenderObjectWidget { @override _SingleSelectionRenderObject createRenderObject(BuildContext context) { return _SingleSelectionRenderObject( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - selectedDate, - disableDatesCollection); + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + selectedDate, + disableDatesCollection, + ); } @override void updateRenderObject( - BuildContext context, _SingleSelectionRenderObject renderObject) { + BuildContext context, + _SingleSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..cellStyle = cellStyle @@ -776,39 +822,39 @@ class _SingleSelectionRenderWidget extends MultiChildRenderObjectWidget { class _MultiSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MultiSelectionRenderWidget( - this.visibleDates, - this.cellStyle, - this.minDate, - this.maxDate, - this.enablePastDates, - this.todayHighlightColor, - this.selectionShape, - this.monthFormat, - this.isRtl, - this.datePickerTheme, - this.locale, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectedDates, - this.selectionRadius, - this.selectionNotifier, - this.textScaleFactor, - this.width, - this.height, - this.view, - this.isHijri, - this.localizations, - this.navigationDirection, - this.disableDatesCollection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.cellStyle, + this.minDate, + this.maxDate, + this.enablePastDates, + this.todayHighlightColor, + this.selectionShape, + this.monthFormat, + this.isRtl, + this.datePickerTheme, + this.locale, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectedDates, + this.selectionRadius, + this.selectionNotifier, + this.textScaleFactor, + this.width, + this.height, + this.view, + this.isHijri, + this.localizations, + this.navigationDirection, + this.disableDatesCollection, { + required List widgets, + }) : super(children: widgets); /// Defines the year cell style. final dynamic cellStyle; @@ -899,41 +945,44 @@ class _MultiSelectionRenderWidget extends MultiChildRenderObjectWidget { @override _MultipleSelectionRenderObject createRenderObject(BuildContext context) { return _MultipleSelectionRenderObject( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - selectedDates, - disableDatesCollection); + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + selectedDates, + disableDatesCollection, + ); } @override void updateRenderObject( - BuildContext context, _MultipleSelectionRenderObject renderObject) { + BuildContext context, + _MultipleSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..cellStyle = cellStyle @@ -970,39 +1019,39 @@ class _MultiSelectionRenderWidget extends MultiChildRenderObjectWidget { class _RangeSelectionRenderWidget extends MultiChildRenderObjectWidget { const _RangeSelectionRenderWidget( - this.visibleDates, - this.cellStyle, - this.minDate, - this.maxDate, - this.enablePastDates, - this.todayHighlightColor, - this.selectionShape, - this.monthFormat, - this.isRtl, - this.datePickerTheme, - this.locale, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectedRange, - this.selectionRadius, - this.selectionNotifier, - this.textScaleFactor, - this.width, - this.height, - this.view, - this.isHijri, - this.localizations, - this.navigationDirection, - this.disableDatesCollection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.cellStyle, + this.minDate, + this.maxDate, + this.enablePastDates, + this.todayHighlightColor, + this.selectionShape, + this.monthFormat, + this.isRtl, + this.datePickerTheme, + this.locale, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectedRange, + this.selectionRadius, + this.selectionNotifier, + this.textScaleFactor, + this.width, + this.height, + this.view, + this.isHijri, + this.localizations, + this.navigationDirection, + this.disableDatesCollection, { + required List widgets, + }) : super(children: widgets); /// Defines the year cell style. final dynamic cellStyle; @@ -1093,41 +1142,44 @@ class _RangeSelectionRenderWidget extends MultiChildRenderObjectWidget { @override _RangeSelectionRenderObject createRenderObject(BuildContext context) { return _RangeSelectionRenderObject( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - selectedRange, - disableDatesCollection); + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + selectedRange, + disableDatesCollection, + ); } @override void updateRenderObject( - BuildContext context, _RangeSelectionRenderObject renderObject) { + BuildContext context, + _RangeSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..cellStyle = cellStyle @@ -1165,40 +1217,40 @@ class _RangeSelectionRenderWidget extends MultiChildRenderObjectWidget { class _ExtendableRangeSelectionRenderWidget extends MultiChildRenderObjectWidget { const _ExtendableRangeSelectionRenderWidget( - this.visibleDates, - this.cellStyle, - this.minDate, - this.maxDate, - this.enablePastDates, - this.todayHighlightColor, - this.selectionShape, - this.monthFormat, - this.isRtl, - this.datePickerTheme, - this.locale, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectedRange, - this.selectionRadius, - this.selectionNotifier, - this.textScaleFactor, - this.width, - this.height, - this.view, - this.isHijri, - this.localizations, - this.navigationDirection, - this.disableDatesCollection, - this.extendableRangeSelectionDirection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.cellStyle, + this.minDate, + this.maxDate, + this.enablePastDates, + this.todayHighlightColor, + this.selectionShape, + this.monthFormat, + this.isRtl, + this.datePickerTheme, + this.locale, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectedRange, + this.selectionRadius, + this.selectionNotifier, + this.textScaleFactor, + this.width, + this.height, + this.view, + this.isHijri, + this.localizations, + this.navigationDirection, + this.disableDatesCollection, + this.extendableRangeSelectionDirection, { + required List widgets, + }) : super(children: widgets); /// Defines the year cell style. final dynamic cellStyle; @@ -1290,44 +1342,48 @@ class _ExtendableRangeSelectionRenderWidget @override _ExtendableRangeSelectionRenderObject createRenderObject( - BuildContext context) { + BuildContext context, + ) { return _ExtendableRangeSelectionRenderObject( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - selectedRange, - disableDatesCollection, - extendableRangeSelectionDirection); + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + selectedRange, + disableDatesCollection, + extendableRangeSelectionDirection, + ); } @override - void updateRenderObject(BuildContext context, - _ExtendableRangeSelectionRenderObject renderObject) { + void updateRenderObject( + BuildContext context, + _ExtendableRangeSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..cellStyle = cellStyle @@ -1365,39 +1421,39 @@ class _ExtendableRangeSelectionRenderWidget class _MultiRangeSelectionRenderWidget extends MultiChildRenderObjectWidget { const _MultiRangeSelectionRenderWidget( - this.visibleDates, - this.cellStyle, - this.minDate, - this.maxDate, - this.enablePastDates, - this.todayHighlightColor, - this.selectionShape, - this.monthFormat, - this.isRtl, - this.datePickerTheme, - this.locale, - this.mouseHoverPosition, - this.enableMultiView, - this.multiViewSpacing, - this.selectionTextStyle, - this.rangeTextStyle, - this.selectionColor, - this.startRangeSelectionColor, - this.endRangeSelectionColor, - this.rangeSelectionColor, - this.selectedRanges, - this.selectionRadius, - this.selectionNotifier, - this.textScaleFactor, - this.width, - this.height, - this.view, - this.isHijri, - this.localizations, - this.navigationDirection, - this.disableDatesCollection, - {required List widgets}) - : super(children: widgets); + this.visibleDates, + this.cellStyle, + this.minDate, + this.maxDate, + this.enablePastDates, + this.todayHighlightColor, + this.selectionShape, + this.monthFormat, + this.isRtl, + this.datePickerTheme, + this.locale, + this.mouseHoverPosition, + this.enableMultiView, + this.multiViewSpacing, + this.selectionTextStyle, + this.rangeTextStyle, + this.selectionColor, + this.startRangeSelectionColor, + this.endRangeSelectionColor, + this.rangeSelectionColor, + this.selectedRanges, + this.selectionRadius, + this.selectionNotifier, + this.textScaleFactor, + this.width, + this.height, + this.view, + this.isHijri, + this.localizations, + this.navigationDirection, + this.disableDatesCollection, { + required List widgets, + }) : super(children: widgets); /// Defines the year cell style. final dynamic cellStyle; @@ -1489,41 +1545,44 @@ class _MultiRangeSelectionRenderWidget extends MultiChildRenderObjectWidget { @override _MultiRangeSelectionRenderObject createRenderObject(BuildContext context) { return _MultiRangeSelectionRenderObject( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - selectedRanges, - disableDatesCollection); + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + selectedRanges, + disableDatesCollection, + ); } @override void updateRenderObject( - BuildContext context, _MultiRangeSelectionRenderObject renderObject) { + BuildContext context, + _MultiRangeSelectionRenderObject renderObject, + ) { renderObject ..visibleDates = visibleDates ..cellStyle = cellStyle @@ -1563,35 +1622,36 @@ class _DatePickerParentData extends ContainerBoxParentData {} abstract class _IYearViewRenderObject extends RenderBox with ContainerRenderObjectMixin { _IYearViewRenderObject( - this._visibleDates, - this._cellStyle, - this._minDate, - this._maxDate, - this._enablePastDates, - this._todayHighlightColor, - this._selectionShape, - this._isRtl, - this._datePickerTheme, - this._mouseHoverPosition, - this._enableMultiView, - this._multiViewSpacing, - this._selectionTextStyle, - this._rangeTextStyle, - this._selectionColor, - this._startRangeSelectionColor, - this._endRangeSelectionColor, - this._rangeSelectionColor, - this._selectionRadius, - this._textScaleFactor, - this._width, - this._height, - this._monthFormat, - this._locale, - this._view, - this._isHijri, - this._navigationDirection, - this.localizations, - this._disableDatesCollection); + this._visibleDates, + this._cellStyle, + this._minDate, + this._maxDate, + this._enablePastDates, + this._todayHighlightColor, + this._selectionShape, + this._isRtl, + this._datePickerTheme, + this._mouseHoverPosition, + this._enableMultiView, + this._multiViewSpacing, + this._selectionTextStyle, + this._rangeTextStyle, + this._selectionColor, + this._startRangeSelectionColor, + this._endRangeSelectionColor, + this._rangeSelectionColor, + this._selectionRadius, + this._textScaleFactor, + this._width, + this._height, + this._monthFormat, + this._locale, + this._view, + this._isHijri, + this._navigationDirection, + this.localizations, + this._disableDatesCollection, + ); DateRangePickerNavigationDirection _navigationDirection; @@ -2062,9 +2122,10 @@ abstract class _IYearViewRenderObject extends RenderBox /// Used to draw year cell text in month view. final TextPainter _textPainter = TextPainter( - textDirection: TextDirection.ltr, - maxLines: 2, - textWidthBasis: TextWidthBasis.longestLine); + textDirection: TextDirection.ltr, + maxLines: 2, + textWidthBasis: TextWidthBasis.longestLine, + ); /// Used to paint the selection of year cell and today highlight on all /// the selection mode. @@ -2102,8 +2163,10 @@ abstract class _IYearViewRenderObject extends RenderBox @override void performLayout() { final Size widgetSize = constraints.biggest; - size = Size(widgetSize.width.isInfinite ? width : widgetSize.width, - widgetSize.height.isInfinite ? height : widgetSize.height); + size = Size( + widgetSize.width.isInfinite ? width : widgetSize.width, + widgetSize.height.isInfinite ? height : widgetSize.height, + ); RenderBox? child = firstChild; if (child == null) { return; @@ -2123,11 +2186,14 @@ abstract class _IYearViewRenderObject extends RenderBox final double cellWidth = currentWidth / YearView.maxColumnCount; final double cellHeight = currentHeight / YearView.maxRowCount; while (child != null) { - child.layout(constraints.copyWith( + child.layout( + constraints.copyWith( minHeight: cellHeight, maxHeight: cellHeight, minWidth: cellWidth, - maxWidth: cellWidth)); + maxWidth: cellWidth, + ), + ); child = childAfter(child); } } @@ -2152,9 +2218,10 @@ abstract class _IYearViewRenderObject extends RenderBox final List semanticsNodes = []; for (int i = 0; i < semantics.length; i++) { final CustomPainterSemantics currentSemantics = semantics[i]; - final SemanticsNode newChild = _cacheNodes!.isNotEmpty - ? _cacheNodes!.removeAt(0) - : SemanticsNode(key: currentSemantics.key); + final SemanticsNode newChild = + _cacheNodes!.isNotEmpty + ? _cacheNodes!.removeAt(0) + : SemanticsNode(key: currentSemantics.key); final SemanticsProperties properties = currentSemantics.properties; final SemanticsConfiguration config = SemanticsConfiguration(); @@ -2200,16 +2267,17 @@ abstract class _IYearViewRenderObject extends RenderBox List getSelectedIndex(int viewStartIndex, int viewEndIndex); void drawSelection( - Canvas canvas, - double cellWidth, - int currentIndex, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double centerYPosition, - double xPosition, - double yPosition, - TextSpan yearText); + Canvas canvas, + double cellWidth, + int currentIndex, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double centerYPosition, + double xPosition, + double yPosition, + TextSpan yearText, + ); /// draw selection when the cell have custom widget. void drawCustomCellSelection(Canvas canvas, Rect rect, int index); @@ -2226,9 +2294,11 @@ abstract class _IYearViewRenderObject extends RenderBox double width = size.width; double height = size.height; double webUIPadding = 0; - final bool isHorizontalMultiView = _enableMultiView && + final bool isHorizontalMultiView = + _enableMultiView && _navigationDirection == DateRangePickerNavigationDirection.horizontal; - final bool isVerticalMultiView = _enableMultiView && + final bool isVerticalMultiView = + _enableMultiView && _navigationDirection == DateRangePickerNavigationDirection.vertical; if (isHorizontalMultiView) { webUIPadding = _multiViewSpacing; @@ -2248,54 +2318,99 @@ abstract class _IYearViewRenderObject extends RenderBox isRtl ? DateRangePickerHelper.getRtlIndex(count, j) : j; left = isRtl ? width - cellWidth : 0; top = 0; - final double startXPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + (currentViewIndex * webUIPadding); - final double startYPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + (currentViewIndex * webUIPadding); + final double startXPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + (currentViewIndex * webUIPadding); + final double startYPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + (currentViewIndex * webUIPadding); final int startIndex = j * datesCount; for (int i = 0; i < datesCount; i++) { final dynamic date = visibleDates[startIndex + i]; if (DateRangePickerHelper.isLeadingCellDate( - startIndex + i, startIndex, _visibleDates, _view)) { + startIndex + i, + startIndex, + _visibleDates, + _view, + )) { leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - isRtl, left, top, cellWidth, cellHeight, width); + isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; continue; } if (!DateRangePickerHelper.isBetweenMinMaxDateCell( - date, _minDate, _maxDate, _enablePastDates, _view, _isHijri) || + date, + _minDate, + _maxDate, + _enablePastDates, + _view, + _isHijri, + ) || DateRangePickerHelper.isDateWithInVisibleDates( - visibleDates, disableDatesCollection, date)) { - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(startXPosition + left, startYPosition + top, - cellWidth, cellHeight), - properties: SemanticsProperties( - label: '${getCellSemanticsText(date)}Disabled cell', - textDirection: TextDirection.ltr, + visibleDates, + disableDatesCollection, + date, + )) { + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + startXPosition + left, + startYPosition + top, + cellWidth, + cellHeight, + ), + properties: SemanticsProperties( + label: '${getCellSemanticsText(date)}Disabled cell', + textDirection: TextDirection.ltr, + ), ), - )); + ); leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - isRtl, left, top, cellWidth, cellHeight, width); + isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; continue; } - semanticsBuilder.add(CustomPainterSemantics( - rect: Rect.fromLTWH(startXPosition + left, startYPosition + top, - cellWidth, cellHeight), - properties: SemanticsProperties( - label: getCellSemanticsText(date), - textDirection: TextDirection.ltr, + semanticsBuilder.add( + CustomPainterSemantics( + rect: Rect.fromLTWH( + startXPosition + left, + startYPosition + top, + cellWidth, + cellHeight, + ), + properties: SemanticsProperties( + label: getCellSemanticsText(date), + textDirection: TextDirection.ltr, + ), ), - )); + ); leftAndTopValue = DateRangePickerHelper.getTopAndLeftValues( - isRtl, left, top, cellWidth, cellHeight, width); + isRtl, + left, + top, + cellWidth, + cellHeight, + width, + ); left = leftAndTopValue['left']!; top = leftAndTopValue['top']!; } @@ -2305,8 +2420,13 @@ abstract class _IYearViewRenderObject extends RenderBox } /// Return list of int value in between start and end date index value. - List _getRangeIndex(dynamic startDate, dynamic endDate, - DateRangePickerView pickerView, int viewStartIndex, int viewEndIndex) { + List _getRangeIndex( + dynamic startDate, + dynamic endDate, + DateRangePickerView pickerView, + int viewStartIndex, + int viewEndIndex, + ) { int startIndex = -1; int endIndex = -1; final List selectedIndex = []; @@ -2317,7 +2437,11 @@ abstract class _IYearViewRenderObject extends RenderBox dynamic endRangeDate; if (endDate != null) { endRangeDate = DateRangePickerHelper.getDate( - endDate.year, endDate.month, endDate.day, _isHijri); + endDate.year, + endDate.month, + endDate.day, + _isHijri, + ); } /// Check the start date as before of end date, if not then swap @@ -2330,7 +2454,10 @@ abstract class _IYearViewRenderObject extends RenderBox final dynamic viewStartDate = visibleDates[viewStartIndex]; final dynamic viewEndDate = DateRangePickerHelper.getLastDate( - visibleDates[viewEndIndex], pickerView, _isHijri); + visibleDates[viewEndIndex], + pickerView, + _isHijri, + ); if (startDate != null) { /// Assign start index as -1 when the start date before view start date. if (viewStartDate.isAfter(startDate) == true && @@ -2338,8 +2465,12 @@ abstract class _IYearViewRenderObject extends RenderBox startIndex = -1; } else { startIndex = DateRangePickerHelper.getDateCellIndex( - visibleDates, startDate, pickerView, - viewStartIndex: viewStartIndex, viewEndIndex: viewEndIndex); + visibleDates, + startDate, + pickerView, + viewStartIndex: viewStartIndex, + viewEndIndex: viewEndIndex, + ); } } @@ -2351,8 +2482,12 @@ abstract class _IYearViewRenderObject extends RenderBox endIndex = viewEndIndex + 1; } else { endIndex = DateRangePickerHelper.getDateCellIndex( - visibleDates, endRangeDate, _view, - viewStartIndex: viewStartIndex, viewEndIndex: viewEndIndex); + visibleDates, + endRangeDate, + _view, + viewStartIndex: viewStartIndex, + viewEndIndex: viewEndIndex, + ); } } @@ -2383,7 +2518,10 @@ abstract class _IYearViewRenderObject extends RenderBox monthFormat == null || monthFormat!.isEmpty ? 'MMM' : monthFormat!; if (isHijri) { return DateRangePickerHelper.getHijriMonthText( - date, localizations, format); + date, + localizations, + format, + ); } else { return DateFormat(format, locale.toString()).format(date); } @@ -2400,7 +2538,10 @@ abstract class _IYearViewRenderObject extends RenderBox if (_view == DateRangePickerView.year) { if (isHijri) { return DateRangePickerHelper.getHijriMonthText( - date, localizations, 'MMMM') + + date, + localizations, + 'MMMM', + ) + date.year.toString(); } else { return DateFormat('MMMM yyyy').format(date); @@ -2415,40 +2556,43 @@ abstract class _IYearViewRenderObject extends RenderBox } void _addMouseHovering( - Canvas canvas, - double cellWidth, - double cellHeight, - double centerYPosition, - int currentViewIndex, - double width, - double highlightPadding, - dynamic date, - double selectionPadding, - double textHalfHeight, - double webUIPadding, - double xOffset, - double xPosition, - double yOffset, - double yPosition) { + Canvas canvas, + double cellWidth, + double cellHeight, + double centerYPosition, + int currentViewIndex, + double width, + double highlightPadding, + dynamic date, + double selectionPadding, + double textHalfHeight, + double webUIPadding, + double xOffset, + double xPosition, + double yOffset, + double yPosition, + ) { if (xPosition <= _mouseHoverPosition.value!.offset!.dx && xPosition + cellWidth >= _mouseHoverPosition.value!.offset!.dx && yPosition <= _mouseHoverPosition.value!.offset!.dy && yPosition + cellHeight >= _mouseHoverPosition.value!.offset!.dy) { _todayHighlightPaint.style = PaintingStyle.fill; _todayHighlightPaint.strokeWidth = 2; - _todayHighlightPaint.color = selectionColor != null - ? selectionColor!.withValues(alpha: 0.4) - : datePickerTheme.selectionColor!.withValues(alpha: 0.4); + _todayHighlightPaint.color = + selectionColor != null + ? selectionColor!.withValues(alpha: 0.4) + : datePickerTheme.selectionColor!.withValues(alpha: 0.4); if (centerYPosition - textHalfHeight < highlightPadding / 2) { highlightPadding = (centerYPosition - textHalfHeight / 2) - 1; } final Rect rect = Rect.fromLTRB( - xPosition + selectionPadding, - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + cellWidth - selectionPadding, - yPosition + centerYPosition + highlightPadding + textHalfHeight); + xPosition + selectionPadding, + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + cellWidth - selectionPadding, + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); double cornerRadius = rect.height / 2; switch (selectionShape) { case DateRangePickerSelectionShape.rectangle: @@ -2461,26 +2605,28 @@ abstract class _IYearViewRenderObject extends RenderBox } canvas.drawRRect( - RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), - _todayHighlightPaint); + RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), + _todayHighlightPaint, + ); } } /// Add the hovering effect when the selection mode set as extendable and the /// hovering date extends the range. void _addRangeHoverEffect( - Canvas canvas, - double xPosition, - double yPosition, - int currentIndex, - List? hoveringIndex, - _IYearViewRenderObject yearView, - double centerYPosition, - double textHalfHeight, - double selectionPadding, - double highlightPadding, - double cellWidth, - double cellHeight) { + Canvas canvas, + double xPosition, + double yPosition, + int currentIndex, + List? hoveringIndex, + _IYearViewRenderObject yearView, + double centerYPosition, + double textHalfHeight, + double selectionPadding, + double highlightPadding, + double cellWidth, + double cellHeight, + ) { if (hoveringIndex == null || hoveringIndex.isEmpty) { return; } @@ -2507,44 +2653,69 @@ abstract class _IYearViewRenderObject extends RenderBox final double endYPosition = yPosition + centerYPosition + highlightPadding + textHalfHeight; final double endXPosition = xPosition + cellWidth; - final double cornerRadius = isBetweenRange - ? 0 - : (selectionShape == DateRangePickerSelectionShape.circle - ? (endYPosition - startYPosition) / 2 - : 3); + final double cornerRadius = + isBetweenRange + ? 0 + : (selectionShape == DateRangePickerSelectionShape.circle + ? (endYPosition - startYPosition) / 2 + : 3); _todayHighlightPaint.style = PaintingStyle.stroke; _todayHighlightPaint.strokeWidth = 1.0; - _todayHighlightPaint.color = selectionColor != null - ? selectionColor!.withValues(alpha: 0.4) - : datePickerTheme.selectionColor!.withValues(alpha: 0.4); + _todayHighlightPaint.color = + selectionColor != null + ? selectionColor!.withValues(alpha: 0.4) + : datePickerTheme.selectionColor!.withValues(alpha: 0.4); if (isStartRange) { - rect = Rect.fromLTRB(endXPosition - cornerRadius, startYPosition, - endXPosition, endYPosition); + rect = Rect.fromLTRB( + endXPosition - cornerRadius, + startYPosition, + endXPosition, + endYPosition, + ); } else if (isEndRange) { rect = Rect.fromLTRB( - xPosition, startYPosition, xPosition + cornerRadius, endYPosition); + xPosition, + startYPosition, + xPosition + cornerRadius, + endYPosition, + ); } else if (isBetweenRange) { rect = Rect.fromLTRB( - xPosition, startYPosition, xPosition + cellWidth, endYPosition); + xPosition, + startYPosition, + xPosition + cellWidth, + endYPosition, + ); } DateRangePickerHelper.drawDashedLine( - rect.left, rect.top, rect.right, canvas, _todayHighlightPaint); + rect.left, + rect.top, + rect.right, + canvas, + _todayHighlightPaint, + ); DateRangePickerHelper.drawDashedLine( - rect.left, rect.bottom, rect.right, canvas, _todayHighlightPaint); + rect.left, + rect.bottom, + rect.right, + canvas, + _todayHighlightPaint, + ); } void _drawTodayHighlight( - Canvas canvas, - double cellWidth, - double cellHeight, - double centerYPosition, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double xPosition, - double yPosition) { + Canvas canvas, + double cellWidth, + double cellHeight, + double centerYPosition, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double xPosition, + double yPosition, + ) { _todayHighlightPaint.color = todayHighlightColor ?? datePickerTheme.todayHighlightColor!; _todayHighlightPaint.isAntiAlias = true; @@ -2557,10 +2728,11 @@ abstract class _IYearViewRenderObject extends RenderBox } final Rect rect = Rect.fromLTRB( - xPosition + selectionPadding, - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + cellWidth - selectionPadding, - yPosition + centerYPosition + highlightPadding + textHalfHeight); + xPosition + selectionPadding, + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + cellWidth - selectionPadding, + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); double cornerRadius = rect.height / 2; switch (selectionShape) { case DateRangePickerSelectionShape.rectangle: @@ -2573,30 +2745,43 @@ abstract class _IYearViewRenderObject extends RenderBox } canvas.drawRRect( - RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), - _todayHighlightPaint); + RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), + _todayHighlightPaint, + ); } void _drawYearDecoration( - Canvas canvas, - Decoration yearDecoration, - double xPosition, - double yPosition, - double decorationPadding, - double cellWidth, - double cellHeight) { - final BoxPainter boxPainter = - yearDecoration.createBoxPainter(markNeedsPaint); + Canvas canvas, + Decoration yearDecoration, + double xPosition, + double yPosition, + double decorationPadding, + double cellWidth, + double cellHeight, + ) { + final BoxPainter boxPainter = yearDecoration.createBoxPainter( + markNeedsPaint, + ); boxPainter.paint( - canvas, - Offset(xPosition + decorationPadding, yPosition + decorationPadding), - ImageConfiguration( - size: Size(cellWidth - (2 * decorationPadding), - cellHeight - (2 * decorationPadding)))); + canvas, + Offset(xPosition + decorationPadding, yPosition + decorationPadding), + ImageConfiguration( + size: Size( + cellWidth - (2 * decorationPadding), + cellHeight - (2 * decorationPadding), + ), + ), + ); } - TextStyle _updateCellTextStyle(int j, bool isCurrentDate, bool isSelected, - bool isEnableDate, bool isActiveDate, bool isDisabledDate) { + TextStyle _updateCellTextStyle( + int j, + bool isCurrentDate, + bool isSelected, + bool isEnableDate, + bool isActiveDate, + bool isDisabledDate, + ) { if (!isEnableDate || isDisabledDate) { return datePickerTheme.disabledCellTextStyle!; } @@ -2616,8 +2801,13 @@ abstract class _IYearViewRenderObject extends RenderBox return datePickerTheme.cellTextStyle!; } - Decoration? _updateCellDecoration(int j, bool isCurrentDate, - bool isEnableDate, bool isActiveDate, bool isDisabledDate) { + Decoration? _updateCellDecoration( + int j, + bool isCurrentDate, + bool isEnableDate, + bool isActiveDate, + bool isDisabledDate, + ) { if ((!isEnableDate || isDisabledDate) && cellStyle.disabledDatesDecoration != null) { return cellStyle.disabledDatesDecoration as Decoration?; @@ -2639,66 +2829,67 @@ abstract class _IYearViewRenderObject extends RenderBox class _SingleSelectionRenderObject extends _IYearViewRenderObject { _SingleSelectionRenderObject( - List visibleDates, - dynamic cellStyle, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - Color? todayHighlightColor, - DateRangePickerSelectionShape selectionShape, - bool isRtl, - SfDateRangePickerThemeData datePickerTheme, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - double selectionRadius, - double textScaleFactor, - double width, - double height, - String? monthFormat, - Locale locale, - DateRangePickerView view, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedDate, - List? disableDatesCollection) - : super( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - disableDatesCollection); + List visibleDates, + dynamic cellStyle, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + Color? todayHighlightColor, + DateRangePickerSelectionShape selectionShape, + bool isRtl, + SfDateRangePickerThemeData datePickerTheme, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + double selectionRadius, + double textScaleFactor, + double width, + double height, + String? monthFormat, + Locale locale, + DateRangePickerView view, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedDate, + List? disableDatesCollection, + ) : super( + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + disableDatesCollection, + ); dynamic _selectedDate; @@ -2724,16 +2915,17 @@ class _SingleSelectionRenderObject extends _IYearViewRenderObject { @override void drawSelection( - Canvas canvas, - double cellWidth, - int currentIndex, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double centerYPosition, - double xPosition, - double yPosition, - TextSpan yearText) { + Canvas canvas, + double cellWidth, + int currentIndex, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double centerYPosition, + double xPosition, + double yPosition, + TextSpan yearText, + ) { _todayHighlightPaint.isAntiAlias = true; _todayHighlightPaint.style = PaintingStyle.fill; final double maximumHighlight = @@ -2743,10 +2935,11 @@ class _SingleSelectionRenderObject extends _IYearViewRenderObject { } final Rect rect = Rect.fromLTRB( - xPosition + selectionPadding, - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + cellWidth - selectionPadding, - yPosition + centerYPosition + highlightPadding + textHalfHeight); + xPosition + selectionPadding, + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + cellWidth - selectionPadding, + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); final double cornerRadius = selectionShape == DateRangePickerSelectionShape.circle ? rect.height / 2 @@ -2755,8 +2948,9 @@ class _SingleSelectionRenderObject extends _IYearViewRenderObject { selectionColor ?? datePickerTheme.selectionColor!; canvas.drawRRect( - RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), - _todayHighlightPaint); + RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), + _todayHighlightPaint, + ); } @override @@ -2776,8 +2970,12 @@ class _SingleSelectionRenderObject extends _IYearViewRenderObject { } final int index = DateRangePickerHelper.getDateCellIndex( - visibleDates, _selectedDate, _view, - viewStartIndex: viewStartIndex, viewEndIndex: viewEndIndex); + visibleDates, + _selectedDate, + _view, + viewStartIndex: viewStartIndex, + viewEndIndex: viewEndIndex, + ); if (index != -1) { selectedIndex.add(index); } @@ -2793,66 +2991,67 @@ class _SingleSelectionRenderObject extends _IYearViewRenderObject { class _MultipleSelectionRenderObject extends _IYearViewRenderObject { _MultipleSelectionRenderObject( - List visibleDates, - dynamic cellStyle, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - Color? todayHighlightColor, - DateRangePickerSelectionShape selectionShape, - bool isRtl, - SfDateRangePickerThemeData datePickerTheme, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - double selectionRadius, - double textScaleFactor, - double width, - double height, - String? monthFormat, - Locale locale, - DateRangePickerView view, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedDates, - List? disableDatesCollection) - : super( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - disableDatesCollection); + List visibleDates, + dynamic cellStyle, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + Color? todayHighlightColor, + DateRangePickerSelectionShape selectionShape, + bool isRtl, + SfDateRangePickerThemeData datePickerTheme, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + double selectionRadius, + double textScaleFactor, + double width, + double height, + String? monthFormat, + Locale locale, + DateRangePickerView view, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedDates, + List? disableDatesCollection, + ) : super( + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + disableDatesCollection, + ); List? _selectedDates; @@ -2878,16 +3077,17 @@ class _MultipleSelectionRenderObject extends _IYearViewRenderObject { @override void drawSelection( - Canvas canvas, - double cellWidth, - int currentIndex, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double centerYPosition, - double xPosition, - double yPosition, - TextSpan yearText) { + Canvas canvas, + double cellWidth, + int currentIndex, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double centerYPosition, + double xPosition, + double yPosition, + TextSpan yearText, + ) { _todayHighlightPaint.isAntiAlias = true; _todayHighlightPaint.style = PaintingStyle.fill; final double maximumHighlight = @@ -2897,10 +3097,11 @@ class _MultipleSelectionRenderObject extends _IYearViewRenderObject { } final Rect rect = Rect.fromLTRB( - xPosition + selectionPadding, - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + cellWidth - selectionPadding, - yPosition + centerYPosition + highlightPadding + textHalfHeight); + xPosition + selectionPadding, + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + cellWidth - selectionPadding, + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); final double cornerRadius = selectionShape == DateRangePickerSelectionShape.circle ? rect.height / 2 @@ -2909,8 +3110,9 @@ class _MultipleSelectionRenderObject extends _IYearViewRenderObject { selectionColor ?? datePickerTheme.selectionColor!; canvas.drawRRect( - RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), - _todayHighlightPaint); + RRect.fromRectAndRadius(rect, Radius.circular(cornerRadius)), + _todayHighlightPaint, + ); } @override @@ -2930,8 +3132,12 @@ class _MultipleSelectionRenderObject extends _IYearViewRenderObject { } for (int i = 0; i < _selectedDates!.length; i++) { final int index = DateRangePickerHelper.getDateCellIndex( - visibleDates, _selectedDates![i], _view, - viewStartIndex: viewStartIndex, viewEndIndex: viewEndIndex); + visibleDates, + _selectedDates![i], + _view, + viewStartIndex: viewStartIndex, + viewEndIndex: viewEndIndex, + ); if (index != -1) { selectedIndex.add(index); } @@ -2948,66 +3154,67 @@ class _MultipleSelectionRenderObject extends _IYearViewRenderObject { class _RangeSelectionRenderObject extends _IYearViewRenderObject { _RangeSelectionRenderObject( - List visibleDates, - dynamic cellStyle, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - Color? todayHighlightColor, - DateRangePickerSelectionShape selectionShape, - bool isRtl, - SfDateRangePickerThemeData datePickerTheme, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - double selectionRadius, - double textScaleFactor, - double width, - double height, - String? monthFormat, - Locale locale, - DateRangePickerView view, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedRange, - List? disableDatesCollection) - : super( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - disableDatesCollection); + List visibleDates, + dynamic cellStyle, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + Color? todayHighlightColor, + DateRangePickerSelectionShape selectionShape, + bool isRtl, + SfDateRangePickerThemeData datePickerTheme, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + double selectionRadius, + double textScaleFactor, + double width, + double height, + String? monthFormat, + Locale locale, + DateRangePickerView view, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedRange, + List? disableDatesCollection, + ) : super( + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + disableDatesCollection, + ); dynamic _selectedRange; @@ -3036,16 +3243,17 @@ class _RangeSelectionRenderObject extends _IYearViewRenderObject { @override void drawSelection( - Canvas canvas, - double cellWidth, - int currentIndex, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double centerYPosition, - double xPosition, - double yPosition, - TextSpan yearText) { + Canvas canvas, + double cellWidth, + int currentIndex, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double centerYPosition, + double xPosition, + double yPosition, + TextSpan yearText, + ) { _todayHighlightPaint.isAntiAlias = true; _todayHighlightPaint.style = PaintingStyle.fill; final double maximumHighlight = @@ -3061,17 +3269,19 @@ class _RangeSelectionRenderObject extends _IYearViewRenderObject { final bool isBetweenRange = selectionDetails[3]; final Rect rect = Rect.fromLTRB( - xPosition + (isBetweenRange || isEndRange ? 0 : selectionPadding), - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + - cellWidth - - (isBetweenRange || isStartRange ? 0 : selectionPadding), - yPosition + centerYPosition + highlightPadding + textHalfHeight); - final double cornerRadius = isBetweenRange - ? 0 - : (selectionShape == DateRangePickerSelectionShape.circle - ? rect.height / 2 - : 3); + xPosition + (isBetweenRange || isEndRange ? 0 : selectionPadding), + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + + cellWidth - + (isBetweenRange || isStartRange ? 0 : selectionPadding), + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); + final double cornerRadius = + isBetweenRange + ? 0 + : (selectionShape == DateRangePickerSelectionShape.circle + ? rect.height / 2 + : 3); final double leftRadius = isStartRange || isSelectedDate ? cornerRadius : 0; final double rightRadius = isEndRange || isSelectedDate ? cornerRadius : 0; if (isSelectedDate) { @@ -3096,12 +3306,15 @@ class _RangeSelectionRenderObject extends _IYearViewRenderObject { } canvas.drawRRect( - RRect.fromRectAndCorners(rect, - topLeft: Radius.circular(leftRadius), - bottomLeft: Radius.circular(leftRadius), - bottomRight: Radius.circular(rightRadius), - topRight: Radius.circular(rightRadius)), - _todayHighlightPaint); + RRect.fromRectAndCorners( + rect, + topLeft: Radius.circular(leftRadius), + bottomLeft: Radius.circular(leftRadius), + bottomRight: Radius.circular(rightRadius), + topRight: Radius.circular(rightRadius), + ), + _todayHighlightPaint, + ); } @override @@ -3179,7 +3392,8 @@ class _RangeSelectionRenderObject extends _IYearViewRenderObject { final dynamic startDate = _selectedRange.startDate; final dynamic endDate = _selectedRange.endDate ?? _selectedRange.startDate; _selectedIndex.addAll( - _getRangeIndex(startDate, endDate, view, viewStartIndex, viewEndIndex)); + _getRangeIndex(startDate, endDate, view, viewStartIndex, viewEndIndex), + ); return _selectedIndex; } @@ -3197,67 +3411,68 @@ class _RangeSelectionRenderObject extends _IYearViewRenderObject { class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { _ExtendableRangeSelectionRenderObject( - List visibleDates, - dynamic cellStyle, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - Color? todayHighlightColor, - DateRangePickerSelectionShape selectionShape, - bool isRtl, - SfDateRangePickerThemeData datePickerTheme, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - double selectionRadius, - double textScaleFactor, - double width, - double height, - String? monthFormat, - Locale locale, - DateRangePickerView view, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedRange, - List? disableDatesCollection, - this._extendableRangeSelectionDirection) - : super( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - disableDatesCollection); + List visibleDates, + dynamic cellStyle, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + Color? todayHighlightColor, + DateRangePickerSelectionShape selectionShape, + bool isRtl, + SfDateRangePickerThemeData datePickerTheme, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + double selectionRadius, + double textScaleFactor, + double width, + double height, + String? monthFormat, + Locale locale, + DateRangePickerView view, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedRange, + List? disableDatesCollection, + this._extendableRangeSelectionDirection, + ) : super( + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + disableDatesCollection, + ); dynamic _selectedRange; @@ -3282,7 +3497,8 @@ class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { _extendableRangeSelectionDirection; set extendableRangeSelectionDirection( - ExtendableRangeSelectionDirection value) { + ExtendableRangeSelectionDirection value, + ) { if (_extendableRangeSelectionDirection == value) { return; } @@ -3305,16 +3521,17 @@ class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { @override void drawSelection( - Canvas canvas, - double cellWidth, - int currentIndex, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double centerYPosition, - double xPosition, - double yPosition, - TextSpan yearText) { + Canvas canvas, + double cellWidth, + int currentIndex, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double centerYPosition, + double xPosition, + double yPosition, + TextSpan yearText, + ) { _todayHighlightPaint.isAntiAlias = true; _todayHighlightPaint.style = PaintingStyle.fill; final double maximumHighlight = @@ -3323,25 +3540,29 @@ class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { highlightPadding = maximumHighlight; } - final List selectionDetails = - _getSelectedRangePosition(currentIndex, _selectedIndex); + final List selectionDetails = _getSelectedRangePosition( + currentIndex, + _selectedIndex, + ); final bool isSelectedDate = selectionDetails[0]; final bool isStartRange = selectionDetails[1]; final bool isEndRange = selectionDetails[2]; final bool isBetweenRange = selectionDetails[3]; final Rect rect = Rect.fromLTRB( - xPosition + (isBetweenRange || isEndRange ? 0 : selectionPadding), - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + - cellWidth - - (isBetweenRange || isStartRange ? 0 : selectionPadding), - yPosition + centerYPosition + highlightPadding + textHalfHeight); - final double cornerRadius = isBetweenRange - ? 0 - : (selectionShape == DateRangePickerSelectionShape.circle - ? rect.height / 2 - : 3); + xPosition + (isBetweenRange || isEndRange ? 0 : selectionPadding), + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + + cellWidth - + (isBetweenRange || isStartRange ? 0 : selectionPadding), + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); + final double cornerRadius = + isBetweenRange + ? 0 + : (selectionShape == DateRangePickerSelectionShape.circle + ? rect.height / 2 + : 3); final double leftRadius = isStartRange || isSelectedDate ? cornerRadius : 0; final double rightRadius = isEndRange || isSelectedDate ? cornerRadius : 0; if (isSelectedDate) { @@ -3366,20 +3587,25 @@ class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { } canvas.drawRRect( - RRect.fromRectAndCorners(rect, - topLeft: Radius.circular(leftRadius), - bottomLeft: Radius.circular(leftRadius), - bottomRight: Radius.circular(rightRadius), - topRight: Radius.circular(rightRadius)), - _todayHighlightPaint); + RRect.fromRectAndCorners( + rect, + topLeft: Radius.circular(leftRadius), + bottomLeft: Radius.circular(leftRadius), + bottomRight: Radius.circular(rightRadius), + topRight: Radius.circular(rightRadius), + ), + _todayHighlightPaint, + ); } @override void drawCustomCellSelection(Canvas canvas, Rect rect, int index) { _todayHighlightPaint.isAntiAlias = true; _todayHighlightPaint.style = PaintingStyle.fill; - final List selectionDetails = - _getSelectedRangePosition(index, _selectedIndex); + final List selectionDetails = _getSelectedRangePosition( + index, + _selectedIndex, + ); final bool isSelectedDate = selectionDetails[0]; final bool isStartRange = selectionDetails[1]; final bool isEndRange = selectionDetails[2]; @@ -3450,7 +3676,8 @@ class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { final dynamic startDate = _selectedRange.startDate; final dynamic endDate = _selectedRange.endDate ?? _selectedRange.startDate; _selectedIndex.addAll( - _getRangeIndex(startDate, endDate, view, viewStartIndex, viewEndIndex)); + _getRangeIndex(startDate, endDate, view, viewStartIndex, viewEndIndex), + ); return _selectedIndex; } @@ -3461,74 +3688,77 @@ class _ExtendableRangeSelectionRenderObject extends _IYearViewRenderObject { /// index is either it is start or end range or selected date and is between /// range as a list, in this list the isBetweenRange boolean index is 3, /// hence we used 3 here. - final List selectionDetails = - _getSelectedRangePosition(index, _selectedIndex); + final List selectionDetails = _getSelectedRangePosition( + index, + _selectedIndex, + ); return selectionDetails[3]; } } class _MultiRangeSelectionRenderObject extends _IYearViewRenderObject { _MultiRangeSelectionRenderObject( - List visibleDates, - dynamic cellStyle, - dynamic minDate, - dynamic maxDate, - bool enablePastDates, - Color? todayHighlightColor, - DateRangePickerSelectionShape selectionShape, - bool isRtl, - SfDateRangePickerThemeData datePickerTheme, - ValueNotifier mouseHoverPosition, - bool enableMultiView, - double multiViewSpacing, - TextStyle? selectionTextStyle, - TextStyle? rangeTextStyle, - Color? selectionColor, - Color? startRangeSelectionColor, - Color? endRangeSelectionColor, - Color? rangeSelectionColor, - double selectionRadius, - double textScaleFactor, - double width, - double height, - String? monthFormat, - Locale locale, - DateRangePickerView view, - bool isHijri, - DateRangePickerNavigationDirection navigationDirection, - SfLocalizations localizations, - this._selectedRanges, - List? disableDatesCollection) - : super( - visibleDates, - cellStyle, - minDate, - maxDate, - enablePastDates, - todayHighlightColor, - selectionShape, - isRtl, - datePickerTheme, - mouseHoverPosition, - enableMultiView, - multiViewSpacing, - selectionTextStyle, - rangeTextStyle, - selectionColor, - startRangeSelectionColor, - endRangeSelectionColor, - rangeSelectionColor, - selectionRadius, - textScaleFactor, - width, - height, - monthFormat, - locale, - view, - isHijri, - navigationDirection, - localizations, - disableDatesCollection); + List visibleDates, + dynamic cellStyle, + dynamic minDate, + dynamic maxDate, + bool enablePastDates, + Color? todayHighlightColor, + DateRangePickerSelectionShape selectionShape, + bool isRtl, + SfDateRangePickerThemeData datePickerTheme, + ValueNotifier mouseHoverPosition, + bool enableMultiView, + double multiViewSpacing, + TextStyle? selectionTextStyle, + TextStyle? rangeTextStyle, + Color? selectionColor, + Color? startRangeSelectionColor, + Color? endRangeSelectionColor, + Color? rangeSelectionColor, + double selectionRadius, + double textScaleFactor, + double width, + double height, + String? monthFormat, + Locale locale, + DateRangePickerView view, + bool isHijri, + DateRangePickerNavigationDirection navigationDirection, + SfLocalizations localizations, + this._selectedRanges, + List? disableDatesCollection, + ) : super( + visibleDates, + cellStyle, + minDate, + maxDate, + enablePastDates, + todayHighlightColor, + selectionShape, + isRtl, + datePickerTheme, + mouseHoverPosition, + enableMultiView, + multiViewSpacing, + selectionTextStyle, + rangeTextStyle, + selectionColor, + startRangeSelectionColor, + endRangeSelectionColor, + rangeSelectionColor, + selectionRadius, + textScaleFactor, + width, + height, + monthFormat, + locale, + view, + isHijri, + navigationDirection, + localizations, + disableDatesCollection, + ); List? _selectedRanges; @@ -3557,16 +3787,17 @@ class _MultiRangeSelectionRenderObject extends _IYearViewRenderObject { @override void drawSelection( - Canvas canvas, - double cellWidth, - int currentIndex, - double highlightPadding, - double selectionPadding, - double textHalfHeight, - double centerYPosition, - double xPosition, - double yPosition, - TextSpan yearText) { + Canvas canvas, + double cellWidth, + int currentIndex, + double highlightPadding, + double selectionPadding, + double textHalfHeight, + double centerYPosition, + double xPosition, + double yPosition, + TextSpan yearText, + ) { _todayHighlightPaint.isAntiAlias = true; _todayHighlightPaint.style = PaintingStyle.fill; final double maximumHighlight = @@ -3582,17 +3813,19 @@ class _MultiRangeSelectionRenderObject extends _IYearViewRenderObject { final bool isBetweenRange = selectionDetails[3]; final Rect rect = Rect.fromLTRB( - xPosition + (isBetweenRange || isEndRange ? 0 : selectionPadding), - yPosition + centerYPosition - highlightPadding - textHalfHeight, - xPosition + - cellWidth - - (isBetweenRange || isStartRange ? 0 : selectionPadding), - yPosition + centerYPosition + highlightPadding + textHalfHeight); - final double cornerRadius = isBetweenRange - ? 0 - : (selectionShape == DateRangePickerSelectionShape.circle - ? rect.height / 2 - : 3); + xPosition + (isBetweenRange || isEndRange ? 0 : selectionPadding), + yPosition + centerYPosition - highlightPadding - textHalfHeight, + xPosition + + cellWidth - + (isBetweenRange || isStartRange ? 0 : selectionPadding), + yPosition + centerYPosition + highlightPadding + textHalfHeight, + ); + final double cornerRadius = + isBetweenRange + ? 0 + : (selectionShape == DateRangePickerSelectionShape.circle + ? rect.height / 2 + : 3); final double leftRadius = isStartRange || isSelectedDate ? cornerRadius : 0; final double rightRadius = isEndRange || isSelectedDate ? cornerRadius : 0; if (isSelectedDate) { @@ -3617,12 +3850,15 @@ class _MultiRangeSelectionRenderObject extends _IYearViewRenderObject { } canvas.drawRRect( - RRect.fromRectAndCorners(rect, - topLeft: Radius.circular(leftRadius), - bottomLeft: Radius.circular(leftRadius), - bottomRight: Radius.circular(rightRadius), - topRight: Radius.circular(rightRadius)), - _todayHighlightPaint); + RRect.fromRectAndCorners( + rect, + topLeft: Radius.circular(leftRadius), + bottomLeft: Radius.circular(leftRadius), + bottomRight: Radius.circular(rightRadius), + topRight: Radius.circular(rightRadius), + ), + _todayHighlightPaint, + ); } @override @@ -3711,7 +3947,12 @@ class _MultiRangeSelectionRenderObject extends _IYearViewRenderObject { final dynamic startDate = range.startDate; final dynamic endDate = range.endDate ?? range.startDate; final List index = _getRangeIndex( - startDate, endDate, view, viewStartIndex, viewEndIndex); + startDate, + endDate, + view, + viewStartIndex, + viewEndIndex, + ); _rangesIndex.add(index); selectedIndex.addAll(index); } @@ -3731,10 +3972,16 @@ class _MultiRangeSelectionRenderObject extends _IYearViewRenderObject { } /// Check the date cell placed in current view or not. -bool _isCurrentViewDateCell(dynamic date, int index, List visibleDates, - bool enableMultiView, dynamic view) { - final DateRangePickerView pickerView = - DateRangePickerHelper.getPickerView(view); +bool _isCurrentViewDateCell( + dynamic date, + int index, + List visibleDates, + bool enableMultiView, + dynamic view, +) { + final DateRangePickerView pickerView = DateRangePickerHelper.getPickerView( + view, + ); if (pickerView == DateRangePickerView.year) { return true; @@ -3755,16 +4002,21 @@ bool _isCurrentViewDateCell(dynamic date, int index, List visibleDates, /// Draws the year cell on canvas based on selection mode. void _drawYearCells( - PaintingContext context, Size size, _IYearViewRenderObject yearView) { + PaintingContext context, + Size size, + _IYearViewRenderObject yearView, +) { final Canvas canvas = context.canvas; double webUIPadding = 0; int count = 1; double width = size.width; double height = size.height; - final bool isHorizontalMultiView = yearView.enableMultiView && + final bool isHorizontalMultiView = + yearView.enableMultiView && yearView.navigationDirection == DateRangePickerNavigationDirection.horizontal; - final bool isVerticalMultiView = yearView.enableMultiView && + final bool isVerticalMultiView = + yearView.enableMultiView && yearView.navigationDirection == DateRangePickerNavigationDirection.vertical; if (isHorizontalMultiView) { @@ -3783,8 +4035,9 @@ void _drawYearCells( double xPosition = 0, yPosition; final bool isNeedWidgetPaint = yearView.childCount != 0; - final DateRangePickerView view = - DateRangePickerHelper.getPickerView(yearView.view); + final DateRangePickerView view = DateRangePickerHelper.getPickerView( + yearView.view, + ); if (isNeedWidgetPaint) { RenderBox? child = yearView.firstChild; @@ -3796,23 +4049,30 @@ void _drawYearCells( final int viewEndIndex = ((j + 1) * visibleDatesCount) - 1; /// Calculate the selected index values based on selected date property. - final List selectedIndex = - yearView.getSelectedIndex(viewStartIndex, viewEndIndex); + final List selectedIndex = yearView.getSelectedIndex( + viewStartIndex, + viewEndIndex, + ); - final double viewStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + (currentViewIndex * webUIPadding); + final double viewStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + (currentViewIndex * webUIPadding); final double viewEndPosition = viewStartPosition + width; xPosition = viewStartPosition; - yPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + (currentViewIndex * webUIPadding); + yPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + (currentViewIndex * webUIPadding); for (int i = 0; i < visibleDatesCount; i++) { int currentIndex = i; if (yearView.isRtl) { final int rowIndex = i ~/ YearView.maxColumnCount; - currentIndex = DateRangePickerHelper.getRtlIndex( - YearView.maxColumnCount, i % YearView.maxColumnCount) + + currentIndex = + DateRangePickerHelper.getRtlIndex( + YearView.maxColumnCount, + i % YearView.maxColumnCount, + ) + (rowIndex * YearView.maxColumnCount); } @@ -3824,7 +4084,11 @@ void _drawYearCells( if ((yearView.enableMultiView || yearView.isHijri) && DateRangePickerHelper.isLeadingCellDate( - currentIndex, viewStartIndex, yearView.visibleDates, view)) { + currentIndex, + viewStartIndex, + yearView.visibleDates, + view, + )) { xPosition += cellWidth; continue; } @@ -3832,33 +4096,43 @@ void _drawYearCells( final dynamic date = yearView.visibleDates[currentIndex]; final bool isSelected = selectedIndex.contains(currentIndex); final bool isEnableDate = DateRangePickerHelper.isBetweenMinMaxDateCell( - date, - yearView.minDate, - yearView.maxDate, - yearView.enablePastDates, - view, - yearView.isHijri); + date, + yearView.minDate, + yearView.maxDate, + yearView.enablePastDates, + view, + yearView.isHijri, + ); bool isDisabledDate = DateRangePickerHelper.isDateWithInVisibleDates( - yearView.visibleDates, yearView.disableDatesCollection, date); + yearView.visibleDates, + yearView.disableDatesCollection, + date, + ); if (!isDisabledDate && yearView is _ExtendableRangeSelectionRenderObject && yearView.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - yearView.selectedRange, - date, - yearView.extendableRangeSelectionDirection, - view, - yearView.isHijri, - isInBetweenEnabled: true)) { + yearView.selectedRange, + date, + yearView.extendableRangeSelectionDirection, + view, + yearView.isHijri, + isInBetweenEnabled: true, + )) { isDisabledDate = true; } if (isSelected && isEnableDate && !isDisabledDate) { yearView.drawCustomCellSelection( - canvas, - Rect.fromLTRB(xPosition, yPosition, xPosition + cellWidth, - yPosition + cellHeight), - currentIndex); + canvas, + Rect.fromLTRB( + xPosition, + yPosition, + xPosition + cellWidth, + yPosition + cellHeight, + ), + currentIndex, + ); } child!.paint(context, Offset(xPosition, yPosition)); @@ -3879,14 +4153,20 @@ void _drawYearCells( yearView._todayHighlightPaint.color = yearView.selectionColor != null ? yearView.selectionColor!.withValues(alpha: 0.4) - : yearView.datePickerTheme.selectionColor! - .withValues(alpha: 0.4); - - final Rect rect = Rect.fromLTRB(xPosition, yPosition, - xPosition + cellWidth, yPosition + cellHeight); + : yearView.datePickerTheme.selectionColor!.withValues( + alpha: 0.4, + ); + + final Rect rect = Rect.fromLTRB( + xPosition, + yPosition, + xPosition + cellWidth, + yPosition + cellHeight, + ); canvas.drawRRect( - RRect.fromRectAndRadius(rect, const Radius.circular(2)), - yearView._todayHighlightPaint); + RRect.fromRectAndRadius(rect, const Radius.circular(2)), + yearView._todayHighlightPaint, + ); } } @@ -3898,8 +4178,9 @@ void _drawYearCells( } final dynamic today = DateRangePickerHelper.getToday(yearView.isHijri); - yearView._textPainter.textScaler = - TextScaler.linear(yearView.textScaleFactor); + yearView._textPainter.textScaler = TextScaler.linear( + yearView.textScaleFactor, + ); const double decorationPadding = 1; const double selectionPadding = 3; @@ -3913,34 +4194,42 @@ void _drawYearCells( final int viewEndIndex = ((j + 1) * visibleDatesCount) - 1; /// Calculate the selected index values based on selected date property. - final List selectedIndex = - yearView.getSelectedIndex(viewStartIndex, viewEndIndex); + final List selectedIndex = yearView.getSelectedIndex( + viewStartIndex, + viewEndIndex, + ); List? hoveringIndex; if (yearView.mouseHoverPosition.value != null && yearView.mouseHoverPosition.value!.hoveringRange != null) { hoveringIndex = yearView._getRangeIndex( - yearView.mouseHoverPosition.value!.hoveringRange.startDate, - yearView.mouseHoverPosition.value!.hoveringRange.endDate, - yearView.view, - viewStartIndex, - viewEndIndex); + yearView.mouseHoverPosition.value!.hoveringRange.startDate, + yearView.mouseHoverPosition.value!.hoveringRange.endDate, + yearView.view, + viewStartIndex, + viewEndIndex, + ); } - final double viewStartPosition = isVerticalMultiView - ? 0 - : (currentViewIndex * width) + (currentViewIndex * webUIPadding); + final double viewStartPosition = + isVerticalMultiView + ? 0 + : (currentViewIndex * width) + (currentViewIndex * webUIPadding); final double viewEndPosition = viewStartPosition + width; xPosition = viewStartPosition; - yPosition = isHorizontalMultiView - ? 0 - : (currentViewIndex * height) + (currentViewIndex * webUIPadding); + yPosition = + isHorizontalMultiView + ? 0 + : (currentViewIndex * height) + (currentViewIndex * webUIPadding); for (int i = 0; i < visibleDatesCount; i++) { int currentIndex = i; if (yearView.isRtl) { final int rowIndex = i ~/ YearView.maxColumnCount; - currentIndex = DateRangePickerHelper.getRtlIndex( - YearView.maxColumnCount, i % YearView.maxColumnCount) + + currentIndex = + DateRangePickerHelper.getRtlIndex( + YearView.maxColumnCount, + i % YearView.maxColumnCount, + ) + (rowIndex * YearView.maxColumnCount); } @@ -3952,43 +4241,71 @@ void _drawYearCells( if ((yearView.enableMultiView || yearView.isHijri) && DateRangePickerHelper.isLeadingCellDate( - currentIndex, viewStartIndex, yearView.visibleDates, view)) { + currentIndex, + viewStartIndex, + yearView.visibleDates, + view, + )) { xPosition += cellWidth; continue; } final dynamic date = yearView.visibleDates[currentIndex]; - final bool isCurrentDate = - DateRangePickerHelper.isSameCellDates(date, today, view); + final bool isCurrentDate = DateRangePickerHelper.isSameCellDates( + date, + today, + view, + ); final bool isSelected = selectedIndex.contains(currentIndex); final bool isEnableDate = DateRangePickerHelper.isBetweenMinMaxDateCell( - date, - yearView.minDate, - yearView.maxDate, - yearView.enablePastDates, - view, - yearView.isHijri); + date, + yearView.minDate, + yearView.maxDate, + yearView.enablePastDates, + view, + yearView.isHijri, + ); final bool isActiveDate = _isCurrentViewDateCell( - date, j, yearView.visibleDates, yearView.enableMultiView, view); + date, + j, + yearView.visibleDates, + yearView.enableMultiView, + view, + ); bool isDisabledDate = DateRangePickerHelper.isDateWithInVisibleDates( - yearView.visibleDates, yearView.disableDatesCollection, date); + yearView.visibleDates, + yearView.disableDatesCollection, + date, + ); if (!isDisabledDate && yearView is _ExtendableRangeSelectionRenderObject && yearView.selectedRange != null && DateRangePickerHelper.isDisableDirectionDate( - yearView.selectedRange, - date, - yearView.extendableRangeSelectionDirection, - view, - yearView.isHijri, - isInBetweenEnabled: true)) { + yearView.selectedRange, + date, + yearView.extendableRangeSelectionDirection, + view, + yearView.isHijri, + isInBetweenEnabled: true, + )) { isDisabledDate = true; } - final TextStyle style = yearView._updateCellTextStyle(j, isCurrentDate, - isSelected, isEnableDate, isActiveDate, isDisabledDate); + final TextStyle style = yearView._updateCellTextStyle( + j, + isCurrentDate, + isSelected, + isEnableDate, + isActiveDate, + isDisabledDate, + ); final Decoration? yearDecoration = yearView._updateCellDecoration( - j, isCurrentDate, isEnableDate, isActiveDate, isDisabledDate); + j, + isCurrentDate, + isEnableDate, + isActiveDate, + isDisabledDate, + ); final TextSpan yearText = TextSpan( text: yearView._getCellText(date), @@ -4003,30 +4320,39 @@ void _drawYearCells( final double textHalfHeight = yearView._textPainter.height / 2; if (isSelected && isEnableDate && !isDisabledDate) { yearView.drawSelection( - canvas, - cellWidth, - currentIndex, - highlightPadding, - selectionPadding, - textHalfHeight, - centerYPosition, - xPosition, - yPosition, - yearText); + canvas, + cellWidth, + currentIndex, + highlightPadding, + selectionPadding, + textHalfHeight, + centerYPosition, + xPosition, + yPosition, + yearText, + ); } else if (yearDecoration != null) { - yearView._drawYearDecoration(canvas, yearDecoration, xPosition, - yPosition, decorationPadding, cellWidth, cellHeight); + yearView._drawYearDecoration( + canvas, + yearDecoration, + xPosition, + yPosition, + decorationPadding, + cellWidth, + cellHeight, + ); } else if (isCurrentDate) { yearView._drawTodayHighlight( - canvas, - cellWidth, - cellHeight, - centerYPosition, - highlightPadding, - selectionPadding, - textHalfHeight, - xPosition, - yPosition); + canvas, + cellWidth, + cellHeight, + centerYPosition, + highlightPadding, + selectionPadding, + textHalfHeight, + xPosition, + yPosition, + ); } double xOffset = @@ -4041,18 +4367,19 @@ void _drawYearCells( hoveringIndex.contains(currentIndex) && isEnableDate) { yearView._addRangeHoverEffect( - canvas, - xPosition, - yPosition, - currentIndex, - hoveringIndex, - yearView, - centerYPosition, - textHalfHeight, - selectionPadding, - highlightPadding, - cellWidth, - cellHeight); + canvas, + xPosition, + yPosition, + currentIndex, + hoveringIndex, + yearView, + centerYPosition, + textHalfHeight, + selectionPadding, + highlightPadding, + cellWidth, + cellHeight, + ); } if ((!isSelected || (yearView.isBetweenRange(currentIndex))) && @@ -4061,21 +4388,22 @@ void _drawYearCells( yearView.mouseHoverPosition.value != null && yearView.mouseHoverPosition.value!.offset != null) { yearView._addMouseHovering( - canvas, - cellWidth, - cellHeight, - centerYPosition, - currentViewIndex, - width, - highlightPadding, - date, - selectionPadding, - textHalfHeight, - webUIPadding, - xOffset, - xPosition, - yOffset, - yPosition); + canvas, + cellWidth, + cellHeight, + centerYPosition, + currentViewIndex, + width, + highlightPadding, + date, + selectionPadding, + textHalfHeight, + webUIPadding, + xOffset, + xPosition, + yOffset, + yPosition, + ); } yearView._textPainter.paint(canvas, Offset(xOffset, yOffset)); diff --git a/packages/syncfusion_flutter_datepicker/pubspec.yaml b/packages/syncfusion_flutter_datepicker/pubspec.yaml index 870e22763..4f003c84d 100644 --- a/packages/syncfusion_flutter_datepicker/pubspec.yaml +++ b/packages/syncfusion_flutter_datepicker/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_datepicker description: The Flutter Date Range Picker widget allows users to easily select dates or a range of dates. It has four built-in views that allow quick navigation to the desired date. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_datepicker screenshots: @@ -8,7 +8,7 @@ screenshots: path: screenshots/flutter-daterangepicker-screenshot.png environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: @@ -20,3 +20,8 @@ dependencies: + +flutter: + uses-material-design: true + assets: + - assets/fonts/Roboto-Medium.ttf \ No newline at end of file diff --git a/packages/syncfusion_flutter_gauges/CHANGELOG.md b/packages/syncfusion_flutter_gauges/CHANGELOG.md index 9f994da02..da55f3fd2 100644 --- a/packages/syncfusion_flutter_gauges/CHANGELOG.md +++ b/packages/syncfusion_flutter_gauges/CHANGELOG.md @@ -2,11 +2,28 @@ **General** +* The compatible version of our Flutter gauges widget has been updated to Flutter SDK 3.32.0. + +# [29.2.6] - 05/27/2025 +## Radial Gauge +**Bugs** +* #FR67597 - Now, the [WidgetPointer](https://pub.dev/documentation/syncfusion_flutter_gauges/latest/gauges/WidgetPointer-class.html) position will update properly, when we override the valueToFactor method in the custom axis renderer to update the widget pointer position. + +## [29.1.39] - 04/22/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 03/25/2025 + +**General** + * The compatible version of our Flutter gauges widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter gauges example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter gauges example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. -## [28.2.7] - 25/02/2025 +## [28.2.7] - 02/25/2025 **General** diff --git a/packages/syncfusion_flutter_gauges/example/lib/main.dart b/packages/syncfusion_flutter_gauges/example/lib/main.dart index 08ea5b7e0..02fba2493 100644 --- a/packages/syncfusion_flutter_gauges/example/lib/main.dart +++ b/packages/syncfusion_flutter_gauges/example/lib/main.dart @@ -37,57 +37,70 @@ class _MyHomePageState extends State { Widget _getRadialGauge() { return SfRadialGauge( - title: GaugeTitle( - text: 'Speedometer', - textStyle: - const TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold)), - axes: [ - RadialAxis(minimum: 0, maximum: 150, ranges: [ + title: GaugeTitle( + text: 'Speedometer', + textStyle: const TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), + ), + axes: [ + RadialAxis( + minimum: 0, + maximum: 150, + ranges: [ GaugeRange( - startValue: 0, - endValue: 50, - color: Colors.green, - startWidth: 10, - endWidth: 10), + startValue: 0, + endValue: 50, + color: Colors.green, + startWidth: 10, + endWidth: 10, + ), GaugeRange( - startValue: 50, - endValue: 100, - color: Colors.orange, - startWidth: 10, - endWidth: 10), + startValue: 50, + endValue: 100, + color: Colors.orange, + startWidth: 10, + endWidth: 10, + ), GaugeRange( - startValue: 100, - endValue: 150, - color: Colors.red, - startWidth: 10, - endWidth: 10) - ], pointers: [ - NeedlePointer(value: 90) - ], annotations: [ + startValue: 100, + endValue: 150, + color: Colors.red, + startWidth: 10, + endWidth: 10, + ), + ], + pointers: [NeedlePointer(value: 90)], + annotations: [ GaugeAnnotation( - widget: Container( - child: const Text('90.0', - style: TextStyle( - fontSize: 25, fontWeight: FontWeight.bold))), - angle: 90, - positionFactor: 0.5) - ]) - ]); + widget: Container( + child: const Text( + '90.0', + style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold), + ), + ), + angle: 90, + positionFactor: 0.5, + ), + ], + ), + ], + ); } Widget _getLinearGauge() { return Container( child: SfLinearGauge( - minimum: 0.0, - maximum: 100.0, - orientation: LinearGaugeOrientation.horizontal, - majorTickStyle: LinearTickStyle(length: 20), - axisLabelStyle: TextStyle(fontSize: 12.0, color: Colors.black), - axisTrackStyle: LinearAxisTrackStyle( - color: Colors.cyan, - edgeStyle: LinearEdgeStyle.bothFlat, - thickness: 15.0, - borderColor: Colors.grey)), + minimum: 0.0, + maximum: 100.0, + orientation: LinearGaugeOrientation.horizontal, + majorTickStyle: LinearTickStyle(length: 20), + axisLabelStyle: TextStyle(fontSize: 12.0, color: Colors.black), + axisTrackStyle: LinearAxisTrackStyle( + color: Colors.cyan, + edgeStyle: LinearEdgeStyle.bothFlat, + thickness: 15.0, + borderColor: Colors.grey, + ), + ), margin: EdgeInsets.all(10), ); } @@ -95,7 +108,8 @@ class _MyHomePageState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar(title: const Text('Syncfusion Flutter Gauge')), - body: _getGauge()); + appBar: AppBar(title: const Text('Syncfusion Flutter Gauge')), + body: _getGauge(), + ); } } diff --git a/packages/syncfusion_flutter_gauges/example/pubspec.yaml b/packages/syncfusion_flutter_gauges/example/pubspec.yaml index 663d19b24..df2c89ae3 100644 --- a/packages/syncfusion_flutter_gauges/example/pubspec.yaml +++ b/packages/syncfusion_flutter_gauges/example/pubspec.yaml @@ -1,20 +1,10 @@ name: example description: A new Flutter project. -# 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 used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -22,53 +12,12 @@ dependencies: syncfusion_flutter_gauges: path: ../ - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: '>=0.1.2 <1.0.7' dev_dependencies: flutter_test: sdk: flutter - -# 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. 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: - # - 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 diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_renderer.dart index c192a8bfb..bf2f30395 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_renderer.dart @@ -19,9 +19,11 @@ import '../../linear_gauge/utils/linear_gauge_typedef.dart'; /// Represents the renderer of linear axis. class LinearAxisRenderObjectWidget extends LeafRenderObjectWidget { /// Creates the axis render with required properties. - const LinearAxisRenderObjectWidget( - {Key? key, required this.linearGauge, this.fadeAnimation}) - : super(key: key); + const LinearAxisRenderObjectWidget({ + Key? key, + required this.linearGauge, + this.fadeAnimation, + }) : super(key: key); /// Holds the linear axis. final SfLinearGauge linearGauge; @@ -62,8 +64,8 @@ class LinearAxisRenderObjectWidget extends LeafRenderObjectWidget { isMirrored: linearGauge.isMirrored, textStyle: theme.textTheme.bodySmall! .copyWith( - color: - gaugeThemeData.axisLabelColor ?? colorScheme.onSurface[223]) + color: gaugeThemeData.axisLabelColor ?? colorScheme.onSurface[223], + ) .merge(gaugeThemeData.axisLabelTextStyle) .merge(linearGauge.axisLabelStyle), showLabels: linearGauge.showLabels, @@ -190,45 +192,48 @@ class RenderLinearAxis extends RenderBox { FactorToValueCallback? factorToValueCallback, List? ranges, required BuildContext context, - }) : _orientation = orientation, - _showAxisTrack = showAxisTrack, - _thickness = thickness, - _color = color, - _borderColor = borderColor, - _borderWidth = borderWidth, - _gradient = gradient, - _edgeStyle = edgeStyle, - _minimum = minimum, - _maximum = maximum, - _interval = interval, - _minorTicksPerInterval = minorTicksPerInterval, - _numberFormat = numberFormat, - _labelOffset = labelOffset, - _labelPosition = labelPosition, - _tickPosition = tickPosition, - _tickOffset = tickOffset, - _textStyle = textStyle, - _showLabels = showLabels, - _isMirrored = isMirrored, - _majorTickLength = majorTickLength, - _majorTickThickness = majorTickThickness, - _majorTickColor = majorTickColor, - _minorTickLength = minorTickLength, - _minorTickThickness = minorTickThickness, - _minorTickColor = minorTickColor, - _showTicks = showTicks, - _isAxisInversed = isAxisInversed, - _maximumLabels = maximumLabels, - _onGenerateLabels = onGenerateLabels, - _axisTrackExtent = axisTrackExtent, - _fadeAnimation = fadeAnimation, - _labelFormatterCallback = labelFormatterCallback, - _ranges = ranges, - _useRangeColorForAxis = useRangeColorForAxis, - _factorToValueCallback = factorToValueCallback, - _valueToFactorCallback = valueToFactorCallback { - _axisPaint = Paint() - ..color = Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.12); + }) : _orientation = orientation, + _showAxisTrack = showAxisTrack, + _thickness = thickness, + _color = color, + _borderColor = borderColor, + _borderWidth = borderWidth, + _gradient = gradient, + _edgeStyle = edgeStyle, + _minimum = minimum, + _maximum = maximum, + _interval = interval, + _minorTicksPerInterval = minorTicksPerInterval, + _numberFormat = numberFormat, + _labelOffset = labelOffset, + _labelPosition = labelPosition, + _tickPosition = tickPosition, + _tickOffset = tickOffset, + _textStyle = textStyle, + _showLabels = showLabels, + _isMirrored = isMirrored, + _majorTickLength = majorTickLength, + _majorTickThickness = majorTickThickness, + _majorTickColor = majorTickColor, + _minorTickLength = minorTickLength, + _minorTickThickness = minorTickThickness, + _minorTickColor = minorTickColor, + _showTicks = showTicks, + _isAxisInversed = isAxisInversed, + _maximumLabels = maximumLabels, + _onGenerateLabels = onGenerateLabels, + _axisTrackExtent = axisTrackExtent, + _fadeAnimation = fadeAnimation, + _labelFormatterCallback = labelFormatterCallback, + _ranges = ranges, + _useRangeColorForAxis = useRangeColorForAxis, + _factorToValueCallback = factorToValueCallback, + _valueToFactorCallback = valueToFactorCallback { + _axisPaint = + Paint() + ..color = Theme.of( + context, + ).colorScheme.onSurface.withValues(alpha: 0.12); _textPainter = TextPainter(textDirection: TextDirection.ltr); _visibleLabels = []; _isHorizontalOrientation = orientation == LinearGaugeOrientation.horizontal; @@ -810,10 +815,7 @@ class RenderLinearAxis extends RenderBox { /// Returns the measured the label size. Size _measureLabelSize(double? value) { final String? label = _labelMap[value]; - final TextSpan textSpan = TextSpan( - text: label, - style: textStyle, - ); + final TextSpan textSpan = TextSpan(text: label, style: textStyle); _textPainter.text = textSpan; _textPainter.layout(); @@ -855,10 +857,14 @@ class RenderLinearAxis extends RenderBox { final double labelSize = getEffectiveLabelSize(); final double tickSize = getTickSize() - tickMarginSize; final double axisSize = getAxisLineThickness(); - final LinearElementPosition position = - getEffectiveElementPosition(tickPosition, isMirrored); - final LinearLabelPosition labelPlacement = - getEffectiveLabelPosition(labelPosition, isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + tickPosition, + isMirrored, + ); + final LinearLabelPosition labelPlacement = getEffectiveLabelPosition( + labelPosition, + isMirrored, + ); switch (position) { case LinearElementPosition.inside: @@ -886,7 +892,8 @@ class RenderLinearAxis extends RenderBox { } break; case LinearElementPosition.cross: - _axisWidgetThickness = axisSize + + _axisWidgetThickness = + axisSize + ((axisSize < tickSize) ? tickSize - axisSize : 0.0) + labelSize; break; @@ -902,10 +909,14 @@ class RenderLinearAxis extends RenderBox { final double tickSize = getTickSize() - tickMarginSize; final double labelSize = getEffectiveLabelSize() - labelMarginSize; final double axisSize = getAxisLineThickness(); - final LinearElementPosition position = - getEffectiveElementPosition(tickPosition, isMirrored); - final LinearLabelPosition labelPlacement = - getEffectiveLabelPosition(labelPosition, isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + tickPosition, + isMirrored, + ); + final LinearLabelPosition labelPlacement = getEffectiveLabelPosition( + labelPosition, + isMirrored, + ); switch (position) { case LinearElementPosition.inside: @@ -919,9 +930,10 @@ class RenderLinearAxis extends RenderBox { case LinearLabelPosition.outside: _labelTop = 0; axisOffset = showAxisTrack ? labelSize + labelMarginSize : 0; - _tickTop = showTicks - ? labelSize + labelMarginSize + axisSize + tickMarginSize - : 0; + _tickTop = + showTicks + ? labelSize + labelMarginSize + axisSize + tickMarginSize + : 0; break; } break; @@ -930,9 +942,10 @@ class RenderLinearAxis extends RenderBox { case LinearLabelPosition.inside: _tickTop = 0; axisOffset = showAxisTrack ? tickSize + tickMarginSize : 0; - _labelTop = showLabels - ? axisSize + tickSize + labelMarginSize + tickMarginSize - : 0; + _labelTop = + showLabels + ? axisSize + tickSize + labelMarginSize + tickMarginSize + : 0; break; case LinearLabelPosition.outside: _labelTop = 0; @@ -955,9 +968,10 @@ class RenderLinearAxis extends RenderBox { if (axisSize < tickSize && tickSize > 0) { _tickTop = 0; axisOffset = showAxisTrack ? (tickSize - axisSize) / 2 : 0; - _labelTop = showLabels - ? (axisSize + (tickSize - axisSize) + labelMarginSize) - : 0; + _labelTop = + showLabels + ? (axisSize + (tickSize - axisSize) + labelMarginSize) + : 0; } else if (axisSize > tickSize && tickSize > 0) { axisOffset = 0; _tickTop = showTicks ? (axisSize - tickSize) / 2 : 0; @@ -972,15 +986,17 @@ class RenderLinearAxis extends RenderBox { if (axisSize < tickSize && tickSize > 0) { _labelTop = 0; _tickTop = showTicks ? labelSize + labelMarginSize : 0; - axisOffset = showAxisTrack - ? labelSize + labelMarginSize + (tickSize - axisSize) / 2 - : 0; + axisOffset = + showAxisTrack + ? labelSize + labelMarginSize + (tickSize - axisSize) / 2 + : 0; } else if (axisSize > tickSize && tickSize > 0) { _labelTop = 0; axisOffset = showAxisTrack ? labelSize + labelMarginSize : 0; - _tickTop = showTicks - ? labelSize + labelMarginSize + (axisSize - tickSize) / 2 - : 0; + _tickTop = + showTicks + ? labelSize + labelMarginSize + (axisSize - tickSize) / 2 + : 0; } else { _labelTop = 0; axisOffset = showAxisTrack ? labelSize + labelMarginSize : 0; @@ -1105,15 +1121,17 @@ class RenderLinearAxis extends RenderBox { /// Get the child padding for positioning. double getChildPadding({dynamic child}) { double paddingSize = math.max( - math.max(axisTrackExtent, pointerStartPadding!), - _getStartLabelPadding()); + math.max(axisTrackExtent, pointerStartPadding!), + _getStartLabelPadding(), + ); if (child != null && (child is RenderLinearWidgetPointer || child is RenderLinearShapePointer)) { - final double childSize = _isHorizontalOrientation - ? child.size.width as double - : child.size.height as double; + final double childSize = + _isHorizontalOrientation + ? child.size.width as double + : child.size.height as double; if (child.markerAlignment == LinearMarkerAlignment.start) { return paddingSize; @@ -1208,19 +1226,25 @@ class RenderLinearAxis extends RenderBox { _axisActualSize = Size(axisWidgetThickness, parentWidgetSize); } - size = Size(math.min(_axisActualSize.width, constraints.maxWidth), - math.min(_axisActualSize.height, constraints.maxHeight)); + size = Size( + math.min(_axisActualSize.width, constraints.maxWidth), + math.min(_axisActualSize.height, constraints.maxHeight), + ); } /// To calculate the axis interval based on the maximum axis label count. double _calculateAxisInterval(Size size) { final double delta = (maximum - minimum).abs(); final double area = _isHorizontalOrientation ? size.width : size.height; - final double actualDesiredIntervalsCount = - math.max((area * maximumLabels) / 100, 1.0); + final double actualDesiredIntervalsCount = math.max( + (area * maximumLabels) / 100, + 1.0, + ); double niceInterval = delta / actualDesiredIntervalsCount; - final num minInterval = - math.pow(10, (math.log(niceInterval) / math.log(10)).floor()); + final num minInterval = math.pow( + 10, + (math.log(niceInterval) / math.log(10)).floor(), + ); final List intervalDivisions = [10, 5, 2, 1]; for (final double intervalDivision in intervalDivisions) { final double currentInterval = minInterval * intervalDivision; @@ -1275,8 +1299,10 @@ class RenderLinearAxis extends RenderBox { /// Returns the pixel position based on value. double valueToPixel(double value, {bool isTickPositionCalculation = false}) { - final double factor = valueToFactor(value, - isTickPositionCalculation: isTickPositionCalculation); + final double factor = valueToFactor( + value, + isTickPositionCalculation: isTickPositionCalculation, + ); double? labelStartPadding = _getStartLabelPadding(); double? labelEndPadding = _getEndLabelPadding(); @@ -1298,8 +1324,14 @@ class RenderLinearAxis extends RenderBox { (labelStartPadding + labelEndPadding)); } - void _drawTickLine(double x1, double y1, double x2, double y2, Canvas canvas, - bool isMajorTick) { + void _drawTickLine( + double x1, + double y1, + double x2, + double y2, + Canvas canvas, + bool isMajorTick, + ) { final Offset majorTickStartOffset = Offset(x1, y1); final Offset majorTickEndOffset = Offset(x2, y2); canvas.drawLine(majorTickStartOffset, majorTickEndOffset, _axisPaint); @@ -1310,13 +1342,18 @@ class RenderLinearAxis extends RenderBox { if (_visibleLabels.length - 1 == index) { return null; } else { - endValuePosition = valueToPixel(_visibleLabels[index + 1].value, - isTickPositionCalculation: true); - } - - final double width = (endValuePosition - - valueToPixel(_visibleLabels[index].value, - isTickPositionCalculation: true)) + endValuePosition = valueToPixel( + _visibleLabels[index + 1].value, + isTickPositionCalculation: true, + ); + } + + final double width = + (endValuePosition - + valueToPixel( + _visibleLabels[index].value, + isTickPositionCalculation: true, + )) .abs() / (minorTicksPerInterval + 1); @@ -1342,15 +1379,22 @@ class RenderLinearAxis extends RenderBox { animationValue = _fadeAnimation!.value; } - _axisPaint.color = - paintColor.withValues(alpha: animationValue * paintColor.a); + _axisPaint.color = paintColor.withValues( + alpha: animationValue * paintColor.a, + ); } ///Draws minor tick elements. - void _drawMinorTicks(double minorTickLeftPosition, double top, - int majorTickIndex, Canvas canvas) { - final LinearElementPosition position = - getEffectiveElementPosition(tickPosition, isMirrored); + void _drawMinorTicks( + double minorTickLeftPosition, + double top, + int majorTickIndex, + Canvas canvas, + ) { + final LinearElementPosition position = getEffectiveElementPosition( + tickPosition, + isMirrored, + ); if (_isHorizontalOrientation) { if (position == LinearElementPosition.outside) { @@ -1372,38 +1416,48 @@ class RenderLinearAxis extends RenderBox { final double? valueGap = _getMinorTickValueGap(majorTickIndex); if (minorTickGap != null) { - for (int minorTickIndex = 1; - minorTickIndex <= minorTicksPerInterval; - minorTickIndex++) { + for ( + int minorTickIndex = 1; + minorTickIndex <= minorTicksPerInterval; + minorTickIndex++ + ) { if (_isHorizontalOrientation) { minorTickLeftPosition += minorTickGap; } else { top += minorTickGap; } - _setPaintColor(useRangeColorForAxis - ? _getRangeColor(_visibleLabels[majorTickIndex].value + - (valueGap! * minorTickIndex)) ?? - minorTickColor - : minorTickColor); + _setPaintColor( + useRangeColorForAxis + ? _getRangeColor( + _visibleLabels[majorTickIndex].value + + (valueGap! * minorTickIndex), + ) ?? + minorTickColor + : minorTickColor, + ); _axisPaint.strokeWidth = minorTickThickness; _drawTickLine( - minorTickLeftPosition, - top, - minorTickLeftPosition + - (!_isHorizontalOrientation ? minorTickLength : 0), - top + (_isHorizontalOrientation ? minorTickLength : 0), - canvas, - false); + minorTickLeftPosition, + top, + minorTickLeftPosition + + (!_isHorizontalOrientation ? minorTickLength : 0), + top + (_isHorizontalOrientation ? minorTickLength : 0), + canvas, + false, + ); } } } /// The style information for text runs, encoded for use by `dart:ui`. - dart_ui.TextStyle _getTextStyle( - {double textScaleFactor = 1.0, required TextStyle style, Color? color}) { + dart_ui.TextStyle _getTextStyle({ + double textScaleFactor = 1.0, + required TextStyle style, + Color? color, + }) { double animationValue = 1; if (_fadeAnimation != null) { @@ -1432,7 +1486,8 @@ class RenderLinearAxis extends RenderBox { height: style.height, locale: style.locale, foreground: style.foreground, - background: style.background ?? + background: + style.background ?? (style.backgroundColor != null ? (Paint()..color = style.backgroundColor!) : null), @@ -1442,18 +1497,26 @@ class RenderLinearAxis extends RenderBox { } ///Draws axis label elements. - void _drawLabels(Canvas canvas, int majorTickIndex, - double majorTickLeftPosition, double top) { + void _drawLabels( + Canvas canvas, + int majorTickIndex, + double majorTickLeftPosition, + double top, + ) { final dart_ui.ParagraphStyle paragraphStyle = dart_ui.ParagraphStyle( - textDirection: TextDirection.ltr, textAlign: TextAlign.left); + textDirection: TextDirection.ltr, + textAlign: TextAlign.left, + ); final String labelText = _labelMap[_visibleLabels[majorTickIndex].value]!; final double value = _visibleLabels[majorTickIndex].value; final dart_ui.TextStyle labelTextStyle = _getTextStyle( - style: textStyle, - color: useRangeColorForAxis - ? _getRangeColor(_visibleLabels[majorTickIndex].value) ?? - textStyle.color - : textStyle.color); + style: textStyle, + color: + useRangeColorForAxis + ? _getRangeColor(_visibleLabels[majorTickIndex].value) ?? + textStyle.color + : textStyle.color, + ); final dart_ui.ParagraphBuilder paragraphBuilder = dart_ui.ParagraphBuilder(paragraphStyle) ..pushStyle(labelTextStyle) @@ -1472,8 +1535,10 @@ class RenderLinearAxis extends RenderBox { final double labelLeftPosition = top - (labelSize.height / 2); if (_labelTop == 0 && _maxLabelWidth > labelSize.width) { - labelOffset = - Offset(_maxLabelWidth - labelSize.width, labelLeftPosition); + labelOffset = Offset( + _maxLabelWidth - labelSize.width, + labelLeftPosition, + ); } else { labelOffset = Offset(_labelTop, labelLeftPosition); } @@ -1501,23 +1566,26 @@ class RenderLinearAxis extends RenderBox { if (_isHorizontalOrientation) { _axisLineRect = Rect.fromLTWH( - offset.dx + startLabelPadding, - offset.dy + axisOffset, - size.width - (startLabelPadding + endLabelPadding), - thickness); + offset.dx + startLabelPadding, + offset.dy + axisOffset, + size.width - (startLabelPadding + endLabelPadding), + thickness, + ); } else { _axisLineRect = Rect.fromLTWH( - offset.dx + axisOffset, - offset.dy + startLabelPadding, - thickness, - size.height - (startLabelPadding + endLabelPadding)); + offset.dx + axisOffset, + offset.dy + startLabelPadding, + thickness, + size.height - (startLabelPadding + endLabelPadding), + ); } _axisLineRect = Rect.fromLTWH( - _axisLineRect.left + borderWidth / 2, - _axisLineRect.top + borderWidth / 2, - _axisLineRect.width - borderWidth, - _axisLineRect.height - borderWidth); + _axisLineRect.left + borderWidth / 2, + _axisLineRect.top + borderWidth / 2, + _axisLineRect.width - borderWidth, + _axisLineRect.height - borderWidth, + ); if (showAxisTrack) { _axisPaint.style = PaintingStyle.fill; @@ -1533,22 +1601,29 @@ class RenderLinearAxis extends RenderBox { _path.addRect(_axisLineRect); break; case LinearEdgeStyle.bothCurve: - _path.addRRect(RRect.fromRectAndRadius( - _axisLineRect, Radius.circular(thickness))); + _path.addRRect( + RRect.fromRectAndRadius(_axisLineRect, Radius.circular(thickness)), + ); break; case LinearEdgeStyle.startCurve: - _path.addRRect(getStartCurve( + _path.addRRect( + getStartCurve( isHorizontal: _isHorizontalOrientation, isAxisInversed: isAxisInversed, rect: _axisLineRect, - radius: thickness / 2)); + radius: thickness / 2, + ), + ); break; case LinearEdgeStyle.endCurve: - _path.addRRect(getEndCurve( + _path.addRRect( + getEndCurve( isHorizontal: _isHorizontalOrientation, isAxisInversed: isAxisInversed, rect: _axisLineRect, - radius: thickness / 2)); + radius: thickness / 2, + ), + ); break; } @@ -1565,20 +1640,26 @@ class RenderLinearAxis extends RenderBox { } void _drawTicksAndLabels(Canvas canvas, Offset offset) { - final double majorTickLeftPosition = - math.max(_getStartLabelPadding(), axisTrackExtent); + final double majorTickLeftPosition = math.max( + _getStartLabelPadding(), + axisTrackExtent, + ); Offset tickStartPoint, tickEndPoint; for (int index = 0; index < _visibleLabels.length; index++) { _axisPaint.shader = null; - _setPaintColor(useRangeColorForAxis - ? _getRangeColor(_visibleLabels[index].value) ?? majorTickColor - : majorTickColor); + _setPaintColor( + useRangeColorForAxis + ? _getRangeColor(_visibleLabels[index].value) ?? majorTickColor + : majorTickColor, + ); _axisPaint.strokeWidth = majorTickThickness; - final double calculatedPosition = valueToPixel( - _visibleLabels[index].value, - isTickPositionCalculation: true) + + final double calculatedPosition = + valueToPixel( + _visibleLabels[index].value, + isTickPositionCalculation: true, + ) + majorTickLeftPosition; tickStartPoint = Offset(calculatedPosition, _tickTop); @@ -1591,8 +1672,14 @@ class RenderLinearAxis extends RenderBox { if (showTicks) { /// Drawing the major ticks. - _drawTickLine(tickStartPoint.dx, tickStartPoint.dy, tickEndPoint.dx, - tickEndPoint.dy, canvas, true); + _drawTickLine( + tickStartPoint.dx, + tickStartPoint.dy, + tickEndPoint.dx, + tickEndPoint.dy, + canvas, + true, + ); _drawMinorTicks(tickStartPoint.dx, tickStartPoint.dy, index, canvas); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_track_style.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_track_style.dart index 3ae6386fa..011e0328d 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_track_style.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_axis_track_style.dart @@ -6,13 +6,14 @@ import '../../linear_gauge/utils/enum.dart'; @immutable class LinearAxisTrackStyle { /// Creates a style for axis line. - const LinearAxisTrackStyle( - {this.thickness = 5.0, - this.edgeStyle = LinearEdgeStyle.bothFlat, - this.color, - this.gradient, - this.borderColor, - this.borderWidth = 0}); + const LinearAxisTrackStyle({ + this.thickness = 5.0, + this.edgeStyle = LinearEdgeStyle.bothFlat, + this.color, + this.gradient, + this.borderColor, + this.borderWidth = 0, + }); /// Specifies the thickness value of an axis track. /// diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_tick_style.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_tick_style.dart index f767ccf0d..eb2ee84c3 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_tick_style.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/axis/linear_tick_style.dart @@ -82,10 +82,6 @@ class LinearTickStyle { @override int get hashCode { - return Object.hash( - length, - color, - thickness, - ); + return Object.hash(length, color, thickness); } } diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge.dart index 37934eaa1..0205f2f43 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge.dart @@ -26,48 +26,48 @@ import '../../linear_gauge/utils/linear_gauge_typedef.dart'; /// ``` class SfLinearGauge extends StatefulWidget { /// Creates a linear gauge - SfLinearGauge( - {Key? key, - this.minimum = 0.0, - this.maximum = 100.0, - this.interval, - this.ranges, - this.barPointers, - this.markerPointers, - this.orientation = LinearGaugeOrientation.horizontal, - this.isAxisInversed = false, - this.isMirrored = false, - this.animateAxis = false, - this.animateRange = false, - this.animationDuration = 1000, - this.showLabels = true, - this.showAxisTrack = true, - this.showTicks = true, - this.minorTicksPerInterval = 1, - this.useRangeColorForAxis = false, - this.axisTrackExtent = 0, - this.labelPosition = LinearLabelPosition.inside, - this.tickPosition = LinearElementPosition.inside, - double tickOffset = 0, - double labelOffset = 4, - this.maximumLabels = 3, - NumberFormat? numberFormat, - this.onGenerateLabels, - this.valueToFactorCallback, - this.factorToValueCallback, - this.labelFormatterCallback, - this.axisLabelStyle, - LinearAxisTrackStyle? axisTrackStyle, - LinearTickStyle? majorTickStyle, - LinearTickStyle? minorTickStyle}) - : assert(minimum <= maximum, 'Maximum should be greater than minimum.'), - axisTrackStyle = axisTrackStyle ?? const LinearAxisTrackStyle(), - tickOffset = tickOffset > 0 ? tickOffset : 0, - labelOffset = labelOffset > 0 ? labelOffset : 4, - majorTickStyle = majorTickStyle ?? const LinearTickStyle(length: 8.0), - minorTickStyle = minorTickStyle ?? const LinearTickStyle(), - numberFormat = numberFormat ?? NumberFormat('#.##'), - super(key: key); + SfLinearGauge({ + Key? key, + this.minimum = 0.0, + this.maximum = 100.0, + this.interval, + this.ranges, + this.barPointers, + this.markerPointers, + this.orientation = LinearGaugeOrientation.horizontal, + this.isAxisInversed = false, + this.isMirrored = false, + this.animateAxis = false, + this.animateRange = false, + this.animationDuration = 1000, + this.showLabels = true, + this.showAxisTrack = true, + this.showTicks = true, + this.minorTicksPerInterval = 1, + this.useRangeColorForAxis = false, + this.axisTrackExtent = 0, + this.labelPosition = LinearLabelPosition.inside, + this.tickPosition = LinearElementPosition.inside, + double tickOffset = 0, + double labelOffset = 4, + this.maximumLabels = 3, + NumberFormat? numberFormat, + this.onGenerateLabels, + this.valueToFactorCallback, + this.factorToValueCallback, + this.labelFormatterCallback, + this.axisLabelStyle, + LinearAxisTrackStyle? axisTrackStyle, + LinearTickStyle? majorTickStyle, + LinearTickStyle? minorTickStyle, + }) : assert(minimum <= maximum, 'Maximum should be greater than minimum.'), + axisTrackStyle = axisTrackStyle ?? const LinearAxisTrackStyle(), + tickOffset = tickOffset > 0 ? tickOffset : 0, + labelOffset = labelOffset > 0 ? labelOffset : 4, + majorTickStyle = majorTickStyle ?? const LinearTickStyle(length: 8.0), + minorTickStyle = minorTickStyle ?? const LinearTickStyle(), + numberFormat = numberFormat ?? NumberFormat('#.##'), + super(key: key); ///Customizes each range by adding it to the [ranges] collection. /// @@ -537,12 +537,14 @@ class _SfLinearGaugeState extends State } void _updateOldList() { - _oldBarPointerList = (widget.barPointers != null) - ? List.from(widget.barPointers!) - : null; - _oldMarkerPointerList = (widget.markerPointers != null) - ? List.from(widget.markerPointers!) - : null; + _oldBarPointerList = + (widget.barPointers != null) + ? List.from(widget.barPointers!) + : null; + _oldMarkerPointerList = + (widget.markerPointers != null) + ? List.from(widget.markerPointers!) + : null; } bool _isEqualLists(List? a, List? b) { @@ -572,13 +574,17 @@ class _SfLinearGaugeState extends State if (widget.animateAxis || widget.animateRange) { _animationController = AnimationController( - vsync: this, - duration: Duration(milliseconds: widget.animationDuration)); + vsync: this, + duration: Duration(milliseconds: widget.animationDuration), + ); _animationController!.addListener(_axisAnimationListener); - _fadeAnimation = Tween(begin: 0, end: 1).animate(CurvedAnimation( + _fadeAnimation = Tween(begin: 0, end: 1).animate( + CurvedAnimation( parent: _animationController!, - curve: const Interval(0.05, 1.0, curve: Curves.ease))); + curve: const Interval(0.05, 1.0, curve: Curves.ease), + ), + ); } else { if (_animationController != null) { _animationController!.removeListener(_axisAnimationListener); @@ -594,12 +600,16 @@ class _SfLinearGaugeState extends State void _addPointerAnimation(int duration, LinearAnimationType animationType) { final AnimationController pointerController = AnimationController( - vsync: this, duration: Duration(milliseconds: duration)); + vsync: this, + duration: Duration(milliseconds: duration), + ); final Animation animation = Tween(begin: 0, end: 1).animate( - CurvedAnimation( - parent: pointerController, - curve: Interval(0, 1, curve: getCurveAnimation(animationType)))); + CurvedAnimation( + parent: pointerController, + curve: Interval(0, 1, curve: getCurveAnimation(animationType)), + ), + ); _pointerAnimations.add(animation); _pointerAnimationControllers.add(pointerController); @@ -617,7 +627,9 @@ class _SfLinearGaugeState extends State barPointer.position == LinearElementPosition.inside) { if (barPointer.enableAnimation && barPointer.animationDuration > 0) { _addPointerAnimation( - barPointer.animationDuration, barPointer.animationType); + barPointer.animationDuration, + barPointer.animationType, + ); } } } @@ -630,7 +642,9 @@ class _SfLinearGaugeState extends State barPointer.enableAnimation && barPointer.animationDuration > 0) { _addPointerAnimation( - barPointer.animationDuration, barPointer.animationType); + barPointer.animationDuration, + barPointer.animationType, + ); } } } @@ -641,7 +655,9 @@ class _SfLinearGaugeState extends State if (shapePointer.enableAnimation && shapePointer.animationDuration > 0) { _addPointerAnimation( - shapePointer.animationDuration, shapePointer.animationType); + shapePointer.animationDuration, + shapePointer.animationType, + ); } } } @@ -672,15 +688,21 @@ class _SfLinearGaugeState extends State } } - void _addChild(Widget child, Animation? animation, - AnimationController? controller) { - _linearGaugeWidgets.add(LinearGaugeScope( + void _addChild( + Widget child, + Animation? animation, + AnimationController? controller, + ) { + _linearGaugeWidgets.add( + LinearGaugeScope( animation: animation, orientation: widget.orientation, isAxisInversed: widget.isAxisInversed, isMirrored: widget.isMirrored, animationController: controller, - child: child)); + child: child, + ), + ); } List _buildChildWidgets(BuildContext context) { @@ -703,8 +725,11 @@ class _SfLinearGaugeState extends State if (barPointer.position == LinearElementPosition.outside || barPointer.position == LinearElementPosition.inside) { if (barPointer.enableAnimation && barPointer.animationDuration > 0) { - _addChild(barPointer, _pointerAnimations[index], - _pointerAnimationControllers[index]); + _addChild( + barPointer, + _pointerAnimations[index], + _pointerAnimationControllers[index], + ); index++; } else { _addChild(barPointer, null, null); @@ -714,9 +739,12 @@ class _SfLinearGaugeState extends State } /// Adding linear gauge axis widget. - _linearGaugeWidgets.add(LinearAxisRenderObjectWidget( + _linearGaugeWidgets.add( + LinearAxisRenderObjectWidget( linearGauge: widget, - fadeAnimation: widget.animateAxis ? _fadeAnimation : null)); + fadeAnimation: widget.animateAxis ? _fadeAnimation : null, + ), + ); if (widget.ranges != null && widget.ranges!.isNotEmpty) { /// Adding linear gauge range widgets. @@ -732,8 +760,11 @@ class _SfLinearGaugeState extends State for (final LinearBarPointer barPointer in widget.barPointers!) { if (barPointer.position == LinearElementPosition.cross) { if (barPointer.enableAnimation && barPointer.animationDuration > 0) { - _addChild(barPointer, _pointerAnimations[index], - _pointerAnimationControllers[index]); + _addChild( + barPointer, + _pointerAnimations[index], + _pointerAnimationControllers[index], + ); index++; } else { _addChild(barPointer, null, null); @@ -746,8 +777,11 @@ class _SfLinearGaugeState extends State /// Adding linear gauge widget bar pointer element. for (final LinearMarkerPointer pointer in widget.markerPointers!) { if (pointer.enableAnimation && pointer.animationDuration > 0) { - _addChild(pointer as Widget, _pointerAnimations[index], - _pointerAnimationControllers[index]); + _addChild( + pointer as Widget, + _pointerAnimations[index], + _pointerAnimationControllers[index], + ); index++; } else { _addChild(pointer as Widget, null, null); @@ -761,8 +795,9 @@ class _SfLinearGaugeState extends State @override Widget build(BuildContext context) { return LinearGaugeRenderWidget( - pointerAnimations: _pointerAnimations, - children: _buildChildWidgets(context)); + pointerAnimations: _pointerAnimations, + children: _buildChildWidgets(context), + ); } void _disposeAnimationControllers() { diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_render_widget.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_render_widget.dart index 7330a131c..81bb3b374 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_render_widget.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_render_widget.dart @@ -31,23 +31,26 @@ const double kDefaultLinearGaugeWidth = 300.0; /// Linear gauge render widget class. class LinearGaugeRenderWidget extends MultiChildRenderObjectWidget { /// Creates instance for [LinearGaugeRenderWidget] class. - const LinearGaugeRenderWidget( - {Key? key, - required this.pointerAnimations, - required List children}) - : super(key: key, children: children); + const LinearGaugeRenderWidget({ + Key? key, + required this.pointerAnimations, + required List children, + }) : super(key: key, children: children); /// Linear gauge pointer animations. final List> pointerAnimations; @override RenderObject createRenderObject(BuildContext context) => RenderLinearGauge( - pointerAnimations: pointerAnimations, - gestureSettings: MediaQuery.of(context).gestureSettings); + pointerAnimations: pointerAnimations, + gestureSettings: MediaQuery.of(context).gestureSettings, + ); @override void updateRenderObject( - BuildContext context, RenderLinearGauge renderObject) { + BuildContext context, + RenderLinearGauge renderObject, + ) { renderObject.pointerAnimations = pointerAnimations; super.updateRenderObject(context, renderObject); } @@ -111,28 +114,30 @@ class RenderLinearGauge extends RenderBox RenderLinearGauge({ required List> pointerAnimations, required DeviceGestureSettings gestureSettings, - }) : _gestureArenaTeam = GestureArenaTeam(), - _pointerAnimations = pointerAnimations { + }) : _gestureArenaTeam = GestureArenaTeam(), + _pointerAnimations = pointerAnimations { _ranges = []; _barPointers = []; _shapePointers = []; _widgetPointers = []; _markerPointers = []; - _verticalDragGestureRecognizer = VerticalDragGestureRecognizer() - ..team = _gestureArenaTeam - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..gestureSettings = gestureSettings - ..dragStartBehavior = DragStartBehavior.start; - - _horizontalDragGestureRecognizer = HorizontalDragGestureRecognizer() - ..team = _gestureArenaTeam - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..gestureSettings = gestureSettings - ..dragStartBehavior = DragStartBehavior.start; + _verticalDragGestureRecognizer = + VerticalDragGestureRecognizer() + ..team = _gestureArenaTeam + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..gestureSettings = gestureSettings + ..dragStartBehavior = DragStartBehavior.start; + + _horizontalDragGestureRecognizer = + HorizontalDragGestureRecognizer() + ..team = _gestureArenaTeam + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..gestureSettings = gestureSettings + ..dragStartBehavior = DragStartBehavior.start; } final GestureArenaTeam _gestureArenaTeam; @@ -276,10 +281,14 @@ class RenderLinearGauge extends RenderBox final double labelSize = axis!.getEffectiveLabelSize(); final double tickSize = axis!.getTickSize(); final double axisLineSize = axis!.getAxisLineThickness(); - final LinearElementPosition position = - getEffectiveElementPosition(axis!.tickPosition, axis!.isMirrored); - final LinearLabelPosition labelPosition = - getEffectiveLabelPosition(axis!.labelPosition, axis!.isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + axis!.tickPosition, + axis!.isMirrored, + ); + final LinearLabelPosition labelPosition = getEffectiveLabelPosition( + axis!.labelPosition, + axis!.isMirrored, + ); final bool isInsideLabel = labelPosition == LinearLabelPosition.inside; late double insideElementSize; @@ -287,9 +296,10 @@ class RenderLinearGauge extends RenderBox switch (position) { case LinearElementPosition.inside: if (isInsideLabel) { - insideElementSize = (_axisWidgetThickness - axisLineSize) > thickness - ? 0 - : thickness - (_axisWidgetThickness - axisLineSize); + insideElementSize = + (_axisWidgetThickness - axisLineSize) > thickness + ? 0 + : thickness - (_axisWidgetThickness - axisLineSize); } else { insideElementSize = thickness - tickSize; } @@ -303,26 +313,32 @@ class RenderLinearGauge extends RenderBox break; case LinearElementPosition.cross: if (isInsideLabel) { - insideElementSize = (_axisWidgetThickness - axisLineSize) > thickness - ? 0 - : thickness - (_axisWidgetThickness - axisLineSize); + insideElementSize = + (_axisWidgetThickness - axisLineSize) > thickness + ? 0 + : thickness - (_axisWidgetThickness - axisLineSize); } else { - insideElementSize = (axis!.showLabels ? thickness : 0) - + insideElementSize = + (axis!.showLabels ? thickness : 0) - (axisLineSize < tickSize ? (tickSize - axisLineSize) / 2 : 0); } break; } - _insideWidgetElementSize = - math.max(_insideWidgetElementSize, insideElementSize); + _insideWidgetElementSize = math.max( + _insideWidgetElementSize, + insideElementSize, + ); } void _updateInsideElementSize(double thickness) { if (!axis!.showTicks && !axis!.showLabels) { _insideWidgetElementSize = math.max(thickness, _insideWidgetElementSize); } else if (thickness > _axisWidgetThickness) { - _insideWidgetElementSize = - math.max(thickness - _axisWidgetThickness, _insideWidgetElementSize); + _insideWidgetElementSize = math.max( + thickness - _axisWidgetThickness, + _insideWidgetElementSize, + ); } } @@ -331,10 +347,14 @@ class RenderLinearGauge extends RenderBox final double labelSize = axis!.getEffectiveLabelSize(); final double tickSize = axis!.getTickSize(); final double axisSize = axis!.getAxisLineThickness(); - final LinearElementPosition position = - getEffectiveElementPosition(axis!.tickPosition, axis!.isMirrored); - final LinearLabelPosition labelPlacement = - getEffectiveLabelPosition(axis!.labelPosition, axis!.isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + axis!.tickPosition, + axis!.isMirrored, + ); + final LinearLabelPosition labelPlacement = getEffectiveLabelPosition( + axis!.labelPosition, + axis!.isMirrored, + ); final bool isInsideLabel = labelPlacement == LinearLabelPosition.inside; switch (position) { @@ -344,15 +364,20 @@ class RenderLinearGauge extends RenderBox } else if (axisSize < thickness) { final double sizeDifference = (thickness - axisSize) / 2 - (isInsideLabel ? 0 : labelSize); - _outsideWidgetElementSize = - math.max(sizeDifference, _outsideWidgetElementSize); + _outsideWidgetElementSize = math.max( + sizeDifference, + _outsideWidgetElementSize, + ); if (_axisWidgetThickness < thickness) { double axisSizeDifference = (thickness - axisSize) / 2; - axisSizeDifference = axisSizeDifference - + axisSizeDifference = + axisSizeDifference - (tickSize + (isInsideLabel ? labelSize : 0)); - _insideWidgetElementSize = - math.max(axisSizeDifference, _insideWidgetElementSize); + _insideWidgetElementSize = math.max( + axisSizeDifference, + _insideWidgetElementSize, + ); } } break; @@ -360,49 +385,63 @@ class RenderLinearGauge extends RenderBox if (axisSize == 0) { _updateInsideElementSize(thickness); } else if (axisSize < thickness) { - final double sizeDifference = (thickness - axisSize) / 2 - + final double sizeDifference = + (thickness - axisSize) / 2 - (tickSize + (isInsideLabel ? 0 : labelSize)); - _outsideWidgetElementSize = - math.max(sizeDifference, _outsideWidgetElementSize); + _outsideWidgetElementSize = math.max( + sizeDifference, + _outsideWidgetElementSize, + ); double axisSizeDifference = (thickness - axisSize) / 2; axisSizeDifference = axisSizeDifference - (isInsideLabel ? labelSize : 0); - _insideWidgetElementSize = - math.max(axisSizeDifference, _insideWidgetElementSize); + _insideWidgetElementSize = math.max( + axisSizeDifference, + _insideWidgetElementSize, + ); } break; case LinearElementPosition.cross: if (axisSize == 0) { _updateInsideElementSize(thickness); } else if (tickSize > axisSize && axisSize < thickness) { - final double sizeDifference = ((thickness - axisSize) / 2) - + final double sizeDifference = + ((thickness - axisSize) / 2) - ((tickSize - axisSize) / 2) - (isInsideLabel ? 0 : labelSize); - _outsideWidgetElementSize = - math.max(sizeDifference, _outsideWidgetElementSize); + _outsideWidgetElementSize = math.max( + sizeDifference, + _outsideWidgetElementSize, + ); if (_axisWidgetThickness < thickness) { double axisSizeDifference = ((thickness - axisSize) / 2) - ((tickSize - axisSize) / 2); axisSizeDifference = axisSizeDifference - (isInsideLabel ? labelSize : 0); - _insideWidgetElementSize = - math.max(axisSizeDifference, _insideWidgetElementSize); + _insideWidgetElementSize = math.max( + axisSizeDifference, + _insideWidgetElementSize, + ); } } else if (axisSize < thickness) { final double sizeDifference = ((thickness - axisSize) / 2) - (isInsideLabel ? 0 : labelSize); - _outsideWidgetElementSize = - math.max(sizeDifference, _outsideWidgetElementSize); + _outsideWidgetElementSize = math.max( + sizeDifference, + _outsideWidgetElementSize, + ); if (_axisWidgetThickness < thickness) { double axisSizeDifference = (thickness - axisSize) / 2; axisSizeDifference = axisSizeDifference - (isInsideLabel ? labelSize : 0); - _insideWidgetElementSize = - math.max(axisSizeDifference, _insideWidgetElementSize); + _insideWidgetElementSize = math.max( + axisSizeDifference, + _insideWidgetElementSize, + ); } } break; @@ -410,21 +449,26 @@ class RenderLinearGauge extends RenderBox } /// Layout the pointer child. - void _layoutPointerChild( - {required RenderObject renderObject, - required LinearElementPosition position, - required double thickness, - required double offset}) { - final LinearElementPosition pointerPosition = - getEffectiveElementPosition(position, axis!.isMirrored); + void _layoutPointerChild({ + required RenderObject renderObject, + required LinearElementPosition position, + required double thickness, + required double offset, + }) { + final LinearElementPosition pointerPosition = getEffectiveElementPosition( + position, + axis!.isMirrored, + ); switch (pointerPosition) { case LinearElementPosition.inside: _measureInsideElementSize(thickness + offset); break; case LinearElementPosition.outside: - _outsideWidgetElementSize = - math.max(_outsideWidgetElementSize, thickness + offset - _axisTop); + _outsideWidgetElementSize = math.max( + _outsideWidgetElementSize, + thickness + offset - _axisTop, + ); break; case LinearElementPosition.cross: _measureCrossElementSize(thickness); @@ -433,8 +477,10 @@ class RenderLinearGauge extends RenderBox } /// Position the child elements. - void _positionChildElement(RenderObject linearGaugeChild, - {double thickness = 0}) { + void _positionChildElement( + RenderObject linearGaugeChild, { + double thickness = 0, + }) { final MultiChildLayoutParentData? childParentData = linearGaugeChild.parentData as MultiChildLayoutParentData?; final double xPoint = @@ -442,23 +488,30 @@ class RenderLinearGauge extends RenderBox final double yPoint = _pointY; if (_isHorizontalOrientation) { - childParentData!.offset = - Offset(xPoint - (_isAxisInversed ? thickness : 0), yPoint); + childParentData!.offset = Offset( + xPoint - (_isAxisInversed ? thickness : 0), + yPoint, + ); } else { - childParentData!.offset = - Offset(yPoint, xPoint - (!_isAxisInversed ? thickness : 0)); + childParentData!.offset = Offset( + yPoint, + xPoint - (!_isAxisInversed ? thickness : 0), + ); } } /// Calculates the marker pointer offset. - double? _calculateMarkerOffset( - {required LinearElementPosition elementPosition, - required double offset, - required Size size}) { + double? _calculateMarkerOffset({ + required LinearElementPosition elementPosition, + required double offset, + required Size size, + }) { final double markerSize = _isHorizontalOrientation ? size.height : size.width; - final LinearElementPosition pointerPosition = - getEffectiveElementPosition(elementPosition, axis!.isMirrored); + final LinearElementPosition pointerPosition = getEffectiveElementPosition( + elementPosition, + axis!.isMirrored, + ); switch (pointerPosition) { case LinearElementPosition.inside: return _outsideWidgetElementSize + @@ -494,8 +547,10 @@ class RenderLinearGauge extends RenderBox } } - void _updatePointerPositionOnDrag(RenderLinearPointerBase pointer, - {bool isDragCall = false}) { + void _updatePointerPositionOnDrag( + RenderLinearPointerBase pointer, { + bool isDragCall = false, + }) { double animationValue = 1; if (!isDragCall) { @@ -507,15 +562,18 @@ class RenderLinearGauge extends RenderBox } } - final double startPosition = - axis!.valueToPixel(pointer.oldValue ?? axis!.minimum); + final double startPosition = axis!.valueToPixel( + pointer.oldValue ?? axis!.minimum, + ); final double endPosition = axis!.valueToPixel(pointer.value).abs(); _pointX = startPosition + ((endPosition - startPosition) * animationValue); - _pointY = _calculateMarkerOffset( - elementPosition: pointer.position, - offset: pointer.offset, - size: Size(pointer.size.width, pointer.size.height))!; + _pointY = + _calculateMarkerOffset( + elementPosition: pointer.position, + offset: pointer.offset, + size: Size(pointer.size.width, pointer.size.height), + )!; /// _pointX calculation is depends on animation, so the constrained marker /// goes beyond the reference marker even though it's constrained. To avoid @@ -565,17 +623,20 @@ class RenderLinearGauge extends RenderBox _pointerEndPadding = 0; _markerPointers.clear(); - _markerPointers = >[ - _shapePointers, - _widgetPointers - ].expand((List x) => x).toList(); - - final double width = constraints.hasBoundedWidth - ? constraints.maxWidth - : kDefaultLinearGaugeWidth; - final double height = constraints.hasBoundedHeight - ? constraints.maxHeight - : kDefaultLinearGaugeHeight; + _markerPointers = + >[ + _shapePointers, + _widgetPointers, + ].expand((List x) => x).toList(); + + final double width = + constraints.hasBoundedWidth + ? constraints.maxWidth + : kDefaultLinearGaugeWidth; + final double height = + constraints.hasBoundedHeight + ? constraints.maxHeight + : kDefaultLinearGaugeHeight; _parentConstraints = BoxConstraints(maxWidth: width, maxHeight: height); } @@ -585,9 +646,10 @@ class RenderLinearGauge extends RenderBox for (final dynamic pointer in _markerPointers) { pointer.layout(_parentConstraints, parentUsesSize: true); - final double thickness = _isHorizontalOrientation - ? pointer.size.width as double - : pointer.size.height as double; + final double thickness = + _isHorizontalOrientation + ? pointer.size.width as double + : pointer.size.height as double; if (pointer.markerAlignment == LinearMarkerAlignment.start) { _pointerEndPadding = math.max(_pointerEndPadding, thickness); @@ -614,12 +676,14 @@ class RenderLinearGauge extends RenderBox final double padding = axis!.getAxisLayoutPadding(); if (_isHorizontalOrientation) { return BoxConstraints( - maxWidth: _parentConstraints.maxWidth - padding, - maxHeight: _parentConstraints.maxHeight); + maxWidth: _parentConstraints.maxWidth - padding, + maxHeight: _parentConstraints.maxHeight, + ); } else { return BoxConstraints( - maxWidth: _parentConstraints.maxWidth, - maxHeight: _parentConstraints.maxHeight - padding); + maxWidth: _parentConstraints.maxWidth, + maxHeight: _parentConstraints.maxHeight - padding, + ); } } @@ -646,16 +710,20 @@ class RenderLinearGauge extends RenderBox range.layout(_childConstraints, parentUsesSize: true); final double rangeThickness = _isHorizontalOrientation ? range.size.height : range.size.width; - final LinearElementPosition position = - getEffectiveElementPosition(range.position, range.isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + range.position, + range.isMirrored, + ); switch (position) { case LinearElementPosition.inside: _measureInsideElementSize(rangeThickness); break; case LinearElementPosition.outside: - _outsideWidgetElementSize = - math.max(_outsideWidgetElementSize, rangeThickness - _axisTop); + _outsideWidgetElementSize = math.max( + _outsideWidgetElementSize, + rangeThickness - _axisTop, + ); break; case LinearElementPosition.cross: _measureCrossElementSize(rangeThickness); @@ -672,10 +740,11 @@ class RenderLinearGauge extends RenderBox barPointer.layout(_childConstraints, parentUsesSize: true); _layoutPointerChild( - renderObject: barPointer, - position: barPointer.position, - thickness: barPointer.thickness, - offset: barPointer.offset); + renderObject: barPointer, + position: barPointer.position, + thickness: barPointer.thickness, + offset: barPointer.offset, + ); } } } @@ -683,15 +752,17 @@ class RenderLinearGauge extends RenderBox void _measureMarkerPointersSize() { if (_markerPointers.isNotEmpty) { for (final dynamic markerPointer in _markerPointers) { - final double thickness = _isHorizontalOrientation - ? markerPointer.size.height as double - : markerPointer.size.width as double; + final double thickness = + _isHorizontalOrientation + ? markerPointer.size.height as double + : markerPointer.size.width as double; _layoutPointerChild( - renderObject: markerPointer, - position: markerPointer.position, - thickness: thickness, - offset: markerPointer.offset); + renderObject: markerPointer, + position: markerPointer.position, + thickness: thickness, + offset: markerPointer.offset, + ); } } } @@ -701,22 +772,25 @@ class RenderLinearGauge extends RenderBox double actualHeight, actualWidth; if (_isHorizontalOrientation) { - actualHeight = constraints.hasBoundedHeight - ? constraints.maxHeight - : _axisWidgetThickness + - _outsideWidgetElementSize + - _insideWidgetElementSize; + actualHeight = + constraints.hasBoundedHeight + ? constraints.maxHeight + : _axisWidgetThickness + + _outsideWidgetElementSize + + _insideWidgetElementSize; actualWidth = _parentConstraints.maxWidth; } else { actualHeight = _parentConstraints.maxHeight; - actualWidth = constraints.hasBoundedWidth - ? constraints.maxWidth - : _axisWidgetThickness + - _outsideWidgetElementSize + - _insideWidgetElementSize; + actualWidth = + constraints.hasBoundedWidth + ? constraints.maxWidth + : _axisWidgetThickness + + _outsideWidgetElementSize + + _insideWidgetElementSize; } - _actualSizeDelta = (_isHorizontalOrientation ? actualHeight : actualWidth) - + _actualSizeDelta = + (_isHorizontalOrientation ? actualHeight : actualWidth) - (_axisWidgetThickness + _outsideWidgetElementSize + _insideWidgetElementSize); @@ -752,13 +826,16 @@ class RenderLinearGauge extends RenderBox _pointX = axis!.valueToPixel(range.startValue).abs(); - final LinearElementPosition position = - getEffectiveElementPosition(range.position, range.isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + range.position, + range.isMirrored, + ); final double axisSize = axis!.showAxisTrack ? axis!.thickness : 0.0; switch (position) { case LinearElementPosition.inside: - _pointY = _outsideWidgetElementSize + + _pointY = + _outsideWidgetElementSize + _axisTop + axisSize + (_actualSizeDelta! / 2); @@ -771,7 +848,8 @@ class RenderLinearGauge extends RenderBox _pointY = positionY + (_actualSizeDelta! / 2); break; case LinearElementPosition.cross: - _pointY = _outsideWidgetElementSize + + _pointY = + _outsideWidgetElementSize + (_actualSizeDelta! / 2) + _getCrossElementPosition(thickness); break; @@ -788,23 +866,28 @@ class RenderLinearGauge extends RenderBox for (final RenderLinearBarPointer barPointer in _barPointers) { _pointX = axis!.valueToPixel(axis!.minimum).abs(); - final double barWidth = _isHorizontalOrientation - ? barPointer.size.width - : barPointer.size.height; + final double barWidth = + _isHorizontalOrientation + ? barPointer.size.width + : barPointer.size.height; - final LinearElementPosition position = - getEffectiveElementPosition(barPointer.position, axis!.isMirrored); + final LinearElementPosition position = getEffectiveElementPosition( + barPointer.position, + axis!.isMirrored, + ); switch (position) { case LinearElementPosition.inside: - _pointY = _outsideWidgetElementSize + + _pointY = + _outsideWidgetElementSize + _axisTop + axis!.getAxisLineThickness() + barPointer.offset + (_actualSizeDelta! / 2); break; case LinearElementPosition.outside: - _pointY = (_actualSizeDelta! / 2) + + _pointY = + (_actualSizeDelta! / 2) + (barPointer.offset * -1) + (_outsideWidgetElementSize + _axisTop > barPointer.thickness ? _outsideWidgetElementSize + @@ -813,7 +896,8 @@ class RenderLinearGauge extends RenderBox : 0); break; case LinearElementPosition.cross: - _pointY = _outsideWidgetElementSize + + _pointY = + _outsideWidgetElementSize + (_actualSizeDelta! / 2) + _getCrossElementPosition(barPointer.thickness); break; @@ -915,7 +999,9 @@ class RenderLinearGauge extends RenderBox } void _applyConstraintBehavior( - RenderLinearPointerBase markerRenderObject, double currentValue) { + RenderLinearPointerBase markerRenderObject, + double currentValue, + ) { if (currentValue > _markerRenderObject.dragRangeMin! && currentValue < _markerRenderObject.dragRangeMax!) { _markerRenderObject.constrainedBy = ConstrainedBy.none; @@ -934,7 +1020,9 @@ class RenderLinearGauge extends RenderBox // This method for pull drag behavior for markers. // ignore: unused_element void _applyPullBehavior( - RenderLinearPointerBase markerRenderObject, double currentValue) { + RenderLinearPointerBase markerRenderObject, + double currentValue, + ) { for (final RenderLinearPointerBase markerPointer in _markerPointers) { if (markerPointer != markerRenderObject) { if (currentValue < _dragStartValue!) { @@ -972,12 +1060,14 @@ class RenderLinearGauge extends RenderBox } void _findDraggableRange(RenderLinearPointerBase pointer) { - pointer.dragRangeMin = pointer.constrainedBy == ConstrainedBy.min - ? pointer.value - : axis!.minimum; - pointer.dragRangeMax = pointer.constrainedBy == ConstrainedBy.max - ? pointer.value - : axis!.maximum; + pointer.dragRangeMin = + pointer.constrainedBy == ConstrainedBy.min + ? pointer.value + : axis!.minimum; + pointer.dragRangeMax = + pointer.constrainedBy == ConstrainedBy.max + ? pointer.value + : axis!.maximum; for (int i = 0; i < _markerPointers.length; i++) { final double currentValue = _markerPointers[i].value; if (pointer.constrainedBy != ConstrainedBy.min && @@ -1039,42 +1129,58 @@ class RenderLinearGauge extends RenderBox @override void paint(PaintingContext context, Offset offset) { context.pushClipRect( - needsCompositing, offset, Rect.fromLTWH(0, 0, size.width, size.height), - (PaintingContext context, Offset offset) { - defaultPaint(context, offset); - // There's no point in drawing the children if we're empty. - if (size.isEmpty) { - return; - } + needsCompositing, + offset, + Rect.fromLTWH(0, 0, size.width, size.height), + (PaintingContext context, Offset offset) { + defaultPaint(context, offset); + // There's no point in drawing the children if we're empty. + if (size.isEmpty) { + return; + } - assert(() { - // Only set this if it's null to save work. It gets reset to null if the - // _direction changes. - final List debugOverflowHints = [ - ErrorDescription( + assert(() { + // Only set this if it's null to save work. It gets reset to null if the + // _direction changes. + final List debugOverflowHints = [ + ErrorDescription( 'The edge of the $runtimeType that is overflowing has been marked ' 'in the rendering with a yellow and black striped pattern. This is ' - 'usually caused by the contents being too big for the $runtimeType.'), - ]; - - // Simulate a child rect that overflows by the right amount. This child - // rect is never used for drawing, just for determining the overflow - // location and amount. - Rect overflowChildRect; - - if (_isHorizontalOrientation) { - overflowChildRect = - Rect.fromLTWH(0.0, 0.0, 0.0, size.height + _overflow!); - } else { - overflowChildRect = - Rect.fromLTWH(0.0, 0.0, size.width + _overflow!, 0.0); - } + 'usually caused by the contents being too big for the $runtimeType.', + ), + ]; + + // Simulate a child rect that overflows by the right amount. This child + // rect is never used for drawing, just for determining the overflow + // location and amount. + Rect overflowChildRect; + + if (_isHorizontalOrientation) { + overflowChildRect = Rect.fromLTWH( + 0.0, + 0.0, + 0.0, + size.height + _overflow!, + ); + } else { + overflowChildRect = Rect.fromLTWH( + 0.0, + 0.0, + size.width + _overflow!, + 0.0, + ); + } - paintOverflowIndicator( - context, offset, Offset.zero & size, overflowChildRect, - overflowHints: debugOverflowHints); - return true; - }()); - }); + paintOverflowIndicator( + context, + offset, + Offset.zero & size, + overflowChildRect, + overflowHints: debugOverflowHints, + ); + return true; + }()); + }, + ); } } diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_scope.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_scope.dart index 62a91f212..49478b53d 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_scope.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/gauge/linear_gauge_scope.dart @@ -6,15 +6,15 @@ import '../utils/enum.dart'; /// Linear gauge scope class. class LinearGaugeScope extends InheritedWidget { /// Creates a object for Linear gauge scope. - const LinearGaugeScope( - {Key? key, - required Widget child, - required this.orientation, - required this.isMirrored, - required this.isAxisInversed, - this.animation, - this.animationController}) - : super(key: key, child: child); + const LinearGaugeScope({ + Key? key, + required Widget child, + required this.orientation, + required this.isMirrored, + required this.isAxisInversed, + this.animation, + this.animationController, + }) : super(key: key, child: child); /// Child animation. final Animation? animation; @@ -35,9 +35,11 @@ class LinearGaugeScope extends InheritedWidget { static LinearGaugeScope of(BuildContext context) { late LinearGaugeScope scope; - final InheritedWidget widget = context - .getElementForInheritedWidgetOfExactType()! - .widget as InheritedWidget; + final InheritedWidget widget = + context + .getElementForInheritedWidgetOfExactType()! + .widget + as InheritedWidget; if (widget is LinearGaugeScope) { scope = widget; diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_pointer.dart index aac73127a..a2cdab80e 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_pointer.dart @@ -7,24 +7,24 @@ import '../../linear_gauge/utils/enum.dart'; /// [LinearBarPointer] has properties for customizing the linear gauge bar pointer. class LinearBarPointer extends SingleChildRenderObjectWidget { /// Creates a new instance for [LinearBarPointer]. - const LinearBarPointer( - {Key? key, - required this.value, - this.enableAnimation = true, - this.animationDuration = 1000, - this.animationType = LinearAnimationType.ease, - this.onAnimationCompleted, - this.thickness = 5.0, - double offset = 0, - this.edgeStyle = LinearEdgeStyle.bothFlat, - this.position = LinearElementPosition.cross, - this.shaderCallback, - this.color, - this.borderColor, - this.borderWidth = 0, - Widget? child}) - : offset = offset > 0 ? offset : 0, - super(key: key, child: child); + const LinearBarPointer({ + Key? key, + required this.value, + this.enableAnimation = true, + this.animationDuration = 1000, + this.animationType = LinearAnimationType.ease, + this.onAnimationCompleted, + this.thickness = 5.0, + double offset = 0, + this.edgeStyle = LinearEdgeStyle.bothFlat, + this.position = LinearElementPosition.cross, + this.shaderCallback, + this.color, + this.borderColor, + this.borderWidth = 0, + Widget? child, + }) : offset = offset > 0 ? offset : 0, + super(key: key, child: child); /// Specifies the pointer value of [SfLinearGauge.barPointers]. /// This value must be between the min and max value of an axis track. @@ -272,36 +272,41 @@ class LinearBarPointer extends SingleChildRenderObjectWidget { final ThemeData themeData = Theme.of(context); final bool isMaterial3 = themeData.useMaterial3; final bool isDarkTheme = themeData.brightness == Brightness.dark; - final Color barPointerColor = isMaterial3 - ? (isDarkTheme ? const Color(0XFFFFF500) : const Color(0XFF06AEE0)) - : themeData.colorScheme.primary; + final Color barPointerColor = + isMaterial3 + ? (isDarkTheme ? const Color(0XFFFFF500) : const Color(0XFF06AEE0)) + : themeData.colorScheme.primary; return RenderLinearBarPointer( - value: value, - edgeStyle: edgeStyle, - shaderCallback: shaderCallback, - color: color ?? barPointerColor, - borderColor: borderColor ?? barPointerColor, - borderWidth: borderWidth, - thickness: thickness, - offset: offset, - position: position, - orientation: linearGaugeScope.orientation, - isAxisInversed: linearGaugeScope.isAxisInversed, - onAnimationCompleted: onAnimationCompleted, - animationController: linearGaugeScope.animationController, - pointerAnimation: linearGaugeScope.animation); + value: value, + edgeStyle: edgeStyle, + shaderCallback: shaderCallback, + color: color ?? barPointerColor, + borderColor: borderColor ?? barPointerColor, + borderWidth: borderWidth, + thickness: thickness, + offset: offset, + position: position, + orientation: linearGaugeScope.orientation, + isAxisInversed: linearGaugeScope.isAxisInversed, + onAnimationCompleted: onAnimationCompleted, + animationController: linearGaugeScope.animationController, + pointerAnimation: linearGaugeScope.animation, + ); } @override void updateRenderObject( - BuildContext context, RenderLinearBarPointer renderObject) { + BuildContext context, + RenderLinearBarPointer renderObject, + ) { final LinearGaugeScope linearGaugeScope = LinearGaugeScope.of(context); final ThemeData themeData = Theme.of(context); final bool isMaterial3 = themeData.useMaterial3; final bool isDarkTheme = themeData.brightness == Brightness.dark; - final Color barPointerColor = isMaterial3 - ? (isDarkTheme ? const Color(0XFFFFF500) : const Color(0XFF06AEE0)) - : themeData.colorScheme.primary; + final Color barPointerColor = + isMaterial3 + ? (isDarkTheme ? const Color(0XFFFFF500) : const Color(0XFF06AEE0)) + : themeData.colorScheme.primary; renderObject ..value = value ..edgeStyle = edgeStyle diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_renderer.dart index e92bf6124..98c1df401 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_bar_renderer.dart @@ -10,34 +10,34 @@ import '../../linear_gauge/utils/linear_gauge_helper.dart'; /// Represents the render object of bar pointer. class RenderLinearBarPointer extends RenderOpacity { /// Creates a instance for [RenderLinearBarPointer]. - RenderLinearBarPointer( - {required double value, - required LinearEdgeStyle edgeStyle, - ShaderCallback? shaderCallback, - required Color color, - required Color borderColor, - required double borderWidth, - required double thickness, - required double offset, - required LinearElementPosition position, - required LinearGaugeOrientation orientation, - Animation? pointerAnimation, - VoidCallback? onAnimationCompleted, - this.animationController, - required bool isAxisInversed}) - : _value = value, - _edgeStyle = edgeStyle, - _shaderCallback = shaderCallback, - _color = color, - _borderColor = borderColor, - _borderWidth = borderWidth, - _thickness = thickness, - _offset = offset, - _position = position, - _orientation = orientation, - _pointerAnimation = pointerAnimation, - _onAnimationCompleted = onAnimationCompleted, - _isAxisInversed = isAxisInversed { + RenderLinearBarPointer({ + required double value, + required LinearEdgeStyle edgeStyle, + ShaderCallback? shaderCallback, + required Color color, + required Color borderColor, + required double borderWidth, + required double thickness, + required double offset, + required LinearElementPosition position, + required LinearGaugeOrientation orientation, + Animation? pointerAnimation, + VoidCallback? onAnimationCompleted, + this.animationController, + required bool isAxisInversed, + }) : _value = value, + _edgeStyle = edgeStyle, + _shaderCallback = shaderCallback, + _color = color, + _borderColor = borderColor, + _borderWidth = borderWidth, + _thickness = thickness, + _offset = offset, + _position = position, + _orientation = orientation, + _pointerAnimation = pointerAnimation, + _onAnimationCompleted = onAnimationCompleted, + _isAxisInversed = isAxisInversed { _barPaint = Paint(); _isHorizontal = orientation == LinearGaugeOrientation.horizontal; _path = Path(); @@ -70,7 +70,11 @@ class RenderLinearBarPointer extends RenderOpacity { if (animationController != null && animationController!.isAnimating) { animationController!.stop(); _oldBarRect = Rect.fromLTWH( - _barPointerOffset.dx, _barPointerOffset.dy, size.width, size.height); + _barPointerOffset.dx, + _barPointerOffset.dy, + size.width, + size.height, + ); } _value = value; @@ -318,8 +322,10 @@ class RenderLinearBarPointer extends RenderOpacity { child!.layout(BoxConstraints.tight(controlSize)); } - size = Size(min(controlSize.width, constraints.maxWidth), - min(controlSize.height, constraints.maxHeight)); + size = Size( + min(controlSize.width, constraints.maxWidth), + min(controlSize.height, constraints.maxHeight), + ); } ///Measures the bar rect. @@ -336,15 +342,15 @@ class RenderLinearBarPointer extends RenderOpacity { if (_isHorizontal) { _barRect = Rect.fromLTWH( - offset.dx + - (isAxisInversed - ? (size.width - _oldBarRect.width) - - ((size.width - _oldBarRect.width) * animationValue) - : 0), - offset.dy, - _oldBarRect.width + - ((size.width - _oldBarRect.width) * animationValue), - size.height); + offset.dx + + (isAxisInversed + ? (size.width - _oldBarRect.width) - + ((size.width - _oldBarRect.width) * animationValue) + : 0), + offset.dy, + _oldBarRect.width + ((size.width - _oldBarRect.width) * animationValue), + size.height, + ); } else { _barRect = Rect.fromLTWH( offset.dx, @@ -361,10 +367,11 @@ class RenderLinearBarPointer extends RenderOpacity { if (borderWidth > 0) { _barRect = Rect.fromLTWH( - _barRect.left + borderWidth / 2, - _barRect.top + borderWidth / 2, - _barRect.width - borderWidth, - _barRect.height - borderWidth); + _barRect.left + borderWidth / 2, + _barRect.top + borderWidth / 2, + _barRect.width - borderWidth, + _barRect.height - borderWidth, + ); } } @@ -376,21 +383,28 @@ class RenderLinearBarPointer extends RenderOpacity { break; case LinearEdgeStyle.bothCurve: _path.addRRect( - RRect.fromRectAndRadius(_barRect, Radius.circular(thickness / 2))); + RRect.fromRectAndRadius(_barRect, Radius.circular(thickness / 2)), + ); break; case LinearEdgeStyle.startCurve: - _path.addRRect(getStartCurve( + _path.addRRect( + getStartCurve( isHorizontal: _isHorizontal, isAxisInversed: isAxisInversed, rect: _barRect, - radius: thickness / 2)); + radius: thickness / 2, + ), + ); break; case LinearEdgeStyle.endCurve: - _path.addRRect(getEndCurve( + _path.addRRect( + getEndCurve( isHorizontal: _isHorizontal, isAxisInversed: isAxisInversed, rect: _barRect, - radius: thickness / 2)); + radius: thickness / 2, + ), + ); break; } diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_marker_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_marker_pointer.dart index 5884d7f7c..3f316b50c 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_marker_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_marker_pointer.dart @@ -5,19 +5,20 @@ import '../../linear_gauge/utils/enum.dart'; /// [LinearMarkerPointer] has properties for customizing linear gauge pointers. abstract class LinearMarkerPointer { /// Creates a pointer for linear axis with the default or required properties. - LinearMarkerPointer( - {required this.value, - this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.enableAnimation = false, - this.animationDuration = 1000, - this.animationType = LinearAnimationType.ease, - this.offset = 0.0, - this.markerAlignment = LinearMarkerAlignment.center, - this.position = LinearElementPosition.cross, - this.dragBehavior = LinearMarkerDragBehavior.free, - this.onAnimationCompleted}); + LinearMarkerPointer({ + required this.value, + this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.enableAnimation = false, + this.animationDuration = 1000, + this.animationType = LinearAnimationType.ease, + this.offset = 0.0, + this.markerAlignment = LinearMarkerAlignment.center, + this.position = LinearElementPosition.cross, + this.dragBehavior = LinearMarkerDragBehavior.free, + this.onAnimationCompleted, + }); /// Specifies the linear axis value to place the pointer. /// @@ -114,30 +115,30 @@ abstract class LinearMarkerPointer { /// Represents the render object base class for shape and widget pointer. class RenderLinearPointerBase extends RenderProxyBox { /// Creates a instance for [RenderLinearPointerBase] - RenderLinearPointerBase( - {required double value, - ValueChanged? onChanged, - this.onChangeStart, - this.onChangeEnd, - required double offset, - required LinearElementPosition position, - required LinearMarkerAlignment markerAlignment, - required bool isAxisInversed, - required bool isMirrored, - Animation? pointerAnimation, - VoidCallback? onAnimationCompleted, - required LinearMarkerDragBehavior dragBehavior, - this.animationController}) - : _value = value, - _onChanged = onChanged, - _offset = offset, - _position = position, - _dragBehavior = dragBehavior, - _markerAlignment = markerAlignment, - _pointerAnimation = pointerAnimation, - _isAxisInversed = isAxisInversed, - _isMirrored = isMirrored, - _onAnimationCompleted = onAnimationCompleted; + RenderLinearPointerBase({ + required double value, + ValueChanged? onChanged, + this.onChangeStart, + this.onChangeEnd, + required double offset, + required LinearElementPosition position, + required LinearMarkerAlignment markerAlignment, + required bool isAxisInversed, + required bool isMirrored, + Animation? pointerAnimation, + VoidCallback? onAnimationCompleted, + required LinearMarkerDragBehavior dragBehavior, + this.animationController, + }) : _value = value, + _onChanged = onChanged, + _offset = offset, + _position = position, + _dragBehavior = dragBehavior, + _markerAlignment = markerAlignment, + _pointerAnimation = pointerAnimation, + _isAxisInversed = isAxisInversed, + _isMirrored = isMirrored, + _onAnimationCompleted = onAnimationCompleted; /// Gets or sets the shape pointer old value. double? oldValue; diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_pointer.dart index 76e7f0c8a..e4f3dd9bd 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_pointer.dart @@ -8,30 +8,30 @@ import '../../linear_gauge/utils/enum.dart'; class LinearShapePointer extends LeafRenderObjectWidget implements LinearMarkerPointer { /// Creates a shape marker pointer for linear axis. - const LinearShapePointer( - {Key? key, - required this.value, - this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.enableAnimation = true, - this.animationDuration = 1000, - this.animationType = LinearAnimationType.ease, - this.onAnimationCompleted, - this.width, - this.height, - double offset = 0.0, - this.markerAlignment = LinearMarkerAlignment.center, - this.position = LinearElementPosition.outside, - this.shapeType = LinearShapePointerType.invertedTriangle, - this.dragBehavior = LinearMarkerDragBehavior.free, - this.color, - this.borderColor, - this.borderWidth = 0.0, - this.elevation = 0, - this.elevationColor = Colors.black}) - : offset = offset > 0 ? offset : 0, - super(key: key); + const LinearShapePointer({ + Key? key, + required this.value, + this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.enableAnimation = true, + this.animationDuration = 1000, + this.animationType = LinearAnimationType.ease, + this.onAnimationCompleted, + this.width, + this.height, + double offset = 0.0, + this.markerAlignment = LinearMarkerAlignment.center, + this.position = LinearElementPosition.outside, + this.shapeType = LinearShapePointerType.invertedTriangle, + this.dragBehavior = LinearMarkerDragBehavior.free, + this.color, + this.borderColor, + this.borderWidth = 0.0, + this.elevation = 0, + this.elevationColor = Colors.black, + }) : offset = offset > 0 ? offset : 0, + super(key: key); /// Specifies the pointer value of [LinearShapePointer]. /// This value must be between the min and max value of an axis track. @@ -443,47 +443,52 @@ class LinearShapePointer extends LeafRenderObjectWidget final ThemeData theme = Theme.of(context); final bool isDarkTheme = theme.brightness == Brightness.dark; final bool isMaterial3 = theme.useMaterial3; - final Color shapePointerColor = isMaterial3 - ? theme.colorScheme.onSurfaceVariant - : isDarkTheme + final Color shapePointerColor = + isMaterial3 + ? theme.colorScheme.onSurfaceVariant + : isDarkTheme ? theme.colorScheme.onSurface.withValues(alpha: 0.70) : theme.colorScheme.onSurface.withValues(alpha: 0.54); return RenderLinearShapePointer( - value: value, - onChanged: onChanged, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - color: color ?? shapePointerColor, - borderColor: borderColor ?? shapePointerColor, - borderWidth: borderWidth, - width: width ?? (shapeType == LinearShapePointerType.diamond ? 12 : 16), - height: - height ?? (shapeType == LinearShapePointerType.rectangle ? 8 : 16), - offset: offset, - position: position, - shapeType: shapeType, - elevation: elevation, - elevationColor: elevationColor, - orientation: linearGaugeScope.orientation, - isMirrored: linearGaugeScope.isMirrored, - isAxisInversed: linearGaugeScope.isAxisInversed, - markerAlignment: markerAlignment, - animationController: linearGaugeScope.animationController, - dragBehavior: dragBehavior, - onAnimationCompleted: onAnimationCompleted, - pointerAnimation: linearGaugeScope.animation); + value: value, + onChanged: onChanged, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + color: color ?? shapePointerColor, + borderColor: borderColor ?? shapePointerColor, + borderWidth: borderWidth, + width: width ?? (shapeType == LinearShapePointerType.diamond ? 12 : 16), + height: + height ?? (shapeType == LinearShapePointerType.rectangle ? 8 : 16), + offset: offset, + position: position, + shapeType: shapeType, + elevation: elevation, + elevationColor: elevationColor, + orientation: linearGaugeScope.orientation, + isMirrored: linearGaugeScope.isMirrored, + isAxisInversed: linearGaugeScope.isAxisInversed, + markerAlignment: markerAlignment, + animationController: linearGaugeScope.animationController, + dragBehavior: dragBehavior, + onAnimationCompleted: onAnimationCompleted, + pointerAnimation: linearGaugeScope.animation, + ); } @override void updateRenderObject( - BuildContext context, RenderLinearShapePointer renderObject) { + BuildContext context, + RenderLinearShapePointer renderObject, + ) { final LinearGaugeScope linearGaugeScope = LinearGaugeScope.of(context); final ThemeData theme = Theme.of(context); final bool isDarkTheme = theme.brightness == Brightness.dark; final bool isMaterial3 = theme.useMaterial3; - final Color shapePointerColor = isMaterial3 - ? theme.colorScheme.onSurfaceVariant - : isDarkTheme + final Color shapePointerColor = + isMaterial3 + ? theme.colorScheme.onSurfaceVariant + : isDarkTheme ? theme.colorScheme.onSurface.withValues(alpha: 0.70) : theme.colorScheme.onSurface.withValues(alpha: 0.54); diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_renderer.dart index 6f95c6891..939a4eae2 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_shape_renderer.dart @@ -33,29 +33,30 @@ class RenderLinearShapePointer extends RenderLinearPointerBase { VoidCallback? onAnimationCompleted, required LinearMarkerDragBehavior dragBehavior, AnimationController? animationController, - }) : _color = color, - _borderColor = borderColor, - _borderWidth = borderWidth, - _shapeType = shapeType, - _elevation = elevation, - _orientation = orientation, - _elevationColor = elevationColor, - _width = width, - _height = height, - super( - value: value, - onChanged: onChanged, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - offset: offset, - position: position, - dragBehavior: dragBehavior, - markerAlignment: markerAlignment, - isMirrored: isMirrored, - isAxisInversed: isAxisInversed, - pointerAnimation: pointerAnimation, - animationController: animationController, - onAnimationCompleted: onAnimationCompleted) { + }) : _color = color, + _borderColor = borderColor, + _borderWidth = borderWidth, + _shapeType = shapeType, + _elevation = elevation, + _orientation = orientation, + _elevationColor = elevationColor, + _width = width, + _height = height, + super( + value: value, + onChanged: onChanged, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + offset: offset, + position: position, + dragBehavior: dragBehavior, + markerAlignment: markerAlignment, + isMirrored: isMirrored, + isAxisInversed: isAxisInversed, + pointerAnimation: pointerAnimation, + animationController: animationController, + onAnimationCompleted: onAnimationCompleted, + ) { _shapePaint = Paint(); _borderPaint = Paint(); } @@ -233,7 +234,9 @@ class RenderLinearShapePointer extends RenderLinearPointerBase { @override void performLayout() { size = Size( - min(width, constraints.maxWidth), min(height, constraints.maxHeight)); + min(width, constraints.maxWidth), + min(height, constraints.maxHeight), + ); } @override @@ -246,10 +249,11 @@ class RenderLinearShapePointer extends RenderLinearPointerBase { if (pointerAnimation == null || (pointerAnimation != null && pointerAnimation!.value > 0)) { _shapeRect = Rect.fromLTWH( - offset.dx + borderWidth / 2, - offset.dy + borderWidth / 2, - size.width - borderWidth, - size.height - borderWidth); + offset.dx + borderWidth / 2, + offset.dy + borderWidth / 2, + size.width - borderWidth, + size.height - borderWidth, + ); _shapePaint.style = PaintingStyle.fill; _shapePaint.color = color; @@ -300,13 +304,14 @@ class RenderLinearShapePointer extends RenderLinearPointerBase { } core.paint( - canvas: canvas, - rect: _shapeRect, - elevation: elevation, - shapeType: markerType, - elevationColor: elevationColor, - paint: _shapePaint, - borderPaint: _borderPaint); + canvas: canvas, + rect: _shapeRect, + elevation: elevation, + shapeType: markerType, + elevationColor: elevationColor, + paint: _shapePaint, + borderPaint: _borderPaint, + ); } } } diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_pointer.dart index 955948520..d060452d8 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_pointer.dart @@ -10,23 +10,23 @@ import '../../linear_gauge/utils/enum.dart'; class LinearWidgetPointer extends SingleChildRenderObjectWidget implements LinearMarkerPointer { /// Creates a widget marker pointer. - const LinearWidgetPointer( - {Key? key, - required this.value, - this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.enableAnimation = true, - this.animationDuration = 1000, - this.animationType = LinearAnimationType.ease, - this.onAnimationCompleted, - double offset = 0.0, - this.position = LinearElementPosition.cross, - this.markerAlignment = LinearMarkerAlignment.center, - this.dragBehavior = LinearMarkerDragBehavior.free, - required Widget child}) - : offset = offset > 0 ? offset : 0, - super(key: key, child: child); + const LinearWidgetPointer({ + Key? key, + required this.value, + this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.enableAnimation = true, + this.animationDuration = 1000, + this.animationType = LinearAnimationType.ease, + this.onAnimationCompleted, + double offset = 0.0, + this.position = LinearElementPosition.cross, + this.markerAlignment = LinearMarkerAlignment.center, + this.dragBehavior = LinearMarkerDragBehavior.free, + required Widget child, + }) : offset = offset > 0 ? offset : 0, + super(key: key, child: child); /// Specifies the pointer value for [LinearWidgetPointer]. /// This value must be between the min and max value of an axis track. @@ -320,24 +320,27 @@ class LinearWidgetPointer extends SingleChildRenderObjectWidget RenderObject createRenderObject(BuildContext context) { final LinearGaugeScope scope = LinearGaugeScope.of(context); return RenderLinearWidgetPointer( - value: value, - onChanged: onChanged, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - offset: offset, - position: position, - markerAlignment: markerAlignment, - animationController: scope.animationController, - onAnimationCompleted: onAnimationCompleted, - pointerAnimation: scope.animation, - isAxisInversed: scope.isAxisInversed, - isMirrored: scope.isMirrored, - dragBehavior: dragBehavior); + value: value, + onChanged: onChanged, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + offset: offset, + position: position, + markerAlignment: markerAlignment, + animationController: scope.animationController, + onAnimationCompleted: onAnimationCompleted, + pointerAnimation: scope.animation, + isAxisInversed: scope.isAxisInversed, + isMirrored: scope.isMirrored, + dragBehavior: dragBehavior, + ); } @override void updateRenderObject( - BuildContext context, RenderLinearWidgetPointer renderObject) { + BuildContext context, + RenderLinearWidgetPointer renderObject, + ) { final LinearGaugeScope scope = LinearGaugeScope.of(context); renderObject diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_renderer.dart index dc7d961fe..9d25eb5b7 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/pointers/linear_widget_renderer.dart @@ -6,35 +6,35 @@ import 'linear_marker_pointer.dart'; /// Represents the render object of shape pointer. class RenderLinearWidgetPointer extends RenderLinearPointerBase { /// Creates a instance for [RenderLinearWidgetPointer]. - RenderLinearWidgetPointer( - {required double value, - ValueChanged? onChanged, - ValueChanged? onChangeStart, - ValueChanged? onChangeEnd, - required double offset, - required LinearElementPosition position, - required LinearMarkerAlignment markerAlignment, - required bool isAxisInversed, - required bool isMirrored, - Animation? pointerAnimation, - VoidCallback? onAnimationCompleted, - required LinearMarkerDragBehavior dragBehavior, - AnimationController? animationController}) - : super( - value: value, - onChanged: onChanged, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - offset: offset, - position: position, - dragBehavior: dragBehavior, - markerAlignment: markerAlignment, - isAxisInversed: isAxisInversed, - isMirrored: isMirrored, - pointerAnimation: pointerAnimation, - animationController: animationController, - onAnimationCompleted: onAnimationCompleted, - ); + RenderLinearWidgetPointer({ + required double value, + ValueChanged? onChanged, + ValueChanged? onChangeStart, + ValueChanged? onChangeEnd, + required double offset, + required LinearElementPosition position, + required LinearMarkerAlignment markerAlignment, + required bool isAxisInversed, + required bool isMirrored, + Animation? pointerAnimation, + VoidCallback? onAnimationCompleted, + required LinearMarkerDragBehavior dragBehavior, + AnimationController? animationController, + }) : super( + value: value, + onChanged: onChanged, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + offset: offset, + position: position, + dragBehavior: dragBehavior, + markerAlignment: markerAlignment, + isAxisInversed: isAxisInversed, + isMirrored: isMirrored, + pointerAnimation: pointerAnimation, + animationController: animationController, + onAnimationCompleted: onAnimationCompleted, + ); @override bool hitTestSelf(Offset position) { diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range.dart index 1a715bfba..b1e40a4fe 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range.dart @@ -8,24 +8,24 @@ import '../../linear_gauge/utils/enum.dart'; class LinearGaugeRange extends SingleChildRenderObjectWidget { /// Creates a new range in linear gauge. /// - const LinearGaugeRange( - {Key? key, - this.startValue = 0, - double? midValue, - this.endValue = 100, - this.startWidth = 5.0, - this.endWidth = 5.0, - double? midWidth, - this.color, - this.shaderCallback, - this.rangeShapeType = LinearRangeShapeType.flat, - this.edgeStyle = LinearEdgeStyle.bothFlat, - this.position = LinearElementPosition.outside, - Widget? child}) - : assert(startValue <= endValue), - midValue = midValue ?? startValue, - midWidth = midWidth ?? startWidth, - super(key: key, child: child); + const LinearGaugeRange({ + Key? key, + this.startValue = 0, + double? midValue, + this.endValue = 100, + this.startWidth = 5.0, + this.endWidth = 5.0, + double? midWidth, + this.color, + this.shaderCallback, + this.rangeShapeType = LinearRangeShapeType.flat, + this.edgeStyle = LinearEdgeStyle.bothFlat, + this.position = LinearElementPosition.outside, + Widget? child, + }) : assert(startValue <= endValue), + midValue = midValue ?? startValue, + midWidth = midWidth ?? startWidth, + super(key: key, child: child); /// Specifies the start value of the range. /// @@ -205,32 +205,37 @@ class LinearGaugeRange extends SingleChildRenderObjectWidget { final ThemeData theme = Theme.of(context); final bool isDarkTheme = theme.brightness == Brightness.dark; return RenderLinearRange( - color: color ?? - (isDarkTheme ? const Color(0xffFF7B7B) : const Color(0xffF45656)), - position: position, - startValue: startValue, - midValue: midValue, - endValue: endValue, - startThickness: startWidth, - midThickness: midWidth, - endThickness: endWidth, - rangeShapeType: rangeShapeType, - shaderCallback: shaderCallback, - edgeStyle: edgeStyle, - orientation: linearGaugeScope.orientation, - isMirrored: linearGaugeScope.isMirrored, - isAxisInversed: linearGaugeScope.isAxisInversed, - rangeAnimation: linearGaugeScope.animation); + color: + color ?? + (isDarkTheme ? const Color(0xffFF7B7B) : const Color(0xffF45656)), + position: position, + startValue: startValue, + midValue: midValue, + endValue: endValue, + startThickness: startWidth, + midThickness: midWidth, + endThickness: endWidth, + rangeShapeType: rangeShapeType, + shaderCallback: shaderCallback, + edgeStyle: edgeStyle, + orientation: linearGaugeScope.orientation, + isMirrored: linearGaugeScope.isMirrored, + isAxisInversed: linearGaugeScope.isAxisInversed, + rangeAnimation: linearGaugeScope.animation, + ); } @override void updateRenderObject( - BuildContext context, RenderLinearRange renderObject) { + BuildContext context, + RenderLinearRange renderObject, + ) { final LinearGaugeScope linearGaugeScope = LinearGaugeScope.of(context); final ThemeData theme = Theme.of(context); final bool isDarkTheme = theme.brightness == Brightness.dark; renderObject - ..color = color ?? + ..color = + color ?? (isDarkTheme ? const Color(0xffFF7B7B) : const Color(0xffF45656)) ..position = position ..startValue = startValue diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range_renderer.dart index 062477ab4..18f853ec8 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/range/linear_gauge_range_renderer.dart @@ -10,37 +10,37 @@ import '../../linear_gauge/utils/linear_gauge_helper.dart'; /// Represents the render object of range element. class RenderLinearRange extends RenderOpacity { ///Creates a instance for RenderLinearRange. - RenderLinearRange( - {required double startValue, - required double midValue, - required double endValue, - required double startThickness, - required double midThickness, - required double endThickness, - required Color color, - required LinearElementPosition position, - required LinearRangeShapeType rangeShapeType, - ShaderCallback? shaderCallback, - required LinearEdgeStyle edgeStyle, - required LinearGaugeOrientation orientation, - Animation? rangeAnimation, - required bool isAxisInversed, - required bool isMirrored}) - : _startValue = startValue, - _midValue = midValue, - _endValue = endValue, - _startThickness = startThickness, - _midThickness = midThickness, - _endThickness = endThickness, - _color = color, - _position = position, - _rangeShapeType = rangeShapeType, - _shaderCallback = shaderCallback, - _edgeStyle = edgeStyle, - _orientation = orientation, - _rangeAnimation = rangeAnimation, - _isAxisInversed = isAxisInversed, - _isMirrored = isMirrored { + RenderLinearRange({ + required double startValue, + required double midValue, + required double endValue, + required double startThickness, + required double midThickness, + required double endThickness, + required Color color, + required LinearElementPosition position, + required LinearRangeShapeType rangeShapeType, + ShaderCallback? shaderCallback, + required LinearEdgeStyle edgeStyle, + required LinearGaugeOrientation orientation, + Animation? rangeAnimation, + required bool isAxisInversed, + required bool isMirrored, + }) : _startValue = startValue, + _midValue = midValue, + _endValue = endValue, + _startThickness = startThickness, + _midThickness = midThickness, + _endThickness = endThickness, + _color = color, + _position = position, + _rangeShapeType = rangeShapeType, + _shaderCallback = shaderCallback, + _edgeStyle = edgeStyle, + _orientation = orientation, + _rangeAnimation = rangeAnimation, + _isAxisInversed = isAxisInversed, + _isMirrored = isMirrored { _rangePaint = Paint()..color = Colors.black12; _rangeOffsets = List.filled(5, Offset.zero); _isHorizontal = orientation == LinearGaugeOrientation.horizontal; @@ -299,8 +299,10 @@ class RenderLinearRange extends RenderOpacity { @override void performLayout() { - final double thickness = - max(max(startThickness, midThickness), endThickness); + final double thickness = max( + max(startThickness, midThickness), + endThickness, + ); double rangeWidth = 0; if (axis != null) { @@ -319,8 +321,10 @@ class RenderLinearRange extends RenderOpacity { child!.layout(BoxConstraints.tight(controlSize)); } - size = Size(min(controlSize.width, constraints.maxWidth), - min(controlSize.height, constraints.maxHeight)); + size = Size( + min(controlSize.width, constraints.maxWidth), + min(controlSize.height, constraints.maxHeight), + ); } ///Calculation Position based on value. @@ -382,8 +386,12 @@ class RenderLinearRange extends RenderOpacity { path.lineTo(_rangeOffsets[1].dx, _rangeOffsets[1].dy); path.lineTo(_rangeOffsets[2].dx, _rangeOffsets[2].dy); } else { - path.quadraticBezierTo(_rangeOffsets[1].dx, _rangeOffsets[1].dy, - _rangeOffsets[2].dx, _rangeOffsets[2].dy); + path.quadraticBezierTo( + _rangeOffsets[1].dx, + _rangeOffsets[1].dy, + _rangeOffsets[2].dx, + _rangeOffsets[2].dy, + ); } path.lineTo(_rangeOffsets[3].dx, _rangeOffsets[3].dy); @@ -392,8 +400,12 @@ class RenderLinearRange extends RenderOpacity { void _getRangePath() { if (startThickness == endThickness && startThickness == midThickness) { - final Rect rangeRect = Rect.fromLTRB(_rangeOffsets[0].dx, - _rangeOffsets[0].dy, _rangeOffsets[3].dx, _rangeOffsets[3].dy); + final Rect rangeRect = Rect.fromLTRB( + _rangeOffsets[0].dx, + _rangeOffsets[0].dy, + _rangeOffsets[3].dx, + _rangeOffsets[3].dy, + ); if (rangeRect.hasNaN) { return; @@ -404,22 +416,32 @@ class RenderLinearRange extends RenderOpacity { _path.addRect(rangeRect); break; case LinearEdgeStyle.bothCurve: - _path.addRRect(RRect.fromRectAndRadius( - rangeRect, Radius.circular(startThickness / 2))); + _path.addRRect( + RRect.fromRectAndRadius( + rangeRect, + Radius.circular(startThickness / 2), + ), + ); break; case LinearEdgeStyle.startCurve: - _path.addRRect(getStartCurve( + _path.addRRect( + getStartCurve( isHorizontal: _isHorizontal, isAxisInversed: isAxisInversed, rect: rangeRect, - radius: startThickness / 2)); + radius: startThickness / 2, + ), + ); break; case LinearEdgeStyle.endCurve: - _path.addRRect(getEndCurve( + _path.addRRect( + getEndCurve( isHorizontal: _isHorizontal, isAxisInversed: isAxisInversed, rect: rangeRect, - radius: startThickness / 2)); + radius: startThickness / 2, + ), + ); break; } } else { diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/enum.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/enum.dart index c77520321..f07f101a9 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/enum.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/enum.dart @@ -4,7 +4,7 @@ enum LinearGaugeOrientation { vertical, ///LinearGaugeOrientation.horizontal will align the linear gauge in horizontal orientation. - horizontal + horizontal, } /// Apply the shape style for range element. @@ -13,7 +13,7 @@ enum LinearRangeShapeType { flat, /// LinearRangeShapeType.curve apply the curve shape between start and end value. - curve + curve, } /// Apply the edge style for range pointer. @@ -28,7 +28,7 @@ enum LinearEdgeStyle { startCurve, /// LinearEdgeStyle.endCurve apply the rounded corner on end(right) side. - endCurve + endCurve, } /// Apply the different marker pointer. @@ -70,7 +70,7 @@ enum LinearAnimationType { linear, /// LinearAnimationType.slowMiddle animates the pointers with Curves.slowMiddle. - slowMiddle + slowMiddle, } /// Apply the different label position based on Axis. @@ -79,7 +79,7 @@ enum LinearLabelPosition { inside, /// LinearAnimationType.outside places the elements inside the axis. - outside + outside, } /// Apply the different element position based on Axis. @@ -91,7 +91,7 @@ enum LinearElementPosition { outside, /// LinearElementPosition.cross places the elements cross the axis. - cross + cross, } /// Apply the different pointer alignment based on Axis. @@ -103,7 +103,7 @@ enum LinearMarkerAlignment { start, /// LinearMarkerAlignment.end points the axis from outside position. - end + end, } /// Apply the different drag behavior for marker pointers. diff --git a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/linear_gauge_helper.dart b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/linear_gauge_helper.dart index 23049f5b3..d2ac5a0fa 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/linear_gauge_helper.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/linear_gauge/utils/linear_gauge_helper.dart @@ -3,32 +3,44 @@ import 'package:flutter/material.dart'; import '../../linear_gauge/utils/enum.dart'; RRect _getHorizontalStartCurve(Rect rect, double radius) { - return RRect.fromRectAndCorners(rect, - topLeft: Radius.circular(radius), bottomLeft: Radius.circular(radius)); + return RRect.fromRectAndCorners( + rect, + topLeft: Radius.circular(radius), + bottomLeft: Radius.circular(radius), + ); } RRect _getHorizontalEndCurvePath(Rect rect, double radius) { - return RRect.fromRectAndCorners(rect, - topRight: Radius.circular(radius), bottomRight: Radius.circular(radius)); + return RRect.fromRectAndCorners( + rect, + topRight: Radius.circular(radius), + bottomRight: Radius.circular(radius), + ); } RRect _getVerticalStartCurve(Rect rect, double radius) { - return RRect.fromRectAndCorners(rect, - topLeft: Radius.circular(radius), topRight: Radius.circular(radius)); + return RRect.fromRectAndCorners( + rect, + topLeft: Radius.circular(radius), + topRight: Radius.circular(radius), + ); } RRect _getVerticalEndCurvePath(Rect rect, double radius) { - return RRect.fromRectAndCorners(rect, - bottomLeft: Radius.circular(radius), - bottomRight: Radius.circular(radius)); + return RRect.fromRectAndCorners( + rect, + bottomLeft: Radius.circular(radius), + bottomRight: Radius.circular(radius), + ); } /// Returns the start curve path. -RRect getStartCurve( - {required bool isHorizontal, - required bool isAxisInversed, - required Rect rect, - required double radius}) { +RRect getStartCurve({ + required bool isHorizontal, + required bool isAxisInversed, + required Rect rect, + required double radius, +}) { if (isHorizontal) { return !isAxisInversed ? _getHorizontalStartCurve(rect, radius) @@ -41,11 +53,12 @@ RRect getStartCurve( } /// Returns the end curve path. -RRect getEndCurve( - {required bool isHorizontal, - required bool isAxisInversed, - required Rect rect, - required double radius}) { +RRect getEndCurve({ + required bool isHorizontal, + required bool isAxisInversed, + required Rect rect, + required double radius, +}) { if (isHorizontal) { return !isAxisInversed ? _getHorizontalEndCurvePath(rect, radius) @@ -59,13 +72,15 @@ RRect getEndCurve( /// Returns the effective element position. LinearElementPosition getEffectiveElementPosition( - LinearElementPosition position, bool isMirrored) { + LinearElementPosition position, + bool isMirrored, +) { if (isMirrored) { return (position == LinearElementPosition.inside) ? LinearElementPosition.outside : (position == LinearElementPosition.outside) - ? LinearElementPosition.inside - : LinearElementPosition.cross; + ? LinearElementPosition.inside + : LinearElementPosition.cross; } return position; @@ -73,11 +88,14 @@ LinearElementPosition getEffectiveElementPosition( /// Returns the effective label position. LinearLabelPosition getEffectiveLabelPosition( - LinearLabelPosition labelPlacement, bool isMirrored) { + LinearLabelPosition labelPlacement, + bool isMirrored, +) { if (isMirrored) { - labelPlacement = (labelPlacement == LinearLabelPosition.inside) - ? LinearLabelPosition.outside - : LinearLabelPosition.inside; + labelPlacement = + (labelPlacement == LinearLabelPosition.inside) + ? LinearLabelPosition.outside + : LinearLabelPosition.inside; } return labelPlacement; diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation.dart index aff4b16a9..540e0e13f 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation.dart @@ -29,17 +29,19 @@ class GaugeAnnotation extends SingleChildRenderObjectWidget { /// /// The arguments [positionFactor] must not be null and [positionFactor] must /// be non-negative. - const GaugeAnnotation( - {Key? key, - this.axisValue, - this.horizontalAlignment = GaugeAlignment.center, - this.angle, - this.verticalAlignment = GaugeAlignment.center, - this.positionFactor = 0, - required this.widget}) - : assert( - positionFactor >= 0, 'Position factor must be greater than zero.'), - super(key: key, child: widget); + const GaugeAnnotation({ + Key? key, + this.axisValue, + this.horizontalAlignment = GaugeAlignment.center, + this.angle, + this.verticalAlignment = GaugeAlignment.center, + this.positionFactor = 0, + required this.widget, + }) : assert( + positionFactor >= 0, + 'Position factor must be greater than zero.', + ), + super(key: key, child: widget); /// Specifies the axis value for positioning annotation. /// @@ -188,7 +190,9 @@ class GaugeAnnotation extends SingleChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, RenderGaugeAnnotation renderObject) { + BuildContext context, + RenderGaugeAnnotation renderObject, + ) { final RadialAxisScope radialAxis = RadialAxisScope.of(context); renderObject ..axisValue = axisValue diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation_renderer.dart index 5d16fe922..1ddbbc34f 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/annotation/gauge_annotation_renderer.dart @@ -10,23 +10,23 @@ import '../../radial_gauge/utils/helper.dart'; /// Represents the renderer of radial gauge annotation. class RenderGaugeAnnotation extends RenderOpacity { /// Creates a instance for [RenderGaugeAnnotation]. - RenderGaugeAnnotation( - {double? axisValue, - required GaugeAlignment horizontalAlignment, - double? angle, - required GaugeAlignment verticalAlignment, - required double positionFactor, - Animation? annotationAnimation, - required ValueNotifier repaintNotifier, - RenderBox? child}) - : _axisValue = axisValue, - _horizontalAlignment = horizontalAlignment, - _angle = angle, - _verticalAlignment = verticalAlignment, - _positionFactor = positionFactor, - _repaintNotifier = repaintNotifier, - _annotationAnimation = annotationAnimation, - super(child: child); + RenderGaugeAnnotation({ + double? axisValue, + required GaugeAlignment horizontalAlignment, + double? angle, + required GaugeAlignment verticalAlignment, + required double positionFactor, + Animation? annotationAnimation, + required ValueNotifier repaintNotifier, + RenderBox? child, + }) : _axisValue = axisValue, + _horizontalAlignment = horizontalAlignment, + _angle = angle, + _verticalAlignment = verticalAlignment, + _positionFactor = positionFactor, + _repaintNotifier = repaintNotifier, + _annotationAnimation = annotationAnimation, + super(child: child); /// Specifies the offset of positioning the annotation. late Offset _annotationPosition; @@ -136,7 +136,8 @@ class RenderGaugeAnnotation extends RenderOpacity { if (angle != null) { actualValue = angle!; } else if (axisValue != null) { - actualValue = (axisRenderer!.valueToFactor(axisValue!) * _sweepAngle) + + actualValue = + (axisRenderer!.valueToFactor(axisValue!) * _sweepAngle) + axisRenderer!.startAngle; } @@ -167,10 +168,12 @@ class RenderGaugeAnnotation extends RenderOpacity { final double radian = getDegreeToRadian(angle); final double axisHalfWidth = positionFactor == 1 ? _actualAxisWidth / 2 : 0; if (!axisRenderer!.canScaleToFit) { - final double x = (_axisSize.width / 2) + + final double x = + (_axisSize.width / 2) + (offset - axisHalfWidth) * math.cos(radian) - _centerXPoint; - final double y = (_axisSize.height / 2) + + final double y = + (_axisSize.height / 2) + (offset - axisHalfWidth) * math.sin(radian) - _centerYPoint; _annotationPosition = Offset(x, y); @@ -196,7 +199,10 @@ class RenderGaugeAnnotation extends RenderOpacity { _axisCenter = axisRenderer!.getAxisCenter(); _radius = _axisRenderer!.getRadius(); _actualAxisWidth = _axisRenderer!.getActualValue( - _axisRenderer!.thickness, _axisRenderer!.thicknessUnit, false); + _axisRenderer!.thickness, + _axisRenderer!.thicknessUnit, + false, + ); } void _addListeners() { @@ -246,18 +252,20 @@ class RenderGaugeAnnotation extends RenderOpacity { if (child!.parentData is BoxParentData) { final BoxParentData? childParentData = child!.parentData as BoxParentData?; - final double dx = _annotationPosition.dx - + final double dx = + _annotationPosition.dx - (horizontalAlignment == GaugeAlignment.near ? 0 : horizontalAlignment == GaugeAlignment.center - ? child!.size.width / 2 - : child!.size.width); - final double dy = _annotationPosition.dy - + ? child!.size.width / 2 + : child!.size.width); + final double dy = + _annotationPosition.dy - (verticalAlignment == GaugeAlignment.near ? 0 : verticalAlignment == GaugeAlignment.center - ? child!.size.height / 2 - : child!.size.height); + ? child!.size.height / 2 + : child!.size.height); childParentData!.offset = Offset(dx, dy); } } else { diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis.dart index 0598f857f..137eff200 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis.dart @@ -39,56 +39,55 @@ class RadialAxis extends StatefulWidget { /// [tickOffset] and [labelOffset] must not be null. /// Additionally [centerX], [centerY] must be non-negative /// and [maximum] must be greater than [minimum]. - RadialAxis( - {Key? key, - this.startAngle = 130, - this.endAngle = 50, - this.radiusFactor = 0.95, - this.centerX = 0.5, - this.centerY = 0.5, - this.onLabelCreated, - this.onAxisTapped, - this.canRotateLabels = false, - this.showFirstLabel = true, - this.showLastLabel = false, - this.canScaleToFit = false, - this.backgroundImage, - this.ranges, - this.pointers, - this.annotations, - this.minimum = 0, - this.maximum = 100, - this.interval, - this.minorTicksPerInterval = 1, - this.showLabels = true, - this.showAxisLine = true, - this.showTicks = true, - this.tickOffset = 0, - this.labelOffset = 15, - this.isInversed = false, - this.maximumLabels = 3, - this.useRangeColorForAxis = false, - this.labelFormat, - NumberFormat? numberFormat, - this.onCreateAxisRenderer, - this.ticksPosition = ElementsPosition.inside, - this.labelsPosition = ElementsPosition.inside, - this.offsetUnit = GaugeSizeUnit.logicalPixel, - GaugeTextStyle? axisLabelStyle, - AxisLineStyle? axisLineStyle, - MajorTickStyle? majorTickStyle, - MinorTickStyle? minorTickStyle}) - : assert( - radiusFactor >= 0, 'Radius factor must be a non-negative value.'), - assert(centerX >= 0, 'Center X must be a non-negative value.'), - assert(centerY >= 0, 'Center Y must be a non-negative value.'), - assert(minimum < maximum, 'Maximum should be greater than minimum.'), - axisLabelStyle = axisLabelStyle ?? const GaugeTextStyle(), - axisLineStyle = axisLineStyle ?? const AxisLineStyle(), - numberFormat = numberFormat ?? NumberFormat('#.##'), - majorTickStyle = majorTickStyle ?? const MajorTickStyle(), - minorTickStyle = minorTickStyle ?? const MinorTickStyle(), - super(key: key); + RadialAxis({ + Key? key, + this.startAngle = 130, + this.endAngle = 50, + this.radiusFactor = 0.95, + this.centerX = 0.5, + this.centerY = 0.5, + this.onLabelCreated, + this.onAxisTapped, + this.canRotateLabels = false, + this.showFirstLabel = true, + this.showLastLabel = false, + this.canScaleToFit = false, + this.backgroundImage, + this.ranges, + this.pointers, + this.annotations, + this.minimum = 0, + this.maximum = 100, + this.interval, + this.minorTicksPerInterval = 1, + this.showLabels = true, + this.showAxisLine = true, + this.showTicks = true, + this.tickOffset = 0, + this.labelOffset = 15, + this.isInversed = false, + this.maximumLabels = 3, + this.useRangeColorForAxis = false, + this.labelFormat, + NumberFormat? numberFormat, + this.onCreateAxisRenderer, + this.ticksPosition = ElementsPosition.inside, + this.labelsPosition = ElementsPosition.inside, + this.offsetUnit = GaugeSizeUnit.logicalPixel, + GaugeTextStyle? axisLabelStyle, + AxisLineStyle? axisLineStyle, + MajorTickStyle? majorTickStyle, + MinorTickStyle? minorTickStyle, + }) : assert(radiusFactor >= 0, 'Radius factor must be a non-negative value.'), + assert(centerX >= 0, 'Center X must be a non-negative value.'), + assert(centerY >= 0, 'Center Y must be a non-negative value.'), + assert(minimum < maximum, 'Maximum should be greater than minimum.'), + axisLabelStyle = axisLabelStyle ?? const GaugeTextStyle(), + axisLineStyle = axisLineStyle ?? const AxisLineStyle(), + numberFormat = numberFormat ?? NumberFormat('#.##'), + majorTickStyle = majorTickStyle ?? const MajorTickStyle(), + minorTickStyle = minorTickStyle ?? const MinorTickStyle(), + super(key: key); /// Specifies the start angle of axis. /// @@ -889,9 +888,10 @@ class _RadialAxisState extends State with TickerProviderStateMixin { } void _updateOldList() { - _oldPointerList = (widget.pointers != null) - ? List.from(widget.pointers!) - : null; + _oldPointerList = + (widget.pointers != null) + ? List.from(widget.pointers!) + : null; } bool _isEqualLists(List? a, List? b) { @@ -923,41 +923,61 @@ class _RadialAxisState extends State with TickerProviderStateMixin { _disposeAnimationControllers(); if (_enableAnimation) { _animationController = AnimationController( - vsync: this, duration: Duration(milliseconds: animationDuration)); + vsync: this, + duration: Duration(milliseconds: animationDuration), + ); _animationController!.addListener(_axisAnimationListener); if (_hasAxisLine) { _axisAnimation = Tween(begin: 0, end: 1).animate( - CurvedAnimation( - parent: _animationController!, - curve: Interval(_axisLineInterval[0]!, _axisLineInterval[1]!, - curve: Curves.easeIn))); + CurvedAnimation( + parent: _animationController!, + curve: Interval( + _axisLineInterval[0]!, + _axisLineInterval[1]!, + curve: Curves.easeIn, + ), + ), + ); } // Includes animation duration for axis ticks and labels if (_hasAxisElements) { _axisElementAnimation = Tween(begin: 0, end: 1).animate( - CurvedAnimation( - parent: _animationController!, - curve: Interval( - _axisElementsInterval[0]!, _axisElementsInterval[1]!, - curve: Curves.easeIn))); + CurvedAnimation( + parent: _animationController!, + curve: Interval( + _axisElementsInterval[0]!, + _axisElementsInterval[1]!, + curve: Curves.easeIn, + ), + ), + ); } if (_hasRanges) { _rangeAnimation = Tween(begin: 0, end: 1).animate( - CurvedAnimation( - parent: _animationController!, - curve: Interval(_rangesInterval[0]!, _rangesInterval[1]!, - curve: Curves.easeIn))); + CurvedAnimation( + parent: _animationController!, + curve: Interval( + _rangesInterval[0]!, + _rangesInterval[1]!, + curve: Curves.easeIn, + ), + ), + ); } if (_hasAnnotations) { _annotationAnimation = Tween(begin: 0, end: 1).animate( - CurvedAnimation( - parent: _animationController!, - curve: Interval( - _annotationInterval[0]!, _annotationInterval[1]!, - curve: Curves.easeIn))); + CurvedAnimation( + parent: _animationController!, + curve: Interval( + _annotationInterval[0]!, + _annotationInterval[1]!, + curve: Curves.easeIn, + ), + ), + ); } } @@ -968,9 +988,11 @@ class _RadialAxisState extends State with TickerProviderStateMixin { AnimationController? pointerAnimationController; if (widget.pointers![i].enableAnimation) { pointerAnimationController = AnimationController( - vsync: this, - duration: Duration( - milliseconds: widget.pointers![i].animationDuration.toInt())); + vsync: this, + duration: Duration( + milliseconds: widget.pointers![i].animationDuration.toInt(), + ), + ); _pointerAnimationControllers.add(pointerAnimationController); } } @@ -1014,20 +1036,26 @@ class _RadialAxisState extends State with TickerProviderStateMixin { _radialAxisWidgets.clear(); /// Adding the axis widget. - _radialAxisWidgets.add(RadialAxisScope( + _radialAxisWidgets.add( + RadialAxisScope( animation1: _axisElementAnimation, isRadialGaugeAnimationEnabled: _enableAnimation, repaintNotifier: _repaintNotifier, animation: _axisAnimation, - child: RadialAxisRenderObjectWidget(axis: widget))); + child: RadialAxisRenderObjectWidget(axis: widget), + ), + ); if (widget.ranges != null) { for (int i = 0; i < widget.ranges!.length; i++) { - _radialAxisWidgets.add(RadialAxisScope( + _radialAxisWidgets.add( + RadialAxisScope( isRadialGaugeAnimationEnabled: _enableAnimation, repaintNotifier: _repaintNotifier, animation: _rangeAnimation, - child: widget.ranges![i])); + child: widget.ranges![i], + ), + ); } } @@ -1044,22 +1072,28 @@ class _RadialAxisState extends State with TickerProviderStateMixin { pointerAnimationController = _animationController; } - _radialAxisWidgets.add(RadialAxisScope( + _radialAxisWidgets.add( + RadialAxisScope( animationController: pointerAnimationController, isRadialGaugeAnimationEnabled: _enableAnimation, repaintNotifier: _repaintNotifier, pointerInterval: _pointersInterval, - child: widget.pointers![i] as Widget)); + child: widget.pointers![i] as Widget, + ), + ); } } if (widget.annotations != null) { for (int i = 0; i < widget.annotations!.length; i++) { - _radialAxisWidgets.add(RadialAxisScope( + _radialAxisWidgets.add( + RadialAxisScope( isRadialGaugeAnimationEnabled: _enableAnimation, repaintNotifier: _repaintNotifier, animation: _annotationAnimation, - child: widget.annotations![i])); + child: widget.annotations![i], + ), + ); } } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_label.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_label.dart index 2b400a84a..2cdc9ac31 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_label.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_label.dart @@ -8,7 +8,11 @@ import '../../radial_gauge/styles/radial_text_style.dart'; class CircularAxisLabel { /// Creates the axis label with default or required properties. CircularAxisLabel( - this.labelStyle, this.text, this.index, this.needsRotateLabel); + this.labelStyle, + this.text, + this.index, + this.needsRotateLabel, + ); /// Style for axis label text. late GaugeTextStyle labelStyle; diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_parent_widget.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_parent_widget.dart index e21cf9cd5..3884e3f65 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_parent_widget.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_parent_widget.dart @@ -33,16 +33,19 @@ const double kDefaultRadialGaugeSize = 350.0; class RadialAxisParentWidget extends MultiChildRenderObjectWidget { /// Creates instance for [RadialGaugeRenderWidget]. const RadialAxisParentWidget({Key? key, required List children}) - : super(key: key, children: children); + : super(key: key, children: children); @override RenderObject createRenderObject(BuildContext context) => RenderRadialAxisParent( - gestureSettings: MediaQuery.of(context).gestureSettings); + gestureSettings: MediaQuery.of(context).gestureSettings, + ); @override void updateRenderObject( - BuildContext context, RenderRadialAxisParent renderObject) { + BuildContext context, + RenderRadialAxisParent renderObject, + ) { super.updateRenderObject(context, renderObject); } @@ -111,24 +114,25 @@ class RenderRadialAxisParent extends RenderBox /// /// By default, the non-positioned children of the stack are aligned by their /// top left corners. - RenderRadialAxisParent({ - required DeviceGestureSettings gestureSettings, - }) : _gestureArenaTeam = GestureArenaTeam() { - _verticalDragGestureRecognizer = VerticalDragGestureRecognizer() - ..team = _gestureArenaTeam - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..gestureSettings = gestureSettings - ..dragStartBehavior = DragStartBehavior.start; - - _horizontalDragGestureRecognizer = HorizontalDragGestureRecognizer() - ..team = _gestureArenaTeam - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..gestureSettings = gestureSettings - ..dragStartBehavior = DragStartBehavior.start; + RenderRadialAxisParent({required DeviceGestureSettings gestureSettings}) + : _gestureArenaTeam = GestureArenaTeam() { + _verticalDragGestureRecognizer = + VerticalDragGestureRecognizer() + ..team = _gestureArenaTeam + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..gestureSettings = gestureSettings + ..dragStartBehavior = DragStartBehavior.start; + + _horizontalDragGestureRecognizer = + HorizontalDragGestureRecognizer() + ..team = _gestureArenaTeam + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..gestureSettings = gestureSettings + ..dragStartBehavior = DragStartBehavior.start; _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUP; @@ -269,14 +273,15 @@ class RenderRadialAxisParent extends RenderBox void _updateElements() { // ignore: always_specify_types - _axisElements = [ - _ranges, - _annotations, - _markerPointers, - _widgetPointers, - _rangePointers, - _needlePointers - ].expand((List x) => x).toList(); + _axisElements = + [ + _ranges, + _annotations, + _markerPointers, + _widgetPointers, + _rangePointers, + _needlePointers, + ].expand((List x) => x).toList(); for (int i = 0; i < _axisElements.length; i++) { _axisElements[i].axisRenderer = axis; @@ -307,25 +312,29 @@ class RenderRadialAxisParent extends RenderBox @override void performLayout() { - final double actualHeight = constraints.hasBoundedHeight - ? constraints.maxHeight - : kDefaultRadialGaugeSize; - final double actualWidth = constraints.hasBoundedWidth - ? constraints.maxWidth - : kDefaultRadialGaugeSize; + final double actualHeight = + constraints.hasBoundedHeight + ? constraints.maxHeight + : kDefaultRadialGaugeSize; + final double actualWidth = + constraints.hasBoundedWidth + ? constraints.maxWidth + : kDefaultRadialGaugeSize; if (axis != null) { axis!.layout( - BoxConstraints(maxHeight: actualHeight, maxWidth: actualWidth), - parentUsesSize: true); + BoxConstraints(maxHeight: actualHeight, maxWidth: actualWidth), + parentUsesSize: true, + ); _updateElements(); } if (_axisElements.isNotEmpty) { for (int i = 0; i < _axisElements.length; i++) { _axisElements[i].layout( - BoxConstraints(maxHeight: actualHeight, maxWidth: actualWidth), - parentUsesSize: true); + BoxConstraints(maxHeight: actualHeight, maxWidth: actualWidth), + parentUsesSize: true, + ); } } @@ -492,15 +501,17 @@ class RenderRadialAxisParent extends RenderBox /// Method to update the drag value. void _updateDragValue(double x, double y, dynamic pointer) { - final double actualCenterX = axis!.canScaleToFit - ? axis!.getAxisCenter().dx - : size.width * axis!.centerX; - final double actualCenterY = axis!.canScaleToFit - ? axis!.getAxisCenter().dy - : size.height * axis!.centerY; + final double actualCenterX = + axis!.canScaleToFit + ? axis!.getAxisCenter().dx + : size.width * axis!.centerX; + final double actualCenterY = + axis!.canScaleToFit + ? axis!.getAxisCenter().dy + : size.height * axis!.centerY; double angle = math.atan2(y - actualCenterY, x - actualCenterX) * (180 / math.pi) + - 360; + 360; final double endAngle = axis!.startAngle + axis!.getAxisSweepAngle(); if (angle < 360 && angle > 180) { @@ -516,11 +527,13 @@ class RenderRadialAxisParent extends RenderBox /// The current pointer value is calculated from the angle if (!axis!.isInversed) { - dragValue = axis!.minimum + + dragValue = + axis!.minimum + (angle - axis!.startAngle) * ((axis!.maximum - axis!.minimum) / axis!.getAxisSweepAngle()); } else { - dragValue = axis!.maximum - + dragValue = + axis!.maximum - (angle - axis!.startAngle) * ((axis!.maximum - axis!.minimum) / axis!.getAxisSweepAngle()); } @@ -566,8 +579,10 @@ class RenderRadialAxisParent extends RenderBox pointer.isHovered = false; if (pointer.pointerRect!.contains(hoverPosition) && _markerPointers.isNotEmpty && - !_markerPointers.any((RenderMarkerPointer element) => - element.isHovered != null && element.isHovered!)) { + !_markerPointers.any( + (RenderMarkerPointer element) => + element.isHovered != null && element.isHovered!, + )) { pointer.isHovered = true; } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_scope.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_scope.dart index 2ff25469b..11e38f1d9 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_scope.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_scope.dart @@ -36,9 +36,10 @@ class RadialAxisScope extends InheritedWidget { static RadialAxisScope of(BuildContext context) { late RadialAxisScope scope; - final Widget widget = context - .getElementForInheritedWidgetOfExactType()! - .widget; + final Widget widget = + context + .getElementForInheritedWidgetOfExactType()! + .widget; if (widget is RadialAxisScope) { scope = widget; diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_widget.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_widget.dart index 6454d7d0d..9a18fd772 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_widget.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/axis/radial_axis_widget.dart @@ -43,67 +43,71 @@ class RadialAxisRenderObjectWidget extends LeafRenderObjectWidget { } return RenderRadialAxisWidget( - startAngle: axis.startAngle, - endAngle: axis.endAngle, - radiusFactor: axis.radiusFactor, - centerX: axis.centerX, - centerY: axis.centerY, - canRotateLabels: axis.canRotateLabels, - canScaleToFit: axis.canScaleToFit, - showFirstLabel: axis.showFirstLabel, - showLastLabel: axis.showLastLabel, - onLabelCreated: axis.onLabelCreated, - onAxisTapped: axis.onAxisTapped, - minimum: axis.minimum, - maximum: axis.maximum, - interval: axis.interval, - isInversed: axis.isInversed, - minorTicksPerInterval: axis.minorTicksPerInterval, - showAxisLine: axis.showAxisLine, - showLabels: axis.showLabels, - showTicks: axis.showTicks, - tickOffset: axis.tickOffset, - numberFormat: axis.numberFormat, - labelFormat: axis.labelFormat, - maximumLabels: axis.maximumLabels, - labelOffset: axis.labelOffset, - useRangeColorForAxis: axis.useRangeColorForAxis, - labelPosition: axis.labelsPosition, - tickPosition: axis.ticksPosition, - offsetUnit: axis.offsetUnit, - thickness: axisLineStyle.thickness, - thicknessUnit: axisLineStyle.thicknessUnit, - axisLineColor: axisLineStyle.color, - axisLineGradient: axisLineStyle.gradient, - axisLineCornerStyle: axisLineStyle.cornerStyle, - axisLineDashArray: axisLineStyle.dashArray, - gaugeTextStyle: axis.axisLabelStyle, - majorTickLength: majorTickStyle.length, - majorTickThickness: majorTickStyle.thickness, - majorTickLengthUnit: majorTickStyle.lengthUnit, - majorTickColor: majorTickStyle.color, - majorTickDashArray: majorTickStyle.dashArray, - minorTickLength: minorTickStyle.length, - minorTickThickness: minorTickStyle.thickness, - minorTickLengthUnit: minorTickStyle.lengthUnit, - minorTickColor: minorTickStyle.color, - minorTickDashArray: minorTickStyle.dashArray, - axisLineAnimation: radialGaugeScope.animation, - axisElementsAnimation: radialGaugeScope.animation1, - repaintNotifier: radialGaugeScope.repaintNotifier, - gaugeThemeData: gaugeTheme, - themeData: themeData, - colorScheme: colorScheme, - ranges: axis.ranges, - renderer: renderer, - backgroundImage: axis.backgroundImage, - imageStream: axis.backgroundImage - ?.resolve(createLocalImageConfiguration(context))); + startAngle: axis.startAngle, + endAngle: axis.endAngle, + radiusFactor: axis.radiusFactor, + centerX: axis.centerX, + centerY: axis.centerY, + canRotateLabels: axis.canRotateLabels, + canScaleToFit: axis.canScaleToFit, + showFirstLabel: axis.showFirstLabel, + showLastLabel: axis.showLastLabel, + onLabelCreated: axis.onLabelCreated, + onAxisTapped: axis.onAxisTapped, + minimum: axis.minimum, + maximum: axis.maximum, + interval: axis.interval, + isInversed: axis.isInversed, + minorTicksPerInterval: axis.minorTicksPerInterval, + showAxisLine: axis.showAxisLine, + showLabels: axis.showLabels, + showTicks: axis.showTicks, + tickOffset: axis.tickOffset, + numberFormat: axis.numberFormat, + labelFormat: axis.labelFormat, + maximumLabels: axis.maximumLabels, + labelOffset: axis.labelOffset, + useRangeColorForAxis: axis.useRangeColorForAxis, + labelPosition: axis.labelsPosition, + tickPosition: axis.ticksPosition, + offsetUnit: axis.offsetUnit, + thickness: axisLineStyle.thickness, + thicknessUnit: axisLineStyle.thicknessUnit, + axisLineColor: axisLineStyle.color, + axisLineGradient: axisLineStyle.gradient, + axisLineCornerStyle: axisLineStyle.cornerStyle, + axisLineDashArray: axisLineStyle.dashArray, + gaugeTextStyle: axis.axisLabelStyle, + majorTickLength: majorTickStyle.length, + majorTickThickness: majorTickStyle.thickness, + majorTickLengthUnit: majorTickStyle.lengthUnit, + majorTickColor: majorTickStyle.color, + majorTickDashArray: majorTickStyle.dashArray, + minorTickLength: minorTickStyle.length, + minorTickThickness: minorTickStyle.thickness, + minorTickLengthUnit: minorTickStyle.lengthUnit, + minorTickColor: minorTickStyle.color, + minorTickDashArray: minorTickStyle.dashArray, + axisLineAnimation: radialGaugeScope.animation, + axisElementsAnimation: radialGaugeScope.animation1, + repaintNotifier: radialGaugeScope.repaintNotifier, + gaugeThemeData: gaugeTheme, + themeData: themeData, + colorScheme: colorScheme, + ranges: axis.ranges, + renderer: renderer, + backgroundImage: axis.backgroundImage, + imageStream: axis.backgroundImage?.resolve( + createLocalImageConfiguration(context), + ), + ); } @override void updateRenderObject( - BuildContext context, RenderRadialAxisWidget renderObject) { + BuildContext context, + RenderRadialAxisWidget renderObject, + ) { final RadialAxisScope radialGaugeScope = RadialAxisScope.of(context); final AxisLineStyle axisLineStyle = axis.axisLineStyle; final MajorTickStyle majorTickStyle = axis.majorTickStyle; @@ -172,8 +176,9 @@ class RadialAxisRenderObjectWidget extends LeafRenderObjectWidget { ..themeData = themeData ..colorScheme = colorScheme ..renderer = renderer - ..imageStream = - axis.backgroundImage?.resolve(createLocalImageConfiguration(context)) + ..imageStream = axis.backgroundImage?.resolve( + createLocalImageConfiguration(context), + ) ..backgroundImage = axis.backgroundImage; super.updateRenderObject(context, renderObject); } @@ -182,117 +187,117 @@ class RadialAxisRenderObjectWidget extends LeafRenderObjectWidget { //// Represents the renderer of radial gauge axis element. class RenderRadialAxisWidget extends RenderBox { /// Creates a object for [RenderRadialAxis]. - RenderRadialAxisWidget( - {required double startAngle, - required double endAngle, - required double radiusFactor, - required double centerX, - required double centerY, - required bool canRotateLabels, - required bool canScaleToFit, - required bool showFirstLabel, - required bool showLastLabel, - ValueChanged? onLabelCreated, - ValueChanged? onAxisTapped, - required double minimum, - required double maximum, - double? interval, - required bool isInversed, - required double minorTicksPerInterval, - required bool showAxisLine, - required bool showLabels, - required bool showTicks, - required double tickOffset, - init.NumberFormat? numberFormat, - String? labelFormat, - required int maximumLabels, - required double labelOffset, - required bool useRangeColorForAxis, - required ElementsPosition labelPosition, - required ElementsPosition tickPosition, - required GaugeSizeUnit offsetUnit, - required double thickness, - required GaugeSizeUnit thicknessUnit, - Color? axisLineColor, - Gradient? axisLineGradient, - required CornerStyle axisLineCornerStyle, - List? axisLineDashArray, - required GaugeTextStyle gaugeTextStyle, - required double majorTickLength, - required double majorTickThickness, - required GaugeSizeUnit majorTickLengthUnit, - Color? majorTickColor, - List? majorTickDashArray, - required double minorTickLength, - required double minorTickThickness, - required GaugeSizeUnit minorTickLengthUnit, - Color? minorTickColor, - List? minorTickDashArray, - required SfGaugeThemeData gaugeThemeData, - required ThemeData themeData, - required SfColorScheme colorScheme, - RadialAxisRenderer? renderer, - List? ranges, - Animation? axisElementsAnimation, - Animation? axisLineAnimation, - ImageStream? imageStream, - required ValueNotifier repaintNotifier, - ImageProvider? backgroundImage}) - : _startAngle = startAngle, - _endAngle = endAngle, - _radiusFactor = radiusFactor, - _centerX = centerX, - _centerY = centerY, - _canRotateLabels = canRotateLabels, - _canScaleToFit = canScaleToFit, - _showFirstLabel = showFirstLabel, - _showLastLabel = showLastLabel, - _onLabelCreated = onLabelCreated, - _onAxisTapped = onAxisTapped, - _minimum = minimum, - _maximum = maximum, - _interval = interval, - _isInversed = isInversed, - _minorTicksPerInterval = minorTicksPerInterval, - _showAxisLine = showAxisLine, - _showLabels = showLabels, - _showTicks = showTicks, - _tickOffset = tickOffset, - _numberFormat = numberFormat, - _labelFormat = labelFormat, - _maximumLabels = maximumLabels, - _labelOffset = labelOffset, - _useRangeColorForAxis = useRangeColorForAxis, - _labelPosition = labelPosition, - _tickPosition = tickPosition, - _offsetUnit = offsetUnit, - _thickness = thickness, - _thicknessUnit = thicknessUnit, - _axisLineColor = axisLineColor, - _axisLineGradient = axisLineGradient, - _axisLineCornerStyle = axisLineCornerStyle, - _axisLineDashArray = axisLineDashArray, - _gaugeTextStyle = gaugeTextStyle, - _majorTickLength = majorTickLength, - _majorTickThickness = majorTickThickness, - _majorTickLengthUnit = majorTickLengthUnit, - _majorTickColor = majorTickColor, - _majorTickDashArray = majorTickDashArray, - _minorTickLength = minorTickLength, - _minorTickThickness = minorTickThickness, - _minorTickLengthUnit = minorTickLengthUnit, - _minorTickColor = minorTickColor, - _minorTickDashArray = minorTickDashArray, - _axisLineAnimation = axisLineAnimation, - _axisElementsAnimation = axisElementsAnimation, - _gaugeThemeData = gaugeThemeData, - _imageStream = imageStream, - _ranges = ranges, - _renderer = renderer, - _repaintNotifier = repaintNotifier, - _themeData = themeData, - _colorScheme = colorScheme, - _backgroundImage = backgroundImage { + RenderRadialAxisWidget({ + required double startAngle, + required double endAngle, + required double radiusFactor, + required double centerX, + required double centerY, + required bool canRotateLabels, + required bool canScaleToFit, + required bool showFirstLabel, + required bool showLastLabel, + ValueChanged? onLabelCreated, + ValueChanged? onAxisTapped, + required double minimum, + required double maximum, + double? interval, + required bool isInversed, + required double minorTicksPerInterval, + required bool showAxisLine, + required bool showLabels, + required bool showTicks, + required double tickOffset, + init.NumberFormat? numberFormat, + String? labelFormat, + required int maximumLabels, + required double labelOffset, + required bool useRangeColorForAxis, + required ElementsPosition labelPosition, + required ElementsPosition tickPosition, + required GaugeSizeUnit offsetUnit, + required double thickness, + required GaugeSizeUnit thicknessUnit, + Color? axisLineColor, + Gradient? axisLineGradient, + required CornerStyle axisLineCornerStyle, + List? axisLineDashArray, + required GaugeTextStyle gaugeTextStyle, + required double majorTickLength, + required double majorTickThickness, + required GaugeSizeUnit majorTickLengthUnit, + Color? majorTickColor, + List? majorTickDashArray, + required double minorTickLength, + required double minorTickThickness, + required GaugeSizeUnit minorTickLengthUnit, + Color? minorTickColor, + List? minorTickDashArray, + required SfGaugeThemeData gaugeThemeData, + required ThemeData themeData, + required SfColorScheme colorScheme, + RadialAxisRenderer? renderer, + List? ranges, + Animation? axisElementsAnimation, + Animation? axisLineAnimation, + ImageStream? imageStream, + required ValueNotifier repaintNotifier, + ImageProvider? backgroundImage, + }) : _startAngle = startAngle, + _endAngle = endAngle, + _radiusFactor = radiusFactor, + _centerX = centerX, + _centerY = centerY, + _canRotateLabels = canRotateLabels, + _canScaleToFit = canScaleToFit, + _showFirstLabel = showFirstLabel, + _showLastLabel = showLastLabel, + _onLabelCreated = onLabelCreated, + _onAxisTapped = onAxisTapped, + _minimum = minimum, + _maximum = maximum, + _interval = interval, + _isInversed = isInversed, + _minorTicksPerInterval = minorTicksPerInterval, + _showAxisLine = showAxisLine, + _showLabels = showLabels, + _showTicks = showTicks, + _tickOffset = tickOffset, + _numberFormat = numberFormat, + _labelFormat = labelFormat, + _maximumLabels = maximumLabels, + _labelOffset = labelOffset, + _useRangeColorForAxis = useRangeColorForAxis, + _labelPosition = labelPosition, + _tickPosition = tickPosition, + _offsetUnit = offsetUnit, + _thickness = thickness, + _thicknessUnit = thicknessUnit, + _axisLineColor = axisLineColor, + _axisLineGradient = axisLineGradient, + _axisLineCornerStyle = axisLineCornerStyle, + _axisLineDashArray = axisLineDashArray, + _gaugeTextStyle = gaugeTextStyle, + _majorTickLength = majorTickLength, + _majorTickThickness = majorTickThickness, + _majorTickLengthUnit = majorTickLengthUnit, + _majorTickColor = majorTickColor, + _majorTickDashArray = majorTickDashArray, + _minorTickLength = minorTickLength, + _minorTickThickness = minorTickThickness, + _minorTickLengthUnit = minorTickLengthUnit, + _minorTickColor = minorTickColor, + _minorTickDashArray = minorTickDashArray, + _axisLineAnimation = axisLineAnimation, + _axisElementsAnimation = axisElementsAnimation, + _gaugeThemeData = gaugeThemeData, + _imageStream = imageStream, + _ranges = ranges, + _renderer = renderer, + _repaintNotifier = repaintNotifier, + _themeData = themeData, + _colorScheme = colorScheme, + _backgroundImage = backgroundImage { _isLabelsOutside = labelPosition == ElementsPosition.outside; _isTicksOutside = tickPosition == ElementsPosition.outside; _imageStreamListener = ImageStreamListener(_updateBackgroundImage); @@ -1167,7 +1172,11 @@ class RenderRadialAxisWidget extends RenderBox { } bounds = Rect.fromLTRB( - x - diff / 2, y, x + minScale + (diff / 2), y + minScale + diff); + x - diff / 2, + y, + x + minScale + (diff / 2), + y + minScale + diff, + ); } else { diff = centerXDiff / 2; final double angleRadius = _axisSize.width / 2 + diff; @@ -1177,14 +1186,20 @@ class RenderRadialAxisWidget extends RenderBox { diff = actualDiff * 0.7; } - bounds = Rect.fromLTRB(x - diff / 2, y - diff / 2, - x + minScale + (diff / 2), y + minScale + (diff / 2)); + bounds = Rect.fromLTRB( + x - diff / 2, + y - diff / 2, + x + minScale + (diff / 2), + y + minScale + (diff / 2), + ); } _diffInRadius = diff; return Offset( - bounds.left + (bounds.width / 2), bounds.top + (bounds.height / 2)); + bounds.left + (bounds.width / 2), + bounds.top + (bounds.height / 2), + ); } /// Get the RadialAxis radius. @@ -1230,8 +1245,10 @@ class RenderRadialAxisWidget extends RenderBox { getCenterY(); if (!canScaleToFit) { - _axisCenter = Offset(_axisSize.width / 2 - _centerXPoint, - _axisSize.height / 2 - _centerYPoint); + _axisCenter = Offset( + _axisSize.width / 2 - _centerXPoint, + _axisSize.height / 2 - _centerYPoint, + ); } else { _axisCenter = Offset(_centerXPoint, _centerYPoint); } @@ -1253,9 +1270,10 @@ class RenderRadialAxisWidget extends RenderBox { _actualMajorTickLength = _getTickLength(true); _actualMinorTickLength = _getTickLength(false); - _maximumTickLength = _actualMajorTickLength > _actualMinorTickLength - ? _actualMajorTickLength - : _actualMinorTickLength; + _maximumTickLength = + _actualMajorTickLength > _actualMinorTickLength + ? _actualMajorTickLength + : _actualMinorTickLength; _actualLabelOffset = getActualValue(labelOffset, offsetUnit, true); _actualTickOffset = getActualValue(tickOffset, offsetUnit, true); } @@ -1296,8 +1314,11 @@ class RenderRadialAxisWidget extends RenderBox { _radius = _center; Offset actualCenter = Offset(x, y); final double actualStartAngle = _getWrapAngle(startAngle, -630, 630); - final double actualEndAngle = - _getWrapAngle(startAngle + _sweepAngle.abs(), -630, 630); + final double actualEndAngle = _getWrapAngle( + startAngle + _sweepAngle.abs(), + -630, + 630, + ); final List regions = [ -630, -540, @@ -1313,52 +1334,84 @@ class RenderRadialAxisWidget extends RenderBox { 360, 450, 540, - 630 + 630, ]; final List region = []; if (actualStartAngle < actualEndAngle) { for (int i = 0; i < regions.length; i++) { if (regions[i] > actualStartAngle && regions[i] < actualEndAngle) { - region.add(((regions[i] % 360) < 0 - ? (regions[i] % 360) + 360 - : (regions[i] % 360)) - .toInt()); + region.add( + ((regions[i] % 360) < 0 + ? (regions[i] % 360) + 360 + : (regions[i] % 360)) + .toInt(), + ); } } } else { for (int i = 0; i < regions.length; i++) { if (regions[i] < actualStartAngle && regions[i] > actualEndAngle) { - region.add(((regions[i] % 360) < 0 - ? (regions[i] % 360) + 360 - : (regions[i] % 360)) - .toInt()); + region.add( + ((regions[i] % 360) < 0 + ? (regions[i] % 360) + 360 + : (regions[i] % 360)) + .toInt(), + ); } } } final double startRadian = 2 * math.pi * (actualStartAngle / 360); final double endRadian = 2 * math.pi * (actualEndAngle / 360); - final Offset startPoint = Offset(x + (_radius * math.cos(startRadian)), - y + (_radius * math.sin(startRadian))); - final Offset endPoint = Offset(x + (_radius * math.cos(endRadian)), - y + (_radius * math.sin(endRadian))); + final Offset startPoint = Offset( + x + (_radius * math.cos(startRadian)), + y + (_radius * math.sin(startRadian)), + ); + final Offset endPoint = Offset( + x + (_radius * math.cos(endRadian)), + y + (_radius * math.sin(endRadian)), + ); switch (region.length) { case 0: actualCenter = _getCenterForLengthZero( - startPoint, endPoint, x, y, _radius, region); + startPoint, + endPoint, + x, + y, + _radius, + region, + ); break; case 1: - actualCenter = - _getCenterLengthOne(startPoint, endPoint, x, y, _radius, region); + actualCenter = _getCenterLengthOne( + startPoint, + endPoint, + x, + y, + _radius, + region, + ); break; case 2: - actualCenter = - _getCenterForLengthTwo(startPoint, endPoint, x, y, _radius, region); + actualCenter = _getCenterForLengthTwo( + startPoint, + endPoint, + x, + y, + _radius, + region, + ); break; case 3: actualCenter = _getCenterForLengthThree( - startPoint, endPoint, x, y, _radius, region); + startPoint, + endPoint, + x, + y, + _radius, + region, + ); break; } @@ -1374,9 +1427,10 @@ class RenderRadialAxisWidget extends RenderBox { late double begin, end; if (pointer is RenderRangePointer) { animationStartValue = pointer.animationStartValue ?? 0; - animationEndValue = isInversed - ? _getSweepAngle(pointer.getSweepAngle()) - : pointer.getSweepAngle(); + animationEndValue = + isInversed + ? _getSweepAngle(pointer.getSweepAngle()) + : pointer.getSweepAngle(); pointer.animationStartValue = animationEndValue; } else { animationStartValue = _getSweepAngle(pointer.oldValue ?? minimum); @@ -1386,40 +1440,66 @@ class RenderRadialAxisWidget extends RenderBox { begin = enableAnimation ? 0 : pointer.pointerInterval![0]! as double; end = enableAnimation ? 1 : pointer.pointerInterval![1]! as double; - return Tween(begin: animationStartValue, end: animationEndValue) - .animate(CurvedAnimation( - parent: pointer.pointerAnimationController!, - curve: Interval(begin, end, - curve: getCurveAnimation(pointer.animationType)))); + return Tween( + begin: animationStartValue, + end: animationEndValue, + ).animate( + CurvedAnimation( + parent: pointer.pointerAnimationController!, + curve: Interval( + begin, + end, + curve: getCurveAnimation(pointer.animationType), + ), + ), + ); } else { return null; } } /// Calculate the center point when the region length is zero. - Offset _getCenterForLengthZero(Offset startPoint, Offset endPoint, double x, - double y, double radius, List region) { - final double longX = (x - startPoint.dx).abs() > (x - endPoint.dx).abs() - ? startPoint.dx - : endPoint.dx; - final double longY = (y - startPoint.dy).abs() > (y - endPoint.dy).abs() - ? startPoint.dy - : endPoint.dy; - final Offset midPoint = - Offset((x + longX).abs() / 2, (y + longY).abs() / 2); + Offset _getCenterForLengthZero( + Offset startPoint, + Offset endPoint, + double x, + double y, + double radius, + List region, + ) { + final double longX = + (x - startPoint.dx).abs() > (x - endPoint.dx).abs() + ? startPoint.dx + : endPoint.dx; + final double longY = + (y - startPoint.dy).abs() > (y - endPoint.dy).abs() + ? startPoint.dy + : endPoint.dy; + final Offset midPoint = Offset( + (x + longX).abs() / 2, + (y + longY).abs() / 2, + ); final double xValue = x + (x - midPoint.dx); final double yValue = y + (y - midPoint.dy); return Offset(xValue, yValue); } ///Calculates the center when the region length is two. - Offset _getCenterLengthOne(Offset startPoint, Offset endPoint, double x, - double y, double radius, List region) { + Offset _getCenterLengthOne( + Offset startPoint, + Offset endPoint, + double x, + double y, + double radius, + List region, + ) { Offset point1 = Offset.zero; Offset point2 = Offset.zero; final double maxRadian = 2 * math.pi * region[0] / 360; final Offset maxPoint = Offset( - x + (radius * math.cos(maxRadian)), y + (radius * math.sin(maxRadian))); + x + (radius * math.cos(maxRadian)), + y + (radius * math.sin(maxRadian)), + ); switch (region[0]) { case 270: @@ -1441,8 +1521,10 @@ class RenderRadialAxisWidget extends RenderBox { break; } - final Offset midPoint = - Offset((point1.dx + point2.dx) / 2, (point1.dy + point2.dy) / 2); + final Offset midPoint = Offset( + (point1.dx + point2.dx) / 2, + (point1.dy + point2.dy) / 2, + ); final double xValue = x + ((x - midPoint.dx) >= radius ? 0 : (x - midPoint.dx)); final double yValue = @@ -1451,16 +1533,26 @@ class RenderRadialAxisWidget extends RenderBox { } ///Calculates the center when the region length is two. - Offset _getCenterForLengthTwo(Offset startPoint, Offset endPoint, double x, - double y, double radius, List region) { + Offset _getCenterForLengthTwo( + Offset startPoint, + Offset endPoint, + double x, + double y, + double radius, + List region, + ) { Offset point1; Offset point2; final double minRadian = 2 * math.pi * region[0] / 360; final double maxRadian = 2 * math.pi * region[1] / 360; final Offset maxPoint = Offset( - x + (radius * math.cos(maxRadian)), y + (radius * math.sin(maxRadian))); + x + (radius * math.cos(maxRadian)), + y + (radius * math.sin(maxRadian)), + ); final Offset minPoint = Offset( - x + (radius * math.cos(minRadian)), y + (radius * math.sin(minRadian))); + x + (radius * math.cos(minRadian)), + y + (radius * math.sin(minRadian)), + ); if ((region[0] == 0 && region[1] == 90) || (region[0] == 180 && region[1] == 270)) { @@ -1470,92 +1562,122 @@ class RenderRadialAxisWidget extends RenderBox { } if (region[0] == 0 || region[0] == 180) { - point2 = Offset(_getMinMaxValue(startPoint, endPoint, region[0]), - _getMinMaxValue(startPoint, endPoint, region[1])); + point2 = Offset( + _getMinMaxValue(startPoint, endPoint, region[0]), + _getMinMaxValue(startPoint, endPoint, region[1]), + ); } else { - point2 = Offset(_getMinMaxValue(startPoint, endPoint, region[1]), - _getMinMaxValue(startPoint, endPoint, region[0])); + point2 = Offset( + _getMinMaxValue(startPoint, endPoint, region[1]), + _getMinMaxValue(startPoint, endPoint, region[0]), + ); } final Offset midPoint = Offset( - (point1.dx - point2.dx).abs() / 2 >= radius - ? 0 - : (point1.dx + point2.dx) / 2, - (point1.dy - point2.dy).abs() / 2 >= radius - ? 0 - : (point1.dy + point2.dy) / 2); - final double xValue = x + + (point1.dx - point2.dx).abs() / 2 >= radius + ? 0 + : (point1.dx + point2.dx) / 2, + (point1.dy - point2.dy).abs() / 2 >= radius + ? 0 + : (point1.dy + point2.dy) / 2, + ); + final double xValue = + x + (midPoint.dx == 0 ? 0 : (x - midPoint.dx) >= radius - ? 0 - : (x - midPoint.dx)); - final double yValue = y + + ? 0 + : (x - midPoint.dx)); + final double yValue = + y + (midPoint.dy == 0 ? 0 : (y - midPoint.dy) >= radius - ? 0 - : (y - midPoint.dy)); + ? 0 + : (y - midPoint.dy)); return Offset(xValue, yValue); } ///Calculates the center when the region length is three. - Offset _getCenterForLengthThree(Offset startPoint, Offset endPoint, double x, - double y, double radius, List region) { + Offset _getCenterForLengthThree( + Offset startPoint, + Offset endPoint, + double x, + double y, + double radius, + List region, + ) { final double region0Radian = 2 * math.pi * region[0] / 360; final double region1Radian = 2 * math.pi * region[1] / 360; final double region2Radian = 2 * math.pi * region[2] / 360; - final Offset region0Point = Offset(x + (radius * math.cos(region0Radian)), - y + (radius * math.sin(region0Radian))); - final Offset region1Point = Offset(x + (radius * math.cos(region1Radian)), - y + (radius * math.sin(region1Radian))); - final Offset region2Point = Offset(x + (radius * math.cos(region2Radian)), - y + (radius * math.sin(region2Radian))); + final Offset region0Point = Offset( + x + (radius * math.cos(region0Radian)), + y + (radius * math.sin(region0Radian)), + ); + final Offset region1Point = Offset( + x + (radius * math.cos(region1Radian)), + y + (radius * math.sin(region1Radian)), + ); + final Offset region2Point = Offset( + x + (radius * math.cos(region2Radian)), + y + (radius * math.sin(region2Radian)), + ); Offset regionStartPoint = Offset.zero; Offset regionEndPoint = Offset.zero; switch (region[2]) { case 0: case 360: regionStartPoint = Offset(region0Point.dx, region1Point.dy); - regionEndPoint = - Offset(region2Point.dx, math.max(startPoint.dy, endPoint.dy)); + regionEndPoint = Offset( + region2Point.dx, + math.max(startPoint.dy, endPoint.dy), + ); break; case 90: - regionStartPoint = - Offset(math.min(startPoint.dx, endPoint.dx), region0Point.dy); + regionStartPoint = Offset( + math.min(startPoint.dx, endPoint.dx), + region0Point.dy, + ); regionEndPoint = Offset(region1Point.dx, region2Point.dy); break; case 180: - regionStartPoint = - Offset(region2Point.dx, math.min(startPoint.dy, endPoint.dy)); + regionStartPoint = Offset( + region2Point.dx, + math.min(startPoint.dy, endPoint.dy), + ); regionEndPoint = Offset(region0Point.dx, region1Point.dy); break; case 270: regionStartPoint = Offset(region1Point.dx, region2Point.dy); - regionEndPoint = - Offset(math.max(startPoint.dx, endPoint.dx), region0Point.dy); + regionEndPoint = Offset( + math.max(startPoint.dx, endPoint.dx), + region0Point.dy, + ); break; } final Offset midRegionPoint = Offset( - (regionStartPoint.dx - regionEndPoint.dx).abs() / 2 >= radius - ? 0 - : (regionStartPoint.dx + regionEndPoint.dx) / 2, - (regionStartPoint.dy - regionEndPoint.dy).abs() / 2 >= radius - ? 0 - : (regionStartPoint.dy + regionEndPoint.dy) / 2); - final double xValue = x + + (regionStartPoint.dx - regionEndPoint.dx).abs() / 2 >= radius + ? 0 + : (regionStartPoint.dx + regionEndPoint.dx) / 2, + (regionStartPoint.dy - regionEndPoint.dy).abs() / 2 >= radius + ? 0 + : (regionStartPoint.dy + regionEndPoint.dy) / 2, + ); + final double xValue = + x + (midRegionPoint.dx == 0 ? 0 : (x - midRegionPoint.dx) >= radius - ? 0 - : (x - midRegionPoint.dx)); - final double yValue = y + + ? 0 + : (x - midRegionPoint.dx)); + final double yValue = + y + (midRegionPoint.dy == 0 ? 0 : (y - midRegionPoint.dy) >= radius - ? 0 - : (y - midRegionPoint.dy)); + ? 0 + : (y - midRegionPoint.dy)); return Offset(xValue, yValue); } @@ -1602,38 +1724,45 @@ class RenderRadialAxisWidget extends RenderBox { switch (axisLineCornerStyle) { case CornerStyle.startCurve: { - _startCornerRadian = isInversed - ? getDegreeToRadian(-_cornerAngle) - : getDegreeToRadian(_cornerAngle); - _sweepCornerRadian = isInversed - ? getDegreeToRadian((-_sweepAngle) + _cornerAngle) - : getDegreeToRadian(_sweepAngle - _cornerAngle); + _startCornerRadian = + isInversed + ? getDegreeToRadian(-_cornerAngle) + : getDegreeToRadian(_cornerAngle); + _sweepCornerRadian = + isInversed + ? getDegreeToRadian((-_sweepAngle) + _cornerAngle) + : getDegreeToRadian(_sweepAngle - _cornerAngle); } break; case CornerStyle.endCurve: { _startCornerRadian = getDegreeToRadian(0); - _sweepCornerRadian = isInversed - ? getDegreeToRadian((-_sweepAngle) + _cornerAngle) - : getDegreeToRadian(_sweepAngle - _cornerAngle); + _sweepCornerRadian = + isInversed + ? getDegreeToRadian((-_sweepAngle) + _cornerAngle) + : getDegreeToRadian(_sweepAngle - _cornerAngle); } break; case CornerStyle.bothCurve: { - _startCornerRadian = isInversed - ? getDegreeToRadian(-_cornerAngle) - : getDegreeToRadian(_cornerAngle); - _sweepCornerRadian = isInversed - ? getDegreeToRadian((-_sweepAngle) + (2 * _cornerAngle)) - : getDegreeToRadian(_sweepAngle - (2 * _cornerAngle)); + _startCornerRadian = + isInversed + ? getDegreeToRadian(-_cornerAngle) + : getDegreeToRadian(_cornerAngle); + _sweepCornerRadian = + isInversed + ? getDegreeToRadian((-_sweepAngle) + (2 * _cornerAngle)) + : getDegreeToRadian(_sweepAngle - (2 * _cornerAngle)); } break; case CornerStyle.bothFlat: - _startCornerRadian = !isInversed - ? getDegreeToRadian(0) - : getDegreeToRadian(startAngle + _sweepAngle); - _sweepCornerRadian = - getDegreeToRadian(_sweepAngle * (isInversed ? -1 : 1)); + _startCornerRadian = + !isInversed + ? getDegreeToRadian(0) + : getDegreeToRadian(startAngle + _sweepAngle); + _sweepCornerRadian = getDegreeToRadian( + _sweepAngle * (isInversed ? -1 : 1), + ); break; } } @@ -1664,8 +1793,8 @@ class RenderRadialAxisWidget extends RenderBox { canScaleToFit ? _axisCenter.dy : size.height * centerY; double angle = math.atan2(offset.dy - actualCenterY, offset.dx - actualCenterX) * - (180 / math.pi) + - 360; + (180 / math.pi) + + 360; final double actualEndAngle = startAngle + _sweepAngle; if (angle < 360 && angle > 180) { angle += 360; @@ -1678,10 +1807,11 @@ class RenderRadialAxisWidget extends RenderBox { if (angle >= startAngle && angle <= actualEndAngle) { final double angleFactor = (angle - startAngle) / _sweepAngle; - final double value = (renderer != null && - renderer!.factorToValue(angleFactor) != null) - ? renderer!.factorToValue(angleFactor) ?? factorToValue(angleFactor) - : factorToValue(angleFactor); + final double value = + (renderer != null && renderer!.factorToValue(angleFactor) != null) + ? renderer!.factorToValue(angleFactor) ?? + factorToValue(angleFactor) + : factorToValue(angleFactor); if (value >= minimum && value <= maximum) { final double tappedValue = _angleToValue(angle); onAxisTapped!(tappedValue); @@ -1692,17 +1822,20 @@ class RenderRadialAxisWidget extends RenderBox { /// Calculate the offset for axis line based on ticks and labels double getAxisOffset() { double offset = 0; - offset = _isTicksOutside - ? showTicks - ? (_maximumTickLength + _actualTickOffset) - : 0 - : 0; - offset += _isLabelsOutside - ? showLabels - ? (math.max(_maximumLabelSize.height, _maximumLabelSize.width) / 2 + - _actualLabelOffset) - : 0 - : 0; + offset = + _isTicksOutside + ? showTicks + ? (_maximumTickLength + _actualTickOffset) + : 0 + : 0; + offset += + _isLabelsOutside + ? showLabels + ? (math.max(_maximumLabelSize.height, _maximumLabelSize.width) / + 2 + + _actualLabelOffset) + : 0 + : 0; return offset; } @@ -1714,7 +1847,8 @@ class RenderRadialAxisWidget extends RenderBox { angle = (_sweepAngle / (maximum - minimum).abs()) * (minimum - value).abs(); } else { - angle = _sweepAngle - + angle = + _sweepAngle - ((_sweepAngle / (maximum - minimum).abs()) * (minimum - value).abs()); } @@ -1725,10 +1859,12 @@ class RenderRadialAxisWidget extends RenderBox { double _angleToValue(double angle) { double value = 0; if (!isInversed) { - value = (((angle - startAngle) / _sweepAngle) * (maximum - minimum)) + + value = + (((angle - startAngle) / _sweepAngle) * (maximum - minimum)) + minimum; } else { - value = maximum - + value = + maximum - (((angle - startAngle) / _sweepAngle) * (maximum - minimum)); } @@ -1741,12 +1877,14 @@ class RenderRadialAxisWidget extends RenderBox { double angularSpaceForTicks; if (_actualInterval != null) { _majorTicksCount = (maximum - minimum) / _actualInterval!; - angularSpaceForTicks = - getDegreeToRadian(_sweepAngle / _majorTicksCount); + angularSpaceForTicks = getDegreeToRadian( + _sweepAngle / _majorTicksCount, + ); } else { _majorTicksCount = _axisLabels!.length; - angularSpaceForTicks = - getDegreeToRadian(_sweepAngle / (_majorTicksCount - 1)); + angularSpaceForTicks = getDegreeToRadian( + _sweepAngle / (_majorTicksCount - 1), + ); } final double axisLineWidth = showAxisLine ? _actualAxisWidth : 0; @@ -1754,20 +1892,26 @@ class RenderRadialAxisWidget extends RenderBox { double tickStartOffset = 0; double tickEndOffset = 0; _majorTickOffsets = []; - angleForTicks = isInversed - ? getDegreeToRadian(startAngle + _sweepAngle - 90) - : getDegreeToRadian(startAngle - 90); - final double offset = _isLabelsOutside - ? showLabels - ? (math.max(_maximumLabelSize.height, _maximumLabelSize.width) / - 2 + - _actualLabelOffset) - : 0 - : 0; + angleForTicks = + isInversed + ? getDegreeToRadian(startAngle + _sweepAngle - 90) + : getDegreeToRadian(startAngle - 90); + final double offset = + _isLabelsOutside + ? showLabels + ? (math.max( + _maximumLabelSize.height, + _maximumLabelSize.width, + ) / + 2 + + _actualLabelOffset) + : 0 + : 0; if (!_isTicksOutside) { tickStartOffset = _radius - (axisLineWidth + _actualTickOffset + offset); - tickEndOffset = _radius - + tickEndOffset = + _radius - (axisLineWidth + _actualMajorTickLength + _actualTickOffset + @@ -1781,22 +1925,31 @@ class RenderRadialAxisWidget extends RenderBox { tickStartOffset = _radius + _actualTickOffset; tickEndOffset = _radius + _actualMajorTickLength + _actualTickOffset; } else { - tickStartOffset = isGreater - ? _radius - offset - : _radius - - (_maximumTickLength - _actualMajorTickLength + offset); + tickStartOffset = + isGreater + ? _radius - offset + : _radius - + (_maximumTickLength - _actualMajorTickLength + offset); tickEndOffset = _radius - (offset + _maximumTickLength); } } _calculateOffsetForMajorTicks( - tickStartOffset, tickEndOffset, angularSpaceForTicks, angleForTicks); + tickStartOffset, + tickEndOffset, + angularSpaceForTicks, + angleForTicks, + ); } } /// Calculates the offset for major ticks - void _calculateOffsetForMajorTicks(double tickStartOffset, - double tickEndOffset, double angularSpaceForTicks, double angleForTicks) { + void _calculateOffsetForMajorTicks( + double tickStartOffset, + double tickEndOffset, + double angularSpaceForTicks, + double angleForTicks, + ) { final num length = _actualInterval != null ? _majorTicksCount : _majorTicksCount - 1; for (num i = 0; i <= length; i++) { @@ -1804,17 +1957,25 @@ class RenderRadialAxisWidget extends RenderBox { final num count = _actualInterval != null ? _majorTicksCount : _majorTicksCount - 1; if (i == 0 || i == count) { - tickAngle = - _getTickPositionInCorner(i, angleForTicks, tickStartOffset, true); + tickAngle = _getTickPositionInCorner( + i, + angleForTicks, + tickStartOffset, + true, + ); } else { tickAngle = angleForTicks; } - final List tickPosition = - _getTickPosition(tickStartOffset, tickEndOffset, tickAngle); + final List tickPosition = _getTickPosition( + tickStartOffset, + tickEndOffset, + tickAngle, + ); final TickOffset tickOffset = TickOffset(); tickOffset.startPoint = tickPosition[0]; tickOffset.endPoint = tickPosition[1]; - final double degree = (isInversed + final double degree = + (isInversed ? getRadianToDegree(tickAngle) + 90 - (startAngle + _sweepAngle) : (getRadianToDegree(tickAngle) + 90 - startAngle)) / _sweepAngle; @@ -1824,10 +1985,14 @@ class RenderRadialAxisWidget extends RenderBox { : factorToValue(degree); final Offset centerPoint = !canScaleToFit ? Offset(_centerXPoint, _centerYPoint) : Offset.zero; - tickOffset.startPoint = Offset(tickOffset.startPoint.dx - centerPoint.dx, - tickOffset.startPoint.dy - centerPoint.dy); - tickOffset.endPoint = Offset(tickOffset.endPoint.dx - centerPoint.dx, - tickOffset.endPoint.dy - centerPoint.dy); + tickOffset.startPoint = Offset( + tickOffset.startPoint.dx - centerPoint.dx, + tickOffset.startPoint.dy - centerPoint.dy, + ); + tickOffset.endPoint = Offset( + tickOffset.endPoint.dx - centerPoint.dx, + tickOffset.endPoint.dy - centerPoint.dy, + ); _majorTickOffsets.add(tickOffset); if (isInversed) { angleForTicks -= angularSpaceForTicks; @@ -1839,19 +2004,27 @@ class RenderRadialAxisWidget extends RenderBox { /// Calculates the angle to adjust the start and end tick double _getTickPositionInCorner( - num num, double angleForTicks, double startOffset, bool isMajor) { + num num, + double angleForTicks, + double startOffset, + bool isMajor, + ) { final double thickness = isMajor ? majorTickThickness : minorTickThickness; - final double angle = - cornerRadiusAngle(startOffset + _actualAxisWidth / 2, thickness / 2); + final double angle = cornerRadiusAngle( + startOffset + _actualAxisWidth / 2, + thickness / 2, + ); if (num == 0) { - final double ticksAngle = !isInversed - ? getRadianToDegree(angleForTicks) + angle - : getRadianToDegree(angleForTicks) - angle; + final double ticksAngle = + !isInversed + ? getRadianToDegree(angleForTicks) + angle + : getRadianToDegree(angleForTicks) - angle; return getDegreeToRadian(ticksAngle); } else { - final double ticksAngle = !isInversed - ? getRadianToDegree(angleForTicks) - angle - : getRadianToDegree(angleForTicks) + angle; + final double ticksAngle = + !isInversed + ? getRadianToDegree(angleForTicks) - angle + : getRadianToDegree(angleForTicks) + angle; return getDegreeToRadian(ticksAngle); } } @@ -1862,17 +2035,22 @@ class RenderRadialAxisWidget extends RenderBox { final double axisLineWidth = showAxisLine ? _actualAxisWidth : 0; double tickStartOffset = 0; double tickEndOffset = 0; - final double offset = _isLabelsOutside - ? showLabels - ? (_actualLabelOffset + - math.max(_maximumLabelSize.height, _maximumLabelSize.width) / - 2) - : 0 - : 0; + final double offset = + _isLabelsOutside + ? showLabels + ? (_actualLabelOffset + + math.max( + _maximumLabelSize.height, + _maximumLabelSize.width, + ) / + 2) + : 0 + : 0; if (!_isTicksOutside) { tickStartOffset = _radius - (axisLineWidth + _actualTickOffset + offset); - tickEndOffset = _radius - + tickEndOffset = + _radius - (axisLineWidth + _actualMinorTickLength + _actualTickOffset + @@ -1883,10 +2061,11 @@ class RenderRadialAxisWidget extends RenderBox { tickStartOffset = _radius + _actualTickOffset; tickEndOffset = _radius + _actualMinorTickLength + _actualTickOffset; } else { - tickStartOffset = isGreater - ? _radius - offset - : _radius - - (_maximumTickLength - _actualMinorTickLength + offset); + tickStartOffset = + isGreater + ? _radius - offset + : _radius - + (_maximumTickLength - _actualMinorTickLength + offset); tickEndOffset = _radius - (_maximumTickLength + offset); } } @@ -1901,14 +2080,17 @@ class RenderRadialAxisWidget extends RenderBox { /// the smaller method but it leads to passing more number of parameter and /// which degrades the performance void _calculateOffsetForMinorTicks( - double tickStartOffset, double tickEndOffset) { + double tickStartOffset, + double tickEndOffset, + ) { _minorTickOffsets = []; double angularSpaceForTicks; double totalMinorTicks; if (_actualInterval != null) { final double majorTicksInterval = (maximum - minimum) / _actualInterval!; - angularSpaceForTicks = - getDegreeToRadian(_sweepAngle / majorTicksInterval); + angularSpaceForTicks = getDegreeToRadian( + _sweepAngle / majorTicksInterval, + ); final double maximumLabelValue = _axisLabels![_axisLabels!.length - 2].value.toDouble(); int remainingTicks; @@ -1921,19 +2103,22 @@ class RenderRadialAxisWidget extends RenderBox { remainingTicks = difference ~/ minorTickInterval; } - final int labelLength = difference == _actualInterval - ? _axisLabels!.length - 1 - : _axisLabels!.length - 2; + final int labelLength = + difference == _actualInterval + ? _axisLabels!.length - 1 + : _axisLabels!.length - 2; totalMinorTicks = (labelLength * minorTicksPerInterval) + remainingTicks; } else { - angularSpaceForTicks = - getDegreeToRadian(_sweepAngle / (_majorTicksCount - 1)); + angularSpaceForTicks = getDegreeToRadian( + _sweepAngle / (_majorTicksCount - 1), + ); totalMinorTicks = (_axisLabels!.length - 1) * minorTicksPerInterval; } - double angleForTicks = isInversed - ? getDegreeToRadian(startAngle + _sweepAngle - 90) - : getDegreeToRadian(startAngle - 90); + double angleForTicks = + isInversed + ? getDegreeToRadian(startAngle + _sweepAngle - 90) + : getDegreeToRadian(startAngle - 90); const num minorTickIndex = 1; // Since the minor tick rendering // needs to be start in the index one @@ -1947,24 +2132,33 @@ class RenderRadialAxisWidget extends RenderBox { angleForTicks += minorTickAngle; } - final double factor = (isInversed + final double factor = + (isInversed ? getRadianToDegree(angleForTicks) + 90 - (startAngle + _sweepAngle) : (getRadianToDegree(angleForTicks) + 90 - startAngle)) / _sweepAngle; - final double tickFactor = (renderer != null) - ? renderer!.factorToValue(factor) ?? factorToValue(factor) - : factorToValue(factor); + final double tickFactor = + (renderer != null) + ? renderer!.factorToValue(factor) ?? factorToValue(factor) + : factorToValue(factor); final double tickValue = double.parse(tickFactor.toStringAsFixed(5)); if (tickValue <= maximum && tickValue >= minimum) { if (tickValue == maximum) { angleForTicks = _getTickPositionInCorner( - i, angleForTicks, tickStartOffset, false); + i, + angleForTicks, + tickStartOffset, + false, + ); } - final List tickPosition = - _getTickPosition(tickStartOffset, tickEndOffset, angleForTicks); + final List tickPosition = _getTickPosition( + tickStartOffset, + tickEndOffset, + angleForTicks, + ); final TickOffset tickOffset = TickOffset(); tickOffset.startPoint = tickPosition[0]; tickOffset.endPoint = tickPosition[1]; @@ -1973,10 +2167,13 @@ class RenderRadialAxisWidget extends RenderBox { final Offset centerPoint = !canScaleToFit ? Offset(_centerXPoint, _centerYPoint) : Offset.zero; tickOffset.startPoint = Offset( - tickOffset.startPoint.dx - centerPoint.dx, - tickOffset.startPoint.dy - centerPoint.dy); - tickOffset.endPoint = Offset(tickOffset.endPoint.dx - centerPoint.dx, - tickOffset.endPoint.dy - centerPoint.dy); + tickOffset.startPoint.dx - centerPoint.dx, + tickOffset.startPoint.dy - centerPoint.dy, + ); + tickOffset.endPoint = Offset( + tickOffset.endPoint.dx - centerPoint.dx, + tickOffset.endPoint.dy - centerPoint.dy, + ); _minorTickOffsets.add(tickOffset); if (i % minorTicksPerInterval == 0) { if (isInversed) { @@ -2001,9 +2198,10 @@ class RenderRadialAxisWidget extends RenderBox { } final double labelSpaceInAngle = _sweepAngle / labelsInterval; final double labelSpaceInRadian = getDegreeToRadian(labelSpaceInAngle); - final double tickLength = _actualMajorTickLength > _actualMinorTickLength - ? _actualMajorTickLength - : _actualMinorTickLength; + final double tickLength = + _actualMajorTickLength > _actualMinorTickLength + ? _actualMajorTickLength + : _actualMinorTickLength; final double tickPadding = showTicks ? tickLength + _actualTickOffset : 0; double labelRadian = 0; double labelAngle = 0; @@ -2020,22 +2218,33 @@ class RenderRadialAxisWidget extends RenderBox { math.max(_maximumLabelSize.height, _maximumLabelSize.width) / 2; if (_isLabelsOutside) { final double featureOffset = labelSize; - labelPosition = _useAxisElementsInsideRadius - ? _radius - featureOffset - : _radius + tickPadding + _actualLabelOffset; + labelPosition = + _useAxisElementsInsideRadius + ? _radius - featureOffset + : _radius + tickPadding + _actualLabelOffset; } else { labelPosition = _radius - (_actualAxisWidth + tickPadding + _actualLabelOffset); } - _calculateLabelPosition(labelPosition, labelRadian, labelAngle, - labelSpaceInRadian, labelSpaceInAngle); + _calculateLabelPosition( + labelPosition, + labelRadian, + labelAngle, + labelSpaceInRadian, + labelSpaceInAngle, + ); } } // Method to calculate label position - void _calculateLabelPosition(double labelPosition, double labelRadian, - double labelAngle, double labelSpaceInRadian, double labelSpaceInAngle) { + void _calculateLabelPosition( + double labelPosition, + double labelRadian, + double labelAngle, + double labelSpaceInRadian, + double labelSpaceInAngle, + ) { for (int i = 0; i < _axisLabels!.length; i++) { final CircularAxisLabel label = _axisLabels![i]; label.angle = labelAngle; @@ -2046,24 +2255,26 @@ class RenderRadialAxisWidget extends RenderBox { label.angle = labelAngle; labelRadian = getDegreeToRadian(labelAngle); } else { - final double coordinateValue = (isInversed + final double coordinateValue = + (isInversed ? labelAngle + 90 - (startAngle + _sweepAngle) : (labelAngle + 90 - startAngle)) / _sweepAngle; - label.value = (renderer != null && - renderer!.factorToValue(coordinateValue) != null) - ? renderer!.factorToValue(coordinateValue) ?? - factorToValue(coordinateValue) - : factorToValue(coordinateValue); + label.value = + (renderer != null && + renderer!.factorToValue(coordinateValue) != null) + ? renderer!.factorToValue(coordinateValue) ?? + factorToValue(coordinateValue) + : factorToValue(coordinateValue); } if (!canScaleToFit) { final double x = ((size.width / 2) - (labelPosition * math.sin(labelRadian))) - - _centerXPoint; + _centerXPoint; final double y = ((size.height / 2) + (labelPosition * math.cos(labelRadian))) - - _centerYPoint; + _centerYPoint; label.position = Offset(x, y); } else { final double x = @@ -2089,14 +2300,16 @@ class RenderRadialAxisWidget extends RenderBox { for (int i = 0; i < _axisLabels!.length; i++) { final CircularAxisLabel label = _axisLabels![i]; label.labelSize = getTextSize(label.text, label.labelStyle); - final double maxWidth = _maximumLabelSize.width < label.labelSize.width - ? label.needsRotateLabel + final double maxWidth = + _maximumLabelSize.width < label.labelSize.width + ? label.needsRotateLabel + ? label.labelSize.height + : label.labelSize.width + : _maximumLabelSize.width; + final double maxHeight = + _maximumLabelSize.height < label.labelSize.height ? label.labelSize.height - : label.labelSize.width - : _maximumLabelSize.width; - final double maxHeight = _maximumLabelSize.height < label.labelSize.height - ? label.labelSize.height - : _maximumLabelSize.height; + : _maximumLabelSize.height; _maximumLabelSize = Size(maxWidth, maxHeight); } @@ -2104,7 +2317,10 @@ class RenderRadialAxisWidget extends RenderBox { /// Gets the start and end offset of tick List _getTickPosition( - double tickStartOffset, double tickEndOffset, double angleForTicks) { + double tickStartOffset, + double tickEndOffset, + double angleForTicks, + ) { final Offset centerPoint = !canScaleToFit ? Offset(size.width / 2, size.height / 2) : _axisCenter; final double tickStartX = @@ -2179,11 +2395,15 @@ class RenderRadialAxisWidget extends RenderBox { num calculateAxisInterval(int actualMaximumValue) { final num delta = _getAxisRange(); final num circumference = 2 * math.pi * _center * (_sweepAngle / 360); - final num desiredIntervalCount = - math.max(circumference * ((0.533 * actualMaximumValue) / 100), 1); + final num desiredIntervalCount = math.max( + circumference * ((0.533 * actualMaximumValue) / 100), + 1, + ); num niceInterval = delta / desiredIntervalCount; - final num minimumInterval = - math.pow(10, (math.log(niceInterval) / math.log(10)).floor()); + final num minimumInterval = math.pow( + 10, + (math.log(niceInterval) / math.log(10)).floor(), + ); final List intervalDivisions = [10, 5, 2, 1]; for (int i = 0; i < intervalDivisions.length; i++) { final num currentInterval = minimumInterval * intervalDivisions[i]; @@ -2238,12 +2458,13 @@ class RenderRadialAxisWidget extends RenderBox { final GaugeTextStyle labelStyle = argsLabelStyle ?? gaugeTextStyle; final CircularAxisLabel label = CircularAxisLabel( - labelStyle, - labelText, - i, - labelCreatedArgs != null && - labelCreatedArgs.canRotate != null && - labelCreatedArgs.canRotate!); + labelStyle, + labelText, + i, + labelCreatedArgs != null && + labelCreatedArgs.canRotate != null && + labelCreatedArgs.canRotate!, + ); label.value = value; return label; } @@ -2281,9 +2502,10 @@ class RenderRadialAxisWidget extends RenderBox { /// Converts the factor value to axis value. double factorToValue(double factor) { - final double angle = isInversed - ? (factor * _sweepAngle) + startAngle + _sweepAngle - : (factor * _sweepAngle) + startAngle; + final double angle = + isInversed + ? (factor * _sweepAngle) + startAngle + _sweepAngle + : (factor * _sweepAngle) + startAngle; return _angleToValue(angle); } @@ -2295,18 +2517,33 @@ class RenderRadialAxisWidget extends RenderBox { SweepGradient? gradient; if (axisLineGradient != null && axisLineGradient!.colors.isNotEmpty) { gradient = SweepGradient( - stops: calculateGradientStops( - _getGradientOffset(), isInversed, _sweepAngle), - colors: isInversed - ? axisLineGradient!.colors.reversed.toList() - : axisLineGradient!.colors); + stops: calculateGradientStops( + _getGradientOffset(), + isInversed, + _sweepAngle, + ), + colors: + isInversed + ? axisLineGradient!.colors.reversed.toList() + : axisLineGradient!.colors, + ); } if (axisLineCornerStyle == CornerStyle.bothFlat || isDashedAxisLine) { _drawAxisPath( - canvas, _startRadian, _endRadian, gradient, isDashedAxisLine); + canvas, + _startRadian, + _endRadian, + gradient, + isDashedAxisLine, + ); } else { - _drawAxisPath(canvas, _startCornerRadian, _sweepCornerRadian, gradient, - isDashedAxisLine); + _drawAxisPath( + canvas, + _startCornerRadian, + _sweepCornerRadian, + gradient, + isDashedAxisLine, + ); } } @@ -2318,8 +2555,10 @@ class RenderRadialAxisWidget extends RenderBox { } else { // Calculates the gradient stop values based on the provided color final double difference = 1 / axisLineGradient!.colors.length; - final List offsets = - List.filled(axisLineGradient!.colors.length, null); + final List offsets = List.filled( + axisLineGradient!.colors.length, + null, + ); for (int i = 0; i < axisLineGradient!.colors.length; i++) { offsets[i] = i * difference; } @@ -2329,17 +2568,24 @@ class RenderRadialAxisWidget extends RenderBox { } /// Method to draw axis line. - void _drawAxisPath(Canvas canvas, double startRadian, double endRadian, - SweepGradient? gradient, bool isDashedAxisLine) { + void _drawAxisPath( + Canvas canvas, + double startRadian, + double endRadian, + SweepGradient? gradient, + bool isDashedAxisLine, + ) { if (_axisLineAnimation != null) { endRadian = endRadian * _axisLineAnimation!.value; } canvas.save(); canvas.translate(_axisCenter.dx, _axisCenter.dy); - canvas.rotate(isInversed - ? getDegreeToRadian(startAngle + _sweepAngle) - : getDegreeToRadian(startAngle)); + canvas.rotate( + isInversed + ? getDegreeToRadian(startAngle + _sweepAngle) + : getDegreeToRadian(startAngle), + ); Path path = Path(); //whether the style of paint is fill. @@ -2358,16 +2604,23 @@ class RenderRadialAxisWidget extends RenderBox { _drawStartCurve(path, endRadian, innerRadius, outerRadius); } - path.addArc(Rect.fromCircle(center: Offset.zero, radius: outerRadius), - _startCornerRadian, endRadian); + path.addArc( + Rect.fromCircle(center: Offset.zero, radius: outerRadius), + _startCornerRadian, + endRadian, + ); // Adds the rounded corner at end of axis line. if (axisLineCornerStyle == CornerStyle.endCurve || axisLineCornerStyle == CornerStyle.bothCurve) { _drawEndCurve(path, endRadian, innerRadius, outerRadius); } - path.arcTo(Rect.fromCircle(center: Offset.zero, radius: innerRadius), - endRadian + _startCornerRadian, -endRadian, false); + path.arcTo( + Rect.fromCircle(center: Offset.zero, radius: innerRadius), + endRadian + _startCornerRadian, + -endRadian, + false, + ); } } else { path = _getPath(endRadian, isFill); @@ -2377,17 +2630,25 @@ class RenderRadialAxisWidget extends RenderBox { } // Method to render the path. - void _renderPath(bool isDashedAxisLine, Path path, Canvas canvas, - SweepGradient? gradient, bool isFill) { + void _renderPath( + bool isDashedAxisLine, + Path path, + Canvas canvas, + SweepGradient? gradient, + bool isFill, + ) { final Paint paint = _getPaint(gradient, isFill); if (!isDashedAxisLine) { canvas.drawPath(path, paint); } else { if (axisLineDashArray != null) { canvas.drawPath( - dashPath(path, - dashArray: CircularIntervalList(axisLineDashArray!)), - paint); + dashPath( + path, + dashArray: CircularIntervalList(axisLineDashArray!), + ), + paint, + ); } } @@ -2406,16 +2667,15 @@ class RenderRadialAxisWidget extends RenderBox { return path; } - Paint _getPaint( - SweepGradient? gradient, - bool isFill, - ) { - final Paint paint = Paint() - ..color = axisLineColor ?? - _gaugeThemeData.axisLineColor ?? - colorScheme.onSurface[35]! - ..style = !isFill ? PaintingStyle.stroke : PaintingStyle.fill - ..strokeWidth = _actualAxisWidth; + Paint _getPaint(SweepGradient? gradient, bool isFill) { + final Paint paint = + Paint() + ..color = + axisLineColor ?? + _gaugeThemeData.axisLineColor ?? + colorScheme.onSurface[35]! + ..style = !isFill ? PaintingStyle.stroke : PaintingStyle.fill + ..strokeWidth = _actualAxisWidth; if (gradient != null) { paint.shader = gradient.createShader(_axisRect); } @@ -2425,45 +2685,65 @@ class RenderRadialAxisWidget extends RenderBox { /// Draws the start corner style void _drawStartCurve( - Path path, double endRadian, double innerRadius, double outerRadius) { + Path path, + double endRadian, + double innerRadius, + double outerRadius, + ) { final Offset midPoint = getDegreeToPoint( - isInversed ? -_cornerAngle : _cornerAngle, - (innerRadius + outerRadius) / 2, - Offset.zero); + isInversed ? -_cornerAngle : _cornerAngle, + (innerRadius + outerRadius) / 2, + Offset.zero, + ); final double midStartAngle = getDegreeToRadian(180); double midEndAngle = midStartAngle + getDegreeToRadian(180); midEndAngle = isInversed ? -midEndAngle : midEndAngle; path.addArc( - Rect.fromCircle( - center: midPoint, radius: (innerRadius - outerRadius).abs() / 2), - midStartAngle, - midEndAngle); + Rect.fromCircle( + center: midPoint, + radius: (innerRadius - outerRadius).abs() / 2, + ), + midStartAngle, + midEndAngle, + ); } ///Draws the end corner curve void _drawEndCurve( - Path path, double sweepRadian, double innerRadius, double outerRadius) { + Path path, + double sweepRadian, + double innerRadius, + double outerRadius, + ) { final double curveCornerAngle = axisLineCornerStyle == CornerStyle.bothCurve ? _cornerAngle : 0; - final double angle = isInversed - ? getRadianToDegree(sweepRadian) - curveCornerAngle - : getRadianToDegree(sweepRadian) + curveCornerAngle; - final Offset midPoint = - getDegreeToPoint(angle, (innerRadius + outerRadius) / 2, Offset.zero); + final double angle = + isInversed + ? getRadianToDegree(sweepRadian) - curveCornerAngle + : getRadianToDegree(sweepRadian) + curveCornerAngle; + final Offset midPoint = getDegreeToPoint( + angle, + (innerRadius + outerRadius) / 2, + Offset.zero, + ); final double midStartAngle = sweepRadian / 2; - final double midEndAngle = isInversed - ? midStartAngle - getDegreeToRadian(180) - : midStartAngle + getDegreeToRadian(180); + final double midEndAngle = + isInversed + ? midStartAngle - getDegreeToRadian(180) + : midStartAngle + getDegreeToRadian(180); path.arcTo( - Rect.fromCircle( - center: midPoint, radius: (innerRadius - outerRadius).abs() / 2), - midStartAngle, - midEndAngle, - false); + Rect.fromCircle( + center: midPoint, + radius: (innerRadius - outerRadius).abs() / 2, + ), + midStartAngle, + midEndAngle, + false, + ); } /// Checks whether the axis line is dashed line @@ -2482,7 +2762,8 @@ class RenderRadialAxisWidget extends RenderBox { for (int i = 0; i < ranges!.length; i++) { if (ranges![i].startValue <= value.roundToDouble() && ranges![i].endValue >= value.roundToDouble()) { - color = ranges![i].color ?? + color = + ranges![i].color ?? gaugeThemeData.rangeColor ?? const Color(0xFFF67280); break; @@ -2501,49 +2782,61 @@ class RenderRadialAxisWidget extends RenderBox { } if (_actualMajorTickLength > 0 && majorTickThickness > 0) { - final Paint tickPaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = majorTickThickness; + final Paint tickPaint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = majorTickThickness; for (int i = 0; i < length; i++) { final TickOffset tickOffset = _majorTickOffsets[i]; if (!(i == 0 && _sweepAngle == 360)) { - tickPaint.color = useRangeColorForAxis - ? _getRangeColor(tickOffset.value, _gaugeThemeData) ?? - majorTickColor ?? - _gaugeThemeData.majorTickColor ?? - colorSchemeMajorTickColor - : majorTickColor ?? - _gaugeThemeData.majorTickColor ?? - colorSchemeMajorTickColor; + tickPaint.color = + useRangeColorForAxis + ? _getRangeColor(tickOffset.value, _gaugeThemeData) ?? + majorTickColor ?? + _gaugeThemeData.majorTickColor ?? + colorSchemeMajorTickColor + : majorTickColor ?? + _gaugeThemeData.majorTickColor ?? + colorSchemeMajorTickColor; if (majorTickDashArray != null && majorTickDashArray!.isNotEmpty) { - final Path path = Path() - ..moveTo(tickOffset.startPoint.dx, tickOffset.startPoint.dy) - ..lineTo(tickOffset.endPoint.dx, tickOffset.endPoint.dy); + final Path path = + Path() + ..moveTo(tickOffset.startPoint.dx, tickOffset.startPoint.dy) + ..lineTo(tickOffset.endPoint.dx, tickOffset.endPoint.dy); canvas.drawPath( - dashPath(path, - dashArray: - CircularIntervalList(majorTickDashArray!)), - tickPaint); + dashPath( + path, + dashArray: CircularIntervalList(majorTickDashArray!), + ), + tickPaint, + ); } else { if ((i == _majorTickOffsets.length - 1) && _sweepAngle == 360) { // Reposition the last tick when its sweep angle is 360 - final double x1 = (_majorTickOffsets[0].startPoint.dx + + final double x1 = + (_majorTickOffsets[0].startPoint.dx + _majorTickOffsets[i].startPoint.dx) / 2; - final double y1 = (_majorTickOffsets[0].startPoint.dy + + final double y1 = + (_majorTickOffsets[0].startPoint.dy + _majorTickOffsets[i].startPoint.dy) / 2; - final double x2 = (_majorTickOffsets[0].endPoint.dx + + final double x2 = + (_majorTickOffsets[0].endPoint.dx + _majorTickOffsets[i].endPoint.dx) / 2; - final double y2 = (_majorTickOffsets[0].endPoint.dy + + final double y2 = + (_majorTickOffsets[0].endPoint.dy + _majorTickOffsets[i].endPoint.dy) / 2; canvas.drawLine(Offset(x1, y1), Offset(x2, y2), tickPaint); } else { canvas.drawLine( - tickOffset.startPoint, tickOffset.endPoint, tickPaint); + tickOffset.startPoint, + tickOffset.endPoint, + tickPaint, + ); } } } @@ -2559,30 +2852,39 @@ class RenderRadialAxisWidget extends RenderBox { length = _minorTickOffsets.length * _axisElementsAnimation!.value; } if (_actualMinorTickLength > 0 && minorTickThickness > 0) { - final Paint tickPaint = Paint() - ..style = PaintingStyle.stroke - ..strokeWidth = minorTickThickness; + final Paint tickPaint = + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = minorTickThickness; for (int i = 0; i < length; i++) { final TickOffset tickOffset = _minorTickOffsets[i]; - tickPaint.color = useRangeColorForAxis - ? _getRangeColor(tickOffset.value, _gaugeThemeData) ?? - minorTickColor ?? - _gaugeThemeData.minorTickColor ?? - colorSchemeMinorTickColor - : minorTickColor ?? - _gaugeThemeData.minorTickColor ?? - colorSchemeMinorTickColor; + tickPaint.color = + useRangeColorForAxis + ? _getRangeColor(tickOffset.value, _gaugeThemeData) ?? + minorTickColor ?? + _gaugeThemeData.minorTickColor ?? + colorSchemeMinorTickColor + : minorTickColor ?? + _gaugeThemeData.minorTickColor ?? + colorSchemeMinorTickColor; if (minorTickDashArray != null && minorTickDashArray!.isNotEmpty) { - final Path path = Path() - ..moveTo(tickOffset.startPoint.dx, tickOffset.startPoint.dy) - ..lineTo(tickOffset.endPoint.dx, tickOffset.endPoint.dy); + final Path path = + Path() + ..moveTo(tickOffset.startPoint.dx, tickOffset.startPoint.dy) + ..lineTo(tickOffset.endPoint.dx, tickOffset.endPoint.dy); canvas.drawPath( - dashPath(path, - dashArray: CircularIntervalList(minorTickDashArray!)), - tickPaint); + dashPath( + path, + dashArray: CircularIntervalList(minorTickDashArray!), + ), + tickPaint, + ); } else { canvas.drawLine( - tickOffset.startPoint, tickOffset.endPoint, tickPaint); + tickOffset.startPoint, + tickOffset.endPoint, + tickPaint, + ); } } } @@ -2598,32 +2900,42 @@ class RenderRadialAxisWidget extends RenderBox { if (!((i == 0 && !showFirstLabel) || (i == _axisLabels!.length - 1 && !showLastLabel))) { final CircularAxisLabel label = _axisLabels![i]; - final Color labelColor = label.labelStyle.color ?? + final Color labelColor = + label.labelStyle.color ?? _gaugeThemeData.axisLabelTextStyle?.color ?? _gaugeThemeData.axisLabelColor ?? colorScheme.onSurface[184]!; - final TextStyle axisLabelTextStyle = - _themeData.textTheme.bodySmall!.copyWith( - color: ranges != null && ranges!.isNotEmpty && useRangeColorForAxis - ? _getRangeColor(label.value, _gaugeThemeData) ?? labelColor - : labelColor, - fontSize: label.labelStyle.fontSize ?? - _gaugeThemeData.axisLabelTextStyle?.fontSize, - fontFamily: label.labelStyle.fontFamily ?? - _gaugeThemeData.axisLabelTextStyle?.fontFamily, - fontStyle: label.labelStyle.fontStyle ?? - _gaugeThemeData.axisLabelTextStyle?.fontStyle, - fontWeight: label.labelStyle.fontWeight ?? - _gaugeThemeData.axisLabelTextStyle?.fontWeight, + final TextStyle axisLabelTextStyle = _themeData.textTheme.bodySmall! + .copyWith( + color: + ranges != null && ranges!.isNotEmpty && useRangeColorForAxis + ? _getRangeColor(label.value, _gaugeThemeData) ?? + labelColor + : labelColor, + fontSize: + label.labelStyle.fontSize ?? + _gaugeThemeData.axisLabelTextStyle?.fontSize, + fontFamily: + label.labelStyle.fontFamily ?? + _gaugeThemeData.axisLabelTextStyle?.fontFamily, + fontStyle: + label.labelStyle.fontStyle ?? + _gaugeThemeData.axisLabelTextStyle?.fontStyle, + fontWeight: + label.labelStyle.fontWeight ?? + _gaugeThemeData.axisLabelTextStyle?.fontWeight, + ); + + final TextSpan span = TextSpan( + text: label.text, + style: axisLabelTextStyle, ); - final TextSpan span = - TextSpan(text: label.text, style: axisLabelTextStyle); - final TextPainter textPainter = TextPainter( - text: span, - textDirection: TextDirection.ltr, - textAlign: TextAlign.center); + text: span, + textDirection: TextDirection.ltr, + textAlign: TextAlign.center, + ); textPainter.layout(); _renderText(canvas, textPainter, label); @@ -2633,21 +2945,29 @@ class RenderRadialAxisWidget extends RenderBox { // Methods to render the range label. void _renderText( - Canvas canvas, TextPainter textPainter, CircularAxisLabel label) { + Canvas canvas, + TextPainter textPainter, + CircularAxisLabel label, + ) { if (canRotateLabels || label.needsRotateLabel) { canvas.save(); canvas.translate(label.position.dx, label.position.dy); // Rotates the labels to its calculated angle. canvas.rotate(getDegreeToRadian(label.angle)); canvas.scale(-1); - textPainter.paint(canvas, - Offset(-label.labelSize.width / 2, -label.labelSize.height / 2)); + textPainter.paint( + canvas, + Offset(-label.labelSize.width / 2, -label.labelSize.height / 2), + ); canvas.restore(); } else { textPainter.paint( - canvas, - Offset(label.position.dx - label.labelSize.width / 2, - label.position.dy - label.labelSize.height / 2)); + canvas, + Offset( + label.position.dx - label.labelSize.width / 2, + label.position.dy - label.labelSize.height / 2, + ), + ); } } @@ -2661,13 +2981,18 @@ class RenderRadialAxisWidget extends RenderBox { if (!canScaleToFit) { final double radius = math.min(size.width, size.height) / 2; rect = Rect.fromLTRB( - size.width / 2 - radius - _centerXPoint, - size.height / 2 - radius - _centerYPoint, - size.width / 2 + radius - _centerXPoint, - size.height / 2 + radius - _centerYPoint); + size.width / 2 - radius - _centerXPoint, + size.height / 2 - radius - _centerYPoint, + size.width / 2 + radius - _centerXPoint, + size.height / 2 + radius - _centerYPoint, + ); } else { - rect = Rect.fromLTRB(_axisCenter.dx - _radius, _axisCenter.dy - _radius, - _axisCenter.dx + _radius, _axisCenter.dx + _radius); + rect = Rect.fromLTRB( + _axisCenter.dx - _radius, + _axisCenter.dy - _radius, + _axisCenter.dx + _radius, + _axisCenter.dx + _radius, + ); } // Draws the background image of axis diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge.dart index 232c14714..d1420e893 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge.dart @@ -38,15 +38,15 @@ class SfRadialGauge extends StatefulWidget { /// /// To enable the loading animation set [enableLoadingAnimation] is true. // ignore: prefer_const_constructors_in_immutables - SfRadialGauge( - {Key? key, - List? axes, - this.enableLoadingAnimation = false, - this.animationDuration = 2000, - this.backgroundColor = Colors.transparent, - this.title}) - : axes = axes ?? [RadialAxis()], - super(key: key); + SfRadialGauge({ + Key? key, + List? axes, + this.enableLoadingAnimation = false, + this.animationDuration = 2000, + this.backgroundColor = Colors.transparent, + this.title, + }) : axes = axes ?? [RadialAxis()], + super(key: key); /// Add a list of radial axis to the gauge and customize each axis by /// adding it to the [axes] collection. @@ -164,16 +164,14 @@ class SfRadialGaugeState extends State final ThemeData themeData = Theme.of(context); final bool isMaterial3 = themeData.useMaterial3; gaugeThemeData = gaugeThemeData.copyWith( - titleTextStyle: Theme.of(context) - .textTheme - .bodySmall! - .copyWith( - color: - gaugeThemeData.titleColor ?? themeData.colorScheme.onSurface, - fontSize: isMaterial3 ? 16 : 15, - ) - .merge(gaugeThemeData.titleTextStyle) - .merge(widget.title?.textStyle)); + titleTextStyle: Theme.of(context).textTheme.bodySmall! + .copyWith( + color: gaugeThemeData.titleColor ?? themeData.colorScheme.onSurface, + fontSize: isMaterial3 ? 16 : 15, + ) + .merge(gaugeThemeData.titleTextStyle) + .merge(widget.title?.textStyle), + ); return gaugeThemeData; } @@ -181,27 +179,30 @@ class SfRadialGaugeState extends State Widget _addGaugeTitle() { if (widget.title != null && widget.title!.text.isNotEmpty) { final Widget titleWidget = Container( - padding: const EdgeInsets.fromLTRB(0, 5, 0, 0), - decoration: BoxDecoration( - color: widget.title!.backgroundColor ?? - _gaugeTheme.titleBackgroundColor, - border: Border.all( - color: - widget.title!.borderColor ?? _gaugeTheme.titleBorderColor, - width: widget.title!.borderWidth)), - alignment: (widget.title!.alignment == GaugeAlignment.near) - ? Alignment.topLeft - : (widget.title!.alignment == GaugeAlignment.far) - ? Alignment.topRight - : (widget.title!.alignment == GaugeAlignment.center) - ? Alignment.topCenter - : Alignment.topCenter, - child: Text( - widget.title!.text, - style: _gaugeTheme.titleTextStyle, - textAlign: TextAlign.center, - overflow: TextOverflow.clip, - )); + padding: const EdgeInsets.fromLTRB(0, 5, 0, 0), + decoration: BoxDecoration( + color: + widget.title!.backgroundColor ?? _gaugeTheme.titleBackgroundColor, + border: Border.all( + color: widget.title!.borderColor ?? _gaugeTheme.titleBorderColor, + width: widget.title!.borderWidth, + ), + ), + alignment: + (widget.title!.alignment == GaugeAlignment.near) + ? Alignment.topLeft + : (widget.title!.alignment == GaugeAlignment.far) + ? Alignment.topRight + : (widget.title!.alignment == GaugeAlignment.center) + ? Alignment.topCenter + : Alignment.topCenter, + child: Text( + widget.title!.text, + style: _gaugeTheme.titleTextStyle, + textAlign: TextAlign.center, + overflow: TextOverflow.clip, + ), + ); return titleWidget; } else { @@ -214,25 +215,35 @@ class SfRadialGaugeState extends State final List radialAxes = []; for (int i = 0; i < widget.axes.length; i++) { - radialAxes.add(RadialGaugeScope( + radialAxes.add( + RadialGaugeScope( enableLoadingAnimation: widget.enableLoadingAnimation, animationDuration: widget.animationDuration.toInt(), - child: widget.axes[i])); + child: widget.axes[i], + ), + ); } return RepaintBoundary( - child: LimitedBox( - maxHeight: 350, - maxWidth: 350, - child: Container( - color: widget.backgroundColor, - child: Column(children: [ - _addGaugeTitle(), - Expanded( - child: Stack( - textDirection: TextDirection.ltr, - children: radialAxes)) - ])))); + child: LimitedBox( + maxHeight: 350, + maxWidth: 350, + child: Container( + color: widget.backgroundColor, + child: Column( + children: [ + _addGaugeTitle(), + Expanded( + child: Stack( + textDirection: TextDirection.ltr, + children: radialAxes, + ), + ), + ], + ), + ), + ), + ); } /// Method to convert the [SfRadialGauge] as an image. diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge_scope.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge_scope.dart index 3050a51f2..439c06dc0 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge_scope.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/gauge/radial_gauge_scope.dart @@ -21,9 +21,10 @@ class RadialGaugeScope extends InheritedWidget { static RadialGaugeScope of(BuildContext context) { late RadialGaugeScope scope; - final Widget widget = context - .getElementForInheritedWidgetOfExactType()! - .widget; + final Widget widget = + context + .getElementForInheritedWidgetOfExactType()! + .widget; if (widget is RadialGaugeScope) { scope = widget; diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer.dart index d2c8de6af..1d308330c 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer.dart @@ -61,15 +61,16 @@ class MarkerPointer extends LeafRenderObjectWidget implements GaugePointer { this.overlayColor, this.overlayRadius, this.elevation = 0, - }) : textStyle = textStyle ?? const GaugeTextStyle(), - assert(animationDuration > 0, - 'Animation duration must be a non-negative value.'), - assert(markerWidth >= 0, 'Marker width must be a non-negative value.'), - assert(markerHeight >= 0, 'Marker height must be non-negative value.'), - assert(borderWidth >= 0, 'Border width must be non-negative value.'), - assert( - elevation >= 0, 'Shadow elevation must be a non-negative value.'), - super(key: key); + }) : textStyle = textStyle ?? const GaugeTextStyle(), + assert( + animationDuration > 0, + 'Animation duration must be a non-negative value.', + ), + assert(markerWidth >= 0, 'Marker width must be a non-negative value.'), + assert(markerHeight >= 0, 'Marker height must be non-negative value.'), + assert(borderWidth >= 0, 'Border width must be non-negative value.'), + assert(elevation >= 0, 'Shadow elevation must be a non-negative value.'), + super(key: key); /// Specifies the built-in shape type for pointer. /// @@ -345,7 +346,7 @@ class MarkerPointer extends LeafRenderObjectWidget implements GaugePointer { /// } ///``` final MarkerPointerRendererFactory? - onCreatePointerRenderer; + onCreatePointerRenderer; /// Elevation of the pointer. /// @@ -657,8 +658,9 @@ class MarkerPointer extends LeafRenderObjectWidget implements GaugePointer { final ThemeData themeData = Theme.of(context); final SfColorScheme colorScheme = SfTheme.colorScheme(context); final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; MarkerPointerRenderer? markerPointerRenderer; if (onCreatePointerRenderer != null) { @@ -667,47 +669,51 @@ class MarkerPointer extends LeafRenderObjectWidget implements GaugePointer { } return RenderMarkerPointer( - value: value.clamp(ancestor.minimum, ancestor.maximum), - enableDragging: enableDragging, - onValueChanged: onValueChanged, - onValueChangeStart: onValueChangeStart, - onValueChangeEnd: onValueChangeEnd, - onValueChanging: onValueChanging, - markerType: markerType, - color: color, - markerWidth: markerWidth, - markerHeight: markerHeight, - borderWidth: borderWidth, - markerOffset: markerOffset, - text: text, - borderColor: borderColor, - offsetUnit: offsetUnit, - imageUrl: imageUrl, - markerPointerRenderer: markerPointerRenderer, - textStyle: textStyle, - overlayColor: overlayColor, - overlayRadius: overlayRadius, - elevation: elevation, - animationType: animationType, - pointerInterval: radialAxisScope.pointerInterval, - enableAnimation: enableAnimation, - isRadialGaugeAnimationEnabled: - radialAxisScope.isRadialGaugeAnimationEnabled, - pointerAnimationController: radialAxisScope.animationController, - repaintNotifier: radialAxisScope.repaintNotifier, - gaugeThemeData: gaugeTheme, - themeData: themeData, - colorScheme: colorScheme); + value: value.clamp(ancestor.minimum, ancestor.maximum), + enableDragging: enableDragging, + onValueChanged: onValueChanged, + onValueChangeStart: onValueChangeStart, + onValueChangeEnd: onValueChangeEnd, + onValueChanging: onValueChanging, + markerType: markerType, + color: color, + markerWidth: markerWidth, + markerHeight: markerHeight, + borderWidth: borderWidth, + markerOffset: markerOffset, + text: text, + borderColor: borderColor, + offsetUnit: offsetUnit, + imageUrl: imageUrl, + markerPointerRenderer: markerPointerRenderer, + textStyle: textStyle, + overlayColor: overlayColor, + overlayRadius: overlayRadius, + elevation: elevation, + animationType: animationType, + pointerInterval: radialAxisScope.pointerInterval, + enableAnimation: enableAnimation, + isRadialGaugeAnimationEnabled: + radialAxisScope.isRadialGaugeAnimationEnabled, + pointerAnimationController: radialAxisScope.animationController, + repaintNotifier: radialAxisScope.repaintNotifier, + gaugeThemeData: gaugeTheme, + themeData: themeData, + colorScheme: colorScheme, + ); } @override void updateRenderObject( - BuildContext context, RenderMarkerPointer renderObject) { + BuildContext context, + RenderMarkerPointer renderObject, + ) { final SfGaugeThemeData gaugeTheme = SfGaugeTheme.of(context)!; final ThemeData themeData = Theme.of(context); final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; MarkerPointerRenderer? markerPointerRenderer; if (onCreatePointerRenderer != null) { markerPointerRenderer = onCreatePointerRenderer!(); diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer_renderer.dart index 4481e9980..bb7a60115 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/marker_pointer_renderer.dart @@ -49,27 +49,27 @@ class RenderMarkerPointer extends RenderBox { required SfGaugeThemeData gaugeThemeData, required ThemeData themeData, required SfColorScheme colorScheme, - }) : _value = value, - _markerType = markerType, - _color = color, - _markerWidth = markerWidth, - _markerHeight = markerHeight, - _borderWidth = borderWidth, - _markerOffset = markerOffset, - _text = text, - _borderColor = borderColor, - _offsetUnit = offsetUnit, - _imageUrl = imageUrl, - _textStyle = textStyle, - _overlayColor = overlayColor, - _overlayRadius = overlayRadius, - _elevation = elevation, - _markerPointerRenderer = markerPointerRenderer, - _pointerAnimationController = pointerAnimationController, - _repaintNotifier = repaintNotifier, - _gaugeThemeData = gaugeThemeData, - _themeData = themeData, - _colorScheme = colorScheme; + }) : _value = value, + _markerType = markerType, + _color = color, + _markerWidth = markerWidth, + _markerHeight = markerHeight, + _borderWidth = borderWidth, + _markerOffset = markerOffset, + _text = text, + _borderColor = borderColor, + _offsetUnit = offsetUnit, + _imageUrl = imageUrl, + _textStyle = textStyle, + _overlayColor = overlayColor, + _overlayRadius = overlayRadius, + _elevation = elevation, + _markerPointerRenderer = markerPointerRenderer, + _pointerAnimationController = pointerAnimationController, + _repaintNotifier = repaintNotifier, + _gaugeThemeData = gaugeThemeData, + _themeData = themeData, + _colorScheme = colorScheme; final double _margin = 15; dart_ui.Image? _image; @@ -505,7 +505,10 @@ class RenderMarkerPointer extends RenderBox { _axisCenter = axisRenderer!.getAxisCenter(); _radius = _axisRenderer!.getRadius(); _actualAxisWidth = _axisRenderer!.getActualValue( - _axisRenderer!.thickness, _axisRenderer!.thicknessUnit, false); + _axisRenderer!.thickness, + _axisRenderer!.thicknessUnit, + false, + ); } void _animationStatusListener(AnimationStatus status) { @@ -560,10 +563,11 @@ class RenderMarkerPointer extends RenderBox { } pointerRect = Rect.fromLTRB( - offset.dx - markerWidth / 2 - _margin, - offset.dy - markerHeight / 2 - _margin, - offset.dx + markerWidth / 2 + _margin, - offset.dy + markerHeight / 2 + _margin); + offset.dx - markerWidth / 2 - _margin, + offset.dy - markerHeight / 2 - _margin, + offset.dx + markerWidth / 2 + _margin, + offset.dy + markerHeight / 2 + _margin, + ); } @override @@ -585,36 +589,45 @@ class RenderMarkerPointer extends RenderBox { /// Method returns the angle of current pointer value double _getPointerAngle() { - final double currentFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer?.valueToFactor(value) != null) - ? axisRenderer!.renderer?.valueToFactor(value) ?? - axisRenderer!.valueToFactor(value) - : axisRenderer!.valueToFactor(value); + final double currentFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer?.valueToFactor(value) != null) + ? axisRenderer!.renderer?.valueToFactor(value) ?? + axisRenderer!.valueToFactor(value) + : axisRenderer!.valueToFactor(value); return (currentFactor * _sweepAngle) + axisRenderer!.startAngle; } /// Calculates the marker offset position Offset _getMarkerOffset(double markerRadian) { - _actualMarkerOffset = - axisRenderer!.getActualValue(markerOffset, offsetUnit, true); - _totalOffset = _actualMarkerOffset < 0 - ? axisRenderer!.getAxisOffset() + _actualMarkerOffset - : (_actualMarkerOffset + axisRenderer!.getAxisOffset()); + _actualMarkerOffset = axisRenderer!.getActualValue( + markerOffset, + offsetUnit, + true, + ); + _totalOffset = + _actualMarkerOffset < 0 + ? axisRenderer!.getAxisOffset() + _actualMarkerOffset + : (_actualMarkerOffset + axisRenderer!.getAxisOffset()); if (!axisRenderer!.canScaleToFit) { - final double x = (size.width / 2) + + final double x = + (size.width / 2) + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.cos(markerRadian) - _centerXPoint; - final double y = (size.height / 2) + + final double y = + (size.height / 2) + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.sin(markerRadian) - _centerYPoint; _offset = Offset(x, y); } else { - final double x = _axisCenter.dx + + final double x = + _axisCenter.dx + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.cos(markerRadian); - final double y = _axisCenter.dy + + final double y = + _axisCenter.dy + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.sin(markerRadian); _offset = Offset(x, y); @@ -627,16 +640,18 @@ class RenderMarkerPointer extends RenderBox { // ignore: avoid_void_async void _loadImage() async { await _renderImage().then((void value) { - WidgetsBinding.instance - .addPostFrameCallback((Duration duration) => markNeedsPaint()); + WidgetsBinding.instance.addPostFrameCallback( + (Duration duration) => markNeedsPaint(), + ); }); } /// Renders the image from the image url Future _renderImage() async { final ByteData imageData = await rootBundle.load(imageUrl!); - final dart_ui.Codec imageCodec = - await dart_ui.instantiateImageCodec(imageData.buffer.asUint8List()); + final dart_ui.Codec imageCodec = await dart_ui.instantiateImageCodec( + imageData.buffer.asUint8List(), + ); final dart_ui.FrameInfo frameInfo = await imageCodec.getNextFrame(); _image = frameInfo.image; } @@ -646,80 +661,108 @@ class RenderMarkerPointer extends RenderBox { /// By overriding this method, you can draw the customized marker /// pointer using required values. /// - void drawPointer(Canvas canvas, PointerPaintingDetails pointerPaintingDetails, - SfGaugeThemeData gaugeThemeData) { - final Paint paint = Paint() - ..color = color ?? - gaugeThemeData.markerColor ?? - colorScheme.secondaryContainer[205]! - ..style = PaintingStyle.fill; + void drawPointer( + Canvas canvas, + PointerPaintingDetails pointerPaintingDetails, + SfGaugeThemeData gaugeThemeData, + ) { + final Paint paint = + Paint() + ..color = + color ?? + gaugeThemeData.markerColor ?? + colorScheme.secondaryContainer[205]! + ..style = PaintingStyle.fill; const Color shadowColor = Colors.black; Paint? overlayPaint; if ((isHovered != null && isHovered!) && overlayColor != colorScheme.transparent) { - overlayPaint = Paint() - ..color = overlayColor ?? - color?.withValues(alpha: 0.12) ?? - gaugeThemeData.markerColor?.withValues(alpha: 0.12) ?? - _themeData.colorScheme.secondaryContainer.withValues(alpha: 0.12) - ..style = PaintingStyle.fill; + overlayPaint = + Paint() + ..color = + overlayColor ?? + color?.withValues(alpha: 0.12) ?? + gaugeThemeData.markerColor?.withValues(alpha: 0.12) ?? + _themeData.colorScheme.secondaryContainer.withValues( + alpha: 0.12, + ) + ..style = PaintingStyle.fill; } Paint? borderPaint; if (borderWidth > 0) { - borderPaint = Paint() - ..color = borderColor ?? gaugeThemeData.markerBorderColor - ..strokeWidth = borderWidth - ..style = PaintingStyle.stroke; + borderPaint = + Paint() + ..color = borderColor ?? gaugeThemeData.markerBorderColor + ..strokeWidth = borderWidth + ..style = PaintingStyle.stroke; } canvas.save(); switch (markerType) { case MarkerType.circle: - _drawCircle(canvas, paint, pointerPaintingDetails.startOffset, - borderPaint, overlayPaint, shadowColor); + _drawCircle( + canvas, + paint, + pointerPaintingDetails.startOffset, + borderPaint, + overlayPaint, + shadowColor, + ); break; case MarkerType.rectangle: _drawRectangle( - canvas, - paint, - pointerPaintingDetails.startOffset, - pointerPaintingDetails.pointerAngle, - borderPaint, - overlayPaint, - shadowColor); + canvas, + paint, + pointerPaintingDetails.startOffset, + pointerPaintingDetails.pointerAngle, + borderPaint, + overlayPaint, + shadowColor, + ); break; case MarkerType.image: - _drawMarkerImage(canvas, paint, pointerPaintingDetails.startOffset, - pointerPaintingDetails.pointerAngle); + _drawMarkerImage( + canvas, + paint, + pointerPaintingDetails.startOffset, + pointerPaintingDetails.pointerAngle, + ); canvas.restore(); break; case MarkerType.triangle: case MarkerType.invertedTriangle: _drawTriangle( - canvas, - paint, - pointerPaintingDetails.startOffset, - pointerPaintingDetails.pointerAngle, - borderPaint, - overlayPaint, - shadowColor); + canvas, + paint, + pointerPaintingDetails.startOffset, + pointerPaintingDetails.pointerAngle, + borderPaint, + overlayPaint, + shadowColor, + ); break; case MarkerType.diamond: _drawDiamond( + canvas, + paint, + pointerPaintingDetails.startOffset, + pointerPaintingDetails.pointerAngle, + borderPaint, + overlayPaint, + shadowColor, + ); + break; + case MarkerType.text: + if (text != null) { + _drawText( canvas, paint, pointerPaintingDetails.startOffset, pointerPaintingDetails.pointerAngle, - borderPaint, - overlayPaint, - shadowColor); - break; - case MarkerType.text: - if (text != null) { - _drawText(canvas, paint, pointerPaintingDetails.startOffset, - pointerPaintingDetails.pointerAngle, gaugeThemeData); + gaugeThemeData, + ); canvas.restore(); } break; @@ -727,22 +770,29 @@ class RenderMarkerPointer extends RenderBox { if (markerType != MarkerType.text && markerType != MarkerType.image) { core.paint( - canvas: canvas, - rect: _markerRect, - paint: paint, - elevation: elevation, - elevationColor: shadowColor, - shapeType: _shapeMarkerType, - borderPaint: borderPaint); + canvas: canvas, + rect: _markerRect, + paint: paint, + elevation: elevation, + elevationColor: shadowColor, + shapeType: _shapeMarkerType, + borderPaint: borderPaint, + ); canvas.restore(); } } /// To render the MarkerShape.Text - void _drawText(Canvas canvas, Paint paint, Offset startPosition, - double pointerAngle, SfGaugeThemeData gaugeThemeData) { + void _drawText( + Canvas canvas, + Paint paint, + Offset startPosition, + double pointerAngle, + SfGaugeThemeData gaugeThemeData, + ) { final TextStyle markerTextStyle = _themeData.textTheme.bodySmall!.copyWith( - color: textStyle.color ?? + color: + textStyle.color ?? _gaugeThemeData.markerTextStyle?.color ?? _gaugeThemeData.axisLabelColor ?? colorScheme.onSurface[184], @@ -756,42 +806,54 @@ class RenderMarkerPointer extends RenderBox { ); final TextSpan span = TextSpan(text: text, style: markerTextStyle); final TextPainter textPainter = TextPainter( - text: span, - textDirection: TextDirection.ltr, - textAlign: TextAlign.center); + text: span, + textDirection: TextDirection.ltr, + textAlign: TextAlign.center, + ); textPainter.layout(); canvas.save(); canvas.translate(startPosition.dx, startPosition.dy); canvas.rotate(getDegreeToRadian(pointerAngle - 90)); canvas.scale(-1); textPainter.paint( - canvas, Offset(-_textSize!.width / 2, -_textSize!.height / 2)); + canvas, + Offset(-_textSize!.width / 2, -_textSize!.height / 2), + ); canvas.restore(); } /// Renders the MarkerShape.circle - void _drawCircle(Canvas canvas, Paint paint, Offset startPosition, - Paint? borderPaint, Paint? overlayPaint, Color shadowColor) { + void _drawCircle( + Canvas canvas, + Paint paint, + Offset startPosition, + Paint? borderPaint, + Paint? overlayPaint, + Color shadowColor, + ) { final double pointerOverlayRadius = overlayRadius ?? 15; _markerRect = Rect.fromLTRB( - startPosition.dx - markerWidth / 2, - startPosition.dy - markerHeight / 2, - startPosition.dx + markerWidth / 2, - startPosition.dy + markerHeight / 2); + startPosition.dx - markerWidth / 2, + startPosition.dy - markerHeight / 2, + startPosition.dx + markerWidth / 2, + startPosition.dy + markerHeight / 2, + ); Rect overlayRect; if (overlayRadius != null) { overlayRect = Rect.fromLTRB( - startPosition.dx - pointerOverlayRadius, - startPosition.dy - pointerOverlayRadius, - startPosition.dx + pointerOverlayRadius, - startPosition.dy + pointerOverlayRadius); + startPosition.dx - pointerOverlayRadius, + startPosition.dy - pointerOverlayRadius, + startPosition.dx + pointerOverlayRadius, + startPosition.dy + pointerOverlayRadius, + ); } else { overlayRect = Rect.fromLTRB( - _markerRect.left - pointerOverlayRadius, - _markerRect.top - pointerOverlayRadius, - _markerRect.right + pointerOverlayRadius, - _markerRect.bottom + pointerOverlayRadius); + _markerRect.left - pointerOverlayRadius, + _markerRect.top - pointerOverlayRadius, + _markerRect.right + pointerOverlayRadius, + _markerRect.bottom + pointerOverlayRadius, + ); } if (overlayPaint != null) { @@ -803,24 +865,30 @@ class RenderMarkerPointer extends RenderBox { /// Renders the MarkerShape.rectangle void _drawRectangle( - Canvas canvas, - Paint paint, - Offset startPosition, - double pointerAngle, - Paint? borderPaint, - Paint? overlayPaint, - Color shadowColor) { + Canvas canvas, + Paint paint, + Offset startPosition, + double pointerAngle, + Paint? borderPaint, + Paint? overlayPaint, + Color shadowColor, + ) { final double pointerOverlayRadius = overlayRadius ?? 15; Rect overlayRect; if (overlayRadius != null) { - overlayRect = Rect.fromLTRB(-pointerOverlayRadius, -pointerOverlayRadius, - pointerOverlayRadius, pointerOverlayRadius); + overlayRect = Rect.fromLTRB( + -pointerOverlayRadius, + -pointerOverlayRadius, + pointerOverlayRadius, + pointerOverlayRadius, + ); } else { overlayRect = Rect.fromLTRB( - _markerRect.left - pointerOverlayRadius, - _markerRect.top - pointerOverlayRadius, - _markerRect.right + pointerOverlayRadius, - _markerRect.bottom + pointerOverlayRadius); + _markerRect.left - pointerOverlayRadius, + _markerRect.top - pointerOverlayRadius, + _markerRect.right + pointerOverlayRadius, + _markerRect.bottom + pointerOverlayRadius, + ); } canvas.translate(startPosition.dx, startPosition.dy); @@ -834,11 +902,19 @@ class RenderMarkerPointer extends RenderBox { /// Renders the MarkerShape.image void _drawMarkerImage( - Canvas canvas, Paint paint, Offset startPosition, double pointerAngle) { + Canvas canvas, + Paint paint, + Offset startPosition, + double pointerAngle, + ) { canvas.translate(startPosition.dx, startPosition.dy); canvas.rotate(getDegreeToRadian(pointerAngle + 90)); final Rect rect = Rect.fromLTRB( - -markerWidth / 2, -markerHeight / 2, markerWidth / 2, markerHeight / 2); + -markerWidth / 2, + -markerHeight / 2, + markerWidth / 2, + markerHeight / 2, + ); if (_image != null) { canvas.drawImageNine(_image!, rect, rect, paint); } @@ -846,13 +922,14 @@ class RenderMarkerPointer extends RenderBox { /// Renders the MarkerShape.diamond void _drawDiamond( - Canvas canvas, - Paint paint, - Offset startPosition, - double pointerAngle, - Paint? borderPaint, - Paint? overlayPaint, - Color shadowColor) { + Canvas canvas, + Paint paint, + Offset startPosition, + double pointerAngle, + Paint? borderPaint, + Paint? overlayPaint, + Color shadowColor, + ) { canvas.translate(startPosition.dx, startPosition.dy); canvas.rotate(getDegreeToRadian(pointerAngle - 90)); @@ -882,17 +959,19 @@ class RenderMarkerPointer extends RenderBox { /// Renders the triangle and the inverted triangle void _drawTriangle( - Canvas canvas, - Paint paint, - Offset startPosition, - double pointerAngle, - Paint? borderPaint, - Paint? overlayPaint, - Color shadowColor) { + Canvas canvas, + Paint paint, + Offset startPosition, + double pointerAngle, + Paint? borderPaint, + Paint? overlayPaint, + Color shadowColor, + ) { canvas.translate(startPosition.dx, startPosition.dy); - final double triangleAngle = markerType == MarkerType.triangle - ? pointerAngle + 90 - : pointerAngle - 90; + final double triangleAngle = + markerType == MarkerType.triangle + ? pointerAngle + 90 + : pointerAngle - 90; canvas.rotate(getDegreeToRadian(triangleAngle)); if (overlayPaint != null) { @@ -904,13 +983,19 @@ class RenderMarkerPointer extends RenderBox { overlayPath.lineTo(0, -pointerOverlayRadius); overlayPath.lineTo(-pointerOverlayRadius, pointerOverlayRadius); } else { - overlayPath.moveTo(-((markerWidth + pointerOverlayRadius) / 2), - (markerHeight + pointerOverlayRadius) / 2); - overlayPath.lineTo((markerWidth + pointerOverlayRadius) / 2, - (markerHeight + pointerOverlayRadius) / 2); + overlayPath.moveTo( + -((markerWidth + pointerOverlayRadius) / 2), + (markerHeight + pointerOverlayRadius) / 2, + ); + overlayPath.lineTo( + (markerWidth + pointerOverlayRadius) / 2, + (markerHeight + pointerOverlayRadius) / 2, + ); overlayPath.lineTo(0, -((markerHeight + pointerOverlayRadius) / 2)); - overlayPath.lineTo(-((markerWidth + pointerOverlayRadius) / 2), - (markerHeight + pointerOverlayRadius) / 2); + overlayPath.lineTo( + -((markerWidth + pointerOverlayRadius) / 2), + (markerHeight + pointerOverlayRadius) / 2, + ); } overlayPath.close(); @@ -939,9 +1024,10 @@ class RenderMarkerPointer extends RenderBox { if (isRadialGaugeAnimationEnabled) { if (_pointerAnimation != null && _isInitialLoading) { - needsShowPointer = axisRenderer!.isInversed - ? _pointerAnimation!.value < 1 - : _pointerAnimation!.value > 0; + needsShowPointer = + axisRenderer!.isInversed + ? _pointerAnimation!.value < 1 + : _pointerAnimation!.value > 0; } else { needsShowPointer = true; } @@ -952,17 +1038,25 @@ class RenderMarkerPointer extends RenderBox { if (needsShowPointer) { final PointerPaintingDetails pointerPaintingDetails = PointerPaintingDetails( - startOffset: markerOffset, - endOffset: markerOffset, - pointerAngle: markerAngle, - axisRadius: _radius, - axisCenter: _axisCenter); - - _markerRect = Rect.fromLTRB(-markerWidth / 2, -markerHeight / 2, - markerWidth / 2, markerHeight / 2); + startOffset: markerOffset, + endOffset: markerOffset, + pointerAngle: markerAngle, + axisRadius: _radius, + axisCenter: _axisCenter, + ); + + _markerRect = Rect.fromLTRB( + -markerWidth / 2, + -markerHeight / 2, + markerWidth / 2, + markerHeight / 2, + ); if (markerPointerRenderer != null) { - markerPointerRenderer! - .drawPointer(canvas, pointerPaintingDetails, _gaugeThemeData); + markerPointerRenderer!.drawPointer( + canvas, + pointerPaintingDetails, + _gaugeThemeData, + ); } else { drawPointer(canvas, pointerPaintingDetails, _gaugeThemeData); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer.dart index 0111cfecb..d55fdf4b3 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer.dart @@ -33,35 +33,41 @@ class NeedlePointer extends LeafRenderObjectWidget implements GaugePointer { /// /// The arguments [value], must not be null and [animationDuration], /// [needleLength], [needleStartWidth], [needleEndWidth] must be non-negative. - const NeedlePointer( - {Key? key, - this.value = 0, - this.enableDragging = false, - this.onValueChanged, - this.onValueChangeStart, - this.onValueChangeEnd, - this.onValueChanging, - KnobStyle? knobStyle, - this.tailStyle, - this.gradient, - this.needleLength = 0.6, - this.lengthUnit = GaugeSizeUnit.factor, - this.needleStartWidth = 1, - this.needleEndWidth = 10, - this.onCreatePointerRenderer, - this.enableAnimation = false, - this.animationDuration = 1000, - this.animationType = AnimationType.ease, - this.needleColor}) - : knobStyle = knobStyle ?? const KnobStyle(), - assert(animationDuration > 0, - 'Animation duration must be a non-negative value'), - assert(needleLength >= 0, 'Needle length must be greater than zero.'), - assert(needleStartWidth >= 0, - 'Needle start width must be greater than zero.'), - assert( - needleEndWidth >= 0, 'Needle end width must be greater than zero.'), - super(key: key); + const NeedlePointer({ + Key? key, + this.value = 0, + this.enableDragging = false, + this.onValueChanged, + this.onValueChangeStart, + this.onValueChangeEnd, + this.onValueChanging, + KnobStyle? knobStyle, + this.tailStyle, + this.gradient, + this.needleLength = 0.6, + this.lengthUnit = GaugeSizeUnit.factor, + this.needleStartWidth = 1, + this.needleEndWidth = 10, + this.onCreatePointerRenderer, + this.enableAnimation = false, + this.animationDuration = 1000, + this.animationType = AnimationType.ease, + this.needleColor, + }) : knobStyle = knobStyle ?? const KnobStyle(), + assert( + animationDuration > 0, + 'Animation duration must be a non-negative value', + ), + assert(needleLength >= 0, 'Needle length must be greater than zero.'), + assert( + needleStartWidth >= 0, + 'Needle start width must be greater than zero.', + ), + assert( + needleEndWidth >= 0, + 'Needle end width must be greater than zero.', + ), + super(key: key); /// The style to use for the needle knob. /// @@ -270,7 +276,7 @@ class NeedlePointer extends LeafRenderObjectWidget implements GaugePointer { /// } ///``` final NeedlePointerRendererFactory? - onCreatePointerRenderer; + onCreatePointerRenderer; /// Specifies the duration of the pointer animation. /// @@ -508,8 +514,9 @@ class NeedlePointer extends LeafRenderObjectWidget implements GaugePointer { final ThemeData themeData = Theme.of(context); final SfColorScheme colorScheme = SfTheme.colorScheme(context); final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; NeedlePointerRenderer? needlePointerRenderer; if (onCreatePointerRenderer != null) { @@ -518,42 +525,46 @@ class NeedlePointer extends LeafRenderObjectWidget implements GaugePointer { } return RenderNeedlePointer( - value: value.clamp(ancestor.minimum, ancestor.maximum), - enableDragging: enableDragging, - onValueChanged: onValueChanged, - onValueChangeStart: onValueChangeStart, - onValueChangeEnd: onValueChangeEnd, - onValueChanging: onValueChanging, - knobStyle: knobStyle, - tailStyle: tailStyle, - gradient: gradient, - needleLength: needleLength, - lengthUnit: lengthUnit, - needleStartWidth: needleStartWidth, - needleEndWidth: needleEndWidth, - needlePointerRenderer: needlePointerRenderer, - needleColor: needleColor, - pointerAnimationController: radialAxisScope.animationController, - pointerInterval: radialAxisScope.pointerInterval, - isRadialGaugeAnimationEnabled: - radialAxisScope.isRadialGaugeAnimationEnabled, - enableAnimation: enableAnimation, - animationType: animationType, - repaintNotifier: radialAxisScope.repaintNotifier, - gaugeThemeData: gaugeTheme, - themeData: themeData, - colorScheme: colorScheme); + value: value.clamp(ancestor.minimum, ancestor.maximum), + enableDragging: enableDragging, + onValueChanged: onValueChanged, + onValueChangeStart: onValueChangeStart, + onValueChangeEnd: onValueChangeEnd, + onValueChanging: onValueChanging, + knobStyle: knobStyle, + tailStyle: tailStyle, + gradient: gradient, + needleLength: needleLength, + lengthUnit: lengthUnit, + needleStartWidth: needleStartWidth, + needleEndWidth: needleEndWidth, + needlePointerRenderer: needlePointerRenderer, + needleColor: needleColor, + pointerAnimationController: radialAxisScope.animationController, + pointerInterval: radialAxisScope.pointerInterval, + isRadialGaugeAnimationEnabled: + radialAxisScope.isRadialGaugeAnimationEnabled, + enableAnimation: enableAnimation, + animationType: animationType, + repaintNotifier: radialAxisScope.repaintNotifier, + gaugeThemeData: gaugeTheme, + themeData: themeData, + colorScheme: colorScheme, + ); } @override void updateRenderObject( - BuildContext context, RenderNeedlePointer renderObject) { + BuildContext context, + RenderNeedlePointer renderObject, + ) { final SfGaugeThemeData gaugeTheme = SfGaugeTheme.of(context)!; final SfColorScheme colorScheme = SfTheme.colorScheme(context); final ThemeData themeData = Theme.of(context); final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; NeedlePointerRenderer? needlePointerRenderer; if (onCreatePointerRenderer != null) { needlePointerRenderer = onCreatePointerRenderer!(); diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer_renderer.dart index 85889b978..eb4992f90 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/needle_pointer_renderer.dart @@ -16,46 +16,46 @@ import '../../radial_gauge/utils/radial_callback_args.dart'; /// Represents the renderer of radial gauge needle pointer. class RenderNeedlePointer extends RenderBox { /// Creates a object for [RenderNeedlePointer]. - RenderNeedlePointer( - {required double value, - required this.enableDragging, - this.onValueChanged, - this.onValueChangeStart, - this.onValueChangeEnd, - this.onValueChanging, - required KnobStyle knobStyle, - TailStyle? tailStyle, - Gradient? gradient, - required double needleLength, - required GaugeSizeUnit lengthUnit, - required double needleStartWidth, - required double needleEndWidth, - NeedlePointerRenderer? needlePointerRenderer, - Color? needleColor, - AnimationController? pointerAnimationController, - this.pointerInterval, - required this.animationType, - required this.enableAnimation, - required this.isRadialGaugeAnimationEnabled, - required ValueNotifier repaintNotifier, - required ThemeData themeData, - required SfColorScheme colorScheme, - required SfGaugeThemeData gaugeThemeData}) - : _value = value, - _knobStyle = knobStyle, - _tailStyle = tailStyle, - _gradient = gradient, - _needleLength = needleLength, - _lengthUnit = lengthUnit, - _needleStartWidth = needleStartWidth, - _needleEndWidth = needleEndWidth, - _needleColor = needleColor, - _repaintNotifier = repaintNotifier, - _pointerAnimationController = pointerAnimationController, - _needlePointerRenderer = needlePointerRenderer, - _themeData = themeData, - _colorScheme = colorScheme, - _gaugeThemeData = gaugeThemeData; + RenderNeedlePointer({ + required double value, + required this.enableDragging, + this.onValueChanged, + this.onValueChangeStart, + this.onValueChangeEnd, + this.onValueChanging, + required KnobStyle knobStyle, + TailStyle? tailStyle, + Gradient? gradient, + required double needleLength, + required GaugeSizeUnit lengthUnit, + required double needleStartWidth, + required double needleEndWidth, + NeedlePointerRenderer? needlePointerRenderer, + Color? needleColor, + AnimationController? pointerAnimationController, + this.pointerInterval, + required this.animationType, + required this.enableAnimation, + required this.isRadialGaugeAnimationEnabled, + required ValueNotifier repaintNotifier, + required ThemeData themeData, + required SfColorScheme colorScheme, + required SfGaugeThemeData gaugeThemeData, + }) : _value = value, + _knobStyle = knobStyle, + _tailStyle = tailStyle, + _gradient = gradient, + _needleLength = needleLength, + _lengthUnit = lengthUnit, + _needleStartWidth = needleStartWidth, + _needleEndWidth = needleEndWidth, + _needleColor = needleColor, + _repaintNotifier = repaintNotifier, + _pointerAnimationController = pointerAnimationController, + _needlePointerRenderer = needlePointerRenderer, + _themeData = themeData, + _colorScheme = colorScheme, + _gaugeThemeData = gaugeThemeData; double _actualTailLength = 0; late double _actualNeedleLength; @@ -474,15 +474,22 @@ class RenderNeedlePointer extends RenderBox { /// Calculates the default value void _calculateDefaultValue() { - _actualNeedleLength = - axisRenderer!.getActualValue(needleLength, lengthUnit, false); - _actualCapRadius = axisRenderer! - .getActualValue(knobStyle.knobRadius, knobStyle.sizeUnit, false); - final double currentFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer!.valueToFactor(value) != null) - ? axisRenderer!.renderer!.valueToFactor(value) ?? - axisRenderer!.valueToFactor(value) - : axisRenderer!.valueToFactor(value); + _actualNeedleLength = axisRenderer!.getActualValue( + needleLength, + lengthUnit, + false, + ); + _actualCapRadius = axisRenderer!.getActualValue( + knobStyle.knobRadius, + knobStyle.sizeUnit, + false, + ); + final double currentFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor(value) != null) + ? axisRenderer!.renderer!.valueToFactor(value) ?? + axisRenderer!.valueToFactor(value) + : axisRenderer!.valueToFactor(value); _angle = (currentFactor * _sweepAngle) + axisRenderer!.startAngle; _radian = getDegreeToRadian(_angle); _centerPoint = _axisCenter; @@ -552,8 +559,11 @@ class RenderNeedlePointer extends RenderBox { /// Calculates the values to render the needle tail void _calculateTailPosition(double needleRadian) { final double pointerWidth = tailStyle!.width; - _actualTailLength = axisRenderer! - .getActualValue(tailStyle!.length, tailStyle!.lengthUnit, false); + _actualTailLength = axisRenderer!.getActualValue( + tailStyle!.length, + tailStyle!.lengthUnit, + false, + ); if (_actualTailLength > 0) { final double tailEndX = _startX - _actualTailLength * math.cos(needleRadian); @@ -576,10 +586,14 @@ class RenderNeedlePointer extends RenderBox { /// By overriding this method, you can draw the customized needled pointer /// using required values. /// - void drawPointer(Canvas canvas, PointerPaintingDetails pointerPaintingDetails, - SfGaugeThemeData gaugeThemeData) { - final double pointerRadian = - getDegreeToRadian(pointerPaintingDetails.pointerAngle); + void drawPointer( + Canvas canvas, + PointerPaintingDetails pointerPaintingDetails, + SfGaugeThemeData gaugeThemeData, + ) { + final double pointerRadian = getDegreeToRadian( + pointerPaintingDetails.pointerAngle, + ); if (_actualNeedleLength > 0) { _renderNeedle(canvas, pointerRadian); } @@ -591,11 +605,13 @@ class RenderNeedlePointer extends RenderBox { /// To render the needle of the pointer void _renderNeedle(Canvas canvas, double pointerRadian) { - final Paint paint = Paint() - ..color = needleColor ?? - _gaugeThemeData.needleColor ?? - colorScheme.onSurface[255]! - ..style = PaintingStyle.fill; + final Paint paint = + Paint() + ..color = + needleColor ?? + _gaugeThemeData.needleColor ?? + colorScheme.onSurface[255]! + ..style = PaintingStyle.fill; final Path path = Path(); path.moveTo(_startLeftX, _startLeftY); @@ -628,23 +644,27 @@ class RenderNeedlePointer extends RenderBox { canvas.translate(_centerPoint.dx, _centerPoint.dy); canvas.rotate(pointerRadian); - final Paint tailPaint = Paint() - ..color = tailStyle!.color ?? - _gaugeThemeData.tailColor ?? - colorScheme.onSurface[255]!; + final Paint tailPaint = + Paint() + ..color = + tailStyle!.color ?? + _gaugeThemeData.tailColor ?? + colorScheme.onSurface[255]!; if (tailStyle!.gradient != null) { - tailPaint.shader = - tailStyle!.gradient!.createShader(tailPath.getBounds()); + tailPaint.shader = tailStyle!.gradient!.createShader( + tailPath.getBounds(), + ); } canvas.drawPath(tailPath, tailPaint); if (tailStyle!.borderWidth > 0) { - final Paint tailStrokePaint = Paint() - ..color = tailStyle!.borderColor ?? _gaugeThemeData.tailBorderColor - ..style = PaintingStyle.stroke - ..strokeWidth = tailStyle!.borderWidth; + final Paint tailStrokePaint = + Paint() + ..color = tailStyle!.borderColor ?? _gaugeThemeData.tailBorderColor + ..style = PaintingStyle.stroke + ..strokeWidth = tailStyle!.borderWidth; canvas.drawPath(tailPath, tailStrokePaint); } @@ -655,20 +675,26 @@ class RenderNeedlePointer extends RenderBox { /// To render the cap of needle void _renderCap(Canvas canvas, SfGaugeThemeData gaugeThemeData) { if (_actualCapRadius > 0) { - final Paint knobPaint = Paint() - ..color = knobStyle.color ?? - gaugeThemeData.knobColor ?? - colorScheme.onSurface[255]!; + final Paint knobPaint = + Paint() + ..color = + knobStyle.color ?? + gaugeThemeData.knobColor ?? + colorScheme.onSurface[255]!; canvas.drawCircle(_axisCenter, _actualCapRadius, knobPaint); if (knobStyle.borderWidth > 0) { - final double actualBorderWidth = axisRenderer! - .getActualValue(knobStyle.borderWidth, knobStyle.sizeUnit, false); - final Paint strokePaint = Paint() - ..color = knobStyle.borderColor ?? gaugeThemeData.knobBorderColor - ..style = PaintingStyle.stroke - ..strokeWidth = actualBorderWidth; + final double actualBorderWidth = axisRenderer!.getActualValue( + knobStyle.borderWidth, + knobStyle.sizeUnit, + false, + ); + final Paint strokePaint = + Paint() + ..color = knobStyle.borderColor ?? gaugeThemeData.knobBorderColor + ..style = PaintingStyle.stroke + ..strokeWidth = actualBorderWidth; canvas.drawCircle(_centerPoint, _actualCapRadius, strokePaint); } @@ -682,7 +708,8 @@ class RenderNeedlePointer extends RenderBox { bool needsShowPointer = false; if (_pointerAnimation != null && _isAnimating) { - angle = (_sweepAngle * _pointerAnimation!.value) + + angle = + (_sweepAngle * _pointerAnimation!.value) + axisRenderer!.startAngle + 90; } else { @@ -691,9 +718,10 @@ class RenderNeedlePointer extends RenderBox { if (isRadialGaugeAnimationEnabled) { if (_pointerAnimation != null && _isInitialLoading) { - needsShowPointer = axisRenderer!.isInversed - ? _pointerAnimation!.value < 1 - : _pointerAnimation!.value > 0; + needsShowPointer = + axisRenderer!.isInversed + ? _pointerAnimation!.value < 1 + : _pointerAnimation!.value > 0; } else { needsShowPointer = true; } @@ -707,14 +735,18 @@ class RenderNeedlePointer extends RenderBox { final PointerPaintingDetails pointerPaintingDetails = PointerPaintingDetails( - startOffset: startPosition, - endOffset: endPosition, - pointerAngle: angle, - axisRadius: _radius, - axisCenter: _axisCenter); + startOffset: startPosition, + endOffset: endPosition, + pointerAngle: angle, + axisRadius: _radius, + axisCenter: _axisCenter, + ); if (needlePointerRenderer != null) { needlePointerRenderer!.drawPointer( - context.canvas, pointerPaintingDetails, _gaugeThemeData); + context.canvas, + pointerPaintingDetails, + _gaugeThemeData, + ); } else { drawPointer(context.canvas, pointerPaintingDetails, _gaugeThemeData); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/pointer_painting_details.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/pointer_painting_details.dart index 9ae69f7aa..99d0b3e0a 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/pointer_painting_details.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/pointer_painting_details.dart @@ -5,12 +5,13 @@ import 'package:flutter/material.dart'; @immutable class PointerPaintingDetails { /// Creates the details which are required to paint the pointer - const PointerPaintingDetails( - {required this.startOffset, - required this.endOffset, - required this.pointerAngle, - required this.axisRadius, - required this.axisCenter}); + const PointerPaintingDetails({ + required this.startOffset, + required this.endOffset, + required this.pointerAngle, + required this.axisRadius, + required this.axisCenter, + }); /// Specifies the starting position of the pointer in the logical pixels. final Offset startOffset; diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer.dart index f57937a5d..ea54171c7 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer.dart @@ -28,32 +28,32 @@ class RangePointer extends LeafRenderObjectWidget implements GaugePointer { /// /// The arguments [value], [pointerOffset], must not be null and /// [animationDuration], [width], must be non-negative. - const RangePointer( - {Key? key, - this.value = 0, - this.enableDragging = false, - this.onValueChanged, - this.onValueChangeStart, - this.onValueChangeEnd, - this.onValueChanging, - this.animationType = AnimationType.ease, - this.enableAnimation = false, - this.animationDuration = 1000, - this.cornerStyle = CornerStyle.bothFlat, - this.gradient, - this.pointerOffset = 0, - this.sizeUnit = GaugeSizeUnit.logicalPixel, - this.width = 10, - this.dashArray, - this.color}) - : assert( - animationDuration > 0, 'Animation duration must be non-negative'), - assert(width >= 0, 'Width must be a non-negative value.'), - assert( - (gradient != null && gradient is SweepGradient) || gradient == null, - 'The gradient must be null or else the gradient must be equal to ' - 'sweep gradient.'), - super(key: key); + const RangePointer({ + Key? key, + this.value = 0, + this.enableDragging = false, + this.onValueChanged, + this.onValueChangeStart, + this.onValueChangeEnd, + this.onValueChanging, + this.animationType = AnimationType.ease, + this.enableAnimation = false, + this.animationDuration = 1000, + this.cornerStyle = CornerStyle.bothFlat, + this.gradient, + this.pointerOffset = 0, + this.sizeUnit = GaugeSizeUnit.logicalPixel, + this.width = 10, + this.dashArray, + this.color, + }) : assert(animationDuration > 0, 'Animation duration must be non-negative'), + assert(width >= 0, 'Width must be a non-negative value.'), + assert( + (gradient != null && gradient is SweepGradient) || gradient == null, + 'The gradient must be null or else the gradient must be equal to ' + 'sweep gradient.', + ), + super(key: key); /// Adjusts the range pointer position. /// @@ -451,8 +451,9 @@ class RangePointer extends LeafRenderObjectWidget implements GaugePointer { final SfGaugeThemeData gaugeTheme = SfGaugeTheme.of(context)!; final ThemeData themeData = Theme.of(context); final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; return RenderRangePointer( value: value.clamp(ancestor.minimum, ancestor.maximum), @@ -482,12 +483,15 @@ class RangePointer extends LeafRenderObjectWidget implements GaugePointer { @override void updateRenderObject( - BuildContext context, RenderRangePointer renderObject) { + BuildContext context, + RenderRangePointer renderObject, + ) { final SfGaugeThemeData gaugeTheme = SfGaugeTheme.of(context)!; final ThemeData themeData = Theme.of(context); final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; renderObject ..enableDragging = enableDragging diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer_renderer.dart index d5bf4a13b..71e56cec4 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/range_pointer_renderer.dart @@ -12,40 +12,40 @@ import '../utils/radial_callback_args.dart'; /// Represents the renderer of radial gauge range pointer. class RenderRangePointer extends RenderBox { /// Creates a object for [RenderRangePointer]. - RenderRangePointer( - {required double value, - required this.enableDragging, - this.onValueChanged, - this.onValueChangeStart, - this.onValueChangeEnd, - this.onValueChanging, - required CornerStyle cornerStyle, - Gradient? gradient, - required double pointerOffset, - required GaugeSizeUnit sizeUnit, - required double width, - List? dashArray, - Color? color, - AnimationController? pointerAnimationController, - this.pointerInterval, - required this.animationType, - required this.enableAnimation, - required this.isRadialGaugeAnimationEnabled, - required ValueNotifier repaintNotifier, - required ThemeData themeData, - required SfGaugeThemeData gaugeThemeData}) - : _value = value, - _cornerStyle = cornerStyle, - _gradient = gradient, - _pointerOffset = pointerOffset, - _sizeUnit = sizeUnit, - _width = width, - _dashArray = dashArray, - _color = color, - _pointerAnimationController = pointerAnimationController, - _repaintNotifier = repaintNotifier, - _themeData = themeData, - _gaugeThemeData = gaugeThemeData; + RenderRangePointer({ + required double value, + required this.enableDragging, + this.onValueChanged, + this.onValueChangeStart, + this.onValueChangeEnd, + this.onValueChanging, + required CornerStyle cornerStyle, + Gradient? gradient, + required double pointerOffset, + required GaugeSizeUnit sizeUnit, + required double width, + List? dashArray, + Color? color, + AnimationController? pointerAnimationController, + this.pointerInterval, + required this.animationType, + required this.enableAnimation, + required this.isRadialGaugeAnimationEnabled, + required ValueNotifier repaintNotifier, + required ThemeData themeData, + required SfGaugeThemeData gaugeThemeData, + }) : _value = value, + _cornerStyle = cornerStyle, + _gradient = gradient, + _pointerOffset = pointerOffset, + _sizeUnit = sizeUnit, + _width = width, + _dashArray = dashArray, + _color = color, + _pointerAnimationController = pointerAnimationController, + _repaintNotifier = repaintNotifier, + _themeData = themeData, + _gaugeThemeData = gaugeThemeData; late double _rangeArcTop; late double _rangeArcBottom; @@ -404,10 +404,11 @@ class RenderRangePointer extends RenderBox { bool hitTestSelf(Offset position) { if (enableDragging) { final Rect pathRect = Rect.fromLTRB( - arcPath.getBounds().left + _axisCenter.dx - 5, - arcPath.getBounds().top + _axisCenter.dy - 5, - arcPath.getBounds().right + _axisCenter.dx + 5, - arcPath.getBounds().bottom + _axisCenter.dy + 5); + arcPath.getBounds().left + _axisCenter.dx - 5, + arcPath.getBounds().top + _axisCenter.dy - 5, + arcPath.getBounds().right + _axisCenter.dx + 5, + arcPath.getBounds().bottom + _axisCenter.dy + 5, + ); return pathRect.contains(position); } else { return false; @@ -417,25 +418,34 @@ class RenderRangePointer extends RenderBox { /// Method to calculate pointer position. void _calculatePosition() { _updateAxisValues(); - _actualRangeThickness = - axisRenderer!.getActualValue(width, sizeUnit, false); - _actualPointerOffset = - axisRenderer!.getActualValue(pointerOffset, sizeUnit, true); - _totalOffset = _actualPointerOffset < 0 - ? axisRenderer!.getAxisOffset() + _actualPointerOffset - : (_actualPointerOffset + axisRenderer!.getAxisOffset()); - final double minFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer!.valueToFactor(axisRenderer!.minimum) != - null) - ? axisRenderer!.renderer!.valueToFactor(axisRenderer!.minimum) ?? - axisRenderer!.valueToFactor(axisRenderer!.minimum) - : axisRenderer!.valueToFactor(axisRenderer!.minimum); + _actualRangeThickness = axisRenderer!.getActualValue( + width, + sizeUnit, + false, + ); + _actualPointerOffset = axisRenderer!.getActualValue( + pointerOffset, + sizeUnit, + true, + ); + _totalOffset = + _actualPointerOffset < 0 + ? axisRenderer!.getAxisOffset() + _actualPointerOffset + : (_actualPointerOffset + axisRenderer!.getAxisOffset()); + final double minFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor(axisRenderer!.minimum) != + null) + ? axisRenderer!.renderer!.valueToFactor(axisRenderer!.minimum) ?? + axisRenderer!.valueToFactor(axisRenderer!.minimum) + : axisRenderer!.valueToFactor(axisRenderer!.minimum); _startArc = (minFactor * _sweepAngle) + axisRenderer!.startAngle; - final double maxFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer!.valueToFactor(value) != null) - ? axisRenderer!.renderer!.valueToFactor(value) ?? - axisRenderer!.valueToFactor(value) - : axisRenderer!.valueToFactor(value); + final double maxFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor(value) != null) + ? axisRenderer!.renderer!.valueToFactor(value) ?? + axisRenderer!.valueToFactor(value) + : axisRenderer!.valueToFactor(value); final double rangeEndAngle = (maxFactor * _sweepAngle) + axisRenderer!.startAngle; _endArc = rangeEndAngle - _startArc; @@ -451,12 +461,24 @@ class RenderRangePointer extends RenderBox { /// To creates the arc rect for range pointer void _createRangeRect() { _arcRect = Rect.fromLTRB( - _rangeArcLeft, _rangeArcTop, _rangeArcRight, _rangeArcBottom); + _rangeArcLeft, + _rangeArcTop, + _rangeArcRight, + _rangeArcBottom, + ); pointerRect = Rect.fromLTRB( - _rangeArcLeft, _rangeArcTop, _rangeArcRight, _rangeArcBottom); + _rangeArcLeft, + _rangeArcTop, + _rangeArcRight, + _rangeArcBottom, + ); arcPath = Path(); - arcPath.arcTo(_arcRect, getDegreeToRadian(_startArc), - getDegreeToRadian(_endArc), true); + arcPath.arcTo( + _arcRect, + getDegreeToRadian(_startArc), + getDegreeToRadian(_endArc), + true, + ); _calculateCornerStylePosition(); } @@ -468,30 +490,35 @@ class RenderRangePointer extends RenderBox { switch (cornerStyle) { case CornerStyle.startCurve: { - _startCornerRadian = axisRenderer!.isInversed - ? getDegreeToRadian(-_cornerAngle) - : getDegreeToRadian(_cornerAngle); - _sweepCornerRadian = axisRenderer!.isInversed - ? getDegreeToRadian(_endArc + _cornerAngle) - : getDegreeToRadian(_endArc - _cornerAngle); + _startCornerRadian = + axisRenderer!.isInversed + ? getDegreeToRadian(-_cornerAngle) + : getDegreeToRadian(_cornerAngle); + _sweepCornerRadian = + axisRenderer!.isInversed + ? getDegreeToRadian(_endArc + _cornerAngle) + : getDegreeToRadian(_endArc - _cornerAngle); } break; case CornerStyle.endCurve: { _startCornerRadian = getDegreeToRadian(0); - _sweepCornerRadian = axisRenderer!.isInversed - ? getDegreeToRadian(_endArc + _cornerAngle) - : getDegreeToRadian(_endArc - _cornerAngle); + _sweepCornerRadian = + axisRenderer!.isInversed + ? getDegreeToRadian(_endArc + _cornerAngle) + : getDegreeToRadian(_endArc - _cornerAngle); } break; case CornerStyle.bothCurve: { - _startCornerRadian = axisRenderer!.isInversed - ? getDegreeToRadian(-_cornerAngle) - : getDegreeToRadian(_cornerAngle); - _sweepCornerRadian = axisRenderer!.isInversed - ? getDegreeToRadian(_endArc + 2 * _cornerAngle) - : getDegreeToRadian(_endArc - 2 * _cornerAngle); + _startCornerRadian = + axisRenderer!.isInversed + ? getDegreeToRadian(-_cornerAngle) + : getDegreeToRadian(_cornerAngle); + _sweepCornerRadian = + axisRenderer!.isInversed + ? getDegreeToRadian(_endArc + 2 * _cornerAngle) + : getDegreeToRadian(_endArc - 2 * _cornerAngle); } break; case CornerStyle.bothFlat: @@ -512,42 +539,58 @@ class RenderRangePointer extends RenderBox { /// Draws the start corner style. void _drawStartCurve(Path path, double innerRadius, double outerRadius) { final Offset midPoint = getDegreeToPoint( - axisRenderer!.isInversed ? -_cornerAngle : _cornerAngle, - (innerRadius + outerRadius) / 2, - Offset.zero); + axisRenderer!.isInversed ? -_cornerAngle : _cornerAngle, + (innerRadius + outerRadius) / 2, + Offset.zero, + ); final double midStartAngle = getDegreeToRadian(180); double midEndAngle = midStartAngle + getDegreeToRadian(180); midEndAngle = axisRenderer!.isInversed ? -midEndAngle : midEndAngle; path.addArc( - Rect.fromCircle( - center: midPoint, radius: (innerRadius - outerRadius).abs() / 2), - midStartAngle, - midEndAngle); + Rect.fromCircle( + center: midPoint, + radius: (innerRadius - outerRadius).abs() / 2, + ), + midStartAngle, + midEndAngle, + ); } ///Draws the end corner curve. void _drawEndCurve( - Path path, double sweepRadian, double innerRadius, double outerRadius) { + Path path, + double sweepRadian, + double innerRadius, + double outerRadius, + ) { final double cornerAngle = cornerStyle == CornerStyle.bothCurve ? _cornerAngle : 0; - final double angle = axisRenderer!.isInversed - ? getRadianToDegree(sweepRadian) - cornerAngle - : getRadianToDegree(sweepRadian) + cornerAngle; - final Offset midPoint = - getDegreeToPoint(angle, (innerRadius + outerRadius) / 2, Offset.zero); + final double angle = + axisRenderer!.isInversed + ? getRadianToDegree(sweepRadian) - cornerAngle + : getRadianToDegree(sweepRadian) + cornerAngle; + final Offset midPoint = getDegreeToPoint( + angle, + (innerRadius + outerRadius) / 2, + Offset.zero, + ); final double midStartAngle = sweepRadian / 2; - final double midEndAngle = axisRenderer!.isInversed - ? midStartAngle - getDegreeToRadian(180) - : midStartAngle + getDegreeToRadian(180); + final double midEndAngle = + axisRenderer!.isInversed + ? midStartAngle - getDegreeToRadian(180) + : midStartAngle + getDegreeToRadian(180); path.arcTo( - Rect.fromCircle( - center: midPoint, radius: (innerRadius - outerRadius).abs() / 2), - midStartAngle, - midEndAngle, - false); + Rect.fromCircle( + center: midPoint, + radius: (innerRadius - outerRadius).abs() / 2, + ), + midStartAngle, + midEndAngle, + false, + ); } /// Checks whether the axis line is dashed line. @@ -574,15 +617,17 @@ class RenderRangePointer extends RenderBox { /// Returns the paint for the pointer. Paint _getPointerPaint(Rect rect, bool isFill) { - final Paint paint = Paint() - ..color = color ?? - gaugeThemeData.rangePointerColor ?? - (_themeData.useMaterial3 - ? _themeData.colorScheme.primary - : _themeData.colorScheme.secondaryContainer) - .withValues(alpha: 0.8) - ..strokeWidth = _actualRangeThickness - ..style = isFill ? PaintingStyle.fill : PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = + color ?? + gaugeThemeData.rangePointerColor ?? + (_themeData.useMaterial3 + ? _themeData.colorScheme.primary + : _themeData.colorScheme.secondaryContainer) + .withValues(alpha: 0.8) + ..strokeWidth = _actualRangeThickness + ..style = isFill ? PaintingStyle.fill : PaintingStyle.stroke; if (gradient != null && gradient!.colors.isNotEmpty) { // Holds the color for gradient. @@ -595,9 +640,13 @@ class RenderRangePointer extends RenderBox { } // gradient for the range pointer. final SweepGradient sweepGradient = SweepGradient( - colors: gradientColors, - stops: calculateGradientStops( - offsets, axisRenderer!.isInversed, sweepAngle)); + colors: gradientColors, + stops: calculateGradientStops( + offsets, + axisRenderer!.isInversed, + sweepAngle, + ), + ); paint.shader = sweepGradient.createShader(rect); } @@ -612,8 +661,10 @@ class RenderRangePointer extends RenderBox { // Calculates the gradient stop values based on the number of // provided color. final double difference = 1 / gradient!.colors.length; - final List offsets = - List.filled(gradient!.colors.length, null); + final List offsets = List.filled( + gradient!.colors.length, + null, + ); for (int i = 0; i < gradient!.colors.length; i++) { offsets[i] = i * difference; } @@ -638,13 +689,14 @@ class RenderRangePointer extends RenderBox { final double outerRadius = _radius - _totalOffset; final double innerRadius = outerRadius - _actualRangeThickness; final double cornerRadius = (innerRadius - outerRadius).abs() / 2; - final double refCurveRadius = (2 * - math.pi * - (innerRadius + outerRadius) / - 2 * - getRadianToDegree(_sweepCornerRadian) / - 360) - .abs(); + final double refCurveRadius = + (2 * + math.pi * + (innerRadius + outerRadius) / + 2 * + getRadianToDegree(_sweepCornerRadian) / + 360) + .abs(); final Path path = Path(); final bool isDashedPointerLine = _getIsDashedLine(); @@ -654,11 +706,12 @@ class RenderRangePointer extends RenderBox { canvas.save(); canvas.translate(_axisCenter.dx, _axisCenter.dy); canvas.rotate(getDegreeToRadian(_startArc)); - final double curveRadius = cornerStyle != CornerStyle.bothFlat - ? cornerStyle == CornerStyle.startCurve - ? cornerRadius - : cornerRadius * 2 - : 0; + final double curveRadius = + cornerStyle != CornerStyle.bothFlat + ? cornerStyle == CornerStyle.startCurve + ? cornerRadius + : cornerRadius * 2 + : 0; if (cornerStyle != CornerStyle.bothFlat && !isDashedPointerLine && (refCurveRadius.floorToDouble() > curveRadius)) { @@ -671,8 +724,11 @@ class RenderRangePointer extends RenderBox { } if (needsToAnimatePointer) { - path.addArc(Rect.fromCircle(center: Offset.zero, radius: outerRadius), - _startCornerRadian, sweepRadian); + path.addArc( + Rect.fromCircle(center: Offset.zero, radius: outerRadius), + _startCornerRadian, + sweepRadian, + ); } if (cornerStyle == CornerStyle.endCurve || @@ -683,14 +739,19 @@ class RenderRangePointer extends RenderBox { } if (needsToAnimatePointer) { - path.arcTo(Rect.fromCircle(center: Offset.zero, radius: innerRadius), - sweepRadian + _startCornerRadian, -sweepRadian, false); + path.arcTo( + Rect.fromCircle(center: Offset.zero, radius: innerRadius), + sweepRadian + _startCornerRadian, + -sweepRadian, + false, + ); } } else { isFill = false; - sweepRadian = cornerStyle == CornerStyle.bothFlat - ? sweepRadian - : getDegreeToRadian(_endArc); + sweepRadian = + cornerStyle == CornerStyle.bothFlat + ? sweepRadian + : getDegreeToRadian(_endArc); path.addArc(_arcRect, 0, sweepRadian); } @@ -701,9 +762,9 @@ class RenderRangePointer extends RenderBox { } else { if (dashArray != null) { canvas.drawPath( - dashPath(path, - dashArray: CircularIntervalList(dashArray!)), - paint); + dashPath(path, dashArray: CircularIntervalList(dashArray!)), + paint, + ); } } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer.dart index e9713ce07..61a2b2d1d 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer.dart @@ -34,23 +34,25 @@ class WidgetPointer extends SingleChildRenderObjectWidget /// The arguments [child], [value], [offset], must not be null and /// [animationDuration] must be non-negative. /// - const WidgetPointer( - {Key? key, - this.value = 0, - this.enableDragging = false, - this.onValueChanged, - this.onValueChangeStart, - this.onValueChangeEnd, - this.onValueChanging, - this.animationType = AnimationType.ease, - this.enableAnimation = false, - this.animationDuration = 1000, - this.offsetUnit = GaugeSizeUnit.logicalPixel, - this.offset = 0, - required this.child}) - : assert(animationDuration > 0, - 'Animation duration must be a non-negative value.'), - super(key: key, child: child); + const WidgetPointer({ + Key? key, + this.value = 0, + this.enableDragging = false, + this.onValueChanged, + this.onValueChangeStart, + this.onValueChangeEnd, + this.onValueChanging, + this.animationType = AnimationType.ease, + this.enableAnimation = false, + this.animationDuration = 1000, + this.offsetUnit = GaugeSizeUnit.logicalPixel, + this.offset = 0, + required this.child, + }) : assert( + animationDuration > 0, + 'Animation duration must be a non-negative value.', + ), + super(key: key, child: child); /// A widget, which is to be used as the pointer. /// @@ -375,32 +377,37 @@ class WidgetPointer extends SingleChildRenderObjectWidget @override RenderObject createRenderObject(BuildContext context) { final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; return RenderWidgetPointer( - value: value.clamp(ancestor.minimum, ancestor.maximum), - enableDragging: enableDragging, - onValueChanged: onValueChanged, - onValueChangeStart: onValueChangeStart, - onValueChangeEnd: onValueChangeEnd, - onValueChanging: onValueChanging, - offsetUnit: offsetUnit, - pointerAnimationController: radialAxisScope.animationController, - pointerInterval: radialAxisScope.pointerInterval, - enableAnimation: enableAnimation, - repaintNotifier: radialAxisScope.repaintNotifier, - isRadialGaugeAnimationEnabled: - radialAxisScope.isRadialGaugeAnimationEnabled, - animationType: animationType, - offset: offset); + value: value.clamp(ancestor.minimum, ancestor.maximum), + enableDragging: enableDragging, + onValueChanged: onValueChanged, + onValueChangeStart: onValueChangeStart, + onValueChangeEnd: onValueChangeEnd, + onValueChanging: onValueChanging, + offsetUnit: offsetUnit, + pointerAnimationController: radialAxisScope.animationController, + pointerInterval: radialAxisScope.pointerInterval, + enableAnimation: enableAnimation, + repaintNotifier: radialAxisScope.repaintNotifier, + isRadialGaugeAnimationEnabled: + radialAxisScope.isRadialGaugeAnimationEnabled, + animationType: animationType, + offset: offset, + ); } @override void updateRenderObject( - BuildContext context, RenderWidgetPointer renderObject) { + BuildContext context, + RenderWidgetPointer renderObject, + ) { final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; renderObject ..enableDragging = enableDragging diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer_renderer.dart index bac4930ea..b7ccf165c 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/pointers/widget_pointer_renderer.dart @@ -11,28 +11,28 @@ import '../../radial_gauge/utils/radial_callback_args.dart'; /// Represents the renderer of radial gauge widget pointer. class RenderWidgetPointer extends RenderShiftedBox { /// Creates a object for [RenderWidgetPointer]. - RenderWidgetPointer( - {required double value, - required this.enableDragging, - this.onValueChanged, - this.onValueChangeStart, - this.onValueChangeEnd, - this.onValueChanging, - required GaugeSizeUnit offsetUnit, - required double offset, - AnimationController? pointerAnimationController, - this.pointerInterval, - required this.animationType, - required this.enableAnimation, - required this.isRadialGaugeAnimationEnabled, - required ValueNotifier repaintNotifier, - RenderBox? child}) - : _value = value, - _offsetUnit = offsetUnit, - _offset = offset, - _pointerAnimationController = pointerAnimationController, - _repaintNotifier = repaintNotifier, - super(child); + RenderWidgetPointer({ + required double value, + required this.enableDragging, + this.onValueChanged, + this.onValueChangeStart, + this.onValueChangeEnd, + this.onValueChanging, + required GaugeSizeUnit offsetUnit, + required double offset, + AnimationController? pointerAnimationController, + this.pointerInterval, + required this.animationType, + required this.enableAnimation, + required this.isRadialGaugeAnimationEnabled, + required ValueNotifier repaintNotifier, + RenderBox? child, + }) : _value = value, + _offsetUnit = offsetUnit, + _offset = offset, + _pointerAnimationController = pointerAnimationController, + _repaintNotifier = repaintNotifier, + super(child); late double _radian; late double _totalOffset; @@ -233,32 +233,45 @@ class RenderWidgetPointer extends RenderShiftedBox { /// Method returns the angle of current pointer value. double getPointerAngle() { - return (axisRenderer!.valueToFactor(value) * _sweepAngle) + - axisRenderer!.startAngle; + final double currentFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer?.valueToFactor(value) != null) + ? axisRenderer!.renderer?.valueToFactor(value) ?? + axisRenderer!.valueToFactor(value) + : axisRenderer!.valueToFactor(value); + return (currentFactor * _sweepAngle) + axisRenderer!.startAngle; } /// Calculates the marker offset position. Offset _getPointerOffset(double pointerRadian) { - _actualWidgetOffset = - axisRenderer!.getActualValue(offset, offsetUnit, true); - _totalOffset = _actualWidgetOffset < 0 - ? axisRenderer!.getAxisOffset() + _actualWidgetOffset - : (_actualWidgetOffset + axisRenderer!.getAxisOffset()); + _actualWidgetOffset = axisRenderer!.getActualValue( + offset, + offsetUnit, + true, + ); + _totalOffset = + _actualWidgetOffset < 0 + ? axisRenderer!.getAxisOffset() + _actualWidgetOffset + : (_actualWidgetOffset + axisRenderer!.getAxisOffset()); if (!axisRenderer!.canScaleToFit) { - final double x = (size.width / 2) + + final double x = + (size.width / 2) + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.cos(pointerRadian) - _centerXPoint; - final double y = (size.height / 2) + + final double y = + (size.height / 2) + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.sin(pointerRadian) - _centerYPoint; _pointerOffset = Offset(x, y); } else { - final double x = _axisCenter.dx + + final double x = + _axisCenter.dx + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.cos(pointerRadian); - final double y = _axisCenter.dy + + final double y = + _axisCenter.dy + (_radius - _totalOffset - (_actualAxisWidth / 2)) * math.sin(pointerRadian); _pointerOffset = Offset(x, y); @@ -274,7 +287,10 @@ class RenderWidgetPointer extends RenderShiftedBox { _axisCenter = axisRenderer!.getAxisCenter(); _radius = _axisRenderer!.getRadius(); _actualAxisWidth = _axisRenderer!.getActualValue( - _axisRenderer!.thickness, _axisRenderer!.thicknessUnit, false); + _axisRenderer!.thickness, + _axisRenderer!.thicknessUnit, + false, + ); } void _animationStatusListener(AnimationStatus status) { @@ -343,9 +359,10 @@ class RenderWidgetPointer extends RenderShiftedBox { if (isRadialGaugeAnimationEnabled) { if (_pointerAnimation != null && _isInitialLoading) { - _needsShowPointer = axisRenderer!.isInversed - ? _pointerAnimation!.value < 1 - : _pointerAnimation!.value > 0; + _needsShowPointer = + axisRenderer!.isInversed + ? _pointerAnimation!.value < 1 + : _pointerAnimation!.value > 0; } else { _needsShowPointer = true; } @@ -364,8 +381,12 @@ class RenderWidgetPointer extends RenderShiftedBox { size = Size.zero; } - _childRect = Rect.fromLTWH(_pointerOffset.dx, _pointerOffset.dy, - child!.size.width, child!.size.height); + _childRect = Rect.fromLTWH( + _pointerOffset.dx, + _pointerOffset.dy, + child!.size.width, + child!.size.height, + ); } } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range.dart index acd27faa7..ae0cf4a0c 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range.dart @@ -28,27 +28,28 @@ class GaugeRange extends LeafRenderObjectWidget { /// Create a range with the default or required properties. /// /// The arguments [startValue], [endValue], must not be null. - GaugeRange( - {Key? key, - required this.startValue, - required this.endValue, - double? startWidth, - double? endWidth, - this.sizeUnit = GaugeSizeUnit.logicalPixel, - this.color, - this.gradient, - this.rangeOffset = 0, - this.label, - GaugeTextStyle? labelStyle}) - : startWidth = - startWidth = startWidth ?? (label != null ? startWidth : 10), - endWidth = endWidth = endWidth ?? (label != null ? endWidth : 10), - labelStyle = labelStyle ?? const GaugeTextStyle(), - assert( - (gradient != null && gradient is SweepGradient) || gradient == null, - 'The gradient must be null or else the gradient must be equal' - ' to sweep gradient.'), - super(key: key); + GaugeRange({ + Key? key, + required this.startValue, + required this.endValue, + double? startWidth, + double? endWidth, + this.sizeUnit = GaugeSizeUnit.logicalPixel, + this.color, + this.gradient, + this.rangeOffset = 0, + this.label, + GaugeTextStyle? labelStyle, + }) : startWidth = + startWidth = startWidth ?? (label != null ? startWidth : 10), + endWidth = endWidth = endWidth ?? (label != null ? endWidth : 10), + labelStyle = labelStyle ?? const GaugeTextStyle(), + assert( + (gradient != null && gradient is SweepGradient) || gradient == null, + 'The gradient must be null or else the gradient must be equal' + ' to sweep gradient.', + ), + super(key: key); /// Specifies the range start value. /// @@ -287,31 +288,34 @@ class GaugeRange extends LeafRenderObjectWidget { RenderObject createRenderObject(BuildContext context) { final SfGaugeThemeData gaugeTheme = SfGaugeTheme.of(context)!; final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; return RenderGaugeRange( - startValue: startValue.clamp(ancestor.minimum, ancestor.maximum), - endValue: endValue.clamp(ancestor.minimum, ancestor.maximum), - startWidth: startWidth, - endWidth: endWidth, - sizeUnit: sizeUnit, - color: color, - gradient: gradient, - rangeOffset: rangeOffset, - label: label, - rangeAnimation: radialAxisScope.animation, - labelStyle: labelStyle, - repaintNotifier: radialAxisScope.repaintNotifier, - gaugeThemeData: gaugeTheme); + startValue: startValue.clamp(ancestor.minimum, ancestor.maximum), + endValue: endValue.clamp(ancestor.minimum, ancestor.maximum), + startWidth: startWidth, + endWidth: endWidth, + sizeUnit: sizeUnit, + color: color, + gradient: gradient, + rangeOffset: rangeOffset, + label: label, + rangeAnimation: radialAxisScope.animation, + labelStyle: labelStyle, + repaintNotifier: radialAxisScope.repaintNotifier, + gaugeThemeData: gaugeTheme, + ); } @override void updateRenderObject(BuildContext context, RenderGaugeRange renderObject) { final SfGaugeThemeData gaugeTheme = SfGaugeTheme.of(context)!; final RadialAxisScope radialAxisScope = RadialAxisScope.of(context); - final RadialAxisInheritedWidget ancestor = context - .dependOnInheritedWidgetOfExactType()!; + final RadialAxisInheritedWidget ancestor = + context + .dependOnInheritedWidgetOfExactType()!; renderObject ..startValue = startValue.clamp(ancestor.minimum, ancestor.maximum) diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range_renderer.dart index 7a7b53d55..898f24314 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/range/gauge_range_renderer.dart @@ -12,33 +12,33 @@ import '../../radial_gauge/utils/helper.dart'; /// Represents the renderer of radial gauge range. class RenderGaugeRange extends RenderBox { ///Creates a object for [RenderGaugeRange]. - RenderGaugeRange( - {required double startValue, - required double endValue, - double? startWidth, - double? endWidth, - required GaugeSizeUnit sizeUnit, - Color? color, - Gradient? gradient, - required double rangeOffset, - String? label, - required GaugeTextStyle labelStyle, - Animation? rangeAnimation, - required ValueNotifier repaintNotifier, - required SfGaugeThemeData gaugeThemeData}) - : _startValue = startValue, - _endValue = endValue, - _startWidth = startWidth, - _endWidth = endWidth, - _sizeUnit = sizeUnit, - _color = color, - _gradient = gradient, - _rangeOffset = rangeOffset, - _label = label, - _labelStyle = labelStyle, - _repaintNotifier = repaintNotifier, - _rangeAnimation = rangeAnimation, - _gaugeThemeData = gaugeThemeData; + RenderGaugeRange({ + required double startValue, + required double endValue, + double? startWidth, + double? endWidth, + required GaugeSizeUnit sizeUnit, + Color? color, + Gradient? gradient, + required double rangeOffset, + String? label, + required GaugeTextStyle labelStyle, + Animation? rangeAnimation, + required ValueNotifier repaintNotifier, + required SfGaugeThemeData gaugeThemeData, + }) : _startValue = startValue, + _endValue = endValue, + _startWidth = startWidth, + _endWidth = endWidth, + _sizeUnit = sizeUnit, + _color = color, + _gradient = gradient, + _rangeOffset = rangeOffset, + _label = label, + _labelStyle = labelStyle, + _repaintNotifier = repaintNotifier, + _rangeAnimation = rangeAnimation, + _gaugeThemeData = gaugeThemeData; late double _rangeMidRadian; late double _maxAngle; @@ -323,14 +323,19 @@ class RenderGaugeRange extends RenderBox { void _calculateRangePosition() { _updateAxisValues(); _calculateActualWidth(); - _actualRangeOffset = - axisRenderer!.getActualValue(rangeOffset, sizeUnit, true); - _center = !axisRenderer!.canScaleToFit - ? Offset(size.width / 2, size.height / 2) - : _axisCenter; - _totalOffset = _actualRangeOffset < 0 - ? axisRenderer!.getAxisOffset() + _actualRangeOffset - : (_actualRangeOffset + axisRenderer!.getAxisOffset()); + _actualRangeOffset = axisRenderer!.getActualValue( + rangeOffset, + sizeUnit, + true, + ); + _center = + !axisRenderer!.canScaleToFit + ? Offset(size.width / 2, size.height / 2) + : _axisCenter; + _totalOffset = + _actualRangeOffset < 0 + ? axisRenderer!.getAxisOffset() + _actualRangeOffset + : (_actualRangeOffset + axisRenderer!.getAxisOffset()); _maxAngle = _sweepAngle; _calculateRangeAngle(); if (_actualStartWidth != _actualEndWidth) { @@ -356,54 +361,66 @@ class RenderGaugeRange extends RenderBox { _outerArc = _getRadiusToAngleConversion(_outerStartOffset, _outerEndOffset); _innerArc = _getRadiusToAngleConversion(_innerStartOffset, _innerEndOffset); - _outerArcSweepAngle = - _getSweepAngle(_outerArc.endAngle - _outerArc.startAngle); - _innerArcSweepAngle = - _getSweepAngle(_innerArc.endAngle - _innerArc.startAngle); + _outerArcSweepAngle = _getSweepAngle( + _outerArc.endAngle - _outerArc.startAngle, + ); + _innerArcSweepAngle = _getSweepAngle( + _innerArc.endAngle - _innerArc.startAngle, + ); _innerArcSweepAngle *= -1; - final double left = _outerArc.arcRect.left < _innerArc.arcRect.left - ? _outerArc.arcRect.left - : _innerArc.arcRect.left; - final double top = _outerArc.arcRect.top < _innerArc.arcRect.top - ? _outerArc.arcRect.top - : _innerArc.arcRect.top; - final double right = _outerArc.arcRect.right < _innerArc.arcRect.right - ? _innerArc.arcRect.right - : _outerArc.arcRect.right; - final double bottom = _outerArc.arcRect.bottom < _innerArc.arcRect.bottom - ? _innerArc.arcRect.bottom - : _outerArc.arcRect.bottom; + final double left = + _outerArc.arcRect.left < _innerArc.arcRect.left + ? _outerArc.arcRect.left + : _innerArc.arcRect.left; + final double top = + _outerArc.arcRect.top < _innerArc.arcRect.top + ? _outerArc.arcRect.top + : _innerArc.arcRect.top; + final double right = + _outerArc.arcRect.right < _innerArc.arcRect.right + ? _innerArc.arcRect.right + : _outerArc.arcRect.right; + final double bottom = + _outerArc.arcRect.bottom < _innerArc.arcRect.bottom + ? _innerArc.arcRect.bottom + : _outerArc.arcRect.bottom; _pathRect = Rect.fromLTRB(left, top, right, bottom); } /// Calculates the range angle void _calculateRangeAngle() { if (!axisRenderer!.isInversed) { - _rangeStartValue = axisRenderer!.startAngle + + _rangeStartValue = + axisRenderer!.startAngle + (_maxAngle / ((axisRenderer!.maximum - axisRenderer!.minimum) / (startValue - axisRenderer!.minimum))); - _rangeEndValue = axisRenderer!.startAngle + + _rangeEndValue = + axisRenderer!.startAngle + (_maxAngle / ((axisRenderer!.maximum - axisRenderer!.minimum) / (endValue - axisRenderer!.minimum))); - _rangeMidValue = axisRenderer!.startAngle + + _rangeMidValue = + axisRenderer!.startAngle + (_maxAngle / ((axisRenderer!.maximum - axisRenderer!.minimum) / ((endValue - startValue) / 2 + startValue))); } else { - _rangeStartValue = axisRenderer!.startAngle + + _rangeStartValue = + axisRenderer!.startAngle + _maxAngle - (_maxAngle / ((axisRenderer!.maximum - axisRenderer!.minimum) / (startValue - axisRenderer!.minimum))); - _rangeEndValue = axisRenderer!.startAngle + + _rangeEndValue = + axisRenderer!.startAngle + _maxAngle - (_maxAngle / ((axisRenderer!.maximum - axisRenderer!.minimum) / (endValue - axisRenderer!.minimum))); - _rangeMidValue = axisRenderer!.startAngle + + _rangeMidValue = + axisRenderer!.startAngle + _maxAngle - (_maxAngle / ((axisRenderer!.maximum - axisRenderer!.minimum) / @@ -418,44 +435,53 @@ class RenderGaugeRange extends RenderBox { /// Method to calculate the rect for range with equal start and end width void _calculateEqualWidthArc() { _thickness = _actualStartWidth; - final double startFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer!.valueToFactor(startValue) != null) - ? axisRenderer!.renderer!.valueToFactor(startValue) ?? - axisRenderer!.valueToFactor(startValue) - : axisRenderer!.valueToFactor(startValue); + final double startFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor(startValue) != null) + ? axisRenderer!.renderer!.valueToFactor(startValue) ?? + axisRenderer!.valueToFactor(startValue) + : axisRenderer!.valueToFactor(startValue); _rangeStartRadian = getDegreeToRadian( - (startFactor * _sweepAngle) + axisRenderer!.startAngle); - final double endFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer!.valueToFactor(endValue) != null) - ? axisRenderer!.renderer!.valueToFactor(endValue) ?? - axisRenderer!.valueToFactor(endValue) - : axisRenderer!.valueToFactor(endValue); - final double endRadian = - getDegreeToRadian((endFactor * _sweepAngle) + axisRenderer!.startAngle); + (startFactor * _sweepAngle) + axisRenderer!.startAngle, + ); + final double endFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor(endValue) != null) + ? axisRenderer!.renderer!.valueToFactor(endValue) ?? + axisRenderer!.valueToFactor(endValue) + : axisRenderer!.valueToFactor(endValue); + final double endRadian = getDegreeToRadian( + (endFactor * _sweepAngle) + axisRenderer!.startAngle, + ); _rangeEndRadian = endRadian - _rangeStartRadian; // To render the range in clock wise if the start value is greater than the end value // for full circle axis track. if (axisRenderer!.startAngle == axisRenderer!.endAngle && startValue > endValue) { - final double midFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer!.valueToFactor(axisRenderer!.maximum) != - null) - ? axisRenderer!.renderer!.valueToFactor(axisRenderer!.maximum) ?? - axisRenderer!.valueToFactor(axisRenderer!.maximum) - : axisRenderer!.valueToFactor(axisRenderer!.maximum); + final double midFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor( + axisRenderer!.maximum, + ) != + null) + ? axisRenderer!.renderer!.valueToFactor(axisRenderer!.maximum) ?? + axisRenderer!.valueToFactor(axisRenderer!.maximum) + : axisRenderer!.valueToFactor(axisRenderer!.maximum); final double midRadian = getDegreeToRadian( - (midFactor * _sweepAngle) + axisRenderer!.startAngle); + (midFactor * _sweepAngle) + axisRenderer!.startAngle, + ); final double startRadian = getDegreeToRadian(axisRenderer!.startAngle); _rangeEndRadian = (midRadian - _rangeStartRadian) + (endRadian - startRadian); } _rangeRect = Rect.fromLTRB( - -(_radius - (_actualStartWidth / 2 + _totalOffset)), - -(_radius - (_actualStartWidth / 2 + _totalOffset)), - _radius - (_actualStartWidth / 2 + _totalOffset), - _radius - (_actualStartWidth / 2 + _totalOffset)); + -(_radius - (_actualStartWidth / 2 + _totalOffset)), + -(_radius - (_actualStartWidth / 2 + _totalOffset)), + _radius - (_actualStartWidth / 2 + _totalOffset), + _radius - (_actualStartWidth / 2 + _totalOffset), + ); } /// Method to calculate the sweep angle @@ -496,22 +522,33 @@ class RenderGaugeRange extends RenderBox { /// Method to create the arc data ArcData _getArcData( - Offset rangeStartOffset, Offset rangeEndOffset, Offset rangeMidOffset) { - final Offset controlPoint = - _getPointConversion(rangeStartOffset, rangeEndOffset, rangeMidOffset); + Offset rangeStartOffset, + Offset rangeEndOffset, + Offset rangeMidOffset, + ) { + final Offset controlPoint = _getPointConversion( + rangeStartOffset, + rangeEndOffset, + rangeMidOffset, + ); final double distance = math.sqrt( - math.pow(rangeStartOffset.dx - controlPoint.dx, 2) + - math.pow(rangeStartOffset.dy - controlPoint.dy, 2)); - - double actualStartAngle = getRadianToDegree(math.atan2( - rangeStartOffset.dy - controlPoint.dy, - rangeStartOffset.dx - controlPoint.dx, - )); - double actualEndAngle = getRadianToDegree(math.atan2( - rangeEndOffset.dy - controlPoint.dy, - rangeEndOffset.dx - controlPoint.dx, - )); + math.pow(rangeStartOffset.dx - controlPoint.dx, 2) + + math.pow(rangeStartOffset.dy - controlPoint.dy, 2), + ); + + double actualStartAngle = getRadianToDegree( + math.atan2( + rangeStartOffset.dy - controlPoint.dy, + rangeStartOffset.dx - controlPoint.dx, + ), + ); + double actualEndAngle = getRadianToDegree( + math.atan2( + rangeEndOffset.dy - controlPoint.dy, + rangeEndOffset.dx - controlPoint.dx, + ), + ); if (actualStartAngle < 0) { actualStartAngle += 360; @@ -531,29 +568,34 @@ class RenderGaugeRange extends RenderBox { arcData.startAngle = actualStartAngle; arcData.endAngle = actualEndAngle; arcData.arcRect = Rect.fromLTRB( - controlPoint.dx - distance + _totalOffset, - controlPoint.dy - distance + _totalOffset, - controlPoint.dx + distance - _totalOffset, - controlPoint.dy + distance - _totalOffset); + controlPoint.dx - distance + _totalOffset, + controlPoint.dy - distance + _totalOffset, + controlPoint.dx + distance - _totalOffset, + controlPoint.dy + distance - _totalOffset, + ); return arcData; } /// calculates the control point for range arc Offset _getPointConversion(Offset offset1, Offset offset2, Offset offset3) { double distance1 = (offset1.dy - offset2.dy) / (offset1.dx - offset2.dx); - distance1 = (offset1.dy - offset2.dy) == 0 || (offset1.dx - offset2.dx) == 0 - ? 0 - : distance1; + distance1 = + (offset1.dy - offset2.dy) == 0 || (offset1.dx - offset2.dx) == 0 + ? 0 + : distance1; double distance2 = (offset3.dy - offset2.dy) / (offset3.dx - offset2.dx); - distance2 = (offset3.dy - offset2.dy) == 0 || (offset3.dx - offset2.dx) == 0 - ? 0 - : distance2; - double x = (distance1 * distance2 * (offset3.dy - offset1.dy) + + distance2 = + (offset3.dy - offset2.dy) == 0 || (offset3.dx - offset2.dx) == 0 + ? 0 + : distance2; + double x = + (distance1 * distance2 * (offset3.dy - offset1.dy) + distance1 * (offset2.dx + offset3.dx) - distance2 * (offset1.dx + offset2.dx)) / (2 * (distance1 - distance2)); final double diff = (1 / distance1).isInfinite ? 0 : (1 / distance1); - double y = -diff * (x - ((offset1.dx + offset2.dx) / 2)) + + double y = + -diff * (x - ((offset1.dx + offset2.dx) / 2)) + ((offset1.dy + offset2.dy) / 2); x = x.isNaN ? 0 : x; y = y.isNaN ? 0 : y; @@ -591,32 +633,41 @@ class RenderGaugeRange extends RenderBox { /// Calculates the label position void _calculateLabelPosition() { - final double midValueFactor = (axisRenderer!.renderer != null && - axisRenderer!.renderer! - .valueToFactor((endValue + startValue) / 2) != - null) - ? axisRenderer!.renderer!.valueToFactor((endValue + startValue) / 2) ?? - axisRenderer!.valueToFactor((endValue + startValue) / 2) - : axisRenderer!.valueToFactor((endValue + startValue) / 2); + final double midValueFactor = + (axisRenderer!.renderer != null && + axisRenderer!.renderer!.valueToFactor( + (endValue + startValue) / 2, + ) != + null) + ? axisRenderer!.renderer!.valueToFactor( + (endValue + startValue) / 2, + ) ?? + axisRenderer!.valueToFactor((endValue + startValue) / 2) + : axisRenderer!.valueToFactor((endValue + startValue) / 2); final double midAngle = (midValueFactor * _sweepAngle) + axisRenderer!.startAngle; final double labelRadian = getDegreeToRadian(midAngle); _labelAngle = midAngle - 90; - final double height = _actualStartWidth != _actualEndWidth - ? (_actualEndWidth - _actualStartWidth).abs() / 2 - : _actualEndWidth / 2; + final double height = + _actualStartWidth != _actualEndWidth + ? (_actualEndWidth - _actualStartWidth).abs() / 2 + : _actualEndWidth / 2; if (!axisRenderer!.canScaleToFit) { - final double x = size.width / 2 + + final double x = + size.width / 2 + ((_radius - (_totalOffset + height)) * math.cos(labelRadian)) - _centerXPoint; - final double y = size.height / 2 + + final double y = + size.height / 2 + ((_radius - (_totalOffset + height)) * math.sin(labelRadian)) - _centerYPoint; _labelPosition = Offset(x, y); } else { - final double x = _axisCenter.dx + + final double x = + _axisCenter.dx + ((_radius - (_totalOffset + height)) * math.cos(labelRadian)); - final double y = _axisCenter.dy + + final double y = + _axisCenter.dy + ((_radius - (_totalOffset + height)) * math.sin(labelRadian)); _labelPosition = Offset(x, y); } @@ -629,10 +680,12 @@ class RenderGaugeRange extends RenderBox { opacity = _rangeAnimation!.value; } - final Paint paint = Paint() - ..style = isFill ? PaintingStyle.fill : PaintingStyle.stroke - ..strokeWidth = strokeWidth - ..color = color ?? _gaugeThemeData.rangeColor ?? const Color(0xFFF67280); + final Paint paint = + Paint() + ..style = isFill ? PaintingStyle.fill : PaintingStyle.stroke + ..strokeWidth = strokeWidth + ..color = + color ?? _gaugeThemeData.rangeColor ?? const Color(0xFFF67280); final double actualOpacity = paint.color.a; paint.color = paint.color.withValues(alpha: opacity * actualOpacity); if (gradient != null && gradient!.colors.isNotEmpty) { @@ -642,20 +695,22 @@ class RenderGaugeRange extends RenderBox { } paint.shader = SweepGradient( - colors: colors, stops: _getGradientStops() as List) - .createShader(rect); + colors: colors, + stops: _getGradientStops() as List, + ).createShader(rect); } return paint; } /// To calculate the gradient stop based on the sweep angle List _getGradientStops() { - final double sweepRadian = _actualStartWidth != _actualEndWidth - ? _rangeEndRadian - _rangeStartRadian - : _rangeEndRadian; + final double sweepRadian = + _actualStartWidth != _actualEndWidth + ? _rangeEndRadian - _rangeStartRadian + : _rangeEndRadian; double rangeStartAngle = axisRenderer!.valueToFactor(startValue) * _sweepAngle + - axisRenderer!.startAngle; + axisRenderer!.startAngle; if (rangeStartAngle < 0) { rangeStartAngle += 360; } @@ -666,7 +721,10 @@ class RenderGaugeRange extends RenderBox { final double sweepAngle = getRadianToDegree(sweepRadian).abs(); return calculateGradientStops( - _getGradientOffset(), axisRenderer!.isInversed, sweepAngle); + _getGradientOffset(), + axisRenderer!.isInversed, + sweepAngle, + ); } /// Returns the gradient stop of axis line gradient @@ -677,8 +735,10 @@ class RenderGaugeRange extends RenderBox { // Calculates the gradient stop values based on the number of provided // color final double difference = 1 / gradient!.colors.length; - final List offsets = - List.filled(gradient!.colors.length, null); + final List offsets = List.filled( + gradient!.colors.length, + null, + ); for (int i = 0; i < gradient!.colors.length; i++) { offsets[i] = i * difference; } @@ -699,24 +759,29 @@ class RenderGaugeRange extends RenderBox { final Color labelColor = labelStyle.color ?? getSaturationColor(rangeColor); final double actualOpacity = labelColor.a; final TextSpan span = TextSpan( - text: label, - style: TextStyle( - color: labelColor.withValues(alpha: actualOpacity * opacity), - fontSize: labelStyle.fontSize, - fontFamily: labelStyle.fontFamily, - fontStyle: labelStyle.fontStyle, - fontWeight: labelStyle.fontWeight)); + text: label, + style: TextStyle( + color: labelColor.withValues(alpha: actualOpacity * opacity), + fontSize: labelStyle.fontSize, + fontFamily: labelStyle.fontFamily, + fontStyle: labelStyle.fontStyle, + fontWeight: labelStyle.fontWeight, + ), + ); final TextPainter textPainter = TextPainter( - text: span, - textDirection: TextDirection.ltr, - textAlign: TextAlign.center); + text: span, + textDirection: TextDirection.ltr, + textAlign: TextAlign.center, + ); textPainter.layout(); canvas.save(); canvas.translate(_labelPosition.dx, _labelPosition.dy); canvas.rotate(getDegreeToRadian(_labelAngle)); canvas.scale(-1); textPainter.paint( - canvas, Offset(-_labelSize.width / 2, -_labelSize.height / 2)); + canvas, + Offset(-_labelSize.width / 2, -_labelSize.height / 2), + ); canvas.restore(); } @@ -730,7 +795,9 @@ class RenderGaugeRange extends RenderBox { canvas.save(); if (!axisRenderer!.canScaleToFit) { canvas.translate( - _center.dx - _centerXPoint, _center.dy - _centerYPoint); + _center.dx - _centerXPoint, + _center.dy - _centerYPoint, + ); } else { canvas.translate(_axisCenter.dx, _axisCenter.dy); } @@ -738,10 +805,18 @@ class RenderGaugeRange extends RenderBox { canvas.rotate(_rangeStartRadian); if (_rangeRect == null) { - path.arcTo(_outerArc.arcRect, getDegreeToRadian(_outerArc.startAngle), - getDegreeToRadian(_outerArcSweepAngle), false); - path.arcTo(_innerArc.arcRect, getDegreeToRadian(_innerArc.endAngle), - getDegreeToRadian(_innerArcSweepAngle), false); + path.arcTo( + _outerArc.arcRect, + getDegreeToRadian(_outerArc.startAngle), + getDegreeToRadian(_outerArcSweepAngle), + false, + ); + path.arcTo( + _innerArc.arcRect, + getDegreeToRadian(_innerArc.endAngle), + getDegreeToRadian(_innerArcSweepAngle), + false, + ); paint = _getRangePaint(true, _pathRect, 0); canvas.drawPath(path, paint); diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/marker_pointer_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/marker_pointer_renderer.dart index 2a245f8ef..20f562fba 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/marker_pointer_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/marker_pointer_renderer.dart @@ -21,6 +21,9 @@ class MarkerPointerRenderer { /// By overriding this method, you can draw the customized marker /// pointer using required values . /// - void drawPointer(Canvas canvas, PointerPaintingDetails pointerPaintingDetails, - SfGaugeThemeData gaugeThemeData) {} + void drawPointer( + Canvas canvas, + PointerPaintingDetails pointerPaintingDetails, + SfGaugeThemeData gaugeThemeData, + ) {} } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/needle_pointer_renderer.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/needle_pointer_renderer.dart index 6a90dd988..e15585020 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/needle_pointer_renderer.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/renderers/needle_pointer_renderer.dart @@ -21,6 +21,9 @@ class NeedlePointerRenderer { /// By overriding this method, you can draw the customized marker /// pointer using required values. /// - void drawPointer(Canvas canvas, PointerPaintingDetails pointerPaintingDetails, - SfGaugeThemeData gaugeThemeData) {} + void drawPointer( + Canvas canvas, + PointerPaintingDetails pointerPaintingDetails, + SfGaugeThemeData gaugeThemeData, + ) {} } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_knob_style.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_knob_style.dart index e56d48738..ba13e923b 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_knob_style.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_knob_style.dart @@ -21,17 +21,18 @@ class KnobStyle { /// Creates the knob style with default or required properties. /// /// The arguments [knobRadius], [borderWidth] must be non-negative. - const KnobStyle( - {this.knobRadius = 0.08, - this.borderWidth = 0, - this.sizeUnit = GaugeSizeUnit.factor, - this.borderColor, - this.color}) - : assert(knobRadius >= 0, 'Knob radius must be a non-negative value.'), - assert( - borderWidth >= 0, - 'Knob border width must be a ' - 'non-negative value.'); + const KnobStyle({ + this.knobRadius = 0.08, + this.borderWidth = 0, + this.sizeUnit = GaugeSizeUnit.factor, + this.borderColor, + this.color, + }) : assert(knobRadius >= 0, 'Knob radius must be a non-negative value.'), + assert( + borderWidth >= 0, + 'Knob border width must be a ' + 'non-negative value.', + ); /// Adjusts the knob radius in needle pointer. /// @@ -159,7 +160,7 @@ class KnobStyle { borderWidth, sizeUnit, borderColor, - color + color, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tail_style.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tail_style.dart index 5bb618fce..2c3550908 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tail_style.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tail_style.dart @@ -19,20 +19,21 @@ import '../../radial_gauge/utils/enum.dart'; @immutable class TailStyle { /// Creates the tail style with default or required properties. - const TailStyle( - {this.color, - this.width = 0, - this.length = 0, - this.borderWidth = 0, - this.gradient, - this.lengthUnit = GaugeSizeUnit.factor, - this.borderColor}) - : assert(width >= 0, 'Tail width must be a non-negative value.'), - assert(length >= 0, 'Tail length must be a non-negative value.'), - assert( - borderWidth >= 0, - 'Tail border width must be a ' - 'non-negative value.'); + const TailStyle({ + this.color, + this.width = 0, + this.length = 0, + this.borderWidth = 0, + this.gradient, + this.lengthUnit = GaugeSizeUnit.factor, + this.borderColor, + }) : assert(width >= 0, 'Tail width must be a non-negative value.'), + assert(length >= 0, 'Tail length must be a non-negative value.'), + assert( + borderWidth >= 0, + 'Tail border width must be a ' + 'non-negative value.', + ); /// Specifies the color of the tail. /// @@ -214,7 +215,7 @@ class TailStyle { length, gradient, lengthUnit, - borderColor + borderColor, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_text_style.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_text_style.dart index 876d6a493..106982e8a 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_text_style.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_text_style.dart @@ -7,12 +7,13 @@ import 'package:flutter/material.dart'; @immutable class GaugeTextStyle { /// Creates a gauge text style with default or required properties. - const GaugeTextStyle( - {this.color, - this.fontFamily, - this.fontStyle, - this.fontWeight, - this.fontSize}); + const GaugeTextStyle({ + this.color, + this.fontFamily, + this.fontStyle, + this.fontWeight, + this.fontSize, + }); /// To set the color of guage text. final Color? color; @@ -58,7 +59,7 @@ class GaugeTextStyle { fontFamily, fontStyle, fontWeight, - fontSize + fontSize, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tick_style.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tick_style.dart index 0ed4638cf..6a76c514d 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tick_style.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/styles/radial_tick_style.dart @@ -22,14 +22,14 @@ class MajorTickStyle { /// Creates a major tick style with default or required properties. /// /// The arguments [length], [thickness], must be non-negative. - const MajorTickStyle( - {this.length = 7, - this.thickness = 1.5, - this.lengthUnit = GaugeSizeUnit.logicalPixel, - this.color, - this.dashArray}) - : assert(length >= 0, 'Tick length must be a non-negative value.'), - assert(thickness >= 0, 'Tick thickness must be a non-negative value.'); + const MajorTickStyle({ + this.length = 7, + this.thickness = 1.5, + this.lengthUnit = GaugeSizeUnit.logicalPixel, + this.color, + this.dashArray, + }) : assert(length >= 0, 'Tick length must be a non-negative value.'), + assert(thickness >= 0, 'Tick thickness must be a non-negative value.'); /// Specifies the length of the tick. /// @@ -147,7 +147,7 @@ class MajorTickStyle { thickness, lengthUnit, color, - dashArray + dashArray, ]; return Object.hashAll(values); } @@ -172,21 +172,21 @@ class MinorTickStyle extends MajorTickStyle { /// Creates a minor tick style with default or required properties. /// /// The arguments [length], [thickness], must be non-negative. - const MinorTickStyle( - {double length = 5, - GaugeSizeUnit lengthUnit = GaugeSizeUnit.logicalPixel, - Color? color, - double thickness = 1.5, - List? dashArray}) - : assert(length >= 0, 'Tick length must be a non-negative value.'), - assert(thickness >= 0, 'Tick thickness must be a non-negative value.'), - super( - length: length, - lengthUnit: lengthUnit, - thickness: thickness, - dashArray: dashArray, - color: color, - ); + const MinorTickStyle({ + double length = 5, + GaugeSizeUnit lengthUnit = GaugeSizeUnit.logicalPixel, + Color? color, + double thickness = 1.5, + List? dashArray, + }) : assert(length >= 0, 'Tick length must be a non-negative value.'), + assert(thickness >= 0, 'Tick thickness must be a non-negative value.'), + super( + length: length, + lengthUnit: lengthUnit, + thickness: thickness, + dashArray: dashArray, + color: color, + ); } /// Create the style of axis line. @@ -207,19 +207,22 @@ class AxisLineStyle { /// Creates a minor tick style with default or required properties. /// /// The arguments [thickness], must be non-negative. - const AxisLineStyle( - {this.thickness = 10, - this.thicknessUnit = GaugeSizeUnit.logicalPixel, - this.color, - this.gradient, - this.cornerStyle = CornerStyle.bothFlat, - this.dashArray}) - : assert(thickness >= 0, - 'Axis line thickness must be a non-negative value.'), - assert( - (gradient != null && gradient is SweepGradient) || gradient == null, - 'The gradient must be null or else ' - 'the gradient must be equal to sweep gradient.'); + const AxisLineStyle({ + this.thickness = 10, + this.thicknessUnit = GaugeSizeUnit.logicalPixel, + this.color, + this.gradient, + this.cornerStyle = CornerStyle.bothFlat, + this.dashArray, + }) : assert( + thickness >= 0, + 'Axis line thickness must be a non-negative value.', + ), + assert( + (gradient != null && gradient is SweepGradient) || gradient == null, + 'The gradient must be null or else ' + 'the gradient must be equal to sweep gradient.', + ); /// Calculates the axis line thickness either in logical pixel /// or radius factor. @@ -373,7 +376,7 @@ class AxisLineStyle { color, gradient, cornerStyle, - dashArray + dashArray, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/title/radial_title.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/title/radial_title.dart index 5a88ee98a..2f3d85d6d 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/title/radial_title.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/title/radial_title.dart @@ -26,13 +26,14 @@ import '../../radial_gauge/utils/enum.dart'; @immutable class GaugeTitle { /// Creates the gauge title with default or required properties. - const GaugeTitle( - {required this.text, - this.textStyle, - this.alignment = GaugeAlignment.center, - this.borderColor, - this.borderWidth = 0, - this.backgroundColor}); + const GaugeTitle({ + required this.text, + this.textStyle, + this.alignment = GaugeAlignment.center, + this.borderColor, + this.borderWidth = 0, + this.backgroundColor, + }); /// Text to be displayed as gauge title. /// @@ -183,7 +184,7 @@ class GaugeTitle { textStyle, borderWidth, borderColor, - backgroundColor + backgroundColor, ]; return Object.hashAll(values); } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/enum.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/enum.dart index dd6d98de2..6e47f375d 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/enum.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/enum.dart @@ -10,7 +10,7 @@ enum GaugeAlignment { /// GaugeAlignment.far aligns the gauge element to far either /// the horizontal or vertical. - far + far, } /// Position the gauge element either inside or outside the axis. @@ -19,7 +19,7 @@ enum ElementsPosition { inside, /// ElementPosition.outside places the axis elements outside the axis. - outside + outside, } /// Apply the corner style for range pointer. @@ -34,7 +34,7 @@ enum CornerStyle { startCurve, /// CornerStyle.endCurce apply the rounded corner on end(right) side. - endCurve + endCurve, } /// Apply the different marker type for pointer. @@ -58,7 +58,7 @@ enum MarkerType { image, /// MarkerText.text points the value with text. - text + text, } /// Apply the different types of animation to pointer. @@ -82,7 +82,7 @@ enum AnimationType { linear, /// AnimationType.slowMiddle animates the pointers with Curves.slowMiddle. - slowMiddle + slowMiddle, } /// Size determined either the logical pixel or the radius factor. @@ -91,5 +91,5 @@ enum GaugeSizeUnit { factor, /// GaugeSizeUnit.logicalPixel specifies the value in logical pixel. - logicalPixel + logicalPixel, } diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/helper.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/helper.dart index 6061a3651..28bbf9803 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/helper.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/helper.dart @@ -43,8 +43,10 @@ double getRadianToDegree(double radian) { /// To get the degree from the point Offset getDegreeToPoint(double degree, double radius, Offset center) { degree = getDegreeToRadian(degree); - return Offset(center.dx + math.cos(degree) * radius, - center.dy + math.sin(degree) * radius); + return Offset( + center.dx + math.cos(degree) * radius, + center.dy + math.sin(degree) * radius, + ); } /// Methods to get the saturation color @@ -66,13 +68,15 @@ Size getTextSize(String textValue, GaugeTextStyle textStyle) { textAlign: TextAlign.center, textDirection: TextDirection.ltr, text: TextSpan( - text: textValue, - style: TextStyle( - color: textStyle.color, - fontSize: textStyle.fontSize, - fontFamily: textStyle.fontFamily, - fontStyle: textStyle.fontStyle, - fontWeight: textStyle.fontWeight)), + text: textValue, + style: TextStyle( + color: textStyle.color, + fontSize: textStyle.fontSize, + fontFamily: textStyle.fontFamily, + fontStyle: textStyle.fontStyle, + fontWeight: textStyle.fontWeight, + ), + ), ); textPainter.layout(); size = Size(textPainter.width, textPainter.height); @@ -81,7 +85,10 @@ Size getTextSize(String textValue, GaugeTextStyle textStyle) { /// Returns the revised gradient stop List calculateGradientStops( - List offsets, bool isInversed, double sweepAngle) { + List offsets, + bool isInversed, + double sweepAngle, +) { final List gradientStops = List.filled(offsets.length, 0); // Normalizes the provided offset values to the corresponding sweep angle @@ -158,8 +165,10 @@ Path dashPath(Path source, {CircularIntervalList? dashArray}) { while (distance < measurePath.length) { final double length = dashArray.next; if (draw) { - path.addPath(measurePath.extractPath(distance, distance + length), - Offset.zero); + path.addPath( + measurePath.extractPath(distance, distance + length), + Offset.zero, + ); } distance += length; draw = !draw; @@ -172,10 +181,12 @@ Path dashPath(Path source, {CircularIntervalList? dashArray}) { /// Calculates the corner radius angle double cornerRadiusAngle(double totalRadius, double circleRadius) { final double perimeter = (totalRadius + totalRadius + circleRadius) / 2; - final double area = math.sqrt(perimeter * - (perimeter - totalRadius) * - (perimeter - totalRadius) * - (perimeter - circleRadius)); + final double area = math.sqrt( + perimeter * + (perimeter - totalRadius) * + (perimeter - totalRadius) * + (perimeter - circleRadius), + ); final double cornerRadiusAngle = math.asin((2 * area) / (totalRadius * totalRadius)) * (180 / math.pi); return cornerRadiusAngle; diff --git a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/radial_gauge_typedef.dart b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/radial_gauge_typedef.dart index 99a6b9f62..a382697f2 100644 --- a/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/radial_gauge_typedef.dart +++ b/packages/syncfusion_flutter_gauges/lib/src/radial_gauge/utils/radial_gauge_typedef.dart @@ -1,14 +1,14 @@ /// Signature for the callback that reports the custom renderer has been extended /// and set to the gauge axis -typedef GaugeAxisRendererFactory = GaugeAxisRenderer - Function(); +typedef GaugeAxisRendererFactory = + GaugeAxisRenderer Function(); /// Signature for the callback that reports the custom renderer has been extended /// and set to the marker pointer -typedef MarkerPointerRendererFactory - = MarkerPointerRenderer Function(); +typedef MarkerPointerRendererFactory = + MarkerPointerRenderer Function(); /// Signature for the callback that report the custom renderer has been extended /// and set to the needle pointer -typedef NeedlePointerRendererFactory - = NeedlePointerRenderer Function(); +typedef NeedlePointerRendererFactory = + NeedlePointerRenderer Function(); diff --git a/packages/syncfusion_flutter_gauges/pubspec.yaml b/packages/syncfusion_flutter_gauges/pubspec.yaml index e45742ccf..084354001 100644 --- a/packages/syncfusion_flutter_gauges/pubspec.yaml +++ b/packages/syncfusion_flutter_gauges/pubspec.yaml @@ -1,10 +1,10 @@ name: syncfusion_flutter_gauges description: The Flutter gauges library includes a linear gauge and radial gauge (a.k.a. circular gauge) to create modern, interactive, animated gauges and radial sliders. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_gauges environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_maps/CHANGELOG.md b/packages/syncfusion_flutter_maps/CHANGELOG.md index e5be1030c..51b29bc68 100644 --- a/packages/syncfusion_flutter_maps/CHANGELOG.md +++ b/packages/syncfusion_flutter_maps/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of our Flutter maps widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter maps widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter maps example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter maps example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_maps/example/lib/main.dart b/packages/syncfusion_flutter_maps/example/lib/main.dart index 17d149805..354e9c187 100644 --- a/packages/syncfusion_flutter_maps/example/lib/main.dart +++ b/packages/syncfusion_flutter_maps/example/lib/main.dart @@ -11,10 +11,7 @@ class MapsApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Maps Demo', - home: MyHomePage(), - ); + return const MaterialApp(title: 'Maps Demo', home: MyHomePage()); } } @@ -36,18 +33,30 @@ class _MyHomePageState extends State { @override void initState() { _data = const [ - Model('New South Wales', Color.fromRGBO(255, 215, 0, 1.0), - ' New\nSouth Wales'), + Model( + 'New South Wales', + Color.fromRGBO(255, 215, 0, 1.0), + ' New\nSouth Wales', + ), Model('Queensland', Color.fromRGBO(72, 209, 204, 1.0), 'Queensland'), - Model('Northern Territory', Color.fromRGBO(255, 78, 66, 1.0), - 'Northern\nTerritory'), + Model( + 'Northern Territory', + Color.fromRGBO(255, 78, 66, 1.0), + 'Northern\nTerritory', + ), Model('Victoria', Color.fromRGBO(171, 56, 224, 0.75), 'Victoria'), - Model('South Australia', Color.fromRGBO(126, 247, 74, 0.75), - 'South Australia'), - Model('Western Australia', Color.fromRGBO(79, 60, 201, 0.7), - 'Western Australia'), + Model( + 'South Australia', + Color.fromRGBO(126, 247, 74, 0.75), + 'South Australia', + ), + Model( + 'Western Australia', + Color.fromRGBO(79, 60, 201, 0.7), + 'Western Australia', + ), Model('Tasmania', Color.fromRGBO(99, 164, 230, 1), 'Tasmania'), - Model('Australian Capital Territory', Colors.teal, 'ACT') + Model('Australian Capital Territory', Colors.teal, 'ACT'), ]; _mapSource = MapShapeSource.asset( @@ -74,9 +83,10 @@ class _MyHomePageState extends State { showDataLabels: true, legend: const MapLegend(MapElement.shape), tooltipSettings: MapTooltipSettings( - color: Colors.grey[700], - strokeColor: Colors.white, - strokeWidth: 2), + color: Colors.grey[700], + strokeColor: Colors.white, + strokeWidth: 2, + ), strokeColor: Colors.white, strokeWidth: 0.5, shapeTooltipBuilder: (BuildContext context, int index) { @@ -90,10 +100,10 @@ class _MyHomePageState extends State { }, dataLabelSettings: MapDataLabelSettings( textStyle: TextStyle( - color: Colors.black, - fontWeight: FontWeight.bold, - fontSize: - Theme.of(context).textTheme.bodySmall!.fontSize), + color: Colors.black, + fontWeight: FontWeight.bold, + fontSize: Theme.of(context).textTheme.bodySmall!.fontSize, + ), ), ), ], diff --git a/packages/syncfusion_flutter_maps/example/pubspec.yaml b/packages/syncfusion_flutter_maps/example/pubspec.yaml index 73b2e4d23..e0089bb94 100644 --- a/packages/syncfusion_flutter_maps/example/pubspec.yaml +++ b/packages/syncfusion_flutter_maps/example/pubspec.yaml @@ -1,20 +1,10 @@ name: maps_sample description: A new Flutter project. -# 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 used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -24,56 +14,15 @@ dependencies: syncfusion_flutter_maps: path: ../ - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: '>=0.1.3 <1.0.7' dev_dependencies: flutter_test: sdk: flutter - -# 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. 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 assets: - assets/world_map.json - assets/australia.json - - # To add assets to your application, add an assets section, like this: - # assets: - # - 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 diff --git a/packages/syncfusion_flutter_maps/lib/maps.dart b/packages/syncfusion_flutter_maps/lib/maps.dart index d6f717e65..14692113b 100644 --- a/packages/syncfusion_flutter_maps/lib/maps.dart +++ b/packages/syncfusion_flutter_maps/lib/maps.dart @@ -267,10 +267,7 @@ Future _fetchResponse(String url) { /// instance of [MapZoomPanBehavior]. class SfMaps extends StatefulWidget { /// Creates a [SfMaps]. - const SfMaps({ - Key? key, - required this.layers, - }) : super(key: key); + const SfMaps({Key? key, required this.layers}) : super(key: key); /// The collection of map shape layer in which geographical rendering is done. /// @@ -326,8 +323,9 @@ class _SfMapsState extends State { /// Otherwise, returns the last layer. List _buildLayers(List layers) { if (layers.length > 1) { - final bool loadMultiTileLayer = - layers.every((MapLayer layer) => layer is MapTileLayer); + final bool loadMultiTileLayer = layers.every( + (MapLayer layer) => layer is MapTileLayer, + ); return loadMultiTileLayer ? layers : [layers.last]; } else { return layers; @@ -337,7 +335,7 @@ class _SfMapsState extends State { class _MapsRenderObjectWidget extends SingleChildRenderObjectWidget { const _MapsRenderObjectWidget({Key? key, required Widget child}) - : super(key: key, child: child); + : super(key: key, child: child); @override _RenderMaps createRenderObject(BuildContext context) { @@ -353,8 +351,10 @@ class _RenderMaps extends RenderProxyBox { final double height = constraints.hasBoundedHeight ? constraints.maxHeight : 300; if (child != null) { - child!.layout(BoxConstraints.loose(Size(width, height)), - parentUsesSize: true); + child!.layout( + BoxConstraints.loose(Size(width, height)), + parentUsesSize: true, + ); size = child!.size; } } @@ -923,18 +923,35 @@ class MapShapeSublayer extends MapSublayer { properties.add(IntProperty('markersCount', initialMarkersCount)); } - properties.add(ObjectFlagProperty.has( - 'markerBuilder', markerBuilder)); - properties.add(ObjectFlagProperty.has( - 'shapeTooltip', shapeTooltipBuilder)); - properties.add(ObjectFlagProperty.has( - 'bubbleTooltip', bubbleTooltipBuilder)); - properties.add(ObjectFlagProperty.has( - 'markerTooltip', markerTooltipBuilder)); - properties.add(FlagProperty('showDataLabels', + properties.add( + ObjectFlagProperty.has('markerBuilder', markerBuilder), + ); + properties.add( + ObjectFlagProperty.has( + 'shapeTooltip', + shapeTooltipBuilder, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'bubbleTooltip', + bubbleTooltipBuilder, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'markerTooltip', + markerTooltipBuilder, + ), + ); + properties.add( + FlagProperty( + 'showDataLabels', value: showDataLabels, ifTrue: 'Data labels are showing', - ifFalse: 'Data labels are not showing')); + ifFalse: 'Data labels are not showing', + ), + ); if (color != null) { properties.add(ColorProperty('color', color)); } @@ -948,11 +965,13 @@ class MapShapeSublayer extends MapSublayer { } properties.add(IntProperty('selectedIndex', selectedIndex)); - properties - .add(dataLabelSettings.toDiagnosticsNode(name: 'dataLabelSettings')); + properties.add( + dataLabelSettings.toDiagnosticsNode(name: 'dataLabelSettings'), + ); properties.add(bubbleSettings.toDiagnosticsNode(name: 'bubbleSettings')); - properties - .add(selectionSettings.toDiagnosticsNode(name: 'selectionSettings')); + properties.add( + selectionSettings.toDiagnosticsNode(name: 'selectionSettings'), + ); } } @@ -1040,17 +1059,17 @@ class MapShapeLayer extends MapLayer { WillZoomCallback? onWillZoom, WillPanCallback? onWillPan, }) : super( - key: key, - initialLatLngBounds: initialLatLngBounds, - sublayers: sublayers, - initialMarkersCount: initialMarkersCount, - markerBuilder: markerBuilder, - markerTooltipBuilder: markerTooltipBuilder, - tooltipSettings: tooltipSettings, - zoomPanBehavior: zoomPanBehavior, - onWillZoom: onWillZoom, - onWillPan: onWillPan, - ); + key: key, + initialLatLngBounds: initialLatLngBounds, + sublayers: sublayers, + initialMarkersCount: initialMarkersCount, + markerBuilder: markerBuilder, + markerTooltipBuilder: markerTooltipBuilder, + tooltipSettings: tooltipSettings, + zoomPanBehavior: zoomPanBehavior, + onWillZoom: onWillZoom, + onWillPan: onWillPan, + ); /// The source that maps the data source with the shape file and provides /// data for the elements of the this layer like data labels, bubbles, @@ -1644,11 +1663,19 @@ class MapShapeLayer extends MapLayer { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(source.toDiagnosticsNode(name: 'source')); - properties.add(ObjectFlagProperty.has( - 'loadingBuilder', loadingBuilder)); + properties.add( + ObjectFlagProperty.has( + 'loadingBuilder', + loadingBuilder, + ), + ); if (initialLatLngBounds != null) { - properties.add(DiagnosticsProperty( - 'initialLatLngBounds', initialLatLngBounds)); + properties.add( + DiagnosticsProperty( + 'initialLatLngBounds', + initialLatLngBounds, + ), + ); } if (controller != null) { properties.add(IntProperty('markersCount', controller!.markersCount)); @@ -1659,18 +1686,35 @@ class MapShapeLayer extends MapLayer { final DebugSublayerTree pointerTreeNode = DebugSublayerTree(sublayers!); properties.add(pointerTreeNode.toDiagnosticsNode()); } - properties.add(ObjectFlagProperty.has( - 'markerBuilder', markerBuilder)); - properties.add(ObjectFlagProperty.has( - 'shapeTooltip', shapeTooltipBuilder)); - properties.add(ObjectFlagProperty.has( - 'bubbleTooltip', bubbleTooltipBuilder)); - properties.add(ObjectFlagProperty.has( - 'markerTooltip', markerTooltipBuilder)); - properties.add(FlagProperty('showDataLabels', + properties.add( + ObjectFlagProperty.has('markerBuilder', markerBuilder), + ); + properties.add( + ObjectFlagProperty.has( + 'shapeTooltip', + shapeTooltipBuilder, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'bubbleTooltip', + bubbleTooltipBuilder, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'markerTooltip', + markerTooltipBuilder, + ), + ); + properties.add( + FlagProperty( + 'showDataLabels', value: showDataLabels, ifTrue: 'Data labels are showing', - ifFalse: 'Data labels are not showing')); + ifFalse: 'Data labels are not showing', + ), + ); if (color != null) { properties.add(ColorProperty('color', color)); } @@ -1684,23 +1728,28 @@ class MapShapeLayer extends MapLayer { } properties.add(IntProperty('selectedIndex', selectedIndex)); - properties - .add(dataLabelSettings.toDiagnosticsNode(name: 'dataLabelSettings')); + properties.add( + dataLabelSettings.toDiagnosticsNode(name: 'dataLabelSettings'), + ); if (legend != null) { properties.add(legend!.toDiagnosticsNode(name: 'legend')); } properties.add(bubbleSettings.toDiagnosticsNode(name: 'bubbleSettings')); - properties - .add(selectionSettings.toDiagnosticsNode(name: 'selectionSettings')); + properties.add( + selectionSettings.toDiagnosticsNode(name: 'selectionSettings'), + ); properties.add(tooltipSettings.toDiagnosticsNode(name: 'tooltipSettings')); if (zoomPanBehavior != null) { - properties - .add(zoomPanBehavior!.toDiagnosticsNode(name: 'zoomPanBehavior')); + properties.add( + zoomPanBehavior!.toDiagnosticsNode(name: 'zoomPanBehavior'), + ); } properties.add( - ObjectFlagProperty.has('onWillZoom', onWillZoom)); - properties - .add(ObjectFlagProperty.has('onWillPan', onWillPan)); + ObjectFlagProperty.has('onWillZoom', onWillZoom), + ); + properties.add( + ObjectFlagProperty.has('onWillPan', onWillPan), + ); } } @@ -1766,9 +1815,10 @@ class _ShapeLayerState extends State<_ShapeLayer> { @override void initState() { - _controller = MapController() - ..tooltipKey = GlobalKey() - ..layerType = LayerType.shape; + _controller = + MapController() + ..tooltipKey = GlobalKey() + ..layerType = LayerType.shape; super.initState(); } @@ -1882,21 +1932,23 @@ class MapTileLayer extends MapLayer { MapZoomPanBehavior? zoomPanBehavior, WillZoomCallback? onWillZoom, WillPanCallback? onWillPan, - }) : assert(initialZoomLevel >= 1 && initialZoomLevel <= 15), - assert(initialMarkersCount == 0 || - initialMarkersCount != 0 && markerBuilder != null), - super( - key: key, - initialLatLngBounds: initialLatLngBounds, - sublayers: sublayers, - initialMarkersCount: initialMarkersCount, - markerBuilder: markerBuilder, - markerTooltipBuilder: markerTooltipBuilder, - tooltipSettings: tooltipSettings, - zoomPanBehavior: zoomPanBehavior, - onWillZoom: onWillZoom, - onWillPan: onWillPan, - ); + }) : assert(initialZoomLevel >= 1 && initialZoomLevel <= 15), + assert( + initialMarkersCount == 0 || + initialMarkersCount != 0 && markerBuilder != null, + ), + super( + key: key, + initialLatLngBounds: initialLatLngBounds, + sublayers: sublayers, + initialMarkersCount: initialMarkersCount, + markerBuilder: markerBuilder, + markerTooltipBuilder: markerTooltipBuilder, + tooltipSettings: tooltipSettings, + zoomPanBehavior: zoomPanBehavior, + onWillZoom: onWillZoom, + onWillPan: onWillPan, + ); /// URL template to request the tiles from the providers. /// @@ -2125,32 +2177,41 @@ class MapTileLayer extends MapLayer { super.debugFillProperties(properties); properties.add(StringProperty('urlTemplate', urlTemplate)); - properties.add(DiagnosticsProperty( - 'initialFocalLatLng', initialFocalLatLng)); + properties.add( + DiagnosticsProperty('initialFocalLatLng', initialFocalLatLng), + ); properties.add(IntProperty('initialZoomLevel', initialZoomLevel)); if (initialLatLngBounds != null) { - properties.add(DiagnosticsProperty( - 'initialLatLngBounds', initialLatLngBounds)); + properties.add( + DiagnosticsProperty( + 'initialLatLngBounds', + initialLatLngBounds, + ), + ); } if (sublayers != null && sublayers!.isNotEmpty) { final DebugSublayerTree pointerTreeNode = DebugSublayerTree(sublayers!); properties.add(pointerTreeNode.toDiagnosticsNode()); } if (zoomPanBehavior != null) { - properties - .add(zoomPanBehavior!.toDiagnosticsNode(name: 'zoomPanBehavior')); + properties.add( + zoomPanBehavior!.toDiagnosticsNode(name: 'zoomPanBehavior'), + ); } - properties.add(ObjectFlagProperty.has( - 'markerBuilder', markerBuilder)); + properties.add( + ObjectFlagProperty.has('markerBuilder', markerBuilder), + ); if (controller != null) { properties.add(IntProperty('markersCount', controller!.markersCount)); } else { properties.add(IntProperty('markersCount', initialMarkersCount)); } properties.add( - ObjectFlagProperty.has('onWillZoom', onWillZoom)); - properties - .add(ObjectFlagProperty.has('onWillPan', onWillPan)); + ObjectFlagProperty.has('onWillZoom', onWillZoom), + ); + properties.add( + ObjectFlagProperty.has('onWillPan', onWillPan), + ); } } @@ -2196,10 +2257,11 @@ class _TileLayerState extends State<_TileLayer> { @override void initState() { - _controller = MapController() - ..tooltipKey = GlobalKey() - ..layerType = LayerType.tile - ..tileCurrentLevelDetails = TileZoomLevelDetails(); + _controller = + MapController() + ..tooltipKey = GlobalKey() + ..layerType = LayerType.tile + ..tileCurrentLevelDetails = TileZoomLevelDetails(); if (widget.zoomPanBehavior != null && widget.zoomPanBehavior!._zoomController == null) { widget.zoomPanBehavior!._zoomController = ZoomableController(); @@ -2342,18 +2404,18 @@ class MapZoomPanBehavior extends MapBehavior { bool enableMouseWheelZooming = false, bool showToolbar = true, MapToolbarSettings toolbarSettings = const MapToolbarSettings(), - }) : _zoomLevel = zoomLevel.clamp(minZoomLevel, maxZoomLevel), - _focalLatLng = focalLatLng, - _latLngBounds = latLngBounds, - _minZoomLevel = minZoomLevel, - _maxZoomLevel = maxZoomLevel, - _enablePinching = enablePinching, - _enablePanning = enablePanning, - _enableDoubleTapZooming = enableDoubleTapZooming, - _enableMouseWheelZooming = enableMouseWheelZooming, - _showToolbar = showToolbar, - _toolbarSettings = toolbarSettings, - _zoomController = ZoomableController(); + }) : _zoomLevel = zoomLevel.clamp(minZoomLevel, maxZoomLevel), + _focalLatLng = focalLatLng, + _latLngBounds = latLngBounds, + _minZoomLevel = minZoomLevel, + _maxZoomLevel = maxZoomLevel, + _enablePinching = enablePinching, + _enablePanning = enablePanning, + _enableDoubleTapZooming = enableDoubleTapZooming, + _enableMouseWheelZooming = enableMouseWheelZooming, + _showToolbar = showToolbar, + _toolbarSettings = toolbarSettings, + _zoomController = ZoomableController(); /// Current zoom level of the map layer. /// @@ -2432,9 +2494,12 @@ class MapZoomPanBehavior extends MapBehavior { _latLngBounds = value; if (_controller != null) { - zoomLevel = getZoomLevel(_latLngBounds!, _controller!.layerType!, - renderBox.size, _controller!.shapeLayerSizeFactor / zoomLevel) - .clamp(minZoomLevel, maxZoomLevel); + zoomLevel = getZoomLevel( + _latLngBounds!, + _controller!.layerType!, + renderBox.size, + _controller!.shapeLayerSizeFactor / zoomLevel, + ).clamp(minZoomLevel, maxZoomLevel); focalLatLng = getFocalLatLng(_latLngBounds!); } } @@ -2648,16 +2713,20 @@ class MapZoomPanBehavior extends MapBehavior { // Converts the current focalLatLng into a offset and validates it with // zoom controller actual rect to perform animation. void _updateZoomControllerActualRect() { - final Offset center = pixelFromLatLng(_focalLatLng!.latitude, - _focalLatLng!.longitude, Size.square(getTotalTileWidth(_zoomLevel))); + final Offset center = pixelFromLatLng( + _focalLatLng!.latitude, + _focalLatLng!.longitude, + Size.square(getTotalTileWidth(_zoomLevel)), + ); final Offset newOffset = Offset( - _zoomController!.parentRect!.width / 2 - center.dx, - _zoomController!.parentRect!.height / 2 - center.dy); + _zoomController!.parentRect!.width / 2 - center.dx, + _zoomController!.parentRect!.height / 2 - center.dy, + ); final Offset delta = newOffset - _zoomController!.actualRect.topLeft; if (delta != Offset.zero) { _zoomController!.actualRect = (_zoomController!.actualRect.topLeft + delta) & - _zoomController!.actualRect.size; + _zoomController!.actualRect.size; return; } } @@ -2669,32 +2738,51 @@ class MapZoomPanBehavior extends MapBehavior { properties.add(DoubleProperty('zoomLevel', zoomLevel)); properties.add(DoubleProperty('minZoomLevel', minZoomLevel)); properties.add(DoubleProperty('maxZoomLevel', maxZoomLevel)); - properties.add(FlagProperty('enablePanning', + properties.add( + FlagProperty( + 'enablePanning', value: enablePanning, ifTrue: 'Panning is enabled', - ifFalse: 'Panning is disabled')); - properties.add(FlagProperty('enablePinching', + ifFalse: 'Panning is disabled', + ), + ); + properties.add( + FlagProperty( + 'enablePinching', value: enablePinching, ifTrue: 'Pinching is enabled', - ifFalse: 'Pinching is disabled')); - properties.add(FlagProperty('enableDoubleTapZooming', + ifFalse: 'Pinching is disabled', + ), + ); + properties.add( + FlagProperty( + 'enableDoubleTapZooming', value: enableDoubleTapZooming, ifTrue: 'Double tap is enabled', - ifFalse: 'Double tap is disabled')); - properties.add(FlagProperty('enableMouseWheelZooming', + ifFalse: 'Double tap is disabled', + ), + ); + properties.add( + FlagProperty( + 'enableMouseWheelZooming', value: enableMouseWheelZooming, ifTrue: 'Mouse wheel is enabled', - ifFalse: 'Mouse wheel is disabled')); + ifFalse: 'Mouse wheel is disabled', + ), + ); properties.add(DiagnosticsProperty('focalLatLng', focalLatLng)); properties.add( - DiagnosticsProperty('latLngBounds', latLngBounds)); - properties.add(FlagProperty('showToolbar', + DiagnosticsProperty('latLngBounds', latLngBounds), + ); + properties.add( + FlagProperty( + 'showToolbar', value: showToolbar, ifTrue: 'Toolbar is enabled', - ifFalse: 'Toolbar is disabled')); - properties.add( - toolbarSettings.toDiagnosticsNode(name: 'toolbarSettings'), + ifFalse: 'Toolbar is disabled', + ), ); + properties.add(toolbarSettings.toDiagnosticsNode(name: 'toolbarSettings')); } } @@ -2702,10 +2790,7 @@ class MapZoomPanBehavior extends MapBehavior { @immutable class MapLatLng { /// Creates a [MapLatLng]. - const MapLatLng( - this.latitude, - this.longitude, - ); + const MapLatLng(this.latitude, this.longitude); /// The latitude in the maps. final double latitude; @@ -2735,8 +2820,10 @@ class MapLatLng { return null; } - return MapLatLng(a.latitude + (b.latitude - a.latitude) * t, - a.longitude + (b.longitude - a.longitude) * t); + return MapLatLng( + a.latitude + (b.latitude - a.latitude) * t, + a.longitude + (b.longitude - a.longitude) * t, + ); } @override @@ -2920,12 +3007,19 @@ class _BehaviorViewState extends State { late Rect? _initialRect; Offset _pixelFromLatLng(MapLatLng latLng, double scale) { - final double latitude = - latLng.latitude.clamp(minimumLatitude, maximumLatitude); - final double longitude = - latLng.longitude.clamp(minimumLongitude, maximumLongitude); + final double latitude = latLng.latitude.clamp( + minimumLatitude, + maximumLatitude, + ); + final double longitude = latLng.longitude.clamp( + minimumLongitude, + maximumLongitude, + ); return pixelFromLatLng( - latitude, longitude, Size.square(getTotalTileWidth(scale))); + latitude, + longitude, + Size.square(getTotalTileWidth(scale)), + ); } MapLatLng _pixelToLatLng(Offset point, double scale) { @@ -2941,17 +3035,23 @@ class _BehaviorViewState extends State { required Offset? pinchCenter, }) { newZoomLevel = newZoomLevel.clamp( - widget.behavior.minZoomLevel, widget.behavior.maxZoomLevel); + widget.behavior.minZoomLevel, + widget.behavior.maxZoomLevel, + ); final Rect previousVisibleBounds = Rect.fromCenter( center: _pixelFromLatLng( - widget.behavior.focalLatLng!, widget.behavior.zoomLevel), + widget.behavior.focalLatLng!, + widget.behavior.zoomLevel, + ), width: _size!.width, height: _size!.height, ); final MapLatLngBounds previousVisibleLatLngBounds = MapLatLngBounds( _pixelToLatLng(previousVisibleBounds.topRight, widget.behavior.zoomLevel), _pixelToLatLng( - previousVisibleBounds.bottomLeft, widget.behavior.zoomLevel), + previousVisibleBounds.bottomLeft, + widget.behavior.zoomLevel, + ), ); widget.controller ..localScale = scale @@ -2991,17 +3091,23 @@ class _BehaviorViewState extends State { void _handleToolbarZooming(double newZoomLevel) { newZoomLevel = newZoomLevel.clamp( - widget.behavior.minZoomLevel, widget.behavior.maxZoomLevel); + widget.behavior.minZoomLevel, + widget.behavior.maxZoomLevel, + ); final Rect previousVisibleBounds = Rect.fromCenter( center: _pixelFromLatLng( - widget.behavior.focalLatLng!, widget.behavior.zoomLevel), + widget.behavior.focalLatLng!, + widget.behavior.zoomLevel, + ), width: _size!.width, height: _size!.height, ); final MapLatLngBounds previousVisibleLatLngBounds = MapLatLngBounds( _pixelToLatLng(previousVisibleBounds.topRight, widget.behavior.zoomLevel), _pixelToLatLng( - previousVisibleBounds.bottomLeft, widget.behavior.zoomLevel), + previousVisibleBounds.bottomLeft, + widget.behavior.zoomLevel, + ), ); final Rect newVisibleBounds = Rect.fromCenter( @@ -3039,14 +3145,18 @@ class _BehaviorViewState extends State { }) { final Rect previousVisibleBounds = Rect.fromCenter( center: _pixelFromLatLng( - widget.behavior.focalLatLng!, widget.behavior.zoomLevel), + widget.behavior.focalLatLng!, + widget.behavior.zoomLevel, + ), width: _size!.width, height: _size!.height, ); final MapLatLngBounds previousVisibleLatLngBounds = MapLatLngBounds( _pixelToLatLng(previousVisibleBounds.topRight, widget.behavior.zoomLevel), _pixelToLatLng( - previousVisibleBounds.bottomLeft, widget.behavior.zoomLevel), + previousVisibleBounds.bottomLeft, + widget.behavior.zoomLevel, + ), ); final Rect newVisibleBounds = Rect.fromCenter( @@ -3083,10 +3193,13 @@ class _BehaviorViewState extends State { void _handleZoomableChange(ZoomPanDetails details) { final Offset focalPoint = Offset( - (_size!.width / 2) - details.actualRect.left, - (_size!.height / 2) - details.actualRect.top); + (_size!.width / 2) - details.actualRect.left, + (_size!.height / 2) - details.actualRect.top, + ); final MapLatLng newFocalLatLng = pixelToLatLng( - focalPoint, Size.square(getTotalTileWidth(details.newZoomLevel))); + focalPoint, + Size.square(getTotalTileWidth(details.newZoomLevel)), + ); _currentZoomLevel = details.newZoomLevel; _currentFocalLatLng = newFocalLatLng; @@ -3123,10 +3236,13 @@ class _BehaviorViewState extends State { bool _handleZoomableFling(ZoomPanDetails details) { final Offset focalPoint = Offset( - (_size!.width / 2) - details.actualRect.left, - (_size!.height / 2) - details.actualRect.top); + (_size!.width / 2) - details.actualRect.left, + (_size!.height / 2) - details.actualRect.top, + ); final MapLatLng newFocalLatLng = pixelToLatLng( - focalPoint, Size.square(getTotalTileWidth(details.newZoomLevel))); + focalPoint, + Size.square(getTotalTileWidth(details.newZoomLevel)), + ); _currentZoomLevel = details.newZoomLevel; _currentFocalLatLng = newFocalLatLng; bool canFling = false; @@ -3160,11 +3276,13 @@ class _BehaviorViewState extends State { Rect _getInitialRect() { widget.behavior._zoomController!.parentRect = Offset.zero & _size!; final double tileSize = getTotalTileWidth(_currentZoomLevel); - final Offset center = - _pixelFromLatLng(_currentFocalLatLng, _currentZoomLevel); + final Offset center = _pixelFromLatLng( + _currentFocalLatLng, + _currentZoomLevel, + ); final Rect initialRect = Offset(_size!.width / 2 - center.dx, _size!.height / 2 - center.dy) & - Size.square(tileSize); + Size.square(tileSize); return initialRect; } @@ -3252,9 +3370,10 @@ class BehaviorViewRenderObjectWidget extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderBehaviorView renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderBehaviorView renderObject, + ) { renderObject ..controller = controller ..zoomPanBehavior = zoomPanBehavior; @@ -3265,8 +3384,8 @@ class _RenderBehaviorView extends RenderBox implements MouseTrackerAnnotation { _RenderBehaviorView({ required MapController listener, required MapZoomPanBehavior zoomPanBehavior, - }) : controller = listener, - _zoomPanBehavior = zoomPanBehavior { + }) : controller = listener, + _zoomPanBehavior = zoomPanBehavior { _zoomPanBehavior._renderBox = this; _zoomPanBehavior._controller = controller; } @@ -3312,9 +3431,10 @@ class _RenderBehaviorView extends RenderBox implements MouseTrackerAnnotation { } @override - MouseCursor get cursor => controller.gesture == Gesture.pan - ? SystemMouseCursors.grabbing - : SystemMouseCursors.basic; + MouseCursor get cursor => + controller.gesture == Gesture.pan + ? SystemMouseCursors.grabbing + : SystemMouseCursors.basic; @override PointerEnterEventListener? get onEnter => _handleEnter; diff --git a/packages/syncfusion_flutter_maps/lib/src/common.dart b/packages/syncfusion_flutter_maps/lib/src/common.dart index 2b3304cc5..2c3bb84f8 100644 --- a/packages/syncfusion_flutter_maps/lib/src/common.dart +++ b/packages/syncfusion_flutter_maps/lib/src/common.dart @@ -38,7 +38,7 @@ enum PointerKind { touch, /// Indicates the pointer kind as hover. - hover + hover, } /// Provides the information about the current and previous zoom level. @@ -165,13 +165,13 @@ class MapModel { /// Base class for shape and tile layer for internal usage. class MapLayerInheritedWidget extends InheritedWidget { /// Creates [MapLayerInheritedWidget]. - const MapLayerInheritedWidget( - {super.key, - required Widget child, - required this.controller, - this.zoomController, - this.sublayers}) - : super(child: child); + const MapLayerInheritedWidget({ + super.key, + required Widget child, + required this.controller, + this.zoomController, + this.sublayers, + }) : super(child: child); /// Creates [MapController]. final MapController controller; @@ -209,10 +209,8 @@ class SublayerContainer extends Stack { /// Adds [MapSublayer] into a stack widget. class RenderSublayerContainer extends RenderStack { /// Creates a [RenderSublayerContainer]. - RenderSublayerContainer({ - required this.container, - required this.context, - }) : super(textDirection: Directionality.of(context)); + RenderSublayerContainer({required this.container, required this.context}) + : super(textDirection: Directionality.of(context)); /// The build context. final BuildContext context; @@ -238,9 +236,14 @@ class ShapeLayerChildRenderBoxBase extends RenderProxyBox { // Handle hover interaction here. } - void paintTooltip(int? elementIndex, Rect? elementRect, - MapLayerElement? element, PointerKind kind, - [int? sublayerIndex, Offset? position]) {} + void paintTooltip( + int? elementIndex, + Rect? elementRect, + MapLayerElement? element, + PointerKind kind, [ + int? sublayerIndex, + Offset? position, + ]) {} void onExit() { // Handle exit interaction here. @@ -278,18 +281,24 @@ class MapIconShape { iconSize = getPreferredSize(iconSize, themeData); final double halfIconWidth = iconSize.width / 2; final double halfIconHeight = iconSize.height / 2; - final bool hasStroke = strokeWidth > 0 && + final bool hasStroke = + strokeWidth > 0 && strokeColor != null && strokeColor != Colors.transparent; - final Paint paint = Paint() - ..isAntiAlias = true - ..color = color; + final Paint paint = + Paint() + ..isAntiAlias = true + ..color = color; Path path; switch (iconType) { case MapIconType.circle: final Rect rect = Rect.fromLTWH( - offset.dx, offset.dy, iconSize.width, iconSize.height); + offset.dx, + offset.dy, + iconSize.width, + iconSize.height, + ); context.canvas.drawOval(rect, paint); if (hasStroke) { paint @@ -301,7 +310,11 @@ class MapIconShape { break; case MapIconType.rectangle: final Rect rect = Rect.fromLTWH( - offset.dx, offset.dy, iconSize.width, iconSize.height); + offset.dx, + offset.dy, + iconSize.width, + iconSize.height, + ); context.canvas.drawRect(rect, paint); if (hasStroke) { paint @@ -312,11 +325,12 @@ class MapIconShape { } break; case MapIconType.triangle: - path = Path() - ..moveTo(offset.dx + halfIconWidth, offset.dy) - ..lineTo(offset.dx + iconSize.width, offset.dy + iconSize.height) - ..lineTo(offset.dx, offset.dy + iconSize.height) - ..close(); + path = + Path() + ..moveTo(offset.dx + halfIconWidth, offset.dy) + ..lineTo(offset.dx + iconSize.width, offset.dy + iconSize.height) + ..lineTo(offset.dx, offset.dy + iconSize.height) + ..close(); context.canvas.drawPath(path, paint); if (hasStroke) { paint @@ -327,12 +341,13 @@ class MapIconShape { } break; case MapIconType.diamond: - path = Path() - ..moveTo(offset.dx + halfIconWidth, offset.dy) - ..lineTo(offset.dx + iconSize.width, offset.dy + halfIconHeight) - ..lineTo(offset.dx + halfIconWidth, offset.dy + iconSize.height) - ..lineTo(offset.dx, offset.dy + halfIconHeight) - ..close(); + path = + Path() + ..moveTo(offset.dx + halfIconWidth, offset.dy) + ..lineTo(offset.dx + iconSize.width, offset.dy + halfIconHeight) + ..lineTo(offset.dx + halfIconWidth, offset.dy + iconSize.height) + ..lineTo(offset.dx, offset.dy + halfIconHeight) + ..close(); context.canvas.drawPath(path, paint); if (hasStroke) { paint diff --git a/packages/syncfusion_flutter_maps/lib/src/controller/layer_controller.dart b/packages/syncfusion_flutter_maps/lib/src/controller/layer_controller.dart index d13e2db58..2d6ffbb41 100644 --- a/packages/syncfusion_flutter_maps/lib/src/controller/layer_controller.dart +++ b/packages/syncfusion_flutter_maps/lib/src/controller/layer_controller.dart @@ -2,8 +2,8 @@ import 'package:flutter/foundation.dart'; import '../common.dart'; -typedef _ListenerEntry = void Function(MarkerAction action, - [List? indices]); +typedef _ListenerEntry = + void Function(MarkerAction action, [List? indices]); /// Base class of [MapShapeLayerController] and [MapTileLayerController]. abstract class MapLayerController extends ChangeNotifier { diff --git a/packages/syncfusion_flutter_maps/lib/src/controller/map_controller.dart b/packages/syncfusion_flutter_maps/lib/src/controller/map_controller.dart index f48a3937d..0c1ecc605 100644 --- a/packages/syncfusion_flutter_maps/lib/src/controller/map_controller.dart +++ b/packages/syncfusion_flutter_maps/lib/src/controller/map_controller.dart @@ -193,47 +193,65 @@ class MapController { translation ??= shapeLayerOffset; visibleFocalLatLng = getVisibleFocalLatLng(translation, factor); visibleBounds = getVisibleBounds(translation, factor, visibleFocalLatLng); - visibleLatLngBounds = getVisibleLatLngBounds(visibleBounds!.topRight, - visibleBounds!.bottomLeft, translation, factor); + visibleLatLngBounds = getVisibleLatLngBounds( + visibleBounds!.topRight, + visibleBounds!.bottomLeft, + translation, + factor, + ); } MapLatLng getVisibleFocalLatLng([Offset? translation, double? factor]) { factor ??= shapeLayerSizeFactor; translation ??= shapeLayerOffset; return pixelToLatLng( - Offset(shapeLayerBoxSize.width / 2, shapeLayerBoxSize.height / 2), - shapeLayerBoxSize, - translation, - factor); - } - - Rect getVisibleBounds( - [Offset? translation, double? factor, MapLatLng? focalLatLng]) { + Offset(shapeLayerBoxSize.width / 2, shapeLayerBoxSize.height / 2), + shapeLayerBoxSize, + translation, + factor, + ); + } + + Rect getVisibleBounds([ + Offset? translation, + double? factor, + MapLatLng? focalLatLng, + ]) { factor ??= shapeLayerSizeFactor; translation ??= shapeLayerOffset; focalLatLng ??= getVisibleFocalLatLng(translation, factor); return Rect.fromCenter( - center: pixelFromLatLng( - visibleFocalLatLng!.latitude, - visibleFocalLatLng!.longitude, - shapeLayerBoxSize, - translation, - factor), - width: shapeLayerBoxSize.width, - height: shapeLayerBoxSize.height); - } - - MapLatLngBounds getVisibleLatLngBounds(Offset topRight, Offset bottomLeft, - [Offset? translation, double? factor]) { + center: pixelFromLatLng( + visibleFocalLatLng!.latitude, + visibleFocalLatLng!.longitude, + shapeLayerBoxSize, + translation, + factor, + ), + width: shapeLayerBoxSize.width, + height: shapeLayerBoxSize.height, + ); + } + + MapLatLngBounds getVisibleLatLngBounds( + Offset topRight, + Offset bottomLeft, [ + Offset? translation, + double? factor, + ]) { factor ??= shapeLayerSizeFactor; translation ??= shapeLayerOffset; return MapLatLngBounds( - pixelToLatLng(topRight, shapeLayerBoxSize, translation, factor), - pixelToLatLng(bottomLeft, shapeLayerBoxSize, translation, factor)); + pixelToLatLng(topRight, shapeLayerBoxSize, translation, factor), + pixelToLatLng(bottomLeft, shapeLayerBoxSize, translation, factor), + ); } - Offset getZoomingTranslation( - {Offset? origin, double? scale, Offset? previousOrigin}) { + Offset getZoomingTranslation({ + Offset? origin, + double? scale, + Offset? previousOrigin, + }) { origin ??= pinchCenter; scale ??= localScale; previousOrigin ??= shapeLayerOffset; @@ -251,12 +269,17 @@ class MapController { return Size.square(256 * pow(2, zoomLevel).toDouble()); } - void applyTransform(PaintingContext context, Offset offset, - [bool isVectorLayer = false]) { + void applyTransform( + PaintingContext context, + Offset offset, [ + bool isVectorLayer = false, + ]) { if (isVectorLayer && layerType == LayerType.tile) { context.canvas - ..translate(offset.dx + tileCurrentLevelDetails.translatePoint.dx, - offset.dy + tileCurrentLevelDetails.translatePoint.dy) + ..translate( + offset.dx + tileCurrentLevelDetails.translatePoint.dx, + offset.dy + tileCurrentLevelDetails.translatePoint.dy, + ) ..scale(tileCurrentLevelDetails.scale); } else { switch (gesture) { @@ -264,20 +287,26 @@ class MapController { // Translating to the focal point // which we got from [ScaleUpdateDetails.localFocalPoint]. context.canvas - ..translate(offset.dx + pinchCenter.dx + normalize.dx, - offset.dy + pinchCenter.dy + normalize.dy) + ..translate( + offset.dx + pinchCenter.dx + normalize.dx, + offset.dy + pinchCenter.dy + normalize.dy, + ) ..scale(localScale) // Moving back to the original position to draw shapes. ..translate(-pinchCenter.dx, -pinchCenter.dy); break; case Gesture.pan: context.canvas.translate( - offset.dx + panDistance.dx, offset.dy + panDistance.dy); + offset.dx + panDistance.dx, + offset.dy + panDistance.dy, + ); break; // ignore: no_default_cases default: - context.canvas - .translate(offset.dx + normalize.dx, offset.dy + normalize.dy); + context.canvas.translate( + offset.dx + normalize.dx, + offset.dy + normalize.dy, + ); } } } diff --git a/packages/syncfusion_flutter_maps/lib/src/elements/bubble.dart b/packages/syncfusion_flutter_maps/lib/src/elements/bubble.dart index 69befd7a2..31d15da0c 100644 --- a/packages/syncfusion_flutter_maps/lib/src/elements/bubble.dart +++ b/packages/syncfusion_flutter_maps/lib/src/elements/bubble.dart @@ -82,16 +82,18 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { required this.dataLabelAnimationController, required this.toggleAnimationController, required this.hoverBubbleAnimationController, - }) : _source = source, - _bubbleSettings = bubbleSettings, - _legend = legend, - _themeData = themeData { + }) : _source = source, + _bubbleSettings = bubbleSettings, + _legend = legend, + _themeData = themeData { _bubbleAnimation = CurvedAnimation( parent: bubbleAnimationController, curve: const Interval(0.2, 1.0, curve: Curves.easeInOut), ); _toggleBubbleAnimation = CurvedAnimation( - parent: toggleAnimationController, curve: Curves.easeInOut); + parent: toggleAnimationController, + curve: Curves.easeInOut, + ); _forwardToggledBubbleColorTween = ColorTween(); _forwardToggledBubbleStrokeColorTween = ColorTween(); @@ -99,7 +101,9 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { _reverseToggledBubbleStrokeColorTween = ColorTween(); _toggleBubbleAnimation = CurvedAnimation( - parent: toggleAnimationController, curve: Curves.easeInOut); + parent: toggleAnimationController, + curve: Curves.easeInOut, + ); _forwardBubbleHoverColorTween = ColorTween(); _forwardBubbleHoverStrokeColorTween = ColorTween(); @@ -107,7 +111,9 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { _reverseBubbleHoverStrokeColorTween = ColorTween(); _hoverBubbleAnimation = CurvedAnimation( - parent: hoverBubbleAnimationController, curve: Curves.easeInOut); + parent: hoverBubbleAnimationController, + curve: Curves.easeInOut, + ); if (_legend != null && _legend!.enableToggleInteraction) { _initializeToggledBubbleTweenColors(); @@ -274,13 +280,19 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { if (_currentHoverItem != null) { _forwardBubbleHoverColorTween.begin = _currentHoverItem!.bubbleColor ?? defaultColor; - _forwardBubbleHoverColorTween.end = - _getHoverFillColor(opacity, defaultColor, _currentHoverItem!); + _forwardBubbleHoverColorTween.end = _getHoverFillColor( + opacity, + defaultColor, + _currentHoverItem!, + ); } if (_previousHoverItem != null) { - _reverseBubbleHoverColorTween.begin = - _getHoverFillColor(opacity, defaultColor, _previousHoverItem!); + _reverseBubbleHoverColorTween.begin = _getHoverFillColor( + opacity, + defaultColor, + _previousHoverItem!, + ); _reverseBubbleHoverColorTween.end = _previousHoverItem!.bubbleColor ?? defaultColor; } @@ -355,8 +367,9 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { void _initializeToggledBubbleTweenColors() { final Color? toggledBubbleColor = _themeData.toggledItemColor != Colors.transparent - ? _themeData.toggledItemColor! - .withValues(alpha: _legend!.toggledItemOpacity) + ? _themeData.toggledItemColor!.withValues( + alpha: _legend!.toggledItemOpacity, + ) : null; _forwardToggledBubbleColorTween.end = toggledBubbleColor; @@ -389,8 +402,9 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { void _updateToggledBubbleTweenColor() { late MapModel model; if (source.bubbleColorMappers == null) { - model = - mapDataSource.values.elementAt(controller!.currentToggledItemIndex); + model = mapDataSource.values.elementAt( + controller!.currentToggledItemIndex, + ); } else { for (final MapModel mapModel in mapDataSource.values) { if (mapModel.dataIndex != null && @@ -408,8 +422,12 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { @override void paint(PaintingContext context, Offset offset) { - final Rect bounds = - Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height); + final Rect bounds = Rect.fromLTWH( + offset.dx, + offset.dy, + size.width, + size.height, + ); context.canvas ..save() ..clipRect(bounds); @@ -419,9 +437,10 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { final Color defaultColor = bubbleSettings.color!.withValues(alpha: opacity); final bool hasToggledIndices = controller!.toggledIndices.isNotEmpty; final Paint fillPaint = Paint()..isAntiAlias = true; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; mapDataSource.forEach((String key, MapModel model) { if (model.bubbleSizeValue == null || @@ -430,16 +449,25 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { return; } - final double bubbleRadius = - _getDesiredValue(_bubbleAnimation.value * model.bubbleRadius!); + final double bubbleRadius = _getDesiredValue( + _bubbleAnimation.value * model.bubbleRadius!, + ); _updateFillColor(model, fillPaint, hasToggledIndices, defaultColor); if (fillPaint.color != Colors.transparent) { - context.canvas - .drawCircle(model.shapePathCenter!, bubbleRadius, fillPaint); + context.canvas.drawCircle( + model.shapePathCenter!, + bubbleRadius, + fillPaint, + ); } _drawBubbleStroke( - context, model, strokePaint, bubbleRadius, hasToggledIndices); + context, + model, + strokePaint, + bubbleRadius, + hasToggledIndices, + ); }); _drawHoveredBubble(context, opacity, defaultColor); @@ -450,16 +478,22 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { (controller!.gesture == Gesture.scale ? controller!.localScale : 1); } - void _drawBubbleStroke(PaintingContext context, MapModel model, - Paint strokePaint, double bubbleRadius, bool hasToggledIndices) { + void _drawBubbleStroke( + PaintingContext context, + MapModel model, + Paint strokePaint, + double bubbleRadius, + bool hasToggledIndices, + ) { if (hasToggledStroke || hasDefaultStroke) { _updateStrokePaint(model, strokePaint, hasToggledIndices, bubbleRadius); strokePaint.strokeWidth /= controller!.gesture == Gesture.scale ? controller!.localScale : 1; context.canvas.drawCircle( - model.shapePathCenter!, - _getDesiredRadius(bubbleRadius, strokePaint.strokeWidth), - strokePaint); + model.shapePathCenter!, + _getDesiredRadius(bubbleRadius, strokePaint.strokeWidth), + strokePaint, + ); } } @@ -471,8 +505,12 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { // Set color to the toggled and un-toggled bubbles based on // the [legendController.toggledIndices] collection. - void _updateFillColor(MapModel model, Paint fillPaint, bool hasToggledIndices, - Color defaultColor) { + void _updateFillColor( + MapModel model, + Paint fillPaint, + bool hasToggledIndices, + Color defaultColor, + ) { fillPaint.style = PaintingStyle.fill; if (_legend != null && _legend!.source == MapElement.bubble) { if (controller!.currentToggledItemIndex == model.legendMapperIndex) { @@ -480,9 +518,14 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { // legend item. If the legend item is toggled, then the // [_forwardToggledBubbleColorTween] return. If the legend item is // un-toggled, then the [_reverseToggledBubbleColorTween] return. - final Color? bubbleColor = controller!.wasToggled(model) - ? _forwardToggledBubbleColorTween.evaluate(_toggleBubbleAnimation) - : _reverseToggledBubbleColorTween.evaluate(_toggleBubbleAnimation); + final Color? bubbleColor = + controller!.wasToggled(model) + ? _forwardToggledBubbleColorTween.evaluate( + _toggleBubbleAnimation, + ) + : _reverseToggledBubbleColorTween.evaluate( + _toggleBubbleAnimation, + ); fillPaint.color = bubbleColor ?? Colors.transparent; return; } else if (hasToggledIndices && controller!.wasToggled(model)) { @@ -495,9 +538,10 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { if (_previousHoverItem != null && _previousHoverItem!.primaryKey == model.primaryKey) { - fillPaint.color = _themeData.bubbleHoverColor != Colors.transparent - ? _reverseBubbleHoverColorTween.evaluate(_hoverBubbleAnimation)! - : (_previousHoverItem!.bubbleColor ?? defaultColor); + fillPaint.color = + _themeData.bubbleHoverColor != Colors.transparent + ? _reverseBubbleHoverColorTween.evaluate(_hoverBubbleAnimation)! + : (_previousHoverItem!.bubbleColor ?? defaultColor); return; } fillPaint.color = model.bubbleColor ?? defaultColor; @@ -505,8 +549,12 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { // Set stroke paint to the toggled and un-toggled bubbles based on // the [legendController.toggledIndices] collection. - void _updateStrokePaint(MapModel model, Paint strokePaint, - bool hasToggledIndices, double bubbleRadius) { + void _updateStrokePaint( + MapModel model, + Paint strokePaint, + bool hasToggledIndices, + double bubbleRadius, + ) { strokePaint.style = PaintingStyle.stroke; if (_legend != null && _legend!.source == MapElement.bubble) { if (controller!.currentToggledItemIndex == model.legendMapperIndex) { @@ -516,14 +564,18 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { // If the legend item is un-toggled, then the // [_reverseToggledBubbleStrokeColorTween] return. strokePaint - ..color = controller!.wasToggled(model) - ? _forwardToggledBubbleStrokeColorTween - .evaluate(_toggleBubbleAnimation)! - : _reverseToggledBubbleStrokeColorTween - .evaluate(_toggleBubbleAnimation)! - ..strokeWidth = controller!.wasToggled(model) - ? _legend!.toggledItemStrokeWidth - : _bubbleSettings.strokeWidth!; + ..color = + controller!.wasToggled(model) + ? _forwardToggledBubbleStrokeColorTween.evaluate( + _toggleBubbleAnimation, + )! + : _reverseToggledBubbleStrokeColorTween.evaluate( + _toggleBubbleAnimation, + )! + ..strokeWidth = + controller!.wasToggled(model) + ? _legend!.toggledItemStrokeWidth + : _bubbleSettings.strokeWidth!; return; } else if (hasToggledIndices && controller!.wasToggled(model)) { // Set toggled stroke color to the previously toggled bubbles. @@ -540,8 +592,10 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { _themeData.bubbleHoverStrokeColor != Colors.transparent) { strokePaint ..style = PaintingStyle.stroke - ..color = _reverseBubbleHoverStrokeColorTween - .evaluate(_hoverBubbleAnimation)! + ..color = + _reverseBubbleHoverStrokeColorTween.evaluate( + _hoverBubbleAnimation, + )! ..strokeWidth = _themeData.bubbleStrokeWidth; return; } else if (hasDefaultStroke) { @@ -554,25 +608,37 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { } strokePaint ..color = _bubbleSettings.strokeColor! - ..strokeWidth = _bubbleSettings.strokeWidth! > bubbleRadius - ? bubbleRadius - : _bubbleSettings.strokeWidth!; + ..strokeWidth = + _bubbleSettings.strokeWidth! > bubbleRadius + ? bubbleRadius + : _bubbleSettings.strokeWidth!; } void _drawHoveredBubble( - PaintingContext context, double opacity, Color defaultColor) { + PaintingContext context, + double opacity, + Color defaultColor, + ) { if (_currentHoverItem != null) { - final double bubbleRadius = - _getDesiredValue(_currentHoverItem!.bubbleRadius!); + final double bubbleRadius = _getDesiredValue( + _currentHoverItem!.bubbleRadius!, + ); final Color defaultColor = bubbleSettings.color!; - final Paint paint = Paint() - ..style = PaintingStyle.fill - ..color = _themeData.bubbleHoverColor != Colors.transparent - ? _forwardBubbleHoverColorTween.evaluate(_hoverBubbleAnimation)! - : (_currentHoverItem!.bubbleColor ?? defaultColor); + final Paint paint = + Paint() + ..style = PaintingStyle.fill + ..color = + _themeData.bubbleHoverColor != Colors.transparent + ? _forwardBubbleHoverColorTween.evaluate( + _hoverBubbleAnimation, + )! + : (_currentHoverItem!.bubbleColor ?? defaultColor); if (paint.color != Colors.transparent) { context.canvas.drawCircle( - _currentHoverItem!.shapePathCenter!, bubbleRadius, paint); + _currentHoverItem!.shapePathCenter!, + bubbleRadius, + paint, + ); } _drawHoveredBubbleStroke(context, bubbleRadius); @@ -580,9 +646,10 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { } void _drawHoveredBubbleStroke(PaintingContext context, double bubbleRadius) { - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; if (_themeData.bubbleHoverStrokeWidth! > 0.0 && _themeData.bubbleHoverStrokeColor != Colors.transparent) { strokePaint @@ -598,11 +665,12 @@ class RenderMapBubble extends ShapeLayerChildRenderBoxBase { if (strokePaint.strokeWidth > 0.0 && strokePaint.color != Colors.transparent) { context.canvas.drawCircle( - _currentHoverItem!.shapePathCenter!, - strokePaint.strokeWidth > bubbleRadius - ? bubbleRadius / 2 - : bubbleRadius - strokePaint.strokeWidth / 2, - strokePaint); + _currentHoverItem!.shapePathCenter!, + strokePaint.strokeWidth > bubbleRadius + ? bubbleRadius / 2 + : bubbleRadius - strokePaint.strokeWidth / 2, + strokePaint, + ); } } } diff --git a/packages/syncfusion_flutter_maps/lib/src/elements/data_label.dart b/packages/syncfusion_flutter_maps/lib/src/elements/data_label.dart index d6ea0d80c..e36848ad4 100644 --- a/packages/syncfusion_flutter_maps/lib/src/elements/data_label.dart +++ b/packages/syncfusion_flutter_maps/lib/src/elements/data_label.dart @@ -45,9 +45,10 @@ class MapDataLabel extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderMapDataLabel renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderMapDataLabel renderObject, + ) { renderObject ..source = source ..mapDataSource = mapDataSource @@ -69,10 +70,10 @@ class _RenderMapDataLabel extends ShapeLayerChildRenderBoxBase { required this.controller, required this.dataLabelAnimationController, required MediaQueryData mediaQueryData, - }) : _settings = settings, - _effectiveTextStyle = effectiveTextStyle, - _themeData = themeData, - _mediaQueryData = mediaQueryData { + }) : _settings = settings, + _effectiveTextStyle = effectiveTextStyle, + _themeData = themeData, + _mediaQueryData = mediaQueryData { _effectiveTextScaleFactor = _mediaQueryData.textScaler; _textPainter = TextPainter(textDirection: TextDirection.ltr) @@ -142,7 +143,8 @@ class _RenderMapDataLabel extends ShapeLayerChildRenderBoxBase { } void _checkDataLabelColor() { - _isCustomTextColor = _settings.textStyle?.color != null || + _isCustomTextColor = + _settings.textStyle?.color != null || _themeData.dataLabelTextStyle?.color != null; } @@ -211,22 +213,29 @@ class _RenderMapDataLabel extends ShapeLayerChildRenderBoxBase { String? dataLabelText; final TextStyle textStyle = _effectiveTextStyle.copyWith( - color: _getAnimatedColor(_effectiveTextStyle.color)); + color: _getAnimatedColor(_effectiveTextStyle.color), + ); final bool hasMapper = source.dataLabelMapper != null; mapDataSource.forEach((String key, MapModel model) { - dataLabelText = controller!.isInInteractive - ? model.visibleDataLabelText - : hasMapper + dataLabelText = + controller!.isInInteractive + ? model.visibleDataLabelText + : hasMapper ? model.dataLabelText : model.primaryKey; if (dataLabelText == null) { return; } - final TextStyle desiredTextStyle = - _updateLuminanceColor(textStyle, _isCustomTextColor, model); - _textPainter.text = - TextSpan(style: desiredTextStyle, text: dataLabelText); + final TextStyle desiredTextStyle = _updateLuminanceColor( + textStyle, + _isCustomTextColor, + model, + ); + _textPainter.text = TextSpan( + style: desiredTextStyle, + text: dataLabelText, + ); _textPainter.layout(); if (!controller!.isInInteractive) { if (_settings.overflowMode == MapLabelOverflow.hide) { @@ -236,13 +245,16 @@ class _RenderMapDataLabel extends ShapeLayerChildRenderBoxBase { } } else if (_settings.overflowMode == MapLabelOverflow.ellipsis) { final String trimmedText = getTrimText( - dataLabelText!, - desiredTextStyle, - model.shapeWidth!, - _textPainter, - _textPainter.width); - _textPainter.text = - TextSpan(style: desiredTextStyle, text: trimmedText); + dataLabelText!, + desiredTextStyle, + model.shapeWidth!, + _textPainter, + _textPainter.width, + ); + _textPainter.text = TextSpan( + style: desiredTextStyle, + text: trimmedText, + ); _textPainter.layout(); } @@ -254,18 +266,24 @@ class _RenderMapDataLabel extends ShapeLayerChildRenderBoxBase { ..save() ..translate(model.shapePathCenter!.dx, model.shapePathCenter!.dy) ..scale(1 / controller!.localScale); - _textPainter.paint(context.canvas, - Offset(-_textPainter.width / 2, -_textPainter.height / 2)); + _textPainter.paint( + context.canvas, + Offset(-_textPainter.width / 2, -_textPainter.height / 2), + ); context.canvas.restore(); }); context.canvas.restore(); } TextStyle _updateLuminanceColor( - TextStyle style, bool isCustomTextStyle, MapModel model) { + TextStyle style, + bool isCustomTextStyle, + MapModel model, + ) { if (!isCustomTextStyle) { - final Brightness brightness = - ThemeData.estimateBrightnessForColor(_getActualShapeColor(model)); + final Brightness brightness = ThemeData.estimateBrightnessForColor( + _getActualShapeColor(model), + ); final Color color = brightness == Brightness.dark ? Colors.white : Colors.black; style = style.copyWith(color: _getAnimatedColor(color)); diff --git a/packages/syncfusion_flutter_maps/lib/src/elements/legend.dart b/packages/syncfusion_flutter_maps/lib/src/elements/legend.dart index 091d220cd..df6230fc2 100644 --- a/packages/syncfusion_flutter_maps/lib/src/elements/legend.dart +++ b/packages/syncfusion_flutter_maps/lib/src/elements/legend.dart @@ -19,8 +19,8 @@ enum _LegendType { } /// Signature to return a [Widget] for the given value. -typedef MapLegendPointerBuilder = Widget Function( - BuildContext context, dynamic value); +typedef MapLegendPointerBuilder = + Widget Function(BuildContext context, dynamic value); /// Shows legend for the bubbles or shapes. /// @@ -319,19 +319,19 @@ class MapLegend extends DiagnosticableTree { this.toggledItemStrokeColor, this.toggledItemStrokeWidth = 1.0, this.toggledItemOpacity = 0.5, - }) : _type = _LegendType.vector, - segmentSize = null, - labelsPlacement = null, - edgeLabelsPlacement = MapLegendEdgeLabelsPlacement.inside, - labelOverflow = MapLabelOverflow.visible, - segmentPaintingStyle = MapLegendPaintingStyle.solid, - showPointerOnHover = false, - pointerBuilder = null, - pointerColor = null, - pointerSize = Size.zero, - assert(spacing >= 0), - assert(toggledItemStrokeWidth >= 0), - assert(toggledItemOpacity >= 0 && toggledItemOpacity <= 1); + }) : _type = _LegendType.vector, + segmentSize = null, + labelsPlacement = null, + edgeLabelsPlacement = MapLegendEdgeLabelsPlacement.inside, + labelOverflow = MapLabelOverflow.visible, + segmentPaintingStyle = MapLegendPaintingStyle.solid, + showPointerOnHover = false, + pointerBuilder = null, + pointerColor = null, + pointerSize = Size.zero, + assert(spacing >= 0), + assert(toggledItemStrokeWidth >= 0), + assert(toggledItemOpacity >= 0 && toggledItemOpacity <= 1); /// Creates a bar type legend for the bubbles or shapes. /// @@ -481,15 +481,15 @@ class MapLegend extends DiagnosticableTree { this.pointerBuilder, this.pointerColor, this.pointerSize = const Size(16, 12), - }) : _type = _LegendType.bar, - enableToggleInteraction = false, - toggledItemColor = null, - toggledItemStrokeColor = null, - toggledItemStrokeWidth = 0.0, - toggledItemOpacity = 0.0, - iconType = MapIconType.circle, - iconSize = const Size(8.0, 8.0), - assert(spacing >= 0); + }) : _type = _LegendType.bar, + enableToggleInteraction = false, + toggledItemColor = null, + toggledItemStrokeColor = null, + toggledItemStrokeWidth = 0.0, + toggledItemOpacity = 0.0, + iconType = MapIconType.circle, + iconSize = const Size(8.0, 8.0), + assert(spacing >= 0); /// Shows legend for the bubbles or shapes. /// @@ -2027,24 +2027,24 @@ class MapLegend extends DiagnosticableTree { @override int get hashCode => Object.hash( - padding, - offset, - spacing, - direction, - overflowMode, - position, - textStyle, - enableToggleInteraction, - toggledItemColor, - toggledItemStrokeColor, - toggledItemStrokeWidth, - toggledItemOpacity, - source, - showPointerOnHover, - pointerBuilder, - pointerColor, - pointerSize, - ); + padding, + offset, + spacing, + direction, + overflowMode, + position, + textStyle, + enableToggleInteraction, + toggledItemColor, + toggledItemStrokeColor, + toggledItemStrokeWidth, + toggledItemOpacity, + source, + showPointerOnHover, + pointerBuilder, + pointerColor, + pointerSize, + ); /// Creates a copy of this class but with the given fields /// replaced with the new values. @@ -2134,8 +2134,9 @@ class MapLegend extends DiagnosticableTree { properties.add(EnumProperty('direction', direction)); } - properties - .add(EnumProperty('overflowMode', overflowMode)); + properties.add( + EnumProperty('overflowMode', overflowMode), + ); properties.add(EnumProperty('position', position)); if (textStyle != null) { properties.add(textStyle!.toDiagnosticsNode(name: 'textStyle')); @@ -2144,32 +2145,51 @@ class MapLegend extends DiagnosticableTree { if (_type == _LegendType.vector) { properties.add(DiagnosticsProperty('iconSize', iconSize)); properties.add(EnumProperty('iconType', iconType)); - properties.add(FlagProperty('enableToggleInteraction', + properties.add( + FlagProperty( + 'enableToggleInteraction', value: enableToggleInteraction, ifTrue: 'Toggle is enabled', - ifFalse: 'Toggle is disabled')); + ifFalse: 'Toggle is disabled', + ), + ); if (toggledItemColor != null) { properties.add(ColorProperty('toggledItemColor', toggledItemColor)); } if (toggledItemStrokeColor != null) { properties.add( - ColorProperty('toggledItemStrokeColor', toggledItemStrokeColor)); + ColorProperty('toggledItemStrokeColor', toggledItemStrokeColor), + ); } properties.add( - DoubleProperty('toggledItemStrokeWidth', toggledItemStrokeWidth)); + DoubleProperty('toggledItemStrokeWidth', toggledItemStrokeWidth), + ); properties.add(DoubleProperty('toggledItemOpacity', toggledItemOpacity)); } else { properties.add(DiagnosticsProperty('segmentSize', segmentSize)); - properties.add(EnumProperty( - 'labelsPlacement', labelsPlacement)); - properties.add(EnumProperty( - 'edgeLabelsPlacement', edgeLabelsPlacement)); properties.add( - EnumProperty('labelOverflowMode', labelOverflow)); - properties.add(EnumProperty( - 'segmentPaintingStyle', segmentPaintingStyle)); + EnumProperty( + 'labelsPlacement', + labelsPlacement, + ), + ); + properties.add( + EnumProperty( + 'edgeLabelsPlacement', + edgeLabelsPlacement, + ), + ); + properties.add( + EnumProperty('labelOverflowMode', labelOverflow), + ); + properties.add( + EnumProperty( + 'segmentPaintingStyle', + segmentPaintingStyle, + ), + ); } } } @@ -2186,8 +2206,8 @@ class Legend extends StatefulWidget { required this.child, required this.themeData, this.controller, - }) : assert(colorMappers != null || dataSource != null), - super(key: key); + }) : assert(colorMappers != null || dataSource != null), + super(key: key); // Collection of [MapColorMapper] which specifies map color based /// on the data. @@ -2234,16 +2254,19 @@ class _LegendState extends State { MapLegendLabelsPlacement.betweenItems) { if (index == 0) { final String startValue = _getStartSegmentLabel(colorMapper); - legendItems - .add(LegendItem(text: startValue, color: colorMapper.color)); + legendItems.add( + LegendItem(text: startValue, color: colorMapper.color), + ); } else { - final String text = colorMapper.text ?? + final String text = + colorMapper.text ?? colorMapper.value ?? colorMapper.to.toString(); legendItems.add(LegendItem(text: text, color: colorMapper.color)); } } else { - final String text = colorMapper.text ?? + final String text = + colorMapper.text ?? colorMapper.value ?? '${colorMapper.from} - ${colorMapper.to}'; legendItems.add(LegendItem(text: text, color: colorMapper.color)); @@ -2254,9 +2277,10 @@ class _LegendState extends State { legendItems.add( LegendItem( text: mapModel.primaryKey, - color: isLegendForBubbles - ? mapModel.bubbleColor ?? widget.themeData.bubbleColor - : mapModel.shapeColor ?? widget.themeData.layerColor, + color: + isLegendForBubbles + ? mapModel.bubbleColor ?? widget.themeData.bubbleColor + : mapModel.shapeColor ?? widget.themeData.layerColor, ), ); }); @@ -2301,7 +2325,8 @@ class _LegendState extends State { } LegendPaintingStyle _getEffectiveSegmentPaintingStyle( - MapLegendPaintingStyle paintingStyle) { + MapLegendPaintingStyle paintingStyle, + ) { switch (paintingStyle) { case MapLegendPaintingStyle.solid: return LegendPaintingStyle.solid; @@ -2311,7 +2336,8 @@ class _LegendState extends State { } LegendLabelOverflow _getEffectiveLabelOverflow( - MapLabelOverflow labelOverflow) { + MapLabelOverflow labelOverflow, + ) { switch (labelOverflow) { case MapLabelOverflow.visible: return LegendLabelOverflow.visible; @@ -2323,7 +2349,8 @@ class _LegendState extends State { } LegendEdgeLabelsPlacement _getEffectiveEdgeLabelsPlacement( - MapLegendEdgeLabelsPlacement edgeLabelsPlacement) { + MapLegendEdgeLabelsPlacement edgeLabelsPlacement, + ) { switch (edgeLabelsPlacement) { case MapLegendEdgeLabelsPlacement.center: return LegendEdgeLabelsPlacement.center; @@ -2333,7 +2360,8 @@ class _LegendState extends State { } LegendLabelsPlacement _getEffectiveLabelPlacement( - MapLegendLabelsPlacement labelsPlacement) { + MapLegendLabelsPlacement labelsPlacement, + ) { switch (labelsPlacement) { case MapLegendLabelsPlacement.betweenItems: return LegendLabelsPlacement.betweenItems; @@ -2356,7 +2384,8 @@ class _LegendState extends State { } LegendOverflowMode _getEffectiveOverflowMode( - MapLegendOverflowMode overflowMode) { + MapLegendOverflowMode overflowMode, + ) { switch (overflowMode) { case MapLegendOverflowMode.scroll: return LegendOverflowMode.scroll; @@ -2406,8 +2435,9 @@ class _LegendState extends State { Color? _getEffectiveToggledItemColor() { if (widget.themeData.toggledItemColor != Colors.transparent) { - return widget.themeData.toggledItemColor! - .withValues(alpha: widget.legend.toggledItemOpacity); + return widget.themeData.toggledItemColor!.withValues( + alpha: widget.legend.toggledItemOpacity, + ); } return widget.themeData.toggledItemColor; } @@ -2430,16 +2460,17 @@ class _LegendState extends State { iconType: _getEffectiveLegendIconType(widget.legend.iconType), iconSize: widget.legend.iconSize, toggledIndices: _toggledIndices, - onToggledIndicesChanged: widget.legend.enableToggleInteraction - ? (List indices, int currentIndex) { - setState(() { - widget.controller!.toggledIndices.clear(); - widget.controller!.toggledIndices.addAll(indices); - widget.controller!.currentToggledItemIndex = currentIndex; - _toggledIndices = indices; - }); - } - : null, + onToggledIndicesChanged: + widget.legend.enableToggleInteraction + ? (List indices, int currentIndex) { + setState(() { + widget.controller!.toggledIndices.clear(); + widget.controller!.toggledIndices.addAll(indices); + widget.controller!.currentToggledItemIndex = currentIndex; + _toggledIndices = indices; + }); + } + : null, toggledIconColor: _getEffectiveToggledItemColor(), toggledTextOpacity: widget.legend.toggledItemOpacity, child: widget.child, @@ -2456,20 +2487,25 @@ class _LegendState extends State { offset: widget.legend.offset, padding: widget.legend.padding, textStyle: widget.themeData.legendTextStyle, - labelsPlacement: - _getEffectiveLabelPlacement(_getActualLabelsPlacement()), + labelsPlacement: _getEffectiveLabelPlacement( + _getActualLabelsPlacement(), + ), edgeLabelsPlacement: _getEffectiveEdgeLabelsPlacement( - widget.legend.edgeLabelsPlacement), - labelOverflow: - _getEffectiveLabelOverflow(widget.legend.labelOverflow), + widget.legend.edgeLabelsPlacement, + ), + labelOverflow: _getEffectiveLabelOverflow( + widget.legend.labelOverflow, + ), segmentSize: widget.legend.segmentSize, segmentPaintingStyle: _getEffectiveSegmentPaintingStyle( - widget.legend.segmentPaintingStyle), + widget.legend.segmentPaintingStyle, + ), pointerBuilder: widget.legend.pointerBuilder, pointerColor: widget.legend.pointerColor, - pointerSize: widget.legend.showPointerOnHover - ? widget.legend.pointerSize - : Size.zero, + pointerSize: + widget.legend.showPointerOnHover + ? widget.legend.pointerSize + : Size.zero, pointerController: widget.pointerController, child: widget.child, ); diff --git a/packages/syncfusion_flutter_maps/lib/src/elements/marker.dart b/packages/syncfusion_flutter_maps/lib/src/elements/marker.dart index 27abbda30..98b386ab4 100644 --- a/packages/syncfusion_flutter_maps/lib/src/elements/marker.dart +++ b/packages/syncfusion_flutter_maps/lib/src/elements/marker.dart @@ -40,9 +40,10 @@ class MarkerContainer extends Stack { @override void updateRenderObject( - BuildContext context, - // ignore: library_private_types_in_public_api - _RenderMarkerContainer renderObject) { + BuildContext context, + // ignore: library_private_types_in_public_api + _RenderMarkerContainer renderObject, + ) { renderObject ..markerTooltipBuilder = markerTooltipBuilder ..themeData = themeData @@ -63,9 +64,10 @@ class _RenderMarkerContainer extends RenderStack { return container.children.indexOf(marker); } - Size get containerSize => controller.layerType == LayerType.tile - ? controller.getTileSize(controller.tileCurrentLevelDetails.zoomLevel) - : controller.shapeLayerBoxSize; + Size get containerSize => + controller.layerType == LayerType.tile + ? controller.getTileSize(controller.tileCurrentLevelDetails.zoomLevel) + : controller.shapeLayerBoxSize; void _handleZooming(MapZoomDetails details) { markNeedsLayout(); @@ -114,9 +116,10 @@ class _RenderMarkerContainer extends RenderStack { @override void performLayout() { - size = controller.layerType == LayerType.shape - ? controller.shapeLayerBoxSize - : controller.tileLayerBoxSize!; + size = + controller.layerType == LayerType.shape + ? controller.shapeLayerBoxSize + : controller.tileLayerBoxSize!; final double factor = getLayerSizeFactor(controller); final Offset translation = getTranslationOffset(controller); RenderBox? child = firstChild; @@ -127,22 +130,31 @@ class _RenderMarkerContainer extends RenderStack { // ignore: avoid_as child.parentData! as StackParentData; child.layout(constraints, parentUsesSize: true); - childParentData.offset = pixelFromLatLng(marker.latitude, - marker.longitude, containerSize, translation, factor); + childParentData.offset = pixelFromLatLng( + marker.latitude, + marker.longitude, + containerSize, + translation, + factor, + ); if (controller.layerType == LayerType.tile) { final TileZoomLevelDetails level = controller.tileCurrentLevelDetails; childParentData.offset = childParentData.offset.scale(level.scale, level.scale) + - level.translatePoint; + level.translatePoint; } - childParentData.offset -= - Offset(marker.size.width / 2, marker.size.height / 2); + childParentData.offset -= Offset( + marker.size.width / 2, + marker.size.height / 2, + ); if (marker.alignment != Alignment.center) { - final Alignment effectiveAlignment = - marker.alignment.resolve(textDirection); + final Alignment effectiveAlignment = marker.alignment.resolve( + textDirection, + ); childParentData.offset -= Offset( - effectiveAlignment.x * marker.size.width / 2, - effectiveAlignment.y * marker.size.height / 2); + effectiveAlignment.x * marker.size.width / 2, + effectiveAlignment.y * marker.size.height / 2, + ); } if (marker.offset != Offset.zero) { @@ -160,8 +172,12 @@ class _RenderMarkerContainer extends RenderStack { final StackParentData childParentData = // ignore: avoid_as child.parentData! as StackParentData; - final Rect childRect = Rect.fromLTWH(childParentData.offset.dx, - childParentData.offset.dy, child.size.width, child.size.height); + final Rect childRect = Rect.fromLTWH( + childParentData.offset.dx, + childParentData.offset.dy, + child.size.width, + child.size.height, + ); if (sublayer != null || controller.visibleBounds!.overlaps(childRect)) { context.paintChild(child, childParentData.offset); } @@ -920,15 +936,15 @@ class _RenderMapMarker extends RenderProxyBox required double? iconStrokeWidth, required MapIconType iconType, required this.marker, - }) : _longitude = longitude, - _latitude = latitude, - _markerSize = markerSize, - _alignment = alignment, - _offset = offset, - _iconColor = iconColor, - _iconStrokeColor = iconStrokeColor, - _iconStrokeWidth = iconStrokeWidth, - _iconType = iconType { + }) : _longitude = longitude, + _latitude = latitude, + _markerSize = markerSize, + _alignment = alignment, + _offset = offset, + _iconColor = iconColor, + _iconStrokeColor = iconStrokeColor, + _iconStrokeWidth = iconStrokeWidth, + _iconType = iconType { _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; } @@ -1051,8 +1067,9 @@ class _RenderMapMarker extends RenderProxyBox if (markerContainer.markerTooltipBuilder != null) { final ShapeLayerChildRenderBoxBase tooltipRenderBox = markerContainer.controller.tooltipKey!.currentContext! - // ignore: avoid_as - .findRenderObject()! as ShapeLayerChildRenderBoxBase; + // ignore: avoid_as + .findRenderObject()! + as ShapeLayerChildRenderBoxBase; tooltipRenderBox.hideTooltip(); } } @@ -1067,24 +1084,28 @@ class _RenderMapMarker extends RenderProxyBox if (markerContainerRenderBox.markerTooltipBuilder != null) { if (markerContainerRenderBox.sublayer != null) { sublayerIndex = markerContainerRenderBox - .container.ancestor!.sublayers! + .container + .ancestor! + .sublayers! .indexOf(markerContainerRenderBox.sublayer!); } final ShapeLayerChildRenderBoxBase tooltipRenderBox = markerContainerRenderBox.controller.tooltipKey!.currentContext! - // ignore: avoid_as - .findRenderObject()! as ShapeLayerChildRenderBoxBase; + // ignore: avoid_as + .findRenderObject()! + as ShapeLayerChildRenderBoxBase; // ignore: avoid_as final StackParentData childParentData = parentData! as StackParentData; tooltipRenderBox.paintTooltip( - markerContainerRenderBox.getMarkerIndex(marker), - childParentData.offset & size, - MapLayerElement.marker, - kind, - // [sublayerIndex] is applicable only when the markers - // added to the [MapShapeSublayer]. - sublayerIndex); + markerContainerRenderBox.getMarkerIndex(marker), + childParentData.offset & size, + MapLayerElement.marker, + kind, + // [sublayerIndex] is applicable only when the markers + // added to the [MapShapeSublayer]. + sublayerIndex, + ); } } } @@ -1170,12 +1191,15 @@ class _RenderMapMarker extends RenderProxyBox parent! as _RenderMarkerContainer; if (child == null) { core.paint( - canvas: context.canvas, - rect: paintBounds, - shapeType: _getEffectiveShapeType(), - paint: Paint() - ..color = _iconColor ?? markerContainer.themeData.markerIconColor!, - borderPaint: _getBorderPaint()); + canvas: context.canvas, + rect: paintBounds, + shapeType: _getEffectiveShapeType(), + paint: + Paint() + ..color = + _iconColor ?? markerContainer.themeData.markerIconColor!, + borderPaint: _getBorderPaint(), + ); } else { context.paintChild(child!, offset); } diff --git a/packages/syncfusion_flutter_maps/lib/src/elements/toolbar.dart b/packages/syncfusion_flutter_maps/lib/src/elements/toolbar.dart index 6b42b75f1..8b0ed766f 100644 --- a/packages/syncfusion_flutter_maps/lib/src/elements/toolbar.dart +++ b/packages/syncfusion_flutter_maps/lib/src/elements/toolbar.dart @@ -123,15 +123,18 @@ class _ToolbarItemState extends State<_ToolbarItem> { bool enabled; switch (widget.icon) { case _ToolbarIcon.zoomIn: - enabled = widget.zoomPanBehavior.zoomLevel != + enabled = + widget.zoomPanBehavior.zoomLevel != widget.zoomPanBehavior.maxZoomLevel; break; case _ToolbarIcon.zoomOut: - enabled = widget.zoomPanBehavior.zoomLevel != + enabled = + widget.zoomPanBehavior.zoomLevel != widget.zoomPanBehavior.minZoomLevel; break; case _ToolbarIcon.reset: - enabled = widget.zoomPanBehavior.zoomLevel != + enabled = + widget.zoomPanBehavior.zoomLevel != widget.zoomPanBehavior.minZoomLevel; break; } @@ -198,9 +201,10 @@ class _ToolbarItemState extends State<_ToolbarItem> { offset: const Offset(0.0, 2.0), ), ], - color: _isLightTheme - ? const Color.fromARGB(255, 250, 250, 250) - : const Color.fromARGB(255, 66, 66, 66), + color: + _isLightTheme + ? const Color.fromARGB(255, 250, 250, 250) + : const Color.fromARGB(255, 66, 66, 66), ), child: Container( height: _toolbarItemSize.height, @@ -215,19 +219,22 @@ class _ToolbarItemState extends State<_ToolbarItem> { highlightColor: Colors.transparent, hoverColor: Colors.transparent, splashColor: Colors.transparent, - disabledColor: _isLightTheme - ? const Color.fromRGBO(0, 0, 0, 0.24) - : const Color.fromRGBO(255, 255, 255, 0.24), + disabledColor: + _isLightTheme + ? const Color.fromRGBO(0, 0, 0, 0.24) + : const Color.fromRGBO(255, 255, 255, 0.24), icon: Icon(widget.iconData), - color: widget.zoomPanBehavior.toolbarSettings.iconColor ?? + color: + widget.zoomPanBehavior.toolbarSettings.iconColor ?? (_isLightTheme ? const Color.fromRGBO(0, 0, 0, 0.54) : const Color.fromRGBO(255, 255, 255, 0.54)), - onPressed: _enabled - ? () { - _handlePointerUp(); - } - : null, + onPressed: + _enabled + ? () { + _handlePointerUp(); + } + : null, mouseCursor: _enabled ? SystemMouseCursors.click : SystemMouseCursors.basic, tooltip: widget.tooltipText, @@ -263,8 +270,10 @@ class _ToolbarItemState extends State<_ToolbarItem> { break; } - newZoomLevel = newZoomLevel.clamp(widget.zoomPanBehavior.minZoomLevel, - widget.zoomPanBehavior.maxZoomLevel); + newZoomLevel = newZoomLevel.clamp( + widget.zoomPanBehavior.minZoomLevel, + widget.zoomPanBehavior.maxZoomLevel, + ); if (widget.controller != null && newZoomLevel != widget.zoomPanBehavior.zoomLevel) { widget.controller!.notifyToolbarZoomedListeners(newZoomLevel); diff --git a/packages/syncfusion_flutter_maps/lib/src/elements/tooltip.dart b/packages/syncfusion_flutter_maps/lib/src/elements/tooltip.dart index 951bb90fd..e4af2baea 100644 --- a/packages/syncfusion_flutter_maps/lib/src/elements/tooltip.dart +++ b/packages/syncfusion_flutter_maps/lib/src/elements/tooltip.dart @@ -108,7 +108,9 @@ class _MapTooltipState extends State void initState() { super.initState(); controller = AnimationController( - vsync: this, duration: const Duration(milliseconds: 200)); + vsync: this, + duration: const Duration(milliseconds: 200), + ); } @override @@ -120,7 +122,8 @@ class _MapTooltipState extends State @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - isDesktop = kIsWeb || + isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -163,7 +166,9 @@ class _MapTooltipRenderObjectWidget extends SingleChildRenderObjectWidget { @override void updateRenderObject( - BuildContext context, _RenderMapTooltip renderObject) { + BuildContext context, + _RenderMapTooltip renderObject, + ) { renderObject ..source = source ..tooltipSettings = tooltipSettings @@ -181,13 +186,15 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { required MediaQueryData mediaQueryData, required this.context, required _MapTooltipState state, - }) : _source = source, - _tooltipSettings = tooltipSettings, - _themeData = themeData, - _mediaQueryData = mediaQueryData, - _state = state { - _scaleAnimation = - CurvedAnimation(parent: _state.controller, curve: Curves.easeOutBack); + }) : _source = source, + _tooltipSettings = tooltipSettings, + _themeData = themeData, + _mediaQueryData = mediaQueryData, + _state = state { + _scaleAnimation = CurvedAnimation( + parent: _state.controller, + curve: Curves.easeOutBack, + ); } static const double tooltipTriangleHeight = 7; @@ -247,8 +254,12 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { hideTooltip(immediately: true); } - void _update(Offset? position, int? index, MapLayerElement? element, - int? sublayerIndex) { + void _update( + Offset? position, + int? index, + MapLayerElement? element, + int? sublayerIndex, + ) { if (index != null) { _state.adoptChild(index, element!, sublayerIndex: sublayerIndex); _currentPosition = position; @@ -287,7 +298,9 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { _showTimer?.cancel(); if (_pointerKind == PointerKind.touch) { _showTimer = Timer( - Duration(seconds: _tooltipSettings.hideDelay.toInt()), hideTooltip); + Duration(seconds: _tooltipSettings.hideDelay.toInt()), + hideTooltip, + ); } } @@ -301,8 +314,13 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { immediately ? _state.controller.reset() : _state.controller.reverse(); } - void _updateTooltipIfNeeded(Offset? position, int? index, Rect? elementRect, - MapLayerElement? element, int? sublayerIndex) { + void _updateTooltipIfNeeded( + Offset? position, + int? index, + Rect? elementRect, + MapLayerElement? element, + int? sublayerIndex, + ) { if (sublayerIndex == _previousSublayerIndex && element != MapLayerElement.shape && element != MapLayerElement.vector && @@ -338,12 +356,22 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { } @override - void paintTooltip(int? elementIndex, Rect? elementRect, - MapLayerElement? element, PointerKind kind, - [int? sublayerIndex, Offset? position]) { + void paintTooltip( + int? elementIndex, + Rect? elementRect, + MapLayerElement? element, + PointerKind kind, [ + int? sublayerIndex, + Offset? position, + ]) { _pointerKind = kind; _updateTooltipIfNeeded( - position, elementIndex, elementRect, element, sublayerIndex); + position, + elementIndex, + elementRect, + element, + sublayerIndex, + ); } @override @@ -411,14 +439,15 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { } _tooltipShape.paint( - context, - offset, - _currentPosition!, - _preferTooltipOnTop, - this, - _scaleAnimation, - _themeData, - _tooltipSettings); + context, + offset, + _currentPosition!, + _preferTooltipOnTop, + this, + _scaleAnimation, + _themeData, + _tooltipSettings, + ); } } @@ -433,23 +462,29 @@ class _RenderMapTooltip extends ShapeLayerChildRenderBoxBase { _updateElementRect(bounds); } final double halfRectWidth = _elementRect!.width / 2; - Offset tooltipPosition = _elementRect!.topLeft + + Offset tooltipPosition = + _elementRect!.topLeft + Offset(halfRectWidth, _elementRect!.height * tooltipHeightFactor); _preferTooltipOnTop = bounds.contains( - tooltipPosition - Offset(0.0, tooltipHeight + tooltipTriangleHeight)); + tooltipPosition - Offset(0.0, tooltipHeight + tooltipTriangleHeight), + ); if (!_preferTooltipOnTop) { // To get the tooltip position at bottom based on the current rect, // we had subtracted 1 with the tooltipHeightFactor. - tooltipPosition = _elementRect!.topLeft + - Offset(halfRectWidth, - _elementRect!.height * (1 - tooltipHeightFactor)); + tooltipPosition = + _elementRect!.topLeft + + Offset( + halfRectWidth, + _elementRect!.height * (1 - tooltipHeightFactor), + ); } _currentPosition = tooltipPosition; } // For shape. else { - _preferTooltipOnTop = bounds.contains(_currentPosition! - - Offset(0.0, tooltipHeight + tooltipTriangleHeight)); + _preferTooltipOnTop = bounds.contains( + _currentPosition! - Offset(0.0, tooltipHeight + tooltipTriangleHeight), + ); } } @@ -483,21 +518,23 @@ class _TooltipShape { /// Paints the tooltip shapes based on the value passed to it. void paint( - PaintingContext context, - Offset offset, - Offset center, - bool preferTooltipOnTop, - RenderProxyBox parentBox, - Animation tooltipAnimation, - SfMapsThemeData themeData, - MapTooltipSettings tooltipSettings) { + PaintingContext context, + Offset offset, + Offset center, + bool preferTooltipOnTop, + RenderProxyBox parentBox, + Animation tooltipAnimation, + SfMapsThemeData themeData, + MapTooltipSettings tooltipSettings, + ) { const double tooltipTriangleWidth = 12.0; const double halfTooltipTriangleWidth = tooltipTriangleWidth / 2; const double elevation = 0.0; Path path = Path(); - BorderRadius borderRadius = - themeData.tooltipBorderRadius.resolve(TextDirection.ltr); + BorderRadius borderRadius = themeData.tooltipBorderRadius.resolve( + TextDirection.ltr, + ); final double tooltipWidth = parentBox.child!.size.width; double tooltipHeight = parentBox.child!.size.height; final double halfTooltipWidth = tooltipWidth / 2; @@ -508,29 +545,36 @@ class _TooltipShape { double tooltipTriangleOffsetY = tooltipStartPoint - triangleHeight; final double endGlobal = parentBox.size.width - marginSpace; - double rightLineWidth = center.dx + halfTooltipWidth > endGlobal - ? endGlobal - center.dx - : halfTooltipWidth; - final double leftLineWidth = center.dx - halfTooltipWidth < marginSpace - ? center.dx - marginSpace - : tooltipWidth - rightLineWidth; - rightLineWidth = leftLineWidth < halfTooltipWidth - ? halfTooltipWidth - leftLineWidth + rightLineWidth - : rightLineWidth; - - double moveNosePoint = leftLineWidth < tooltipWidth * 0.2 - ? tooltipWidth * 0.2 - leftLineWidth - : 0.0; - moveNosePoint = rightLineWidth < tooltipWidth * 0.2 - ? -(tooltipWidth * 0.2 - rightLineWidth) - : moveNosePoint; - - double shiftText = leftLineWidth > rightLineWidth - ? -(halfTooltipWidth - rightLineWidth) - : 0.0; - shiftText = leftLineWidth < rightLineWidth - ? (halfTooltipWidth - leftLineWidth) - : shiftText; + double rightLineWidth = + center.dx + halfTooltipWidth > endGlobal + ? endGlobal - center.dx + : halfTooltipWidth; + final double leftLineWidth = + center.dx - halfTooltipWidth < marginSpace + ? center.dx - marginSpace + : tooltipWidth - rightLineWidth; + rightLineWidth = + leftLineWidth < halfTooltipWidth + ? halfTooltipWidth - leftLineWidth + rightLineWidth + : rightLineWidth; + + double moveNosePoint = + leftLineWidth < tooltipWidth * 0.2 + ? tooltipWidth * 0.2 - leftLineWidth + : 0.0; + moveNosePoint = + rightLineWidth < tooltipWidth * 0.2 + ? -(tooltipWidth * 0.2 - rightLineWidth) + : moveNosePoint; + + double shiftText = + leftLineWidth > rightLineWidth + ? -(halfTooltipWidth - rightLineWidth) + : 0.0; + shiftText = + leftLineWidth < rightLineWidth + ? (halfTooltipWidth - leftLineWidth) + : shiftText; rightLineWidth = rightLineWidth + elevation; if (!preferTooltipOnTop) { @@ -545,44 +589,56 @@ class _TooltipShape { tooltipHeight *= -1; borderRadius = BorderRadius.only( topRight: Radius.elliptical( - borderRadius.bottomRight.x, -borderRadius.bottomRight.y), + borderRadius.bottomRight.x, + -borderRadius.bottomRight.y, + ), bottomRight: Radius.elliptical( - borderRadius.topRight.x, -borderRadius.topRight.y), + borderRadius.topRight.x, + -borderRadius.topRight.y, + ), topLeft: Radius.elliptical( - borderRadius.bottomLeft.x, -borderRadius.bottomLeft.y), - bottomLeft: - Radius.elliptical(borderRadius.topLeft.x, -borderRadius.topLeft.y), + borderRadius.bottomLeft.x, + -borderRadius.bottomLeft.y, + ), + bottomLeft: Radius.elliptical( + borderRadius.topLeft.x, + -borderRadius.topLeft.y, + ), ); } path = _getTooltipPath( - path, - triangleHeight, - halfTooltipHeight, - halfTooltipTriangleWidth, - tooltipTriangleOffsetY, - moveNosePoint, - rightLineWidth, - leftLineWidth, - borderRadius, - tooltipHeight); + path, + triangleHeight, + halfTooltipHeight, + halfTooltipTriangleWidth, + tooltipTriangleOffsetY, + moveNosePoint, + rightLineWidth, + leftLineWidth, + borderRadius, + tooltipHeight, + ); context.canvas.save(); - context.canvas - .translate(center.dx, center.dy - triangleHeight - halfTooltipHeight); + context.canvas.translate( + center.dx, + center.dy - triangleHeight - halfTooltipHeight, + ); context.canvas.scale(tooltipAnimation.value); // In web HTML rendering, fill color clipped half of its tooltip's size. // To avoid this issue we are drawing stroke before fill. final Color? strokeColor = tooltipSettings.strokeColor ?? themeData.tooltipStrokeColor; - final Paint paint = Paint() - ..color = strokeColor ?? Colors.transparent - // We are drawing stroke before fill to avoid tooltip rendering issue - // in a web HTML rendering. Due to this, half of the stroke width only - // visible to us so that we are twice the stroke width. - ..strokeWidth = - (tooltipSettings.strokeWidth ?? themeData.tooltipStrokeWidth) * 2 - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = strokeColor ?? Colors.transparent + // We are drawing stroke before fill to avoid tooltip rendering issue + // in a web HTML rendering. Due to this, half of the stroke width only + // visible to us so that we are twice the stroke width. + ..strokeWidth = + (tooltipSettings.strokeWidth ?? themeData.tooltipStrokeWidth) * 2 + ..style = PaintingStyle.stroke; // Drawing stroke. context.canvas.drawPath(path, paint); // Drawing fill color. @@ -592,22 +648,25 @@ class _TooltipShape { context.canvas.drawPath(path, paint); context.canvas.clipPath(path); - context.paintChild(parentBox.child!, - offset - _getShiftPosition(offset, center, parentBox)); + context.paintChild( + parentBox.child!, + offset - _getShiftPosition(offset, center, parentBox), + ); context.canvas.restore(); } Path _getTooltipPath( - Path path, - double tooltipTriangleHeight, - double halfTooltipHeight, - double halfTooltipTriangleWidth, - double tooltipTriangleOffsetY, - double moveNosePoint, - double rightLineWidth, - double leftLineWidth, - BorderRadius borderRadius, - double tooltipHeight) { + Path path, + double tooltipTriangleHeight, + double halfTooltipHeight, + double halfTooltipTriangleWidth, + double tooltipTriangleOffsetY, + double moveNosePoint, + double rightLineWidth, + double leftLineWidth, + BorderRadius borderRadius, + double tooltipHeight, + ) { path.reset(); path.moveTo(0, tooltipTriangleHeight + halfTooltipHeight); @@ -617,7 +676,9 @@ class _TooltipShape { // preferTooltipOnTop is false, // \ path.lineTo( - halfTooltipTriangleWidth + moveNosePoint, tooltipTriangleOffsetY); + halfTooltipTriangleWidth + moveNosePoint, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ___ // / @@ -625,7 +686,9 @@ class _TooltipShape { // preferTooltipOnTop is false, // \___ path.lineTo( - rightLineWidth - borderRadius.bottomRight.x, tooltipTriangleOffsetY); + rightLineWidth - borderRadius.bottomRight.x, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ___| // / @@ -633,10 +696,16 @@ class _TooltipShape { // preferTooltipOnTop is false, // \___ // | - path.quadraticBezierTo(rightLineWidth, tooltipTriangleOffsetY, - rightLineWidth, tooltipTriangleOffsetY - borderRadius.bottomRight.y); - path.lineTo(rightLineWidth, - tooltipTriangleOffsetY - tooltipHeight + borderRadius.topRight.y); + path.quadraticBezierTo( + rightLineWidth, + tooltipTriangleOffsetY, + rightLineWidth, + tooltipTriangleOffsetY - borderRadius.bottomRight.y, + ); + path.lineTo( + rightLineWidth, + tooltipTriangleOffsetY - tooltipHeight + borderRadius.topRight.y, + ); // preferTooltipOnTop is true, // _______ // ___| @@ -646,12 +715,15 @@ class _TooltipShape { // \___ // ________| path.quadraticBezierTo( - rightLineWidth, - tooltipTriangleOffsetY - tooltipHeight, - rightLineWidth - borderRadius.topRight.x, - tooltipTriangleOffsetY - tooltipHeight); - path.lineTo(-leftLineWidth + borderRadius.topLeft.x, - tooltipTriangleOffsetY - tooltipHeight); + rightLineWidth, + tooltipTriangleOffsetY - tooltipHeight, + rightLineWidth - borderRadius.topRight.x, + tooltipTriangleOffsetY - tooltipHeight, + ); + path.lineTo( + -leftLineWidth + borderRadius.topLeft.x, + tooltipTriangleOffsetY - tooltipHeight, + ); // preferTooltipOnTop is true, // _______ // | ___| @@ -661,12 +733,15 @@ class _TooltipShape { // \___ // |________| path.quadraticBezierTo( - -leftLineWidth, - tooltipTriangleOffsetY - tooltipHeight, - -leftLineWidth, - tooltipTriangleOffsetY - tooltipHeight + borderRadius.topLeft.y); + -leftLineWidth, + tooltipTriangleOffsetY - tooltipHeight, + -leftLineWidth, + tooltipTriangleOffsetY - tooltipHeight + borderRadius.topLeft.y, + ); path.lineTo( - -leftLineWidth, tooltipTriangleOffsetY - borderRadius.bottomLeft.y); + -leftLineWidth, + tooltipTriangleOffsetY - borderRadius.bottomLeft.y, + ); // preferTooltipOnTop is true, // ________ // |___ ___| @@ -675,10 +750,16 @@ class _TooltipShape { // preferTooltipOnTop is false, // ___ \___ // |________| - path.quadraticBezierTo(-leftLineWidth, tooltipTriangleOffsetY, - -leftLineWidth + borderRadius.bottomLeft.x, tooltipTriangleOffsetY); + path.quadraticBezierTo( + -leftLineWidth, + tooltipTriangleOffsetY, + -leftLineWidth + borderRadius.bottomLeft.x, + tooltipTriangleOffsetY, + ); path.lineTo( - -halfTooltipTriangleWidth + moveNosePoint, tooltipTriangleOffsetY); + -halfTooltipTriangleWidth + moveNosePoint, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ________ // |___ ___| @@ -693,7 +774,10 @@ class _TooltipShape { } Offset _getShiftPosition( - Offset offset, Offset center, RenderProxyBox parent) { + Offset offset, + Offset center, + RenderProxyBox parent, + ) { final Size childSize = parent.child!.size; final double halfChildWidth = childSize.width / 2; final double halfChildHeight = childSize.height / 2; @@ -702,8 +786,9 @@ class _TooltipShape { // edge goes out of the map's right edge. if (center.dx + halfChildWidth + marginSpace > parent.size.width) { return Offset( - childSize.width + center.dx - parent.size.width + marginSpace, - halfChildHeight); + childSize.width + center.dx - parent.size.width + marginSpace, + halfChildHeight, + ); } // Shifting the position of the tooltip to the right side, if its left // edge goes out of the map's left edge. diff --git a/packages/syncfusion_flutter_maps/lib/src/enum.dart b/packages/syncfusion_flutter_maps/lib/src/enum.dart index b0d4055c7..ef78a6657 100644 --- a/packages/syncfusion_flutter_maps/lib/src/enum.dart +++ b/packages/syncfusion_flutter_maps/lib/src/enum.dart @@ -47,7 +47,7 @@ enum MapLabelOverflow { /// It trims the labels based on the available space in their respective /// shape. - ellipsis + ellipsis, } /// Shows legend for the shapes or the bubbles. @@ -71,7 +71,7 @@ enum MapToolbarPosition { bottomLeft, /// Positions the toolbar on right bottom. - bottomRight + bottomRight, } /// Option to place the labels either between the bars or on the bar in bar @@ -81,7 +81,7 @@ enum MapLegendLabelsPlacement { onItem, /// [MapLegendLabelsPlacement.betweenItems] places labels in-between two bars. - betweenItems + betweenItems, } /// Placement of edge labels in the bar legend. @@ -91,7 +91,7 @@ enum MapLegendEdgeLabelsPlacement { /// Place the edge labels in the center of the starting position of the /// legend bars. - center + center, } /// Applies gradient or solid color for the bar segments. @@ -100,5 +100,5 @@ enum MapLegendPaintingStyle { solid, /// Applies gradient color for bar segments. - gradient + gradient, } diff --git a/packages/syncfusion_flutter_maps/lib/src/layer/shape_layer.dart b/packages/syncfusion_flutter_maps/lib/src/layer/shape_layer.dart index 6d3d7a06b..007897fc7 100644 --- a/packages/syncfusion_flutter_maps/lib/src/layer/shape_layer.dart +++ b/packages/syncfusion_flutter_maps/lib/src/layer/shape_layer.dart @@ -164,18 +164,24 @@ class MapShapeSource extends DiagnosticableTree { this.bubbleSizeMapper, this.shapeColorValueMapper, this.bubbleColorValueMapper, - }) : _path = name, - _type = GeoJSONSourceType.asset, - assert((primaryValueMapper != null && dataCount > 0) || - primaryValueMapper == null), - assert((shapeColorMappers != null && - primaryValueMapper != null && - shapeColorValueMapper != null) || - shapeColorMappers == null), - assert((bubbleColorMappers != null && - primaryValueMapper != null && - bubbleColorValueMapper != null) || - bubbleColorMappers == null); + }) : _path = name, + _type = GeoJSONSourceType.asset, + assert( + (primaryValueMapper != null && dataCount > 0) || + primaryValueMapper == null, + ), + assert( + (shapeColorMappers != null && + primaryValueMapper != null && + shapeColorValueMapper != null) || + shapeColorMappers == null, + ), + assert( + (bubbleColorMappers != null && + primaryValueMapper != null && + bubbleColorValueMapper != null) || + bubbleColorMappers == null, + ); /// Creates a layer using the .json file from the network. /// @@ -218,18 +224,24 @@ class MapShapeSource extends DiagnosticableTree { this.bubbleSizeMapper, this.shapeColorValueMapper, this.bubbleColorValueMapper, - }) : _path = src, - _type = GeoJSONSourceType.network, - assert((primaryValueMapper != null && dataCount > 0) || - primaryValueMapper == null), - assert((shapeColorMappers != null && - primaryValueMapper != null && - shapeColorValueMapper != null) || - shapeColorMappers == null), - assert((bubbleColorMappers != null && - primaryValueMapper != null && - bubbleColorValueMapper != null) || - bubbleColorMappers == null); + }) : _path = src, + _type = GeoJSONSourceType.network, + assert( + (primaryValueMapper != null && dataCount > 0) || + primaryValueMapper == null, + ), + assert( + (shapeColorMappers != null && + primaryValueMapper != null && + shapeColorValueMapper != null) || + shapeColorMappers == null, + ), + assert( + (bubbleColorMappers != null && + primaryValueMapper != null && + bubbleColorValueMapper != null) || + bubbleColorMappers == null, + ); /// Creates a layer using the GeoJSON source as bytes from [Uint8List]. /// @@ -274,18 +286,24 @@ class MapShapeSource extends DiagnosticableTree { this.bubbleSizeMapper, this.shapeColorValueMapper, this.bubbleColorValueMapper, - }) : _path = bytes, - _type = GeoJSONSourceType.memory, - assert((primaryValueMapper != null && dataCount > 0) || - primaryValueMapper == null), - assert((shapeColorMappers != null && - primaryValueMapper != null && - shapeColorValueMapper != null) || - shapeColorMappers == null), - assert((bubbleColorMappers != null && - primaryValueMapper != null && - bubbleColorValueMapper != null) || - bubbleColorMappers == null); + }) : _path = bytes, + _type = GeoJSONSourceType.memory, + assert( + (primaryValueMapper != null && dataCount > 0) || + primaryValueMapper == null, + ), + assert( + (shapeColorMappers != null && + primaryValueMapper != null && + shapeColorValueMapper != null) || + shapeColorMappers == null, + ), + assert( + (bubbleColorMappers != null && + primaryValueMapper != null && + bubbleColorValueMapper != null) || + bubbleColorMappers == null, + ); /// Field name in the .json file to identify each shape. /// @@ -835,20 +853,48 @@ class MapShapeSource extends DiagnosticableTree { } properties.add(StringProperty('shapeDataField', shapeDataField)); properties.add(IntProperty('dataCount', dataCount)); - properties.add(ObjectFlagProperty.has( - 'primaryValueMapper', primaryValueMapper)); - properties.add(ObjectFlagProperty>.has( - 'shapeColorMappers', shapeColorMappers)); - properties.add(ObjectFlagProperty>.has( - 'bubbleColorMappers', bubbleColorMappers)); - properties.add(ObjectFlagProperty.has( - 'dataLabelMapper', dataLabelMapper)); - properties.add(ObjectFlagProperty.has( - 'bubbleSizeMapper', bubbleSizeMapper)); - properties.add(ObjectFlagProperty.has( - 'shapeColorValueMapper', shapeColorValueMapper)); - properties.add(ObjectFlagProperty.has( - 'bubbleColorValueMapper', bubbleColorValueMapper)); + properties.add( + ObjectFlagProperty.has( + 'primaryValueMapper', + primaryValueMapper, + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'shapeColorMappers', + shapeColorMappers, + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'bubbleColorMappers', + bubbleColorMappers, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'dataLabelMapper', + dataLabelMapper, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'bubbleSizeMapper', + bubbleSizeMapper, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'shapeColorValueMapper', + shapeColorValueMapper, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'bubbleColorValueMapper', + bubbleColorValueMapper, + ), + ); } } @@ -882,10 +928,11 @@ class _ShapeFileData { } Future<_ShapeFileData> _retrieveDataFromShapeFile( - MapProvider provider, - String? shapeDataField, - _ShapeFileData shapeFileData, - bool isSublayer) async { + MapProvider provider, + String? shapeDataField, + _ShapeFileData shapeFileData, + bool isSublayer, +) async { if (shapeFileData.mapDataSource.isNotEmpty) { return shapeFileData; } @@ -894,7 +941,7 @@ Future<_ShapeFileData> _retrieveDataFromShapeFile( 'AssertBundleData': assertBundleData, 'ShapeDataField': shapeDataField, 'ShapeFileData': shapeFileData, - 'IsSublayer': isSublayer + 'IsSublayer': isSublayer, }; return compute(_decodeJsonData, data); } @@ -918,25 +965,30 @@ void _readJsonFile(Map data) { final String? shapeDataField = data['ShapeDataField'] as String?; // ignore: avoid_as final bool isSublayer = data['IsSublayer'] as bool; - final bool hasFeatures = - shapeFileData.decodedJsonData!.containsKey('features'); - final bool hasGeometries = - shapeFileData.decodedJsonData!.containsKey('geometries'); - final String? key = hasFeatures - ? 'features' - : hasGeometries + final bool hasFeatures = shapeFileData.decodedJsonData!.containsKey( + 'features', + ); + final bool hasGeometries = shapeFileData.decodedJsonData!.containsKey( + 'geometries', + ); + final String? key = + hasFeatures + ? 'features' + : hasGeometries ? 'geometries' : null; - final int jsonLength = key == null || key.isEmpty - ? 0 - // ignore: avoid_as - : shapeFileData.decodedJsonData![key].length as int; + final int jsonLength = + key == null || key.isEmpty + ? 0 + // ignore: avoid_as + : shapeFileData.decodedJsonData![key].length as int; if (isSublayer) { shapeFileData.bounds = _ShapeBounds( - minLatitude: minimumLatitude, - maxLatitude: maximumLatitude, - minLongitude: minimumLongitude, - maxLongitude: maximumLongitude); + minLatitude: minimumLatitude, + maxLatitude: maximumLatitude, + minLongitude: minimumLongitude, + maxLongitude: maximumLongitude, + ); } for (int i = 0; i < jsonLength; i++) { @@ -954,23 +1006,38 @@ void _readJsonFile(Map data) { if (geometry['type'] == 'Polygon') { // ignore: avoid_as polygonGeometryData = geometry['coordinates'][0] as List; - _updateMapDataSource(shapeFileData, shapeDataField, properties, - polygonGeometryData, isSublayer); + _updateMapDataSource( + shapeFileData, + shapeDataField, + properties, + polygonGeometryData, + isSublayer, + ); } else { // ignore: avoid_as multipolygonGeometryLength = geometry['coordinates'].length as int; for (int j = 0; j < multipolygonGeometryLength; j++) { // ignore: avoid_as polygonGeometryData = geometry['coordinates'][j][0] as List; - _updateMapDataSource(shapeFileData, shapeDataField, properties, - polygonGeometryData, isSublayer); + _updateMapDataSource( + shapeFileData, + shapeDataField, + properties, + polygonGeometryData, + isSublayer, + ); } } } } -void _updateMapDataSource(_ShapeFileData shapeFileData, String? shapeDataField, - Map? properties, List points, bool isSublayer) { +void _updateMapDataSource( + _ShapeFileData shapeFileData, + String? shapeDataField, + Map? properties, + List points, + bool isSublayer, +) { final String dataPath = // ignore: avoid_as (properties != null ? (properties[shapeDataField] ?? '') : '') as String; @@ -996,7 +1063,9 @@ void _updateMapDataSource(_ShapeFileData shapeFileData, String? shapeDataField, } void _updateShapeBounds( - _ShapeFileData shapeFileData, List coordinates) { + _ShapeFileData shapeFileData, + List coordinates, +) { List data; num longitude, latitude; final int length = coordinates.length; @@ -1013,14 +1082,22 @@ void _updateShapeBounds( shapeFileData.bounds.maxLongitude = longitude; shapeFileData.bounds.maxLatitude = latitude; } else { - shapeFileData.bounds.minLongitude = - min(longitude, shapeFileData.bounds.minLongitude!); - shapeFileData.bounds.minLatitude = - min(latitude, shapeFileData.bounds.minLatitude!); - shapeFileData.bounds.maxLongitude = - max(longitude, shapeFileData.bounds.maxLongitude!); - shapeFileData.bounds.maxLatitude = - max(latitude, shapeFileData.bounds.maxLatitude!); + shapeFileData.bounds.minLongitude = min( + longitude, + shapeFileData.bounds.minLongitude!, + ); + shapeFileData.bounds.minLatitude = min( + latitude, + shapeFileData.bounds.minLatitude!, + ); + shapeFileData.bounds.maxLongitude = max( + longitude, + shapeFileData.bounds.maxLongitude!, + ); + shapeFileData.bounds.maxLatitude = max( + latitude, + shapeFileData.bounds.maxLatitude!, + ); } } } @@ -1118,10 +1195,11 @@ class MapShapeLayerController extends MapLayerController { /// Converts pixel point to [MapLatLng]. MapLatLng pixelToLatLng(Offset position) { return getPixelToLatLng( - position, - _parentBox.size, - _parentBox._controller.shapeLayerOffset, - _parentBox._controller.shapeLayerSizeFactor); + position, + _parentBox.size, + _parentBox._controller.shapeLayerOffset, + _parentBox._controller.shapeLayerSizeFactor, + ); } } @@ -1231,24 +1309,28 @@ class _GeoJSONLayerState extends State selectionSettings: widget.selectionSettings, zoomPanBehavior: widget.zoomPanBehavior, bubbleSettings: widget.bubbleSettings.copyWith( - color: themeData.bubbleColor, - strokeColor: themeData.bubbleStrokeColor, - strokeWidth: themeData.bubbleStrokeWidth), + color: themeData.bubbleColor, + strokeColor: themeData.bubbleStrokeColor, + strokeWidth: themeData.bubbleStrokeWidth, + ), themeData: themeData, isDesktop: isDesktop, state: this, children: [ if (_hasSublayer) SublayerContainer( - ancestor: ancestor, children: widget.sublayers!), + ancestor: ancestor, + children: widget.sublayers!, + ), if (_markers != null && _markers!.isNotEmpty) MarkerContainer( - controller: _controller!, - markerTooltipBuilder: widget.markerTooltipBuilder, - themeData: themeData, - sublayer: widget.sublayerAncestor, - ancestor: ancestor, - children: _markers) + controller: _controller!, + markerTooltipBuilder: widget.markerTooltipBuilder, + themeData: themeData, + sublayer: widget.sublayerAncestor, + ancestor: ancestor, + children: _markers, + ), ], ), if (widget.source.bubbleSizeMapper != null) @@ -1258,9 +1340,10 @@ class _GeoJSONLayerState extends State source: widget.source, mapDataSource: shapeFileData.mapDataSource, bubbleSettings: widget.bubbleSettings.copyWith( - color: themeData.bubbleColor, - strokeColor: themeData.bubbleStrokeColor, - strokeWidth: themeData.bubbleStrokeWidth), + color: themeData.bubbleColor, + strokeColor: themeData.bubbleStrokeColor, + strokeWidth: themeData.bubbleStrokeWidth, + ), legend: widget.legend, showDataLabels: widget.showDataLabels, themeData: themeData, @@ -1290,8 +1373,9 @@ class _GeoJSONLayerState extends State widget.zoomPanBehavior!.showToolbar && isDesktop) MapToolbar( - controller: _controller, - zoomPanBehavior: widget.zoomPanBehavior!), + controller: _controller, + zoomPanBehavior: widget.zoomPanBehavior!, + ), if (_hasTooltipBuilder()) MapTooltip( key: _controller!.tooltipKey, @@ -1357,20 +1441,26 @@ class _GeoJSONLayerState extends State return false; } - SfMapsThemeData _updateThemeData(BuildContext context, ThemeData themeData, - SfMapsThemeData mapsThemeData) { + SfMapsThemeData _updateThemeData( + BuildContext context, + ThemeData themeData, + SfMapsThemeData mapsThemeData, + ) { final MapsThemeData effectiveThemeData = MapsThemeData(context); return mapsThemeData.copyWith( - layerColor: widget.color ?? + layerColor: + widget.color ?? (isSublayer ? effectiveThemeData.subLayerColor : mapsThemeData.layerColor ?? effectiveThemeData.layerColor), - layerStrokeColor: widget.strokeColor ?? + layerStrokeColor: + widget.strokeColor ?? (isSublayer ? effectiveThemeData.subLayerStrokeColor : mapsThemeData.layerStrokeColor ?? effectiveThemeData.layerStrokeColor), - layerStrokeWidth: widget.strokeWidth ?? + layerStrokeWidth: + widget.strokeWidth ?? (isSublayer ? effectiveThemeData.subLayerStrokeWidth : mapsThemeData.layerStrokeWidth), @@ -1378,47 +1468,62 @@ class _GeoJSONLayerState extends State mapsThemeData.shapeHoverStrokeWidth ?? mapsThemeData.layerStrokeWidth, legendTextStyle: themeData.textTheme.bodySmall! .copyWith( - color: - themeData.textTheme.bodySmall!.color!.withValues(alpha: 0.87)) + color: themeData.textTheme.bodySmall!.color!.withValues( + alpha: 0.87, + ), + ) .merge(mapsThemeData.legendTextStyle) .merge(widget.legend?.textStyle), markerIconColor: mapsThemeData.markerIconColor ?? effectiveThemeData.markerIconColor, - bubbleColor: widget.bubbleSettings.color ?? + bubbleColor: + widget.bubbleSettings.color ?? mapsThemeData.bubbleColor ?? effectiveThemeData.bubbleColor, - bubbleStrokeColor: widget.bubbleSettings.strokeColor ?? + bubbleStrokeColor: + widget.bubbleSettings.strokeColor ?? mapsThemeData.bubbleStrokeColor ?? effectiveThemeData.bubbleStrokeColor, bubbleStrokeWidth: widget.bubbleSettings.strokeWidth ?? mapsThemeData.bubbleStrokeWidth, - bubbleHoverStrokeWidth: mapsThemeData.bubbleHoverStrokeWidth ?? + bubbleHoverStrokeWidth: + mapsThemeData.bubbleHoverStrokeWidth ?? mapsThemeData.bubbleStrokeWidth, - selectionColor: widget.selectionSettings.color ?? + selectionColor: + widget.selectionSettings.color ?? mapsThemeData.selectionColor ?? effectiveThemeData.selectionColor, - selectionStrokeColor: widget.selectionSettings.strokeColor ?? + selectionStrokeColor: + widget.selectionSettings.strokeColor ?? mapsThemeData.selectionStrokeColor ?? effectiveThemeData.selectionStrokeColor, - selectionStrokeWidth: widget.selectionSettings.strokeWidth ?? + selectionStrokeWidth: + widget.selectionSettings.strokeWidth ?? mapsThemeData.selectionStrokeWidth, - tooltipColor: widget.tooltipSettings.color ?? + tooltipColor: + widget.tooltipSettings.color ?? mapsThemeData.tooltipColor ?? effectiveThemeData.tooltipColor, - tooltipStrokeColor: widget.tooltipSettings.strokeColor ?? + tooltipStrokeColor: + widget.tooltipSettings.strokeColor ?? mapsThemeData.tooltipStrokeColor ?? effectiveThemeData.tooltipStrokeColor, - tooltipStrokeWidth: widget.tooltipSettings.strokeWidth ?? + tooltipStrokeWidth: + widget.tooltipSettings.strokeWidth ?? mapsThemeData.tooltipStrokeWidth, - tooltipBorderRadius: - mapsThemeData.tooltipBorderRadius.resolve(Directionality.of(context)), - toggledItemColor: widget.legend?.toggledItemColor ?? + tooltipBorderRadius: mapsThemeData.tooltipBorderRadius.resolve( + Directionality.of(context), + ), + toggledItemColor: + widget.legend?.toggledItemColor ?? mapsThemeData.toggledItemColor ?? effectiveThemeData.toggledItemColor, - toggledItemStrokeColor: widget.legend?.toggledItemStrokeColor ?? + toggledItemStrokeColor: + widget.legend?.toggledItemStrokeColor ?? mapsThemeData.toggledItemStrokeColor ?? effectiveThemeData.toggledItemStrokeColor, - toggledItemStrokeWidth: widget.legend?.toggledItemStrokeWidth ?? + toggledItemStrokeWidth: + widget.legend?.toggledItemStrokeWidth ?? mapsThemeData.toggledItemStrokeWidth, ); } @@ -1457,27 +1562,38 @@ class _GeoJSONLayerState extends State } void _updateShapeColor( - bool hasShapeColorValueMapper, int index, MapModel mapModel) { + bool hasShapeColorValueMapper, + int index, + MapModel mapModel, + ) { if (hasShapeColorValueMapper) { mapModel.shapeColor = _getActualColor( - widget.source.shapeColorValueMapper!(index), - widget.source.shapeColorMappers, - mapModel); + widget.source.shapeColorValueMapper!(index), + widget.source.shapeColorMappers, + mapModel, + ); } } void _updateBubbleColor( - bool hasBubbleColorValueMapper, int index, MapModel mapModel) { + bool hasBubbleColorValueMapper, + int index, + MapModel mapModel, + ) { if (hasBubbleColorValueMapper) { mapModel.bubbleColor = _getActualColor( - widget.source.bubbleColorValueMapper!(index), - widget.source.bubbleColorMappers, - mapModel); + widget.source.bubbleColorValueMapper!(index), + widget.source.bubbleColorMappers, + mapModel, + ); } } void _validateBubbleSize( - bool hasBubbleSizeMapper, int index, MapModel mapModel) { + bool hasBubbleSizeMapper, + int index, + MapModel mapModel, + ) { if (hasBubbleSizeMapper) { mapModel.bubbleSizeValue = widget.source.bubbleSizeMapper!(index); if (minBubbleValue == null) { @@ -1544,8 +1660,11 @@ class _GeoJSONLayerState extends State } /// Returns color from [MapColorMapper] based on the data source value. - Color? _getActualColor(Object? colorValue, List? colorMappers, - MapModel mapModel) { + Color? _getActualColor( + Object? colorValue, + List? colorMappers, + MapModel mapModel, + ) { MapColorMapper mapper; if (colorValue == null) { return null; @@ -1575,8 +1694,12 @@ class _GeoJSONLayerState extends State mapModel.colorValue = colorValue; if (mapper.minOpacity != null && mapper.maxOpacity != null) { return mapper.color.withValues( - alpha: lerpDouble(mapper.minOpacity, mapper.maxOpacity, - (colorValue - mapper.from!) / (mapper.to! - mapper.from!))); + alpha: lerpDouble( + mapper.minOpacity, + mapper.maxOpacity, + (colorValue - mapper.from!) / (mapper.to! - mapper.from!), + ), + ); } return mapper.color; } @@ -1662,13 +1785,18 @@ class _GeoJSONLayerState extends State } void _obtainDataSource() { - _computeDataSource = _obtainDataSourceAndBindDataSource() - .then((_ShapeFileData data) => data); + _computeDataSource = _obtainDataSourceAndBindDataSource().then( + (_ShapeFileData data) => data, + ); } Future<_ShapeFileData> _obtainDataSourceAndBindDataSource() async { shapeFileData = await _retrieveDataFromShapeFile( - _provider, widget.source.shapeDataField, shapeFileData, isSublayer); + _provider, + widget.source.shapeDataField, + shapeFileData, + isSublayer, + ); if (_shouldUpdateMapDataSource) { minBubbleValue = null; maxBubbleValue = null; @@ -1685,25 +1813,43 @@ class _GeoJSONLayerState extends State void initState() { _pointerController = PointerController(); bubbleKey = GlobalKey(); - shapeFileData = _ShapeFileData() - ..mapDataSource = {} - ..bounds = _ShapeBounds(); + shapeFileData = + _ShapeFileData() + ..mapDataSource = {} + ..bounds = _ShapeBounds(); dataLabelAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 750)); + vsync: this, + duration: const Duration(milliseconds: 750), + ); bubbleAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 500)); + vsync: this, + duration: const Duration(milliseconds: 500), + ); toggleAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); _hoverBubbleAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); hoverShapeAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); selectionAnimationController = AnimationController( - vsync: this, value: 1.0, duration: const Duration(milliseconds: 150)); + vsync: this, + value: 1.0, + duration: const Duration(milliseconds: 150), + ); zoomLevelAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 650)); + vsync: this, + duration: const Duration(milliseconds: 650), + ); focalLatLngAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 650)); + vsync: this, + duration: const Duration(milliseconds: 650), + ); if (widget.controller != null) { widget.controller!._markersCount = widget.initialMarkersCount; @@ -1727,8 +1873,9 @@ class _GeoJSONLayerState extends State @override void didChangeDependencies() { if (_controller == null) { - ancestor = context - .dependOnInheritedWidgetOfExactType()!; + ancestor = + context + .dependOnInheritedWidgetOfExactType()!; _controller = ancestor.controller; } super.didChangeDependencies(); @@ -1740,8 +1887,10 @@ class _GeoJSONLayerState extends State _hasSublayer = widget.sublayers != null && widget.sublayers!.isNotEmpty; isSublayer = widget.sublayerAncestor != null; - final MapProvider currentProvider = - getSourceProvider(widget.source._path, widget.source._type); + final MapProvider currentProvider = getSourceProvider( + widget.source._path, + widget.source._type, + ); if (_provider != currentProvider) { _provider = currentProvider; shapeFileData.reset(); @@ -1797,23 +1946,35 @@ class _GeoJSONLayerState extends State @override Widget build(BuildContext context) { - assert(!widget.showDataLabels || - (widget.showDataLabels && widget.source.shapeDataField != null)); - assert(widget.source.bubbleSizeMapper == null || - widget.source.bubbleSizeMapper != null && - widget.source.primaryValueMapper != null); - assert(widget.source.dataLabelMapper == null || - (widget.source.dataLabelMapper != null && widget.showDataLabels)); - assert(widget.source.shapeColorMappers == null || - widget.source.shapeColorMappers!.isNotEmpty); + assert( + !widget.showDataLabels || + (widget.showDataLabels && widget.source.shapeDataField != null), + ); + assert( + widget.source.bubbleSizeMapper == null || + widget.source.bubbleSizeMapper != null && + widget.source.primaryValueMapper != null, + ); + assert( + widget.source.dataLabelMapper == null || + (widget.source.dataLabelMapper != null && widget.showDataLabels), + ); + assert( + widget.source.shapeColorMappers == null || + widget.source.shapeColorMappers!.isNotEmpty, + ); final ThemeData themeData = Theme.of(context); - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; - final SfMapsThemeData mapsThemeData = - _updateThemeData(context, themeData, SfMapsTheme.of(context)!); + final SfMapsThemeData mapsThemeData = _updateThemeData( + context, + themeData, + SfMapsTheme.of(context)!, + ); return FutureBuilder<_ShapeFileData>( future: _computeDataSource, @@ -1890,7 +2051,9 @@ class _GeoJSONLayerRenderObjectWidget extends Stack { @override void updateRenderObject( - BuildContext context, _RenderGeoJSONLayer renderObject) { + BuildContext context, + _RenderGeoJSONLayer renderObject, + ) { renderObject ..mapDataSource = mapDataSource ..mapSource = mapSource @@ -1922,23 +2085,24 @@ class _RenderGeoJSONLayer extends RenderStack required this.isDesktop, required this.context, required _GeoJSONLayerState state, - }) : _controller = controller, - _initialLatLngBounds = initialLatLngBounds, - _currentZoomLevel = initialZoomLevel, - _mapDataSource = mapDataSource, - _mapSource = mapSource, - _selectedIndex = selectedIndex, - _legend = legend, - _bubbleSettings = bubbleSettings, - _selectionSettings = selectionSettings, - _zoomPanBehavior = zoomPanBehavior, - _themeData = themeData, - _state = state, - super(textDirection: Directionality.of(state.context)) { - _scaleGestureRecognizer = ScaleGestureRecognizer() - ..onStart = _handleScaleStart - ..onUpdate = _handleScaleUpdate - ..onEnd = _handleScaleEnd; + }) : _controller = controller, + _initialLatLngBounds = initialLatLngBounds, + _currentZoomLevel = initialZoomLevel, + _mapDataSource = mapDataSource, + _mapSource = mapSource, + _selectedIndex = selectedIndex, + _legend = legend, + _bubbleSettings = bubbleSettings, + _selectionSettings = selectionSettings, + _zoomPanBehavior = zoomPanBehavior, + _themeData = themeData, + _state = state, + super(textDirection: Directionality.of(state.context)) { + _scaleGestureRecognizer = + ScaleGestureRecognizer() + ..onStart = _handleScaleStart + ..onUpdate = _handleScaleUpdate + ..onEnd = _handleScaleEnd; _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; @@ -1954,14 +2118,18 @@ class _RenderGeoJSONLayer extends RenderStack _reverseToggledShapeStrokeColorTween = ColorTween(); _hoverColorAnimation = CurvedAnimation( - parent: _state.hoverShapeAnimationController, curve: Curves.easeInOut); + parent: _state.hoverShapeAnimationController, + curve: Curves.easeInOut, + ); _forwardHoverColorTween = ColorTween(); _forwardHoverStrokeColorTween = ColorTween(); _reverseHoverColorTween = ColorTween(); _reverseHoverStrokeColorTween = ColorTween(); _toggleShapeAnimation = CurvedAnimation( - parent: _state.toggleAnimationController, curve: Curves.easeInOut); + parent: _state.toggleAnimationController, + curve: Curves.easeInOut, + ); if (_zoomPanBehavior != null) { _initializeZoomPanAnimations(); @@ -2078,8 +2246,9 @@ class _RenderGeoJSONLayer extends RenderStack _state.bubbleAnimationController.value = 0.0; _refresh(); markNeedsPaint(); - SchedulerBinding.instance - .addPostFrameCallback(_initiateInitialAnimations); + SchedulerBinding.instance.addPostFrameCallback( + _initiateInitialAnimations, + ); } } @@ -2193,9 +2362,10 @@ class _RenderGeoJSONLayer extends RenderStack Rect get paintBounds => Offset.zero & _size; @override - MouseCursor get cursor => _controller.gesture == Gesture.pan - ? SystemMouseCursors.grabbing - : SystemMouseCursors.basic; + MouseCursor get cursor => + _controller.gesture == Gesture.pan + ? SystemMouseCursors.grabbing + : SystemMouseCursors.basic; @override PointerEnterEventListener? get onEnter => null; @@ -2214,21 +2384,30 @@ class _RenderGeoJSONLayer extends RenderStack void _initializeZoomPanAnimations() { _flingZoomLevelCurvedAnimation = CurvedAnimation( - parent: _state.zoomLevelAnimationController, curve: Curves.decelerate); + parent: _state.zoomLevelAnimationController, + curve: Curves.decelerate, + ); _flingFocalLatLngCurvedAnimation = CurvedAnimation( - parent: _state.focalLatLngAnimationController, - curve: Curves.decelerate); + parent: _state.focalLatLngAnimationController, + curve: Curves.decelerate, + ); _zoomLevelCurvedAnimation = CurvedAnimation( - parent: _state.zoomLevelAnimationController, curve: Curves.easeInOut); + parent: _state.zoomLevelAnimationController, + curve: Curves.easeInOut, + ); _focalLatLngCurvedAnimation = CurvedAnimation( - parent: _state.focalLatLngAnimationController, curve: Curves.easeInOut); + parent: _state.focalLatLngAnimationController, + curve: Curves.easeInOut, + ); _focalLatLngTween = MapLatLngTween(); _zoomLevelTween = Tween(); } void _initializeSelectionTween() { _selectionColorAnimation = CurvedAnimation( - parent: _state.selectionAnimationController, curve: Curves.easeInOut); + parent: _state.selectionAnimationController, + curve: Curves.easeInOut, + ); _forwardSelectionColorTween = ColorTween(); _forwardSelectionStrokeColorTween = ColorTween(); _reverseSelectionColorTween = ColorTween(); @@ -2251,10 +2430,11 @@ class _RenderGeoJSONLayer extends RenderStack void _updateCurrentSelectedItemTween() { if (_currentSelectedItem != null && (_state.isSublayer || !_controller.wasToggled(_currentSelectedItem!))) { - _forwardSelectionColorTween!.begin = (_currentHoverItem != null && - _currentInteractedElement == MapLayerElement.shape) - ? _forwardHoverColorTween.end - : getActualShapeColor(_currentSelectedItem!); + _forwardSelectionColorTween!.begin = + (_currentHoverItem != null && + _currentInteractedElement == MapLayerElement.shape) + ? _forwardHoverColorTween.end + : getActualShapeColor(_currentSelectedItem!); } if (_prevSelectedItem != null) { @@ -2365,28 +2545,39 @@ class _RenderGeoJSONLayer extends RenderStack if (latlng == null && initialBounds != null) { initialBounds = _getMaxVisibleBounds(initialBounds); zoomLevel = getZoomLevel( - initialBounds, _controller.layerType!, _size, _actualFactor); + initialBounds, + _controller.layerType!, + _size, + _actualFactor, + ); latlng = getFocalLatLng(initialBounds); } if (_zoomPanBehavior != null) { _currentZoomLevel = zoomLevel.clamp( - _zoomPanBehavior!.minZoomLevel, _zoomPanBehavior!.maxZoomLevel); + _zoomPanBehavior!.minZoomLevel, + _zoomPanBehavior!.maxZoomLevel, + ); _zoomPanBehavior!.zoomLevel = _currentZoomLevel; final double inflateWidth = _size.width * _currentZoomLevel / 2 - _size.width / 2; final double inflateHeight = _size.height * _currentZoomLevel / 2 - _size.height / 2; _controller.shapeLayerOrigin = Offset( - paintBounds.left - inflateWidth, paintBounds.top - inflateHeight); + paintBounds.left - inflateWidth, + paintBounds.top - inflateHeight, + ); } else { - _currentZoomLevel = - zoomLevel.clamp(kDefaultMinZoomLevel, kDefaultMaxZoomLevel); + _currentZoomLevel = zoomLevel.clamp( + kDefaultMinZoomLevel, + kDefaultMaxZoomLevel, + ); } _controller.shapeLayerSizeFactor = _actualFactor * _currentZoomLevel; - _controller.shapeLayerOffset = - _getTranslationPoint(_controller.shapeLayerSizeFactor); + _controller.shapeLayerOffset = _getTranslationPoint( + _controller.shapeLayerSizeFactor, + ); final Offset offsetBeforeAdjust = _controller.shapeLayerOffset; _adjustLayerOffsetTo(latlng); if (!_state.isSublayer) { @@ -2402,17 +2593,23 @@ class _RenderGeoJSONLayer extends RenderStack void _computeActualFactor() { final Offset minPoint = pixelFromLatLng( - _state.shapeFileData.bounds.minLatitude!, - _state.shapeFileData.bounds.minLongitude!, - _size); + _state.shapeFileData.bounds.minLatitude!, + _state.shapeFileData.bounds.minLongitude!, + _size, + ); final Offset maxPoint = pixelFromLatLng( - _state.shapeFileData.bounds.maxLatitude!, - _state.shapeFileData.bounds.maxLongitude!, - _size); + _state.shapeFileData.bounds.maxLatitude!, + _state.shapeFileData.bounds.maxLongitude!, + _size, + ); _actualShapeSize = Size( - (maxPoint.dx - minPoint.dx).abs(), (maxPoint.dy - minPoint.dy).abs()); - _actualFactor = min(_size.height / _actualShapeSize.height, - _size.width / _actualShapeSize.width); + (maxPoint.dx - minPoint.dx).abs(), + (maxPoint.dy - minPoint.dy).abs(), + ); + _actualFactor = min( + _size.height / _actualShapeSize.height, + _size.width / _actualShapeSize.width, + ); } Offset _getTranslationPoint(double factor, [Rect? bounds]) { @@ -2421,30 +2618,37 @@ class _RenderGeoJSONLayer extends RenderStack // We cant use the clamp() directly here because the upperLimit must be // greater than or equal to lowerLimit. This shows assert error when using. // So, we have used the min and max mathematical function for clamping. - final double dx = - min(max(0.0, _size.width - _actualShapeSize.width), -bounds.left); - final double dy = - min(max(0.0, _size.height - _actualShapeSize.height), -bounds.top); + final double dx = min( + max(0.0, _size.width - _actualShapeSize.width), + -bounds.left, + ); + final double dy = min( + max(0.0, _size.height - _actualShapeSize.height), + -bounds.top, + ); final Size widgetSize = _state.isSublayer ? size : _size; final Offset shift = Offset( - widgetSize.width - _actualShapeSize.width * factor, - widgetSize.height - _actualShapeSize.height * factor); + widgetSize.width - _actualShapeSize.width * factor, + widgetSize.height - _actualShapeSize.height * factor, + ); return Offset(dx + shift.dx / 2, dy + shift.dy / 2); } Rect _getShapeBounds(double factor, [Offset translation = Offset.zero]) { final Offset minPoint = pixelFromLatLng( - _state.shapeFileData.bounds.minLatitude!, - _state.shapeFileData.bounds.minLongitude!, - _size, - translation, - factor); + _state.shapeFileData.bounds.minLatitude!, + _state.shapeFileData.bounds.minLongitude!, + _size, + translation, + factor, + ); final Offset maxPoint = pixelFromLatLng( - _state.shapeFileData.bounds.maxLatitude!, - _state.shapeFileData.bounds.maxLongitude!, - _size, - translation, - factor); + _state.shapeFileData.bounds.maxLatitude!, + _state.shapeFileData.bounds.maxLongitude!, + _size, + translation, + factor, + ); return Rect.fromPoints(minPoint, maxPoint); } @@ -2475,22 +2679,29 @@ class _RenderGeoJSONLayer extends RenderStack _mapDataSource.forEach((String key, MapModel mapModel) { double signedArea = 0.0, centerX = 0.0, centerY = 0.0; rawPointsLength = mapModel.rawPoints.length; - mapModel.pixelPoints = - List>.filled(rawPointsLength, []); + mapModel.pixelPoints = List>.filled( + rawPointsLength, + [], + ); shapePath = Path(); for (int j = 0; j < rawPointsLength; j++) { rawPoints = mapModel.rawPoints[j]; pointsLength = rawPoints.length; - pixelPoints = mapModel.pixelPoints![j] = - List.filled(pointsLength, Offset.zero); + pixelPoints = + mapModel.pixelPoints![j] = List.filled( + pointsLength, + Offset.zero, + ); for (int k = 0; k < pointsLength; k++) { coordinate = rawPoints[k]; - point = pixelPoints[k] = pixelFromLatLng( - coordinate[1], - coordinate[0], - _size, - _controller.shapeLayerOffset, - _controller.shapeLayerSizeFactor); + point = + pixelPoints[k] = pixelFromLatLng( + coordinate[1], + coordinate[0], + _size, + _controller.shapeLayerOffset, + _controller.shapeLayerSizeFactor, + ); if (k == 0) { shapePath.moveTo(point.dx, point.dy); } else { @@ -2530,10 +2741,12 @@ class _RenderGeoJSONLayer extends RenderStack } else if (bubbleSizeValue == _state.maxBubbleValue) { mapModel.bubbleRadius = _bubbleSettings.maxRadius; } else { - final double percentage = ((bubbleSizeValue - _state.minBubbleValue!) / + final double percentage = + ((bubbleSizeValue - _state.minBubbleValue!) / (_state.maxBubbleValue! - _state.minBubbleValue!)) * 100; - mapModel.bubbleRadius = bubbleSettings.minRadius + + mapModel.bubbleRadius = + bubbleSettings.minRadius + (bubbleSettings.maxRadius - bubbleSettings.minRadius) * (percentage / 100); } @@ -2541,13 +2754,13 @@ class _RenderGeoJSONLayer extends RenderStack if ((_state.widget.bubbleTooltipBuilder != null || hasBubbleHoverColor) && mapModel.bubbleRadius != null) { - mapModel.bubblePath = Path() - ..addOval( - Rect.fromCircle( - center: mapModel.shapePathCenter!, - radius: mapModel.bubbleRadius!, - ), - ); + mapModel.bubblePath = + Path()..addOval( + Rect.fromCircle( + center: mapModel.shapePathCenter!, + radius: mapModel.bubbleRadius!, + ), + ); } } @@ -2580,10 +2793,13 @@ class _RenderGeoJSONLayer extends RenderStack _maximumReachedScaleOnInteraction = 1.0; _downGlobalPoint = globalFocalPoint; _downLocalPoint = localFocalPoint; - _referenceVisibleBounds = - _controller.getVisibleBounds(_controller.shapeLayerOffset); + _referenceVisibleBounds = _controller.getVisibleBounds( + _controller.shapeLayerOffset, + ); _referenceShapeBounds = _getShapeBounds( - _controller.shapeLayerSizeFactor, _controller.shapeLayerOffset); + _controller.shapeLayerSizeFactor, + _controller.shapeLayerOffset, + ); _zoomDetails = MapZoomDetails( newVisibleBounds: _controller.getVisibleLatLngBounds( _referenceVisibleBounds!.topRight, @@ -2632,9 +2848,11 @@ class _RenderGeoJSONLayer extends RenderStack if (_zoomPanBehavior!.enablePinching && !_state.zoomLevelAnimationController.isAnimating && !_state.focalLatLngAnimationController.isAnimating) { - _invokeOnZooming(scale, - localFocalPoint: _downLocalPoint, - globalFocalPoint: _downGlobalPoint); + _invokeOnZooming( + scale, + localFocalPoint: _downLocalPoint, + globalFocalPoint: _downGlobalPoint, + ); } return; case Gesture.pan: @@ -2642,7 +2860,10 @@ class _RenderGeoJSONLayer extends RenderStack !_state.focalLatLngAnimationController.isAnimating && !_state.zoomLevelAnimationController.isAnimating) { _invokeOnPanning( - details.localFocalPoint, _downLocalPoint!, details.focalPoint); + details.localFocalPoint, + _downLocalPoint!, + details.focalPoint, + ); } return; } @@ -2686,10 +2907,11 @@ class _RenderGeoJSONLayer extends RenderStack // the ScaleGestureRecognizer for the web platform alone if (!_initailPinchZooming && kIsWeb) { _scaleGestureRecognizer.dispose(); - _scaleGestureRecognizer = ScaleGestureRecognizer() - ..onStart = _handleScaleStart - ..onUpdate = _handleScaleUpdate - ..onEnd = _handleScaleEnd; + _scaleGestureRecognizer = + ScaleGestureRecognizer() + ..onStart = _handleScaleStart + ..onUpdate = _handleScaleUpdate + ..onEnd = _handleScaleEnd; _initailPinchZooming = true; } } @@ -2697,11 +2919,12 @@ class _RenderGeoJSONLayer extends RenderStack void _startFlingAnimationForPanning(ScaleEndDetails details) { _isFlingAnimationActive = true; final Offset currentPixelPoint = pixelFromLatLng( - _controller.visibleFocalLatLng!.latitude, - _controller.visibleFocalLatLng!.longitude, - _size, - _controller.shapeLayerOffset, - _controller.shapeLayerSizeFactor); + _controller.visibleFocalLatLng!.latitude, + _controller.visibleFocalLatLng!.longitude, + _size, + _controller.shapeLayerOffset, + _controller.shapeLayerSizeFactor, + ); final FrictionSimulation frictionX = FrictionSimulation( _frictionCoefficient, currentPixelPoint.dx, @@ -2715,12 +2938,15 @@ class _RenderGeoJSONLayer extends RenderStack ); final MapLatLng latLng = getPixelToLatLng( - Offset(frictionX.finalX, frictionY.finalX), - _size, - _controller.shapeLayerOffset, - _controller.shapeLayerSizeFactor); + Offset(frictionX.finalX, frictionY.finalX), + _size, + _controller.shapeLayerOffset, + _controller.shapeLayerSizeFactor, + ); _state.focalLatLngAnimationController.duration = _getFlingAnimationDuration( - details.velocity.pixelsPerSecond.distance, _frictionCoefficient); + details.velocity.pixelsPerSecond.distance, + _frictionCoefficient, + ); _controller.isInInteractive = false; _panDistanceBeforeFlinging = _controller.panDistance; _handlePanningCallback(latLng); @@ -2730,14 +2956,19 @@ class _RenderGeoJSONLayer extends RenderStack _isFlingAnimationActive = true; final int direction = _controller.localScale >= _maximumReachedScaleOnInteraction ? 1 : -1; - double newZoomLevel = _currentZoomLevel + + double newZoomLevel = + _currentZoomLevel + (direction * (details.velocity.pixelsPerSecond.distance / kMaxFlingVelocity) * _zoomPanBehavior!.maxZoomLevel); newZoomLevel = newZoomLevel.clamp( - _zoomPanBehavior!.minZoomLevel, _zoomPanBehavior!.maxZoomLevel); + _zoomPanBehavior!.minZoomLevel, + _zoomPanBehavior!.maxZoomLevel, + ); _state.zoomLevelAnimationController.duration = _getFlingAnimationDuration( - details.velocity.pixelsPerSecond.distance, _frictionCoefficient); + details.velocity.pixelsPerSecond.distance, + _frictionCoefficient, + ); _controller.isInInteractive = false; _handleZoomingCallback(newZoomLevel, downPoint: _downLocalPoint); } @@ -2745,7 +2976,9 @@ class _RenderGeoJSONLayer extends RenderStack // Returns the animation duration for the given distance and // friction co-efficient. Duration _getFlingAnimationDuration( - double distance, double frictionCoefficient) { + double distance, + double frictionCoefficient, + ) { final int duration = (log(10.0 / distance) / log(frictionCoefficient / 100)).round(); final int durationInMs = duration * 650; @@ -2774,8 +3007,11 @@ class _RenderGeoJSONLayer extends RenderStack scale = _actualFactor / _controller.shapeLayerSizeFactor; } - _invokeOnZooming(scale, - localFocalPoint: _downLocalPoint, globalFocalPoint: _downGlobalPoint); + _invokeOnZooming( + scale, + localFocalPoint: _downLocalPoint, + globalFocalPoint: _downGlobalPoint, + ); // When the user didn't scrolled or scaled for certain time period, // we will refresh the map to the corresponding zoom level. _zoomingDelayTimer?.cancel(); @@ -2785,35 +3021,43 @@ class _RenderGeoJSONLayer extends RenderStack } } - void _invokeOnZooming(double scale, - {MapLatLng? focalLatLng, - Offset? localFocalPoint, - Offset? globalFocalPoint}) { + void _invokeOnZooming( + double scale, { + MapLatLng? focalLatLng, + Offset? localFocalPoint, + Offset? globalFocalPoint, + }) { final double newZoomLevel = _getZoomLevel(scale); final double newShapeLayerSizeFactor = _getScale(newZoomLevel) * _controller.shapeLayerSizeFactor; - final Offset newShapeLayerOffset = - _controller.getZoomingTranslation(origin: localFocalPoint); + final Offset newShapeLayerOffset = _controller.getZoomingTranslation( + origin: localFocalPoint, + ); _controller.visibleFocalLatLng = _controller.getVisibleFocalLatLng( - newShapeLayerOffset, newShapeLayerSizeFactor); + newShapeLayerOffset, + newShapeLayerSizeFactor, + ); final Rect newVisibleBounds = _controller.getVisibleBounds( - newShapeLayerOffset, newShapeLayerSizeFactor); - final MapLatLngBounds newVisibleLatLngBounds = - _controller.getVisibleLatLngBounds( - newVisibleBounds.topRight, - newVisibleBounds.bottomLeft, newShapeLayerOffset, newShapeLayerSizeFactor, ); + final MapLatLngBounds newVisibleLatLngBounds = _controller + .getVisibleLatLngBounds( + newVisibleBounds.topRight, + newVisibleBounds.bottomLeft, + newShapeLayerOffset, + newShapeLayerSizeFactor, + ); if (_currentZoomLevel != newZoomLevel) { _zoomDetails = MapZoomDetails( localFocalPoint: localFocalPoint, globalFocalPoint: globalFocalPoint, previousZoomLevel: _currentZoomLevel, newZoomLevel: newZoomLevel, - previousVisibleBounds: _zoomDetails != null - ? _zoomDetails!.newVisibleBounds - : _controller.visibleLatLngBounds, + previousVisibleBounds: + _zoomDetails != null + ? _zoomDetails!.newVisibleBounds + : _controller.visibleLatLngBounds, newVisibleBounds: newVisibleLatLngBounds, focalLatLng: focalLatLng ?? getFocalLatLng(newVisibleLatLngBounds), ); @@ -2826,33 +3070,38 @@ class _RenderGeoJSONLayer extends RenderStack void _handleZoomingCallback(double newZoomLevel, {Offset? downPoint}) { downPoint ??= pixelFromLatLng( - _controller.visibleFocalLatLng!.latitude, - _controller.visibleFocalLatLng!.longitude, - _size, - _controller.shapeLayerOffset, - _controller.shapeLayerSizeFactor); + _controller.visibleFocalLatLng!.latitude, + _controller.visibleFocalLatLng!.longitude, + _size, + _controller.shapeLayerOffset, + _controller.shapeLayerSizeFactor, + ); final double newShapeLayerSizeFactor = _getScale(newZoomLevel) * _controller.shapeLayerSizeFactor; - final Offset newShapeLayerOffset = - _controller.getZoomingTranslation(origin: downPoint); + final Offset newShapeLayerOffset = _controller.getZoomingTranslation( + origin: downPoint, + ); final Rect newVisibleBounds = _controller.getVisibleBounds( - newShapeLayerOffset, newShapeLayerSizeFactor); - final MapLatLngBounds newVisibleLatLngBounds = - _controller.getVisibleLatLngBounds( - newVisibleBounds.topRight, - newVisibleBounds.bottomLeft, newShapeLayerOffset, newShapeLayerSizeFactor, ); + final MapLatLngBounds newVisibleLatLngBounds = _controller + .getVisibleLatLngBounds( + newVisibleBounds.topRight, + newVisibleBounds.bottomLeft, + newShapeLayerOffset, + newShapeLayerSizeFactor, + ); if (_currentZoomLevel != newZoomLevel) { _zoomDetails = MapZoomDetails( localFocalPoint: downPoint, globalFocalPoint: localToGlobal(downPoint), previousZoomLevel: _currentZoomLevel, newZoomLevel: newZoomLevel, - previousVisibleBounds: _zoomDetails != null - ? _zoomDetails!.newVisibleBounds - : _controller.visibleLatLngBounds, + previousVisibleBounds: + _zoomDetails != null + ? _zoomDetails!.newVisibleBounds + : _controller.visibleLatLngBounds, newVisibleBounds: newVisibleLatLngBounds, focalLatLng: getFocalLatLng(newVisibleLatLngBounds), ); @@ -2865,35 +3114,40 @@ class _RenderGeoJSONLayer extends RenderStack void _handlePanningCallback(MapLatLng newLatLng) { final Offset localFocalPoint = pixelFromLatLng( - newLatLng.latitude, - newLatLng.longitude, - _size, - _controller.shapeLayerOffset + _panDistanceBeforeFlinging, - _controller.shapeLayerSizeFactor); + newLatLng.latitude, + newLatLng.longitude, + _size, + _controller.shapeLayerOffset + _panDistanceBeforeFlinging, + _controller.shapeLayerSizeFactor, + ); final Offset previousFocalPoint = pixelFromLatLng( - _controller.visibleFocalLatLng!.latitude, - _controller.visibleFocalLatLng!.longitude, - _size, - _controller.shapeLayerOffset + _panDistanceBeforeFlinging, - _controller.shapeLayerSizeFactor); - final Offset delta = - _getValidPanDelta(localFocalPoint - previousFocalPoint); - final Rect visibleBounds = - _controller.getVisibleBounds(_controller.shapeLayerOffset + delta); - final MapLatLngBounds newVisibleLatLngBounds = - _controller.getVisibleLatLngBounds( - visibleBounds.topRight, - visibleBounds.bottomLeft, + _controller.visibleFocalLatLng!.latitude, + _controller.visibleFocalLatLng!.longitude, + _size, + _controller.shapeLayerOffset + _panDistanceBeforeFlinging, + _controller.shapeLayerSizeFactor, + ); + final Offset delta = _getValidPanDelta( + localFocalPoint - previousFocalPoint, + ); + final Rect visibleBounds = _controller.getVisibleBounds( _controller.shapeLayerOffset + delta, ); + final MapLatLngBounds newVisibleLatLngBounds = _controller + .getVisibleLatLngBounds( + visibleBounds.topRight, + visibleBounds.bottomLeft, + _controller.shapeLayerOffset + delta, + ); _panDetails = MapPanDetails( globalFocalPoint: localToGlobal(localFocalPoint), localFocalPoint: localFocalPoint, zoomLevel: _zoomPanBehavior!.zoomLevel, delta: delta, - previousVisibleBounds: _panDetails != null - ? _panDetails!.newVisibleBounds - : _controller.visibleLatLngBounds, + previousVisibleBounds: + _panDetails != null + ? _panDetails!.newVisibleBounds + : _controller.visibleLatLngBounds, newVisibleBounds: newVisibleLatLngBounds, focalLatLng: newLatLng, ); @@ -2914,8 +3168,9 @@ class _RenderGeoJSONLayer extends RenderStack _controller.localScale = _getScale(details.newZoomLevel!); _controller.pinchCenter = details.localFocalPoint!; _controller.updateVisibleBounds( - _controller.getZoomingTranslation() + _controller.normalize, - _controller.shapeLayerSizeFactor * _controller.localScale); + _controller.getZoomingTranslation() + _controller.normalize, + _controller.shapeLayerSizeFactor * _controller.localScale, + ); _validateEdges(details.newZoomLevel!); } else if (!_doubleTapEnabled) { // Updating map via toolbar. @@ -2939,18 +3194,20 @@ class _RenderGeoJSONLayer extends RenderStack return; } if (!_isFlingAnimationActive && !_doubleTapEnabled) { - _state.zoomLevelAnimationController.duration = - const Duration(milliseconds: 650); + _state.zoomLevelAnimationController.duration = const Duration( + milliseconds: 650, + ); } _zoomLevelTween.begin = _currentZoomLevel; _zoomLevelTween.end = _zoomPanBehavior!.zoomLevel; if (!_isFlingAnimationActive && !_doubleTapEnabled) { _downLocalPoint = pixelFromLatLng( - _controller.visibleFocalLatLng!.latitude, - _controller.visibleFocalLatLng!.longitude, - _size, - _controller.shapeLayerOffset, - _controller.shapeLayerSizeFactor); + _controller.visibleFocalLatLng!.latitude, + _controller.visibleFocalLatLng!.longitude, + _size, + _controller.shapeLayerOffset, + _controller.shapeLayerSizeFactor, + ); } _controller.isInInteractive = true; _controller.gesture = Gesture.scale; @@ -2961,14 +3218,17 @@ class _RenderGeoJSONLayer extends RenderStack void _handleZoomLevelAnimation() { if (_zoomLevelTween.end != null) { - _currentZoomLevel = _zoomLevelTween.evaluate(_isFlingAnimationActive - ? _flingZoomLevelCurvedAnimation - : _zoomLevelCurvedAnimation!); + _currentZoomLevel = _zoomLevelTween.evaluate( + _isFlingAnimationActive + ? _flingZoomLevelCurvedAnimation + : _zoomLevelCurvedAnimation!, + ); } _controller.localScale = _getScale(_currentZoomLevel); _controller.updateVisibleBounds( - _controller.getZoomingTranslation() + _controller.normalize, - _controller.shapeLayerSizeFactor * _controller.localScale); + _controller.getZoomingTranslation() + _controller.normalize, + _controller.shapeLayerSizeFactor * _controller.localScale, + ); _validateEdges(_currentZoomLevel); _controller.notifyRefreshListeners(); markNeedsPaint(); @@ -3002,8 +3262,10 @@ class _RenderGeoJSONLayer extends RenderStack if (_zoomPanBehavior != null && !_state.isSublayer) { _controller.shapeLayerOffset = _controller.getZoomingTranslation() + _controller.normalize; - _controller.shapeLayerOrigin = _controller.getZoomingTranslation( - previousOrigin: _controller.shapeLayerOrigin) + + _controller.shapeLayerOrigin = + _controller.getZoomingTranslation( + previousOrigin: _controller.shapeLayerOrigin, + ) + _controller.normalize; _controller.shapeLayerSizeFactor *= _controller.localScale; _updateMapDataSourceForVisual(); @@ -3018,28 +3280,34 @@ class _RenderGeoJSONLayer extends RenderStack } void _invokeOnPanning( - Offset localFocalPoint, Offset previousFocalPoint, Offset focalPoint, - [bool canAvoidPanUpdate = false]) { + Offset localFocalPoint, + Offset previousFocalPoint, + Offset focalPoint, [ + bool canAvoidPanUpdate = false, + ]) { _avoidPanUpdate = canAvoidPanUpdate; - final Offset delta = - _getValidPanDelta(localFocalPoint - previousFocalPoint); + final Offset delta = _getValidPanDelta( + localFocalPoint - previousFocalPoint, + ); final Rect visibleBounds = _controller.getVisibleBounds( - _controller.shapeLayerOffset + - (canAvoidPanUpdate ? Offset.zero : delta)); - final MapLatLngBounds newVisibleLatLngBounds = - _controller.getVisibleLatLngBounds( - visibleBounds.topRight, - visibleBounds.bottomLeft, _controller.shapeLayerOffset + (canAvoidPanUpdate ? Offset.zero : delta), ); + final MapLatLngBounds newVisibleLatLngBounds = _controller + .getVisibleLatLngBounds( + visibleBounds.topRight, + visibleBounds.bottomLeft, + _controller.shapeLayerOffset + + (canAvoidPanUpdate ? Offset.zero : delta), + ); _panDetails = MapPanDetails( globalFocalPoint: focalPoint, localFocalPoint: localFocalPoint, zoomLevel: _zoomPanBehavior!.zoomLevel, delta: delta, - previousVisibleBounds: _panDetails != null - ? _panDetails!.newVisibleBounds - : _controller.visibleLatLngBounds, + previousVisibleBounds: + _panDetails != null + ? _panDetails!.newVisibleBounds + : _controller.visibleLatLngBounds, newVisibleBounds: newVisibleLatLngBounds, focalLatLng: getFocalLatLng(newVisibleLatLngBounds), ); @@ -3061,8 +3329,9 @@ class _RenderGeoJSONLayer extends RenderStack if (!_state.isSublayer) { _controller.panDistance = details.delta!; - _controller - .updateVisibleBounds(_controller.shapeLayerOffset + details.delta!); + _controller.updateVisibleBounds( + _controller.shapeLayerOffset + details.delta!, + ); } markNeedsPaint(); @@ -3081,8 +3350,9 @@ class _RenderGeoJSONLayer extends RenderStack return; } if (!_isFlingAnimationActive) { - _state.focalLatLngAnimationController.duration = - const Duration(milliseconds: 650); + _state.focalLatLngAnimationController.duration = const Duration( + milliseconds: 650, + ); } if (_state.focalLatLngAnimationController.isAnimating) { @@ -3092,15 +3362,19 @@ class _RenderGeoJSONLayer extends RenderStack _focalLatLngTween.begin = _controller.visibleFocalLatLng; _focalLatLngTween.end = _zoomPanBehavior!.focalLatLng; _downLocalPoint = pixelFromLatLng( - _controller.visibleFocalLatLng!.latitude, - _controller.visibleFocalLatLng!.longitude, - _size, - _controller.shapeLayerOffset + _panDistanceBeforeFlinging, - _controller.shapeLayerSizeFactor); - _referenceVisibleBounds = - _controller.getVisibleBounds(_controller.shapeLayerOffset); + _controller.visibleFocalLatLng!.latitude, + _controller.visibleFocalLatLng!.longitude, + _size, + _controller.shapeLayerOffset + _panDistanceBeforeFlinging, + _controller.shapeLayerSizeFactor, + ); + _referenceVisibleBounds = _controller.getVisibleBounds( + _controller.shapeLayerOffset, + ); _referenceShapeBounds = _getShapeBounds( - _controller.shapeLayerSizeFactor, _controller.shapeLayerOffset); + _controller.shapeLayerSizeFactor, + _controller.shapeLayerOffset, + ); _controller.isInInteractive = true; _controller.gesture = Gesture.pan; _state.focalLatLngAnimationController.forward(from: 0.0); @@ -3108,20 +3382,24 @@ class _RenderGeoJSONLayer extends RenderStack } void _handleFocalLatLngAnimation() { - final MapLatLng latLng = _focalLatLngTween.evaluate(_isFlingAnimationActive - ? _flingFocalLatLngCurvedAnimation - : _focalLatLngCurvedAnimation); + final MapLatLng latLng = _focalLatLngTween.evaluate( + _isFlingAnimationActive + ? _flingFocalLatLngCurvedAnimation + : _focalLatLngCurvedAnimation, + ); final Offset localFocalPoint = pixelFromLatLng( - latLng.latitude, - latLng.longitude, - _size, - _controller.shapeLayerOffset + _panDistanceBeforeFlinging, - _controller.shapeLayerSizeFactor); + latLng.latitude, + latLng.longitude, + _size, + _controller.shapeLayerOffset + _panDistanceBeforeFlinging, + _controller.shapeLayerSizeFactor, + ); final Offset delta = _getValidPanDelta(_downLocalPoint! - localFocalPoint); _controller.panDistance = _panDistanceBeforeFlinging + delta; _controller.updateVisibleBounds( - _controller.shapeLayerOffset + _panDistanceBeforeFlinging + delta); + _controller.shapeLayerOffset + _panDistanceBeforeFlinging + delta, + ); _controller.notifyRefreshListeners(); markNeedsPaint(); } @@ -3139,10 +3417,13 @@ class _RenderGeoJSONLayer extends RenderStack void _handleFocalLatLngAnimationEnd() { _isFlingAnimationActive = false; _panEnd(); - _referenceVisibleBounds = - _controller.getVisibleBounds(_controller.shapeLayerOffset); + _referenceVisibleBounds = _controller.getVisibleBounds( + _controller.shapeLayerOffset, + ); _referenceShapeBounds = _getShapeBounds( - _controller.shapeLayerSizeFactor, _controller.shapeLayerOffset); + _controller.shapeLayerSizeFactor, + _controller.shapeLayerOffset, + ); } void _panEnd() { @@ -3223,9 +3504,10 @@ class _RenderGeoJSONLayer extends RenderStack if (_currentInteractedItem != null && deviceKind != PointerDeviceKind.mouse) { _invokeTooltip( - position: position, - model: _currentInteractedItem, - element: _currentInteractedElement); + position: position, + model: _currentInteractedItem, + element: _currentInteractedElement, + ); } _downLocalPoint = null; @@ -3239,22 +3521,27 @@ class _RenderGeoJSONLayer extends RenderStack if (_controller.gesture == null && _zoomPanBehavior != null) { double newZoomLevel = _currentZoomLevel + 1; newZoomLevel = newZoomLevel.clamp( - _zoomPanBehavior!.minZoomLevel, _zoomPanBehavior!.maxZoomLevel); + _zoomPanBehavior!.minZoomLevel, + _zoomPanBehavior!.maxZoomLevel, + ); if (newZoomLevel == _currentZoomLevel) { return; } - _state.zoomLevelAnimationController.duration = - const Duration(milliseconds: 200); + _state.zoomLevelAnimationController.duration = const Duration( + milliseconds: 200, + ); _doubleTapEnabled = true; // Based on the isInInteractive value we have updated the maps at // _handleZooming(). To avoid this at double tap zooming, we have reset // the isInInteractive. _controller.isInInteractive = false; - _invokeOnZooming(_getScale(newZoomLevel), - localFocalPoint: _downLocalPoint, - globalFocalPoint: _downGlobalPoint, - focalLatLng: _controller.visibleFocalLatLng); + _invokeOnZooming( + _getScale(newZoomLevel), + localFocalPoint: _downLocalPoint, + globalFocalPoint: _downGlobalPoint, + focalLatLng: _controller.visibleFocalLatLng, + ); } } @@ -3287,7 +3574,8 @@ class _RenderGeoJSONLayer extends RenderStack _state._updateLegendPointer(null); } _state._updateLegendPointer( - _currentInteractedItem!.colorValue?.toDouble()); + _currentInteractedItem!.colorValue?.toDouble(), + ); } else { _state._updateLegendPointer(null); } @@ -3350,7 +3638,9 @@ class _RenderGeoJSONLayer extends RenderStack Offset _getValidPanDelta(Offset delta) { final Rect currentShapeBounds = _getShapeBounds( - _controller.shapeLayerSizeFactor, _controller.shapeLayerOffset + delta); + _controller.shapeLayerSizeFactor, + _controller.shapeLayerOffset + delta, + ); double dx = 0.0, dy = 0.0; if (_referenceVisibleBounds!.width < _referenceShapeBounds!.width) { dx = delta.dx; @@ -3379,11 +3669,16 @@ class _RenderGeoJSONLayer extends RenderStack void _validateEdges(double zoomLevel, [Offset? origin]) { final Offset leftTop = _controller.getZoomingTranslation( - origin: origin, - scale: _getScale(zoomLevel), - previousOrigin: _controller.shapeLayerOrigin); - _controller.currentBounds = Rect.fromLTWH(leftTop.dx, leftTop.dy, - _size.width * zoomLevel, _size.height * zoomLevel); + origin: origin, + scale: _getScale(zoomLevel), + previousOrigin: _controller.shapeLayerOrigin, + ); + _controller.currentBounds = Rect.fromLTWH( + leftTop.dx, + leftTop.dy, + _size.width * zoomLevel, + _size.height * zoomLevel, + ); _controller.normalize = _getNormalizedOffset(zoomLevel); } @@ -3438,7 +3733,10 @@ class _RenderGeoJSONLayer extends RenderStack _currentInteractedItem = mapModel; } } else if (_isShapeContains( - position, mapModel, _currentInteractedElement) && + position, + mapModel, + _currentInteractedElement, + ) && !(wasToggled && _legend!.source == MapElement.shape)) { _currentInteractedItem = mapModel; _currentInteractedElement = MapLayerElement.shape; @@ -3460,7 +3758,10 @@ class _RenderGeoJSONLayer extends RenderStack } bool _isShapeContains( - Offset position, MapModel mapModel, MapLayerElement? element) { + Offset position, + MapModel mapModel, + MapLayerElement? element, + ) { return (_state.widget.onSelectionChanged != null || _state.widget.shapeTooltipBuilder != null || hasShapeHoverColor) && @@ -3472,10 +3773,11 @@ class _RenderGeoJSONLayer extends RenderStack void _performChildHover(Offset position) { final MapModel? currentInteractedItem = _currentInteractedItem; _invokeTooltip( - position: position, - model: _currentInteractedItem, - element: _currentInteractedElement, - kind: PointerKind.hover); + position: position, + model: _currentInteractedItem, + element: _currentInteractedElement, + kind: PointerKind.hover, + ); if (_state.widget.source.bubbleSizeMapper != null && _state.bubbleKey.currentContext != null) { final ShapeLayerChildRenderBoxBase bubbleRenderObject = @@ -3483,7 +3785,9 @@ class _RenderGeoJSONLayer extends RenderStack // ignore: avoid_as as ShapeLayerChildRenderBoxBase; bubbleRenderObject.onHover( - currentInteractedItem, _currentInteractedElement); + currentInteractedItem, + _currentInteractedElement, + ); } if (hasShapeHoverColor && @@ -3513,11 +3817,12 @@ class _RenderGeoJSONLayer extends RenderStack } } - void _invokeTooltip( - {MapModel? model, - Offset? position, - MapLayerElement? element, - PointerKind kind = PointerKind.touch}) { + void _invokeTooltip({ + MapModel? model, + Offset? position, + MapLayerElement? element, + PointerKind kind = PointerKind.touch, + }) { if ((_state.widget.shapeTooltipBuilder != null || _state.widget.bubbleTooltipBuilder != null) && _controller.tooltipKey != null && @@ -3529,18 +3834,27 @@ class _RenderGeoJSONLayer extends RenderStack as ShapeLayerChildRenderBoxBase; if (model != null && element == MapLayerElement.bubble) { elementRect = Rect.fromCircle( - center: model.shapePathCenter!, radius: model.bubbleRadius!); + center: model.shapePathCenter!, + radius: model.bubbleRadius!, + ); } int? sublayerIndex; if (_state.isSublayer) { - sublayerIndex = - _state.ancestor.sublayers!.indexOf(_state.widget.sublayerAncestor!); + sublayerIndex = _state.ancestor.sublayers!.indexOf( + _state.widget.sublayerAncestor!, + ); } // The elementRect is not applicable, if the actual element is shape. The // sublayerIndex is not applicable, if the actual layer is shape layer. - tooltipRenderObject.paintTooltip(model?.dataIndex, elementRect, element, - kind, sublayerIndex, position); + tooltipRenderObject.paintTooltip( + model?.dataIndex, + elementRect, + element, + kind, + sublayerIndex, + position, + ); } } @@ -3555,7 +3869,8 @@ class _RenderGeoJSONLayer extends RenderStack _currentSelectedItem = null; } else { _currentSelectedItem = _mapDataSource.values.firstWhere( - (MapModel element) => element.dataIndex == _selectedIndex); + (MapModel element) => element.dataIndex == _selectedIndex, + ); _currentSelectedItem!.isSelected = !_currentSelectedItem!.isSelected; if (_prevSelectedItem != null) { _prevSelectedItem!.isSelected = false; @@ -3571,8 +3886,9 @@ class _RenderGeoJSONLayer extends RenderStack if (_legend != null && _legend!.source == MapElement.shape) { late MapModel model; if (_state.widget.source.shapeColorMappers == null) { - model = - mapDataSource.values.elementAt(_controller.currentToggledItemIndex); + model = mapDataSource.values.elementAt( + _controller.currentToggledItemIndex, + ); } else { for (final MapModel mapModel in _mapDataSource.values) { if (mapModel.dataIndex != null && @@ -3584,10 +3900,11 @@ class _RenderGeoJSONLayer extends RenderStack } } - final Color shapeColor = (_currentSelectedItem != null && - _currentSelectedItem!.actualIndex == model.actualIndex) - ? _themeData.selectionColor! - : getActualShapeColor(model); + final Color shapeColor = + (_currentSelectedItem != null && + _currentSelectedItem!.actualIndex == model.actualIndex) + ? _themeData.selectionColor! + : getActualShapeColor(model); _forwardToggledShapeColorTween.begin = shapeColor; _reverseToggledShapeColorTween.end = shapeColor; _state.toggleAnimationController.forward(from: 0); @@ -3731,12 +4048,15 @@ class _RenderGeoJSONLayer extends RenderStack _controller.applyTransform(context, offset); final bool hasToggledIndices = _controller.toggledIndices.isNotEmpty; final Paint fillPaint = Paint()..isAntiAlias = true; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; - final bool hasPrevSelectedItem = _prevSelectedItem != null && + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; + final bool hasPrevSelectedItem = + _prevSelectedItem != null && !_controller.wasToggled(_prevSelectedItem!); - final bool hasCurrentSelectedItem = _currentSelectedItem != null && + final bool hasCurrentSelectedItem = + _currentSelectedItem != null && !_controller.wasToggled(_currentSelectedItem!); _mapDataSource.forEach((String key, MapModel model) { @@ -3753,17 +4073,20 @@ class _RenderGeoJSONLayer extends RenderStack fillPaint.color = _reverseSelectionColorTween.evaluate(_selectionColorAnimation)!; strokePaint - ..color = _reverseSelectionStrokeColorTween - .evaluate(_selectionColorAnimation)! + ..color = + _reverseSelectionStrokeColorTween.evaluate( + _selectionColorAnimation, + )! ..strokeWidth = _themeData.selectionStrokeWidth; } else if (_previousHoverItem != null && _previousHoverItem!.primaryKey == key && !_controller.wasToggled(_previousHoverItem!) && _previousHoverItem != _currentHoverItem) { - fillPaint.color = _themeData.shapeHoverColor != Colors.transparent - ? (_reverseHoverColorTween.evaluate(_hoverColorAnimation) ?? - getActualShapeColor(model)) - : getActualShapeColor(model); + fillPaint.color = + _themeData.shapeHoverColor != Colors.transparent + ? (_reverseHoverColorTween.evaluate(_hoverColorAnimation) ?? + getActualShapeColor(model)) + : getActualShapeColor(model); if (_themeData.shapeHoverStrokeWidth! > 0.0 && _themeData.shapeHoverStrokeColor != Colors.transparent) { @@ -3784,8 +4107,9 @@ class _RenderGeoJSONLayer extends RenderStack context.canvas.drawPath(model.shapePath!, fillPaint); if (strokePaint.strokeWidth > 0.0 && strokePaint.color != Colors.transparent) { - strokePaint.strokeWidth = - _getIntrinsicStrokeWidth(strokePaint.strokeWidth); + strokePaint.strokeWidth = _getIntrinsicStrokeWidth( + strokePaint.strokeWidth, + ); context.canvas.drawPath(model.shapePath!, strokePaint); } }); @@ -3800,13 +4124,19 @@ class _RenderGeoJSONLayer extends RenderStack // Set the color to the toggled and un-toggled shapes based on // the [legendController.toggledIndices] collection. void _updateFillColor( - MapModel model, Paint fillPaint, bool hasToggledIndices) { + MapModel model, + Paint fillPaint, + bool hasToggledIndices, + ) { fillPaint.style = PaintingStyle.fill; if (_legend != null && _legend!.source == MapElement.shape) { if (_controller.currentToggledItemIndex == model.legendMapperIndex) { - final Color? shapeColor = _controller.wasToggled(model) - ? _forwardToggledShapeColorTween.evaluate(_toggleShapeAnimation) - : _reverseToggledShapeColorTween.evaluate(_toggleShapeAnimation); + final Color? shapeColor = + _controller.wasToggled(model) + ? _forwardToggledShapeColorTween.evaluate(_toggleShapeAnimation) + : _reverseToggledShapeColorTween.evaluate( + _toggleShapeAnimation, + ); // Set tween color to the shape based on the currently tapped // legend item. If the legend item is toggled, then the // [_forwardToggledShapeColorTween] return. If the legend item is @@ -3827,23 +4157,30 @@ class _RenderGeoJSONLayer extends RenderStack // Set the stroke paint to the toggled and un-toggled shapes based on // the [legendController.toggledIndices] collection. void _updateStrokePaint( - MapModel model, Paint strokePaint, bool hasToggledIndices) { + MapModel model, + Paint strokePaint, + bool hasToggledIndices, + ) { if (_legend != null && _legend!.source == MapElement.shape) { if (_controller.currentToggledItemIndex == model.legendMapperIndex) { - final Color? shapeStrokeColor = _controller.wasToggled(model) - ? _forwardToggledShapeStrokeColorTween - .evaluate(_toggleShapeAnimation) - : _reverseToggledShapeStrokeColorTween - .evaluate(_toggleShapeAnimation); + final Color? shapeStrokeColor = + _controller.wasToggled(model) + ? _forwardToggledShapeStrokeColorTween.evaluate( + _toggleShapeAnimation, + ) + : _reverseToggledShapeStrokeColorTween.evaluate( + _toggleShapeAnimation, + ); // Set tween color to the shape stroke based on the currently // tapped legend item. If the legend item is toggled, then the // [_forwardToggledShapeStrokeColorTween] return. If the legend item is // un-toggled, then the [_reverseToggledShapeStrokeColorTween] return. strokePaint ..color = shapeStrokeColor ?? Colors.transparent - ..strokeWidth = _controller.wasToggled(model) - ? _themeData.toggledItemStrokeWidth! - : _themeData.layerStrokeWidth; + ..strokeWidth = + _controller.wasToggled(model) + ? _themeData.toggledItemStrokeWidth! + : _themeData.layerStrokeWidth; return; } else if (hasToggledIndices && _controller.wasToggled(model)) { // Set toggled stroke color to the previously toggled shapes. @@ -3872,7 +4209,10 @@ class _RenderGeoJSONLayer extends RenderStack } void _drawSelectedShape( - PaintingContext context, Paint fillPaint, Paint strokePaint) { + PaintingContext context, + Paint fillPaint, + Paint strokePaint, + ) { if (_currentSelectedItem != null && !_controller.wasToggled(_currentSelectedItem!)) { fillPaint.color = @@ -3880,29 +4220,37 @@ class _RenderGeoJSONLayer extends RenderStack context.canvas.drawPath(_currentSelectedItem!.shapePath!, fillPaint); if (_themeData.selectionStrokeWidth > 0.0) { strokePaint - ..color = _forwardSelectionStrokeColorTween - .evaluate(_selectionColorAnimation)! - ..strokeWidth = - _getIntrinsicStrokeWidth(_themeData.selectionStrokeWidth); + ..color = + _forwardSelectionStrokeColorTween.evaluate( + _selectionColorAnimation, + )! + ..strokeWidth = _getIntrinsicStrokeWidth( + _themeData.selectionStrokeWidth, + ); context.canvas.drawPath(_currentSelectedItem!.shapePath!, strokePaint); } } } void _drawHoverShape( - PaintingContext context, Paint fillPaint, Paint strokePaint) { + PaintingContext context, + Paint fillPaint, + Paint strokePaint, + ) { if (_currentHoverItem != null) { - fillPaint.color = _themeData.shapeHoverColor != Colors.transparent - ? _forwardHoverColorTween.evaluate(_hoverColorAnimation)! - : getActualShapeColor(_currentHoverItem!); + fillPaint.color = + _themeData.shapeHoverColor != Colors.transparent + ? _forwardHoverColorTween.evaluate(_hoverColorAnimation)! + : getActualShapeColor(_currentHoverItem!); context.canvas.drawPath(_currentHoverItem!.shapePath!, fillPaint); if (_themeData.shapeHoverStrokeWidth! > 0.0 && _themeData.shapeHoverStrokeColor != Colors.transparent) { strokePaint ..color = _forwardHoverStrokeColorTween.evaluate(_hoverColorAnimation)! - ..strokeWidth = - _getIntrinsicStrokeWidth(_themeData.shapeHoverStrokeWidth!); + ..strokeWidth = _getIntrinsicStrokeWidth( + _themeData.shapeHoverStrokeWidth!, + ); } else { strokePaint ..color = _themeData.layerStrokeColor! diff --git a/packages/syncfusion_flutter_maps/lib/src/layer/tile_layer.dart b/packages/syncfusion_flutter_maps/lib/src/layer/tile_layer.dart index e4bf5b4bb..86528e509 100644 --- a/packages/syncfusion_flutter_maps/lib/src/layer/tile_layer.dart +++ b/packages/syncfusion_flutter_maps/lib/src/layer/tile_layer.dart @@ -17,12 +17,19 @@ import '../theme.dart'; import '../utils.dart'; Offset _pixelFromLatLng(MapLatLng latLng, double scale) { - final double latitude = - latLng.latitude.clamp(minimumLatitude, maximumLatitude); - final double longitude = - latLng.longitude.clamp(minimumLongitude, maximumLongitude); + final double latitude = latLng.latitude.clamp( + minimumLatitude, + maximumLatitude, + ); + final double longitude = latLng.longitude.clamp( + minimumLongitude, + maximumLongitude, + ); return pixelFromLatLng( - latitude, longitude, Size.square(getTotalTileWidth(scale))); + latitude, + longitude, + Size.square(getTotalTileWidth(scale)), + ); } MapLatLng _pixelToLatLng(Offset point, double scale) { @@ -115,10 +122,13 @@ class MapTileLayerController extends MapLayerController { /// Converts pixel point to [MapLatLng]. MapLatLng pixelToLatLng(Offset position) { final Offset localPointCenterDiff = Offset( - (_state._size!.width / 2) - position.dx, - (_state._size!.height / 2) - position.dy); - final Offset actualCenterPixelPosition = - _pixelFromLatLng(_state._currentFocalLatLng, _state._currentZoomLevel); + (_state._size!.width / 2) - position.dx, + (_state._size!.height / 2) - position.dy, + ); + final Offset actualCenterPixelPosition = _pixelFromLatLng( + _state._currentFocalLatLng, + _state._currentZoomLevel, + ); final Offset newCenterPoint = actualCenterPixelPosition - localPointCenterDiff; return _pixelToLatLng(newCenterPoint, _state._currentZoomLevel); @@ -228,15 +238,19 @@ class _TileLayerState extends State with TickerProviderStateMixin { void _requestAndPopulateNewTiles() { _updateZoomLevel(); final double tileCount = pow(2, _nextZoomLevel).toDouble(); - final Offset actualCenterPixelPosition = - _pixelFromLatLng(_currentFocalLatLng, _currentZoomLevel); + final Offset actualCenterPixelPosition = _pixelFromLatLng( + _currentFocalLatLng, + _currentZoomLevel, + ); final Rect newVisibleBounds = Rect.fromCenter( - center: actualCenterPixelPosition, - width: _size!.width, - height: _size!.height); + center: actualCenterPixelPosition, + width: _size!.width, + height: _size!.height, + ); final MapLatLngBounds visibleLatLngBounds = MapLatLngBounds( - _pixelToLatLng(newVisibleBounds.topRight, _currentZoomLevel), - _pixelToLatLng(newVisibleBounds.bottomLeft, _currentZoomLevel)); + _pixelToLatLng(newVisibleBounds.topRight, _currentZoomLevel), + _pixelToLatLng(newVisibleBounds.bottomLeft, _currentZoomLevel), + ); _updateVisibleBounds(visibleLatLngBounds); final Offset halfSize = Offset(_size!.width, _size!.height) / 2; @@ -261,8 +275,11 @@ class _TileLayerState extends State with TickerProviderStateMixin { for (int i = startX; i <= endX; i++) { for (int j = startY; j <= endY; j++) { - final _MapTileCoordinate tileCoordinate = - _MapTileCoordinate(i, j, _nextZoomLevel); + final _MapTileCoordinate tileCoordinate = _MapTileCoordinate( + i, + j, + _nextZoomLevel, + ); if ((tileCoordinate.x < _globalTileStart.dx || tileCoordinate.x > globalTileEnd.dx) || @@ -281,11 +298,15 @@ class _TileLayerState extends State with TickerProviderStateMixin { } final Offset tileCenter = Offset((startX + endX) / 2, (startY + endY) / 2); - tileCoordinates.sort((_MapTileCoordinate a, _MapTileCoordinate b) => - (a.distanceTo(Offset(a.x.toDouble(), a.y.toDouble()), tileCenter) - - b.distanceTo( - Offset(b.x.toDouble(), b.y.toDouble()), tileCenter)) - .toInt()); + tileCoordinates.sort( + (_MapTileCoordinate a, _MapTileCoordinate b) => + (a.distanceTo(Offset(a.x.toDouble(), a.y.toDouble()), tileCenter) - + b.distanceTo( + Offset(b.x.toDouble(), b.y.toDouble()), + tileCenter, + )) + .toInt(), + ); for (int i = 0; i < tileCoordinates.length; i++) { _addTile(tileCoordinates[i]); @@ -296,17 +317,18 @@ class _TileLayerState extends State with TickerProviderStateMixin { final TileZoomLevelDetails level = _levels[_nextZoomLevel]!; Offset topRight = _pixelFromLatLng(latLngBounds.northeast, level.zoomLevel) - - level.origin!; + level.origin!; // Adjust the topRight value based on the current scale value. - topRight = Offset(topRight.dx * level.scale, topRight.dy * level.scale) + + topRight = + Offset(topRight.dx * level.scale, topRight.dy * level.scale) + level.translatePoint; Offset bottomLeft = _pixelFromLatLng(latLngBounds.southwest, level.zoomLevel) - - level.origin!; + level.origin!; // Adjust the bottomLeft value based on the current scale value. bottomLeft = Offset(bottomLeft.dx * level.scale, bottomLeft.dy * level.scale) + - level.translatePoint; + level.translatePoint; _controller!.visibleBounds = Rect.fromPoints(bottomLeft, topRight); } @@ -352,7 +374,10 @@ class _TileLayerState extends State with TickerProviderStateMixin { (_zoomController != null && _zoomController!.actionType == ActionType.pinch)) { _updateZoomLevelTransform( - level, _currentFocalLatLng, _currentZoomLevel); + level, + _currentFocalLatLng, + _currentZoomLevel, + ); } } @@ -391,7 +416,10 @@ class _TileLayerState extends State with TickerProviderStateMixin { // Calculate amount of scale and translation for each zoom level while // scaling. void _updateZoomLevelTransform( - TileZoomLevelDetails level, MapLatLng center, double zoom) { + TileZoomLevelDetails level, + MapLatLng center, + double zoom, + ) { if (level.origin == null) { return; } @@ -399,8 +427,9 @@ class _TileLayerState extends State with TickerProviderStateMixin { getTotalTileWidth(zoom) / getTotalTileWidth(level.zoomLevel); final Offset scaledPixelOrigin = _getLevelOrigin(center, zoom); level.translatePoint = Offset( - (level.origin!.dx * currentScale) - scaledPixelOrigin.dx, - (level.origin!.dy * currentScale) - scaledPixelOrigin.dy); + (level.origin!.dx * currentScale) - scaledPixelOrigin.dx, + (level.origin!.dy * currentScale) - scaledPixelOrigin.dy, + ); level.scale = currentScale; if (level.zoomLevel == _nextZoomLevel) { @@ -428,10 +457,7 @@ class _TileLayerState extends State with TickerProviderStateMixin { xyzKey: tileFactorToKey, tilePos: Offset(tileLeftPos, tileTopPos), level: _levels[tileFactor.z]!, - image: Image.network( - url, - fit: BoxFit.fill, - ), + image: Image.network(url, fit: BoxFit.fill), ); } @@ -574,22 +600,25 @@ class _TileLayerState extends State with TickerProviderStateMixin { final List children = []; Widget current; - current = Stack(children: [ - _buildTiles(), - if (_hasSublayer) - SublayerContainer(ancestor: _ancestor, children: widget.sublayers!), - if (_markers != null && _markers!.isNotEmpty) - MarkerContainer( - markerTooltipBuilder: widget.markerTooltipBuilder, - controller: _controller!, - themeData: _mapsThemeData, - children: _markers, - ), - ]); + current = Stack( + children: [ + _buildTiles(), + if (_hasSublayer) + SublayerContainer(ancestor: _ancestor, children: widget.sublayers!), + if (_markers != null && _markers!.isNotEmpty) + MarkerContainer( + markerTooltipBuilder: widget.markerTooltipBuilder, + controller: _controller!, + themeData: _mapsThemeData, + children: _markers, + ), + ], + ); children.add(current); if (widget.zoomPanBehavior != null) { - children.add(BehaviorView( + children.add( + BehaviorView( zoomLevel: _currentZoomLevel, focalLatLng: _currentFocalLatLng, controller: _controller!, @@ -597,24 +626,30 @@ class _TileLayerState extends State with TickerProviderStateMixin { onWillZoom: widget.onWillZoom, onWillPan: widget.onWillPan, enableMouseWheelZooming: - widget.zoomPanBehavior!.enableMouseWheelZooming)); + widget.zoomPanBehavior!.enableMouseWheelZooming, + ), + ); if (_isDesktop && widget.zoomPanBehavior!.showToolbar) { - children.add(MapToolbar( - zoomPanBehavior: widget.zoomPanBehavior!, - controller: _controller, - )); + children.add( + MapToolbar( + zoomPanBehavior: widget.zoomPanBehavior!, + controller: _controller, + ), + ); } } if (_hasTooltipBuilder()) { - children.add(MapTooltip( - key: _controller!.tooltipKey, - controller: _controller, - sublayers: widget.sublayers, - markerTooltipBuilder: widget.markerTooltipBuilder, - tooltipSettings: widget.tooltipSettings, - themeData: _mapsThemeData, - )); + children.add( + MapTooltip( + key: _controller!.tooltipKey, + controller: _controller, + sublayers: widget.sublayers, + markerTooltipBuilder: widget.markerTooltipBuilder, + tooltipSettings: widget.tooltipSettings, + themeData: _mapsThemeData, + ), + ); } return SizedBox( @@ -636,10 +671,13 @@ class _TileLayerState extends State with TickerProviderStateMixin { setState(() { _currentZoomLevel = _zoomController!.zoomLevel; final Offset point = Offset( - (_size!.width / 2) - _zoomController!.actualRect.left, - (_size!.height / 2) - _zoomController!.actualRect.top); + (_size!.width / 2) - _zoomController!.actualRect.left, + (_size!.height / 2) - _zoomController!.actualRect.top, + ); final MapLatLng newFocalLatLng = pixelToLatLng( - point, Size.square(getTotalTileWidth(_currentZoomLevel))); + point, + Size.square(getTotalTileWidth(_currentZoomLevel)), + ); _currentFocalLatLng = newFocalLatLng; _handleTransform(); if (_hasSublayer) { @@ -667,12 +705,13 @@ class _TileLayerState extends State with TickerProviderStateMixin { void _initializeController() { _ancestor = context.dependOnInheritedWidgetOfExactType()!; - _controller ??= _ancestor.controller - ..tileZoomLevel = _currentZoomLevel - ..visibleFocalLatLng = _currentFocalLatLng; + _controller ??= + _ancestor.controller + ..tileZoomLevel = _currentZoomLevel + ..visibleFocalLatLng = _currentFocalLatLng; if (_ancestor.zoomController != null) { - _zoomController ??= _ancestor.zoomController! - ..addListener(_handledZoomPanChange); + _zoomController ??= + _ancestor.zoomController!..addListener(_handledZoomPanChange); } } @@ -680,16 +719,22 @@ class _TileLayerState extends State with TickerProviderStateMixin { final MapLatLngBounds? bounds = widget.zoomPanBehavior?.latLngBounds ?? widget.initialLatLngBounds; if (bounds != null) { - final double zoomLevel = - getZoomLevel(bounds, _controller!.layerType!, _size!); + final double zoomLevel = getZoomLevel( + bounds, + _controller!.layerType!, + _size!, + ); _currentFocalLatLng = getFocalLatLng(bounds); if (widget.zoomPanBehavior != null) { _currentZoomLevel = zoomLevel.clamp( - widget.zoomPanBehavior!.minZoomLevel, - widget.zoomPanBehavior!.maxZoomLevel); + widget.zoomPanBehavior!.minZoomLevel, + widget.zoomPanBehavior!.maxZoomLevel, + ); } else { - _currentZoomLevel = - zoomLevel.clamp(kDefaultMinZoomLevel, kDefaultMaxZoomLevel); + _currentZoomLevel = zoomLevel.clamp( + kDefaultMinZoomLevel, + kDefaultMaxZoomLevel, + ); } _nextZoomLevel = _currentZoomLevel.floor(); _controller! @@ -702,10 +747,11 @@ class _TileLayerState extends State with TickerProviderStateMixin { void initState() { _currentFocalLatLng = widget.zoomPanBehavior?.focalLatLng ?? widget.initialFocalLatLng; - _currentZoomLevel = (widget.zoomPanBehavior != null && - widget.zoomPanBehavior!.zoomLevel != 1) - ? widget.zoomPanBehavior!.zoomLevel - : widget.initialZoomLevel.toDouble(); + _currentZoomLevel = + (widget.zoomPanBehavior != null && + widget.zoomPanBehavior!.zoomLevel != 1) + ? widget.zoomPanBehavior!.zoomLevel + : widget.initialZoomLevel.toDouble(); widget.zoomPanBehavior?.zoomLevel = _currentZoomLevel; _nextZoomLevel = _currentZoomLevel.floor(); if (widget.controller != null) { @@ -752,24 +798,30 @@ class _TileLayerState extends State with TickerProviderStateMixin { Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); final MapsThemeData effectiveMapsThemeData = MapsThemeData(context); - _isDesktop = kIsWeb || + _isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; _mapsThemeData = SfMapsTheme.of(context)!; _mapsThemeData = _mapsThemeData.copyWith( - tooltipColor: widget.tooltipSettings.color ?? + tooltipColor: + widget.tooltipSettings.color ?? _mapsThemeData.tooltipColor ?? effectiveMapsThemeData.tooltipColor, - tooltipStrokeColor: widget.tooltipSettings.strokeColor ?? + tooltipStrokeColor: + widget.tooltipSettings.strokeColor ?? _mapsThemeData.tooltipStrokeColor ?? effectiveMapsThemeData.tooltipStrokeColor, - tooltipStrokeWidth: widget.tooltipSettings.strokeWidth ?? + tooltipStrokeWidth: + widget.tooltipSettings.strokeWidth ?? _mapsThemeData.tooltipStrokeWidth, - tooltipBorderRadius: _mapsThemeData.tooltipBorderRadius - .resolve(Directionality.of(context)), - markerIconColor: _mapsThemeData.markerIconColor ?? + tooltipBorderRadius: _mapsThemeData.tooltipBorderRadius.resolve( + Directionality.of(context), + ), + markerIconColor: + _mapsThemeData.markerIconColor ?? effectiveMapsThemeData.markerIconColor, ); diff --git a/packages/syncfusion_flutter_maps/lib/src/layer/vector_layers.dart b/packages/syncfusion_flutter_maps/lib/src/layer/vector_layers.dart index 884ffbd89..606613059 100644 --- a/packages/syncfusion_flutter_maps/lib/src/layer/vector_layers.dart +++ b/packages/syncfusion_flutter_maps/lib/src/layer/vector_layers.dart @@ -31,8 +31,10 @@ Offset _getTranslation(MapController controller) { Offset _getScaledOffset(Offset offset, MapController controller) { if (controller.layerType == LayerType.tile) { - return Offset(offset.dx * controller.tileCurrentLevelDetails.scale, - offset.dy * controller.tileCurrentLevelDetails.scale) + + return Offset( + offset.dx * controller.tileCurrentLevelDetails.scale, + offset.dy * controller.tileCurrentLevelDetails.scale, + ) + controller.tileCurrentLevelDetails.translatePoint; } @@ -41,13 +43,19 @@ Offset _getScaledOffset(Offset offset, MapController controller) { // To calculate a point along a line with a radius away from another point. Offset _getPointAlongLineWithCap( - Offset start, Offset end, double capRadius, bool canUpdateStartPoint) { + Offset start, + Offset end, + double capRadius, + bool canUpdateStartPoint, +) { // Calculate distance between two points. // i.e, d = sqrt[(x1 - x2)^2 + (y1 - y2)^2]. // Here, x1 = end point's dx value, x2 = start point's dx value, // y1 = end point's dy value and y2 = start point's dy value. - final double lineLength = sqrt((end.dx - start.dx) * (end.dx - start.dx) + - (end.dy - start.dy) * (end.dy - start.dy)); + final double lineLength = sqrt( + (end.dx - start.dx) * (end.dx - start.dx) + + (end.dy - start.dy) * (end.dy - start.dy), + ); if (canUpdateStartPoint) { // Calculated the center point, if the distance between the two points // is less than the cap diameter. @@ -62,8 +70,9 @@ Offset _getPointAlongLineWithCap( // y1 = start point's dy value, y2 = end point's dy value // and d = startPointDifference. return Offset( - (1 - startPointDifference) * start.dx + startPointDifference * end.dx, - (1 - startPointDifference) * start.dy + startPointDifference * end.dy); + (1 - startPointDifference) * start.dx + startPointDifference * end.dx, + (1 - startPointDifference) * start.dy + startPointDifference * end.dy, + ); } else { // Returned the start point, if the distance between the two points // is less than the cap radius. @@ -78,44 +87,51 @@ Offset _getPointAlongLineWithCap( // y1 = start point's dy value, y2 = end point's dy value // and d = endPointDifference. return Offset( - (1 - endPointDifference) * start.dx + endPointDifference * end.dx, - (1 - endPointDifference) * start.dy + endPointDifference * end.dy); + (1 - endPointDifference) * start.dx + endPointDifference * end.dx, + (1 - endPointDifference) * start.dy + endPointDifference * end.dy, + ); } } void _drawInvertedPath( - PaintingContext context, - Path path, - MapController controller, - Paint fillPaint, - Paint strokePaint, - Offset offset) { + PaintingContext context, + Path path, + MapController controller, + Paint fillPaint, + Paint strokePaint, + Offset offset, +) { // Path.combine option is not supported in web platform, so we have obtained // inverted rendering using [Path.fillType] for web and [Path.combine] for // other platforms. if (kIsWeb) { context.canvas.drawPath( - Path() - ..addPath(path, offset) - ..addRect(controller.visibleBounds!) - ..fillType = PathFillType.evenOdd, - fillPaint); + Path() + ..addPath(path, offset) + ..addRect(controller.visibleBounds!) + ..fillType = PathFillType.evenOdd, + fillPaint, + ); context.canvas.drawPath(path, strokePaint); } else { context.canvas ..drawPath( - Path.combine( - PathOperation.difference, - Path()..addRect(controller.visibleBounds!), - path, - ), - fillPaint) + Path.combine( + PathOperation.difference, + Path()..addRect(controller.visibleBounds!), + path, + ), + fillPaint, + ) ..drawPath(path, strokePaint); } } Color _getHoverColor( - Color? elementColor, Color layerColor, SfMapsThemeData themeData) { + Color? elementColor, + Color layerColor, + SfMapsThemeData themeData, +) { final Color color = elementColor ?? layerColor; return themeData.shapeHoverColor != null && themeData.shapeHoverColor != Colors.transparent @@ -126,10 +142,8 @@ Color _getHoverColor( /// Base class for all vector layers. abstract class MapVectorLayer extends MapSublayer { /// Creates a [MapVectorLayer]. - const MapVectorLayer({ - Key? key, - IndexedWidgetBuilder? tooltipBuilder, - }) : super(key: key, tooltipBuilder: tooltipBuilder); + const MapVectorLayer({Key? key, IndexedWidgetBuilder? tooltipBuilder}) + : super(key: key, tooltipBuilder: tooltipBuilder); } /// A sublayer which renders group of [MapLine] on [MapShapeLayer] and @@ -675,14 +689,17 @@ class MapLineLayer extends MapVectorLayer { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (lines.isNotEmpty) { - final _DebugVectorShapeTree pointerTreeNode = - _DebugVectorShapeTree(lines); + final _DebugVectorShapeTree pointerTreeNode = _DebugVectorShapeTree( + lines, + ); properties.add(pointerTreeNode.toDiagnosticsNode()); } - properties - .add(ObjectFlagProperty>.has('animation', animation)); - properties.add(ObjectFlagProperty.has( - 'tooltip', tooltipBuilder)); + properties.add( + ObjectFlagProperty>.has('animation', animation), + ); + properties.add( + ObjectFlagProperty.has('tooltip', tooltipBuilder), + ); properties.add(DiagnosticsProperty>('dashArray', dashArray)); if (color != null) { @@ -729,14 +746,17 @@ class _MapLineLayerState extends State<_MapLineLayer> void initState() { super.initState(); _hoverAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); } @override void didChangeDependencies() { if (_controller == null) { - ancestor = context - .dependOnInheritedWidgetOfExactType()!; + ancestor = + context + .dependOnInheritedWidgetOfExactType()!; _controller = ancestor.controller; } super.didChangeDependencies(); @@ -752,7 +772,8 @@ class _MapLineLayerState extends State<_MapLineLayer> @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -761,7 +782,8 @@ class _MapLineLayerState extends State<_MapLineLayer> controller: _controller, lines: widget.lines, animation: widget.animation, - color: widget.color ?? + color: + widget.color ?? (themeData.brightness == Brightness.light ? themeData.colorScheme.onSurface.withValues(alpha: 0.44) : themeData.colorScheme.onSurface.withValues(alpha: 0.78)), @@ -861,20 +883,22 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { required this.isDesktop, required this.hoverAnimationController, required this.state, - }) : _controller = controller, - _lines = lines, - _animation = animation, - _color = color, - _width = width, - _strokeCap = strokeCap, - _dashArray = dashArray, - _tooltipBuilder = tooltipBuilder, - _themeData = themeData { + }) : _controller = controller, + _lines = lines, + _animation = animation, + _color = color, + _width = width, + _strokeCap = strokeCap, + _dashArray = dashArray, + _tooltipBuilder = tooltipBuilder, + _themeData = themeData { selectedLinePoints = []; _forwardHoverColor = ColorTween(); _reverseHoverColor = ColorTween(); _hoverColorAnimation = CurvedAnimation( - parent: hoverAnimationController, curve: Curves.easeInOut); + parent: hoverAnimationController, + curve: Curves.easeInOut, + ); linesInList = _lines.toList(); _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; } @@ -987,8 +1011,11 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { void _updateHoverItemTween() { if (isDesktop) { - final Color hoverStrokeColor = - _getHoverColor(selectedLine?.color, _color, _themeData); + final Color hoverStrokeColor = _getHoverColor( + selectedLine?.color, + _color, + _themeData, + ); final Color beginColor = selectedLine?.color ?? _color; if (_previousHoverItem != null) { @@ -1034,8 +1061,10 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { markNeedsPaint(); } - void _handleInteraction(Offset position, - [PointerKind kind = PointerKind.touch]) { + void _handleInteraction( + Offset position, [ + PointerKind kind = PointerKind.touch, + ]) { if (_controller != null && _controller!.tooltipKey != null && _controller!.tooltipKey!.currentContext != null) { @@ -1047,10 +1076,11 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { final Offset startPoint = selectedLinePoints![0]; final Offset endPoint = selectedLinePoints![1]; final Offset lineMidPosition = Offset( - min(startPoint.dx, endPoint.dx) + - ((startPoint.dx - endPoint.dx).abs() / 2), - min(startPoint.dy, endPoint.dy) + - ((startPoint.dy - endPoint.dy).abs() / 2)); + min(startPoint.dx, endPoint.dx) + + ((startPoint.dx - endPoint.dx).abs() / 2), + min(startPoint.dy, endPoint.dy) + + ((startPoint.dy - endPoint.dy).abs() / 2), + ); position = !paintBounds.contains(lineMidPosition) ? position : lineMidPosition; tooltipRenderer.paintTooltip( @@ -1092,9 +1122,10 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { return false; } - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); int index = linesInList!.length - 1; for (final MapLine line in linesInList!.reversed) { @@ -1120,7 +1151,11 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { endPoint = _getScaledOffset(endPoint, _controller!); if (_liesPointOnLine( - startPoint, endPoint, actualTouchTolerance, position)) { + startPoint, + endPoint, + actualTouchTolerance, + position, + )) { selectedLine = line; selectedIndex = index; selectedLinePoints! @@ -1150,7 +1185,9 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { // ignore: avoid_as final RenderBox renderBox = context.findRenderObject()! as RenderBox; _handleInteraction( - renderBox.globalToLocal(event.position), PointerKind.hover); + renderBox.globalToLocal(event.position), + PointerKind.hover, + ); } } @@ -1202,13 +1239,15 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { context.canvas.save(); Offset startPoint; Offset endPoint; - final Paint paint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; Path path = Path(); - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); _controller!.applyTransform(context, offset, true); @@ -1227,15 +1266,25 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { translationOffset, _controller!.shapeLayerSizeFactor, ); - final double strokeWidth = - _getCurrentWidth(line.width ?? _width, _controller!); + final double strokeWidth = _getCurrentWidth( + line.width ?? _width, + _controller!, + ); final StrokeCap strokeCap = line.strokeCap ?? _strokeCap; final bool hasCap = strokeCap != StrokeCap.butt; if (hasCap) { startPoint = _getPointAlongLineWithCap( - startPoint, endPoint, strokeWidth / 2, true); + startPoint, + endPoint, + strokeWidth / 2, + true, + ); endPoint = _getPointAlongLineWithCap( - startPoint, endPoint, strokeWidth / 2, false); + startPoint, + endPoint, + strokeWidth / 2, + false, + ); } if (_previousHoverItem != null && @@ -1263,8 +1312,13 @@ class _RenderMapLine extends RenderBox implements MouseTrackerAnnotation { if (line.dashArray != null) { assert(line.dashArray!.length >= 2 && line.dashArray!.length.isEven); - _drawDashedLine(context.canvas, line.dashArray!, paint, path, - hasCap ? strokeWidth / 2 : 0); + _drawDashedLine( + context.canvas, + line.dashArray!, + paint, + path, + hasCap ? strokeWidth / 2 : 0, + ); } else { _drawDashedLine(context.canvas, _dashArray, paint, path); } @@ -1746,10 +1800,12 @@ class MapArcLayer extends MapVectorLayer { final _DebugVectorShapeTree pointerTreeNode = _DebugVectorShapeTree(arcs); properties.add(pointerTreeNode.toDiagnosticsNode()); } - properties - .add(ObjectFlagProperty>.has('animation', animation)); - properties.add(ObjectFlagProperty.has( - 'tooltip', tooltipBuilder)); + properties.add( + ObjectFlagProperty>.has('animation', animation), + ); + properties.add( + ObjectFlagProperty.has('tooltip', tooltipBuilder), + ); properties.add(DiagnosticsProperty>('dashArray', dashArray)); if (color != null) { properties.add(ColorProperty('color', color)); @@ -1792,14 +1848,17 @@ class _MapArcLayerState extends State<_MapArcLayer> void initState() { super.initState(); _hoverAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); } @override void didChangeDependencies() { if (_controller == null) { - ancestor = context - .dependOnInheritedWidgetOfExactType()!; + ancestor = + context + .dependOnInheritedWidgetOfExactType()!; _controller = ancestor.controller; } super.didChangeDependencies(); @@ -1815,7 +1874,8 @@ class _MapArcLayerState extends State<_MapArcLayer> @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -1824,7 +1884,8 @@ class _MapArcLayerState extends State<_MapArcLayer> controller: _controller, arcs: widget.arcs, animation: widget.animation, - color: widget.color ?? + color: + widget.color ?? (themeData.brightness == Brightness.light ? themeData.colorScheme.onSurface.withValues(alpha: 0.44) : themeData.colorScheme.onSurface.withValues(alpha: 0.78)), @@ -1918,18 +1979,20 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { required this.isDesktop, required this.hoverAnimationController, required this.state, - }) : _controller = controller, - _arcs = arcs, - _color = color, - _width = width, - _dashArray = dashArray, - _animation = animation, - _tooltipBuilder = tooltipBuilder, - _themeData = themeData { + }) : _controller = controller, + _arcs = arcs, + _color = color, + _width = width, + _dashArray = dashArray, + _animation = animation, + _tooltipBuilder = tooltipBuilder, + _themeData = themeData { _forwardHoverColor = ColorTween(); _reverseHoverColor = ColorTween(); _hoverColorAnimation = CurvedAnimation( - parent: hoverAnimationController, curve: Curves.easeInOut); + parent: hoverAnimationController, + curve: Curves.easeInOut, + ); arcsInList = _arcs.toList(); _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; } @@ -2031,8 +2094,11 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { void _updateHoverItemTween() { if (isDesktop) { - final Color hoverStrokeColor = - _getHoverColor(selectedArc.color, _color, _themeData); + final Color hoverStrokeColor = _getHoverColor( + selectedArc.color, + _color, + _themeData, + ); final Color beginColor = selectedArc.color ?? _color; if (_previousHoverItem != null) { @@ -2098,8 +2164,10 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { // ignore: override_on_non_overriding_member bool get validForMouseTracker => true; - void _handleInteraction(Offset position, - [PointerKind kind = PointerKind.touch]) { + void _handleInteraction( + Offset position, [ + PointerKind kind = PointerKind.touch, + ]) { if (_controller != null && _controller!.tooltipKey != null && _controller!.tooltipKey!.currentContext != null) { @@ -2126,9 +2194,10 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { return false; } - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); int index = arcsInList!.length - 1; for (final MapArc arc in arcsInList!.reversed) { @@ -2153,10 +2222,19 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { startPoint = _getScaledOffset(startPoint, _controller!); endPoint = _getScaledOffset(endPoint, _controller!); final Offset controlPoint = _calculateControlPoint( - startPoint, endPoint, arc.heightFactor, arc.controlPointFactor); + startPoint, + endPoint, + arc.heightFactor, + arc.controlPointFactor, + ); - if (_liesPointOnArc(startPoint, endPoint, controlPoint, - actualTouchTolerance, position)) { + if (_liesPointOnArc( + startPoint, + endPoint, + controlPoint, + actualTouchTolerance, + position, + )) { selectedArc = arc; selectedIndex = index; return true; @@ -2182,7 +2260,9 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { // ignore: avoid_as final RenderBox renderBox = context.findRenderObject()! as RenderBox; _handleInteraction( - renderBox.globalToLocal(event.position), PointerKind.hover); + renderBox.globalToLocal(event.position), + PointerKind.hover, + ); } } @@ -2234,13 +2314,15 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { context.canvas.save(); Offset startPoint; Offset endPoint; - final Paint paint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; Path path = Path(); - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); _controller!.applyTransform(context, offset, true); @@ -2260,7 +2342,11 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { _controller!.shapeLayerSizeFactor, ); final Offset controlPoint = _calculateControlPoint( - startPoint, endPoint, arc.heightFactor, arc.controlPointFactor); + startPoint, + endPoint, + arc.heightFactor, + arc.controlPointFactor, + ); if (_previousHoverItem != null && _previousHoverItem == arc && @@ -2279,7 +2365,11 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { ..reset() ..moveTo(startPoint.dx, startPoint.dy) ..quadraticBezierTo( - controlPoint.dx, controlPoint.dy, endPoint.dx, endPoint.dy); + controlPoint.dx, + controlPoint.dy, + endPoint.dx, + endPoint.dy, + ); if (_animation != null) { path = _getAnimatedPath(path, _animation!); } @@ -2294,8 +2384,12 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { context.canvas.restore(); } - Offset _calculateControlPoint(Offset startPoint, Offset endPoint, - double heightFactor, double controlPointFactor) { + Offset _calculateControlPoint( + Offset startPoint, + Offset endPoint, + double heightFactor, + double controlPointFactor, + ) { final double width = endPoint.dx - startPoint.dx; final double height = endPoint.dy - startPoint.dy; // Calculating curve height from base line based on the value of @@ -2307,17 +2401,22 @@ class _RenderMapArc extends RenderBox implements MouseTrackerAnnotation { // value. Converting factor value into pixel value using this formula // (((1 − factor)𝑥0 + factor * 𝑥1),((1 − factor)𝑦0 + factor * 𝑦1)) Offset controlPoint = Offset( - (1 - controlPointFactor) * startPoint.dx + - controlPointFactor * endPoint.dx, - (1 - controlPointFactor) * startPoint.dy + - controlPointFactor * endPoint.dy); + (1 - controlPointFactor) * startPoint.dx + + controlPointFactor * endPoint.dx, + (1 - controlPointFactor) * startPoint.dy + + controlPointFactor * endPoint.dy, + ); if (startPoint.dx < endPoint.dx) { - controlPoint = Offset(controlPoint.dx + horizontalDistance, - controlPoint.dy - verticalDistance); + controlPoint = Offset( + controlPoint.dx + horizontalDistance, + controlPoint.dy - verticalDistance, + ); } else { - controlPoint = Offset(controlPoint.dx - horizontalDistance, - controlPoint.dy + verticalDistance); + controlPoint = Offset( + controlPoint.dx - horizontalDistance, + controlPoint.dy + verticalDistance, + ); } return controlPoint; } @@ -2820,14 +2919,17 @@ class MapPolylineLayer extends MapVectorLayer { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (polylines.isNotEmpty) { - final _DebugVectorShapeTree pointerTreeNode = - _DebugVectorShapeTree(polylines); + final _DebugVectorShapeTree pointerTreeNode = _DebugVectorShapeTree( + polylines, + ); properties.add(pointerTreeNode.toDiagnosticsNode()); } - properties - .add(ObjectFlagProperty>.has('animation', animation)); - properties.add(ObjectFlagProperty.has( - 'tooltip', tooltipBuilder)); + properties.add( + ObjectFlagProperty>.has('animation', animation), + ); + properties.add( + ObjectFlagProperty.has('tooltip', tooltipBuilder), + ); properties.add(DiagnosticsProperty>('dashArray', dashArray)); if (color != null) { properties.add(ColorProperty('color', color)); @@ -2873,14 +2975,17 @@ class _MapPolylineLayerState extends State<_MapPolylineLayer> void initState() { super.initState(); _hoverAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); } @override void didChangeDependencies() { if (_controller == null) { - ancestor = context - .dependOnInheritedWidgetOfExactType()!; + ancestor = + context + .dependOnInheritedWidgetOfExactType()!; _controller = ancestor.controller; } super.didChangeDependencies(); @@ -2896,7 +3001,8 @@ class _MapPolylineLayerState extends State<_MapPolylineLayer> @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -2905,7 +3011,8 @@ class _MapPolylineLayerState extends State<_MapPolylineLayer> controller: _controller, polylines: widget.polylines, animation: widget.animation, - color: widget.color ?? + color: + widget.color ?? (themeData.brightness == Brightness.light ? themeData.colorScheme.onSurface.withValues(alpha: 0.44) : themeData.colorScheme.onSurface.withValues(alpha: 0.78)), @@ -2975,7 +3082,9 @@ class _MapPolylineLayerRenderObject extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, _RenderMapPolyline renderObject) { + BuildContext context, + _RenderMapPolyline renderObject, + ) { renderObject ..polylines = polylines ..animation = animation @@ -3006,19 +3115,21 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { required this.isDesktop, required this.hoverAnimationController, required this.state, - }) : _controller = controller, - _polylines = polylines, - _color = color, - _width = width, - _strokeCap = strokeCap, - _dashArray = dashArray, - _animation = animation, - _tooltipBuilder = tooltipBuilder, - _themeData = themeData { + }) : _controller = controller, + _polylines = polylines, + _color = color, + _width = width, + _strokeCap = strokeCap, + _dashArray = dashArray, + _animation = animation, + _tooltipBuilder = tooltipBuilder, + _themeData = themeData { _forwardHoverColor = ColorTween(); _reverseHoverColor = ColorTween(); _hoverColorAnimation = CurvedAnimation( - parent: hoverAnimationController, curve: Curves.easeInOut); + parent: hoverAnimationController, + curve: Curves.easeInOut, + ); polylinesInList = _polylines.toList(); _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; } @@ -3129,8 +3240,11 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { void _updateHoverItemTween() { if (isDesktop) { - final Color hoverStrokeColor = - _getHoverColor(selectedPolyline.color, _color, _themeData); + final Color hoverStrokeColor = _getHoverColor( + selectedPolyline.color, + _color, + _themeData, + ); final Color beginColor = selectedPolyline.color ?? _color; if (_previousHoverItem != null) { @@ -3177,8 +3291,10 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { markNeedsPaint(); } - void _handleInteraction(Offset position, - [PointerKind kind = PointerKind.touch]) { + void _handleInteraction( + Offset position, [ + PointerKind kind = PointerKind.touch, + ]) { if (_controller != null && _controller!.tooltipKey != null && _controller!.tooltipKey!.currentContext != null) { @@ -3224,9 +3340,10 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { return false; } - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); bool tappedOnLine = false; int index = polylinesInList!.length - 1; @@ -3260,7 +3377,11 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { endPoint = _getScaledOffset(endPoint, _controller!); if (_liesPointOnLine( - startPoint, endPoint, actualTouchTolerance, position)) { + startPoint, + endPoint, + actualTouchTolerance, + position, + )) { tappedOnLine = true; selectedPolyline = polyline; selectedIndex = index; @@ -3320,7 +3441,9 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { // ignore: avoid_as final RenderBox renderBox = context.findRenderObject()! as RenderBox; _handleInteraction( - renderBox.globalToLocal(event.position), PointerKind.hover); + renderBox.globalToLocal(event.position), + PointerKind.hover, + ); } } @@ -3338,62 +3461,79 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { return; } context.canvas.save(); - final Paint paint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; Path path = Path(); - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); _controller!.applyTransform(context, offset, true); for (final MapPolyline polyline in polylines) { final int polylinePointsLength = polyline.points.length; final MapLatLng startCoordinate = polyline.points[0]; final MapLatLng endCoordinate = polyline.points[polylinePointsLength - 1]; - final double strokeWidth = - _getCurrentWidth(polyline.width ?? _width, _controller!); + final double strokeWidth = _getCurrentWidth( + polyline.width ?? _width, + _controller!, + ); final StrokeCap strokeCap = polyline.strokeCap ?? _strokeCap; final bool hasCap = strokeCap != StrokeCap.butt; Offset startPoint = pixelFromLatLng( - startCoordinate.latitude, - startCoordinate.longitude, - boxSize, - translationOffset, - _controller!.shapeLayerSizeFactor); + startCoordinate.latitude, + startCoordinate.longitude, + boxSize, + translationOffset, + _controller!.shapeLayerSizeFactor, + ); Offset endPoint = pixelFromLatLng( - endCoordinate.latitude, - endCoordinate.longitude, - boxSize, - translationOffset, - _controller!.shapeLayerSizeFactor); + endCoordinate.latitude, + endCoordinate.longitude, + boxSize, + translationOffset, + _controller!.shapeLayerSizeFactor, + ); if (hasCap) { final MapLatLng? secondCoordinate = polylinePointsLength > 1 ? polyline.points[1] : null; - final MapLatLng? beforeEndCoordinate = polylinePointsLength > 1 - ? polyline.points[polylinePointsLength - 2] - : null; + final MapLatLng? beforeEndCoordinate = + polylinePointsLength > 1 + ? polyline.points[polylinePointsLength - 2] + : null; if (secondCoordinate != null) { final Offset secondPoint = pixelFromLatLng( - secondCoordinate.latitude, - secondCoordinate.longitude, - boxSize, - translationOffset, - _controller!.shapeLayerSizeFactor); + secondCoordinate.latitude, + secondCoordinate.longitude, + boxSize, + translationOffset, + _controller!.shapeLayerSizeFactor, + ); startPoint = _getPointAlongLineWithCap( - startPoint, secondPoint, strokeWidth / 2, true); + startPoint, + secondPoint, + strokeWidth / 2, + true, + ); } if (beforeEndCoordinate != null) { final Offset beforeEndPoint = pixelFromLatLng( - beforeEndCoordinate.latitude, - beforeEndCoordinate.longitude, - boxSize, - translationOffset, - _controller!.shapeLayerSizeFactor); + beforeEndCoordinate.latitude, + beforeEndCoordinate.longitude, + boxSize, + translationOffset, + _controller!.shapeLayerSizeFactor, + ); endPoint = _getPointAlongLineWithCap( - beforeEndPoint, endPoint, strokeWidth / 2, false); + beforeEndPoint, + endPoint, + strokeWidth / 2, + false, + ); } } @@ -3409,11 +3549,12 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { for (int j = 1; j < polylinePointsLength; j++) { final MapLatLng nextCoordinate = polyline.points[j]; final Offset nextPoint = pixelFromLatLng( - nextCoordinate.latitude, - nextCoordinate.longitude, - boxSize, - translationOffset, - _controller!.shapeLayerSizeFactor); + nextCoordinate.latitude, + nextCoordinate.longitude, + boxSize, + translationOffset, + _controller!.shapeLayerSizeFactor, + ); if (j < polylinePointsLength - 1) { path.lineTo(nextPoint.dx, nextPoint.dy); } else { @@ -3438,10 +3579,16 @@ class _RenderMapPolyline extends RenderBox implements MouseTrackerAnnotation { } if (polyline.dashArray != null) { - assert(polyline.dashArray!.length >= 2 && - polyline.dashArray!.length.isEven); - _drawDashedLine(context.canvas, polyline.dashArray!, paint, path, - hasCap ? strokeWidth / 2 : 0); + assert( + polyline.dashArray!.length >= 2 && polyline.dashArray!.length.isEven, + ); + _drawDashedLine( + context.canvas, + polyline.dashArray!, + paint, + path, + hasCap ? strokeWidth / 2 : 0, + ); } else { _drawDashedLine(context.canvas, _dashArray, paint, path); } @@ -3513,8 +3660,8 @@ class MapPolygonLayer extends MapVectorLayer { this.strokeWidth = 1, this.strokeColor, IndexedWidgetBuilder? tooltipBuilder, - }) : _fillType = _VectorFillType.inner, - super(key: key, tooltipBuilder: tooltipBuilder); + }) : _fillType = _VectorFillType.inner, + super(key: key, tooltipBuilder: tooltipBuilder); /// Creates the inverted color polygon shape. /// @@ -3576,8 +3723,8 @@ class MapPolygonLayer extends MapVectorLayer { this.color, this.strokeColor, IndexedWidgetBuilder? tooltipBuilder, - }) : _fillType = _VectorFillType.outer, - super(key: key, tooltipBuilder: tooltipBuilder); + }) : _fillType = _VectorFillType.outer, + super(key: key, tooltipBuilder: tooltipBuilder); /// A collection of [MapPolygon]. /// @@ -3825,12 +3972,14 @@ class MapPolygonLayer extends MapVectorLayer { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (polygons.isNotEmpty) { - final _DebugVectorShapeTree pointerTreeNode = - _DebugVectorShapeTree(polygons); + final _DebugVectorShapeTree pointerTreeNode = _DebugVectorShapeTree( + polygons, + ); properties.add(pointerTreeNode.toDiagnosticsNode()); } - properties.add(ObjectFlagProperty.has( - 'tooltip', tooltipBuilder)); + properties.add( + ObjectFlagProperty.has('tooltip', tooltipBuilder), + ); if (color != null) { properties.add(ColorProperty('color', color)); } @@ -3877,14 +4026,17 @@ class _MapPolygonLayerState extends State<_MapPolygonLayer> void initState() { super.initState(); _hoverAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); } @override void didChangeDependencies() { if (_controller == null) { - ancestor = context - .dependOnInheritedWidgetOfExactType()!; + ancestor = + context + .dependOnInheritedWidgetOfExactType()!; _controller = ancestor.controller; } super.didChangeDependencies(); @@ -3903,39 +4055,52 @@ class _MapPolygonLayerState extends State<_MapPolygonLayer> if (widget.fillType == _VectorFillType.outer) { for (final MapPolygon polygon in widget.polygons) { assert( - polygon.color == null, - throw FlutterError.fromParts([ - ErrorSummary('Incorrect MapPolygon arguments.'), - ErrorDescription( - 'Inverted polygons cannot be customized individually.'), - ErrorHint("To customize all the polygon's color," - ' use MapPolygonLayer.color') - ])); + polygon.color == null, + throw FlutterError.fromParts([ + ErrorSummary('Incorrect MapPolygon arguments.'), + ErrorDescription( + 'Inverted polygons cannot be customized individually.', + ), + ErrorHint( + "To customize all the polygon's color," + ' use MapPolygonLayer.color', + ), + ]), + ); assert( - polygon.strokeColor == null, - throw FlutterError.fromParts([ - ErrorSummary('Incorrect MapPolygon arguments.'), - ErrorDescription( - 'Inverted polygons cannot be customized individually.'), - ErrorHint("To customize all the polygon's stroke color," - ' use MapPolygonLayer.strokeColor') - ])); + polygon.strokeColor == null, + throw FlutterError.fromParts([ + ErrorSummary('Incorrect MapPolygon arguments.'), + ErrorDescription( + 'Inverted polygons cannot be customized individually.', + ), + ErrorHint( + "To customize all the polygon's stroke color," + ' use MapPolygonLayer.strokeColor', + ), + ]), + ); assert( - polygon.strokeWidth == null, - throw FlutterError.fromParts([ - ErrorSummary('Incorrect MapPolygon arguments.'), - ErrorDescription( - 'Inverted polygons cannot be customized individually.'), - ErrorHint("To customize all the polygon's stroke width," - ' use MapPolygonLayer.strokeWidth') - ])); + polygon.strokeWidth == null, + throw FlutterError.fromParts([ + ErrorSummary('Incorrect MapPolygon arguments.'), + ErrorDescription( + 'Inverted polygons cannot be customized individually.', + ), + ErrorHint( + "To customize all the polygon's stroke width," + ' use MapPolygonLayer.strokeWidth', + ), + ]), + ); } } return true; }()); final ThemeData themeData = Theme.of(context); - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -3943,14 +4108,16 @@ class _MapPolygonLayerState extends State<_MapPolygonLayer> return _MapPolygonLayerRenderObject( controller: _controller, polygons: widget.polygons, - color: widget.color ?? + color: + widget.color ?? (widget.fillType == _VectorFillType.inner ? const Color.fromRGBO(51, 153, 144, 1) : (themeData.brightness == Brightness.light ? const Color.fromRGBO(3, 3, 3, 0.15) : const Color.fromRGBO(0, 0, 0, 0.2))), strokeWidth: widget.strokeWidth, - strokeColor: widget.strokeColor ?? + strokeColor: + widget.strokeColor ?? (widget.fillType == _VectorFillType.inner ? const Color.fromRGBO(51, 153, 144, 1) : (themeData.brightness == Brightness.light @@ -4017,7 +4184,9 @@ class _MapPolygonLayerRenderObject extends LeafRenderObjectWidget { @override void updateRenderObject( - BuildContext context, _RenderMapPolygon renderObject) { + BuildContext context, + _RenderMapPolygon renderObject, + ) { renderObject ..polygons = polygons ..color = color @@ -4046,19 +4215,21 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { required this.isDesktop, required this.fillType, required this.state, - }) : _controller = controller, - _polygons = polygons, - _color = color, - _strokeWidth = strokeWidth, - _strokeColor = strokeColor, - _tooltipBuilder = tooltipBuilder, - _themeData = themeData { + }) : _controller = controller, + _polygons = polygons, + _color = color, + _strokeWidth = strokeWidth, + _strokeColor = strokeColor, + _tooltipBuilder = tooltipBuilder, + _themeData = themeData { _forwardHoverColor = ColorTween(); _reverseHoverColor = ColorTween(); _forwardHoverStrokeColor = ColorTween(); _reverseHoverStrokeColor = ColorTween(); _hoverColorAnimation = CurvedAnimation( - parent: hoverAnimationController, curve: Curves.easeInOut); + parent: hoverAnimationController, + curve: Curves.easeInOut, + ); _polygonsInList = _polygons.toList(); _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; } @@ -4235,8 +4406,10 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { markNeedsPaint(); } - void _handleInteraction(Offset position, - [PointerKind kind = PointerKind.touch]) { + void _handleInteraction( + Offset position, [ + PointerKind kind = PointerKind.touch, + ]) { if (_controller != null && _controller!.tooltipKey != null && _controller!.tooltipKey!.currentContext != null) { @@ -4244,8 +4417,14 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { _controller!.tooltipKey!.currentContext!.findRenderObject()! // ignore: avoid_as as ShapeLayerChildRenderBoxBase; - tooltipRenderer.paintTooltip(_selectedIndex, null, MapLayerElement.vector, - kind, state.ancestor.sublayers?.indexOf(polygonLayer), position); + tooltipRenderer.paintTooltip( + _selectedIndex, + null, + MapLayerElement.vector, + kind, + state.ancestor.sublayers?.indexOf(polygonLayer), + position, + ); } } @@ -4279,9 +4458,10 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { return false; } int index = _polygonsInList!.length - 1; - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = getTranslationOffset(_controller!); for (final MapPolygon polygon in _polygonsInList!.reversed) { if (polygon.onTap != null || _tooltipBuilder != null || isDesktop) { @@ -4289,22 +4469,24 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { final MapLatLng startCoordinate = polygon.points[0]; Offset startPoint = pixelFromLatLng( - startCoordinate.latitude, - startCoordinate.longitude, - boxSize, - translationOffset, - getLayerSizeFactor(_controller!)); + startCoordinate.latitude, + startCoordinate.longitude, + boxSize, + translationOffset, + getLayerSizeFactor(_controller!), + ); startPoint = _getScaledOffset(startPoint, _controller!); path.moveTo(startPoint.dx, startPoint.dy); for (int j = 1; j < polygon.points.length; j++) { final MapLatLng nextCoordinate = polygon.points[j]; Offset nextPoint = pixelFromLatLng( - nextCoordinate.latitude, - nextCoordinate.longitude, - boxSize, - translationOffset, - getLayerSizeFactor(_controller!)); + nextCoordinate.latitude, + nextCoordinate.longitude, + boxSize, + translationOffset, + getLayerSizeFactor(_controller!), + ); nextPoint = _getScaledOffset(nextPoint, _controller!); path.lineTo(nextPoint.dx, nextPoint.dy); } @@ -4335,7 +4517,9 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { // ignore: avoid_as final RenderBox renderBox = context.findRenderObject()! as RenderBox; _handleInteraction( - renderBox.globalToLocal(event.position), PointerKind.hover); + renderBox.globalToLocal(event.position), + PointerKind.hover, + ); } } @@ -4381,12 +4565,14 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { void paint(PaintingContext context, Offset offset) { context.canvas.save(); final Paint fillPaint = Paint()..isAntiAlias = true; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = getTranslationOffset(_controller!); // Check whether the color will apply to the inner side or outer side of // the polygon shape. @@ -4404,11 +4590,12 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { final MapLatLng startLatLng = polygon.points[0]; Offset startPoint = pixelFromLatLng( - startLatLng.latitude, - startLatLng.longitude, - boxSize, - translationOffset, - getLayerSizeFactor(_controller!)); + startLatLng.latitude, + startLatLng.longitude, + boxSize, + translationOffset, + getLayerSizeFactor(_controller!), + ); startPoint = _getScaledOffset(startPoint, _controller!); path.moveTo(startPoint.dx, startPoint.dy); @@ -4416,11 +4603,12 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { for (int j = 1; j < polygon.points.length; j++) { final MapLatLng nextCoordinate = polygon.points[j]; Offset nextPoint = pixelFromLatLng( - nextCoordinate.latitude, - nextCoordinate.longitude, - boxSize, - translationOffset, - getLayerSizeFactor(_controller!)); + nextCoordinate.latitude, + nextCoordinate.longitude, + boxSize, + translationOffset, + getLayerSizeFactor(_controller!), + ); nextPoint = _getScaledOffset(nextPoint, _controller!); path.lineTo(nextPoint.dx, nextPoint.dy); } @@ -4441,7 +4629,13 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { ..strokeWidth = _strokeWidth ..color = _strokeColor; _drawInvertedPath( - context, path, _controller!, fillPaint, strokePaint, offset); + context, + path, + _controller!, + fillPaint, + strokePaint, + offset, + ); } context.canvas.restore(); } @@ -4453,13 +4647,15 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { } if (_previousHoverItem != null && _previousHoverItem == polygon) { - paint.color = _themeData.shapeHoverColor != Colors.transparent - ? _reverseHoverColor.evaluate(_hoverColorAnimation)! - : (polygon.color ?? _color); + paint.color = + _themeData.shapeHoverColor != Colors.transparent + ? _reverseHoverColor.evaluate(_hoverColorAnimation)! + : (polygon.color ?? _color); } else if (_currentHoverItem != null && _currentHoverItem == polygon) { - paint.color = _themeData.shapeHoverColor != Colors.transparent - ? _forwardHoverColor.evaluate(_hoverColorAnimation)! - : (polygon.color ?? _color); + paint.color = + _themeData.shapeHoverColor != Colors.transparent + ? _forwardHoverColor.evaluate(_hoverColorAnimation)! + : (polygon.color ?? _color); } else { paint.color = polygon.color ?? _color; } @@ -4494,7 +4690,10 @@ class _RenderMapPolygon extends RenderBox implements MouseTrackerAnnotation { } void _updateHoverStrokeColor( - Paint paint, MapPolygon polygon, ColorTween tween) { + Paint paint, + MapPolygon polygon, + ColorTween tween, + ) { if (_themeData.shapeHoverStrokeColor != Colors.transparent) { paint.color = tween.evaluate(_hoverColorAnimation)!; } else { @@ -4572,8 +4771,8 @@ class MapCircleLayer extends MapVectorLayer { this.strokeWidth = 1, this.strokeColor, IndexedWidgetBuilder? tooltipBuilder, - }) : _fillType = _VectorFillType.inner, - super(key: key, tooltipBuilder: tooltipBuilder); + }) : _fillType = _VectorFillType.inner, + super(key: key, tooltipBuilder: tooltipBuilder); /// You may highlight a specific area on a map to make it more readable by /// using the [circles] property of [MapCircleLayer.inverted] by adding mask @@ -4639,8 +4838,8 @@ class MapCircleLayer extends MapVectorLayer { this.color, this.strokeColor, IndexedWidgetBuilder? tooltipBuilder, - }) : _fillType = _VectorFillType.outer, - super(key: key, tooltipBuilder: tooltipBuilder); + }) : _fillType = _VectorFillType.outer, + super(key: key, tooltipBuilder: tooltipBuilder); /// A collection of [MapCircle]. /// @@ -4993,14 +5192,17 @@ class MapCircleLayer extends MapVectorLayer { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (circles.isNotEmpty) { - final _DebugVectorShapeTree pointerTreeNode = - _DebugVectorShapeTree(circles); + final _DebugVectorShapeTree pointerTreeNode = _DebugVectorShapeTree( + circles, + ); properties.add(pointerTreeNode.toDiagnosticsNode()); } - properties - .add(ObjectFlagProperty>.has('animation', animation)); - properties.add(ObjectFlagProperty.has( - 'tooltip', tooltipBuilder)); + properties.add( + ObjectFlagProperty>.has('animation', animation), + ); + properties.add( + ObjectFlagProperty.has('tooltip', tooltipBuilder), + ); if (color != null) { properties.add(ColorProperty('color', color)); @@ -5050,14 +5252,17 @@ class _MapCircleLayerState extends State<_MapCircleLayer> void initState() { super.initState(); _hoverAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 250)); + vsync: this, + duration: const Duration(milliseconds: 250), + ); } @override void didChangeDependencies() { if (_controller == null) { - ancestor = context - .dependOnInheritedWidgetOfExactType()!; + ancestor = + context + .dependOnInheritedWidgetOfExactType()!; _controller = ancestor.controller; } super.didChangeDependencies(); @@ -5076,39 +5281,52 @@ class _MapCircleLayerState extends State<_MapCircleLayer> if (widget.fillType == _VectorFillType.outer) { for (final MapCircle circle in widget.circles) { assert( - circle.color == null, - throw FlutterError.fromParts([ - ErrorSummary('Incorrect MapCircle arguments.'), - ErrorDescription( - 'Inverted circles cannot be customized individually.'), - ErrorHint("To customize all the circle's color," - ' use MapCircleLayer.color') - ])); + circle.color == null, + throw FlutterError.fromParts([ + ErrorSummary('Incorrect MapCircle arguments.'), + ErrorDescription( + 'Inverted circles cannot be customized individually.', + ), + ErrorHint( + "To customize all the circle's color," + ' use MapCircleLayer.color', + ), + ]), + ); assert( - circle.strokeColor == null, - throw FlutterError.fromParts([ - ErrorSummary('Incorrect MapCircle arguments.'), - ErrorDescription( - 'Inverted circles cannot be customized individually.'), - ErrorHint("To customize all the circle's stroke color," - ' use MapCircleLayer.strokeColor') - ])); + circle.strokeColor == null, + throw FlutterError.fromParts([ + ErrorSummary('Incorrect MapCircle arguments.'), + ErrorDescription( + 'Inverted circles cannot be customized individually.', + ), + ErrorHint( + "To customize all the circle's stroke color," + ' use MapCircleLayer.strokeColor', + ), + ]), + ); assert( - circle.strokeWidth == null, - throw FlutterError.fromParts([ - ErrorSummary('Incorrect MapCircle arguments.'), - ErrorDescription( - 'Inverted circles cannot be customized individually.'), - ErrorHint("To customize all the circle's stroke width," - ' use MapCircleLayer.strokeWidth') - ])); + circle.strokeWidth == null, + throw FlutterError.fromParts([ + ErrorSummary('Incorrect MapCircle arguments.'), + ErrorDescription( + 'Inverted circles cannot be customized individually.', + ), + ErrorHint( + "To customize all the circle's stroke width," + ' use MapCircleLayer.strokeWidth', + ), + ]), + ); } } return true; }()); final ThemeData themeData = Theme.of(context); - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -5117,14 +5335,16 @@ class _MapCircleLayerState extends State<_MapCircleLayer> controller: _controller, circles: widget.circles, animation: widget.animation, - color: widget.color ?? + color: + widget.color ?? (widget.fillType == _VectorFillType.inner ? const Color.fromRGBO(51, 153, 144, 1) : (themeData.brightness == Brightness.light ? const Color.fromRGBO(3, 3, 3, 0.15) : const Color.fromRGBO(0, 0, 0, 0.2))), strokeWidth: widget.strokeWidth, - strokeColor: widget.strokeColor ?? + strokeColor: + widget.strokeColor ?? (widget.fillType == _VectorFillType.inner ? const Color.fromRGBO(51, 153, 144, 1) : (themeData.brightness == Brightness.light @@ -5224,20 +5444,22 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { required this.isDesktop, required this.fillType, required this.state, - }) : _controller = controller, - _circles = circles, - _animation = animation, - _color = color, - _strokeColor = strokeColor, - _strokeWidth = strokeWidth, - _tooltipBuilder = tooltipBuilder, - _themeData = themeData { + }) : _controller = controller, + _circles = circles, + _animation = animation, + _color = color, + _strokeColor = strokeColor, + _strokeWidth = strokeWidth, + _tooltipBuilder = tooltipBuilder, + _themeData = themeData { _forwardHoverColor = ColorTween(); _reverseHoverColor = ColorTween(); _forwardHoverStrokeColor = ColorTween(); _reverseHoverStrokeColor = ColorTween(); _hoverColorAnimation = CurvedAnimation( - parent: hoverAnimationController, curve: Curves.easeInOut); + parent: hoverAnimationController, + curve: Curves.easeInOut, + ); _circlesInList = _circles.toList(); _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; } @@ -5423,8 +5645,10 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { markNeedsPaint(); } - void _handleInteraction(Offset position, - [PointerKind kind = PointerKind.touch]) { + void _handleInteraction( + Offset position, [ + PointerKind kind = PointerKind.touch, + ]) { if (_controller != null && _controller!.tooltipKey != null && _controller!.tooltipKey!.currentContext != null) { @@ -5432,9 +5656,10 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { _controller!.tooltipKey!.currentContext!.findRenderObject()! // ignore: avoid_as as ShapeLayerChildRenderBoxBase; - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = _getTranslation(_controller!); if (_selectedIndex != -1) { @@ -5447,8 +5672,10 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { ); center = _getScaledOffset(center, _controller!); - final Rect circleRect = - Rect.fromCircle(center: center, radius: _selectedCircle.radius); + final Rect circleRect = Rect.fromCircle( + center: center, + radius: _selectedCircle.radius, + ); tooltipRenderer.paintTooltip( _selectedIndex, circleRect, @@ -5494,9 +5721,10 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { } int index = _circlesInList!.length - 1; - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = getTranslationOffset(_controller!); for (final MapCircle circle in _circlesInList!.reversed) { @@ -5511,10 +5739,7 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { ); center = _getScaledOffset(center, _controller!); - path.addOval(Rect.fromCircle( - center: center, - radius: circle.radius, - )); + path.addOval(Rect.fromCircle(center: center, radius: circle.radius)); if (path.contains(position)) { _selectedCircle = circle; _selectedIndex = index; @@ -5572,7 +5797,9 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { // ignore: avoid_as final RenderBox renderBox = context.findRenderObject()! as RenderBox; _handleInteraction( - renderBox.globalToLocal(event.position), PointerKind.hover); + renderBox.globalToLocal(event.position), + PointerKind.hover, + ); } } @@ -5592,12 +5819,14 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { context.canvas.save(); final Paint fillPaint = Paint()..isAntiAlias = true; - final Paint strokePaint = Paint() - ..isAntiAlias = true - ..style = PaintingStyle.stroke; - final Size boxSize = _controller?.layerType == LayerType.tile - ? _controller!.totalTileSize! - : size; + final Paint strokePaint = + Paint() + ..isAntiAlias = true + ..style = PaintingStyle.stroke; + final Size boxSize = + _controller?.layerType == LayerType.tile + ? _controller!.totalTileSize! + : size; final Offset translationOffset = getTranslationOffset(_controller!); // Check whether the color will apply to the inner side or outer side of // the circle shape. @@ -5642,7 +5871,13 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { ..strokeWidth = _strokeWidth ..color = _strokeColor; _drawInvertedPath( - context, path, _controller!, fillPaint, strokePaint, offset); + context, + path, + _controller!, + fillPaint, + strokePaint, + offset, + ); } context.canvas.restore(); } @@ -5654,13 +5889,15 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { } if (_previousHoverItem != null && _previousHoverItem == circle) { - paint.color = _themeData.shapeHoverColor != Colors.transparent - ? _reverseHoverColor.evaluate(_hoverColorAnimation)! - : (circle.color ?? _color); + paint.color = + _themeData.shapeHoverColor != Colors.transparent + ? _reverseHoverColor.evaluate(_hoverColorAnimation)! + : (circle.color ?? _color); } else if (_currentHoverItem != null && _currentHoverItem == circle) { - paint.color = _themeData.shapeHoverColor != Colors.transparent - ? _forwardHoverColor.evaluate(_hoverColorAnimation)! - : (circle.color ?? _color); + paint.color = + _themeData.shapeHoverColor != Colors.transparent + ? _forwardHoverColor.evaluate(_hoverColorAnimation)! + : (circle.color ?? _color); } else { paint.color = circle.color ?? _color; } @@ -5695,7 +5932,10 @@ class _RenderMapCircle extends RenderBox implements MouseTrackerAnnotation { } void _updateHoverStrokeColor( - Paint paint, MapCircle circle, ColorTween tween) { + Paint paint, + MapCircle circle, + ColorTween tween, + ) { if (_themeData.shapeHoverStrokeColor != Colors.transparent) { paint.color = tween.evaluate(_hoverColorAnimation)!; } else { @@ -8218,12 +8458,20 @@ Path? _dashPath( double startPoint = distance; double endPoint = distance + length; if (capRadius != 0) { - startPoint = _getPointAlongLineWithCap( - Offset(startPoint, 0), Offset(endPoint, 0), capRadius, true) - .dx; - endPoint = _getPointAlongLineWithCap( - Offset(startPoint, 0), Offset(endPoint, 0), capRadius, false) - .dx; + startPoint = + _getPointAlongLineWithCap( + Offset(startPoint, 0), + Offset(endPoint, 0), + capRadius, + true, + ).dx; + endPoint = + _getPointAlongLineWithCap( + Offset(startPoint, 0), + Offset(endPoint, 0), + capRadius, + false, + ).dx; } path.addPath(matric.extractPath(startPoint, endPoint), Offset.zero); } @@ -8235,8 +8483,12 @@ Path? _dashPath( } void _drawDashedLine( - Canvas canvas, List dashArray, Paint paint, Path path, - [double capRadius = 0]) { + Canvas canvas, + List dashArray, + Paint paint, + Path path, [ + double capRadius = 0, +]) { bool even = false; for (int i = 1; i < dashArray.length; i = i + 2) { if (dashArray[i] == 0) { @@ -8246,12 +8498,13 @@ void _drawDashedLine( if (!even) { paint.isAntiAlias = false; canvas.drawPath( - _dashPath( - path, - dashArray: _IntervalList(dashArray), - capRadius: capRadius, - )!, - paint); + _dashPath( + path, + dashArray: _IntervalList(dashArray), + capRadius: capRadius, + )!, + paint, + ); } else { canvas.drawPath(path, paint); } @@ -8272,8 +8525,12 @@ class _IntervalList { } } -bool _liesPointOnLine(Offset startPoint, Offset endPoint, double touchTolerance, - Offset touchPosition) { +bool _liesPointOnLine( + Offset startPoint, + Offset endPoint, + double touchTolerance, + Offset touchPosition, +) { final Path path = Path(); // Calculate distance between two points i.e, d = sqrt[(x1-x2)^2+(y1-y2)^2]. final double width = endPoint.dx - startPoint.dx; @@ -8282,14 +8539,22 @@ bool _liesPointOnLine(Offset startPoint, Offset endPoint, double touchTolerance, final double horizontalTouchLength = touchTolerance * height / lineLength; final double verticalTouchLength = touchTolerance * width / lineLength; - final Offset lineTopLeft = Offset(startPoint.dx - horizontalTouchLength, - startPoint.dy + verticalTouchLength); - final Offset lineTopRight = Offset(startPoint.dx + horizontalTouchLength, - startPoint.dy - verticalTouchLength); + final Offset lineTopLeft = Offset( + startPoint.dx - horizontalTouchLength, + startPoint.dy + verticalTouchLength, + ); + final Offset lineTopRight = Offset( + startPoint.dx + horizontalTouchLength, + startPoint.dy - verticalTouchLength, + ); final Offset lineBottomRight = Offset( - endPoint.dx + horizontalTouchLength, endPoint.dy - verticalTouchLength); + endPoint.dx + horizontalTouchLength, + endPoint.dy - verticalTouchLength, + ); final Offset lineBottomLeft = Offset( - endPoint.dx - horizontalTouchLength, endPoint.dy + verticalTouchLength); + endPoint.dx - horizontalTouchLength, + endPoint.dy + verticalTouchLength, + ); path ..moveTo(lineTopLeft.dx, lineTopLeft.dy) ..lineTo(lineTopRight.dx, lineTopRight.dy) @@ -8304,9 +8569,10 @@ Path _getAnimatedPath(Path originalPath, Animation animation) { double currentLength = 0.0; final PathMetrics pathMetrics = originalPath.computeMetrics(); final double pathLength = pathMetrics.fold( - 0.0, - (double previousValue, PathMetric pathMetric) => - previousValue + pathMetric.length); + 0.0, + (double previousValue, PathMetric pathMetric) => + previousValue + pathMetric.length, + ); final double requiredPathLength = pathLength * animation.value; final Iterator metricsIterator = originalPath.computeMetrics().iterator; @@ -8316,8 +8582,9 @@ Path _getAnimatedPath(Path originalPath, Animation animation) { final double nextLength = currentLength + metric.length; if (nextLength > requiredPathLength) { extractedPath.addPath( - metric.extractPath(0.0, requiredPathLength - currentLength), - Offset.zero); + metric.extractPath(0.0, requiredPathLength - currentLength), + Offset.zero, + ); break; } extractedPath.addPath(metric.extractPath(0.0, metric.length), Offset.zero); @@ -8327,8 +8594,13 @@ Path _getAnimatedPath(Path originalPath, Animation animation) { return extractedPath; } -bool _liesPointOnArc(Offset startPoint, Offset endPoint, Offset controlPoint, - double touchTolerance, Offset touchPosition) { +bool _liesPointOnArc( + Offset startPoint, + Offset endPoint, + Offset controlPoint, + double touchTolerance, + Offset touchPosition, +) { final Path path = Path(); final double width = endPoint.dx - startPoint.dx; final double height = endPoint.dy - startPoint.dy; @@ -8337,26 +8609,45 @@ bool _liesPointOnArc(Offset startPoint, Offset endPoint, Offset controlPoint, final double horizontalTouchLength = touchTolerance * height / lineLength; final double verticalTouchLength = touchTolerance * width / lineLength; - final Offset lineBottomLeft = Offset(startPoint.dx - horizontalTouchLength, - startPoint.dy + verticalTouchLength); - final Offset lineTopLeft = Offset(startPoint.dx + horizontalTouchLength, - startPoint.dy - verticalTouchLength); + final Offset lineBottomLeft = Offset( + startPoint.dx - horizontalTouchLength, + startPoint.dy + verticalTouchLength, + ); + final Offset lineTopLeft = Offset( + startPoint.dx + horizontalTouchLength, + startPoint.dy - verticalTouchLength, + ); final Offset lineTopRight = Offset( - endPoint.dx + horizontalTouchLength, endPoint.dy - verticalTouchLength); + endPoint.dx + horizontalTouchLength, + endPoint.dy - verticalTouchLength, + ); final Offset lineBottomRight = Offset( - endPoint.dx - horizontalTouchLength, endPoint.dy + verticalTouchLength); - final Offset controlPointTop = Offset(controlPoint.dx + horizontalTouchLength, - controlPoint.dy - verticalTouchLength); + endPoint.dx - horizontalTouchLength, + endPoint.dy + verticalTouchLength, + ); + final Offset controlPointTop = Offset( + controlPoint.dx + horizontalTouchLength, + controlPoint.dy - verticalTouchLength, + ); final Offset controlPointBottom = Offset( - controlPoint.dx - horizontalTouchLength, - controlPoint.dy + verticalTouchLength); + controlPoint.dx - horizontalTouchLength, + controlPoint.dy + verticalTouchLength, + ); path ..moveTo(lineTopLeft.dx, lineTopLeft.dy) - ..quadraticBezierTo(controlPointTop.dx, controlPointTop.dy, lineTopRight.dx, - lineTopRight.dy) + ..quadraticBezierTo( + controlPointTop.dx, + controlPointTop.dy, + lineTopRight.dx, + lineTopRight.dy, + ) ..lineTo(lineBottomRight.dx, lineBottomRight.dy) - ..quadraticBezierTo(controlPointBottom.dx, controlPointBottom.dy, - lineBottomLeft.dx, lineBottomLeft.dy) + ..quadraticBezierTo( + controlPointBottom.dx, + controlPointBottom.dy, + lineBottomLeft.dx, + lineBottomLeft.dy, + ) ..close(); return path.contains(touchPosition); } diff --git a/packages/syncfusion_flutter_maps/lib/src/layer/zoomable.dart b/packages/syncfusion_flutter_maps/lib/src/layer/zoomable.dart index d8d7ed7e5..f55951281 100644 --- a/packages/syncfusion_flutter_maps/lib/src/layer/zoomable.dart +++ b/packages/syncfusion_flutter_maps/lib/src/layer/zoomable.dart @@ -41,7 +41,7 @@ enum ActionType { panFling, /// Denotes there is no action currently. - none + none, } /// Contains details about the current zooming and panning action. @@ -104,11 +104,12 @@ class Zoomable extends StatefulWidget { required this.onComplete, required this.onFling, this.child, - }) : assert(minZoomLevel >= 1 && minZoomLevel <= maxZoomLevel), - assert(initialZoomLevel >= minZoomLevel && - initialZoomLevel <= maxZoomLevel), - assert(frictionCoefficient > 0.0), - super(key: key); + }) : assert(minZoomLevel >= 1 && minZoomLevel <= maxZoomLevel), + assert( + initialZoomLevel >= minZoomLevel && initialZoomLevel <= maxZoomLevel, + ), + assert(frictionCoefficient > 0.0), + super(key: key); /// Specifies the initial zoomLevel of the widget. /// @@ -236,14 +237,19 @@ class _ZoomableState extends State with TickerProviderStateMixin { assert(scale != 0.0); final double currentScale = matrix.getMaxScaleOnAxis(); - final double clampedTotalScale = (currentScale * scale) - .clamp(_getScale(widget.minZoomLevel), _getScale(widget.maxZoomLevel)); + final double clampedTotalScale = (currentScale * scale).clamp( + _getScale(widget.minZoomLevel), + _getScale(widget.maxZoomLevel), + ); final double clampedScale = clampedTotalScale / currentScale; return matrix.clone()..scale(clampedScale); } ActionType _getActionTypes( - double scale, Offset focalPoint, Offset startFocalPoint) { + double scale, + Offset focalPoint, + Offset startFocalPoint, + ) { // The minimum distance required to start scale or pan gesture. const int minScaleDistance = 3; final Offset distance = focalPoint - startFocalPoint; @@ -280,12 +286,17 @@ class _ZoomableState extends State with TickerProviderStateMixin { if (!_zoomLevelAnimationController.isAnimating && !_actualRectAnimationController.isAnimating) { final double scale = _newMatrix.getMaxScaleOnAxis(); - final Offset matrixFocalPoint = - _getActualPointInMatrix(_newMatrix, details.localFocalPoint); + final Offset matrixFocalPoint = _getActualPointInMatrix( + _newMatrix, + details.localFocalPoint, + ); if (widget.zoomController.actionType == ActionType.none) { widget.zoomController.actionType = _getActionTypes( - details.scale, details.localFocalPoint, _startLocalPoint); + details.scale, + details.localFocalPoint, + _startLocalPoint, + ); } if (widget.zoomController.actionType == ActionType.none) { @@ -309,14 +320,23 @@ class _ZoomableState extends State with TickerProviderStateMixin { final double newScale = desiredScale / scale; _newMatrix = _matrixScale(_newMatrix, newScale); - final Offset matrixFocalPointScaled = - _getActualPointInMatrix(_newMatrix, _startLocalPoint); + final Offset matrixFocalPointScaled = _getActualPointInMatrix( + _newMatrix, + _startLocalPoint, + ); _newMatrix = _translateMatrix( - _newMatrix, matrixFocalPointScaled - _matrixStartPoint!); + _newMatrix, + matrixFocalPointScaled - _matrixStartPoint!, + ); - _invokeZoomableUpdate(_newMatrix, details.localFocalPoint, - details.focalPoint, details.scale, _startLocalPoint); + _invokeZoomableUpdate( + _newMatrix, + details.localFocalPoint, + details.focalPoint, + details.scale, + _startLocalPoint, + ); break; case ActionType.pan: @@ -328,10 +348,15 @@ class _ZoomableState extends State with TickerProviderStateMixin { final Offset newTranslation = matrixFocalPoint - _matrixStartPoint!; _newMatrix = _translateMatrix(_newMatrix, newTranslation); - _matrixStartPoint = - _getActualPointInMatrix(_newMatrix, details.localFocalPoint); + _matrixStartPoint = _getActualPointInMatrix( + _newMatrix, + details.localFocalPoint, + ); _invokeZoomableUpdate( - _newMatrix, details.localFocalPoint, details.focalPoint); + _newMatrix, + details.localFocalPoint, + details.focalPoint, + ); break; case ActionType.tap: case ActionType.pinchFling: @@ -372,7 +397,8 @@ class _ZoomableState extends State with TickerProviderStateMixin { _lastScaleValueOnInteraction >= _maximumReachedScaleOnInteraction ? 1 : -1; - double newZoomLevel = zoomLevel + + double newZoomLevel = + zoomLevel + (direction * (details.velocity.pixelsPerSecond.distance / kMaxFlingVelocity) * widget.maxZoomLevel); @@ -380,14 +406,19 @@ class _ZoomableState extends State with TickerProviderStateMixin { widget.zoomController.actionType = ActionType.pinchFling; final double scale = _getScale(newZoomLevel) / _zoomLevelTween.begin!; Matrix4 matrix = _matrixScale(_newMatrix, scale); - final Offset matrixFocalPointScaled = - _getActualPointInMatrix(matrix, _startLocalPoint); - matrix = - _translateMatrix(matrix, matrixFocalPointScaled - _matrixStartPoint!); + final Offset matrixFocalPointScaled = _getActualPointInMatrix( + matrix, + _startLocalPoint, + ); + matrix = _translateMatrix( + matrix, + matrixFocalPointScaled - _matrixStartPoint!, + ); if (_invokeZoomableUpdate(matrix, null, null, scale, _startLocalPoint)) { _zoomLevelTween.end = _getScale(newZoomLevel); - _zoomLevelAnimationController.duration = - _getFlingAnimationDuration(details.velocity.pixelsPerSecond.distance); + _zoomLevelAnimationController.duration = _getFlingAnimationDuration( + details.velocity.pixelsPerSecond.distance, + ); _zoomLevelAnimationController.forward(from: 0.0); } else { _scaleStart = null; @@ -413,15 +444,18 @@ class _ZoomableState extends State with TickerProviderStateMixin { translation.dy, details.velocity.pixelsPerSecond.dy, ); - _actualRectTween.end = - Offset(frictionSimulationX.finalX, frictionSimulationY.finalX); + _actualRectTween.end = Offset( + frictionSimulationX.finalX, + frictionSimulationY.finalX, + ); widget.zoomController.actionType = ActionType.panFling; final Offset newTranslation = _actualRectTween.end! - _actualRectTween.begin!; final Matrix4 matrix = _translateMatrix(_newMatrix, newTranslation); if (_invokeZoomableUpdate(matrix)) { - _actualRectAnimationController.duration = - _getFlingAnimationDuration(details.velocity.pixelsPerSecond.distance); + _actualRectAnimationController.duration = _getFlingAnimationDuration( + details.velocity.pixelsPerSecond.distance, + ); _actualRectAnimationController.forward(from: 0.0); } else { _scaleStart = null; @@ -446,19 +480,26 @@ class _ZoomableState extends State with TickerProviderStateMixin { final double desiredScale = _zoomLevelTween.evaluate(_zoomLevelAnimation); final double scaleChange = desiredScale / scale; _newMatrix = _matrixScale(_newMatrix, scaleChange); - final Offset matrixFocalPointScaled = - _getActualPointInMatrix(_newMatrix, _startLocalPoint); + final Offset matrixFocalPointScaled = _getActualPointInMatrix( + _newMatrix, + _startLocalPoint, + ); _newMatrix = _translateMatrix( - _newMatrix, matrixFocalPointScaled - _matrixStartPoint!); + _newMatrix, + matrixFocalPointScaled - _matrixStartPoint!, + ); if (widget.zoomController.actionType == ActionType.none || widget.zoomController.actionType == ActionType.pinchFling) { final double zoomLevel = _getZoomLevel(_newMatrix.getMaxScaleOnAxis()); final Offset translatedPoint = _getTranslationOffset(_newMatrix); - final Rect actualRect = translatedPoint & - Size(_getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), - _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2)); + final Rect actualRect = + translatedPoint & + Size( + _getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), + _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2), + ); widget.zoomController._internalSetValues(zoomLevel, actualRect); } else { _invokeZoomableUpdate(_newMatrix, _startLocalPoint); @@ -470,12 +511,17 @@ class _ZoomableState extends State with TickerProviderStateMixin { _isFlingAnimationActive ? Curves.decelerate : Curves.easeInOut; final Vector3 translationVector = _newMatrix.getTranslation(); final Offset translation = Offset(translationVector.x, translationVector.y); - final Offset matrixActualPoint = - _getActualPointInMatrix(_newMatrix, translation); - final Offset newTranslation = - _actualRectTween.evaluate(_actualRectAnimation); - final Offset animationMatrixPoint = - _getActualPointInMatrix(_newMatrix, newTranslation); + final Offset matrixActualPoint = _getActualPointInMatrix( + _newMatrix, + translation, + ); + final Offset newTranslation = _actualRectTween.evaluate( + _actualRectAnimation, + ); + final Offset animationMatrixPoint = _getActualPointInMatrix( + _newMatrix, + newTranslation, + ); final Offset matrixTranslationChange = animationMatrixPoint - matrixActualPoint; _newMatrix = _translateMatrix(_newMatrix, matrixTranslationChange); @@ -484,9 +530,12 @@ class _ZoomableState extends State with TickerProviderStateMixin { widget.zoomController.actionType == ActionType.panFling) { final double zoomLevel = _getZoomLevel(_newMatrix.getMaxScaleOnAxis()); final Offset translatedPoint = _getTranslationOffset(_newMatrix); - final Rect actualRect = translatedPoint & - Size(_getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), - _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2)); + final Rect actualRect = + translatedPoint & + Size( + _getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), + _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2), + ); widget.zoomController._internalSetValues(zoomLevel, actualRect); } else { _invokeZoomableUpdate(_newMatrix); @@ -513,8 +562,10 @@ class _ZoomableState extends State with TickerProviderStateMixin { _startLocalPoint = widget.zoomController.parentRect!.center; _newMatrix = widget.zoomController.controllerMatrix.clone(); final Vector3 translationVector = _newMatrix.getTranslation(); - final Offset translation = - Offset(translationVector.x, translationVector.y); + final Offset translation = Offset( + translationVector.x, + translationVector.y, + ); _actualRectTween.begin = translation; _actualRectTween.end = actualRect.topLeft; _actualRectAnimationController.duration = widget.animationDuration; @@ -552,13 +603,18 @@ class _ZoomableState extends State with TickerProviderStateMixin { _resetDoubleTapTimer(); // By default, we have increased the zoom level by 1 while double tapping. final double lastZoomLevel = _getZoomLevel( - widget.zoomController.controllerMatrix.getMaxScaleOnAxis()); + widget.zoomController.controllerMatrix.getMaxScaleOnAxis(), + ); double newZoomLevel = lastZoomLevel + 1; - newZoomLevel = - newZoomLevel.clamp(widget.minZoomLevel, widget.maxZoomLevel); + newZoomLevel = newZoomLevel.clamp( + widget.minZoomLevel, + widget.maxZoomLevel, + ); if (newZoomLevel != lastZoomLevel) { _handleDoubleTap( - event.localPosition, pow(2, newZoomLevel - 1).toDouble()); + event.localPosition, + pow(2, newZoomLevel - 1).toDouble(), + ); } } } @@ -605,7 +661,9 @@ class _ZoomableState extends State with TickerProviderStateMixin { _doubleTapEnabled = false; widget.zoomController.actionType = ActionType.pinch; _invokeZoomableUpdate( - widget.zoomController.controllerMatrix, _startLocalPoint); + widget.zoomController.controllerMatrix, + _startLocalPoint, + ); widget.zoomController.actionType = ActionType.none; _invokeZoomableComplete(widget.zoomController.controllerMatrix); } @@ -614,7 +672,9 @@ class _ZoomableState extends State with TickerProviderStateMixin { _isFlingAnimationActive = false; widget.zoomController.actionType = ActionType.pan; _invokeZoomableUpdate( - widget.zoomController.controllerMatrix, _startLocalPoint); + widget.zoomController.controllerMatrix, + _startLocalPoint, + ); widget.zoomController.actionType = ActionType.none; _invokeZoomableComplete(widget.zoomController.controllerMatrix); } @@ -630,15 +690,21 @@ class _ZoomableState extends State with TickerProviderStateMixin { final double scaleChange = exp(-event.scrollDelta.dy / 200); _newMatrix = widget.zoomController.controllerMatrix.clone(); - final Offset matrixFocalPoint = - _getActualPointInMatrix(_newMatrix, event.localPosition); + final Offset matrixFocalPoint = _getActualPointInMatrix( + _newMatrix, + event.localPosition, + ); _newMatrix = _matrixScale(_newMatrix, scaleChange); - final Offset matrixFocalPointScaled = - _getActualPointInMatrix(_newMatrix, event.localPosition); + final Offset matrixFocalPointScaled = _getActualPointInMatrix( + _newMatrix, + event.localPosition, + ); _newMatrix = _translateMatrix( - _newMatrix, matrixFocalPointScaled - matrixFocalPoint); + _newMatrix, + matrixFocalPointScaled - matrixFocalPoint, + ); widget.zoomController.actionType = ActionType.pinch; _invokeZoomableUpdate(_newMatrix, event.localPosition, event.position); widget.zoomController.actionType = ActionType.none; @@ -646,11 +712,13 @@ class _ZoomableState extends State with TickerProviderStateMixin { } } - bool _invokeZoomableUpdate(Matrix4 matrix, - [Offset? localFocalPoint, - Offset? globalFocalPoint, - double scale = 1.0, - Offset? pinchCenter]) { + bool _invokeZoomableUpdate( + Matrix4 matrix, [ + Offset? localFocalPoint, + Offset? globalFocalPoint, + double scale = 1.0, + Offset? pinchCenter, + ]) { final double zoomLevel = _getZoomLevel(matrix.getMaxScaleOnAxis()); localFocalPoint ??= widget.zoomController.parentRect!.center; if (globalFocalPoint == null) { @@ -658,9 +726,12 @@ class _ZoomableState extends State with TickerProviderStateMixin { globalFocalPoint = renderBox.localToGlobal(localFocalPoint); } final Offset translatedPoint = _getTranslationOffset(matrix); - final Rect actualRect = translatedPoint & - Size(_getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), - _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2)); + final Rect actualRect = + translatedPoint & + Size( + _getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), + _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2), + ); final ZoomPanDetails details = ZoomPanDetails( localFocalPoint: localFocalPoint, globalFocalPoint: globalFocalPoint, @@ -680,11 +751,13 @@ class _ZoomableState extends State with TickerProviderStateMixin { return true; } - void _invokeZoomableComplete(Matrix4 matrix, - [Offset? localFocalPoint, - Offset? globalFocalPoint, - double scale = 1.0, - Offset? pinchCenter]) { + void _invokeZoomableComplete( + Matrix4 matrix, [ + Offset? localFocalPoint, + Offset? globalFocalPoint, + double scale = 1.0, + Offset? pinchCenter, + ]) { final double zoomLevel = _getZoomLevel(matrix.getMaxScaleOnAxis()); localFocalPoint ??= widget.zoomController.parentRect!.center; if (globalFocalPoint == null) { @@ -692,9 +765,12 @@ class _ZoomableState extends State with TickerProviderStateMixin { globalFocalPoint = renderBox.localToGlobal(localFocalPoint); } final Offset translatedPoint = _getTranslationOffset(matrix); - final Rect actualRect = translatedPoint & - Size(_getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), - _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2)); + final Rect actualRect = + translatedPoint & + Size( + _getTotalChildSize(zoomLevel, _boundaryRect!.width / 2), + _getTotalChildSize(zoomLevel, _boundaryRect!.height / 2), + ); final ZoomPanDetails details = ZoomPanDetails( localFocalPoint: localFocalPoint, globalFocalPoint: globalFocalPoint, @@ -718,9 +794,13 @@ class _ZoomableState extends State with TickerProviderStateMixin { ..addListener(_handleActualRectAnimation) ..addStatusListener(_handleActualRectAnimationStatusChange); _zoomLevelAnimation = CurvedAnimation( - parent: _zoomLevelAnimationController, curve: Curves.easeInOut); + parent: _zoomLevelAnimationController, + curve: Curves.easeInOut, + ); _actualRectAnimation = CurvedAnimation( - parent: _actualRectAnimationController, curve: Curves.easeInOut); + parent: _actualRectAnimationController, + curve: Curves.easeInOut, + ); _actualRectTween = Tween(); _zoomLevelTween = Tween(); } @@ -751,37 +831,40 @@ class _ZoomableState extends State with TickerProviderStateMixin { @override Widget build(BuildContext context) { return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - final Size newSize = Size(constraints.maxWidth, constraints.maxHeight); - if (_size == null || _size != newSize) { - _size = newSize; - widget.zoomController - ..parentRect = Offset.zero & _size! - .._actualRect = widget.initialRect - .._zoomLevel = widget.initialZoomLevel; - _boundaryRect = _getBoundaryRect(); - widget.zoomController.controllerMatrix = Matrix4.identity() - ..scale(_getScale(widget.initialZoomLevel)) - ..setTranslation( - Vector3(widget.initialRect.left, widget.initialRect.top, 0.0)); - } - - return Listener( - onPointerDown: _handlePointerDown, - onPointerUp: _handlePointerUp, - onPointerCancel: _handlePointerCancel, - onPointerSignal: - widget.enableMouseWheelZooming ? _handleMouseWheelZooming : null, - behavior: HitTestBehavior.translucent, - child: GestureDetector( - onScaleStart: _handleScaleStart, - onScaleUpdate: _handleScaleUpdate, - onScaleEnd: _handleScaleEnd, + builder: (BuildContext context, BoxConstraints constraints) { + final Size newSize = Size(constraints.maxWidth, constraints.maxHeight); + if (_size == null || _size != newSize) { + _size = newSize; + widget.zoomController + ..parentRect = Offset.zero & _size! + .._actualRect = widget.initialRect + .._zoomLevel = widget.initialZoomLevel; + _boundaryRect = _getBoundaryRect(); + widget.zoomController.controllerMatrix = + Matrix4.identity() + ..scale(_getScale(widget.initialZoomLevel)) + ..setTranslation( + Vector3(widget.initialRect.left, widget.initialRect.top, 0.0), + ); + } + + return Listener( + onPointerDown: _handlePointerDown, + onPointerUp: _handlePointerUp, + onPointerCancel: _handlePointerCancel, + onPointerSignal: + widget.enableMouseWheelZooming ? _handleMouseWheelZooming : null, behavior: HitTestBehavior.translucent, - child: widget.child, - ), - ); - }); + child: GestureDetector( + onScaleStart: _handleScaleStart, + onScaleUpdate: _handleScaleUpdate, + onScaleEnd: _handleScaleEnd, + behavior: HitTestBehavior.translucent, + child: widget.child, + ), + ); + }, + ); } } @@ -810,8 +893,9 @@ double _getScale(double zoomLevel) { /// Return the exact pixel point of the given matrix. Offset _getActualPointInMatrix(Matrix4 matrix, Offset localPoint) { final Matrix4 inverseMatrix = Matrix4.inverted(matrix); - final Vector3 untransformed = - inverseMatrix.transform3(Vector3(localPoint.dx, localPoint.dy, 0)); + final Vector3 untransformed = inverseMatrix.transform3( + Vector3(localPoint.dx, localPoint.dy, 0), + ); return Offset(untransformed.x, untransformed.y); } @@ -861,9 +945,10 @@ class ZoomableController { if (actionType != ActionType.none) { _actualRect = value; final double newScale = pow(2, _zoomLevel - 1).toDouble(); - controllerMatrix = Matrix4.identity() - ..scale(newScale) - ..setTranslation(Vector3(_actualRect.left, _actualRect.top, 0.0)); + controllerMatrix = + Matrix4.identity() + ..scale(newScale) + ..setTranslation(Vector3(_actualRect.left, _actualRect.top, 0.0)); notifyListeners(); return; } @@ -874,9 +959,10 @@ class ZoomableController { _zoomLevel = zoomLevel; _actualRect = actualRect; final double newScale = pow(2, _zoomLevel - 1).toDouble(); - controllerMatrix = Matrix4.identity() - ..scale(newScale) - ..setTranslation(Vector3(_actualRect.left, _actualRect.top, 0.0)); + controllerMatrix = + Matrix4.identity() + ..scale(newScale) + ..setTranslation(Vector3(_actualRect.left, _actualRect.top, 0.0)); notifyListeners(); } diff --git a/packages/syncfusion_flutter_maps/lib/src/settings.dart b/packages/syncfusion_flutter_maps/lib/src/settings.dart index f79021fca..d5ec172be 100644 --- a/packages/syncfusion_flutter_maps/lib/src/settings.dart +++ b/packages/syncfusion_flutter_maps/lib/src/settings.dart @@ -183,10 +183,12 @@ class MapColorMapper { this.minOpacity, this.maxOpacity, this.text, - }) : assert((from == null && to == null) || - (from != null && to != null && from < to && to > from)), - assert(minOpacity == null || minOpacity != 0), - assert(maxOpacity == null || maxOpacity != 0); + }) : assert( + (from == null && to == null) || + (from != null && to != null && from < to && to > from), + ), + assert(minOpacity == null || minOpacity != 0), + assert(maxOpacity == null || maxOpacity != 0); /// Sets the range start for the color mapping. /// @@ -895,8 +897,9 @@ class MapDataLabelSettings extends DiagnosticableTree { if (textStyle != null) { properties.add(textStyle!.toDiagnosticsNode(name: 'textStyle')); } - properties - .add(EnumProperty('overflowMode', overflowMode)); + properties.add( + EnumProperty('overflowMode', overflowMode), + ); } } diff --git a/packages/syncfusion_flutter_maps/lib/src/theme.dart b/packages/syncfusion_flutter_maps/lib/src/theme.dart index 1cb6df725..1dc589aab 100644 --- a/packages/syncfusion_flutter_maps/lib/src/theme.dart +++ b/packages/syncfusion_flutter_maps/lib/src/theme.dart @@ -19,14 +19,16 @@ class MapsThemeData extends SfMapsThemeData { late final SfColorScheme colorScheme = SfTheme.colorScheme(context); /// Specifies the sub layer color of the maps widgets. - Color get subLayerColor => colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(198, 198, 198, 1) - : const Color.fromRGBO(71, 71, 71, 1); + Color get subLayerColor => + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(198, 198, 198, 1) + : const Color.fromRGBO(71, 71, 71, 1); /// Specifies the sub layer stroke color of the maps widgets. - Color get subLayerStrokeColor => colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(145, 145, 145, 1) - : const Color.fromRGBO(133, 133, 133, 1); + Color get subLayerStrokeColor => + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(145, 145, 145, 1) + : const Color.fromRGBO(133, 133, 133, 1); /// Specifies the sub layer width of the maps widgets. double get subLayerStrokeWidth => @@ -43,11 +45,12 @@ class MapsThemeData extends SfMapsThemeData { Color? get markerIconColor => colorScheme.primary[98]; @override - Color? get bubbleColor => colorScheme.useMaterial3 - ? colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(255, 180, 0, 0.4) - : const Color.fromRGBO(201, 88, 142, 0.4) - : colorScheme.brightness == Brightness.light + Color? get bubbleColor => + colorScheme.useMaterial3 + ? colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(255, 180, 0, 0.4) + : const Color.fromRGBO(201, 88, 142, 0.4) + : colorScheme.brightness == Brightness.light ? const Color.fromRGBO(98, 0, 238, 0.5) : const Color.fromRGBO(187, 134, 252, 0.8); diff --git a/packages/syncfusion_flutter_maps/lib/src/utils.dart b/packages/syncfusion_flutter_maps/lib/src/utils.dart index 9c0c4f859..3d8e792b8 100644 --- a/packages/syncfusion_flutter_maps/lib/src/utils.dart +++ b/packages/syncfusion_flutter_maps/lib/src/utils.dart @@ -29,10 +29,11 @@ Color getSaturatedColor(Color color, [Color mix = Colors.black]) { return color == Colors.transparent ? color : Color.fromRGBO( - ((1 - factor) * (color.r * 255) + factor * (mix.r * 255)).toInt(), - ((1 - factor) * (color.g * 255) + factor * (mix.g * 255)).toInt(), - ((1 - factor) * (color.b * 255) + factor * (mix.b * 255)).toInt(), - 1); + ((1 - factor) * (color.r * 255) + factor * (mix.r * 255)).toInt(), + ((1 - factor) * (color.g * 255) + factor * (mix.g * 255)).toInt(), + ((1 - factor) * (color.b * 255) + factor * (mix.b * 255)).toInt(), + 1, + ); } Size getBoxSize(BoxConstraints constraints) { @@ -42,8 +43,13 @@ Size getBoxSize(BoxConstraints constraints) { return Size(width, height); } -Offset pixelFromLatLng(num latitude, num longitude, Size size, - [Offset offset = Offset.zero, double scale = 1.0]) { +Offset pixelFromLatLng( + num latitude, + num longitude, + Size size, [ + Offset offset = Offset.zero, + double scale = 1.0, +]) { final double x = (longitude + 180.0) / 360.0; final double sinLatitude = sin(latitude * pi / 180.0); final double y = @@ -55,12 +61,20 @@ Offset pixelFromLatLng(num latitude, num longitude, Size size, } MapLatLng getPixelToLatLng( - Offset offset, Size size, Offset translation, double scale) { + Offset offset, + Size size, + Offset translation, + double scale, +) { return pixelToLatLng(offset, size, translation, scale); } -MapLatLng pixelToLatLng(Offset offset, Size size, - [Offset translation = Offset.zero, double scale = 1.0]) { +MapLatLng pixelToLatLng( + Offset offset, + Size size, [ + Offset translation = Offset.zero, + double scale = 1.0, +]) { final double mapSize = size.longestSide * scale; final double x = ((offset.dx - translation.dx).clamp(0, mapSize - 1) / mapSize) - 0.5; @@ -79,14 +93,24 @@ MapLatLng getFocalLatLng(MapLatLngBounds bounds) { return MapLatLng(latitude, longitude); } -double getZoomLevel(MapLatLngBounds bounds, LayerType layerType, Size size, - [double actualShapeSizeFactor = 1.0]) { +double getZoomLevel( + MapLatLngBounds bounds, + LayerType layerType, + Size size, [ + double actualShapeSizeFactor = 1.0, +]) { switch (layerType) { case LayerType.shape: final Offset northEast = pixelFromLatLng( - bounds.northeast.latitude, bounds.northeast.longitude, size); + bounds.northeast.latitude, + bounds.northeast.longitude, + size, + ); final Offset southWest = pixelFromLatLng( - bounds.southwest.latitude, bounds.southwest.longitude, size); + bounds.southwest.latitude, + bounds.southwest.longitude, + size, + ); final Rect boundsRect = Rect.fromPoints(northEast, southWest); final double latZoom = size.height / boundsRect.height; final double lngZoom = size.width / boundsRect.width; @@ -94,12 +118,19 @@ double getZoomLevel(MapLatLngBounds bounds, LayerType layerType, Size size, case LayerType.tile: // Calculating the scale value for the given bounds using the // default tile layer size with default minimum zoom level. - final Size tileLayerSize = - Size.square(getTotalTileWidth(kDefaultMinZoomLevel)); + final Size tileLayerSize = Size.square( + getTotalTileWidth(kDefaultMinZoomLevel), + ); final Offset northEast = pixelFromLatLng( - bounds.northeast.latitude, bounds.northeast.longitude, tileLayerSize); + bounds.northeast.latitude, + bounds.northeast.longitude, + tileLayerSize, + ); final Offset southWest = pixelFromLatLng( - bounds.southwest.latitude, bounds.southwest.longitude, tileLayerSize); + bounds.southwest.latitude, + bounds.southwest.longitude, + tileLayerSize, + ); final Rect boundsRect = Rect.fromPoints(northEast, southWest); // Converting scale into zoom level. final double latZoomLevel = log(boundsRect.height / size.height) / log(2); @@ -108,9 +139,15 @@ double getZoomLevel(MapLatLngBounds bounds, LayerType layerType, Size size, } } -String getTrimText(String text, TextStyle style, double maxWidth, - TextPainter painter, double width, - [double? nextTextHalfWidth, bool isInsideLastLabel = false]) { +String getTrimText( + String text, + TextStyle style, + double maxWidth, + TextPainter painter, + double width, [ + double? nextTextHalfWidth, + bool isInsideLastLabel = false, +]) { final int actualTextLength = text.length; String trimmedText = text; int trimLength = 3; // 3 dots @@ -122,7 +159,10 @@ String getTrimText(String text, TextStyle style, double maxWidth, break; } else { trimmedText = text.replaceRange( - actualTextLength - trimLength, actualTextLength, '...'); + actualTextLength - trimLength, + actualTextLength, + '...', + ); painter.text = TextSpan(style: style, text: trimmedText); painter.layout(); trimLength++; @@ -131,9 +171,10 @@ String getTrimText(String text, TextStyle style, double maxWidth, if (isInsideLastLabel && nextTextHalfWidth != null) { width = painter.width + nextTextHalfWidth; } else { - width = nextTextHalfWidth != null - ? painter.width / 2 + nextTextHalfWidth - : painter.width; + width = + nextTextHalfWidth != null + ? painter.width / 2 + nextTextHalfWidth + : painter.width; } } @@ -168,7 +209,9 @@ double getLayerSizeFactor(MapController controller) { } MapProvider getSourceProvider( - Object geoJsonSource, GeoJSONSourceType geoJSONSourceType) { + Object geoJsonSource, + GeoJSONSourceType geoJSONSourceType, +) { switch (geoJSONSourceType) { case GeoJSONSourceType.asset: return AssetMapProvider(geoJsonSource.toString()); @@ -182,7 +225,11 @@ MapProvider getSourceProvider( // Calculates the shape's path center and width for data label rendering. void findPathCenterAndWidth( - double signedArea, double centerX, double centerY, MapModel mapModel) { + double signedArea, + double centerX, + double centerY, + MapModel mapModel, +) { // Used mathematical formula to find the center of polygon points. signedArea /= 2; centerX = centerX / (6 * signedArea); @@ -233,7 +280,7 @@ void findPathCenterAndWidth( class MapLatLngTween extends Tween { /// Creates an [MapLatLng] tween. MapLatLngTween({MapLatLng? begin, MapLatLng? end}) - : super(begin: begin, end: end); + : super(begin: begin, end: end); @override MapLatLng lerp(double t) => MapLatLng.lerp(begin, end, t)!; diff --git a/packages/syncfusion_flutter_maps/pubspec.yaml b/packages/syncfusion_flutter_maps/pubspec.yaml index 6db824c2b..db1bb7366 100644 --- a/packages/syncfusion_flutter_maps/pubspec.yaml +++ b/packages/syncfusion_flutter_maps/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_maps description: A Flutter Maps library for creating beautiful, interactive, and customizable maps from shape files or WMTS services to visualize the geographical area. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_maps screenshots: @@ -10,7 +10,7 @@ screenshots: path: screenshots/tile_layer_maps.png environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_pdf/CHANGELOG.md b/packages/syncfusion_flutter_pdf/CHANGELOG.md index 10f911b6d..bf01dfbf3 100644 --- a/packages/syncfusion_flutter_pdf/CHANGELOG.md +++ b/packages/syncfusion_flutter_pdf/CHANGELOG.md @@ -1,5 +1,76 @@ ## Unreleased +**Bugs** + +* The compatible version of our Flutter PDF library has been updated to Flutter SDK 3.32.0. + +## [29.2.11] - 17/06/2025 + +**Bugs** + +* Resolved an exception that occurred when hiding document-level layers in a specific PDF document. + +## [29.2.9] - 05/06/2025 + +**Bugs** + +* Resolved a mismatch error in the text word length and text glyph length from a specific PDF document. + +## [29.2.7] - 27/05/2025 + +**Bugs** + +* Resolved a range error exception while extracting text lines from a specific PDF document. + +## [29.2.4] - 13/05/2025 + +**Bugs** + +* Resolved an Out-Of-Memory crash that occurred during the decryption of PDF document. +* Resolved a performance issue when decrypting password-protected PDF documents. + +## [29.1.41] - 06/05/2025 + +**Bugs** + +* Resolved an issue where an exception occurred when flattening a signature field in a PDF document. + +## [29.1.40] - 29/04/2025 + +**Bugs** + +* Resolved a content preservation issue that occurred when drawing multiple PDF grids on the same page of a PDF document. +* Resolved an issue where PDF form is returned as null when acro form has no fields. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.38] - 04/15/2025 + +**Bugs** + +* Resolved an issue where the null check operator was incorrectly used on a nullable value. +* Resolved an issue where the PDF was shifting towards the top right corner when drawing existing page templates on PDFs. +* Exception occurs when getting the bounds of the text box form field item in a document has been resolved. + +## [29.1.37] - 04/08/2025 + +**Bugs** + +* Resolved the invalid cross reference table issue occurs while loading the specific PDF document. +* Resolved the Layer name not preserved properly while removing layers in the PDF document + +## [29.1.35] - 04/01/2025 + +**Bugs** + +* Resolved the exception that occurred while decrypting PDF files on the Flutter web platform. + +## [29.1.33] - 03/25/2025 + **General** * The compatible version of our Flutter PDF library has been updated to Flutter SDK 3.29.0. @@ -390,7 +461,7 @@ **Breaking changes** -* The `save` method has been changed to an asynchronous type in the `PdfDocument` and the `saveSync` method has been added for synchronous. +* The `save` method has been changed to an asynchronous type in the `PdfDocument` and the `saveSync` method has been added for synchronous. **Features** diff --git a/packages/syncfusion_flutter_pdf/example/lib/main.dart b/packages/syncfusion_flutter_pdf/example/lib/main.dart index cb7a90139..09dcdf665 100644 --- a/packages/syncfusion_flutter_pdf/example/lib/main.dart +++ b/packages/syncfusion_flutter_pdf/example/lib/main.dart @@ -16,9 +16,7 @@ class CreatePdfWidget extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - home: CreatePdfStatefulWidget(), - ); + return const MaterialApp(home: CreatePdfStatefulWidget()); } } @@ -35,9 +33,7 @@ class _CreatePdfState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Create PDF document'), - ), + appBar: AppBar(title: const Text('Create PDF document')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -50,7 +46,7 @@ class _CreatePdfState extends State { ), onPressed: generateInvoice, child: const Text('Generate PDF'), - ) + ), ], ), ), @@ -66,8 +62,9 @@ class _CreatePdfState extends State { final Size pageSize = page.getClientSize(); //Draw rectangle page.graphics.drawRectangle( - bounds: Rect.fromLTWH(0, 0, pageSize.width, pageSize.height), - pen: PdfPen(PdfColor(142, 170, 219))); + bounds: Rect.fromLTWH(0, 0, pageSize.width, pageSize.height), + pen: PdfPen(PdfColor(142, 170, 219)), + ); //Generate PDF grid. final PdfGrid grid = getGrid(); //Draw the header section by creating text element @@ -88,35 +85,46 @@ class _CreatePdfState extends State { PdfLayoutResult drawHeader(PdfPage page, Size pageSize, PdfGrid grid) { //Draw rectangle page.graphics.drawRectangle( - brush: PdfSolidBrush(PdfColor(91, 126, 215)), - bounds: Rect.fromLTWH(0, 0, pageSize.width - 115, 90)); + brush: PdfSolidBrush(PdfColor(91, 126, 215)), + bounds: Rect.fromLTWH(0, 0, pageSize.width - 115, 90), + ); //Draw string page.graphics.drawString( - 'INVOICE', PdfStandardFont(PdfFontFamily.helvetica, 30), - brush: PdfBrushes.white, - bounds: Rect.fromLTWH(25, 0, pageSize.width - 115, 90), - format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle)); + 'INVOICE', + PdfStandardFont(PdfFontFamily.helvetica, 30), + brush: PdfBrushes.white, + bounds: Rect.fromLTWH(25, 0, pageSize.width - 115, 90), + format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle), + ); page.graphics.drawRectangle( - bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 90), - brush: PdfSolidBrush(PdfColor(65, 104, 205))); + bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 90), + brush: PdfSolidBrush(PdfColor(65, 104, 205)), + ); - page.graphics.drawString(r'$' + getTotalAmount(grid).toString(), - PdfStandardFont(PdfFontFamily.helvetica, 18), - bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 100), - brush: PdfBrushes.white, - format: PdfStringFormat( - alignment: PdfTextAlignment.center, - lineAlignment: PdfVerticalAlignment.middle)); + page.graphics.drawString( + r'$' + getTotalAmount(grid).toString(), + PdfStandardFont(PdfFontFamily.helvetica, 18), + bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 100), + brush: PdfBrushes.white, + format: PdfStringFormat( + alignment: PdfTextAlignment.center, + lineAlignment: PdfVerticalAlignment.middle, + ), + ); final PdfFont contentFont = PdfStandardFont(PdfFontFamily.helvetica, 9); //Draw string - page.graphics.drawString('Amount', contentFont, - brush: PdfBrushes.white, - bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 33), - format: PdfStringFormat( - alignment: PdfTextAlignment.center, - lineAlignment: PdfVerticalAlignment.bottom)); + page.graphics.drawString( + 'Amount', + contentFont, + brush: PdfBrushes.white, + bounds: Rect.fromLTWH(400, 0, pageSize.width - 400, 33), + format: PdfStringFormat( + alignment: PdfTextAlignment.center, + lineAlignment: PdfVerticalAlignment.bottom, + ), + ); //Create data foramt and convert it to text. final DateFormat format = DateFormat.yMMMMd('en_US'); final String invoiceNumber = @@ -128,14 +136,24 @@ class _CreatePdfState extends State { \r\n\r\n9920 BridgePointe Parkway, \r\n\r\n9365550136'''; PdfTextElement(text: invoiceNumber, font: contentFont).draw( - page: page, - bounds: Rect.fromLTWH(pageSize.width - (contentSize.width + 30), 120, - contentSize.width + 30, pageSize.height - 120)); + page: page, + bounds: Rect.fromLTWH( + pageSize.width - (contentSize.width + 30), + 120, + contentSize.width + 30, + pageSize.height - 120, + ), + ); return PdfTextElement(text: address, font: contentFont).draw( - page: page, - bounds: Rect.fromLTWH(30, 120, - pageSize.width - (contentSize.width + 30), pageSize.height - 120))!; + page: page, + bounds: Rect.fromLTWH( + 30, + 120, + pageSize.width - (contentSize.width + 30), + pageSize.height - 120, + ), + )!; } //Draws the grid @@ -152,45 +170,61 @@ class _CreatePdfState extends State { } }; //Draw the PDF grid and get the result. - result = grid.draw( - page: page, bounds: Rect.fromLTWH(0, result.bounds.bottom + 40, 0, 0))!; + result = + grid.draw( + page: page, + bounds: Rect.fromLTWH(0, result.bounds.bottom + 40, 0, 0), + )!; //Draw grand total. - page.graphics.drawString('Grand Total', - PdfStandardFont(PdfFontFamily.helvetica, 9, style: PdfFontStyle.bold), - bounds: Rect.fromLTWH( - quantityCellBounds!.left, - result.bounds.bottom + 10, - quantityCellBounds!.width, - quantityCellBounds!.height)); - page.graphics.drawString(getTotalAmount(grid).toString(), - PdfStandardFont(PdfFontFamily.helvetica, 9, style: PdfFontStyle.bold), - bounds: Rect.fromLTWH( - totalPriceCellBounds!.left, - result.bounds.bottom + 10, - totalPriceCellBounds!.width, - totalPriceCellBounds!.height)); + page.graphics.drawString( + 'Grand Total', + PdfStandardFont(PdfFontFamily.helvetica, 9, style: PdfFontStyle.bold), + bounds: Rect.fromLTWH( + quantityCellBounds!.left, + result.bounds.bottom + 10, + quantityCellBounds!.width, + quantityCellBounds!.height, + ), + ); + page.graphics.drawString( + getTotalAmount(grid).toString(), + PdfStandardFont(PdfFontFamily.helvetica, 9, style: PdfFontStyle.bold), + bounds: Rect.fromLTWH( + totalPriceCellBounds!.left, + result.bounds.bottom + 10, + totalPriceCellBounds!.width, + totalPriceCellBounds!.height, + ), + ); } //Draw the invoice footer data. void drawFooter(PdfPage page, Size pageSize) { - final PdfPen linePen = - PdfPen(PdfColor(142, 170, 219), dashStyle: PdfDashStyle.custom); + final PdfPen linePen = PdfPen( + PdfColor(142, 170, 219), + dashStyle: PdfDashStyle.custom, + ); linePen.dashPattern = [3, 3]; //Draw line - page.graphics.drawLine(linePen, Offset(0, pageSize.height - 100), - Offset(pageSize.width, pageSize.height - 100)); + page.graphics.drawLine( + linePen, + Offset(0, pageSize.height - 100), + Offset(pageSize.width, pageSize.height - 100), + ); const String footerContent = - // ignore: leading_newlines_in_multiline_strings - '''800 Interchange Blvd.\r\n\r\nSuite 2501, Austin, + // ignore: leading_newlines_in_multiline_strings + '''800 Interchange Blvd.\r\n\r\nSuite 2501, Austin, TX 78721\r\n\r\nAny Questions? support@adventure-works.com'''; //Added 30 as a margin for the layout page.graphics.drawString( - footerContent, PdfStandardFont(PdfFontFamily.helvetica, 9), - format: PdfStringFormat(alignment: PdfTextAlignment.right), - bounds: Rect.fromLTWH(pageSize.width - 30, pageSize.height - 70, 0, 0)); + footerContent, + PdfStandardFont(PdfFontFamily.helvetica, 9), + format: PdfStringFormat(alignment: PdfTextAlignment.right), + bounds: Rect.fromLTWH(pageSize.width - 30, pageSize.height - 70, 0, 0), + ); } //Create PDF grid and return @@ -222,8 +256,12 @@ class _CreatePdfState extends State { //Set gird columns width grid.columns[1].width = 200; for (int i = 0; i < headerRow.cells.count; i++) { - headerRow.cells[i].style.cellPadding = - PdfPaddings(bottom: 5, left: 5, right: 5, top: 5); + headerRow.cells[i].style.cellPadding = PdfPaddings( + bottom: 5, + left: 5, + right: 5, + top: 5, + ); } for (int i = 0; i < grid.rows.count; i++) { final PdfGridRow row = grid.rows[i]; @@ -232,16 +270,26 @@ class _CreatePdfState extends State { if (j == 0) { cell.stringFormat.alignment = PdfTextAlignment.center; } - cell.style.cellPadding = - PdfPaddings(bottom: 5, left: 5, right: 5, top: 5); + cell.style.cellPadding = PdfPaddings( + bottom: 5, + left: 5, + right: 5, + top: 5, + ); } } return grid; } //Create and row for the grid. - void addProducts(String productId, String productName, double price, - int quantity, double total, PdfGrid grid) { + void addProducts( + String productId, + String productName, + double price, + int quantity, + double total, + PdfGrid grid, + ) { final PdfGridRow row = grid.rows.add(); row.cells[0].value = productId; row.cells[1].value = productName; diff --git a/packages/syncfusion_flutter_pdf/example/lib/save_file_mobile.dart b/packages/syncfusion_flutter_pdf/example/lib/save_file_mobile.dart index 270ca572f..eb186a86d 100644 --- a/packages/syncfusion_flutter_pdf/example/lib/save_file_mobile.dart +++ b/packages/syncfusion_flutter_pdf/example/lib/save_file_mobile.dart @@ -19,8 +19,9 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else { path = await PathProviderPlatform.instance.getApplicationSupportPath(); } - final File file = - File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName'); + final File file = File( + Platform.isWindows ? '$path\\$fileName' : '$path/$fileName', + ); await file.writeAsBytes(bytes, flush: true); if (Platform.isAndroid || Platform.isIOS) { //Launch the file (used open_file package) @@ -30,7 +31,8 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else if (Platform.isMacOS) { await Process.run('open', ['$path/$fileName'], runInShell: true); } else if (Platform.isLinux) { - await Process.run('xdg-open', ['$path/$fileName'], - runInShell: true); + await Process.run('xdg-open', [ + '$path/$fileName', + ], runInShell: true); } } diff --git a/packages/syncfusion_flutter_pdf/example/lib/save_file_web.dart b/packages/syncfusion_flutter_pdf/example/lib/save_file_web.dart index 49e510b70..82d87615c 100644 --- a/packages/syncfusion_flutter_pdf/example/lib/save_file_web.dart +++ b/packages/syncfusion_flutter_pdf/example/lib/save_file_web.dart @@ -12,11 +12,11 @@ Future saveAndLaunchFile(List bytes, String fileName) async { ..style.display = 'none' ..download = fileName; -// Insert the new element into the DOM + // Insert the new element into the DOM document.body!.appendChild(anchor); -// Initiate the download + // Initiate the download anchor.click(); -// Clean up the DOM by removing the anchor element + // Clean up the DOM by removing the anchor element document.body!.removeChild(anchor); } diff --git a/packages/syncfusion_flutter_pdf/example/pubspec.yaml b/packages/syncfusion_flutter_pdf/example/pubspec.yaml index 5d90bc069..a9e4e8e02 100644 --- a/packages/syncfusion_flutter_pdf/example/pubspec.yaml +++ b/packages/syncfusion_flutter_pdf/example/pubspec.yaml @@ -3,7 +3,7 @@ description: Demo for creating a PDF file using syncfusion_flutter_pdf package. version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_action.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_action.dart index 0944b52f7..daa31aa06 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_action.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_action.dart @@ -19,8 +19,9 @@ abstract class PdfAction implements IPdfWrapper { set next(PdfAction? value) { if (value != null && _helper.action != value) { _helper.action = value; - _helper.dictionary.setArray(PdfDictionaryProperties.next, - [PdfReferenceHolder(_helper.action)]); + _helper.dictionary.setArray(PdfDictionaryProperties.next, [ + PdfReferenceHolder(_helper.action), + ]); } } } @@ -43,8 +44,10 @@ class PdfActionHelper { /// internal method void initialize() { - dictionary.setProperty(PdfName(PdfDictionaryProperties.type), - PdfName(PdfDictionaryProperties.action)); + dictionary.setProperty( + PdfName(PdfDictionaryProperties.type), + PdfName(PdfDictionaryProperties.action), + ); element = dictionary; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_annotation_action.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_annotation_action.dart index 08abd1d9d..0280d03b0 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_annotation_action.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_annotation_action.dart @@ -7,16 +7,23 @@ import 'pdf_action.dart'; class PdfAnnotationActions implements IPdfWrapper { //Constructor /// Initializes a new instance of the [PdfAnnotationActions] class. - PdfAnnotationActions( - {PdfAction? mouseEnter, - PdfAction? mouseLeave, - PdfAction? mouseUp, - PdfAction? mouseDown, - PdfAction? gotFocus, - PdfAction? lostFocus}) { + PdfAnnotationActions({ + PdfAction? mouseEnter, + PdfAction? mouseLeave, + PdfAction? mouseUp, + PdfAction? mouseDown, + PdfAction? gotFocus, + PdfAction? lostFocus, + }) { _helper = PdfAnnotationActionsHelper(); _initValues( - mouseEnter, mouseLeave, mouseUp, mouseDown, gotFocus, lostFocus); + mouseEnter, + mouseLeave, + mouseUp, + mouseDown, + gotFocus, + lostFocus, + ); } PdfAnnotationActions._loaded(PdfDictionary? dictionary) { @@ -93,8 +100,14 @@ class PdfAnnotationActions implements IPdfWrapper { } // Implementation - void _initValues(PdfAction? mEnter, PdfAction? mLeave, PdfAction? mUp, - PdfAction? mDown, PdfAction? gotF, PdfAction? lostF) { + void _initValues( + PdfAction? mEnter, + PdfAction? mLeave, + PdfAction? mUp, + PdfAction? mDown, + PdfAction? gotF, + PdfAction? lostF, + ) { if (mEnter != null) { mouseEnter = mEnter; } @@ -137,7 +150,8 @@ class PdfAnnotationActionsHelper { /// internal method static PdfAnnotationActionsHelper getHelper( - PdfAnnotationActions annotationActions) { + PdfAnnotationActions annotationActions, + ) { return annotationActions._helper; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_field_actions.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_field_actions.dart index d56f05eba..e29276a38 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_field_actions.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_field_actions.dart @@ -11,11 +11,13 @@ class PdfFieldActions implements IPdfWrapper { //Constructor /// Initializes a new instance of the [PdfFieldActions] class with /// the [PdfAnnotationActions] - PdfFieldActions(PdfAnnotationActions annotationActions, - {PdfJavaScriptAction? keyPressed, - PdfJavaScriptAction? format, - PdfJavaScriptAction? validate, - PdfJavaScriptAction? calculate}) { + PdfFieldActions( + PdfAnnotationActions annotationActions, { + PdfJavaScriptAction? keyPressed, + PdfJavaScriptAction? format, + PdfJavaScriptAction? validate, + PdfJavaScriptAction? calculate, + }) { _helper.annotationActions = annotationActions; _initValues(keyPressed, format, validate, calculate); } @@ -198,10 +200,13 @@ class PdfJavaScriptAction extends PdfAction { PdfJavaScriptAction(String javaScript) : super() { _initValue(javaScript); PdfActionHelper.getHelper(this).dictionary.setProperty( - PdfDictionaryProperties.s, PdfName(PdfDictionaryProperties.javaScript)); - PdfActionHelper.getHelper(this) - .dictionary - .setProperty(PdfDictionaryProperties.js, PdfString(_javaScript)); + PdfDictionaryProperties.s, + PdfName(PdfDictionaryProperties.javaScript), + ); + PdfActionHelper.getHelper(this).dictionary.setProperty( + PdfDictionaryProperties.js, + PdfString(_javaScript), + ); } //Fields @@ -214,9 +219,9 @@ class PdfJavaScriptAction extends PdfAction { set javaScript(String value) { if (_javaScript != value) { _javaScript = value; - PdfActionHelper.getHelper(this) - .dictionary - .setString(PdfDictionaryProperties.js, _javaScript); + PdfActionHelper.getHelper( + this, + ).dictionary.setString(PdfDictionaryProperties.js, _javaScript); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_submit_action.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_submit_action.dart index f037f451c..7552d0a49 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_submit_action.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_submit_action.dart @@ -14,40 +14,44 @@ class PdfSubmitAction extends PdfFormAction { //Constructor /// Initializes a new instance of the [PdfSubmitAction] class with /// URL to submit the form data - PdfSubmitAction(String url, - {HttpMethod httpMethod = HttpMethod.post, - SubmitDataFormat dataFormat = SubmitDataFormat.fdf, - bool canonicalDateTimeFormat = false, - bool submitCoordinates = false, - bool includeNoValueFields = false, - bool includeIncrementalUpdates = false, - bool includeAnnotations = false, - bool excludeNonUserAnnotations = false, - bool embedForm = false, - bool include = false, - List? fields}) - : super._() { + PdfSubmitAction( + String url, { + HttpMethod httpMethod = HttpMethod.post, + SubmitDataFormat dataFormat = SubmitDataFormat.fdf, + bool canonicalDateTimeFormat = false, + bool submitCoordinates = false, + bool includeNoValueFields = false, + bool includeIncrementalUpdates = false, + bool includeAnnotations = false, + bool excludeNonUserAnnotations = false, + bool embedForm = false, + bool include = false, + List? fields, + }) : super._() { final PdfActionHelper helper = PdfActionHelper.getHelper(this); helper.dictionary.beginSave = _dictionaryBeginSave; helper.dictionary.setProperty( - PdfDictionaryProperties.s, PdfName(PdfDictionaryProperties.submitForm)); + PdfDictionaryProperties.s, + PdfName(PdfDictionaryProperties.submitForm), + ); if (url.isEmpty) { ArgumentError.value("The URL can't be an empty string."); } _url = url; helper.dictionary.setProperty(PdfDictionaryProperties.f, PdfString(_url)); _initValues( - httpMethod = HttpMethod.post, - dataFormat, - canonicalDateTimeFormat, - submitCoordinates, - includeNoValueFields, - includeIncrementalUpdates, - includeAnnotations, - excludeNonUserAnnotations, - embedForm, - include, - fields); + httpMethod = HttpMethod.post, + dataFormat, + canonicalDateTimeFormat, + submitCoordinates, + includeNoValueFields, + includeIncrementalUpdates, + includeAnnotations, + excludeNonUserAnnotations, + embedForm, + include, + fields, + ); } //Fields @@ -216,21 +220,24 @@ class PdfSubmitAction extends PdfFormAction { void _dictionaryBeginSave(Object sender, SavePdfPrimitiveArgs? ars) { PdfActionHelper.getHelper(this).dictionary.setProperty( - PdfDictionaryProperties.flags, PdfNumber(_getFlagValue(_flags))); + PdfDictionaryProperties.flags, + PdfNumber(_getFlagValue(_flags)), + ); } void _initValues( - HttpMethod http, - SubmitDataFormat format, - bool canonicalDateTime, - bool submit, - bool includeNoValue, - bool includeIncremental, - bool includeAnnot, - bool excludeNonUserAnnot, - bool embed, - bool initInclude, - List? field) { + HttpMethod http, + SubmitDataFormat format, + bool canonicalDateTime, + bool submit, + bool includeNoValue, + bool includeIncremental, + bool includeAnnot, + bool excludeNonUserAnnot, + bool embed, + bool initInclude, + List? field, + ) { httpMethod = http; dataFormat = format; canonicalDateTimeFormat = canonicalDateTime; @@ -321,9 +328,9 @@ class PdfFormAction extends PdfAction { PdfFormFieldCollection get fields { if (_fields == null) { _fields = PdfFormFieldCollectionHelper.getCollection(); - PdfActionHelper.getHelper(this) - .dictionary - .setProperty(PdfDictionaryProperties.fields, _fields); + PdfActionHelper.getHelper( + this, + ).dictionary.setProperty(PdfDictionaryProperties.fields, _fields); } PdfFormFieldCollectionHelper.getHelper(_fields!).isAction = true; return _fields!; @@ -337,7 +344,9 @@ class PdfResetAction extends PdfFormAction { /// Initializes a new instance of the [PdfResetAction] class. PdfResetAction({bool? include, List? fields}) : super._() { PdfActionHelper.getHelper(this).dictionary.setProperty( - PdfDictionaryProperties.s, PdfName(PdfDictionaryProperties.resetForm)); + PdfDictionaryProperties.s, + PdfName(PdfDictionaryProperties.resetForm), + ); _initValues(include, fields); } @@ -346,9 +355,10 @@ class PdfResetAction extends PdfFormAction { set include(bool value) { if (super.include != value) { super.include = value; - PdfActionHelper.getHelper(this) - .dictionary - .setNumber(PdfDictionaryProperties.flags, super.include ? 0 : 1); + PdfActionHelper.getHelper(this).dictionary.setNumber( + PdfDictionaryProperties.flags, + super.include ? 0 : 1, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_uri_action.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_uri_action.dart index dfc7889c0..f71dc1c50 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_uri_action.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/actions/pdf_uri_action.dart @@ -13,8 +13,9 @@ class PdfUriAction extends PdfAction { this.uri = uri; } PdfActionHelper.getHelper(this).dictionary.setProperty( - PdfName(PdfDictionaryProperties.s), - PdfName(PdfDictionaryProperties.uri)); + PdfName(PdfDictionaryProperties.s), + PdfName(PdfDictionaryProperties.uri), + ); } // fields @@ -27,8 +28,8 @@ class PdfUriAction extends PdfAction { /// Sets the unique resource identifier. set uri(String value) { _uri = value; - PdfActionHelper.getHelper(this) - .dictionary - .setString(PdfDictionaryProperties.uri, _uri); + PdfActionHelper.getHelper( + this, + ).dictionary.setString(PdfDictionaryProperties.uri, _uri); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/appearance/pdf_extended_appearance.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/appearance/pdf_extended_appearance.dart index 682c45a65..73d402c69 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/appearance/pdf_extended_appearance.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/appearance/pdf_extended_appearance.dart @@ -21,8 +21,10 @@ class PdfExtendedAppearance implements IPdfWrapper { PdfAppearanceState get normal { if (_normal == null) { _normal = PdfAppearanceState(); - _dictionary! - .setProperty(PdfDictionaryProperties.n, PdfReferenceHolder(_normal)); + _dictionary!.setProperty( + PdfDictionaryProperties.n, + PdfReferenceHolder(_normal), + ); } return _normal!; } @@ -32,7 +34,9 @@ class PdfExtendedAppearance implements IPdfWrapper { if (_mouseHover == null) { _mouseHover = PdfAppearanceState(); _dictionary!.setProperty( - PdfDictionaryProperties.r, PdfReferenceHolder(_mouseHover)); + PdfDictionaryProperties.r, + PdfReferenceHolder(_mouseHover), + ); } return _mouseHover!; } @@ -41,8 +45,10 @@ class PdfExtendedAppearance implements IPdfWrapper { PdfAppearanceState get pressed { if (_pressed == null) { _pressed = PdfAppearanceState(); - _dictionary! - .setProperty(PdfDictionaryProperties.d, PdfReferenceHolder(_pressed)); + _dictionary!.setProperty( + PdfDictionaryProperties.d, + PdfReferenceHolder(_pressed), + ); } return _pressed!; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/enum.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/enum.dart index 3abb8acbf..12ade3fce 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/enum.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/enum.dart @@ -10,7 +10,7 @@ enum PdfHighlightMode { outline, /// Pushed highlighting. - push + push, } /// Specifies the file path type. @@ -19,7 +19,7 @@ enum PdfFilePathType { relative, /// Specifies the location, including the domain name. - absolute + absolute, } /// Specifies the annotation types. @@ -64,7 +64,7 @@ enum PdfAnnotationTypes { popupAnnotation, /// No annotation. - noAnnotation + noAnnotation, } /// Specifies the annotation export types. @@ -94,7 +94,7 @@ enum PdfAnnotationExportType { squigglyAnnotation, /// Popup annotation type. - popupAnnotation + popupAnnotation, } /// Specifies the format of Export or Import data. @@ -129,7 +129,7 @@ enum PdfBorderStyle { underline, /// A dotted rectangle surrounding the annotation. - dot + dot, } /// Gets or sets the line intent of the annotation. @@ -180,7 +180,7 @@ enum PdfLineEndingStyle { square, /// Indicates Slash - slash + slash, } /// Specifies the available data formats for submitting the form data. @@ -197,7 +197,6 @@ enum PdfSubmitFormFlags { /// Exclude flag are submitted, regardless of whether they have a value. /// For fields without a value, only the /// field name is transmitted. - includeNoValueFields, /// Meaningful only if the SubmitPDF and XFDF flags are clear. If set, @@ -265,7 +264,7 @@ enum PdfSubmitFormFlags { /// flags are clear). If set, the F entry of the submitted FDF is a file /// specification containing an embedded file stream representing the /// PDF file from which the FDF is being submitted. - embedForm + embedForm, } /// Specifies the enumeration of submit data formats. @@ -280,7 +279,7 @@ enum SubmitDataFormat { fdf, /// Data should be transmitted as XML Forms Data Format. - xfdf + xfdf, } /// Specifies Http request method. @@ -289,7 +288,7 @@ enum HttpMethod { getHttp, /// Data submitted using Http Post method. - post + post, } /// Specifies the Style of the Text Markup Annotation @@ -328,7 +327,7 @@ enum PdfPopupIcon { newParagraph, /// Indicates paragraph popup annotation. - paragraph + paragraph, } /// Specifies the enumeration of the annotation flags. @@ -361,5 +360,5 @@ enum PdfAnnotationFlags { locked, /// Annotation flag's key with no toggle view. - toggleNoView + toggleNoView, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_document.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_document.dart index ba34662bd..fa06b04a1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_document.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_document.dart @@ -29,7 +29,11 @@ class FdfDocument { /// Internal method Map exportAnnotations( - int currentID, List annotID, int pageIndex, bool hasAppearance) { + int currentID, + List annotID, + int pageIndex, + bool hasAppearance, + ) { const String startObject = '${PdfOperators.whiteSpace}0${PdfOperators.whiteSpace}${PdfOperators.obj}${PdfOperators.newLine}'; const String endObject = @@ -43,11 +47,12 @@ class FdfDocument { annotID.add(_annotationID); dictionary.items![PdfName('Page')] = PdfNumber(pageIndex); Map exportDataDictionary = _getEntriesInDictionary( - subDictionaries, - streamReferences, - currentID, - dictionary, - hasAppearance); + subDictionaries, + streamReferences, + currentID, + dictionary, + hasAppearance, + ); exportData.addAll(exportDataDictionary['exportData'] as List); currentID = exportDataDictionary['currentID'] as int; dictionary.remove('Page'); @@ -68,8 +73,13 @@ class FdfDocument { } } exportData.addAll(utf8.encode('$key$startObject<<')); - exportDataDictionary = _getEntriesInDictionary(subDictionaries, - streamReferences, currentID, dictionary, hasAppearance); + exportDataDictionary = _getEntriesInDictionary( + subDictionaries, + streamReferences, + currentID, + dictionary, + hasAppearance, + ); exportData.addAll(exportDataDictionary['exportData'] as List); currentID = exportDataDictionary['currentID'] as int; if (dictionary.containsKey('Page')) { @@ -86,20 +96,31 @@ class FdfDocument { } else if (subDictionaries[key] is PdfArray) { final PdfArray array = subDictionaries[key]! as PdfArray; exportData.addAll(utf8.encode('$key$startObject')); - final Map result = _appendArrayElements(array, - currentID, hasAppearance, subDictionaries, streamReferences); + final Map result = _appendArrayElements( + array, + currentID, + hasAppearance, + subDictionaries, + streamReferences, + ); exportData.addAll(result['exportData'] as List); currentID = result['currentID'] as int; exportData.addAll(utf8.encode(endObject)); } else if (subDictionaries[key] is PdfBoolean) { final PdfBoolean boolean = subDictionaries[key]! as PdfBoolean; - exportData.addAll(utf8.encode( - '$key$startObject${boolean.value! ? 'true' : 'false'}$endObject')); + exportData.addAll( + utf8.encode( + '$key$startObject${boolean.value! ? 'true' : 'false'}$endObject', + ), + ); } else if (subDictionaries[key] is PdfString) { final PdfString data = subDictionaries[key]! as PdfString; if (data.value != null) { - exportData.addAll(utf8.encode( - '$key$startObject(${_getFormattedStringFDF(data.value!)})$endObject')); + exportData.addAll( + utf8.encode( + '$key$startObject(${_getFormattedStringFDF(data.value!)})$endObject', + ), + ); } } subDictionaries.remove(key); @@ -123,11 +144,12 @@ class FdfDocument { } Map _getEntriesInDictionary( - Map dictionaries, - List streamReferences, - int currentID, - PdfDictionary dictionary, - bool hasAppearance) { + Map dictionaries, + List streamReferences, + int currentID, + PdfDictionary dictionary, + bool hasAppearance, + ) { final List annotationData = []; bool isStream = false; final List keys = dictionary.items!.keys.toList(); @@ -147,13 +169,19 @@ class FdfDocument { if (primitive is PdfString) { if (primitive.value != null) { annotationData.addAll( - utf8.encode('(${_getFormattedStringFDF(primitive.value!)})')); + utf8.encode('(${_getFormattedStringFDF(primitive.value!)})'), + ); } } else if (primitive is PdfName) { annotationData.addAll(utf8.encode(primitive.toString())); } else if (primitive is PdfArray) { final Map result = _appendArrayElements( - primitive, currentID, isStream, dictionaries, streamReferences); + primitive, + currentID, + isStream, + dictionaries, + streamReferences, + ); annotationData.addAll(result['exportData'] as List); currentID = result['currentID'] as int; } else if (primitive is PdfNumber) { @@ -162,15 +190,21 @@ class FdfDocument { annotationData.addAll(utf8.encode(' ${primitive.value!}')); } else if (primitive is PdfDictionary) { annotationData.addAll(utf8.encode('<<')); - final Map data = _getEntriesInDictionary(dictionaries, - streamReferences, currentID, primitive, hasAppearance); + final Map data = _getEntriesInDictionary( + dictionaries, + streamReferences, + currentID, + primitive, + hasAppearance, + ); annotationData.addAll(data['exportData'] as List); currentID = data['currentID'] as int; annotationData.addAll(utf8.encode('>>')); } else if (primitive is PdfReferenceHolder) { if (PdfPageHelper.getHelper(page).document != null) { - final int pageNumber = - PdfPageHelper.getHelper(page).document!.pages.indexOf(page); + final int pageNumber = PdfPageHelper.getHelper( + page, + ).document!.pages.indexOf(page); if (key.name == PdfDictionaryProperties.parent) { annotationData.addAll(utf8.encode(' $_annotationID 0 R')); annotationData.addAll(utf8.encode('/Page $pageNumber')); @@ -180,12 +214,14 @@ class FdfDocument { if (inReplyTo != null && inReplyTo is PdfDictionary && inReplyTo.containsKey('NM')) { - final IPdfPrimitive? name = - PdfCrossTable.dereference(inReplyTo['NM']); + final IPdfPrimitive? name = PdfCrossTable.dereference( + inReplyTo['NM'], + ); if (name != null && name is PdfString) { if (name.value != null) { - annotationData.addAll(utf8 - .encode('(${_getFormattedStringFDF(name.value!)})')); + annotationData.addAll( + utf8.encode('(${_getFormattedStringFDF(name.value!)})'), + ); } } } @@ -206,7 +242,7 @@ class FdfDocument { } return { 'exportData': annotationData, - 'currentID': currentID + 'currentID': currentID, }; } @@ -232,11 +268,12 @@ class FdfDocument { } Map _appendArrayElements( - PdfArray array, - int currentID, - bool isStream, - Map dictionaries, - List streamReferences) { + PdfArray array, + int currentID, + bool isStream, + Map dictionaries, + List streamReferences, + ) { final List arrayData = []; arrayData.addAll(utf8.encode('[')); if (array.elements.isNotEmpty) { @@ -251,7 +288,12 @@ class FdfDocument { arrayData.addAll(utf8.encode(' ')); } final Map result = _appendElement( - element!, currentID, isStream, dictionaries, streamReferences); + element!, + currentID, + isStream, + dictionaries, + streamReferences, + ); arrayData.addAll(result['exportData'] as List); currentID = result['currentID'] as int; } @@ -261,11 +303,12 @@ class FdfDocument { } Map _appendElement( - IPdfPrimitive element, - int currentID, - bool isStream, - Map dictionaries, - List streamReferences) { + IPdfPrimitive element, + int currentID, + bool isStream, + Map dictionaries, + List streamReferences, + ) { final List exportData = []; if (element is PdfNumber) { exportData.addAll(utf8.encode(element.value!.toString())); @@ -273,8 +316,9 @@ class FdfDocument { exportData.addAll(utf8.encode(element.toString())); } else if (element is PdfString) { if (element.value != null) { - exportData - .addAll(utf8.encode('(${_getFormattedStringFDF(element.value!)})')); + exportData.addAll( + utf8.encode('(${_getFormattedStringFDF(element.value!)})'), + ); } } else if (element is PdfBoolean) { exportData.addAll(utf8.encode(element.value!.toString())); @@ -289,13 +333,23 @@ class FdfDocument { exportData.addAll(utf8.encode('$currentID 0 R')); } else if (element is PdfArray) { final Map result = _appendArrayElements( - element, currentID, isStream, dictionaries, streamReferences); + element, + currentID, + isStream, + dictionaries, + streamReferences, + ); currentID = result['currentID'] as int; exportData.addAll(result['exportData'] as List); } else if (element is PdfDictionary) { exportData.addAll(utf8.encode('<<')); final Map data = _getEntriesInDictionary( - dictionaries, streamReferences, currentID, element, isStream); + dictionaries, + streamReferences, + currentID, + element, + isStream, + ); exportData.addAll(data['exportData'] as List); currentID = data['currentID'] as int; exportData.addAll(utf8.encode('>>')); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_parser.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_parser.dart index c9cb03558..293982667 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_parser.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/fdf_parser.dart @@ -43,7 +43,7 @@ class FdfParser { return _groupObjects!; } -//Implementations. + //Implementations. /// Parse the annotation data. void parseAnnotationData() { final PdfCrossTable table = PdfCrossTable.fromFdf(_data); @@ -112,15 +112,20 @@ class FdfParser { contentText = contentText.substring(1); } while (contentText.endsWith(')')) { - contentText = - contentText.substring(0, contentText.length - 1); + contentText = contentText.substring( + 0, + contentText.length - 1, + ); } } - dictionary[PdfDictionaryProperties.contents] = - PdfString(contentText); + dictionary[PdfDictionaryProperties.contents] = PdfString( + contentText, + ); if (dictionary.containsKey('RC')) { - dictionary.setString('RC', - '

$contentText

'); + dictionary.setString( + 'RC', + '

$contentText

', + ); } dictionary.modify(); } @@ -136,12 +141,14 @@ class FdfParser { final PdfDictionary? pageDictionary = PdfPageHelper.getHelper(loadedPage).dictionary; if (pageDictionary != null) { - if (!pageDictionary - .containsKey(PdfDictionaryProperties.annots)) { + if (!pageDictionary.containsKey( + PdfDictionaryProperties.annots, + )) { pageDictionary[PdfDictionaryProperties.annots] = PdfArray(); } final IPdfPrimitive? annots = PdfCrossTable.dereference( - pageDictionary[PdfDictionaryProperties.annots]); + pageDictionary[PdfDictionaryProperties.annots], + ); if (annots != null && annots is PdfArray) { annots.elements.add(holder); annots.changed = true; @@ -201,8 +208,9 @@ class FdfParser { final String key = '${reference.objNum} ${reference.genNum}'; if (objects.containsKey(key)) { - mappedObjects[key] = - PdfReferenceHolder(objects[key]); + mappedObjects[key] = PdfReferenceHolder( + objects[key], + ); objects.remove(key); } } @@ -245,7 +253,8 @@ class FdfParser { final int index = header.indexOf('%FDF-'); if (index < 0) { throw ArgumentError( - 'The source is not a valid FDF file because it does not start with"%FDF-"'); + 'The source is not a valid FDF file because it does not start with"%FDF-"', + ); } return index + headerLength; } @@ -352,8 +361,9 @@ class FdfParser { } else if (objects[objectKey] != null && objects[objectKey] is PdfDictionary) { _parseDictionary(objects[objectKey]! as PdfDictionary); - final PdfReferenceHolder holder = - PdfReferenceHolder(objects[objectKey]); + final PdfReferenceHolder holder = PdfReferenceHolder( + objects[objectKey], + ); array.elements[i] = holder; objects[objectKey] = holder; array.changed = true; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_document.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_document.dart index 871ad62e8..bb6c50283 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_document.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_document.dart @@ -32,8 +32,12 @@ class JsonDocument { //Implementation /// Internal method. - void exportAnnotationData(Map table, bool exportAppearance, - int pageIndex, PdfDictionary dictionary) { + void exportAnnotationData( + Map table, + bool exportAppearance, + int pageIndex, + PdfDictionary dictionary, + ) { bool hasAppearance = exportAppearance; _skipBorderStyle = false; final String? annotationType = _getAnnotationType(dictionary); @@ -44,7 +48,8 @@ class JsonDocument { case PdfDictionaryProperties.line: if (dictionary.containsKey(PdfDictionaryProperties.l)) { final IPdfPrimitive? linePoints = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.l]); + dictionary[PdfDictionaryProperties.l], + ); if (linePoints != null && linePoints is PdfArray && linePoints.count == 4 && @@ -76,8 +81,9 @@ class JsonDocument { } if (dictionary.containsKey(PdfDictionaryProperties.be) && dictionary.containsKey(PdfDictionaryProperties.bs)) { - final IPdfPrimitive? borderEffect = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.be]); + final IPdfPrimitive? borderEffect = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.be], + ); if (borderEffect != null && borderEffect is PdfDictionary && borderEffect.containsKey(PdfDictionaryProperties.s)) { @@ -112,12 +118,17 @@ class JsonDocument { return json; } - void _writeDictionary(int pageIndex, PdfDictionary dictionary, - bool hasAppearance, Map table) { + void _writeDictionary( + int pageIndex, + PdfDictionary dictionary, + bool hasAppearance, + Map table, + ) { bool isBSdictionary = false; if (dictionary.containsKey(PdfDictionaryProperties.type)) { - final IPdfPrimitive? name = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.type]); + final IPdfPrimitive? name = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.type], + ); if (name != null && name is PdfName && name.name != null && @@ -167,16 +178,18 @@ class JsonDocument { _exportMeasureDictionary(dictionary, table); } if (hasAppearance && dictionary.containsKey(PdfDictionaryProperties.ap)) { - List? bytes = - _getAppearanceString(dictionary[PdfDictionaryProperties.ap]!); + List? bytes = _getAppearanceString( + dictionary[PdfDictionaryProperties.ap]!, + ); if (bytes.isNotEmpty) { table['appearance'] = base64.encode(bytes); } bytes = null; } if (dictionary.containsKey('Sound')) { - final IPdfPrimitive? sound = - PdfCrossTable.dereference(dictionary['Sound']); + final IPdfPrimitive? sound = PdfCrossTable.dereference( + dictionary['Sound'], + ); if (sound != null && sound is PdfStream) { if (sound.containsKey('B')) { final String? bits = _getValue(sound['B']); @@ -208,15 +221,17 @@ class JsonDocument { table[XfdfProperties.mode.toLowerCase()] = 'raw'; table['encodings'] = 'hex'; if (sound.containsKey(PdfDictionaryProperties.length)) { - final String? length = - _getValue(sound[PdfDictionaryProperties.length]); + final String? length = _getValue( + sound[PdfDictionaryProperties.length], + ); if (!isNullOrEmpty(length)) { table[PdfDictionaryProperties.length.toLowerCase()] = length!; } } if (sound.containsKey(PdfDictionaryProperties.filter)) { - final String? filter = - _getValue(sound[PdfDictionaryProperties.filter]); + final String? filter = _getValue( + sound[PdfDictionaryProperties.filter], + ); if (!isNullOrEmpty(filter)) { table[PdfDictionaryProperties.filter.toLowerCase()] = filter!; } @@ -226,66 +241,83 @@ class JsonDocument { } } } else if (dictionary.containsKey(PdfDictionaryProperties.fs)) { - final IPdfPrimitive? fsDictionary = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.fs]); + final IPdfPrimitive? fsDictionary = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.fs], + ); if (fsDictionary != null && fsDictionary is PdfDictionary) { if (fsDictionary.containsKey(PdfDictionaryProperties.f)) { - final String? file = - _getValue(fsDictionary[PdfDictionaryProperties.f]); + final String? file = _getValue( + fsDictionary[PdfDictionaryProperties.f], + ); if (!isNullOrEmpty(file)) { table['file'] = file!; } } if (fsDictionary.containsKey(PdfDictionaryProperties.ef)) { final IPdfPrimitive? efDictionary = PdfCrossTable.dereference( - fsDictionary[PdfDictionaryProperties.ef]); + fsDictionary[PdfDictionaryProperties.ef], + ); if (efDictionary != null && efDictionary is PdfDictionary && efDictionary.containsKey(PdfDictionaryProperties.f)) { final IPdfPrimitive? fStream = PdfCrossTable.dereference( - efDictionary[PdfDictionaryProperties.f]); + efDictionary[PdfDictionaryProperties.f], + ); if (fStream != null && fStream is PdfStream) { if (fStream.containsKey(PdfDictionaryProperties.params)) { final IPdfPrimitive? paramsDictionary = PdfCrossTable.dereference( - fStream[PdfDictionaryProperties.params]); + fStream[PdfDictionaryProperties.params], + ); if (paramsDictionary != null && paramsDictionary is PdfDictionary) { - if (paramsDictionary - .containsKey(PdfDictionaryProperties.creationDate)) { + if (paramsDictionary.containsKey( + PdfDictionaryProperties.creationDate, + )) { final IPdfPrimitive? creationDate = - PdfCrossTable.dereference(paramsDictionary[ - PdfDictionaryProperties.creationDate]); + PdfCrossTable.dereference( + paramsDictionary[PdfDictionaryProperties + .creationDate], + ); if (creationDate != null && creationDate is PdfString) { - final DateTime dateTime = - dictionary.getDateTime(creationDate); - table['creation'] = - DateFormat('M/d/yyyy h:mm:ss a').format(dateTime); + final DateTime dateTime = dictionary.getDateTime( + creationDate, + ); + table['creation'] = DateFormat( + 'M/d/yyyy h:mm:ss a', + ).format(dateTime); } } - if (paramsDictionary - .containsKey(PdfDictionaryProperties.modificationDate)) { + if (paramsDictionary.containsKey( + PdfDictionaryProperties.modificationDate, + )) { final IPdfPrimitive? modifyDate = PdfCrossTable.dereference( - paramsDictionary[ - PdfDictionaryProperties.modificationDate]); + paramsDictionary[PdfDictionaryProperties + .modificationDate], + ); if (modifyDate != null && modifyDate is PdfString) { - final DateTime dateTime = - dictionary.getDateTime(modifyDate); - table['modification'] = - DateFormat('M/d/yyyy h:mm:ss a').format(dateTime); + final DateTime dateTime = dictionary.getDateTime( + modifyDate, + ); + table['modification'] = DateFormat( + 'M/d/yyyy h:mm:ss a', + ).format(dateTime); } } - if (paramsDictionary - .containsKey(PdfDictionaryProperties.size)) { + if (paramsDictionary.containsKey( + PdfDictionaryProperties.size, + )) { final String? size = _getValue( - paramsDictionary[PdfDictionaryProperties.size]); + paramsDictionary[PdfDictionaryProperties.size], + ); if (!isNullOrEmpty(size)) { table[PdfDictionaryProperties.size.toLowerCase()] = size!; } } if (paramsDictionary.containsKey('CheckSum')) { - final String? checksumValue = - _getValue(paramsDictionary['CheckSum']); + final String? checksumValue = _getValue( + paramsDictionary['CheckSum'], + ); if (!isNullOrEmpty(checksumValue)) { final List checksum = utf8.encode(checksumValue!); final String hexString = PdfString.bytesToHex(checksum); @@ -303,16 +335,18 @@ class JsonDocument { table[PdfDictionaryProperties.encoding.toLowerCase()] = XfdfProperties.hex.toLowerCase(); if (fStream.containsKey(PdfDictionaryProperties.length)) { - final String? length = - _getValue(fStream[PdfDictionaryProperties.length]); + final String? length = _getValue( + fStream[PdfDictionaryProperties.length], + ); if (!isNullOrEmpty(length)) { table[PdfDictionaryProperties.length.toLowerCase()] = length!; } } if (fStream.containsKey(PdfDictionaryProperties.filter)) { - final String? filter = - _getValue(fStream[PdfDictionaryProperties.filter]); + final String? filter = _getValue( + fStream[PdfDictionaryProperties.filter], + ); if (!isNullOrEmpty(filter)) { table[PdfDictionaryProperties.filter.toLowerCase()] = filter!; @@ -341,7 +375,9 @@ class JsonDocument { } void _writeAppearanceDictionary( - Map textWriter, PdfDictionary dictionary) { + Map textWriter, + PdfDictionary dictionary, + ) { if (dictionary.count > 0) { dictionary.items!.forEach((PdfName? name, IPdfPrimitive? value) { _writeObject(textWriter, name!.name, value, null); @@ -349,8 +385,12 @@ class JsonDocument { } } - void _writeObject(Map? textWriter, String? key, - IPdfPrimitive? primitive, List>? arrayWriter) { + void _writeObject( + Map? textWriter, + String? key, + IPdfPrimitive? primitive, + List>? arrayWriter, + ) { if (primitive != null) { final String type = primitive.runtimeType.toString(); switch (type) { @@ -381,23 +421,27 @@ class JsonDocument { final Map streamTable = {}; _writeAppearanceDictionary(streamTable, streamElement); final Map dataTable = {}; - final String? type = - _getValue(streamElement[PdfDictionaryProperties.subtype]); + final String? type = _getValue( + streamElement[PdfDictionaryProperties.subtype], + ); if ((streamElement.containsKey(PdfDictionaryProperties.subtype) && !isNullOrEmpty(type) && PdfDictionaryProperties.image == type!) || (!streamElement.containsKey(PdfDictionaryProperties.type) && - !streamElement - .containsKey(PdfDictionaryProperties.subtype))) { + !streamElement.containsKey( + PdfDictionaryProperties.subtype, + ))) { dataTable['mode'] = 'raw'; dataTable['encoding'] = 'hex'; - final String data = - PdfString.bytesToHex(streamElement.dataStream!); + final String data = PdfString.bytesToHex( + streamElement.dataStream!, + ); if (!isNullOrEmpty(data)) { dataTable['bytes'] = data; } - } else if (streamElement - .containsKey(PdfDictionaryProperties.subtype) && + } else if (streamElement.containsKey( + PdfDictionaryProperties.subtype, + ) && !isNullOrEmpty(type) && (PdfDictionaryProperties.form == type || 'CIDFontType0C' == type || @@ -405,8 +449,9 @@ class JsonDocument { dataTable['mode'] = 'raw'; dataTable['encoding'] = 'hex'; streamElement.decompress(); - final String data = - PdfString.bytesToHex(streamElement.dataStream!); + final String data = PdfString.bytesToHex( + streamElement.dataStream!, + ); if (!isNullOrEmpty(data)) { dataTable['bytes'] = data; } @@ -414,8 +459,9 @@ class JsonDocument { dataTable['mode'] = 'filtered'; dataTable['encoding'] = 'ascii'; streamElement.decompress(); - final String ascii = - PdfString.bytesToHex(streamElement.dataStream!); + final String ascii = PdfString.bytesToHex( + streamElement.dataStream!, + ); if (!isNullOrEmpty(ascii)) { dataTable['bytes'] = ascii; } @@ -474,8 +520,9 @@ class JsonDocument { arrayWriter!.add(integer); } } else { - final String value = - primitive.value!.toDouble().toStringAsFixed(6); + final String value = primitive.value!.toDouble().toStringAsFixed( + 6, + ); final Map integer = {}; integer['fixed'] = value; if (key != null) { @@ -581,8 +628,13 @@ class JsonDocument { return value; } - void _writeAttribute(String key, IPdfPrimitive primitive, int p, - PdfDictionary dictionary, Map table) { + void _writeAttribute( + String key, + IPdfPrimitive primitive, + int p, + PdfDictionary dictionary, + Map table, + ) { switch (key) { case PdfDictionaryProperties.c: final String color = _getColor(primitive); @@ -591,8 +643,9 @@ class JsonDocument { } break; case PdfDictionaryProperties.da: - final IPdfPrimitive? defaultAppearance = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.da]); + final IPdfPrimitive? defaultAppearance = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.da], + ); if (defaultAppearance != null && defaultAppearance is PdfString && !isNullOrEmpty(defaultAppearance.value)) { @@ -606,8 +659,9 @@ class JsonDocument { } break; case PdfDictionaryProperties.m: - final IPdfPrimitive? modifiedDate = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.m]); + final IPdfPrimitive? modifiedDate = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.m], + ); if (modifiedDate != null && modifiedDate is PdfString && !isNullOrEmpty(modifiedDate.value)) { @@ -653,13 +707,15 @@ class JsonDocument { break; case PdfDictionaryProperties.creationDate: final IPdfPrimitive? createDate = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.creationDate]); + dictionary[PdfDictionaryProperties.creationDate], + ); if (createDate != null && createDate is PdfString && !isNullOrEmpty(createDate.value)) { final DateTime creationDate = dictionary.getDateTime(createDate); - table[key.toLowerCase()] = - DateFormat('M/d/yyyy h:mm:ss a').format(creationDate); + table[key.toLowerCase()] = DateFormat( + 'M/d/yyyy h:mm:ss a', + ).format(creationDate); } break; case PdfDictionaryProperties.rotate: @@ -790,18 +846,21 @@ class JsonDocument { if (primitive is PdfNumber) { final List annotationFlags = PdfAnnotationHelper.obtainAnnotationFlags( - primitive.value!.toInt()); - final String flag = annotationFlags - .map((PdfAnnotationFlags flag) => getEnumName(flag)) - .toString() - .replaceAll(RegExp('[ ()]'), '') - .toLowerCase(); + primitive.value!.toInt(), + ); + final String flag = + annotationFlags + .map((PdfAnnotationFlags flag) => getEnumName(flag)) + .toString() + .replaceAll(RegExp('[ ()]'), '') + .toLowerCase(); table[PdfDictionaryProperties.flags.toLowerCase()] = flag; } break; case PdfDictionaryProperties.contents: final IPdfPrimitive? contents = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.contents]); + dictionary[PdfDictionaryProperties.contents], + ); if (contents != null && contents is PdfString && !isNullOrEmpty(contents.value)) { @@ -810,8 +869,9 @@ class JsonDocument { break; case 'InkList': final Map points = {}; - final IPdfPrimitive? inkList = - PdfCrossTable.dereference(dictionary['InkList']); + final IPdfPrimitive? inkList = PdfCrossTable.dereference( + dictionary['InkList'], + ); if (inkList != null && inkList is PdfArray && inkList.count > 0) { final List element = []; for (int j = 0; j < inkList.count; j++) { @@ -825,7 +885,8 @@ class JsonDocument { break; case PdfDictionaryProperties.vertices: final IPdfPrimitive? vertices = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.vertices]); + dictionary[PdfDictionaryProperties.vertices], + ); if (vertices != null && vertices is PdfArray && vertices.count > 0) { if (vertices.count.isEven) { String value = ''; @@ -854,8 +915,9 @@ class JsonDocument { break; case 'DS': if (dictionary.containsKey('DS')) { - final IPdfPrimitive? defaultStyle = - PdfCrossTable.dereference(dictionary['DS']); + final IPdfPrimitive? defaultStyle = PdfCrossTable.dereference( + dictionary['DS'], + ); final Map styleTable = {}; if (defaultStyle != null && defaultStyle is PdfString && @@ -874,8 +936,9 @@ class JsonDocument { break; case 'RC': if (dictionary.containsKey('RC')) { - final IPdfPrimitive? contentStyle = - PdfCrossTable.dereference(dictionary['RC']); + final IPdfPrimitive? contentStyle = PdfCrossTable.dereference( + dictionary['RC'], + ); if (contentStyle != null && contentStyle is PdfString && !isNullOrEmpty(contentStyle.value)) { @@ -935,24 +998,30 @@ class JsonDocument { String _getColor(IPdfPrimitive primitive) { String color = ''; if (primitive is PdfArray && primitive.count >= 3) { - final String r = PdfString.bytesToHex([ - ((primitive.elements[0]! as PdfNumber).value! * 255).round() - ]).toUpperCase(); - final String g = PdfString.bytesToHex([ - ((primitive.elements[1]! as PdfNumber).value! * 255).round() - ]).toUpperCase(); - final String b = PdfString.bytesToHex([ - ((primitive.elements[2]! as PdfNumber).value! * 255).round() - ]).toUpperCase(); + final String r = + PdfString.bytesToHex([ + ((primitive.elements[0]! as PdfNumber).value! * 255).round(), + ]).toUpperCase(); + final String g = + PdfString.bytesToHex([ + ((primitive.elements[1]! as PdfNumber).value! * 255).round(), + ]).toUpperCase(); + final String b = + PdfString.bytesToHex([ + ((primitive.elements[2]! as PdfNumber).value! * 255).round(), + ]).toUpperCase(); color = '#$r$g$b'; } return color; } void _exportMeasureDictionary( - PdfDictionary dictionary, Map table) { - final IPdfPrimitive? mdictionary = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.measure]); + PdfDictionary dictionary, + Map table, + ) { + final IPdfPrimitive? mdictionary = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.measure], + ); if (mdictionary != null && mdictionary is PdfDictionary) { if (mdictionary.containsKey(PdfDictionaryProperties.type)) { table['type1'] = 'Measure'; @@ -964,8 +1033,9 @@ class JsonDocument { } } if (mdictionary.containsKey(PdfDictionaryProperties.subtype)) { - final String? value = - _getValue(mdictionary[PdfDictionaryProperties.subtype]); + final String? value = _getValue( + mdictionary[PdfDictionaryProperties.subtype], + ); if (!isNullOrEmpty(value)) { table[PdfDictionaryProperties.subtype] = value!; } @@ -981,8 +1051,9 @@ class JsonDocument { if (aArray != null && aArray is PdfArray && aArray.elements.isNotEmpty) { - final IPdfPrimitive? adictionary = - PdfCrossTable.dereference(aArray.elements[0]); + final IPdfPrimitive? adictionary = PdfCrossTable.dereference( + aArray.elements[0], + ); if (adictionary != null && adictionary is PdfDictionary) { _exportMeasureFormatDetails('area', adictionary, table); } @@ -993,8 +1064,9 @@ class JsonDocument { if (dArray != null && dArray is PdfArray && dArray.elements.isNotEmpty) { - final IPdfPrimitive? ddictionary = - PdfCrossTable.dereference(dArray.elements[0]); + final IPdfPrimitive? ddictionary = PdfCrossTable.dereference( + dArray.elements[0], + ); if (ddictionary != null && ddictionary is PdfDictionary) { _exportMeasureFormatDetails('distance', ddictionary, table); } @@ -1005,8 +1077,9 @@ class JsonDocument { if (xArray != null && xArray is PdfArray && xArray.elements.isNotEmpty) { - final IPdfPrimitive? xdictionary = - PdfCrossTable.dereference(xArray.elements[0]); + final IPdfPrimitive? xdictionary = PdfCrossTable.dereference( + xArray.elements[0], + ); if (xdictionary != null && xdictionary is PdfDictionary) { _exportMeasureFormatDetails('xformat', xdictionary, table); } @@ -1017,8 +1090,9 @@ class JsonDocument { if (tArray != null && tArray is PdfArray && tArray.elements.isNotEmpty) { - final IPdfPrimitive? tdictionary = - PdfCrossTable.dereference(tArray.elements[0]); + final IPdfPrimitive? tdictionary = PdfCrossTable.dereference( + tArray.elements[0], + ); if (tdictionary != null && tdictionary is PdfDictionary) { _exportMeasureFormatDetails('tformat', tdictionary, table); } @@ -1029,8 +1103,9 @@ class JsonDocument { if (vArray != null && vArray is PdfArray && vArray.elements.isNotEmpty) { - final IPdfPrimitive? vdictionary = - PdfCrossTable.dereference(vArray.elements[0]); + final IPdfPrimitive? vdictionary = PdfCrossTable.dereference( + vArray.elements[0], + ); if (vdictionary != null && vdictionary is PdfDictionary) { _exportMeasureFormatDetails('vformat', vdictionary, table); } @@ -1040,39 +1115,47 @@ class JsonDocument { } void _exportMeasureFormatDetails( - String key, PdfDictionary measurementDetails, Map table) { + String key, + PdfDictionary measurementDetails, + Map table, + ) { final Map subTable = {}; if (measurementDetails.containsKey(PdfDictionaryProperties.c)) { - final String? value = - _getValue(measurementDetails[PdfDictionaryProperties.c]); + final String? value = _getValue( + measurementDetails[PdfDictionaryProperties.c], + ); if (!isNullOrEmpty(value)) { subTable['c'] = value!; } } if (measurementDetails.containsKey(PdfDictionaryProperties.f)) { - final String? value = - _getValue(measurementDetails[PdfDictionaryProperties.f]); + final String? value = _getValue( + measurementDetails[PdfDictionaryProperties.f], + ); if (!isNullOrEmpty(value)) { subTable['f'] = value!; } } if (measurementDetails.containsKey(PdfDictionaryProperties.d)) { - final String? value = - _getValue(measurementDetails[PdfDictionaryProperties.d]); + final String? value = _getValue( + measurementDetails[PdfDictionaryProperties.d], + ); if (!isNullOrEmpty(value)) { subTable['d'] = value!; } } if (measurementDetails.containsKey(PdfDictionaryProperties.rd)) { - final String? value = - _getValue(measurementDetails[PdfDictionaryProperties.rd]); + final String? value = _getValue( + measurementDetails[PdfDictionaryProperties.rd], + ); if (!isNullOrEmpty(value)) { subTable['rd'] = value!; } } if (measurementDetails.containsKey(PdfDictionaryProperties.u)) { - final String? value = - _getValue(measurementDetails[PdfDictionaryProperties.u]); + final String? value = _getValue( + measurementDetails[PdfDictionaryProperties.u], + ); if (!isNullOrEmpty(value)) { subTable['u'] = value!; } @@ -1096,8 +1179,9 @@ class JsonDocument { } } if (measurementDetails.containsKey(PdfDictionaryProperties.type)) { - final String? value = - _getValue(measurementDetails[PdfDictionaryProperties.type]); + final String? value = _getValue( + measurementDetails[PdfDictionaryProperties.type], + ); if (!isNullOrEmpty(value)) { subTable[PdfDictionaryProperties.type] = value!; } @@ -1122,7 +1206,8 @@ class JsonDocument { String? _getAnnotationType(PdfDictionary dictionary) { if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? subtype = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.subtype]); + dictionary[PdfDictionaryProperties.subtype], + ); if (subtype != null && subtype is PdfName && subtype.name != null) { return subtype.name!; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_parser.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_parser.dart index 90936e3d2..915d65ea4 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_parser.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/json_parser.dart @@ -66,7 +66,8 @@ class JsonParser { if (groupHolders != null && groupHolders!.isNotEmpty) { for (final PdfDictionary dictionary in groupHolders!) { final IPdfPrimitive? inReplyTo = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.irt]); + dictionary[PdfDictionaryProperties.irt], + ); if (inReplyTo != null && inReplyTo is PdfString && !isNullOrEmpty(inReplyTo.value)) { @@ -118,8 +119,11 @@ class JsonParser { if (pageIndex >= 0 && pageIndex < document.pages.count) { final PdfPage loadedPage = document.pages[pageIndex]; PdfPageHelper.getHelper(loadedPage).importAnnotation = true; - final PdfDictionary annotDictionary = - getAnnotationData(type, pageIndex, annotData); + final PdfDictionary annotDictionary = getAnnotationData( + type, + pageIndex, + annotData, + ); if (annotDictionary.count > 0) { final PdfReferenceHolder holder = PdfReferenceHolder(annotDictionary); if (annotDictionary.containsKey(PdfDictionaryProperties.nm) || @@ -133,7 +137,8 @@ class JsonParser { pageDictionary[PdfDictionaryProperties.annots] = PdfArray(); } final IPdfPrimitive? annots = PdfCrossTable.dereference( - pageDictionary[PdfDictionaryProperties.annots]); + pageDictionary[PdfDictionaryProperties.annots], + ); if (annots != null && annots is PdfArray) { annots.elements.add(holder); annots.changed = true; @@ -147,9 +152,12 @@ class JsonParser { /// Internal Method. void addReferenceToGroup( - PdfReferenceHolder holder, PdfDictionary dictionary) { - IPdfPrimitive? name = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.nm]); + PdfReferenceHolder holder, + PdfDictionary dictionary, + ) { + IPdfPrimitive? name = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.nm], + ); groupReferences ??= {}; if (name != null && name is PdfString && !isNullOrEmpty(name.value)) { groupReferences![name.value!] = holder; @@ -159,8 +167,9 @@ class JsonParser { } } else if (name == null) { if (dictionary.containsKey(PdfDictionaryProperties.irt)) { - name = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.irt]); + name = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.irt], + ); } if (name != null && name is PdfString && !isNullOrEmpty(name.value)) { if (groupReferences!.containsKey(name.value)) { @@ -174,41 +183,58 @@ class JsonParser { /// Internal Method. PdfDictionary getAnnotationData( - String type, int pageindex, Map annotData) { + String type, + int pageindex, + Map annotData, + ) { final PdfDictionary annotDictionary = PdfDictionary(); annotDictionary.setName( - PdfDictionaryProperties.type, PdfDictionaryProperties.annot); + PdfDictionaryProperties.type, + PdfDictionaryProperties.annot, + ); bool isValidType = true; switch (type.toLowerCase()) { case 'line': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.line); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.line, + ); break; case 'circle': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.circle); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.circle, + ); break; case 'square': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.square); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.square, + ); break; case 'polyline': annotDictionary.setName(PdfDictionaryProperties.subtype, 'PolyLine'); break; case 'polygon': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.polygon); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.polygon, + ); break; case 'ink': annotDictionary.setName(PdfDictionaryProperties.subtype, 'Ink'); break; case 'popup': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.popup); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.popup, + ); break; case 'text': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.text); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.text, + ); break; case 'freetext': annotDictionary.setName(PdfDictionaryProperties.subtype, 'FreeText'); @@ -218,23 +244,33 @@ class JsonParser { break; case 'highlight': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.highlight); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.highlight, + ); break; case 'squiggly': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.squiggly); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.squiggly, + ); break; case 'underline': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.underline); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.underline, + ); break; case 'strikeout': annotDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.strikeOut); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.strikeOut, + ); break; case 'fileattachment': annotDictionary.setName( - PdfDictionaryProperties.subtype, 'FileAttachment'); + PdfDictionaryProperties.subtype, + 'FileAttachment', + ); break; case 'sound': annotDictionary.setName(PdfDictionaryProperties.subtype, 'Sound'); @@ -260,8 +296,11 @@ class JsonParser { } /// Internal method. - void addAnnotationData(PdfDictionary annotDictionary, - Map annotData, int index) { + void addAnnotationData( + PdfDictionary annotDictionary, + Map annotData, + int index, + ) { List? linePoints = []; final PdfDictionary borderEffectDictionary = PdfDictionary(); final PdfDictionary borderStyleDictionary = PdfDictionary(); @@ -275,7 +314,9 @@ class JsonParser { linePoints!.addAll(_obtainFloatPoints(value)); if (linePoints!.length == 4) { annotDictionary.setProperty( - PdfDictionaryProperties.l, PdfArray(linePoints)); + PdfDictionaryProperties.l, + PdfArray(linePoints), + ); linePoints!.clear(); linePoints = null; } @@ -295,20 +336,29 @@ class JsonParser { break; case 'inreplyto': addString( - annotDictionary, PdfDictionaryProperties.irt, value.toString()); + annotDictionary, + PdfDictionaryProperties.irt, + value.toString(), + ); break; case 'dashes': case 'width': case 'intensity': case 'style': addBorderStyle( - key, value, borderEffectDictionary, borderStyleDictionary); + key, + value, + borderEffectDictionary, + borderStyleDictionary, + ); break; case 'rect': final List points = _obtainFloatPoints(value.values.toList()); if (points.length == 4) { annotDictionary.setProperty( - PdfDictionaryProperties.rect, PdfArray(points)); + PdfDictionaryProperties.rect, + PdfArray(points), + ); } break; case 'color': @@ -316,7 +366,9 @@ class JsonParser { final PdfArray? colorArray = getColorArray(value); if (colorArray != null) { annotDictionary.setProperty( - PdfDictionaryProperties.c, colorArray); + PdfDictionaryProperties.c, + colorArray, + ); } } break; @@ -326,7 +378,9 @@ class JsonParser { final PdfArray? colorArray = getColorArray(value); if (colorArray != null) { annotDictionary.setProperty( - PdfDictionaryProperties.ic, colorArray); + PdfDictionaryProperties.ic, + colorArray, + ); } } } @@ -336,21 +390,32 @@ class JsonParser { final PdfArray? colorArray = getColorArray(value); if (colorArray != null) { annotDictionary.setProperty( - PdfDictionaryProperties.ic, colorArray); + PdfDictionaryProperties.ic, + colorArray, + ); } } break; case 'date': addString( - annotDictionary, PdfDictionaryProperties.m, value.toString()); + annotDictionary, + PdfDictionaryProperties.m, + value.toString(), + ); break; case 'creationdate': - addString(annotDictionary, PdfDictionaryProperties.creationDate, - value.toString()); + addString( + annotDictionary, + PdfDictionaryProperties.creationDate, + value.toString(), + ); break; case 'name': addString( - annotDictionary, PdfDictionaryProperties.nm, value.toString()); + annotDictionary, + PdfDictionaryProperties.nm, + value.toString(), + ); break; case 'icon': if (value is String && !isNullOrEmpty(value)) { @@ -359,7 +424,10 @@ class JsonParser { break; case 'subject': addString( - annotDictionary, PdfDictionaryProperties.subj, value.toString()); + annotDictionary, + PdfDictionaryProperties.subj, + value.toString(), + ); break; case 'title': addString(annotDictionary, PdfDictionaryProperties.t, value); @@ -368,8 +436,11 @@ class JsonParser { addNumber(annotDictionary, PdfDictionaryProperties.rotate, value); break; case 'fringe': - addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.rd); + addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.rd, + ); break; case 'it': if (value is String && !isNullOrEmpty(value)) { @@ -378,16 +449,24 @@ class JsonParser { break; case 'leaderlength': addNumber( - annotDictionary, PdfDictionaryProperties.ll, value.toString()); + annotDictionary, + PdfDictionaryProperties.ll, + value.toString(), + ); break; case 'leaderextend': addNumber( - annotDictionary, PdfDictionaryProperties.lle, value.toString()); + annotDictionary, + PdfDictionaryProperties.lle, + value.toString(), + ); break; case 'caption': if (value is String && !isNullOrEmpty(value)) { - annotDictionary.setBoolean(PdfDictionaryProperties.cap, - value.toLowerCase() == 'yes' || value.toLowerCase() == 'true'); + annotDictionary.setBoolean( + PdfDictionaryProperties.cap, + value.toLowerCase() == 'yes' || value.toLowerCase() == 'true', + ); } break; case 'caption-style': @@ -396,32 +475,45 @@ class JsonParser { } break; case 'callout': - addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.cl); + addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.cl, + ); break; case 'coords': - addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.quadPoints); + addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.quadPoints, + ); break; case 'border': - addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.border); + addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.border, + ); break; case 'opacity': addNumber(annotDictionary, PdfDictionaryProperties.ds, value); break; case 'defaultstyle': addString( - annotDictionary, - PdfDictionaryProperties.ds, - value - .toString() - .replaceAll(RegExp(r'[{}]'), '') - .replaceAll(',', ';')); + annotDictionary, + PdfDictionaryProperties.ds, + value + .toString() + .replaceAll(RegExp(r'[{}]'), '') + .replaceAll(',', ';'), + ); break; case 'defaultappearance': - addString(annotDictionary, PdfDictionaryProperties.da, - value.toString().replaceAll(RegExp(r'[{},]'), '')); + addString( + annotDictionary, + PdfDictionaryProperties.da, + value.toString().replaceAll(RegExp(r'[{},]'), ''), + ); break; case 'contents-richtext': final String richtext = trimEscapeCharacters(value); @@ -444,8 +536,9 @@ class JsonParser { } int flagValue = 0; for (int i = 0; i < annotFlag.length; i++) { - flagValue |= - PdfAnnotationHelper.getAnnotationFlagsValue(annotFlag[i]); + flagValue |= PdfAnnotationHelper.getAnnotationFlagsValue( + annotFlag[i], + ); } if (flagValue > 0) { annotDictionary.setNumber(PdfDictionaryProperties.f, flagValue); @@ -454,14 +547,18 @@ class JsonParser { break; case 'open': if (value is String && !isNullOrEmpty(value)) { - annotDictionary.setBoolean(PdfDictionaryProperties.open, - value == 'true' || value == 'yes'); + annotDictionary.setBoolean( + PdfDictionaryProperties.open, + value == 'true' || value == 'yes', + ); } break; case 'repeat': if (value is String && !isNullOrEmpty(value)) { - annotDictionary.setBoolean(PdfDictionaryProperties.repeat, - value == 'true' || value == 'yes'); + annotDictionary.setBoolean( + PdfDictionaryProperties.repeat, + value == 'true' || value == 'yes', + ); } break; case 'overlaytext': @@ -471,7 +568,9 @@ class JsonParser { final String contents = trimEscapeCharacters(value); if (!isNullOrEmpty(contents)) { annotDictionary.setString( - PdfDictionaryProperties.contents, contents); + PdfDictionaryProperties.contents, + contents, + ); } break; case 'q': @@ -501,15 +600,19 @@ class JsonParser { pointsList.clear(); } annotDictionary.setProperty( - PdfDictionaryProperties.inkList, inkListCollection); + PdfDictionaryProperties.inkList, + inkListCollection, + ); break; case 'head': - beginLineStyle = - getEnumName(XfdfParser.mapLineEndingStyle(value.toString())); + beginLineStyle = getEnumName( + XfdfParser.mapLineEndingStyle(value.toString()), + ); break; case 'tail': - endLineStyle = - getEnumName(XfdfParser.mapLineEndingStyle(value.toString())); + endLineStyle = getEnumName( + XfdfParser.mapLineEndingStyle(value.toString()), + ); break; case 'creation': case 'modification': @@ -538,14 +641,19 @@ class JsonParser { } if (verticesList.isNotEmpty && verticesList.length.isEven) { annotDictionary.setProperty( - PdfDictionaryProperties.vertices, PdfArray(verticesList)); + PdfDictionaryProperties.vertices, + PdfArray(verticesList), + ); } } } break; case 'customdata': - addString(annotDictionary, PdfDictionaryProperties.customData, - trimEscapeCharacters(value.toString())); + addString( + annotDictionary, + PdfDictionaryProperties.customData, + trimEscapeCharacters(value.toString()), + ); break; case 'appearance': _addAppearanceData(annotDictionary, value.toString()); @@ -561,7 +669,9 @@ class JsonParser { lineEndingStyles.add(PdfName(beginLineStyle)); lineEndingStyles.add(PdfName(endLineStyle)); annotDictionary.setProperty( - PdfDictionaryProperties.le, lineEndingStyles); + PdfDictionaryProperties.le, + lineEndingStyles, + ); } else { annotDictionary.setName(PdfDictionaryProperties.le, beginLineStyle); } @@ -569,14 +679,20 @@ class JsonParser { annotDictionary.setName(PdfDictionaryProperties.le, beginLineStyle); } if (borderStyleDictionary.count > 0) { - borderStyleDictionary.setProperty(PdfDictionaryProperties.type, - PdfName(PdfDictionaryProperties.border)); - annotDictionary.setProperty(PdfDictionaryProperties.bs, - PdfReferenceHolder(borderStyleDictionary)); + borderStyleDictionary.setProperty( + PdfDictionaryProperties.type, + PdfName(PdfDictionaryProperties.border), + ); + annotDictionary.setProperty( + PdfDictionaryProperties.bs, + PdfReferenceHolder(borderStyleDictionary), + ); } if (borderEffectDictionary.count > 0) { - annotDictionary.setProperty(PdfDictionaryProperties.be, - PdfReferenceHolder(borderEffectDictionary)); + annotDictionary.setProperty( + PdfDictionaryProperties.be, + PdfReferenceHolder(borderEffectDictionary), + ); } if (dataStream != null && values != null) { addStreamData(dataStream!, annotDictionary, values!); @@ -584,7 +700,9 @@ class JsonParser { } void _addMeasureDictionary( - PdfDictionary annotDictionary, Map element) { + PdfDictionary annotDictionary, + Map element, + ) { Map? area; Map? distance; Map? xformat; @@ -608,7 +726,9 @@ class JsonParser { measureDictionary.items![PdfName(PdfDictionaryProperties.v)] = vArray; if (element.containsKey(PdfDictionaryProperties.type1.toLowerCase())) { measureDictionary.setName( - PdfDictionaryProperties.type, PdfDictionaryProperties.measure); + PdfDictionaryProperties.type, + PdfDictionaryProperties.measure, + ); } element.forEach((String key, dynamic value) { if (value is String) { @@ -621,7 +741,9 @@ class JsonParser { break; case 'targetunitconversion': measureDictionary.setString( - PdfDictionaryProperties.targetUnitConversion, value); + PdfDictionaryProperties.targetUnitConversion, + value, + ); break; case 'area': area = {}; @@ -668,8 +790,9 @@ class JsonParser { } if (measureDictionary.count > 0 && measureDictionary.containsKey(PdfDictionaryProperties.type)) { - annotDictionary.items![PdfName(PdfDictionaryProperties.measure)] = - PdfReferenceHolder(measureDictionary); + annotDictionary.items![PdfName( + PdfDictionaryProperties.measure, + )] = PdfReferenceHolder(measureDictionary); } } @@ -679,40 +802,49 @@ class JsonParser { if (elementValue != null) { switch (key.toLowerCase()) { case 'd': - dictionary.items![PdfName(PdfDictionaryProperties.d)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.d)] = PdfNumber( + elementValue, + ); break; case 'c': - dictionary.items![PdfName(PdfDictionaryProperties.c)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.c)] = PdfNumber( + elementValue, + ); break; case 'rt': - dictionary.items![PdfName(PdfDictionaryProperties.rt)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.rt)] = PdfNumber( + elementValue, + ); break; case 'rd': - dictionary.items![PdfName(PdfDictionaryProperties.rd)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.rd)] = PdfNumber( + elementValue, + ); break; case 'ss': - dictionary.items![PdfName(PdfDictionaryProperties.ss)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.ss)] = PdfNumber( + elementValue, + ); break; case 'u': - dictionary.items![PdfName(PdfDictionaryProperties.u)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.u)] = PdfNumber( + elementValue, + ); break; case 'f': - dictionary.items![PdfName(PdfDictionaryProperties.f)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.f)] = PdfNumber( + elementValue, + ); break; case 'fd': - dictionary.items![PdfName(PdfDictionaryProperties.fd)] = - PdfNumber(elementValue); + dictionary.items![PdfName(PdfDictionaryProperties.fd)] = PdfNumber( + elementValue, + ); break; case 'type': - dictionary.items![PdfName(PdfDictionaryProperties.type)] = - PdfNumber(elementValue); + dictionary.items![PdfName( + PdfDictionaryProperties.type, + )] = PdfNumber(elementValue); break; } } @@ -720,7 +852,9 @@ class JsonParser { } Map _addDictionaryData( - Map data, String value) { + Map data, + String value, + ) { String addValue = ''; for (int k = 0; k < value.length; k++) { addValue += (value[k] == ':' || value[k] == ';') ? '#' : value[k]; @@ -736,13 +870,15 @@ class JsonParser { if (!isNullOrEmpty(value)) { final List appearanceData = base64.decode(value); if (appearanceData.isNotEmpty) { - final Map dict = - json.decode(utf8.decode(appearanceData)); + final Map dict = json.decode( + utf8.decode(appearanceData), + ); final PdfDictionary appearance = PdfDictionary(); if (dict.isNotEmpty) { for (final dynamic dictValue in dict.values) { dictionary[PdfDictionaryProperties.ap] = PdfReferenceHolder( - _parseDictionaryItems(dictValue, appearance)); + _parseDictionaryItems(dictValue, appearance), + ); } } } @@ -751,7 +887,9 @@ class JsonParser { } IPdfPrimitive _parseDictionaryItems( - dynamic elementValue, IPdfPrimitive primitive) { + dynamic elementValue, + IPdfPrimitive primitive, + ) { if (elementValue != null) { if (elementValue is Map) { for (String token in elementValue.keys) { @@ -802,7 +940,8 @@ class JsonParser { bool isImage = false; if (primitive.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? subtype = PdfCrossTable.dereference( - primitive[PdfDictionaryProperties.subtype]); + primitive[PdfDictionaryProperties.subtype], + ); if (subtype != null && subtype is PdfName && subtype.name == PdfDictionaryProperties.image) { @@ -827,13 +966,15 @@ class JsonParser { } else if (primitive is PdfDictionary) { _isNormalAppearanceAdded = true; final PdfDictionary dic = PdfDictionary(); - primitive[token] = - PdfReferenceHolder(_parseDictionaryItems(value, dic)); + primitive[token] = PdfReferenceHolder( + _parseDictionaryItems(value, dic), + ); } else { _isNormalAppearanceAdded = true; final PdfDictionary dic = PdfDictionary(); - dic[token] = - PdfReferenceHolder(_parseDictionaryItems(value, dic)); + dic[token] = PdfReferenceHolder( + _parseDictionaryItems(value, dic), + ); return dic; } break; @@ -910,8 +1051,9 @@ class JsonParser { default: if (primitive is PdfDictionary) { final PdfDictionary temp = PdfDictionary(); - primitive[token] = - PdfReferenceHolder(_parseDictionaryItems(value, temp)); + primitive[token] = PdfReferenceHolder( + _parseDictionaryItems(value, temp), + ); } break; } @@ -944,8 +1086,9 @@ class JsonParser { break; case 'dict': PdfDictionary pdfDictionary = PdfDictionary(); - pdfDictionary = _parseDictionaryItems(value, pdfDictionary) - as PdfDictionary; + pdfDictionary = + _parseDictionaryItems(value, pdfDictionary) + as PdfDictionary; primitive.add(PdfReferenceHolder(pdfDictionary)); break; case 'array': @@ -1012,10 +1155,11 @@ class JsonParser { /// Internal Methods. void addBorderStyle( - String key, - dynamic value, - PdfDictionary borderEffectDictionary, - PdfDictionary borderStyleDictionary) { + String key, + dynamic value, + PdfDictionary borderEffectDictionary, + PdfDictionary borderStyleDictionary, + ) { if (value is String) { switch (value) { case 'dash': @@ -1052,14 +1196,18 @@ class JsonParser { } } if (!isNullOrEmpty(style)) { - (isBasicStyle ? borderStyleDictionary : borderEffectDictionary) - .setName(PdfDictionaryProperties.s, style); + (isBasicStyle ? borderStyleDictionary : borderEffectDictionary).setName( + PdfDictionaryProperties.s, + style, + ); } if (key == 'dashes') { final List dashPoints = _obtainFloatPoints(value.toString()); if (dashPoints.isNotEmpty) { borderStyleDictionary.setProperty( - PdfDictionaryProperties.d, PdfArray(dashPoints)); + PdfDictionaryProperties.d, + PdfArray(dashPoints), + ); } } } @@ -1124,11 +1272,15 @@ class JsonParser { } /// Internal Methods. - void addStreamData(Map dataValues, - PdfDictionary annotDictionary, String values) { + void addStreamData( + Map dataValues, + PdfDictionary annotDictionary, + String values, + ) { if (annotDictionary.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? primitive = PdfCrossTable.dereference( - annotDictionary[PdfDictionaryProperties.subtype]); + annotDictionary[PdfDictionaryProperties.subtype], + ); if (primitive != null && primitive is PdfName && primitive.name != null) { final String subtype = primitive.name!; final List raw = List.from(hex.decode(values)); @@ -1136,7 +1288,9 @@ class JsonParser { if (subtype.toLowerCase() == 'sound') { final PdfStream soundStream = PdfStream(); soundStream.setName( - PdfDictionaryProperties.type, PdfDictionaryProperties.sound); + PdfDictionaryProperties.type, + PdfDictionaryProperties.sound, + ); dataValues.forEach((String key, String value) { switch (key) { case 'bits': @@ -1166,13 +1320,17 @@ class JsonParser { }); soundStream.data = raw; annotDictionary.setProperty( - PdfDictionaryProperties.sound, PdfReferenceHolder(soundStream)); + PdfDictionaryProperties.sound, + PdfReferenceHolder(soundStream), + ); } else if (subtype.toLowerCase() == 'fileattachment') { final PdfDictionary fileDictionary = PdfDictionary(); final PdfStream fileStream = PdfStream(); final PdfDictionary param = PdfDictionary(); fileDictionary.setName( - PdfDictionaryProperties.type, PdfDictionaryProperties.filespec); + PdfDictionaryProperties.type, + PdfDictionaryProperties.filespec, + ); dataValues.forEach((String key, String value) { switch (key) { case 'file': @@ -1188,11 +1346,17 @@ class JsonParser { break; case 'creation': addString( - param, 'creation', PdfDictionaryProperties.creationDate); + param, + 'creation', + PdfDictionaryProperties.creationDate, + ); break; case 'modification': - addString(param, 'modification', - PdfDictionaryProperties.modificationDate); + addString( + param, + 'modification', + PdfDictionaryProperties.modificationDate, + ); break; } }); @@ -1200,11 +1364,17 @@ class JsonParser { fileStream.data = raw; final PdfDictionary embeddedFile = PdfDictionary(); embeddedFile.setProperty( - PdfDictionaryProperties.f, PdfReferenceHolder(fileStream)); + PdfDictionaryProperties.f, + PdfReferenceHolder(fileStream), + ); fileDictionary.setProperty( - PdfDictionaryProperties.ef, embeddedFile); + PdfDictionaryProperties.ef, + embeddedFile, + ); annotDictionary.setProperty( - PdfDictionaryProperties.fs, PdfReferenceHolder(fileDictionary)); + PdfDictionaryProperties.fs, + PdfReferenceHolder(fileDictionary), + ); } } } @@ -1218,8 +1388,10 @@ class JsonParser { } List _obtainFloatPoints(dynamic points) { - final List pointsValue = - points.toString().replaceAll(RegExp(r'[\[\]{}:]'), '').split(','); + final List pointsValue = points + .toString() + .replaceAll(RegExp(r'[\[\]{}:]'), '') + .split(','); final List linePoints = []; for (final dynamic value in pointsValue) { if (value is String && !isNullOrEmpty(value)) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_action_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_action_annotation.dart index d1e2ee659..27dd4d36d 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_action_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_action_annotation.dart @@ -39,9 +39,9 @@ abstract class PdfLinkAnnotation extends PdfAnnotation implements IPdfWrapper { set highlightMode(PdfHighlightMode value) { _highlightMode = value; final String mode = _getHighlightMode(_highlightMode); - PdfAnnotationHelper.getHelper(this) - .dictionary! - .setName(PdfName(PdfDictionaryProperties.h), mode); + PdfAnnotationHelper.getHelper( + this, + ).dictionary!.setName(PdfName(PdfDictionaryProperties.h), mode); } String _getHighlightMode(PdfHighlightMode mode) { @@ -65,11 +65,14 @@ abstract class PdfLinkAnnotation extends PdfAnnotation implements IPdfWrapper { PdfHighlightMode _obtainHighlightMode() { PdfHighlightMode mode = PdfHighlightMode.noHighlighting; - if (PdfAnnotationHelper.getHelper(this) - .dictionary! - .containsKey(PdfDictionaryProperties.h)) { - final PdfName name = PdfAnnotationHelper.getHelper(this) - .dictionary![PdfDictionaryProperties.h]! as PdfName; + if (PdfAnnotationHelper.getHelper( + this, + ).dictionary!.containsKey(PdfDictionaryProperties.h)) { + final PdfName name = + PdfAnnotationHelper.getHelper( + this, + ).dictionary![PdfDictionaryProperties.h]! + as PdfName; switch (name.name) { case 'I': mode = PdfHighlightMode.invert; @@ -93,15 +96,22 @@ abstract class PdfLinkAnnotation extends PdfAnnotation implements IPdfWrapper { class PdfLinkAnnotationHelper extends PdfAnnotationHelper { /// internal constructor PdfLinkAnnotationHelper( - PdfLinkAnnotation super.linkAnnotation, Rect? bounds) { + PdfLinkAnnotation super.linkAnnotation, + Rect? bounds, + ) { initializeAnnotation(bounds: bounds); - dictionary!.setProperty(PdfName(PdfDictionaryProperties.subtype), - PdfName(PdfDictionaryProperties.link)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.subtype), + PdfName(PdfDictionaryProperties.link), + ); } /// internal constructor - PdfLinkAnnotationHelper.load(PdfLinkAnnotation super.linkAnnotation, - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfLinkAnnotationHelper.load( + PdfLinkAnnotation super.linkAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { initializeExistingAnnotation(dictionary, crossTable); } } @@ -122,9 +132,10 @@ abstract class PdfActionLinkAnnotation extends PdfLinkAnnotation { class PdfActionLinkAnnotationHelper extends PdfLinkAnnotationHelper { /// internal constructor PdfActionLinkAnnotationHelper( - PdfActionLinkAnnotation actionLinkAnnotation, Rect bounds, - [PdfAction? action]) - : super(actionLinkAnnotation, bounds) { + PdfActionLinkAnnotation actionLinkAnnotation, + Rect bounds, [ + PdfAction? action, + ]) : super(actionLinkAnnotation, bounds) { if (action != null) { actionLinkAnnotation._action = action; } @@ -132,10 +143,10 @@ class PdfActionLinkAnnotationHelper extends PdfLinkAnnotationHelper { /// internal constructor PdfActionLinkAnnotationHelper.load( - PdfActionLinkAnnotation super.actionLinkAnnotation, - super.dictionary, - super.crossTable) - : super.load(); + PdfActionLinkAnnotation super.actionLinkAnnotation, + super.dictionary, + super.crossTable, + ) : super.load(); } /// Represents the annotation with associated action. @@ -171,8 +182,10 @@ class PdfActionAnnotation extends PdfActionLinkAnnotation { class PdfActionAnnotationHelper extends PdfActionLinkAnnotationHelper { /// internal method PdfActionAnnotationHelper( - this.actionAnnotation, Rect bounds, PdfAction action) - : super(actionAnnotation, bounds, action); + this.actionAnnotation, + Rect bounds, + PdfAction action, + ) : super(actionAnnotation, bounds, action); /// internal method PdfActionAnnotation actionAnnotation; @@ -184,8 +197,10 @@ class PdfActionAnnotationHelper extends PdfActionLinkAnnotationHelper { /// internal method void save() { - dictionary!.setProperty(PdfName(PdfDictionaryProperties.a), - IPdfWrapper.getElement(actionAnnotation.action!)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.a), + IPdfWrapper.getElement(actionAnnotation.action!), + ); } /// internal method diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation.dart index 4a1a6b8e0..05a0f77df 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation.dart @@ -157,47 +157,52 @@ class PdfAnnotationHelper { /// internal method /// Initialize [PdfAnnotation] object - void initializeAnnotation( - {PdfPage? page, - String? text, - Rect? bounds, - PdfAnnotationBorder? border, - PdfColor? color, - PdfColor? innerColor, - String? author, - double? opacity, - String? subject, - DateTime? modifiedDate, - List? flags, - bool? setAppearance}) { + void initializeAnnotation({ + PdfPage? page, + String? text, + Rect? bounds, + PdfAnnotationBorder? border, + PdfColor? color, + PdfColor? innerColor, + String? author, + double? opacity, + String? subject, + DateTime? modifiedDate, + List? flags, + bool? setAppearance, + }) { base._helper = this; initializeAnnotationProperties( - page, - text, - bounds, - border, - color, - innerColor, - author, - opacity, - subject, - modifiedDate, - flags, - setAppearance); + page, + text, + bounds, + border, + color, + innerColor, + author, + opacity, + subject, + modifiedDate, + flags, + setAppearance, + ); } /// internal method /// Initialize [PdfAnnotation] object void initializeExistingAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { base._helper = this; this.dictionary = dictionary; this.crossTable = crossTable; isLoadedAnnotation = true; PdfName? name; if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { - name = dictionary.items![PdfName(PdfDictionaryProperties.subtype)] - as PdfName?; + name = + dictionary.items![PdfName(PdfDictionaryProperties.subtype)] + as PdfName?; } if (name != null) { if (name.name == PdfDictionaryProperties.circle || @@ -304,11 +309,12 @@ class PdfAnnotationHelper { return rectangle.rect; } else { final PdfRectangle rect = _getBounds(dictionary!, crossTable); - rect.y = page != null - ? rect.y == 0 && rect.height == 0 - ? rect.y + rect.height - : page!.size.height - (rect.y + rect.height) - : rect.y - rect.height; + rect.y = + page != null + ? rect.y == 0 && rect.height == 0 + ? rect.y + rect.height + : page!.size.height - (rect.y + rect.height) + : rect.y - rect.height; return rect.rect; } } @@ -319,8 +325,10 @@ class PdfAnnotationHelper { final PdfRectangle rect = PdfRectangle.fromRect(value); if (rectangle != rect) { rectangle = rect; - dictionary!.setProperty(PdfName(PdfDictionaryProperties.rect), - PdfArray.fromRectangle(rect)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.rect), + PdfArray.fromRectangle(rect), + ); } } else { isBounds = true; @@ -332,7 +340,7 @@ class PdfAnnotationHelper { PdfNumber(value.left), PdfNumber(height - (value.top + value.height)), PdfNumber(value.left + value.width), - PdfNumber(height - value.top) + PdfNumber(height - value.top), ]; final PdfDictionary dic = dictionary!; dic.setArray(PdfDictionaryProperties.rect, values); @@ -346,8 +354,10 @@ class PdfAnnotationHelper { } else { annotationBorder ??= _obtainBorder(); if (!isLineBorder()) { - dictionary! - .setProperty(PdfDictionaryProperties.border, annotationBorder); + dictionary!.setProperty( + PdfDictionaryProperties.border, + annotationBorder, + ); } } PdfAnnotationBorderHelper.getHelper(annotationBorder!).isLineBorder = @@ -362,7 +372,9 @@ class PdfAnnotationHelper { dictionary!.setProperty(PdfName(PdfDictionaryProperties.bs), border); } else { dictionary!.setProperty( - PdfName(PdfDictionaryProperties.border), annotationBorder); + PdfName(PdfDictionaryProperties.border), + annotationBorder, + ); } } @@ -400,11 +412,12 @@ class PdfAnnotationHelper { annotationColor = value; PdfColorSpace? cs = PdfColorSpace.rgb; if (page != null && !PdfPageHelper.getHelper(page!).isLoadedPage) { - cs = PdfSectionCollectionHelper.getHelper(PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(page!).section!) - .parent!) - .document! - .colorSpace; + cs = + PdfSectionCollectionHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page!).section!, + ).parent!, + ).document!.colorSpace; } final PdfArray colours = PdfColorHelper.toArray(annotationColor, cs); dictionary!.setProperty(PdfDictionaryProperties.c, colours); @@ -426,8 +439,10 @@ class PdfAnnotationHelper { annotationInnerColor = value; if (isLoadedAnnotation) { if (PdfColorHelper.getHelper(annotationInnerColor!).alpha != 0) { - dictionary!.setProperty(PdfDictionaryProperties.iC, - PdfColorHelper.toArray(annotationInnerColor!)); + dictionary!.setProperty( + PdfDictionaryProperties.iC, + PdfColorHelper.toArray(annotationInnerColor!), + ); } else if (dictionary!.containsKey(PdfDictionaryProperties.iC)) { dictionary!.remove(PdfDictionaryProperties.iC); } @@ -490,8 +505,10 @@ class PdfAnnotationHelper { set modifiedDate(DateTime? value) { if (annotationModifiedDate != value) { annotationModifiedDate = value; - dictionary! - .setDateTime(PdfDictionaryProperties.m, annotationModifiedDate!); + dictionary!.setDateTime( + PdfDictionaryProperties.m, + annotationModifiedDate!, + ); } } @@ -517,7 +534,9 @@ class PdfAnnotationHelper { if (annotationOpacity != value) { annotationOpacity = value; dictionary!.setProperty( - PdfDictionaryProperties.ca, PdfNumber(annotationOpacity)); + PdfDictionaryProperties.ca, + PdfNumber(annotationOpacity), + ); } } @@ -548,21 +567,24 @@ class PdfAnnotationHelper { /// internal method void initializeAnnotationProperties( - PdfPage? page, - String? annotText, - Rect? bounds, - PdfAnnotationBorder? border, - PdfColor? color, - PdfColor? innerColor, - String? author, - double? opacity, - String? subject, - DateTime? modifiedDate, - List? flags, - bool? setAppearance) { + PdfPage? page, + String? annotText, + Rect? bounds, + PdfAnnotationBorder? border, + PdfColor? color, + PdfColor? innerColor, + String? author, + double? opacity, + String? subject, + DateTime? modifiedDate, + List? flags, + bool? setAppearance, + ) { dictionary!.beginSave = dictionaryBeginSave; - dictionary!.setProperty(PdfName(PdfDictionaryProperties.type), - PdfName(PdfDictionaryProperties.annot)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.type), + PdfName(PdfDictionaryProperties.annot), + ); if (page != null) { this.page = page; } @@ -572,7 +594,9 @@ class PdfAnnotationHelper { if (annotText != null) { text = annotText; dictionary!.setProperty( - PdfName(PdfDictionaryProperties.contents), PdfString(text)); + PdfName(PdfDictionaryProperties.contents), + PdfString(text), + ); } if (border != null) { this.border = border; @@ -617,11 +641,16 @@ class PdfAnnotationHelper { bool contains = false; PdfArray? annotation; if (page != null && - PdfPageHelper.getHelper(page!) - .dictionary! - .containsKey(PdfDictionaryProperties.annots)) { - annotation = PdfCrossTable.dereference(PdfPageHelper.getHelper(page!) - .dictionary![PdfDictionaryProperties.annots]) as PdfArray?; + PdfPageHelper.getHelper( + page!, + ).dictionary!.containsKey(PdfDictionaryProperties.annots)) { + annotation = + PdfCrossTable.dereference( + PdfPageHelper.getHelper( + page!, + ).dictionary![PdfDictionaryProperties.annots], + ) + as PdfArray?; if (annotation != null && annotation.elements.isNotEmpty && annotation.contains(annotation.elements[0]!)) { @@ -641,7 +670,8 @@ class PdfAnnotationHelper { PdfDocumentHelper.getHelper(document).conformanceLevel == PdfConformanceLevel.a1b) { throw ArgumentError( - 'The specified annotation type is not supported by PDF/A1-B or PDF/A1-A standard documents.'); + 'The specified annotation type is not supported by PDF/A1-B or PDF/A1-A standard documents.', + ); } //This is needed to attain specific PDF/A conformance. if (base is! PdfLinkAnnotation && @@ -651,7 +681,8 @@ class PdfAnnotationHelper { PdfDocumentHelper.getHelper(document).conformanceLevel == PdfConformanceLevel.a3b)) { throw ArgumentError( - "The appearance dictionary doesn't contain an entry. Enable setAppearance in PdfAnnotation class to overcome this error."); + "The appearance dictionary doesn't contain an entry. Enable setAppearance in PdfAnnotation class to overcome this error.", + ); } dictionary!.setNumber(PdfDictionaryProperties.f, 4); } @@ -659,8 +690,10 @@ class PdfAnnotationHelper { if (isLineBorder()) { dictionary!.setProperty(PdfDictionaryProperties.bs, border); } else { - dictionary! - .setProperty(PdfName(PdfDictionaryProperties.border), border); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.border), + border, + ); } } if ((base is! PdfLinkAnnotation && base is! PdfTextWebLink) || @@ -670,24 +703,33 @@ class PdfAnnotationHelper { if (annotationInnerColor != null && !annotationInnerColor!.isEmpty && PdfColorHelper.getHelper(annotationInnerColor!).alpha != 0.0) { - dictionary!.setProperty(PdfName(PdfDictionaryProperties.ic), - PdfColorHelper.toArray(annotationInnerColor!)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.ic), + PdfColorHelper.toArray(annotationInnerColor!), + ); } - dictionary!.setProperty(PdfName(PdfDictionaryProperties.rect), - PdfArray.fromRectangle(nativeRectangle)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.rect), + PdfArray.fromRectangle(nativeRectangle), + ); } } PdfRectangle _obtainNativeRectangle() { - final PdfRectangle nativeRectangle = - PdfRectangle(bounds.left, bounds.bottom, bounds.width, bounds.height); + final PdfRectangle nativeRectangle = PdfRectangle( + bounds.left, + bounds.bottom, + bounds.width, + bounds.height, + ); Size? size; PdfArray? cropOrMediaBox; if (page != null) { if (!PdfPageHelper.getHelper(page!).isLoadedPage) { final PdfSection section = PdfPageHelper.getHelper(page!).section!; - nativeRectangle.location = PdfSectionHelper.getHelper(section) - .pointToNativePdf(page!, nativeRectangle.location); + nativeRectangle.location = PdfSectionHelper.getHelper( + section, + ).pointToNativePdf(page!, nativeRectangle.location); } else { size = page!.size; nativeRectangle.y = size.height - rectangle.bottom; @@ -698,9 +740,11 @@ class PdfAnnotationHelper { if (cropOrMediaBox.count > 2) { if ((cropOrMediaBox[0]! as PdfNumber).value != 0 || (cropOrMediaBox[1]! as PdfNumber).value != 0) { - nativeRectangle.x = nativeRectangle.x + + nativeRectangle.x = + nativeRectangle.x + (cropOrMediaBox[0]! as PdfNumber).value!.toDouble(); - nativeRectangle.y = nativeRectangle.y + + nativeRectangle.y = + nativeRectangle.y + (cropOrMediaBox[1]! as PdfNumber).value!.toDouble(); } } @@ -715,8 +759,11 @@ class PdfAnnotationHelper { PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.cropBox]) as PdfArray?; } else if (dictionary.containsKey(PdfDictionaryProperties.mediaBox)) { - cropOrMediaBox = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.mediaBox]) as PdfArray?; + cropOrMediaBox = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.mediaBox], + ) + as PdfArray?; } return cropOrMediaBox; } @@ -734,8 +781,9 @@ class PdfAnnotationHelper { pdfPage.graphics; //Accessed for creating page content. ArgumentError.checkNotNull(graphics); if (dictionary!.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName? name = dictionary! - .items![PdfName(PdfDictionaryProperties.subtype)] as PdfName?; + final PdfName? name = + dictionary!.items![PdfName(PdfDictionaryProperties.subtype)] + as PdfName?; if (name != null) { if (name.name == PdfDictionaryProperties.text || name.name == PdfDictionaryProperties.square || @@ -758,8 +806,9 @@ class PdfAnnotationHelper { final PdfCatalog catalog = PdfDocumentHelper.getHelper(document).catalog; if (dictionary!.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName? name = dictionary! - .items![PdfName(PdfDictionaryProperties.subtype)] as PdfName?; + final PdfName? name = + dictionary!.items![PdfName(PdfDictionaryProperties.subtype)] + as PdfName?; catalog.beginSaveList ??= []; if (name != null) { if (name.name == PdfDictionaryProperties.circle || @@ -784,7 +833,9 @@ class PdfAnnotationHelper { } if (page != null && !PdfPageHelper.getHelper(page!).isLoadedPage) { dictionary!.setProperty( - PdfName(PdfDictionaryProperties.p), PdfReferenceHolder(page)); + PdfName(PdfDictionaryProperties.p), + PdfReferenceHolder(page), + ); } } @@ -792,8 +843,9 @@ class PdfAnnotationHelper { PdfRectangle _getBounds(PdfDictionary dictionary, PdfCrossTable crossTable) { PdfArray? array; if (dictionary.containsKey(PdfDictionaryProperties.rect)) { - array = crossTable.getObject(dictionary[PdfDictionaryProperties.rect]) - as PdfArray?; + array = + crossTable.getObject(dictionary[PdfDictionaryProperties.rect]) + as PdfArray?; } return array!.toRectangle(); } @@ -820,8 +872,9 @@ class PdfAnnotationHelper { } } } else if (dictionary!.containsKey(PdfDictionaryProperties.bs)) { - final PdfDictionary lbDic = crossTable - .getObject(dictionary![PdfDictionaryProperties.bs])! as PdfDictionary; + final PdfDictionary lbDic = + crossTable.getObject(dictionary![PdfDictionaryProperties.bs])! + as PdfDictionary; if (lbDic.containsKey(PdfDictionaryProperties.w)) { final PdfNumber? value = lbDic[PdfDictionaryProperties.w] as PdfNumber?; if (value != null) { @@ -855,8 +908,11 @@ class PdfAnnotationHelper { String? _obtainText() { String tempText; if (dictionary!.containsKey(PdfDictionaryProperties.contents)) { - final PdfString? mText = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.contents]) as PdfString?; + final PdfString? mText = + PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.contents], + ) + as PdfString?; if (mText != null) { textValue = mText.value.toString(); } @@ -932,15 +988,17 @@ class PdfAnnotationHelper { String author = ''; if (dictionary!.containsKey(PdfDictionaryProperties.author)) { final IPdfPrimitive? tempAuthor = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.author]); + dictionary![PdfDictionaryProperties.author], + ); if (tempAuthor != null && tempAuthor is PdfString && tempAuthor.value != null) { author = tempAuthor.value!; } } else if (dictionary!.containsKey(PdfDictionaryProperties.t)) { - final IPdfPrimitive? tempAuthor = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.t]); + final IPdfPrimitive? tempAuthor = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.t], + ); if (tempAuthor != null && tempAuthor is PdfString && tempAuthor.value != null) { @@ -955,15 +1013,17 @@ class PdfAnnotationHelper { String subject = ''; if (dictionary!.containsKey(PdfDictionaryProperties.subject)) { final IPdfPrimitive? tempSubject = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.subject]); + dictionary![PdfDictionaryProperties.subject], + ); if (tempSubject != null && tempSubject is PdfString && tempSubject.value != null) { subject = tempSubject.value!; } } else if (dictionary!.containsKey(PdfDictionaryProperties.subj)) { - final IPdfPrimitive? tempSubject = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.subj]); + final IPdfPrimitive? tempSubject = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.subj], + ); if (tempSubject != null && tempSubject is PdfString && tempSubject.value != null) { @@ -1001,12 +1061,15 @@ class PdfAnnotationHelper { PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.iC]) as PdfArray?; if (colours != null && colours.count > 0) { - final int red = - ((colours[0]! as PdfNumber).value! * 255).round().toUnsigned(8); - final int green = - ((colours[1]! as PdfNumber).value! * 255).round().toUnsigned(8); - final int blue = - ((colours[2]! as PdfNumber).value! * 255).round().toUnsigned(8); + final int red = ((colours[0]! as PdfNumber).value! * 255) + .round() + .toUnsigned(8); + final int green = ((colours[1]! as PdfNumber).value! * 255) + .round() + .toUnsigned(8); + final int blue = ((colours[2]! as PdfNumber).value! * 255) + .round() + .toUnsigned(8); color = PdfColor(red, green, blue); } } @@ -1025,19 +1088,35 @@ class PdfAnnotationHelper { void flattenPopup() { if (page != null && !isLoadedAnnotation) { _flattenAnnotationPopups( - page!, color, bounds, border, author, subject, text); - } - } - - void _flattenAnnotationPopups(PdfPage page, PdfColor color, Rect annotBounds, - PdfAnnotationBorder border, String author, String subject, String text) { - final Size clientSize = PdfPageHelper.getHelper(page).isLoadedPage - ? page.size - : page.getClientSize(); + page!, + color, + bounds, + border, + author, + subject, + text, + ); + } + } + + void _flattenAnnotationPopups( + PdfPage page, + PdfColor color, + Rect annotBounds, + PdfAnnotationBorder border, + String author, + String subject, + String text, + ) { + final Size clientSize = + PdfPageHelper.getHelper(page).isLoadedPage + ? page.size + : page.getClientSize(); final double x = clientSize.width - 180; - final double y = (annotBounds.top + 142) < clientSize.height - ? annotBounds.top - : clientSize.height - 142; + final double y = + (annotBounds.top + 142) < clientSize.height + ? annotBounds.top + : clientSize.height - 142; Rect bounds = Rect.fromLTWH(x, y, 180, 142); // Draw annotation based on bounds if (dictionary![PdfDictionaryProperties.popup] != null) { @@ -1045,8 +1124,11 @@ class PdfAnnotationHelper { final PdfDictionary? tempDictionary = PdfCrossTable.dereference(obj) as PdfDictionary?; if (tempDictionary != null) { - final PdfArray? rectValue = PdfCrossTable.dereference( - tempDictionary[PdfDictionaryProperties.rect]) as PdfArray?; + final PdfArray? rectValue = + PdfCrossTable.dereference( + tempDictionary[PdfDictionaryProperties.rect], + ) + as PdfArray?; final PdfCrossTable? crosstable = PdfPageHelper.getHelper(page).crossTable; if (rectValue != null) { @@ -1059,10 +1141,11 @@ class PdfAnnotationHelper { final PdfNumber height = crosstable.getReference(rectValue[3]) as PdfNumber; bounds = Rect.fromLTWH( - left.value! as double, - top.value! as double, - width.value! - (left.value! as double), - height.value! - (top.value! as double)); + left.value! as double, + top.value! as double, + width.value! - (left.value! as double), + height.value! - (top.value! as double), + ); } } } @@ -1071,68 +1154,107 @@ class PdfAnnotationHelper { double? trackingHeight = 0; final PdfBrush aBrush = PdfSolidBrush(_getForeColor(color)); if (author != '') { - final Map returnedValue = _drawAuthor(author, subject, - bounds, backBrush, aBrush, page, trackingHeight, border); + final Map returnedValue = _drawAuthor( + author, + subject, + bounds, + backBrush, + aBrush, + page, + trackingHeight, + border, + ); trackingHeight = returnedValue['height']; } else if (subject != '') { - final Rect titleRect = Rect.fromLTWH(bounds.left + borderWidth, - bounds.top + borderWidth, bounds.width - border.width, 40); + final Rect titleRect = Rect.fromLTWH( + bounds.left + borderWidth, + bounds.top + borderWidth, + bounds.width - border.width, + 40, + ); _saveGraphics(page, PdfBlendMode.hardLight); page.graphics.drawRectangle( - pen: PdfPens.black, brush: backBrush, bounds: titleRect); + pen: PdfPens.black, + brush: backBrush, + bounds: titleRect, + ); page.graphics.restore(); - Rect contentRect = Rect.fromLTWH(titleRect.left + 11, titleRect.top, - titleRect.width, titleRect.height / 2); + Rect contentRect = Rect.fromLTWH( + titleRect.left + 11, + titleRect.top, + titleRect.width, + titleRect.height / 2, + ); contentRect = Rect.fromLTWH( - contentRect.left, - contentRect.top + contentRect.height - 2, - contentRect.width, - titleRect.height / 2); + contentRect.left, + contentRect.top + contentRect.height - 2, + contentRect.width, + titleRect.height / 2, + ); _saveGraphics(page, PdfBlendMode.normal); _drawSubject(subject, contentRect, page); page.graphics.restore(); trackingHeight = 40; } else { _saveGraphics(page, PdfBlendMode.hardLight); - final Rect titleRect = Rect.fromLTWH(bounds.left + borderWidth, - bounds.top + borderWidth, bounds.width - border.width, 20); + final Rect titleRect = Rect.fromLTWH( + bounds.left + borderWidth, + bounds.top + borderWidth, + bounds.width - border.width, + 20, + ); page.graphics.drawRectangle( - pen: PdfPens.black, brush: backBrush, bounds: titleRect); + pen: PdfPens.black, + brush: backBrush, + bounds: titleRect, + ); trackingHeight = 20; page.graphics.restore(); } Rect cRect = Rect.fromLTWH( - bounds.left + borderWidth, - bounds.top + borderWidth + trackingHeight!, - bounds.width - border.width, - bounds.height - (trackingHeight + border.width)); + bounds.left + borderWidth, + bounds.top + borderWidth + trackingHeight!, + bounds.width - border.width, + bounds.height - (trackingHeight + border.width), + ); _saveGraphics(page, PdfBlendMode.hardLight); page.graphics.drawRectangle( - pen: PdfPens.black, brush: PdfBrushes.white, bounds: cRect); + pen: PdfPens.black, + brush: PdfBrushes.white, + bounds: cRect, + ); cRect = Rect.fromLTWH( - cRect.left + 11, cRect.top + 5, cRect.width - 22, cRect.height); + cRect.left + 11, + cRect.top + 5, + cRect.width - 22, + cRect.height, + ); page.graphics.restore(); _saveGraphics(page, PdfBlendMode.normal); page.graphics.drawString( - text, PdfStandardFont(PdfFontFamily.helvetica, 10.5), - brush: PdfBrushes.black, bounds: cRect); + text, + PdfStandardFont(PdfFontFamily.helvetica, 10.5), + brush: PdfBrushes.black, + bounds: cRect, + ); page.graphics.restore(); } void _drawSubject(String subject, Rect bounds, PdfPage page) { page.graphics.drawString( - subject, - PdfStandardFont(PdfFontFamily.helvetica, 10.5, - style: PdfFontStyle.bold), - brush: PdfBrushes.black, - bounds: bounds, - format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle)); + subject, + PdfStandardFont(PdfFontFamily.helvetica, 10.5, style: PdfFontStyle.bold), + brush: PdfBrushes.black, + bounds: bounds, + format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle), + ); } void _saveGraphics(PdfPage page, PdfBlendMode mode) { page.graphics.save(); - PdfGraphicsHelper.getHelper(page.graphics) - .applyTransparency(0.8, 8.0, mode); + PdfGraphicsHelper.getHelper( + page.graphics, + ).applyTransparency(0.8, 8.0, mode); } PdfColor _getForeColor(PdfColor c) { @@ -1142,57 +1264,82 @@ class PdfAnnotationHelper { } Map _drawAuthor( - String author, - String subject, - Rect bounds, - PdfBrush backBrush, - PdfBrush aBrush, - PdfPage page, - double? trackingHeight, - PdfAnnotationBorder border) { + String author, + String subject, + Rect bounds, + PdfBrush backBrush, + PdfBrush aBrush, + PdfPage page, + double? trackingHeight, + PdfAnnotationBorder border, + ) { final double borderWidth = border.width / 2; - final PdfRectangle titleRect = PdfRectangle.fromRect(Rect.fromLTWH( + final PdfRectangle titleRect = PdfRectangle.fromRect( + Rect.fromLTWH( bounds.left + borderWidth, bounds.top + borderWidth, bounds.width - border.width, - 20)); + 20, + ), + ); if (subject != '') { titleRect.height += 20; trackingHeight = titleRect.height; _saveGraphics(page, PdfBlendMode.hardLight); page.graphics.drawRectangle( - pen: PdfPens.black, brush: backBrush, bounds: titleRect.rect); + pen: PdfPens.black, + brush: backBrush, + bounds: titleRect.rect, + ); page.graphics.restore(); Rect contentRect = Rect.fromLTWH( - titleRect.x + 11, titleRect.y, titleRect.width, titleRect.height / 2); + titleRect.x + 11, + titleRect.y, + titleRect.width, + titleRect.height / 2, + ); _saveGraphics(page, PdfBlendMode.normal); page.graphics.drawString( - author, - PdfStandardFont(PdfFontFamily.helvetica, 10.5, - style: PdfFontStyle.bold), - brush: aBrush, - bounds: contentRect, - format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle)); + author, + PdfStandardFont( + PdfFontFamily.helvetica, + 10.5, + style: PdfFontStyle.bold, + ), + brush: aBrush, + bounds: contentRect, + format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle), + ); contentRect = Rect.fromLTWH( - contentRect.left, - contentRect.top + contentRect.height - 2, - contentRect.width, - titleRect.height / 2); + contentRect.left, + contentRect.top + contentRect.height - 2, + contentRect.width, + titleRect.height / 2, + ); _drawSubject(subject, contentRect, page); page.graphics.restore(); } else { _saveGraphics(page, PdfBlendMode.hardLight); page.graphics.drawRectangle( - pen: PdfPens.black, brush: backBrush, bounds: titleRect.rect); + pen: PdfPens.black, + brush: backBrush, + bounds: titleRect.rect, + ); page.graphics.restore(); final Rect contentRect = Rect.fromLTWH( - titleRect.x + 11, titleRect.y, titleRect.width, titleRect.height); + titleRect.x + 11, + titleRect.y, + titleRect.width, + titleRect.height, + ); _saveGraphics(page, PdfBlendMode.normal); page.graphics.drawString( - author, PdfStandardFont(PdfFontFamily.helvetica, 10.5), - brush: aBrush, - bounds: contentRect, - format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle)); + author, + PdfStandardFont(PdfFontFamily.helvetica, 10.5), + brush: aBrush, + bounds: contentRect, + format: PdfStringFormat(lineAlignment: PdfVerticalAlignment.middle), + ); trackingHeight = titleRect.height; page.graphics.restore(); } @@ -1201,14 +1348,19 @@ class PdfAnnotationHelper { /// internal method Rect calculateTemplateBounds( - Rect bounds, PdfPage? page, PdfTemplate? template, bool isNormalMatrix) { + Rect bounds, + PdfPage? page, + PdfTemplate? template, + bool isNormalMatrix, + ) { double x = bounds.left, y = bounds.top, width = bounds.width, height = bounds.height; if (page != null) { final int graphicsRotation = _obtainGraphicsRotation( - PdfGraphicsHelper.getHelper(page.graphics).matrix); + PdfGraphicsHelper.getHelper(page.graphics).matrix, + ); if (graphicsRotation == 0 && !isNormalMatrix) { x = bounds.left; y = bounds.top + bounds.height - bounds.width; @@ -1221,8 +1373,10 @@ class PdfAnnotationHelper { int _obtainGraphicsRotation(PdfTransformationMatrix matrix) { int angle = 0; - final double radians = - atan2(matrix.matrix.elements[2], matrix.matrix.elements[0]); + final double radians = atan2( + matrix.matrix.elements[2], + matrix.matrix.elements[0], + ); angle = (radians * 180 / pi).round(); switch (angle) { case -90: @@ -1248,7 +1402,7 @@ class PdfAnnotationHelper { 0, 1, -(bbox[0]! as PdfNumber).value! as double, - -(bbox[1]! as PdfNumber).value! as double + -(bbox[1]! as PdfNumber).value! as double, ]; template[PdfDictionaryProperties.matrix] = PdfArray(elements); } @@ -1278,12 +1432,13 @@ class PdfAnnotationHelper { /// internal method PdfRectangle calculateLineBounds( - List linePoints, - int leaderLineExt, - int leaderLineValue, - int leaderOffset, - PdfArray lineStyle, - double borderLength) { + List linePoints, + int leaderLineExt, + int leaderLineValue, + int leaderOffset, + PdfArray lineStyle, + double borderLength, + ) { PdfRectangle tempBounds = PdfRectangle.fromRect(bounds); final PdfPath path = PdfPath(); if (linePoints.length == 4) { @@ -1313,10 +1468,16 @@ class PdfAnnotationHelper { final List x1y1 = [x1, y1]; final List x2y2 = [x2, y2]; if (leaderOffset != 0) { - final List offsetPoint1 = - getAxisValue(x1y1, lineAngle + 90, leaderOffset.toDouble()); - final List offsetPoint2 = - getAxisValue(x2y2, lineAngle + 90, leaderOffset.toDouble()); + final List offsetPoint1 = getAxisValue( + x1y1, + lineAngle + 90, + leaderOffset.toDouble(), + ); + final List offsetPoint2 = getAxisValue( + x2y2, + lineAngle + 90, + leaderOffset.toDouble(), + ); linePoints[0] = offsetPoint1[0].toInt(); linePoints[1] = offsetPoint1[1].toInt(); linePoints[2] = offsetPoint2[0].toInt(); @@ -1324,15 +1485,27 @@ class PdfAnnotationHelper { } final List startingPoint = getAxisValue( - x1y1, lineAngle + 90, (leaderLine + leaderOffset).toDouble()); + x1y1, + lineAngle + 90, + (leaderLine + leaderOffset).toDouble(), + ); final List endingPoint = getAxisValue( - x2y2, lineAngle + 90, (leaderLine + leaderOffset).toDouble()); - - final List beginLineLeader = getAxisValue(x1y1, lineAngle + 90, - (leaderLineExt + leaderLine + leaderOffset).toDouble()); - - final List endLineLeader = getAxisValue(x2y2, lineAngle + 90, - (leaderLineExt + leaderLine + leaderOffset).toDouble()); + x2y2, + lineAngle + 90, + (leaderLine + leaderOffset).toDouble(), + ); + + final List beginLineLeader = getAxisValue( + x1y1, + lineAngle + 90, + (leaderLineExt + leaderLine + leaderOffset).toDouble(), + ); + + final List endLineLeader = getAxisValue( + x2y2, + lineAngle + 90, + (leaderLineExt + leaderLine + leaderOffset).toDouble(), + ); final List stylePoint = []; @@ -1404,8 +1577,10 @@ class PdfAnnotationHelper { [startingPoint[0], endingPoint[0]].reduce(min)) { startingPoint[0] -= widthX[0] * borderLength; endingPoint[0] += widthX[1] * borderLength; - startingPoint[0] = - [startingPoint[0], linePoints[0].toDouble()].reduce(min); + startingPoint[0] = [ + startingPoint[0], + linePoints[0].toDouble(), + ].reduce(min); startingPoint[0] = min(startingPoint[0], beginLineLeader[0]); endingPoint[0] = max(endingPoint[0], linePoints[2].toDouble()); endingPoint[0] = max(endingPoint[0], endLineLeader[0]); @@ -1432,8 +1607,10 @@ class PdfAnnotationHelper { endingPoint[1] = min(endingPoint[1], linePoints[3].toDouble()); endingPoint[1] = min(endingPoint[1], endLineLeader[1]); } - path.addLine(Offset(startingPoint[0], startingPoint[1]), - Offset(endingPoint[0], endingPoint[1])); + path.addLine( + Offset(startingPoint[0], startingPoint[1]), + Offset(endingPoint[0], endingPoint[1]), + ); tempBounds = PdfPathHelper.getHelper(path).getBoundsInternal(); } return tempBounds; @@ -1471,14 +1648,15 @@ class PdfAnnotationHelper { /// internal method void setLineEndingStyles( - List startingPoint, - List endingPoint, - PdfGraphics? graphics, - double angle, - PdfPen? borderPen, - PdfBrush? backBrush, - PdfArray lineStyle, - double borderLength) { + List startingPoint, + List endingPoint, + PdfGraphics? graphics, + double angle, + PdfPen? borderPen, + PdfBrush? backBrush, + PdfArray lineStyle, + double borderLength, + ) { List axisPoint; if (borderLength == 0) { borderLength = 1; @@ -1500,21 +1678,26 @@ class PdfAnnotationHelper { case 'Square': { final Rect rect = Rect.fromLTWH( - axisPoint[0] - (3 * borderLength), - -(axisPoint[1] + (3 * borderLength)), - 6 * borderLength, - 6 * borderLength); - graphics! - .drawRectangle(bounds: rect, pen: borderPen, brush: backBrush); + axisPoint[0] - (3 * borderLength), + -(axisPoint[1] + (3 * borderLength)), + 6 * borderLength, + 6 * borderLength, + ); + graphics!.drawRectangle( + bounds: rect, + pen: borderPen, + brush: backBrush, + ); } break; case 'Circle': { final Rect rect = Rect.fromLTWH( - axisPoint[0] - (3 * borderLength), - -(axisPoint[1] + (3 * borderLength)), - 6 * borderLength, - 6 * borderLength); + axisPoint[0] - (3 * borderLength), + -(axisPoint[1] + (3 * borderLength)), + 6 * borderLength, + 6 * borderLength, + ); graphics!.drawEllipse(rect, pen: borderPen, brush: backBrush); } break; @@ -1533,16 +1716,26 @@ class PdfAnnotationHelper { } else { startPoint = getAxisValue(axisPoint, angle, -borderLength); } - final List point1 = - getAxisValue(startPoint, angle + arraowAngle, length); - final List point2 = - getAxisValue(startPoint, angle - arraowAngle, length); + final List point1 = getAxisValue( + startPoint, + angle + arraowAngle, + length, + ); + final List point2 = getAxisValue( + startPoint, + angle - arraowAngle, + length, + ); final PdfPath path = PdfPath(pen: borderPen); - path.addLine(Offset(startPoint[0], -startPoint[1]), - Offset(point1[0], -point1[1])); - path.addLine(Offset(startPoint[0], -startPoint[1]), - Offset(point2[0], -point2[1])); + path.addLine( + Offset(startPoint[0], -startPoint[1]), + Offset(point1[0], -point1[1]), + ); + path.addLine( + Offset(startPoint[0], -startPoint[1]), + Offset(point2[0], -point2[1]), + ); graphics!.drawPath(path, pen: borderPen); } break; @@ -1561,14 +1754,20 @@ class PdfAnnotationHelper { } else { startPoint = getAxisValue(axisPoint, angle, -borderLength); } - final List point1 = - getAxisValue(startPoint, angle + arraowAngle, length); - final List point2 = - getAxisValue(startPoint, angle - arraowAngle, length); + final List point1 = getAxisValue( + startPoint, + angle + arraowAngle, + length, + ); + final List point2 = getAxisValue( + startPoint, + angle - arraowAngle, + length, + ); final List points = [ Offset(startPoint[0], -startPoint[1]), Offset(point1[0], -point1[1]), - Offset(point2[0], -point2[1]) + Offset(point2[0], -point2[1]), ]; graphics!.drawPolygon(points, pen: borderPen, brush: backBrush); } @@ -1588,16 +1787,26 @@ class PdfAnnotationHelper { } else { startPoint = getAxisValue(axisPoint, angle, borderLength); } - final List point1 = - getAxisValue(startPoint, angle + arraowAngle, length); - final List point2 = - getAxisValue(startPoint, angle - arraowAngle, length); + final List point1 = getAxisValue( + startPoint, + angle + arraowAngle, + length, + ); + final List point2 = getAxisValue( + startPoint, + angle - arraowAngle, + length, + ); final PdfPath path = PdfPath(pen: borderPen); - path.addLine(Offset(startPoint[0], -startPoint[1]), - Offset(point1[0], -point1[1])); - path.addLine(Offset(startPoint[0], -startPoint[1]), - Offset(point2[0], -point2[1])); + path.addLine( + Offset(startPoint[0], -startPoint[1]), + Offset(point1[0], -point1[1]), + ); + path.addLine( + Offset(startPoint[0], -startPoint[1]), + Offset(point2[0], -point2[1]), + ); graphics!.drawPath(path, pen: borderPen); } break; @@ -1617,14 +1826,20 @@ class PdfAnnotationHelper { startPoint = getAxisValue(axisPoint, angle, borderLength); } - final List point1 = - getAxisValue(startPoint, angle + arraowAngle, length); - final List point2 = - getAxisValue(startPoint, angle - arraowAngle, length); + final List point1 = getAxisValue( + startPoint, + angle + arraowAngle, + length, + ); + final List point2 = getAxisValue( + startPoint, + angle - arraowAngle, + length, + ); final List points = [ Offset(startPoint[0], -startPoint[1]), Offset(point1[0], -point1[1]), - Offset(point2[0], -point2[1]) + Offset(point2[0], -point2[1]), ]; graphics!.drawPolygon(points, pen: borderPen, brush: backBrush); } @@ -1632,14 +1847,26 @@ class PdfAnnotationHelper { case 'Slash': { final double length = 9 * borderLength; - final List point1 = - getAxisValue(axisPoint, angle + 60, length); - final List point2 = - getAxisValue(axisPoint, angle - 120, length); - graphics!.drawLine(borderPen!, Offset(axisPoint[0], -axisPoint[1]), - Offset(point1[0], -point1[1])); - graphics.drawLine(borderPen, Offset(axisPoint[0], -axisPoint[1]), - Offset(point2[0], -point2[1])); + final List point1 = getAxisValue( + axisPoint, + angle + 60, + length, + ); + final List point2 = getAxisValue( + axisPoint, + angle - 120, + length, + ); + graphics!.drawLine( + borderPen!, + Offset(axisPoint[0], -axisPoint[1]), + Offset(point1[0], -point1[1]), + ); + graphics.drawLine( + borderPen, + Offset(axisPoint[0], -axisPoint[1]), + Offset(point2[0], -point2[1]), + ); } break; case 'Diamond': @@ -1653,7 +1880,7 @@ class PdfAnnotationHelper { Offset(point1[0], -point1[1]), Offset(point2[0], -point2[1]), Offset(point3[0], -point3[1]), - Offset(point4[0], -point4[1]) + Offset(point4[0], -point4[1]), ]; graphics!.drawPolygon(points, pen: borderPen, brush: backBrush); } @@ -1661,13 +1888,22 @@ class PdfAnnotationHelper { case 'Butt': { final double length = 3 * borderLength; - final List point1 = - getAxisValue(axisPoint, angle + 90, length); - final List point2 = - getAxisValue(axisPoint, angle - 90, length); - - graphics!.drawLine(borderPen!, Offset(point1[0], -point1[1]), - Offset(point2[0], -point2[1])); + final List point1 = getAxisValue( + axisPoint, + angle + 90, + length, + ); + final List point2 = getAxisValue( + axisPoint, + angle - 90, + length, + ); + + graphics!.drawLine( + borderPen!, + Offset(point1[0], -point1[1]), + Offset(point2[0], -point2[1]), + ); } break; } @@ -1697,14 +1933,19 @@ class PdfAnnotationHelper { /// Returns the boolean if the template matrix is valid or not bool isValidTemplateMatrix( - PdfDictionary dictionary, Offset bounds, PdfTemplate template) { + PdfDictionary dictionary, + Offset bounds, + PdfTemplate template, + ) { bool isValidMatrix = true; Offset point = bounds; if (dictionary.containsKey(PdfDictionaryProperties.matrix)) { - final IPdfPrimitive? bbox = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.bBox]); - final IPdfPrimitive? matrix = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.matrix]); + final IPdfPrimitive? bbox = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.bBox], + ); + final IPdfPrimitive? matrix = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.matrix], + ); if (matrix != null && bbox != null && matrix is PdfArray && @@ -1726,8 +1967,10 @@ class PdfAnnotationHelper { if (opacity < 1) { pageGraphics.setTransparency(opacity); } - point = Offset(point.dx - (bbox[0]! as PdfNumber).value!.toDouble(), - point.dy + (bbox[1]! as PdfNumber).value!.toDouble()); + point = Offset( + point.dx - (bbox[0]! as PdfNumber).value!.toDouble(), + point.dy + (bbox[1]! as PdfNumber).value!.toDouble(), + ); pageGraphics.drawPdfTemplate(template, point); pageGraphics.restore(state); page!.annotations.remove(base); @@ -1756,19 +1999,32 @@ class PdfAnnotationHelper { if (opacity < 1) { page!.graphics.setTransparency(opacity); } - final Rect bound = - calculateTemplateBounds(bounds, page, appearance, isNormalMatrix); + final Rect bound = calculateTemplateBounds( + bounds, + page, + appearance, + isNormalMatrix, + ); page!.graphics.drawPdfTemplate(appearance, bound.topLeft, bounds.size); page!.graphics.restore(state); page!.annotations.remove(base); } /// Draw CloudStye to the Shapes - void drawCloudStyle(PdfGraphics graphics, PdfBrush? brush, PdfPen? pen, - double radius, double overlap, List points, bool isAppearance) { + void drawCloudStyle( + PdfGraphics graphics, + PdfBrush? brush, + PdfPen? pen, + double radius, + double overlap, + List points, + bool isAppearance, + ) { if (_isClockWise(points)) { points = List.generate( - points.length, (int i) => points[points.length - (i + 1)]); + points.length, + (int i) => points[points.length - (i + 1)], + ); } // Create a list of circles @@ -1785,8 +2041,10 @@ class PdfAnnotationHelper { final double d = circleOverlap; for (double a = 0; a + 0.1 * d < len; a += d) { final _CloudStyleArc cur = _CloudStyleArc(); - cur.point = - Offset(previousPoint.dx + a * dx, previousPoint.dy + a * dy); + cur.point = Offset( + previousPoint.dx + a * dx, + previousPoint.dy + a * dy, + ); circles.add(cur); } previousPoint = currentPoint; @@ -1799,7 +2057,10 @@ class PdfAnnotationHelper { for (int i = 0; i < circles.length; i++) { final _CloudStyleArc currentCurvedStyleArc = circles[i]; final Offset angle = _getIntersectionDegrees( - previousCurvedStyleArc.point, currentCurvedStyleArc.point, radius); + previousCurvedStyleArc.point, + currentCurvedStyleArc.point, + radius, + ); previousCurvedStyleArc.endAngle = angle.dx; currentCurvedStyleArc.startAngle = angle.dy; previousCurvedStyleArc = currentCurvedStyleArc; @@ -1809,12 +2070,14 @@ class PdfAnnotationHelper { PdfPath path = PdfPath(); for (int i = 0; i < circles.length; i++) { final _CloudStyleArc curr = circles[i]; - final double angle = curr.startAngle < 0 - ? ((curr.startAngle * -1) % 360) * -1 - : curr.startAngle % 360; - final double angle1 = curr.endAngle < 0 - ? ((curr.endAngle * -1) % 360) * -1 - : curr.endAngle % 360; + final double angle = + curr.startAngle < 0 + ? ((curr.startAngle * -1) % 360) * -1 + : curr.startAngle % 360; + final double angle1 = + curr.endAngle < 0 + ? ((curr.endAngle * -1) % 360) * -1 + : curr.endAngle % 360; double sweepAngel = 0; if (angle > 0 && angle1 < 0) { sweepAngel = (180 - angle) + (180 - (angle1 < 0 ? -angle1 : angle1)); @@ -1842,27 +2105,35 @@ class PdfAnnotationHelper { } curr.endAngle = sweepAngel; path.addArc( - Rect.fromLTWH(curr.point.dx - radius, curr.point.dy - radius, - 2 * radius, 2 * radius), - angle, - sweepAngel); + Rect.fromLTWH( + curr.point.dx - radius, + curr.point.dy - radius, + 2 * radius, + 2 * radius, + ), + angle, + sweepAngel, + ); } path.closeFigure(); PdfPath pdfPath = PdfPath(); if (isAppearance) { for (int i = 0; i < PdfPathHelper.getHelper(path).points.length; i++) { - PdfPathHelper.getHelper(pdfPath).points.add(Offset( + PdfPathHelper.getHelper(pdfPath).points.add( + Offset( PdfPathHelper.getHelper(path).points[i].dx, - -PdfPathHelper.getHelper(path).points[i].dy)); + -PdfPathHelper.getHelper(path).points[i].dy, + ), + ); } } else { - PdfPathHelper.getHelper(pdfPath) - .points - .addAll(PdfPathHelper.getHelper(path).points); + PdfPathHelper.getHelper( + pdfPath, + ).points.addAll(PdfPathHelper.getHelper(path).points); } - PdfPathHelper.getHelper(pdfPath) - .pathTypes - .addAll(PdfPathHelper.getHelper(path).pathTypes); + PdfPathHelper.getHelper( + pdfPath, + ).pathTypes.addAll(PdfPathHelper.getHelper(path).pathTypes); if (brush != null) { graphics.drawPath(pdfPath, brush: brush); } @@ -1871,27 +2142,35 @@ class PdfAnnotationHelper { for (int i = 0; i < circles.length; i++) { final _CloudStyleArc curr = circles[i]; path.addArc( - Rect.fromLTWH(curr.point.dx - radius, curr.point.dy - radius, - 2 * radius, 2 * radius), - curr.startAngle, - curr.endAngle + incise); + Rect.fromLTWH( + curr.point.dx - radius, + curr.point.dy - radius, + 2 * radius, + 2 * radius, + ), + curr.startAngle, + curr.endAngle + incise, + ); } path.closeFigure(); pdfPath = PdfPath(); if (isAppearance) { for (int i = 0; i < PdfPathHelper.getHelper(path).points.length; i++) { - PdfPathHelper.getHelper(pdfPath).points.add(Offset( + PdfPathHelper.getHelper(pdfPath).points.add( + Offset( PdfPathHelper.getHelper(path).points[i].dx, - -PdfPathHelper.getHelper(path).points[i].dy)); + -PdfPathHelper.getHelper(path).points[i].dy, + ), + ); } } else { - PdfPathHelper.getHelper(pdfPath) - .points - .addAll(PdfPathHelper.getHelper(path).points); + PdfPathHelper.getHelper( + pdfPath, + ).points.addAll(PdfPathHelper.getHelper(path).points); } - PdfPathHelper.getHelper(pdfPath) - .pathTypes - .addAll(PdfPathHelper.getHelper(path).pathTypes); + PdfPathHelper.getHelper( + pdfPath, + ).pathTypes.addAll(PdfPathHelper.getHelper(path).pathTypes); graphics.drawPath(pdfPath, pen: pen); } @@ -1918,13 +2197,18 @@ class PdfAnnotationHelper { } final double radian = atan2(dy, dx); final double cosvalue = acos(a); - return Offset((radian - cosvalue) * (180 / pi), - (pi + radian + cosvalue) * (180 / pi)); + return Offset( + (radian - cosvalue) * (180 / pi), + (pi + radian + cosvalue) * (180 / pi), + ); } // Searches the in parents. static IPdfPrimitive? _searchInParents( - PdfDictionary dictionary, PdfCrossTable? crossTable, String value) { + PdfDictionary dictionary, + PdfCrossTable? crossTable, + String value, + ) { IPdfPrimitive? primitive; PdfDictionary? dic = dictionary; while ((primitive == null) && (dic != null)) { @@ -1932,8 +2216,9 @@ class PdfAnnotationHelper { primitive = crossTable!.getObject(dic[value]); } else { if (dic.containsKey(PdfDictionaryProperties.parent)) { - dic = crossTable!.getObject(dic[PdfDictionaryProperties.parent]) - as PdfDictionary?; + dic = + crossTable!.getObject(dic[PdfDictionaryProperties.parent]) + as PdfDictionary?; } else { dic = null; } @@ -1943,8 +2228,12 @@ class PdfAnnotationHelper { } /// internal method - static IPdfPrimitive? getValue(PdfDictionary dictionary, - PdfCrossTable? crossTable, String value, bool inheritable) { + static IPdfPrimitive? getValue( + PdfDictionary dictionary, + PdfCrossTable? crossTable, + String value, + bool inheritable, + ) { IPdfPrimitive? primitive; if (dictionary.containsKey(value)) { primitive = crossTable!.getObject(dictionary[value]); @@ -1986,8 +2275,9 @@ class PdfAnnotationHelper { isSaveComplete = true; } if (!PdfAnnotationHelper.getHelper(annotation).flatten) { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); if (helper.flag != null) { int flagValue = 0; for (int i = 0; i < helper.flag!.length; i++) { @@ -2004,8 +2294,12 @@ class PdfAnnotationHelper { /// Internal method. int? getFlagValue() { if (dictionary!.containsKey(PdfDictionaryProperties.f)) { - final IPdfPrimitive? annotFlags = - getValue(dictionary!, crossTable, PdfDictionaryProperties.f, false); + final IPdfPrimitive? annotFlags = getValue( + dictionary!, + crossTable, + PdfDictionaryProperties.f, + false, + ); if (annotFlags != null && annotFlags is PdfNumber && annotFlags.value != null) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_border.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_border.dart index 730f86ee6..963a61508 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_border.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_border.dart @@ -15,12 +15,13 @@ class PdfAnnotationBorder implements IPdfWrapper { /// horizontal and vertical radius. /// /// The borderStyle and dashArray only used for shape annotations. - PdfAnnotationBorder( - [double? borderWidth, - double? horizontalRadius, - double? verticalRadius, - PdfBorderStyle? borderStyle, - int? dashArray]) { + PdfAnnotationBorder([ + double? borderWidth, + double? horizontalRadius, + double? verticalRadius, + PdfBorderStyle? borderStyle, + int? dashArray, + ]) { _helper.array.add(PdfNumber(0)); _helper.array.add(PdfNumber(0)); _helper.array.add(PdfNumber(1)); @@ -29,7 +30,9 @@ class PdfAnnotationBorder implements IPdfWrapper { this.verticalRadius = verticalRadius ??= 0; _borderStyle = borderStyle ??= PdfBorderStyle.solid; _helper.dictionary.setName( - PdfName(PdfDictionaryProperties.s), _styleToString(_borderStyle)); + PdfName(PdfDictionaryProperties.s), + _styleToString(_borderStyle), + ); if (dashArray != null) { this.dashArray = dashArray; } @@ -37,10 +40,14 @@ class PdfAnnotationBorder implements IPdfWrapper { PdfAnnotationBorder._asWidgetBorder() { _helper.dictionary.setProperty( - PdfDictionaryProperties.type, PdfName(PdfDictionaryProperties.border)); + PdfDictionaryProperties.type, + PdfName(PdfDictionaryProperties.border), + ); _borderStyle = PdfBorderStyle.solid; _helper.dictionary.setName( - PdfName(PdfDictionaryProperties.s), _styleToString(_borderStyle)); + PdfName(PdfDictionaryProperties.s), + _styleToString(_borderStyle), + ); _helper.isWidgetBorder = true; } @@ -82,8 +89,10 @@ class PdfAnnotationBorder implements IPdfWrapper { if (!_helper.isWidgetBorder) { _setNumber(2, value); } - _helper.dictionary - .setNumber(PdfDictionaryProperties.w, _borderWidth.toInt()); + _helper.dictionary.setNumber( + PdfDictionaryProperties.w, + _borderWidth.toInt(), + ); } } @@ -94,7 +103,9 @@ class PdfAnnotationBorder implements IPdfWrapper { if (value != _borderStyle) { _borderStyle = value; _helper.dictionary.setName( - PdfName(PdfDictionaryProperties.s), _styleToString(_borderStyle)); + PdfName(PdfDictionaryProperties.s), + _styleToString(_borderStyle), + ); } } @@ -172,7 +183,8 @@ class PdfAnnotationBorderHelper { /// internal method static PdfAnnotationBorderHelper getHelper( - PdfAnnotationBorder annotationBorder) { + PdfAnnotationBorder annotationBorder, + ) { return annotationBorder._helper; } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_collection.dart index 824724519..020e09c75 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_annotation_collection.dart @@ -73,9 +73,11 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfAnnotationCollectionHelper(this.base, this.page) : super(base); PdfAnnotationCollectionHelper._(this.base, this.page) : super(base) { - for (int i = 0; - i < PdfPageHelper.getHelper(page).terminalAnnotation.length; - ++i) { + for ( + int i = 0; + i < PdfPageHelper.getHelper(page).terminalAnnotation.length; + ++i + ) { final PdfAnnotation? annot = _getAnnotation(i); if (annot != null) { final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper(annot); @@ -111,17 +113,20 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { /// internal method PdfArray? rearrange(PdfReference reference, int tabIndex, int index) { - final PdfArray? annots = PdfPageHelper.getHelper(page) - .crossTable! - .getObject(PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.annots]) as PdfArray?; + final PdfArray? annots = + PdfPageHelper.getHelper(page).crossTable!.getObject( + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .annots], + ) + as PdfArray?; if (annots != null) { if (tabIndex > annots.count) { tabIndex = 0; } if (index >= annots.count) { - index = - PdfPageHelper.getHelper(page).annotsReference.indexOf(reference); + index = PdfPageHelper.getHelper( + page, + ).annotsReference.indexOf(reference); } final IPdfPrimitive? annotReference = annots.elements[index]; if (annotReference != null && annotReference is PdfReferenceHolder) { @@ -153,11 +158,16 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { if (flatten && PdfPageHelper.getHelper(page).document != null) { final PdfCrossTable? cross = PdfPageHelper.getHelper(page).crossTable; if (cross != null && - PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.annots)) { - final PdfArray? annots = cross.getObject(PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.annots]) as PdfArray?; + PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.annots)) { + final PdfArray? annots = + cross.getObject( + PdfPageHelper.getHelper( + page, + ).dictionary![PdfDictionaryProperties.annots], + ) + as PdfArray?; if (annots != null) { for (int count = 0; count < annots.count; ++count) { final PdfDictionary? annotDicrionary = @@ -207,12 +217,16 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { final PdfDictionary dictionary = PdfPageHelper.getHelper(page).dictionary!; if (dictionary.containsKey(PdfDictionaryProperties.annots)) { - array = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.annots]) as PdfArray?; + array = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.annots], + ) + as PdfArray?; } array ??= PdfArray(); - final PdfReferenceHolder reference = - PdfReferenceHolder(PdfAnnotationHelper.getHelper(annot).dictionary); + final PdfReferenceHolder reference = PdfReferenceHolder( + PdfAnnotationHelper.getHelper(annot).dictionary, + ); if (!PdfAnnotationHelper.getHelper(annot).isOldAnnotation && !_checkPresence(array, reference)) { array.add(reference); @@ -222,7 +236,9 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { final IPdfPrimitive? tempElement = IPdfWrapper.getElement(annot); if (tempElement == null) { IPdfWrapper.setElement( - annot, PdfAnnotationHelper.getHelper(annot).dictionary); + annot, + PdfAnnotationHelper.getHelper(annot).dictionary, + ); } annotations.add(PdfReferenceHolder(annot)); list.add(annot); @@ -260,25 +276,30 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { final PdfDictionary pageDic = PdfPageHelper.getHelper(page).dictionary!; PdfArray? annots; if (pageDic.containsKey(PdfDictionaryProperties.annots)) { - annots = PdfPageHelper.getHelper(page) - .crossTable! - .getObject(pageDic[PdfDictionaryProperties.annots]) as PdfArray?; + annots = + PdfPageHelper.getHelper( + page, + ).crossTable!.getObject(pageDic[PdfDictionaryProperties.annots]) + as PdfArray?; } else { annots = PdfArray(); } - if (PdfAnnotationHelper.getHelper(annot) - .dictionary! - .containsKey(PdfDictionaryProperties.popup)) { + if (PdfAnnotationHelper.getHelper( + annot, + ).dictionary!.containsKey(PdfDictionaryProperties.popup)) { final IPdfPrimitive? popUpDictionary = - (PdfAnnotationHelper.getHelper(annot) - .dictionary![PdfName(PdfDictionaryProperties.popup)] + (PdfAnnotationHelper.getHelper(annot).dictionary![PdfName( + PdfDictionaryProperties.popup, + )] is PdfReferenceHolder) - ? (PdfAnnotationHelper.getHelper(annot) - .dictionary![PdfName(PdfDictionaryProperties.popup)]! + ? (PdfAnnotationHelper.getHelper(annot).dictionary![PdfName( + PdfDictionaryProperties.popup, + )]! as PdfReferenceHolder) .object - : PdfAnnotationHelper.getHelper(annot) - .dictionary![PdfName(PdfDictionaryProperties.popup)]; + : PdfAnnotationHelper.getHelper(annot).dictionary![PdfName( + PdfDictionaryProperties.popup, + )]; if (popUpDictionary is PdfDictionary) { for (int i = 0; i < annots!.count; i++) { if (popUpDictionary == @@ -289,22 +310,22 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { break; } } - final IPdfPrimitive popUpObj = PdfPageHelper.getHelper(page) - .crossTable! - .getObject(popUpDictionary)!; - final int? popUpIndex = - PdfPageHelper.getHelper(page).crossTable!.items!.lookFor(popUpObj); + final IPdfPrimitive popUpObj = + PdfPageHelper.getHelper( + page, + ).crossTable!.getObject(popUpDictionary)!; + final int? popUpIndex = PdfPageHelper.getHelper( + page, + ).crossTable!.items!.lookFor(popUpObj); if (popUpIndex != null && popUpIndex != -1) { - PdfPageHelper.getHelper(page) - .crossTable! - .items! - .objectCollection! - .removeAt(popUpIndex); + PdfPageHelper.getHelper( + page, + ).crossTable!.items!.objectCollection!.removeAt(popUpIndex); } _removeAllReference(popUpObj); - PdfPageHelper.getHelper(page) - .terminalAnnotation - .remove(popUpDictionary); + PdfPageHelper.getHelper( + page, + ).terminalAnnotation.remove(popUpDictionary); } } for (int i = 0; i < annots!.count; i++) { @@ -317,9 +338,9 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { } } PdfAnnotationHelper.getHelper(annot).dictionary!.changed = false; - PdfPageHelper.getHelper(page) - .dictionary! - .setProperty(PdfDictionaryProperties.annots, annots); + PdfPageHelper.getHelper( + page, + ).dictionary!.setProperty(PdfDictionaryProperties.annots, annots); } void _removeAllReference(IPdfPrimitive obj) { @@ -332,14 +353,13 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { k.name != PdfDictionaryProperties.parent) { final IPdfPrimitive newobj = PdfPageHelper.getHelper(page).crossTable!.getObject(v)!; - final int? index = - PdfPageHelper.getHelper(page).crossTable!.items!.lookFor(newobj); + final int? index = PdfPageHelper.getHelper( + page, + ).crossTable!.items!.lookFor(newobj); if (index != null && index != -1) { - PdfPageHelper.getHelper(page) - .crossTable! - .items! - .objectCollection! - .removeAt(index); + PdfPageHelper.getHelper( + page, + ).crossTable!.items!.objectCollection!.removeAt(index); } _removeAllReference(v!); (PdfCrossTable.dereference(v)! as PdfStream) @@ -357,11 +377,19 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { final PdfCrossTable? crossTable = PdfPageHelper.getHelper(page).crossTable; PdfAnnotation? annot; if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName name = PdfAnnotationHelper.getValue( - dictionary, crossTable, PdfDictionaryProperties.subtype, true)! - as PdfName; - final PdfAnnotationTypes type = - getAnnotationType(name, dictionary, crossTable); + final PdfName name = + PdfAnnotationHelper.getValue( + dictionary, + crossTable, + PdfDictionaryProperties.subtype, + true, + )! + as PdfName; + final PdfAnnotationTypes type = getAnnotationType( + name, + dictionary, + crossTable, + ); final PdfArray? rectValue = PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.rect]) as PdfArray?; @@ -369,7 +397,8 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { String text = ''; if (dictionary.containsKey(PdfDictionaryProperties.contents)) { final IPdfPrimitive? str = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.contents]); + dictionary[PdfDictionaryProperties.contents], + ); if (str != null && str is PdfString) { text = str.value.toString(); } @@ -380,13 +409,19 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { break; case PdfAnnotationTypes.linkAnnotation: if (dictionary.containsKey(PdfDictionaryProperties.a)) { - final PdfDictionary? remoteLinkDic = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.a]) as PdfDictionary?; + final PdfDictionary? remoteLinkDic = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.a], + ) + as PdfDictionary?; if (remoteLinkDic != null && remoteLinkDic.containsKey(PdfDictionaryProperties.s)) { PdfName? gotor; - gotor = PdfCrossTable.dereference( - remoteLinkDic[PdfDictionaryProperties.s]) as PdfName?; + gotor = + PdfCrossTable.dereference( + remoteLinkDic[PdfDictionaryProperties.s], + ) + as PdfName?; if (gotor != null && gotor.name == 'URI') { annot = _createLinkAnnotation(dictionary, crossTable!, text); } @@ -436,7 +471,10 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { /// Gets the type of the annotation. static PdfAnnotationTypes getAnnotationType( - PdfName name, PdfDictionary dictionary, PdfCrossTable? crossTable) { + PdfName name, + PdfDictionary dictionary, + PdfCrossTable? crossTable, + ) { final String str = name.name!; PdfAnnotationTypes type = PdfAnnotationTypes.noAnnotation; switch (str.toLowerCase()) { @@ -448,13 +486,19 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { as PdfDictionary?; } if (linkDic != null && linkDic.containsKey(PdfDictionaryProperties.s)) { - name = PdfCrossTable.dereference(linkDic[PdfDictionaryProperties.s])! - as PdfName; - final PdfArray? border = (PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.border]) is PdfArray) - ? PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.border]) as PdfArray? - : null; + name = + PdfCrossTable.dereference(linkDic[PdfDictionaryProperties.s])! + as PdfName; + final PdfArray? border = + (PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.border], + ) + is PdfArray) + ? PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.border], + ) + as PdfArray? + : null; final bool mType = _findAnnotation(border); if (name.name == 'URI') { type = PdfAnnotationTypes.linkAnnotation; @@ -469,8 +513,11 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { type = PdfAnnotationTypes.documentLinkAnnotation; } } else if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName? strText = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.subtype]) as PdfName?; + final PdfName? strText = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.subtype], + ) + as PdfName?; if (strText != null) { switch (strText.name) { case 'Link': @@ -520,27 +567,43 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { // Creates the file link annotation. PdfAnnotation _createDocumentLinkAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfAnnotation annot = - PdfDocumentLinkAnnotationHelper.load(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfAnnotation annot = PdfDocumentLinkAnnotationHelper.load( + dictionary, + crossTable, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); PdfAnnotationHelper.getHelper(annot).page = page; return annot; } PdfAnnotation _createLinkAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfUriAnnotationHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfUriAnnotationHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); return annot; } // Creates the Line Annotation. PdfAnnotation _createLineAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfLineAnnotationHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfLineAnnotationHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); PdfAnnotationHelper.getHelper(annot).page = page; return annot; @@ -548,9 +611,15 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { // Creates the Ellipse Annotation. PdfAnnotation _createEllipseAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfEllipseAnnotationHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfEllipseAnnotationHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); PdfAnnotationHelper.getHelper(annot).page = page; return annot; @@ -558,9 +627,15 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { // Creates the Rectangle Annotation. PdfAnnotation _createRectangleAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfRectangleAnnotationHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfRectangleAnnotationHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); PdfAnnotationHelper.getHelper(annot).page = page; return annot; @@ -568,44 +643,70 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { // Creates the Polygon Annotation. PdfAnnotation _createPolygonAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfPolygonAnnotationHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfPolygonAnnotationHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); PdfAnnotationHelper.getHelper(annot).page = page; return annot; } PdfAnnotation _createTextWebLinkAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfTextWebLinkHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfTextWebLinkHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); return annot; } //Creates the widget annotation. PdfAnnotation _createWidgetAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfAnnotation annot = - WidgetAnnotationHelper.load(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfAnnotation annot = WidgetAnnotationHelper.load( + dictionary, + crossTable, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); return annot; } /// Creates the Markup Annotation. PdfAnnotation _createMarkupAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfAnnotation annot = - PdfTextMarkupAnnotationHelper.load(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfAnnotation annot = PdfTextMarkupAnnotationHelper.load( + dictionary, + crossTable, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); return annot; } PdfAnnotation _createPopupAnnotation( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { - final PdfAnnotation annot = - PdfPopupAnnotationHelper.load(dictionary, crossTable, text); + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { + final PdfAnnotation annot = PdfPopupAnnotationHelper.load( + dictionary, + crossTable, + text, + ); PdfAnnotationHelper.getHelper(annot).setPage(page); return annot; } @@ -650,7 +751,8 @@ class PdfAnnotationCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfAnnotationCollectionHelper getHelper( - PdfAnnotationCollection annotationCollection) { + PdfAnnotationCollection annotationCollection, + ) { return annotationCollection._helper; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_appearance.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_appearance.dart index 1600cb3d0..7bd34408c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_appearance.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_appearance.dart @@ -22,9 +22,13 @@ class PdfAppearance implements IPdfWrapper { PdfTemplate get normal { if (_helper.templateNormal == null) { _helper.templateNormal = PdfTemplate( - _annotation.bounds.size.width, _annotation.bounds.size.height); - _helper.dictionary!.setProperty(PdfDictionaryProperties.n, - PdfReferenceHolder(_helper.templateNormal)); + _annotation.bounds.size.width, + _annotation.bounds.size.height, + ); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.n, + PdfReferenceHolder(_helper.templateNormal), + ); } return _helper.templateNormal!; } @@ -33,18 +37,24 @@ class PdfAppearance implements IPdfWrapper { set normal(PdfTemplate value) { if (_helper.templateNormal != value) { _helper.templateNormal = value; - _helper.dictionary!.setProperty(PdfDictionaryProperties.n, - PdfReferenceHolder(_helper.templateNormal)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.n, + PdfReferenceHolder(_helper.templateNormal), + ); } } /// Gets or sets [PdfTemplate] object which applied to an annotation when mouse button is pressed. PdfTemplate get pressed { if (_helper.templatePressed == null) { - _helper.templatePressed = - PdfTemplate(_annotation.bounds.width, _annotation.bounds.height); - _helper.dictionary!.setProperty(PdfDictionaryProperties.d, - PdfReferenceHolder(_helper.templatePressed)); + _helper.templatePressed = PdfTemplate( + _annotation.bounds.width, + _annotation.bounds.height, + ); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.d, + PdfReferenceHolder(_helper.templatePressed), + ); } return _helper.templatePressed!; } @@ -52,8 +62,10 @@ class PdfAppearance implements IPdfWrapper { set pressed(PdfTemplate value) { if (value != _helper.templatePressed) { _helper.templatePressed = value; - _helper.dictionary!.setProperty(PdfDictionaryProperties.d, - PdfReferenceHolder(_helper.templatePressed)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.d, + PdfReferenceHolder(_helper.templatePressed), + ); } } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_document_link_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_document_link_annotation.dart index 8ab185eab..79f1c428b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_document_link_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_document_link_annotation.dart @@ -56,7 +56,9 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { } PdfDocumentLinkAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { _helper = PdfDocumentLinkAnnotationHelper._(this, dictionary, crossTable); } @@ -94,9 +96,9 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { _helper.destination = value; } if (PdfAnnotationHelper.getHelper(this).isLoadedAnnotation) { - PdfAnnotationHelper.getHelper(this) - .dictionary! - .setProperty(PdfDictionaryProperties.dest, value); + PdfAnnotationHelper.getHelper( + this, + ).dictionary!.setProperty(PdfDictionaryProperties.dest, value); } } } @@ -127,24 +129,28 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { final PdfCrossTable crossTable = PdfAnnotationHelper.getHelper(this).crossTable; if (dictionary.containsKey(PdfDictionaryProperties.dest)) { - final IPdfPrimitive? obj = - crossTable.getObject(dictionary[PdfDictionaryProperties.dest]); + final IPdfPrimitive? obj = crossTable.getObject( + dictionary[PdfDictionaryProperties.dest], + ); PdfArray? array; if (obj is PdfArray) { array = obj; } else if (crossTable.document != null && PdfDocumentHelper.getHelper(crossTable.document!).isLoadedDocument) { if (obj is PdfName || obj is PdfString) { - array = PdfDocumentHelper.getHelper(crossTable.document!) - .getNamedDestination(obj!); + array = PdfDocumentHelper.getHelper( + crossTable.document!, + ).getNamedDestination(obj!); } } PdfPage page; if (array != null && array[0] is PdfReferenceHolder) { - final PdfDictionary? dic = crossTable - .getObject(array[0]! as PdfReferenceHolder) as PdfDictionary?; - page = PdfPageCollectionHelper.getHelper(crossTable.document!.pages) - .getPage(dic); + final PdfDictionary? dic = + crossTable.getObject(array[0]! as PdfReferenceHolder) + as PdfDictionary?; + page = PdfPageCollectionHelper.getHelper( + crossTable.document!.pages, + ).getPage(dic); final PdfName? mode = array[1] as PdfName?; if (mode != null) { if (mode.name == 'XYZ') { @@ -187,7 +193,9 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { final double width = (array[4]! as PdfNumber).value!.toDouble(); final double height = (array[5]! as PdfNumber).value!.toDouble(); dest = PdfDestinationHelper.getDestination( - page, PdfRectangle(left, top, width, height)); + page, + PdfRectangle(left, top, width, height), + ); dest.mode = PdfDestinationMode.fitR; } } @@ -207,8 +215,9 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { } else if (crossTable.document != null && PdfDocumentHelper.getHelper(crossTable.document!).isLoadedDocument) { if (obj is PdfName || obj is PdfString) { - array = PdfDocumentHelper.getHelper(crossTable.document!) - .getNamedDestination(obj); + array = PdfDocumentHelper.getHelper( + crossTable.document!, + ).getNamedDestination(obj); } } if (array != null && array[0] is PdfReferenceHolder) { @@ -217,8 +226,9 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { final IPdfPrimitive? primitiveObj = PdfCrossTable.dereference(holder); final PdfDictionary? dic = primitiveObj as PdfDictionary?; if (dic != null) { - page = PdfPageCollectionHelper.getHelper(crossTable.document!.pages) - .getPage(dic); + page = PdfPageCollectionHelper.getHelper( + crossTable.document!.pages, + ).getPage(dic); } if (page != null) { final PdfName mode = array[1]! as PdfName; @@ -260,9 +270,14 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { final PdfNumber right = array[4]! as PdfNumber; final PdfNumber top = array[5]! as PdfNumber; dest = PdfDestinationHelper.getDestination( - page, - PdfRectangle(left.value!.toDouble(), bottom.value!.toDouble(), - right.value!.toDouble(), top.value!.toDouble())); + page, + PdfRectangle( + left.value!.toDouble(), + bottom.value!.toDouble(), + right.value!.toDouble(), + top.value!.toDouble(), + ), + ); dest.mode = PdfDestinationMode.fitR; } } else { @@ -282,10 +297,12 @@ class PdfDocumentLinkAnnotation extends PdfLinkAnnotation { class PdfDocumentLinkAnnotationHelper extends PdfLinkAnnotationHelper { /// internal constructor PdfDocumentLinkAnnotationHelper(this.documentLinkHelper, Rect bounds) - : super(documentLinkHelper, bounds); - PdfDocumentLinkAnnotationHelper._(this.documentLinkHelper, - PdfDictionary dictionary, PdfCrossTable crossTable) - : super.load(documentLinkHelper, dictionary, crossTable); + : super(documentLinkHelper, bounds); + PdfDocumentLinkAnnotationHelper._( + this.documentLinkHelper, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super.load(documentLinkHelper, dictionary, crossTable); /// internal field PdfDocumentLinkAnnotation documentLinkHelper; @@ -301,20 +318,24 @@ class PdfDocumentLinkAnnotationHelper extends PdfLinkAnnotationHelper { void save() { if (destination != null) { PdfAnnotationHelper.getHelper(base).dictionary!.setProperty( - PdfName(PdfDictionaryProperties.dest), - IPdfWrapper.getElement(destination!)); + PdfName(PdfDictionaryProperties.dest), + IPdfWrapper.getElement(destination!), + ); } } /// internal method static PdfDocumentLinkAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfDocumentLinkAnnotation._(dictionary, crossTable); } /// internal method static PdfDocumentLinkAnnotationHelper getHelper( - PdfDocumentLinkAnnotation annotation) { + PdfDocumentLinkAnnotation annotation, + ) { return annotation._helper; } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_ellipse_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_ellipse_annotation.dart index 73ef55a58..fc78ded91 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_ellipse_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_ellipse_annotation.dart @@ -44,30 +44,40 @@ class PdfEllipseAnnotation extends PdfAnnotation { /// List bytes = await document.save(); /// document.dispose(); /// ``` - PdfEllipseAnnotation(Rect bounds, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - DateTime? modifiedDate, - double? opacity, - List? flags, - bool? setAppearance}) { - _helper = PdfEllipseAnnotationHelper(this, bounds, text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + PdfEllipseAnnotation( + Rect bounds, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + DateTime? modifiedDate, + double? opacity, + List? flags, + bool? setAppearance, + }) { + _helper = PdfEllipseAnnotationHelper( + this, + bounds, + text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); } PdfEllipseAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { _helper = PdfEllipseAnnotationHelper._(this, dictionary, crossTable); this.text = text; } @@ -113,36 +123,44 @@ class PdfEllipseAnnotation extends PdfAnnotation { /// [PdfEllipseAnnotation] helper class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { /// internal constructor - PdfEllipseAnnotationHelper(this.annotation, Rect bounds, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - DateTime? modifiedDate, - double? opacity, - List? flags, - bool? setAppearance}) - : super(annotation) { + PdfEllipseAnnotationHelper( + this.annotation, + Rect bounds, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + DateTime? modifiedDate, + double? opacity, + List? flags, + bool? setAppearance, + }) : super(annotation) { initializeAnnotation( - bounds: bounds, - text: text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); - dictionary!.setProperty(PdfDictionaryProperties.subtype, - PdfName(PdfDictionaryProperties.circle)); + bounds: bounds, + text: text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); + dictionary!.setProperty( + PdfDictionaryProperties.subtype, + PdfName(PdfDictionaryProperties.circle), + ); } PdfEllipseAnnotationHelper._( - this.annotation, PdfDictionary dictionary, PdfCrossTable crossTable) - : super(annotation) { + this.annotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(annotation) { initializeExistingAnnotation(dictionary, crossTable); } @@ -151,10 +169,12 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { /// internal method void save() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); - if (PdfAnnotationCollectionHelper.getHelper(annotation.page!.annotations) - .flatten) { + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); + if (PdfAnnotationCollectionHelper.getHelper( + annotation.page!.annotations, + ).flatten) { helper.flatten = true; } final PdfAppearance? pdfAppearance = helper.appearance; @@ -175,15 +195,19 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { } else { if (appearance != null) { annotation.appearance.normal = appearance; - helper.dictionary!.setProperty(PdfDictionaryProperties.ap, - PdfReferenceHolder(annotation.appearance)); + helper.dictionary!.setProperty( + PdfDictionaryProperties.ap, + PdfReferenceHolder(annotation.appearance), + ); } } } if (!helper.flatten && !isLoadedAnnotation) { helper.saveAnnotation(); - helper.dictionary! - .setProperty(PdfDictionaryProperties.bs, annotation.border); + helper.dictionary!.setProperty( + PdfDictionaryProperties.bs, + annotation.border, + ); } if (helper.flattenPopups) { helper.flattenPopup(); @@ -191,32 +215,41 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { } void _flattenAnnotation(PdfPage? page, PdfTemplate? appearance) { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); if (helper.isLoadedAnnotation) { - final bool isContainsAP = - helper.dictionary!.containsKey(PdfDictionaryProperties.ap); + final bool isContainsAP = helper.dictionary!.containsKey( + PdfDictionaryProperties.ap, + ); if (appearance == null) { if (isContainsAP) { - PdfDictionary? appearanceDictionary = PdfCrossTable.dereference( - helper.dictionary![PdfDictionaryProperties.ap]) as PdfDictionary?; + PdfDictionary? appearanceDictionary = + PdfCrossTable.dereference( + helper.dictionary![PdfDictionaryProperties.ap], + ) + as PdfDictionary?; if (appearanceDictionary != null) { - appearanceDictionary = PdfCrossTable.dereference( - appearanceDictionary[PdfDictionaryProperties.n]) - as PdfDictionary?; + appearanceDictionary = + PdfCrossTable.dereference( + appearanceDictionary[PdfDictionaryProperties.n], + ) + as PdfDictionary?; if (appearanceDictionary != null) { final PdfStream appearanceStream = appearanceDictionary as PdfStream; appearance = PdfTemplateHelper.fromPdfStream(appearanceStream); - final bool isNormalMatrix = - helper.validateTemplateMatrix(appearanceDictionary); + final bool isNormalMatrix = helper.validateTemplateMatrix( + appearanceDictionary, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } else { annotation.setAppearance = true; appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } @@ -226,50 +259,68 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } } else { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } else { page!.graphics.save(); final Rect rectangle = helper.calculateTemplateBounds( - annotation.bounds, page, appearance, true); + annotation.bounds, + page, + appearance, + true, + ); if (annotation.opacity < 1) { page.graphics.setTransparency(annotation.opacity); } page.graphics.drawPdfTemplate( - appearance!, Offset(rectangle.left, rectangle.top), rectangle.size); + appearance!, + Offset(rectangle.left, rectangle.top), + rectangle.size, + ); page.annotations.remove(annotation); page.graphics.restore(); } } PdfTemplate? _createAppearance() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); final bool isLoadedAnnotation = helper.isLoadedAnnotation; if (isLoadedAnnotation && !annotation.setAppearance) { return null; } - final PdfRectangle nativeRectangle = - PdfRectangle(0, 0, annotation.bounds.width, annotation.bounds.height); - final PdfTemplate template = - PdfTemplateHelper.fromRect(nativeRectangle.rect); + final PdfRectangle nativeRectangle = PdfRectangle( + 0, + 0, + annotation.bounds.width, + annotation.bounds.height, + ); + final PdfTemplate template = PdfTemplateHelper.fromRect( + nativeRectangle.rect, + ); PdfAnnotationHelper.setMatrixToZeroRotation( - PdfTemplateHelper.getHelper(template).content); + PdfTemplateHelper.getHelper(template).content, + ); if (isLoadedAnnotation && helper.dictionary!.containsKey(PdfDictionaryProperties.be)) { PdfTemplateHelper.getHelper(template).writeTransformation = false; } final PaintParams paintParams = PaintParams(); final double borderWidth = annotation.border.width / 2; - final PdfPen mBorderPen = - PdfPen(annotation.color, width: annotation.border.width); + final PdfPen mBorderPen = PdfPen( + annotation.color, + width: annotation.border.width, + ); if (annotation.border.width > 0 && PdfColorHelper.getHelper(annotation.color).alpha != 0) { paintParams.borderPen = mBorderPen; @@ -286,28 +337,42 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { graphics.setTransparency(annotation.opacity); } if (isLoadedAnnotation) { - final PdfRectangle rectangle = - _obtainStyle(mBorderPen, nativeRectangle, borderWidth); + final PdfRectangle rectangle = _obtainStyle( + mBorderPen, + nativeRectangle, + borderWidth, + ); if (helper.dictionary!.containsKey(PdfDictionaryProperties.be)) { _drawAppearance(rectangle, borderWidth, graphics, paintParams); } else { graphics!.drawEllipse( - Rect.fromLTWH(rectangle.x + borderWidth, rectangle.y, - rectangle.width - annotation.border.width, rectangle.height), - pen: paintParams.borderPen, - brush: paintParams.backBrush); + Rect.fromLTWH( + rectangle.x + borderWidth, + rectangle.y, + rectangle.width - annotation.border.width, + rectangle.height, + ), + pen: paintParams.borderPen, + brush: paintParams.backBrush, + ); } } else { - final Rect rect = Rect.fromLTWH(nativeRectangle.left, nativeRectangle.top, - nativeRectangle.width, nativeRectangle.height); + final Rect rect = Rect.fromLTWH( + nativeRectangle.left, + nativeRectangle.top, + nativeRectangle.width, + nativeRectangle.height, + ); graphics!.drawEllipse( - Rect.fromLTWH( - rect.left + borderWidth, - rect.top + borderWidth, - rect.width - annotation.border.width, - rect.height - annotation.border.width), - pen: paintParams.borderPen, - brush: paintParams.backBrush); + Rect.fromLTWH( + rect.left + borderWidth, + rect.top + borderWidth, + rect.width - annotation.border.width, + rect.height - annotation.border.width, + ), + pen: paintParams.borderPen, + brush: paintParams.backBrush, + ); } if (annotation.opacity < 1) { graphics!.restore(); @@ -317,7 +382,10 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { // Obtain Style for annotation PdfRectangle _obtainStyle( - PdfPen mBorderPen, PdfRectangle rectangle, double borderWidth) { + PdfPen mBorderPen, + PdfRectangle rectangle, + double borderWidth, + ) { final PdfDictionary dictionary = PdfAnnotationHelper.getHelper(annotation).dictionary!; if (dictionary.containsKey(PdfDictionaryProperties.bs)) { @@ -333,7 +401,8 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { final List dashPattern = []; for (int i = 0; i < dashPatternArray.count; i++) { dashPattern.add( - (dashPatternArray.elements[i]! as PdfNumber).value!.toDouble()); + (dashPatternArray.elements[i]! as PdfNumber).value!.toDouble(), + ); } mBorderPen.dashStyle = PdfDashStyle.dash; mBorderPen.dashPattern = dashPattern; @@ -363,32 +432,43 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { } // Draw appearance for annotation - void _drawAppearance(PdfRectangle rectangle, double borderWidth, - PdfGraphics? graphics, PaintParams paintParams) { + void _drawAppearance( + PdfRectangle rectangle, + double borderWidth, + PdfGraphics? graphics, + PaintParams paintParams, + ) { final PdfPath graphicsPath = PdfPath(); - graphicsPath.addEllipse(Rect.fromLTWH( + graphicsPath.addEllipse( + Rect.fromLTWH( rectangle.x + borderWidth, -rectangle.y - rectangle.height, rectangle.width - annotation.border.width, - rectangle.height)); + rectangle.height, + ), + ); double? radius = 0; - if (PdfAnnotationHelper.getHelper(annotation) - .dictionary! - .containsKey(PdfDictionaryProperties.rd)) { - final PdfArray? rdArray = PdfCrossTable.dereference( - PdfAnnotationHelper.getHelper(annotation) - .dictionary! - .items![PdfName(PdfDictionaryProperties.rd)]) as PdfArray?; + if (PdfAnnotationHelper.getHelper( + annotation, + ).dictionary!.containsKey(PdfDictionaryProperties.rd)) { + final PdfArray? rdArray = + PdfCrossTable.dereference( + PdfAnnotationHelper.getHelper( + annotation, + ).dictionary!.items![PdfName(PdfDictionaryProperties.rd)], + ) + as PdfArray?; if (rdArray != null) { radius = (rdArray.elements[0]! as PdfNumber).value as double?; } } if (radius! > 0) { final PdfRectangle rect = PdfRectangle( - rectangle.x + borderWidth, - -rectangle.y - rectangle.height, - rectangle.width - annotation.border.width, - rectangle.height); + rectangle.x + borderWidth, + -rectangle.y - rectangle.height, + rectangle.width - annotation.border.width, + rectangle.height, + ); final List startPointList = []; final List controlPointList = []; final List endPointList = []; @@ -411,56 +491,91 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { for (int i = 0; i < controlPointList.length; i++) { _createBezier( - startPointList[i], controlPointList[i], endPointList[i], points); + startPointList[i], + controlPointList[i], + endPointList[i], + points, + ); } PdfAnnotationHelper.getHelper(annotation).drawCloudStyle( - graphics!, - paintParams.backBrush, - paintParams.borderPen, - radius, - 0.833, - points, - false); + graphics!, + paintParams.backBrush, + paintParams.borderPen, + radius, + 0.833, + points, + false, + ); startPointList.clear(); controlPointList.clear(); endPointList.clear(); points.clear(); } else { graphics!.drawEllipse( - Rect.fromLTWH(rectangle.x + borderWidth, -rectangle.y, - rectangle.width - annotation.border.width, -rectangle.height), - pen: paintParams.borderPen, - brush: paintParams.backBrush); + Rect.fromLTWH( + rectangle.x + borderWidth, + -rectangle.y, + rectangle.width - annotation.border.width, + -rectangle.height, + ), + pen: paintParams.borderPen, + brush: paintParams.backBrush, + ); } } // Create bezier curve void _createBezier( - Offset ctrl1, Offset ctrl2, Offset ctrl3, List bezierPoints) { + Offset ctrl1, + Offset ctrl2, + Offset ctrl3, + List bezierPoints, + ) { bezierPoints.add(ctrl1); // add the first control point _populateBezierPoints(ctrl1, ctrl2, ctrl3, 0, bezierPoints); bezierPoints.add(ctrl3); // add the last control point } // calculate bezier points - void _populateBezierPoints(Offset ctrl1, Offset ctrl2, Offset ctrl3, - int currentIteration, List bezierPoints) { + void _populateBezierPoints( + Offset ctrl1, + Offset ctrl2, + Offset ctrl3, + int currentIteration, + List bezierPoints, + ) { if (currentIteration < 2) { //calculate next mid points - final Offset midPoint1 = - Offset((ctrl1.dx + ctrl2.dx) / 2, (ctrl1.dy + ctrl2.dy) / 2); - final Offset midPoint2 = - Offset((ctrl2.dx + ctrl3.dx) / 2, (ctrl2.dy + ctrl3.dy) / 2); + final Offset midPoint1 = Offset( + (ctrl1.dx + ctrl2.dx) / 2, + (ctrl1.dy + ctrl2.dy) / 2, + ); + final Offset midPoint2 = Offset( + (ctrl2.dx + ctrl3.dx) / 2, + (ctrl2.dy + ctrl3.dy) / 2, + ); final Offset midPoint3 = Offset( - (midPoint1.dx + midPoint2.dx) / 2, (midPoint1.dy + midPoint2.dy) / 2); + (midPoint1.dx + midPoint2.dx) / 2, + (midPoint1.dy + midPoint2.dy) / 2, + ); //the next control point currentIteration++; - _populateBezierPoints(ctrl1, midPoint1, midPoint3, currentIteration, - bezierPoints); //left branch + _populateBezierPoints( + ctrl1, + midPoint1, + midPoint3, + currentIteration, + bezierPoints, + ); //left branch bezierPoints.add(midPoint3); //add the next control point - _populateBezierPoints(midPoint3, midPoint2, ctrl3, currentIteration, - bezierPoints); //right branch + _populateBezierPoints( + midPoint3, + midPoint2, + ctrl3, + currentIteration, + bezierPoints, + ); //right branch } } @@ -477,7 +592,10 @@ class PdfEllipseAnnotationHelper extends PdfAnnotationHelper { /// internal method static PdfEllipseAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfEllipseAnnotation._(dictionary, crossTable, text); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_line_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_line_annotation.dart index 82ea30a31..fc0bf5321 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_line_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_line_annotation.dart @@ -55,33 +55,40 @@ class PdfLineAnnotation extends PdfAnnotation { /// List bytes = await document.save(); /// document.dispose(); /// ``` - PdfLineAnnotation(List linePoints, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - DateTime? modifiedDate, - double? opacity, - bool? setAppearance, - PdfLineEndingStyle beginLineStyle = PdfLineEndingStyle.none, - PdfLineEndingStyle endLineStyle = PdfLineEndingStyle.none, - PdfLineCaptionType captionType = PdfLineCaptionType.inline, - PdfLineIntent lineIntent = PdfLineIntent.lineArrow, - int? leaderLine, - int? leaderLineExt, - bool lineCaption = false, - List? flags}) { - _helper = PdfLineAnnotationHelper(this, linePoints, text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + PdfLineAnnotation( + List linePoints, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + DateTime? modifiedDate, + double? opacity, + bool? setAppearance, + PdfLineEndingStyle beginLineStyle = PdfLineEndingStyle.none, + PdfLineEndingStyle endLineStyle = PdfLineEndingStyle.none, + PdfLineCaptionType captionType = PdfLineCaptionType.inline, + PdfLineIntent lineIntent = PdfLineIntent.lineArrow, + int? leaderLine, + int? leaderLineExt, + bool lineCaption = false, + List? flags, + }) { + _helper = PdfLineAnnotationHelper( + this, + linePoints, + text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); this.beginLineStyle = beginLineStyle; this.endLineStyle = endLineStyle; this.captionType = captionType; @@ -96,7 +103,10 @@ class PdfLineAnnotation extends PdfAnnotation { } PdfLineAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable, String annotText) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String annotText, + ) { _helper = PdfLineAnnotationHelper._(this, dictionary, crossTable); text = annotText; } @@ -112,9 +122,10 @@ class PdfLineAnnotation extends PdfAnnotation { // Properties /// Gets the leader line. - int get leaderLine => PdfAnnotationHelper.getHelper(this).isLoadedAnnotation - ? _helper._obtainLeaderLine() - : _helper.leaderLine; + int get leaderLine => + PdfAnnotationHelper.getHelper(this).isLoadedAnnotation + ? _helper._obtainLeaderLine() + : _helper.leaderLine; /// Sets the leader line. set leaderLine(int value) { @@ -139,8 +150,10 @@ class PdfLineAnnotation extends PdfAnnotation { _helper.points = value; _helper.linePoints = PdfArray(_helper.points); if (helper.isLoadedAnnotation) { - helper.dictionary! - .setProperty(PdfDictionaryProperties.l, _helper.linePoints); + helper.dictionary!.setProperty( + PdfDictionaryProperties.l, + _helper.linePoints, + ); } } @@ -157,14 +170,17 @@ class PdfLineAnnotation extends PdfAnnotation { _lineIntent = value; } else { helper.dictionary!.setName( - PdfName(PdfDictionaryProperties.it), helper.getEnumName(value)); + PdfName(PdfDictionaryProperties.it), + helper.getEnumName(value), + ); } } /// Gets the line caption of the annotation. - bool get lineCaption => PdfAnnotationHelper.getHelper(this).isLoadedAnnotation - ? _helper._obtainLineCaption() - : _lineCaption; + bool get lineCaption => + PdfAnnotationHelper.getHelper(this).isLoadedAnnotation + ? _helper._obtainLineCaption() + : _lineCaption; /// Sets the line caption of the annotation. set lineCaption(bool value) { @@ -211,9 +227,13 @@ class PdfLineAnnotation extends PdfAnnotation { lineStyle.elements.removeAt(0); } lineStyle.insert( - 0, - PdfName(helper.getEnumName( - _helper._getLineStyle(helper.getEnumName(value.toString()))))); + 0, + PdfName( + helper.getEnumName( + _helper._getLineStyle(helper.getEnumName(value.toString())), + ), + ), + ); helper.dictionary!.setProperty(PdfDictionaryProperties.le, lineStyle); } } @@ -237,9 +257,13 @@ class PdfLineAnnotation extends PdfAnnotation { lineStyle.elements.removeAt(1); } lineStyle.insert( - 1, - PdfName(helper.getEnumName( - _helper._getLineStyle(helper.getEnumName(value.toString()))))); + 1, + PdfName( + helper.getEnumName( + _helper._getLineStyle(helper.getEnumName(value.toString())), + ), + ), + ); helper.dictionary!.setProperty(PdfDictionaryProperties.le, lineStyle); } } @@ -257,9 +281,13 @@ class PdfLineAnnotation extends PdfAnnotation { _captionType = value; } else { helper.dictionary!.setProperty( - PdfDictionaryProperties.cp, - PdfName(helper.getEnumName( - _helper._getCaptionType(helper.getEnumName(value.toString()))))); + PdfDictionaryProperties.cp, + PdfName( + helper.getEnumName( + _helper._getCaptionType(helper.getEnumName(value.toString())), + ), + ), + ); } } @@ -273,8 +301,10 @@ class PdfLineAnnotation extends PdfAnnotation { final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper(this); if (helper.textValue != value) { helper.textValue = value; - helper.dictionary! - .setString(PdfDictionaryProperties.contents, helper.textValue); + helper.dictionary!.setString( + PdfDictionaryProperties.contents, + helper.textValue, + ); } } @@ -317,36 +347,43 @@ class PdfLineAnnotation extends PdfAnnotation { class PdfLineAnnotationHelper extends PdfAnnotationHelper { /// internal constructor PdfLineAnnotationHelper( - this.lineAnnotation, List linePoints, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - DateTime? modifiedDate, - double? opacity, - List? flags, - bool? setAppearance}) - : super(lineAnnotation) { + this.lineAnnotation, + List linePoints, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + DateTime? modifiedDate, + double? opacity, + List? flags, + bool? setAppearance, + }) : super(lineAnnotation) { initializeAnnotation( - text: text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + text: text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); this.linePoints = PdfArray(linePoints); points = linePoints; dictionary!.setProperty( - PdfDictionaryProperties.subtype, PdfName(PdfDictionaryProperties.line)); + PdfDictionaryProperties.subtype, + PdfName(PdfDictionaryProperties.line), + ); } PdfLineAnnotationHelper._( - this.lineAnnotation, PdfDictionary dictionary, PdfCrossTable crossTable) - : super(lineAnnotation) { + this.lineAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(lineAnnotation) { initializeExistingAnnotation(dictionary, crossTable); } @@ -376,11 +413,12 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { /// internal method void save() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); if (PdfAnnotationCollectionHelper.getHelper( - lineAnnotation.page!.annotations) - .flatten) { + lineAnnotation.page!.annotations, + ).flatten) { helper.flatten = true; } if (helper.flatten || lineAnnotation.setAppearance) { @@ -394,8 +432,10 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { } else { if (appearance != null) { lineAnnotation.appearance.normal = appearance; - helper.dictionary!.setProperty(PdfDictionaryProperties.ap, - PdfReferenceHolder(lineAnnotation.appearance)); + helper.dictionary!.setProperty( + PdfDictionaryProperties.ap, + PdfReferenceHolder(lineAnnotation.appearance), + ); } } } @@ -409,18 +449,24 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { } void _savePdfLineDictionary() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); helper.saveAnnotation(); lineStyle = PdfArray(); if (lineStyle!.elements.isNotEmpty) { lineStyle!.insert( - 0, PdfName(helper.getEnumName(lineAnnotation.beginLineStyle))); - lineStyle! - .insert(1, PdfName(helper.getEnumName(lineAnnotation.endLineStyle))); + 0, + PdfName(helper.getEnumName(lineAnnotation.beginLineStyle)), + ); + lineStyle!.insert( + 1, + PdfName(helper.getEnumName(lineAnnotation.endLineStyle)), + ); } else { - lineStyle! - .add(PdfName(helper.getEnumName(lineAnnotation.beginLineStyle))); + lineStyle!.add( + PdfName(helper.getEnumName(lineAnnotation.beginLineStyle)), + ); lineStyle!.add(PdfName(helper.getEnumName(lineAnnotation.endLineStyle))); } final PdfDictionary dictionary = helper.dictionary!; @@ -440,58 +486,77 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { dictionary.setProperty(PdfDictionaryProperties.bs, lineAnnotation.border); if (!lineAnnotation.innerColor.isEmpty && PdfColorHelper.getHelper(lineAnnotation.innerColor).alpha != 0) { - dictionary.setProperty(PdfDictionaryProperties.ic, - PdfColorHelper.toArray(lineAnnotation.innerColor)); + dictionary.setProperty( + PdfDictionaryProperties.ic, + PdfColorHelper.toArray(lineAnnotation.innerColor), + ); } - dictionary[PdfDictionaryProperties.c] = - PdfColorHelper.toArray(lineAnnotation.color); + dictionary[PdfDictionaryProperties.c] = PdfColorHelper.toArray( + lineAnnotation.color, + ); - dictionary.setProperty(PdfDictionaryProperties.it, - PdfName(helper.getEnumName(lineAnnotation.lineIntent))); + dictionary.setProperty( + PdfDictionaryProperties.it, + PdfName(helper.getEnumName(lineAnnotation.lineIntent)), + ); dictionary.setProperty( - PdfDictionaryProperties.lle, PdfNumber(lineAnnotation.leaderLineExt)); + PdfDictionaryProperties.lle, + PdfNumber(lineAnnotation.leaderLineExt), + ); dictionary.setProperty(PdfDictionaryProperties.ll, PdfNumber(leaderLine)); - dictionary.setProperty(PdfDictionaryProperties.cp, - PdfName(helper.getEnumName(lineAnnotation.captionType))); + dictionary.setProperty( + PdfDictionaryProperties.cp, + PdfName(helper.getEnumName(lineAnnotation.captionType)), + ); dictionary.setProperty( - PdfDictionaryProperties.cap, PdfBoolean(lineAnnotation.lineCaption)); + PdfDictionaryProperties.cap, + PdfBoolean(lineAnnotation.lineCaption), + ); - dictionary.setProperty(PdfDictionaryProperties.rect, - PdfArray.fromRectangle(_obtainLineBounds())); + dictionary.setProperty( + PdfDictionaryProperties.rect, + PdfArray.fromRectangle(_obtainLineBounds()), + ); } void _flattenAnnotation(PdfPage? page, PdfTemplate? appearance) { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); final PdfDictionary dictionary = helper.dictionary!; if (helper.isLoadedAnnotation) { - final bool isContainsAP = - dictionary.containsKey(PdfDictionaryProperties.ap); + final bool isContainsAP = dictionary.containsKey( + PdfDictionaryProperties.ap, + ); if (isContainsAP && appearance == null) { PdfDictionary? appearanceDictionary = PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.ap]) as PdfDictionary?; if (appearanceDictionary != null) { - appearanceDictionary = PdfCrossTable.dereference( - appearanceDictionary[PdfDictionaryProperties.n]) - as PdfDictionary?; + appearanceDictionary = + PdfCrossTable.dereference( + appearanceDictionary[PdfDictionaryProperties.n], + ) + as PdfDictionary?; if (appearanceDictionary != null) { final PdfStream appearanceStream = appearanceDictionary as PdfStream; appearance = PdfTemplateHelper.fromPdfStream(appearanceStream); - final bool isNormalMatrix = - helper.validateTemplateMatrix(appearanceDictionary); + final bool isNormalMatrix = helper.validateTemplateMatrix( + appearanceDictionary, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } else { lineAnnotation.setAppearance = true; appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } @@ -501,31 +566,41 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } else { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance!).content); + PdfTemplateHelper.getHelper(appearance!).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } else { page!.graphics.save(); final Rect rectangle = helper.calculateTemplateBounds( - lineAnnotation.bounds, page, appearance, true); + lineAnnotation.bounds, + page, + appearance, + true, + ); if (lineAnnotation.opacity < 1) { page.graphics.setTransparency(lineAnnotation.opacity); } page.graphics.drawPdfTemplate( - appearance!, Offset(rectangle.left, rectangle.top), rectangle.size); + appearance!, + Offset(rectangle.left, rectangle.top), + rectangle.size, + ); page.annotations.remove(lineAnnotation); page.graphics.restore(); } } PdfTemplate? _createAppearance() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); final bool isLoadedAnnotation = helper.isLoadedAnnotation; if (isLoadedAnnotation && !lineAnnotation.setAppearance) { return null; @@ -533,12 +608,15 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { final Rect nativeRectangle = _obtainLineBounds().rect; final PdfTemplate template = PdfTemplateHelper.fromRect(nativeRectangle); PdfAnnotationHelper.setMatrixToZeroRotation( - PdfTemplateHelper.getHelper(template).content); + PdfTemplateHelper.getHelper(template).content, + ); PdfTemplateHelper.getHelper(template).writeTransformation = false; final PaintParams paintParams = PaintParams(); final PdfGraphics? graphics = template.graphics; - final PdfPen mBorderPen = - PdfPen(lineAnnotation.color, width: lineAnnotation.border.width); + final PdfPen mBorderPen = PdfPen( + lineAnnotation.color, + width: lineAnnotation.border.width, + ); if (lineAnnotation.border.borderStyle == PdfBorderStyle.dashed) { mBorderPen.dashStyle = PdfDashStyle.dash; } else if (lineAnnotation.border.borderStyle == PdfBorderStyle.dot) { @@ -547,8 +625,10 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { paintParams.borderPen = mBorderPen; paintParams.foreBrush = PdfSolidBrush(lineAnnotation.color); final PdfFont mFont = PdfStandardFont( - PdfFontFamily.helvetica, isLoadedAnnotation ? 10 : 9, - style: PdfFontStyle.regular); + PdfFontFamily.helvetica, + isLoadedAnnotation ? 10 : 9, + style: PdfFontStyle.regular, + ); final PdfStringFormat format = PdfStringFormat(); format.alignment = PdfTextAlignment.center; format.lineAlignment = PdfVerticalAlignment.middle; @@ -581,34 +661,54 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { } final List x1y1 = [x1, y1]; final List x2y2 = [x2, y2]; - final double line = leadLine + + final double line = + leadLine + (isLoadedAnnotation ? _obtainLeaderOffset().toDouble() : 0); - final List startingPoint = - helper.getAxisValue(x1y1, lineAngle + 90, line); - final List endingPoint = - helper.getAxisValue(x2y2, lineAngle + 90, line); + final List startingPoint = helper.getAxisValue( + x1y1, + lineAngle + 90, + line, + ); + final List endingPoint = helper.getAxisValue( + x2y2, + lineAngle + 90, + line, + ); final double lineDistance = sqrt( - pow(endingPoint[0] - startingPoint[0], 2) + - pow(endingPoint[1] - startingPoint[1], 2)); + pow(endingPoint[0] - startingPoint[0], 2) + + pow(endingPoint[1] - startingPoint[1], 2), + ); final double centerWidth = lineDistance / 2 - ((lineWidth / 2) + lineAnnotation.border.width); - final List middlePoint1 = - helper.getAxisValue(startingPoint, angle, centerWidth); - final List middlePoint2 = - helper.getAxisValue(endingPoint, angle + 180, centerWidth); + final List middlePoint1 = helper.getAxisValue( + startingPoint, + angle, + centerWidth, + ); + final List middlePoint2 = helper.getAxisValue( + endingPoint, + angle + 180, + centerWidth, + ); List lineStartingPoint; List lineEndingPoint; if (lineAnnotation.beginLineStyle == PdfLineEndingStyle.openArrow || lineAnnotation.beginLineStyle == PdfLineEndingStyle.closedArrow) { lineStartingPoint = helper.getAxisValue( - startingPoint, angle, lineAnnotation.border.width); + startingPoint, + angle, + lineAnnotation.border.width, + ); } else { lineStartingPoint = startingPoint; } if (lineAnnotation.endLineStyle == PdfLineEndingStyle.openArrow || lineAnnotation.endLineStyle == PdfLineEndingStyle.closedArrow) { lineEndingPoint = helper.getAxisValue( - endingPoint, angle, -lineAnnotation.border.width); + endingPoint, + angle, + -lineAnnotation.border.width, + ); } else { lineEndingPoint = endingPoint; } @@ -621,18 +721,21 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { caption == 'Top' || !lineAnnotation.lineCaption) { graphics!.drawLine( - mBorderPen, - Offset(lineStartingPoint[0], -lineStartingPoint[1]), - Offset(lineEndingPoint[0], -lineEndingPoint[1])); + mBorderPen, + Offset(lineStartingPoint[0], -lineStartingPoint[1]), + Offset(lineEndingPoint[0], -lineEndingPoint[1]), + ); } else { graphics!.drawLine( - mBorderPen, - Offset(lineStartingPoint[0], -lineStartingPoint[1]), - Offset(middlePoint1[0], -middlePoint1[1])); + mBorderPen, + Offset(lineStartingPoint[0], -lineStartingPoint[1]), + Offset(middlePoint1[0], -middlePoint1[1]), + ); graphics.drawLine( - mBorderPen, - Offset(lineEndingPoint[0], -lineEndingPoint[1]), - Offset(middlePoint2[0], -middlePoint2[1])); + mBorderPen, + Offset(lineEndingPoint[0], -lineEndingPoint[1]), + Offset(middlePoint2[0], -middlePoint2[1]), + ); } if (lineAnnotation.opacity < 1) { graphics.restore(); @@ -641,88 +744,149 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { final PdfBrush backBrush = PdfSolidBrush(lineAnnotation.innerColor); final PdfArray lineStyle = PdfArray(); lineStyle.insert( - 0, PdfName(helper.getEnumName(lineAnnotation.beginLineStyle))); + 0, + PdfName(helper.getEnumName(lineAnnotation.beginLineStyle)), + ); lineStyle.insert( - 1, PdfName(helper.getEnumName(lineAnnotation.endLineStyle))); + 1, + PdfName(helper.getEnumName(lineAnnotation.endLineStyle)), + ); final double borderLength = lineAnnotation.border.width; - helper.setLineEndingStyles(startingPoint, endingPoint, graphics, angle, - mBorderPen, backBrush, lineStyle, borderLength); + helper.setLineEndingStyles( + startingPoint, + endingPoint, + graphics, + angle, + mBorderPen, + backBrush, + lineStyle, + borderLength, + ); //Set leader extension. - final List beginLineExt = helper.getAxisValue(startingPoint, - lineAngle + 90, lineAnnotation.leaderLineExt.toDouble()); - graphics.drawLine(mBorderPen, Offset(startingPoint[0], -startingPoint[1]), - Offset(beginLineExt[0], -beginLineExt[1])); + final List beginLineExt = helper.getAxisValue( + startingPoint, + lineAngle + 90, + lineAnnotation.leaderLineExt.toDouble(), + ); + graphics.drawLine( + mBorderPen, + Offset(startingPoint[0], -startingPoint[1]), + Offset(beginLineExt[0], -beginLineExt[1]), + ); final List endLineExt = helper.getAxisValue( - endingPoint, lineAngle + 90, lineAnnotation.leaderLineExt.toDouble()); - graphics.drawLine(mBorderPen, Offset(endingPoint[0], -endingPoint[1]), - Offset(endLineExt[0], -endLineExt[1])); + endingPoint, + lineAngle + 90, + lineAnnotation.leaderLineExt.toDouble(), + ); + graphics.drawLine( + mBorderPen, + Offset(endingPoint[0], -endingPoint[1]), + Offset(endLineExt[0], -endLineExt[1]), + ); //Set leader line - final List beginLeaderLine = - helper.getAxisValue(startingPoint, lineAngle - 90, leadLine); - graphics.drawLine(mBorderPen, Offset(startingPoint[0], -startingPoint[1]), - Offset(beginLeaderLine[0], -beginLeaderLine[1])); - final List endLeaderLine = - helper.getAxisValue(endingPoint, lineAngle - 90, leadLine); - graphics.drawLine(mBorderPen, Offset(endingPoint[0], -endingPoint[1]), - Offset(endLeaderLine[0], -endLeaderLine[1])); + final List beginLeaderLine = helper.getAxisValue( + startingPoint, + lineAngle - 90, + leadLine, + ); + graphics.drawLine( + mBorderPen, + Offset(startingPoint[0], -startingPoint[1]), + Offset(beginLeaderLine[0], -beginLeaderLine[1]), + ); + final List endLeaderLine = helper.getAxisValue( + endingPoint, + lineAngle - 90, + leadLine, + ); + graphics.drawLine( + mBorderPen, + Offset(endingPoint[0], -endingPoint[1]), + Offset(endLeaderLine[0], -endLeaderLine[1]), + ); //Set caption Type. if (lineAnnotation.lineCaption) { final double midpoint = lineDistance / 2; - final List centerPoint = - helper.getAxisValue(startingPoint, angle, midpoint); - final List captionPosition = - _getCaptionPosition(caption, centerPoint, angle, mFont); + final List centerPoint = helper.getAxisValue( + startingPoint, + angle, + midpoint, + ); + final List captionPosition = _getCaptionPosition( + caption, + centerPoint, + angle, + mFont, + ); graphics.translateTransform(captionPosition[0], -captionPosition[1]); graphics.rotateTransform(-angle); - graphics.drawString(lineAnnotation.text, mFont, - brush: backBrush, bounds: Rect.fromLTWH(-lineWidth / 2, 0, 0, 0)); + graphics.drawString( + lineAnnotation.text, + mFont, + brush: backBrush, + bounds: Rect.fromLTWH(-lineWidth / 2, 0, 0, 0), + ); } } if (isLoadedAnnotation) { - helper.dictionary!.setProperty(PdfDictionaryProperties.rect, - PdfArray.fromRectangle(_obtainLineBounds())); + helper.dictionary!.setProperty( + PdfDictionaryProperties.rect, + PdfArray.fromRectangle(_obtainLineBounds()), + ); } if (!isLoadedAnnotation && helper.flatten) { final double pageHeight = lineAnnotation.page!.size.height; final PdfMargins? margins = helper.obtainMargin(); if (lineAnnotation.page != null) { lineAnnotation.bounds = Rect.fromLTWH( - nativeRectangle.left - margins!.left, - pageHeight - - (nativeRectangle.top + nativeRectangle.height) - - margins.top, - nativeRectangle.width, - nativeRectangle.height); + nativeRectangle.left - margins!.left, + pageHeight - + (nativeRectangle.top + nativeRectangle.height) - + margins.top, + nativeRectangle.width, + nativeRectangle.height, + ); } else { lineAnnotation.bounds = Rect.fromLTWH( - nativeRectangle.left, - pageHeight - (nativeRectangle.top + nativeRectangle.height), - nativeRectangle.width, - nativeRectangle.height); + nativeRectangle.left, + pageHeight - (nativeRectangle.top + nativeRectangle.height), + nativeRectangle.width, + nativeRectangle.height, + ); } } return template; } List _getCaptionPosition( - String caption, List centerPoint, double angle, PdfFont font) { + String caption, + List centerPoint, + double angle, + PdfFont font, + ) { List captionPosition = List.filled(2, 0); - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); if (helper.isLoadedAnnotation) { - final bool isContainsMeasure = helper.dictionary!.items! - .containsKey(PdfName(PdfDictionaryProperties.measure)); - final double length = caption == 'Top' - ? isContainsMeasure - ? 2 * font.height - : font.height - : isContainsMeasure + final bool isContainsMeasure = helper.dictionary!.items!.containsKey( + PdfName(PdfDictionaryProperties.measure), + ); + final double length = + caption == 'Top' + ? isContainsMeasure + ? 2 * font.height + : font.height + : isContainsMeasure ? 3 * (font.height / 2) : font.height / 2; captionPosition = helper.getAxisValue(centerPoint, angle + 90, length); } else { - captionPosition = helper.getAxisValue(centerPoint, angle + 90, - caption == 'Top' ? font.height : font.height / 2); + captionPosition = helper.getAxisValue( + centerPoint, + angle + 90, + caption == 'Top' ? font.height : font.height / 2, + ); } return captionPosition; } @@ -730,8 +894,9 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets leader line of the lineAnnotation. int _obtainLeaderLine() { int lLine = 0; - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); if (helper.dictionary!.containsKey(PdfDictionaryProperties.ll)) { final PdfNumber ll = helper.dictionary![PdfDictionaryProperties.ll]! as PdfNumber; @@ -743,12 +908,15 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets the line intent of the annotation. PdfLineIntent _obtainLineIntent() { PdfLineIntent lineintentValue = PdfLineIntent.lineArrow; - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); if (helper.dictionary!.containsKey(PdfDictionaryProperties.it)) { - final PdfName lineintent = helper.crossTable - .getObject(helper.dictionary![PdfDictionaryProperties.it])! - as PdfName; + final PdfName lineintent = + helper.crossTable.getObject( + helper.dictionary![PdfDictionaryProperties.it], + )! + as PdfName; lineintentValue = _getLineIntentText(lineintent.name.toString()); } return lineintentValue; @@ -780,12 +948,16 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { } } } else { - if (PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary! - .containsKey(PdfDictionaryProperties.l)) { - linePoints = PdfCrossTable.dereference( - PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary![PdfDictionaryProperties.l]) as PdfArray?; + if (PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary!.containsKey(PdfDictionaryProperties.l)) { + linePoints = + PdfCrossTable.dereference( + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary![PdfDictionaryProperties.l], + ) + as PdfArray?; if (linePoints != null) { points = []; // ignore: prefer_final_in_for_each @@ -803,11 +975,14 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets line caption of the annotation. bool _obtainLineCaption() { bool lCaption = false; - if (PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary! - .containsKey(PdfDictionaryProperties.cap)) { - final PdfBoolean lCap = PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary![PdfDictionaryProperties.cap]! as PdfBoolean; + if (PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary!.containsKey(PdfDictionaryProperties.cap)) { + final PdfBoolean lCap = + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary![PdfDictionaryProperties.cap]! + as PdfBoolean; lCaption = lCap.value!; } return lCaption; @@ -816,11 +991,14 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets leader ext of the annotation. int _obtainLeaderExt() { int lLineExt = 0; - if (PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary! - .containsKey(PdfDictionaryProperties.lle)) { - final PdfNumber lExt = PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary![PdfDictionaryProperties.lle]! as PdfNumber; + if (PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary!.containsKey(PdfDictionaryProperties.lle)) { + final PdfNumber lExt = + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary![PdfDictionaryProperties.lle]! + as PdfNumber; lLineExt = lExt.value!.toInt(); } return lLineExt; @@ -881,35 +1059,53 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { final PdfArray lineStyle = PdfArray(); if (lineStyle.elements.isNotEmpty) { lineStyle.insert( - 0, - PdfName(PdfAnnotationHelper.getHelper(lineAnnotation) - .getEnumName(lineAnnotation.beginLineStyle))); + 0, + PdfName( + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).getEnumName(lineAnnotation.beginLineStyle), + ), + ); lineStyle.insert( - 1, - PdfName(PdfAnnotationHelper.getHelper(lineAnnotation) - .getEnumName(lineAnnotation.endLineStyle))); + 1, + PdfName( + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).getEnumName(lineAnnotation.endLineStyle), + ), + ); } else { lineStyle.add(PdfName(lineAnnotation.beginLineStyle.toString())); lineStyle.add(PdfName(lineAnnotation.endLineStyle.toString())); } - bounds = PdfAnnotationHelper.getHelper(lineAnnotation) - .isLoadedAnnotation - ? PdfAnnotationHelper.getHelper(lineAnnotation).calculateLineBounds( - lPoints, - lineAnnotation.leaderLineExt, - lineAnnotation.leaderLine, - _obtainLeaderOffset(), - lineStyle, - lineAnnotation.border.width) - : PdfAnnotationHelper.getHelper(lineAnnotation).calculateLineBounds( - lPoints, - lineAnnotation.leaderLineExt, - leaderLine, - 0, - lineStyle, - lineAnnotation.border.width); - bounds = PdfRectangle(bounds.left - 8, bounds.top - 8, - bounds.width + 2 * 8, bounds.height + 2 * 8); + bounds = + PdfAnnotationHelper.getHelper(lineAnnotation).isLoadedAnnotation + ? PdfAnnotationHelper.getHelper( + lineAnnotation, + ).calculateLineBounds( + lPoints, + lineAnnotation.leaderLineExt, + lineAnnotation.leaderLine, + _obtainLeaderOffset(), + lineStyle, + lineAnnotation.border.width, + ) + : PdfAnnotationHelper.getHelper( + lineAnnotation, + ).calculateLineBounds( + lPoints, + lineAnnotation.leaderLineExt, + leaderLine, + 0, + lineStyle, + lineAnnotation.border.width, + ); + bounds = PdfRectangle( + bounds.left - 8, + bounds.top - 8, + bounds.width + 2 * 8, + bounds.height + 2 * 8, + ); } } return bounds; @@ -918,11 +1114,14 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets leader offset of the annotation. int _obtainLeaderOffset() { int lLineOffset = 0; - if (PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary! - .containsKey(PdfDictionaryProperties.llo)) { - final PdfNumber lOffset = PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary![PdfDictionaryProperties.llo]! as PdfNumber; + if (PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary!.containsKey(PdfDictionaryProperties.llo)) { + final PdfNumber lOffset = + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary![PdfDictionaryProperties.llo]! + as PdfNumber; lLineOffset = lOffset.value!.toInt(); } return lLineOffset; @@ -931,12 +1130,15 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets line style of the annotation. PdfArray? _obtainLineStyle() { PdfArray? array; - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(lineAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + lineAnnotation, + ); if (helper.dictionary!.containsKey(PdfDictionaryProperties.le)) { - array = helper.crossTable - .getObject(helper.dictionary![PdfDictionaryProperties.le]) - as PdfArray?; + array = + helper.crossTable.getObject( + helper.dictionary![PdfDictionaryProperties.le], + ) + as PdfArray?; } return array; } @@ -944,11 +1146,14 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { // Gets caption type of the annotation. PdfLineCaptionType _obtainCaptionType() { PdfLineCaptionType captiontypeValue = PdfLineCaptionType.inline; - if (PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary! - .containsKey(PdfDictionaryProperties.cp)) { - final PdfName cType = PdfAnnotationHelper.getHelper(lineAnnotation) - .dictionary![PdfDictionaryProperties.cp]! as PdfName; + if (PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary!.containsKey(PdfDictionaryProperties.cp)) { + final PdfName cType = + PdfAnnotationHelper.getHelper( + lineAnnotation, + ).dictionary![PdfDictionaryProperties.cp]! + as PdfName; captiontypeValue = _getCaptionType(cType.name.toString()); } return captiontypeValue; @@ -967,7 +1172,10 @@ class PdfLineAnnotationHelper extends PdfAnnotationHelper { /// internal method static PdfLineAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfLineAnnotation._(dictionary, crossTable, text); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_paintparams.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_paintparams.dart index 2d5332c93..b6ba3862e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_paintparams.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_paintparams.dart @@ -7,14 +7,15 @@ import 'enum.dart'; /// internal class class PaintParams { /// internal constructor - PaintParams( - {this.backBrush, - this.foreBrush, - this.borderPen, - this.bounds, - this.style, - this.borderWidth, - this.shadowBrush}); + PaintParams({ + this.backBrush, + this.foreBrush, + this.borderPen, + this.bounds, + this.style, + this.borderWidth, + this.shadowBrush, + }); /// internal field PdfBrush? backBrush; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_polygon_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_polygon_annotation.dart index 86019e60d..c581177ab 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_polygon_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_polygon_annotation.dart @@ -50,30 +50,40 @@ class PdfPolygonAnnotation extends PdfAnnotation { /// List bytes = await document.save(); /// document.dispose(); /// ``` - PdfPolygonAnnotation(List points, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - DateTime? modifiedDate, - double? opacity, - List? flags, - bool? setAppearance}) { - _helper = PdfPolygonAnnotationHelper(this, points, text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + PdfPolygonAnnotation( + List points, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + DateTime? modifiedDate, + double? opacity, + List? flags, + bool? setAppearance, + }) { + _helper = PdfPolygonAnnotationHelper( + this, + points, + text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); } PdfPolygonAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { _helper = PdfPolygonAnnotationHelper._(this, dictionary, crossTable); this.text = text; } @@ -143,36 +153,44 @@ class PdfPolygonAnnotation extends PdfAnnotation { /// [PdfPolygonAnnotation] helper class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { /// internal constructor - PdfPolygonAnnotationHelper(this.annotation, List points, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - DateTime? modifiedDate, - double? opacity, - List? flags, - bool? setAppearance}) - : super(annotation) { + PdfPolygonAnnotationHelper( + this.annotation, + List points, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + DateTime? modifiedDate, + double? opacity, + List? flags, + bool? setAppearance, + }) : super(annotation) { initializeAnnotation( - text: text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); - dictionary!.setProperty(PdfDictionaryProperties.subtype, - PdfName(PdfDictionaryProperties.polygon)); + text: text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); + dictionary!.setProperty( + PdfDictionaryProperties.subtype, + PdfName(PdfDictionaryProperties.polygon), + ); linePoints = PdfArray(points); _polygonPoints = points; } PdfPolygonAnnotationHelper._( - this.annotation, PdfDictionary dictionary, PdfCrossTable crossTable) - : super(annotation) { + this.annotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(annotation) { initializeExistingAnnotation(dictionary, crossTable); } @@ -185,7 +203,10 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { /// internal method static PdfPolygonAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfPolygonAnnotation._(dictionary, crossTable, text); } @@ -205,8 +226,9 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { /// internal method void save() { - if (PdfAnnotationCollectionHelper.getHelper(annotation.page!.annotations) - .flatten) { + if (PdfAnnotationCollectionHelper.getHelper( + annotation.page!.annotations, + ).flatten) { PdfAnnotationHelper.getHelper(annotation).flatten = true; } if (PdfAnnotationHelper.getHelper(annotation).isLoadedAnnotation) { @@ -217,40 +239,52 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } void _saveNewPolygonAnnotation() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); final PdfDictionary dictionary = helper.dictionary!; Rect nativeRectangle = Rect.zero; if (annotation.setAppearance) { _getBoundsValue(); nativeRectangle = Rect.fromLTWH( - annotation.bounds.left - annotation.border.width, - annotation.bounds.top - (annotation.border.width), - annotation.bounds.width + (2 * annotation.border.width), - annotation.bounds.height + (2 * annotation.border.width)); + annotation.bounds.left - annotation.border.width, + annotation.bounds.top - (annotation.border.width), + annotation.bounds.width + (2 * annotation.border.width), + annotation.bounds.height + (2 * annotation.border.width), + ); dictionary.setProperty(PdfDictionaryProperties.ap, annotation.appearance); if (dictionary[PdfDictionaryProperties.ap] != null) { - annotation.appearance.normal = - PdfTemplateHelper.fromRect(nativeRectangle); + annotation.appearance.normal = PdfTemplateHelper.fromRect( + nativeRectangle, + ); final PdfTemplate template = annotation.appearance.normal; PdfTemplateHelper.getHelper(template).writeTransformation = false; final PdfGraphics? graphics = template.graphics; - final PdfBrush? backBrushColor = annotation.innerColor.isEmpty - ? null - : PdfSolidBrush(annotation.innerColor); + final PdfBrush? backBrushColor = + annotation.innerColor.isEmpty + ? null + : PdfSolidBrush(annotation.innerColor); PdfPen? borderPenColor; if (annotation.border.width > 0 && PdfColorHelper.getHelper(annotation.color).alpha != 0) { - borderPenColor = - PdfPen(annotation.color, width: annotation.border.width); + borderPenColor = PdfPen( + annotation.color, + width: annotation.border.width, + ); } if (helper.flatten) { annotation.page!.annotations.remove(annotation); - annotation.page!.graphics.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backBrushColor); + annotation.page!.graphics.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backBrushColor, + ); } else { - graphics!.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backBrushColor); + graphics!.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backBrushColor, + ); } } } @@ -259,49 +293,64 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { PdfPen? borderPenColor; if (annotation.border.width > 0 && PdfColorHelper.getHelper(annotation.color).alpha != 0) { - borderPenColor = - PdfPen(annotation.color, width: annotation.border.width); + borderPenColor = PdfPen( + annotation.color, + width: annotation.border.width, + ); } - final PdfBrush? backBrushColor = annotation.innerColor.isEmpty - ? null - : PdfSolidBrush(annotation.innerColor); - annotation.page!.graphics.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backBrushColor); + final PdfBrush? backBrushColor = + annotation.innerColor.isEmpty + ? null + : PdfSolidBrush(annotation.innerColor); + annotation.page!.graphics.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backBrushColor, + ); } else if (!helper.flatten) { helper.saveAnnotation(); dictionary.setProperty( - PdfDictionaryProperties.vertices, PdfArray(linePoints)); + PdfDictionaryProperties.vertices, + PdfArray(linePoints), + ); dictionary.setProperty(PdfDictionaryProperties.bs, annotation.border); _getBoundsValue(); - dictionary.setProperty(PdfDictionaryProperties.rect, - PdfArray.fromRectangle(PdfRectangle.fromRect(annotation.bounds))); + dictionary.setProperty( + PdfDictionaryProperties.rect, + PdfArray.fromRectangle(PdfRectangle.fromRect(annotation.bounds)), + ); if (annotation.setAppearance) { - dictionary.setProperty(PdfDictionaryProperties.rect, - PdfArray.fromRectangle(PdfRectangle.fromRect(nativeRectangle))); + dictionary.setProperty( + PdfDictionaryProperties.rect, + PdfArray.fromRectangle(PdfRectangle.fromRect(nativeRectangle)), + ); } } } void _saveOldPolygonAnnotation() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); PdfGraphicsState? state; PdfRectangle nativeRectangle = PdfRectangle.empty; final PdfDictionary dictionary = helper.dictionary!; if (annotation.setAppearance) { _getBoundsValue(); nativeRectangle = PdfRectangle( - annotation.bounds.left - annotation.border.width, - annotation.page!.size.height - - annotation.bounds.top - - (annotation.border.width) - - annotation.bounds.height, - annotation.bounds.width + (2 * annotation.border.width), - annotation.bounds.height + (2 * annotation.border.width)); + annotation.bounds.left - annotation.border.width, + annotation.page!.size.height - + annotation.bounds.top - + (annotation.border.width) - + annotation.bounds.height, + annotation.bounds.width + (2 * annotation.border.width), + annotation.bounds.height + (2 * annotation.border.width), + ); dictionary.setProperty(PdfDictionaryProperties.ap, annotation.appearance); if (dictionary[PdfDictionaryProperties.ap] != null) { - annotation.appearance.normal = - PdfTemplateHelper.fromRect(nativeRectangle.rect); + annotation.appearance.normal = PdfTemplateHelper.fromRect( + nativeRectangle.rect, + ); final PdfTemplate template = annotation.appearance.normal; PdfTemplateHelper.getHelper(template).writeTransformation = false; final PdfGraphics? graphics = annotation.appearance.normal.graphics; @@ -311,8 +360,10 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } PdfPen? borderPenColor; if (annotation.border.width > 0) { - borderPenColor = - PdfPen(annotation.color, width: annotation.border.width); + borderPenColor = PdfPen( + annotation.color, + width: annotation.border.width, + ); } if (dictionary.containsKey(PdfDictionaryProperties.bs)) { PdfDictionary? bSDictionary; @@ -320,20 +371,26 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { is PdfReferenceHolder) { bSDictionary = (dictionary.items![PdfName(PdfDictionaryProperties.bs)]! - as PdfReferenceHolder) - .object as PdfDictionary?; + as PdfReferenceHolder) + .object + as PdfDictionary?; } else { - bSDictionary = dictionary - .items![PdfName(PdfDictionaryProperties.bs)] as PdfDictionary?; + bSDictionary = + dictionary.items![PdfName(PdfDictionaryProperties.bs)] + as PdfDictionary?; } if (bSDictionary!.containsKey(PdfDictionaryProperties.d)) { - final PdfArray? dashPatternArray = PdfCrossTable.dereference( - bSDictionary.items![PdfName(PdfDictionaryProperties.d)]) - as PdfArray?; + final PdfArray? dashPatternArray = + PdfCrossTable.dereference( + bSDictionary.items![PdfName(PdfDictionaryProperties.d)], + ) + as PdfArray?; if (dashPatternArray != null) { final List dashPattern = List.filled( - dashPatternArray.count, 0, - growable: true); + dashPatternArray.count, + 0, + growable: true, + ); for (int i = 0; i < dashPatternArray.count; i++) { final IPdfPrimitive? pdfPrimitive = dashPatternArray.elements[i]; @@ -357,25 +414,47 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { final PdfDictionary beDictionary = dictionary[PdfName(PdfDictionaryProperties.be)]! as PdfDictionary; - final double? iNumber = (beDictionary - .items![PdfName(PdfDictionaryProperties.i)]! as PdfNumber) - .value as double?; + final double? iNumber = + (beDictionary.items![PdfName(PdfDictionaryProperties.i)]! + as PdfNumber) + .value + as double?; final double radius = iNumber == 1 ? 5 : 10; if (radius > 0) { final List points = _getLinePoints()!; if (points[0].dy > points[points.length - 1].dy) { - helper.drawCloudStyle(graphics!, backgroundBrush, - borderPenColor, radius, 0.833, _getLinePoints()!, false); + helper.drawCloudStyle( + graphics!, + backgroundBrush, + borderPenColor, + radius, + 0.833, + _getLinePoints()!, + false, + ); } - helper.drawCloudStyle(annotation.page!.graphics, backgroundBrush, - borderPenColor, radius, 0.833, _getLinePoints()!, false); + helper.drawCloudStyle( + annotation.page!.graphics, + backgroundBrush, + borderPenColor, + radius, + 0.833, + _getLinePoints()!, + false, + ); } else { - annotation.page!.graphics.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backgroundBrush); + annotation.page!.graphics.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backgroundBrush, + ); } } else { - annotation.page!.graphics.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backgroundBrush); + annotation.page!.graphics.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backgroundBrush, + ); } if (annotation.opacity < 1) { annotation.page!.graphics.restore(state); @@ -389,9 +468,11 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { final PdfDictionary beDictionary = dictionary[PdfName(PdfDictionaryProperties.be)]! as PdfDictionary; - final double? iNumber = (beDictionary - .items![PdfName(PdfDictionaryProperties.i)]! as PdfNumber) - .value as double?; + final double? iNumber = + (beDictionary.items![PdfName(PdfDictionaryProperties.i)]! + as PdfNumber) + .value + as double?; final double radius = iNumber == 1 ? 5 : 10; List points = _getLinePoints()!; if (points[0].dy > points[points.length - 1].dy) { @@ -400,22 +481,41 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { point.add(Offset(points[i].dx, -points[i].dy)); } points = point; - helper.drawCloudStyle(graphics!, backgroundBrush, borderPenColor, - radius, 0.833, points, true); + helper.drawCloudStyle( + graphics!, + backgroundBrush, + borderPenColor, + radius, + 0.833, + points, + true, + ); } else { - helper.drawCloudStyle(graphics!, backgroundBrush, borderPenColor, - radius, 0.833, points, false); + helper.drawCloudStyle( + graphics!, + backgroundBrush, + borderPenColor, + radius, + 0.833, + points, + false, + ); } } else { - graphics!.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backgroundBrush); + graphics!.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backgroundBrush, + ); } if (annotation.opacity < 1) { graphics.restore(state); } } - dictionary.setProperty(PdfDictionaryProperties.rect, - PdfArray.fromRectangle(nativeRectangle)); + dictionary.setProperty( + PdfDictionaryProperties.rect, + PdfArray.fromRectangle(nativeRectangle), + ); } } if (helper.flatten && !annotation.setAppearance) { @@ -435,20 +535,30 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } final bool isNormalMatrix = helper.validateTemplateMatrix(dic); final Rect rect = helper.calculateTemplateBounds( - annotation.bounds, annotation.page, template, isNormalMatrix); - annotation.page!.graphics - .drawPdfTemplate(template, rect.topLeft, rect.size); + annotation.bounds, + annotation.page, + template, + isNormalMatrix, + ); + annotation.page!.graphics.drawPdfTemplate( + template, + rect.topLeft, + rect.size, + ); annotation.page!.graphics.restore(state); annotation.page!.annotations.remove(annotation); } } } else { annotation.page!.annotations.remove(annotation); - final PdfPen borderPenColor = - PdfPen(annotation.color, width: annotation.border.width); - final PdfBrush? backgroundBrush = annotation.innerColor.isEmpty - ? null - : PdfSolidBrush(annotation.innerColor); + final PdfPen borderPenColor = PdfPen( + annotation.color, + width: annotation.border.width, + ); + final PdfBrush? backgroundBrush = + annotation.innerColor.isEmpty + ? null + : PdfSolidBrush(annotation.innerColor); if (annotation.opacity < 1) { state = annotation.page!.graphics.save(); annotation.page!.graphics.setTransparency(annotation.opacity); @@ -456,18 +566,30 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { if (dictionary.containsKey(PdfDictionaryProperties.be)) { final IPdfPrimitive? primitive = dictionary[PdfName(PdfDictionaryProperties.be)]; - final PdfDictionary beDictionary = (primitive is PdfReferenceHolder - ? primitive.object - : primitive)! as PdfDictionary; - final double? iNumber = (beDictionary - .items![PdfName(PdfDictionaryProperties.i)]! as PdfNumber) - .value as double?; + final PdfDictionary beDictionary = + (primitive is PdfReferenceHolder ? primitive.object : primitive)! + as PdfDictionary; + final double? iNumber = + (beDictionary.items![PdfName(PdfDictionaryProperties.i)]! + as PdfNumber) + .value + as double?; final double radius = iNumber == 1 ? 5 : 10; - helper.drawCloudStyle(annotation.page!.graphics, backgroundBrush, - borderPenColor, radius, 0.833, _getLinePoints()!, false); + helper.drawCloudStyle( + annotation.page!.graphics, + backgroundBrush, + borderPenColor, + radius, + 0.833, + _getLinePoints()!, + false, + ); } else { - annotation.page!.graphics.drawPolygon(_getLinePoints()!, - pen: borderPenColor, brush: backgroundBrush); + annotation.page!.graphics.drawPolygon( + _getLinePoints()!, + pen: borderPenColor, + brush: backgroundBrush, + ); } if (annotation.opacity < 1) { annotation.page!.graphics.restore(state); @@ -480,8 +602,9 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } List? _getLinePoints() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); if (helper.isLoadedAnnotation) { List? points; if (helper.dictionary!.containsKey(PdfDictionaryProperties.vertices)) { @@ -496,8 +619,9 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { points = []; for (int j = 0; j < point.length; j = j + 2) { if (helper.flatten) { - points.add(Offset( - point[j], annotation.page!.size.height - point[j + 1])); + points.add( + Offset(point[j], annotation.page!.size.height - point[j + 1]), + ); } else { points.add(Offset(point[j], -point[j + 1])); } @@ -520,21 +644,21 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { if (helper.flatten) { PdfPageHelper.getHelper(annotation.page!).isLoadedPage ? points.add( - Offset(pointsValue[j], pageHeight - pointsValue[j + 1])) - : points.add(Offset( + Offset(pointsValue[j], pageHeight - pointsValue[j + 1]), + ) + : points.add( + Offset( pointsValue[j] - - PdfPageHelper.getHelper(annotation.page!) - .section! - .pageSettings - .margins - .left, + PdfPageHelper.getHelper( + annotation.page!, + ).section!.pageSettings.margins.left, pageHeight - pointsValue[j + 1] - - PdfPageHelper.getHelper(annotation.page!) - .section! - .pageSettings - .margins - .right)); + PdfPageHelper.getHelper( + annotation.page!, + ).section!.pageSettings.margins.right, + ), + ); } else { points.add(Offset(pointsValue[j], -pointsValue[j + 1])); } @@ -545,8 +669,9 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } void _getBoundsValue() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); if (helper.isLoadedAnnotation) { final PdfArray rect = helper.dictionary![PdfDictionaryProperties.rect]! as PdfArray; @@ -554,11 +679,17 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { final List xval = []; final List yval = []; if (helper.dictionary!.containsKey(PdfDictionaryProperties.vertices)) { - final PdfArray linePoints = PdfCrossTable.dereference( - helper.dictionary![PdfDictionaryProperties.vertices])! as PdfArray; + final PdfArray linePoints = + PdfCrossTable.dereference( + helper.dictionary![PdfDictionaryProperties.vertices], + )! + as PdfArray; if (linePoints.count > 0) { - final List points = - List.filled(linePoints.count, 0, growable: true); + final List points = List.filled( + linePoints.count, + 0, + growable: true, + ); for (int j = 0; j < linePoints.count; j++) { final PdfNumber number = linePoints[j]! as PdfNumber; points[j] = number.value!.toDouble(); @@ -574,8 +705,12 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } xval.sort(); yval.sort(); - annotation.bounds = Rect.fromLTWH(xval[0], yval[0], - xval[xval.length - 1] - xval[0], yval[yval.length - 1] - yval[0]); + annotation.bounds = Rect.fromLTWH( + xval[0], + yval[0], + xval[xval.length - 1] - xval[0], + yval[yval.length - 1] - yval[0], + ); } else { final List xval = []; final List yval = []; @@ -597,8 +732,12 @@ class PdfPolygonAnnotationHelper extends PdfAnnotationHelper { } xval.sort(); yval.sort(); - annotation.bounds = Rect.fromLTWH(xval[0], yval[0], - xval[xval.length - 1] - xval[0], yval[yval.length - 1] - yval[0]); + annotation.bounds = Rect.fromLTWH( + xval[0], + yval[0], + xval[xval.length - 1] - xval[0], + yval[yval.length - 1] - yval[0], + ); } } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_popup_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_popup_annotation.dart index 2f93a18b7..cc00b2785 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_popup_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_popup_annotation.dart @@ -33,22 +33,40 @@ class PdfPopupAnnotation extends PdfAnnotation { /// final List bytes = await document.save(); /// document.dispose(); /// ``` - PdfPopupAnnotation(Rect bounds, String text, - {bool? open, - String? author, - PdfColor? color, - String? subject, - double? opacity, - DateTime? modifiedDate, - PdfPopupIcon? icon, - List? flags, - bool? setAppearance}) { - _helper = PdfPopupAnnotationHelper(this, bounds, text, open, author, color, - subject, opacity, modifiedDate, icon, flags, setAppearance); + PdfPopupAnnotation( + Rect bounds, + String text, { + bool? open, + String? author, + PdfColor? color, + String? subject, + double? opacity, + DateTime? modifiedDate, + PdfPopupIcon? icon, + List? flags, + bool? setAppearance, + }) { + _helper = PdfPopupAnnotationHelper( + this, + bounds, + text, + open, + author, + color, + subject, + opacity, + modifiedDate, + icon, + flags, + setAppearance, + ); } PdfPopupAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { _helper = PdfPopupAnnotationHelper._(this, dictionary, crossTable, text); } @@ -86,38 +104,44 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { //Constructor /// internal constructor PdfPopupAnnotationHelper( - this.popupAnnotation, - Rect bounds, - String text, - bool? open, - String? author, - PdfColor? color, - String? subject, - double? opacity, - DateTime? modifiedDate, - PdfPopupIcon? icon, - List? flags, - bool? setAppearance) - : super(popupAnnotation) { + this.popupAnnotation, + Rect bounds, + String text, + bool? open, + String? author, + PdfColor? color, + String? subject, + double? opacity, + DateTime? modifiedDate, + PdfPopupIcon? icon, + List? flags, + bool? setAppearance, + ) : super(popupAnnotation) { initializeAnnotation( - bounds: bounds, - text: text, - color: color, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + bounds: bounds, + text: text, + color: color, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); this.open = open ??= false; dictionary!.setProperty( - PdfDictionaryProperties.subtype, PdfName(PdfDictionaryProperties.text)); + PdfDictionaryProperties.subtype, + PdfName(PdfDictionaryProperties.text), + ); this.icon = icon ?? PdfPopupIcon.note; } - PdfPopupAnnotationHelper._(this.popupAnnotation, PdfDictionary dictionary, - PdfCrossTable crossTable, String text) - : super(popupAnnotation) { + PdfPopupAnnotationHelper._( + this.popupAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) : super(popupAnnotation) { this.text = text; initializeExistingAnnotation(dictionary, crossTable); } @@ -135,7 +159,10 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { /// internal method static PdfPopupAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfPopupAnnotation._(dictionary, crossTable, text); } @@ -159,16 +186,19 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { set icon(PdfPopupIcon value) { if (_icon != value) { _icon = value; - dictionary! - .setName(PdfName(PdfDictionaryProperties.name), getEnumName(_icon)); + dictionary!.setName( + PdfName(PdfDictionaryProperties.name), + getEnumName(_icon), + ); } } /// Internal method. bool obtainOpen() { if (dictionary!.containsKey(PdfDictionaryProperties.open)) { - final IPdfPrimitive? open = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.open]); + final IPdfPrimitive? open = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.open], + ); if (open != null && open is PdfBoolean) { return open.value ?? false; } @@ -179,8 +209,9 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { /// Internal method. PdfPopupIcon obtainIcon() { if (dictionary!.containsKey(PdfDictionaryProperties.name)) { - final IPdfPrimitive? icon = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.name]); + final IPdfPrimitive? icon = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.name], + ); if (icon != null && icon is PdfName) { return getIconName(icon.name.toString()); } else if (icon != null && icon is PdfString) { @@ -213,26 +244,32 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { /// Internal method. void save() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(popupAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + popupAnnotation, + ); if (PdfAnnotationCollectionHelper.getHelper( - popupAnnotation.page!.annotations) - .flatten) { + popupAnnotation.page!.annotations, + ).flatten) { helper.flatten = true; } if (helper.isLoadedAnnotation) { if (helper.setAppearance) { - popupAnnotation.appearance.normal = - PdfTemplate(bounds.width, bounds.height); + popupAnnotation.appearance.normal = PdfTemplate( + bounds.width, + bounds.height, + ); drawIcon(popupAnnotation.appearance.normal.graphics!); dictionary!.setProperty( - PdfDictionaryProperties.ap, popupAnnotation.appearance); + PdfDictionaryProperties.ap, + popupAnnotation.appearance, + ); } if (helper.flatten) { bool isFlattenPopup = true; if (dictionary!.containsKey(PdfDictionaryProperties.f)) { - final IPdfPrimitive? flag = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.f]); + final IPdfPrimitive? flag = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.f], + ); if (flag != null && flag is PdfNumber && flag.value == 30) { if (!helper.flattenPopups) { isFlattenPopup = false; @@ -241,7 +278,8 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { } if (dictionary![PdfDictionaryProperties.ap] != null && isFlattenPopup) { IPdfPrimitive? dic = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.ap]); + dictionary![PdfDictionaryProperties.ap], + ); PdfTemplate template; if (dic != null && dic is PdfDictionary) { dic = PdfCrossTable.dereference(dic[PdfDictionaryProperties.n]); @@ -252,8 +290,11 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { page!.graphics.save(); page!.graphics.setTransparency(opacity); } - page!.graphics - .drawPdfTemplate(template, bounds.topLeft, bounds.size); + page!.graphics.drawPdfTemplate( + template, + bounds.topLeft, + bounds.size, + ); if (!setAppearance && opacity < 1) { page!.graphics.restore(); } @@ -267,12 +308,17 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { if (helper.setAppearance || helper.flatten) { drawIcon(popupAnnotation.appearance.normal.graphics!); if (helper.flatten) { - page!.graphics.drawPdfTemplate(popupAnnotation.appearance.normal, - bounds.topLeft, popupAnnotation.appearance.normal.size); + page!.graphics.drawPdfTemplate( + popupAnnotation.appearance.normal, + bounds.topLeft, + popupAnnotation.appearance.normal.size, + ); page!.annotations.remove(popupAnnotation); } else { dictionary!.setProperty( - PdfDictionaryProperties.ap, popupAnnotation.appearance); + PdfDictionaryProperties.ap, + popupAnnotation.appearance, + ); } } } @@ -284,13 +330,15 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { /// Internal method. void drawIcon(PdfGraphics graphics) { if (dictionary!.containsKey(PdfDictionaryProperties.name)) { - final IPdfPrimitive? name = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.name]); + final IPdfPrimitive? name = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.name], + ); if (name != null && name is PdfName && name.name == 'Comment') { if (flatten) { popupAnnotation.appearance.normal = PdfTemplate( - bounds.width > 24 ? bounds.width : 24, - bounds.height > 22 ? bounds.height : 22); + bounds.width > 24 ? bounds.width : 24, + bounds.height > 22 ? bounds.height : 22, + ); graphics = popupAnnotation.appearance.normal.graphics!; } final PdfPen pen = PdfPen(PdfColor(0, 0, 0), width: 0.3); @@ -299,7 +347,7 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { final List points = [ const Offset(7, 15.45), const Offset(9, 16.15), - const Offset(4, 19) + const Offset(4, 19), ]; final PdfPath path = PdfPath(); if (color.isEmpty == true) { @@ -311,14 +359,23 @@ class PdfPopupAnnotationHelper extends PdfAnnotationHelper { template.graphics!.setTransparency(opacity); } template.graphics!.drawRectangle( - bounds: const Rect.fromLTWH(0, 0, 24, 22), pen: pen, brush: brush); - template.graphics! - .drawPolygon(points, pen: pen, brush: PdfBrushes.white); + bounds: const Rect.fromLTWH(0, 0, 24, 22), + pen: pen, + brush: brush, + ); + template.graphics!.drawPolygon( + points, + pen: pen, + brush: PdfBrushes.white, + ); path.addEllipse(const Rect.fromLTWH(2.5, 2.5, 19, 14)); template.graphics!.drawPath(pen: pen, brush: PdfBrushes.white, path); template.graphics!.drawArc( - const Rect.fromLTWH(2.5, 2.5, 19, 14), 110.7, 10.3, - pen: pen1); + const Rect.fromLTWH(2.5, 2.5, 19, 14), + 110.7, + 10.3, + pen: pen1, + ); if (opacity < 1) { template.graphics!.restore(); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_rectangle_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_rectangle_annotation.dart index 277ffbbb7..e17202bff 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_rectangle_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_rectangle_annotation.dart @@ -38,30 +38,40 @@ class PdfRectangleAnnotation extends PdfAnnotation { /// List bytes = await document.save(); /// document.dispose(); /// ``` - PdfRectangleAnnotation(Rect bounds, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - double? opacity, - DateTime? modifiedDate, - List? flags, - bool? setAppearance}) { - _helper = PdfRectangleAnnotationHelper(this, bounds, text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + PdfRectangleAnnotation( + Rect bounds, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + double? opacity, + DateTime? modifiedDate, + List? flags, + bool? setAppearance, + }) { + _helper = PdfRectangleAnnotationHelper( + this, + bounds, + text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); } PdfRectangleAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { _helper = PdfRectangleAnnotationHelper._(this, dictionary, crossTable); this.text = text; } @@ -109,35 +119,42 @@ class PdfRectangleAnnotation extends PdfAnnotation { class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { /// internal constructor PdfRectangleAnnotationHelper( - this.rectangleAnnotation, Rect bounds, String text, - {PdfColor? color, - PdfColor? innerColor, - PdfAnnotationBorder? border, - String? author, - String? subject, - double? opacity, - DateTime? modifiedDate, - List? flags, - bool? setAppearance}) - : super(rectangleAnnotation) { + this.rectangleAnnotation, + Rect bounds, + String text, { + PdfColor? color, + PdfColor? innerColor, + PdfAnnotationBorder? border, + String? author, + String? subject, + double? opacity, + DateTime? modifiedDate, + List? flags, + bool? setAppearance, + }) : super(rectangleAnnotation) { initializeAnnotation( - bounds: bounds, - text: text, - color: color, - innerColor: innerColor, - border: border, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); - dictionary!.setProperty(PdfDictionaryProperties.subtype, - PdfName(PdfDictionaryProperties.square)); + bounds: bounds, + text: text, + color: color, + innerColor: innerColor, + border: border, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); + dictionary!.setProperty( + PdfDictionaryProperties.subtype, + PdfName(PdfDictionaryProperties.square), + ); } - PdfRectangleAnnotationHelper._(this.rectangleAnnotation, - PdfDictionary dictionary, PdfCrossTable crossTable) - : super(rectangleAnnotation) { + PdfRectangleAnnotationHelper._( + this.rectangleAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(rectangleAnnotation) { initializeExistingAnnotation(dictionary, crossTable); } @@ -146,13 +163,17 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { /// internal method static PdfRectangleAnnotationHelper getHelper( - PdfRectangleAnnotation annotation) { + PdfRectangleAnnotation annotation, + ) { return annotation._helper; } /// internal method static PdfRectangleAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfRectangleAnnotation._(dictionary, crossTable, text); } @@ -166,11 +187,12 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { /// internal method void save() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(rectangleAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + rectangleAnnotation, + ); if (PdfAnnotationCollectionHelper.getHelper( - rectangleAnnotation.page!.annotations) - .flatten) { + rectangleAnnotation.page!.annotations, + ).flatten) { helper.flatten = true; } if (helper.flatten || @@ -191,15 +213,19 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } else { if (appearance != null) { rectangleAnnotation.appearance.normal = appearance; - helper.dictionary!.setProperty(PdfDictionaryProperties.ap, - PdfReferenceHolder(rectangleAnnotation.appearance)); + helper.dictionary!.setProperty( + PdfDictionaryProperties.ap, + PdfReferenceHolder(rectangleAnnotation.appearance), + ); } } } if (!helper.flatten && !helper.isLoadedAnnotation) { helper.saveAnnotation(); - helper.dictionary! - .setProperty(PdfDictionaryProperties.bs, rectangleAnnotation.border); + helper.dictionary!.setProperty( + PdfDictionaryProperties.bs, + rectangleAnnotation.border, + ); } if (helper.flattenPopups) { helper.flattenPopup(); @@ -207,27 +233,33 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } PdfTemplate? _createAppearance() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(rectangleAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + rectangleAnnotation, + ); if (helper.isLoadedAnnotation) { if (rectangleAnnotation.setAppearance) { final PaintParams paintParams = PaintParams(); final double borderWidth = rectangleAnnotation.border.width / 2; - final PdfPen mBorderPen = PdfPen(rectangleAnnotation.color, - width: rectangleAnnotation.border.width); + final PdfPen mBorderPen = PdfPen( + rectangleAnnotation.color, + width: rectangleAnnotation.border.width, + ); PdfBrush? mBackBrush; final Map result = _calculateCloudBorderBounds(); final double borderIntensity = result['borderIntensity'] as double; final String? borderStyle = result['borderStyle'] as String?; final PdfRectangle nativeRectangle = PdfRectangle( - 0, - 0, - rectangleAnnotation.bounds.width, - rectangleAnnotation.bounds.height); - final PdfTemplate template = - PdfTemplateHelper.fromRect(nativeRectangle.rect); + 0, + 0, + rectangleAnnotation.bounds.width, + rectangleAnnotation.bounds.height, + ); + final PdfTemplate template = PdfTemplateHelper.fromRect( + nativeRectangle.rect, + ); PdfAnnotationHelper.setMatrixToZeroRotation( - PdfTemplateHelper.getHelper(template).content); + PdfTemplateHelper.getHelper(template).content, + ); if (borderIntensity > 0 && borderStyle == 'C') { PdfTemplateHelper.getHelper(template).writeTransformation = false; } @@ -242,21 +274,35 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { paintParams.foreBrush = PdfSolidBrush(rectangleAnnotation.color); paintParams.backBrush = mBackBrush; final PdfRectangle rectangle = _obtainStyle( - mBorderPen, nativeRectangle, borderWidth, - borderIntensity: borderIntensity, borderStyle: borderStyle); + mBorderPen, + nativeRectangle, + borderWidth, + borderIntensity: borderIntensity, + borderStyle: borderStyle, + ); if (rectangleAnnotation.opacity < 1) { graphics!.save(); graphics.setTransparency(rectangleAnnotation.opacity); } if (borderIntensity > 0 && borderStyle == 'C') { _drawAppearance( - rectangle, borderWidth, graphics, paintParams, borderIntensity); + rectangle, + borderWidth, + graphics, + paintParams, + borderIntensity, + ); } else { graphics!.drawRectangle( - pen: paintParams.borderPen, - brush: paintParams.backBrush, - bounds: Rect.fromLTWH( - rectangle.x, rectangle.y, rectangle.width, rectangle.height)); + pen: paintParams.borderPen, + brush: paintParams.backBrush, + bounds: Rect.fromLTWH( + rectangle.x, + rectangle.y, + rectangle.width, + rectangle.height, + ), + ); } if (rectangleAnnotation.opacity < 1) { graphics!.restore(); @@ -265,18 +311,27 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } return null; } else { - final Rect nativeRectangle = Rect.fromLTWH(0, 0, - rectangleAnnotation.bounds.width, rectangleAnnotation.bounds.height); + final Rect nativeRectangle = Rect.fromLTWH( + 0, + 0, + rectangleAnnotation.bounds.width, + rectangleAnnotation.bounds.height, + ); final PdfTemplate template = PdfTemplate( - rectangleAnnotation.bounds.width, rectangleAnnotation.bounds.height); + rectangleAnnotation.bounds.width, + rectangleAnnotation.bounds.height, + ); PdfAnnotationHelper.setMatrixToZeroRotation( - PdfTemplateHelper.getHelper(template).content); + PdfTemplateHelper.getHelper(template).content, + ); final PaintParams paintParams = PaintParams(); final PdfGraphics graphics = template.graphics!; if (rectangleAnnotation.border.width > 0 && PdfColorHelper.getHelper(rectangleAnnotation.color).alpha != 0) { - final PdfPen mBorderPen = PdfPen(rectangleAnnotation.color, - width: rectangleAnnotation.border.width); + final PdfPen mBorderPen = PdfPen( + rectangleAnnotation.color, + width: rectangleAnnotation.border.width, + ); paintParams.borderPen = mBorderPen; } PdfBrush? mBackBrush; @@ -289,20 +344,26 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { if (paintParams.foreBrush != PdfSolidBrush(rectangleAnnotation.color)) { paintParams.foreBrush = PdfSolidBrush(rectangleAnnotation.color); } - final Rect rect = Rect.fromLTWH(nativeRectangle.left, nativeRectangle.top, - nativeRectangle.width, nativeRectangle.height); + final Rect rect = Rect.fromLTWH( + nativeRectangle.left, + nativeRectangle.top, + nativeRectangle.width, + nativeRectangle.height, + ); if (rectangleAnnotation.opacity < 1) { graphics.save(); graphics.setTransparency(rectangleAnnotation.opacity); } graphics.drawRectangle( - bounds: Rect.fromLTWH( - rect.left + width, - rect.top + width, - rect.width - rectangleAnnotation.border.width, - rect.height - rectangleAnnotation.border.width), - pen: paintParams.borderPen, - brush: paintParams.backBrush); + bounds: Rect.fromLTWH( + rect.left + width, + rect.top + width, + rect.width - rectangleAnnotation.border.width, + rect.height - rectangleAnnotation.border.width, + ), + pen: paintParams.borderPen, + brush: paintParams.backBrush, + ); if (rectangleAnnotation.opacity < 1) { graphics.restore(); } @@ -311,8 +372,9 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } Map _calculateCloudBorderBounds() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(rectangleAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + rectangleAnnotation, + ); double borderIntensity = 0; String borderStyle = ''; final PdfDictionary dictionary = helper.dictionary!; @@ -322,8 +384,9 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.be])! as PdfDictionary; if (dict.containsKey(PdfDictionaryProperties.s)) { - borderStyle = helper - .getEnumName((dict[PdfDictionaryProperties.s]! as PdfName).name); + borderStyle = helper.getEnumName( + (dict[PdfDictionaryProperties.s]! as PdfName).name, + ); } if (dict.containsKey(PdfDictionaryProperties.i)) { borderIntensity = @@ -331,24 +394,25 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } if (borderIntensity != 0 && borderStyle == 'C') { final Rect cloudRectangle = Rect.fromLTWH( - rectangleAnnotation.bounds.left - - borderIntensity * 5 - - rectangleAnnotation.border.width / 2, - rectangleAnnotation.bounds.top - - borderIntensity * 5 - - rectangleAnnotation.border.width / 2, - rectangleAnnotation.bounds.width + - borderIntensity * 10 + - rectangleAnnotation.border.width, - rectangleAnnotation.bounds.height + - borderIntensity * 10 + - rectangleAnnotation.border.width); + rectangleAnnotation.bounds.left - + borderIntensity * 5 - + rectangleAnnotation.border.width / 2, + rectangleAnnotation.bounds.top - + borderIntensity * 5 - + rectangleAnnotation.border.width / 2, + rectangleAnnotation.bounds.width + + borderIntensity * 10 + + rectangleAnnotation.border.width, + rectangleAnnotation.bounds.height + + borderIntensity * 10 + + rectangleAnnotation.border.width, + ); final double radius = borderIntensity * 5; final List arr = [ radius + rectangleAnnotation.border.width / 2, radius + rectangleAnnotation.border.width / 2, radius + rectangleAnnotation.border.width / 2, - radius + rectangleAnnotation.border.width / 2 + radius + rectangleAnnotation.border.width / 2, ]; dictionary.setProperty(PdfDictionaryProperties.rd, PdfArray(arr)); rectangleAnnotation.bounds = cloudRectangle; @@ -362,30 +426,32 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { final PdfNumber num3 = mRdArray.elements[2]! as PdfNumber; final PdfNumber num4 = mRdArray.elements[3]! as PdfNumber; Rect cloudRectangle = Rect.fromLTWH( - rectangleAnnotation.bounds.left + num1.value!.toDouble(), - rectangleAnnotation.bounds.top + num2.value!.toDouble(), - rectangleAnnotation.bounds.width - num3.value!.toDouble() * 2, - rectangleAnnotation.bounds.height - num4.value!.toDouble() * 2); + rectangleAnnotation.bounds.left + num1.value!.toDouble(), + rectangleAnnotation.bounds.top + num2.value!.toDouble(), + rectangleAnnotation.bounds.width - num3.value!.toDouble() * 2, + rectangleAnnotation.bounds.height - num4.value!.toDouble() * 2, + ); if (borderIntensity != 0 && borderStyle == 'C') { cloudRectangle = Rect.fromLTWH( - cloudRectangle.left - - borderIntensity * 5 - - rectangleAnnotation.border.width / 2, - cloudRectangle.top - - borderIntensity * 5 - - rectangleAnnotation.border.width / 2, - cloudRectangle.width + - borderIntensity * 10 + - rectangleAnnotation.border.width, - cloudRectangle.height + - borderIntensity * 10 + - rectangleAnnotation.border.width); + cloudRectangle.left - + borderIntensity * 5 - + rectangleAnnotation.border.width / 2, + cloudRectangle.top - + borderIntensity * 5 - + rectangleAnnotation.border.width / 2, + cloudRectangle.width + + borderIntensity * 10 + + rectangleAnnotation.border.width, + cloudRectangle.height + + borderIntensity * 10 + + rectangleAnnotation.border.width, + ); final double radius = borderIntensity * 5; final List arr = [ radius + rectangleAnnotation.border.width / 2, radius + rectangleAnnotation.border.width / 2, radius + rectangleAnnotation.border.width / 2, - radius + rectangleAnnotation.border.width / 2 + radius + rectangleAnnotation.border.width / 2, ]; dictionary.setProperty(PdfDictionaryProperties.rd, PdfArray(arr)); } else { @@ -395,38 +461,44 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } return { 'borderIntensity': borderIntensity, - 'borderStyle': borderStyle + 'borderStyle': borderStyle, }; } void _flattenAnnotation(PdfPage? page, PdfTemplate? appearance) { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(rectangleAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + rectangleAnnotation, + ); final PdfDictionary dictionary = helper.dictionary!; if (helper.isLoadedAnnotation) { - final bool isContainsAP = - dictionary.containsKey(PdfDictionaryProperties.ap); + final bool isContainsAP = dictionary.containsKey( + PdfDictionaryProperties.ap, + ); if (isContainsAP && appearance == null) { PdfDictionary? appearanceDictionary = PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.ap]) as PdfDictionary?; if (appearanceDictionary != null) { - appearanceDictionary = PdfCrossTable.dereference( - appearanceDictionary[PdfDictionaryProperties.n]) - as PdfDictionary?; + appearanceDictionary = + PdfCrossTable.dereference( + appearanceDictionary[PdfDictionaryProperties.n], + ) + as PdfDictionary?; if (appearanceDictionary != null) { final PdfStream appearanceStream = appearanceDictionary as PdfStream; appearance = PdfTemplateHelper.fromPdfStream(appearanceStream); - final bool isNormalMatrix = - helper.validateTemplateMatrix(appearanceDictionary); + final bool isNormalMatrix = helper.validateTemplateMatrix( + appearanceDictionary, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } else { rectangleAnnotation.setAppearance = true; appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } @@ -436,24 +508,33 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } else { final bool isNormalMatrix = helper.validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance!).content); + PdfTemplateHelper.getHelper(appearance!).content, + ); helper.flattenAnnotationTemplate(appearance, isNormalMatrix); } } else { page!.graphics.save(); final Rect rectangle = helper.calculateTemplateBounds( - rectangleAnnotation.bounds, page, appearance, true); + rectangleAnnotation.bounds, + page, + appearance, + true, + ); if (rectangleAnnotation.opacity < 1) { page.graphics.setTransparency(rectangleAnnotation.opacity); } page.graphics.drawPdfTemplate( - appearance!, Offset(rectangle.left, rectangle.top), rectangle.size); + appearance!, + Offset(rectangle.left, rectangle.top), + rectangle.size, + ); page.annotations.remove(rectangleAnnotation); page.graphics.restore(); } @@ -461,14 +542,22 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { // Obtain Style from annotation PdfRectangle _obtainStyle( - PdfPen mBorderPen, PdfRectangle rectangle, double borderWidth, - {double? borderIntensity, String? borderStyle}) { - if (PdfAnnotationHelper.getHelper(rectangleAnnotation) - .dictionary! - .containsKey(PdfDictionaryProperties.bs)) { - final PdfDictionary? bSDictionary = PdfCrossTable.dereference( - PdfAnnotationHelper.getHelper(rectangleAnnotation) - .dictionary![PdfDictionaryProperties.bs]) as PdfDictionary?; + PdfPen mBorderPen, + PdfRectangle rectangle, + double borderWidth, { + double? borderIntensity, + String? borderStyle, + }) { + if (PdfAnnotationHelper.getHelper( + rectangleAnnotation, + ).dictionary!.containsKey(PdfDictionaryProperties.bs)) { + final PdfDictionary? bSDictionary = + PdfCrossTable.dereference( + PdfAnnotationHelper.getHelper( + rectangleAnnotation, + ).dictionary![PdfDictionaryProperties.bs], + ) + as PdfDictionary?; if (bSDictionary != null && bSDictionary.containsKey(PdfDictionaryProperties.d)) { final PdfArray dashPatternArray = @@ -477,7 +566,8 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { final List dashPattern = []; for (int i = 0; i < dashPatternArray.count; i++) { dashPattern.add( - (dashPatternArray.elements[i]! as PdfNumber).value!.toDouble()); + (dashPatternArray.elements[i]! as PdfNumber).value!.toDouble(), + ); } mBorderPen.dashStyle = PdfDashStyle.dash; mBorderPen.dashPattern = dashPattern; @@ -502,8 +592,13 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { } // Draw appearance for annotation - void _drawAppearance(PdfRectangle rectangle, double borderWidth, - PdfGraphics? graphics, PaintParams paintParams, double borderIntensity) { + void _drawAppearance( + PdfRectangle rectangle, + double borderWidth, + PdfGraphics? graphics, + PaintParams paintParams, + double borderIntensity, + ) { final PdfPath graphicsPath = PdfPath(); graphicsPath.addRectangle(rectangle.rect); final double radius = borderIntensity * 4.25; @@ -513,29 +608,38 @@ class PdfRectangleAnnotationHelper extends PdfAnnotationHelper { PdfPathHelper.getHelper(graphicsPath).points.removeAt(4); } final List points = []; - for (int i = 0; - i < PdfPathHelper.getHelper(graphicsPath).points.length; - i++) { - points.add(Offset(PdfPathHelper.getHelper(graphicsPath).points[i].dx, - -PdfPathHelper.getHelper(graphicsPath).points[i].dy)); + for ( + int i = 0; + i < PdfPathHelper.getHelper(graphicsPath).points.length; + i++ + ) { + points.add( + Offset( + PdfPathHelper.getHelper(graphicsPath).points[i].dx, + -PdfPathHelper.getHelper(graphicsPath).points[i].dy, + ), + ); } PdfAnnotationHelper.getHelper(rectangleAnnotation).drawCloudStyle( - graphics!, - paintParams.backBrush, - paintParams.borderPen, - radius, - 0.833, - points, - false); + graphics!, + paintParams.backBrush, + paintParams.borderPen, + radius, + 0.833, + points, + false, + ); } else { graphics!.drawRectangle( - pen: paintParams.borderPen, - brush: paintParams.backBrush, - bounds: Rect.fromLTWH( - rectangle.x + borderWidth, - rectangle.y, - rectangle.width - rectangleAnnotation.border.width, - rectangle.height)); + pen: paintParams.borderPen, + brush: paintParams.backBrush, + bounds: Rect.fromLTWH( + rectangle.x + borderWidth, + rectangle.y, + rectangle.width - rectangleAnnotation.border.width, + rectangle.height, + ), + ); } } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_markup_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_markup_annotation.dart index a4816bc51..cad794afe 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_markup_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_markup_annotation.dart @@ -54,34 +54,41 @@ class PdfTextMarkupAnnotation extends PdfAnnotation { /// final List bytes = document.saveSync(); /// document.dispose(); /// ``` - PdfTextMarkupAnnotation(Rect bounds, String text, PdfColor color, - {String? author, - String? subject, - double? opacity, - DateTime? modifiedDate, - bool? setAppearance, - List? boundsCollection, - List? flags, - PdfTextMarkupAnnotationType? textMarkupAnnotationType}) { + PdfTextMarkupAnnotation( + Rect bounds, + String text, + PdfColor color, { + String? author, + String? subject, + double? opacity, + DateTime? modifiedDate, + bool? setAppearance, + List? boundsCollection, + List? flags, + PdfTextMarkupAnnotationType? textMarkupAnnotationType, + }) { _helper = PdfTextMarkupAnnotationHelper( - this, - bounds, - text, - color, - author, - subject, - opacity, - modifiedDate, - setAppearance, - flags, - textMarkupAnnotationType); + this, + bounds, + text, + color, + author, + subject, + opacity, + modifiedDate, + setAppearance, + flags, + textMarkupAnnotationType, + ); if (boundsCollection != null) { this.boundsCollection = boundsCollection; } } PdfTextMarkupAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { _helper = PdfTextMarkupAnnotationHelper._(this, dictionary, crossTable); } @@ -120,37 +127,42 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { //Constructor /// internal constructor PdfTextMarkupAnnotationHelper( - this.textMarkupAnnotation, - Rect bounds, - String text, - PdfColor color, - String? author, - String? subject, - double? opacity, - DateTime? modifiedDate, - bool? setAppearance, - List? flags, - PdfTextMarkupAnnotationType? textMarkupAnnotationType) - : super(textMarkupAnnotation) { + this.textMarkupAnnotation, + Rect bounds, + String text, + PdfColor color, + String? author, + String? subject, + double? opacity, + DateTime? modifiedDate, + bool? setAppearance, + List? flags, + PdfTextMarkupAnnotationType? textMarkupAnnotationType, + ) : super(textMarkupAnnotation) { initializeAnnotation( - bounds: bounds, - text: text, - color: color, - author: author, - subject: subject, - modifiedDate: modifiedDate, - opacity: opacity, - flags: flags, - setAppearance: setAppearance); + bounds: bounds, + text: text, + color: color, + author: author, + subject: subject, + modifiedDate: modifiedDate, + opacity: opacity, + flags: flags, + setAppearance: setAppearance, + ); this.textMarkupAnnotationType = textMarkupAnnotationType ?? PdfTextMarkupAnnotationType.highlight; - dictionary!.setProperty(PdfDictionaryProperties.subtype, - PdfName(getEnumName(this.textMarkupAnnotationType.toString()))); + dictionary!.setProperty( + PdfDictionaryProperties.subtype, + PdfName(getEnumName(this.textMarkupAnnotationType.toString())), + ); } - PdfTextMarkupAnnotationHelper._(this.textMarkupAnnotation, - PdfDictionary dictionary, PdfCrossTable crossTable) - : super(textMarkupAnnotation) { + PdfTextMarkupAnnotationHelper._( + this.textMarkupAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(textMarkupAnnotation) { initializeExistingAnnotation(dictionary, crossTable); } @@ -167,13 +179,16 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { /// internal method static PdfTextMarkupAnnotationHelper getHelper( - PdfTextMarkupAnnotation annotation) { + PdfTextMarkupAnnotation annotation, + ) { return annotation._helper; } /// internal method static PdfTextMarkupAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfTextMarkupAnnotation._(dictionary, crossTable); } @@ -203,16 +218,18 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { } /// Gets text markup annotation Type. - PdfTextMarkupAnnotationType get textMarkupAnnotationType => isLoadedAnnotation - ? _obtainTextMarkupAnnotationType() - : _textMarkupAnnotationType!; + PdfTextMarkupAnnotationType get textMarkupAnnotationType => + isLoadedAnnotation + ? _obtainTextMarkupAnnotationType() + : _textMarkupAnnotationType!; /// Sets text markup annotation Type. set textMarkupAnnotationType(PdfTextMarkupAnnotationType value) { _textMarkupAnnotationType = value; if (isLoadedAnnotation) { - dictionary![PdfDictionaryProperties.subtype] = - PdfName(getEnumName(_textMarkupAnnotationType)); + dictionary![PdfDictionaryProperties.subtype] = PdfName( + getEnumName(_textMarkupAnnotationType), + ); } } @@ -223,8 +240,12 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { final double pageHeight = pageSize.height; final PdfMargins margins = obtainMargin()!; if (bounds.width == 0 && bounds.height == 0) { - bounds = - Rect.fromLTWH(bounds.left, bounds.top, bounds.width, bounds.height); + bounds = Rect.fromLTWH( + bounds.left, + bounds.top, + bounds.width, + bounds.height, + ); } if (_boundsCollection.isEmpty && !_boundsCollection.contains(bounds)) { _boundsCollection.add(bounds); @@ -250,8 +271,10 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { points = PdfArray(textQuadLocation); dictionary!.setProperty(PdfDictionaryProperties.quadPoints, points); } else { - final List textQuadLocation = - List.filled(_boundsCollection.length * 8, 0); + final List textQuadLocation = List.filled( + _boundsCollection.length * 8, + 0, + ); final double pageHeight = pageSize.height; for (int i = 0; i < _boundsCollection.length; i++) { final double locationX = _boundsCollection[i].left, @@ -267,7 +290,9 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { textQuadLocation[7 + (i * 8)] = textQuadLocation[5 + (i * 8)]; } dictionary!.setProperty( - PdfDictionaryProperties.quadPoints, PdfArray(textQuadLocation)); + PdfDictionaryProperties.quadPoints, + PdfArray(textQuadLocation), + ); } } @@ -275,7 +300,8 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { final List collection = []; if (dictionary!.containsKey(PdfDictionaryProperties.quadPoints)) { final IPdfPrimitive? points = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.quadPoints]); + dictionary![PdfDictionaryProperties.quadPoints], + ); double x, y, width, height; if (points != null && points is PdfArray) { for (int i = 0; i < (points.count / 8).round(); i++) { @@ -333,11 +359,12 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { /// internal method void save() { - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(textMarkupAnnotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + textMarkupAnnotation, + ); if (PdfAnnotationCollectionHelper.getHelper( - textMarkupAnnotation.page!.annotations) - .flatten) { + textMarkupAnnotation.page!.annotations, + ).flatten) { helper.flatten = true; } if (!helper.isLoadedAnnotation) { @@ -369,8 +396,10 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { } else { if (appearance != null) { textMarkupAnnotation.appearance.normal = appearance; - dictionary!.setProperty(PdfDictionaryProperties.ap, - PdfReferenceHolder(textMarkupAnnotation.appearance)); + dictionary!.setProperty( + PdfDictionaryProperties.ap, + PdfReferenceHolder(textMarkupAnnotation.appearance), + ); } } } @@ -398,7 +427,9 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { void _saveTextMarkUpDictionary() { dictionary!.setProperty( - PdfDictionaryProperties.subtype, PdfName(_getMarkupAnnotationType())); + PdfDictionaryProperties.subtype, + PdfName(_getMarkupAnnotationType()), + ); } PdfTemplate? _createAppearance() { @@ -418,12 +449,15 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { } else { if (dictionary!.containsKey(PdfDictionaryProperties.quadPoints)) { final IPdfPrimitive? mQuadPoints = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.quadPoints]); + dictionary![PdfDictionaryProperties.quadPoints], + ); if (mQuadPoints != null && mQuadPoints is PdfArray) { for (int i = 0; i < (mQuadPoints.count / 8); i++) { if (isLoadedAnnotation) { - final List quadPoints = - List.filled(mQuadPoints.count ~/ 2, Offset.zero); + final List quadPoints = List.filled( + mQuadPoints.count ~/ 2, + Offset.zero, + ); int j = 0; for (int k = 0; k < mQuadPoints.count;) { final double x1 = @@ -440,19 +474,23 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { height = rectangle.height; width = rectangle.width; } else { - x = ((mQuadPoints[4 + (i * 8)]! as PdfNumber).value! - - (mQuadPoints[0 + (i * 8)]! as PdfNumber).value!) - .toDouble(); - y = ((mQuadPoints[5 + (i * 8)]! as PdfNumber).value! - - (mQuadPoints[1 + (i * 8)]! as PdfNumber).value!) - .toDouble(); + x = + ((mQuadPoints[4 + (i * 8)]! as PdfNumber).value! - + (mQuadPoints[0 + (i * 8)]! as PdfNumber).value!) + .toDouble(); + y = + ((mQuadPoints[5 + (i * 8)]! as PdfNumber).value! - + (mQuadPoints[1 + (i * 8)]! as PdfNumber).value!) + .toDouble(); height = sqrt((x * x) + (y * y)); - x = ((mQuadPoints[6 + (i * 8)]! as PdfNumber).value! - - (mQuadPoints[4 + (i * 8)]! as PdfNumber).value!) - .toDouble(); - y = ((mQuadPoints[7 + (i * 8)]! as PdfNumber).value! - - (mQuadPoints[5 + (i * 8)]! as PdfNumber).value!) - .toDouble(); + x = + ((mQuadPoints[6 + (i * 8)]! as PdfNumber).value! - + (mQuadPoints[4 + (i * 8)]! as PdfNumber).value!) + .toDouble(); + y = + ((mQuadPoints[7 + (i * 8)]! as PdfNumber).value! - + (mQuadPoints[5 + (i * 8)]! as PdfNumber).value!) + .toDouble(); width = sqrt((x * x) + (y * y)); bounds = Rect.fromLTWH(bounds.left, bounds.top, width, height); } @@ -462,7 +500,8 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { } final PdfTemplate template = PdfTemplate(width, height); PdfAnnotationHelper.setMatrixToZeroRotation( - PdfTemplateHelper.getHelper(template).content); + PdfTemplateHelper.getHelper(template).content, + ); final PdfGraphics graphics = template.graphics!; graphics.setTransparency(opacity, mode: PdfBlendMode.multiply); if (boundsCollection.length > 1) { @@ -470,82 +509,108 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.highlight) { graphics.drawRectangle( - brush: PdfSolidBrush(color), - bounds: Rect.fromLTWH( - boundsCollection[i].left - rectangle!.x, - boundsCollection[i].top - rectangle.y, - boundsCollection[i].width, - boundsCollection[i].height)); + brush: PdfSolidBrush(color), + bounds: Rect.fromLTWH( + boundsCollection[i].left - rectangle!.x, + boundsCollection[i].top - rectangle.y, + boundsCollection[i].width, + boundsCollection[i].height, + ), + ); } else if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.underline) { graphics.drawLine( - PdfPen(color, width: boundsCollection[i].height * 0.05), - Offset( - boundsCollection[i].left - rectangle!.x, - (boundsCollection[i].top - rectangle.y) + - (boundsCollection[i].height - - ((boundsCollection[i].height / 2) / 3))), - Offset( - boundsCollection[i].width + - (boundsCollection[i].left - rectangle.x), - (boundsCollection[i].top - rectangle.y) + - (boundsCollection[i].height - - ((boundsCollection[i].height / 2) / 3)))); + PdfPen(color, width: boundsCollection[i].height * 0.05), + Offset( + boundsCollection[i].left - rectangle!.x, + (boundsCollection[i].top - rectangle.y) + + (boundsCollection[i].height - + ((boundsCollection[i].height / 2) / 3)), + ), + Offset( + boundsCollection[i].width + + (boundsCollection[i].left - rectangle.x), + (boundsCollection[i].top - rectangle.y) + + (boundsCollection[i].height - + ((boundsCollection[i].height / 2) / 3)), + ), + ); } else if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.strikethrough) { graphics.drawLine( - PdfPen(color, width: boundsCollection[i].height * 0.05), - Offset( - boundsCollection[i].left - rectangle!.x, - (boundsCollection[i].top - rectangle.y) + - (boundsCollection[i].height - - (boundsCollection[i].height / 2))), - Offset( - boundsCollection[i].width + - (boundsCollection[i].left - rectangle.x), - (boundsCollection[i].top - rectangle.y) + - (boundsCollection[i].height - - (boundsCollection[i].height / 2)))); + PdfPen(color, width: boundsCollection[i].height * 0.05), + Offset( + boundsCollection[i].left - rectangle!.x, + (boundsCollection[i].top - rectangle.y) + + (boundsCollection[i].height - + (boundsCollection[i].height / 2)), + ), + Offset( + boundsCollection[i].width + + (boundsCollection[i].left - rectangle.x), + (boundsCollection[i].top - rectangle.y) + + (boundsCollection[i].height - + (boundsCollection[i].height / 2)), + ), + ); } else if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.squiggly) { - final PdfPen pdfPen = - PdfPen(color, width: boundsCollection[i].height * 0.02); + final PdfPen pdfPen = PdfPen( + color, + width: boundsCollection[i].height * 0.02, + ); graphics.save(); - graphics.translateTransform(boundsCollection[i].left - rectangle!.x, - boundsCollection[i].top - rectangle.y); + graphics.translateTransform( + boundsCollection[i].left - rectangle!.x, + boundsCollection[i].top - rectangle.y, + ); graphics.setClip( - bounds: Rect.fromLTWH(0, 0, boundsCollection[i].width, - boundsCollection[i].height)); + bounds: Rect.fromLTWH( + 0, + 0, + boundsCollection[i].width, + boundsCollection[i].height, + ), + ); graphics.drawPath( - _drawSquiggly( - boundsCollection[i].width, boundsCollection[i].height), - pen: pdfPen); + _drawSquiggly( + boundsCollection[i].width, + boundsCollection[i].height, + ), + pen: pdfPen, + ); graphics.restore(); } } } else { if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.highlight) { graphics.drawRectangle( - brush: PdfSolidBrush(color), - bounds: Rect.fromLTWH(0, 0, width, height)); + brush: PdfSolidBrush(color), + bounds: Rect.fromLTWH(0, 0, width, height), + ); } else if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.underline) { graphics.drawLine( - PdfPen(color, width: height * 0.05), - Offset(0, height - ((height / 2) / 3)), - Offset(width, height - ((height / 2) / 3))); + PdfPen(color, width: height * 0.05), + Offset(0, height - ((height / 2) / 3)), + Offset(width, height - ((height / 2) / 3)), + ); } else if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.strikethrough) { - graphics.drawLine(PdfPen(color, width: height * 0.05), - Offset(0, height / 2), Offset(width, height / 2)); + graphics.drawLine( + PdfPen(color, width: height * 0.05), + Offset(0, height / 2), + Offset(width, height / 2), + ); } else if (textMarkupAnnotationType == PdfTextMarkupAnnotationType.squiggly) { final PdfPen pdfPen = PdfPen(color, width: height * 0.02); graphics.drawPath(_drawSquiggly(width, height), pen: pdfPen); } if (isLoadedAnnotation) { - dictionary![PdfDictionaryProperties.rect] = - PdfArray.fromRectangle(rectangle!); + dictionary![PdfDictionaryProperties.rect] = PdfArray.fromRectangle( + rectangle!, + ); } } return template; @@ -558,15 +623,19 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { width = width + 1; } final PdfPath path = PdfPath(); - final List mPathPoints = - List.filled(((width / height) * 16).ceil(), Offset.zero); + final List mPathPoints = List.filled( + ((width / height) * 16).ceil(), + Offset.zero, + ); final double length = width / (mPathPoints.length / 2); final double location = (length + length) * 0.6; double zigZag = location; double x = 0; for (int i = 0; i < mPathPoints.length; i++, x += length) { - mPathPoints[i] = - Offset(x, ((height - location) + zigZag) - (height * 0.02)); + mPathPoints[i] = Offset( + x, + ((height - location) + zigZag) - (height * 0.02), + ); if (zigZag == 0) { zigZag = location; } else { @@ -581,13 +650,20 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { if (!isLoadedAnnotation) { if (appearance != null) { page.graphics.save(); - final Rect rectangle = - calculateTemplateBounds(bounds, page, appearance, true); + final Rect rectangle = calculateTemplateBounds( + bounds, + page, + appearance, + true, + ); if (opacity < 1) { page.graphics.setTransparency(opacity); } page.graphics.drawPdfTemplate( - appearance, Offset(rectangle.left, rectangle.top), rectangle.size); + appearance, + Offset(rectangle.left, rectangle.top), + rectangle.size, + ); page.annotations.remove(textMarkupAnnotation); page.graphics.restore(); } @@ -595,23 +671,29 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { if (dictionary != null && dictionary!.containsKey(PdfDictionaryProperties.ap) && appearance == null) { - IPdfPrimitive? appearanceDictionary = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.ap]); + IPdfPrimitive? appearanceDictionary = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.ap], + ); if (appearanceDictionary != null && appearanceDictionary is PdfDictionary) { appearanceDictionary = PdfCrossTable.dereference( - appearanceDictionary[PdfDictionaryProperties.n]); + appearanceDictionary[PdfDictionaryProperties.n], + ); if (appearanceDictionary != null && appearanceDictionary is PdfStream) { appearance = PdfTemplateHelper.fromPdfStream(appearanceDictionary); - final bool isNormalMatrix = - validateTemplateMatrix(appearanceDictionary); + final bool isNormalMatrix = validateTemplateMatrix( + appearanceDictionary, + ); if (isNormalMatrix && page.rotation != PdfPageRotateAngle.rotateAngle0) { flattenAnnotationTemplate(appearance, isNormalMatrix); } else if (isNormalMatrix && isValidTemplateMatrix( - appearanceDictionary, bounds.topLeft, appearance)) { + appearanceDictionary, + bounds.topLeft, + appearance, + )) { flattenAnnotationTemplate(appearance, isNormalMatrix); } } else { @@ -619,7 +701,8 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); flattenAnnotationTemplate(appearance, isNormalMatrix); } } @@ -630,26 +713,30 @@ class PdfTextMarkupAnnotationHelper extends PdfAnnotationHelper { appearance = _createAppearance(); if (appearance != null) { final bool isNormalMatrix = validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); flattenAnnotationTemplate(appearance, isNormalMatrix); } } else if (!dictionary!.containsKey(PdfDictionaryProperties.ap) && appearance != null) { final bool isNormalMatrix = validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); flattenAnnotationTemplate(appearance, isNormalMatrix); } else if (dictionary!.containsKey(PdfDictionaryProperties.ap) && appearance != null) { final bool isNormalMatrix = validateTemplateMatrix( - PdfTemplateHelper.getHelper(appearance).content); + PdfTemplateHelper.getHelper(appearance).content, + ); flattenAnnotationTemplate(appearance, isNormalMatrix); } } } PdfTextMarkupAnnotationType _obtainTextMarkupAnnotationType() { - final IPdfPrimitive? annotType = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.subtype]); + final IPdfPrimitive? annotType = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.subtype], + ); if (annotType != null && annotType is PdfName) { final String aType = annotType.name.toString(); return _getTextMarkupAnnotation(aType); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_web_link.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_web_link.dart index d39f37d4f..978ab2008 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_web_link.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_text_web_link.dart @@ -59,20 +59,24 @@ class PdfTextWebLink extends PdfAnnotation { /// //Dispose the document. /// document.dispose(); /// ``` - PdfTextWebLink( - {required String url, - String? text, - PdfBrush? brush, - PdfFont? font, - PdfPen? pen, - PdfStringFormat? format}) { + PdfTextWebLink({ + required String url, + String? text, + PdfBrush? brush, + PdfFont? font, + PdfPen? pen, + PdfStringFormat? format, + }) { _helper = PdfTextWebLinkHelper(this); _initializeWebLink(text, font, pen, brush, format); this.url = url; } PdfTextWebLink._( - PdfDictionary dictionary, PdfCrossTable crossTable, String? annotText) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String? annotText, + ) { _helper = PdfTextWebLinkHelper._(this, dictionary, crossTable); text = annotText != null && annotText.isNotEmpty ? annotText : ''; } @@ -231,8 +235,13 @@ class PdfTextWebLink extends PdfAnnotation { } // implementation - void _initializeWebLink(String? annotText, PdfFont? font, PdfPen? pen, - PdfBrush? brush, PdfStringFormat? format) { + void _initializeWebLink( + String? annotText, + PdfFont? font, + PdfPen? pen, + PdfBrush? brush, + PdfStringFormat? format, + ) { text = annotText != null && annotText.isNotEmpty ? annotText : ''; if (font != null) { this.font = font; @@ -275,7 +284,11 @@ class PdfTextWebLink extends PdfAnnotation { font != null ? font! : PdfStandardFont(PdfFontFamily.helvetica, 8); final Size textSize = pdfFont.measureString(text); final Rect rect = Rect.fromLTWH( - location.dx, location.dy, textSize.width, textSize.height); + location.dx, + location.dy, + textSize.width, + textSize.height, + ); _uriAnnotation = PdfUriAnnotation(bounds: rect, uri: url); _uriAnnotation.border = PdfAnnotationBorder(0, 0, 0); page.annotations.add(_uriAnnotation); @@ -284,8 +297,14 @@ class PdfTextWebLink extends PdfAnnotation { } void _drawInternal(PdfGraphics graphics, Rect bounds, PdfFont pdfFont) { - graphics.drawString(text, pdfFont, - pen: pen, brush: brush, bounds: bounds, format: stringFormat); + graphics.drawString( + text, + pdfFont, + pen: pen, + brush: brush, + bounds: bounds, + format: stringFormat, + ); } String? _obtainUrl() { @@ -319,8 +338,10 @@ class PdfTextWebLinkHelper extends PdfAnnotationHelper { /// internal constructor PdfTextWebLinkHelper._( - this.webLinkHelper, PdfDictionary dictionary, PdfCrossTable crossTable) - : super(webLinkHelper) { + this.webLinkHelper, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(webLinkHelper) { initializeExistingAnnotation(dictionary, crossTable); } @@ -333,7 +354,10 @@ class PdfTextWebLinkHelper extends PdfAnnotationHelper { /// internal method static PdfTextWebLink load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfTextWebLink._(dictionary, crossTable, text); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_uri_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_uri_annotation.dart index 828624668..9b8d80576 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_uri_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/pdf_uri_annotation.dart @@ -24,7 +24,10 @@ class PdfUriAnnotation extends PdfActionLinkAnnotation { } PdfUriAnnotation._( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { _helper = PdfUriAnnotationHelper._(this, dictionary, crossTable); super.text = text; } @@ -51,8 +54,11 @@ class PdfUriAnnotation extends PdfActionLinkAnnotation { if (_uri != value) { _uri = value; if (tempDictionary.containsKey(PdfDictionaryProperties.a)) { - final PdfDictionary? dictionary = PdfCrossTable.dereference( - tempDictionary[PdfDictionaryProperties.a]) as PdfDictionary?; + final PdfDictionary? dictionary = + PdfCrossTable.dereference( + tempDictionary[PdfDictionaryProperties.a], + ) + as PdfDictionary?; if (dictionary != null) { dictionary.setString(PdfDictionaryProperties.uri, _uri); dictionary.modify(); @@ -66,8 +72,11 @@ class PdfUriAnnotation extends PdfActionLinkAnnotation { if (helper.isLoadedAnnotation) { PdfDictionary? dictionary = tempDictionary; if (tempDictionary.containsKey(PdfDictionaryProperties.a)) { - dictionary = PdfCrossTable.dereference( - tempDictionary[PdfDictionaryProperties.a]) as PdfDictionary?; + dictionary = + PdfCrossTable.dereference( + tempDictionary[PdfDictionaryProperties.a], + ) + as PdfDictionary?; if (dictionary != null) { dictionary.setString(PdfDictionaryProperties.uri, _uri); } @@ -135,20 +144,26 @@ class PdfUriAnnotation extends PdfActionLinkAnnotation { class PdfUriAnnotationHelper extends PdfActionLinkAnnotationHelper { /// internal constructor PdfUriAnnotationHelper(this.uriAnnotation, Rect bounds) - : super(uriAnnotation, bounds) { + : super(uriAnnotation, bounds) { _uriAction ??= PdfUriAction(); - dictionary!.setProperty(PdfName(PdfDictionaryProperties.subtype), - PdfName(PdfDictionaryProperties.link)); + dictionary!.setProperty( + PdfName(PdfDictionaryProperties.subtype), + PdfName(PdfDictionaryProperties.link), + ); final IPdfPrimitive? element = IPdfWrapper.getElement(_uriAction!); if (element == null) { IPdfWrapper.setElement( - _uriAction!, PdfActionHelper.getHelper(_uriAction!).dictionary); + _uriAction!, + PdfActionHelper.getHelper(_uriAction!).dictionary, + ); } dictionary!.setProperty(PdfName(PdfDictionaryProperties.a), element); } PdfUriAnnotationHelper._( - this.uriAnnotation, PdfDictionary dictionary, PdfCrossTable crossTable) - : super.load(uriAnnotation, dictionary, crossTable); + this.uriAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super.load(uriAnnotation, dictionary, crossTable); /// internal field late PdfUriAnnotation uriAnnotation; @@ -160,7 +175,10 @@ class PdfUriAnnotationHelper extends PdfActionLinkAnnotationHelper { /// internal method static PdfUriAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable, String text) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + String text, + ) { return PdfUriAnnotation._(dictionary, crossTable, text); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_annotation.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_annotation.dart index b72b278bf..063f425ba 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_annotation.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_annotation.dart @@ -57,10 +57,12 @@ class WidgetAnnotation extends PdfAnnotation { _parent = value; _parent != null ? PdfAnnotationHelper.getHelper(this).dictionary!.setProperty( - PdfDictionaryProperties.parent, PdfReferenceHolder(_parent)) - : PdfAnnotationHelper.getHelper(this) - .dictionary! - .remove(PdfDictionaryProperties.parent); + PdfDictionaryProperties.parent, + PdfReferenceHolder(_parent), + ) + : PdfAnnotationHelper.getHelper( + this, + ).dictionary!.remove(PdfDictionaryProperties.parent); } } @@ -69,9 +71,10 @@ class WidgetAnnotation extends PdfAnnotation { set textAlignment(PdfTextAlignment? value) { if (alignment != value) { alignment = value; - PdfAnnotationHelper.getHelper(this) - .dictionary! - .setProperty(PdfDictionaryProperties.q, PdfNumber(alignment!.index)); + PdfAnnotationHelper.getHelper(this).dictionary!.setProperty( + PdfDictionaryProperties.q, + PdfNumber(alignment!.index), + ); } } @@ -83,8 +86,9 @@ class WidgetAnnotation extends PdfAnnotation { set highlightMode(PdfHighlightMode? value) { _highlightMode = value; PdfAnnotationHelper.getHelper(this).dictionary!.setName( - PdfName(PdfDictionaryProperties.h), - _helper.highlightModeToString(_highlightMode)); + PdfName(PdfDictionaryProperties.h), + _helper.highlightModeToString(_highlightMode), + ); } /// internal property @@ -103,7 +107,9 @@ class WidgetAnnotation extends PdfAnnotation { if (_appearState != value) { _appearState = value; PdfAnnotationHelper.getHelper(this).dictionary!.setName( - PdfName(PdfDictionaryProperties.usageApplication), _appearState); + PdfName(PdfDictionaryProperties.usageApplication), + _appearState, + ); } } @@ -111,9 +117,9 @@ class WidgetAnnotation extends PdfAnnotation { PdfAnnotationActions? get actions { if (_actions == null) { _actions = PdfAnnotationActions(); - PdfAnnotationHelper.getHelper(this) - .dictionary! - .setProperty(PdfDictionaryProperties.aa, _actions); + PdfAnnotationHelper.getHelper( + this, + ).dictionary!.setProperty(PdfDictionaryProperties.aa, _actions); } return _actions; } @@ -121,9 +127,9 @@ class WidgetAnnotation extends PdfAnnotation { set actions(PdfAnnotationActions? value) { if (value != null) { _actions = value; - PdfAnnotationHelper.getHelper(this) - .dictionary! - .setProperty(PdfDictionaryProperties.aa, _actions); + PdfAnnotationHelper.getHelper( + this, + ).dictionary!.setProperty(PdfDictionaryProperties.aa, _actions); } } } @@ -134,17 +140,23 @@ class WidgetAnnotationHelper extends PdfAnnotationHelper { WidgetAnnotationHelper(this.widgetAnnotation) : super(widgetAnnotation) { initializeAnnotation(); dictionary!.setNumber(PdfDictionaryProperties.f, 4); //Sets print. - dictionary!.setProperty(PdfDictionaryProperties.subtype, - PdfName(PdfDictionaryProperties.widget)); + dictionary!.setProperty( + PdfDictionaryProperties.subtype, + PdfName(PdfDictionaryProperties.widget), + ); widgetAnnotation.widgetBorder ??= PdfAnnotationBorderHelper.getWidgetBorder(); - dictionary! - .setProperty(PdfDictionaryProperties.bs, widgetAnnotation.widgetBorder); + dictionary!.setProperty( + PdfDictionaryProperties.bs, + widgetAnnotation.widgetBorder, + ); widgetAppearance = WidgetAppearance(); } WidgetAnnotationHelper._( - this.widgetAnnotation, PdfDictionary dictionary, PdfCrossTable crossTable) - : super(widgetAnnotation) { + this.widgetAnnotation, + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) : super(widgetAnnotation) { initializeExistingAnnotation(dictionary, crossTable); } @@ -165,7 +177,9 @@ class WidgetAnnotationHelper extends PdfAnnotationHelper { /// internal method static WidgetAnnotation load( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return WidgetAnnotation._(dictionary, crossTable); } @@ -188,7 +202,8 @@ class WidgetAnnotationHelper extends PdfAnnotationHelper { PdfDocumentHelper.getHelper(document).conformanceLevel == PdfConformanceLevel.a3b)) { throw ArgumentError( - "The appearance dictionary doesn't contain an entry in the conformance PDF."); + "The appearance dictionary doesn't contain an entry in the conformance PDF.", + ); } helper.saveAnnotation(); _onBeginSave(); @@ -200,21 +215,23 @@ class WidgetAnnotationHelper extends PdfAnnotationHelper { dictionary.setProperty(PdfDictionaryProperties.ap, null); final PdfAppearance? tempAppearance = helper.appearance; dictionary.setProperty( - PdfDictionaryProperties.ap, - tempAppearance != null && - PdfAppearanceHelper.getHelper(tempAppearance) - .templateNormal != - null - ? tempAppearance - : null); + PdfDictionaryProperties.ap, + tempAppearance != null && + PdfAppearanceHelper.getHelper(tempAppearance).templateNormal != + null + ? tempAppearance + : null, + ); if (widgetAppearance != null && widgetAppearance!.dictionary!.count > 0) { dictionary.setProperty(PdfDictionaryProperties.mk, widgetAppearance); } dictionary.setProperty(PdfDictionaryProperties.usageApplication, null); } if (pdfDefaultAppearance != null) { - dictionary.setProperty(PdfDictionaryProperties.da, - PdfString(pdfDefaultAppearance!.getString())); + dictionary.setProperty( + PdfDictionaryProperties.da, + PdfString(pdfDefaultAppearance!.getString()), + ); } } @@ -241,11 +258,14 @@ class WidgetAnnotationHelper extends PdfAnnotationHelper { PdfHighlightMode _obtainHighlightMode() { PdfHighlightMode mode = PdfHighlightMode.noHighlighting; - if (PdfAnnotationHelper.getHelper(base) - .dictionary! - .containsKey(PdfDictionaryProperties.h)) { - final PdfName name = PdfAnnotationHelper.getHelper(base) - .dictionary![PdfDictionaryProperties.h]! as PdfName; + if (PdfAnnotationHelper.getHelper( + base, + ).dictionary!.containsKey(PdfDictionaryProperties.h)) { + final PdfName name = + PdfAnnotationHelper.getHelper( + base, + ).dictionary![PdfDictionaryProperties.h]! + as PdfName; switch (name.name) { case 'I': mode = PdfHighlightMode.invert; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_appearance.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_appearance.dart index e50da1f83..6c0bb474e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_appearance.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/widget_appearance.dart @@ -9,7 +9,9 @@ class WidgetAppearance implements IPdfWrapper { /// internal Constructor WidgetAppearance() : super() { dictionary!.setProperty( - PdfDictionaryProperties.bc, PdfColorHelper.toArray(_borderColor)); + PdfDictionaryProperties.bc, + PdfColorHelper.toArray(_borderColor), + ); } /// internal field @@ -32,10 +34,14 @@ class WidgetAppearance implements IPdfWrapper { if (_borderColor != value) { _borderColor = value; PdfColorHelper.getHelper(value).alpha == 0 - ? dictionary! - .setProperty(PdfDictionaryProperties.bc, PdfArray([])) + ? dictionary!.setProperty( + PdfDictionaryProperties.bc, + PdfArray([]), + ) : dictionary!.setProperty( - PdfDictionaryProperties.bc, PdfColorHelper.toArray(_borderColor)); + PdfDictionaryProperties.bc, + PdfColorHelper.toArray(_borderColor), + ); } } @@ -45,12 +51,16 @@ class WidgetAppearance implements IPdfWrapper { if (_backColor != value) { _backColor = value; if (PdfColorHelper.getHelper(_backColor).alpha == 0) { - dictionary! - .setProperty(PdfDictionaryProperties.bc, PdfArray([0, 0, 0])); + dictionary!.setProperty( + PdfDictionaryProperties.bc, + PdfArray([0, 0, 0]), + ); dictionary!.remove(PdfDictionaryProperties.bg); } else { dictionary!.setProperty( - PdfDictionaryProperties.bg, PdfColorHelper.toArray(_backColor)); + PdfDictionaryProperties.bg, + PdfColorHelper.toArray(_backColor), + ); } } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/xfdf_parser.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/xfdf_parser.dart index adf8bf8da..b5201aaf1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/xfdf_parser.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/annotations/xfdf_parser.dart @@ -35,7 +35,10 @@ class XfdfParser { _xmlDocument = XmlDocument.parse(xmlString); if (_xmlDocument.rootElement.localName.toLowerCase() != 'xfdf') { throw ArgumentError.value( - _xmlDocument.rootElement.localName, 'xmlString', 'Invalid XFDF data'); + _xmlDocument.rootElement.localName, + 'xmlString', + 'Invalid XFDF data', + ); } } @@ -64,11 +67,14 @@ class XfdfParser { if (pageIndex >= 0 && pageIndex < _document.pages.count) { PdfPageHelper.getHelper(_document.pages[pageIndex]).importAnnotation = true; - final PdfDictionary annotationDictionary = - _getAnnotation(element, pageIndex); + final PdfDictionary annotationDictionary = _getAnnotation( + element, + pageIndex, + ); if (annotationDictionary.count > 0) { - final PdfReferenceHolder holder = - PdfReferenceHolder(annotationDictionary); + final PdfReferenceHolder holder = PdfReferenceHolder( + annotationDictionary, + ); if (annotationDictionary.containsKey('NM') || annotationDictionary.containsKey(PdfDictionaryProperties.irt)) { _addReferenceToGroup(holder, annotationDictionary); @@ -80,7 +86,8 @@ class XfdfParser { pageDictionary[PdfDictionaryProperties.annots] = PdfArray(); } final IPdfPrimitive? annots = PdfCrossTable.dereference( - pageDictionary[PdfDictionaryProperties.annots]); + pageDictionary[PdfDictionaryProperties.annots], + ); if (annots != null && annots is PdfArray) { annots.elements.add(holder); _handlePopUp(annots, holder, annotationDictionary); @@ -93,11 +100,15 @@ class XfdfParser { } } - void _handlePopUp(PdfArray annots, PdfReferenceHolder holder, - PdfDictionary annotDictionary) { + void _handlePopUp( + PdfArray annots, + PdfReferenceHolder holder, + PdfDictionary annotDictionary, + ) { if (annotDictionary.containsKey(PdfDictionaryProperties.popup)) { final IPdfPrimitive? popup = PdfCrossTable.dereference( - annotDictionary[PdfDictionaryProperties.popup]); + annotDictionary[PdfDictionaryProperties.popup], + ); if (popup != null && popup is PdfDictionary) { popup.setProperty(PdfDictionaryProperties.parent, holder); annots.add(popup); @@ -108,13 +119,17 @@ class XfdfParser { PdfDictionary _getAnnotation(XmlElement element, int pageIndex) { final PdfDictionary annotationDictionary = PdfDictionary(); annotationDictionary.setName( - PdfName(PdfDictionaryProperties.name), PdfDictionaryProperties.annot); + PdfName(PdfDictionaryProperties.name), + PdfDictionaryProperties.annot, + ); bool isValidType = true; if (!isNullOrEmpty(element.localName)) { switch (element.localName.toLowerCase()) { case 'line': - annotationDictionary.setName(PdfName(PdfDictionaryProperties.subtype), - PdfDictionaryProperties.line); + annotationDictionary.setName( + PdfName(PdfDictionaryProperties.subtype), + PdfDictionaryProperties.line, + ); final String? start = element.getAttribute('start'); final String? end = element.getAttribute('end'); if (start != null && end != null) { @@ -123,7 +138,9 @@ class XfdfParser { _addLinePoints(linePoints, end); if (linePoints.length == 4) { annotationDictionary.setProperty( - PdfDictionaryProperties.l, PdfArray(linePoints)); + PdfDictionaryProperties.l, + PdfArray(linePoints), + ); } linePoints.clear(); } @@ -131,20 +148,28 @@ class XfdfParser { break; case 'circle': annotationDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.circle); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.circle, + ); break; case 'square': annotationDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.square); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.square, + ); break; case 'polyline': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'PolyLine'); + PdfDictionaryProperties.subtype, + 'PolyLine', + ); _addLineEndStyle(element, annotationDictionary); break; case 'polygon': annotationDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.polygon); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.polygon, + ); _addLineEndStyle(element, annotationDictionary); break; case 'ink': @@ -152,56 +177,82 @@ class XfdfParser { break; case 'popup': annotationDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.popup); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.popup, + ); break; case 'text': annotationDictionary.setName( - PdfDictionaryProperties.subtype, PdfDictionaryProperties.text); + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.text, + ); break; case 'freetext': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'FreeText'); + PdfDictionaryProperties.subtype, + 'FreeText', + ); _addLineEndStyle(element, annotationDictionary); break; case 'stamp': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'Stamp'); + PdfDictionaryProperties.subtype, + 'Stamp', + ); break; case 'highlight': - annotationDictionary.setName(PdfDictionaryProperties.subtype, - PdfDictionaryProperties.highlight); + annotationDictionary.setName( + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.highlight, + ); break; case 'squiggly': - annotationDictionary.setName(PdfDictionaryProperties.subtype, - PdfDictionaryProperties.squiggly); + annotationDictionary.setName( + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.squiggly, + ); break; case 'underline': - annotationDictionary.setName(PdfDictionaryProperties.subtype, - PdfDictionaryProperties.underline); + annotationDictionary.setName( + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.underline, + ); break; case 'strikeout': - annotationDictionary.setName(PdfDictionaryProperties.subtype, - PdfDictionaryProperties.strikeOut); + annotationDictionary.setName( + PdfDictionaryProperties.subtype, + PdfDictionaryProperties.strikeOut, + ); break; case 'fileattachment': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'FileAttachment'); + PdfDictionaryProperties.subtype, + 'FileAttachment', + ); break; case 'sound': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'Sound'); + PdfDictionaryProperties.subtype, + 'Sound', + ); break; case 'caret': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'Caret'); + PdfDictionaryProperties.subtype, + 'Caret', + ); break; case 'redact': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'Redact'); + PdfDictionaryProperties.subtype, + 'Redact', + ); break; case 'watermark': annotationDictionary.setName( - PdfDictionaryProperties.subtype, 'Watermark'); + PdfDictionaryProperties.subtype, + 'Watermark', + ); break; default: isValidType = false; @@ -215,7 +266,10 @@ class XfdfParser { } void _addAnnotationData( - PdfDictionary annotDictionary, XmlElement element, int pageIndex) { + PdfDictionary annotDictionary, + XmlElement element, + int pageIndex, + ) { _addBorderStyle(annotDictionary, element); _applyAttributeValues(annotDictionary, element); _parseInnerElements(annotDictionary, element, pageIndex); @@ -229,7 +283,9 @@ class XfdfParser { String? attribute = element.getAttribute('width'); if (!isNullOrEmpty(attribute)) { borderStyleDictionary.setNumber( - PdfDictionaryProperties.w, double.parse(attribute!)); + PdfDictionaryProperties.w, + double.parse(attribute!), + ); } bool isBasicStyle = true; attribute = element.getAttribute('style'); @@ -262,31 +318,41 @@ class XfdfParser { attribute = element.getAttribute('intensity'); if (!isBasicStyle && !isNullOrEmpty(attribute)) { borderEffectDictionary.setNumber( - PdfDictionaryProperties.i, double.parse(attribute!)); + PdfDictionaryProperties.i, + double.parse(attribute!), + ); } else { attribute = element.getAttribute('dashes'); if (!isNullOrEmpty(attribute)) { final List dashPoints = _obtainFloatPoints(attribute!); if (dashPoints.isNotEmpty) { borderStyleDictionary.setProperty( - PdfDictionaryProperties.d, PdfArray(dashPoints)); + PdfDictionaryProperties.d, + PdfArray(dashPoints), + ); } } } } } if (borderEffectDictionary.count > 0) { - annotDictionary.setProperty(PdfDictionaryProperties.be, - PdfReferenceHolder(borderEffectDictionary)); + annotDictionary.setProperty( + PdfDictionaryProperties.be, + PdfReferenceHolder(borderEffectDictionary), + ); } else { borderEffectDictionary.clear(); borderEffectDictionary.isSaving = false; } if (borderStyleDictionary.count > 0) { - borderStyleDictionary.setProperty(PdfDictionaryProperties.type, - PdfName(PdfDictionaryProperties.border)); - annotDictionary.setProperty(PdfDictionaryProperties.bs, - PdfReferenceHolder(borderStyleDictionary)); + borderStyleDictionary.setProperty( + PdfDictionaryProperties.type, + PdfName(PdfDictionaryProperties.border), + ); + annotDictionary.setProperty( + PdfDictionaryProperties.bs, + PdfReferenceHolder(borderStyleDictionary), + ); } else { borderStyleDictionary.clear(); borderStyleDictionary.isSaving = false; @@ -321,7 +387,9 @@ class XfdfParser { } void _applyAttributeValues( - PdfDictionary annotDictionary, XmlElement element) { + PdfDictionary annotDictionary, + XmlElement element, + ) { for (final XmlAttribute attribute in element.attributes) { final String value = attribute.value; final XmlName name = attribute.name; @@ -354,7 +422,9 @@ class XfdfParser { final List points = _obtainFloatPoints(value); if (points.isNotEmpty && points.length == 4) { annotDictionary.setProperty( - PdfDictionaryProperties.rect, PdfArray(points)); + PdfDictionaryProperties.rect, + PdfArray(points), + ); } break; case 'color': @@ -362,7 +432,9 @@ class XfdfParser { final PdfArray? colorArray = _getColorArray(value); if (colorArray != null) { annotDictionary.setProperty( - PdfDictionaryProperties.c, colorArray); + PdfDictionaryProperties.c, + colorArray, + ); } } break; @@ -371,7 +443,9 @@ class XfdfParser { final PdfArray? colorArray = _getColorArray(value); if (colorArray != null) { annotDictionary.setProperty( - PdfDictionaryProperties.ic, colorArray); + PdfDictionaryProperties.ic, + colorArray, + ); } } break; @@ -380,7 +454,10 @@ class XfdfParser { break; case 'creationdate': _addString( - annotDictionary, PdfDictionaryProperties.creationDate, value); + annotDictionary, + PdfDictionaryProperties.creationDate, + value, + ); break; case 'name': _addString(annotDictionary, 'NM', value); @@ -391,12 +468,18 @@ class XfdfParser { } break; case 'subject': - _addString(annotDictionary, PdfDictionaryProperties.subj, - _getFormattedString(value)); + _addString( + annotDictionary, + PdfDictionaryProperties.subj, + _getFormattedString(value), + ); break; case 'title': - _addString(annotDictionary, PdfDictionaryProperties.t, - _getFormattedString(value)); + _addString( + annotDictionary, + PdfDictionaryProperties.t, + _getFormattedString(value), + ); break; case 'rotation': _addInt(annotDictionary, PdfDictionaryProperties.rotate, value); @@ -405,8 +488,11 @@ class XfdfParser { _addInt(annotDictionary, PdfDictionaryProperties.q, value); break; case 'fringe': - _addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.rd); + _addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.rd, + ); break; case 'it': if (!isNullOrEmpty(value)) { @@ -421,14 +507,18 @@ class XfdfParser { final double? leaderExtend = double.tryParse(value); if (leaderExtend != null) { annotDictionary.setNumber( - PdfDictionaryProperties.lle, leaderExtend); + PdfDictionaryProperties.lle, + leaderExtend, + ); } } break; case 'caption': if (!isNullOrEmpty(value)) { annotDictionary.setBoolean( - PdfDictionaryProperties.cap, value.toLowerCase() == 'yes'); + PdfDictionaryProperties.cap, + value.toLowerCase() == 'yes', + ); } break; case 'caption-style': @@ -440,12 +530,18 @@ class XfdfParser { _addFloatPoints(annotDictionary, _obtainFloatPoints(value), 'CL'); break; case 'coords': - _addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.quadPoints); + _addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.quadPoints, + ); break; case 'border': - _addFloatPoints(annotDictionary, _obtainFloatPoints(value), - PdfDictionaryProperties.border); + _addFloatPoints( + annotDictionary, + _obtainFloatPoints(value), + PdfDictionaryProperties.border, + ); break; case 'opacity': if (!isNullOrEmpty(value)) { @@ -469,7 +565,8 @@ class XfdfParser { int flagValue = 0; for (int i = 0; i < annotationFlags.length; i++) { flagValue |= PdfAnnotationHelper.getAnnotationFlagsValue( - annotationFlags[i]); + annotationFlags[i], + ); } if (flagValue > 0) { annotDictionary.setNumber(PdfDictionaryProperties.f, flagValue); @@ -478,8 +575,10 @@ class XfdfParser { break; case 'open': if (!isNullOrEmpty(value)) { - annotDictionary.setBoolean(PdfDictionaryProperties.open, - value == 'true' || value == 'yes'); + annotDictionary.setBoolean( + PdfDictionaryProperties.open, + value == 'true' || value == 'yes', + ); } break; case 'calibrate': @@ -493,7 +592,9 @@ class XfdfParser { break; case 'repeat': annotDictionary.setBoolean( - 'Repeat', value == 'true' || value == 'yes'); + 'Repeat', + value == 'true' || value == 'yes', + ); break; default: break; @@ -502,7 +603,10 @@ class XfdfParser { } void _parseInnerElements( - PdfDictionary annotDictionary, XmlElement element, int pageIndex) { + PdfDictionary annotDictionary, + XmlElement element, + int pageIndex, + ) { if (element.attributes.isNotEmpty) { for (final XmlNode childNode in element.children) { if (childNode is XmlElement) { @@ -510,13 +614,18 @@ class XfdfParser { switch (childName.local.toLowerCase()) { case 'popup': if (childNode.attributes.isNotEmpty) { - final PdfDictionary popupDictionary = - _getAnnotation(childNode, pageIndex); + final PdfDictionary popupDictionary = _getAnnotation( + childNode, + pageIndex, + ); if (popupDictionary.count > 0) { - final PdfReferenceHolder holder = - PdfReferenceHolder(popupDictionary); + final PdfReferenceHolder holder = PdfReferenceHolder( + popupDictionary, + ); annotDictionary.setProperty( - PdfDictionaryProperties.popup, holder); + PdfDictionaryProperties.popup, + holder, + ); if (popupDictionary.containsKey('NM')) { _addReferenceToGroup(holder, popupDictionary); } @@ -529,7 +638,9 @@ class XfdfParser { contents = contents.replaceAll('<', '<'); contents = contents.replaceAll('>', '>'); annotDictionary.setString( - PdfDictionaryProperties.contents, contents); + PdfDictionaryProperties.contents, + contents, + ); } break; case 'contents-richtext': @@ -539,15 +650,22 @@ class XfdfParser { final String contentText = childNode.innerText; if (!isNullOrEmpty(richTextContents) && !isNullOrEmpty(contentText) && - !annotDictionary - .containsKey(PdfDictionaryProperties.contents)) { + !annotDictionary.containsKey( + PdfDictionaryProperties.contents, + )) { annotDictionary.setString( - 'RC', '$richTextContents'); + 'RC', + '$richTextContents', + ); annotDictionary.setString( - PdfDictionaryProperties.contents, contentText); + PdfDictionaryProperties.contents, + contentText, + ); } else if (!isNullOrEmpty(richTextContents)) { annotDictionary.setString( - 'RC', '$richTextContents'); + 'RC', + '$richTextContents', + ); } } break; @@ -555,39 +673,47 @@ class XfdfParser { _addString(annotDictionary, 'DS', childNode.innerText); break; case 'defaultappearance': - _addString(annotDictionary, PdfDictionaryProperties.da, - childNode.innerText); + _addString( + annotDictionary, + PdfDictionaryProperties.da, + childNode.innerText, + ); break; case 'vertices': if (!isNullOrEmpty(childNode.innerText)) { - final String verticesValue = - childNode.innerText.replaceAll(';', ','); + final String verticesValue = childNode.innerText.replaceAll( + ';', + ',', + ); if (verticesValue != '') { final List verticesList = []; _addLinePoints(verticesList, verticesValue); if (verticesList.isNotEmpty && verticesList.length.isEven) { annotDictionary.setProperty( - PdfDictionaryProperties.vertices, - PdfArray(verticesList)); + PdfDictionaryProperties.vertices, + PdfArray(verticesList), + ); } } } break; case 'appearance': if (!isNullOrEmpty(childNode.innerText)) { - final List appearanceArray = - base64.decode(childNode.innerText); + final List appearanceArray = base64.decode( + childNode.innerText, + ); if (appearanceArray.isNotEmpty) { - final XmlDocument appearanceDoc = - XmlDocument.parse(utf8.decode(appearanceArray)); + final XmlDocument appearanceDoc = XmlDocument.parse( + utf8.decode(appearanceArray), + ); final List childNodes = appearanceDoc.children; for (final XmlNode rootElement in childNodes) { if (rootElement is XmlElement) { if (rootElement.childElements.isNotEmpty) { final XmlName rootName = rootElement.name; if (rootName.local == XfdfProperties.dict) { - final String? rootAttribute = - rootElement.getAttribute(XfdfProperties.key); + final String? rootAttribute = rootElement + .getAttribute(XfdfProperties.key); if (rootAttribute != null && !isNullOrEmpty(rootAttribute)) { if (rootAttribute == 'AP') { @@ -600,7 +726,9 @@ class XfdfParser { } if (appearance.count > 0) { annotDictionary.setProperty( - PdfDictionaryProperties.ap, appearance); + PdfDictionaryProperties.ap, + appearance, + ); } } } @@ -623,8 +751,8 @@ class XfdfParser { final XmlName childNodeName = child.name; if (childNodeName.local.toLowerCase() == 'gesture' && !isNullOrEmpty(child.innerText)) { - final String pointsArrayValue = - child.innerText.replaceAll(';', ','); + final String pointsArrayValue = child.innerText + .replaceAll(';', ','); if (pointsArrayValue != '') { final PdfArray inkListCollection = PdfArray(); final List pointsList = []; @@ -635,7 +763,9 @@ class XfdfParser { pointsList.clear(); if (inkListCollection.count > 0) { annotDictionary.setProperty( - 'InkList', inkListCollection); + 'InkList', + inkListCollection, + ); } } } @@ -645,26 +775,40 @@ class XfdfParser { break; case 'data': if (!isNullOrEmpty(childNode.innerText)) { - final List raw = - List.from(hex.decode(childNode.innerText)); + final List raw = List.from( + hex.decode(childNode.innerText), + ); if (raw.isNotEmpty) { - if (annotDictionary - .containsKey(PdfDictionaryProperties.subtype)) { + if (annotDictionary.containsKey( + PdfDictionaryProperties.subtype, + )) { final IPdfPrimitive? subtype = PdfCrossTable.dereference( - annotDictionary[PdfDictionaryProperties.subtype]); + annotDictionary[PdfDictionaryProperties.subtype], + ); if (subtype != null && subtype is PdfName) { if (subtype.name == 'FileAttachment') { final PdfDictionary fileDictionary = PdfDictionary(); - fileDictionary.setName(PdfDictionaryProperties.type, - PdfDictionaryProperties.filespec); - _addElementStrings(fileDictionary, element, 'file', - PdfDictionaryProperties.f); - _addElementStrings(fileDictionary, element, 'file', - PdfDictionaryProperties.uf); + fileDictionary.setName( + PdfDictionaryProperties.type, + PdfDictionaryProperties.filespec, + ); + _addElementStrings( + fileDictionary, + element, + 'file', + PdfDictionaryProperties.f, + ); + _addElementStrings( + fileDictionary, + element, + 'file', + PdfDictionaryProperties.uf, + ); final PdfStream fileStream = PdfStream(); final PdfDictionary param = PdfDictionary(); - final String? sizeAttributes = - element.getAttribute('size'); + final String? sizeAttributes = element.getAttribute( + 'size', + ); if (!isNullOrEmpty(sizeAttributes)) { final int? size = int.tryParse(sizeAttributes!); if (size != null) { @@ -672,44 +816,79 @@ class XfdfParser { fileStream.setNumber('DL', size); } } - _addElementStrings(param, element, 'modification', - PdfDictionaryProperties.modificationDate); - _addElementStrings(param, element, 'creation', - PdfDictionaryProperties.creationDate); + _addElementStrings( + param, + element, + 'modification', + PdfDictionaryProperties.modificationDate, + ); + _addElementStrings( + param, + element, + 'creation', + PdfDictionaryProperties.creationDate, + ); fileStream.setProperty( - PdfDictionaryProperties.params, param); - _addElementStrings(fileStream, element, 'mimetype', - PdfDictionaryProperties.subtype); + PdfDictionaryProperties.params, + param, + ); + _addElementStrings( + fileStream, + element, + 'mimetype', + PdfDictionaryProperties.subtype, + ); fileStream.data = raw; final PdfDictionary embeddedFile = PdfDictionary(); - embeddedFile.setProperty(PdfDictionaryProperties.f, - PdfReferenceHolder(fileStream)); + embeddedFile.setProperty( + PdfDictionaryProperties.f, + PdfReferenceHolder(fileStream), + ); fileDictionary.setProperty( - PdfDictionaryProperties.ef, embeddedFile); - annotDictionary.setProperty(PdfDictionaryProperties.fs, - PdfReferenceHolder(fileDictionary)); + PdfDictionaryProperties.ef, + embeddedFile, + ); + annotDictionary.setProperty( + PdfDictionaryProperties.fs, + PdfReferenceHolder(fileDictionary), + ); } else if (subtype.name == 'Sound') { final PdfStream soundStream = PdfStream(); soundStream.setName( - PdfDictionaryProperties.type, 'Sound'); + PdfDictionaryProperties.type, + 'Sound', + ); _addNumber(soundStream, element, 'bits', 'B'); - _addNumber(soundStream, element, 'rate', - PdfDictionaryProperties.r); - _addNumber(soundStream, element, 'channels', - PdfDictionaryProperties.c); + _addNumber( + soundStream, + element, + 'rate', + PdfDictionaryProperties.r, + ); + _addNumber( + soundStream, + element, + 'channels', + PdfDictionaryProperties.c, + ); String? attribute = element.getAttribute('encoding'); if (!isNullOrEmpty(attribute)) { soundStream.setName( - PdfDictionaryProperties.e, attribute); + PdfDictionaryProperties.e, + attribute, + ); } soundStream.data = raw; attribute = element.getAttribute('filter'); if (!isNullOrEmpty(attribute)) { - soundStream - .addFilter(PdfDictionaryProperties.flateDecode); + soundStream.addFilter( + PdfDictionaryProperties.flateDecode, + ); } annotDictionary.setProperty( - 'Sound', PdfReferenceHolder(soundStream)); + 'Sound', + PdfReferenceHolder(soundStream), + ); } } } @@ -722,8 +901,12 @@ class XfdfParser { } } - void _addElementStrings(PdfDictionary dictionary, XmlElement element, - String attributeName, String key) { + void _addElementStrings( + PdfDictionary dictionary, + XmlElement element, + String attributeName, + String key, + ) { if (element.attributes.isNotEmpty) { final String? attribute = element.getAttribute(attributeName); if (!isNullOrEmpty(attribute)) { @@ -732,8 +915,12 @@ class XfdfParser { } } - void _addNumber(PdfDictionary dictionary, XmlElement element, - String attributeName, String key) { + void _addNumber( + PdfDictionary dictionary, + XmlElement element, + String attributeName, + String key, + ) { if (element.attributes.isNotEmpty) { final String? attribute = element.getAttribute(attributeName); if (!isNullOrEmpty(attribute)) { @@ -750,7 +937,8 @@ class XfdfParser { final List appearanceArray = base64.decode(convert); final PdfBitmap image = PdfBitmap(appearanceArray); final IPdfPrimitive? array = PdfCrossTable.dereference( - annotDictionary[PdfDictionaryProperties.rect]); + annotDictionary[PdfDictionaryProperties.rect], + ); if (array != null && array is PdfArray) { const double x = 0; const double y = 0; @@ -759,23 +947,29 @@ class XfdfParser { final Rect rect = Rect.fromLTWH(x, y, width, height); final PdfTemplate template = PdfTemplate(width, height); _setMatrix( - PdfTemplateHelper.getHelper(template).content, annotDictionary); + PdfTemplateHelper.getHelper(template).content, + annotDictionary, + ); template.graphics!.drawImage(image, rect); final PdfReferenceHolder refHolder = PdfReferenceHolder(template); final PdfDictionary appearanceDictionary = PdfDictionary(); appearanceDictionary.setProperty(PdfDictionaryProperties.n, refHolder); annotDictionary.setProperty( - PdfDictionaryProperties.ap, appearanceDictionary); + PdfDictionaryProperties.ap, + appearanceDictionary, + ); } } void _setMatrix(PdfDictionary template, PdfDictionary annotDictionary) { - final IPdfPrimitive? bbox = - PdfCrossTable.dereference(template[PdfDictionaryProperties.bBox]); + final IPdfPrimitive? bbox = PdfCrossTable.dereference( + template[PdfDictionaryProperties.bBox], + ); if (bbox != null && bbox is PdfArray) { if (annotDictionary.containsKey(PdfDictionaryProperties.rotate)) { final IPdfPrimitive? rotate = PdfCrossTable.dereference( - annotDictionary[PdfDictionaryProperties.rotate]); + annotDictionary[PdfDictionaryProperties.rotate], + ); if (rotate is PdfNumber && rotate.value != 0) { int rotateAngle = rotate.value!.toInt(); if (rotateAngle == 0) { @@ -793,7 +987,7 @@ class XfdfParser { 0, 1, -(bbox[0]! as PdfNumber).value!, - -(bbox[1]! as PdfNumber).value! + -(bbox[1]! as PdfNumber).value!, ]; template[PdfDictionaryProperties.matrix] = PdfArray(elements); } @@ -849,7 +1043,8 @@ class XfdfParser { bool isImage = false; if (appearance.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? subtype = PdfCrossTable.dereference( - appearance[PdfDictionaryProperties.subtype]); + appearance[PdfDictionaryProperties.subtype], + ); if (subtype != null && subtype is PdfName && subtype.name == PdfDictionaryProperties.image) { @@ -875,7 +1070,9 @@ class XfdfParser { } void _addMeasureDictionary( - PdfDictionary annotDictionary, XmlElement element) { + PdfDictionary annotDictionary, + XmlElement element, + ) { XmlElement? measurement; XmlElement? area; XmlElement? distance; @@ -901,7 +1098,9 @@ class XfdfParser { measureDictionary.items![PdfName(PdfDictionaryProperties.x)] = xArray; if (measurement != null) { measureDictionary.setName( - PdfDictionaryProperties.type, PdfDictionaryProperties.measure); + PdfDictionaryProperties.type, + PdfDictionaryProperties.measure, + ); if (measurement.attributes.isNotEmpty) { final String? attribute = measurement.getAttribute('rateValue'); if (!isNullOrEmpty(attribute)) { @@ -937,8 +1136,9 @@ class XfdfParser { } if (measureDictionary.items!.isNotEmpty && measureDictionary.containsKey(PdfDictionaryProperties.type)) { - annotDictionary.items![PdfName(PdfDictionaryProperties.measure)] = - PdfReferenceHolder(measureDictionary); + annotDictionary.items![PdfName( + PdfDictionaryProperties.measure, + )] = PdfReferenceHolder(measureDictionary); } } @@ -949,7 +1149,9 @@ class XfdfParser { final double? d = double.tryParse(attribute); if (d != null) { dictionary.setProperty( - PdfName(PdfDictionaryProperties.d), PdfNumber(d)); + PdfName(PdfDictionaryProperties.d), + PdfNumber(d), + ); } } attribute = element.getAttribute(PdfDictionaryProperties.c.toLowerCase()); @@ -957,7 +1159,9 @@ class XfdfParser { final double? c = double.tryParse(attribute); if (c != null) { dictionary.setProperty( - PdfName(PdfDictionaryProperties.c), PdfNumber(c)); + PdfName(PdfDictionaryProperties.c), + PdfNumber(c), + ); } } attribute = element.getAttribute('rt'); @@ -966,8 +1170,9 @@ class XfdfParser { } attribute = element.getAttribute('rd'); if (attribute != null) { - dictionary.items![PdfName(PdfDictionaryProperties.rd)] = - PdfString(attribute); + dictionary.items![PdfName(PdfDictionaryProperties.rd)] = PdfString( + attribute, + ); } attribute = element.getAttribute('ss'); if (attribute != null) { @@ -975,13 +1180,15 @@ class XfdfParser { } attribute = element.getAttribute(PdfDictionaryProperties.u.toLowerCase()); if (attribute != null) { - dictionary.items![PdfName(PdfDictionaryProperties.u)] = - PdfString(attribute); + dictionary.items![PdfName(PdfDictionaryProperties.u)] = PdfString( + attribute, + ); } attribute = element.getAttribute(PdfDictionaryProperties.f.toLowerCase()); if (attribute != null) { - dictionary.items![PdfName(PdfDictionaryProperties.f)] = - PdfName(attribute); + dictionary.items![PdfName(PdfDictionaryProperties.f)] = PdfName( + attribute, + ); } attribute = element.getAttribute('fd'); if (attribute != null) { @@ -1003,7 +1210,10 @@ class XfdfParser { } void _addKey( - IPdfPrimitive? primitive, PdfDictionary dictionary, XmlElement element) { + IPdfPrimitive? primitive, + PdfDictionary dictionary, + XmlElement element, + ) { if (primitive != null && element.attributes.isNotEmpty) { final String? attribute = element.getAttribute(XfdfProperties.key); if (!isNullOrEmpty(attribute)) { @@ -1171,7 +1381,9 @@ class XfdfParser { } void _addReferenceToGroup( - PdfReferenceHolder holder, PdfDictionary dictionary) { + PdfReferenceHolder holder, + PdfDictionary dictionary, + ) { IPdfPrimitive? name = PdfCrossTable.dereference(dictionary['NM']); if (name != null && name is PdfString && !isNullOrEmpty(name.value)) { _groupReferences ??= {}; @@ -1182,8 +1394,9 @@ class XfdfParser { } } else if (name == null) { if (dictionary.containsKey(PdfDictionaryProperties.irt)) { - name = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.irt]); + name = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.irt], + ); } if (name != null && name is PdfString && !isNullOrEmpty(name.value)) { if (_groupReferences != null && @@ -1305,7 +1518,9 @@ class XfdfParser { lineEndingStyles.add(PdfName(beginLineStyle)); lineEndingStyles.add(PdfName(endLineStyle)); annotDictionary.setProperty( - PdfDictionaryProperties.le, lineEndingStyles); + PdfDictionaryProperties.le, + lineEndingStyles, + ); } else { annotDictionary.setName(PdfDictionaryProperties.le, beginLineStyle); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/color_space/pdf_icc_color_profile.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/color_space/pdf_icc_color_profile.dart index 120772b64..e4322d613 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/color_space/pdf_icc_color_profile.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/color_space/pdf_icc_color_profile.dart @@ -13,8 +13,10 @@ class PdfICCColorProfile implements IPdfWrapper { /// Initializes a new instance of the [PdfICCColorProfile] class. PdfICCColorProfile() : super() { stream.compress = true; - stream.setProperty(PdfDictionaryProperties.filter, - PdfName(PdfDictionaryProperties.flateDecode)); + stream.setProperty( + PdfDictionaryProperties.filter, + PdfName(PdfDictionaryProperties.flateDecode), + ); stream.setProperty(PdfDictionaryProperties.n, PdfNumber(3)); stream.beginSave = _beginSaveStream; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_reader.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_reader.dart index 42281b075..48c9f5b55 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_reader.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_reader.dart @@ -72,7 +72,7 @@ class CompressedStreamReader { 163, 195, 227, - 258 + 258, ]; /// internal field @@ -105,7 +105,7 @@ class CompressedStreamReader { 5, 5, 5, - 0 + 0, ]; /// internal field @@ -139,7 +139,7 @@ class CompressedStreamReader { 8193, 12289, 16385, - 24577 + 24577, ]; /// internal field @@ -173,7 +173,7 @@ class CompressedStreamReader { 12, 12, 13, - 13 + 13, ]; /// internal field @@ -218,7 +218,9 @@ class CompressedStreamReader { final int header = _readInt16(); if (header == -1) { throw ArgumentError.value( - header, 'Header of the stream can not be read.'); + header, + 'Header of the stream can not be read.', + ); } if (header % 31 != 0) { throw ArgumentError.value(header, 'Header checksum illegal'); @@ -229,11 +231,15 @@ class CompressedStreamReader { _windowSize = pow(2, ((header & _defHeaderInfoMask) >> 12) + 8) as int; if (_windowSize > _maxValue) { throw ArgumentError.value( - header, 'Unsupported window size for deflate compression method.'); + header, + 'Unsupported window size for deflate compression method.', + ); } if ((header & _defHeaderFlagsFdict) >> 5 == 1) { throw ArgumentError.value( - header, 'Custom dictionary is not supported at the moment.'); + header, + 'Custom dictionary is not supported at the moment.', + ); } } @@ -263,7 +269,9 @@ class CompressedStreamReader { if (length > _maxValue) { throw ArgumentError.value( - length, 'Uncompressed block length can not be more than 65535.'); + length, + 'Uncompressed block length can not be more than 65535.', + ); } _uncompressedDataLength = length; @@ -279,8 +287,10 @@ class CompressedStreamReader { case 2: _readingUncompressed = false; _uncompressedDataLength = -1; - final Map result = - _decodeDynamicHeader(_currentLengthTree, _currentDistanceTree); + final Map result = _decodeDynamicHeader( + _currentLengthTree, + _currentDistanceTree, + ); _currentLengthTree = result['lengthTree'] as DecompressorHuffmanTree; _currentDistanceTree = result['distanceTree'] as DecompressorHuffmanTree; @@ -291,8 +301,10 @@ class CompressedStreamReader { return true; } - Map _decodeDynamicHeader(DecompressorHuffmanTree? lengthTree, - DecompressorHuffmanTree? distanceTree) { + Map _decodeDynamicHeader( + DecompressorHuffmanTree? lengthTree, + DecompressorHuffmanTree? distanceTree, + ) { List arrDecoderCodeLengths; List arrResultingCodeLengths; @@ -309,8 +321,11 @@ class CompressedStreamReader { iDistancesCount += 1; final int iResultingCodeLengthsCount = iLengthsCount + iDistancesCount; - arrResultingCodeLengths = - List.filled(iResultingCodeLengthsCount, 0, growable: true); + arrResultingCodeLengths = List.filled( + iResultingCodeLengthsCount, + 0, + growable: true, + ); arrDecoderCodeLengths = List.filled(19, 0, growable: true); iCodeLengthsCount += 4; int iCurrentCode = 0; @@ -323,11 +338,13 @@ class CompressedStreamReader { } arrDecoderCodeLengths[CompressedStreamWriter - .defHuffmanDyntreeCodeLengthsOrder[iCurrentCode++]] = - len.toUnsigned(8); + .defHuffmanDyntreeCodeLengthsOrder[iCurrentCode++]] = len.toUnsigned( + 8, + ); } - final DecompressorHuffmanTree treeInternalDecoder = - DecompressorHuffmanTree(arrDecoderCodeLengths); + final DecompressorHuffmanTree treeInternalDecoder = DecompressorHuffmanTree( + arrDecoderCodeLengths, + ); iCurrentCode = 0; @@ -383,21 +400,37 @@ class CompressedStreamReader { } } - final List tempLengthArray = - List.filled(iLengthsCount, 0, growable: true); + final List tempLengthArray = List.filled( + iLengthsCount, + 0, + growable: true, + ); List.copyRange( - tempLengthArray, 0, arrResultingCodeLengths, 0, iLengthsCount); + tempLengthArray, + 0, + arrResultingCodeLengths, + 0, + iLengthsCount, + ); lengthTree = DecompressorHuffmanTree(tempLengthArray); - final List tempDistanceArray = - List.filled(iDistancesCount, 0, growable: true); - List.copyRange(tempDistanceArray, 0, arrResultingCodeLengths, iLengthsCount, - iLengthsCount + iDistancesCount); + final List tempDistanceArray = List.filled( + iDistancesCount, + 0, + growable: true, + ); + List.copyRange( + tempDistanceArray, + 0, + arrResultingCodeLengths, + iLengthsCount, + iLengthsCount + iDistancesCount, + ); distanceTree = DecompressorHuffmanTree(tempDistanceArray); return { 'lengthTree': lengthTree, - 'distanceTree': distanceTree + 'distanceTree': distanceTree, }; } @@ -528,7 +561,9 @@ class CompressedStreamReader { Map read(List buffer, int offset, int length) { if (offset < 0 || offset > buffer.length - 1) { throw ArgumentError.value( - offset, 'Offset does not belong to specified buffer.'); + offset, + 'Offset does not belong to specified buffer.', + ); } if (length < 0 || length > buffer.length - offset) { throw ArgumentError.value(length, 'Length is illegal.'); @@ -537,13 +572,20 @@ class CompressedStreamReader { while (length > 0) { if (_currentPosition < _dataLength) { final int inBlockPosition = _currentPosition % _maxValue; - int dataToCopy = - min(_maxValue - inBlockPosition, _dataLength - _currentPosition); + int dataToCopy = min( + _maxValue - inBlockPosition, + _dataLength - _currentPosition, + ); dataToCopy = min(dataToCopy, length); // Copy data. - List.copyRange(buffer, offset, _blockBuffer!, inBlockPosition, - inBlockPosition + dataToCopy); + List.copyRange( + buffer, + offset, + _blockBuffer!, + inBlockPosition, + inBlockPosition + dataToCopy, + ); _currentPosition += dataToCopy; offset += dataToCopy; length -= dataToCopy; @@ -567,13 +609,20 @@ class CompressedStreamReader { } else { // Position of the data end in block buffer. final int inBlockPosition = _dataLength % _maxValue; - final int dataToRead = - min(_uncompressedDataLength, _maxValue - inBlockPosition); - final int dataRead = - _readPackedBytes(_blockBuffer!, inBlockPosition, dataToRead); + final int dataToRead = min( + _uncompressedDataLength, + _maxValue - inBlockPosition, + ); + final int dataRead = _readPackedBytes( + _blockBuffer!, + inBlockPosition, + dataToRead, + ); if (dataToRead != dataRead) { throw ArgumentError.value( - dataToRead, 'Not enough data in stream.'); + dataToRead, + 'Not enough data in stream.', + ); } _uncompressedDataLength -= dataRead; _dataLength += dataRead; @@ -605,19 +654,25 @@ class CompressedStreamReader { return { 'length': initialLength - length, - 'buffer': buffer + 'buffer': buffer, }; } void _checksumUpdate(List? buffer, int offset, int length) { _checkSum = CompressedStreamWriter.checksumUpdate( - _checkSum, buffer, offset, length); + _checkSum, + buffer, + offset, + length, + ); } int _readPackedBytes(List buffer, int offset, int length) { if (offset < 0 || offset > buffer.length - 1) { - throw ArgumentError.value(offset, - 'Offset cannot be less than zero or greater than buffer length - 1.'); + throw ArgumentError.value( + offset, + 'Offset cannot be less than zero or greater than buffer length - 1.', + ); } if (length < 0) { @@ -630,7 +685,9 @@ class CompressedStreamReader { if ((bufferedBits & 7) != 0) { throw ArgumentError.value( - buffer, 'Reading of unalligned data is not supported.'); + buffer, + 'Reading of unalligned data is not supported.', + ); } if (length == 0) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_writer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_writer.dart index 308de9a91..0ea19e403 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_writer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressed_stream_writer.dart @@ -6,14 +6,30 @@ import 'compressor_huffman_tree.dart'; /// internal class class CompressedStreamWriter { /// internal constructor - CompressedStreamWriter(List outputStream, bool bNoWrap, - PdfCompressionLevel? level, bool bCloseStream) { - _treeLiteral = - CompressorHuffmanTree(this, defHuffmanLiteralAlphabetLength, 257, 15); - _treeDistances = - CompressorHuffmanTree(this, defHuffmanDistancesAlphabetLength, 1, 15); - _treeCodeLengths = - CompressorHuffmanTree(this, defHuffmanBitlenTreeLength, 4, 7); + CompressedStreamWriter( + List outputStream, + bool bNoWrap, + PdfCompressionLevel? level, + bool bCloseStream, + ) { + _treeLiteral = CompressorHuffmanTree( + this, + defHuffmanLiteralAlphabetLength, + 257, + 15, + ); + _treeDistances = CompressorHuffmanTree( + this, + defHuffmanDistancesAlphabetLength, + 1, + 15, + ); + _treeCodeLengths = CompressorHuffmanTree( + this, + defHuffmanBitlenTreeLength, + 4, + 7, + ); _arrDistancesBuffer = List.filled(defHuffmanBufferSize, 0); _arrLiteralsBuffer = List.filled(defHuffmanBufferSize, 0); _stream = outputStream; @@ -114,7 +130,7 @@ class CompressedStreamWriter { 128, 128, 258, - 258 + 258, ]; /// Internal compression engine constant @@ -128,7 +144,7 @@ class CompressedStreamWriter { 128, 256, 1024, - 4096 + 4096, ]; /// internal field @@ -148,7 +164,7 @@ class CompressedStreamWriter { 3, 11, 7, - 15 + 15, ]; /// internal field @@ -171,7 +187,7 @@ class CompressedStreamWriter { 2, 14, 1, - 15 + 15, ]; /// internal field @@ -261,10 +277,14 @@ class CompressedStreamWriter { _arrLiteralCodes![i] = bitReverse(((0x0c0 - 280) + i) << 8); _arrLiteralLengths[i++] = 8; } - _arrDistanceCodes = - List.filled(defHuffmanDistancesAlphabetLength, 0); - _arrDistanceLengths = - List.filled(defHuffmanDistancesAlphabetLength, 0); + _arrDistanceCodes = List.filled( + defHuffmanDistancesAlphabetLength, + 0, + ); + _arrDistanceLengths = List.filled( + defHuffmanDistancesAlphabetLength, + 0, + ); for (i = 0; i < defHuffmanDistancesAlphabetLength; i++) { _arrDistanceCodes[i] = bitReverse(i << 11); @@ -362,7 +382,11 @@ class CompressedStreamWriter { _matchPreviousAvailable = false; _huffmanFlushBlock( - _dataWindow, _blockStart, _stringStart - _blockStart, finish); + _dataWindow, + _blockStart, + _stringStart - _blockStart, + finish, + ); _blockStart = _stringStart; @@ -446,7 +470,11 @@ class CompressedStreamWriter { while (_lookAhead >= minLookahead || flush) { if (_lookAhead == 0) { _huffmanFlushBlock( - _dataWindow, _blockStart, _stringStart - _blockStart, finish); + _dataWindow, + _blockStart, + _stringStart - _blockStart, + finish, + ); _blockStart = _stringStart; return false; } @@ -462,7 +490,11 @@ class CompressedStreamWriter { if (_huffmanTallyDist(_stringStart - _matchStart, _matchLength)) { final bool lastBlock = finish && _lookAhead == 0; _huffmanFlushBlock( - _dataWindow, _blockStart, _stringStart - _blockStart, lastBlock); + _dataWindow, + _blockStart, + _stringStart - _blockStart, + lastBlock, + ); _blockStart = _stringStart; } _lookAhead -= _matchLength; @@ -491,7 +523,11 @@ class CompressedStreamWriter { if (_huffmanIsFull) { final bool lastBlock = finish && _lookAhead == 0; _huffmanFlushBlock( - _dataWindow, _blockStart, _stringStart - _blockStart, lastBlock); + _dataWindow, + _blockStart, + _stringStart - _blockStart, + lastBlock, + ); _blockStart = _stringStart; return !lastBlock; @@ -589,7 +625,11 @@ class CompressedStreamWriter { } void _huffmanFlushBlock( - List? stored, int storedOffset, int storedLength, bool lastBlock) { + List? stored, + int storedOffset, + int storedLength, + bool lastBlock, + ) { _treeLiteral.codeFrequences[defHuffmanEndblockSymbol]++; // Build trees. @@ -610,7 +650,8 @@ class CompressedStreamWriter { blTreeCodes = i + 1; } } - int optLen = 14 + + int optLen = + 14 + blTreeCodes * 3 + _treeCodeLengths!.getEncodedLength() + _treeLiteral.getEncodedLength() + @@ -657,9 +698,9 @@ class CompressedStreamWriter { for (int rank = 0; rank < blTreeCodes; rank++) { pendingBufferWriteBits( - _treeCodeLengths! - .codeLengths![defHuffmanDyntreeCodeLengthsOrder[rank]], - 3); + _treeCodeLengths!.codeLengths![defHuffmanDyntreeCodeLengthsOrder[rank]], + 3, + ); } _treeLiteral.writeTree(_treeCodeLengths); @@ -668,7 +709,8 @@ class CompressedStreamWriter { int _insertString() { int match; - final int hash = ((_currentHash << hashShift) ^ + final int hash = + ((_currentHash << hashShift) ^ _dataWindow![_stringStart + (minMatch - 1)]) & hashMask; @@ -733,7 +775,11 @@ class CompressedStreamWriter { } void _huffmanFlushStoredBlock( - List stored, int storedOffset, int storedLength, bool lastBlock) { + List stored, + int storedOffset, + int storedLength, + bool lastBlock, + ) { pendingBufferWriteBits((0 << 1) + (lastBlock ? 1 : 0), 3); _pendingBufferAlignToByte(); _pendingBufferWriteShort(storedLength); @@ -757,18 +803,23 @@ class CompressedStreamWriter { void _pendingBufferWriteByteBlock(List data, int offset, int length) { List.copyRange( - _pendingBuffer, _pendingBufferLength, data, offset, offset + length); + _pendingBuffer, + _pendingBufferLength, + data, + offset, + offset + length, + ); _pendingBufferLength += length; } void _pendingBufferAlignToByte() { if (_pendingBufferBitsInCache > 0) { - _pendingBuffer[_pendingBufferLength++] = - _pendingBufferBitsCache.toUnsigned(8); + _pendingBuffer[_pendingBufferLength++] = _pendingBufferBitsCache + .toUnsigned(8); if (_pendingBufferBitsInCache > 8) { - _pendingBuffer[_pendingBufferLength++] = - (_pendingBufferBitsCache >> 8).toUnsigned(8); + _pendingBuffer[_pendingBufferLength++] = (_pendingBufferBitsCache >> 8) + .toUnsigned(8); } } @@ -801,8 +852,13 @@ class CompressedStreamWriter { if (more > _inputEnd - _inputOffset) { more = _inputEnd - _inputOffset; } - List.copyRange(_dataWindow!, _stringStart + _lookAhead, _inputBuffer!, - _inputOffset, _inputOffset + more); + List.copyRange( + _dataWindow!, + _stringStart + _lookAhead, + _inputBuffer!, + _inputOffset, + _inputOffset + more, + ); _inputOffset += more; _lookAhead += more; @@ -831,7 +887,8 @@ class CompressedStreamWriter { } void _updateHash() { - _currentHash = (_dataWindow![_stringStart] << hashShift) ^ + _currentHash = + (_dataWindow![_stringStart] << hashShift) ^ _dataWindow![_stringStart + 1]; } @@ -850,8 +907,8 @@ class CompressedStreamWriter { int result = 0; while (_pendingBufferBitsInCache >= 8 && _pendingBufferLength < defPendingBufferSize) { - _pendingBuffer[_pendingBufferLength++] = - _pendingBufferBitsCache.toUnsigned(8); + _pendingBuffer[_pendingBufferLength++] = _pendingBufferBitsCache + .toUnsigned(8); _pendingBufferBitsCache >>= 8; _pendingBufferBitsInCache -= 8; result++; @@ -898,7 +955,11 @@ class CompressedStreamWriter { /// internal method static int checksumUpdate( - int checksum, List? buffer, int offset, int length) { + int checksum, + List? buffer, + int offset, + int length, + ) { int checksumUint = checksum.toUnsigned(32); int s1 = checksumUint & 65535; int s2 = checksumUint >> checkSumBitOffset; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressor_huffman_tree.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressor_huffman_tree.dart index bc9dcb732..00ef61169 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressor_huffman_tree.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/compressor_huffman_tree.dart @@ -5,8 +5,12 @@ import 'compressed_stream_writer.dart'; /// Represents the Huffman Tree. class CompressorHuffmanTree { /// Create a new Huffman tree. - CompressorHuffmanTree(CompressedStreamWriter writer, int iElementsCount, - int iMinimumCodes, int iMaximumLength) { + CompressorHuffmanTree( + CompressedStreamWriter writer, + int iElementsCount, + int iMinimumCodes, + int iMaximumLength, + ) { _writer = writer; _codeMinimumCount = iMinimumCodes; _maximumLength = iMaximumLength; @@ -31,7 +35,7 @@ class CompressorHuffmanTree { 3, 11, 7, - 15 + 15, ]; List? _codes; late List _lengthCounts; @@ -62,8 +66,8 @@ class CompressorHuffmanTree { int pos = iTreeLength++; int ppos; - while ( - pos > 0 && codeFrequences[arrTree[ppos = (pos - 1) ~/ 2]] > freq) { + while (pos > 0 && + codeFrequences[arrTree[ppos = (pos - 1) ~/ 2]] > freq) { arrTree[pos] = arrTree[ppos]; pos = ppos; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/decompressor_huffman_tree.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/decompressor_huffman_tree.dart index 9f1db50e7..66762afea 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/decompressor_huffman_tree.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/decompressor_huffman_tree.dart @@ -60,26 +60,42 @@ class DecompressorHuffmanTree { _distanceTree = DecompressorHuffmanTree(lengths); } catch (e) { throw ArgumentError.value( - e, 'DecompressorHuffmanTree: fixed trees generation failed'); + e, + 'DecompressorHuffmanTree: fixed trees generation failed', + ); } } void _buildTree(List lengths) { - final List blCount = - List.filled(_maxBitLength + 1, 0, growable: true); - final List nextCode = - List.filled(_maxBitLength + 1, 0, growable: true); + final List blCount = List.filled( + _maxBitLength + 1, + 0, + growable: true, + ); + final List nextCode = List.filled( + _maxBitLength + 1, + 0, + growable: true, + ); int? treeSize; int? code = 0; - final Map result = - _prepareData(blCount, nextCode, lengths, treeSize); + final Map result = _prepareData( + blCount, + nextCode, + lengths, + treeSize, + ); treeSize = result['treeSize'] as int?; code = result['code'] as int; _tree = _treeFromData(blCount, nextCode, lengths, code, treeSize!); } Map _prepareData( - List blCount, List nextCode, List lengths, int? treeSize) { + List blCount, + List nextCode, + List lengths, + int? treeSize, + ) { int code = 0; treeSize = 512; for (int i = 0; i < lengths.length; i++) { @@ -101,8 +117,13 @@ class DecompressorHuffmanTree { return {'treeSize': treeSize, 'code': code}; } - List _treeFromData(List blCount, List nextCode, - List lengths, int? code, int treeSize) { + List _treeFromData( + List blCount, + List nextCode, + List lengths, + int? code, + int treeSize, + ) { final List tree = List.filled(treeSize, 0, growable: true); int pointer = 512; const int increment = 1 << 7; @@ -111,8 +132,8 @@ class DecompressorHuffmanTree { code -= blCount[bits] << (16 - bits); final int start = code & 0x1ff80; for (int i = start; i < end; i += increment) { - tree[CompressedStreamWriter.bitReverse(i)] = - ((-pointer << 4) | bits).toSigned(16); + tree[CompressedStreamWriter.bitReverse(i)] = ((-pointer << 4) | bits) + .toSigned(16); pointer += 1 << (bits - 9); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/decompressed_output.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/decompressed_output.dart index c139fda76..d7b4a9070 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/decompressed_output.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/decompressed_output.dart @@ -41,7 +41,12 @@ class DecompressedOutput { if (copyStart <= border && _end < border) { if (length <= distance) { List.copyRange( - _dOutput!, _end, _dOutput!, copyStart, copyStart + length); + _dOutput!, + _end, + _dOutput!, + copyStart, + copyStart + length, + ); _end += length; } else { while (length-- > 0) { @@ -88,16 +93,23 @@ class DecompressedOutput { final int tailLen = length - end; int sourceStart = _dOutSize - tailLen; if (tailLen > 0) { - for (int i = 0; - i < tailLen && - i + sourceStart < _dOutput!.length && - i + offset < output.length; - i++) { + for ( + int i = 0; + i < tailLen && + i + sourceStart < _dOutput!.length && + i + offset < output.length; + i++ + ) { output[offset + i] = _dOutput![sourceStart + i]; } final int sourceStartIndex = _dOutSize - tailLen; - List.copyRange(output, offset, _dOutput!, sourceStartIndex, - sourceStartIndex + tailLen); + List.copyRange( + output, + offset, + _dOutput!, + sourceStartIndex, + sourceStartIndex + tailLen, + ); offset += tailLen; length = end; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/deflate_stream.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/deflate_stream.dart index e11258711..55f58bf4a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/deflate_stream.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/deflate_stream.dart @@ -25,8 +25,11 @@ class DeflateStream { int cOffset = offset; int rCount = count; while (true) { - final Map inflateResult = - _inflater.inflate(array!, cOffset, rCount); + final Map inflateResult = _inflater.inflate( + array!, + cOffset, + rCount, + ); length = inflateResult['count'] as int?; array = inflateResult['data'] as List; cOffset += length!; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_buffer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_buffer.dart index 85da61953..1556447df 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_buffer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_buffer.dart @@ -94,11 +94,11 @@ class InBuffer { if (length > avail) { length = avail; } - for (int i = 0; - i < length && - i + _begin < _buffer!.length && - i + offset < output!.length; - i++) { + for ( + int i = 0; + i < length && i + _begin < _buffer!.length && i + offset < output!.length; + i++ + ) { output[offset + i] = _buffer![_begin + i]; } _begin += length; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_flatter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_flatter.dart index b9574559c..db8549628 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_flatter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/deflate/in_flatter.dart @@ -20,8 +20,11 @@ class Inflater { _output = DecompressedOutput(); _input = InBuffer(); _loopCounter = 0; - _codeList = List.filled(HuffmanTree.maxLTree + HuffmanTree.maxDTree, 0, - growable: true); + _codeList = List.filled( + HuffmanTree.maxLTree + HuffmanTree.maxDTree, + 0, + growable: true, + ); _cltcl = List.filled(HuffmanTree.nCLength, 0, growable: true); _inflaterstate = InflaterState.readingBFinal; } @@ -147,7 +150,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } break; @@ -159,7 +162,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } break; @@ -172,20 +175,20 @@ class Inflater { return { 'result': true, 'eob': endblock, - 'output': _output + 'output': _output, }; } if (_output.unusedBytes == 0) { return { 'result': true, 'eob': endblock, - 'output': _output + 'output': _output, }; } return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; // ignore: no_default_cases default: @@ -200,8 +203,8 @@ class Inflater { return false; } _blBuffer[_getInflaterStateValue(_inflaterstate) - - _getInflaterStateValue(InflaterState.unCompressedByte1)] = - bits.toUnsigned(8); + _getInflaterStateValue(InflaterState.unCompressedByte1)] = bits + .toUnsigned(8); if (_inflaterstate == InflaterState.unCompressedByte4) { _bLength = _blBuffer[0] + (_blBuffer[1]) * 256; if (_bLength.toUnsigned(16) != @@ -209,8 +212,9 @@ class Inflater { throw ArgumentError.value('Ivalid block length.'); } } - _inflaterstate = - _getInflaterState(_getInflaterStateValue(_inflaterstate) + 1); + _inflaterstate = _getInflaterState( + _getInflaterStateValue(_inflaterstate) + 1, + ); return true; } @@ -226,7 +230,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } if (symbol < 256) { @@ -238,7 +242,7 @@ class Inflater { return { 'result': true, 'eob': endblock, - 'output': _output + 'output': _output, }; } else { symbol -= 257; @@ -261,7 +265,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } } @@ -273,7 +277,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } break; @@ -284,7 +288,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } break; @@ -295,7 +299,7 @@ class Inflater { return { 'result': false, 'eob': endblock, - 'output': _output + 'output': _output, }; } break; @@ -307,7 +311,7 @@ class Inflater { return { 'result': true, 'eob': endblock, - 'output': _output + 'output': _output, }; } @@ -410,13 +414,22 @@ class Inflater { break; } - final List literalTreeCodeLength = - List.filled(HuffmanTree.maxLTree, 0); + final List literalTreeCodeLength = List.filled( + HuffmanTree.maxLTree, + 0, + ); List.copyRange(literalTreeCodeLength, 0, _codeList, 0, _llCodeCount); - final List distanceTreeCodeLength = - List.filled(HuffmanTree.maxDTree, 0); - List.copyRange(distanceTreeCodeLength, 0, _codeList, _llCodeCount, - _llCodeCount + _dCodeCount); + final List distanceTreeCodeLength = List.filled( + HuffmanTree.maxDTree, + 0, + ); + List.copyRange( + distanceTreeCodeLength, + 0, + _codeList, + _llCodeCount, + _llCodeCount + _dCodeCount, + ); _llTree = HuffmanTree(code: literalTreeCodeLength); _distanceTree = HuffmanTree(code: distanceTreeCodeLength); _inflaterstate = InflaterState.decodeTop; @@ -670,7 +683,7 @@ class Inflater { 163, 195, 227, - 258 + 258, ]; static const List _distanceBasePosition = [ 1, @@ -704,7 +717,7 @@ class Inflater { 16385, 24577, 0, - 0 + 0, ]; static const List _codeOrder = [ 16, @@ -725,7 +738,7 @@ class Inflater { 2, 14, 1, - 15 + 15, ]; static const List _staticDistanceTreeTable = [ 0x00, @@ -759,7 +772,7 @@ class Inflater { 0x07, 0x17, 0x0f, - 0x1f + 0x1f, ]; static const List _extraLengthBits = [ 0, @@ -790,6 +803,6 @@ class Inflater { 5, 5, 5, - 0 + 0, ]; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/enums.dart index 05a6e2f00..5ffc60e11 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/enums.dart @@ -67,7 +67,7 @@ enum InflaterState { vFooter, /// internal enumerator - done + done, } /// internal enumerator @@ -79,5 +79,5 @@ enum BlockType { staticType, /// internal enumerator - dynamicType + dynamicType, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_png_filter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_png_filter.dart index 560ab9fec..e1a5ebe4b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_png_filter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_png_filter.dart @@ -16,8 +16,10 @@ class PdfPngFilter { /// internal method List decompress(List data, int bytesPerRow) { if (bytesPerRow <= 0) { - throw ArgumentError.value(bytesPerRow, - 'There cannot be less or equal to zero bytes in a line.'); + throw ArgumentError.value( + bytesPerRow, + 'There cannot be less or equal to zero bytes in a line.', + ); } return _modify(data, bytesPerRow + 1, _decompressFilter, false); } @@ -40,36 +42,78 @@ class PdfPngFilter { return result; } - List _decompressData(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR) { + List _decompressData( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ) { final _Type type = _getType(data[inIndex]); switch (type) { case _Type.none: - result = - _decompressNone(data, inIndex + 1, inBPR, result, resIndex, resBPR); + result = _decompressNone( + data, + inIndex + 1, + inBPR, + result, + resIndex, + resBPR, + ); break; case _Type.sub: - result = - _deompressSub(data, inIndex + 1, inBPR, result, resIndex, resBPR); + result = _deompressSub( + data, + inIndex + 1, + inBPR, + result, + resIndex, + resBPR, + ); break; case _Type.up: - result = - _decompressUp(data, inIndex + 1, inBPR, result, resIndex, resBPR); + result = _decompressUp( + data, + inIndex + 1, + inBPR, + result, + resIndex, + resBPR, + ); break; case _Type.average: result = _decompressAverage( - data, inIndex + 1, inBPR, result, resIndex, resBPR); + data, + inIndex + 1, + inBPR, + result, + resIndex, + resBPR, + ); break; case _Type.paeth: result = _decompressPaeth( - data, inIndex + 1, inBPR, result, resIndex, resBPR); + data, + inIndex + 1, + inBPR, + result, + resIndex, + resBPR, + ); break; } return result; } - List _decompressNone(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR) { + List _decompressNone( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ) { for (int i = 1; i < inBPR; ++i) { result[resIndex] = data[inIndex]; ++resIndex; @@ -78,24 +122,36 @@ class PdfPngFilter { return result; } - List _deompressSub(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR) { + List _deompressSub( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ) { for (int i = 0; i < resBPR; ++i) { - result[resIndex] = - (data[inIndex] + ((i > 0) ? result[resIndex - 1] : 0)).toUnsigned(8); + result[resIndex] = (data[inIndex] + ((i > 0) ? result[resIndex - 1] : 0)) + .toUnsigned(8); ++resIndex; ++inIndex; } return result; } - List _decompressUp(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR) { + List _decompressUp( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ) { int prevIndex = resIndex - resBPR; for (int i = 0; i < resBPR; ++i) { - result[resIndex] = - (data[inIndex] + ((prevIndex < 0) ? 0 : result[prevIndex])) - .toUnsigned(8); + result[resIndex] = (data[inIndex] + + ((prevIndex < 0) ? 0 : result[prevIndex])) + .toUnsigned(8); ++resIndex; ++inIndex; ++prevIndex; @@ -103,8 +159,14 @@ class PdfPngFilter { return result; } - List _decompressAverage(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR) { + List _decompressAverage( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ) { int prevIndex = resIndex - resBPR; final List previous = List.filled(resBPR, 0, growable: true); for (int i = 0; i < resBPR; i++) { @@ -114,8 +176,9 @@ class PdfPngFilter { if (prevIndex < 0) { result[resIndex] = (data[inIndex] + previous[resIndex]).toUnsigned(8); } else { - result[resIndex] = - (data[inIndex] + (result[prevIndex] / 2)).toInt().toUnsigned(8); + result[resIndex] = (data[inIndex] + (result[prevIndex] / 2)) + .toInt() + .toUnsigned(8); } ++prevIndex; ++resIndex; @@ -141,8 +204,14 @@ class PdfPngFilter { return result; } - List _decompressPaeth(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR) { + List _decompressPaeth( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ) { int prevIndex = resIndex - resBPR; for (int i = 0; i < resBPR; i++) { result[resIndex + i] = data[inIndex + i]; @@ -156,8 +225,8 @@ class PdfPngFilter { final int a = result[resIndex - bytesPerPixel] & 0xff; final int b = result[prevIndex] & 0xff; final int c = result[prevIndex - bytesPerPixel] & 0xff; - result[resIndex] = - (result[resIndex] + _paethPredictor(a, b, c)).toUnsigned(8); + result[resIndex] = (result[resIndex] + _paethPredictor(a, b, c)) + .toUnsigned(8); ++resIndex; ++inIndex; ++prevIndex; @@ -199,8 +268,15 @@ class PdfPngFilter { } //Delegates -typedef _RowFilter = List Function(List data, int inIndex, int inBPR, - List result, int resIndex, int resBPR); +typedef _RowFilter = + List Function( + List data, + int inIndex, + int inBPR, + List result, + int resIndex, + int resBPR, + ); //Enum enum _Type { none, sub, up, average, paeth } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_zlib_compressor.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_zlib_compressor.dart index 3bc27fdf5..ab2dc822c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_zlib_compressor.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/compression/pdf_zlib_compressor.dart @@ -40,8 +40,11 @@ class PdfZlibCompressor { int? numRead = 0; outputStream = []; do { - final Map result = - deflateStream.read(buffer, 0, buffer.length); + final Map result = deflateStream.read( + buffer, + 0, + buffer.length, + ); numRead = result['count'] as int?; buffer = result['data'] as List; for (int i = 0; i < numRead!; i++) { @@ -84,8 +87,11 @@ class PdfAscii85Compressor { switch (c) { case 'z': if (count != 0) { - throw ArgumentError.value(c, 'c', - 'The character "z" is invalid inside an ASCII85 block.'); + throw ArgumentError.value( + c, + 'c', + 'The character "z" is invalid inside an ASCII85 block.', + ); } _decodedBlock = List.filled(4, 0, growable: true); for (int i = 0; i < _decodedBlock.length; i++) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/drawing/color.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/drawing/color.dart index 9bb7da46b..8e8872b8e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/drawing/color.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/drawing/color.dart @@ -1087,5 +1087,5 @@ enum KnownColor { yellow, /// internal enumerator - yellowGreen + yellowGreen, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/enums.dart index 96dee65bc..ca9af76f0 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/enums.dart @@ -7,5 +7,5 @@ enum TextSearchOption { caseSensitive, /// Searches words with both the case sensitive and whole word. - both + both, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/font_structure.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/font_structure.dart index d00fde883..87d753c28 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/font_structure.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/font_structure.dart @@ -39,8 +39,9 @@ class FontStructure { if (fontDictionary['CharProcs'] is PdfDictionary) { charProcs = fontDictionary['CharProcs'] as PdfDictionary?; } else { - charProcs = (fontDictionary['CharProcs']! as PdfReferenceHolder) - .object as PdfDictionary?; + charProcs = + (fontDictionary['CharProcs']! as PdfReferenceHolder).object + as PdfDictionary?; } final List names = charProcs!.items!.keys.toList(); int i = 0; @@ -182,7 +183,7 @@ class FontStructure { /// internal field bool macRomanEncoded = false; -//Properties + //Properties /// internal property String? get fontEncoding => _fontEncoding ??= getFontEncoding(); @@ -319,13 +320,13 @@ class FontStructure { 'HYSMyeongJo-Medium,BoldItalic', 'HYSMyeongJo-Medium,Bold', 'HYSMyeongJo-Medium,Italic', - 'HYSMyeongJo-Medium' + 'HYSMyeongJo-Medium', ]; cjkEncoding = [ 'UniKS-UCS2-H', 'UniJIS-UCS2-H', 'UniCNS-UCS2-H', - 'UniGB-UCS2-H' + 'UniGB-UCS2-H', ]; standardFontNames = [ 'Helvetica', @@ -352,7 +353,7 @@ class FontStructure { 'Times-Italic', 'Times-BoldItalic', 'Symbol', - 'ZapfDingbats' + 'ZapfDingbats', ]; _windows1252MapTable = [ '\u0000', @@ -609,7 +610,7 @@ class FontStructure { 'ü', 'ý', 'þ', - 'ÿ' + 'ÿ', ]; } @@ -648,8 +649,9 @@ class FontStructure { final IPdfPrimitive? primitiveObject = referenceholder.object; if (primitiveObject != null && primitiveObject is PdfDictionary) { final PdfDictionary dictionary = primitiveObject; - if (dictionary - .containsKey(PdfDictionaryProperties.fontDescriptor)) { + if (dictionary.containsKey( + PdfDictionaryProperties.fontDescriptor, + )) { IPdfPrimitive? fontDescriptor = dictionary[PdfDictionaryProperties.fontDescriptor]; PdfDictionary? descriptorDictionary; @@ -663,8 +665,9 @@ class FontStructure { descriptorDictionary = fontDescriptor; } if (descriptorDictionary != null && - descriptorDictionary - .containsKey(PdfDictionaryProperties.flags)) { + descriptorDictionary.containsKey( + PdfDictionaryProperties.flags, + )) { primitive = descriptorDictionary[PdfDictionaryProperties.flags]; if (primitive is PdfNumber) { @@ -788,14 +791,14 @@ class FontStructure { int firstChar = 0; final PdfDictionary dictionary = fontDictionary; if (dictionary.containsKey(PdfDictionaryProperties.dw)) { - defaultGlyphWidth = (dictionary[PdfDictionaryProperties.dw]! as PdfNumber) - .value! - .toDouble(); + defaultGlyphWidth = + (dictionary[PdfDictionaryProperties.dw]! as PdfNumber).value! + .toDouble(); } if (dictionary.containsKey(PdfDictionaryProperties.firstChar)) { - firstChar = (dictionary[PdfDictionaryProperties.firstChar]! as PdfNumber) - .value! - .toInt(); + firstChar = + (dictionary[PdfDictionaryProperties.firstChar]! as PdfNumber).value! + .toInt(); } _fontGlyphWidth = {}; PdfArray? w; @@ -862,8 +865,9 @@ class FontStructure { _fontGlyphWidth![entryValue] = (tempW[j]! as PdfNumber).value!.toInt(); } - } else if (differencesDictionary - .containsKey(index.toString())) { + } else if (differencesDictionary.containsKey( + index.toString(), + )) { if (!_fontGlyphWidth!.containsKey(index)) { _fontGlyphWidth![index] = (tempW[j]! as PdfNumber).value!.toInt(); @@ -909,8 +913,9 @@ class FontStructure { } if (baseFont != null) { _standardFontName = baseFont.name; - result &= - standardFontNames.contains(_resolveFontName(_standardFontName)); + result &= standardFontNames.contains( + _resolveFontName(_standardFontName), + ); } else { result = false; } @@ -950,7 +955,8 @@ class FontStructure { } } result &= encoding != null && cjkEncoding.contains(encoding.name); - result &= _standardCJKFontName != '' && + result &= + _standardCJKFontName != '' && standardCJKFontNames.contains(_standardCJKFontName); } else { result = false; @@ -989,8 +995,11 @@ class FontStructure { final List styles = _getFontStyle(_standardFontName!); if (styles.contains(PdfFontStyle.bold) && styles.contains(PdfFontStyle.italic)) { - font = PdfStandardFont(fontFamily, size, - multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic]); + font = PdfStandardFont( + fontFamily, + size, + multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic], + ); } else if (styles.contains(PdfFontStyle.bold)) { font = PdfStandardFont(fontFamily, size, style: PdfFontStyle.bold); } else if (styles.contains(PdfFontStyle.italic)) { @@ -1005,13 +1014,17 @@ class FontStructure { /// internal method PdfFont? createStandardCJKFont(double size) { if (_standardCJKFontName != '') { - final PdfCjkFontFamily fontFamily = - _getCJKFontFamily(_standardCJKFontName!); + final PdfCjkFontFamily fontFamily = _getCJKFontFamily( + _standardCJKFontName!, + ); final List styles = _getCJKFontStyle(_standardCJKFontName!); if (styles.contains(PdfFontStyle.bold) && styles.contains(PdfFontStyle.italic)) { - font = PdfCjkStandardFont(fontFamily, size, - multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic]); + font = PdfCjkStandardFont( + fontFamily, + size, + multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic], + ); } else if (styles.contains(PdfFontStyle.bold)) { font = PdfCjkStandardFont(fontFamily, size, style: PdfFontStyle.bold); } else if (styles.contains(PdfFontStyle.italic)) { @@ -1095,18 +1108,22 @@ class FontStructure { } else { PdfDictionary? baseFontDict = PdfDictionary(); if (fontDictionary[PdfDictionaryProperties.encoding] is PdfDictionary) { - baseFontDict = fontDictionary[PdfDictionaryProperties.encoding] - as PdfDictionary?; + baseFontDict = + fontDictionary[PdfDictionaryProperties.encoding] + as PdfDictionary?; if (baseFontDict == null) { - baseFont = (fontDictionary[PdfDictionaryProperties.encoding]! - as PdfReferenceHolder) - .object as PdfName?; + baseFont = + (fontDictionary[PdfDictionaryProperties.encoding]! + as PdfReferenceHolder) + .object + as PdfName?; fontEncoding = baseFont!.name; } } else if (fontDictionary[PdfDictionaryProperties.encoding] is PdfReferenceHolder) { final IPdfPrimitive? primitive = PdfCrossTable.dereference( - fontDictionary[PdfDictionaryProperties.encoding]); + fontDictionary[PdfDictionaryProperties.encoding], + ); if (primitive != null && primitive is PdfName) { baseFont = primitive; fontEncoding = baseFont.name; @@ -1148,9 +1165,11 @@ class FontStructure { baseFont = fontDictionary[PdfDictionaryProperties.baseFont] as PdfName?; } else if (fontDictionary[PdfDictionaryProperties.baseFont] is PdfReferenceHolder) { - baseFont = (fontDictionary[PdfDictionaryProperties.baseFont]! - as PdfReferenceHolder) - .object as PdfName?; + baseFont = + (fontDictionary[PdfDictionaryProperties.baseFont]! + as PdfReferenceHolder) + .object + as PdfName?; } String font = baseFont!.name!; if (font.contains('#20') && !font.contains('+')) { @@ -1381,17 +1400,23 @@ class FontStructure { final int numberOfCharacters = tableValue.length ~/ 4; for (int j2 = 0; j2 < numberOfCharacters; j2++) { final String mapChar = String.fromCharCode( - int.parse(tableValue.substring(0, 4), radix: 16) - .toSigned(64)); + int.parse( + tableValue.substring(0, 4), + radix: 16, + ).toSigned(64), + ); tableValue = tableValue.substring(4); mapValue += mapChar; } mapValue = checkContainInvalidChar(mapValue); if (!mapTable.containsKey( - int.parse(tmpList[0], radix: 16).toSigned(64))) { - mapTable[int.parse(tmpList[0], radix: 16) - .toSigned(64) - .toDouble()] = mapValue; + int.parse(tmpList[0], radix: 16).toSigned(64), + )) { + mapTable[int.parse( + tmpList[0], + radix: 16, + ).toSigned(64).toDouble()] = + mapValue; } continue; } @@ -1399,13 +1424,16 @@ class FontStructure { tmpList[0] != '' && tmpList[1] != '' && !mapTable.containsKey( - int.parse(tmpList[0], radix: 16) - .toSigned(64))) { + int.parse(tmpList[0], radix: 16).toSigned(64), + )) { final String mapValue = String.fromCharCode( - int.parse(tmpList[1], radix: 16).toSigned(64)); - mapTable[int.parse(tmpList[0], radix: 16) - .toSigned(64) - .toDouble()] = mapValue; + int.parse(tmpList[1], radix: 16).toSigned(64), + ); + mapTable[int.parse( + tmpList[0], + radix: 16, + ).toSigned(64).toDouble()] = + mapValue; } } } @@ -1422,28 +1450,37 @@ class FontStructure { final int numberOfCharacters = tableValue.length ~/ 4; for (int j = 0; j < numberOfCharacters; j++) { final String mapChar = String.fromCharCode( - int.parse(tableValue.substring(0, 4), radix: 16) - .toSigned(64)); + int.parse( + tableValue.substring(0, 4), + radix: 16, + ).toSigned(64), + ); tableValue = tableValue.substring(4); mapValue += mapChar; } mapValue = checkContainInvalidChar(mapValue); if (!mapTable.containsKey( - int.parse(tempStringList[0], radix: 16) - .toSigned(64))) { - mapTable[int.parse(tempStringList[0], radix: 16) - .toSigned(64) - .toDouble()] = mapValue; + int.parse(tempStringList[0], radix: 16).toSigned(64), + )) { + mapTable[int.parse( + tempStringList[0], + radix: 16, + ).toSigned(64).toDouble()] = + mapValue; } continue; } if (!mapTable.containsKey( - int.parse(tempStringList[0]).toSigned(64))) { + int.parse(tempStringList[0]).toSigned(64), + )) { final String mapValue = String.fromCharCode( - int.parse(tempStringList[1], radix: 16).toSigned(64)); - mapTable[int.parse(tempStringList[0], radix: 16) - .toSigned(64) - .toDouble()] = mapValue; + int.parse(tempStringList[1], radix: 16).toSigned(64), + ); + mapTable[int.parse( + tempStringList[0], + radix: 16, + ).toSigned(64).toDouble()] = + mapValue; } } } @@ -1457,13 +1494,17 @@ class FontStructure { final int subArrayStatIndex = tableEntry[i].indexOf('['); final int subArrayEndIndex = tableEntry[i].indexOf(']'); if (subArrayEndIndex == -1) { - str = tableEntry[i] - .substring(subArrayStatIndex, tableEntry[i].length); + str = tableEntry[i].substring( + subArrayStatIndex, + tableEntry[i].length, + ); i++; while (true) { if (tableEntry[i].contains(']')) { - str += tableEntry[i] - .substring(0, tableEntry[i].indexOf(']')); + str += tableEntry[i].substring( + 0, + tableEntry[i].indexOf(']'), + ); break; } else { str += tableEntry[i]; @@ -1471,8 +1512,10 @@ class FontStructure { } } } else { - str = tableEntry[i] - .substring(subArrayStatIndex, subArrayEndIndex); + str = tableEntry[i].substring( + subArrayStatIndex, + subArrayEndIndex, + ); } List subArray = []; subArray = getHexCode(str); @@ -1487,27 +1530,39 @@ class FontStructure { } endOfTable = i; if (tempStringList.length > 1) { - startRange = int.parse(tempStringList[0], radix: 16) - .toSigned(64) - .toDouble(); - endRange = int.parse(tempStringList[1], radix: 16) - .toSigned(64) - .toDouble(); + startRange = + int.parse( + tempStringList[0], + radix: 16, + ).toSigned(64).toDouble(); + endRange = + int.parse( + tempStringList[1], + radix: 16, + ).toSigned(64).toDouble(); int t = 0; - for (double j = startRange, k = 0; - j <= endRange; - j++, k++, t++) { + for ( + double j = startRange, k = 0; + j <= endRange; + j++, k++, t++ + ) { String mapString = ''; int l = 0; while (l < subArray[t].length) { - final String mapValueHex = - subArray[t].substring(l, l + 4); - final int hexEquivalent = - int.parse(mapValueHex, radix: 16).toSigned(64); + final String mapValueHex = subArray[t].substring( + l, + l + 4, + ); + final int hexEquivalent = int.parse( + mapValueHex, + radix: 16, + ).toSigned(64); final int hex = hexEquivalent; final String hexString = hex.toRadixString(16); - final int mapValue = - int.parse(hexString, radix: 16).toSigned(64); + final int mapValue = int.parse( + hexString, + radix: 16, + ).toSigned(64); final String mapChar = String.fromCharCode(mapValue); mapString += mapChar; l += 4; @@ -1520,33 +1575,46 @@ class FontStructure { } else { tempStringList = getHexCode(tableEntry[i]); if (tempStringList.length == 3) { - startRange = int.parse(tempStringList[0], radix: 16) - .toSigned(64) - .toDouble(); - endRange = int.parse(tempStringList[1], radix: 16) - .toSigned(64) - .toDouble(); + startRange = + int.parse( + tempStringList[0], + radix: 16, + ).toSigned(64).toDouble(); + endRange = + int.parse( + tempStringList[1], + radix: 16, + ).toSigned(64).toDouble(); String mapValueHex = tempStringList[2]; if (tempStringList[2].length > 4) { final String mapFirstHex = mapValueHex.substring(0, 4); - final int hexFirstEquivalent = - int.parse(mapFirstHex, radix: 16).toSigned(64); + final int hexFirstEquivalent = int.parse( + mapFirstHex, + radix: 16, + ).toSigned(64); final int mapFirstValue = int.parse( - hexFirstEquivalent.toRadixString(16), - radix: 16) - .toSigned(64); - final String mapFirstChar = - String.fromCharCode(mapFirstValue); + hexFirstEquivalent.toRadixString(16), + radix: 16, + ).toSigned(64); + final String mapFirstChar = String.fromCharCode( + mapFirstValue, + ); mapValueHex = mapValueHex.substring(5, 8); - final int hexEquivalent = - int.parse(mapValueHex, radix: 16).toSigned(64); - for (double j = startRange, k = 0; - j <= endRange; - j++, k++) { + final int hexEquivalent = int.parse( + mapValueHex, + radix: 16, + ).toSigned(64); + for ( + double j = startRange, k = 0; + j <= endRange; + j++, k++ + ) { final int hex = hexEquivalent + k.toInt(); final String hexString = hex.toRadixString(16); - final int mapValue = - int.parse(hexString, radix: 16).toSigned(64); + final int mapValue = int.parse( + hexString, + radix: 16, + ).toSigned(64); String mapChar = mapFirstChar + String.fromCharCode(mapValue); mapChar = checkContainInvalidChar(mapChar); @@ -1555,15 +1623,21 @@ class FontStructure { } } } else { - final int hexEquivalent = - int.parse(mapValueHex, radix: 16).toSigned(64); - for (double j = startRange, k = 0; - j <= endRange; - j++, k++) { + final int hexEquivalent = int.parse( + mapValueHex, + radix: 16, + ).toSigned(64); + for ( + double j = startRange, k = 0; + j <= endRange; + j++, k++ + ) { final int hex = hexEquivalent + k.toInt(); final String hexString = hex.toRadixString(16); - final int mapValue = - int.parse(hexString, radix: 16).toSigned(64); + final int mapValue = int.parse( + hexString, + radix: 16, + ).toSigned(64); final String mapChar = String.fromCharCode(mapValue); if (!mapTable.containsKey(j)) { mapTable[j] = mapChar; @@ -1575,11 +1649,16 @@ class FontStructure { semiCount = tempStringList.length; for (int k = 0; k < semiCount;) { final String mapValue = String.fromCharCode( - int.parse(tempStringList[k + 2], radix: 16) - .toSigned(64)); - mapTable[int.parse(tempStringList[k], radix: 16) - .toSigned(64) - .toDouble()] = mapValue; + int.parse( + tempStringList[k + 2], + radix: 16, + ).toSigned(64), + ); + mapTable[int.parse( + tempStringList[k], + radix: 16, + ).toSigned(64).toDouble()] = + mapValue; k = k + 3; } } @@ -1616,7 +1695,8 @@ class FontStructure { if (fontDictionary[PdfDictionaryProperties.encoding] is PdfReferenceHolder) { final IPdfPrimitive? primitive = PdfCrossTable.dereference( - fontDictionary[PdfDictionaryProperties.encoding]); + fontDictionary[PdfDictionaryProperties.encoding], + ); if (primitive != null && primitive is PdfDictionary) { encodingDictionary = primitive; } @@ -1627,8 +1707,9 @@ class FontStructure { } if (encodingDictionary != null) { - if (encodingDictionary - .containsKey(PdfDictionaryProperties.differences)) { + if (encodingDictionary.containsKey( + PdfDictionaryProperties.differences, + )) { int differenceCount = 0; final IPdfPrimitive? obj = encodingDictionary[PdfDictionaryProperties.differences]; @@ -1649,16 +1730,17 @@ class FontStructure { text = (differences[i]! as PdfName).name; if ((fontType!.name == 'Type1') && (text == '.notdef')) { text = ' '; - differencesDictionary[differenceCount.toString()] = - getLatinCharacter(text); + differencesDictionary[differenceCount + .toString()] = getLatinCharacter(text); differenceCount++; } else { text = getLatinCharacter(text); text = getSpecialCharacter(text); - if (!differencesDictionary - .containsKey(differenceCount.toString())) { - differencesDictionary[differenceCount.toString()] = - getLatinCharacter(text); + if (!differencesDictionary.containsKey( + differenceCount.toString(), + )) { + differencesDictionary[differenceCount + .toString()] = getLatinCharacter(text); } differenceCount++; } @@ -2510,8 +2592,11 @@ class FontStructure { } /// internal method - String decodeTextExtraction(String textToDecode, bool isSameFont, - [List? charcodes]) { + String decodeTextExtraction( + String textToDecode, + bool isSameFont, [ + List? charcodes, + ]) { String decodedText = ''; String encodedText = textToDecode; this.isSameFont = isSameFont; @@ -2540,10 +2625,11 @@ class FontStructure { 'UniCNS-UCS2-H', 'UniKS-UCS2-H', 'UniJIS-UCS2-H', - 'UniGB-UCS2-H' + 'UniGB-UCS2-H', ].contains( - (fontDictionary[PdfDictionaryProperties.encoding]! as PdfName) - .name)) { + (fontDictionary[PdfDictionaryProperties.encoding]! as PdfName) + .name, + )) { String text = decodedText; if (!hasEscapeChar) { do { @@ -2599,23 +2685,29 @@ class FontStructure { } } - final String tempString = - encodedText.substring(textStart + 1, textEnd); + final String tempString = encodedText.substring( + textStart + 1, + textEnd, + ); if (isHex) { decodedText += getHexaDecimalString(tempString, charcodes); } else { decodedText += getLiteralString(tempString, charcodes); } - encodedText = - encodedText.substring(textEnd + 1, encodedText.length); + encodedText = encodedText.substring( + textEnd + 1, + encodedText.length, + ); } } break; case '<': { - final String hexEncodedText = - encodedText.substring(1, encodedText.length - 1); + final String hexEncodedText = encodedText.substring( + 1, + encodedText.length - 1, + ); decodedText = getHexaDecimalString(hexEncodedText, charcodes); isHex = true; } @@ -2735,9 +2827,10 @@ class FontStructure { decodedList.add(listElement); } final String tempString = encodedText.substring(textStart + 1, textEnd); - listElement = isHex - ? getHexaDecimalCJKString(tempString) - : getLiteralString(tempString); + listElement = + isHex + ? getHexaDecimalCJKString(tempString) + : getLiteralString(tempString); decodedText += listElement; listElement = skipEscapeSequence(listElement); if (listElement.isNotEmpty) { @@ -2745,8 +2838,11 @@ class FontStructure { listElement[0].codeUnitAt(0) <= 3711 && decodedList.isNotEmpty) { String previous = decodedList[0]; - previous = - previous.replaceRange(previous.length - 1, previous.length, ''); + previous = previous.replaceRange( + previous.length - 1, + previous.length, + '', + ); previous += listElement; listElement = previous; decodedList[0] = '${fromUnicodeText(listElement)}s'; @@ -2758,7 +2854,10 @@ class FontStructure { decodedList.isNotEmpty) { String previous = decodedList[0]; previous = previous.replaceRange( - previous.length - 1, previous.length, ''); + previous.length - 1, + previous.length, + '', + ); previous += listElement; listElement = previous; decodedList[0] = '${fromUnicodeText(listElement)}s'; @@ -2797,7 +2896,9 @@ class FontStructure { /// internal method Map, String> decodeTextExtractionTJ( - String textToDecode, bool isSameFont) { + String textToDecode, + bool isSameFont, + ) { String decodedText = ''; String encodedText = textToDecode; String listElement; @@ -2900,8 +3001,10 @@ class FontStructure { charCodes = []; } } - final String tempString = - encodedText.substring(textStart + 1, textEnd); + final String tempString = encodedText.substring( + textStart + 1, + textEnd, + ); if (isHex) { listElement = getHexaDecimalString(tempString, charCodes); if (listElement.contains(r'\')) { @@ -2916,7 +3019,9 @@ class FontStructure { if (listElement.contains('\u0000') && !characterMapTable.containsKey(0)) { listElement = listElement.replaceAll( - '\u0000', ''); //replace empty character. + '\u0000', + '', + ); //replace empty character. } listElement = skipEscapeSequence(listElement); if (fontEncoding != 'Identity-H' || @@ -2950,7 +3055,10 @@ class FontStructure { decodedList.isNotEmpty) { String previous = decodedList.values.toList()[0]; previous = previous.replaceRange( - previous.length - 1, previous.length, ''); + previous.length - 1, + previous.length, + '', + ); previous += listElement; listElement = previous; decodedList[decodedList.keys.toList()[0]] = '${listElement}s'; @@ -2962,7 +3070,10 @@ class FontStructure { decodedList.isNotEmpty) { String previous = decodedList.values.toList()[0]; previous = previous.replaceRange( - previous.length - 1, previous.length, ''); + previous.length - 1, + previous.length, + '', + ); previous += listElement; listElement = previous; decodedList[decodedList.keys.toList()[0]] = '${listElement}s'; @@ -2981,15 +3092,19 @@ class FontStructure { decodedList[charCodes] = listElement; charCodes = []; } - encodedText = - encodedText.substring(textEnd + 1, encodedText.length); + encodedText = encodedText.substring( + textEnd + 1, + encodedText.length, + ); } } break; case '<': { - final String hexEncodedText = - encodedText.substring(1, encodedText.length - 1); + final String hexEncodedText = encodedText.substring( + 1, + encodedText.length - 1, + ); decodedText = getHexaDecimalString(hexEncodedText, charCodes); } break; @@ -2997,7 +3112,10 @@ class FontStructure { break; } decodedText = skipEscapeSequence(decodedText); - isWhiteSpace = decodedText.isEmpty || decodedText.trimRight() == ''; + isWhiteSpace = + decodedText.isEmpty || + (!decodedText.contains(RegExp(r'[\f\r]')) && + decodedText.trimRight().isEmpty); return decodedList; } @@ -3008,7 +3126,8 @@ class FontStructure { for (int i = 0; i < value.length; i++) { if (i + 1 < value.length) { result += String.fromCharCode( - (value.codeUnitAt(i) * 256) + value.codeUnitAt(i + 1)); + (value.codeUnitAt(i) * 256) + value.codeUnitAt(i + 1), + ); i++; } else { result += String.fromCharCode(value.codeUnitAt(i)); @@ -3017,7 +3136,8 @@ class FontStructure { } else { for (int i = 0; i < value.length; i++) { result += String.fromCharCode( - (value.codeUnitAt(i) * 256) + value.codeUnitAt(i + 1)); + (value.codeUnitAt(i) * 256) + value.codeUnitAt(i + 1), + ); i++; } } @@ -3142,8 +3262,10 @@ class FontStructure { } } } - final String tempString = - textToEncode.substring(textStart + 1, textEnd); + final String tempString = textToEncode.substring( + textStart + 1, + textEnd, + ); if (isHex) { encodedText += getHexaDecimalString(tempString); } else if (!isHex && fontEncoding == 'Identity-H') { @@ -3151,15 +3273,19 @@ class FontStructure { } else { encodedText += getLiteralString(tempString); } - textToEncode = - textToEncode.substring(textEnd + 1, textToEncode.length); + textToEncode = textToEncode.substring( + textEnd + 1, + textToEncode.length, + ); } } break; case '<': { - final String hexEncodedText = - textToEncode.substring(1, textToEncode.length - 1); + final String hexEncodedText = textToEncode.substring( + 1, + textToEncode.length - 1, + ); encodedText = getHexaDecimalString(hexEncodedText); if (encodedText.contains(r'\')) { // ignore: use_raw_strings @@ -3178,7 +3304,10 @@ class FontStructure { if (!isTextExtraction) { encodedText = skipEscapeSequence(encodedText); } - isWhiteSpace = encodedText.isEmpty || encodedText.trimRight() == ''; + isWhiteSpace = + encodedText.isEmpty || + (!encodedText.contains(RegExp(r'[\f\r]')) && + encodedText.trimRight().isEmpty); return encodedText; } @@ -3198,8 +3327,9 @@ class FontStructure { primitive = (descendantFontArray[0]! as PdfReferenceHolder).object; if (primitive is PdfDictionary) { final PdfDictionary descendantDictionary = primitive; - if (descendantDictionary - .containsKey(PdfDictionaryProperties.subtype)) { + if (descendantDictionary.containsKey( + PdfDictionaryProperties.subtype, + )) { primitive = descendantDictionary[PdfDictionaryProperties.subtype]; if (primitive is PdfName) { @@ -3222,8 +3352,9 @@ class FontStructure { primitive = (descendantFontArray[0]! as PdfReferenceHolder).object; if (primitive is PdfDictionary) { final PdfDictionary descendantDictionary = primitive; - if (descendantDictionary - .containsKey(PdfDictionaryProperties.subtype)) { + if (descendantDictionary.containsKey( + PdfDictionaryProperties.subtype, + )) { primitive = descendantDictionary[PdfDictionaryProperties.subtype]; if (primitive is PdfName) { final PdfName subtype = @@ -3326,9 +3457,9 @@ class FontStructure { encodedText = unescape(encodedText!); } catch (e) { if (encodedText != null && encodedText.isNotEmpty) { - encodedText = RegExp.escape(encodedText) - .replaceAll(r"\'''", r"'''") - .replaceAll(r'\\', r'\'); + encodedText = RegExp.escape( + encodedText, + ).replaceAll(r"\'''", r"'''").replaceAll(r'\\', r'\'); } else { throw ArgumentError(e.toString()); } @@ -3350,7 +3481,8 @@ class FontStructure { if (textDecoded.length == 7 && textDecoded.toLowerCase().startsWith('uni')) { textDecoded = String.fromCharCode( - int.parse(textDecoded.substring(3), radix: 16)); + int.parse(textDecoded.substring(3), radix: 16), + ); } decodedText += textDecoded; } else { @@ -3365,8 +3497,9 @@ class FontStructure { } } } - if (!reverseDictMapping - .containsKey(differencesDictionary[character.toString()])) { + if (!reverseDictMapping.containsKey( + differencesDictionary[character.toString()], + )) { reverseDictMapping[differencesDictionary[character.toString()]] = character; } @@ -3383,15 +3516,17 @@ class FontStructure { if (skip) { switch (encodedText[i]) { case 'n': - if (differencesDictionary - .containsKey('\n'.codeUnitAt(0).toString())) { + if (differencesDictionary.containsKey( + '\n'.codeUnitAt(0).toString(), + )) { decodedText += differencesDictionary['\n'.codeUnitAt(0).toString()]!; } break; case 'r': - if (differencesDictionary - .containsKey('\r'.codeUnitAt(0).toString())) { + if (differencesDictionary.containsKey( + '\r'.codeUnitAt(0).toString(), + )) { decodedText += differencesDictionary['\r'.codeUnitAt(0).toString()]!; } @@ -4275,8 +4410,9 @@ class FontStructure { mappingString = mappingString.replaceAll(mappingString[index], ''); } if (mappingString.isNotEmpty) { - if (!cidToGidReverseMapTable - .containsKey(mappingString.codeUnitAt(0))) { + if (!cidToGidReverseMapTable.containsKey( + mappingString.codeUnitAt(0), + )) { cidToGidReverseMapTable[mappingString.codeUnitAt(0)] = character; } } @@ -4385,9 +4521,11 @@ class FontStructure { } limit = 2; } - for (int i = octalIndex + 1; - i <= octalIndex + limit; - i++) //check for octal characters + for ( + int i = octalIndex + 1; + i <= octalIndex + limit; + i++ + ) //check for octal characters { if (i < decodedText.length) { int val = 0; @@ -4420,7 +4558,7 @@ class FontStructure { temp = _getWindows1252DecodedText(charbytes); List tempchar; tempchar = [ - _getWindows1252DecodedText([decimalValue.toUnsigned(8)]) + _getWindows1252DecodedText([decimalValue.toUnsigned(8)]), ]; int charvalue = 0; for (final String tempchar1 in tempchar) { @@ -4434,7 +4572,7 @@ class FontStructure { final List charbytes = [decimalValue.toUnsigned(8)]; temp = String.fromCharCodes(charbytes); final List tempchar = [ - String.fromCharCodes([decimalValue.toUnsigned(8)]) + String.fromCharCodes([decimalValue.toUnsigned(8)]), ]; int charvalue = 0; for (final String tempchar1 in tempchar) { @@ -4447,8 +4585,11 @@ class FontStructure { } } (charCodes ??= []).add(decimalValue); - decodedText = - decodedText.replaceRange(octalIndex, octalIndex + limit + 1, ''); + decodedText = decodedText.replaceRange( + octalIndex, + octalIndex + limit + 1, + '', + ); final List str = decodedText.split(''); str.insert(octalIndex, temp); octalIndexCollection.add(octalIndex); @@ -4466,7 +4607,7 @@ class FontStructure { 'r': '\r', 't': '\t', 'v': '\v', - "'": "'" + "'": "'", }; if (decodedText.contains(r'\')) { for (int i = count - 2; i >= 0; i--) { @@ -4484,12 +4625,15 @@ class FontStructure { //Update the octal index collection and char codes, //if character map table contains the escape sequence. for (int j = 0; j < octalIndexCollection.length; j++) { - if (characterMapTable - .containsKey(escapeSequence[sequence]!.codeUnitAt(0))) { + if (characterMapTable.containsKey( + escapeSequence[sequence]!.codeUnitAt(0), + )) { if (i < octalIndexCollection[j]) { octalIndexCollection.insert(j, i); - charCodes! - .insert(j, escapeSequence[sequence]!.codeUnitAt(0)); + charCodes!.insert( + j, + escapeSequence[sequence]!.codeUnitAt(0), + ); break; } else if (j == octalIndexCollection.length - 1 && i > octalIndexCollection[j]) { @@ -4512,8 +4656,10 @@ class FontStructure { for (int i = 0; i < count; i++) { if (!octalIndexCollection.contains(i)) { if (characterMapTable.containsKey(str[i].codeUnitAt(0))) { - (charCodes ??= []) - .insert(i + combinedGlyphDiff, str[i].codeUnitAt(0)); + (charCodes ??= []).insert( + i + combinedGlyphDiff, + str[i].codeUnitAt(0), + ); } else { (charCodes ??= []).insert(i + combinedGlyphDiff, 0); } @@ -4594,8 +4740,10 @@ class FontStructure { } /// Decodes the HEX encoded string and returns Decoded string. - String getHexaDecimalString(String hexEncodedText, - [List? charCodes]) { + String getHexaDecimalString( + String hexEncodedText, [ + List? charCodes, + ]) { String decodedText = ''; // IsHexaDecimalString = true; if (hexEncodedText.isNotEmpty) { @@ -4617,25 +4765,29 @@ class FontStructure { } String hexChar = hexEncodedText.substring(0, limit); - if (fontDictionary - .containsKey(PdfDictionaryProperties.descendantFonts) && + if (fontDictionary.containsKey( + PdfDictionaryProperties.descendantFonts, + ) && !fontDictionary.containsKey(PdfDictionaryProperties.toUnicode)) { final IPdfPrimitive? descendantArray = fontDictionary[PdfDictionaryProperties.descendantFonts]; if (descendantArray != null && descendantArray is PdfArray) { PdfDictionary? descendantDictionary; if (descendantArray[0] is PdfReferenceHolder) { - descendantDictionary = (descendantArray[0]! as PdfReferenceHolder) - .object as PdfDictionary?; + descendantDictionary = + (descendantArray[0]! as PdfReferenceHolder).object + as PdfDictionary?; } else if (descendantArray[0] is PdfDictionary) { descendantDictionary = descendantArray[0]! as PdfDictionary; } if (descendantDictionary != null) { PdfDictionary? descriptorDictionary; - if (descendantDictionary - .containsKey(PdfDictionaryProperties.fontDescriptor)) { - IPdfPrimitive? primitive = descendantDictionary[ - PdfDictionaryProperties.fontDescriptor]; + if (descendantDictionary.containsKey( + PdfDictionaryProperties.fontDescriptor, + )) { + IPdfPrimitive? primitive = + descendantDictionary[PdfDictionaryProperties + .fontDescriptor]; if (primitive is PdfReferenceHolder) { primitive = primitive.object; if (primitive != null && primitive is PdfDictionary) { @@ -4646,10 +4798,12 @@ class FontStructure { } } if (descriptorDictionary != null) { - if (descendantDictionary - .containsKey(PdfDictionaryProperties.subtype) && - !descriptorDictionary - .containsKey(PdfDictionaryProperties.fontFile2)) { + if (descendantDictionary.containsKey( + PdfDictionaryProperties.subtype, + ) && + !descriptorDictionary.containsKey( + PdfDictionaryProperties.fontFile2, + )) { final PdfName subtype = descendantDictionary[PdfDictionaryProperties.subtype]! as PdfName; @@ -4659,11 +4813,13 @@ class FontStructure { } } } - } else if (fontDictionary.items! - .containsKey(PdfName(PdfDictionaryProperties.descendantFonts))) { + } else if (fontDictionary.items!.containsKey( + PdfName(PdfDictionaryProperties.descendantFonts), + )) { final PdfReferenceHolder? descendantFontArrayReference = - fontDictionary.items![ - PdfName(PdfDictionaryProperties.descendantFonts)] + fontDictionary.items![PdfName( + PdfDictionaryProperties.descendantFonts, + )] as PdfReferenceHolder?; if (descendantFontArrayReference != null) { PdfName? subtype; @@ -4674,24 +4830,31 @@ class FontStructure { (descendantFontArray[0]! as PdfReferenceHolder).object as PdfDictionary?; if (descendantDictionary != null && - descendantDictionary - .containsKey(PdfDictionaryProperties.cidSystemInfo) && - descendantDictionary - .containsKey(PdfDictionaryProperties.subtype)) { + descendantDictionary.containsKey( + PdfDictionaryProperties.cidSystemInfo, + ) && + descendantDictionary.containsKey( + PdfDictionaryProperties.subtype, + )) { subtype = descendantDictionary[PdfDictionaryProperties.subtype] as PdfName?; - final PdfDictionary? cidSystemInfo = (descendantDictionary[ - PdfDictionaryProperties.cidSystemInfo]! - as PdfReferenceHolder) - .object as PdfDictionary?; + final PdfDictionary? cidSystemInfo = + (descendantDictionary[PdfDictionaryProperties + .cidSystemInfo]! + as PdfReferenceHolder) + .object + as PdfDictionary?; if (cidSystemInfo != null && - cidSystemInfo - .containsKey(PdfDictionaryProperties.registry) && - cidSystemInfo - .containsKey(PdfDictionaryProperties.ordering) && - cidSystemInfo - .containsKey(PdfDictionaryProperties.supplement)) { + cidSystemInfo.containsKey( + PdfDictionaryProperties.registry, + ) && + cidSystemInfo.containsKey( + PdfDictionaryProperties.ordering, + ) && + cidSystemInfo.containsKey( + PdfDictionaryProperties.supplement, + )) { final PdfString pdfRegistry = cidSystemInfo[PdfDictionaryProperties.registry]! as PdfString; @@ -4731,8 +4894,10 @@ class FontStructure { decodedTxt.contains('’')) && tempHexEncodedText.length < limit) { decodedText = tempDecodedText; - final int hexNum = - int.parse(tempHexEncodedText, radix: 16).toSigned(32); + final int hexNum = int.parse( + tempHexEncodedText, + radix: 16, + ).toSigned(32); (charCodes ??= []).add(hexNum); hexEncodedText = String.fromCharCode(hexNum); decodedText += hexEncodedText; @@ -4819,7 +4984,8 @@ class FontStructure { characterMapTable.length != reverseMapTable!.length) { if (isCancel(mappingString) || isNonPrintableCharacter( - character)) //Contains 'CANCEL' of ASCII value 24 + character, + )) //Contains 'CANCEL' of ASCII value 24 { mappingString = character; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/image_renderer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/image_renderer.dart index 4505853ab..aca16d722 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/image_renderer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/image_renderer.dart @@ -14,30 +14,44 @@ import 'xobject_element.dart'; /// internal class class ImageRenderer { /// internal constructor - ImageRenderer(PdfRecordCollection? contentElements, - PdfPageResources resources, this.currentPageHeight, - [GraphicsObject? g]) { + ImageRenderer( + PdfRecordCollection? contentElements, + PdfPageResources resources, + this.currentPageHeight, [ + GraphicsObject? g, + ]) { const int dpiX = 96; _graphicsObject = GraphicsObject(); _graphicsState = GraphicStateCollection(); graphicsObjects = GraphicObjectDataCollection(); final GraphicObjectData newObject = GraphicObjectData(); - newObject.currentTransformationMatrix = - MatrixHelper(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); + newObject.currentTransformationMatrix = MatrixHelper( + 1.0, + 0.0, + 0.0, + 1.0, + 0.0, + 0.0, + ); final MatrixHelper transformMatrix = g != null ? g.transformMatrix! : _graphicsObject!.transformMatrix!; newObject.currentTransformationMatrix!.translate( - transformMatrix.offsetX / 1.333, transformMatrix.offsetY / 1.333); + transformMatrix.offsetX / 1.333, + transformMatrix.offsetY / 1.333, + ); newObject.drawing2dMatrixCTM = MatrixHelper(1, 0, 0, 1, 0, 0); newObject.drawing2dMatrixCTM!.translate( - transformMatrix.offsetX / 1.333, transformMatrix.offsetY / 1.333); + transformMatrix.offsetX / 1.333, + transformMatrix.offsetY / 1.333, + ); newObject.documentMatrix = MatrixHelper( - 1.33333333333333 * (dpiX / 96) * transformMatrix.m11, - 0, - 0, - -1.33333333333333 * (dpiX / 96) * transformMatrix.m22, - 0, - currentPageHeight! * transformMatrix.m22); + 1.33333333333333 * (dpiX / 96) * transformMatrix.m11, + 0, + 0, + -1.33333333333333 * (dpiX / 96) * transformMatrix.m22, + 0, + currentPageHeight! * transformMatrix.m22, + ); graphicsObjects!.push(newObject); graphicsObjects!.push(newObject); _contentElements = contentElements; @@ -238,8 +252,9 @@ class ImageRenderer { if (elements[1].contains('ActualText') && elements[1].contains('(')) { _actualText = elements[1].substring( - elements[1].indexOf('(') + 1, - elements[1].lastIndexOf(')')); + elements[1].indexOf('(') + 1, + elements[1].lastIndexOf(')'), + ); const String bigEndianPreambleString = 'þÿ'; if (_actualText != null && _actualText!.startsWith(bigEndianPreambleString)) { @@ -318,8 +333,9 @@ class ImageRenderer { } final GraphicsState? state = _graphicsObject!.save(); _graphicsState!.push(state); - _graphicsObject! - .multiplyTransform(MatrixHelper(a, -b, -c, d, e, -f)); + _graphicsObject!.multiplyTransform( + MatrixHelper(a, -b, -c, d, e, -f), + ); currentLocation = Offset.zero; _textMatrix = true; break; @@ -390,8 +406,9 @@ class ImageRenderer { case "'": { _moveToNextLineWithCurrentTextLeading(); - final MatrixHelper transformMatrix = - _getTextRenderingMatrix(false); + final MatrixHelper transformMatrix = _getTextRenderingMatrix( + false, + ); objects.textMatrixUpdate = transformMatrix; if (_textScaling != 100) { final GraphicsState? state = _graphicsObject!.save(); @@ -399,8 +416,9 @@ class ImageRenderer { _graphicsObject!.scaleTransform(_textScaling! / 100, 1); isScaledText = true; currentLocation = Offset( - currentLocation!.dx / (_textScaling! / 100), - currentLocation!.dy); + currentLocation!.dx / (_textScaling! / 100), + currentLocation!.dy, + ); } _renderTextElementWithLeading(elements!, token); break; @@ -414,8 +432,9 @@ class ImageRenderer { case 'TD': { currentLocation = Offset( - currentLocation!.dx + double.tryParse(elements![0])!, - currentLocation!.dy - double.tryParse(elements[1])!); + currentLocation!.dx + double.tryParse(elements![0])!, + currentLocation!.dy - double.tryParse(elements[1])!, + ); _moveToNextLineWithLeading(elements); break; } @@ -423,8 +442,10 @@ class ImageRenderer { { final double dx = double.tryParse(elements![0])!; final double dy = double.tryParse(elements[1])!; - currentLocation = - Offset(currentLocation!.dx + dx, currentLocation!.dy - dy); + currentLocation = Offset( + currentLocation!.dx + dx, + currentLocation!.dy - dy, + ); _moveToNextLine(dx, dy); break; } @@ -481,22 +502,30 @@ class ImageRenderer { } final MatrixHelper initialmatrix = documentMatrix!; final MatrixHelper currentCTM = MatrixHelper( - drawing2dMatrixCTM!.m11, - drawing2dMatrixCTM!.m12, - drawing2dMatrixCTM!.m21, - drawing2dMatrixCTM!.m22, - drawing2dMatrixCTM!.offsetX, - drawing2dMatrixCTM!.offsetY); + drawing2dMatrixCTM!.m11, + drawing2dMatrixCTM!.m12, + drawing2dMatrixCTM!.m21, + drawing2dMatrixCTM!.m22, + drawing2dMatrixCTM!.offsetX, + drawing2dMatrixCTM!.offsetY, + ); final MatrixHelper result = currentCTM * initialmatrix; final MatrixHelper transformMatrix = MatrixHelper( - result.m11, - result.m12, - result.m21, - result.m22, - result.offsetX, - result.offsetY); - MatrixHelper graphicsTransformMatrix = - MatrixHelper(1, 0, 0, 1, 0, 0); + result.m11, + result.m12, + result.m21, + result.m22, + result.offsetX, + result.offsetY, + ); + MatrixHelper graphicsTransformMatrix = MatrixHelper( + 1, + 0, + 0, + 1, + 0, + 0, + ); graphicsTransformMatrix = graphicsTransformMatrix * transformMatrix; _graphicsObject!.transformMatrix = @@ -516,12 +545,13 @@ class ImageRenderer { MatrixHelper _getTextRenderingMatrix(bool isPath) { MatrixHelper mat = MatrixHelper( - fontSize! * (objects.horizontalScaling! / 100), - 0, - 0, - isPath ? fontSize! : (-fontSize!), - 0, - (isPath ? objects.rise! : (fontSize! + objects.rise!)) as double); + fontSize! * (objects.horizontalScaling! / 100), + 0, + 0, + isPath ? fontSize! : (-fontSize!), + 0, + (isPath ? objects.rise! : (fontSize! + objects.rise!)) as double, + ); mat *= textLineMatrix! * currentTransformationMatrix!; return mat; } @@ -572,13 +602,16 @@ class ImageRenderer { _isCurrentPositionChanged = true; if ((-textLeading!) != 0) { _currentLocation = Offset( - _currentLocation!.dx, - (-textLeading!) < 0 - ? _currentLocation!.dy - (-textLeading!) - : _currentLocation!.dy + (-textLeading!)); + _currentLocation!.dx, + (-textLeading!) < 0 + ? _currentLocation!.dy - (-textLeading!) + : _currentLocation!.dy + (-textLeading!), + ); } else { - _currentLocation = - Offset(_currentLocation!.dx, _currentLocation!.dy + fontSize!); + _currentLocation = Offset( + _currentLocation!.dx, + _currentLocation!.dy + fontSize!, + ); } } @@ -600,12 +633,13 @@ class ImageRenderer { xObjectElement.pageHeight = pageHeight; } final Map result = xObjectElement.renderTextElement( - _graphicsObject, - _resources, - _graphicsState, - graphicsObjects, - currentPageHeight, - xObjectGlyphs); + _graphicsObject, + _resources, + _graphicsState, + graphicsObjects, + currentPageHeight, + xObjectGlyphs, + ); _graphicsState = result['graphicStates'] as GraphicStateCollection?; graphicsObjects = result['objects'] as GraphicObjectDataCollection?; xObjectGlyphs = result['glyphList'] as List?; @@ -622,7 +656,9 @@ class ImageRenderer { } void _renderTextElementWithLeading( - List textElements, String tokenType) { + List textElements, + String tokenType, + ) { String text = textElements.join(); final List retrievedCharCodes = []; if (_resources!.containsKey(currentFont)) { @@ -640,7 +676,10 @@ class ImageRenderer { text = structure.getEncodedText(text, true); } else { text = structure.decodeTextExtraction( - text, _resources!.isSameFont(), retrievedCharCodes); + text, + _resources!.isSameFont(), + retrievedCharCodes, + ); } if (_actualText != null && _actualText!.isNotEmpty) { text = _actualText!; @@ -684,33 +723,41 @@ class ImageRenderer { _isCurrentPositionChanged = false; _endTextPosition = currentLocation!; final Map renderedResult = element.renderTextElement( - _graphicsObject, - Offset(_endTextPosition.dx, - _endTextPosition.dy + ((-textLeading!) / 4)), - _textScaling, - glyphWidths, - structure.type1GlyphHeight, - structure.differenceTable, - structure.differencesDictionary, - structure.differenceEncoding, - tempTextMatrix, - retrievedCharCodes); + _graphicsObject, + Offset( + _endTextPosition.dx, + _endTextPosition.dy + ((-textLeading!) / 4), + ), + _textScaling, + glyphWidths, + structure.type1GlyphHeight, + structure.differenceTable, + structure.differencesDictionary, + structure.differenceEncoding, + tempTextMatrix, + retrievedCharCodes, + ); _textElementWidth = renderedResult['textElementWidth'] as double; textMatrix = renderedResult['tempTextMatrix'] as MatrixHelper; } else { _endTextPosition = Offset( - _endTextPosition.dx + _textElementWidth, _endTextPosition.dy); + _endTextPosition.dx + _textElementWidth, + _endTextPosition.dy, + ); final Map renderedResult = element.renderTextElement( - _graphicsObject, - Offset( - _endTextPosition.dx, _endTextPosition.dy + (-textLeading! / 4)), - _textScaling, - glyphWidths, - structure.type1GlyphHeight, - structure.differenceTable, - structure.differencesDictionary, - structure.differenceEncoding, - tempTextMatrix); + _graphicsObject, + Offset( + _endTextPosition.dx, + _endTextPosition.dy + (-textLeading! / 4), + ), + _textScaling, + glyphWidths, + structure.type1GlyphHeight, + structure.differenceTable, + structure.differencesDictionary, + structure.differenceEncoding, + tempTextMatrix, + ); _textElementWidth = renderedResult['textElementWidth'] as double; textMatrix = renderedResult['tempTextMatrix'] as MatrixHelper; } @@ -725,8 +772,10 @@ class ImageRenderer { _whiteSpace[0].textLineMatrix!.offsetY == element.textLineMatrix!.offsetY) { if (_whiteSpace[0].text.isNotEmpty) { - element.textElementGlyphList - .insert(0, _whiteSpace[0].textElementGlyphList[0]); + element.textElementGlyphList.insert( + 0, + _whiteSpace[0].textElementGlyphList[0], + ); } extractTextElement.add(_whiteSpace[0]); } @@ -744,7 +793,9 @@ class ImageRenderer { } void _renderTextElementWithSpacing( - List textElements, String tokenType) { + List textElements, + String tokenType, + ) { List decodedList = []; Map, String> decodedListCollection = , String>{}; @@ -758,17 +809,22 @@ class ImageRenderer { if (!structure.isEmbedded && structure.isStandardCJKFont && structure.font != null) { - decodedList = - structure.decodeCjkTextExtractionTJ(text, _resources!.isSameFont()); + decodedList = structure.decodeCjkTextExtractionTJ( + text, + _resources!.isSameFont(), + ); for (final String decodedString in decodedList) { decodedListCollection[[]] = decodedString; } } else { - decodedListCollection = - structure.decodeTextExtractionTJ(text, _resources!.isSameFont()); + decodedListCollection = structure.decodeTextExtractionTJ( + text, + _resources!.isSameFont(), + ); } - final List bytes = - utf8.encode(structure.getEncodedText(text, _resources!.isSameFont())); + final List bytes = utf8.encode( + structure.getEncodedText(text, _resources!.isSameFont()), + ); final Map encodedTextBytes = {}; int z = 0; for (int j = 0; j < bytes.length; j = j + 2) { @@ -820,20 +876,23 @@ class ImageRenderer { _endTextPosition = currentLocation!; } else { _endTextPosition = Offset( - _endTextPosition.dx + _textElementWidth, _endTextPosition.dy); + _endTextPosition.dx + _textElementWidth, + _endTextPosition.dy, + ); } final Map renderedResult = element.renderWithSpacing( - _graphicsObject, - Offset(_endTextPosition.dx, _endTextPosition.dy - fontSize!), - decodedListCollection, - characterSpacings, - _textScaling, - glyphWidths, - structure.type1GlyphHeight, - structure.differenceTable, - structure.differencesDictionary, - structure.differenceEncoding, - tempTextMatrix); + _graphicsObject, + Offset(_endTextPosition.dx, _endTextPosition.dy - fontSize!), + decodedListCollection, + characterSpacings, + _textScaling, + glyphWidths, + structure.type1GlyphHeight, + structure.differenceTable, + structure.differencesDictionary, + structure.differenceEncoding, + tempTextMatrix, + ); _textElementWidth = renderedResult['textElementWidth'] as double; textMatrix = renderedResult['tempTextMatrix'] as MatrixHelper; if (!structure.isWhiteSpace) { @@ -847,8 +906,10 @@ class ImageRenderer { _whiteSpace[0].textLineMatrix!.offsetY == element.textLineMatrix!.offsetY && _whiteSpace[0].textElementGlyphList.isNotEmpty) { - element.textElementGlyphList - .insert(0, _whiteSpace[0].textElementGlyphList[0]); + element.textElementGlyphList.insert( + 0, + _whiteSpace[0].textElementGlyphList[0], + ); extractTextElement.add(_whiteSpace[0]); } _whiteSpace = []; @@ -881,21 +942,35 @@ class ImageRenderer { } void _setTextMatrix( - double a, double b, double c, double d, double e, double f) { + double a, + double b, + double c, + double d, + double e, + double f, + ) { textMatrix = MatrixHelper(a, b, c, d, e, f); textLineMatrix = textMatrix!.clone(); } MatrixHelper _setMatrix( - double a, double b, double c, double d, double e, double f) { - currentTransformationMatrix = MatrixHelper(a, b, c, d, e, f) * + double a, + double b, + double c, + double d, + double e, + double f, + ) { + currentTransformationMatrix = + MatrixHelper(a, b, c, d, e, f) * graphicsObjects!.last.currentTransformationMatrix!; return MatrixHelper( - currentTransformationMatrix!.m11, - currentTransformationMatrix!.m12, - currentTransformationMatrix!.m21, - currentTransformationMatrix!.m22, - currentTransformationMatrix!.offsetX, - currentTransformationMatrix!.offsetY); + currentTransformationMatrix!.m11, + currentTransformationMatrix!.m12, + currentTransformationMatrix!.m21, + currentTransformationMatrix!.m22, + currentTransformationMatrix!.offsetX, + currentTransformationMatrix!.offsetY, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/matrix_helper.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/matrix_helper.dart index f79692d86..00a3816c1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/matrix_helper.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/matrix_helper.dart @@ -5,7 +5,13 @@ import 'dart:ui'; class MatrixHelper { /// internal constructor MatrixHelper( - this.m11, this.m12, this.m21, this.m22, this.offsetX, this.offsetY) { + this.m11, + this.m12, + this.m21, + this.m22, + this.offsetX, + this.offsetY, + ) { type = MatrixTypes.unknown; _checkMatrixType(); } @@ -40,12 +46,13 @@ class MatrixHelper { /// internal property MatrixHelper operator *(MatrixHelper matrix) { return MatrixHelper( - m11 * matrix.m11 + m12 * matrix.m21, - m11 * matrix.m12 + m12 * matrix.m22, - m21 * matrix.m11 + m22 * matrix.m21, - m21 * matrix.m12 + m22 * matrix.m22, - offsetX * matrix.m11 + offsetY * matrix.m21 + matrix.offsetX, - offsetX * matrix.m12 + offsetY * matrix.m22 + matrix.offsetY); + m11 * matrix.m11 + m12 * matrix.m21, + m11 * matrix.m12 + m12 * matrix.m22, + m21 * matrix.m11 + m22 * matrix.m21, + m21 * matrix.m12 + m22 * matrix.m22, + offsetX * matrix.m11 + offsetY * matrix.m21 + matrix.offsetX, + offsetX * matrix.m12 + offsetY * matrix.m22 + matrix.offsetY, + ); } /// internal method @@ -60,15 +67,23 @@ class MatrixHelper { this.offsetX += offsetX; this.offsetY += offsetY; type = _getType( - _getTypeIndex(type) | _getTypeIndex(MatrixTypes.translation)); + _getTypeIndex(type) | _getTypeIndex(MatrixTypes.translation), + ); } } return this; } /// internal method - void setMatrix(double m11, double m12, double m21, double m22, double offsetX, - double offsetY, MatrixTypes type) { + void setMatrix( + double m11, + double m12, + double m21, + double m22, + double offsetX, + double offsetY, + MatrixTypes type, + ) { this.m11 = m11; this.m12 = m12; this.m21 = m21; @@ -89,7 +104,8 @@ class MatrixHelper { } if (offsetX != 0.0 || offsetY != 0.0) { type = _getType( - _getTypeIndex(type) | _getTypeIndex(MatrixTypes.translation)); + _getTypeIndex(type) | _getTypeIndex(MatrixTypes.translation), + ); } if (_getTypeIndex(type) & 3 == _getTypeIndex(MatrixTypes.identity)) { type = MatrixTypes.identity; @@ -129,11 +145,22 @@ class MatrixHelper { /// internal method MatrixHelper scale( - double scaleX, double scaleY, double centerX, double centerY) { + double scaleX, + double scaleY, + double centerX, + double centerY, + ) { final MatrixHelper newMatrix = MatrixHelper(scaleX, 0.0, 0.0, scaleY, centerX, centerY) * this; - setMatrix(newMatrix.m11, newMatrix.m12, newMatrix.m21, newMatrix.m22, - newMatrix.offsetX, newMatrix.offsetY, newMatrix.type); + setMatrix( + newMatrix.m11, + newMatrix.m12, + newMatrix.m21, + newMatrix.m22, + newMatrix.offsetX, + newMatrix.offsetY, + newMatrix.type, + ); return this; } @@ -143,29 +170,45 @@ class MatrixHelper { final double num1 = sin(angle); final double num2 = cos(angle); MatrixHelper matrix = MatrixHelper( - num2, - num1, - -num1, - num2, - centerX * (1.0 - num2) + centerY * num1, - centerY * (1.0 - num2) - centerX * num1); + num2, + num1, + -num1, + num2, + centerX * (1.0 - num2) + centerY * num1, + centerY * (1.0 - num2) - centerX * num1, + ); matrix.type = MatrixTypes.unknown; matrix *= this; - setMatrix(matrix.m11, matrix.m12, matrix.m21, matrix.m22, matrix.offsetX, - matrix.offsetY, matrix.type); + setMatrix( + matrix.m11, + matrix.m12, + matrix.m21, + matrix.m22, + matrix.offsetX, + matrix.offsetY, + matrix.type, + ); return this; } /// internal method Offset transform(Offset point) { - return Offset(point.dx * m11 + point.dy * m21 + offsetX, - point.dx * m12 + point.dy * m22 + offsetY); + return Offset( + point.dx * m11 + point.dy * m21 + offsetX, + point.dx * m12 + point.dy * m22 + offsetY, + ); } /// internal method MatrixHelper clone() { - final MatrixHelper result = - MatrixHelper(m11, m12, m21, m22, offsetX, offsetY); + final MatrixHelper result = MatrixHelper( + m11, + m12, + m21, + m22, + offsetX, + offsetY, + ); result.type = type; return result; } @@ -186,5 +229,5 @@ enum MatrixTypes { scalingAndTranslation, /// internal enumerator - unknown + unknown, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/page_resource_loader.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/page_resource_loader.dart index d7d8c4f7c..fdb118a08 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/page_resource_loader.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/page_resource_loader.dart @@ -23,10 +23,14 @@ class PageResourceLoader { PdfPageResources pageResources = PdfPageResources(); double resourceNumber = 0; PdfDictionary? resources = PdfPageHelper.getHelper(page).getResources(); - pageResources = - updatePageResources(pageResources, getFontResources(resources, page)); - pageResources = updatePageResources(pageResources, - getFormResources(resources, PdfPageHelper.getHelper(page).crossTable)); + pageResources = updatePageResources( + pageResources, + getFontResources(resources, page), + ); + pageResources = updatePageResources( + pageResources, + getFormResources(resources, PdfPageHelper.getHelper(page).crossTable), + ); while (resources != null && resources.containsKey(PdfDictionaryProperties.xObject)) { PdfDictionary? tempResources = resources; @@ -34,7 +38,8 @@ class PageResourceLoader { if (resources[PdfDictionaryProperties.xObject] is PdfReferenceHolder) { xobjects = (resources[PdfDictionaryProperties.xObject]! as PdfReferenceHolder) - .object as PdfDictionary?; + .object + as PdfDictionary?; } else { xobjects = resources[PdfDictionaryProperties.xObject] as PdfDictionary?; } @@ -67,8 +72,9 @@ class PageResourceLoader { continue; } } else { - resources = xobjectDictionary[PdfDictionaryProperties.resources] - as PdfDictionary?; + resources = + xobjectDictionary[PdfDictionaryProperties.resources] + as PdfDictionary?; } xobjectDictionary = null; if (resources == tempResources) { @@ -76,7 +82,9 @@ class PageResourceLoader { tempResources = null; } pageResources = updatePageResources( - pageResources, getFontResources(resources, page)); + pageResources, + getFontResources(resources, page), + ); } else { if (objKey != null && !pageResources.resources.containsKey(objKey.name) && @@ -108,8 +116,10 @@ class PageResourceLoader { } /// internal method - Map getFormResources(PdfDictionary? resourceDictionary, - [PdfCrossTable? crosstable]) { + Map getFormResources( + PdfDictionary? resourceDictionary, [ + PdfCrossTable? crosstable, + ]) { final Map pageResources = {}; if (resourceDictionary != null && resourceDictionary.containsKey(PdfDictionaryProperties.xObject)) { @@ -142,8 +152,10 @@ class PageResourceLoader { (subType.name == PdfDictionaryProperties.form || (subType.name != PdfDictionaryProperties.image && !pageResources.containsKey(key!.name)))) { - pageResources[key!.name] = - XObjectElement(xObjectDictionary, key.name); + pageResources[key!.name] = XObjectElement( + xObjectDictionary, + key.name, + ); } else if (xObjectDictionary is PdfStream) { if (crosstable != null && referenceHolder != null && @@ -153,8 +165,10 @@ class PageResourceLoader { crosstable.items!.remove(referenceHolder.reference!.objNum!); crosstable.objNumbers.remove(referenceHolder.reference); if (crosstable.crossTable != null) { - final ObjectInformation? oi = crosstable - .crossTable![referenceHolder.reference!.objNum!]; + final ObjectInformation? oi = + crosstable.crossTable![referenceHolder + .reference! + .objNum!]; oi!.obj = null; } } @@ -171,8 +185,10 @@ class PageResourceLoader { // Collects all the fonts in the page in a dictionary. // Returns dictionary containing font name and the font. /// internal method - Map getFontResources(PdfDictionary? resourceDictionary, - [PdfPage? page]) { + Map getFontResources( + PdfDictionary? resourceDictionary, [ + PdfPage? page, + ]) { final Map pageResources = {}; if (resourceDictionary != null) { IPdfPrimitive? fonts = resourceDictionary[PdfDictionaryProperties.font]; @@ -188,8 +204,10 @@ class PageResourceLoader { fontsDictionary.items!.forEach((PdfName? k, IPdfPrimitive? v) { if (v is PdfReferenceHolder) { if (v.reference != null) { - pageResources[k!.name] = - FontStructure(v.object, v.reference.toString()); + pageResources[k!.name] = FontStructure( + v.object, + v.reference.toString(), + ); } else { pageResources[k!.name] = FontStructure(v.object); } @@ -198,20 +216,24 @@ class PageResourceLoader { pageResources[k!.name] = FontStructure(v); } else { pageResources[k!.name] = FontStructure( - v, (v! as PdfReferenceHolder).reference.toString()); + v, + (v! as PdfReferenceHolder).reference.toString(), + ); } } }); } } if (page != null) { - final IPdfPrimitive? parentPage = PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.parent]; + final IPdfPrimitive? parentPage = + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .parent]; if (parentPage != null) { final IPdfPrimitive? parentRef = (parentPage as PdfReferenceHolder).object; - final PdfResources parentResources = - PdfResources(parentRef as PdfDictionary?); + final PdfResources parentResources = PdfResources( + parentRef as PdfDictionary?, + ); fonts = parentResources[PdfDictionaryProperties.font]; if (fonts != null && fonts is PdfDictionary) { final PdfDictionary fontsDictionary = fonts; @@ -220,7 +242,9 @@ class PageResourceLoader { pageResources[k!.name] = (v as PdfReferenceHolder).object; } pageResources[k!.name] = FontStructure( - v, (v! as PdfReferenceHolder).reference.toString()); + v, + (v! as PdfReferenceHolder).reference.toString(), + ); }); } } @@ -231,7 +255,9 @@ class PageResourceLoader { /// Updates the resources in the page PdfPageResources updatePageResources( - PdfPageResources pageResources, Map objects) { + PdfPageResources pageResources, + Map objects, + ) { objects.forEach((String? k, Object? v) { pageResources.add(k, v); }); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/parser/content_parser.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/parser/content_parser.dart index 5719d1ba3..324f1468a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/parser/content_parser.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/parser/content_parser.dart @@ -99,7 +99,7 @@ class ContentParser { 'B*', "'", '"', - 'true' + 'true', ]; // Implementation @@ -184,18 +184,20 @@ class ContentParser { ArgumentError.value('Invalid operand'); } PdfRecord record; - final List op = operands.isNotEmpty - ? List.filled(operands.length, '', growable: true) - : []; + final List op = + operands.isNotEmpty + ? List.filled(operands.length, '', growable: true) + : []; if (operands.isNotEmpty) { List.copyRange(op, 0, operands); } if (!_isByteOperands) { record = PdfRecord(operand, op); } else { - final List imBytes = inlineImageBytes!.isNotEmpty - ? List.filled(inlineImageBytes.length, 0, growable: true) - : []; + final List imBytes = + inlineImageBytes!.isNotEmpty + ? List.filled(inlineImageBytes.length, 0, growable: true) + : []; if (inlineImageBytes.isNotEmpty) { List.copyRange(imBytes, 0, inlineImageBytes); } @@ -242,17 +244,21 @@ class ContentParser { snc == '\r') && thirdChar.isNotEmpty) { if (String.fromCharCode( - int.parse(thirdChar[thirdChar.length - 1])) == + int.parse(thirdChar[thirdChar.length - 1]), + ) == 'Q' || thirdChar[thirdChar.length - 1] == '65535' || String.fromCharCode( - int.parse(thirdChar[thirdChar.length - 1])) == + int.parse(thirdChar[thirdChar.length - 1]), + ) == 'S') { _operatorParams!.clear(); - _operatorParams! - .write(String.fromCharCode(int.parse(currentChar))); - _operatorParams! - .write(String.fromCharCode(int.parse(nextChar))); + _operatorParams!.write( + String.fromCharCode(int.parse(currentChar)), + ); + _operatorParams!.write( + String.fromCharCode(int.parse(nextChar)), + ); _isByteOperands = true; _createRecord(operands, inlineImageBytes); _isByteOperands = false; @@ -320,10 +326,12 @@ class ContentParser { thirdChar == '65535' || String.fromCharCode(int.parse(thirdChar)) == 'S') { _operatorParams!.clear(); - _operatorParams! - .write(String.fromCharCode(int.parse(currentChar))); - _operatorParams! - .write(String.fromCharCode(int.parse(nextChar))); + _operatorParams!.write( + String.fromCharCode(int.parse(currentChar)), + ); + _operatorParams!.write( + String.fromCharCode(int.parse(nextChar)), + ); _isByteOperands = true; _createRecord(operands, inlineImageBytes); _isByteOperands = false; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/pdf_text_extractor.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/pdf_text_extractor.dart index 0c35ab612..7472e22f1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/pdf_text_extractor.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/pdf_text_extractor.dart @@ -48,8 +48,11 @@ class PdfTextExtractor { /// ``` PdfTextExtractor(PdfDocument document) { if (!PdfDocumentHelper.getHelper(document).isLoadedDocument) { - ArgumentError.value(document, 'document', - 'document instance is not a loaded PDF document'); + ArgumentError.value( + document, + 'document', + 'document instance is not a loaded PDF document', + ); } _document = document; _initialize(); @@ -103,8 +106,11 @@ class PdfTextExtractor { /// //Dispose the document. /// document.dispose(); /// ``` - String extractText( - {int? startPageIndex, int? endPageIndex, bool? layoutText}) { + String extractText({ + int? startPageIndex, + int? endPageIndex, + bool? layoutText, + }) { _isLayout = layoutText ?? false; return _extractText(startPageIndex, endPageIndex); } @@ -155,10 +161,12 @@ class PdfTextExtractor { /// //Dispose the document. /// document.dispose(); /// ``` - List findText(List searchString, - {int? startPageIndex, - int? endPageIndex, - TextSearchOption? searchOption}) { + List findText( + List searchString, { + int? startPageIndex, + int? endPageIndex, + TextSearchOption? searchOption, + }) { return _findText(searchString, startPageIndex, endPageIndex, searchOption); } @@ -182,8 +190,11 @@ class PdfTextExtractor { String _extractText(int? startPageIndex, int? endPageIndex) { if (startPageIndex == null) { if (endPageIndex != null) { - throw ArgumentError.value(endPageIndex, 'endPageIndex', - 'Invalid argument. start page index cannot be null'); + throw ArgumentError.value( + endPageIndex, + 'endPageIndex', + 'Invalid argument. start page index cannot be null', + ); } else { return _extractTextFromRange(0, _document.pages.count - 1); } @@ -201,8 +212,11 @@ class PdfTextExtractor { List _extractTextLines(int? startPageIndex, int? endPageIndex) { if (startPageIndex == null) { if (endPageIndex != null) { - throw ArgumentError.value(endPageIndex, 'endPageIndex', - 'Invalid argument. start page index cannot be null'); + throw ArgumentError.value( + endPageIndex, + 'endPageIndex', + 'Invalid argument. start page index cannot be null', + ); } else { return _extractTextLineFromRange(0, _document.pages.count - 1); } @@ -217,26 +231,44 @@ class PdfTextExtractor { } } - List _findText(List searchString, int? startPageIndex, - int? endPageIndex, TextSearchOption? searchOption) { + List _findText( + List searchString, + int? startPageIndex, + int? endPageIndex, + TextSearchOption? searchOption, + ) { if (startPageIndex == null) { if (endPageIndex != null) { - throw ArgumentError.value(endPageIndex, 'endPageIndex', - 'Invalid argument. start page index cannot be null'); + throw ArgumentError.value( + endPageIndex, + 'endPageIndex', + 'Invalid argument. start page index cannot be null', + ); } else { return _findTextFromRange( - 0, _document.pages.count - 1, searchString, searchOption); + 0, + _document.pages.count - 1, + searchString, + searchOption, + ); } } else if (endPageIndex == null) { _checkPageNumber(startPageIndex); _currentPageIndex = startPageIndex; return _searchInBackground( - _document.pages[startPageIndex], searchString, searchOption); + _document.pages[startPageIndex], + searchString, + searchOption, + ); } else { _checkPageNumber(startPageIndex); _checkPageNumber(endPageIndex); return _findTextFromRange( - startPageIndex, endPageIndex, searchString, searchOption); + startPageIndex, + endPageIndex, + searchString, + searchOption, + ); } } @@ -244,7 +276,8 @@ class PdfTextExtractor { String resultText = ''; for (int i = startPageIndex; i <= endPageIndex; i++) { final String text = _getText(_document.pages[i]); - resultText = resultText + + resultText = + resultText + (i > startPageIndex && (!_isLayout || (_isLayout && !resultText.endsWith('\n'))) ? '\r\n' @@ -255,7 +288,9 @@ class PdfTextExtractor { } List _extractTextLineFromRange( - int startPageIndex, int endPageIndex) { + int startPageIndex, + int endPageIndex, + ) { final List result = []; for (int i = startPageIndex; i <= endPageIndex; i++) { _currentPageIndex = i; @@ -267,13 +302,20 @@ class PdfTextExtractor { return result; } - List _findTextFromRange(int startPageIndex, int endPageIndex, - List searchString, TextSearchOption? searchOption) { + List _findTextFromRange( + int startPageIndex, + int endPageIndex, + List searchString, + TextSearchOption? searchOption, + ) { final List result = []; for (int i = startPageIndex; i <= endPageIndex; i++) { _currentPageIndex = i; - final List textLines = - _searchInBackground(_document.pages[i], searchString, searchOption); + final List textLines = _searchInBackground( + _document.pages[i], + searchString, + searchOption, + ); if (textLines.isNotEmpty) { result.addAll(textLines); } @@ -292,8 +334,14 @@ class PdfTextExtractor { String resultantText; if (_isLayout) { try { - _initialTransform = MatrixHelper(1.3333333333333333, 0, 0, - -1.3333333333333333, 0, page.size.height * 1.3333333333333333); + _initialTransform = MatrixHelper( + 1.3333333333333333, + 0, + 0, + -1.3333333333333333, + 0, + page.size.height * 1.3333333333333333, + ); } catch (e) { _initialTransform = MatrixHelper.identity; } @@ -336,10 +384,14 @@ class PdfTextExtractor { final bool isChanged = _checkPageDictionary(pdfPage); final bool isContentChanged = _checkContentArray(pdfPage); final PdfRecordCollection? recordCollection = _getRecordCollection(pdfPage); - final PdfPageResources pageResources = - _resourceLoader.getPageResources(pdfPage); - final ImageRenderer renderer = ImageRenderer(recordCollection, - pageResources, pdfPage.size.height * 1.3333333333333333); + final PdfPageResources pageResources = _resourceLoader.getPageResources( + pdfPage, + ); + final ImageRenderer renderer = ImageRenderer( + recordCollection, + pageResources, + pdfPage.size.height * 1.3333333333333333, + ); renderer.isExtractLineCollection = true; final double rotation = _getPageRotation(pdfPage); renderer.pageRotation = rotation; @@ -380,15 +432,25 @@ class PdfTextExtractor { (i == renderer.imageRenderGlyphList.length - 1)) { offsetY = yPos.toInt(); if (textLine.wordCollection.isNotEmpty) { - result.add(_prepareTextLine( - textLine, renderer, lineStartIndex, i, rotation)); + result.add( + _prepareTextLine( + textLine, + renderer, + lineStartIndex, + i, + rotation, + ), + ); } lineStartIndex = i; textLine = TextLineHelper.initialize(); } final TextElement textElement = renderer.extractTextElement[k]; final List words = _splitRenderedText( - textElement.renderedText, renderer.imageRenderGlyphList, i); + textElement.renderedText, + renderer.imageRenderGlyphList, + i, + ); textElement.text = ' '; TextWord? textwords; List glyphs = []; @@ -396,18 +458,28 @@ class PdfTextExtractor { if (pagestring.contains(words[x]) && words[x].isNotEmpty) { glyphs = []; int lastIndex = i; - for (int m = i; m < i + words[x].length; m++) { + for ( + int m = i; + m < i + words[x].length && + m < renderer.imageRenderGlyphList.length; + m++ + ) { final Glyph tempGlyph = renderer.imageRenderGlyphList[m]; final Rect tempBounds = tempGlyph.boundingRect; - final Rect glyphBounds = Rect.fromLTRB(tempBounds.left, - tempBounds.top, tempBounds.right, tempBounds.bottom); + final Rect glyphBounds = Rect.fromLTRB( + tempBounds.left, + tempBounds.top, + tempBounds.right, + tempBounds.bottom, + ); final TextGlyph textGlyph = TextGlyphHelper.initialize( - tempGlyph.toUnicode, - textElement.fontName, - textElement.fontStyle, - _calculateBounds(glyphBounds), - textElement.fontSize, - tempGlyph.isRotated); + tempGlyph.toUnicode, + textElement.fontName, + textElement.fontStyle, + _calculateBounds(glyphBounds), + textElement.fontSize, + tempGlyph.isRotated, + ); glyphs.add(textGlyph); lastIndex = m; } @@ -416,40 +488,57 @@ class PdfTextExtractor { dy = renderer.imageRenderGlyphList[i].boundingRect.top; if (hasRotation && rotation == 270) { width = renderer.imageRenderGlyphList[i].boundingRect.width; - height = renderer - .imageRenderGlyphList[lastIndex].boundingRect.bottom; + height = + renderer + .imageRenderGlyphList[lastIndex] + .boundingRect + .bottom; wordBound = Rect.fromLTWH(dx, dy, width, height - dy); } else { height = renderer.imageRenderGlyphList[i].boundingRect.height; if (dx > renderer - .imageRenderGlyphList[lastIndex].boundingRect.left) { - width = (dx - - renderer.imageRenderGlyphList[lastIndex].boundingRect + .imageRenderGlyphList[lastIndex] + .boundingRect + .left) { + width = + (dx - + renderer + .imageRenderGlyphList[lastIndex] + .boundingRect .left) + renderer - .imageRenderGlyphList[lastIndex].boundingRect.width; + .imageRenderGlyphList[lastIndex] + .boundingRect + .width; } else { - width = (renderer - .imageRenderGlyphList[lastIndex].boundingRect.left) + + width = + (renderer + .imageRenderGlyphList[lastIndex] + .boundingRect + .left) + renderer - .imageRenderGlyphList[lastIndex].boundingRect.width; + .imageRenderGlyphList[lastIndex] + .boundingRect + .width; } wordBound = Rect.fromLTWH(dx, dy, width - dx, height); } i = lastIndex + 1; String word = words[x]; if (word.isNotEmpty && bidi.Bidi.hasAnyRtl(word)) { - word = _bidi.getLogicalToVisualString(word, true)['rtlText'] - as String; + word = + _bidi.getLogicalToVisualString(word, true)['rtlText'] + as String; } textwords = TextWordHelper.initialize( - word, - textElement.fontName, - textElement.fontStyle, - glyphs, - _calculateBounds(wordBound), - textElement.fontSize); + word, + textElement.fontName, + textElement.fontStyle, + glyphs, + _calculateBounds(wordBound), + textElement.fontSize, + ); textLine.wordCollection.add(textwords); } textElement.text = words[x]; @@ -458,14 +547,26 @@ class PdfTextExtractor { i <= renderer.imageRenderGlyphList.length - 1 && renderer.imageRenderGlyphList[i].toUnicode == ' ') { if (i != 0) { - final Map tempResult = _addSpace(textwords, - renderer, textElement, i, dx, dy, width, height); + final Map tempResult = _addSpace( + textwords, + renderer, + textElement, + i, + dx, + dy, + width, + height, + ); dx = tempResult['dx'] as double?; dy = tempResult['dy'] as double?; width = tempResult['width'] as double?; height = tempResult['height'] as double?; - final Rect wordBound = - Rect.fromLTWH(dx!, dy!, width!, height!); + final Rect wordBound = Rect.fromLTWH( + dx!, + dy!, + width!, + height!, + ); tempResult['word'].bounds = _calculateBounds(wordBound); textLine.wordCollection.add(tempResult['word']); } @@ -486,14 +587,26 @@ class PdfTextExtractor { if (x != words.length - 1 && renderer.imageRenderGlyphList[i].toUnicode == ' ') { if (i != 0) { - final Map tempResult = _addSpace(textwords, - renderer, textElement, i, dx, dy, width, height); + final Map tempResult = _addSpace( + textwords, + renderer, + textElement, + i, + dx, + dy, + width, + height, + ); dx = tempResult['dx'] as double?; dy = tempResult['dy'] as double?; width = tempResult['width'] as double?; height = tempResult['height'] as double?; - final Rect wordBound = - Rect.fromLTWH(dx!, dy!, width!, height!); + final Rect wordBound = Rect.fromLTWH( + dx!, + dy!, + width!, + height!, + ); tempResult['word'].bounds = _calculateBounds(wordBound); textLine.wordCollection.add(tempResult['word']); } @@ -510,8 +623,15 @@ class PdfTextExtractor { if (renderer.extractTextElement.isNotEmpty && k == 0) { offsetY = yPos.toInt(); if (textLine.wordCollection.isNotEmpty) { - result.add(_prepareTextLine( - textLine, renderer, lineStartIndex, i, rotation)); + result.add( + _prepareTextLine( + textLine, + renderer, + lineStartIndex, + i, + rotation, + ), + ); } lineStartIndex = i; textLine = TextLineHelper.initialize(); @@ -526,13 +646,15 @@ class PdfTextExtractor { element.renderedText != '' && element.renderedText != ' ') { result.add( - _prepareTextLine(textLine, renderer, lineStartIndex, i, rotation)); + _prepareTextLine(textLine, renderer, lineStartIndex, i, rotation), + ); textLine = TextLineHelper.initialize(); } } if (textLine.wordCollection.isNotEmpty && !result.contains(textLine)) { result.add( - _prepareTextLine(textLine, renderer, lineStartIndex, i, rotation)); + _prepareTextLine(textLine, renderer, lineStartIndex, i, rotation), + ); textLine = TextLineHelper.initialize(); } PdfPageHelper.getHelper(pdfPage).contents.changed = isContentChanged; @@ -604,27 +726,39 @@ class PdfTextExtractor { } List _searchInBackground( - PdfPage page, List searchString, TextSearchOption? searchOption) { + PdfPage page, + List searchString, + TextSearchOption? searchOption, + ) { final List result = []; _isLayout = true; final String pageText = _getText(page); _isLayout = false; final bool containsRtl = bidi.Bidi.hasAnyRtl(pageText); if (pageText != '') { - bool isMatched = - _isMatchFound(searchString, searchOption, pageText, containsRtl); + bool isMatched = _isMatchFound( + searchString, + searchOption, + pageText, + containsRtl, + ); if (isMatched || containsRtl) { _currentPage = page; _fontSize = 0; PdfPageHelper.getHelper(page).isTextExtraction = true; final bool isChanged = _checkPageDictionary(page); final bool isContentChanged = _checkContentArray(page); - final PdfRecordCollection? recordCollection = - _getRecordCollection(page); - final PdfPageResources pageResources = - _resourceLoader.getPageResources(page); - final ImageRenderer renderer = ImageRenderer(recordCollection, - pageResources, page.size.height * 1.3333333333333333); + final PdfRecordCollection? recordCollection = _getRecordCollection( + page, + ); + final PdfPageResources pageResources = _resourceLoader.getPageResources( + page, + ); + final ImageRenderer renderer = ImageRenderer( + recordCollection, + pageResources, + page.size.height * 1.3333333333333333, + ); renderer.pageRotation = _getPageRotation(page); renderer.renderAsImage(); String renderedString = ''; @@ -639,8 +773,8 @@ class PdfTextExtractor { } List? visualOrderedTextGlyph; if (containsRtl) { - final Map visualOrderResult = - _bidi.getLogicalToVisualString(renderedString, true); + final Map visualOrderResult = _bidi + .getLogicalToVisualString(renderedString, true); renderedString = visualOrderResult['rtlText'] as String; final List visualOrderIndexes = visualOrderResult['orderedIndexes'] as List; @@ -652,11 +786,15 @@ class PdfTextExtractor { if (newIndex + 1 < visualOrderIndexes.length && visualOrderIndexes[newIndex + 1] == key + 1) { visualOrderIndexes.removeRange( - newIndex + 1, newIndex + value); + newIndex + 1, + newIndex + value, + ); } else if (newIndex - 1 > -1 && visualOrderIndexes[newIndex - 1] == key + 1) { visualOrderIndexes.removeRange( - newIndex - value + 1, newIndex); + newIndex - value + 1, + newIndex, + ); } } }); @@ -679,16 +817,17 @@ class PdfTextExtractor { } } if (index < glyphListLength) { - visualOrderedTextGlyph - .add(renderer.imageRenderGlyphList[index]); + visualOrderedTextGlyph.add( + renderer.imageRenderGlyphList[index], + ); } } } final List renderedStringCollection = [ - renderedString + renderedString, ]; final List?> textGlyphCollection = ?>[ - visualOrderedTextGlyph ?? renderer.imageRenderGlyphList + visualOrderedTextGlyph ?? renderer.imageRenderGlyphList, ]; if (renderedString.contains(' ') || renderedString.contains('\t\t')) { @@ -703,8 +842,9 @@ class PdfTextExtractor { spaceStartIndex = innerSpaceTrimmedString.indexOf('\t\t'); } if (spaceStartIndex >= 0) { - final List stringList = - innerSpaceTrimmedString.split(''); + final List stringList = innerSpaceTrimmedString.split( + '', + ); int i = spaceStartIndex + 2; for (i = spaceStartIndex + 2; i < stringList.length; i++) { if (stringList[i] == ' ' || stringList[i] == '\t') { @@ -714,7 +854,9 @@ class PdfTextExtractor { } else { stringList.removeRange(spaceStartIndex + 1, i); innerSpaceTrimmedTextGlyph.removeRange( - spaceStartIndex + 1, i); + spaceStartIndex + 1, + i, + ); break; } } @@ -730,7 +872,11 @@ class PdfTextExtractor { if (!isMatched) { for (final String renderedText in renderedStringCollection) { isMatched = _isMatchFound( - searchString, searchOption, renderedText, containsRtl); + searchString, + searchOption, + renderedText, + containsRtl, + ); if (isMatched) { break; } @@ -738,13 +884,14 @@ class PdfTextExtractor { } if (isMatched) { _getMatchedItems( - page, - searchString, - searchOption, - renderedStringCollection, - combinedGlyphLength, - textGlyphCollection, - result); + page, + searchString, + searchOption, + renderedStringCollection, + combinedGlyphLength, + textGlyphCollection, + result, + ); } } PdfPageHelper.getHelper(page).contents.changed = isContentChanged; @@ -755,8 +902,12 @@ class PdfTextExtractor { return result; } - bool _isMatchFound(List searchString, TextSearchOption? searchOption, - String pageText, bool containsRtl) { + bool _isMatchFound( + List searchString, + TextSearchOption? searchOption, + String pageText, + bool containsRtl, + ) { ArabicShapeRenderer? shapeRenderer; if (containsRtl) { shapeRenderer = ArabicShapeRenderer(); @@ -803,9 +954,9 @@ class PdfTextExtractor { if (!tempTermCollection.contains(tempRenderedTerm)) { tempTermCollection.add(tempRenderedTerm); if (!searchString.contains(tempRenderedTerm) && - pageText - .toLowerCase() - .contains(tempRenderedTerm.toLowerCase())) { + pageText.toLowerCase().contains( + tempRenderedTerm.toLowerCase(), + )) { searchString.add(tempRenderedTerm); isMatched = true; } @@ -826,13 +977,14 @@ class PdfTextExtractor { } void _getMatchedItems( - PdfPage page, - List searchString, - TextSearchOption? searchOption, - List renderedStringCollection, - Map combinedGlyphLength, - List?> glyphListCollection, - List result) { + PdfPage page, + List searchString, + TextSearchOption? searchOption, + List renderedStringCollection, + Map combinedGlyphLength, + List?> glyphListCollection, + List result, + ) { if (renderedStringCollection.isNotEmpty && renderedStringCollection[0] != '') { final Map> mappedIndexes = >{}; @@ -849,36 +1001,45 @@ class PdfTextExtractor { for (final String term in searchString) { if (term != '' && !mappedIndexes.containsKey(term)) { final List indexes = []; - final String currentText = (searchOption != null && - (searchOption == TextSearchOption.caseSensitive || - searchOption == TextSearchOption.both)) - ? term - : term.toLowerCase(); + final String currentText = + (searchOption != null && + (searchOption == TextSearchOption.caseSensitive || + searchOption == TextSearchOption.both)) + ? term + : term.toLowerCase(); int startIndex = 0; final int length = currentText.length; for (int i = 0; i < renderedStringCollection.length; i++) { while (startIndex <= textLengthCollection[i] && renderedStringCollection[i].contains(currentText, startIndex)) { - int index = - renderedStringCollection[i].indexOf(currentText, startIndex); + int index = renderedStringCollection[i].indexOf( + currentText, + startIndex, + ); final int tempIndex = index; if (searchOption != null && (searchOption == TextSearchOption.wholeWords || searchOption == TextSearchOption.both)) { if (index == 0 || _hasEscapeCharacter( - renderedStringCollection[i][index - 1])) { + renderedStringCollection[i][index - 1], + )) { if (index + length == textLengthCollection[i]) { if (combinedGlyphLength.isNotEmpty) { - index = - _checkCombinedTextIndex(index, combinedGlyphLength); + index = _checkCombinedTextIndex( + index, + combinedGlyphLength, + ); } indexes.add(index); } else if (_hasEscapeCharacter( - renderedStringCollection[i][index + length])) { + renderedStringCollection[i][index + length], + )) { if (combinedGlyphLength.isNotEmpty) { - index = - _checkCombinedTextIndex(index, combinedGlyphLength); + index = _checkCombinedTextIndex( + index, + combinedGlyphLength, + ); } indexes.add(index); } @@ -896,13 +1057,15 @@ class PdfTextExtractor { if (glyphListCollection[i] != null && index < glyphListCollection[i]!.length) { final List rect = _calculatedTextounds( - glyphListCollection[i]!, - term, - index, - page, - bidi.Bidi.hasAnyRtl(term)); - result.add(MatchedItemHelper.initialize( - term, rect, _currentPageIndex)); + glyphListCollection[i]!, + term, + index, + page, + bidi.Bidi.hasAnyRtl(term), + ); + result.add( + MatchedItemHelper.initialize(term, rect, _currentPageIndex), + ); } } break; @@ -914,7 +1077,9 @@ class PdfTextExtractor { } int _checkCombinedTextIndex( - int textIndex, Map combinedGlyphLength) { + int textIndex, + Map combinedGlyphLength, + ) { int adjustableLength = 0; combinedGlyphLength.forEach((int index, int length) { if (index < textIndex) { @@ -926,9 +1091,9 @@ class PdfTextExtractor { PdfRecordCollection? _getRecordCollection(PdfPage page) { PdfRecordCollection? recordCollection; - List? combinedData = - PdfPageLayerCollectionHelper.getHelper(page.layers) - .combineContent(true); + List? combinedData = PdfPageLayerCollectionHelper.getHelper( + page.layers, + ).combineContent(true); if (combinedData != null) { final ContentParser parser = ContentParser(combinedData); parser.isTextExtractionProcess = true; @@ -947,11 +1112,12 @@ class PdfTextExtractor { bool _checkContentArray(PdfPage page) { bool isContentChanged = false; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.contents)) { - final IPdfPrimitive? contents = PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.contents]; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.contents)) { + final IPdfPrimitive? contents = + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .contents]; if (contents is PdfReferenceHolder) { final PdfReferenceHolder holder = contents; final IPdfPrimitive? primitive = holder.object; @@ -968,51 +1134,65 @@ class PdfTextExtractor { } Map _addSpace( - TextWord? textwords, - ImageRenderer renderer, - TextElement textElement, - int i, - double? dx, - double? dy, - double? width, - double? height) { + TextWord? textwords, + ImageRenderer renderer, + TextElement textElement, + int i, + double? dx, + double? dy, + double? width, + double? height, + ) { final Rect tempBounds = renderer.imageRenderGlyphList[i].boundingRect; final Rect glyphBounds = Rect.fromLTWH( - tempBounds.left, tempBounds.top, tempBounds.width, tempBounds.height); + tempBounds.left, + tempBounds.top, + tempBounds.width, + tempBounds.height, + ); final TextGlyph textGlyph = TextGlyphHelper.initialize( - renderer.imageRenderGlyphList[i].toUnicode, - textElement.fontName, - textElement.fontStyle, - _calculateBounds(glyphBounds), - textElement.fontSize, - renderer.imageRenderGlyphList[i].isRotated); + renderer.imageRenderGlyphList[i].toUnicode, + textElement.fontName, + textElement.fontStyle, + _calculateBounds(glyphBounds), + textElement.fontSize, + renderer.imageRenderGlyphList[i].isRotated, + ); dx = renderer.imageRenderGlyphList[i].boundingRect.left; dy = renderer.imageRenderGlyphList[i].boundingRect.top; height = renderer.imageRenderGlyphList[i].boundingRect.height; if (dx > renderer.imageRenderGlyphList[i].boundingRect.left) { - width = (dx - renderer.imageRenderGlyphList[i].boundingRect.left) + + width = + (dx - renderer.imageRenderGlyphList[i].boundingRect.left) + renderer.imageRenderGlyphList[i].boundingRect.width; } else { - width = (renderer.imageRenderGlyphList[i].boundingRect.left - dx) + + width = + (renderer.imageRenderGlyphList[i].boundingRect.left - dx) + renderer.imageRenderGlyphList[i].boundingRect.width; } return { 'word': TextWordHelper.initialize( - ' ', - textElement.fontName, - textElement.fontStyle, - [textGlyph], - Rect.fromLTWH(dx, dy, width, height), - textElement.fontSize), + ' ', + textElement.fontName, + textElement.fontStyle, + [textGlyph], + Rect.fromLTWH(dx, dy, width, height), + textElement.fontSize, + ), 'dx': dx, 'dy': dy, 'width': width, - 'height': height + 'height': height, }; } List _calculatedTextounds( - List glyphs, String text, int index, PdfPage page, bool isRTL) { + List glyphs, + String text, + int index, + PdfPage page, + bool isRTL, + ) { Rect textBounds = Rect.zero; if (!isRTL) { textBounds = _getLTRBounds(glyphs, text, index, page); @@ -1047,11 +1227,13 @@ class PdfTextExtractor { } textCollection.forEach((int key, String value) { if (bidi.Bidi.hasAnyRtl(value)) { - boundsCollection - .add(_calculateBounds(_getRTLBounds(glyphs, value, key, page))); + boundsCollection.add( + _calculateBounds(_getRTLBounds(glyphs, value, key, page)), + ); } else { - boundsCollection - .add(_calculateBounds(_getLTRBounds(glyphs, value, key, page))); + boundsCollection.add( + _calculateBounds(_getLTRBounds(glyphs, value, key, page)), + ); } }); return boundsCollection; @@ -1208,8 +1390,13 @@ class PdfTextExtractor { return bounds; } - TextLine _prepareTextLine(TextLine textLine, ImageRenderer renderer, - int lineStartIndex, int glyphIndex, double rotation) { + TextLine _prepareTextLine( + TextLine textLine, + ImageRenderer renderer, + int lineStartIndex, + int glyphIndex, + double rotation, + ) { bool isSameFontName = true; bool isSameFontSize = true; bool isSameFontStyle = true; @@ -1220,18 +1407,20 @@ class PdfTextExtractor { if (rotation == 270 && renderer.imageRenderGlyphList[lineStartIndex].isRotated) { textLine.bounds = Rect.fromLTWH( - renderer.imageRenderGlyphList[lineStartIndex].boundingRect.left, - renderer.imageRenderGlyphList[lineStartIndex].boundingRect.top, - renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.width, - renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.bottom - - renderer.imageRenderGlyphList[lineStartIndex].boundingRect.top); + renderer.imageRenderGlyphList[lineStartIndex].boundingRect.left, + renderer.imageRenderGlyphList[lineStartIndex].boundingRect.top, + renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.width, + renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.bottom - + renderer.imageRenderGlyphList[lineStartIndex].boundingRect.top, + ); } else { textLine.bounds = Rect.fromLTWH( - renderer.imageRenderGlyphList[lineStartIndex].boundingRect.left, - renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.top, - renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.right - - renderer.imageRenderGlyphList[lineStartIndex].boundingRect.left, - renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.height); + renderer.imageRenderGlyphList[lineStartIndex].boundingRect.left, + renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.top, + renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.right - + renderer.imageRenderGlyphList[lineStartIndex].boundingRect.left, + renderer.imageRenderGlyphList[glyphIndex - 1].boundingRect.height, + ); } textLine.bounds = _calculateBounds(textLine.bounds); Rect? prevBounds; @@ -1280,14 +1469,17 @@ class PdfTextExtractor { } } if (textLine.text.isNotEmpty && bidi.Bidi.hasAnyRtl(textLine.text)) { - textLine.text = _bidi.getLogicalToVisualString( - textLine.text, true)['rtlText'] as String; + textLine.text = + _bidi.getLogicalToVisualString(textLine.text, true)['rtlText'] + as String; } return textLine; } String _renderText( - PdfRecordCollection? recordCollection, PdfPageResources pageResources) { + PdfRecordCollection? recordCollection, + PdfPageResources pageResources, + ) { String resultantText = ''; if (recordCollection != null && recordCollection.recordCollection.isNotEmpty) { @@ -1334,10 +1526,15 @@ class PdfTextExtractor { case 'TJ': case "'": { - final String? resultText = (_actualText != null && - _actualText!.isNotEmpty) - ? _actualText - : _renderTextElement(elements!, token, pageResources, null); + final String? resultText = + (_actualText != null && _actualText!.isNotEmpty) + ? _actualText + : _renderTextElement( + elements!, + token, + pageResources, + null, + ); if (resultText != null) { resultantText += resultText; } @@ -1348,8 +1545,11 @@ class PdfTextExtractor { } case 'Do': { - final String? result = - _getXObject(resultantText, elements!, pageResources); + final String? result = _getXObject( + resultantText, + elements!, + pageResources, + ); if (result != null && result != '') { resultantText += result; } @@ -1364,7 +1564,9 @@ class PdfTextExtractor { } String _renderTextAsLayout( - PdfRecordCollection? recordCollection, PdfPageResources pageResources) { + PdfRecordCollection? recordCollection, + PdfPageResources pageResources, + ) { double? currentMatrixY = 0; double? prevMatrixY = 0; double? currentY = 0; @@ -1475,13 +1677,15 @@ class PdfTextExtractor { case 'TD': { textLeading = double.tryParse(elements![1]); - _textMatrix = MatrixHelper( - 1, - 0, - 0, - 1, - double.tryParse(elements[0])!, - double.tryParse(elements[1])!) * + _textMatrix = + MatrixHelper( + 1, + 0, + 0, + 1, + double.tryParse(elements[0])!, + double.tryParse(elements[1])!, + ) * _textLineMatrix!; _textLineMatrix = _textMatrix!.clone(); if (_textLineMatrix!.offsetY != _currentTextMatrix!.offsetY || @@ -1495,13 +1699,15 @@ class PdfTextExtractor { } case 'Td': { - _textMatrix = MatrixHelper( - 1, - 0, - 0, - 1, - double.tryParse(elements![0])!, - double.tryParse(elements[1])!) * + _textMatrix = + MatrixHelper( + 1, + 0, + 0, + 1, + double.tryParse(elements![0])!, + double.tryParse(elements[1])!, + ) * _textLineMatrix!; _textLineMatrix = _textMatrix!.clone(); if (_textLineMatrix!.offsetY != _currentTextMatrix!.offsetY || @@ -1550,7 +1756,7 @@ class PdfTextExtractor { _hasET = true; final double endTextPosition = (_textLineMatrix!.offsetX - _tempBoundingRectangle!.right) / - 10; + 10; if (_hasLeading && endTextPosition == 0 && hasNoSpacing) { resultantText += ' '; _tempBoundingRectangle = Rect.zero; @@ -1585,7 +1791,8 @@ class PdfTextExtractor { bool isEncoded = true; if (elements != null) { final String text = elements.join(); - isEncoded = text[0] != '(' || + isEncoded = + text[0] != '(' || (text[0] == '(' && _hasOctalEscape(text)); } if (currentToken == 'Tj' && @@ -1597,11 +1804,20 @@ class PdfTextExtractor { } spaceBetweenWord = false; hasTj = true; - currentText = currentToken == 'TJ' - ? _renderTextElementTJ( - elements!, token, pageResources, horizontalScaling) - : _renderTextElement( - elements!, token, pageResources, horizontalScaling); + currentText = + currentToken == 'TJ' + ? _renderTextElementTJ( + elements!, + token, + pageResources, + horizontalScaling, + ) + : _renderTextElement( + elements!, + token, + pageResources, + horizontalScaling, + ); if (_actualText != null && _actualText!.isNotEmpty) { currentText = _actualText; _actualText = null; @@ -1646,17 +1862,21 @@ class PdfTextExtractor { if (isSpaceAdded && resultantText.isNotEmpty && resultantText.endsWith(' ')) { - resultantText = - resultantText.substring(0, resultantText.length - 1); + resultantText = resultantText.substring( + 0, + resultantText.length - 1, + ); } resultantText += '\r\n'; } isSpaceAdded = false; prevY = currentY; - final int currentXPosition = - _textLineMatrix!.offsetX.toInt().toSigned(64); - final int prevXPosition = - _currentTextMatrix!.offsetX.toInt().toSigned(64); + final int currentXPosition = _textLineMatrix!.offsetX + .toInt() + .toSigned(64); + final int prevXPosition = _currentTextMatrix!.offsetX + .toInt() + .toSigned(64); if ((prevXPosition - currentXPosition) > 0) { hasNoSpacing = true; } @@ -1664,15 +1884,22 @@ class PdfTextExtractor { MatrixHelper(1, 0, 0, 1, 0, textLeading!) * _textLineMatrix!; _textLineMatrix = _textMatrix!.clone(); currentText = _renderTextElement( - elements!, token, pageResources, horizontalScaling); + elements!, + token, + pageResources, + horizontalScaling, + ); _currentTextMatrix = _textLineMatrix!.clone(); resultantText += currentText!; break; } case 'Do': { - final String? result = - _getXObject(resultantText, elements!, pageResources); + final String? result = _getXObject( + resultantText, + elements!, + pageResources, + ); if (result != null && result != '') { resultantText += result; } @@ -1744,8 +1971,12 @@ class PdfTextExtractor { } } - String _renderTextElementTJ(List elements, String tokenType, - PdfPageResources pageResources, double? horizontalScaling) { + String _renderTextElementTJ( + List elements, + String tokenType, + PdfPageResources pageResources, + double? horizontalScaling, + ) { List decodedList = []; Map?, String> decodedListCollection = ?, String>{}; final String text = elements.join(); @@ -1763,15 +1994,22 @@ class PdfTextExtractor { fontStructure.isStandardCJKFont && fontStructure.font != null) { decodedList = fontStructure.decodeCjkTextExtractionTJ( - text, pageResources.isSameFont()); + text, + pageResources.isSameFont(), + ); } else { decodedListCollection = fontStructure.decodeTextExtractionTJ( - text, pageResources.isSameFont()); + text, + pageResources.isSameFont(), + ); decodedList = decodedListCollection.values.toList(); } fontStructure.isTextExtraction = false; - tempText = - _renderTextFromTJ(decodedList, horizontalScaling, fontStructure); + tempText = _renderTextFromTJ( + decodedList, + horizontalScaling, + fontStructure, + ); if (bidi.Bidi.hasAnyRtl(tempText)) { tempText = _bidi.getLogicalToVisualString(tempText, true)['rtlText'] as String; @@ -1780,14 +2018,19 @@ class PdfTextExtractor { return tempText; } - String _renderTextFromTJ(List decodedList, double? horizontalScaling, - FontStructure? fontStructure) { + String _renderTextFromTJ( + List decodedList, + double? horizontalScaling, + FontStructure? fontStructure, + ) { String extractedText = ''; for (String word in decodedList) { final double? space = double.tryParse(word); if (space != null) { - _textLineMatrix = - _updateTextMatrixWithSpacing(space, horizontalScaling!); + _textLineMatrix = _updateTextMatrixWithSpacing( + space, + horizontalScaling!, + ); if ((_textLineMatrix!.offsetX - _textMatrix!.offsetX).toInt() > 1 && !_hasBDC) { extractedText += ' '; @@ -1820,20 +2063,26 @@ class PdfTextExtractor { fontStructure.isStandardFont && fontStructure.font != null) { final PdfStandardFont font = fontStructure.font! as PdfStandardFont; - characterWidth = PdfStandardFontHelper.getHelper(font) - .getCharWidthInternal(renderedCharacter) * + characterWidth = + PdfStandardFontHelper.getHelper( + font, + ).getCharWidthInternal(renderedCharacter) * PdfFontHelper.characterSizeMultiplier; } else if (!fontStructure.isEmbedded && fontStructure.isStandardCJKFont && fontStructure.font != null) { final PdfCjkStandardFont font = fontStructure.font! as PdfCjkStandardFont; - characterWidth = PdfCjkStandardFontHelper.getHelper(font) - .getCharWidthInternal(renderedCharacter) * + characterWidth = + PdfCjkStandardFontHelper.getHelper( + font, + ).getCharWidthInternal(renderedCharacter) * PdfFontHelper.characterSizeMultiplier; } else { - characterWidth = - _getCharacterWidth(renderedCharacter, fontStructure); + characterWidth = _getCharacterWidth( + renderedCharacter, + fontStructure, + ); } _textMatrix = _getTextRenderingMatrix(horizontalScaling!); final MatrixHelper identity = MatrixHelper.identity.clone(); @@ -1854,10 +2103,11 @@ class PdfTextExtractor { tempFontSize = _fontSize; } final Rect boundingRect = Rect.fromLTWH( - matrix.offsetX / 1.3333333333333333, - (matrix.offsetY - tempFontSize!) / 1.3333333333333333, - characterWidth * tempFontSize, - tempFontSize); + matrix.offsetX / 1.3333333333333333, + (matrix.offsetY - tempFontSize!) / 1.3333333333333333, + characterWidth * tempFontSize, + tempFontSize, + ); if (_tempBoundingRectangle != null) { final double boundingDifference = ((boundingRect.left - _tempBoundingRectangle!.right) / 10) @@ -1871,8 +2121,10 @@ class PdfTextExtractor { } } extractedText += renderedCharacter; - _textLineMatrix = - _updateTextMatrix(characterWidth, horizontalScaling); + _textLineMatrix = _updateTextMatrix( + characterWidth, + horizontalScaling, + ); _tempBoundingRectangle = boundingRect; _textMatrix = _textLineMatrix!.clone(); } @@ -1881,8 +2133,12 @@ class PdfTextExtractor { return extractedText; } - String? _renderTextElement(List elements, String tokenType, - PdfPageResources pageResources, double? horizontalScaling) { + String? _renderTextElement( + List elements, + String tokenType, + PdfPageResources pageResources, + double? horizontalScaling, + ) { try { String text = elements.join(); if (!pageResources.containsKey(_currentFont)) { @@ -1901,7 +2157,11 @@ class PdfTextExtractor { text = fontStructure.decodeTextExtraction(text, true); if (_isLayout) { text = _renderTextFromLeading( - text, _textLineMatrix, fontStructure, horizontalScaling); + text, + _textLineMatrix, + fontStructure, + horizontalScaling, + ); } fontStructure.isTextExtraction = false; } @@ -1915,8 +2175,11 @@ class PdfTextExtractor { } String _renderTextFromLeading( - String decodedText, MatrixHelper? textLineMatrix, FontStructure structure, - [double? horizontalScaling = 100]) { + String decodedText, + MatrixHelper? textLineMatrix, + FontStructure structure, [ + double? horizontalScaling = 100, + ]) { String extractedText = ''; for (int i = 0; i < decodedText.length; i++) { final String ch = decodedText[i]; @@ -1925,12 +2188,12 @@ class PdfTextExtractor { final PdfStandardFont font = structure.font! as PdfStandardFont; characterWidth = PdfStandardFontHelper.getHelper(font).getCharWidthInternal(ch) * - PdfFontHelper.characterSizeMultiplier; + PdfFontHelper.characterSizeMultiplier; } else if (structure.isStandardCJKFont) { final PdfCjkStandardFont font = structure.font! as PdfCjkStandardFont; characterWidth = PdfCjkStandardFontHelper.getHelper(font).getCharWidthInternal(ch) * - PdfFontHelper.characterSizeMultiplier; + PdfFontHelper.characterSizeMultiplier; } else { characterWidth = _getCharacterWidth(ch, structure); } @@ -1957,10 +2220,11 @@ class PdfTextExtractor { tempFontSize = structure.fontSize; } final Rect boundingRect = Rect.fromLTWH( - matrix.offsetX / 1.3333333333333333, - (matrix.offsetY - tempFontSize!) / 1.3333333333333333, - characterWidth * tempFontSize, - tempFontSize); + matrix.offsetX / 1.3333333333333333, + (matrix.offsetY - tempFontSize!) / 1.3333333333333333, + characterWidth * tempFontSize, + tempFontSize, + ); if (_tempBoundingRectangle != null) { final double boundingDifference = ((boundingRect.left - _tempBoundingRectangle!.right) / 10) @@ -1979,8 +2243,11 @@ class PdfTextExtractor { return extractedText; } - String? _getXObject(String resultantText, List xobjectElement, - PdfPageResources pageResources) { + String? _getXObject( + String resultantText, + List xobjectElement, + PdfPageResources pageResources, + ) { String? result; final String key = xobjectElement[0].replaceAll('/', ''); if (pageResources.containsKey(key)) { @@ -2000,9 +2267,13 @@ class PdfTextExtractor { pageDictionary = resource; } childResource = _resourceLoader.updatePageResources( - childResource, _resourceLoader.getFormResources(pageDictionary)); - childResource = _resourceLoader.updatePageResources(childResource, - _resourceLoader.getFontResources(pageDictionary, _currentPage)); + childResource, + _resourceLoader.getFormResources(pageDictionary), + ); + childResource = _resourceLoader.updatePageResources( + childResource, + _resourceLoader.getFontResources(pageDictionary, _currentPage), + ); } else { childResource = _updateFontResources(pageResources); } @@ -2029,7 +2300,9 @@ class PdfTextExtractor { } MatrixHelper? _updateTextMatrixWithSpacing( - double space, double horizontalScaling) { + double space, + double horizontalScaling, + ) { final double x = -(space * 0.001 * _fontSize! * horizontalScaling / 100); final Offset point = _textLineMatrix!.transform(Offset.zero); final Offset point2 = _textLineMatrix!.transform(Offset(x, 0.0)); @@ -2042,8 +2315,14 @@ class PdfTextExtractor { } MatrixHelper _getTextRenderingMatrix(double textHorizontalScaling) { - return MatrixHelper(_fontSize! * (textHorizontalScaling / 100), 0, 0, - -_fontSize!, 0, _fontSize!) * + return MatrixHelper( + _fontSize! * (textHorizontalScaling / 100), + 0, + 0, + -_fontSize!, + 0, + _fontSize!, + ) * _textLineMatrix! * _currentTransformationMatrix; } @@ -2058,10 +2337,12 @@ class PdfTextExtractor { } MatrixHelper _updateTextMatrix( - double characterWidth, double horizontalScaling) { + double characterWidth, + double horizontalScaling, + ) { final double offsetX = (characterWidth * _fontSize! + _characterSpacing + _wordSpacing) * - (horizontalScaling / 100); + (horizontalScaling / 100); return MatrixHelper(1.0, 0.0, 0.0, 1.0, offsetX, 0.0) * _textLineMatrix!; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_element.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_element.dart index 3c389833d..e39c82118 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_element.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_element.dart @@ -297,29 +297,36 @@ class TextElement { 184, 733, 731, - 711 + 711, ]; } MatrixHelper _getTextRenderingMatrix() { - return MatrixHelper(fontSize * (textHorizontalScaling! / 100), 0, 0, - -fontSize, 0, fontSize + rise!) * + return MatrixHelper( + fontSize * (textHorizontalScaling! / 100), + 0, + 0, + -fontSize, + 0, + fontSize + rise!, + ) * textLineMatrix! * currentTransformationMatrix!; } /// internal method Map renderTextElement( - GraphicsObject? g, - Offset currentLocation, - double? textScaling, - Map? glyphWidths, - double? type1Height, - Map differenceTable, - Map differenceMappedTable, - Map? differenceEncoding, - MatrixHelper? txtMatrix, - [List? retrievedCharCodes]) { + GraphicsObject? g, + Offset currentLocation, + double? textScaling, + Map? glyphWidths, + double? type1Height, + Map differenceTable, + Map differenceMappedTable, + Map? differenceEncoding, + MatrixHelper? txtMatrix, [ + List? retrievedCharCodes, + ]) { txtMatrix = MatrixHelper(0, 0, 0, 0, 0, 0); txtMatrix.type = MatrixTypes.identity; double changeInX = currentLocation.dx; @@ -343,13 +350,17 @@ class TextElement { glyph.charSpacing = characterSpacing!; if (structure.isStandardFont) { final PdfStandardFont font = structure.font! as PdfStandardFont; - glyph.width = PdfStandardFontHelper.getHelper(font) - .getCharWidthInternal(character) * + glyph.width = + PdfStandardFontHelper.getHelper( + font, + ).getCharWidthInternal(character) * PdfFontHelper.characterSizeMultiplier; } else if (structure.isStandardCJKFont) { final PdfCjkStandardFont font = structure.font! as PdfCjkStandardFont; - glyph.width = PdfCjkStandardFontHelper.getHelper(font) - .getCharWidthInternal(character) * + glyph.width = + PdfCjkStandardFontHelper.getHelper( + font, + ).getCharWidthInternal(character) * PdfFontHelper.characterSizeMultiplier; } final MatrixHelper identity = MatrixHelper.identity.clone(); @@ -377,12 +388,13 @@ class TextElement { tempFontSize = glyph.fontSize; } glyph.boundingRect = Rect.fromLTWH( - (matrix.offsetX / 1.3333333333333333) / zoomFactor!, - ((matrix.offsetY - (tempFontSize * zoomFactor!)) / - 1.3333333333333333) / - zoomFactor!, - glyph.width * tempFontSize, - tempFontSize); + (matrix.offsetX / 1.3333333333333333) / zoomFactor!, + ((matrix.offsetY - (tempFontSize * zoomFactor!)) / + 1.3333333333333333) / + zoomFactor!, + glyph.width * tempFontSize, + tempFontSize, + ); textElementGlyphList.add(glyph); _updateTextMatrix(glyph); transformations._popTransform(); @@ -399,12 +411,13 @@ class TextElement { } for (int i = 0; i < text.length; i++) { final String letter = text[i]; - final dynamic retrievedCharCode = (retrievedCharCodes != null && - i < retrievedCharCodes.length && - retrievedCharCodes[i] != null && - retrievedCharCodes[i] != 0) - ? retrievedCharCodes[i] - : null; + final dynamic retrievedCharCode = + (retrievedCharCodes != null && + i < retrievedCharCodes.length && + retrievedCharCodes[i] != null && + retrievedCharCodes[i] != 0) + ? retrievedCharCodes[i] + : null; letterCount += 1; final int charCode = letter.codeUnitAt(0); isTextGlyphAdded = false; @@ -413,7 +426,11 @@ class TextElement { !isEmbeddedFont) { isTextGlyphAdded = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - letter, g!, txtMatrix, retrievedCharCode); + letter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -423,7 +440,11 @@ class TextElement { if (renderingMode == 1) { isTextGlyphAdded = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - letter, g!, txtMatrix, retrievedCharCode); + letter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -433,16 +454,23 @@ class TextElement { reverseMapTable!.containsKey(letter)) { final int tempCharCode = reverseMapTable![letter]!.toInt(); if (fontGlyphWidths != null) { - currentGlyphWidth = (fontGlyphWidths! - .containsKey(retrievedCharCode ?? tempCharCode) + currentGlyphWidth = + (fontGlyphWidths!.containsKey( + retrievedCharCode ?? tempCharCode, + ) ? fontGlyphWidths![retrievedCharCode ?? tempCharCode] : defaultGlyphWidth)! * charSizeMultiplier; } else { currentGlyphWidth = defaultGlyphWidth! * charSizeMultiplier; } - txtMatrix = - drawGlyphs(currentGlyphWidth, g!, txtMatrix, letter, false); + txtMatrix = drawGlyphs( + currentGlyphWidth, + g!, + txtMatrix, + letter, + false, + ); isTextGlyphAdded = true; } else { if (characterMapTable.isNotEmpty && @@ -450,7 +478,11 @@ class TextElement { final String tempLetter = characterMapTable[charCode]![0]; isTextGlyphAdded = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - tempLetter, g!, txtMatrix, retrievedCharCode); + tempLetter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -471,14 +503,15 @@ class TextElement { !structure.isMappingDone) { currentGlyphWidth = fontGlyphWidths![cidToGidReverseMapTable![charCode]!]! * - charSizeMultiplier; + charSizeMultiplier; } else if (fontGlyphWidths!.containsKey(charCode)) { currentGlyphWidth = fontGlyphWidths![charCode]! * charSizeMultiplier; } else { if (reverseMapTable!.containsKey(unicode) && - !fontGlyphWidths! - .containsKey(reverseMapTable![unicode]!.toInt())) { + !fontGlyphWidths!.containsKey( + reverseMapTable![unicode]!.toInt(), + )) { currentGlyphWidth = defaultGlyphWidth! * charSizeMultiplier; } @@ -500,7 +533,8 @@ class TextElement { } } } else if (fontGlyphWidths != null) { - currentGlyphWidth = (fontGlyphWidths!.containsKey(charCode) + currentGlyphWidth = + (fontGlyphWidths!.containsKey(charCode) ? fontGlyphWidths![charCode] : defaultGlyphWidth)! * charSizeMultiplier; @@ -511,31 +545,37 @@ class TextElement { location = Offset(location.dx + characterSpacing!, location.dy); } if (!isTextGlyphAdded) { - txtMatrix = - drawGlyphs(currentGlyphWidth, g!, txtMatrix, letter, false); + txtMatrix = drawGlyphs( + currentGlyphWidth, + g!, + txtMatrix, + letter, + false, + ); } } } changeInX = location.dx - changeInX; return { 'textElementWidth': changeInX, - 'tempTextMatrix': txtMatrix + 'tempTextMatrix': txtMatrix, }; } /// internal method Map renderWithSpacing( - GraphicsObject? g, - Offset currentLocation, - Map?, String> decodedList, - List? characterSpacing, - double? textScaling, - Map? glyphWidths, - double? type1Height, - Map differenceTable, - Map differenceMappedTable, - Map? differenceEncoding, - MatrixHelper? txtMatrix) { + GraphicsObject? g, + Offset currentLocation, + Map?, String> decodedList, + List? characterSpacing, + double? textScaling, + Map? glyphWidths, + double? type1Height, + Map differenceTable, + Map differenceMappedTable, + Map? differenceEncoding, + MatrixHelper? txtMatrix, + ) { txtMatrix = MatrixHelper(0, 0, 0, 0, 0, 0); txtMatrix.type = MatrixTypes.identity; double changeInX = currentLocation.dx; @@ -569,14 +609,18 @@ class TextElement { glyph.charSpacing = this.characterSpacing!; if (structure.isStandardFont) { final PdfStandardFont font = structure.font! as PdfStandardFont; - glyph.width = PdfStandardFontHelper.getHelper(font) - .getCharWidthInternal(character) * + glyph.width = + PdfStandardFontHelper.getHelper( + font, + ).getCharWidthInternal(character) * PdfFontHelper.characterSizeMultiplier; } else if (structure.isStandardCJKFont) { final PdfCjkStandardFont font = structure.font! as PdfCjkStandardFont; - glyph.width = PdfCjkStandardFontHelper.getHelper(font) - .getCharWidthInternal(character) * + glyph.width = + PdfCjkStandardFontHelper.getHelper( + font, + ).getCharWidthInternal(character) * PdfFontHelper.characterSizeMultiplier; } final MatrixHelper identity = MatrixHelper.identity.clone(); @@ -601,12 +645,13 @@ class TextElement { tempFontSize = glyph.fontSize; } glyph.boundingRect = Rect.fromLTWH( - (matrix.offsetX / 1.3333333333333333) / zoomFactor!, - ((matrix.offsetY - (tempFontSize * zoomFactor!)) / - 1.3333333333333333) / - zoomFactor!, - glyph.width * tempFontSize, - tempFontSize); + (matrix.offsetX / 1.3333333333333333) / zoomFactor!, + ((matrix.offsetY - (tempFontSize * zoomFactor!)) / + 1.3333333333333333) / + zoomFactor!, + glyph.width * tempFontSize, + tempFontSize, + ); textElementGlyphList.add(glyph); _updateTextMatrix(glyph); transformations._popTransform(); @@ -632,19 +677,24 @@ class TextElement { reverseMapTable!.isNotEmpty && reverseMapTable!.containsKey(word)) { final int charCode = reverseMapTable![word]!.toInt(); - final dynamic retrievedCharCode = (keys != null && - keys.isNotEmpty && - keys[0] != null && - keys[0] != 0) - ? keys[0] - : null; + final dynamic retrievedCharCode = + (keys != null && + keys.isNotEmpty && + keys[0] != null && + keys[0] != 0) + ? keys[0] + : null; if (characterMapTable.isNotEmpty && characterMapTable.containsKey(charCode)) { final String tempLetter = characterMapTable[charCode]!; isTextGlyphAdded = true; isComplexScript = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - tempLetter, g!, txtMatrix, retrievedCharCode); + tempLetter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -658,19 +708,24 @@ class TextElement { final String letter = word[i]; letterCount += 1; int charCode = letter.codeUnitAt(0); - final dynamic retrievedCharCode = (keys != null && - i < keys.length && - keys[i] != null && - keys[i] != 0) - ? keys[i] - : null; + final dynamic retrievedCharCode = + (keys != null && + i < keys.length && + keys[i] != null && + keys[i] != 0) + ? keys[i] + : null; isTextGlyphAdded = false; if (charCode.toUnsigned(8) > 126 && fontEncoding == 'MacRomanEncoding' && !isEmbeddedFont) { isTextGlyphAdded = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - letter, g!, txtMatrix, retrievedCharCode); + letter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -680,7 +735,11 @@ class TextElement { if (renderingMode == 1) { isTextGlyphAdded = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - letter, g!, txtMatrix, retrievedCharCode); + letter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -696,7 +755,11 @@ class TextElement { final String tempLetter = characterMapTable[charCode]![0]; isTextGlyphAdded = true; final MatrixHelper? tempMatrix = drawSystemFontGlyphShape( - tempLetter, g!, txtMatrix, retrievedCharCode); + tempLetter, + g!, + txtMatrix, + retrievedCharCode, + ); if (tempMatrix != null) { txtMatrix = tempMatrix; } else { @@ -715,8 +778,8 @@ class TextElement { if (cidToGidReverseMapTable != null && cidToGidReverseMapTable!.containsKey(charCode) && !structure.isMappingDone) { - currentGlyphWidth = fontGlyphWidths![ - cidToGidReverseMapTable![charCode]!]! * + currentGlyphWidth = + fontGlyphWidths![cidToGidReverseMapTable![charCode]!]! * charSizeMultiplier; } else if (fontGlyphWidths!.containsKey(charCode)) { currentGlyphWidth = @@ -724,7 +787,8 @@ class TextElement { } else { if (reverseMapTable!.containsKey(unicode) && !fontGlyphWidths!.containsKey( - reverseMapTable![unicode]!.toInt())) { + reverseMapTable![unicode]!.toInt(), + )) { currentGlyphWidth = defaultGlyphWidth! * charSizeMultiplier; } @@ -746,22 +810,30 @@ class TextElement { } } } else if (fontGlyphWidths != null) { - currentGlyphWidth = (fontGlyphWidths!.containsKey(charCode) + currentGlyphWidth = + (fontGlyphWidths!.containsKey(charCode) ? fontGlyphWidths![charCode] : defaultGlyphWidth)! * charSizeMultiplier; } } if (letterCount < word.length) { - location = - Offset(location.dx + this.characterSpacing!, location.dy); + location = Offset( + location.dx + this.characterSpacing!, + location.dy, + ); } if (!isTextGlyphAdded && (retrievedCharCode == null || (retrievedCharCode != null && retrievedCharCode is! String))) { txtMatrix = drawGlyphs( - currentGlyphWidth, g!, txtMatrix, letter, i == 0); + currentGlyphWidth, + g!, + txtMatrix, + letter, + i == 0, + ); } } } @@ -772,13 +844,18 @@ class TextElement { changeInX = location.dx - changeInX; return { 'textElementWidth': changeInX, - 'tempTextMatrix': txtMatrix + 'tempTextMatrix': txtMatrix, }; } /// internal method - MatrixHelper? drawGlyphs(double? glyphwidth, GraphicsObject g, - MatrixHelper? temptextmatrix, String? glyphChar, bool renderWithSpace) { + MatrixHelper? drawGlyphs( + double? glyphwidth, + GraphicsObject g, + MatrixHelper? temptextmatrix, + String? glyphChar, + bool renderWithSpace, + ) { final MatrixHelper defaultTransformations = g.transformMatrix!.clone(); g.transformMatrix = MatrixHelper(1, 0, 0, 1, 0, 0); final Glyph glyph = Glyph(); @@ -804,16 +881,20 @@ class TextElement { if (cidToGidReverseMapTable != null && cidToGidReverseMapTable!.containsKey(glyphChar!.codeUnitAt(0)) && (structure.characterMapTable.isNotEmpty)) { - glyphChar = characterMapTable[ - cidToGidReverseMapTable![glyphChar.codeUnitAt(0)]]; + glyphChar = + characterMapTable[cidToGidReverseMapTable![glyphChar.codeUnitAt( + 0, + )]]; } else if (structure.characterMapTable.isNotEmpty) { glyphChar = structure.mapCharactersFromTable(glyphChar!); } else if (structure.differencesDictionary.isNotEmpty) { glyphChar = structure.mapDifferences(glyphChar); - } else if (structure.cidToGidReverseMapTable - .containsKey(glyphChar!.codeUnitAt(0))) { + } else if (structure.cidToGidReverseMapTable.containsKey( + glyphChar!.codeUnitAt(0), + )) { glyphChar = String.fromCharCode( - structure.cidToGidReverseMapTable[glyphChar.codeUnitAt(0)]!); + structure.cidToGidReverseMapTable[glyphChar.codeUnitAt(0)]!, + ); } if (glyphChar!.contains('\u0092')) { glyphChar = glyphChar.replaceAll('\u0092', '’'); @@ -824,9 +905,10 @@ class TextElement { tempFontSize = glyph.transformMatrix.m11; } else if (glyph.transformMatrix.m12 != 0 && glyph.transformMatrix.m21 != 0) { - tempFontSize = glyph.transformMatrix.m12 < 0 - ? -glyph.transformMatrix.m12 - : glyph.transformMatrix.m12; + tempFontSize = + glyph.transformMatrix.m12 < 0 + ? -glyph.transformMatrix.m12 + : glyph.transformMatrix.m12; } else { tempFontSize = glyph.fontSize; } @@ -859,11 +941,13 @@ class TextElement { } else if (matrix.m12 < 0 && matrix.m21 < 0) { glyph.rotationAngle = 180; } - final double x = ((matrix.offsetX + + final double x = + ((matrix.offsetX + ((tempFontSize + (glyph.ascent / 1000.0)) * matrix.m21)) / 1.3333333333333333) / zoomFactor!; - double y = ((matrix.offsetY - + double y = + ((matrix.offsetY - ((pageRotation == 270 ? tempFontSize : (glyph.width * tempFontSize)) * @@ -890,12 +974,12 @@ class TextElement { glyph.boundingRect = Rect.fromLTWH(x, y, width, height); } else { glyph.boundingRect = Rect.fromLTWH( - (matrix.offsetX / 1.3333333333333333) / zoomFactor!, - ((matrix.offsetY - (tempFontSize * zoomFactor!)) / - 1.3333333333333333) / - zoomFactor!, - glyph.width * tempFontSize, - tempFontSize); + (matrix.offsetX / 1.3333333333333333) / zoomFactor!, + ((matrix.offsetY - (tempFontSize * zoomFactor!)) / 1.3333333333333333) / + zoomFactor!, + glyph.width * tempFontSize, + tempFontSize, + ); } if (glyph.toUnicode.length != 1) { textElementGlyphList.add(glyph); @@ -916,8 +1000,11 @@ class TextElement { /// internal method MatrixHelper? drawSystemFontGlyphShape( - String letter, GraphicsObject g, MatrixHelper? temptextmatrix, - [dynamic charCode]) { + String letter, + GraphicsObject g, + MatrixHelper? temptextmatrix, [ + dynamic charCode, + ]) { final MatrixHelper? defaultTransformations = g.transformMatrix; g.transformMatrix = MatrixHelper(1, 0, 0, 1, 0, 0); final Glyph gly = Glyph(); @@ -963,9 +1050,10 @@ class TextElement { if (gly.transformMatrix.m11 > 0) { tempFontSize = gly.transformMatrix.m11; } else if (gly.transformMatrix.m12 != 0 && gly.transformMatrix.m21 != 0) { - tempFontSize = gly.transformMatrix.m12 < 0 - ? -gly.transformMatrix.m12 - : gly.transformMatrix.m12; + tempFontSize = + gly.transformMatrix.m12 < 0 + ? -gly.transformMatrix.m12 + : gly.transformMatrix.m12; } else { tempFontSize = gly.fontSize; } @@ -974,16 +1062,20 @@ class TextElement { if (cidToGidReverseMapTable != null && cidToGidReverseMapTable!.containsKey(glyphName.codeUnitAt(0)) && (structure.characterMapTable.isNotEmpty)) { - glyphName = characterMapTable[ - cidToGidReverseMapTable![glyphName.codeUnitAt(0)]]; + glyphName = + characterMapTable[cidToGidReverseMapTable![glyphName.codeUnitAt( + 0, + )]]; } else if (structure.characterMapTable.isNotEmpty) { glyphName = structure.mapCharactersFromTable(glyphName); } else if (structure.differencesDictionary.isNotEmpty) { glyphName = structure.mapDifferences(glyphName); - } else if (structure.cidToGidReverseMapTable - .containsKey(glyphName.codeUnitAt(0))) { + } else if (structure.cidToGidReverseMapTable.containsKey( + glyphName.codeUnitAt(0), + )) { glyphName = String.fromCharCode( - structure.cidToGidReverseMapTable[glyphName.codeUnitAt(0)]!); + structure.cidToGidReverseMapTable[glyphName.codeUnitAt(0)]!, + ); } if (glyphName!.contains('\u0092')) { glyphName = glyphName.replaceAll('\u0092', '’'); @@ -1009,17 +1101,22 @@ class TextElement { } gly.toUnicode = glyphName; gly.boundingRect = Rect.fromLTWH( - (matrix.offsetX / 1.3333333333333333) / zoomFactor!, - ((matrix.offsetY - (tempFontSize * zoomFactor!)) / 1.3333333333333333) / - zoomFactor!, - gly.width * tempFontSize, - tempFontSize); + (matrix.offsetX / 1.3333333333333333) / zoomFactor!, + ((matrix.offsetY - (tempFontSize * zoomFactor!)) / 1.3333333333333333) / + zoomFactor!, + gly.width * tempFontSize, + tempFontSize, + ); textElementGlyphList.add(gly); if (isExtractTextData && gly.toUnicode.length != 1) { for (int i = 0; i < gly.toUnicode.length - 1; i++) { final Glyph emptyGlyph = Glyph(); - emptyGlyph.boundingRect = - Rect.fromLTWH(gly.boundingRect.right, gly.boundingRect.top, 0, 0); + emptyGlyph.boundingRect = Rect.fromLTWH( + gly.boundingRect.right, + gly.boundingRect.top, + 0, + 0, + ); textElementGlyphList.add(emptyGlyph); } } @@ -1053,16 +1150,17 @@ class TextElement { final double width = glyph.width; final double offsetX = (width * glyph.fontSize + glyph.charSpacing + glyph.wordSpacing) * - (glyph.horizontalScaling / 100); + (glyph.horizontalScaling / 100); return MatrixHelper(1.0, 0.0, 0.0, 1.0, offsetX, 0.0) * m; } } class TransformationStack { TransformationStack([MatrixHelper? transformMatrix]) { - _initialTransform = (transformMatrix != null) - ? transformMatrix - : MatrixHelper(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); + _initialTransform = + (transformMatrix != null) + ? transformMatrix + : MatrixHelper(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); transformStack = Queue(); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_glyph.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_glyph.dart index ff98b656b..e7631c63e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_glyph.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_glyph.dart @@ -3,8 +3,14 @@ import '../../graphics/fonts/enums.dart'; /// Gets the details of character in the word. class TextGlyph { - TextGlyph._(this.text, this.fontName, this.fontStyle, this.bounds, - this.fontSize, this.isRotated); + TextGlyph._( + this.text, + this.fontName, + this.fontStyle, + this.bounds, + this.fontSize, + this.isRotated, + ); //Fields /// Gets the bounds of glyph. @@ -31,8 +37,13 @@ class TextGlyph { class TextGlyphHelper { /// internal method static TextGlyph initialize( - String text, String fontName, List fontStyle, - [Rect bounds = Rect.zero, double fontSize = 0, bool isRotated = false]) { + String text, + String fontName, + List fontStyle, [ + Rect bounds = Rect.zero, + double fontSize = 0, + bool isRotated = false, + ]) { return TextGlyph._(text, fontName, fontStyle, bounds, fontSize, isRotated); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_word.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_word.dart index dbd183972..0f6555edd 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_word.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/text_word.dart @@ -6,8 +6,14 @@ import 'text_glyph.dart'; /// Details of a word present in the line. class TextWord { //constructor - TextWord._(this.text, this.fontName, this.fontStyle, List glyphs, - this.bounds, this.fontSize) { + TextWord._( + this.text, + this.fontName, + this.fontStyle, + List glyphs, + this.bounds, + this.fontSize, + ) { _glyphs = glyphs; } @@ -37,9 +43,14 @@ class TextWord { /// [TextWord] helper class TextWordHelper { /// internal method - static TextWord initialize(String text, String fontName, - List fontStyle, List glyphs, - [Rect bounds = Rect.zero, double fontSize = 0]) { + static TextWord initialize( + String text, + String fontName, + List fontStyle, + List glyphs, [ + Rect bounds = Rect.zero, + double fontSize = 0, + ]) { return TextWord._(text, fontName, fontStyle, glyphs, bounds, fontSize); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/xobject_element.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/xobject_element.dart index 304ac1a6b..cd9eb22be 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/xobject_element.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/exporting/pdf_text_extractor/xobject_element.dart @@ -71,12 +71,13 @@ class XObjectElement { /// internal method Map renderTextElement( - GraphicsObject? g, - PdfPageResources? resources, - GraphicStateCollection? graphicsStates, - GraphicObjectDataCollection? objects, - double? currentPageHeight, - List? glyphList) { + GraphicsObject? g, + PdfPageResources? resources, + GraphicStateCollection? graphicsStates, + GraphicObjectDataCollection? objects, + double? currentPageHeight, + List? glyphList, + ) { glyphList = []; List? extractTextElement; if (_objectType != null && @@ -102,9 +103,13 @@ class XObjectElement { pageDictionary = primitive; } childResource = resourceLoader.updatePageResources( - childResource, resourceLoader.getFontResources(pageDictionary)); + childResource, + resourceLoader.getFontResources(pageDictionary), + ); childResource = resourceLoader.updatePageResources( - childResource, resourceLoader.getFormResources(pageDictionary)); + childResource, + resourceLoader.getFormResources(pageDictionary), + ); } MatrixHelper xFormsMatrix = MatrixHelper(1.0, 0.0, 0.0, 1.0, 0.0, 0.0); if (xobjects.containsKey(PdfDictionaryProperties.matrix)) { @@ -142,20 +147,25 @@ class XObjectElement { } } } - final ImageRenderer renderer = - ImageRenderer(contentTree, childResource, currentPageHeight, g); + final ImageRenderer renderer = ImageRenderer( + contentTree, + childResource, + currentPageHeight, + g, + ); renderer.isExtractLineCollection = isExtractTextLine!; renderer.graphicsObjects = objects; final MatrixHelper parentMatrix = objects!.last.currentTransformationMatrix!; final MatrixHelper newMatrix = xFormsMatrix * parentMatrix; objects.last.drawing2dMatrixCTM = MatrixHelper( - newMatrix.m11, - newMatrix.m12, - newMatrix.m21, - newMatrix.m22, - newMatrix.offsetX, - newMatrix.offsetY); + newMatrix.m11, + newMatrix.m12, + newMatrix.m21, + newMatrix.m22, + newMatrix.offsetX, + newMatrix.offsetY, + ); objects.last.currentTransformationMatrix = newMatrix; renderer.selectablePrintDocument = isPrintSelected; renderer.pageHeight = pageHeight; @@ -174,7 +184,7 @@ class XObjectElement { 'graphicStates': graphicsStates, 'glyphList': glyphList, 'objects': objects, - 'extractTextElement': extractTextElement + 'extractTextElement': extractTextElement, }; } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/enum.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/enum.dart index 2294c1aba..4eed9f30a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/enum.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/enum.dart @@ -88,7 +88,7 @@ enum FieldFlags { /// device. This option enables applications to perform an action once a selection is /// made, without requiring the user to exit the field. If clear, the new value is not /// committed until the user exits the field. - commitOnSelChange + commitOnSelChange, } /// Specifies the style for a check box field. @@ -109,7 +109,7 @@ enum PdfCheckBoxStyle { square, /// A star is used for the checked state. - star + star, } /// internal enumerator @@ -124,7 +124,7 @@ enum PdfCheckFieldState { pressedUnchecked, /// Indicated pressed checked state. - pressedChecked + pressedChecked, } /// internal enumerator @@ -151,7 +151,7 @@ enum PdfFieldTypes { comboBox, /// Identify that field has no type. - none + none, } /// internal enumerator @@ -171,7 +171,7 @@ enum SignatureFlags { /// previous version is safe. Viewer applications can use this flag to present /// a user requesting a full save with an additional alert box warning that signatures /// will be invalidated and requiring explicit confirmation before continuing with the operation. - appendOnly + appendOnly, } /// Specifies the format of Export or Import data. @@ -186,5 +186,5 @@ enum DataFormat { json, /// Specifies XML file format - xml + xml, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_button_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_button_field.dart index 55bea49e7..efa853ada 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_button_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_button_field.dart @@ -38,29 +38,39 @@ class PdfButtonField extends PdfField { //Constructor /// Initializes an instance of the [PdfButtonField] class with the specific /// page, name, and bounds. - PdfButtonField(PdfPage page, String name, Rect bounds, - {String? text, - PdfFont? font, - PdfColor? borderColor, - PdfColor? backColor, - PdfColor? foreColor, - int? borderWidth, - PdfHighlightMode highlightMode = PdfHighlightMode.invert, - PdfBorderStyle borderStyle = PdfBorderStyle.solid, - PdfFieldActions? actions, - String? tooltip}) { + PdfButtonField( + PdfPage page, + String name, + Rect bounds, { + String? text, + PdfFont? font, + PdfColor? borderColor, + PdfColor? backColor, + PdfColor? foreColor, + int? borderWidth, + PdfHighlightMode highlightMode = PdfHighlightMode.invert, + PdfBorderStyle borderStyle = PdfBorderStyle.solid, + PdfFieldActions? actions, + String? tooltip, + }) { _helper = PdfButtonFieldHelper(this); - _helper.internal(page, name, bounds, - tooltip: tooltip, - font: font, - borderColor: borderColor, - backColor: backColor, - foreColor: foreColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle); + _helper.internal( + page, + name, + bounds, + tooltip: tooltip, + font: font, + borderColor: borderColor, + backColor: backColor, + foreColor: foreColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + ); _helper.dictionary!.setProperty( - PdfDictionaryProperties.ft, PdfName(PdfDictionaryProperties.btn)); + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.btn), + ); if (backColor == null) { _helper.backColor = PdfColor(211, 211, 211); } @@ -153,23 +163,29 @@ class PdfButtonField extends PdfField { PdfFieldActions get actions { if (_helper.isLoadedField && _helper.actions == null) { if (_helper.dictionary!.containsKey(PdfDictionaryProperties.aa)) { - final PdfDictionary actionDict = _helper.crossTable! - .getObject(_helper.dictionary![PdfDictionaryProperties.aa])! - as PdfDictionary; + final PdfDictionary actionDict = + _helper.crossTable!.getObject( + _helper.dictionary![PdfDictionaryProperties.aa], + )! + as PdfDictionary; _helper.actions = PdfFieldActionsHelper.load(actionDict); _helper.widget!.actions = PdfFieldActionsHelper.getHelper(_helper.actions!).annotationActions; } else { _helper.actions = PdfFieldActionsHelper.load(PdfDictionary()); - _helper.dictionary! - .setProperty(PdfDictionaryProperties.aa, _helper.actions); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.aa, + _helper.actions, + ); } _helper.changed = true; } else { if (_helper.actions == null) { _helper.actions = PdfFieldActions(_helper.widget!.actions!); - _helper.dictionary! - .setProperty(PdfDictionaryProperties.aa, _helper.actions); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.aa, + _helper.actions, + ); } } return _helper.actions!; @@ -214,18 +230,23 @@ class PdfButtonFieldHelper extends PdfFieldHelper { void addPrintAction() { final PdfDictionary actionDictionary = PdfDictionary(); actionDictionary.setProperty( - PdfDictionaryProperties.n, PdfName(PdfDictionaryProperties.print)); + PdfDictionaryProperties.n, + PdfName(PdfDictionaryProperties.print), + ); actionDictionary.setProperty(PdfDictionaryProperties.s, PdfName('Named')); if (isLoadedField) { - final PdfArray? kidsArray = crossTable! - .getObject(dictionary![PdfDictionaryProperties.kids]) as PdfArray?; + final PdfArray? kidsArray = + crossTable!.getObject(dictionary![PdfDictionaryProperties.kids]) + as PdfArray?; if (kidsArray != null) { final PdfReferenceHolder buttonObject = kidsArray[0]! as PdfReferenceHolder; final PdfDictionary buttonDictionary = buttonObject.object! as PdfDictionary; buttonDictionary.setProperty( - PdfDictionaryProperties.a, actionDictionary); + PdfDictionaryProperties.a, + actionDictionary, + ); } else { dictionary!.setProperty(PdfDictionaryProperties.a, actionDictionary); } @@ -250,12 +271,12 @@ class PdfButtonFieldHelper extends PdfFieldHelper { final PdfPage? page = buttonField.page; if (widget != null) { page!.annotations.remove(widget!); - PdfAnnotationCollectionHelper.getHelper(page.annotations) - .annotations - .insert(buttonField.tabIndex, PdfReferenceHolder(widget)); - PdfObjectCollectionHelper.getHelper(page.annotations) - .list - .insert(buttonField.tabIndex, widget!); + PdfAnnotationCollectionHelper.getHelper( + page.annotations, + ).annotations.insert(buttonField.tabIndex, PdfReferenceHolder(widget)); + PdfObjectCollectionHelper.getHelper( + page.annotations, + ).list.insert(buttonField.tabIndex, widget!); } } if (buttonField.form != null && @@ -281,20 +302,26 @@ class PdfButtonFieldHelper extends PdfFieldHelper { buttonField.text = buttonField.name!; } final PaintParams paintParams = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, widget!.bounds.size.width, widget!.bounds.size.height), - backBrush: PdfSolidBrush(buttonField.backColor), - foreBrush: PdfSolidBrush(buttonField.foreColor), - borderPen: borderPen, - style: buttonField.borderStyle, - borderWidth: borderWidth, - shadowBrush: PdfSolidBrush(buttonField.backColor)); + bounds: Rect.fromLTWH( + 0, + 0, + widget!.bounds.size.width, + widget!.bounds.size.height, + ), + backBrush: PdfSolidBrush(buttonField.backColor), + foreBrush: PdfSolidBrush(buttonField.foreColor), + borderPen: borderPen, + style: buttonField.borderStyle, + borderWidth: borderWidth, + shadowBrush: PdfSolidBrush(buttonField.backColor), + ); FieldPainter().drawButton( - template.graphics!, - paintParams, - buttonField.text, - (font == null) ? PdfStandardFont(PdfFontFamily.helvetica, 8) : font!, - format); + template.graphics!, + paintParams, + buttonField.text, + (font == null) ? PdfStandardFont(PdfFontFamily.helvetica, 8) : font!, + format, + ); } void _drawPressedAppearance(PdfTemplate template) { @@ -302,40 +329,54 @@ class PdfButtonFieldHelper extends PdfFieldHelper { buttonField.text = buttonField.name!; } final PaintParams paintParams = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, widget!.bounds.size.width, widget!.bounds.size.height), - backBrush: PdfSolidBrush(buttonField.backColor), - foreBrush: PdfSolidBrush(buttonField.foreColor), - borderPen: borderPen, - style: buttonField.borderStyle, - borderWidth: borderWidth, - shadowBrush: PdfSolidBrush(buttonField.backColor)); + bounds: Rect.fromLTWH( + 0, + 0, + widget!.bounds.size.width, + widget!.bounds.size.height, + ), + backBrush: PdfSolidBrush(buttonField.backColor), + foreBrush: PdfSolidBrush(buttonField.foreColor), + borderPen: borderPen, + style: buttonField.borderStyle, + borderWidth: borderWidth, + shadowBrush: PdfSolidBrush(buttonField.backColor), + ); FieldPainter().drawPressedButton( - template.graphics!, - paintParams, - buttonField.text, - (font == null) ? PdfStandardFont(PdfFontFamily.helvetica, 8) : font!, - format); + template.graphics!, + paintParams, + buttonField.text, + (font == null) ? PdfStandardFont(PdfFontFamily.helvetica, 8) : font!, + format, + ); } String _obtainText() { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); String? str; if (widget.containsKey(PdfDictionaryProperties.mk)) { - final PdfDictionary appearance = crossTable! - .getObject(widget[PdfDictionaryProperties.mk])! as PdfDictionary; + final PdfDictionary appearance = + crossTable!.getObject(widget[PdfDictionaryProperties.mk])! + as PdfDictionary; if (appearance.containsKey(PdfDictionaryProperties.ca)) { - final PdfString text = crossTable! - .getObject(appearance[PdfDictionaryProperties.ca])! as PdfString; + final PdfString text = + crossTable!.getObject(appearance[PdfDictionaryProperties.ca])! + as PdfString; str = text.value; } } if (str == null) { - PdfString? val = crossTable! - .getObject(dictionary![PdfDictionaryProperties.v]) as PdfString?; - val ??= PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true) - as PdfString?; + PdfString? val = + crossTable!.getObject(dictionary![PdfDictionaryProperties.v]) + as PdfString?; + val ??= + PdfFieldHelper.getValue( + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ) + as PdfString?; if (val != null) { str = val.value; } else { @@ -349,16 +390,21 @@ class PdfButtonFieldHelper extends PdfFieldHelper { final String text = value; final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); if (widget.containsKey(PdfDictionaryProperties.mk)) { - final PdfDictionary appearance = crossTable! - .getObject(widget[PdfDictionaryProperties.mk])! as PdfDictionary; + final PdfDictionary appearance = + crossTable!.getObject(widget[PdfDictionaryProperties.mk])! + as PdfDictionary; appearance.setString(PdfDictionaryProperties.ca, text); widget.setProperty( - PdfDictionaryProperties.mk, PdfReferenceHolder(appearance)); + PdfDictionaryProperties.mk, + PdfReferenceHolder(appearance), + ); } else { final PdfDictionary appearance = PdfDictionary(); appearance.setString(PdfDictionaryProperties.ca, text); widget.setProperty( - PdfDictionaryProperties.mk, PdfReferenceHolder(appearance)); + PdfDictionaryProperties.mk, + PdfReferenceHolder(appearance), + ); } if (widget.containsKey(PdfDictionaryProperties.ap)) { _applyAppearance(widget, null); @@ -402,32 +448,48 @@ class PdfButtonFieldHelper extends PdfFieldHelper { PdfAnnotationHelper.getHelper(widget!).appearance; if (appearance != null) { buttonField.page!.graphics.drawPdfTemplate( - appearance.normal, Offset(widget!.bounds.left, widget!.bounds.top)); + appearance.normal, + Offset(widget!.bounds.left, widget!.bounds.top), + ); } else { Rect rect = buttonField.bounds; rect = Rect.fromLTWH( - 0, 0, buttonField.bounds.width, buttonField.bounds.height); + 0, + 0, + buttonField.bounds.width, + buttonField.bounds.height, + ); final PdfFont tempFont = font ?? PdfStandardFont(PdfFontFamily.helvetica, 8); final PaintParams params = PaintParams( - bounds: rect, - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: buttonField.borderStyle, - borderWidth: buttonField.borderWidth, - shadowBrush: shadowBrush); + bounds: rect, + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: buttonField.borderStyle, + borderWidth: buttonField.borderWidth, + shadowBrush: shadowBrush, + ); final PdfTemplate template = PdfTemplate(rect.width, rect.height); - FieldPainter().drawButton(template.graphics!, params, buttonField.text, - tempFont, stringFormat); - buttonField.page!.graphics.drawPdfTemplate(template, - Offset(buttonField.bounds.left, buttonField.bounds.top), rect.size); + FieldPainter().drawButton( + template.graphics!, + params, + buttonField.text, + tempFont, + stringFormat, + ); + buttonField.page!.graphics.drawPdfTemplate( + template, + Offset(buttonField.bounds.left, buttonField.bounds.top), + rect.size, + ); buttonField.page!.graphics.drawString( - (buttonField.text.isEmpty) ? buttonField.name! : buttonField.text, - tempFont, - brush: params.foreBrush, - bounds: buttonField.bounds, - format: stringFormat); + (buttonField.text.isEmpty) ? buttonField.name! : buttonField.text, + tempFont, + brush: params.foreBrush, + bounds: buttonField.bounds, + format: stringFormat, + ); } } } @@ -438,19 +500,23 @@ class PdfButtonFieldHelper extends PdfFieldHelper { widget!.setProperty(PdfDictionaryProperties.aa, actions); } if ((widget != null) && (widget.containsKey(PdfDictionaryProperties.ap))) { - final PdfDictionary? appearance = crossTable! - .getObject(widget[PdfDictionaryProperties.ap]) as PdfDictionary?; + final PdfDictionary? appearance = + crossTable!.getObject(widget[PdfDictionaryProperties.ap]) + as PdfDictionary?; if ((appearance != null) && (appearance.containsKey(PdfDictionaryProperties.n))) { final Rect bounds = (item == null) ? buttonField.bounds : item.bounds; PdfTemplate template = PdfTemplate(bounds.width, bounds.height); - final PdfTemplate pressedTemplate = - PdfTemplate(bounds.width, bounds.height); + final PdfTemplate pressedTemplate = PdfTemplate( + bounds.width, + bounds.height, + ); if (widget.containsKey(PdfDictionaryProperties.mk)) { PdfDictionary? mkDic; if (widget[PdfDictionaryProperties.mk] is PdfReferenceHolder) { - mkDic = crossTable!.getObject(widget[PdfDictionaryProperties.mk]) - as PdfDictionary?; + mkDic = + crossTable!.getObject(widget[PdfDictionaryProperties.mk]) + as PdfDictionary?; } else { mkDic = widget[PdfDictionaryProperties.mk] as PdfDictionary?; } @@ -462,30 +528,44 @@ class PdfButtonFieldHelper extends PdfFieldHelper { template = PdfTemplate(bounds.size.height, bounds.size.width); PdfTemplateHelper.getHelper(template).writeTransformation = false; - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = - PdfArray([0, 1, -1, 0, bounds.size.width, 0]); + PdfTemplateHelper.getHelper( + template, + ).content[PdfDictionaryProperties.matrix] = PdfArray([ + 0, + 1, + -1, + 0, + bounds.size.width, + 0, + ]); } else if (angle.value == 180) { template = PdfTemplate(bounds.size.width, bounds.size.height); PdfTemplateHelper.getHelper(template).writeTransformation = false; - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = - PdfArray([ + PdfTemplateHelper.getHelper( + template, + ).content[PdfDictionaryProperties.matrix] = PdfArray([ -1, 0, 0, -1, bounds.size.width, - bounds.size.height + bounds.size.height, ]); } else if (angle.value == 270) { template = PdfTemplate(bounds.size.height, bounds.size.width); PdfTemplateHelper.getHelper(template).writeTransformation = false; - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = - PdfArray([0, -1, 1, 0, 0, bounds.size.height]); + PdfTemplateHelper.getHelper( + template, + ).content[PdfDictionaryProperties.matrix] = PdfArray([ + 0, + -1, + 1, + 0, + 0, + bounds.size.height, + ]); } } } @@ -493,31 +573,40 @@ class PdfButtonFieldHelper extends PdfFieldHelper { _drawButton(template.graphics, item, widget); _drawButton(pressedTemplate.graphics, item, widget); appearance.setProperty( - PdfDictionaryProperties.n, PdfReferenceHolder(template)); + PdfDictionaryProperties.n, + PdfReferenceHolder(template), + ); appearance.setProperty( - PdfDictionaryProperties.d, PdfReferenceHolder(pressedTemplate)); + PdfDictionaryProperties.d, + PdfReferenceHolder(pressedTemplate), + ); widget.setProperty(PdfDictionaryProperties.ap, appearance); } - } else if (PdfFormHelper.getHelper(buttonField.form!) - .setAppearanceDictionary) { + } else if (PdfFormHelper.getHelper( + buttonField.form!, + ).setAppearanceDictionary) { PdfFormHelper.getHelper(buttonField.form!).needAppearances = true; } } - void _drawButton(PdfGraphics? graphics, PdfButtonField? item, - [PdfDictionary? widget]) { + void _drawButton( + PdfGraphics? graphics, + PdfButtonField? item, [ + PdfDictionary? widget, + ]) { final GraphicsProperties gp = GraphicsProperties(buttonField); if (!flattenField) { gp.bounds = Rect.fromLTWH(0, 0, gp.bounds!.width, gp.bounds!.height); } final PaintParams prms = PaintParams( - bounds: gp.bounds, - backBrush: gp.backBrush, - foreBrush: gp.foreBrush, - borderPen: gp.borderPen, - style: gp.style, - borderWidth: gp.borderWidth, - shadowBrush: gp.shadowBrush); + bounds: gp.bounds, + backBrush: gp.backBrush, + foreBrush: gp.foreBrush, + borderPen: gp.borderPen, + style: gp.style, + borderWidth: gp.borderWidth, + shadowBrush: gp.shadowBrush, + ); if (dictionary!.containsKey(PdfDictionaryProperties.ap) && !(PdfGraphicsHelper.getHelper(graphics!).layer != null && PdfGraphicsHelper.getHelper(graphics).page!.rotation != @@ -533,10 +622,13 @@ class PdfButtonFieldHelper extends PdfFieldHelper { if (buttonResource != null) { final PdfStream? stream = buttonResource as PdfStream?; if (stream != null) { - final PdfTemplate buttonShape = - PdfTemplateHelper.fromPdfStream(stream); - buttonField.page!.graphics.drawPdfTemplate(buttonShape, - Offset(buttonField.bounds.left, buttonField.bounds.top)); + final PdfTemplate buttonShape = PdfTemplateHelper.fromPdfStream( + stream, + ); + buttonField.page!.graphics.drawPdfTemplate( + buttonShape, + Offset(buttonField.bounds.left, buttonField.bounds.top), + ); } } } @@ -557,22 +649,32 @@ class PdfButtonFieldHelper extends PdfFieldHelper { if (buttonResource != null) { final PdfStream? stream = buttonResource as PdfStream?; if (stream != null) { - final PdfTemplate buttonShape = - PdfTemplateHelper.fromPdfStream(stream); - buttonField.page!.graphics.drawPdfTemplate(buttonShape, - Offset(buttonField.bounds.left, buttonField.bounds.top)); + final PdfTemplate buttonShape = PdfTemplateHelper.fromPdfStream( + stream, + ); + buttonField.page!.graphics.drawPdfTemplate( + buttonShape, + Offset(buttonField.bounds.left, buttonField.bounds.top), + ); } } } } else { FieldPainter().drawButton( - graphics!, prms, buttonField.text, gp.font!, gp.stringFormat); + graphics!, + prms, + buttonField.text, + gp.font!, + gp.stringFormat, + ); } } /// internal method static PdfButtonField loadButtonField( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfButtonField._loaded(dictionary, crossTable); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_check_box_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_check_box_field.dart index 76d18905d..33383b456 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_check_box_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_check_box_field.dart @@ -30,26 +30,34 @@ class PdfCheckBoxField extends PdfCheckFieldBase { //Constructor /// Initializes a new instance of the [PdfCheckBoxField] class with /// the specific page, name and bounds. - PdfCheckBoxField(PdfPage page, String name, Rect bounds, - {bool isChecked = false, - PdfCheckBoxStyle style = PdfCheckBoxStyle.check, - PdfColor? borderColor, - PdfColor? backColor, - PdfColor? foreColor, - int? borderWidth, - PdfHighlightMode highlightMode = PdfHighlightMode.invert, - PdfBorderStyle borderStyle = PdfBorderStyle.solid, - String? tooltip}) { + PdfCheckBoxField( + PdfPage page, + String name, + Rect bounds, { + bool isChecked = false, + PdfCheckBoxStyle style = PdfCheckBoxStyle.check, + PdfColor? borderColor, + PdfColor? backColor, + PdfColor? foreColor, + int? borderWidth, + PdfHighlightMode highlightMode = PdfHighlightMode.invert, + PdfBorderStyle borderStyle = PdfBorderStyle.solid, + String? tooltip, + }) { _helper = PdfCheckBoxFieldHelper(this); - _helper.initialize(page, name, bounds, - style: style, - borderColor: borderColor, - backColor: backColor, - foreColor: foreColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + _helper.initialize( + page, + name, + bounds, + style: style, + borderColor: borderColor, + backColor: backColor, + foreColor: foreColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); _setCheckBoxValue(isChecked); } @@ -62,8 +70,9 @@ class PdfCheckBoxField extends PdfCheckFieldBase { for (int i = 0; i < kids.count; ++i) { final PdfDictionary? itemDictionary = crossTable.getObject(kids[i]) as PdfDictionary?; - PdfFieldItemCollectionHelper.getHelper(_items!) - .add(PdfCheckBoxItemHelper.getItem(this, i, itemDictionary)); + PdfFieldItemCollectionHelper.getHelper( + _items!, + ).add(PdfCheckBoxItemHelper.getItem(this, i, itemDictionary)); } _helper.array = kids; } @@ -82,20 +91,26 @@ class PdfCheckBoxField extends PdfCheckFieldBase { if (_helper.isLoadedField) { if (items != null && items!.count > 0) { final IPdfPrimitive? state = PdfCrossTable.dereference( - PdfFieldItemHelper.getHelper(items![_helper.defaultIndex]) - .dictionary![PdfDictionaryProperties.usageApplication]); + PdfFieldItemHelper.getHelper( + items![_helper.defaultIndex], + ).dictionary![PdfDictionaryProperties.usageApplication], + ); if (state == null) { final IPdfPrimitive? name = PdfFieldHelper.getValue( - _helper.dictionary!, - _helper.crossTable, - PdfDictionaryProperties.v, - false); + _helper.dictionary!, + _helper.crossTable, + PdfDictionaryProperties.v, + false, + ); if (name != null && name is PdfName) { - _checked = name.name == + _checked = + name.name == _helper.getItemValue( - PdfFieldItemHelper.getHelper(items![_helper.defaultIndex]) - .dictionary!, - _helper.crossTable); + PdfFieldItemHelper.getHelper( + items![_helper.defaultIndex], + ).dictionary!, + _helper.crossTable, + ); } } else if (state is PdfName) { _checked = state.name != PdfDictionaryProperties.off; @@ -153,18 +168,23 @@ class PdfCheckBoxField extends PdfCheckFieldBase { val = _helper._enableItems(value, val); } if (_checked) { - _helper.dictionary!.setName(PdfName(PdfDictionaryProperties.v), - val ?? PdfDictionaryProperties.yes); + _helper.dictionary!.setName( + PdfName(PdfDictionaryProperties.v), + val ?? PdfDictionaryProperties.yes, + ); _helper.dictionary!.setProperty( - PdfDictionaryProperties.usageApplication, - PdfName(val ?? PdfDictionaryProperties.yes)); + PdfDictionaryProperties.usageApplication, + PdfName(val ?? PdfDictionaryProperties.yes), + ); } else { _helper.dictionary!.remove(PdfDictionaryProperties.v); - if (_helper.dictionary! - .containsKey(PdfDictionaryProperties.usageApplication)) { + if (_helper.dictionary!.containsKey( + PdfDictionaryProperties.usageApplication, + )) { _helper.dictionary!.setName( - PdfName(PdfDictionaryProperties.usageApplication), - PdfDictionaryProperties.off); + PdfName(PdfDictionaryProperties.usageApplication), + PdfDictionaryProperties.off, + ); } } } @@ -195,7 +215,9 @@ class PdfCheckBoxFieldHelper extends PdfCheckFieldBaseHelper { /// internal method static PdfCheckBoxField loadCheckBoxField( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfCheckBoxField._loaded(dictionary, crossTable); } @@ -229,7 +251,8 @@ class PdfCheckBoxFieldHelper extends PdfCheckFieldBaseHelper { String? val; if (dictionary!.containsKey(PdfDictionaryProperties.usageApplication)) { final IPdfPrimitive? state = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.usageApplication]); + dictionary![PdfDictionaryProperties.usageApplication], + ); if (state != null && state is PdfName) { isChecked = state.name != PdfDictionaryProperties.off; } @@ -250,8 +273,9 @@ class PdfCheckBoxFieldHelper extends PdfCheckFieldBaseHelper { if (checkBoxField.items != null && checkBoxField.items!.count > 0) { (checkBoxField.items![defaultIndex] as PdfCheckBoxItem).checked = check; final PdfDictionary? dic = - PdfFieldItemHelper.getHelper(checkBoxField.items![defaultIndex]) - .dictionary; + PdfFieldItemHelper.getHelper( + checkBoxField.items![defaultIndex], + ).dictionary; if (dic != null) { value = getItemValue(dic, crossTable); } @@ -262,34 +286,51 @@ class PdfCheckBoxFieldHelper extends PdfCheckFieldBaseHelper { /// internal method void drawCheckAppearance() { final PaintParams paintParams = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, widget!.bounds.size.width, widget!.bounds.size.height), - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: checkBoxField.borderStyle, - borderWidth: checkBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: Rect.fromLTWH( + 0, + 0, + widget!.bounds.size.width, + widget!.bounds.size.height, + ), + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: checkBoxField.borderStyle, + borderWidth: checkBoxField.borderWidth, + shadowBrush: shadowBrush, + ); PdfTemplate template = widget!.extendedAppearance!.normal.activate!; - FieldPainter().drawCheckBox(template.graphics!, paintParams, - styleToString(checkBoxField.style), PdfCheckFieldState.checked, font); + FieldPainter().drawCheckBox( + template.graphics!, + paintParams, + styleToString(checkBoxField.style), + PdfCheckFieldState.checked, + font, + ); template = widget!.extendedAppearance!.normal.off!; - FieldPainter().drawCheckBox(template.graphics!, paintParams, - styleToString(checkBoxField.style), PdfCheckFieldState.unchecked, font); + FieldPainter().drawCheckBox( + template.graphics!, + paintParams, + styleToString(checkBoxField.style), + PdfCheckFieldState.unchecked, + font, + ); template = widget!.extendedAppearance!.pressed.activate!; FieldPainter().drawCheckBox( - template.graphics!, - paintParams, - styleToString(checkBoxField.style), - PdfCheckFieldState.pressedChecked, - font); + template.graphics!, + paintParams, + styleToString(checkBoxField.style), + PdfCheckFieldState.pressedChecked, + font, + ); template = widget!.extendedAppearance!.pressed.off!; FieldPainter().drawCheckBox( - template.graphics!, - paintParams, - styleToString(checkBoxField.style), - PdfCheckFieldState.pressedUnchecked, - font); + template.graphics!, + paintParams, + styleToString(checkBoxField.style), + PdfCheckFieldState.pressedUnchecked, + font, + ); } /// internal method @@ -311,18 +352,20 @@ class PdfCheckBoxFieldHelper extends PdfCheckFieldBaseHelper { @override void draw() { super.draw(); - PdfCheckFieldState state = checkBoxField.isChecked - ? PdfCheckFieldState.checked - : PdfCheckFieldState.unchecked; + PdfCheckFieldState state = + checkBoxField.isChecked + ? PdfCheckFieldState.checked + : PdfCheckFieldState.unchecked; if (!isLoadedField) { final PaintParams params = PaintParams( - bounds: checkBoxField.bounds, - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: checkBoxField.borderStyle, - borderWidth: checkBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: checkBoxField.bounds, + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: checkBoxField.borderStyle, + borderWidth: checkBoxField.borderWidth, + shadowBrush: shadowBrush, + ); if (fieldItems != null && fieldItems!.isNotEmpty) { for (int i = 0; i < array.count; i++) { final PdfCheckBoxField item = fieldItems![i] as PdfCheckBoxField; @@ -334,20 +377,29 @@ class PdfCheckBoxFieldHelper extends PdfCheckFieldBaseHelper { params.borderWidth = item.borderWidth; params.shadowBrush = item._helper.shadowBrush; FieldPainter().drawCheckBox( - item.page!.graphics, params, styleToString(item.style), state); + item.page!.graphics, + params, + styleToString(item.style), + state, + ); } } else { - FieldPainter().drawCheckBox(checkBoxField.page!.graphics, params, - styleToString(checkBoxField.style), state); + FieldPainter().drawCheckBox( + checkBoxField.page!.graphics, + params, + styleToString(checkBoxField.style), + state, + ); } } else { if (kids != null) { for (int i = 0; i < kids!.count; ++i) { final PdfCheckBoxItem item = checkBoxField._items![i] as PdfCheckBoxItem; - state = item.checked - ? PdfCheckFieldState.checked - : PdfCheckFieldState.unchecked; + state = + item.checked + ? PdfCheckFieldState.checked + : PdfCheckFieldState.unchecked; if (item.page != null) { drawStateItem(item.page!.graphics, state, null, item); } @@ -458,26 +510,36 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { /// Initializes a instance of the [PdfCheckFieldBase] class with /// the specific page, name and bounds. - void initialize(PdfPage? page, String? name, Rect bounds, - {PdfCheckBoxStyle? style, - PdfColor? borderColor, - PdfColor? backColor, - PdfColor? foreColor, - int? borderWidth, - PdfHighlightMode? highlightMode, - PdfBorderStyle? borderStyle, - String? tooltip}) { + void initialize( + PdfPage? page, + String? name, + Rect bounds, { + PdfCheckBoxStyle? style, + PdfColor? borderColor, + PdfColor? backColor, + PdfColor? foreColor, + int? borderWidth, + PdfHighlightMode? highlightMode, + PdfBorderStyle? borderStyle, + String? tooltip, + }) { checkField._checkBaseHelper = this; - internal(page, name, bounds, - borderColor: borderColor, - backColor: backColor, - foreColor: foreColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + internal( + page, + name, + bounds, + borderColor: borderColor, + backColor: backColor, + foreColor: foreColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); dictionary!.setProperty( - PdfDictionaryProperties.ft, PdfName(PdfDictionaryProperties.btn)); + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.btn), + ); checkField._initValues(style); } @@ -505,17 +567,21 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { void save() { super.save(); if (checkField.form != null) { - final Map checkValue = - _createTemplate(_checkedTemplate); + final Map checkValue = _createTemplate( + _checkedTemplate, + ); _checkedTemplate = checkValue['template']; - final Map unCheckValue = - _createTemplate(_uncheckedTemplate); + final Map unCheckValue = _createTemplate( + _uncheckedTemplate, + ); _uncheckedTemplate = unCheckValue['template']; - final Map pressedValue = - _createTemplate(_pressedCheckedTemplate); + final Map pressedValue = _createTemplate( + _pressedCheckedTemplate, + ); _pressedCheckedTemplate = pressedValue['template']; - final Map unPressedValue = - _createTemplate(_pressedUncheckedTemplate); + final Map unPressedValue = _createTemplate( + _pressedUncheckedTemplate, + ); _pressedUncheckedTemplate = unPressedValue['template']; widget!.extendedAppearance!.normal.activate = _checkedTemplate; widget!.extendedAppearance!.normal.off = _uncheckedTemplate; @@ -532,8 +598,10 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { Map _createTemplate(PdfTemplate? template) { if (template == null) { - template = - PdfTemplate(widget!.bounds.size.width, widget!.bounds.size.height); + template = PdfTemplate( + widget!.bounds.size.width, + widget!.bounds.size.height, + ); } else { template.reset(widget!.bounds.size.width, widget!.bounds.size.height); } @@ -552,28 +620,39 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { (checkField as PdfCheckBoxField)._helper.drawCheckAppearance(); } else if (checkField is PdfRadioButtonListItem) { PdfRadioButtonListItemHelper.getHelper( - checkField as PdfRadioButtonListItem) - .drawCheckAppearance(); + checkField as PdfRadioButtonListItem, + ).drawCheckAppearance(); } } /// internal method - void applyAppearance(PdfDictionary? widget, PdfCheckFieldBase? item, - [PdfFieldItem? fieldItem]) { + void applyAppearance( + PdfDictionary? widget, + PdfCheckFieldBase? item, [ + PdfFieldItem? fieldItem, + ]) { if (widget != null && item != null) { - if (item._checkBaseHelper.dictionary! - .containsKey(PdfDictionaryProperties.v) && + if (item._checkBaseHelper.dictionary!.containsKey( + PdfDictionaryProperties.v, + ) && item is! PdfRadioButtonListItem) { widget.setName( - PdfName(PdfDictionaryProperties.v), PdfDictionaryProperties.yes); - widget.setName(PdfName(PdfDictionaryProperties.usageApplication), - PdfDictionaryProperties.yes); - } else if (!item._checkBaseHelper.dictionary! - .containsKey(PdfDictionaryProperties.v) && + PdfName(PdfDictionaryProperties.v), + PdfDictionaryProperties.yes, + ); + widget.setName( + PdfName(PdfDictionaryProperties.usageApplication), + PdfDictionaryProperties.yes, + ); + } else if (!item._checkBaseHelper.dictionary!.containsKey( + PdfDictionaryProperties.v, + ) && item is! PdfRadioButtonListItem) { widget.remove(PdfDictionaryProperties.v); - widget.setName(PdfName(PdfDictionaryProperties.usageApplication), - PdfDictionaryProperties.off); + widget.setName( + PdfName(PdfDictionaryProperties.usageApplication), + PdfDictionaryProperties.off, + ); } } else if (widget != null && fieldItem != null) { widget = PdfFieldItemHelper.getHelper(fieldItem).dictionary; @@ -581,8 +660,9 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { widget = item!._checkBaseHelper.dictionary; } if ((widget != null) && (widget.containsKey(PdfDictionaryProperties.ap))) { - final PdfDictionary? appearance = crossTable! - .getObject(widget[PdfDictionaryProperties.ap]) as PdfDictionary?; + final PdfDictionary? appearance = + crossTable!.getObject(widget[PdfDictionaryProperties.ap]) + as PdfDictionary?; if ((appearance != null) && (appearance.containsKey(PdfDictionaryProperties.n))) { String? value = ''; @@ -592,63 +672,97 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { rect = item.bounds; } else if (fieldItem != null) { value = getItemValue( - widget, - PdfFieldHelper.getHelper( - PdfFieldItemHelper.getHelper(fieldItem).field) - .crossTable); + widget, + PdfFieldHelper.getHelper( + PdfFieldItemHelper.getHelper(fieldItem).field, + ).crossTable, + ); rect = fieldItem.bounds; } else { value = getItemValue(widget, crossTable); rect = checkField.bounds; } - IPdfPrimitive? holder = - PdfCrossTable.dereference(appearance[PdfDictionaryProperties.n]); + IPdfPrimitive? holder = PdfCrossTable.dereference( + appearance[PdfDictionaryProperties.n], + ); PdfDictionary? normal = holder as PdfDictionary?; if (fieldChanged == true && normal != null) { normal = PdfDictionary(); - final PdfTemplate checkedTemplate = - PdfTemplate(rect.width, rect.height); - final PdfTemplate unchekedTemplate = - PdfTemplate(rect.width, rect.height); - drawStateItem(checkedTemplate.graphics!, PdfCheckFieldState.checked, - item, fieldItem); - drawStateItem(unchekedTemplate.graphics!, - PdfCheckFieldState.unchecked, item, fieldItem); + final PdfTemplate checkedTemplate = PdfTemplate( + rect.width, + rect.height, + ); + final PdfTemplate unchekedTemplate = PdfTemplate( + rect.width, + rect.height, + ); + drawStateItem( + checkedTemplate.graphics!, + PdfCheckFieldState.checked, + item, + fieldItem, + ); + drawStateItem( + unchekedTemplate.graphics!, + PdfCheckFieldState.unchecked, + item, + fieldItem, + ); normal.setProperty(value, PdfReferenceHolder(checkedTemplate)); - normal.setProperty(PdfDictionaryProperties.off, - PdfReferenceHolder(unchekedTemplate)); + normal.setProperty( + PdfDictionaryProperties.off, + PdfReferenceHolder(unchekedTemplate), + ); appearance.remove(PdfDictionaryProperties.n); appearance[PdfDictionaryProperties.n] = PdfReferenceHolder(normal); } - holder = - PdfCrossTable.dereference(appearance[PdfDictionaryProperties.d]); + holder = PdfCrossTable.dereference( + appearance[PdfDictionaryProperties.d], + ); PdfDictionary? pressed = holder as PdfDictionary?; if (fieldChanged == true && pressed != null) { pressed = PdfDictionary(); - final PdfTemplate checkedTemplate = - PdfTemplate(rect.width, rect.height); - final PdfTemplate unchekedTemplate = - PdfTemplate(rect.width, rect.height); - drawStateItem(checkedTemplate.graphics!, - PdfCheckFieldState.pressedChecked, item, fieldItem); - drawStateItem(unchekedTemplate.graphics!, - PdfCheckFieldState.pressedUnchecked, item, fieldItem); - pressed.setProperty(PdfDictionaryProperties.off, - PdfReferenceHolder(unchekedTemplate)); + final PdfTemplate checkedTemplate = PdfTemplate( + rect.width, + rect.height, + ); + final PdfTemplate unchekedTemplate = PdfTemplate( + rect.width, + rect.height, + ); + drawStateItem( + checkedTemplate.graphics!, + PdfCheckFieldState.pressedChecked, + item, + fieldItem, + ); + drawStateItem( + unchekedTemplate.graphics!, + PdfCheckFieldState.pressedUnchecked, + item, + fieldItem, + ); + pressed.setProperty( + PdfDictionaryProperties.off, + PdfReferenceHolder(unchekedTemplate), + ); pressed.setProperty(value, PdfReferenceHolder(checkedTemplate)); appearance.remove(PdfDictionaryProperties.d); appearance[PdfDictionaryProperties.d] = PdfReferenceHolder(pressed); } } widget.setProperty(PdfDictionaryProperties.ap, appearance); - } else if (PdfFormHelper.getHelper(checkField.form!) - .setAppearanceDictionary) { + } else if (PdfFormHelper.getHelper( + checkField.form!, + ).setAppearanceDictionary) { PdfFormHelper.getHelper(checkField.form!).needAppearances = true; } else if (PdfFormHelper.getHelper(form!).setAppearanceDictionary && !PdfFormHelper.getHelper(form!).needAppearances!) { final PdfDictionary dic = PdfDictionary(); - final PdfTemplate template = - PdfTemplate(checkField.bounds.width, checkField.bounds.height); + final PdfTemplate template = PdfTemplate( + checkField.bounds.width, + checkField.bounds.height, + ); drawAppearance(template); dic.setProperty(PdfDictionaryProperties.n, PdfReferenceHolder(template)); widget!.setProperty(PdfDictionaryProperties.ap, dic); @@ -659,8 +773,9 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfCheckBoxStyle style = PdfCheckBoxStyle.check; if (widget.containsKey(PdfDictionaryProperties.mk)) { - final PdfDictionary bs = crossTable! - .getObject(widget[PdfDictionaryProperties.mk])! as PdfDictionary; + final PdfDictionary bs = + crossTable!.getObject(widget[PdfDictionaryProperties.mk])! + as PdfDictionary; style = _createStyle(bs); } return style; @@ -724,8 +839,9 @@ class PdfCheckFieldBaseHelper extends PdfFieldHelper { break; } if (widget[PdfDictionaryProperties.mk] is PdfReferenceHolder) { - final PdfDictionary widgetDict = crossTable! - .getObject(widget[PdfDictionaryProperties.mk])! as PdfDictionary; + final PdfDictionary widgetDict = + crossTable!.getObject(widget[PdfDictionaryProperties.mk])! + as PdfDictionary; if (widgetDict.containsKey(PdfDictionaryProperties.ca)) { widgetDict[PdfDictionaryProperties.ca] = PdfString(style); } else { @@ -765,25 +881,32 @@ class PdfRadioButtonListItem extends PdfCheckFieldBase { //Constructor /// Initializes a instance of the [PdfRadioButtonListItem] class with /// the specific value and bounds. - PdfRadioButtonListItem(String value, Rect bounds, - {PdfCheckBoxStyle style = PdfCheckBoxStyle.circle, - PdfColor? borderColor, - PdfColor? backColor, - PdfColor? foreColor, - int? borderWidth, - PdfHighlightMode highlightMode = PdfHighlightMode.invert, - PdfBorderStyle borderStyle = PdfBorderStyle.solid, - String? tooltip}) { + PdfRadioButtonListItem( + String value, + Rect bounds, { + PdfCheckBoxStyle style = PdfCheckBoxStyle.circle, + PdfColor? borderColor, + PdfColor? backColor, + PdfColor? foreColor, + int? borderWidth, + PdfHighlightMode highlightMode = PdfHighlightMode.invert, + PdfBorderStyle borderStyle = PdfBorderStyle.solid, + String? tooltip, + }) { _radioButtonListItemHelper = PdfRadioButtonListItemHelper(this); - _radioButtonListItemHelper.initialize(null, null, bounds, - style: style, - borderColor: borderColor, - backColor: backColor, - foreColor: foreColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + _radioButtonListItemHelper.initialize( + null, + null, + bounds, + style: style, + borderColor: borderColor, + backColor: backColor, + foreColor: foreColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); this.value = value; _radioButtonListItemHelper.dictionary!.beginSave = _radioButtonListItemHelper.dictionaryBeginSave; @@ -792,8 +915,11 @@ class PdfRadioButtonListItem extends PdfCheckFieldBase { style = PdfCheckBoxStyle.circle; } - PdfRadioButtonListItem._loaded(PdfDictionary dictionary, - PdfCrossTable crossTable, PdfRadioButtonListField field) { + PdfRadioButtonListItem._loaded( + PdfDictionary dictionary, + PdfCrossTable crossTable, + PdfRadioButtonListField field, + ) { _radioButtonListItemHelper = PdfRadioButtonListItemHelper(this); _radioButtonListItemHelper.load(dictionary, crossTable); _radioButtonListItemHelper._field = field; @@ -804,10 +930,11 @@ class PdfRadioButtonListItem extends PdfCheckFieldBase { ///Gets or sets the value. String get value { if (_radioButtonListItemHelper.isLoadedField) { - _radioButtonListItemHelper._value = - _radioButtonListItemHelper.getItemValue( - _radioButtonListItemHelper.dictionary!, - _radioButtonListItemHelper.crossTable); + _radioButtonListItemHelper._value = _radioButtonListItemHelper + .getItemValue( + _radioButtonListItemHelper.dictionary!, + _radioButtonListItemHelper.crossTable, + ); } return _radioButtonListItemHelper._value!; } @@ -824,9 +951,10 @@ class PdfRadioButtonListItem extends PdfCheckFieldBase { /// Gets the form of the field.{Read-Only} @override - PdfForm? get form => (_radioButtonListItemHelper._field != null) - ? _radioButtonListItemHelper._field!.form - : null; + PdfForm? get form => + (_radioButtonListItemHelper._field != null) + ? _radioButtonListItemHelper._field!.form + : null; @override set style(PdfCheckBoxStyle value) { @@ -841,10 +969,10 @@ class PdfRadioButtonListItem extends PdfCheckFieldBase { } else { if (super.style != value) { super.style = value; - WidgetAnnotationHelper.getHelper(_radioButtonListItemHelper.widget!) - .widgetAppearance! - .normalCaption = - _radioButtonListItemHelper.styleToString(super.style); + WidgetAnnotationHelper.getHelper( + _radioButtonListItemHelper.widget!, + ).widgetAppearance!.normalCaption = _radioButtonListItemHelper + .styleToString(super.style); } } } @@ -864,8 +992,11 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { String? optionValue; /// internal method - static PdfRadioButtonListItem loaded(PdfDictionary dictionary, - PdfCrossTable crossTable, PdfRadioButtonListField field) { + static PdfRadioButtonListItem loaded( + PdfDictionary dictionary, + PdfCrossTable crossTable, + PdfRadioButtonListField field, + ) { return PdfRadioButtonListItem._loaded(dictionary, crossTable, field); } @@ -919,9 +1050,11 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { final PdfDictionary pageDic = PdfPageHelper.getHelper(page).dictionary!; PdfArray? annots; if (pageDic.containsKey(PdfDictionaryProperties.annots)) { - annots = PdfPageHelper.getHelper(page) - .crossTable! - .getObject(pageDic[PdfDictionaryProperties.annots]) as PdfArray?; + annots = + PdfPageHelper.getHelper( + page, + ).crossTable!.getObject(pageDic[PdfDictionaryProperties.annots]) + as PdfArray?; } else { annots = PdfArray(); } @@ -936,9 +1069,9 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { if (!field.page!.annotations.contains(widget!)) { field.page!.annotations.add(widget!); } - PdfPageHelper.getHelper(field.page!) - .dictionary! - .setProperty(PdfDictionaryProperties.annots, annots); + PdfPageHelper.getHelper( + field.page!, + ).dictionary!.setProperty(PdfDictionaryProperties.annots, annots); } } if (field != null) { @@ -949,27 +1082,35 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { void _setItemValue(String value) { final String str = value; if (dictionary!.containsKey(PdfDictionaryProperties.ap)) { - PdfDictionary dic = crossTable! - .getObject(dictionary![PdfDictionaryProperties.ap])! as PdfDictionary; + PdfDictionary dic = + crossTable!.getObject(dictionary![PdfDictionaryProperties.ap])! + as PdfDictionary; if (dic.containsKey(PdfDictionaryProperties.n)) { - final PdfReference normal = - crossTable!.getReference(dic[PdfDictionaryProperties.n]); + final PdfReference normal = crossTable!.getReference( + dic[PdfDictionaryProperties.n], + ); dic = crossTable!.getObject(normal)! as PdfDictionary; final String? dicValue = getItemValue(dictionary!, crossTable); if (dic.containsKey(dicValue)) { final PdfReference valRef = crossTable!.getReference(dic[dicValue]); dic.remove(base.value); dic.setProperty( - str, PdfReferenceHolder.fromReference(valRef, crossTable)); + str, + PdfReferenceHolder.fromReference(valRef, crossTable), + ); } } } if (str == _field!.selectedValue) { - dictionary! - .setName(PdfName(PdfDictionaryProperties.usageApplication), str); + dictionary!.setName( + PdfName(PdfDictionaryProperties.usageApplication), + str, + ); } else { - dictionary!.setName(PdfName(PdfDictionaryProperties.usageApplication), - PdfDictionaryProperties.off); + dictionary!.setName( + PdfName(PdfDictionaryProperties.usageApplication), + PdfDictionaryProperties.off, + ); } } @@ -978,13 +1119,14 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { void draw() { removeAnnotationFromPage(_field!.page); final PaintParams params = PaintParams( - bounds: base.bounds, - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: base.borderStyle, - borderWidth: base.borderWidth, - shadowBrush: shadowBrush); + bounds: base.bounds, + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: base.borderStyle, + borderWidth: base.borderWidth, + shadowBrush: shadowBrush, + ); if (params.borderPen != null && params.borderWidth == 0) { params.borderWidth = 1; } @@ -993,7 +1135,11 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { state = PdfCheckFieldState.checked; } FieldPainter().drawRadioButton( - _field!.page!.graphics, params, styleToString(base.style), state); + _field!.page!.graphics, + params, + styleToString(base.style), + state, + ); } /// internal method @@ -1008,15 +1154,20 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { bounds = array.toRectangle().rect; double? y = 0; if ((PdfCrossTable.dereference(array[1])! as PdfNumber).value! < 0) { - y = (PdfCrossTable.dereference(array[1])! as PdfNumber).value - as double?; + y = + (PdfCrossTable.dereference(array[1])! as PdfNumber).value + as double?; if ((PdfCrossTable.dereference(array[1])! as PdfNumber).value! > (PdfCrossTable.dereference(array[3])! as PdfNumber).value!) { y = y! - bounds.height; } } bounds = Rect.fromLTWH( - bounds.left, y! <= 0 ? bounds.top : y, bounds.width, bounds.height); + bounds.left, + y! <= 0 ? bounds.top : y, + bounds.width, + bounds.height, + ); } else { bounds = Rect.zero; } @@ -1026,29 +1177,50 @@ class PdfRadioButtonListItemHelper extends PdfCheckFieldBaseHelper { /// internal method void drawCheckAppearance() { final PaintParams paintParams = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, widget!.bounds.size.width, widget!.bounds.size.height), - backBrush: PdfSolidBrush(base.backColor), - foreBrush: PdfSolidBrush(base.foreColor), - borderPen: borderPen, - style: base.borderStyle, - borderWidth: base.borderWidth, - shadowBrush: PdfSolidBrush(base.backColor)); + bounds: Rect.fromLTWH( + 0, + 0, + widget!.bounds.size.width, + widget!.bounds.size.height, + ), + backBrush: PdfSolidBrush(base.backColor), + foreBrush: PdfSolidBrush(base.foreColor), + borderPen: borderPen, + style: base.borderStyle, + borderWidth: base.borderWidth, + shadowBrush: PdfSolidBrush(base.backColor), + ); PdfTemplate template = widget!.extendedAppearance!.normal.activate!; - FieldPainter().drawRadioButton(template.graphics, paintParams, - styleToString(base.style), PdfCheckFieldState.checked); + FieldPainter().drawRadioButton( + template.graphics, + paintParams, + styleToString(base.style), + PdfCheckFieldState.checked, + ); template = widget!.extendedAppearance!.normal.off!; - FieldPainter().drawRadioButton(template.graphics, paintParams, - styleToString(base.style), PdfCheckFieldState.unchecked); + FieldPainter().drawRadioButton( + template.graphics, + paintParams, + styleToString(base.style), + PdfCheckFieldState.unchecked, + ); template = widget!.extendedAppearance!.pressed.activate!; - FieldPainter().drawRadioButton(template.graphics, paintParams, - styleToString(base.style), PdfCheckFieldState.pressedChecked); + FieldPainter().drawRadioButton( + template.graphics, + paintParams, + styleToString(base.style), + PdfCheckFieldState.pressedChecked, + ); template = widget!.extendedAppearance!.pressed.off!; - FieldPainter().drawRadioButton(template.graphics, paintParams, - styleToString(base.style), PdfCheckFieldState.pressedUnchecked); + FieldPainter().drawRadioButton( + template.graphics, + paintParams, + styleToString(base.style), + PdfCheckFieldState.pressedUnchecked, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_combo_box_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_combo_box_field.dart index b7897fdff..183ce06bf 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_combo_box_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_combo_box_field.dart @@ -30,32 +30,40 @@ import 'pdf_list_field_item.dart'; class PdfComboBoxField extends PdfListField { /// Initializes a new instance of the [PdfComboBoxField] class with /// the specific page, name and bounds. - PdfComboBoxField(PdfPage page, String name, Rect bounds, - {List? items, - bool editable = false, - int? selectedIndex, - String? selectedValue, - PdfFont? font, - PdfTextAlignment alignment = PdfTextAlignment.left, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode highlightMode = PdfHighlightMode.invert, - PdfBorderStyle borderStyle = PdfBorderStyle.solid, - String? tooltip}) { + PdfComboBoxField( + PdfPage page, + String name, + Rect bounds, { + List? items, + bool editable = false, + int? selectedIndex, + String? selectedValue, + PdfFont? font, + PdfTextAlignment alignment = PdfTextAlignment.left, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode highlightMode = PdfHighlightMode.invert, + PdfBorderStyle borderStyle = PdfBorderStyle.solid, + String? tooltip, + }) { _helper = PdfComboBoxFieldHelper(this); - _helper.initializeInternal(page, name, bounds, - font: font, - alignment: alignment, - items: items, - borderColor: borderColor, - foreColor: foreColor, - backColor: backColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + _helper.initializeInternal( + page, + name, + bounds, + font: font, + alignment: alignment, + items: items, + borderColor: borderColor, + foreColor: foreColor, + backColor: backColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); _helper.flags.add(FieldFlags.combo); this.editable = editable; if (selectedIndex != null) { @@ -82,7 +90,8 @@ class PdfComboBoxField extends PdfListField { /// The default value is false. bool get editable { if (_helper.isLoadedField) { - _editable = _helper.isFlagPresent(FieldFlags.edit) || + _editable = + _helper.isFlagPresent(FieldFlags.edit) || _helper.flags.contains(FieldFlags.edit); } return _editable; @@ -94,8 +103,8 @@ class PdfComboBoxField extends PdfListField { _editable ? _helper.flags.add(FieldFlags.edit) : _helper.isLoadedField - ? _helper.removeFlag(FieldFlags.edit) - : _helper.flags.remove(FieldFlags.edit); + ? _helper.removeFlag(FieldFlags.edit) + : _helper.flags.remove(FieldFlags.edit); } } @@ -128,7 +137,9 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { /// internal method static PdfComboBoxField loadComboBox( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfComboBoxField._load(dictionary, crossTable); } @@ -142,36 +153,44 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { void drawAppearance(PdfTemplate template) { super.drawAppearance(template); final PaintParams params = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, comboBoxField.bounds.width, comboBoxField.bounds.height), - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: comboBoxField.borderStyle, - borderWidth: comboBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: Rect.fromLTWH( + 0, + 0, + comboBoxField.bounds.width, + comboBoxField.bounds.height, + ), + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: comboBoxField.borderStyle, + borderWidth: comboBoxField.borderWidth, + shadowBrush: shadowBrush, + ); FieldPainter().drawRectangularControl(template.graphics!, params); if (comboBoxField.selectedIndex != -1 && comboBoxField.items[comboBoxField.selectedIndex].text != '' && PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(comboBoxField.page!).document!) - .conformanceLevel == + PdfPageHelper.getHelper(comboBoxField.page!).document!, + ).conformanceLevel == PdfConformanceLevel.none) { - final int multiplier = params.style == PdfBorderStyle.beveled || - params.style == PdfBorderStyle.inset - ? 2 - : 1; + final int multiplier = + params.style == PdfBorderStyle.beveled || + params.style == PdfBorderStyle.inset + ? 2 + : 1; final Rect rectangle = Rect.fromLTWH( - params.bounds!.left + (2 * multiplier) * params.borderWidth!, - params.bounds!.top + (2 * multiplier) * params.borderWidth!, - params.bounds!.width - (4 * multiplier) * params.borderWidth!, - params.bounds!.height - (4 * multiplier) * params.borderWidth!); + params.bounds!.left + (2 * multiplier) * params.borderWidth!, + params.bounds!.top + (2 * multiplier) * params.borderWidth!, + params.bounds!.width - (4 * multiplier) * params.borderWidth!, + params.bounds!.height - (4 * multiplier) * params.borderWidth!, + ); template.graphics!.drawString( - comboBoxField.items[comboBoxField.selectedIndex].text, - comboBoxField.font ?? PdfStandardFont(PdfFontFamily.timesRoman, 12), - brush: params.foreBrush, - bounds: rectangle, - format: format); + comboBoxField.items[comboBoxField.selectedIndex].text, + comboBoxField.font ?? PdfStandardFont(PdfFontFamily.timesRoman, 12), + brush: params.foreBrush, + bounds: rectangle, + format: format, + ); } } @@ -185,29 +204,37 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { void _applyAppearance(PdfDictionary widget) { if (widget.containsKey(PdfDictionaryProperties.ap) && !PdfFormHelper.getHelper(comboBoxField.form!).needAppearances!) { - final IPdfPrimitive? appearance = - crossTable!.getObject(widget[PdfDictionaryProperties.ap]); + final IPdfPrimitive? appearance = crossTable!.getObject( + widget[PdfDictionaryProperties.ap], + ); if ((appearance != null) && appearance is PdfDictionary && (appearance.containsKey(PdfDictionaryProperties.n))) { final PdfTemplate template = PdfTemplate( - comboBoxField.bounds.width, comboBoxField.bounds.height); + comboBoxField.bounds.width, + comboBoxField.bounds.height, + ); _drawComboBox(template.graphics); appearance.remove(PdfDictionaryProperties.n); appearance.setProperty( - PdfDictionaryProperties.n, PdfReferenceHolder(template)); + PdfDictionaryProperties.n, + PdfReferenceHolder(template), + ); widget.setProperty(PdfDictionaryProperties.ap, appearance); } } else if (comboBoxField.form!.readOnly == true || comboBoxField.readOnly == true) { PdfFormHelper.getHelper(comboBoxField.form!).setAppearanceDictionary = true; - } else if (PdfFormHelper.getHelper(comboBoxField.form!) - .setAppearanceDictionary && + } else if (PdfFormHelper.getHelper( + comboBoxField.form!, + ).setAppearanceDictionary && !PdfFormHelper.getHelper(comboBoxField.form!).needAppearances!) { final PdfDictionary dic = PdfDictionary(); - final PdfTemplate template = - PdfTemplate(comboBoxField.bounds.width, comboBoxField.bounds.height); + final PdfTemplate template = PdfTemplate( + comboBoxField.bounds.width, + comboBoxField.bounds.height, + ); drawAppearance(template); dic.setProperty(PdfDictionaryProperties.n, PdfReferenceHolder(template)); widget.setProperty(PdfDictionaryProperties.ap, dic); @@ -221,21 +248,31 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { if (!isLoadedField && PdfAnnotationHelper.getHelper(widget!).appearance != null) { comboBoxField.page!.graphics.drawPdfTemplate( - widget!.appearance.normal, comboBoxField.bounds.topLeft); + widget!.appearance.normal, + comboBoxField.bounds.topLeft, + ); } else { final Rect rect = Rect.fromLTWH( - 0, 0, comboBoxField.bounds.width, comboBoxField.bounds.height); - final PdfFont font = comboBoxField.font ?? + 0, + 0, + comboBoxField.bounds.width, + comboBoxField.bounds.height, + ); + final PdfFont font = + comboBoxField.font ?? PdfStandardFont( - PdfFontFamily.helvetica, getFontHeight(PdfFontFamily.helvetica)); + PdfFontFamily.helvetica, + getFontHeight(PdfFontFamily.helvetica), + ); final PaintParams parameters = PaintParams( - bounds: rect, - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: comboBoxField.borderStyle, - borderWidth: comboBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: rect, + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: comboBoxField.borderStyle, + borderWidth: comboBoxField.borderWidth, + shadowBrush: shadowBrush, + ); final PdfTemplate template = PdfTemplate(rect.width, rect.height); String? text = ''; if (comboBoxField.selectedIndex != -1) { @@ -245,8 +282,9 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { dictionary!.containsKey(PdfDictionaryProperties.v) && dictionary!.containsKey(PdfDictionaryProperties.ap) && !dictionary!.containsKey(PdfDictionaryProperties.parent)) { - final IPdfPrimitive? value = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.v]); + final IPdfPrimitive? value = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.v], + ); if (value != null && value is PdfString) { text = value.value; } @@ -256,7 +294,8 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { (dictionary![PdfDictionaryProperties.dv]! as PdfString).value; } else { final IPdfPrimitive? str = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.dv]); + dictionary![PdfDictionaryProperties.dv], + ); if (str != null && str is PdfString) { text = str.value; } @@ -267,37 +306,54 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { FieldPainter().drawRectangularControl(template.graphics!, parameters); final double borderWidth = parameters.borderWidth!.toDouble(); final double doubleBorderWidth = 2 * borderWidth; - final bool padding = parameters.style == PdfBorderStyle.inset || + final bool padding = + parameters.style == PdfBorderStyle.inset || parameters.style == PdfBorderStyle.beveled; - final Offset point = padding - ? Offset(2 * doubleBorderWidth, 2 * borderWidth) - : Offset(doubleBorderWidth, borderWidth); + final Offset point = + padding + ? Offset(2 * doubleBorderWidth, 2 * borderWidth) + : Offset(doubleBorderWidth, borderWidth); final double width = parameters.bounds!.width - doubleBorderWidth; final Rect itemTextBound = Rect.fromLTWH( - point.dx, - point.dy, - width - point.dx, - parameters.bounds!.height - - (padding ? doubleBorderWidth : borderWidth)); - template.graphics!.drawString(text!, font, - brush: foreBrush, bounds: itemTextBound, format: format); - comboBoxField.page!.graphics - .drawPdfTemplate(template, comboBoxField.bounds.topLeft, rect.size); + point.dx, + point.dy, + width - point.dx, + parameters.bounds!.height - + (padding ? doubleBorderWidth : borderWidth), + ); + template.graphics!.drawString( + text!, + font, + brush: foreBrush, + bounds: itemTextBound, + format: format, + ); + comboBoxField.page!.graphics.drawPdfTemplate( + template, + comboBoxField.bounds.topLeft, + rect.size, + ); } else { final GraphicsProperties gp = GraphicsProperties(comboBoxField); final PaintParams prms = PaintParams( - bounds: gp.bounds, - backBrush: gp.backBrush, - foreBrush: gp.foreBrush, - borderPen: gp.borderPen, - style: gp.style, - borderWidth: gp.borderWidth, - shadowBrush: gp.shadowBrush); + bounds: gp.bounds, + backBrush: gp.backBrush, + foreBrush: gp.foreBrush, + borderPen: gp.borderPen, + style: gp.style, + borderWidth: gp.borderWidth, + shadowBrush: gp.shadowBrush, + ); if (gp.font!.height > comboBoxField.bounds.height) { setFittingFontSize(gp, prms, text!); } FieldPainter().drawComboBox( - comboBoxField.page!.graphics, prms, text, gp.font, gp.stringFormat); + comboBoxField.page!.graphics, + prms, + text, + gp.font, + gp.stringFormat, + ); } } } @@ -305,15 +361,20 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { void _drawComboBox(PdfGraphics? graphics) { final GraphicsProperties gp = GraphicsProperties(comboBoxField); gp.bounds = Rect.fromLTWH( - 0, 0, comboBoxField.bounds.width, comboBoxField.bounds.height); + 0, + 0, + comboBoxField.bounds.width, + comboBoxField.bounds.height, + ); final PaintParams prms = PaintParams( - bounds: gp.bounds, - backBrush: gp.backBrush, - foreBrush: gp.foreBrush, - borderPen: gp.borderPen, - style: gp.style, - borderWidth: gp.borderWidth, - shadowBrush: gp.shadowBrush); + bounds: gp.bounds, + backBrush: gp.backBrush, + foreBrush: gp.foreBrush, + borderPen: gp.borderPen, + style: gp.style, + borderWidth: gp.borderWidth, + shadowBrush: gp.shadowBrush, + ); String? text; if (selectedItems.count > 0 && comboBoxField.selectedIndex != -1 && @@ -321,18 +382,29 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { text = selectedItems[0].text; } else if (dictionary!.containsKey(PdfDictionaryProperties.dv) && !flattenField) { - final IPdfPrimitive? defaultValue = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.dv]); + final IPdfPrimitive? defaultValue = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.dv], + ); if (defaultValue != null && defaultValue is PdfString) { text = defaultValue.value; } } if (selectedItems.count == 0) { - FieldPainter().drawComboBox(graphics!, prms, comboBoxField.selectedValue, - gp.font, gp.stringFormat); + FieldPainter().drawComboBox( + graphics!, + prms, + comboBoxField.selectedValue, + gp.font, + gp.stringFormat, + ); } else if (text != null && !flattenField) { - FieldPainter() - .drawComboBox(graphics!, prms, text, gp.font, gp.stringFormat); + FieldPainter().drawComboBox( + graphics!, + prms, + text, + gp.font, + gp.stringFormat, + ); } else { FieldPainter().drawRectangularControl(graphics!, prms); } @@ -345,8 +417,9 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { final List widths = []; if (comboBoxField.selectedIndex != -1) { final PdfFont itemFont = PdfStandardFont(family, 12); - widths - .add(itemFont.measureString(comboBoxField.selectedItem!.text).width); + widths.add( + itemFont.measureString(comboBoxField.selectedItem!.text).width, + ); } else { final PdfFont sfont = PdfStandardFont(family, 12); double max = sfont.measureString(comboBoxField.items[0].text).width; @@ -358,12 +431,13 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { } } widths.sort(); - double s = widths.isNotEmpty - ? ((12 * - (comboBoxField.bounds.size.width - - 4 * comboBoxField.borderWidth)) / - widths[widths.length - 1]) - : 12; + double s = + widths.isNotEmpty + ? ((12 * + (comboBoxField.bounds.size.width - + 4 * comboBoxField.borderWidth)) / + widths[widths.length - 1]) + : 12; if (comboBoxField.selectedIndex != -1) { final PdfFont font = PdfStandardFont(family, s); final String text = comboBoxField.selectedValue; @@ -384,8 +458,11 @@ class PdfComboBoxFieldHelper extends PdfListFieldHelper { do { fontSize = fontSize - 0.001; PdfFontHelper.getHelper(font).setSize(fontSize); - final double textWidth = - PdfFontHelper.getLineWidth(font, text, format); + final double textWidth = PdfFontHelper.getLineWidth( + font, + text, + format, + ); if (fontSize < minimumFontSize) { PdfFontHelper.getHelper(font).setSize(minimumFontSize); break; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field.dart index 745dd080c..2a1a8b9a6 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field.dart @@ -60,17 +60,21 @@ import 'pdf_text_box_field.dart'; abstract class PdfField implements IPdfWrapper { //Constructor /// Initializes a new instance of the [PdfField] class with the specific page and name. - void _internal(PdfPage? page, String? name, Rect bounds, - {PdfFont? font, - PdfTextAlignment? alignment, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode? highlightMode, - PdfBorderStyle? borderStyle, - String? tooltip, - PdfFieldHelper? helper}) { + void _internal( + PdfPage? page, + String? name, + Rect bounds, { + PdfFont? font, + PdfTextAlignment? alignment, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode? highlightMode, + PdfBorderStyle? borderStyle, + String? tooltip, + PdfFieldHelper? helper, + }) { _fieldHelper = helper!; if (this is PdfSignatureField) { if (page != null && PdfPageHelper.getHelper(page).document != null) { @@ -84,8 +88,10 @@ abstract class PdfField implements IPdfWrapper { this.bounds = bounds; if (name != null) { _fieldHelper.name = name; - _fieldHelper.dictionary! - .setProperty(PdfDictionaryProperties.t, PdfString(name)); + _fieldHelper.dictionary!.setProperty( + PdfDictionaryProperties.t, + PdfString(name), + ); } if (font != null) { _fieldHelper.font = font; @@ -120,8 +126,11 @@ abstract class PdfField implements IPdfWrapper { } /// internal constructor - void _load(PdfDictionary dictionary, PdfCrossTable crossTable, - PdfFieldHelper helper) { + void _load( + PdfDictionary dictionary, + PdfCrossTable crossTable, + PdfFieldHelper helper, + ) { _fieldHelper = helper; _fieldHelper.dictionary = dictionary; _fieldHelper.crossTable = crossTable; @@ -192,10 +201,11 @@ abstract class PdfField implements IPdfWrapper { if (_fieldHelper.isLoadedField && (_mappingName == null || _mappingName!.isEmpty)) { final IPdfPrimitive? str = PdfFieldHelper.getValue( - _fieldHelper.dictionary!, - _fieldHelper.crossTable, - PdfDictionaryProperties.tm, - false); + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + PdfDictionaryProperties.tm, + false, + ); if (str != null && str is PdfString) { _mappingName = str.value; } @@ -206,8 +216,10 @@ abstract class PdfField implements IPdfWrapper { set mappingName(String value) { if (_mappingName != value) { _mappingName = value; - _fieldHelper.dictionary! - .setString(PdfDictionaryProperties.tm, _mappingName); + _fieldHelper.dictionary!.setString( + PdfDictionaryProperties.tm, + _mappingName, + ); } if (_fieldHelper.isLoadedField) { _fieldHelper.changed = true; @@ -218,10 +230,11 @@ abstract class PdfField implements IPdfWrapper { String get tooltip { if (_fieldHelper.isLoadedField && (_tooltip == null || _tooltip!.isEmpty)) { final IPdfPrimitive? str = PdfFieldHelper.getValue( - _fieldHelper.dictionary!, - _fieldHelper.crossTable, - PdfDictionaryProperties.tu, - false); + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + PdfDictionaryProperties.tu, + false, + ); if (str != null && str is PdfString) { _tooltip = str.value; } @@ -244,8 +257,9 @@ abstract class PdfField implements IPdfWrapper { /// The default value is true. bool get canExport { if (_fieldHelper.isLoadedField) { - _export = !(_fieldHelper.isFlagPresent(FieldFlags.noExport) || - _fieldHelper.flags.contains(FieldFlags.noExport)); + _export = + !(_fieldHelper.isFlagPresent(FieldFlags.noExport) || + _fieldHelper.flags.contains(FieldFlags.noExport)); } return _export; } @@ -292,9 +306,14 @@ abstract class PdfField implements IPdfWrapper { } else if (dictionary.containsKey(PdfDictionaryProperties.mediaBox)) { PdfArray? mediaBox; if (PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.mediaBox]) is PdfArray) { - mediaBox = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.mediaBox]) as PdfArray?; + dictionary[PdfDictionaryProperties.mediaBox], + ) + is PdfArray) { + mediaBox = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.mediaBox], + ) + as PdfArray?; } if ((mediaBox![0]! as PdfNumber).value! > 0 || (mediaBox[1]! as PdfNumber).value! > 0 || @@ -311,8 +330,12 @@ abstract class PdfField implements IPdfWrapper { } else { y = rect.top + rect.height; } - return Rect.fromLTWH(x == 0 ? rect.left : x, y == 0 ? rect.top : y, - rect.width, rect.height); + return Rect.fromLTWH( + x == 0 ? rect.left : x, + y == 0 ? rect.top : y, + rect.width, + rect.height, + ); } else { return _fieldHelper.widget!.bounds; } @@ -329,12 +352,14 @@ abstract class PdfField implements IPdfWrapper { PdfNumber(rect.left), PdfNumber(height - (rect.top + rect.height)), PdfNumber(rect.left + rect.width), - PdfNumber(height - rect.top) + PdfNumber(height - rect.top), ]; PdfDictionary dic = _fieldHelper.dictionary!; if (!dic.containsKey(PdfDictionaryProperties.rect)) { dic = _fieldHelper.getWidgetAnnotation( - _fieldHelper.dictionary!, _fieldHelper.crossTable); + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + ); } dic.setArray(PdfDictionaryProperties.rect, values); _fieldHelper.changed = true; @@ -350,11 +375,15 @@ abstract class PdfField implements IPdfWrapper { if (_fieldHelper.isLoadedField) { if (page != null) { final PdfDictionary annotDic = _fieldHelper.getWidgetAnnotation( - _fieldHelper.dictionary!, _fieldHelper.crossTable); - final PdfReference reference = - PdfPageHelper.getHelper(page!).crossTable!.getReference(annotDic); - _tabIndex = - PdfPageHelper.getHelper(page!).annotsReference.indexOf(reference); + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + ); + final PdfReference reference = PdfPageHelper.getHelper( + page!, + ).crossTable!.getReference(annotDic); + _tabIndex = PdfPageHelper.getHelper( + page!, + ).annotsReference.indexOf(reference); } } return _tabIndex; @@ -366,21 +395,24 @@ abstract class PdfField implements IPdfWrapper { page != null && page!.formFieldsTabOrder == PdfFormFieldsTabOrder.manual) { final PdfAnnotation annotationReference = WidgetAnnotationHelper.load( - _fieldHelper.dictionary!, _fieldHelper.crossTable!); - final PdfReference reference = PdfPageHelper.getHelper(page!) - .crossTable! - .getReference(IPdfWrapper.getElement(annotationReference)); - int index = - PdfPageHelper.getHelper(page!).annotsReference.indexOf(reference); + _fieldHelper.dictionary!, + _fieldHelper.crossTable!, + ); + final PdfReference reference = PdfPageHelper.getHelper( + page!, + ).crossTable!.getReference(IPdfWrapper.getElement(annotationReference)); + int index = PdfPageHelper.getHelper( + page!, + ).annotsReference.indexOf(reference); if (index < 0) { index = _fieldHelper.annotationIndex; } - final PdfArray? annots = - PdfAnnotationCollectionHelper.getHelper(page!.annotations) - .rearrange(reference, _tabIndex, index); - PdfPageHelper.getHelper(page!) - .dictionary! - .setProperty(PdfDictionaryProperties.annots, annots); + final PdfArray? annots = PdfAnnotationCollectionHelper.getHelper( + page!.annotations, + ).rearrange(reference, _tabIndex, index); + PdfPageHelper.getHelper( + page!, + ).dictionary!.setProperty(PdfDictionaryProperties.annots, annots); } } @@ -392,9 +424,10 @@ abstract class PdfField implements IPdfWrapper { //Implementations void _initialize() { - _fieldHelper.dictionary!.beginSave = this is PdfSignatureField - ? _fieldHelper.dictionaryBeginSave - : _dictBeginSave; + _fieldHelper.dictionary!.beginSave = + this is PdfSignatureField + ? _fieldHelper.dictionaryBeginSave + : _dictBeginSave; _fieldHelper.widget = WidgetAnnotation(); if (this is PdfSignatureField && form!.fieldAutoNaming) { _fieldHelper._createBorderPen(); @@ -405,15 +438,18 @@ abstract class PdfField implements IPdfWrapper { _fieldHelper.widget!.parent = this; if (this is! PdfSignatureField) { _fieldHelper.format = PdfStringFormat( - alignment: _fieldHelper.widget!.alignment!, - lineAlignment: PdfVerticalAlignment.middle); + alignment: _fieldHelper.widget!.alignment!, + lineAlignment: PdfVerticalAlignment.middle, + ); _fieldHelper._createBorderPen(); _fieldHelper._createBackBrush(); } final PdfArray array = PdfArray(); array.add(PdfReferenceHolder(_fieldHelper.widget)); - _fieldHelper.dictionary! - .setProperty(PdfDictionaryProperties.kids, PdfArray(array)); + _fieldHelper.dictionary!.setProperty( + PdfDictionaryProperties.kids, + PdfArray(array), + ); } _fieldHelper.widget!.defaultAppearance.fontName = 'TiRo'; } @@ -426,50 +462,74 @@ abstract class PdfField implements IPdfWrapper { String? name; PdfString? str; if (!_fieldHelper.dictionary!.containsKey(PdfDictionaryProperties.parent)) { - str = PdfFieldHelper.getValue( - _fieldHelper.dictionary!, - _fieldHelper.crossTable, - PdfDictionaryProperties.t, - false) as PdfString?; + str = + PdfFieldHelper.getValue( + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + PdfDictionaryProperties.t, + false, + ) + as PdfString?; } else { - IPdfPrimitive? dic = _fieldHelper.crossTable! - .getObject(_fieldHelper.dictionary![PdfDictionaryProperties.parent]); + IPdfPrimitive? dic = _fieldHelper.crossTable!.getObject( + _fieldHelper.dictionary![PdfDictionaryProperties.parent], + ); while (dic != null && dic is PdfDictionary && dic.containsKey(PdfDictionaryProperties.parent)) { if (dic.containsKey(PdfDictionaryProperties.t)) { - name = name == null - ? (PdfFieldHelper.getValue(dic, _fieldHelper.crossTable, - PdfDictionaryProperties.t, false)! as PdfString) - .value - : '${(PdfFieldHelper.getValue(dic, _fieldHelper.crossTable, PdfDictionaryProperties.t, false)! as PdfString).value!}.$name'; + name = + name == null + ? (PdfFieldHelper.getValue( + dic, + _fieldHelper.crossTable, + PdfDictionaryProperties.t, + false, + )! + as PdfString) + .value + : '${(PdfFieldHelper.getValue(dic, _fieldHelper.crossTable, PdfDictionaryProperties.t, false)! as PdfString).value!}.$name'; } - dic = _fieldHelper.crossTable! - .getObject(dic[PdfDictionaryProperties.parent]) as PdfDictionary?; + dic = + _fieldHelper.crossTable!.getObject( + dic[PdfDictionaryProperties.parent], + ) + as PdfDictionary?; } if (dic != null && dic is PdfDictionary && dic.containsKey(PdfDictionaryProperties.t)) { - name = name == null - ? (PdfFieldHelper.getValue(dic, _fieldHelper.crossTable, - PdfDictionaryProperties.t, false)! as PdfString) - .value - : '${(PdfFieldHelper.getValue(dic, _fieldHelper.crossTable, PdfDictionaryProperties.t, false)! as PdfString).value!}.$name'; + name = + name == null + ? (PdfFieldHelper.getValue( + dic, + _fieldHelper.crossTable, + PdfDictionaryProperties.t, + false, + )! + as PdfString) + .value + : '${(PdfFieldHelper.getValue(dic, _fieldHelper.crossTable, PdfDictionaryProperties.t, false)! as PdfString).value!}.$name'; final IPdfPrimitive? strName = PdfFieldHelper.getValue( - _fieldHelper.dictionary!, - _fieldHelper.crossTable, - PdfDictionaryProperties.t, - false); + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + PdfDictionaryProperties.t, + false, + ); if (strName != null && strName is PdfString) { name = '${name!}.${strName.value!}'; } - } else if (_fieldHelper.dictionary! - .containsKey(PdfDictionaryProperties.t)) { - str = PdfFieldHelper.getValue( - _fieldHelper.dictionary!, - _fieldHelper.crossTable, - PdfDictionaryProperties.t, - false) as PdfString?; + } else if (_fieldHelper.dictionary!.containsKey( + PdfDictionaryProperties.t, + )) { + str = + PdfFieldHelper.getValue( + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + PdfDictionaryProperties.t, + false, + ) + as PdfString?; } } if (str != null) { @@ -485,18 +545,21 @@ abstract class PdfField implements IPdfWrapper { _fieldHelper.crossTable != null) { final PdfDocument? doc = _fieldHelper.crossTable!.document; final PdfDictionary widget = _fieldHelper.getWidgetAnnotation( - _fieldHelper.dictionary!, _fieldHelper.crossTable); + _fieldHelper.dictionary!, + _fieldHelper.crossTable, + ); if (widget.containsKey(PdfDictionaryProperties.p) && PdfCrossTable.dereference(widget[PdfDictionaryProperties.p]) is! PdfNull) { - final IPdfPrimitive? pageRef = _fieldHelper.crossTable! - .getObject(widget[PdfDictionaryProperties.p]); + final IPdfPrimitive? pageRef = _fieldHelper.crossTable!.getObject( + widget[PdfDictionaryProperties.p], + ); if (pageRef != null && pageRef is PdfDictionary) { page = PdfPageCollectionHelper.getHelper(doc!.pages).getPage(pageRef); } } else { - final PdfReference widgetReference = - _fieldHelper.crossTable!.getReference(widget); + final PdfReference widgetReference = _fieldHelper.crossTable! + .getReference(widget); for (int j = 0; j < doc!.pages.count; j++) { final PdfPage loadedPage = doc.pages[j]; final PdfArray? lAnnots = @@ -527,17 +590,17 @@ abstract class PdfField implements IPdfWrapper { } } if (page != null && - PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.tabs)) { + PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.tabs)) { final IPdfPrimitive? tabName = PdfCrossTable.dereference( - PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.tabs]); + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties.tabs], + ); if (tabName != null && ((tabName is PdfName && tabName.name == '') || (tabName is PdfString && tabName.value == ''))) { - PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.tabs] = PdfName(' '); + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .tabs] = PdfName(' '); } } return page; @@ -546,40 +609,50 @@ abstract class PdfField implements IPdfWrapper { void _addAnnotationToPage(PdfPage? page, PdfAnnotation? widget) { if (page != null && !PdfPageHelper.getHelper(page).isLoadedPage) { PdfAnnotationHelper.getHelper(widget!).dictionary!.setProperty( - PdfDictionaryProperties.t, PdfString(_fieldHelper.name!)); + PdfDictionaryProperties.t, + PdfString(_fieldHelper.name!), + ); } else { final PdfDictionary pageDic = PdfPageHelper.getHelper(page!).dictionary!; PdfArray? annots; if (pageDic.containsKey(PdfDictionaryProperties.annots)) { - final IPdfPrimitive? obj = PdfPageHelper.getHelper(page) - .crossTable! - .getObject(pageDic[PdfDictionaryProperties.annots]); + final IPdfPrimitive? obj = PdfPageHelper.getHelper( + page, + ).crossTable!.getObject(pageDic[PdfDictionaryProperties.annots]); if (obj != null && obj is PdfArray) { annots = obj; } } annots ??= PdfArray(); - PdfAnnotationHelper.getHelper(widget!) - .dictionary! - .setProperty(PdfDictionaryProperties.p, PdfReferenceHolder(page)); + PdfAnnotationHelper.getHelper(widget!).dictionary!.setProperty( + PdfDictionaryProperties.p, + PdfReferenceHolder(page), + ); form!.fieldAutoNaming ? PdfAnnotationHelper.getHelper(widget).dictionary!.setProperty( - PdfDictionaryProperties.t, PdfString(_fieldHelper.name!)) + PdfDictionaryProperties.t, + PdfString(_fieldHelper.name!), + ) : _fieldHelper.dictionary!.setProperty( - PdfDictionaryProperties.t, PdfString(_fieldHelper.name!)); + PdfDictionaryProperties.t, + PdfString(_fieldHelper.name!), + ); annots.add(PdfReferenceHolder(widget)); - PdfPageHelper.getHelper(page) - .dictionary! - .setProperty(PdfDictionaryProperties.annots, annots); + PdfPageHelper.getHelper( + page, + ).dictionary!.setProperty(PdfDictionaryProperties.annots, annots); } } List _getWidgetAnnotations( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { final List widgetAnnotationCollection = []; if (dictionary.containsKey(PdfDictionaryProperties.kids)) { - final IPdfPrimitive? array = - crossTable.getObject(dictionary[PdfDictionaryProperties.kids]); + final IPdfPrimitive? array = crossTable.getObject( + dictionary[PdfDictionaryProperties.kids], + ); if (array != null && array is PdfArray && array.count > 0) { for (int i = 0; i < array.count; i++) { final IPdfPrimitive item = array[i]!; @@ -591,8 +664,9 @@ abstract class PdfField implements IPdfWrapper { } } } else if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { - final IPdfPrimitive? type = - crossTable.getObject(dictionary[PdfDictionaryProperties.subtype]); + final IPdfPrimitive? type = crossTable.getObject( + dictionary[PdfDictionaryProperties.subtype], + ); if (type != null && type is PdfName && type.name == PdfDictionaryProperties.widget) { @@ -620,27 +694,35 @@ class PdfFieldHelper { } /// internal method - void internal(PdfPage? page, String? name, Rect bounds, - {PdfFont? font, - PdfTextAlignment? alignment, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode? highlightMode, - PdfBorderStyle? borderStyle, - String? tooltip}) { - field._internal(page, name, bounds, - font: font, - alignment: alignment, - borderColor: borderColor, - foreColor: foreColor, - backColor: backColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip, - helper: this); + void internal( + PdfPage? page, + String? name, + Rect bounds, { + PdfFont? font, + PdfTextAlignment? alignment, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode? highlightMode, + PdfBorderStyle? borderStyle, + String? tooltip, + }) { + field._internal( + page, + name, + bounds, + font: font, + alignment: alignment, + borderColor: borderColor, + foreColor: foreColor, + backColor: backColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + helper: this, + ); } /// internal field @@ -756,8 +838,9 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfColor bc = PdfColor.empty; if (widget.containsKey(PdfDictionaryProperties.mk)) { - final IPdfPrimitive? getObject = - crossTable!.getObject(widget[PdfDictionaryProperties.mk]); + final IPdfPrimitive? getObject = crossTable!.getObject( + widget[PdfDictionaryProperties.mk], + ); if (getObject != null && getObject is PdfDictionary && getObject.containsKey(PdfDictionaryProperties.bc)) { @@ -768,9 +851,9 @@ class PdfFieldHelper { } return bc; } else { - return WidgetAnnotationHelper.getHelper(widget!) - .widgetAppearance! - .borderColor; + return WidgetAnnotationHelper.getHelper( + widget!, + ).widgetAppearance!.borderColor; } } @@ -789,9 +872,12 @@ class PdfFieldHelper { } /// Gets or sets the color of the background. - PdfColor get backColor => isLoadedField - ? getBackColor() - : WidgetAnnotationHelper.getHelper(widget!).widgetAppearance!.backColor; + PdfColor get backColor => + isLoadedField + ? getBackColor() + : WidgetAnnotationHelper.getHelper( + widget!, + ).widgetAppearance!.backColor; set backColor(PdfColor value) { if (isLoadedField) { @@ -825,12 +911,15 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfColor color = PdfColor(0, 0, 0); if (widget.containsKey(PdfDictionaryProperties.da)) { - final PdfString defaultAppearance = crossTable! - .getObject(widget[PdfDictionaryProperties.da])! as PdfString; + final PdfString defaultAppearance = + crossTable!.getObject(widget[PdfDictionaryProperties.da])! + as PdfString; color = _getForeColor(defaultAppearance.value); } else { final IPdfPrimitive? defaultAppearance = widget.getValue( - PdfDictionaryProperties.da, PdfDictionaryProperties.parent); + PdfDictionaryProperties.da, + PdfDictionaryProperties.parent, + ); if (defaultAppearance != null && defaultAppearance is PdfString) { color = _getForeColor(defaultAppearance.value); } @@ -863,15 +952,17 @@ class PdfFieldHelper { defaultAppearance.fontName = name; defaultAppearance.fontSize = height; defaultAppearance.foreColor = value; - widget[PdfDictionaryProperties.da] = - PdfString(defaultAppearance.getString()); + widget[PdfDictionaryProperties.da] = PdfString( + defaultAppearance.getString(), + ); } else if (font != null) { final PdfDefaultAppearance defaultAppearance = PdfDefaultAppearance(); defaultAppearance.fontName = font!.name; defaultAppearance.fontSize = font!.size; defaultAppearance.foreColor = value; - widget[PdfDictionaryProperties.da] = - PdfString(defaultAppearance.getString()); + widget[PdfDictionaryProperties.da] = PdfString( + defaultAppearance.getString(), + ); } PdfFormHelper.getHelper(field.form!).setAppearanceDictionary = true; } else { @@ -883,9 +974,10 @@ class PdfFieldHelper { } /// Gets or sets the width of the border. - int get borderWidth => isLoadedField - ? _obtainBorderWidth() - : widget!.widgetBorder!.width.toInt(); + int get borderWidth => + isLoadedField + ? _obtainBorderWidth() + : widget!.widgetBorder!.width.toInt(); set borderWidth(int value) { if (widget!.widgetBorder!.width != value) { widget!.widgetBorder!.width = value.toDouble(); @@ -893,9 +985,9 @@ class PdfFieldHelper { _assignBorderWidth(value); } else { value == 0 - ? WidgetAnnotationHelper.getHelper(widget!) - .widgetAppearance! - .borderColor = PdfColor(255, 255, 255) + ? WidgetAnnotationHelper.getHelper( + widget!, + ).widgetAppearance!.borderColor = PdfColor(255, 255, 255) : _createBorderPen(); } } @@ -904,9 +996,10 @@ class PdfFieldHelper { /// Gets or sets the highlighting mode. PdfHighlightMode get highlightMode => isLoadedField ? _obtainHighlightMode() : widget!.highlightMode!; - set highlightMode(PdfHighlightMode value) => isLoadedField - ? _assignHighlightMode(value) - : widget!.highlightMode = value; + set highlightMode(PdfHighlightMode value) => + isLoadedField + ? _assignHighlightMode(value) + : widget!.highlightMode = value; /// Gets or sets the border style. PdfBorderStyle get borderStyle => @@ -928,8 +1021,9 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfBorderStyle style = PdfBorderStyle.solid; if (widget.containsKey(PdfDictionaryProperties.bs)) { - final PdfDictionary bs = crossTable! - .getObject(widget[PdfDictionaryProperties.bs])! as PdfDictionary; + final PdfDictionary bs = + crossTable!.getObject(widget[PdfDictionaryProperties.bs])! + as PdfDictionary; style = _createBorderStyle(bs); } return style; @@ -938,8 +1032,9 @@ class PdfFieldHelper { PdfBorderStyle _createBorderStyle(PdfDictionary bs) { PdfBorderStyle style = PdfBorderStyle.solid; if (bs.containsKey(PdfDictionaryProperties.s)) { - final IPdfPrimitive? name = - crossTable!.getObject(bs[PdfDictionaryProperties.s]); + final IPdfPrimitive? name = crossTable!.getObject( + bs[PdfDictionaryProperties.s], + ); if (name != null && name is PdfName) { switch (name.name!.toLowerCase()) { case 'd': @@ -971,10 +1066,12 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); if (widget.containsKey(PdfDictionaryProperties.da) || dictionary!.containsKey(PdfDictionaryProperties.da)) { - IPdfPrimitive? defaultAppearance = - crossTable!.getObject(widget[PdfDictionaryProperties.da]); - defaultAppearance ??= - crossTable!.getObject(dictionary![PdfDictionaryProperties.da]); + IPdfPrimitive? defaultAppearance = crossTable!.getObject( + widget[PdfDictionaryProperties.da], + ); + defaultAppearance ??= crossTable!.getObject( + dictionary![PdfDictionaryProperties.da], + ); String? fontName; if (defaultAppearance != null && defaultAppearance is PdfString) { final Map value = _getFont(defaultAppearance.value!); @@ -983,9 +1080,9 @@ class PdfFieldHelper { fontName = value['fontName'] as String?; if (!isCorrectFont! && fontName != null) { widget.setProperty( - PdfDictionaryProperties.da, - PdfString( - defaultAppearance.value!.replaceAll(fontName, '/Helv'))); + PdfDictionaryProperties.da, + PdfString(defaultAppearance.value!.replaceAll(fontName, '/Helv')), + ); } } } @@ -1006,21 +1103,26 @@ class PdfFieldHelper { defaultAppearance.fontSize = _internalFont!.size; defaultAppearance.foreColor = foreColor; final IPdfPrimitive? fontDictionary = PdfCrossTable.dereference( - PdfFormHelper.getHelper(form!) - .resources[PdfDictionaryProperties.font]); + PdfFormHelper.getHelper(form!).resources[PdfDictionaryProperties + .font], + ); if (fontDictionary != null && fontDictionary is PdfDictionary && !fontDictionary.containsKey(defaultAppearance.fontName)) { final IPdfWrapper fontWrapper = _internalFont!; final PdfDictionary? fontElement = IPdfWrapper.getElement(fontWrapper) as PdfDictionary?; - fontDictionary.items![PdfName(defaultAppearance.fontName)] = - PdfReferenceHolder(fontElement); + fontDictionary.items![PdfName( + defaultAppearance.fontName, + )] = PdfReferenceHolder(fontElement); } - final PdfDictionary widget = - getWidgetAnnotation(dictionary!, crossTable); - widget[PdfDictionaryProperties.da] = - PdfString(defaultAppearance.getString()); + final PdfDictionary widget = getWidgetAnnotation( + dictionary!, + crossTable, + ); + widget[PdfDictionaryProperties.da] = PdfString( + defaultAppearance.getString(), + ); } else { _defineDefaultAppearance(); } @@ -1038,7 +1140,9 @@ class PdfFieldHelper { } else if (widget!.textAlignment != value) { widget!.textAlignment = value; format = PdfStringFormat( - alignment: value, lineAlignment: PdfVerticalAlignment.middle); + alignment: value, + lineAlignment: PdfVerticalAlignment.middle, + ); } } @@ -1106,8 +1210,9 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfColor c = PdfColor.empty; if (widget.containsKey(PdfDictionaryProperties.mk)) { - final IPdfPrimitive? bs = - crossTable!.getObject(widget[PdfDictionaryProperties.mk]); + final IPdfPrimitive? bs = crossTable!.getObject( + widget[PdfDictionaryProperties.mk], + ); if (bs is PdfDictionary) { IPdfPrimitive? array; if (bs.containsKey(PdfDictionaryProperties.bg)) { @@ -1170,7 +1275,8 @@ class PdfFieldHelper { int flagValue = isLoadedField ? this.flagValue : 0; // ignore: avoid_function_literals_in_foreach_calls value.forEach( - (FieldFlags element) => flagValue |= _getFieldFlagsValue(element)); + (FieldFlags element) => flagValue |= _getFieldFlagsValue(element), + ); flagValues = flagValue; dictionary!.setNumber(PdfDictionaryProperties.fieldFlags, flagValues); } @@ -1183,25 +1289,33 @@ class PdfFieldHelper { /// internal method int getFlagValue() { final IPdfPrimitive? number = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.fieldFlags, true); + dictionary!, + crossTable, + PdfDictionaryProperties.fieldFlags, + true, + ); return number != null && number is PdfNumber ? number.value!.toInt() : 0; } void _defineDefaultAppearance() { if (field.form != null && _internalFont != null) { if (isLoadedField) { - final PdfDictionary widget = - getWidgetAnnotation(dictionary!, crossTable); - final PdfName name = - PdfFormHelper.getHelper(form!).resources.getName(font!); + final PdfDictionary widget = getWidgetAnnotation( + dictionary!, + crossTable, + ); + final PdfName name = PdfFormHelper.getHelper( + form!, + ).resources.getName(font!); PdfFormHelper.getHelper(form!).resources.add(_internalFont, name); PdfFormHelper.getHelper(form!).needAppearances = true; final PdfDefaultAppearance defaultAppearance = PdfDefaultAppearance(); defaultAppearance.fontName = name.name; defaultAppearance.fontSize = _internalFont!.size; defaultAppearance.foreColor = foreColor; - widget[PdfDictionaryProperties.da] = - PdfString(defaultAppearance.getString()); + widget[PdfDictionaryProperties.da] = PdfString( + defaultAppearance.getString(), + ); if (field is PdfRadioButtonListField) { final PdfRadioButtonListField radioButtonListField = field as PdfRadioButtonListField; @@ -1209,18 +1323,20 @@ class PdfFieldHelper { final PdfRadioButtonListItem item = radioButtonListField.items[i]; if (PdfFieldHelper.getHelper(item).font != null) { PdfFormHelper.getHelper(field.form!).resources.add( - PdfFieldHelper.getHelper(radioButtonListField.items[i]).font, - PdfName(WidgetAnnotationHelper.getHelper( - PdfFieldHelper.getHelper(item).widget!) - .pdfDefaultAppearance! - .fontName)); + PdfFieldHelper.getHelper(radioButtonListField.items[i]).font, + PdfName( + WidgetAnnotationHelper.getHelper( + PdfFieldHelper.getHelper(item).widget!, + ).pdfDefaultAppearance!.fontName, + ), + ); } } } } else { - final PdfName name = PdfFormHelper.getHelper(field.form!) - .resources - .getName(_internalFont!); + final PdfName name = PdfFormHelper.getHelper( + field.form!, + ).resources.getName(_internalFont!); widget!.defaultAppearance.fontName = name.name; widget!.defaultAppearance.fontSize = _internalFont!.size; } @@ -1266,14 +1382,18 @@ class PdfFieldHelper { /// Gets the widget annotation. PdfDictionary getWidgetAnnotation( - PdfDictionary dictionary, PdfCrossTable? crossTable) { + PdfDictionary dictionary, + PdfCrossTable? crossTable, + ) { PdfDictionary? dic; if (dictionary.containsKey(PdfDictionaryProperties.kids)) { - final IPdfPrimitive? array = - crossTable!.getObject(dictionary[PdfDictionaryProperties.kids]); + final IPdfPrimitive? array = crossTable!.getObject( + dictionary[PdfDictionaryProperties.kids], + ); if (array is PdfArray && array.count > 0) { - final IPdfPrimitive reference = - crossTable.getReference(array[defaultIndex]); + final IPdfPrimitive reference = crossTable.getReference( + array[defaultIndex], + ); if (reference is PdfReference) { dic = crossTable.getObject(reference) as PdfDictionary?; } @@ -1288,19 +1408,22 @@ class PdfFieldHelper { if ((font is PdfStandardFont || font is PdfCjkStandardFont) && page != null && PdfPageHelper.getHelper(page!).document != null && - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!) - .conformanceLevel != + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page!).document!, + ).conformanceLevel != PdfConformanceLevel.none) { throw ArgumentError( - 'All the fonts must be embedded in ${PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!).conformanceLevel} document.'); + 'All the fonts must be embedded in ${PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!).conformanceLevel} document.', + ); } else if (font is PdfTrueTypeFont && PdfPageHelper.getHelper(page!).document != null && - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!) - .conformanceLevel == + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page!).document!, + ).conformanceLevel == PdfConformanceLevel.a1b) { - PdfTrueTypeFontHelper.getHelper(font! as PdfTrueTypeFont) - .fontInternal - .initializeCidSet(); + PdfTrueTypeFontHelper.getHelper( + font! as PdfTrueTypeFont, + ).fontInternal.initializeCidSet(); } } } @@ -1317,8 +1440,9 @@ class PdfFieldHelper { double height = fontNameDic['height'] as double; PdfFont font = PdfStandardFont(PdfFontFamily.helvetica, height); IPdfPrimitive? fontDictionary = crossTable!.getObject( - PdfFormHelper.getHelper(field.form!) - .resources[PdfDictionaryProperties.font]); + PdfFormHelper.getHelper(field.form!).resources[PdfDictionaryProperties + .font], + ); if (height == 0) { if (font is PdfStandardFont) { height = getFontHeight(font.fontFamily); @@ -1336,17 +1460,23 @@ class PdfFieldHelper { if (fontDictionary != null && fontDictionary is PdfDictionary && fontDictionary.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName fontSubtype = crossTable! - .getObject(fontDictionary[PdfDictionaryProperties.subtype])! - as PdfName; + final PdfName fontSubtype = + crossTable!.getObject( + fontDictionary[PdfDictionaryProperties.subtype], + )! + as PdfName; if (fontSubtype.name == PdfDictionaryProperties.type1) { - final PdfName baseFont = crossTable! - .getObject(fontDictionary[PdfDictionaryProperties.baseFont])! - as PdfName; - final List fontStyle = - _getFontStyle(PdfName.decodeName(baseFont.name)!); - final dynamic fontFamilyDic = - _getFontFamily(PdfName.decodeName(baseFont.name)!); + final PdfName baseFont = + crossTable!.getObject( + fontDictionary[PdfDictionaryProperties.baseFont], + )! + as PdfName; + final List fontStyle = _getFontStyle( + PdfName.decodeName(baseFont.name)!, + ); + final dynamic fontFamilyDic = _getFontFamily( + PdfName.decodeName(baseFont.name)!, + ); final PdfFontFamily? fontFamily = fontFamilyDic['fontFamily'] as PdfFontFamily?; final String? standardName = fontFamilyDic['standardName'] as String?; @@ -1371,15 +1501,17 @@ class PdfFieldHelper { final PdfReferenceHolder kids = kidsArray[i]! as PdfReferenceHolder; final IPdfPrimitive? dictionary = kids.object; - appearanceDictionary = dictionary != null && - dictionary is PdfDictionary && - dictionary - .containsKey(PdfDictionaryProperties.ap) && - dictionary[PdfDictionaryProperties.ap] - is PdfDictionary - ? dictionary[PdfDictionaryProperties.ap] - as PdfDictionary? - : null; + appearanceDictionary = + dictionary != null && + dictionary is PdfDictionary && + dictionary.containsKey( + PdfDictionaryProperties.ap, + ) && + dictionary[PdfDictionaryProperties.ap] + is PdfDictionary + ? dictionary[PdfDictionaryProperties.ap] + as PdfDictionary? + : null; break; } } @@ -1388,12 +1520,14 @@ class PdfFieldHelper { if (appearanceDictionary != null && appearanceDictionary.containsKey(PdfDictionaryProperties.n)) { final IPdfPrimitive? dic = PdfCrossTable.dereference( - appearanceDictionary[PdfDictionaryProperties.n]); + appearanceDictionary[PdfDictionaryProperties.n], + ); if (dic != null && dic is PdfStream) { final PdfStream stream = dic; stream.decompress(); - final dynamic fontNameDict = - _fontName(utf8.decode(stream.dataStream!.toList())); + final dynamic fontNameDict = _fontName( + utf8.decode(stream.dataStream!.toList()), + ); height = fontNameDict['height'] as double; } } @@ -1404,45 +1538,66 @@ class PdfFieldHelper { font = PdfStandardFont.prototype(stdf, height); } if (fontStyle != [PdfFontStyle.regular]) { - font = PdfStandardFont(PdfFontFamily.helvetica, height, - multiStyle: fontStyle); + font = PdfStandardFont( + PdfFontFamily.helvetica, + height, + multiStyle: fontStyle, + ); } if (standardName != getEnumName(fontFamily)) { font = _updateFontEncoding(font, fontDictionary); } - PdfFontHelper.getHelper(font).metrics = - _createFont(fontDictionary, height, baseFont); + PdfFontHelper.getHelper(font).metrics = _createFont( + fontDictionary, + height, + baseFont, + ); PdfFontHelper.getHelper(font).fontInternals = fontDictionary; } } else if (fontSubtype.name == 'TrueType') { - final PdfName baseFont = crossTable! - .getObject(fontDictionary[PdfDictionaryProperties.baseFont])! - as PdfName; + final PdfName baseFont = + crossTable!.getObject( + fontDictionary[PdfDictionaryProperties.baseFont], + )! + as PdfName; final List fontStyle = _getFontStyle(baseFont.name!); font = PdfStandardFont.prototype( - PdfStandardFont(PdfFontFamily.helvetica, 8), height, - multiStyle: fontStyle); + PdfStandardFont(PdfFontFamily.helvetica, 8), + height, + multiStyle: fontStyle, + ); font = _createFontFromFontStream( - font, fontDictionary, height, fontStyle); + font, + fontDictionary, + height, + fontStyle, + ); final IPdfPrimitive? tempName = fontDictionary[PdfDictionaryProperties.name]; if (tempName != null && tempName is PdfName) { if (font is PdfStandardFont && font.name != tempName.name) { final PdfFontHelper fontHelper = PdfFontHelper.getHelper(font); final WidthTable? widthTable = fontHelper.metrics!.widthTable; - fontHelper.metrics = - _createFont(fontDictionary, height, baseFont); + fontHelper.metrics = _createFont( + fontDictionary, + height, + baseFont, + ); fontHelper.metrics!.widthTable = widthTable; } } } else if (fontSubtype.name == PdfDictionaryProperties.type0) { - final IPdfPrimitive? baseFont = crossTable! - .getObject(fontDictionary[PdfDictionaryProperties.baseFont]); + final IPdfPrimitive? baseFont = crossTable!.getObject( + fontDictionary[PdfDictionaryProperties.baseFont], + ); if (baseFont != null && baseFont is PdfName && _isCjkFont(baseFont.name)) { - font = PdfCjkStandardFont(_getCjkFontFamily(baseFont.name)!, height, - multiStyle: _getFontStyle(baseFont.name!)); + font = PdfCjkStandardFont( + _getCjkFontFamily(baseFont.name)!, + height, + multiStyle: _getFontStyle(baseFont.name!), + ); } else { IPdfPrimitive? descendantFontsArray; IPdfPrimitive? descendantFontsDic; @@ -1450,13 +1605,15 @@ class PdfFieldHelper { IPdfPrimitive? fontDescriptorDic; IPdfPrimitive? fontName; descendantFontsArray = crossTable!.getObject( - fontDictionary[PdfDictionaryProperties.descendantFonts]); + fontDictionary[PdfDictionaryProperties.descendantFonts], + ); if (descendantFontsArray != null && descendantFontsArray is PdfArray && descendantFontsArray.count > 0) { - descendantFontsDic = descendantFontsArray[0] is PdfDictionary - ? descendantFontsArray[0] - : (descendantFontsArray[0]! as PdfReferenceHolder).object; + descendantFontsDic = + descendantFontsArray[0] is PdfDictionary + ? descendantFontsArray[0] + : (descendantFontsArray[0]! as PdfReferenceHolder).object; } if (descendantFontsDic != null && descendantFontsDic is PdfDictionary) { @@ -1472,12 +1629,14 @@ class PdfFieldHelper { fontName = fontDescriptorDic[PdfDictionaryProperties.fontName]; } if (fontName != null && fontName is PdfName) { - String fontNameStr = - fontName.name!.substring(fontName.name!.indexOf('+') + 1); + String fontNameStr = fontName.name!.substring( + fontName.name!.indexOf('+') + 1, + ); final PdfFontMetrics fontMetrics = _createFont( - descendantFontsDic! as PdfDictionary, - height, - PdfName(fontNameStr)); + descendantFontsDic! as PdfDictionary, + height, + PdfName(fontNameStr), + ); if (fontNameStr.contains('PSMT')) { fontNameStr = fontNameStr.replaceAll('PSMT', ''); } @@ -1504,28 +1663,36 @@ class PdfFieldHelper { return { 'font': font, 'isCorrectFont': isCorrectFont, - 'FontName': name + 'FontName': name, }; } - PdfFont _createFontFromFontStream(PdfFont font, PdfDictionary fontDictionary, - double height, List fontStyle) { + PdfFont _createFontFromFontStream( + PdfFont font, + PdfDictionary fontDictionary, + double height, + List fontStyle, + ) { if (fontDictionary.containsKey(PdfDictionaryProperties.fontDescriptor)) { IPdfPrimitive? fontDescriptor = PdfCrossTable.dereference( - fontDictionary[PdfDictionaryProperties.fontDescriptor]); + fontDictionary[PdfDictionaryProperties.fontDescriptor], + ); if (fontDescriptor == null && fontDescriptor is PdfDictionary && fontDictionary.containsKey(PdfDictionaryProperties.descendantFonts)) { final IPdfPrimitive? descendFonts = PdfCrossTable.dereference( - fontDictionary[PdfDictionaryProperties.descendantFonts]); + fontDictionary[PdfDictionaryProperties.descendantFonts], + ); if (descendFonts != null && descendFonts is PdfArray) { - final IPdfPrimitive? descendDict = - PdfCrossTable.dereference(descendFonts[0]); + final IPdfPrimitive? descendDict = PdfCrossTable.dereference( + descendFonts[0], + ); if (descendDict != null && descendDict is PdfDictionary && descendDict.containsKey(PdfDictionaryProperties.fontDescriptor)) { fontDescriptor = PdfCrossTable.dereference( - descendDict[PdfDictionaryProperties.fontDescriptor]); + descendDict[PdfDictionaryProperties.fontDescriptor], + ); } } } @@ -1533,7 +1700,8 @@ class PdfFieldHelper { if (fontDescriptor != null && fontDescriptor is PdfDictionary) { if (fontDescriptor.containsKey(PdfDictionaryProperties.fontFile2)) { fontFile = PdfCrossTable.dereference( - fontDescriptor[PdfDictionaryProperties.fontFile2]); + fontDescriptor[PdfDictionaryProperties.fontFile2], + ); } if (fontDescriptor.containsKey('FontFile3')) { fontFile = PdfCrossTable.dereference(fontDescriptor['FontFile3']); @@ -1545,8 +1713,11 @@ class PdfFieldHelper { try { fontFile.position = 0; if (fontFile.dataStream != null) { - font = PdfTrueTypeFont(fontFile.dataStream!, height, - multiStyle: fontStyle); + font = PdfTrueTypeFont( + fontFile.dataStream!, + height, + multiStyle: fontStyle, + ); } } catch (e) { return font; @@ -1557,7 +1728,10 @@ class PdfFieldHelper { } PdfFontMetrics _createFont( - PdfDictionary fontDictionary, double? height, PdfName baseFont) { + PdfDictionary fontDictionary, + double? height, + PdfName baseFont, + ) { final PdfFontMetrics fontMetrics = PdfFontMetrics(); if (fontDictionary.containsKey(PdfDictionaryProperties.fontDescriptor)) { IPdfPrimitive? createFontDictionary; @@ -1574,11 +1748,13 @@ class PdfFieldHelper { createFontDictionary is PdfDictionary) { fontMetrics.ascent = (createFontDictionary[PdfDictionaryProperties.ascent]! as PdfNumber) - .value! as double; + .value! + as double; fontMetrics.descent = (createFontDictionary[PdfDictionaryProperties.descent]! - as PdfNumber) - .value! as double; + as PdfNumber) + .value! + as double; fontMetrics.size = height!; fontMetrics.height = fontMetrics.ascent - fontMetrics.descent; fontMetrics.postScriptName = baseFont.name; @@ -1588,8 +1764,9 @@ class PdfFieldHelper { if (fontDictionary.containsKey(PdfDictionaryProperties.widths)) { if (fontDictionary[PdfDictionaryProperties.widths] is PdfReferenceHolder) { - final PdfReferenceHolder tableReference = - PdfReferenceHolder(fontDictionary[PdfDictionaryProperties.widths]); + final PdfReferenceHolder tableReference = PdfReferenceHolder( + fontDictionary[PdfDictionaryProperties.widths], + ); final PdfReferenceHolder tableArray = tableReference.object! as PdfReferenceHolder; array = tableArray.object as PdfArray?; @@ -1615,56 +1792,92 @@ class PdfFieldHelper { PdfFont? font; switch (name) { case 'CoBO': //"Courier-BoldOblique" - font = PdfStandardFont(PdfFontFamily.courier, height, - multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic]); + font = PdfStandardFont( + PdfFontFamily.courier, + height, + multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic], + ); break; case 'CoBo': //"Courier-Bold" - font = PdfStandardFont(PdfFontFamily.courier, height, - style: PdfFontStyle.bold); + font = PdfStandardFont( + PdfFontFamily.courier, + height, + style: PdfFontStyle.bold, + ); break; case 'CoOb': //"Courier-Oblique" - font = PdfStandardFont(PdfFontFamily.courier, height, - style: PdfFontStyle.italic); + font = PdfStandardFont( + PdfFontFamily.courier, + height, + style: PdfFontStyle.italic, + ); break; case 'Courier': case 'Cour': //"Courier" - font = PdfStandardFont(PdfFontFamily.courier, height, - style: PdfFontStyle.regular); + font = PdfStandardFont( + PdfFontFamily.courier, + height, + style: PdfFontStyle.regular, + ); break; case 'HeBO': //"Helvetica-BoldOblique" - font = PdfStandardFont(PdfFontFamily.helvetica, height, - multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic]); + font = PdfStandardFont( + PdfFontFamily.helvetica, + height, + multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic], + ); break; case 'HeBo': //"Helvetica-Bold" - font = PdfStandardFont(PdfFontFamily.helvetica, height, - style: PdfFontStyle.bold); + font = PdfStandardFont( + PdfFontFamily.helvetica, + height, + style: PdfFontStyle.bold, + ); break; case 'HeOb': //"Helvetica-Oblique" - font = PdfStandardFont(PdfFontFamily.helvetica, height, - style: PdfFontStyle.italic); + font = PdfStandardFont( + PdfFontFamily.helvetica, + height, + style: PdfFontStyle.italic, + ); break; case 'Helv': //"Helvetica" - font = PdfStandardFont(PdfFontFamily.helvetica, height, - style: PdfFontStyle.regular); + font = PdfStandardFont( + PdfFontFamily.helvetica, + height, + style: PdfFontStyle.regular, + ); break; case 'Symb': // "Symbol" font = PdfStandardFont(PdfFontFamily.symbol, height); break; case 'TiBI': // "Times-BoldItalic" - font = PdfStandardFont(PdfFontFamily.timesRoman, height, - multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic]); + font = PdfStandardFont( + PdfFontFamily.timesRoman, + height, + multiStyle: [PdfFontStyle.bold, PdfFontStyle.italic], + ); break; case 'TiBo': // "Times-Bold" - font = PdfStandardFont(PdfFontFamily.timesRoman, height, - style: PdfFontStyle.bold); + font = PdfStandardFont( + PdfFontFamily.timesRoman, + height, + style: PdfFontStyle.bold, + ); break; case 'TiIt': // "Times-Italic" - font = PdfStandardFont(PdfFontFamily.timesRoman, height, - style: PdfFontStyle.italic); + font = PdfStandardFont( + PdfFontFamily.timesRoman, + height, + style: PdfFontStyle.italic, + ); break; case 'TiRo': // "Times-Roman" - font = PdfStandardFont(PdfFontFamily.timesRoman, height, - style: PdfFontStyle.regular); + font = PdfStandardFont( + PdfFontFamily.timesRoman, + height, + style: PdfFontStyle.regular, + ); break; case 'ZaDb': // "ZapfDingbats" font = PdfStandardFont(PdfFontFamily.zapfDingbats, height); @@ -1696,22 +1909,22 @@ class PdfFieldHelper { colour = PdfColorHelper.fromGray(_parseFloatColour(operands.last!)); } else if (token == 'rg') { colour = PdfColor( - (_parseFloatColour(operands.elementAt(operands.length - 3)!) * - 255) - .toInt() - .toUnsigned(8), - (_parseFloatColour(operands.elementAt(operands.length - 2)!) * - 255) - .toInt() - .toUnsigned(8), - (_parseFloatColour(operands.last!) * 255).toInt().toUnsigned(8)); + (_parseFloatColour(operands.elementAt(operands.length - 3)!) * 255) + .toInt() + .toUnsigned(8), + (_parseFloatColour(operands.elementAt(operands.length - 2)!) * 255) + .toInt() + .toUnsigned(8), + (_parseFloatColour(operands.last!) * 255).toInt().toUnsigned(8), + ); operands.clear(); } else if (token == 'k') { colour = PdfColor.fromCMYK( - _parseFloatColour(operands.elementAt(operands.length - 4)!), - _parseFloatColour(operands.elementAt(operands.length - 3)!), - _parseFloatColour(operands.elementAt(operands.length - 2)!), - _parseFloatColour(operands.last!)); + _parseFloatColour(operands.elementAt(operands.length - 4)!), + _parseFloatColour(operands.elementAt(operands.length - 3)!), + _parseFloatColour(operands.elementAt(operands.length - 2)!), + _parseFloatColour(operands.last!), + ); operands.clear(); } else { operands.add(token); @@ -1775,7 +1988,7 @@ class PdfFieldHelper { 'HYSMyeongJo-Medium', 'MSung-Light', 'MHei-Medium', - 'HYGoThic-Medium' + 'HYGoThic-Medium', ]; for (int i = 0; i < 7; i++) { if (fontName!.contains(fontString[i])) { @@ -1793,7 +2006,7 @@ class PdfFieldHelper { 'HYSMyeongJo-Medium', 'MSung-Light', 'MHei-Medium', - 'HYGoThic-Medium' + 'HYGoThic-Medium', ]; String? value; for (int i = 0; i < 7; i++) { @@ -1898,7 +2111,7 @@ class PdfFieldHelper { 'Courier', 'TimesRoman', 'Symbol', - 'ZapfDingbats' + 'ZapfDingbats', ]; if (standardName != null && fontFamilyList.contains(standardName)) { fontFamily = PdfFontFamily.values[fontFamilyList.indexOf(standardName)]; @@ -1906,15 +2119,16 @@ class PdfFieldHelper { } return { 'fontFamily': fontFamily, - 'standardName': standardName + 'standardName': standardName, }; } PdfFont _updateFontEncoding(PdfFont font, PdfDictionary fontDictionary) { final PdfDictionary? fontInternalDictionary = PdfFontHelper.getHelper(font).fontInternals as PdfDictionary?; - if (fontDictionary.items! - .containsKey(PdfName(PdfDictionaryProperties.encoding))) { + if (fontDictionary.items!.containsKey( + PdfName(PdfDictionaryProperties.encoding), + )) { final PdfName encodingName = PdfName(PdfDictionaryProperties.encoding); final IPdfPrimitive? encodingReferenceHolder = fontDictionary.items![PdfName(PdfDictionaryProperties.encoding)]; @@ -1922,10 +2136,12 @@ class PdfFieldHelper { encodingReferenceHolder is PdfReferenceHolder) { final IPdfPrimitive? dictionary = encodingReferenceHolder.object; if (dictionary != null && dictionary is PdfDictionary) { - if (fontInternalDictionary!.items! - .containsKey(PdfName(PdfDictionaryProperties.encoding))) { - fontInternalDictionary.items! - .remove(PdfName(PdfDictionaryProperties.encoding)); + if (fontInternalDictionary!.items!.containsKey( + PdfName(PdfDictionaryProperties.encoding), + )) { + fontInternalDictionary.items!.remove( + PdfName(PdfDictionaryProperties.encoding), + ); } fontInternalDictionary.items![encodingName] = dictionary; } @@ -1933,10 +2149,12 @@ class PdfFieldHelper { final IPdfPrimitive? encodingDictionary = fontDictionary.items![PdfName(PdfDictionaryProperties.encoding)]; if (encodingDictionary != null && encodingDictionary is PdfDictionary) { - if (fontInternalDictionary!.items! - .containsKey(PdfName(PdfDictionaryProperties.encoding))) { - fontInternalDictionary.items! - .remove(PdfName(PdfDictionaryProperties.encoding)); + if (fontInternalDictionary!.items!.containsKey( + PdfName(PdfDictionaryProperties.encoding), + )) { + fontInternalDictionary.items!.remove( + PdfName(PdfDictionaryProperties.encoding), + ); } fontInternalDictionary.items![encodingName] = encodingDictionary; } @@ -1947,12 +2165,16 @@ class PdfFieldHelper { /// internal method void setFittingFontSize( - GraphicsProperties gp, PaintParams prms, String text) { + GraphicsProperties gp, + PaintParams prms, + String text, + ) { double fontSize = 0; - final double width = prms.style == PdfBorderStyle.beveled || - prms.style == PdfBorderStyle.inset - ? gp.bounds!.width - 8 * prms.borderWidth! - : gp.bounds!.width - 4 * prms.borderWidth!; + final double width = + prms.style == PdfBorderStyle.beveled || + prms.style == PdfBorderStyle.inset + ? gp.bounds!.width - 8 * prms.borderWidth! + : gp.bounds!.width - 4 * prms.borderWidth!; final double height = gp.bounds!.height - 2 * gp.borderWidth!; const double minimumFontSize = 0.248; if (text.endsWith(' ')) { @@ -1966,8 +2188,11 @@ class PdfFieldHelper { do { fontSize = fontSize - 0.001; PdfFontHelper.getHelper(gp.font!).setSize(fontSize); - final double textWidth = - PdfFontHelper.getLineWidth(gp.font!, text, gp.stringFormat); + final double textWidth = PdfFontHelper.getLineWidth( + gp.font!, + text, + gp.stringFormat, + ); if (fontSize < minimumFontSize) { PdfFontHelper.getHelper(gp.font!).setSize(minimumFontSize); break; @@ -2005,11 +2230,15 @@ class PdfFieldHelper { /// internal method void drawStateItem( - PdfGraphics graphics, PdfCheckFieldState state, PdfCheckFieldBase? item, - [PdfFieldItem? fieldItem]) { - final GraphicsProperties gp = item != null - ? GraphicsProperties(item) - : GraphicsProperties.fromFieldItem(fieldItem!); + PdfGraphics graphics, + PdfCheckFieldState state, + PdfCheckFieldBase? item, [ + PdfFieldItem? fieldItem, + ]) { + final GraphicsProperties gp = + item != null + ? GraphicsProperties(item) + : GraphicsProperties.fromFieldItem(fieldItem!); if (!flattenField) { gp.bounds = Rect.fromLTWH(0, 0, gp.bounds!.width, gp.bounds!.height); } @@ -2018,41 +2247,45 @@ class PdfFieldHelper { } graphics.save(); final PaintParams prms = PaintParams( - bounds: gp.bounds, - backBrush: gp.backBrush, - foreBrush: gp.foreBrush, - borderPen: gp.borderPen, - style: gp.style, - borderWidth: gp.borderWidth, - shadowBrush: gp.shadowBrush); + bounds: gp.bounds, + backBrush: gp.backBrush, + foreBrush: gp.foreBrush, + borderPen: gp.borderPen, + style: gp.style, + borderWidth: gp.borderWidth, + shadowBrush: gp.shadowBrush, + ); if (fieldChanged == true) { _drawFields(graphics, gp, prms, state); } else { - PdfGraphicsHelper.getHelper(graphics) - .streamWriter! - .setTextRenderingMode(0); + PdfGraphicsHelper.getHelper( + graphics, + ).streamWriter!.setTextRenderingMode(0); final PdfTemplate? stateTemplate = _getStateTemplate( - state, - item != null - ? PdfFieldHelper.getHelper(item).dictionary! - : PdfFieldItemHelper.getHelper(fieldItem!).dictionary!); + state, + item != null + ? PdfFieldHelper.getHelper(item).dictionary! + : PdfFieldItemHelper.getHelper(fieldItem!).dictionary!, + ); if (stateTemplate != null) { - final Rect bounds = item == null && fieldItem == null - ? field.bounds - : item != null + final Rect bounds = + item == null && fieldItem == null + ? field.bounds + : item != null ? item.bounds : fieldItem!.bounds; bool encryptedContent = false; if (crossTable != null && crossTable!.document != null && - PdfDocumentHelper.getHelper(crossTable!.document!) - .isLoadedDocument) { + PdfDocumentHelper.getHelper( + crossTable!.document!, + ).isLoadedDocument) { final PdfDocument? loadedDocument = crossTable!.document; if (loadedDocument != null && PdfDocumentHelper.getHelper(loadedDocument).isEncrypted) { - if (PdfSecurityHelper.getHelper(loadedDocument.security) - .encryptor - .isEncrypt! && + if (PdfSecurityHelper.getHelper( + loadedDocument.security, + ).encryptor.isEncrypt! && loadedDocument.security.encryptionOptions == PdfEncryptionOptions.encryptAllContents) { encryptedContent = true; @@ -2067,12 +2300,14 @@ class PdfFieldHelper { field is PdfCheckBoxField) { gp.font = null; FieldPainter().drawCheckBox( - graphics, - prms, - PdfCheckFieldBaseHelper.getHelper(field as PdfCheckBoxField) - .styleToString((field as PdfCheckBoxField).style), - state, - gp.font); + graphics, + prms, + PdfCheckFieldBaseHelper.getHelper( + field as PdfCheckBoxField, + ).styleToString((field as PdfCheckBoxField).style), + state, + gp.font, + ); } else { graphics.drawPdfTemplate(stateTemplate, bounds.topLeft, bounds.size); } @@ -2084,18 +2319,23 @@ class PdfFieldHelper { } PdfTemplate? _getStateTemplate( - PdfCheckFieldState state, PdfDictionary? itemDictionary) { + PdfCheckFieldState state, + PdfDictionary? itemDictionary, + ) { final PdfDictionary dic = itemDictionary ?? dictionary!; - final String? value = state == PdfCheckFieldState.checked - ? getItemValue(dic, crossTable) - : PdfDictionaryProperties.off; + final String? value = + state == PdfCheckFieldState.checked + ? getItemValue(dic, crossTable) + : PdfDictionaryProperties.off; PdfTemplate? template; if (dic.containsKey(PdfDictionaryProperties.ap)) { - final IPdfPrimitive? appearance = - PdfCrossTable.dereference(dic[PdfDictionaryProperties.ap]); + final IPdfPrimitive? appearance = PdfCrossTable.dereference( + dic[PdfDictionaryProperties.ap], + ); if (appearance != null && appearance is PdfDictionary) { - final IPdfPrimitive? norm = - PdfCrossTable.dereference(appearance[PdfDictionaryProperties.n]); + final IPdfPrimitive? norm = PdfCrossTable.dereference( + appearance[PdfDictionaryProperties.n], + ); if (value != null && value.isNotEmpty && norm != null && @@ -2116,34 +2356,45 @@ class PdfFieldHelper { return template; } - void _drawFields(PdfGraphics graphics, GraphicsProperties gp, - PaintParams params, PdfCheckFieldState state) { + void _drawFields( + PdfGraphics graphics, + GraphicsProperties gp, + PaintParams params, + PdfCheckFieldState state, + ) { if (gp.font!.size >= 0) { gp.font = null; } if (field is PdfCheckBoxField) { FieldPainter().drawCheckBox( - graphics, - params, - PdfCheckBoxFieldHelper.getHelper(field as PdfCheckBoxField) - .styleToString((field as PdfCheckBoxField).style), - state, - gp.font); + graphics, + params, + PdfCheckBoxFieldHelper.getHelper( + field as PdfCheckBoxField, + ).styleToString((field as PdfCheckBoxField).style), + state, + gp.font, + ); } else if (field is PdfRadioButtonListItem) { FieldPainter().drawRadioButton( - graphics, - params, - PdfRadioButtonListItemHelper.getHelper( - field as PdfRadioButtonListItem) - .styleToString((field as PdfRadioButtonListItem).style), - state); + graphics, + params, + PdfRadioButtonListItemHelper.getHelper( + field as PdfRadioButtonListItem, + ).styleToString((field as PdfRadioButtonListItem).style), + state, + ); } } /// internal method void importFieldValue(Object fieldValue) { final IPdfPrimitive? primitive = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.ft, true); + dictionary!, + crossTable, + PdfDictionaryProperties.ft, + true, + ); String? value; if (fieldValue is String) { value = fieldValue; @@ -2177,15 +2428,17 @@ class PdfFieldHelper { value.toUpperCase() == 'YES') { field1.isChecked = true; } else if (_containsExportValue( - value, field1._fieldHelper.dictionary!)) { + value, + field1._fieldHelper.dictionary!, + )) { field1.isChecked = true; } else if (field1.items != null && field1.items!.count > 0) { bool isChecked = false; for (int i = 0; i < field1.items!.count; i++) { if (_containsExportValue( - value, - PdfFieldItemHelper.getHelper(field1.items![i]) - .dictionary!)) { + value, + PdfFieldItemHelper.getHelper(field1.items![i]).dictionary!, + )) { (field1.items![i] as PdfCheckBoxItem).checked = true; isChecked = true; } @@ -2228,8 +2481,9 @@ class PdfFieldHelper { break; } if (widget[PdfDictionaryProperties.bs] is PdfReferenceHolder) { - final PdfDictionary widgetDict = crossTable! - .getObject(widget[PdfDictionaryProperties.bs])! as PdfDictionary; + final PdfDictionary widgetDict = + crossTable!.getObject(widget[PdfDictionaryProperties.bs])! + as PdfDictionary; if (widgetDict.containsKey(PdfDictionaryProperties.s)) { widgetDict[PdfDictionaryProperties.s] = PdfName(style); } else { @@ -2249,9 +2503,11 @@ class PdfFieldHelper { if (!widget.containsKey(PdfDictionaryProperties.bs)) { this.widget!.widgetBorder!.borderStyle = borderStyle!; widget.setProperty( - PdfDictionaryProperties.bs, - PdfAnnotationBorderHelper.getHelper(this.widget!.widgetBorder!) - .dictionary); + PdfDictionaryProperties.bs, + PdfAnnotationBorderHelper.getHelper( + this.widget!.widgetBorder!, + ).dictionary, + ); } } if (widget.containsKey(PdfDictionaryProperties.mk) && @@ -2265,12 +2521,14 @@ class PdfFieldHelper { .dictionary! .items! .forEach((PdfName? key, IPdfPrimitive? value) { - mkDict.setProperty(key, value); - }); + mkDict.setProperty(key, value); + }); } } else { - widget.setProperty(PdfDictionaryProperties.mk, - WidgetAnnotationHelper.getHelper(this.widget!).widgetAppearance); + widget.setProperty( + PdfDictionaryProperties.mk, + WidgetAnnotationHelper.getHelper(this.widget!).widgetAppearance, + ); } } @@ -2299,16 +2557,20 @@ class PdfFieldHelper { bool _containsExportValue(String value, PdfDictionary dictionary) { bool result = false; - final PdfDictionary widgetDictionary = - getWidgetAnnotation(dictionary, crossTable); + final PdfDictionary widgetDictionary = getWidgetAnnotation( + dictionary, + crossTable, + ); if (widgetDictionary.containsKey(PdfDictionaryProperties.ap)) { - final IPdfPrimitive? appearance = - crossTable!.getObject(widgetDictionary[PdfDictionaryProperties.ap]); + final IPdfPrimitive? appearance = crossTable!.getObject( + widgetDictionary[PdfDictionaryProperties.ap], + ); if (appearance != null && appearance is PdfDictionary && appearance.containsKey(PdfDictionaryProperties.n)) { - final IPdfPrimitive? normalTemplate = - PdfCrossTable.dereference(appearance[PdfDictionaryProperties.n]); + final IPdfPrimitive? normalTemplate = PdfCrossTable.dereference( + appearance[PdfDictionaryProperties.n], + ); if (normalTemplate != null && normalTemplate is PdfDictionary && normalTemplate.containsKey(value)) { @@ -2327,27 +2589,40 @@ class PdfFieldHelper { kids = crossTable!.getObject(dictionary![PdfDictionaryProperties.kids]); if (kids != null && kids is PdfArray) { for (int i = 0; i < kids.count; i++) { - flag = flag || + flag = + flag || (kids[i] is PdfField && (kids[i]! as PdfField)._fieldHelper.isLoadedField); } } } final IPdfPrimitive? name = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.ft, true); + dictionary!, + crossTable, + PdfDictionaryProperties.ft, + true, + ); String? strValue = ''; if (name != null && name is PdfName) { switch (name.name) { case 'Tx': final IPdfPrimitive? tempName = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true); + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ); if (tempName != null && tempName is PdfString) { strValue = tempName.value; } break; case 'Ch': final IPdfPrimitive? checkBoxPrimitive = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true); + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ); if (checkBoxPrimitive != null) { final String? value = getExportValue(field, checkBoxPrimitive); if (value != null && value.isNotEmpty) { @@ -2357,7 +2632,11 @@ class PdfFieldHelper { break; case 'Btn': final IPdfPrimitive? buttonFieldPrimitive = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true); + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ); if (buttonFieldPrimitive != null) { final String? value = getExportValue(field, buttonFieldPrimitive); if (value != null && value.isNotEmpty) { @@ -2372,8 +2651,10 @@ class PdfFieldHelper { if (field is PdfRadioButtonListField) { strValue = getAppearanceStateValue(field); } else { - final PdfDictionary holder = - getWidgetAnnotation(dictionary!, crossTable); + final PdfDictionary holder = getWidgetAnnotation( + dictionary!, + crossTable, + ); final IPdfPrimitive? holderName = holder[PdfDictionaryProperties.usageApplication]; if (holderName != null && holderName is PdfName) { @@ -2393,8 +2674,8 @@ class PdfFieldHelper { field is PdfField && (field as PdfField)._fieldHelper.isLoadedField && (field as PdfField).canExport) { - final Map out = - (field as PdfField)._fieldHelper.exportField(bytes, objectID); + final Map out = (field as PdfField)._fieldHelper + .exportField(bytes, objectID); bytes = out['bytes'] as List; objectID = out['objectID'] as int; } @@ -2405,7 +2686,8 @@ class PdfFieldHelper { ..encode = ForceEncoding.ascii; final StringBuffer buffer = StringBuffer(); buffer.write( - '$objID 0 obj<
/Kids ['); + '$objID 0 obj<
/Kids [', + ); for (int i = 0; i < kids.count; i++) { final PdfField field = kids[i]! as PdfField; @@ -2433,8 +2715,8 @@ class PdfFieldHelper { final PdfString stringFieldName = PdfString(this.name!) ..encode = ForceEncoding.ascii; final PdfString buildString = PdfString( - '$objID 0 obj<
/V $strValue >>endobj\n') - ..encode = ForceEncoding.ascii; + '$objID 0 obj<
/V $strValue >>endobj\n', + )..encode = ForceEncoding.ascii; bytes.addAll(buildString.value!.codeUnits); } } @@ -2484,7 +2766,9 @@ class PdfFieldHelper { /// internal method String getAppearanceStateValue(PdfField field) { final List holders = field._getWidgetAnnotations( - field._fieldHelper.dictionary!, field._fieldHelper.crossTable!); + field._fieldHelper.dictionary!, + field._fieldHelper.crossTable!, + ); String? value; for (int i = 0; i < holders.length; i++) { final IPdfPrimitive? pdfName = @@ -2504,7 +2788,11 @@ class PdfFieldHelper { /// internal method XmlElement? exportFieldForXml() { final IPdfPrimitive? name = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.ft, true); + dictionary!, + crossTable, + PdfDictionaryProperties.ft, + true, + ); String fieldName = this.name!.replaceAll(' ', '_x0020_'); fieldName = fieldName .replaceAll(r'\', '_x005C_') @@ -2522,7 +2810,11 @@ class PdfFieldHelper { switch (name.name) { case 'Tx': final IPdfPrimitive? str = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true); + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ); if ((str != null && str is PdfString) || exportEmptyField) { element = XmlElement(XmlName(fieldName)); if (str != null && str is PdfString) { @@ -2534,7 +2826,11 @@ class PdfFieldHelper { break; case 'Ch': final IPdfPrimitive? str = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true); + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ); if (str != null && str is PdfName) { final XmlElement element = XmlElement(XmlName(fieldName)); element.innerText = str.name!; @@ -2549,7 +2845,11 @@ class PdfFieldHelper { break; case 'Btn': final IPdfPrimitive? buttonFieldPrimitive = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.v, true); + dictionary!, + crossTable, + PdfDictionaryProperties.v, + true, + ); if (buttonFieldPrimitive != null) { final String? value = getExportValue(field, buttonFieldPrimitive); if ((value != null && value.isNotEmpty) || exportEmptyField) { @@ -2571,11 +2871,14 @@ class PdfFieldHelper { } else { if (field is PdfRadioButtonListField) { element = XmlElement(XmlName(fieldName)); - element.innerText = - getAppearanceStateValue(field as PdfRadioButtonListField); + element.innerText = getAppearanceStateValue( + field as PdfRadioButtonListField, + ); } else { - final PdfDictionary holder = - getWidgetAnnotation(dictionary!, crossTable); + final PdfDictionary holder = getWidgetAnnotation( + dictionary!, + crossTable, + ); if ((holder[PdfDictionaryProperties.usageApplication] is PdfName) || exportEmptyField) { @@ -2614,12 +2917,12 @@ class PdfFieldHelper { if (page != null && page!.formFieldsTabOrder == PdfFormFieldsTabOrder.manual) { page!.annotations.remove(widget!); - PdfAnnotationCollectionHelper.getHelper(page!.annotations) - .annotations - .insert(field.tabIndex, PdfReferenceHolder(widget)); - PdfObjectCollectionHelper.getHelper(page!.annotations) - .list - .insert(field.tabIndex, widget!); + PdfAnnotationCollectionHelper.getHelper( + page!.annotations, + ).annotations.insert(field.tabIndex, PdfReferenceHolder(widget)); + PdfObjectCollectionHelper.getHelper( + page!.annotations, + ).list.insert(field.tabIndex, widget!); } if (form != null && !PdfFormHelper.getHelper(form!).needAppearances! && @@ -2634,9 +2937,11 @@ class PdfFieldHelper { String? value = ''; PdfName? name; if (dictionary.containsKey(PdfDictionaryProperties.usageApplication)) { - name = crossTable! - .getObject(dictionary[PdfDictionaryProperties.usageApplication]) - as PdfName?; + name = + crossTable!.getObject( + dictionary[PdfDictionaryProperties.usageApplication], + ) + as PdfName?; if (name != null && name.name != PdfDictionaryProperties.off) { value = PdfName.decodeName(name.name); } @@ -2647,8 +2952,9 @@ class PdfFieldHelper { crossTable!.getObject(dictionary[PdfDictionaryProperties.ap])! as PdfDictionary; if (dic.containsKey(PdfDictionaryProperties.n)) { - final PdfReference reference = - crossTable.getReference(dic[PdfDictionaryProperties.n]); + final PdfReference reference = crossTable.getReference( + dic[PdfDictionaryProperties.n], + ); final PdfDictionary normalAppearance = crossTable.getObject(reference)! as PdfDictionary; final List list = []; @@ -2676,16 +2982,20 @@ class PdfFieldHelper { page.annotations.remove(widget!); } else { final PdfDictionary pageDic = PdfPageHelper.getHelper(page).dictionary!; - final PdfArray annots = pageDic - .containsKey(PdfDictionaryProperties.annots) - ? PdfPageHelper.getHelper(page) - .crossTable! - .getObject(pageDic[PdfDictionaryProperties.annots])! as PdfArray - : PdfArray(); - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(widget!); - helper.dictionary! - .setProperty(PdfDictionaryProperties.p, PdfReferenceHolder(page)); + final PdfArray annots = + pageDic.containsKey(PdfDictionaryProperties.annots) + ? PdfPageHelper.getHelper(page).crossTable!.getObject( + pageDic[PdfDictionaryProperties.annots], + )! + as PdfArray + : PdfArray(); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + widget!, + ); + helper.dictionary!.setProperty( + PdfDictionaryProperties.p, + PdfReferenceHolder(page), + ); for (int i = 0; i < annots.count; i++) { final IPdfPrimitive? obj = annots[i]; if (obj != null && @@ -2696,9 +3006,9 @@ class PdfFieldHelper { break; } } - PdfPageHelper.getHelper(page) - .dictionary! - .setProperty(PdfDictionaryProperties.annots, annots); + PdfPageHelper.getHelper( + page, + ).dictionary!.setProperty(PdfDictionaryProperties.annots, annots); } } } @@ -2707,8 +3017,9 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfPen? pen; if (widget.containsKey(PdfDictionaryProperties.mk)) { - final IPdfPrimitive? mk = - crossTable!.getObject(widget[PdfDictionaryProperties.mk]); + final IPdfPrimitive? mk = crossTable!.getObject( + widget[PdfDictionaryProperties.mk], + ); if (mk is PdfDictionary && mk.containsKey(PdfDictionaryProperties.bc)) { final PdfArray array = crossTable!.getObject(mk[PdfDictionaryProperties.bc])! as PdfArray; @@ -2735,8 +3046,9 @@ class PdfFieldHelper { if (borderStyle == PdfBorderStyle.dashed) { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); if (widget.containsKey(PdfDictionaryProperties.d)) { - final IPdfPrimitive? dashes = - crossTable!.getObject(widget[PdfDictionaryProperties.d]); + final IPdfPrimitive? dashes = crossTable!.getObject( + widget[PdfDictionaryProperties.d], + ); if (dashes != null && dashes is PdfArray) { if (dashes.count == 2) { array = [0, 0]; @@ -2765,9 +3077,11 @@ class PdfFieldHelper { void _assignHighlightMode(PdfHighlightMode? highlightMode) { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); widget.setName( - PdfName(PdfDictionaryProperties.h), - WidgetAnnotationHelper.getHelper(this.widget!) - .highlightModeToString(highlightMode)); + PdfName(PdfDictionaryProperties.h), + WidgetAnnotationHelper.getHelper( + this.widget!, + ).highlightModeToString(highlightMode), + ); changed = true; } @@ -2790,19 +3104,23 @@ class PdfFieldHelper { if (parentDictionary.containsKey(PdfDictionaryProperties.ft) && (parentDictionary[PdfDictionaryProperties.ft]! as PdfName).name == PdfDictionaryProperties.btn) { - final PdfDictionary widget = - getWidgetAnnotation(parentDictionary, crossTable); + final PdfDictionary widget = getWidgetAnnotation( + parentDictionary, + crossTable, + ); if (widget.containsKey(PdfDictionaryProperties.rect)) { - array = - crossTable!.getObject(widget[PdfDictionaryProperties.rect]); + array = crossTable!.getObject( + widget[PdfDictionaryProperties.rect], + ); } } } } if (array == null && dictionary!.containsKey(PdfDictionaryProperties.rect)) { - array = - crossTable!.getObject(dictionary![PdfDictionaryProperties.rect]); + array = crossTable!.getObject( + dictionary![PdfDictionaryProperties.rect], + ); } } Rect bounds; @@ -2824,7 +3142,11 @@ class PdfFieldHelper { } } bounds = Rect.fromLTWH( - bounds.left, y <= 0 ? bounds.top : y, bounds.width, bounds.height); + bounds.left, + y <= 0 ? bounds.top : y, + bounds.width, + bounds.height, + ); } else { bounds = Rect.zero; } @@ -2836,8 +3158,9 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); PdfColor c = PdfColor.empty; if (widget.containsKey(PdfDictionaryProperties.mk)) { - final IPdfPrimitive? bs = - crossTable!.getObject(widget[PdfDictionaryProperties.mk]); + final IPdfPrimitive? bs = crossTable!.getObject( + widget[PdfDictionaryProperties.mk], + ); if (bs is PdfDictionary) { IPdfPrimitive? array; if (bs.containsKey(PdfDictionaryProperties.bg)) { @@ -2863,35 +3186,42 @@ class PdfFieldHelper { } switch (dim) { case 1: - color = (colors[0] > 0.0) && (colors[0] <= 1.0) - ? PdfColorHelper.fromGray(colors[0]) - : PdfColorHelper.fromGray( - colors[0].toInt().toUnsigned(8).toDouble()); + color = + (colors[0] > 0.0) && (colors[0] <= 1.0) + ? PdfColorHelper.fromGray(colors[0]) + : PdfColorHelper.fromGray( + colors[0].toInt().toUnsigned(8).toDouble(), + ); break; case 3: - color = ((colors[0] > 0.0) && (colors[0] <= 1.0)) || - ((colors[1] > 0.0) && (colors[1] <= 1.0)) || - ((colors[2] > 0.0) && (colors[2] <= 1.0)) - ? PdfColor( - (colors[0] * 255).toInt().toUnsigned(8), - (colors[1] * 255).toInt().toUnsigned(8), - (colors[2] * 255).toInt().toUnsigned(8)) - : PdfColor( - colors[0].toInt().toUnsigned(8), - colors[1].toInt().toUnsigned(8), - colors[2].toInt().toUnsigned(8)); + color = + ((colors[0] > 0.0) && (colors[0] <= 1.0)) || + ((colors[1] > 0.0) && (colors[1] <= 1.0)) || + ((colors[2] > 0.0) && (colors[2] <= 1.0)) + ? PdfColor( + (colors[0] * 255).toInt().toUnsigned(8), + (colors[1] * 255).toInt().toUnsigned(8), + (colors[2] * 255).toInt().toUnsigned(8), + ) + : PdfColor( + colors[0].toInt().toUnsigned(8), + colors[1].toInt().toUnsigned(8), + colors[2].toInt().toUnsigned(8), + ); break; case 4: - color = ((colors[0] > 0.0) && (colors[0] <= 1.0)) || - ((colors[1] > 0.0) && (colors[1] <= 1.0)) || - ((colors[2] > 0.0) && (colors[2] <= 1.0)) || - ((colors[3] > 0.0) && (colors[3] <= 1.0)) - ? PdfColor.fromCMYK(colors[0], colors[1], colors[2], colors[3]) - : PdfColor.fromCMYK( - colors[0].toInt().toUnsigned(8).toDouble(), - colors[1].toInt().toUnsigned(8).toDouble(), - colors[2].toInt().toUnsigned(8).toDouble(), - colors[3].toInt().toUnsigned(8).toDouble()); + color = + ((colors[0] > 0.0) && (colors[0] <= 1.0)) || + ((colors[1] > 0.0) && (colors[1] <= 1.0)) || + ((colors[2] > 0.0) && (colors[2] <= 1.0)) || + ((colors[3] > 0.0) && (colors[3] <= 1.0)) + ? PdfColor.fromCMYK(colors[0], colors[1], colors[2], colors[3]) + : PdfColor.fromCMYK( + colors[0].toInt().toUnsigned(8).toDouble(), + colors[1].toInt().toUnsigned(8).toDouble(), + colors[2].toInt().toUnsigned(8).toDouble(), + colors[3].toInt().toUnsigned(8).toDouble(), + ); break; } return color; @@ -2901,10 +3231,13 @@ class PdfFieldHelper { void assignBackColor(PdfColor? value) { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); if (widget.containsKey(PdfDictionaryProperties.mk)) { - final PdfDictionary mk = (crossTable != null - ? crossTable!.getObject(widget[PdfDictionaryProperties.mk]) - : PdfCrossTable.dereference(widget[PdfDictionaryProperties.mk]))! - as PdfDictionary; + final PdfDictionary mk = + (crossTable != null + ? crossTable!.getObject(widget[PdfDictionaryProperties.mk]) + : PdfCrossTable.dereference( + widget[PdfDictionaryProperties.mk], + ))! + as PdfDictionary; final PdfArray array = PdfColorHelper.toArray(value!); mk[PdfDictionaryProperties.bg] = array; } else { @@ -2919,17 +3252,22 @@ class PdfFieldHelper { /// internal method void assignBorderColor(PdfColor borderColor) { if (dictionary!.containsKey(PdfDictionaryProperties.kids)) { - final IPdfPrimitive? kids = - crossTable!.getObject(dictionary![PdfDictionaryProperties.kids]); + final IPdfPrimitive? kids = crossTable!.getObject( + dictionary![PdfDictionaryProperties.kids], + ); if (kids != null && kids is PdfArray) { for (int i = 0; i < kids.count; i++) { final IPdfPrimitive? widget = PdfCrossTable.dereference(kids[i]); if (widget != null && widget is PdfDictionary) { if (widget.containsKey(PdfDictionaryProperties.mk)) { - final IPdfPrimitive? mk = crossTable != null - ? crossTable!.getObject(widget[PdfDictionaryProperties.mk]) - : PdfCrossTable.dereference( - widget[PdfDictionaryProperties.mk]); + final IPdfPrimitive? mk = + crossTable != null + ? crossTable!.getObject( + widget[PdfDictionaryProperties.mk], + ) + : PdfCrossTable.dereference( + widget[PdfDictionaryProperties.mk], + ); if (mk != null && mk is PdfDictionary) { final PdfArray array = PdfColorHelper.toArray(borderColor); if (PdfColorHelper.getHelper(borderColor).alpha == 0) { @@ -2954,9 +3292,10 @@ class PdfFieldHelper { } else { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); if (widget.containsKey(PdfDictionaryProperties.mk)) { - final IPdfPrimitive? mk = crossTable != null - ? crossTable!.getObject(widget[PdfDictionaryProperties.mk]) - : PdfCrossTable.dereference(widget[PdfDictionaryProperties.mk]); + final IPdfPrimitive? mk = + crossTable != null + ? crossTable!.getObject(widget[PdfDictionaryProperties.mk]) + : PdfCrossTable.dereference(widget[PdfDictionaryProperties.mk]); if (mk != null && mk is PdfDictionary) { final PdfArray array = PdfColorHelper.toArray(borderColor); if (PdfColorHelper.getHelper(borderColor).alpha == 0) { @@ -2981,14 +3320,17 @@ class PdfFieldHelper { int _obtainBorderWidth() { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); int width = 0; - final IPdfPrimitive? name = - crossTable!.getObject(widget[PdfDictionaryProperties.ft]); + final IPdfPrimitive? name = crossTable!.getObject( + widget[PdfDictionaryProperties.ft], + ); if (widget.containsKey(PdfDictionaryProperties.bs)) { width = 1; - final PdfDictionary bs = crossTable! - .getObject(widget[PdfDictionaryProperties.bs])! as PdfDictionary; - final IPdfPrimitive? number = - crossTable!.getObject(bs[PdfDictionaryProperties.w]); + final PdfDictionary bs = + crossTable!.getObject(widget[PdfDictionaryProperties.bs])! + as PdfDictionary; + final IPdfPrimitive? number = crossTable!.getObject( + bs[PdfDictionaryProperties.w], + ); if (number != null && number is PdfNumber) { width = number.value!.toInt(); } @@ -3002,8 +3344,9 @@ class PdfFieldHelper { final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); if (widget.containsKey(PdfDictionaryProperties.bs)) { if (widget[PdfDictionaryProperties.bs] is PdfReferenceHolder) { - final PdfDictionary widgetDict = crossTable! - .getObject(widget[PdfDictionaryProperties.bs])! as PdfDictionary; + final PdfDictionary widgetDict = + crossTable!.getObject(widget[PdfDictionaryProperties.bs])! + as PdfDictionary; if (widgetDict.containsKey(PdfDictionaryProperties.w)) { widgetDict[PdfDictionaryProperties.w] = PdfNumber(width); } else { @@ -3017,11 +3360,15 @@ class PdfFieldHelper { } else { if (!widget.containsKey(PdfDictionaryProperties.bs)) { widget.setProperty( - PdfDictionaryProperties.bs, - PdfAnnotationBorderHelper.getHelper(this.widget!.widgetBorder!) - .dictionary); - (widget[PdfDictionaryProperties.bs]! as PdfDictionary) - .setProperty(PdfDictionaryProperties.w, PdfNumber(width)); + PdfDictionaryProperties.bs, + PdfAnnotationBorderHelper.getHelper( + this.widget!.widgetBorder!, + ).dictionary, + ); + (widget[PdfDictionaryProperties.bs]! as PdfDictionary).setProperty( + PdfDictionaryProperties.w, + PdfNumber(width), + ); _createBorderPen(); } } @@ -3031,8 +3378,9 @@ class PdfFieldHelper { void _createBorderPen() { final double width = widget!.widgetBorder!.width; borderPen = PdfPen( - WidgetAnnotationHelper.getHelper(widget!).widgetAppearance!.borderColor, - width: width); + WidgetAnnotationHelper.getHelper(widget!).widgetAppearance!.borderColor, + width: width, + ); if (widget!.widgetBorder!.borderStyle == PdfBorderStyle.dashed || widget!.widgetBorder!.borderStyle == PdfBorderStyle.dot) { borderPen!.dashStyle = PdfDashStyle.custom; @@ -3063,7 +3411,9 @@ class PdfFieldHelper { dictionary![PdfDictionaryProperties.tu]; if (toolTip != null && toolTip is PdfString) { widgetAnnot.setString( - PdfDictionaryProperties.tu, toolTip.value); + PdfDictionaryProperties.tu, + toolTip.value, + ); } } } @@ -3073,8 +3423,12 @@ class PdfFieldHelper { } /// Gets the value. - static IPdfPrimitive? getValue(PdfDictionary dictionary, - PdfCrossTable? crossTable, String value, bool inheritable) { + static IPdfPrimitive? getValue( + PdfDictionary dictionary, + PdfCrossTable? crossTable, + String value, + bool inheritable, + ) { IPdfPrimitive? primitive; if (dictionary.containsKey(value)) { primitive = crossTable!.getObject(dictionary[value]); @@ -3086,17 +3440,21 @@ class PdfFieldHelper { /// Searches the in parents. static IPdfPrimitive? searchInParents( - PdfDictionary dictionary, PdfCrossTable? crossTable, String value) { + PdfDictionary dictionary, + PdfCrossTable? crossTable, + String value, + ) { IPdfPrimitive? primitive; PdfDictionary? dic = dictionary; while (primitive == null && dic != null) { if (dic.containsKey(value)) { primitive = crossTable!.getObject(dic[value]); } else { - dic = dic.containsKey(PdfDictionaryProperties.parent) - ? (crossTable!.getObject(dic[PdfDictionaryProperties.parent]) - as PdfDictionary?)! - : null; + dic = + dic.containsKey(PdfDictionaryProperties.parent) + ? (crossTable!.getObject(dic[PdfDictionaryProperties.parent]) + as PdfDictionary?)! + : null; } } return primitive; @@ -3119,8 +3477,11 @@ class GraphicsProperties { if ((!field._fieldHelper.isLoadedField) && field.page != null && field.page!.rotation != PdfPageRotateAngle.rotateAngle0) { - bounds = - _rotateTextbox(field.bounds, field.page!.size, field.page!.rotation); + bounds = _rotateTextbox( + field.bounds, + field.page!.size, + field.page!.rotation, + ); } } @@ -3139,8 +3500,11 @@ class GraphicsProperties { if ((!helper.field._fieldHelper.isLoadedField) && item.page != null && item.page!.rotation != PdfPageRotateAngle.rotateAngle0) { - bounds = - _rotateTextbox(item.bounds, item.page!.size, item.page!.rotation); + bounds = _rotateTextbox( + item.bounds, + item.page!.size, + item.page!.rotation, + ); } } @@ -3176,16 +3540,28 @@ class GraphicsProperties { Rect _rotateTextbox(Rect rect, Size? size, PdfPageRotateAngle angle) { Rect rectangle = rect; if (angle == PdfPageRotateAngle.rotateAngle180) { - rectangle = Rect.fromLTWH(size!.width - rect.left - rect.width, - size.height - rect.top - rect.height, rect.width, rect.height); + rectangle = Rect.fromLTWH( + size!.width - rect.left - rect.width, + size.height - rect.top - rect.height, + rect.width, + rect.height, + ); } if (angle == PdfPageRotateAngle.rotateAngle270) { - rectangle = Rect.fromLTWH(rect.top, size!.width - rect.left - rect.width, - rect.height, rect.width); + rectangle = Rect.fromLTWH( + rect.top, + size!.width - rect.left - rect.width, + rect.height, + rect.width, + ); } if (angle == PdfPageRotateAngle.rotateAngle90) { - rectangle = Rect.fromLTWH(size!.height - rect.top - rect.height, - rect.left, rect.height, rect.width); + rectangle = Rect.fromLTWH( + size!.height - rect.top - rect.height, + rect.left, + rect.height, + rect.width, + ); } return rectangle; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item.dart index 6bbfd82f1..a5bc5f56a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item.dart @@ -73,11 +73,13 @@ class PdfFieldItem { final PdfDocument? doc = crosstable.document; if (doc != null && PdfDocumentHelper.getHelper(doc).isLoadedDocument) { if (_helper.dictionary!.containsKey(pName)) { - final IPdfPrimitive? pageRef = crosstable - .getObject(_helper.dictionary![PdfDictionaryProperties.p]); + final IPdfPrimitive? pageRef = crosstable.getObject( + _helper.dictionary![PdfDictionaryProperties.p], + ); if (pageRef != null && pageRef is PdfDictionary) { - final PdfReference widgetReference = - crosstable.getReference(_helper.dictionary); + final PdfReference widgetReference = crosstable.getReference( + _helper.dictionary, + ); for (int i = 0; i < doc.pages.count; i++) { final PdfPage loadedPage = doc.pages[i]; final PdfArray? lAnnots = @@ -90,17 +92,20 @@ class PdfFieldItem { holder.reference != null && holder.reference!.objNum == widgetReference.objNum && holder.reference!.genNum == widgetReference.genNum) { - _page = PdfPageCollectionHelper.getHelper(doc.pages) - .getPage(pageRef); + _page = PdfPageCollectionHelper.getHelper( + doc.pages, + ).getPage(pageRef); helper.defaultIndex = backUpIndex; return _page; } } } - if (_helper.dictionary! - .containsKey(PdfDictionaryProperties.p)) { + if (_helper.dictionary!.containsKey( + PdfDictionaryProperties.p, + )) { final IPdfPrimitive? itemPageDict = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.p]); + _helper.dictionary![PdfDictionaryProperties.p], + ); final PdfDictionary pageDict = PdfPageHelper.getHelper(loadedPage).dictionary!; if (itemPageDict is PdfDictionary && @@ -115,8 +120,9 @@ class PdfFieldItem { _page = null; } } else { - final PdfReference widgetReference = - crosstable.getReference(_helper.dictionary); + final PdfReference widgetReference = crosstable.getReference( + _helper.dictionary, + ); for (int i = 0; i < doc.pages.count; i++) { final PdfPage loadedPage = doc.pages[i]; final PdfArray? lAnnots = @@ -251,18 +257,21 @@ class PdfFieldItemHelper { IPdfPrimitive? state; if (dictionary!.containsKey(PdfDictionaryProperties.usageApplication)) { state = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.usageApplication]); + dictionary![PdfDictionaryProperties.usageApplication], + ); } if (state == null) { final PdfFieldHelper fieldHelper = PdfFieldHelper.getHelper(field); final IPdfPrimitive? name = PdfFieldHelper.getValue( - fieldHelper.dictionary!, - fieldHelper.crossTable, - PdfDictionaryProperties.v, - false); + fieldHelper.dictionary!, + fieldHelper.crossTable, + PdfDictionaryProperties.v, + false, + ); if (name != null && name is PdfName) { - check = (name.name == - fieldHelper.getItemValue(dictionary!, fieldHelper.crossTable)); + check = + (name.name == + fieldHelper.getItemValue(dictionary!, fieldHelper.crossTable)); } } else if (state is PdfName) { check = (state.name != PdfDictionaryProperties.off); @@ -282,20 +291,25 @@ class PdfFieldItemHelper { val = PdfDictionaryProperties.yes; } fieldHelper.dictionary!.setName(PdfName(PdfDictionaryProperties.v), val); - dictionary! - .setProperty(PdfDictionaryProperties.usageApplication, PdfName(val)); + dictionary!.setProperty( + PdfDictionaryProperties.usageApplication, + PdfName(val), + ); dictionary!.setProperty(PdfDictionaryProperties.v, PdfName(val)); } else { IPdfPrimitive? v; if (fieldHelper.dictionary!.containsKey(PdfDictionaryProperties.v)) { v = PdfCrossTable.dereference( - fieldHelper.dictionary![PdfDictionaryProperties.v]); + fieldHelper.dictionary![PdfDictionaryProperties.v], + ); } if (v != null && v is PdfName && val == v.name) { fieldHelper.dictionary!.remove(PdfDictionaryProperties.v); } - dictionary!.setProperty(PdfDictionaryProperties.usageApplication, - PdfName(PdfDictionaryProperties.off)); + dictionary!.setProperty( + PdfDictionaryProperties.usageApplication, + PdfName(PdfDictionaryProperties.off), + ); } fieldHelper.changed = true; } @@ -312,8 +326,9 @@ class PdfFieldItemHelper { final PdfFieldItem item = items[i]; if (item != fieldItem && item is PdfCheckBoxItem) { final String? val = fieldHelper.getItemValue( - PdfFieldItemHelper.getHelper(item).dictionary!, - fieldHelper.crossTable); + PdfFieldItemHelper.getHelper(item).dictionary!, + fieldHelper.crossTable, + ); final bool v = val != null && val == value; if (v && check) { item.checked = true; @@ -378,7 +393,9 @@ class PdfCheckBoxItem extends PdfFieldItem { widgetDict[PdfDictionaryProperties.ca] = PdfString(style); } else { widgetDict.setProperty( - PdfDictionaryProperties.ca, PdfString(style)); + PdfDictionaryProperties.ca, + PdfString(style), + ); } } } else if (mk is PdfDictionary) { @@ -398,7 +415,10 @@ class PdfCheckBoxItemHelper { /// internal method static PdfCheckBoxItem getItem( - PdfField field, int index, PdfDictionary? dictionary) { + PdfField field, + int index, + PdfDictionary? dictionary, + ) { return PdfCheckBoxItem._(field, index, dictionary); } } @@ -413,7 +433,10 @@ class PdfTextBoxItem extends PdfFieldItem { class PdfTextBoxItemHelper { /// internal method static PdfTextBoxItem getItem( - PdfField field, int index, PdfDictionary? dictionary) { + PdfField field, + int index, + PdfDictionary? dictionary, + ) { return PdfTextBoxItem._(field, index, dictionary); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item_collection.dart index 34e16fa71..43e5678e6 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_item_collection.dart @@ -33,7 +33,7 @@ class PdfFieldItemCollection extends PdfObjectCollection { class PdfFieldItemCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfFieldItemCollectionHelper(this.fieldItemCollection, this.field) - : super(fieldItemCollection); + : super(fieldItemCollection); /// internal field late PdfFieldItemCollection fieldItemCollection; @@ -51,7 +51,8 @@ class PdfFieldItemCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfFieldItemCollectionHelper getHelper( - PdfFieldItemCollection collection) { + PdfFieldItemCollection collection, + ) { return collection._helper; } @@ -64,8 +65,8 @@ class PdfFieldItemCollectionHelper extends PdfObjectCollectionHelper { void clear() { PdfFieldHelper.getHelper(field).array.clear(); list.clear(); - PdfFieldHelper.getHelper(field) - .dictionary! - .remove(PdfDictionaryProperties.kids); + PdfFieldHelper.getHelper( + field, + ).dictionary!.remove(PdfDictionaryProperties.kids); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_painter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_painter.dart index 0f81f6eb2..9492eee52 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_painter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_field_painter.dart @@ -28,21 +28,44 @@ class FieldPainter { /// Draws a rectangular control. void drawRectangularControl(PdfGraphics graphics, PaintParams params) { graphics.drawRectangle( - bounds: params.bounds ?? Rect.zero, brush: params.backBrush); - drawBorder(graphics, params.bounds, params.borderPen, params.style, - params.borderWidth); + bounds: params.bounds ?? Rect.zero, + brush: params.backBrush, + ); + drawBorder( + graphics, + params.bounds, + params.borderPen, + params.style, + params.borderWidth, + ); switch (params.style) { case PdfBorderStyle.inset: drawLeftTopShadow( - graphics, params.bounds!, params.borderWidth!, PdfBrushes.gray); + graphics, + params.bounds!, + params.borderWidth!, + PdfBrushes.gray, + ); drawRightBottomShadow( - graphics, params.bounds!, params.borderWidth!, PdfBrushes.silver); + graphics, + params.bounds!, + params.borderWidth!, + PdfBrushes.silver, + ); break; case PdfBorderStyle.beveled: drawLeftTopShadow( - graphics, params.bounds!, params.borderWidth!, PdfBrushes.white); + graphics, + params.bounds!, + params.borderWidth!, + PdfBrushes.white, + ); drawRightBottomShadow( - graphics, params.bounds!, params.borderWidth!, params.shadowBrush); + graphics, + params.bounds!, + params.borderWidth!, + params.shadowBrush, + ); break; // ignore: no_default_cases default: @@ -51,16 +74,22 @@ class FieldPainter { } /// internal method - void drawCheckBox(PdfGraphics g, PaintParams paintParams, String checkSymbol, - PdfCheckFieldState state, - [PdfFont? font]) { + void drawCheckBox( + PdfGraphics g, + PaintParams paintParams, + String checkSymbol, + PdfCheckFieldState state, [ + PdfFont? font, + ]) { switch (state) { case PdfCheckFieldState.unchecked: case PdfCheckFieldState.checked: if (paintParams.borderPen != null && PdfColorHelper.getHelper(paintParams.borderPen!.color).alpha != 0) { g.drawRectangle( - brush: paintParams.backBrush, bounds: paintParams.bounds!); + brush: paintParams.backBrush, + bounds: paintParams.bounds!, + ); } break; @@ -72,37 +101,62 @@ class FieldPainter { PdfColorHelper.getHelper(paintParams.borderPen!.color).alpha != 0) { g.drawRectangle( - brush: paintParams.backBrush, bounds: paintParams.bounds!); + brush: paintParams.backBrush, + bounds: paintParams.bounds!, + ); } } else { if (paintParams.borderPen != null && PdfColorHelper.getHelper(paintParams.borderPen!.color).alpha != 0) { g.drawRectangle( - brush: paintParams.shadowBrush, bounds: paintParams.bounds!); + brush: paintParams.shadowBrush, + bounds: paintParams.bounds!, + ); } } break; } - drawBorder(g, paintParams.bounds, paintParams.borderPen, paintParams.style, - paintParams.borderWidth); + drawBorder( + g, + paintParams.bounds, + paintParams.borderPen, + paintParams.style, + paintParams.borderWidth, + ); if ((state == PdfCheckFieldState.pressedChecked) || (state == PdfCheckFieldState.pressedUnchecked)) { switch (paintParams.style) { case PdfBorderStyle.inset: - drawLeftTopShadow(g, paintParams.bounds!, paintParams.borderWidth!, - PdfBrushes.black); - drawRightBottomShadow(g, paintParams.bounds!, - paintParams.borderWidth!, PdfBrushes.white); + drawLeftTopShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.black, + ); + drawRightBottomShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.white, + ); break; case PdfBorderStyle.beveled: - drawLeftTopShadow(g, paintParams.bounds!, paintParams.borderWidth!, - paintParams.shadowBrush); - drawRightBottomShadow(g, paintParams.bounds!, - paintParams.borderWidth!, PdfBrushes.white); + drawLeftTopShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + paintParams.shadowBrush, + ); + drawRightBottomShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.white, + ); break; // ignore: no_default_cases default: @@ -110,17 +164,33 @@ class FieldPainter { } else { switch (paintParams.style) { case PdfBorderStyle.inset: - drawLeftTopShadow(g, paintParams.bounds!, paintParams.borderWidth!, - PdfBrushes.gray); - drawRightBottomShadow(g, paintParams.bounds!, - paintParams.borderWidth!, PdfBrushes.silver); + drawLeftTopShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.gray, + ); + drawRightBottomShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.silver, + ); break; case PdfBorderStyle.beveled: - drawLeftTopShadow(g, paintParams.bounds!, paintParams.borderWidth!, - PdfBrushes.white); - drawRightBottomShadow(g, paintParams.bounds!, - paintParams.borderWidth!, paintParams.shadowBrush); + drawLeftTopShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.white, + ); + drawRightBottomShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + paintParams.shadowBrush, + ); break; // ignore: no_default_cases default: @@ -134,21 +204,23 @@ class FieldPainter { if (font == null) { final bool extraBorder = paintParams.style == PdfBorderStyle.beveled || - paintParams.style == PdfBorderStyle.inset; + paintParams.style == PdfBorderStyle.inset; double borderWidth = paintParams.borderWidth!.toDouble(); if (extraBorder) { borderWidth *= 2; } - double xPosition = extraBorder - ? 2.0 * paintParams.borderWidth! - : paintParams.borderWidth!.toDouble(); + double xPosition = + extraBorder + ? 2.0 * paintParams.borderWidth! + : paintParams.borderWidth!.toDouble(); xPosition = max(xPosition, 1); final double xOffset = min(borderWidth, xPosition); - size = (paintParams.bounds!.width > paintParams.bounds!.height) - ? paintParams.bounds!.height - : paintParams.bounds!.width; + size = + (paintParams.bounds!.width > paintParams.bounds!.height) + ? paintParams.bounds!.height + : paintParams.bounds!.width; final double fontSize = size - 2 * xOffset; @@ -165,18 +237,24 @@ class FieldPainter { if (size < font.size) { ArgumentError.value( - 'Font size cannot be greater than CheckBox height'); + 'Font size cannot be greater than CheckBox height', + ); } - g.drawString(checkSymbol, font, - brush: paintParams.foreBrush, - bounds: Rect.fromLTWH( - paintParams.bounds!.left, - paintParams.bounds!.top - yOffset, - paintParams.bounds!.width, - paintParams.bounds!.height), - format: PdfStringFormat( - alignment: PdfTextAlignment.center, - lineAlignment: PdfVerticalAlignment.middle)); + g.drawString( + checkSymbol, + font, + brush: paintParams.foreBrush, + bounds: Rect.fromLTWH( + paintParams.bounds!.left, + paintParams.bounds!.top - yOffset, + paintParams.bounds!.width, + paintParams.bounds!.height, + ), + format: PdfStringFormat( + alignment: PdfTextAlignment.center, + lineAlignment: PdfVerticalAlignment.middle, + ), + ); break; // ignore: no_default_cases default: @@ -184,33 +262,46 @@ class FieldPainter { } /// Draws a border. - void drawBorder(PdfGraphics graphics, Rect? bounds, PdfPen? borderPen, - PdfBorderStyle? style, int? borderWidth) { + void drawBorder( + PdfGraphics graphics, + Rect? bounds, + PdfPen? borderPen, + PdfBorderStyle? style, + int? borderWidth, + ) { if (borderPen != null) { if (borderWidth! > 0 && !borderPen.color.isEmpty) { if (style == PdfBorderStyle.underline) { graphics.drawLine( - borderPen, - Offset( - bounds!.left, bounds.top + bounds.height - borderWidth / 2), - Offset(bounds.left + bounds.width, - bounds.top + bounds.height - borderWidth / 2)); + borderPen, + Offset(bounds!.left, bounds.top + bounds.height - borderWidth / 2), + Offset( + bounds.left + bounds.width, + bounds.top + bounds.height - borderWidth / 2, + ), + ); } else { graphics.drawRectangle( - pen: borderPen, - bounds: Rect.fromLTWH( - bounds!.left + borderWidth / 2, - bounds.top + borderWidth / 2, - bounds.width - borderWidth, - bounds.height - borderWidth)); + pen: borderPen, + bounds: Rect.fromLTWH( + bounds!.left + borderWidth / 2, + bounds.top + borderWidth / 2, + bounds.width - borderWidth, + bounds.height - borderWidth, + ), + ); } } } } /// internal method - void drawRadioButton(PdfGraphics? g, PaintParams paintParams, - String checkSymbol, PdfCheckFieldState state) { + void drawRadioButton( + PdfGraphics? g, + PaintParams paintParams, + String checkSymbol, + PdfCheckFieldState state, + ) { //if the symbol is not a circle type ("l") then we need to draw the checkbox appearance if (checkSymbol != 'l') { drawCheckBox(g!, paintParams, checkSymbol, state); @@ -232,25 +323,33 @@ class FieldPainter { break; } - drawRoundBorder(g, paintParams.bounds, paintParams.borderPen, - paintParams.borderWidth); + drawRoundBorder( + g, + paintParams.bounds, + paintParams.borderPen, + paintParams.borderWidth, + ); drawRoundShadow(g, paintParams, state); switch (state) { case PdfCheckFieldState.checked: case PdfCheckFieldState.pressedChecked: final Rect outward = Rect.fromLTWH( - paintParams.bounds!.left + paintParams.borderWidth! / 2.0, - paintParams.bounds!.top + paintParams.borderWidth! / 2.0, - paintParams.bounds!.width - paintParams.borderWidth!, - paintParams.bounds!.height - paintParams.borderWidth!); + paintParams.bounds!.left + paintParams.borderWidth! / 2.0, + paintParams.bounds!.top + paintParams.borderWidth! / 2.0, + paintParams.bounds!.width - paintParams.borderWidth!, + paintParams.bounds!.height - paintParams.borderWidth!, + ); Rect checkedBounds = outward; checkedBounds = Rect.fromLTWH( - checkedBounds.left + (outward.width / 4), - checkedBounds.top + (outward.width / 4), - checkedBounds.width - (outward.width / 2), - checkedBounds.height - (outward.width / 2)); - g.drawEllipse(checkedBounds, - brush: paintParams.foreBrush ?? PdfBrushes.black); + checkedBounds.left + (outward.width / 4), + checkedBounds.top + (outward.width / 4), + checkedBounds.width - (outward.width / 2), + checkedBounds.height - (outward.width / 2), + ); + g.drawEllipse( + checkedBounds, + brush: paintParams.foreBrush ?? PdfBrushes.black, + ); break; // ignore: no_default_cases default: @@ -261,107 +360,173 @@ class FieldPainter { /// Draws the left top shadow. void drawLeftTopShadow( - PdfGraphics graphics, Rect bounds, int width, PdfBrush? brush) { + PdfGraphics graphics, + Rect bounds, + int width, + PdfBrush? brush, + ) { final List points = [ Offset(bounds.left + width, bounds.top + width), Offset(bounds.left + width, bounds.bottom - width), Offset(bounds.left + 2 * width, bounds.bottom - 2 * width), Offset(bounds.left + 2 * width, bounds.top + 2 * width), Offset(bounds.right - 2 * width, bounds.top + 2 * width), - Offset(bounds.right - width, bounds.top + width) + Offset(bounds.right - width, bounds.top + width), ]; graphics.drawPath(PdfPath()..addPolygon(points), brush: brush); } /// Draws the right bottom shadow. void drawRightBottomShadow( - PdfGraphics graphics, Rect bounds, int width, PdfBrush? brush) { + PdfGraphics graphics, + Rect bounds, + int width, + PdfBrush? brush, + ) { final List points = [ Offset(bounds.left + width, bounds.bottom - width), Offset(bounds.left + 2 * width, bounds.bottom - 2 * width), Offset(bounds.right - 2 * width, bounds.bottom - 2 * width), Offset(bounds.right - 2 * width, bounds.top + 2 * width), Offset(bounds.left + bounds.width - width, bounds.top + width), - Offset(bounds.right - width, bounds.bottom - width) + Offset(bounds.right - width, bounds.bottom - width), ]; graphics.drawPath(PdfPath()..addPolygon(points), brush: brush); } /// internal method - void drawButton(PdfGraphics g, PaintParams paintParams, String text, - PdfFont font, PdfStringFormat? format) { + void drawButton( + PdfGraphics g, + PaintParams paintParams, + String text, + PdfFont font, + PdfStringFormat? format, + ) { drawRectangularControl(g, paintParams); final Rect? rectangle = paintParams.bounds; - g.drawString(text, font, - brush: paintParams.foreBrush, bounds: rectangle, format: format); + g.drawString( + text, + font, + brush: paintParams.foreBrush, + bounds: rectangle, + format: format, + ); } /// internal method - void drawPressedButton(PdfGraphics g, PaintParams paintParams, String text, - PdfFont font, PdfStringFormat? format) { + void drawPressedButton( + PdfGraphics g, + PaintParams paintParams, + String text, + PdfFont font, + PdfStringFormat? format, + ) { switch (paintParams.style) { case PdfBorderStyle.inset: g.drawRectangle( - brush: paintParams.shadowBrush, bounds: paintParams.bounds!); + brush: paintParams.shadowBrush, + bounds: paintParams.bounds!, + ); break; // ignore: no_default_cases default: g.drawRectangle( - brush: paintParams.backBrush, bounds: paintParams.bounds!); + brush: paintParams.backBrush, + bounds: paintParams.bounds!, + ); break; } - drawBorder(g, paintParams.bounds, paintParams.borderPen, paintParams.style, - paintParams.borderWidth); + drawBorder( + g, + paintParams.bounds, + paintParams.borderPen, + paintParams.style, + paintParams.borderWidth, + ); final Rect rectangle = Rect.fromLTWH( - paintParams.borderWidth!.toDouble(), - paintParams.borderWidth!.toDouble(), - paintParams.bounds!.size.width - paintParams.borderWidth!, - paintParams.bounds!.size.height - paintParams.borderWidth!); - g.drawString(text, font, - brush: paintParams.foreBrush, bounds: rectangle, format: format); + paintParams.borderWidth!.toDouble(), + paintParams.borderWidth!.toDouble(), + paintParams.bounds!.size.width - paintParams.borderWidth!, + paintParams.bounds!.size.height - paintParams.borderWidth!, + ); + g.drawString( + text, + font, + brush: paintParams.foreBrush, + bounds: rectangle, + format: format, + ); switch (paintParams.style) { case PdfBorderStyle.inset: drawLeftTopShadow( - g, paintParams.bounds!, paintParams.borderWidth!, PdfBrushes.gray); - drawRightBottomShadow(g, paintParams.bounds!, paintParams.borderWidth!, - PdfBrushes.silver); + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.gray, + ); + drawRightBottomShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.silver, + ); break; case PdfBorderStyle.beveled: - drawLeftTopShadow(g, paintParams.bounds!, paintParams.borderWidth!, - paintParams.shadowBrush); + drawLeftTopShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + paintParams.shadowBrush, + ); drawRightBottomShadow( - g, paintParams.bounds!, paintParams.borderWidth!, PdfBrushes.white); + g, + paintParams.bounds!, + paintParams.borderWidth!, + PdfBrushes.white, + ); break; // ignore: no_default_cases default: - drawLeftTopShadow(g, paintParams.bounds!, paintParams.borderWidth!, - paintParams.shadowBrush); + drawLeftTopShadow( + g, + paintParams.bounds!, + paintParams.borderWidth!, + paintParams.shadowBrush, + ); break; } } /// internal method void drawRoundBorder( - PdfGraphics? g, Rect? bounds, PdfPen? borderPen, int? borderWidth) { + PdfGraphics? g, + Rect? bounds, + PdfPen? borderPen, + int? borderWidth, + ) { Rect? outward = bounds; if (outward != Rect.zero) { outward = Rect.fromLTWH( - bounds!.left + borderWidth! / 2.0, - bounds.top + borderWidth / 2.0, - bounds.width - borderWidth, - bounds.height - borderWidth); + bounds!.left + borderWidth! / 2.0, + bounds.top + borderWidth / 2.0, + bounds.width - borderWidth, + bounds.height - borderWidth, + ); g!.drawEllipse(outward, pen: borderPen); } } /// internal method void drawRoundShadow( - PdfGraphics? g, PaintParams paintParams, PdfCheckFieldState state) { + PdfGraphics? g, + PaintParams paintParams, + PdfCheckFieldState state, + ) { final double borderWidth = paintParams.borderWidth!.toDouble(); final Rect rectangle = paintParams.bounds!; rectangle.inflate(-1.5 * borderWidth); @@ -376,8 +541,10 @@ class FieldPainter { case PdfCheckFieldState.pressedChecked: case PdfCheckFieldState.pressedUnchecked: leftTopPen = PdfPen(shadowColor, width: borderWidth); - rightBottomPen = - PdfPen(PdfColor(255, 255, 255), width: borderWidth); + rightBottomPen = PdfPen( + PdfColor(255, 255, 255), + width: borderWidth, + ); break; case PdfCheckFieldState.checked: @@ -398,10 +565,14 @@ class FieldPainter { case PdfCheckFieldState.checked: case PdfCheckFieldState.unchecked: - leftTopPen = - PdfPen(PdfColor(255, 128, 128, 128), width: borderWidth); - rightBottomPen = - PdfPen(PdfColor(255, 192, 192, 192), width: borderWidth); + leftTopPen = PdfPen( + PdfColor(255, 128, 128, 128), + width: borderWidth, + ); + rightBottomPen = PdfPen( + PdfColor(255, 192, 192, 192), + width: borderWidth, + ); break; } break; @@ -415,41 +586,59 @@ class FieldPainter { } /// Draws the combo box - void drawComboBox(PdfGraphics graphics, PaintParams paintParams, String? text, - PdfFont? font, PdfStringFormat? format) { + void drawComboBox( + PdfGraphics graphics, + PaintParams paintParams, + String? text, + PdfFont? font, + PdfStringFormat? format, + ) { drawRectangularControl(graphics, paintParams); final Rect? rectangle = paintParams.bounds; - graphics.drawString(text!, font!, - brush: paintParams.foreBrush, bounds: rectangle, format: format); + graphics.drawString( + text!, + font!, + brush: paintParams.foreBrush, + bounds: rectangle, + format: format, + ); } /// Draws the list box void drawListBox( - PdfGraphics graphics, - PaintParams params, - PdfListFieldItemCollection items, - List selectedItem, - PdfFont font, - PdfStringFormat? stringFormat) { + PdfGraphics graphics, + PaintParams params, + PdfListFieldItemCollection items, + List selectedItem, + PdfFont font, + PdfStringFormat? stringFormat, + ) { FieldPainter().drawRectangularControl(graphics, params); for (int index = 0; index < items.count; index++) { final PdfListFieldItem item = items[index]; final int borderWidth = params.borderWidth!; final double doubleBorderWidth = (2 * borderWidth).toDouble(); - final bool padding = params.style == PdfBorderStyle.inset || + final bool padding = + params.style == PdfBorderStyle.inset || params.style == PdfBorderStyle.beveled; - final Offset point = padding - ? Offset(2 * doubleBorderWidth, - (index + 2) * borderWidth + font.size * index) - : Offset( - doubleBorderWidth, (index + 1) * borderWidth + font.size * index); + final Offset point = + padding + ? Offset( + 2 * doubleBorderWidth, + (index + 2) * borderWidth + font.size * index, + ) + : Offset( + doubleBorderWidth, + (index + 1) * borderWidth + font.size * index, + ); PdfBrush? brush = params.foreBrush; double width = params.bounds!.width - doubleBorderWidth; final Rect rectangle = Rect.fromLTWH( - params.bounds!.left, - params.bounds!.top, - params.bounds!.width, - params.bounds!.height - (padding ? doubleBorderWidth : borderWidth)); + params.bounds!.left, + params.bounds!.top, + params.bounds!.width, + params.bounds!.height - (padding ? doubleBorderWidth : borderWidth), + ); graphics.setClip(bounds: rectangle, mode: PdfFillMode.winding); bool selected = false; for (final int selectedIndex in selectedItem) { @@ -465,66 +654,97 @@ class FieldPainter { } brush = PdfSolidBrush(PdfColor(51, 153, 255)); graphics.drawRectangle( - brush: brush, - bounds: Rect.fromLTWH(x, point.dy, width, font.height)); + brush: brush, + bounds: Rect.fromLTWH(x, point.dy, width, font.height), + ); brush = PdfSolidBrush(PdfColor(255, 255, 255)); } final String value = item.text; - final PdfRectangle itemTextBound = - PdfRectangle(point.dx, point.dy, width - point.dx, font.height); - PdfGraphicsHelper.getHelper(graphics).layoutString(value, font, - brush: brush ?? PdfSolidBrush(PdfColor(0, 0, 0)), - layoutRectangle: itemTextBound, - format: stringFormat); + final PdfRectangle itemTextBound = PdfRectangle( + point.dx, + point.dy, + width - point.dx, + font.height, + ); + PdfGraphicsHelper.getHelper(graphics).layoutString( + value, + font, + brush: brush ?? PdfSolidBrush(PdfColor(0, 0, 0)), + layoutRectangle: itemTextBound, + format: stringFormat, + ); } } /// Draws the text box - void drawTextBox(PdfGraphics graphics, PaintParams params, String text, - PdfFont font, PdfStringFormat format, bool insertSpaces, bool multiline) { + void drawTextBox( + PdfGraphics graphics, + PaintParams params, + String text, + PdfFont font, + PdfStringFormat format, + bool insertSpaces, + bool multiline, + ) { if (!insertSpaces) { FieldPainter().drawRectangularControl(graphics, params); } - final int multiplier = params.style == PdfBorderStyle.beveled || - params.style == PdfBorderStyle.inset - ? 2 - : 1; + final int multiplier = + params.style == PdfBorderStyle.beveled || + params.style == PdfBorderStyle.inset + ? 2 + : 1; Rect rectangle = Rect.fromLTWH( - params.bounds!.left + (2 * multiplier) * params.borderWidth!, - params.bounds!.top + (2 * multiplier) * params.borderWidth!, - params.bounds!.width - (4 * multiplier) * params.borderWidth!, - params.bounds!.height - (4 * multiplier) * params.borderWidth!); + params.bounds!.left + (2 * multiplier) * params.borderWidth!, + params.bounds!.top + (2 * multiplier) * params.borderWidth!, + params.bounds!.width - (4 * multiplier) * params.borderWidth!, + params.bounds!.height - (4 * multiplier) * params.borderWidth!, + ); // Calculate position of the text. if (multiline) { final double tempHeight = format.lineSpacing == 0 ? font.height : format.lineSpacing; final bool subScript = format.subSuperscript == PdfSubSuperscript.subscript; - final double ascent = - PdfFontHelper.getHelper(font).metrics!.getAscent(format); - final double descent = - PdfFontHelper.getHelper(font).metrics!.getDescent(format); - final double shift = subScript - ? tempHeight - (font.height + descent) - : tempHeight - ascent; + final double ascent = PdfFontHelper.getHelper( + font, + ).metrics!.getAscent(format); + final double descent = PdfFontHelper.getHelper( + font, + ).metrics!.getDescent(format); + final double shift = + subScript + ? tempHeight - (font.height + descent) + : tempHeight - ascent; if (rectangle.left == 0 && rectangle.top == 0) { - rectangle = Rect.fromLTWH(rectangle.left, -(rectangle.top - shift), - rectangle.width, rectangle.height); + rectangle = Rect.fromLTWH( + rectangle.left, + -(rectangle.top - shift), + rectangle.width, + rectangle.height, + ); } - graphics.drawString(text, font, - brush: params.foreBrush, - bounds: rectangle, - format: PdfStringFormat( - alignment: format.alignment, lineAlignment: format.lineAlignment) - ..lineLimit = false); + graphics.drawString( + text, + font, + brush: params.foreBrush, + bounds: rectangle, + format: PdfStringFormat( + alignment: format.alignment, + lineAlignment: format.lineAlignment, + )..lineLimit = false, + ); } else { - graphics.drawString(text, font, - brush: params.foreBrush, - bounds: rectangle, - format: PdfStringFormat( - alignment: format.alignment, - lineAlignment: PdfVerticalAlignment.middle) - ..lineLimit = false); + graphics.drawString( + text, + font, + brush: params.foreBrush, + bounds: rectangle, + format: PdfStringFormat( + alignment: format.alignment, + lineAlignment: PdfVerticalAlignment.middle, + )..lineLimit = false, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form.dart index e22a18e46..2e99b3d42 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form.dart @@ -39,34 +39,40 @@ class PdfForm implements IPdfWrapper { _helper = PdfFormHelper(this); _helper._fields = PdfFormFieldCollectionHelper.getCollection(); PdfFormFieldCollectionHelper.getHelper(_helper._fields!).form = this; - _helper.dictionary! - .setProperty(PdfDictionaryProperties.fields, _helper._fields); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.fields, + _helper._fields, + ); if (!_helper.isLoadedForm) { _helper.dictionary!.beginSave = _helper.beginSave; } _helper.setAppearanceDictionary = true; } - PdfForm._internal(PdfCrossTable? crossTable, - [PdfDictionary? formDictionary]) { + PdfForm._internal( + PdfCrossTable? crossTable, [ + PdfDictionary? formDictionary, + ]) { _helper = PdfFormHelper(this); _helper.isLoadedForm = true; _helper.crossTable = crossTable; _helper.dictionary!.setBoolean( - PdfDictionaryProperties.needAppearances, _helper.needAppearances); + PdfDictionaryProperties.needAppearances, + _helper.needAppearances, + ); PdfDocumentHelper.getHelper(_helper.crossTable!.document!) .catalog .beginSaveList ??= []; - PdfDocumentHelper.getHelper(_helper.crossTable!.document!) - .catalog - .beginSaveList! - .add(_helper.beginSave); + PdfDocumentHelper.getHelper( + _helper.crossTable!.document!, + ).catalog.beginSaveList!.add(_helper.beginSave); PdfDocumentHelper.getHelper(_helper.crossTable!.document!).catalog.modify(); - if (PdfDocumentHelper.getHelper(_helper.crossTable!.document!) - .catalog - .containsKey(PdfDictionaryProperties.perms)) { + if (PdfDocumentHelper.getHelper( + _helper.crossTable!.document!, + ).catalog.containsKey(PdfDictionaryProperties.perms)) { _checkPerms( - PdfDocumentHelper.getHelper(_helper.crossTable!.document!).catalog); + PdfDocumentHelper.getHelper(_helper.crossTable!.document!).catalog, + ); } if (formDictionary != null) { _initialize(formDictionary, crossTable!); @@ -127,15 +133,24 @@ class PdfForm implements IPdfWrapper { } /// Imports form value from base 64 string to the file with the specific [DataFormat]. - void importDataFromBase64String(String base64String, DataFormat dataFormat, - [bool continueImportOnError = false]) { - importData(base64.decode(base64String).toList(), dataFormat, - continueImportOnError); + void importDataFromBase64String( + String base64String, + DataFormat dataFormat, [ + bool continueImportOnError = false, + ]) { + importData( + base64.decode(base64String).toList(), + dataFormat, + continueImportOnError, + ); } /// Imports form value to the file with the specific [DataFormat]. - void importData(List inputBytes, DataFormat dataFormat, - [bool continueImportOnError = false]) { + void importData( + List inputBytes, + DataFormat dataFormat, [ + bool continueImportOnError = false, + ]) { if (dataFormat == DataFormat.fdf) { _importDataFDF(inputBytes, continueImportOnError); } else if (dataFormat == DataFormat.json) { @@ -170,8 +185,9 @@ class PdfForm implements IPdfWrapper { for (final XmlNode node in xmlDoc.rootElement.firstElementChild!.children) { if (node is XmlElement) { final String fieldName = node.attributes.first.value; - final int index = PdfFormFieldCollectionHelper.getHelper(fields) - .getFieldIndex(fieldName); + final int index = PdfFormFieldCollectionHelper.getHelper( + fields, + ).getFieldIndex(fieldName); if (index >= 0 && index < fields.count) { formField = fields[index]; String? fieldInnerValue; @@ -184,11 +200,13 @@ class PdfForm implements IPdfWrapper { fieldInnerValue = node.firstElementChild!.innerText; } if (fieldInnerValues.isNotEmpty) { - PdfFieldHelper.getHelper(formField) - .importFieldValue(fieldInnerValues); + PdfFieldHelper.getHelper( + formField, + ).importFieldValue(fieldInnerValues); } else if (fieldInnerValue != null) { - PdfFieldHelper.getHelper(formField) - .importFieldValue(fieldInnerValue); + PdfFieldHelper.getHelper( + formField, + ).importFieldValue(fieldInnerValue); } } } @@ -202,11 +220,14 @@ class PdfForm implements IPdfWrapper { //Get terminal fields. _createFields(); //Gets NeedAppearance - if (_helper.dictionary! - .containsKey(PdfDictionaryProperties.needAppearances)) { - final PdfBoolean needAppearance = crossTable.getObject( - _helper.dictionary![PdfDictionaryProperties.needAppearances])! - as PdfBoolean; + if (_helper.dictionary!.containsKey( + PdfDictionaryProperties.needAppearances, + )) { + final PdfBoolean needAppearance = + crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.needAppearances], + )! + as PdfBoolean; _helper.needAppearances = needAppearance.value; _helper.setAppearanceDictionary = true; } else { @@ -215,7 +236,8 @@ class PdfForm implements IPdfWrapper { //Gets resource dictionary if (_helper.dictionary!.containsKey(PdfDictionaryProperties.dr)) { final IPdfPrimitive? resourceDictionary = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.dr]); + _helper.dictionary![PdfDictionaryProperties.dr], + ); if (resourceDictionary != null && resourceDictionary is PdfDictionary) { _helper.resources = PdfResources(resourceDictionary); } @@ -226,8 +248,9 @@ class PdfForm implements IPdfWrapper { void _createFields() { PdfArray? fields; if (_helper.dictionary!.containsKey(PdfDictionaryProperties.fields)) { - final IPdfPrimitive? obj = _helper.crossTable! - .getObject(_helper.dictionary![PdfDictionaryProperties.fields]); + final IPdfPrimitive? obj = _helper.crossTable!.getObject( + _helper.dictionary![PdfDictionaryProperties.fields], + ); if (obj != null) { fields = obj as PdfArray; } @@ -236,24 +259,28 @@ class PdfForm implements IPdfWrapper { final Queue<_NodeInfo> nodes = Queue<_NodeInfo>(); while (true && fields != null) { for (; count < fields!.count; ++count) { - final IPdfPrimitive? fieldDictionary = - _helper.crossTable!.getObject(fields[count]); + final IPdfPrimitive? fieldDictionary = _helper.crossTable!.getObject( + fields[count], + ); PdfArray? fieldKids; if (fieldDictionary != null && fieldDictionary is PdfDictionary && fieldDictionary.containsKey(PdfDictionaryProperties.kids)) { - final IPdfPrimitive? fieldKid = _helper.crossTable! - .getObject(fieldDictionary[PdfDictionaryProperties.kids]); + final IPdfPrimitive? fieldKid = _helper.crossTable!.getObject( + fieldDictionary[PdfDictionaryProperties.kids], + ); if (fieldKid != null && fieldKid is PdfArray) { fieldKids = fieldKid; for (int i = 0; i < fieldKids.count; i++) { - final IPdfPrimitive? kidsDict = - PdfCrossTable.dereference(fieldKids[i]); + final IPdfPrimitive? kidsDict = PdfCrossTable.dereference( + fieldKids[i], + ); if (kidsDict != null && kidsDict is PdfDictionary && !kidsDict.containsKey(PdfDictionaryProperties.parent)) { - kidsDict[PdfDictionaryProperties.parent] = - PdfReferenceHolder(fieldDictionary); + kidsDict[PdfDictionaryProperties.parent] = PdfReferenceHolder( + fieldDictionary, + ); } } } @@ -265,8 +292,9 @@ class PdfForm implements IPdfWrapper { } } } else { - if (!(fieldDictionary! as PdfDictionary) - .containsKey(PdfDictionaryProperties.ft) || + if (!(fieldDictionary! as PdfDictionary).containsKey( + PdfDictionaryProperties.ft, + ) || _isNode(fieldKids)) { nodes.addFirst(_NodeInfo(fields, count)); _helper.formHasKids = true; @@ -294,8 +322,11 @@ class PdfForm implements IPdfWrapper { final PdfDictionary dictionary = _helper.crossTable!.getObject(kids[0])! as PdfDictionary; if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName name = _helper.crossTable! - .getObject(dictionary[PdfDictionaryProperties.subtype])! as PdfName; + final PdfName name = + _helper.crossTable!.getObject( + dictionary[PdfDictionaryProperties.subtype], + )! + as PdfName; if (name.name != PdfDictionaryProperties.widget) { isNode = true; } @@ -327,7 +358,8 @@ class PdfForm implements IPdfWrapper { token = reader.getNextToken(); if (token != null && !token.startsWith('FDF-')) { throw ArgumentError( - 'The source is not a valid FDF file because it does not start with"%FDF-"'); + 'The source is not a valid FDF file because it does not start with"%FDF-"', + ); } } final Map> table = >{}; @@ -347,8 +379,9 @@ class PdfForm implements IPdfWrapper { PdfField? field; table.forEach((String k, List v) { try { - final int index = - PdfFormFieldCollectionHelper.getHelper(fields).getFieldIndex(k); + final int index = PdfFormFieldCollectionHelper.getHelper( + fields, + ).getFieldIndex(k); if (index == -1) { throw ArgumentError('Incorrect field name.'); } @@ -385,7 +418,8 @@ class PdfForm implements IPdfWrapper { ..encode = ForceEncoding.ascii; final StringBuffer buffer = StringBuffer(); buffer.write( - '$count 0 obj< /Fields ['); + '$count 0 obj< /Fields [', + ); for (int i = 0; i < fields.count; i++) { final PdfField field = fields[i]; final PdfFieldHelper helper = PdfFieldHelper.getHelper(field); @@ -432,8 +466,12 @@ class PdfForm implements IPdfWrapper { return [fieldname, token]; } - void _getFieldValue(PdfReader reader, String? token, String fieldName, - Map> table) { + void _getFieldValue( + PdfReader reader, + String? token, + String fieldName, + Map> table, + ) { token = reader.getNextToken(); if (token != null && token.isNotEmpty) { if (token == '[') { @@ -441,8 +479,14 @@ class PdfForm implements IPdfWrapper { if (token != null && token.isNotEmpty) { final List fieldValues = []; while (token != ']') { - token = - _fieldValue(reader, token, true, table, fieldName, fieldValues); + token = _fieldValue( + reader, + token, + true, + table, + fieldName, + fieldValues, + ); } if (!table.containsKey(fieldName) && fieldValues.isNotEmpty) { table[fieldName] = fieldValues; @@ -455,12 +499,13 @@ class PdfForm implements IPdfWrapper { } String? _fieldValue( - PdfReader reader, - String? token, - bool isMultiSelect, - Map> table, - String fieldName, - List? fieldValues) { + PdfReader reader, + String? token, + bool isMultiSelect, + Map> table, + String fieldName, + List? fieldValues, + ) { if (token == '<') { token = reader.getNextToken(); if (token != null && token.isNotEmpty && token != '>') { @@ -540,16 +585,21 @@ class PdfForm implements IPdfWrapper { final PdfFieldHelper helper = PdfFieldHelper.getHelper(field); if (field.canExport) { helper.exportEmptyField = exportEmptyFields; - final IPdfPrimitive? name = PdfFieldHelper.getValue(helper.dictionary!, - helper.crossTable, PdfDictionaryProperties.ft, true); + final IPdfPrimitive? name = PdfFieldHelper.getValue( + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.ft, + true, + ); if (name != null && name is PdfName) { switch (name.name) { case 'Tx': final IPdfPrimitive? fieldValue = PdfFieldHelper.getValue( - helper.dictionary!, - helper.crossTable, - PdfDictionaryProperties.v, - true); + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (fieldValue is PdfString) { xfdf.setFields(field.name!, fieldValue.value!); } else if (exportEmptyFields) { @@ -559,10 +609,11 @@ class PdfForm implements IPdfWrapper { case 'Ch': if (field is PdfListBoxField) { final IPdfPrimitive? primitive = PdfFieldHelper.getValue( - helper.dictionary!, - helper.crossTable, - PdfDictionaryProperties.v, - true); + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (primitive is PdfArray) { xfdf.setFields(field.name!, primitive); } else if (primitive is PdfString) { @@ -572,18 +623,20 @@ class PdfForm implements IPdfWrapper { } } else { final IPdfPrimitive? listField = PdfFieldHelper.getValue( - helper.dictionary!, - helper.crossTable, - PdfDictionaryProperties.v, - true); + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (listField is PdfName) { xfdf.setFields(field.name!, listField.name!); } else { final IPdfPrimitive? comboValue = PdfFieldHelper.getValue( - helper.dictionary!, - helper.crossTable, - PdfDictionaryProperties.v, - true); + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (comboValue is PdfString) { xfdf.setFields(field.name!, comboValue.value!); } else if (exportEmptyFields) { @@ -594,11 +647,17 @@ class PdfForm implements IPdfWrapper { break; case 'Btn': final IPdfPrimitive? buttonFieldPrimitive = - PdfFieldHelper.getValue(helper.dictionary!, helper.crossTable, - PdfDictionaryProperties.v, true); + PdfFieldHelper.getValue( + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (buttonFieldPrimitive != null) { - final String? value = - helper.getExportValue(field, buttonFieldPrimitive); + final String? value = helper.getExportValue( + field, + buttonFieldPrimitive, + ); if (value != null && value.isNotEmpty) { xfdf.setFields(field.name!, value); } else if (field is PdfRadioButtonListField || @@ -612,7 +671,9 @@ class PdfForm implements IPdfWrapper { } else { if (field is PdfRadioButtonListField) { xfdf.setFields( - field.name!, helper.getAppearanceStateValue(field)); + field.name!, + helper.getAppearanceStateValue(field), + ); } else { final PdfDictionary holder = helper.getWidgetAnnotation( helper.dictionary!, @@ -656,8 +717,9 @@ class PdfForm implements IPdfWrapper { } } if (fieldKey != null && fieldValue != null) { - table[PdfFormHelper.decodeXMLConversion(fieldKey)] = - PdfFormHelper.decodeXMLConversion(fieldValue); + table[PdfFormHelper.decodeXMLConversion( + fieldKey, + )] = PdfFormHelper.decodeXMLConversion(fieldValue); fieldKey = fieldValue = null; } token = reader.getNextJsonToken(); @@ -665,8 +727,9 @@ class PdfForm implements IPdfWrapper { PdfField? field; table.forEach((String k, String v) { try { - final int index = - PdfFormFieldCollectionHelper.getHelper(fields).getFieldIndex(k); + final int index = PdfFormFieldCollectionHelper.getHelper( + fields, + ).getFieldIndex(k); if (index == -1) { throw ArgumentError('Incorrect field name.'); } @@ -689,16 +752,21 @@ class PdfForm implements IPdfWrapper { final PdfField field = fields[i]; final PdfFieldHelper helper = PdfFieldHelper.getHelper(field); if (helper.isLoadedField && field.canExport) { - final IPdfPrimitive? name = PdfFieldHelper.getValue(helper.dictionary!, - helper.crossTable, PdfDictionaryProperties.ft, true); + final IPdfPrimitive? name = PdfFieldHelper.getValue( + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.ft, + true, + ); if (name != null && name is PdfName) { switch (name.name) { case 'Tx': final IPdfPrimitive? textField = PdfFieldHelper.getValue( - helper.dictionary!, - helper.crossTable, - PdfDictionaryProperties.v, - true); + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (textField != null && textField is PdfString) { table[field.name!] = textField.value!; } @@ -706,10 +774,11 @@ class PdfForm implements IPdfWrapper { case 'Ch': if (field is PdfListBoxField || field is PdfComboBoxField) { final IPdfPrimitive? listValue = PdfFieldHelper.getValue( - helper.dictionary!, - helper.crossTable, - PdfDictionaryProperties.v, - true); + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (listValue != null) { final String? value = helper.getExportValue(field, listValue); if (value != null && value.isNotEmpty) { @@ -720,11 +789,17 @@ class PdfForm implements IPdfWrapper { break; case 'Btn': final IPdfPrimitive? buttonFieldPrimitive = - PdfFieldHelper.getValue(helper.dictionary!, helper.crossTable, - PdfDictionaryProperties.v, true); + PdfFieldHelper.getValue( + helper.dictionary!, + helper.crossTable, + PdfDictionaryProperties.v, + true, + ); if (buttonFieldPrimitive != null) { - final String? value = - helper.getExportValue(field, buttonFieldPrimitive); + final String? value = helper.getExportValue( + field, + buttonFieldPrimitive, + ); if (value != null && value.isNotEmpty) { table[field.name!] = value; } else if (field is PdfRadioButtonListField || @@ -736,7 +811,9 @@ class PdfForm implements IPdfWrapper { table[field.name!] = helper.getAppearanceStateValue(field); } else { final PdfDictionary holder = helper.getWidgetAnnotation( - helper.dictionary!, helper.crossTable); + helper.dictionary!, + helper.crossTable, + ); final IPdfPrimitive? holderName = holder[PdfDictionaryProperties.usageApplication]; if (holderName != null && holderName is PdfName) { @@ -803,14 +880,16 @@ class PdfForm implements IPdfWrapper { .replaceAll('_x007D_', '}') .replaceAll('_x0024_', r'$'); try { - final int index = PdfFormFieldCollectionHelper.getHelper(fields) - .getFieldIndex(fieldName); + final int index = PdfFormFieldCollectionHelper.getHelper( + fields, + ).getFieldIndex(fieldName); if (index == -1) { throw ArgumentError('Incorrect field name.'); } final PdfField formField = fields[index]; - PdfFieldHelper.getHelper(formField) - .importFieldValue(childNode.innerText); + PdfFieldHelper.getHelper( + formField, + ).importFieldValue(childNode.innerText); } catch (e) { if (!continueImportOnError) { rethrow; @@ -904,8 +983,10 @@ class PdfFormHelper { } /// internal method - static PdfForm internal(PdfCrossTable? crossTable, - [PdfDictionary? formDictionary]) { + static PdfForm internal( + PdfCrossTable? crossTable, [ + PdfDictionary? formDictionary, + ]) { return PdfForm._internal(crossTable, formDictionary); } @@ -938,7 +1019,9 @@ class PdfFormHelper { _checkFlatten(); if (form.fields.count > 0 && setAppearanceDictionary) { dictionary!.setBoolean( - PdfDictionaryProperties.needAppearances, needAppearances); + PdfDictionaryProperties.needAppearances, + needAppearances, + ); } } else { int i = 0; @@ -952,7 +1035,9 @@ class PdfFormHelper { } if (dictionary!.containsKey(PdfDictionaryProperties.needAppearances)) { dictionary!.setBoolean( - PdfDictionaryProperties.needAppearances, needAppearances); + PdfDictionaryProperties.needAppearances, + needAppearances, + ); } } while (i < form.fields.count) { @@ -966,8 +1051,9 @@ class PdfFormHelper { bool isSigned = false; if (field is PdfSignatureField) { if (dic.containsKey(PdfDictionaryProperties.v)) { - final IPdfPrimitive? value = - PdfCrossTable.dereference(dic[PdfDictionaryProperties.v]); + final IPdfPrimitive? value = PdfCrossTable.dereference( + dic[PdfDictionaryProperties.v], + ); if (value != null) { isSigned = true; } @@ -986,16 +1072,20 @@ class PdfFormHelper { } int fieldFlag = 0; if (dic.containsKey(PdfDictionaryProperties.f)) { - final IPdfPrimitive? flag = - PdfCrossTable.dereference(dic[PdfDictionaryProperties.f]); + final IPdfPrimitive? flag = PdfCrossTable.dereference( + dic[PdfDictionaryProperties.f], + ); if (flag != null && flag is PdfNumber) { fieldFlag = flag.value!.toInt(); } } PdfArray? kids; if (helper.dictionary!.containsKey(PdfDictionaryProperties.kids)) { - kids = PdfCrossTable.dereference( - helper.dictionary![PdfDictionaryProperties.kids]) as PdfArray?; + kids = + PdfCrossTable.dereference( + helper.dictionary![PdfDictionaryProperties.kids], + ) + as PdfArray?; } if (helper.flattenField && fieldFlag != 6) { if (field.page != null || kids != null) { @@ -1020,24 +1110,28 @@ class PdfFormHelper { } else { helper.save(); } - if (_fields?.count == 0) { - final int? index = crossTable!.items!.lookFor(helper.dictionary!); - dictionary?.clear(); - (sender as PdfDictionary).remove(PdfDictionaryProperties.acroForm); - if (index != -1) { - crossTable!.items!.objectCollection!.removeAt(index!); - } + } + if (_fields?.count == 0) { + final int? index = crossTable!.items!.lookFor(helper.dictionary!); + dictionary?.clear(); + (sender as PdfDictionary).remove(PdfDictionaryProperties.acroForm); + if (index != -1) { + crossTable!.items!.objectCollection!.removeAt(index!); } } ++i; } if (_isDefaultAppearance) { dictionary!.setBoolean( - PdfDictionaryProperties.needAppearances, _isDefaultAppearance); + PdfDictionaryProperties.needAppearances, + _isDefaultAppearance, + ); } else if (!_isDefaultAppearance && dictionary!.containsKey(PdfDictionaryProperties.needAppearances)) { dictionary!.setBoolean( - PdfDictionaryProperties.needAppearances, _isDefaultAppearance); + PdfDictionaryProperties.needAppearances, + _isDefaultAppearance, + ); } dictionary!.remove('XFA'); } @@ -1066,8 +1160,9 @@ class PdfFormHelper { if (pageFontResource == null || (pageFontResource is PdfDictionary && !pageFontResource.containsKey(key))) { - final PdfReferenceHolder? fieldFontReference = (fieldFontResource! - as PdfDictionary)[key] as PdfReferenceHolder?; + final PdfReferenceHolder? fieldFontReference = + (fieldFontResource! as PdfDictionary)[key] + as PdfReferenceHolder?; if (pageFontResource == null) { final PdfDictionary fontDictionary = PdfDictionary(); fontDictionary.items![key] = fieldFontReference; @@ -1091,8 +1186,9 @@ class PdfFormHelper { int? fieldFlag = 0; final PdfDictionary fieldDictionary = helper.dictionary!; if (fieldDictionary.containsKey(PdfDictionaryProperties.f)) { - fieldFlag = (fieldDictionary[PdfDictionaryProperties.f]! as PdfNumber) - .value as int?; + fieldFlag = + (fieldDictionary[PdfDictionaryProperties.f]! as PdfNumber).value + as int?; } if (fieldFlag != 6) { _addFieldResourcesToPage(field); @@ -1140,7 +1236,8 @@ class PdfFormHelper { pageRef = crossTable!.getReference(dic[pName]); } else if (field.page != null) { pageRef = crossTable!.getReference( - PdfPageHelper.getHelper(field.page!).dictionary); + PdfPageHelper.getHelper(field.page!).dictionary, + ); } page = crossTable!.getObject(pageRef) as PdfDictionary?; } @@ -1182,10 +1279,9 @@ class PdfFormHelper { final PdfAnnotationCollection annotCollection = helper.page!.annotations; if (annotCollection.count > 0) { - final int index = - PdfAnnotationCollectionHelper.getHelper(annotCollection) - .annotations - .indexOf(holder); + final int index = PdfAnnotationCollectionHelper.getHelper( + annotCollection, + ).annotations.indexOf(holder); if (index >= 0 && index < annotCollection.count) { annotCollection.remove(annotCollection[index]); } @@ -1196,12 +1292,16 @@ class PdfFormHelper { } else if (isLoaded) { helper.requiredReference = holder; if (field.page != null && - PdfPageHelper.getHelper(field.page!) - .dictionary! - .containsKey(annotsName)) { - final PdfArray annots = crossTable!.getObject( - PdfPageHelper.getHelper(field.page!) - .dictionary![annotsName])! as PdfArray; + PdfPageHelper.getHelper( + field.page!, + ).dictionary!.containsKey(annotsName)) { + final PdfArray annots = + crossTable!.getObject( + PdfPageHelper.getHelper( + field.page!, + ).dictionary![annotsName], + )! + as PdfArray; for (int i = 0; i < annots.count; i++) { final IPdfPrimitive? obj = annots.elements[i]; if (obj != null && @@ -1216,8 +1316,9 @@ class PdfFormHelper { } if (crossTable!.items != null && crossTable!.items!.contains(widget)) { - crossTable!.items!.objectCollection! - .removeAt(crossTable!.items!.lookFor(widget)!); + crossTable!.items!.objectCollection!.removeAt( + crossTable!.items!.lookFor(widget)!, + ); } helper.requiredReference = null; } @@ -1225,10 +1326,12 @@ class PdfFormHelper { } else { IPdfPrimitive? page; if (!isLoaded) { - final PdfReferenceHolder pageRef = dic.containsKey(pName) - ? (dic[pName] as PdfReferenceHolder?)! - : PdfReferenceHolder( - PdfPageHelper.getHelper(field.page!).dictionary); + final PdfReferenceHolder pageRef = + dic.containsKey(pName) + ? (dic[pName] as PdfReferenceHolder?)! + : PdfReferenceHolder( + PdfPageHelper.getHelper(field.page!).dictionary, + ); page = pageRef.object; } else { PdfReference? pageRef; @@ -1236,17 +1339,19 @@ class PdfFormHelper { dic[PdfDictionaryProperties.p] is! PdfNull) { pageRef = crossTable!.getReference(dic[pName]); } else if (field.page != null) { - pageRef = crossTable! - .getReference(PdfPageHelper.getHelper(field.page!).dictionary); + pageRef = crossTable!.getReference( + PdfPageHelper.getHelper(field.page!).dictionary, + ); } page = crossTable!.getObject(pageRef); } if (page != null && page is PdfDictionary && page.containsKey(PdfDictionaryProperties.annots)) { - final IPdfPrimitive? annots = isLoaded - ? crossTable!.getObject(page[annotsName]) - : page[PdfDictionaryProperties.annots]; + final IPdfPrimitive? annots = + isLoaded + ? crossTable!.getObject(page[annotsName]) + : page[PdfDictionaryProperties.annots]; if (annots != null && annots is PdfArray) { for (int i = 0; i < annots.count; i++) { final IPdfPrimitive? obj = annots.elements[i]; @@ -1263,12 +1368,16 @@ class PdfFormHelper { } } else if (isLoaded && field.page != null && - PdfPageHelper.getHelper(field.page!) - .dictionary! - .containsKey(annotsName)) { - final PdfArray annots = crossTable!.getObject( - PdfPageHelper.getHelper(field.page!).dictionary![annotsName])! - as PdfArray; + PdfPageHelper.getHelper( + field.page!, + ).dictionary!.containsKey(annotsName)) { + final PdfArray annots = + crossTable!.getObject( + PdfPageHelper.getHelper( + field.page!, + ).dictionary![annotsName], + )! + as PdfArray; for (int i = 0; i < annots.count; i++) { final IPdfPrimitive? obj = annots.elements[i]; if (obj != null && @@ -1300,10 +1409,11 @@ class PdfFormHelper { if (dic.items != null) { if (dic.containsKey(PdfDictionaryProperties.kids)) { PdfArray? array; - array = !helper.isLoadedField - ? dic[PdfDictionaryProperties.kids] as PdfArray? - : crossTable!.getObject(dic[PdfDictionaryProperties.kids]) - as PdfArray?; + array = + !helper.isLoadedField + ? dic[PdfDictionaryProperties.kids] as PdfArray? + : crossTable!.getObject(dic[PdfDictionaryProperties.kids]) + as PdfArray?; array!.clear(); dic.setProperty(PdfDictionaryProperties.kids, array); } @@ -1327,8 +1437,10 @@ class PdfFormHelper { /// internal method //Removes field and kids annotation from dictionaries. - void removeFromDictionaries(PdfField field, - [bool removeFieldFromAcroForm = false]) { + void removeFromDictionaries( + PdfField field, [ + bool removeFieldFromAcroForm = false, + ]) { final PdfFieldHelper helper = PdfFieldHelper.getHelper(field); if ((_fields != null && _fields!.count > 0) || removeFieldFromAcroForm) { final PdfName fieldsDict = PdfName(PdfDictionaryProperties.fields); @@ -1346,36 +1458,18 @@ class PdfFormHelper { } helper.dictionary!.isSkip = true; fields.changed = true; - if (!formHasKids || - !helper.dictionary!.items! - .containsKey(PdfName(PdfDictionaryProperties.parent))) { - for (int i = 0; i < fields.count; i++) { - final IPdfPrimitive? fieldDictionary = - PdfCrossTable.dereference(crossTable!.getObject(fields[i])); - final PdfName kidsName = PdfName(PdfDictionaryProperties.kids); - if (fieldDictionary != null && - fieldDictionary is PdfDictionary && - fieldDictionary.containsKey(kidsName)) { - final PdfArray kids = - crossTable!.getObject(fieldDictionary[kidsName])! as PdfArray; - for (int i = 0; i < kids.count; i++) { - final IPdfPrimitive? obj = kids[i]; - if (obj != null && - obj is PdfReferenceHolder && - obj.object == helper.dictionary) { - kids.remove(obj); - break; - } - } - } - } - } else { - if (helper.dictionary!.items! - .containsKey(PdfName(PdfDictionaryProperties.parent))) { + if (!(!formHasKids || + !helper.dictionary!.items!.containsKey( + PdfName(PdfDictionaryProperties.parent), + ))) { + if (helper.dictionary!.items!.containsKey( + PdfName(PdfDictionaryProperties.parent), + )) { final PdfDictionary dic = (helper.dictionary![PdfDictionaryProperties.parent]! - as PdfReferenceHolder) - .object! as PdfDictionary; + as PdfReferenceHolder) + .object! + as PdfDictionary; final PdfArray kids = dic.items![PdfName(PdfDictionaryProperties.kids)]! as PdfArray; for (int k = 0; k < kids.count; k++) { @@ -1405,11 +1499,16 @@ class PdfFormHelper { final String tempString = newString.substring(index); if (tempString.length >= 7 && tempString[6] == '_') { newString = newString.replaceRange(index, index + 2, '--'); - final int? charCode = - int.tryParse(value.substring(index + 2, index + 6), radix: 16); + final int? charCode = int.tryParse( + value.substring(index + 2, index + 6), + radix: 16, + ); if (charCode != null && charCode >= 0) { value = value.replaceRange( - index, index + 7, String.fromCharCode(charCode)); + index, + index + 7, + String.fromCharCode(charCode), + ); newString = newString.replaceRange(index, index + 7, '-'); } } else { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form_field_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form_field_collection.dart index 77ac61723..62abf43b4 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form_field_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_form_field_collection.dart @@ -88,7 +88,7 @@ class PdfFormFieldCollection extends PdfObjectCollection class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfFormFieldCollectionHelper(this.formFieldCollection, PdfForm? form) - : super(formFieldCollection) { + : super(formFieldCollection) { if (form != null) { this.form = form; final PdfFormHelper formHelper = PdfFormHelper.getHelper(form); @@ -126,7 +126,8 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfFormFieldCollectionHelper getHelper( - PdfFormFieldCollection collection) { + PdfFormFieldCollection collection, + ) { return collection._helper; } @@ -144,9 +145,11 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { /// internal method void createFormFieldsFromWidgets(int startFormFieldIndex) { - for (int i = startFormFieldIndex; - i < PdfFormHelper.getHelper(form!).terminalFields.length; - ++i) { + for ( + int i = startFormFieldIndex; + i < PdfFormHelper.getHelper(form!).terminalFields.length; + ++i + ) { final PdfField? field = _getField(index: i); if (field != null) { _doAdd(field); @@ -160,9 +163,9 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { if (dictValue.isNotEmpty) { final PdfField? field = _getField(dictionary: dictValue[0]); if (field != null) { - PdfFormHelper.getHelper(form!) - .terminalFields - .add(PdfFieldHelper.getHelper(field).dictionary!); + PdfFormHelper.getHelper( + form!, + ).terminalFields.add(PdfFieldHelper.getHelper(field).dictionary!); _doAdd(field); } } @@ -180,17 +183,20 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { PdfArray? array; bool skipField = false; if (isLoaded) { - array = PdfFormHelper.getHelper(form!) - .dictionary! - .containsKey(PdfDictionaryProperties.fields) - ? PdfFormHelper.getHelper(form!).crossTable!.getObject( - PdfFormHelper.getHelper(form!) - .dictionary![PdfDictionaryProperties.fields]) as PdfArray? - : PdfArray(); - if (PdfFieldHelper.getHelper(field) - .dictionary! - .items! - .containsKey(PdfName(PdfDictionaryProperties.parent))) { + array = + PdfFormHelper.getHelper( + form!, + ).dictionary!.containsKey(PdfDictionaryProperties.fields) + ? PdfFormHelper.getHelper(form!).crossTable!.getObject( + PdfFormHelper.getHelper( + form!, + ).dictionary![PdfDictionaryProperties.fields], + ) + as PdfArray? + : PdfArray(); + if (PdfFieldHelper.getHelper(field).dictionary!.items!.containsKey( + PdfName(PdfDictionaryProperties.parent), + )) { skipField = true; } } else { @@ -202,20 +208,21 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { if (!isLoaded || !PdfFieldHelper.getHelper(field).isLoadedField) { if (form!.fieldAutoNaming && !skipField) { if (!isLoaded) { - PdfFieldHelper.getHelper(field) - .applyName(PdfFormHelper.getHelper(form!).getCorrectName(name)); + PdfFieldHelper.getHelper( + field, + ).applyName(PdfFormHelper.getHelper(form!).getCorrectName(name)); } else { PdfFieldHelper.getHelper(field).applyName(getCorrectName(name)); array!.add(PdfReferenceHolder(field)); - PdfFormHelper.getHelper(form!) - .dictionary! - .setProperty(PdfDictionaryProperties.fields, array); + PdfFormHelper.getHelper( + form!, + ).dictionary!.setProperty(PdfDictionaryProperties.fields, array); } } else if (isLoaded && !addedFieldNames.contains(name) && !skipField) { array!.add(PdfReferenceHolder(field)); - PdfFormHelper.getHelper(form!) - .dictionary! - .setProperty(PdfDictionaryProperties.fields, array); + PdfFormHelper.getHelper( + form!, + ).dictionary!.setProperty(PdfDictionaryProperties.fields, array); } else if (isLoaded && (!addedFieldNames.contains(name) && skipField) || (form!.fieldAutoNaming && skipField)) { addedFieldNames.add(field.name); @@ -241,10 +248,9 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { } if (field is! PdfRadioButtonListField && PdfFieldHelper.getHelper(field).page != null) { - PdfFieldHelper.getHelper(field) - .page! - .annotations - .add(PdfFieldHelper.getHelper(field).widget!); + PdfFieldHelper.getHelper( + field, + ).page!.annotations.add(PdfFieldHelper.getHelper(field).widget!); } array.add(PdfReferenceHolder(field)); list.add(field); @@ -260,8 +266,9 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { if ((field is PdfTextBoxField && oldField is PdfTextBoxField) || (field is PdfCheckBoxField && oldField is PdfCheckBoxField)) { final PdfFieldHelper fieldHelper = PdfFieldHelper.getHelper(field); - final PdfFieldHelper oldFieldHelper = - PdfFieldHelper.getHelper(oldField); + final PdfFieldHelper oldFieldHelper = PdfFieldHelper.getHelper( + oldField, + ); PdfDictionary? dic; PdfDictionary? oldFieldDic; if (isLoaded) { @@ -275,20 +282,36 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { dic = PdfAnnotationHelper.getHelper(fieldHelper.widget!).dictionary; oldFieldDic = - PdfAnnotationHelper.getHelper(oldFieldHelper.widget!) - .dictionary; + PdfAnnotationHelper.getHelper( + oldFieldHelper.widget!, + ).dictionary; + } + if (isLoaded) { + final PdfCrossTable? crossTable = + PdfFormHelper.getHelper(form!).crossTable; + final PdfDictionary? cloneIprimitive = + dic?.cloneObject(crossTable!) as PdfDictionary?; + dic = cloneIprimitive; + dic?.setProperty( + PdfDictionaryProperties.p, + PdfReferenceHolder(field.page), + ); } dic!.remove(PdfDictionaryProperties.parent); if (isLoaded) { - dic.setProperty(PdfDictionaryProperties.parent, - PdfReferenceHolder(oldFieldDic)); + dic.setProperty( + PdfDictionaryProperties.parent, + PdfReferenceHolder(oldFieldDic), + ); } fieldHelper.widget!.parent = oldField; if (!isLoaded && fieldHelper.page != null) { fieldHelper.page!.annotations.add(fieldHelper.widget!); } - final bool isOldFieldPresent = - _checkCollection(oldFieldHelper.array, oldFieldDic!); + final bool isOldFieldPresent = _checkCollection( + oldFieldHelper.array, + oldFieldDic!, + ); bool isNewFieldPresent = false; if (isLoaded) { isNewFieldPresent = _checkCollection(oldFieldHelper.array, dic); @@ -308,46 +331,56 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { oldFieldHelper.fieldItems ??= []; oldFieldHelper.fieldItems!.add(field); oldFieldHelper.dictionary!.setProperty( - PdfDictionaryProperties.kids, oldFieldHelper.array); + PdfDictionaryProperties.kids, + oldFieldHelper.array, + ); } if (isLoaded) { if (oldFieldReferenceHolder != null) { _addItem(oldField, oldFieldReferenceHolder, 0, true); } if (newFieldReferenceHolder != null) { - _addItem(oldField, newFieldReferenceHolder, - oldFieldHelper.array.count - 1, false); + _addItem( + oldField, + newFieldReferenceHolder, + oldFieldHelper.array.count - 1, + false, + ); } if (PdfFieldHelper.getHelper(field).isLoadedField) { - PdfFormHelper.getHelper(form!) - .removeFromDictionaries(field, true); + PdfFormHelper.getHelper( + form!, + ).removeFromDictionaries(field, true); } } return formFieldCollection.count - 1; } else if (!isLoaded && field is PdfSignatureField) { final PdfSignatureField currentField = field; - final PdfDictionary dictionary = PdfAnnotationHelper.getHelper( - PdfFieldHelper.getHelper(currentField).widget!) - .dictionary!; + final PdfDictionary dictionary = + PdfAnnotationHelper.getHelper( + PdfFieldHelper.getHelper(currentField).widget!, + ).dictionary!; if (dictionary.containsKey(PdfDictionaryProperties.parent)) { dictionary.remove(PdfDictionaryProperties.parent); } PdfFieldHelper.getHelper(currentField).widget!.parent = oldField; IPdfPrimitive? oldKids; IPdfPrimitive? newKids; - if (PdfFieldHelper.getHelper(oldField) - .dictionary! - .containsKey(PdfDictionaryProperties.kids)) { - oldKids = PdfFieldHelper.getHelper(oldField) - .dictionary! - .items![PdfName(PdfDictionaryProperties.kids)]; + if (PdfFieldHelper.getHelper( + oldField, + ).dictionary!.containsKey(PdfDictionaryProperties.kids)) { + oldKids = + PdfFieldHelper.getHelper(oldField).dictionary!.items![PdfName( + PdfDictionaryProperties.kids, + )]; } - if (PdfFieldHelper.getHelper(field) - .dictionary! - .containsKey(PdfDictionaryProperties.kids)) { - newKids = PdfFieldHelper.getHelper(field) - .dictionary! - .items![PdfName(PdfDictionaryProperties.kids)]; + if (PdfFieldHelper.getHelper( + field, + ).dictionary!.containsKey(PdfDictionaryProperties.kids)) { + newKids = + PdfFieldHelper.getHelper(field).dictionary!.items![PdfName( + PdfDictionaryProperties.kids, + )]; } if (newKids != null && newKids is PdfArray) { if (oldKids == null || oldKids is! PdfArray) { @@ -361,15 +394,17 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { } } } - PdfFieldHelper.getHelper(oldField) - .dictionary! - .setProperty(PdfDictionaryProperties.kids, oldKids); + PdfFieldHelper.getHelper( + oldField, + ).dictionary!.setProperty(PdfDictionaryProperties.kids, oldKids); PdfSignatureFieldHelper.getHelper(currentField) .skipKidsCertificate = true; - if (!field.page!.annotations - .contains(PdfFieldHelper.getHelper(currentField).widget!)) { - field.page!.annotations - .add(PdfFieldHelper.getHelper(currentField).widget!); + if (!field.page!.annotations.contains( + PdfFieldHelper.getHelper(currentField).widget!, + )) { + field.page!.annotations.add( + PdfFieldHelper.getHelper(currentField).widget!, + ); } return formFieldCollection.count - 1; } @@ -381,8 +416,9 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { PdfDictionary _getWidgetAnnotation(PdfDictionary dictionary) { if (dictionary.containsKey(PdfDictionaryProperties.kids)) { - final IPdfPrimitive? array = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.kids]); + final IPdfPrimitive? array = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.kids], + ); if (array is PdfArray && array.count > 0) { final IPdfPrimitive? dic = PdfCrossTable.dereference(array[0]); if (dic is PdfDictionary) { @@ -393,8 +429,12 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { return dictionary; } - void _addItem(PdfField field, PdfReferenceHolder referenceHolder, int index, - bool initializeNew) { + void _addItem( + PdfField field, + PdfReferenceHolder referenceHolder, + int index, + bool initializeNew, + ) { PdfFieldItemCollection? items; if (initializeNew) { items = PdfFieldItemCollectionHelper.load(field); @@ -413,8 +453,15 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { if (items != null) { final PdfDictionary? itemDictionary = PdfCrossTable.dereference(referenceHolder) as PdfDictionary?; - PdfFieldItemCollectionHelper.getHelper(items) - .add(PdfCheckBoxItemHelper.getItem(field, index, itemDictionary)); + if (field is PdfCheckBoxField) { + PdfFieldItemCollectionHelper.getHelper( + items, + ).add(PdfCheckBoxItemHelper.getItem(field, index, itemDictionary)); + } else if (field is PdfTextBoxField) { + PdfFieldItemCollectionHelper.getHelper( + items, + ).add(PdfTextBoxItemHelper.getItem(field, index, itemDictionary)); + } } } @@ -437,11 +484,19 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { index != null ? dictionary = PdfFormHelper.getHelper(form!).terminalFields[index] : ArgumentError.checkNotNull( - dictionary, 'method cannot be initialized without parameters'); + dictionary, + 'method cannot be initialized without parameters', + ); final PdfCrossTable? crossTable = PdfFormHelper.getHelper(form!).crossTable; PdfField? field; - final PdfName? name = PdfFieldHelper.getValue( - dictionary!, crossTable, PdfDictionaryProperties.ft, true) as PdfName?; + final PdfName? name = + PdfFieldHelper.getValue( + dictionary!, + crossTable, + PdfDictionaryProperties.ft, + true, + ) + as PdfName?; PdfFieldTypes type = PdfFieldTypes.none; if (name != null) { type = _getFieldType(name, dictionary, crossTable); @@ -484,12 +539,20 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { //Gets the type of the field. PdfFieldTypes _getFieldType( - PdfName name, PdfDictionary dictionary, PdfCrossTable? crossTable) { + PdfName name, + PdfDictionary dictionary, + PdfCrossTable? crossTable, + ) { final String str = name.name!; PdfFieldTypes type = PdfFieldTypes.none; - final PdfNumber? number = PdfFieldHelper.getValue( - dictionary, crossTable, PdfDictionaryProperties.fieldFlags, true) - as PdfNumber?; + final PdfNumber? number = + PdfFieldHelper.getValue( + dictionary, + crossTable, + PdfDictionaryProperties.fieldFlags, + true, + ) + as PdfNumber?; int fieldFlags = 0; if (number != null) { fieldFlags = number.value!.toInt(); @@ -524,56 +587,78 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { //Creates the combo box. PdfField _createComboBox(PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfComboBoxFieldHelper.loadComboBox(dictionary, crossTable); + final PdfField field = PdfComboBoxFieldHelper.loadComboBox( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } //Creates the list box. PdfField _createListBox(PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfListBoxFieldHelper.loadListBox(dictionary, crossTable); + final PdfField field = PdfListBoxFieldHelper.loadListBox( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } //Creates the text field. PdfField _createTextField( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfTextBoxFieldHelper.loadTextBox(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfField field = PdfTextBoxFieldHelper.loadTextBox( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } PdfField _createCheckBox(PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfCheckBoxFieldHelper.loadCheckBoxField(dictionary, crossTable); + final PdfField field = PdfCheckBoxFieldHelper.loadCheckBoxField( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } PdfField _createRadioButton( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfRadioButtonListFieldHelper.loaded(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfField field = PdfRadioButtonListFieldHelper.loaded( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } PdfField _createPushButton( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfButtonFieldHelper.loadButtonField(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfField field = PdfButtonFieldHelper.loadButtonField( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } PdfField _createSignatureField( - PdfDictionary dictionary, PdfCrossTable crossTable) { - final PdfField field = - PdfSignatureFieldHelper.loadSignatureField(dictionary, crossTable); + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { + final PdfField field = PdfSignatureFieldHelper.loadSignatureField( + dictionary, + crossTable, + ); PdfFieldHelper.getHelper(field).setForm(form); return field; } @@ -625,8 +710,9 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { /// internal method void removeContainingField(PdfReferenceHolder pageReferenceHolder) { for (int i = array.count - 1; i >= 0; --i) { - final IPdfPrimitive? fieldDictionary = - PdfCrossTable.dereference(array[i]); + final IPdfPrimitive? fieldDictionary = PdfCrossTable.dereference( + array[i], + ); if (fieldDictionary != null && fieldDictionary is PdfDictionary) { if (fieldDictionary.containsKey(PdfDictionaryProperties.p)) { final IPdfPrimitive? holder = @@ -637,8 +723,10 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { _doRemoveAt(i); } } else if (fieldDictionary.containsKey(PdfDictionaryProperties.kids)) { - final bool removed = - _removeContainingFieldItems(fieldDictionary, pageReferenceHolder); + final bool removed = _removeContainingFieldItems( + fieldDictionary, + pageReferenceHolder, + ); if (removed) { _doRemoveAt(i); } @@ -701,11 +789,14 @@ class PdfFormFieldCollectionHelper extends PdfObjectCollectionHelper { } bool _removeContainingFieldItems( - PdfDictionary fieldDictionary, PdfReferenceHolder pageReferenceHolder) { + PdfDictionary fieldDictionary, + PdfReferenceHolder pageReferenceHolder, + ) { bool isAllKidsRemoved = false; if (fieldDictionary.containsKey(PdfDictionaryProperties.kids)) { final IPdfPrimitive? array = PdfCrossTable.dereference( - fieldDictionary[PdfDictionaryProperties.kids]); + fieldDictionary[PdfDictionaryProperties.kids], + ); if (array != null && array is PdfArray) { for (int i = array.count - 1; i >= 0; --i) { IPdfPrimitive? holder; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_box_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_box_field.dart index 638f1a200..d86918d4a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_box_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_box_field.dart @@ -30,32 +30,40 @@ import 'pdf_list_field_item_collection.dart'; class PdfListBoxField extends PdfListField { //Constructor /// Initializes a new instance of the [PdfListBoxField] class with the specific page and name. - PdfListBoxField(PdfPage page, String name, Rect bounds, - {List? items, - bool multiSelect = false, - List? selectedIndexes, - List? selectedValues, - PdfFont? font, - PdfTextAlignment alignment = PdfTextAlignment.left, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode highlightMode = PdfHighlightMode.invert, - PdfBorderStyle borderStyle = PdfBorderStyle.solid, - String? tooltip}) { + PdfListBoxField( + PdfPage page, + String name, + Rect bounds, { + List? items, + bool multiSelect = false, + List? selectedIndexes, + List? selectedValues, + PdfFont? font, + PdfTextAlignment alignment = PdfTextAlignment.left, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode highlightMode = PdfHighlightMode.invert, + PdfBorderStyle borderStyle = PdfBorderStyle.solid, + String? tooltip, + }) { _helper = PdfListBoxFieldHelper(this); - _helper.initializeInternal(page, name, bounds, - font: font, - alignment: alignment, - items: items, - borderColor: borderColor, - foreColor: foreColor, - backColor: backColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + _helper.initializeInternal( + page, + name, + bounds, + font: font, + alignment: alignment, + items: items, + borderColor: borderColor, + foreColor: foreColor, + backColor: backColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); this.multiSelect = multiSelect; if (selectedIndexes != null) { this.selectedIndexes = selectedIndexes; @@ -81,7 +89,8 @@ class PdfListBoxField extends PdfListField { /// The default value is false. bool get multiSelect { if (_helper.isLoadedField) { - _multiSelect = _helper.isFlagPresent(FieldFlags.multiSelect) || + _multiSelect = + _helper.isFlagPresent(FieldFlags.multiSelect) || _helper.flags.contains(FieldFlags.multiSelect); } return _multiSelect; @@ -93,8 +102,8 @@ class PdfListBoxField extends PdfListField { _multiSelect ? _helper.flags.add(FieldFlags.multiSelect) : _helper.isLoadedField - ? _helper.removeFlag(FieldFlags.multiSelect) - : _helper.flags.remove(FieldFlags.multiSelect); + ? _helper.removeFlag(FieldFlags.multiSelect) + : _helper.flags.remove(FieldFlags.multiSelect); } } @@ -140,31 +149,45 @@ class PdfListBoxFieldHelper extends PdfListFieldHelper { void drawAppearance(PdfTemplate template) { super.drawAppearance(template); final PaintParams params = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, listBoxField.bounds.width, listBoxField.bounds.height), - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: listBoxField.borderStyle, - borderWidth: listBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: Rect.fromLTWH( + 0, + 0, + listBoxField.bounds.width, + listBoxField.bounds.height, + ), + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: listBoxField.borderStyle, + borderWidth: listBoxField.borderWidth, + shadowBrush: shadowBrush, + ); PdfFont font; if (listBoxField.font == null) { if (PdfPageHelper.getHelper(listBoxField.page!).document != null && PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(listBoxField.page!).document!) - .conformanceLevel != + PdfPageHelper.getHelper(listBoxField.page!).document!, + ).conformanceLevel != PdfConformanceLevel.none) { throw ArgumentError( - 'Font data is not embedded to the conformance PDF.'); + 'Font data is not embedded to the conformance PDF.', + ); } font = PdfStandardFont( - PdfFontFamily.timesRoman, getFontHeight(PdfFontFamily.timesRoman)); + PdfFontFamily.timesRoman, + getFontHeight(PdfFontFamily.timesRoman), + ); } else { font = listBoxField.font!; } - FieldPainter().drawListBox(template.graphics!, params, listBoxField.items, - selectedIndexes, font, format); + FieldPainter().drawListBox( + template.graphics!, + params, + listBoxField.items, + selectedIndexes, + font, + format, + ); } /// internal method @@ -174,33 +197,56 @@ class PdfListBoxFieldHelper extends PdfListFieldHelper { if (!isLoadedField) { if (PdfAnnotationHelper.getHelper(widget!).appearance != null) { listBoxField.page!.graphics.drawPdfTemplate( - widget!.appearance.normal, listBoxField.bounds.topLeft); + widget!.appearance.normal, + listBoxField.bounds.topLeft, + ); } else { final Rect rect = Rect.fromLTWH( - 0, 0, listBoxField.bounds.width, listBoxField.bounds.height); - final PdfFont font = listBoxField.font ?? - PdfStandardFont(PdfFontFamily.helvetica, - getFontHeight(PdfFontFamily.helvetica)); + 0, + 0, + listBoxField.bounds.width, + listBoxField.bounds.height, + ); + final PdfFont font = + listBoxField.font ?? + PdfStandardFont( + PdfFontFamily.helvetica, + getFontHeight(PdfFontFamily.helvetica), + ); final PaintParams parameters = PaintParams( - bounds: rect, - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: listBoxField.borderStyle, - borderWidth: listBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: rect, + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: listBoxField.borderStyle, + borderWidth: listBoxField.borderWidth, + shadowBrush: shadowBrush, + ); final PdfTemplate template = PdfTemplate(rect.width, rect.height); - FieldPainter().drawListBox(template.graphics!, parameters, - listBoxField.items, listBoxField.selectedIndexes, font, format); - listBoxField.page!.graphics - .drawPdfTemplate(template, listBoxField.bounds.topLeft, rect.size); + FieldPainter().drawListBox( + template.graphics!, + parameters, + listBoxField.items, + listBoxField.selectedIndexes, + font, + format, + ); + listBoxField.page!.graphics.drawPdfTemplate( + template, + listBoxField.bounds.topLeft, + rect.size, + ); } } else { - final PdfTemplate template = - PdfTemplate(listBoxField.bounds.width, listBoxField.bounds.height); + final PdfTemplate template = PdfTemplate( + listBoxField.bounds.width, + listBoxField.bounds.height, + ); _drawListBox(template.graphics!); - listBoxField.page!.graphics - .drawPdfTemplate(template, listBoxField.bounds.topLeft); + listBoxField.page!.graphics.drawPdfTemplate( + template, + listBoxField.bounds.topLeft, + ); } } @@ -214,33 +260,41 @@ class PdfListBoxFieldHelper extends PdfListFieldHelper { void _applyAppearance(PdfDictionary widget) { if (widget.containsKey(PdfDictionaryProperties.ap) && !PdfFormHelper.getHelper(listBoxField.form!).needAppearances!) { - final IPdfPrimitive? appearance = - crossTable!.getObject(widget[PdfDictionaryProperties.ap]); + final IPdfPrimitive? appearance = crossTable!.getObject( + widget[PdfDictionaryProperties.ap], + ); if (appearance != null && appearance is PdfDictionary && appearance.containsKey(PdfDictionaryProperties.n)) { - final PdfTemplate template = - PdfTemplate(listBoxField.bounds.width, listBoxField.bounds.height); + final PdfTemplate template = PdfTemplate( + listBoxField.bounds.width, + listBoxField.bounds.height, + ); PdfTemplateHelper.getHelper(template).writeTransformation = false; - beginMarkupSequence(PdfGraphicsHelper.getHelper(template.graphics!) - .streamWriter! - .stream!); + beginMarkupSequence( + PdfGraphicsHelper.getHelper(template.graphics!).streamWriter!.stream!, + ); PdfGraphicsHelper.getHelper(template.graphics!).initializeCoordinates(); _drawListBox(template.graphics!); - endMarkupSequence(PdfGraphicsHelper.getHelper(template.graphics!) - .streamWriter! - .stream!); + endMarkupSequence( + PdfGraphicsHelper.getHelper(template.graphics!).streamWriter!.stream!, + ); appearance.remove(PdfDictionaryProperties.n); appearance.setProperty( - PdfDictionaryProperties.n, PdfReferenceHolder(template)); + PdfDictionaryProperties.n, + PdfReferenceHolder(template), + ); widget.setProperty(PdfDictionaryProperties.ap, appearance); } - } else if (PdfFormHelper.getHelper(listBoxField.form!) - .setAppearanceDictionary && + } else if (PdfFormHelper.getHelper( + listBoxField.form!, + ).setAppearanceDictionary && !PdfFormHelper.getHelper(listBoxField.form!).needAppearances!) { final PdfDictionary dic = PdfDictionary(); - final PdfTemplate template = - PdfTemplate(listBoxField.bounds.width, listBoxField.bounds.height); + final PdfTemplate template = PdfTemplate( + listBoxField.bounds.width, + listBoxField.bounds.height, + ); drawAppearance(template); dic.setProperty(PdfDictionaryProperties.n, PdfReferenceHolder(template)); widget.setProperty(PdfDictionaryProperties.ap, dic); @@ -250,21 +304,32 @@ class PdfListBoxFieldHelper extends PdfListFieldHelper { void _drawListBox(PdfGraphics graphics) { final GraphicsProperties gp = GraphicsProperties(listBoxField); gp.bounds = Rect.fromLTWH( - 0, 0, listBoxField.bounds.width, listBoxField.bounds.height); + 0, + 0, + listBoxField.bounds.width, + listBoxField.bounds.height, + ); final PaintParams prms = PaintParams( - bounds: gp.bounds, - backBrush: gp.backBrush, - foreBrush: gp.foreBrush, - borderPen: gp.borderPen, - style: gp.style, - borderWidth: gp.borderWidth, - shadowBrush: gp.shadowBrush); + bounds: gp.bounds, + backBrush: gp.backBrush, + foreBrush: gp.foreBrush, + borderPen: gp.borderPen, + style: gp.style, + borderWidth: gp.borderWidth, + shadowBrush: gp.shadowBrush, + ); if (!PdfFormHelper.getHelper(listBoxField.form!).setAppearanceDictionary && !PdfFormHelper.getHelper(listBoxField.form!).flatten) { prms.backBrush = null; } - FieldPainter().drawListBox(graphics, prms, listBoxField.items, - selectedIndexes, gp.font!, gp.stringFormat); + FieldPainter().drawListBox( + graphics, + prms, + listBoxField.items, + selectedIndexes, + gp.font!, + gp.stringFormat, + ); } /// internal method @@ -287,7 +352,9 @@ class PdfListBoxFieldHelper extends PdfListFieldHelper { /// internal method static PdfListBoxField loadListBox( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfListBoxField._load(dictionary, crossTable); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field.dart index 3a7d486f4..657f6ca76 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field.dart @@ -22,41 +22,54 @@ import 'pdf_list_field_item_collection.dart'; /// Represents base class for form's list fields. abstract class PdfListField extends PdfField { /// internal constructor - void _internal(PdfPage? page, String name, Rect bounds, - {List? items, - PdfFont? font, - PdfTextAlignment? alignment, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode? highlightMode, - PdfBorderStyle? borderStyle, - String? tooltip, - PdfListFieldHelper? helper}) { + void _internal( + PdfPage? page, + String name, + Rect bounds, { + List? items, + PdfFont? font, + PdfTextAlignment? alignment, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode? highlightMode, + PdfBorderStyle? borderStyle, + String? tooltip, + PdfListFieldHelper? helper, + }) { _helper = helper!; - _helper.internal(page, name, bounds, - font: font, - alignment: alignment, - borderColor: borderColor, - foreColor: foreColor, - backColor: backColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + _helper.internal( + page, + name, + bounds, + font: font, + alignment: alignment, + borderColor: borderColor, + foreColor: foreColor, + backColor: backColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); _helper.dictionary!.setProperty( - PdfDictionaryProperties.ft, PdfName(PdfDictionaryProperties.ch)); + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.ch), + ); if (items != null && items.isNotEmpty) { - items - .toList() - .forEach((PdfListFieldItem element) => this.items.add(element)); + items.toList().forEach( + (PdfListFieldItem element) => this.items.add(element), + ); } } /// internal constructor - void _load(PdfDictionary dictionary, PdfCrossTable crossTable, - PdfListFieldHelper helper) { + void _load( + PdfDictionary dictionary, + PdfCrossTable crossTable, + PdfListFieldHelper helper, + ) { _helper = helper; _helper.load(dictionary, crossTable); } @@ -70,8 +83,10 @@ abstract class PdfListField extends PdfField { if (_helper._items == null) { if (!_helper.isLoadedField) { _helper._items = PdfListFieldItemCollectionHelper.itemCollection(); - _helper.dictionary! - .setProperty(PdfDictionaryProperties.opt, _helper._items); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.opt, + _helper._items, + ); } else { _helper._items = _getListItemCollection(); } @@ -145,17 +160,26 @@ abstract class PdfListField extends PdfField { PdfListFieldItemCollection _getListItemCollection() { final PdfListFieldItemCollection items = PdfListFieldItemCollectionHelper.itemCollection(this); - final IPdfPrimitive? array = PdfFieldHelper.getValue(_helper.dictionary!, - _helper.crossTable, PdfDictionaryProperties.opt, true); + final IPdfPrimitive? array = PdfFieldHelper.getValue( + _helper.dictionary!, + _helper.crossTable, + PdfDictionaryProperties.opt, + true, + ); if (array != null && array is PdfArray) { for (int i = 0; i < array.count; i++) { - final IPdfPrimitive? primitive = - _helper.crossTable!.getObject(array[i]); + final IPdfPrimitive? primitive = _helper.crossTable!.getObject( + array[i], + ); PdfListFieldItem item; if (primitive is PdfString) { final PdfString str = primitive; item = PdfListFieldItemHelper.load( - str.value, null, this, _helper.crossTable); + str.value, + null, + this, + _helper.crossTable, + ); } else { final PdfArray arr = primitive! as PdfArray; final PdfString value = @@ -163,7 +187,11 @@ abstract class PdfListField extends PdfField { final PdfString text = _helper.crossTable!.getObject(arr[1])! as PdfString; item = PdfListFieldItemHelper.load( - text.value, value.value, this, _helper.crossTable); + text.value, + value.value, + this, + _helper.crossTable, + ); } PdfListFieldItemCollectionHelper.getHelper(items).addItem(item); } @@ -185,29 +213,37 @@ class PdfListFieldHelper extends PdfFieldHelper { PdfListFieldItemCollection? _items; /// internal method - void initializeInternal(PdfPage? page, String name, Rect bounds, - {List? items, - PdfFont? font, - PdfTextAlignment? alignment, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode? highlightMode, - PdfBorderStyle? borderStyle, - String? tooltip}) { - listField._internal(page, name, bounds, - items: items, - font: font, - alignment: alignment, - borderColor: borderColor, - foreColor: foreColor, - backColor: backColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip, - helper: this); + void initializeInternal( + PdfPage? page, + String name, + Rect bounds, { + List? items, + PdfFont? font, + PdfTextAlignment? alignment, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode? highlightMode, + PdfBorderStyle? borderStyle, + String? tooltip, + }) { + listField._internal( + page, + name, + bounds, + items: items, + font: font, + alignment: alignment, + borderColor: borderColor, + foreColor: foreColor, + backColor: backColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + helper: this, + ); } /// internal method @@ -234,8 +270,10 @@ class PdfListFieldHelper extends PdfFieldHelper { } else { if (selectedIndex != value) { selectedIndex = value; - dictionary! - .setProperty(PdfDictionaryProperties.i, PdfArray(selectedIndex)); + dictionary!.setProperty( + PdfDictionaryProperties.i, + PdfArray(selectedIndex), + ); } } } @@ -270,8 +308,10 @@ class PdfListFieldHelper extends PdfFieldHelper { break; } } - dictionary! - .setProperty(PdfDictionaryProperties.i, PdfArray(selectedIndex)); + dictionary!.setProperty( + PdfDictionaryProperties.i, + PdfArray(selectedIndex), + ); } } @@ -282,13 +322,15 @@ class PdfListFieldHelper extends PdfFieldHelper { } final PdfListFieldItemCollection item = PdfListFieldItemCollectionHelper.itemCollection( - isLoadedField ? listField : null); + isLoadedField ? listField : null, + ); for (final int index in selectedIndexes) { if (index > -1 && listField.items.count > 0 && listField.items.count > index) { - PdfListFieldItemCollectionHelper.getHelper(item) - .addItem(listField.items[index]); + PdfListFieldItemCollectionHelper.getHelper( + item, + ).addItem(listField.items[index]); } } return item; @@ -297,8 +339,9 @@ class PdfListFieldHelper extends PdfFieldHelper { List _obtainSelectedIndex() { final List selectedIndex = []; if (dictionary!.containsKey(PdfDictionaryProperties.i)) { - final IPdfPrimitive? array = - crossTable!.getObject(dictionary![PdfDictionaryProperties.i]); + final IPdfPrimitive? array = crossTable!.getObject( + dictionary![PdfDictionaryProperties.i], + ); if (array != null && array is PdfArray) { if (array.count > 0) { for (int i = 0; i < array.count; i++) { @@ -309,8 +352,9 @@ class PdfListFieldHelper extends PdfFieldHelper { } } } else { - final IPdfPrimitive? number = - crossTable!.getObject(dictionary![PdfDictionaryProperties.i]); + final IPdfPrimitive? number = crossTable!.getObject( + dictionary![PdfDictionaryProperties.i], + ); if (number != null && number is PdfNumber) { selectedIndex.add(number.value!.toInt()); } @@ -323,8 +367,9 @@ class PdfListFieldHelper extends PdfFieldHelper { List _obtainSelectedValue() { final List value = []; if (dictionary!.containsKey(PdfDictionaryProperties.v)) { - final IPdfPrimitive? primitive = - crossTable!.getObject(dictionary![PdfDictionaryProperties.v]); + final IPdfPrimitive? primitive = crossTable!.getObject( + dictionary![PdfDictionaryProperties.v], + ); if (primitive is PdfString) { value.add(primitive.value!); } else { @@ -403,15 +448,18 @@ class PdfListFieldHelper extends PdfFieldHelper { } if (selectedIndexes.isNotEmpty) { selectedIndexes.sort(); - dictionary! - .setProperty(PdfDictionaryProperties.i, PdfArray(selectedIndexes)); + dictionary!.setProperty( + PdfDictionaryProperties.i, + PdfArray(selectedIndexes), + ); } else { dictionary!.remove(PdfDictionaryProperties.i); } } if (dictionary!.containsKey(PdfDictionaryProperties.v)) { - final IPdfPrimitive? primitive = - crossTable!.getObject(dictionary![PdfDictionaryProperties.v]); + final IPdfPrimitive? primitive = crossTable!.getObject( + dictionary![PdfDictionaryProperties.v], + ); if ((primitive == null) || (primitive is PdfString)) { if (listField is PdfListBoxField) { final PdfArray array = PdfArray(); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item.dart index ad8e450ec..53e8307e5 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item.dart @@ -18,7 +18,11 @@ class PdfListFieldItem implements IPdfWrapper { /// Initializes a new instance of the [PdfListFieldItem] class. PdfListFieldItem._load( - String? text, String? value, PdfListField field, PdfCrossTable? cTable) { + String? text, + String? value, + PdfListField field, + PdfCrossTable? cTable, + ) { _helper = PdfListFieldItemHelper(this); _field = field; _crossTable = cTable; @@ -73,15 +77,17 @@ class PdfListFieldItem implements IPdfWrapper { final PdfDictionary fieldDic = PdfFieldHelper.getHelper(_field!).dictionary!; if (fieldDic.containsKey(PdfDictionaryProperties.opt)) { - final PdfArray array = _crossTable! - .getObject(fieldDic[PdfDictionaryProperties.opt])! as PdfArray; - final PdfArray item = isText - ? (PdfArray() - ..add(PdfString(_value!)) - ..add(PdfString(value))) - : (PdfArray() - ..add(PdfString(value)) - ..add(PdfString(_text!))); + final PdfArray array = + _crossTable!.getObject(fieldDic[PdfDictionaryProperties.opt])! + as PdfArray; + final PdfArray item = + isText + ? (PdfArray() + ..add(PdfString(_value!)) + ..add(PdfString(value))) + : (PdfArray() + ..add(PdfString(value)) + ..add(PdfString(_text!))); for (int i = 0; i < array.count; ++i) { final IPdfPrimitive primitive = _crossTable!.getObject(array[i])!; final PdfArray arr = primitive as PdfArray; @@ -123,7 +129,11 @@ class PdfListFieldItemHelper { /// internal method static PdfListFieldItem load( - String? text, String? value, PdfListField field, PdfCrossTable? cTable) { + String? text, + String? value, + PdfListField field, + PdfCrossTable? cTable, + ) { return PdfListFieldItem._load(text, value, field, cTable); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item_collection.dart index b180fe38e..db90064f1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_list_field_item_collection.dart @@ -74,9 +74,9 @@ class PdfListFieldItemCollection extends PdfObjectCollection void clear() { if (_field != null && PdfFieldHelper.getHelper(_field!).isLoadedField) { final PdfArray list = _getItems()..clear(); - PdfFieldHelper.getHelper(_field!) - .dictionary! - .setProperty(PdfDictionaryProperties.opt, list); + PdfFieldHelper.getHelper( + _field!, + ).dictionary!.setProperty(PdfDictionaryProperties.opt, list); } else { _helper._items.clear(); } @@ -89,9 +89,9 @@ class PdfListFieldItemCollection extends PdfObjectCollection final PdfArray list = _getItems(); final PdfArray itemArray = _getArray(item); list.add(itemArray); - PdfFieldHelper.getHelper(_field!) - .dictionary! - .setProperty(PdfDictionaryProperties.opt, list); + PdfFieldHelper.getHelper( + _field!, + ).dictionary!.setProperty(PdfDictionaryProperties.opt, list); } else { _helper._items.add(IPdfWrapper.getElement(item)!); } @@ -104,9 +104,9 @@ class PdfListFieldItemCollection extends PdfObjectCollection final PdfArray list = _getItems(); final PdfArray itemArray = _getArray(item); list.insert(index, itemArray); - PdfFieldHelper.getHelper(_field!) - .dictionary! - .setProperty(PdfDictionaryProperties.opt, list); + PdfFieldHelper.getHelper( + _field!, + ).dictionary!.setProperty(PdfDictionaryProperties.opt, list); } else { _helper._items.insert(index, IPdfWrapper.getElement(item)!); } @@ -119,9 +119,9 @@ class PdfListFieldItemCollection extends PdfObjectCollection } if (_field != null && PdfFieldHelper.getHelper(_field!).isLoadedField) { final PdfArray list = _getItems()..removeAt(index!); - PdfFieldHelper.getHelper(_field!) - .dictionary! - .setProperty(PdfDictionaryProperties.opt, list); + PdfFieldHelper.getHelper( + _field!, + ).dictionary!.setProperty(PdfDictionaryProperties.opt, list); } else { _helper._items.removeAt(index!); } @@ -130,13 +130,15 @@ class PdfListFieldItemCollection extends PdfObjectCollection PdfArray _getItems() { PdfArray? items; - if (PdfFieldHelper.getHelper(_field!) - .dictionary! - .containsKey(PdfDictionaryProperties.opt)) { - final IPdfPrimitive? obj = PdfFieldHelper.getHelper(_field!) - .crossTable! - .getObject(PdfFieldHelper.getHelper(_field!) - .dictionary![PdfDictionaryProperties.opt]); + if (PdfFieldHelper.getHelper( + _field!, + ).dictionary!.containsKey(PdfDictionaryProperties.opt)) { + final IPdfPrimitive? obj = PdfFieldHelper.getHelper( + _field!, + ).crossTable!.getObject( + PdfFieldHelper.getHelper(_field!).dictionary![PdfDictionaryProperties + .opt], + ); if (obj != null && obj is PdfArray) { items = obj; } @@ -160,7 +162,7 @@ class PdfListFieldItemCollection extends PdfObjectCollection class PdfListFieldItemCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfListFieldItemCollectionHelper(this.listFieldItemCollection) - : super(listFieldItemCollection); + : super(listFieldItemCollection); /// internal field PdfListFieldItemCollection listFieldItemCollection; @@ -175,7 +177,8 @@ class PdfListFieldItemCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfListFieldItemCollectionHelper getHelper( - PdfListFieldItemCollection itemCollection) { + PdfListFieldItemCollection itemCollection, + ) { return itemCollection._helper; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_item_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_item_collection.dart index 9f8ad2c8f..b1801a89d 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_item_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_item_collection.dart @@ -59,7 +59,7 @@ class PdfRadioButtonItemCollection extends PdfObjectCollection class PdfRadioButtonItemCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfRadioButtonItemCollectionHelper(this.radioButtonItemCollection, this.field) - : super(radioButtonItemCollection); + : super(radioButtonItemCollection); /// internal field PdfRadioButtonItemCollection radioButtonItemCollection; @@ -72,13 +72,15 @@ class PdfRadioButtonItemCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfRadioButtonItemCollectionHelper getHelper( - PdfRadioButtonItemCollection collection) { + PdfRadioButtonItemCollection collection, + ) { return collection._helper; } /// internal method static PdfRadioButtonItemCollection getCollection( - PdfRadioButtonListField field) { + PdfRadioButtonListField field, + ) { return PdfRadioButtonItemCollection._(field); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_list_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_list_field.dart index dba208a20..3830fe39b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_list_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_radio_button_list_field.dart @@ -20,20 +20,27 @@ class PdfRadioButtonListField extends PdfField { //Constructor /// Initializes a new instance of the [PdfRadioButtonListField] class with /// the specific page, name and bounds. - PdfRadioButtonListField(PdfPage page, String name, - {List? items, - int? selectedIndex, - String? selectedValue}) { + PdfRadioButtonListField( + PdfPage page, + String name, { + List? items, + int? selectedIndex, + String? selectedValue, + }) { _helper = PdfRadioButtonListFieldHelper(this); _helper.internal(page, name, Rect.zero); _initValues(items, selectedIndex, selectedValue); _helper.flags.add(FieldFlags.radio); _helper.dictionary!.setProperty( - PdfDictionaryProperties.ft, PdfName(PdfDictionaryProperties.btn)); + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.btn), + ); } PdfRadioButtonListField._loaded( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { _helper = PdfRadioButtonListFieldHelper(this); _helper.load(dictionary, crossTable); _retrieveOptionValue(); @@ -48,7 +55,8 @@ class PdfRadioButtonListField extends PdfField { PdfRadioButtonItemCollection get items { if (_helper.isLoadedField) { _items ??= _getRadioButtonListItems( - PdfRadioButtonItemCollectionHelper.getCollection(this)); + PdfRadioButtonItemCollectionHelper.getCollection(this), + ); return _items!; } else { if (_items == null) { @@ -135,11 +143,14 @@ class PdfRadioButtonListField extends PdfField { //Implementation void _initValues( - List? radioItems, int? index, String? value) { + List? radioItems, + int? index, + String? value, + ) { if (radioItems != null) { - radioItems - .toList() - .forEach((PdfRadioButtonListItem item) => items.add(item)); + radioItems.toList().forEach( + (PdfRadioButtonListItem item) => items.add(item), + ); } if (index != null) { selectedIndex = index; @@ -150,7 +161,8 @@ class PdfRadioButtonListField extends PdfField { } PdfRadioButtonItemCollection _getRadioButtonListItems( - PdfRadioButtonItemCollection listItems) { + PdfRadioButtonItemCollection listItems, + ) { final PdfArray? fieldKids = _helper.obtainKids(); if (fieldKids != null) { for (int i = 0; i < fieldKids.count; i++) { @@ -158,9 +170,13 @@ class PdfRadioButtonListField extends PdfField { if (kidsDict != null && kidsDict is PdfDictionary) { final PdfRadioButtonListItem item = PdfRadioButtonListItemHelper.loaded( - kidsDict, _helper.crossTable!, this); - PdfRadioButtonItemCollectionHelper.getHelper(listItems) - .doAdd(item, true); + kidsDict, + _helper.crossTable!, + this, + ); + PdfRadioButtonItemCollectionHelper.getHelper( + listItems, + ).doAdd(item, true); } } } @@ -173,11 +189,15 @@ class PdfRadioButtonListField extends PdfField { final PdfRadioButtonListItem item = items[i]; final PdfDictionary dic = PdfFieldHelper.getHelper(item).dictionary!; final IPdfPrimitive? checkNamePrimitive = PdfFieldHelper.searchInParents( - dic, _helper.crossTable, PdfDictionaryProperties.v); + dic, + _helper.crossTable, + PdfDictionaryProperties.v, + ); if (dic.containsKey(PdfDictionaryProperties.usageApplication) && (checkNamePrimitive is PdfName || checkNamePrimitive is PdfString)) { - final IPdfPrimitive? name = _helper.crossTable! - .getObject(dic[PdfDictionaryProperties.usageApplication]); + final IPdfPrimitive? name = _helper.crossTable!.getObject( + dic[PdfDictionaryProperties.usageApplication], + ); if (name is PdfName && name.name!.toLowerCase() != 'off') { if (checkNamePrimitive is PdfName && checkNamePrimitive.name!.toLowerCase() != 'off') { @@ -212,14 +232,16 @@ class PdfRadioButtonListField extends PdfField { final PdfRadioButtonListItem item = items[i]; if (item.value == name.name) { PdfFieldHelper.getHelper(item).dictionary!.setName( - PdfName(PdfDictionaryProperties.usageApplication), - PdfDictionaryProperties.off); + PdfName(PdfDictionaryProperties.usageApplication), + PdfDictionaryProperties.off, + ); } } } PdfFieldHelper.getHelper(items[value]).dictionary!.setName( - PdfName(PdfDictionaryProperties.usageApplication), - items[value].value); + PdfName(PdfDictionaryProperties.usageApplication), + items[value].value, + ); } } @@ -236,8 +258,9 @@ class PdfRadioButtonListField extends PdfField { final PdfRadioButtonListItem item = items[i]; if (item.value == PdfName.decodeName(name.name)) { PdfFieldHelper.getHelper(item).dictionary!.setName( - PdfName(PdfDictionaryProperties.usageApplication), - PdfDictionaryProperties.off); + PdfName(PdfDictionaryProperties.usageApplication), + PdfDictionaryProperties.off, + ); } } } @@ -249,15 +272,23 @@ class PdfRadioButtonListField extends PdfField { PdfRadioButtonListItemHelper.getHelper(item).optionValue == value)) { _helper.selectedIndex = items.indexOf(item); - _helper.dictionary! - .setName(PdfName(PdfDictionaryProperties.v), item.value); - _helper.dictionary! - .setName(PdfName(PdfDictionaryProperties.dv), item.value); + _helper.dictionary!.setName( + PdfName(PdfDictionaryProperties.v), + item.value, + ); + _helper.dictionary!.setName( + PdfName(PdfDictionaryProperties.dv), + item.value, + ); final PdfFieldHelper helper = PdfFieldHelper.getHelper(item); helper.dictionary!.setName( - PdfName(PdfDictionaryProperties.usageApplication), item.value); - helper.dictionary! - .setName(PdfName(PdfDictionaryProperties.v), item.value); + PdfName(PdfDictionaryProperties.usageApplication), + item.value, + ); + helper.dictionary!.setName( + PdfName(PdfDictionaryProperties.v), + item.value, + ); break; } } @@ -273,9 +304,10 @@ class PdfRadioButtonListField extends PdfField { final int count = (options.count <= items.count) ? options.count : items.count; for (int i = 0; i < count; i++) { - final IPdfPrimitive? option = options[i] is PdfReferenceHolder - ? (options[i]! as PdfReferenceHolder).object - : options[i]; + final IPdfPrimitive? option = + options[i] is PdfReferenceHolder + ? (options[i]! as PdfReferenceHolder).object + : options[i]; if (option != null && option is PdfString) { PdfRadioButtonListItemHelper.getHelper(items[i]).optionValue = option.value; @@ -299,13 +331,16 @@ class PdfRadioButtonListFieldHelper extends PdfFieldHelper { /// internal method static PdfRadioButtonListFieldHelper getHelper( - PdfRadioButtonListField radioButtonList) { + PdfRadioButtonListField radioButtonList, + ) { return radioButtonList._helper; } /// internal method static PdfRadioButtonListField loaded( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfRadioButtonListField._loaded(dictionary, crossTable); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_signature_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_signature_field.dart index 85ca8e582..fdf4ccd96 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_signature_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_signature_field.dart @@ -32,34 +32,45 @@ import 'pdf_form.dart'; class PdfSignatureField extends PdfField { //Constructor /// Initializes a new instance of the [PdfSignatureField] class. - PdfSignatureField(PdfPage page, String name, - {Rect bounds = Rect.zero, - int? borderWidth, - PdfHighlightMode? highlightMode, - PdfSignature? signature, - String? tooltip, - PdfColor? backColor, - PdfColor? borderColor, - PdfBorderStyle? borderStyle}) { + PdfSignatureField( + PdfPage page, + String name, { + Rect bounds = Rect.zero, + int? borderWidth, + PdfHighlightMode? highlightMode, + PdfSignature? signature, + String? tooltip, + PdfColor? backColor, + PdfColor? borderColor, + PdfBorderStyle? borderStyle, + }) { _helper = PdfSignatureFieldHelper(this); - _helper.internal(page, name, bounds, - borderWidth: borderWidth, - highlightMode: highlightMode, - tooltip: tooltip, - backColor: backColor, - borderColor: borderColor, - borderStyle: borderStyle); + _helper.internal( + page, + name, + bounds, + borderWidth: borderWidth, + highlightMode: highlightMode, + tooltip: tooltip, + backColor: backColor, + borderColor: borderColor, + borderStyle: borderStyle, + ); form!.fieldAutoNaming - ? PdfAnnotationHelper.getHelper(_helper.widget!) - .dictionary! - .setProperty(PdfDictionaryProperties.ft, - PdfName(PdfDictionaryProperties.sig)) + ? PdfAnnotationHelper.getHelper( + _helper.widget!, + ).dictionary!.setProperty( + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.sig), + ) : _helper.dictionary!.setProperty( - PdfDictionaryProperties.ft, PdfName(PdfDictionaryProperties.sig)); + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.sig), + ); if (PdfPageHelper.getHelper(page).document != null) { PdfFormHelper.getHelper(form!).signatureFlags = [ SignatureFlags.signaturesExists, - SignatureFlags.appendOnly + SignatureFlags.appendOnly, ]; } if (signature != null) { @@ -172,32 +183,34 @@ class PdfSignatureField extends PdfField { PdfSignatureHelper.getHelper(_signature!).page = page; PdfSignatureHelper.getHelper(_signature!).document = PdfPageHelper.getHelper( - PdfSignatureHelper.getHelper(_signature!).page!) - .document; - PdfSignatureHelper.getHelper(_signature!) - .checkAnnotationElementsContainsSignature(page!, name); + PdfSignatureHelper.getHelper(_signature!).page!, + ).document; + PdfSignatureHelper.getHelper( + _signature!, + ).checkAnnotationElementsContainsSignature(page!, name); PdfSignatureHelper.getHelper(_signature!).field = this; PdfDocumentHelper.getHelper( - PdfSignatureHelper.getHelper(_signature!).document!) - .catalog - .beginSave = + PdfSignatureHelper.getHelper(_signature!).document!, + ).catalog.beginSave = PdfSignatureHelper.getHelper(_signature!).catalogBeginSave; _helper.dictionary!.beginSaveList ??= []; - _helper.dictionary!.beginSaveList! - .add(PdfSignatureHelper.getHelper(_signature!).dictionaryBeginSave); + _helper.dictionary!.beginSaveList!.add( + PdfSignatureHelper.getHelper(_signature!).dictionaryBeginSave, + ); if (!_helper.skipKidsCertificate) { final PdfDocument document = PdfSignatureHelper.getHelper(_signature!).document!; - PdfSignatureHelper.getHelper(_signature!).signatureDictionary = - PdfSignatureDictionary(document, _signature!); + PdfSignatureHelper.getHelper( + _signature!, + ).signatureDictionary = PdfSignatureDictionary(document, _signature!); final PdfSignatureDictionary signatureDictionary = PdfSignatureHelper.getHelper(_signature!).signatureDictionary!; if (!PdfDocumentHelper.getHelper(document).isLoadedDocument || document.fileStructure.incrementalUpdate != false) { signatureDictionary.dictionary!.archive = false; - PdfDocumentHelper.getHelper(document) - .objects - .add(signatureDictionary.element); + PdfDocumentHelper.getHelper( + document, + ).objects.add(signatureDictionary.element); PdfDocumentHelper.getHelper(document) .objects[PdfDocumentHelper.getHelper(document).objects.count - 1] .isModified = true; @@ -206,12 +219,15 @@ class PdfSignatureField extends PdfField { if (_helper.isLoadedField) { PdfFormHelper.getHelper(form!).signatureFlags = [ SignatureFlags.signaturesExists, - SignatureFlags.appendOnly + SignatureFlags.appendOnly, ]; final PdfDictionary widget = _helper.getWidgetAnnotation( - _helper.dictionary!, _helper.crossTable); - widget[PdfDictionaryProperties.v] = - PdfReferenceHolder(signatureDictionary); + _helper.dictionary!, + _helper.crossTable, + ); + widget[PdfDictionaryProperties.v] = PdfReferenceHolder( + signatureDictionary, + ); widget.modify(); _helper.changed = true; widget.setProperty(PdfDictionaryProperties.fieldFlags, PdfNumber(0)); @@ -219,14 +235,17 @@ class PdfSignatureField extends PdfField { } else { final PdfDictionary widget = PdfAnnotationHelper.getHelper(_helper.widget!).dictionary!; - widget.setProperty(PdfDictionaryProperties.v, - PdfReferenceHolder(signatureDictionary)); + widget.setProperty( + PdfDictionaryProperties.v, + PdfReferenceHolder(signatureDictionary), + ); widget.setProperty(PdfDictionaryProperties.fieldFlags, PdfNumber(0)); } } else { - PdfAnnotationHelper.getHelper(_helper.widget!) - .dictionary! - .setProperty(PdfDictionaryProperties.fieldFlags, PdfNumber(0)); + PdfAnnotationHelper.getHelper(_helper.widget!).dictionary!.setProperty( + PdfDictionaryProperties.fieldFlags, + PdfNumber(0), + ); } _helper.widget!.bounds = bounds; } @@ -244,7 +263,8 @@ class PdfSignatureField extends PdfField { String? subFilterType = ''; if (signatureDictionary.containsKey(PdfDictionaryProperties.subFilter)) { final IPdfPrimitive? filter = PdfCrossTable.dereference( - signatureDictionary[PdfDictionaryProperties.subFilter]); + signatureDictionary[PdfDictionaryProperties.subFilter], + ); if (filter != null && filter is PdfName) { subFilterType = filter.name; } @@ -254,8 +274,9 @@ class PdfSignatureField extends PdfField { } if (crossTable.document != null && !PdfDocumentHelper.getHelper(crossTable.document!).isLoadedDocument) { - if (signatureDictionary - .containsKey(PdfDictionaryProperties.reference)) { + if (signatureDictionary.containsKey( + PdfDictionaryProperties.reference, + )) { final IPdfPrimitive? tempArray = signatureDictionary[PdfDictionaryProperties.reference]; if (tempArray != null && tempArray is PdfArray) { @@ -268,15 +289,20 @@ class PdfSignatureField extends PdfField { tempDictionary[PdfDictionaryProperties.data]; if (tempReferenceHolder != null && tempReferenceHolder is PdfReferenceHolder && - !mainObjectCollection - .containsReference(tempReferenceHolder.reference!)) { - final IPdfPrimitive? tempObject = mainObjectCollection - .objectCollection![ - tempReferenceHolder.reference!.objectCollectionIndex!] - .object; + !mainObjectCollection.containsReference( + tempReferenceHolder.reference!, + )) { + final IPdfPrimitive? tempObject = + mainObjectCollection + .objectCollection![tempReferenceHolder + .reference! + .objectCollectionIndex!] + .object; tempReferenceHolder = PdfReferenceHolder(tempObject); tempDictionary.setProperty( - PdfDictionaryProperties.data, tempReferenceHolder); + PdfDictionaryProperties.data, + tempReferenceHolder, + ); } } } @@ -284,15 +310,19 @@ class PdfSignatureField extends PdfField { } signatureDictionary.remove(PdfDictionaryProperties.byteRange); PdfSignatureDictionary.fromDictionary( - crossTable.document!, signatureDictionary); + crossTable.document!, + signatureDictionary, + ); _helper.dictionary!.remove(PdfDictionaryProperties.contents); _helper.dictionary!.remove(PdfDictionaryProperties.byteRange); } if (signatureDictionary.containsKey(PdfDictionaryProperties.m) && signatureDictionary[PdfDictionaryProperties.m] is PdfString) { - PdfSignatureHelper.getHelper(_signature!).dateOfSign = - _helper.dictionary!.getDateTime( - signatureDictionary[PdfDictionaryProperties.m]! as PdfString); + PdfSignatureHelper.getHelper(_signature!).dateOfSign = _helper + .dictionary! + .getDateTime( + signatureDictionary[PdfDictionaryProperties.m]! as PdfString, + ); } if (signatureDictionary.containsKey(PdfDictionaryProperties.name) && signatureDictionary[PdfDictionaryProperties.name] is PdfString) { @@ -302,22 +332,26 @@ class PdfSignatureField extends PdfField { } if (signatureDictionary.containsKey(PdfDictionaryProperties.reason)) { final IPdfPrimitive? reason = PdfCrossTable.dereference( - signatureDictionary[PdfDictionaryProperties.reason]); + signatureDictionary[PdfDictionaryProperties.reason], + ); if (reason != null && reason is PdfString) { _signature!.reason = reason.value; } } if (signatureDictionary.containsKey(PdfDictionaryProperties.location)) { final IPdfPrimitive? location = PdfCrossTable.dereference( - signatureDictionary[PdfDictionaryProperties.location]); + signatureDictionary[PdfDictionaryProperties.location], + ); if (location != null && location is PdfString) { _signature!.locationInfo = location.value; } } - if (signatureDictionary - .containsKey(PdfDictionaryProperties.contactInfo)) { + if (signatureDictionary.containsKey( + PdfDictionaryProperties.contactInfo, + )) { final IPdfPrimitive? contactInfo = PdfCrossTable.dereference( - signatureDictionary[PdfDictionaryProperties.contactInfo]); + signatureDictionary[PdfDictionaryProperties.contactInfo], + ); if (contactInfo != null && contactInfo is PdfString) { _signature!.contactInfo = contactInfo.value; } @@ -346,10 +380,12 @@ class PdfSignatureField extends PdfField { : docPermission; if (permissionDictionary != null && permissionDictionary is PdfDictionary && - permissionDictionary - .containsKey(PdfDictionaryProperties.byteRange)) { + permissionDictionary.containsKey( + PdfDictionaryProperties.byteRange, + )) { final IPdfPrimitive? byteRange = PdfCrossTable.dereference( - permissionDictionary[PdfDictionaryProperties.byteRange]); + permissionDictionary[PdfDictionaryProperties.byteRange], + ); bool isValid = true; if (byteRange != null && byteRange is PdfArray && @@ -375,16 +411,18 @@ class PdfSignatureField extends PdfField { } } if (hasPermission && - signatureDictionary - .containsKey(PdfDictionaryProperties.reference)) { + signatureDictionary.containsKey( + PdfDictionaryProperties.reference, + )) { IPdfPrimitive? primitive = signatureDictionary[PdfDictionaryProperties.reference]; if (primitive is PdfArray) { primitive = primitive.elements[0]; } - IPdfPrimitive? reference = (primitive is PdfReferenceHolder) - ? primitive.object - : primitive; + IPdfPrimitive? reference = + (primitive is PdfReferenceHolder) + ? primitive.object + : primitive; if (reference != null && reference is PdfDictionary && reference.containsKey('TransformParams')) { @@ -398,11 +436,13 @@ class PdfSignatureField extends PdfField { reference.containsKey(PdfDictionaryProperties.p)) { final IPdfPrimitive? permissionNumber = PdfCrossTable.dereference( - reference[PdfDictionaryProperties.p]); + reference[PdfDictionaryProperties.p], + ); if (permissionNumber != null && permissionNumber is PdfNumber) { - _signature!.documentPermissions = - PdfSignatureHelper.getHelper(_signature!) - .getCertificateFlags(permissionNumber.value!.toInt()); + _signature! + .documentPermissions = PdfSignatureHelper.getHelper( + _signature!, + ).getCertificateFlags(permissionNumber.value!.toInt()); } } } @@ -434,7 +474,9 @@ class PdfSignatureFieldHelper extends PdfFieldHelper { /// internal method static PdfSignatureField loadSignatureField( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfSignatureField._(dictionary, crossTable); } @@ -448,50 +490,66 @@ class PdfSignatureFieldHelper extends PdfFieldHelper { if (!isLoadedField) { if (PdfAnnotationHelper.getHelper(widget!).appearance == null && appearance) { - PdfAnnotationHelper.getHelper(widget!).appearance = - PdfAppearance(widget!); + PdfAnnotationHelper.getHelper(widget!).appearance = PdfAppearance( + widget!, + ); PdfAnnotationHelper.getHelper(widget!).appearance!.normal = PdfTemplate( - signatureField.bounds.width, signatureField.bounds.height); + signatureField.bounds.width, + signatureField.bounds.height, + ); drawAppearance( - PdfAnnotationHelper.getHelper(widget!).appearance!.normal); + PdfAnnotationHelper.getHelper(widget!).appearance!.normal, + ); } super.draw(); if (PdfAnnotationHelper.getHelper(widget!).appearance != null) { signatureField.page!.graphics.drawPdfTemplate( - widget!.appearance.normal, signatureField.bounds.topLeft); + widget!.appearance.normal, + signatureField.bounds.topLeft, + ); } } else if (flattenField) { if (!isLoadedSign && - PdfAppearanceHelper.getHelper(signatureField.appearance) - .templateNormal != + PdfAppearanceHelper.getHelper( + signatureField.appearance, + ).templateNormal != null) { - final PdfDictionary widget = - getWidgetAnnotation(dictionary!, crossTable); + final PdfDictionary widget = getWidgetAnnotation( + dictionary!, + crossTable, + ); widget.setProperty( - PdfDictionaryProperties.ap, signatureField.appearance); + PdfDictionaryProperties.ap, + signatureField.appearance, + ); } if (dictionary![PdfDictionaryProperties.ap] != null) { final IPdfPrimitive? tempDictionary = dictionary![PdfDictionaryProperties.ap]; - final IPdfPrimitive? appearanceDictionary = - PdfCrossTable.dereference(tempDictionary); + final IPdfPrimitive? appearanceDictionary = PdfCrossTable.dereference( + tempDictionary, + ); PdfTemplate template; if (appearanceDictionary != null && appearanceDictionary is PdfDictionary) { final IPdfPrimitive? appearanceRefHolder = appearanceDictionary[PdfDictionaryProperties.n]; - final IPdfPrimitive? objectDictionary = - PdfCrossTable.dereference(appearanceRefHolder); + final IPdfPrimitive? objectDictionary = PdfCrossTable.dereference( + appearanceRefHolder, + ); if (objectDictionary != null && objectDictionary is PdfDictionary) { if (objectDictionary is PdfStream && objectDictionary.dataStream != null && objectDictionary.dataStream!.isNotEmpty && (isLoadedSign || (!isLoadedSign && !appearance))) { final PdfStream stream = objectDictionary; - template = - _drawRotatedTemplate(PdfTemplateHelper.fromPdfStream(stream)); - signatureField.page!.graphics - .drawPdfTemplate(template, signatureField.bounds.topLeft); + template = _drawRotatedTemplate( + PdfTemplateHelper.fromPdfStream(stream), + ); + signatureField.page!.graphics.drawPdfTemplate( + template, + signatureField.bounds.topLeft, + ); } else { drawRectangularControl(); } @@ -506,35 +564,54 @@ class PdfSignatureFieldHelper extends PdfFieldHelper { PdfTemplate _drawRotatedTemplate(PdfTemplate template) { final PdfStream content = PdfTemplateHelper.getHelper(template).content; if (content.containsKey(PdfDictionaryProperties.matrix)) { - final IPdfPrimitive? matrix = - PdfCrossTable.dereference(content[PdfDictionaryProperties.matrix]); + final IPdfPrimitive? matrix = PdfCrossTable.dereference( + content[PdfDictionaryProperties.matrix], + ); if (matrix != null && matrix is PdfArray) { final int angle = _obtainGraphicsRotation( - (matrix.elements[2]! as PdfNumber).value!, - (matrix.elements[0]! as PdfNumber).value!); + (matrix.elements[2]! as PdfNumber).value!, + (matrix.elements[0]! as PdfNumber).value!, + ); if (angle != 0) { PdfAnnotationHelper.setMatrixToZeroRotation(content); - final PdfTemplate rotatedTemplate = - PdfTemplate(template.size.width, template.size.height); + final PdfTemplate rotatedTemplate = PdfTemplate( + template.size.width, + template.size.height, + ); rotatedTemplate.graphics!.save(); if (angle == 90) { - rotatedTemplate.graphics! - .translateTransform(0, template.size.height); + rotatedTemplate.graphics!.translateTransform( + 0, + template.size.height, + ); rotatedTemplate.graphics!.rotateTransform(-90); - rotatedTemplate.graphics!.drawPdfTemplate(template, Offset.zero, - Size(template.size.height, template.size.width)); + rotatedTemplate.graphics!.drawPdfTemplate( + template, + Offset.zero, + Size(template.size.height, template.size.width), + ); } else if (angle == 180) { - rotatedTemplate.graphics! - .translateTransform(template.size.width, template.size.height); + rotatedTemplate.graphics!.translateTransform( + template.size.width, + template.size.height, + ); rotatedTemplate.graphics!.rotateTransform(-180); - rotatedTemplate.graphics! - .drawPdfTemplate(template, Offset.zero, template.size); + rotatedTemplate.graphics!.drawPdfTemplate( + template, + Offset.zero, + template.size, + ); } else if (angle == 270) { - rotatedTemplate.graphics! - .translateTransform(template.size.width, 0); + rotatedTemplate.graphics!.translateTransform( + template.size.width, + 0, + ); rotatedTemplate.graphics!.rotateTransform(-270); - rotatedTemplate.graphics!.drawPdfTemplate(template, Offset.zero, - Size(template.size.height, template.size.width)); + rotatedTemplate.graphics!.drawPdfTemplate( + template, + Offset.zero, + Size(template.size.height, template.size.width), + ); } rotatedTemplate.graphics!.restore(); return rotatedTemplate; @@ -566,13 +643,14 @@ class PdfSignatureFieldHelper extends PdfFieldHelper { void drawRectangularControl() { if (!isLoadedSign && appearance) { final PaintParams params = PaintParams( - bounds: signatureField.bounds, - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: signatureField.borderStyle, - borderWidth: signatureField.borderWidth, - shadowBrush: shadowBrush); + bounds: signatureField.bounds, + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: signatureField.borderStyle, + borderWidth: signatureField.borderWidth, + shadowBrush: shadowBrush, + ); FieldPainter().drawSignature(signatureField.page!.graphics, params); } } @@ -583,21 +661,32 @@ class PdfSignatureFieldHelper extends PdfFieldHelper { super.drawAppearance(template); if (appearance) { final PaintParams params = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, signatureField.bounds.width, signatureField.bounds.height), - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: signatureField.borderStyle, - borderWidth: signatureField.borderWidth, - shadowBrush: shadowBrush); + bounds: Rect.fromLTWH( + 0, + 0, + signatureField.bounds.width, + signatureField.bounds.height, + ), + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: signatureField.borderStyle, + borderWidth: signatureField.borderWidth, + shadowBrush: shadowBrush, + ); FieldPainter().drawSignature(template.graphics!, params); } else { FieldPainter().drawSignature( - template.graphics!, - PaintParams( - bounds: Rect.fromLTWH(0, 0, signatureField.bounds.width, - signatureField.bounds.height))); + template.graphics!, + PaintParams( + bounds: Rect.fromLTWH( + 0, + 0, + signatureField.bounds.width, + signatureField.bounds.height, + ), + ), + ); } } @@ -606,11 +695,14 @@ class PdfSignatureFieldHelper extends PdfFieldHelper { void beginSave() { if (!isLoadedSign && appearance && - PdfAppearanceHelper.getHelper(signatureField.appearance) - .templateNormal == + PdfAppearanceHelper.getHelper( + signatureField.appearance, + ).templateNormal == null) { signatureField.appearance.normal = PdfTemplate( - signatureField.bounds.width, signatureField.bounds.height); + signatureField.bounds.width, + signatureField.bounds.height, + ); drawAppearance(signatureField.appearance.normal); final PdfDictionary widget = getWidgetAnnotation(dictionary!, crossTable); widget.setProperty(PdfDictionaryProperties.ap, signatureField.appearance); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_text_box_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_text_box_field.dart index ce71adb51..a3616f65d 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_text_box_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_text_box_field.dart @@ -34,41 +34,59 @@ import 'pdf_form.dart'; class PdfTextBoxField extends PdfField { //Constructor /// Initializes a new instance of the [PdfTextBoxField] class with the provided page and name. - PdfTextBoxField(PdfPage page, String name, Rect bounds, - {PdfFont? font, - String? text, - String? defaultValue, - int maxLength = 0, - bool spellCheck = false, - bool insertSpaces = false, - bool multiline = false, - bool isPassword = false, - bool scrollable = false, - PdfTextAlignment alignment = PdfTextAlignment.left, - PdfColor? borderColor, - PdfColor? foreColor, - PdfColor? backColor, - int? borderWidth, - PdfHighlightMode highlightMode = PdfHighlightMode.invert, - PdfBorderStyle borderStyle = PdfBorderStyle.solid, - String? tooltip}) { + PdfTextBoxField( + PdfPage page, + String name, + Rect bounds, { + PdfFont? font, + String? text, + String? defaultValue, + int maxLength = 0, + bool spellCheck = false, + bool insertSpaces = false, + bool multiline = false, + bool isPassword = false, + bool scrollable = false, + PdfTextAlignment alignment = PdfTextAlignment.left, + PdfColor? borderColor, + PdfColor? foreColor, + PdfColor? backColor, + int? borderWidth, + PdfHighlightMode highlightMode = PdfHighlightMode.invert, + PdfBorderStyle borderStyle = PdfBorderStyle.solid, + String? tooltip, + }) { _helper = PdfTextBoxFieldHelper(this); - _helper.internal(page, name, bounds, - font: font, - alignment: alignment, - borderColor: borderColor, - foreColor: foreColor, - backColor: backColor, - borderWidth: borderWidth, - highlightMode: highlightMode, - borderStyle: borderStyle, - tooltip: tooltip); + _helper.internal( + page, + name, + bounds, + font: font, + alignment: alignment, + borderColor: borderColor, + foreColor: foreColor, + backColor: backColor, + borderWidth: borderWidth, + highlightMode: highlightMode, + borderStyle: borderStyle, + tooltip: tooltip, + ); this.font = font ?? PdfStandardFont(PdfFontFamily.helvetica, 8); - _init(text, defaultValue, maxLength, spellCheck, insertSpaces, multiline, - isPassword, scrollable); + _init( + text, + defaultValue, + maxLength, + spellCheck, + insertSpaces, + multiline, + isPassword, + scrollable, + ); _helper.flags.add(FieldFlags.doNotSpellCheck); _helper.dictionary!.setProperty( - PdfDictionaryProperties.ft, PdfName(PdfDictionaryProperties.tx)); + PdfDictionaryProperties.ft, + PdfName(PdfDictionaryProperties.tx), + ); } /// Initializes a new instance of the [PdfTextBoxField] class. @@ -81,8 +99,9 @@ class PdfTextBoxField extends PdfField { for (int i = 0; i < kids.count; ++i) { final PdfDictionary? itemDictionary = crossTable.getObject(kids[i]) as PdfDictionary?; - PdfFieldItemCollectionHelper.getHelper(_items!) - .add(PdfTextBoxItemHelper.getItem(this, i, itemDictionary)); + PdfFieldItemCollectionHelper.getHelper( + _items!, + ).add(PdfTextBoxItemHelper.getItem(this, i, itemDictionary)); } _helper.array = kids; } @@ -108,8 +127,9 @@ class PdfTextBoxField extends PdfField { final IPdfPrimitive? referenceHolder = _helper.dictionary![PdfDictionaryProperties.v]; if (referenceHolder != null && referenceHolder is PdfReferenceHolder) { - final IPdfPrimitive? textObject = - PdfCrossTable.dereference(referenceHolder); + final IPdfPrimitive? textObject = PdfCrossTable.dereference( + referenceHolder, + ); if (textObject is PdfStream) { final PdfStream stream = referenceHolder.object! as PdfStream; stream.decompress(); @@ -117,14 +137,22 @@ class PdfTextBoxField extends PdfField { final String data = utf8.decode(bytes); str = PdfString(data); } else if (textObject is PdfString) { - str = PdfFieldHelper.getValue(_helper.dictionary!, _helper.crossTable, - PdfDictionaryProperties.v, true); + str = PdfFieldHelper.getValue( + _helper.dictionary!, + _helper.crossTable, + PdfDictionaryProperties.v, + true, + ); } else { str = PdfString(''); } } else { - str = PdfFieldHelper.getValue(_helper.dictionary!, _helper.crossTable, - PdfDictionaryProperties.v, true); + str = PdfFieldHelper.getValue( + _helper.dictionary!, + _helper.crossTable, + PdfDictionaryProperties.v, + true, + ); } _text = str != null && str is PdfString ? str.value : ''; return _text!; @@ -145,18 +173,23 @@ class PdfTextBoxField extends PdfField { if (dicRef != null && dicRef is PdfReferenceHolder) { final IPdfPrimitive? dict = dicRef.object; if (dict != null && dict is PdfDictionary) { - final IPdfPrimitive? str = - PdfCrossTable.dereference(dict['JS']); + final IPdfPrimitive? str = PdfCrossTable.dereference( + dict['JS'], + ); if (str != null && str is PdfString) { _helper.dictionary!.setProperty( - PdfDictionaryProperties.v, PdfString(str.value!)); + PdfDictionaryProperties.v, + PdfString(str.value!), + ); } } } } } - _helper.dictionary! - .setProperty(PdfDictionaryProperties.v, PdfString(value)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.v, + PdfString(value), + ); _helper.changed = true; PdfFormHelper.getHelper(super.form!).setAppearanceDictionary = true; if (PdfFormHelper.getHelper(super.form!).isUR3) { @@ -183,8 +216,12 @@ class PdfTextBoxField extends PdfField { /// Gets or sets the default value. String get defaultValue { if (_helper.isLoadedField) { - final IPdfPrimitive? str = PdfFieldHelper.getValue(_helper.dictionary!, - _helper.crossTable, PdfDictionaryProperties.dv, true); + final IPdfPrimitive? str = PdfFieldHelper.getValue( + _helper.dictionary!, + _helper.crossTable, + PdfDictionaryProperties.dv, + true, + ); if (str != null && str is PdfString) { _defaultValue = str.value; } @@ -207,8 +244,12 @@ class PdfTextBoxField extends PdfField { /// The default value is 0. int get maxLength { if (_helper.isLoadedField) { - final IPdfPrimitive? number = PdfFieldHelper.getValue(_helper.dictionary!, - _helper.crossTable, PdfDictionaryProperties.maxLen, true); + final IPdfPrimitive? number = PdfFieldHelper.getValue( + _helper.dictionary!, + _helper.crossTable, + PdfDictionaryProperties.maxLen, + true, + ); if (number != null && number is PdfNumber) { _maxLength = number.value!.toInt(); } @@ -231,8 +272,9 @@ class PdfTextBoxField extends PdfField { /// The default value is false. bool get spellCheck { if (_helper.isLoadedField) { - _spellCheck = !(_helper.isFlagPresent(FieldFlags.doNotSpellCheck) || - _helper.flags.contains(FieldFlags.doNotSpellCheck)); + _spellCheck = + !(_helper.isFlagPresent(FieldFlags.doNotSpellCheck) || + _helper.flags.contains(FieldFlags.doNotSpellCheck)); } return _spellCheck; } @@ -256,12 +298,14 @@ class PdfTextBoxField extends PdfField { /// The default value is false. bool get insertSpaces { final List flags = _helper.flags; - _insertSpaces = flags.contains(FieldFlags.comb) && + _insertSpaces = + flags.contains(FieldFlags.comb) && !flags.contains(FieldFlags.multiline) && !flags.contains(FieldFlags.password) && !flags.contains(FieldFlags.fileSelect); if (_helper.isLoadedField) { - _insertSpaces = _insertSpaces || + _insertSpaces = + _insertSpaces || (_helper.isFlagPresent(FieldFlags.comb) && !_helper.isFlagPresent(FieldFlags.multiline) && !_helper.isFlagPresent(FieldFlags.password) && @@ -276,8 +320,8 @@ class PdfTextBoxField extends PdfField { _insertSpaces ? _helper.flags.add(FieldFlags.comb) : _helper.isLoadedField - ? _helper.removeFlag(FieldFlags.comb) - : _helper.flags.remove(FieldFlags.comb); + ? _helper.removeFlag(FieldFlags.comb) + : _helper.flags.remove(FieldFlags.comb); } } @@ -286,7 +330,8 @@ class PdfTextBoxField extends PdfField { /// The default value is false. bool get multiline { if (_helper.isLoadedField) { - _multiline = _helper.isFlagPresent(FieldFlags.multiline) || + _multiline = + _helper.isFlagPresent(FieldFlags.multiline) || _helper.flags.contains(FieldFlags.multiline); } return _multiline; @@ -312,7 +357,8 @@ class PdfTextBoxField extends PdfField { /// The default value is false. bool get isPassword { if (_helper.isLoadedField) { - _password = _helper.isFlagPresent(FieldFlags.password) || + _password = + _helper.isFlagPresent(FieldFlags.password) || _helper.flags.contains(FieldFlags.password); } return _password; @@ -324,8 +370,8 @@ class PdfTextBoxField extends PdfField { _password ? _helper.flags.add(FieldFlags.password) : _helper.isLoadedField - ? _helper.removeFlag(FieldFlags.password) - : _helper.flags.remove(FieldFlags.password); + ? _helper.removeFlag(FieldFlags.password) + : _helper.flags.remove(FieldFlags.password); } } @@ -334,8 +380,9 @@ class PdfTextBoxField extends PdfField { /// The default value is true. bool get scrollable { if (_helper.isLoadedField) { - _scrollable = !(_helper.isFlagPresent(FieldFlags.doNotScroll) || - _helper.flags.contains(FieldFlags.doNotScroll)); + _scrollable = + !(_helper.isFlagPresent(FieldFlags.doNotScroll) || + _helper.flags.contains(FieldFlags.doNotScroll)); } return _scrollable; } @@ -416,8 +463,16 @@ class PdfTextBoxField extends PdfField { _helper.beginSave(); } - void _init(String? text, String? defaultValue, int maxLength, bool spellCheck, - bool insertSpaces, bool multiline, bool password, bool scrollable) { + void _init( + String? text, + String? defaultValue, + int maxLength, + bool spellCheck, + bool insertSpaces, + bool multiline, + bool password, + bool scrollable, + ) { if (text != null) { this.text = text; } @@ -432,8 +487,11 @@ class PdfTextBoxField extends PdfField { this.scrollable = scrollable; } - void _drawTextBox(PdfGraphics? graphics, - {PaintParams? params, PdfFieldItem? item}) { + void _drawTextBox( + PdfGraphics? graphics, { + PaintParams? params, + PdfFieldItem? item, + }) { if (params != null) { String newText = text; if (isPassword && text.isNotEmpty) { @@ -449,73 +507,116 @@ class PdfTextBoxField extends PdfField { if (maxLength > 0) { width = params.bounds!.width / maxLength; graphics.drawRectangle( - bounds: params.bounds!, pen: _helper.borderPen); + bounds: params.bounds!, + pen: _helper.borderPen, + ); for (int i = 0; i < maxLength; i++) { if (_helper.format!.alignment != PdfTextAlignment.right) { if (_helper.format!.alignment == PdfTextAlignment.center && ch.length < maxLength) { final int startLocation = (maxLength / 2 - (ch.length / 2).ceil()).toInt(); - newText = i >= startLocation && i < startLocation + ch.length - ? ch[i - startLocation] - : ''; + newText = + i >= startLocation && i < startLocation + ch.length + ? ch[i - startLocation] + : ''; } else { newText = ch.length > i ? ch[i] : ''; } } else { - newText = maxLength - ch.length <= i - ? ch[i - (maxLength - ch.length)] - : ''; + newText = + maxLength - ch.length <= i + ? ch[i - (maxLength - ch.length)] + : ''; } - params.bounds = Rect.fromLTWH(params.bounds!.left, - params.bounds!.top, width, params.bounds!.height); + params.bounds = Rect.fromLTWH( + params.bounds!.left, + params.bounds!.top, + width, + params.bounds!.height, + ); final PdfStringFormat format = PdfStringFormat( - alignment: PdfTextAlignment.center, - lineAlignment: _helper.format!.lineAlignment); - FieldPainter().drawTextBox(graphics, params, newText, font, format, - insertSpaces, multiline); - params.bounds = Rect.fromLTWH(params.bounds!.left + width, - params.bounds!.top, width, params.bounds!.height); + alignment: PdfTextAlignment.center, + lineAlignment: _helper.format!.lineAlignment, + ); + FieldPainter().drawTextBox( + graphics, + params, + newText, + font, + format, + insertSpaces, + multiline, + ); + params.bounds = Rect.fromLTWH( + params.bounds!.left + width, + params.bounds!.top, + width, + params.bounds!.height, + ); if (params.borderWidth != 0) { graphics.drawLine( - params.borderPen!, - Offset(params.bounds!.left, params.bounds!.top), - Offset(params.bounds!.left, - params.bounds!.top + params.bounds!.height)); + params.borderPen!, + Offset(params.bounds!.left, params.bounds!.top), + Offset( + params.bounds!.left, + params.bounds!.top + params.bounds!.height, + ), + ); } } } else { - FieldPainter().drawTextBox(graphics, params, newText, font, - _helper.format!, insertSpaces, multiline); + FieldPainter().drawTextBox( + graphics, + params, + newText, + font, + _helper.format!, + insertSpaces, + multiline, + ); } } else { - FieldPainter().drawTextBox(graphics, params, newText, font, - _helper.format!, insertSpaces, multiline); + FieldPainter().drawTextBox( + graphics, + params, + newText, + font, + _helper.format!, + insertSpaces, + multiline, + ); } graphics.restore(); } else { - final GraphicsProperties gp = item != null - ? GraphicsProperties.fromFieldItem(item) - : GraphicsProperties(this); + final GraphicsProperties gp = + item != null + ? GraphicsProperties.fromFieldItem(item) + : GraphicsProperties(this); if (gp.borderWidth == 0 && gp.borderPen != null) { gp.borderWidth = 1; gp.borderPen!.width = 1; } if (PdfGraphicsHelper.getHelper(graphics!).layer == null) { - gp.bounds = Rect.fromLTWH(gp.bounds!.left, gp.bounds!.top, - graphics.size.width, graphics.size.height); + gp.bounds = Rect.fromLTWH( + gp.bounds!.left, + gp.bounds!.top, + graphics.size.width, + graphics.size.height, + ); } if (!_helper.flattenField) { gp.bounds = Rect.fromLTWH(0, 0, gp.bounds!.width, gp.bounds!.height); } final PaintParams prms = PaintParams( - bounds: gp.bounds, - backBrush: gp.backBrush, - foreBrush: gp.foreBrush, - borderPen: gp.borderPen, - style: gp.style, - borderWidth: gp.borderWidth, - shadowBrush: gp.shadowBrush); + bounds: gp.bounds, + backBrush: gp.backBrush, + foreBrush: gp.foreBrush, + borderPen: gp.borderPen, + style: gp.style, + borderWidth: gp.borderWidth, + shadowBrush: gp.shadowBrush, + ); _drawTextBox(graphics, params: prms); } } @@ -536,25 +637,40 @@ class PdfTextBoxField extends PdfField { if (angle != null && angle is PdfNumber) { if (angle.value == 90) { template = PdfTemplate(bounds.size.height, bounds.size.width); - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = - PdfArray([0, 1, -1, 0, bounds.size.width, 0]); + PdfTemplateHelper.getHelper( + template, + ).content[PdfDictionaryProperties.matrix] = PdfArray([ + 0, + 1, + -1, + 0, + bounds.size.width, + 0, + ]); } else if (angle.value == 180) { template = PdfTemplate(bounds.size.width, bounds.size.height); - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = PdfArray([ + PdfTemplateHelper.getHelper( + template, + ).content[PdfDictionaryProperties.matrix] = PdfArray([ -1, 0, 0, -1, bounds.size.width, - bounds.size.height + bounds.size.height, ]); } else if (angle.value == 270) { template = PdfTemplate(bounds.size.height, bounds.size.width); - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = - PdfArray([0, -1, 1, 0, 0, bounds.size.height]); + PdfTemplateHelper.getHelper( + template, + ).content[PdfDictionaryProperties.matrix] = PdfArray([ + 0, + -1, + 1, + 0, + 0, + bounds.size.height, + ]); } if (template != null) { PdfTemplateHelper.getHelper(template).writeTransformation = @@ -566,27 +682,31 @@ class PdfTextBoxField extends PdfField { if (template == null) { template = PdfTemplate(bounds.size.width, bounds.size.height); PdfTemplateHelper.getHelper(template).writeTransformation = false; - PdfTemplateHelper.getHelper(template) - .content[PdfDictionaryProperties.matrix] = - PdfArray([1, 0, 0, 1, 0, 0]); + PdfTemplateHelper.getHelper(template).content[PdfDictionaryProperties + .matrix] = PdfArray([1, 0, 0, 1, 0, 0]); } if (item != null) { _helper.beginMarkupSequence( - PdfGraphicsHelper.getHelper(template.graphics!) - .streamWriter! - .stream!); - PdfGraphicsHelper.getHelper(template.graphics!) - .initializeCoordinates(); + PdfGraphicsHelper.getHelper( + template.graphics!, + ).streamWriter!.stream!, + ); + PdfGraphicsHelper.getHelper( + template.graphics!, + ).initializeCoordinates(); _drawTextBox(template.graphics, item: item); _helper.endMarkupSequence( - PdfGraphicsHelper.getHelper(template.graphics!) - .streamWriter! - .stream!); + PdfGraphicsHelper.getHelper( + template.graphics!, + ).streamWriter!.stream!, + ); } else { _helper.drawAppearance(template); } appearance.setProperty( - PdfDictionaryProperties.n, PdfReferenceHolder(template)); + PdfDictionaryProperties.n, + PdfReferenceHolder(template), + ); widget.setProperty(PdfDictionaryProperties.ap, appearance); } else { PdfFormHelper.getHelper(super.form!).needAppearances = true; @@ -616,7 +736,9 @@ class PdfTextBoxFieldHelper extends PdfFieldHelper { /// internal method static PdfTextBoxField loadTextBox( - PdfDictionary dictionary, PdfCrossTable crossTable) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + ) { return PdfTextBoxField._load(dictionary, crossTable); } @@ -638,18 +760,24 @@ class PdfTextBoxFieldHelper extends PdfFieldHelper { void drawAppearance(PdfTemplate template) { super.drawAppearance(template); final PaintParams params = PaintParams( - bounds: Rect.fromLTWH( - 0, 0, textBoxField.bounds.width, textBoxField.bounds.height), - backBrush: backBrush, - foreBrush: foreBrush, - borderPen: borderPen, - style: textBoxField.borderStyle, - borderWidth: textBoxField.borderWidth, - shadowBrush: shadowBrush); + bounds: Rect.fromLTWH( + 0, + 0, + textBoxField.bounds.width, + textBoxField.bounds.height, + ), + backBrush: backBrush, + foreBrush: foreBrush, + borderPen: borderPen, + style: textBoxField.borderStyle, + borderWidth: textBoxField.borderWidth, + shadowBrush: shadowBrush, + ); PdfTemplateHelper.getHelper(template).writeTransformation = false; final PdfGraphics graphics = template.graphics!; beginMarkupSequence( - PdfGraphicsHelper.getHelper(graphics).streamWriter!.stream!); + PdfGraphicsHelper.getHelper(graphics).streamWriter!.stream!, + ); PdfGraphicsHelper.getHelper(graphics).initializeCoordinates(); if (params.borderWidth == 0 && params.borderPen != null) { params.borderWidth = 1; @@ -657,7 +785,8 @@ class PdfTextBoxFieldHelper extends PdfFieldHelper { } textBoxField._drawTextBox(graphics, params: params); endMarkupSequence( - PdfGraphicsHelper.getHelper(graphics).streamWriter!.stream!); + PdfGraphicsHelper.getHelper(graphics).streamWriter!.stream!, + ); } /// internal method @@ -671,8 +800,9 @@ class PdfTextBoxFieldHelper extends PdfFieldHelper { textBoxField._applyAppearance(widget, textBoxField.items![i]); } } else { - textBoxField - ._applyAppearance(getWidgetAnnotation(dictionary!, crossTable)); + textBoxField._applyAppearance( + getWidgetAnnotation(dictionary!, crossTable), + ); } } @@ -683,7 +813,8 @@ class PdfTextBoxFieldHelper extends PdfFieldHelper { if (!textBoxField.multiline) { final PdfStandardFont font = PdfStandardFont(family, 12); final Size fontSize = font.measureString(textBoxField.text); - s = (8 * + s = + (8 * (textBoxField.bounds.size.width - 4 * textBoxField.borderWidth)) / fontSize.width; s = (s > 8) ? 8 : s; @@ -700,17 +831,19 @@ class PdfTextBoxFieldHelper extends PdfFieldHelper { if (!isLoadedField && PdfAnnotationHelper.getHelper(widget!).appearance != null) { textBoxField.page!.graphics.drawPdfTemplate( - PdfAnnotationHelper.getHelper(widget!).appearance!.normal, - Offset(textBoxField.bounds.width, textBoxField.bounds.height)); + PdfAnnotationHelper.getHelper(widget!).appearance!.normal, + Offset(textBoxField.bounds.width, textBoxField.bounds.height), + ); if (fieldItems != null && fieldItems!.length > 1) { for (int i = 1; i < fieldItems!.length; i++) { final PdfTextBoxField field = fieldItems![i] as PdfTextBoxField; field.text = textBoxField.text; field.page!.graphics.drawPdfTemplate( - PdfAnnotationHelper.getHelper(field._helper.widget!) - .appearance! - .normal, - Offset(field.bounds.width, field.bounds.height)); + PdfAnnotationHelper.getHelper( + field._helper.widget!, + ).appearance!.normal, + Offset(field.bounds.width, field.bounds.height), + ); } } } else { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_xfdf_document.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_xfdf_document.dart index 3f2fce07a..ef26ebe75 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_xfdf_document.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/forms/pdf_xfdf_document.dart @@ -44,21 +44,31 @@ class XFdfDocument { List xmlData; final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0" encoding="utf-8"'); - builder.element(PdfDictionaryProperties.xfdf.toLowerCase(), nest: () { - builder.attribute('xmlns', 'http://ns.adobe.com/xfdf/'); - builder.attribute('xml:space', 'preserve'); - if (annotationData != null && annotationData.isNotEmpty) { - builder.element(PdfDictionaryProperties.annots.toLowerCase(), - nest: annotationData); - } else { - builder.element(PdfDictionaryProperties.fields.toLowerCase(), - nest: _writeFormData()); - } - builder.element('f', nest: () { - // ignore: unnecessary_null_checks - builder.attribute('href', _pdfFilePath!); - }); - }); + builder.element( + PdfDictionaryProperties.xfdf.toLowerCase(), + nest: () { + builder.attribute('xmlns', 'http://ns.adobe.com/xfdf/'); + builder.attribute('xml:space', 'preserve'); + if (annotationData != null && annotationData.isNotEmpty) { + builder.element( + PdfDictionaryProperties.annots.toLowerCase(), + nest: annotationData, + ); + } else { + builder.element( + PdfDictionaryProperties.fields.toLowerCase(), + nest: _writeFormData(), + ); + } + builder.element( + 'f', + nest: () { + // ignore: unnecessary_null_checks + builder.attribute('href', _pdfFilePath!); + }, + ); + }, + ); xmlData = utf8.encode(builder.buildDocument().toXmlString(pretty: true)); return xmlData; } @@ -66,24 +76,35 @@ class XFdfDocument { List _writeFormData() { final List elements = []; _table.forEach((Object key, Object value) { - final XmlElement xmlElement = - XmlElement(XmlName(PdfDictionaryProperties.field.toLowerCase())); - xmlElement.attributes.add(XmlAttribute( - XmlName(PdfDictionaryProperties.name.toLowerCase()), key.toString())); + final XmlElement xmlElement = XmlElement( + XmlName(PdfDictionaryProperties.field.toLowerCase()), + ); + xmlElement.attributes.add( + XmlAttribute( + XmlName(PdfDictionaryProperties.name.toLowerCase()), + key.toString(), + ), + ); if (value is PdfArray) { for (final IPdfPrimitive? str in value.elements) { if (str is PdfString) { - xmlElement.children.add(XmlElement( + xmlElement.children.add( + XmlElement( XmlName(PdfDictionaryProperties.value.toLowerCase()), [], - [XmlText(str.value.toString())])); + [XmlText(str.value.toString())], + ), + ); } } } else { - xmlElement.children.add(XmlElement( + xmlElement.children.add( + XmlElement( XmlName(PdfDictionaryProperties.value.toLowerCase()), [], - [XmlText(value.toString())])); + [XmlText(value.toString())], + ), + ); } elements.add(xmlElement); }); @@ -91,31 +112,43 @@ class XFdfDocument { } /// internal method - XmlElement? exportAnnotationData(PdfDictionary annotationDictionary, - int pageIndex, bool exportAppearance, PdfDocument document) { + XmlElement? exportAnnotationData( + PdfDictionary annotationDictionary, + int pageIndex, + bool exportAppearance, + PdfDocument document, + ) { _document = document; if (!PdfDocumentHelper.isLinkAnnotation(annotationDictionary)) { return _writeAnnotationData( - pageIndex, exportAppearance, annotationDictionary); + pageIndex, + exportAppearance, + annotationDictionary, + ); } return null; } - XmlElement? _writeAnnotationData(int pageIndex, bool exportAppearance, - PdfDictionary annotationDictionary) { + XmlElement? _writeAnnotationData( + int pageIndex, + bool exportAppearance, + PdfDictionary annotationDictionary, + ) { XmlElement? element; final String? type = _getAnnotationType(annotationDictionary); _skipBorderStyle = false; if (type != null && type.isNotEmpty) { _annotationAttributes ??= []; element = XmlElement(XmlName(type.toLowerCase())); - element.attributes - .add(XmlAttribute(XmlName('page'), pageIndex.toString())); + element.attributes.add( + XmlAttribute(XmlName('page'), pageIndex.toString()), + ); switch (type) { case PdfDictionaryProperties.line: if (annotationDictionary.containsKey(PdfDictionaryProperties.l)) { final IPdfPrimitive? linePoints = PdfCrossTable.dereference( - annotationDictionary[PdfDictionaryProperties.l]); + annotationDictionary[PdfDictionaryProperties.l], + ); if (linePoints != null && linePoints is PdfArray && linePoints.count == 4 && @@ -127,10 +160,18 @@ class XFdfDocument { linePoints[2] is PdfNumber && linePoints[3] != null && linePoints[3] is PdfNumber) { - element.attributes.add(XmlAttribute(XmlName('start'), - '${(linePoints[0]! as PdfNumber).value},${(linePoints[1]! as PdfNumber).value}')); - element.attributes.add(XmlAttribute(XmlName('end'), - '${(linePoints[2]! as PdfNumber).value},${(linePoints[3]! as PdfNumber).value}')); + element.attributes.add( + XmlAttribute( + XmlName('start'), + '${(linePoints[0]! as PdfNumber).value},${(linePoints[1]! as PdfNumber).value}', + ), + ); + element.attributes.add( + XmlAttribute( + XmlName('end'), + '${(linePoints[2]! as PdfNumber).value},${(linePoints[3]! as PdfNumber).value}', + ), + ); } } break; @@ -152,7 +193,8 @@ class XFdfDocument { if (annotationDictionary.containsKey(PdfDictionaryProperties.be) && annotationDictionary.containsKey(PdfDictionaryProperties.bs)) { final IPdfPrimitive? borderEffect = PdfCrossTable.dereference( - annotationDictionary[PdfDictionaryProperties.be]); + annotationDictionary[PdfDictionaryProperties.be], + ); if (borderEffect != null && borderEffect is PdfDictionary && borderEffect.containsKey(PdfDictionaryProperties.s)) { @@ -160,7 +202,11 @@ class XFdfDocument { } } _writeDictionary( - annotationDictionary, pageIndex, element, exportAppearance); + annotationDictionary, + pageIndex, + element, + exportAppearance, + ); _annotationAttributes!.clear(); if (_isStampAnnotation) { _isStampAnnotation = false; @@ -169,12 +215,17 @@ class XFdfDocument { return element; } - void _writeDictionary(PdfDictionary dictionary, int pageIndex, - XmlElement element, bool exportAppearance) { + void _writeDictionary( + PdfDictionary dictionary, + int pageIndex, + XmlElement element, + bool exportAppearance, + ) { bool isBSdictionary = false; if (dictionary.containsKey(PdfDictionaryProperties.type)) { - final IPdfPrimitive? name = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.type]); + final IPdfPrimitive? name = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.type], + ); if (name != null && name is PdfName && name.name == PdfDictionaryProperties.border && @@ -201,7 +252,8 @@ class XFdfDocument { case PdfDictionaryProperties.irt: if (obj.containsKey('NM')) { element.attributes.add( - XmlAttribute(XmlName('inreplyto'), _getValue(obj['NM']))); + XmlAttribute(XmlName('inreplyto'), _getValue(obj['NM'])), + ); } break; } @@ -216,13 +268,17 @@ class XFdfDocument { }); if (exportAppearance && dictionary.containsKey(PdfDictionaryProperties.ap)) { - final IPdfPrimitive? appearance = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.ap]); + final IPdfPrimitive? appearance = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.ap], + ); if (appearance != null && appearance is PdfDictionary) { final List elements = _getAppearanceString(appearance); if (elements.isNotEmpty) { - element.children.add(XmlElement(XmlName('appearance'), - [], [XmlText(base64.encode(elements))])); + element.children.add( + XmlElement(XmlName('appearance'), [], [ + XmlText(base64.encode(elements)), + ]), + ); } } } @@ -230,119 +286,176 @@ class XFdfDocument { element.children.add(_exportMeasureDictionary(dictionary)); } if (dictionary.containsKey('Sound')) { - final IPdfPrimitive? sound = - PdfCrossTable.dereference(dictionary['Sound']); + final IPdfPrimitive? sound = PdfCrossTable.dereference( + dictionary['Sound'], + ); if (sound != null && sound is PdfStream) { if (sound.containsKey('B')) { - element.attributes - .add(XmlAttribute(XmlName('bits'), _getValue(sound['B']))); + element.attributes.add( + XmlAttribute(XmlName('bits'), _getValue(sound['B'])), + ); } if (sound.containsKey(PdfDictionaryProperties.c)) { - element.attributes.add(XmlAttribute(XmlName('channels'), - _getValue(sound[PdfDictionaryProperties.c]))); + element.attributes.add( + XmlAttribute( + XmlName('channels'), + _getValue(sound[PdfDictionaryProperties.c]), + ), + ); } if (sound.containsKey(PdfDictionaryProperties.e)) { - element.attributes.add(XmlAttribute(XmlName('encoding'), - _getValue(sound[PdfDictionaryProperties.e]))); + element.attributes.add( + XmlAttribute( + XmlName('encoding'), + _getValue(sound[PdfDictionaryProperties.e]), + ), + ); } if (sound.containsKey(PdfDictionaryProperties.r)) { - element.attributes.add(XmlAttribute( - XmlName('rate'), _getValue(sound[PdfDictionaryProperties.r]))); + element.attributes.add( + XmlAttribute( + XmlName('rate'), + _getValue(sound[PdfDictionaryProperties.r]), + ), + ); } if (sound.dataStream != null && sound.dataStream!.isNotEmpty) { final String data = PdfString.bytesToHex(sound.dataStream!); if (!isNullOrEmpty(data)) { - element.children.add(XmlElement( - XmlName(XfdfProperties.data.toLowerCase()), [ - XmlAttribute(XmlName(XfdfProperties.mode), 'raw'), - XmlAttribute( - XmlName(PdfDictionaryProperties.encoding.toLowerCase()), - 'hex'), - if (sound.containsKey(PdfDictionaryProperties.length)) - XmlAttribute( - XmlName(PdfDictionaryProperties.length.toLowerCase()), - _getValue(sound[PdfDictionaryProperties.length])), - if (sound.containsKey(PdfDictionaryProperties.filter)) - XmlAttribute(XmlName(PdfDictionaryProperties.filter), - _getValue(sound[PdfDictionaryProperties.filter])) - ], [ - XmlText(data) - ])); + element.children.add( + XmlElement( + XmlName(XfdfProperties.data.toLowerCase()), + [ + XmlAttribute(XmlName(XfdfProperties.mode), 'raw'), + XmlAttribute( + XmlName(PdfDictionaryProperties.encoding.toLowerCase()), + 'hex', + ), + if (sound.containsKey(PdfDictionaryProperties.length)) + XmlAttribute( + XmlName(PdfDictionaryProperties.length.toLowerCase()), + _getValue(sound[PdfDictionaryProperties.length]), + ), + if (sound.containsKey(PdfDictionaryProperties.filter)) + XmlAttribute( + XmlName(PdfDictionaryProperties.filter), + _getValue(sound[PdfDictionaryProperties.filter]), + ), + ], + [XmlText(data)], + ), + ); } } } } else if (dictionary.containsKey(PdfDictionaryProperties.fs)) { - final IPdfPrimitive? fsDictionary = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.fs]); + final IPdfPrimitive? fsDictionary = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.fs], + ); if (fsDictionary != null && fsDictionary is PdfDictionary) { if (fsDictionary.containsKey(PdfDictionaryProperties.f)) { - element.attributes.add(XmlAttribute(XmlName('file'), - _getValue(fsDictionary[PdfDictionaryProperties.f]))); + element.attributes.add( + XmlAttribute( + XmlName('file'), + _getValue(fsDictionary[PdfDictionaryProperties.f]), + ), + ); } if (fsDictionary.containsKey(PdfDictionaryProperties.ef)) { final IPdfPrimitive? efDictionary = PdfCrossTable.dereference( - fsDictionary[PdfDictionaryProperties.ef]); + fsDictionary[PdfDictionaryProperties.ef], + ); if (efDictionary != null && efDictionary is PdfDictionary && efDictionary.containsKey(PdfDictionaryProperties.f)) { final IPdfPrimitive? fStream = PdfCrossTable.dereference( - efDictionary[PdfDictionaryProperties.f]); + efDictionary[PdfDictionaryProperties.f], + ); if (fStream != null && fStream is PdfStream) { if (fStream.containsKey(PdfDictionaryProperties.params)) { final IPdfPrimitive? paramsDictionary = PdfCrossTable.dereference( - fStream[PdfDictionaryProperties.params]); + fStream[PdfDictionaryProperties.params], + ); if (paramsDictionary != null && paramsDictionary is PdfDictionary) { - if (paramsDictionary - .containsKey(PdfDictionaryProperties.creationDate)) { - element.attributes.add(XmlAttribute( + if (paramsDictionary.containsKey( + PdfDictionaryProperties.creationDate, + )) { + element.attributes.add( + XmlAttribute( XmlName('creation'), - _getValue(paramsDictionary[ - PdfDictionaryProperties.creationDate]))); + _getValue( + paramsDictionary[PdfDictionaryProperties + .creationDate], + ), + ), + ); } - if (paramsDictionary - .containsKey(PdfDictionaryProperties.modificationDate)) { - element.attributes.add(XmlAttribute( + if (paramsDictionary.containsKey( + PdfDictionaryProperties.modificationDate, + )) { + element.attributes.add( + XmlAttribute( XmlName('modification'), - _getValue(paramsDictionary[ - PdfDictionaryProperties.modificationDate]))); + _getValue( + paramsDictionary[PdfDictionaryProperties + .modificationDate], + ), + ), + ); } - if (paramsDictionary - .containsKey(PdfDictionaryProperties.size)) { - element.attributes.add(XmlAttribute( + if (paramsDictionary.containsKey( + PdfDictionaryProperties.size, + )) { + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.size.toLowerCase()), _getValue( - paramsDictionary[PdfDictionaryProperties.size]))); + paramsDictionary[PdfDictionaryProperties.size], + ), + ), + ); } if (paramsDictionary.containsKey('CheckSum')) { - final List checksum = - utf8.encode(_getValue(paramsDictionary['CheckSum'])); + final List checksum = utf8.encode( + _getValue(paramsDictionary['CheckSum']), + ); final String hexString = PdfString.bytesToHex(checksum); - element.attributes - .add(XmlAttribute(XmlName('checksum'), hexString)); + element.attributes.add( + XmlAttribute(XmlName('checksum'), hexString), + ); } } } final String data = PdfString.bytesToHex(fStream.dataStream!); if (!isNullOrEmpty(data)) { - element.children.add(XmlElement( - XmlName(XfdfProperties.data.toLowerCase()), [ - XmlAttribute(XmlName(XfdfProperties.mode), - XfdfProperties.raw.toLowerCase()), - XmlAttribute( - XmlName(PdfDictionaryProperties.encoding.toLowerCase()), - XfdfProperties.hex.toLowerCase()), - if (fStream.containsKey(PdfDictionaryProperties.length)) - XmlAttribute( - XmlName(PdfDictionaryProperties.length.toLowerCase()), - _getValue(fStream[PdfDictionaryProperties.length])), - if (fStream.containsKey(PdfDictionaryProperties.filter)) - XmlAttribute(XmlName(PdfDictionaryProperties.filter), - _getValue(fStream[PdfDictionaryProperties.filter])) - ], [ - XmlText(data) - ])); + element.children.add( + XmlElement( + XmlName(XfdfProperties.data.toLowerCase()), + [ + XmlAttribute( + XmlName(XfdfProperties.mode), + XfdfProperties.raw.toLowerCase(), + ), + XmlAttribute( + XmlName(PdfDictionaryProperties.encoding.toLowerCase()), + XfdfProperties.hex.toLowerCase(), + ), + if (fStream.containsKey(PdfDictionaryProperties.length)) + XmlAttribute( + XmlName(PdfDictionaryProperties.length.toLowerCase()), + _getValue(fStream[PdfDictionaryProperties.length]), + ), + if (fStream.containsKey(PdfDictionaryProperties.filter)) + XmlAttribute( + XmlName(PdfDictionaryProperties.filter), + _getValue(fStream[PdfDictionaryProperties.filter]), + ), + ], + [XmlText(data)], + ), + ); } } } @@ -350,10 +463,12 @@ class XFdfDocument { } } if (dictionary.containsKey(PdfDictionaryProperties.vertices)) { - final XmlElement verticesElement = - XmlElement(XmlName(PdfDictionaryProperties.vertices.toLowerCase())); + final XmlElement verticesElement = XmlElement( + XmlName(PdfDictionaryProperties.vertices.toLowerCase()), + ); final IPdfPrimitive? vertices = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.vertices]); + dictionary[PdfDictionaryProperties.vertices], + ); if (vertices != null && vertices is PdfArray && vertices.count > 0) { final int elementCount = vertices.count; if (elementCount.isEven) { @@ -377,54 +492,73 @@ class XFdfDocument { element.children.add(verticesElement); } if (dictionary.containsKey(PdfDictionaryProperties.popup)) { - final IPdfPrimitive? popup = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.popup]); + final IPdfPrimitive? popup = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.popup], + ); if (popup != null && popup is PdfDictionary) { - final XmlElement? popupElement = - _writeAnnotationData(pageIndex, exportAppearance, popup); + final XmlElement? popupElement = _writeAnnotationData( + pageIndex, + exportAppearance, + popup, + ); if (popupElement != null) { element.children.add(popupElement); } } } if (dictionary.containsKey(PdfDictionaryProperties.da)) { - final IPdfPrimitive? defaultAppearance = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.da]); + final IPdfPrimitive? defaultAppearance = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.da], + ); if (defaultAppearance != null && defaultAppearance is PdfString) { if (!isNullOrEmpty(defaultAppearance.value)) { - element.children.add(XmlElement(XmlName('defaultappearance'), - [], [XmlText(defaultAppearance.value!)])); + element.children.add( + XmlElement( + XmlName('defaultappearance'), + [], + [XmlText(defaultAppearance.value!)], + ), + ); } } } if (dictionary.containsKey('DS')) { - final IPdfPrimitive? defaultStyle = - PdfCrossTable.dereference(dictionary['DS']); + final IPdfPrimitive? defaultStyle = PdfCrossTable.dereference( + dictionary['DS'], + ); if (defaultStyle != null && defaultStyle is PdfString) { if (!isNullOrEmpty(defaultStyle.value)) { - element.children.add(XmlElement(XmlName('defaultstyle'), - [], [XmlText(defaultStyle.value!)])); + element.children.add( + XmlElement(XmlName('defaultstyle'), [], [ + XmlText(defaultStyle.value!), + ]), + ); } } } if (dictionary.containsKey('InkList')) { - final IPdfPrimitive? inkList = - PdfCrossTable.dereference(dictionary['InkList']); + final IPdfPrimitive? inkList = PdfCrossTable.dereference( + dictionary['InkList'], + ); if (inkList != null && inkList is PdfArray && inkList.count > 0) { final XmlElement inkListElement = XmlElement(XmlName('inkList')); for (int j = 0; j < inkList.count; j++) { final IPdfPrimitive? list = PdfCrossTable.dereference(inkList[j]); if (list != null && list is PdfArray) { - inkListElement.children.add(XmlElement(XmlName('gesture'), - [], [XmlText(_getValue(list))])); + inkListElement.children.add( + XmlElement(XmlName('gesture'), [], [ + XmlText(_getValue(list)), + ]), + ); } } element.children.add(inkListElement); } } if (dictionary.containsKey('RC')) { - final IPdfPrimitive? contents = - PdfCrossTable.dereference(dictionary['RC']); + final IPdfPrimitive? contents = PdfCrossTable.dereference( + dictionary['RC'], + ); if (contents != null && contents is PdfString) { String? value = contents.value; if (!isNullOrEmpty(value)) { @@ -432,18 +566,27 @@ class XFdfDocument { if (index > 0) { value = value.substring(index); } - element.children.add(XmlElement(XmlName('contents-richtext'), - [], [XmlText(value)])); + element.children.add( + XmlElement( + XmlName('contents-richtext'), + [], + [XmlText(value)], + ), + ); } } } if (dictionary.containsKey(PdfDictionaryProperties.contents)) { final IPdfPrimitive? contents = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.contents]); + dictionary[PdfDictionaryProperties.contents], + ); if (contents != null && contents is PdfString) { if (!isNullOrEmpty(contents.value)) { - element.children.add(XmlElement(XmlName('contents'), [], - [XmlText(contents.value!)])); + element.children.add( + XmlElement(XmlName('contents'), [], [ + XmlText(contents.value!), + ]), + ); } } } @@ -453,22 +596,28 @@ class XFdfDocument { String color = ''; final PdfArray colorArray = primitive as PdfArray; if (colorArray.count >= 3) { - final String r = PdfString.bytesToHex([ - ((colorArray.elements[0]! as PdfNumber).value! * 255).round() - ]).toUpperCase(); - final String g = PdfString.bytesToHex([ - ((colorArray.elements[1]! as PdfNumber).value! * 255).round() - ]).toUpperCase(); - final String b = PdfString.bytesToHex([ - ((colorArray.elements[2]! as PdfNumber).value! * 255).round() - ]).toUpperCase(); + final String r = + PdfString.bytesToHex([ + ((colorArray.elements[0]! as PdfNumber).value! * 255).round(), + ]).toUpperCase(); + final String g = + PdfString.bytesToHex([ + ((colorArray.elements[1]! as PdfNumber).value! * 255).round(), + ]).toUpperCase(); + final String b = + PdfString.bytesToHex([ + ((colorArray.elements[2]! as PdfNumber).value! * 255).round(), + ]).toUpperCase(); color = '#$r$g$b'; } return color; } void _writeAttribute( - XmlElement element, String key, IPdfPrimitive primitive) { + XmlElement element, + String key, + IPdfPrimitive primitive, + ) { if (_annotationAttributes != null && !_annotationAttributes!.contains(key)) { switch (key) { @@ -491,92 +640,120 @@ class XFdfDocument { final String interiorColor = _getColor(primitive); if (!isNullOrEmpty(interiorColor) && !_annotationAttributes!.contains('interior-color')) { - element.attributes - .add(XmlAttribute(XmlName('interior-color'), interiorColor)); + element.attributes.add( + XmlAttribute(XmlName('interior-color'), interiorColor), + ); _annotationAttributes!.add('interior-color'); } break; case PdfDictionaryProperties.m: if (!_annotationAttributes!.contains('date')) { - element.attributes - .add(XmlAttribute(XmlName('date'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('date'), _getValue(primitive)), + ); _annotationAttributes!.add('date'); } break; case 'NM': - if (!_annotationAttributes! - .contains(PdfDictionaryProperties.name.toLowerCase())) { - element.attributes.add(XmlAttribute( + if (!_annotationAttributes!.contains( + PdfDictionaryProperties.name.toLowerCase(), + )) { + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.name.toLowerCase()), - _getValue(primitive))); - _annotationAttributes! - .add(PdfDictionaryProperties.name.toLowerCase()); + _getValue(primitive), + ), + ); + _annotationAttributes!.add( + PdfDictionaryProperties.name.toLowerCase(), + ); } break; case PdfDictionaryProperties.name: if (!_annotationAttributes!.contains('icon')) { - element.attributes - .add(XmlAttribute(XmlName('icon'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('icon'), _getValue(primitive)), + ); _annotationAttributes!.add('icon'); } break; case PdfDictionaryProperties.subj: - if (!_annotationAttributes! - .contains(PdfDictionaryProperties.subject.toLowerCase())) { - element.attributes.add(XmlAttribute( + if (!_annotationAttributes!.contains( + PdfDictionaryProperties.subject.toLowerCase(), + )) { + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.subject.toLowerCase()), - _getValue(primitive))); - _annotationAttributes! - .add(PdfDictionaryProperties.subject.toLowerCase()); + _getValue(primitive), + ), + ); + _annotationAttributes!.add( + PdfDictionaryProperties.subject.toLowerCase(), + ); } break; case PdfDictionaryProperties.t: - if (!_annotationAttributes! - .contains(PdfDictionaryProperties.title.toLowerCase())) { - element.attributes.add(XmlAttribute( + if (!_annotationAttributes!.contains( + PdfDictionaryProperties.title.toLowerCase(), + )) { + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.title.toLowerCase()), - _getValue(primitive))); - _annotationAttributes! - .add(PdfDictionaryProperties.title.toLowerCase()); + _getValue(primitive), + ), + ); + _annotationAttributes!.add( + PdfDictionaryProperties.title.toLowerCase(), + ); } break; case PdfDictionaryProperties.rect: case PdfDictionaryProperties.creationDate: if (!_annotationAttributes!.contains(key.toLowerCase())) { element.attributes.add( - XmlAttribute(XmlName(key.toLowerCase()), _getValue(primitive))); + XmlAttribute(XmlName(key.toLowerCase()), _getValue(primitive)), + ); _annotationAttributes!.add(key.toLowerCase()); } break; case PdfDictionaryProperties.rotate: if (!_annotationAttributes!.contains('rotation')) { - element.attributes - .add(XmlAttribute(XmlName('rotation'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('rotation'), _getValue(primitive)), + ); _annotationAttributes!.add('rotation'); } break; case PdfDictionaryProperties.w: - if (!_annotationAttributes! - .contains(PdfDictionaryProperties.width.toLowerCase())) { - element.attributes.add(XmlAttribute( + if (!_annotationAttributes!.contains( + PdfDictionaryProperties.width.toLowerCase(), + )) { + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.width.toLowerCase()), - _getValue(primitive))); - _annotationAttributes! - .add(PdfDictionaryProperties.width.toLowerCase()); + _getValue(primitive), + ), + ); + _annotationAttributes!.add( + PdfDictionaryProperties.width.toLowerCase(), + ); } break; case PdfDictionaryProperties.le: if (primitive is PdfArray) { if (primitive.count == 2) { - element.attributes.add(XmlAttribute( - XmlName('head'), _getValue(primitive.elements[0]))); - element.attributes.add(XmlAttribute( - XmlName('tail'), _getValue(primitive.elements[1]))); + element.attributes.add( + XmlAttribute(XmlName('head'), _getValue(primitive.elements[0])), + ); + element.attributes.add( + XmlAttribute(XmlName('tail'), _getValue(primitive.elements[1])), + ); } } else if (primitive is PdfName && !_annotationAttributes!.contains('head')) { - element.attributes - .add(XmlAttribute(XmlName('head'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('head'), _getValue(primitive)), + ); _annotationAttributes!.add('head'); } break; @@ -587,22 +764,25 @@ class XFdfDocument { element.attributes.add(XmlAttribute(XmlName('style'), 'dash')); break; case PdfDictionaryProperties.c: - element.attributes - .add(XmlAttribute(XmlName('style'), 'cloudy')); + element.attributes.add( + XmlAttribute(XmlName('style'), 'cloudy'), + ); break; case PdfDictionaryProperties.s: element.attributes.add(XmlAttribute(XmlName('style'), 'solid')); break; case 'B': - element.attributes - .add(XmlAttribute(XmlName('style'), 'bevelled')); + element.attributes.add( + XmlAttribute(XmlName('style'), 'bevelled'), + ); break; case PdfDictionaryProperties.i: element.attributes.add(XmlAttribute(XmlName('style'), 'inset')); break; case PdfDictionaryProperties.u: - element.attributes - .add(XmlAttribute(XmlName('style'), 'underline')); + element.attributes.add( + XmlAttribute(XmlName('style'), 'underline'), + ); break; } _annotationAttributes!.add('style'); @@ -610,119 +790,143 @@ class XFdfDocument { break; case PdfDictionaryProperties.d: if (!_annotationAttributes!.contains('dashes')) { - element.attributes - .add(XmlAttribute(XmlName('dashes'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('dashes'), _getValue(primitive)), + ); _annotationAttributes!.add('dashes'); } break; case PdfDictionaryProperties.i: if (!_annotationAttributes!.contains('intensity')) { - element.attributes - .add(XmlAttribute(XmlName('intensity'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('intensity'), _getValue(primitive)), + ); _annotationAttributes!.add('intensity'); } break; case PdfDictionaryProperties.rd: if (!_annotationAttributes!.contains('fringe')) { - element.attributes - .add(XmlAttribute(XmlName('fringe'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('fringe'), _getValue(primitive)), + ); _annotationAttributes!.add('fringe'); } break; case PdfDictionaryProperties.it: if (!_annotationAttributes!.contains(key)) { - element.attributes - .add(XmlAttribute(XmlName(key), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName(key), _getValue(primitive)), + ); _annotationAttributes!.add(key); } break; case 'RT': if (!_annotationAttributes!.contains('replyType')) { - element.attributes.add(XmlAttribute( - XmlName('replyType'), _getValue(primitive).toLowerCase())); + element.attributes.add( + XmlAttribute( + XmlName('replyType'), + _getValue(primitive).toLowerCase(), + ), + ); _annotationAttributes!.add('replyType'); } break; case PdfDictionaryProperties.ll: if (!_annotationAttributes!.contains('leaderLength')) { element.attributes.add( - XmlAttribute(XmlName('leaderLength'), _getValue(primitive))); + XmlAttribute(XmlName('leaderLength'), _getValue(primitive)), + ); _annotationAttributes!.add('leaderLength'); } break; case PdfDictionaryProperties.lle: if (!_annotationAttributes!.contains('leaderExtend')) { element.attributes.add( - XmlAttribute(XmlName('leaderExtend'), _getValue(primitive))); + XmlAttribute(XmlName('leaderExtend'), _getValue(primitive)), + ); _annotationAttributes!.add('leaderExtend'); } break; case PdfDictionaryProperties.cap: if (!_annotationAttributes!.contains('caption')) { - element.attributes - .add(XmlAttribute(XmlName('caption'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('caption'), _getValue(primitive)), + ); _annotationAttributes!.add('caption'); } break; case PdfDictionaryProperties.q: if (!_annotationAttributes!.contains('justification')) { element.attributes.add( - XmlAttribute(XmlName('justification'), _getValue(primitive))); + XmlAttribute(XmlName('justification'), _getValue(primitive)), + ); _annotationAttributes!.add('justification'); } break; case PdfDictionaryProperties.cp: if (!_annotationAttributes!.contains('caption-style')) { element.attributes.add( - XmlAttribute(XmlName('caption-style'), _getValue(primitive))); + XmlAttribute(XmlName('caption-style'), _getValue(primitive)), + ); _annotationAttributes!.add('caption-style'); } break; case 'CL': if (!_annotationAttributes!.contains('callout')) { - element.attributes - .add(XmlAttribute(XmlName('callout'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('callout'), _getValue(primitive)), + ); _annotationAttributes!.add('callout'); } break; case 'FD': if (!_annotationAttributes!.contains(key.toLowerCase())) { element.attributes.add( - XmlAttribute(XmlName(key.toLowerCase()), _getValue(primitive))); + XmlAttribute(XmlName(key.toLowerCase()), _getValue(primitive)), + ); _annotationAttributes!.add(key.toLowerCase()); } break; case PdfDictionaryProperties.quadPoints: if (!_annotationAttributes!.contains('Coords')) { - element.attributes - .add(XmlAttribute(XmlName('coords'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('coords'), _getValue(primitive)), + ); _annotationAttributes!.add('coords'); } break; case PdfDictionaryProperties.ca: if (!_annotationAttributes!.contains('opacity')) { - element.attributes - .add(XmlAttribute(XmlName('opacity'), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName('opacity'), _getValue(primitive)), + ); _annotationAttributes!.add('opacity'); } break; case PdfDictionaryProperties.f: if (primitive is PdfNumber && - !_annotationAttributes! - .contains(PdfDictionaryProperties.flags.toLowerCase())) { + !_annotationAttributes!.contains( + PdfDictionaryProperties.flags.toLowerCase(), + )) { final List annotationFlags = PdfAnnotationHelper.obtainAnnotationFlags( - primitive.value!.toInt()); + primitive.value!.toInt(), + ); final String flag = annotationFlags - .map((PdfAnnotationFlags flag) => - getEnumName(flag).toLowerCase()) + .map( + (PdfAnnotationFlags flag) => getEnumName(flag).toLowerCase(), + ) .toString() .replaceAll(' ', ''); - element.attributes.add(XmlAttribute( + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.flags.toLowerCase()), - flag.substring(1, flag.length - 1))); - _annotationAttributes! - .add(PdfDictionaryProperties.flags.toLowerCase()); + flag.substring(1, flag.length - 1), + ), + ); + _annotationAttributes!.add( + PdfDictionaryProperties.flags.toLowerCase(), + ); } break; case 'InkList': @@ -750,32 +954,42 @@ class XFdfDocument { case 'Repeat': if (!_annotationAttributes!.contains(key)) { element.attributes.add( - XmlAttribute(XmlName(key.toLowerCase()), _getValue(primitive))); + XmlAttribute(XmlName(key.toLowerCase()), _getValue(primitive)), + ); _annotationAttributes!.add(key.toLowerCase()); } break; case PdfDictionaryProperties.border: - if (!_annotationAttributes! - .contains(PdfDictionaryProperties.width.toLowerCase()) && - !_annotationAttributes! - .contains(PdfDictionaryProperties.border.toLowerCase()) && + if (!_annotationAttributes!.contains( + PdfDictionaryProperties.width.toLowerCase(), + ) && + !_annotationAttributes!.contains( + PdfDictionaryProperties.border.toLowerCase(), + ) && primitive is PdfArray && primitive.count >= 3 && primitive.elements[2] is PdfNumber) { - element.attributes.add(XmlAttribute( + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.width.toLowerCase()), - _getValue(primitive.elements[2]))); - element.attributes.add(XmlAttribute( + _getValue(primitive.elements[2]), + ), + ); + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.border.toLowerCase()), - _getValue(primitive))); + _getValue(primitive), + ), + ); _annotationAttributes!.add(PdfDictionaryProperties.border); _annotationAttributes!.add(PdfDictionaryProperties.width); } break; default: if (!_annotationAttributes!.contains(key)) { - element.attributes - .add(XmlAttribute(XmlName(key), _getValue(primitive))); + element.attributes.add( + XmlAttribute(XmlName(key), _getValue(primitive)), + ); _annotationAttributes!.add(key); } break; @@ -813,7 +1027,8 @@ class XFdfDocument { String? _getAnnotationType(PdfDictionary dictionary) { if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? subtype = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.subtype]); + dictionary[PdfDictionaryProperties.subtype], + ); if (subtype != null && subtype is PdfName && subtype.name != null) { return subtype.name!; } @@ -824,11 +1039,13 @@ class XFdfDocument { List _getAppearanceString(PdfDictionary appearanceDictionary) { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0" encoding="utf-8"'); - builder.element('DICT', - attributes: { - XfdfProperties.key: PdfDictionaryProperties.ap - }, - nest: _writeAppearanceDictionary(appearanceDictionary)); + builder.element( + 'DICT', + attributes: { + XfdfProperties.key: PdfDictionaryProperties.ap, + }, + nest: _writeAppearanceDictionary(appearanceDictionary), + ); final String xmlString = builder.buildDocument().toXmlString(); return utf8.encode(xmlString); } @@ -856,35 +1073,46 @@ class XFdfDocument { break; case 'PdfDictionary': element = XmlElement(XmlName(XfdfProperties.dict)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); - element.children - .addAll(_writeAppearanceDictionary(primitive as PdfDictionary)); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); + element.children.addAll( + _writeAppearanceDictionary(primitive as PdfDictionary), + ); break; case 'PdfStream': final PdfStream streamElement = primitive as PdfStream; if (streamElement.dataStream != null && streamElement.dataStream!.isNotEmpty) { element = XmlElement(XmlName(XfdfProperties.stream)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.define), '')); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.define), ''), + ); element.children.addAll(_writeAppearanceDictionary(streamElement)); - final String type = - _getValue(streamElement[PdfDictionaryProperties.subtype]); - final XmlElement dataElement = - XmlElement(XmlName(XfdfProperties.data)); + final String type = _getValue( + streamElement[PdfDictionaryProperties.subtype], + ); + final XmlElement dataElement = XmlElement( + XmlName(XfdfProperties.data), + ); if ((streamElement.containsKey(PdfDictionaryProperties.subtype) && PdfDictionaryProperties.image == type) || (!streamElement.containsKey(PdfDictionaryProperties.type) && - !streamElement - .containsKey(PdfDictionaryProperties.subtype))) { - dataElement.attributes.add(XmlAttribute( - XmlName(XfdfProperties.mode), XfdfProperties.raw)); - dataElement.attributes.add(XmlAttribute( + !streamElement.containsKey( + PdfDictionaryProperties.subtype, + ))) { + dataElement.attributes.add( + XmlAttribute(XmlName(XfdfProperties.mode), XfdfProperties.raw), + ); + dataElement.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.hex)); + XfdfProperties.hex, + ), + ); String data = ''; if (streamElement.dataStream != null) { data = PdfString.bytesToHex(streamElement.dataStream!); @@ -892,15 +1120,20 @@ class XFdfDocument { if (data.isNotEmpty) { dataElement.children.add(XmlText(data)); } - } else if (streamElement - .containsKey(PdfDictionaryProperties.subtype) && + } else if (streamElement.containsKey( + PdfDictionaryProperties.subtype, + ) && PdfDictionaryProperties.form == type && !_isStampAnnotation) { - dataElement.attributes.add(XmlAttribute( - XmlName(XfdfProperties.mode), XfdfProperties.raw)); - dataElement.attributes.add(XmlAttribute( + dataElement.attributes.add( + XmlAttribute(XmlName(XfdfProperties.mode), XfdfProperties.raw), + ); + dataElement.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.hex)); + XfdfProperties.hex, + ), + ); String data = ''; streamElement.decompress(); if (streamElement.dataStream != null) { @@ -914,22 +1147,37 @@ class XFdfDocument { if (streamElement.dataStream != null) { final String ascii = utf8.decode(streamElement.dataStream!); if (_isStampAnnotation && !ascii.contains('TJ')) { - dataElement.attributes.add(XmlAttribute( - XmlName(XfdfProperties.mode), XfdfProperties.filtered)); - dataElement.attributes.add(XmlAttribute( + dataElement.attributes.add( + XmlAttribute( + XmlName(XfdfProperties.mode), + XfdfProperties.filtered, + ), + ); + dataElement.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.ascii)); + XfdfProperties.ascii, + ), + ); if (!isNullOrEmpty(ascii)) { - dataElement.children - .add(XmlText(_getFormatedString(ascii))); + dataElement.children.add( + XmlText(_getFormatedString(ascii)), + ); } } } else { - dataElement.attributes.add(XmlAttribute( - XmlName(XfdfProperties.mode), XfdfProperties.raw)); - dataElement.attributes.add(XmlAttribute( + dataElement.attributes.add( + XmlAttribute( + XmlName(XfdfProperties.mode), + XfdfProperties.raw, + ), + ); + dataElement.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.hex)); + XfdfProperties.hex, + ), + ); String data = ''; streamElement.decompress(); if (streamElement.dataStream != null) { @@ -945,48 +1193,67 @@ class XFdfDocument { break; case 'PdfBoolean': element = XmlElement(XmlName(XfdfProperties.bool)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); - element.attributes.add(XmlAttribute( + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); + element.attributes.add( + XmlAttribute( XmlName(XfdfProperties.val), primitive is PdfBoolean && primitive.value != null && primitive.value! ? 'true' - : 'false')); + : 'false', + ), + ); break; case 'PdfName': element = XmlElement(XmlName(XfdfProperties.name)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); - element.attributes.add(XmlAttribute( - XmlName(XfdfProperties.val), (primitive as PdfName).name ?? '')); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); + element.attributes.add( + XmlAttribute( + XmlName(XfdfProperties.val), + (primitive as PdfName).name ?? '', + ), + ); break; case 'PdfString': element = XmlElement(XmlName(XfdfProperties.string)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); - element.attributes.add(XmlAttribute(XmlName(XfdfProperties.val), - (primitive as PdfString).value ?? '')); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); + element.attributes.add( + XmlAttribute( + XmlName(XfdfProperties.val), + (primitive as PdfString).value ?? '', + ), + ); break; case 'PdfNumber': element = XmlElement(XmlName(XfdfProperties.fixed)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); - final String value = - (primitive as PdfNumber).value!.toDouble().toStringAsFixed(6); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.val), value)); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); + final String value = (primitive as PdfNumber).value! + .toDouble() + .toStringAsFixed(6); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.val), value), + ); break; case 'PdfNull': element = XmlElement(XmlName(XfdfProperties.nullVal)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); break; case 'PdfArray': element = XmlElement(XmlName(XfdfProperties.array)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.key), key)); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.key), key), + ); element.children.addAll(_writeArray(primitive as PdfArray)); break; } @@ -1015,8 +1282,12 @@ class XFdfDocument { break; case 'PdfName': element = XmlElement(XmlName(XfdfProperties.name)); - element.attributes.add(XmlAttribute( - XmlName(XfdfProperties.val), (primitive as PdfName).name ?? '')); + element.attributes.add( + XmlAttribute( + XmlName(XfdfProperties.val), + (primitive as PdfName).name ?? '', + ), + ); break; case 'PdfString': element = XmlElement(XmlName(XfdfProperties.string)); @@ -1027,56 +1298,73 @@ class XFdfDocument { primitive.isHex!) { final List bytes = primitive.pdfEncode(_document); primitive.value = PdfString.byteToString(bytes); - element.attributes.add(XmlAttribute( + element.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.hex)); + XfdfProperties.hex, + ), + ); if (!isNullOrEmpty(primitive.value)) { element.children.add(XmlText(_getFormatedString(primitive.value!))); } } else { element.attributes.add( - XmlAttribute(XmlName(XfdfProperties.val), primitive.value ?? '')); + XmlAttribute(XmlName(XfdfProperties.val), primitive.value ?? ''), + ); } break; case 'PdfNumber': element = XmlElement(XmlName(XfdfProperties.fixed)); - final String value = - (primitive as PdfNumber).value!.toDouble().toStringAsFixed(6); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.val), value)); + final String value = (primitive as PdfNumber).value! + .toDouble() + .toStringAsFixed(6); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.val), value), + ); break; case 'PdfBoolean': element = XmlElement(XmlName(XfdfProperties.bool)); - element.attributes.add(XmlAttribute( + element.attributes.add( + XmlAttribute( XmlName(XfdfProperties.val), (primitive as PdfBoolean).value != null && primitive.value! ? 'true' - : 'false')); + : 'false', + ), + ); break; case 'PdfDictionary': element = XmlElement(XmlName(XfdfProperties.dict)); - element.children - .addAll(_writeAppearanceDictionary(primitive as PdfDictionary)); + element.children.addAll( + _writeAppearanceDictionary(primitive as PdfDictionary), + ); break; case 'PdfStream': final PdfStream streamElement = primitive as PdfStream; if (streamElement.dataStream != null && streamElement.dataStream!.isNotEmpty) { element = XmlElement(XmlName(XfdfProperties.stream)); - element.attributes - .add(XmlAttribute(XmlName(XfdfProperties.define), '')); + element.attributes.add( + XmlAttribute(XmlName(XfdfProperties.define), ''), + ); element.children.addAll(_writeAppearanceDictionary(streamElement)); - final XmlElement dataElement = - XmlElement(XmlName(XfdfProperties.data)); - final String type = - _getValue(streamElement[PdfDictionaryProperties.subtype]); + final XmlElement dataElement = XmlElement( + XmlName(XfdfProperties.data), + ); + final String type = _getValue( + streamElement[PdfDictionaryProperties.subtype], + ); if (streamElement.containsKey(PdfDictionaryProperties.subtype) && PdfDictionaryProperties.image == type) { dataElement.attributes.add( - XmlAttribute(XmlName(XfdfProperties.mode), XfdfProperties.raw)); - dataElement.attributes.add(XmlAttribute( + XmlAttribute(XmlName(XfdfProperties.mode), XfdfProperties.raw), + ); + dataElement.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.hex)); + XfdfProperties.hex, + ), + ); String data = ''; streamElement.decompress(); if (streamElement.dataStream != null) { @@ -1086,11 +1374,18 @@ class XFdfDocument { dataElement.children.add(XmlText(data)); } } else { - dataElement.attributes.add(XmlAttribute( - XmlName(XfdfProperties.mode), XfdfProperties.filtered)); - dataElement.attributes.add(XmlAttribute( + dataElement.attributes.add( + XmlAttribute( + XmlName(XfdfProperties.mode), + XfdfProperties.filtered, + ), + ); + dataElement.attributes.add( + XmlAttribute( XmlName(PdfDictionaryProperties.encoding.toUpperCase()), - XfdfProperties.ascii)); + XfdfProperties.ascii, + ), + ); String data = ''; streamElement.decompress(); if (streamElement.dataStream != null) { @@ -1114,16 +1409,22 @@ class XFdfDocument { XmlElement _exportMeasureDictionary(PdfDictionary dictionary) { final XmlElement measureXmlElement = XmlElement(XmlName('measure')); - final IPdfPrimitive? mdictionary = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.measure]); + final IPdfPrimitive? mdictionary = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.measure], + ); if (mdictionary != null && mdictionary is PdfDictionary) { if (mdictionary.containsKey(PdfDictionaryProperties.r)) { - measureXmlElement.attributes.add(XmlAttribute(XmlName('rateValue'), - _getValue(mdictionary[PdfDictionaryProperties.r]))); + measureXmlElement.attributes.add( + XmlAttribute( + XmlName('rateValue'), + _getValue(mdictionary[PdfDictionaryProperties.r]), + ), + ); } if (mdictionary.containsKey(PdfDictionaryProperties.a)) { - IPdfPrimitive? aprimitive = - PdfCrossTable.dereference(mdictionary[PdfDictionaryProperties.a]); + IPdfPrimitive? aprimitive = PdfCrossTable.dereference( + mdictionary[PdfDictionaryProperties.a], + ); if (aprimitive != null && aprimitive is PdfArray) { aprimitive = PdfCrossTable.dereference(aprimitive.elements[0]); if (aprimitive != null && aprimitive is PdfDictionary) { @@ -1134,21 +1435,24 @@ class XFdfDocument { } } if (mdictionary.containsKey(PdfDictionaryProperties.d)) { - IPdfPrimitive? dprimitive = - PdfCrossTable.dereference(mdictionary[PdfDictionaryProperties.d]); + IPdfPrimitive? dprimitive = PdfCrossTable.dereference( + mdictionary[PdfDictionaryProperties.d], + ); if (dprimitive != null && dprimitive is PdfArray) { dprimitive = PdfCrossTable.dereference(dprimitive.elements[0]); if (dprimitive != null && dprimitive is PdfDictionary) { - final XmlElement distanceXmlElement = - XmlElement(XmlName('distance')); + final XmlElement distanceXmlElement = XmlElement( + XmlName('distance'), + ); _exportMeasureFormatDetails(dprimitive, distanceXmlElement); measureXmlElement.children.add(distanceXmlElement); } } } if (mdictionary.containsKey(PdfDictionaryProperties.x)) { - IPdfPrimitive? xprimitive = - PdfCrossTable.dereference(mdictionary[PdfDictionaryProperties.x]); + IPdfPrimitive? xprimitive = PdfCrossTable.dereference( + mdictionary[PdfDictionaryProperties.x], + ); if (xprimitive != null && xprimitive is PdfArray) { xprimitive = PdfCrossTable.dereference(xprimitive.elements[0]); if (xprimitive != null && xprimitive is PdfDictionary) { @@ -1163,38 +1467,63 @@ class XFdfDocument { } void _exportMeasureFormatDetails( - PdfDictionary measurementDetails, XmlElement element) { + PdfDictionary measurementDetails, + XmlElement element, + ) { if (measurementDetails.containsKey(PdfDictionaryProperties.c)) { - element.attributes.add(XmlAttribute(XmlName('c'), - _getValue(measurementDetails[PdfDictionaryProperties.c]))); + element.attributes.add( + XmlAttribute( + XmlName('c'), + _getValue(measurementDetails[PdfDictionaryProperties.c]), + ), + ); } if (measurementDetails.containsKey(PdfDictionaryProperties.f)) { - element.attributes.add(XmlAttribute(XmlName('f'), - _getValue(measurementDetails[PdfDictionaryProperties.f]))); + element.attributes.add( + XmlAttribute( + XmlName('f'), + _getValue(measurementDetails[PdfDictionaryProperties.f]), + ), + ); } if (measurementDetails.containsKey(PdfDictionaryProperties.d)) { - element.attributes.add(XmlAttribute(XmlName('d'), - _getValue(measurementDetails[PdfDictionaryProperties.d]))); + element.attributes.add( + XmlAttribute( + XmlName('d'), + _getValue(measurementDetails[PdfDictionaryProperties.d]), + ), + ); } if (measurementDetails.containsKey(PdfDictionaryProperties.rd)) { - element.attributes.add(XmlAttribute(XmlName('rd'), - _getValue(measurementDetails[PdfDictionaryProperties.rd]))); + element.attributes.add( + XmlAttribute( + XmlName('rd'), + _getValue(measurementDetails[PdfDictionaryProperties.rd]), + ), + ); } if (measurementDetails.containsKey(PdfDictionaryProperties.u)) { - element.attributes.add(XmlAttribute(XmlName('u'), - _getValue(measurementDetails[PdfDictionaryProperties.u]))); + element.attributes.add( + XmlAttribute( + XmlName('u'), + _getValue(measurementDetails[PdfDictionaryProperties.u]), + ), + ); } if (measurementDetails.containsKey('RT')) { element.attributes.add( - XmlAttribute(XmlName('rt'), _getValue(measurementDetails['RT']))); + XmlAttribute(XmlName('rt'), _getValue(measurementDetails['RT'])), + ); } if (measurementDetails.containsKey('SS')) { element.attributes.add( - XmlAttribute(XmlName('ss'), _getValue(measurementDetails['SS']))); + XmlAttribute(XmlName('ss'), _getValue(measurementDetails['SS'])), + ); } if (measurementDetails.containsKey('FD')) { element.attributes.add( - XmlAttribute(XmlName('fd'), _getValue(measurementDetails['FD']))); + XmlAttribute(XmlName('fd'), _getValue(measurementDetails['FD'])), + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file.dart index 8d73927a6..19f1e4776 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file.dart @@ -50,8 +50,10 @@ class EmbeddedFile implements IPdfWrapper { //Implementations. void _initialize() { - _stream.setProperty(PdfDictionaryProperties.type, - PdfName(PdfDictionaryProperties.embeddedFile)); + _stream.setProperty( + PdfDictionaryProperties.type, + PdfName(PdfDictionaryProperties.embeddedFile), + ); _stream.setProperty(PdfDictionaryProperties.params, params); _stream.beginSave = _streamBeginSave; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file_specification.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file_specification.dart index 89b358002..07bd6fa4b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file_specification.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/embedded_file_specification.dart @@ -12,9 +12,9 @@ class PdfEmbeddedFileSpecification extends PdfFileSpecificationBase { /// Initializes a new instance of the [PdfEmbeddedFileSpecification] class PdfEmbeddedFileSpecification(String fileName, List data) : super() { _helper = PdfEmbeddedFileSpecificationHelper(this); - PdfFileSpecificationBaseHelper.getHelper(this) - .dictionary! - .setProperty(PdfDictionaryProperties.ef, _helper._dict); + PdfFileSpecificationBaseHelper.getHelper( + this, + ).dictionary!.setProperty(PdfDictionaryProperties.ef, _helper._dict); _helper.embeddedFile = EmbeddedFile(fileName, data); _helper.description = fileName; } @@ -33,7 +33,8 @@ class PdfEmbeddedFileSpecificationHelper { /// internal method static PdfEmbeddedFileSpecificationHelper getHelper( - PdfEmbeddedFileSpecification base) { + PdfEmbeddedFileSpecification base, + ) { return base._helper; } @@ -53,9 +54,9 @@ class PdfEmbeddedFileSpecificationHelper { set description(String value) { if (_desc != value) { _desc = value; - PdfFileSpecificationBaseHelper.getHelper(base) - .dictionary! - .setString(PdfDictionaryProperties.description, _desc); + PdfFileSpecificationBaseHelper.getHelper( + base, + ).dictionary!.setString(PdfDictionaryProperties.description, _desc); } } @@ -70,13 +71,15 @@ class PdfEmbeddedFileSpecificationHelper { void save() { _dict[PdfDictionaryProperties.f] = PdfReferenceHolder(embeddedFile); final PdfString str = PdfString( - PdfFileSpecificationBaseHelper.getHelper(base) - .formatFileName(embeddedFile.fileName, false)); - PdfFileSpecificationBaseHelper.getHelper(base) - .dictionary! - .setProperty(PdfDictionaryProperties.f, str); - PdfFileSpecificationBaseHelper.getHelper(base) - .dictionary! - .setProperty(PdfDictionaryProperties.uf, str); + PdfFileSpecificationBaseHelper.getHelper( + base, + ).formatFileName(embeddedFile.fileName, false), + ); + PdfFileSpecificationBaseHelper.getHelper( + base, + ).dictionary!.setProperty(PdfDictionaryProperties.f, str); + PdfFileSpecificationBaseHelper.getHelper( + base, + ).dictionary!.setProperty(PdfDictionaryProperties.uf, str); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/enum.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/enum.dart index 962689afd..72ac59380 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/enum.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/enum.dart @@ -25,5 +25,5 @@ enum PdfDestinationMode { /// top positioned at the top edge of the window and the contents of the page /// magnified just enough to fit the entire width of the page /// within the window. - fitH + fitH, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/file_specification_base.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/file_specification_base.dart index d28495aa8..2d2520a29 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/file_specification_base.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/file_specification_base.dart @@ -30,7 +30,8 @@ class PdfFileSpecificationBaseHelper { /// internal method static PdfFileSpecificationBaseHelper getHelper( - PdfFileSpecificationBase base) { + PdfFileSpecificationBase base, + ) { return base._helper; } @@ -44,8 +45,10 @@ class PdfFileSpecificationBaseHelper { void initialize() { dictionary = PdfDictionary(); - dictionary!.setProperty(PdfDictionaryProperties.type, - PdfName(PdfDictionaryProperties.filespec)); + dictionary!.setProperty( + PdfDictionaryProperties.type, + PdfName(PdfDictionaryProperties.filespec), + ); dictionary!.beginSave = _dictionaryBeginSave; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_destination.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_destination.dart index 1e6c42c3e..f0d2fd111 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_destination.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_destination.dart @@ -145,8 +145,9 @@ class PdfDestination implements IPdfWrapper { } PdfPoint _pointToNativePdf(PdfPage page, PdfPoint point) { - return PdfSectionHelper.getHelper(PdfPageHelper.getHelper(page).section!) - .pointToNativePdf(page, point); + return PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).pointToNativePdf(page, point); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination.dart index 91efaa163..69333f7da 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination.dart @@ -26,8 +26,10 @@ class PdfNamedDestination implements IPdfWrapper { } PdfNamedDestination._( - PdfDictionary dictionary, PdfCrossTable crossTable, bool isLoaded) - : super() { + PdfDictionary dictionary, + PdfCrossTable crossTable, + bool isLoaded, + ) : super() { _helper = PdfNamedDestinationHelper(this); _helper.dictionary = dictionary; _crossTable = crossTable; @@ -65,8 +67,11 @@ class PdfNamedDestination implements IPdfWrapper { if (_isLoaded) { String? title = ''; if (_helper.dictionary!.containsKey(PdfDictionaryProperties.title)) { - final PdfString str = _crossTable.getObject( - _helper.dictionary![PdfDictionaryProperties.title])! as PdfString; + final PdfString str = + _crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.title], + )! + as PdfString; title = str.value; } return title!; @@ -92,14 +97,17 @@ class PdfNamedDestination implements IPdfWrapper { _helper.dictionary!.setProperty(PdfDictionaryProperties.d, _destination); }; _helper.dictionary!.setProperty( - PdfDictionaryProperties.s, PdfName(PdfDictionaryProperties.goTo)); + PdfDictionaryProperties.s, + PdfName(PdfDictionaryProperties.goTo), + ); } PdfDestination? _obtainDestination() { if (_helper.dictionary!.containsKey(PdfDictionaryProperties.d) && (_destination == null)) { - final IPdfPrimitive? obj = - _crossTable.getObject(_helper.dictionary![PdfDictionaryProperties.d]); + final IPdfPrimitive? obj = _crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.d], + ); final PdfArray? destination = obj as PdfArray?; if (destination != null && destination.count > 1) { final PdfReferenceHolder? referenceHolder = @@ -109,9 +117,9 @@ class PdfNamedDestination implements IPdfWrapper { final PdfDictionary? dictionary = _crossTable.getObject(referenceHolder) as PdfDictionary?; if (dictionary != null) { - page = - PdfPageCollectionHelper.getHelper(_crossTable.document!.pages) - .getPage(dictionary); + page = PdfPageCollectionHelper.getHelper( + _crossTable.document!.pages, + ).getPage(dictionary); } } @@ -181,7 +189,10 @@ class PdfNamedDestinationHelper { /// internal method static PdfNamedDestination load( - PdfDictionary dictionary, PdfCrossTable crossTable, bool isLoaded) { + PdfDictionary dictionary, + PdfCrossTable crossTable, + bool isLoaded, + ) { return PdfNamedDestination._(dictionary, crossTable, isLoaded); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination_collection.dart index b3e04c74d..d87f1fd46 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/pdf_named_destination_collection.dart @@ -17,7 +17,9 @@ class PdfNamedDestinationCollection implements IPdfWrapper { } PdfNamedDestinationCollection._( - PdfDictionary? dictionary, PdfCrossTable? crossTable) { + PdfDictionary? dictionary, + PdfCrossTable? crossTable, + ) { _helper = PdfNamedDestinationCollectionHelper(this); _helper.dictionary = dictionary; if (crossTable != null) { @@ -25,8 +27,11 @@ class PdfNamedDestinationCollection implements IPdfWrapper { } if (_helper.dictionary != null && _helper.dictionary!.containsKey(PdfDictionaryProperties.dests)) { - final PdfDictionary? destination = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.dests]) as PdfDictionary?; + final PdfDictionary? destination = + PdfCrossTable.dereference( + _helper.dictionary![PdfDictionaryProperties.dests], + ) + as PdfDictionary?; if (destination != null && destination.containsKey(PdfDictionaryProperties.names)) { _addCollection(destination); @@ -38,32 +43,43 @@ class PdfNamedDestinationCollection implements IPdfWrapper { if (kids != null) { for (int i = 0; i < kids.count; i++) { _findDestination( - PdfCrossTable.dereference(kids[i]) as PdfDictionary?); + PdfCrossTable.dereference(kids[i]) as PdfDictionary?, + ); } } } } - PdfDocumentHelper.getHelper(_crossTable.document!).catalog.beginSave = - (Object sender, SavePdfPrimitiveArgs? ars) { + PdfDocumentHelper.getHelper(_crossTable.document!).catalog.beginSave = ( + Object sender, + SavePdfPrimitiveArgs? ars, + ) { for (final PdfNamedDestination values in _namedCollections) { _namedDestination.add(PdfString(values.title)); _namedDestination.add(PdfReferenceHolder(values)); } _helper.dictionary!.setProperty( - PdfDictionaryProperties.names, PdfReferenceHolder(_namedDestination)); + PdfDictionaryProperties.names, + PdfReferenceHolder(_namedDestination), + ); if (_helper.dictionary!.containsKey(PdfDictionaryProperties.dests)) { - final PdfDictionary? destsDictionary = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.dests]) - as PdfDictionary?; + final PdfDictionary? destsDictionary = + PdfCrossTable.dereference( + _helper.dictionary![PdfDictionaryProperties.dests], + ) + as PdfDictionary?; if (destsDictionary != null && !destsDictionary.containsKey(PdfDictionaryProperties.kids)) { - destsDictionary.setProperty(PdfDictionaryProperties.names, - PdfReferenceHolder(_namedDestination)); + destsDictionary.setProperty( + PdfDictionaryProperties.names, + PdfReferenceHolder(_namedDestination), + ); } } else { - _helper.dictionary!.setProperty(PdfDictionaryProperties.names, - PdfReferenceHolder(_namedDestination)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.names, + PdfReferenceHolder(_namedDestination), + ); } }; PdfDocumentHelper.getHelper(_crossTable.document!).catalog.modify(); @@ -114,7 +130,8 @@ class PdfNamedDestinationCollection implements IPdfWrapper { void removeAt(int index) { if (index >= _namedCollections.length) { throw RangeError( - 'The index value should not be greater than or equal to the count.'); + 'The index value should not be greater than or equal to the count.', + ); } _namedCollections.removeAt(index); } @@ -128,7 +145,8 @@ class PdfNamedDestinationCollection implements IPdfWrapper { void insert(int index, PdfNamedDestination namedDestination) { if (index < 0 || index > count) { throw RangeError( - "The index can't be less then zero or greater then Count."); + "The index can't be less then zero or greater then Count.", + ); } _namedCollections.insert(index, namedDestination); } @@ -141,13 +159,18 @@ class PdfNamedDestinationCollection implements IPdfWrapper { _namedDestination.add(PdfReferenceHolder(values)); } _helper.dictionary!.setProperty( - PdfDictionaryProperties.names, PdfReferenceHolder(_namedDestination)); + PdfDictionaryProperties.names, + PdfReferenceHolder(_namedDestination), + ); }; } void _addCollection(PdfDictionary namedDictionary) { - final PdfArray? elements = PdfCrossTable.dereference( - namedDictionary[PdfDictionaryProperties.names]) as PdfArray?; + final PdfArray? elements = + PdfCrossTable.dereference( + namedDictionary[PdfDictionaryProperties.names], + ) + as PdfArray?; if (elements != null) { for (int i = 1; i <= elements.count; i = i + 2) { PdfReferenceHolder? reference; @@ -157,13 +180,17 @@ class PdfNamedDestinationCollection implements IPdfWrapper { PdfDictionary? dictionary; if (reference != null && reference.object is PdfArray) { dictionary = PdfDictionary(); - dictionary.setProperty(PdfDictionaryProperties.d, - PdfArray(reference.object as PdfArray?)); + dictionary.setProperty( + PdfDictionaryProperties.d, + PdfArray(reference.object as PdfArray?), + ); } else if (reference == null && elements[i] is PdfArray) { dictionary = PdfDictionary(); final PdfArray referenceArray = elements[i]! as PdfArray; dictionary.setProperty( - PdfDictionaryProperties.d, PdfArray(referenceArray)); + PdfDictionaryProperties.d, + PdfArray(referenceArray), + ); } else { dictionary = reference!.object as PdfDictionary?; } @@ -192,7 +219,8 @@ class PdfNamedDestinationCollection implements IPdfWrapper { if (kids != null) { for (int i = 0; i < kids.count; i++) { _findDestination( - PdfCrossTable.dereference(kids[i]) as PdfDictionary?); + PdfCrossTable.dereference(kids[i]) as PdfDictionary?, + ); } } } @@ -212,13 +240,16 @@ class PdfNamedDestinationCollectionHelper { /// internal method static PdfNamedDestinationCollectionHelper getHelper( - PdfNamedDestinationCollection destination) { + PdfNamedDestinationCollection destination, + ) { return destination._helper; } /// internal method static PdfNamedDestinationCollection load( - PdfDictionary? dictionary, PdfCrossTable? crossTable) { + PdfDictionary? dictionary, + PdfCrossTable? crossTable, + ) { return PdfNamedDestinationCollection._(dictionary, crossTable); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/windows1252encoding.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/windows1252encoding.dart index de4e22e55..85fae6576 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/windows1252encoding.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/general/windows1252encoding.dart @@ -255,7 +255,7 @@ class Windows1252Encoding { 252, 253, 254, - 255 + 255, ]; List getBytes(String s) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_brush.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_brush.dart index 17bc184fc..412e2c7bb 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_brush.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_brush.dart @@ -3010,8 +3010,9 @@ class PdfBrushes { static PdfBrush _getBrush(KnownColor kColor) { final ColorHelper color = ColorHelper(kColor); - final PdfBrush brush = - PdfSolidBrush(PdfColor(color.r, color.g, color.b, color.a)); + final PdfBrush brush = PdfSolidBrush( + PdfColor(color.r, color.g, color.b, color.a), + ); _brushes[kColor] = brush; return brush; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_solid_brush.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_solid_brush.dart index d2d46c4a6..3b5140717 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_solid_brush.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/brushes/pdf_solid_brush.dart @@ -26,11 +26,12 @@ class PdfSolidBrush implements PdfBrush { @override bool _monitorChanges( - PdfBrush? brush, - PdfStreamWriter? streamWriter, - Function? getResources, - bool saveChanges, - PdfColorSpace? currentColorSpace) { + PdfBrush? brush, + PdfStreamWriter? streamWriter, + Function? getResources, + bool saveChanges, + PdfColorSpace? currentColorSpace, + ) { bool diff = false; if (getResources != null && streamWriter != null) { if (brush == null) { @@ -72,11 +73,12 @@ class PdfSolidBrush implements PdfBrush { /// ``` abstract class PdfBrush { bool _monitorChanges( - PdfBrush? brush, - PdfStreamWriter? streamWriter, - Function? getResources, - bool saveChanges, - PdfColorSpace? currentColorSpace); + PdfBrush? brush, + PdfStreamWriter? streamWriter, + Function? getResources, + bool saveChanges, + PdfColorSpace? currentColorSpace, + ); } // ignore: avoid_classes_with_only_static_members @@ -84,13 +86,19 @@ abstract class PdfBrush { class PdfBrushHelper { /// internal method static bool monitorChanges( - PdfBrush base, - PdfBrush? brush, - PdfStreamWriter? streamWriter, - Function? getResources, - bool saveChanges, - PdfColorSpace? currentColorSpace) { + PdfBrush base, + PdfBrush? brush, + PdfStreamWriter? streamWriter, + Function? getResources, + bool saveChanges, + PdfColorSpace? currentColorSpace, + ) { return base._monitorChanges( - brush, streamWriter, getResources, saveChanges, currentColorSpace); + brush, + streamWriter, + getResources, + saveChanges, + currentColorSpace, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/enums.dart index c04530f87..55f5d8252 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/enums.dart @@ -22,7 +22,7 @@ enum PdfTextAlignment { right, /// Specifies the text as Justified text. - justify + justify, } /// Specifies the type of Vertical alignment. @@ -70,7 +70,7 @@ enum PdfTextDirection { leftToRight, /// Specifies the right to left direction. - rightToLeft + rightToLeft, } /// Defines set of color spaces. @@ -99,7 +99,7 @@ enum PdfColorSpace { grayScale, /// Indexed color space. - indexed + indexed, } /// Possible dash styles of the pen. @@ -134,7 +134,7 @@ enum PdfDashStyle { dashDotDot, /// User defined dash style. - custom + custom, } /// Specifies the corner style of the shapes. @@ -164,7 +164,7 @@ enum PdfLineJoin { /// The two segments are finished with caps and the resulting notch beyond /// the ends of the segments is filled with a triangle. - bevel + bevel, } /// Specifies the line cap style to be used at the ends of the lines. @@ -193,7 +193,7 @@ enum PdfLineCap { /// The stroke continues beyond the endpoint of the path for a distance /// equal to half the line width and is squared off. - square + square, } /// Specifies how the shapes are filled. @@ -217,7 +217,7 @@ enum PdfFillMode { winding, /// Even odd rule of determining "insideness" of point. - alternate + alternate, } /// Specifies the blend mode for transparency. @@ -321,5 +321,5 @@ enum PdfBlendMode { /// Creates a color with the luminosity of the source color /// and the hue and saturation of the backdrop color. This /// produces an inverse effect to that of the Color mode. - luminosity + luminosity, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/element_layouter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/element_layouter.dart index d7c53e67e..dc5afb420 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/element_layouter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/element_layouter.dart @@ -50,7 +50,11 @@ abstract class ElementLayouter { return param.format!._boundsSet ? PdfRectangle.fromRect(param.format!.paginateBounds) : PdfRectangle( - param.bounds!.x, 0, param.bounds!.width, param.bounds!.height); + param.bounds!.x, + 0, + param.bounds!.width, + param.bounds!.height, + ); } } @@ -58,10 +62,11 @@ abstract class ElementLayouter { class PdfLayoutFormat { //Constructor /// Initializes a new instance of the [PdfLayoutFormat] class. - PdfLayoutFormat( - {PdfLayoutType? layoutType, - PdfLayoutBreakType? breakType, - Rect? paginateBounds}) { + PdfLayoutFormat({ + PdfLayoutType? layoutType, + PdfLayoutBreakType? breakType, + Rect? paginateBounds, + }) { this.breakType = breakType ?? PdfLayoutBreakType.fitPage; this.layoutType = layoutType ?? PdfLayoutType.paginate; if (paginateBounds != null) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/layout_element.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/layout_element.dart index 9973ef5ff..292665532 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/layout_element.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/layout_element.dart @@ -30,18 +30,23 @@ abstract class PdfLayoutElement { /// /// If both graphics and page provide in the arguments /// then page takes more precedence than graphics - PdfLayoutResult? draw( - {PdfGraphics? graphics, - PdfPage? page, - Rect? bounds, - PdfLayoutFormat? format}) { + PdfLayoutResult? draw({ + PdfGraphics? graphics, + PdfPage? page, + Rect? bounds, + PdfLayoutFormat? format, + }) { return _draw(graphics, page, bounds, format); } //Implementation - PdfLayoutResult? _draw(PdfGraphics? graphics, PdfPage? page, Rect? bounds, - PdfLayoutFormat? format) { + PdfLayoutResult? _draw( + PdfGraphics? graphics, + PdfPage? page, + Rect? bounds, + PdfLayoutFormat? format, + ) { if (page != null) { final PdfLayoutParams param = PdfLayoutParams(); param.page = page; @@ -100,8 +105,9 @@ class PdfLayoutElementHelper { if (base is PdfShapeElement) { return PdfShapeElementHelper.layout(base as PdfShapeElement, param); } else if (base is PdfTextElement) { - return PdfTextElementHelper.getHelper(base as PdfTextElement) - .layout(param); + return PdfTextElementHelper.getHelper( + base as PdfTextElement, + ).layout(param); } else if (base is PdfList) { return PdfListHelper.getHelper(base as PdfList).layout(param); } else if (base is PdfGrid) { @@ -127,16 +133,19 @@ class PdfLayoutElementHelper { /// internal method void drawInternal(PdfGraphics graphics, PdfRectangle bounds) { if (base is PdfBezierCurve) { - PdfBezierCurveHelper.getHelper(base as PdfBezierCurve) - .drawInternal(graphics, bounds); + PdfBezierCurveHelper.getHelper( + base as PdfBezierCurve, + ).drawInternal(graphics, bounds); } else if (base is PdfPath) { PdfPathHelper.getHelper(base as PdfPath).drawInternal(graphics, bounds); } else if (base is PdfTextElement) { - PdfTextElementHelper.getHelper(base as PdfTextElement) - .drawInternal(graphics, bounds); + PdfTextElementHelper.getHelper( + base as PdfTextElement, + ).drawInternal(graphics, bounds); } else if (base is PdfImage) { - PdfBitmapHelper.getHelper(base as PdfBitmap) - .drawInternal(graphics, bounds); + PdfBitmapHelper.getHelper( + base as PdfBitmap, + ).drawInternal(graphics, bounds); } else if (base is PdfList) { PdfListHelper.getHelper(base as PdfList).drawInternal(graphics, bounds); } else if (base is PdfGrid) { @@ -206,10 +215,10 @@ class PdfCancelArgs { /// Represents the method that will handle an event /// that before lay outing on the page. -typedef BeginPageLayoutCallback = void Function( - Object sender, BeginPageLayoutArgs args); +typedef BeginPageLayoutCallback = + void Function(Object sender, BeginPageLayoutArgs args); /// Represents the method that will handle an event, /// once completed the lay outing on the page. -typedef EndPageLayoutCallback = void Function( - Object sender, EndPageLayoutArgs args); +typedef EndPageLayoutCallback = + void Function(Object sender, EndPageLayoutArgs args); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/pdf_shape_element.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/pdf_shape_element.dart index 7354aa7e8..5bf1097ed 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/pdf_shape_element.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/pdf_shape_element.dart @@ -41,8 +41,9 @@ abstract class PdfShapeElement extends PdfLayoutElement { PdfRectangle? _getBoundsInternal() { if (this is PdfBezierCurve) { - return PdfBezierCurveHelper.getHelper(this as PdfBezierCurve) - .getBoundsInternal(); + return PdfBezierCurveHelper.getHelper( + this as PdfBezierCurve, + ).getBoundsInternal(); } else if (this is PdfPath) { return PdfPathHelper.getHelper(this as PdfPath).getBoundsInternal(); } else if (this is PdfImage) { @@ -75,7 +76,9 @@ class PdfShapeElementHelper { /// internal method static PdfLayoutResult? layout( - PdfShapeElement element, PdfLayoutParams param) { + PdfShapeElement element, + PdfLayoutParams param, + ) { return element._layout(param); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/shape_layouter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/shape_layouter.dart index 9fb5915d4..f737a6730 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/shape_layouter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/shape_layouter.dart @@ -35,23 +35,30 @@ class ShapeLayouter extends ElementLayouter { pageResult._page = currentPage; while (true) { // ref is there so implement in proper way - final Map returnedValue = - _raiseBeforePageLayout(currentPage, currentBounds!.rect); + final Map returnedValue = _raiseBeforePageLayout( + currentPage, + currentBounds!.rect, + ); bool cancel = returnedValue['cancel'] as bool; currentBounds = PdfRectangle.fromRect(returnedValue['bounds']); EndPageLayoutArgs? endArgs; if (!cancel) { pageResult = _layoutOnPage( - currentPage!, currentBounds, shapeLayoutBounds!, param); + currentPage!, + currentBounds, + shapeLayoutBounds!, + param, + ); endArgs = _raiseEndPageLayout(pageResult); cancel = endArgs != null && endArgs.cancel; } if (!pageResult._end && !cancel) { currentBounds = getPaginateBounds(param); shapeLayoutBounds = _getNextShapeBounds(shapeLayoutBounds!, pageResult); - currentPage = (endArgs == null || endArgs.nextPage == null) - ? getNextPage(currentPage!) - : endArgs.nextPage; + currentPage = + (endArgs == null || endArgs.nextPage == null) + ? getNextPage(currentPage!) + : endArgs.nextPage; } else { result = _getLayoutResult(pageResult); break; @@ -61,11 +68,15 @@ class ShapeLayouter extends ElementLayouter { } Map _raiseBeforePageLayout( - PdfPage? currentPage, Rect currentBounds) { + PdfPage? currentPage, + Rect currentBounds, + ) { bool cancel = false; if (PdfLayoutElementHelper.getHelper(element!).raiseBeginPageLayout) { - final BeginPageLayoutArgs args = - BeginPageLayoutArgs(currentBounds, currentPage!); + final BeginPageLayoutArgs args = BeginPageLayoutArgs( + currentBounds, + currentPage!, + ); PdfLayoutElementHelper.getHelper(element!).onBeginPageLayout(args); cancel = args.cancel; currentBounds = args.bounds; @@ -74,13 +85,18 @@ class ShapeLayouter extends ElementLayouter { } _ShapeLayoutResult _layoutOnPage( - PdfPage currentPage, - PdfRectangle currentBounds, - PdfRectangle shapeLayoutBounds, - PdfLayoutParams param) { + PdfPage currentPage, + PdfRectangle currentBounds, + PdfRectangle shapeLayoutBounds, + PdfLayoutParams param, + ) { final _ShapeLayoutResult result = _ShapeLayoutResult(); currentBounds = _checkCorrectCurrentBounds( - currentPage, currentBounds, shapeLayoutBounds, param); + currentPage, + currentBounds, + shapeLayoutBounds, + param, + ); final bool fitToPage = _fitsToBounds(currentBounds, shapeLayoutBounds); final bool canDraw = !(param.format!.breakType == PdfLayoutBreakType.fitElement && @@ -88,8 +104,10 @@ class ShapeLayouter extends ElementLayouter { currentPage == param.page); bool shapeFinished = false; if (canDraw) { - final PdfRectangle drawRectangle = - _getDrawBounds(currentBounds, shapeLayoutBounds); + final PdfRectangle drawRectangle = _getDrawBounds( + currentBounds, + shapeLayoutBounds, + ); _drawShape(currentPage.graphics, currentBounds.rect, drawRectangle); result._bounds = _getPageResultBounds(currentBounds, shapeLayoutBounds).rect; @@ -103,59 +121,79 @@ class ShapeLayouter extends ElementLayouter { } PdfRectangle _checkCorrectCurrentBounds( - PdfPage currentPage, - PdfRectangle currentBounds, - PdfRectangle shapeLayoutBounds, - PdfLayoutParams param) { + PdfPage currentPage, + PdfRectangle currentBounds, + PdfRectangle shapeLayoutBounds, + PdfLayoutParams param, + ) { final Size pageSize = currentPage.graphics.clientSize; - currentBounds.width = (currentBounds.width > 0) - ? currentBounds.width - : pageSize.width - currentBounds.x; - currentBounds.height = (currentBounds.height > 0) - ? currentBounds.height - : pageSize.height - currentBounds.y; + currentBounds.width = + (currentBounds.width > 0) + ? currentBounds.width + : pageSize.width - currentBounds.x; + currentBounds.height = + (currentBounds.height > 0) + ? currentBounds.height + : pageSize.height - currentBounds.y; return currentBounds; } bool _fitsToBounds( - PdfRectangle currentBounds, PdfRectangle shapeLayoutBounds) { + PdfRectangle currentBounds, + PdfRectangle shapeLayoutBounds, + ) { final bool fits = shapeLayoutBounds.height <= currentBounds.height; return fits; } PdfRectangle _getDrawBounds( - PdfRectangle currentBounds, PdfRectangle shapeLayoutBounds) { - final PdfRectangle result = PdfRectangle(currentBounds.x, currentBounds.y, - currentBounds.width, currentBounds.height); + PdfRectangle currentBounds, + PdfRectangle shapeLayoutBounds, + ) { + final PdfRectangle result = PdfRectangle( + currentBounds.x, + currentBounds.y, + currentBounds.width, + currentBounds.height, + ); result.y -= shapeLayoutBounds.y; result.height += shapeLayoutBounds.y; return result; } void _drawShape( - PdfGraphics g, Rect currentBounds, PdfRectangle drawRectangle) { + PdfGraphics g, + Rect currentBounds, + PdfRectangle drawRectangle, + ) { final PdfGraphicsState gState = g.save(); try { g.setClip(bounds: currentBounds); element!.draw( - graphics: g, - bounds: Rect.fromLTWH(drawRectangle.x, drawRectangle.y, 0, 0)); + graphics: g, + bounds: Rect.fromLTWH(drawRectangle.x, drawRectangle.y, 0, 0), + ); } finally { g.restore(gState); } } PdfRectangle _getPageResultBounds( - PdfRectangle currentBounds, PdfRectangle shapeLayoutBounds) { + PdfRectangle currentBounds, + PdfRectangle shapeLayoutBounds, + ) { final PdfRectangle result = currentBounds; - result.height = (result.height > shapeLayoutBounds.height) - ? shapeLayoutBounds.height - : result.height; + result.height = + (result.height > shapeLayoutBounds.height) + ? shapeLayoutBounds.height + : result.height; return result; } PdfRectangle _getNextShapeBounds( - PdfRectangle shapeLayoutBounds, _ShapeLayoutResult pageResult) { + PdfRectangle shapeLayoutBounds, + _ShapeLayoutResult pageResult, + ) { shapeLayoutBounds.y += pageResult._bounds!.height; shapeLayoutBounds.height -= pageResult._bounds!.height; return shapeLayoutBounds; @@ -172,8 +210,10 @@ class ShapeLayouter extends ElementLayouter { } PdfLayoutResult _getLayoutResult(_ShapeLayoutResult pageResult) { - final PdfLayoutResult result = - PdfLayoutResultHelper.load(pageResult._page!, pageResult._bounds!); + final PdfLayoutResult result = PdfLayoutResultHelper.load( + pageResult._page!, + pageResult._bounds!, + ); return result; } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/text_layouter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/text_layouter.dart index d96c4cb39..8bfbf7fbe 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/text_layouter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/base/text_layouter.dart @@ -27,8 +27,12 @@ class TextLayouter extends ElementLayouter { super.element is PdfTextElement ? super.element as PdfTextElement? : null; //Implementation - _TextPageLayoutResult _layoutOnPage(String text, PdfPage currentPage, - PdfRectangle currentBounds, PdfLayoutParams param) { + _TextPageLayoutResult _layoutOnPage( + String text, + PdfPage currentPage, + PdfRectangle currentBounds, + PdfLayoutParams param, + ) { final _TextPageLayoutResult result = _TextPageLayoutResult(); result.remainder = text; result.page = currentPage; @@ -37,109 +41,150 @@ class TextLayouter extends ElementLayouter { currentPage = getNextPage(currentPage)!; result.page = currentPage; currentBounds = PdfRectangle( - currentBounds.x, 0, currentBounds.width, currentBounds.height); + currentBounds.x, + 0, + currentBounds.width, + currentBounds.height, + ); } final PdfStringLayouter layouter = PdfStringLayouter(); final PdfStringLayoutResult stringResult = layouter.layout( - text, element!.font, _format, - bounds: currentBounds, pageHeight: currentPage.getClientSize().height); + text, + element!.font, + _format, + bounds: currentBounds, + pageHeight: currentPage.getClientSize().height, + ); final bool textFinished = stringResult.remainder == null || stringResult.remainder!.isEmpty; final bool doesntFit = param.format!.breakType == PdfLayoutBreakType.fitElement && - currentPage == param.page && - !textFinished; + currentPage == param.page && + !textFinished; final bool canDraw = !(doesntFit || stringResult.isEmpty); if (canDraw) { final PdfGraphics graphics = currentPage.graphics; PdfGraphicsHelper.getHelper(graphics).drawStringLayoutResult( - stringResult, - element!.font, - element!.pen, - PdfTextElementHelper.getHelper(element!).obtainBrush(), - currentBounds, - _format); + stringResult, + element!.font, + element!.pen, + PdfTextElementHelper.getHelper(element!).obtainBrush(), + currentBounds, + _format, + ); final LineInfo lineInfo = stringResult.lines![stringResult.lineCount - 1]; - result.lastLineBounds = PdfGraphicsHelper.getHelper(graphics) - .getLineBounds(stringResult.lineCount - 1, stringResult, - element!.font, currentBounds, _format); - result.bounds = - _getTextPageBounds(currentPage, currentBounds, stringResult); + result.lastLineBounds = PdfGraphicsHelper.getHelper( + graphics, + ).getLineBounds( + stringResult.lineCount - 1, + stringResult, + element!.font, + currentBounds, + _format, + ); + result.bounds = _getTextPageBounds( + currentPage, + currentBounds, + stringResult, + ); result.remainder = stringResult.remainder; _checkCorectStringFormat(lineInfo); } else { - result.bounds = - _getTextPageBounds(currentPage, currentBounds, stringResult); + result.bounds = _getTextPageBounds( + currentPage, + currentBounds, + stringResult, + ); } - final bool stopLayouting = stringResult.isEmpty && + final bool stopLayouting = + stringResult.isEmpty && ((param.format!.breakType != PdfLayoutBreakType.fitElement) && (param.format!.layoutType != PdfLayoutType.paginate) && canDraw) || (param.format!.breakType == PdfLayoutBreakType.fitElement && currentPage != param.page); - result.end = textFinished || + result.end = + textFinished || stopLayouting || param.format!.layoutType == PdfLayoutType.onePage; return result; } PdfRectangle _checkCorrectBounds( - PdfPage currentPage, PdfRectangle currentBounds) { + PdfPage currentPage, + PdfRectangle currentBounds, + ) { final Size pageSize = currentPage.graphics.clientSize; - currentBounds.height = (currentBounds.height > 0) - ? currentBounds.height - : pageSize.height - currentBounds.y; + currentBounds.height = + (currentBounds.height > 0) + ? currentBounds.height + : pageSize.height - currentBounds.y; return currentBounds; } - Rect _getTextPageBounds(PdfPage currentPage, PdfRectangle currentBounds, - PdfStringLayoutResult stringResult) { + Rect _getTextPageBounds( + PdfPage currentPage, + PdfRectangle currentBounds, + PdfStringLayoutResult stringResult, + ) { final PdfSize textSize = stringResult.size; double? x = currentBounds.x; double? y = currentBounds.y; final double width = (currentBounds.width > 0) ? currentBounds.width : textSize.width; final double height = textSize.height; - final PdfRectangle shiftedRect = - PdfGraphicsHelper.getHelper(currentPage.graphics) - .checkCorrectLayoutRectangle( - textSize, currentBounds.x, currentBounds.y, _format); + final PdfRectangle shiftedRect = PdfGraphicsHelper.getHelper( + currentPage.graphics, + ).checkCorrectLayoutRectangle( + textSize, + currentBounds.x, + currentBounds.y, + _format, + ); if (currentBounds.width <= 0) { x = shiftedRect.x; } if (currentBounds.height <= 0) { y = shiftedRect.y; } - final double verticalShift = - PdfGraphicsHelper.getHelper(currentPage.graphics) - .getTextVerticalAlignShift( - textSize.height, currentBounds.height, _format); + final double verticalShift = PdfGraphicsHelper.getHelper( + currentPage.graphics, + ).getTextVerticalAlignShift(textSize.height, currentBounds.height, _format); y += verticalShift; return Rect.fromLTWH(x, y, width, height); } void _checkCorectStringFormat(LineInfo lineInfo) { if (_format != null) { - PdfStringFormatHelper.getHelper(_format!).firstLineIndent = (lineInfo - .lineType & - PdfStringLayouter.getLineTypeValue(LineType.newLineBreak)! > - 0) - ? PdfStringFormatHelper.getHelper(element!.stringFormat!) - .firstLineIndent - : 0; + PdfStringFormatHelper.getHelper(_format!).firstLineIndent = + (lineInfo.lineType & + PdfStringLayouter.getLineTypeValue( + LineType.newLineBreak, + )! > + 0) + ? PdfStringFormatHelper.getHelper( + element!.stringFormat!, + ).firstLineIndent + : 0; } } PdfTextLayoutResult _getLayoutResult(_TextPageLayoutResult pageResult) { - return PdfTextLayoutResult._(pageResult.page, pageResult.bounds, - pageResult.remainder, pageResult.lastLineBounds); + return PdfTextLayoutResult._( + pageResult.page, + pageResult.bounds, + pageResult.remainder, + pageResult.lastLineBounds, + ); } bool _raiseBeforePageLayout(PdfPage? currentPage, Rect currentBounds) { bool cancel = false; if (PdfLayoutElementHelper.getHelper(element!).raiseBeginPageLayout) { - final BeginPageLayoutArgs args = - BeginPageLayoutArgs(currentBounds, currentPage!); + final BeginPageLayoutArgs args = BeginPageLayoutArgs( + currentBounds, + currentPage!, + ); PdfLayoutElementHelper.getHelper(element!).onBeginPageLayout(args); cancel = args.cancel; currentBounds = args.bounds; @@ -183,9 +228,10 @@ class TextLayouter extends ElementLayouter { } currentBounds = getPaginateBounds(param); text = pageResult.remainder; - currentPage = endArgs == null || endArgs.nextPage == null - ? getNextPage(currentPage!) - : endArgs.nextPage; + currentPage = + endArgs == null || endArgs.nextPage == null + ? getNextPage(currentPage!) + : endArgs.nextPage; } else { result = _getLayoutResult(pageResult); break; @@ -202,8 +248,11 @@ class TextLayouter extends ElementLayouter { class PdfTextLayoutResult extends PdfLayoutResult { //Contructor PdfTextLayoutResult._( - PdfPage? page, Rect? bounds, String? remainder, Rect? lastLineBounds) - : super._(page!, bounds!) { + PdfPage? page, + Rect? bounds, + String? remainder, + Rect? lastLineBounds, + ) : super._(page!, bounds!) { _remainder = remainder; _lastLineBounds = lastLineBounds; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/enums.dart index 8a33398e1..3bc9a90b9 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/enums.dart @@ -4,7 +4,7 @@ enum PdfLayoutType { paginate, /// Draw the element on the one page only. - onePage + onePage, } /// Specifies how the element should be contained on the page. @@ -16,7 +16,7 @@ enum PdfLayoutBreakType { fitElement, /// Fit the columns withtin the page. - fitColumnsToPage + fitColumnsToPage, } /// Specifies path point type @@ -31,5 +31,5 @@ enum PathPointType { bezier3, /// closeSubpath type - closeSubpath + closeSubpath, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_bezier_curve.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_bezier_curve.dart index 973ba731a..3a305ec6f 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_bezier_curve.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_bezier_curve.dart @@ -10,9 +10,13 @@ class PdfBezierCurve extends PdfShapeElement { // constructor /// Initializes a new instance of the [PdfBezierCurve] class /// with the specified [PdfPen] and [Offset] structure. - PdfBezierCurve(Offset startPoint, Offset firstControlPoint, - Offset secondControlPoint, Offset endPoint, - {PdfPen? pen}) { + PdfBezierCurve( + Offset startPoint, + Offset firstControlPoint, + Offset secondControlPoint, + Offset endPoint, { + PdfPen? pen, + }) { _helper = PdfBezierCurveHelper(this); if (pen != null) { super.pen = pen; @@ -79,9 +83,13 @@ class PdfBezierCurveHelper { /// internal method void drawInternal(PdfGraphics graphics, PdfRectangle bounds) { - graphics.drawBezier(base.startPoint, base.firstControlPoint, - base.secondControlPoint, base.endPoint, - pen: PdfShapeElementHelper.obtainPen(base)); + graphics.drawBezier( + base.startPoint, + base.firstControlPoint, + base.secondControlPoint, + base.endPoint, + pen: PdfShapeElementHelper.obtainPen(base), + ); } /// internal method diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_path.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_path.dart index 2332b6887..2b6303bfe 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_path.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_path.dart @@ -15,12 +15,13 @@ class PdfPath extends PdfShapeElement { // constructor /// Initializes a new instance of the [PdfPath] class /// with pen, brush, fillMode, points and pathTypes - PdfPath( - {PdfPen? pen, - PdfBrush? brush, - PdfFillMode fillMode = PdfFillMode.winding, - List points = const [], - List? pathTypes}) { + PdfPath({ + PdfPen? pen, + PdfBrush? brush, + PdfFillMode fillMode = PdfFillMode.winding, + List points = const [], + List? pathTypes, + }) { _helper = PdfPathHelper(this); if (pen != null) { super.pen = pen; @@ -79,7 +80,8 @@ class PdfPath extends PdfShapeElement { final int count = pathPoints.length; if (count != pathTypes.length) { throw ArgumentError.value( - 'The argument arrays should be of equal length.'); + 'The argument arrays should be of equal length.', + ); } _helper.points.addAll(pathPoints); _helper.pathTypes.addAll(_assignPathtype(pathTypes)); @@ -87,8 +89,12 @@ class PdfPath extends PdfShapeElement { /// Adds a line void addLine(Offset point1, Offset point2) { - _addPoints([point1.dx, point1.dy, point2.dx, point2.dy], - PathPointType.line); + _addPoints([ + point1.dx, + point1.dy, + point2.dx, + point2.dy, + ], PathPointType.line); } /// Adds a rectangle @@ -102,7 +108,7 @@ class PdfPath extends PdfShapeElement { bounds.left + bounds.width, bounds.top + bounds.height, bounds.left, - bounds.top + bounds.height + bounds.top + bounds.height, ], PathPointType.line); closeFigure(); } @@ -112,8 +118,9 @@ class PdfPath extends PdfShapeElement { startFigure(); addArc(bounds, startAngle, sweepAngle); _addPoint( - Offset(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2), - PathPointType.line); + Offset(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2), + PathPointType.line, + ); closeFigure(); } @@ -125,8 +132,12 @@ class PdfPath extends PdfShapeElement { } /// Adds an bezier curve - void addBezier(Offset startPoint, Offset firstControlPoint, - Offset secondControlPoint, Offset endPoint) { + void addBezier( + Offset startPoint, + Offset firstControlPoint, + Offset secondControlPoint, + Offset endPoint, + ) { final List points = []; points.add(startPoint.dx); points.add(startPoint.dy); @@ -142,12 +153,13 @@ class PdfPath extends PdfShapeElement { /// Adds an arc void addArc(Rect bounds, double startAngle, double sweepAngle) { final List> points = PdfGraphicsHelper.getBezierArcPoints( - bounds.left, - bounds.top, - bounds.left + bounds.width, - bounds.top + bounds.height, - startAngle, - sweepAngle); + bounds.left, + bounds.top, + bounds.left + bounds.width, + bounds.top + bounds.height, + startAngle, + sweepAngle, + ); final List list = []; for (int i = 0; i < points.length; ++i) { final List pt = points[i]; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_template.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_template.dart index 240f5a5ef..bd9359d67 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_template.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_template.dart @@ -48,39 +48,53 @@ class PdfTemplate implements IPdfWrapper { _helper = PdfTemplateHelper(this); _helper.content = PdfStream(); _setSize(width, height); - _helper.content[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.xObject); - _helper.content[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.form); + _helper.content[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.xObject, + ); + _helper.content[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.form, + ); } PdfTemplate._fromRect(Rect bounds) { _helper = PdfTemplateHelper(this); _helper.content = PdfStream(); _setBounds(bounds); - _helper.content[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.xObject); - _helper.content[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.form); + _helper.content[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.xObject, + ); + _helper.content[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.form, + ); } PdfTemplate._fromPdfStream(PdfStream template) { _helper = PdfTemplateHelper(this); _helper.content = template; - final IPdfPrimitive obj = PdfCrossTable.dereference( - _helper.content[PdfDictionaryProperties.bBox])!; + final IPdfPrimitive obj = + PdfCrossTable.dereference( + _helper.content[PdfDictionaryProperties.bBox], + )!; final PdfRectangle rect = (obj as PdfArray).toRectangle(); _size = rect.size; _helper.isReadonly = true; } - PdfTemplate._(Offset origin, Size size, List stream, - PdfDictionary resources, bool isLoadedPage, PdfPageHelper page) - : super() { + PdfTemplate._( + Offset origin, + Size size, + List stream, + PdfDictionary resources, + bool isLoadedPage, + PdfPageHelper page, + ) : super() { _helper = PdfTemplateHelper(this); if (size == Size.zero) { throw ArgumentError.value( - size, 'size', 'The size of the new PdfTemplate cannot be empty.'); + size, + 'size', + 'The size of the new PdfTemplate cannot be empty.', + ); } _helper.content = PdfStream(); if (page.cropBox.left > 0 && page.cropBox.top > 0) { @@ -96,8 +110,9 @@ class PdfTemplate implements IPdfWrapper { } _initialize(); _helper.content.dataStream!.addAll(stream); - _helper.content[PdfDictionaryProperties.resources] = - PdfDictionary(resources); + _helper.content[PdfDictionaryProperties.resources] = PdfDictionary( + resources, + ); _helper._resources = PdfResources(resources); _helper.isLoadedPageTemplate = isLoadedPage; _helper.isReadonly = true; @@ -214,14 +229,19 @@ class PdfTemplate implements IPdfWrapper { void _setSize(double width, double height, [Offset? origin]) { if (origin != null) { - final PdfArray array = - PdfArray([origin.dx, origin.dy, width, height]); + final PdfArray array = PdfArray([ + origin.dx, + origin.dy, + width, + height, + ]); _helper.content[PdfDictionaryProperties.bBox] = array; _size = PdfSize(width, height); } else { final PdfRectangle rectangle = PdfRectangle(0, 0, width, height); - _helper.content[PdfDictionaryProperties.bBox] = - PdfArray.fromRectangle(rectangle); + _helper.content[PdfDictionaryProperties.bBox] = PdfArray.fromRectangle( + rectangle, + ); _size = PdfSize(width, height); } } @@ -234,10 +254,12 @@ class PdfTemplate implements IPdfWrapper { } void _initialize() { - _helper.content[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.xObject); - _helper.content[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.form); + _helper.content[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.xObject, + ); + _helper.content[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.form, + ); } } @@ -290,8 +312,14 @@ class PdfTemplateHelper { } /// internal method - static PdfTemplate internal(Offset origin, Size size, List stream, - PdfDictionary resources, bool isLoadedPage, PdfPageHelper page) { + static PdfTemplate internal( + Offset origin, + Size size, + List stream, + PdfDictionary resources, + bool isLoadedPage, + PdfPageHelper page, + ) { return PdfTemplate._(origin, size, stream, resources, isLoadedPage, page); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_text_element.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_text_element.dart index 398ac1669..25f7c3836 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_text_element.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/figures/pdf_text_element.dart @@ -16,12 +16,13 @@ import 'base/text_layouter.dart'; class PdfTextElement extends PdfLayoutElement { //Constructors /// Initializes a new instance of the [PdfTextElement] class. - PdfTextElement( - {String text = '', - PdfFont? font, - PdfPen? pen, - PdfBrush? brush, - PdfStringFormat? format}) { + PdfTextElement({ + String text = '', + PdfFont? font, + PdfPen? pen, + PdfBrush? brush, + PdfStringFormat? format, + }) { _helper = PdfTextElementHelper(this); _initialize(text, font, pen, brush, format); } @@ -48,8 +49,13 @@ class PdfTextElement extends PdfLayoutElement { PdfStringFormat? stringFormat; //Implementation - void _initialize(String text, PdfFont? font, PdfPen? pen, PdfBrush? brush, - PdfStringFormat? format) { + void _initialize( + String text, + PdfFont? font, + PdfPen? pen, + PdfBrush? brush, + PdfStringFormat? format, + ) { this.text = text; if (font != null) { this.font = font; @@ -101,10 +107,13 @@ class PdfTextElementHelper { /// internal method void drawInternal(PdfGraphics graphics, PdfRectangle bounds) { - graphics.drawString(base.text, base.font, - pen: base.pen, - brush: obtainBrush(), - bounds: bounds.rect, - format: base.stringFormat); + graphics.drawString( + base.text, + base.font, + pen: base.pen, + brush: obtainBrush(), + bounds: bounds.rect, + format: base.stringFormat, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/enums.dart index 7b8eef9d9..3ef4c90fe 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/enums.dart @@ -24,7 +24,7 @@ enum PdfFontStyle { underline, ///Represents Strikeout text - strikethrough + strikethrough, } /// Indicates type of standard PDF fonts. @@ -80,7 +80,7 @@ enum PdfSubSuperscript { superscript, /// Specifies subscript format. - subscript + subscript, } /// Specifies the type of CJK font. @@ -116,7 +116,7 @@ enum PdfCjkFontFamily { monotypeSungLight, /// Represents the sinotype song light font. - sinoTypeSongLight + sinoTypeSongLight, } /// Specifies the types of text wrapping. @@ -148,7 +148,7 @@ enum PdfWordWrapType { /// Text is wrapped by characters. In this case the word /// at the end of the text line can be split. - character + character, } /// Break type of the line. @@ -166,5 +166,5 @@ enum LineType { firstParagraphLine, /// The line is the last in the paragraph. - lastParagraphLine + lastParagraphLine, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cid_font.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cid_font.dart index 2beaebf2d..615b0a69b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cid_font.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cid_font.dart @@ -12,18 +12,27 @@ import 'pdf_font_metrics.dart'; /// internal class class PdfCidFont extends PdfDictionary { /// Initializes a new instance of the [PdfCidFont] class. - PdfCidFont(PdfCjkFontFamily? fontFamily, int? fontStyle, - PdfFontMetrics fontMetrics) { + PdfCidFont( + PdfCjkFontFamily? fontFamily, + int? fontStyle, + PdfFontMetrics fontMetrics, + ) { this[PdfDictionaryProperties.type] = PdfName(PdfDictionaryProperties.font); - this[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.cidFontType2); - this[PdfDictionaryProperties.baseFont] = - PdfName(fontMetrics.postScriptName); - this[PdfDictionaryProperties.dw] = - PdfNumber((fontMetrics.widthTable! as CjkWidthTable).defaultWidth); + this[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.cidFontType2, + ); + this[PdfDictionaryProperties.baseFont] = PdfName( + fontMetrics.postScriptName, + ); + this[PdfDictionaryProperties.dw] = PdfNumber( + (fontMetrics.widthTable! as CjkWidthTable).defaultWidth, + ); this[PdfDictionaryProperties.w] = fontMetrics.widthTable!.toArray(); - this[PdfDictionaryProperties.fontDescriptor] = - _getFontDescryptor(fontFamily, fontStyle, fontMetrics); + this[PdfDictionaryProperties.fontDescriptor] = _getFontDescryptor( + fontFamily, + fontStyle, + fontMetrics, + ); this[PdfDictionaryProperties.cidSystemInfo] = _getSystemInfo(fontFamily); } @@ -59,21 +68,34 @@ class PdfCidFont extends PdfDictionary { } /// internal method - PdfDictionary _getFontDescryptor(PdfCjkFontFamily? fontFamily, int? fontStyle, - PdfFontMetrics fontMetrics) { + PdfDictionary _getFontDescryptor( + PdfCjkFontFamily? fontFamily, + int? fontStyle, + PdfFontMetrics fontMetrics, + ) { final PdfDictionary fontDescryptor = PdfDictionary(); switch (fontFamily) { case PdfCjkFontFamily.hanyangSystemsGothicMedium: _fillHanyangSystemsGothicMedium( - fontDescryptor, fontFamily, fontMetrics); + fontDescryptor, + fontFamily, + fontMetrics, + ); break; case PdfCjkFontFamily.hanyangSystemsShinMyeongJoMedium: _fillHanyangSystemsShinMyeongJoMedium( - fontDescryptor, fontFamily, fontMetrics); + fontDescryptor, + fontFamily, + fontMetrics, + ); break; case PdfCjkFontFamily.heiseiKakuGothicW5: _fillHanyangSystemsGothicMediumWithStyle( - fontDescryptor, fontStyle!, fontFamily, fontMetrics); + fontDescryptor, + fontStyle!, + fontFamily, + fontMetrics, + ); break; case PdfCjkFontFamily.heiseiMinchoW3: _fillHeiseiMinchoW3(fontDescryptor, fontFamily, fontMetrics); @@ -95,8 +117,11 @@ class PdfCidFont extends PdfDictionary { } /// Fills the monotype sung light font descryptor. - void _fillMonotypeSungLight(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillMonotypeSungLight( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(-160, -249, 1175, 1137); _fillFontBBox(fontDescryptor, fontBBox); _fillKnownInfo(fontDescryptor, fontFamily, fontMetrics); @@ -112,8 +137,11 @@ class PdfCidFont extends PdfDictionary { } /// Fills the hanyang systems shin myeong jo medium font descryptor. - void _fillHanyangSystemsShinMyeongJoMedium(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillHanyangSystemsShinMyeongJoMedium( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(0, -148, 1001, 1028); _fillFontBBox(fontDescryptor, fontBBox); _fillKnownInfo(fontDescryptor, fontFamily, fontMetrics); @@ -129,8 +157,11 @@ class PdfCidFont extends PdfDictionary { } /// Fills the heisei mincho w3 font descryptor. - void _fillHeiseiMinchoW3(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillHeiseiMinchoW3( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(-123, -257, 1124, 1167); _fillFontBBox(fontDescryptor, fontBBox); _fillKnownInfo(fontDescryptor, fontFamily, fontMetrics); @@ -146,8 +177,11 @@ class PdfCidFont extends PdfDictionary { } /// Fills the sino type song light font descryptor. - void _fillSinoTypeSongLight(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillSinoTypeSongLight( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(-25, -254, 1025, 1134); _fillFontBBox(fontDescryptor, fontBBox); _fillKnownInfo(fontDescryptor, fontFamily, fontMetrics); @@ -163,8 +197,11 @@ class PdfCidFont extends PdfDictionary { } /// Fills the monotype hei medium font descryptor. - void _fillMonotypeHeiMedium(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillMonotypeHeiMedium( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(-45, -250, 1060, 1137); _fillFontBBox(fontDescryptor, fontBBox); _fillKnownInfo(fontDescryptor, fontFamily, fontMetrics); @@ -180,8 +217,11 @@ class PdfCidFont extends PdfDictionary { } /// Fills the hanyang systems gothic medium font descryptor. - void _fillHanyangSystemsGothicMedium(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillHanyangSystemsGothicMedium( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(-6, -145, 1009, 1025); _fillFontBBox(fontDescryptor, fontBBox); _fillKnownInfo(fontDescryptor, fontFamily, fontMetrics); @@ -198,8 +238,12 @@ class PdfCidFont extends PdfDictionary { } /// Fills the heisei kaku gothic w5 font descryptor. - void _fillHanyangSystemsGothicMediumWithStyle(PdfDictionary fontDescryptor, - int fontStyle, PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { + void _fillHanyangSystemsGothicMediumWithStyle( + PdfDictionary fontDescryptor, + int fontStyle, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { final PdfRectangle fontBBox = PdfRectangle(-92, -250, 1102, 1175); final PdfRectangle fontBBoxI = PdfRectangle(-92, -250, 1102, 1932); if ((fontStyle & @@ -223,19 +267,27 @@ class PdfCidFont extends PdfDictionary { } /// Fills the known info. - void _fillKnownInfo(PdfDictionary fontDescryptor, - PdfCjkFontFamily? fontFamily, PdfFontMetrics fontMetrics) { - fontDescryptor[PdfDictionaryProperties.fontName] = - PdfName(fontMetrics.postScriptName); - fontDescryptor[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.fontDescriptor); + void _fillKnownInfo( + PdfDictionary fontDescryptor, + PdfCjkFontFamily? fontFamily, + PdfFontMetrics fontMetrics, + ) { + fontDescryptor[PdfDictionaryProperties.fontName] = PdfName( + fontMetrics.postScriptName, + ); + fontDescryptor[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.fontDescriptor, + ); fontDescryptor[PdfDictionaryProperties.italicAngle] = PdfNumber(0); - fontDescryptor[PdfDictionaryProperties.missingWidth] = - PdfNumber((fontMetrics.widthTable! as CjkWidthTable).defaultWidth); - fontDescryptor[PdfDictionaryProperties.ascent] = - PdfNumber(fontMetrics.ascent); - fontDescryptor[PdfDictionaryProperties.descent] = - PdfNumber(fontMetrics.descent); + fontDescryptor[PdfDictionaryProperties.missingWidth] = PdfNumber( + (fontMetrics.widthTable! as CjkWidthTable).defaultWidth, + ); + fontDescryptor[PdfDictionaryProperties.ascent] = PdfNumber( + fontMetrics.ascent, + ); + fontDescryptor[PdfDictionaryProperties.descent] = PdfNumber( + fontMetrics.descent, + ); _fillFlags(fontDescryptor, fontFamily); } @@ -261,7 +313,8 @@ class PdfCidFont extends PdfDictionary { /// Fills the font BBox. void _fillFontBBox(PdfDictionary fontDescryptor, PdfRectangle fontBBox) { - fontDescryptor[PdfDictionaryProperties.fontBBox] = - PdfArray.fromRectangle(fontBBox); + fontDescryptor[PdfDictionaryProperties.fontBBox] = PdfArray.fromRectangle( + fontBBox, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font.dart index 3fe3a8b84..527070d5e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font.dart @@ -42,11 +42,16 @@ class PdfCjkStandardFont extends PdfFont { /// //Close the document. /// document.dispose(); /// ``` - PdfCjkStandardFont(PdfCjkFontFamily fontFamily, double size, - {PdfFontStyle? style, List? multiStyle}) { + PdfCjkStandardFont( + PdfCjkFontFamily fontFamily, + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { _helper = PdfCjkStandardFontHelper(this); - PdfFontHelper.getHelper(this) - .initialize(size, style: style, multiStyle: multiStyle); + PdfFontHelper.getHelper( + this, + ).initialize(size, style: style, multiStyle: multiStyle); _fontFamily = fontFamily; _initializeInternals(); } @@ -68,11 +73,16 @@ class PdfCjkStandardFont extends PdfFont { /// //Close the document. /// document.dispose(); /// ``` - PdfCjkStandardFont.protoType(PdfCjkStandardFont prototype, double size, - {PdfFontStyle? style, List? multiStyle}) { + PdfCjkStandardFont.protoType( + PdfCjkStandardFont prototype, + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { _helper = PdfCjkStandardFontHelper(this); - PdfFontHelper.getHelper(this) - .initialize(size, style: style, multiStyle: multiStyle); + PdfFontHelper.getHelper( + this, + ).initialize(size, style: style, multiStyle: multiStyle); _fontFamily = prototype.fontFamily; if (style == null && (multiStyle == null || multiStyle.isEmpty)) { PdfFontHelper.getHelper(this).setStyle(prototype.style, null); @@ -107,9 +117,13 @@ class PdfCjkStandardFont extends PdfFont { PdfCjkFontFamily get fontFamily => _fontFamily; void _initializeInternals() { - PdfFontHelper.getHelper(this).metrics = - PdfCjkStandardFontMetricsFactory.getMetrics( - _fontFamily, PdfFontHelper.getHelper(this).fontStyle, size); + PdfFontHelper.getHelper( + this, + ).metrics = PdfCjkStandardFontMetricsFactory.getMetrics( + _fontFamily, + PdfFontHelper.getHelper(this).fontStyle, + size, + ); PdfFontHelper.getHelper(this).fontInternals = _createInternals(); } @@ -117,12 +131,15 @@ class PdfCjkStandardFont extends PdfFont { PdfDictionary _createInternals() { final PdfDictionary dictionary = PdfDictionary(); - dictionary[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.font); - dictionary[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.type0); - dictionary[PdfDictionaryProperties.baseFont] = - PdfName(PdfFontHelper.getHelper(this).metrics!.postScriptName); + dictionary[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.font, + ); + dictionary[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.type0, + ); + dictionary[PdfDictionaryProperties.baseFont] = PdfName( + PdfFontHelper.getHelper(this).metrics!.postScriptName, + ); dictionary[PdfDictionaryProperties.encoding] = _getEncoding(_fontFamily); dictionary[PdfDictionaryProperties.descendantFonts] = _getDescendantFont(); @@ -162,9 +179,10 @@ class PdfCjkStandardFont extends PdfFont { PdfArray _getDescendantFont() { final PdfArray df = PdfArray(); final PdfCidFont cidFont = PdfCidFont( - _fontFamily, - PdfFontHelper.getHelper(this).fontStyle, - PdfFontHelper.getHelper(this).metrics!); + _fontFamily, + PdfFontHelper.getHelper(this).fontStyle, + PdfFontHelper.getHelper(this).metrics!, + ); df.add(cidFont); return df; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font_metrics_factory.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font_metrics_factory.dart index 3cdbbc7c4..2e679d630 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font_metrics_factory.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_cjk_standard_font_metrics_factory.dart @@ -13,19 +13,28 @@ class PdfCjkStandardFontMetricsFactory { /// Returns font metrics depending on the font settings. static PdfFontMetrics getMetrics( - PdfCjkFontFamily? fontFamily, int? fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int? fontStyle, + double size, + ) { PdfFontMetrics metrics; final PdfCjkStandardFontMetricsFactory fontfactory = PdfCjkStandardFontMetricsFactory(); switch (fontFamily) { case PdfCjkFontFamily.hanyangSystemsGothicMedium: - metrics = - _getHanyangSystemsGothicMediumMetrix(fontFamily, fontStyle!, size); + metrics = _getHanyangSystemsGothicMediumMetrix( + fontFamily, + fontStyle!, + size, + ); break; case PdfCjkFontFamily.hanyangSystemsShinMyeongJoMedium: metrics = _getHanyangSystemsShinMyeongJoMediumMetrix( - fontFamily, fontStyle!, size); + fontFamily, + fontStyle!, + size, + ); break; case PdfCjkFontFamily.heiseiKakuGothicW5: @@ -45,8 +54,11 @@ class PdfCjkStandardFontMetricsFactory { break; case PdfCjkFontFamily.sinoTypeSongLight: - metrics = - fontfactory._getSinoTypeSongLight(fontFamily, fontStyle!, size); + metrics = fontfactory._getSinoTypeSongLight( + fontFamily, + fontStyle!, + size, + ); break; // ignore: no_default_cases @@ -63,7 +75,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the hanyang systems gothic medium font metrix. static PdfFontMetrics _getHanyangSystemsGothicMediumMetrix( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; @@ -94,7 +109,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the monotype hei medium metrix. static PdfFontMetrics _getMonotypeHeiMedium( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; @@ -125,7 +143,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the monotype sung light metrix. static PdfFontMetrics _getMonotypeSungLightMetrix( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; @@ -156,7 +177,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the sino type song light font metrics. PdfFontMetrics _getSinoTypeSongLight( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; @@ -189,7 +213,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the heisei mincho w3. static PdfFontMetrics _getHeiseiMinchoW3( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; @@ -220,7 +247,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the heisei kaku gothic w5 metrix. static PdfFontMetrics _getHeiseiKakuGothicW5Metrix( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; @@ -251,7 +281,10 @@ class PdfCjkStandardFontMetricsFactory { /// Gets the hanyang systems shin myeong jo medium metrix. static PdfFontMetrics _getHanyangSystemsShinMyeongJoMediumMetrix( - PdfCjkFontFamily? fontFamily, int fontStyle, double size) { + PdfCjkFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final CjkWidthTable widthTable = CjkWidthTable(1000); metrics.widthTable = widthTable; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font.dart index b0ac6114a..0ef21dca3 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font.dart @@ -128,8 +128,13 @@ abstract class PdfFont implements IPdfWrapper { Size measureString(String text, {Size? layoutArea, PdfStringFormat? format}) { layoutArea ??= Size.zero; final PdfStringLayouter layouter = PdfStringLayouter(); - final PdfStringLayoutResult result = layouter.layout(text, this, format, - width: layoutArea.width, height: layoutArea.height); + final PdfStringLayoutResult result = layouter.layout( + text, + this, + format, + width: layoutArea.width, + height: layoutArea.height, + ); return result.size.size; } @@ -140,15 +145,20 @@ abstract class PdfFont implements IPdfWrapper { /// Applies settings to the default line width. double _applyFormatSettings( - String line, PdfStringFormat? format, double width) { + String line, + PdfStringFormat? format, + double width, + ) { double realWidth = width; if (format != null && width > 0) { if (format.characterSpacing != 0) { realWidth += (line.length - 1) * format.characterSpacing; } if (format.wordSpacing != 0) { - final int whitespacesCount = - StringTokenizer.getCharacterCount(line, StringTokenizer.spaces); + final int whitespacesCount = StringTokenizer.getCharacterCount( + line, + StringTokenizer.spaces, + ); realWidth += whitespacesCount * format.wordSpacing; } } @@ -173,7 +183,7 @@ class PdfFontHelper { 'courier', 'TimesRoman', 'Symbol', - 'ZapfDingbats' + 'ZapfDingbats', ]; /// internal field @@ -184,7 +194,7 @@ class PdfFontHelper { 'HeiseiMinchoW3', 'MonotypeHeiMedium', 'MonotypeSungLight', - 'SinoTypeSongLight' + 'SinoTypeSongLight', ]; /// internal field @@ -220,8 +230,11 @@ class PdfFontHelper { /// Initializes a new instance of the [PdfFont] class /// with font size and style. - void initialize(double size, - {PdfFontStyle? style, List? multiStyle}) { + void initialize( + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { setSize(size); setStyle(style, multiStyle); } @@ -278,10 +291,14 @@ class PdfFontHelper { /// internal method static double getLineWidth( - PdfFont font, String line, PdfStringFormat? format) { + PdfFont font, + String line, + PdfStringFormat? format, + ) { if (font is PdfCjkStandardFont) { - return PdfCjkStandardFontHelper.getHelper(font) - .getLineWidth(line, format); + return PdfCjkStandardFontHelper.getHelper( + font, + ).getLineWidth(line, format); } else if (font is PdfStandardFont) { return PdfStandardFontHelper.getHelper(font).getLineWidth(line, format); } else if (font is PdfTrueTypeFont) { @@ -292,7 +309,11 @@ class PdfFontHelper { /// internal method static double applyFormatSettings( - PdfFont font, String line, PdfStringFormat? format, double width) { + PdfFont font, + String line, + PdfStringFormat? format, + double width, + ) { return font._applyFormatSettings(line, format, width); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font_metrics.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font_metrics.dart index 146a9c74d..9af8c2c3e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font_metrics.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_font_metrics.dart @@ -113,7 +113,9 @@ class StandardWidthTable extends WidthTable { int? _returnValue(int index) { if (index < 0 || index >= _widths!.length) { throw ArgumentError.value( - index, 'The character is not supported by the font.'); + index, + 'The character is not supported by the font.', + ); } return _widths![index]; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font.dart index 9547b2c06..345a92bb2 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font.dart @@ -38,11 +38,16 @@ class PdfStandardFont extends PdfFont { /// //Close the document. /// document.dispose(); /// ``` - PdfStandardFont(PdfFontFamily fontFamily, double size, - {PdfFontStyle? style, List? multiStyle}) { + PdfStandardFont( + PdfFontFamily fontFamily, + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { _helper = PdfStandardFontHelper(this); - PdfFontHelper.getHelper(this) - .initialize(size, style: style, multiStyle: multiStyle); + PdfFontHelper.getHelper( + this, + ).initialize(size, style: style, multiStyle: multiStyle); _fontFamily = fontFamily; _checkStyle(); _initializeInternals(); @@ -66,11 +71,16 @@ class PdfStandardFont extends PdfFont { /// //Close the document. /// document.dispose(); /// ``` - PdfStandardFont.prototype(PdfStandardFont prototype, double size, - {PdfFontStyle? style, List? multiStyle}) { + PdfStandardFont.prototype( + PdfStandardFont prototype, + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { _helper = PdfStandardFontHelper(this); - PdfFontHelper.getHelper(this) - .initialize(size, style: style, multiStyle: multiStyle); + PdfFontHelper.getHelper( + this, + ).initialize(size, style: style, multiStyle: multiStyle); _fontFamily = prototype.fontFamily; if (style == null && (multiStyle == null || multiStyle.isEmpty)) { PdfFontHelper.getHelper(this).setStyle(prototype.style, null); @@ -114,29 +124,36 @@ class PdfStandardFont extends PdfFont { fontFamily == PdfFontFamily.zapfDingbats) { PdfFontHelper.getHelper(this).fontStyle = PdfFontHelper.getHelper(this).fontStyle & - ~(PdfFontHelper.getPdfFontStyle(PdfFontStyle.bold) | - PdfFontHelper.getPdfFontStyle(PdfFontStyle.italic)); + ~(PdfFontHelper.getPdfFontStyle(PdfFontStyle.bold) | + PdfFontHelper.getPdfFontStyle(PdfFontStyle.italic)); PdfFontHelper.getHelper(this).style = PdfFontStyle.regular; } } /// Initializes font internals. void _initializeInternals() { - PdfFontHelper.getHelper(this).metrics = - PdfStandardFontMetricsFactory.getMetrics( - _fontFamily, PdfFontHelper.getHelper(this).fontStyle, size); + PdfFontHelper.getHelper( + this, + ).metrics = PdfStandardFontMetricsFactory.getMetrics( + _fontFamily, + PdfFontHelper.getHelper(this).fontStyle, + size, + ); PdfFontHelper.getHelper(this).fontInternals = _createInternals(); } /// Creates font's dictionary. PdfDictionary _createInternals() { final PdfDictionary dictionary = PdfDictionary(); - dictionary[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.font); - dictionary[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.type1); - dictionary[PdfDictionaryProperties.baseFont] = - PdfName(PdfFontHelper.getHelper(this).metrics!.postScriptName); + dictionary[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.font, + ); + dictionary[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.type1, + ); + dictionary[PdfDictionaryProperties.baseFont] = PdfName( + PdfFontHelper.getHelper(this).metrics!.postScriptName, + ); if (fontFamily != PdfFontFamily.symbol && fontFamily != PdfFontFamily.zapfDingbats) { dictionary[PdfDictionaryProperties.encoding] = PdfName('WinAnsiEncoding'); @@ -410,7 +427,7 @@ class PdfStandardFontHelper { 'ü', 'ý', 'þ', - 'ÿ' + 'ÿ', ]; return _windows1252MapTable; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font_metrics_factory.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font_metrics_factory.dart index 4843f62cc..e4bccec6c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font_metrics_factory.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_standard_font_metrics_factory.dart @@ -138,7 +138,10 @@ class PdfStandardFontMetricsFactory { /// Returns metrics of the font. static PdfFontMetrics getMetrics( - PdfFontFamily? fontFamily, int? fontStyle, double size) { + PdfFontFamily? fontFamily, + int? fontStyle, + double size, + ) { PdfFontMetrics metrics; switch (fontFamily) { case PdfFontFamily.helvetica: @@ -158,8 +161,11 @@ class PdfStandardFontMetricsFactory { break; // ignore: no_default_cases default: - metrics = - _getHelveticaMetrics(PdfFontFamily.helvetica, fontStyle!, size); + metrics = _getHelveticaMetrics( + PdfFontFamily.helvetica, + fontStyle!, + size, + ); break; } metrics.name = PdfFontHelper.standardFontNames[fontFamily!.index]; @@ -170,7 +176,10 @@ class PdfStandardFontMetricsFactory { /// Creates Helvetica font metrics. static PdfFontMetrics _getHelveticaMetrics( - PdfFontFamily? fontFamily, int fontStyle, double size) { + PdfFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); final PdfStandardFontMetricsFactory standardFontMetricsFactory = PdfStandardFontMetricsFactory(); @@ -180,8 +189,9 @@ class PdfStandardFontMetricsFactory { metrics.descent = _helveticaBoldItalicDescent; metrics.postScriptName = _helveticaBoldItalicName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._arialBoldWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._arialBoldWidth, + ); metrics.height = metrics.ascent - metrics.descent; } else if (fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.bold) > 0) { @@ -189,8 +199,9 @@ class PdfStandardFontMetricsFactory { metrics.descent = standardFontMetricsFactory._helveticaBoldDescent; metrics.postScriptName = _helveticaBoldName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._arialBoldWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._arialBoldWidth, + ); metrics.height = metrics.ascent - metrics.descent; } else if (fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.italic) > 0) { @@ -213,7 +224,10 @@ class PdfStandardFontMetricsFactory { /// Creates Courier font metrics. static PdfFontMetrics _getCourierMetrics( - PdfFontFamily? fontFamily, int fontStyle, double size) { + PdfFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); if (fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.bold) > 0 && fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.italic) > 0) { @@ -252,7 +266,10 @@ class PdfStandardFontMetricsFactory { /// Creates Times font metrics. static PdfFontMetrics _getTimesMetrics( - PdfFontFamily? fontFamily, int fontStyle, double size) { + PdfFontFamily? fontFamily, + int fontStyle, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); if (fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.bold) > 0 && fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.italic) > 0) { @@ -260,8 +277,9 @@ class PdfStandardFontMetricsFactory { metrics.descent = _timesBoldItalicDescent; metrics.postScriptName = _timesBoldItalicName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._timesRomanBoldItalicWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._timesRomanBoldItalicWidth, + ); metrics.height = metrics.ascent - metrics.descent; } else if (fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.bold) > 0) { @@ -269,8 +287,9 @@ class PdfStandardFontMetricsFactory { metrics.descent = _timesBoldDescent; metrics.postScriptName = _timesBoldName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._timesRomanBoldWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._timesRomanBoldWidth, + ); metrics.height = metrics.ascent - metrics.descent; } else if (fontStyle & PdfFontHelper.getPdfFontStyle(PdfFontStyle.italic) > 0) { @@ -278,16 +297,18 @@ class PdfStandardFontMetricsFactory { metrics.descent = _timesItalicDescent; metrics.postScriptName = _timesItalicName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._timesRomanItalicWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._timesRomanItalicWidth, + ); metrics.height = metrics.ascent - metrics.descent; } else { metrics.ascent = _timesAscent; metrics.descent = _timesDescent; metrics.postScriptName = _timesName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._timesRomanWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._timesRomanWidth, + ); metrics.height = metrics.ascent - metrics.descent; } return metrics; @@ -295,7 +316,9 @@ class PdfStandardFontMetricsFactory { /// Creates Symbol font metrics. static PdfFontMetrics _getSymbolMetrics( - PdfFontFamily? fontFamily, double size) { + PdfFontFamily? fontFamily, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); metrics.ascent = _symbolAscent; @@ -309,14 +332,17 @@ class PdfStandardFontMetricsFactory { /// Creates ZapfDingbats font metrics. static PdfFontMetrics _getZapfDingbatsMetrics( - PdfFontFamily? fontFamily, double size) { + PdfFontFamily? fontFamily, + double size, + ) { final PdfFontMetrics metrics = PdfFontMetrics(); metrics.ascent = _zapfDingbatsAscent; metrics.descent = _zapfDingbatsDescent; metrics.postScriptName = _zapfDingbatsName; metrics.size = size; - metrics.widthTable = - StandardWidthTable(_StandardFontWidth._zapfDingbatsWidth); + metrics.widthTable = StandardWidthTable( + _StandardFontWidth._zapfDingbatsWidth, + ); metrics.height = metrics.ascent - metrics.descent; return metrics; } @@ -547,7 +573,7 @@ class _StandardFontWidth { 556, 500, 556, - 500 + 500, ]; static const List _arialBoldWidth = [ 278, @@ -773,7 +799,7 @@ class _StandardFontWidth { 611, 556, 611, - 556 + 556, ]; static const List _fixedWidth = [ 600, @@ -999,7 +1025,7 @@ class _StandardFontWidth { 600, 600, 600, - 600 + 600, ]; static const List _timesRomanWidth = [ 250, @@ -1225,7 +1251,7 @@ class _StandardFontWidth { 500, 500, 500, - 500 + 500, ]; static const List _timesRomanBoldWidth = [ 250, @@ -1451,7 +1477,7 @@ class _StandardFontWidth { 556, 500, 556, - 500 + 500, ]; static const List _timesRomanItalicWidth = [ 250, @@ -1677,7 +1703,7 @@ class _StandardFontWidth { 500, 444, 500, - 444 + 444, ]; static const List _timesRomanBoldItalicWidth = [ 250, @@ -1903,7 +1929,7 @@ class _StandardFontWidth { 556, 444, 500, - 444 + 444, ]; static const List _symbolWidth = [ 250, @@ -2095,7 +2121,7 @@ class _StandardFontWidth { 494, 494, 494, - -1 + -1, ]; static const List _zapfDingbatsWidth = [ 278, @@ -2299,6 +2325,6 @@ class _StandardFontWidth { 873, 927, 970, - 918 + 918, ]; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_format.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_format.dart index 022c0d610..8a729da0f 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_format.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_format.dart @@ -52,29 +52,31 @@ class PdfStringFormat { /// //Close the document. /// document.dispose(); /// ``` - PdfStringFormat( - {PdfTextAlignment alignment = PdfTextAlignment.left, - PdfVerticalAlignment lineAlignment = PdfVerticalAlignment.top, - PdfTextDirection textDirection = PdfTextDirection.none, - double characterSpacing = 0, - double wordSpacing = 0, - double lineSpacing = 0, - PdfSubSuperscript subSuperscript = PdfSubSuperscript.none, - double paragraphIndent = 0, - bool measureTrailingSpaces = false, - PdfWordWrapType wordWrap = PdfWordWrapType.word}) { + PdfStringFormat({ + PdfTextAlignment alignment = PdfTextAlignment.left, + PdfVerticalAlignment lineAlignment = PdfVerticalAlignment.top, + PdfTextDirection textDirection = PdfTextDirection.none, + double characterSpacing = 0, + double wordSpacing = 0, + double lineSpacing = 0, + PdfSubSuperscript subSuperscript = PdfSubSuperscript.none, + double paragraphIndent = 0, + bool measureTrailingSpaces = false, + PdfWordWrapType wordWrap = PdfWordWrapType.word, + }) { _helper = PdfStringFormatHelper(); _initialize( - alignment, - lineAlignment, - textDirection, - characterSpacing, - wordSpacing, - lineSpacing, - subSuperscript, - paragraphIndent, - measureTrailingSpaces, - wordWrap); + alignment, + lineAlignment, + textDirection, + characterSpacing, + wordSpacing, + lineSpacing, + subSuperscript, + paragraphIndent, + measureTrailingSpaces, + wordWrap, + ); } //Fields @@ -335,16 +337,17 @@ class PdfStringFormat { //Implementation void _initialize( - PdfTextAlignment textAlignment, - PdfVerticalAlignment verticalAlignment, - PdfTextDirection textDirection, - double characterSpacing, - double wordSpacing, - double lineSpacing, - PdfSubSuperscript subSuperscript, - double paragraphIndent, - bool measureTrailingSpaces, - PdfWordWrapType wordWrap) { + PdfTextAlignment textAlignment, + PdfVerticalAlignment verticalAlignment, + PdfTextDirection textDirection, + double characterSpacing, + double wordSpacing, + double lineSpacing, + PdfSubSuperscript subSuperscript, + double paragraphIndent, + bool measureTrailingSpaces, + PdfWordWrapType wordWrap, + ) { alignment = textAlignment; lineAlignment = verticalAlignment; this.characterSpacing = characterSpacing; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_layouter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_layouter.dart index cc52c06aa..8c787352e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_layouter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_string_layouter.dart @@ -30,11 +30,14 @@ class PdfStringLayouter { //Implementation /// internal method PdfStringLayoutResult layout( - String text, PdfFont font, PdfStringFormat? format, - {double? width, - double? height, - PdfRectangle? bounds, - double? pageHeight}) { + String text, + PdfFont font, + PdfStringFormat? format, { + double? width, + double? height, + PdfRectangle? bounds, + double? pageHeight, + }) { _text = text; _font = font; _format = format; @@ -85,12 +88,14 @@ class PdfStringLayouter { double? _getLineIndent(bool firstLine) { double? lineIndent = 0; if (_format != null) { - lineIndent = firstLine - ? PdfStringFormatHelper.getHelper(_format!).firstLineIndent - : _format!.paragraphIndent; - lineIndent = (_size.width > 0) - ? (_size.width <= lineIndent ? _size.width : lineIndent) - : lineIndent; + lineIndent = + firstLine + ? PdfStringFormatHelper.getHelper(_format!).firstLineIndent + : _format!.paragraphIndent; + lineIndent = + (_size.width > 0) + ? (_size.width <= lineIndent ? _size.width : lineIndent) + : lineIndent; } return lineIndent; } @@ -117,12 +122,12 @@ class PdfStringLayouter { if (maxWidth <= 0 || lineWidth.roundToDouble() <= maxWidth.roundToDouble()) { _addToLineResult( - lineResult, - lines, - line, - lineWidth, - getLineTypeValue(LineType.newLineBreak)! | - getLineTypeValue(lineType)!); + lineResult, + lines, + line, + lineWidth, + getLineTypeValue(LineType.newLineBreak)! | getLineTypeValue(lineType)!, + ); } else { String builder = ''; String curLine = ''; @@ -167,12 +172,13 @@ class PdfStringLayouter { final String ln = builder; if (ln != ' ') { _addToLineResult( - lineResult, - lines, - ln, - lineWidth, - getLineTypeValue(LineType.layoutBreak)! | - getLineTypeValue(lineType)!); + lineResult, + lines, + ln, + lineWidth, + getLineTypeValue(LineType.layoutBreak)! | + getLineTypeValue(lineType)!, + ); } curLine = ''; builder = ''; @@ -203,12 +209,13 @@ class PdfStringLayouter { if (builder.isNotEmpty) { final String ln = builder; _addToLineResult( - lineResult, - lines, - ln, - lineWidth, - getLineTypeValue(LineType.newLineBreak)! | - getLineTypeValue(LineType.lastParagraphLine)!); + lineResult, + lines, + ln, + lineWidth, + getLineTypeValue(LineType.newLineBreak)! | + getLineTypeValue(LineType.lastParagraphLine)!, + ); } reader.close(); } @@ -217,8 +224,13 @@ class PdfStringLayouter { return lineResult; } - void _addToLineResult(PdfStringLayoutResult lineResult, List lines, - String line, double lineWidth, int breakType) { + void _addToLineResult( + PdfStringLayoutResult lineResult, + List lines, + String line, + double lineWidth, + int breakType, + ) { final LineInfo info = LineInfo(); info.text = line; info.width = lineWidth; @@ -266,10 +278,11 @@ class PdfStringLayouter { } dynamic _copyToResult( - PdfStringLayoutResult result, - PdfStringLayoutResult lineResult, - List lines, - int? numInserted) { + PdfStringLayoutResult result, + PdfStringLayoutResult lineResult, + List lines, + int? numInserted, + ) { bool success = true; final bool allowPartialLines = _format != null && !_format!.lineLimit; double? height = result.size.height; @@ -317,7 +330,8 @@ class PdfStringLayouter { LineInfo _trimLine(LineInfo info, bool firstLine) { String line = info.text.toString(); double? lineWidth = info.width; - final bool start = _format == null || + final bool start = + _format == null || _format!.textDirection != PdfTextDirection.rightToLeft; if (!info.lineTypeList.contains(LineType.firstParagraphLine)) { line = start ? line.trimLeft() : line.trimRight(); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_true_type_font.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_true_type_font.dart index 7e2b6be6d..2dccc099a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_true_type_font.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/pdf_true_type_font.dart @@ -45,8 +45,12 @@ class PdfTrueTypeFont extends PdfFont { /// //Dispose the document. /// document.dispose(); /// ``` - PdfTrueTypeFont(List fontData, double size, - {PdfFontStyle? style, List? multiStyle}) { + PdfTrueTypeFont( + List fontData, + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { _helper = PdfTrueTypeFontHelper(this); _initializeFont(fontData, size, style, multiStyle); } @@ -75,8 +79,12 @@ class PdfTrueTypeFont extends PdfFont { /// //Dispose the document. /// doc.dispose(); /// ``` - PdfTrueTypeFont.fromBase64String(String fontData, double size, - {PdfFontStyle? style, List? multiStyle}) { + PdfTrueTypeFont.fromBase64String( + String fontData, + double size, { + PdfFontStyle? style, + List? multiStyle, + }) { _helper = PdfTrueTypeFontHelper(this); if (fontData.isEmpty) { throw ArgumentError.value(fontData, 'fontData', 'Invalid font data'); @@ -88,10 +96,15 @@ class PdfTrueTypeFont extends PdfFont { late PdfTrueTypeFontHelper _helper; //Implementation - void _initializeFont(List fontData, double size, PdfFontStyle? style, - List? multiStyle) { - PdfFontHelper.getHelper(this) - .initialize(size, style: style, multiStyle: multiStyle); + void _initializeFont( + List fontData, + double size, + PdfFontStyle? style, + List? multiStyle, + ) { + PdfFontHelper.getHelper( + this, + ).initialize(size, style: style, multiStyle: multiStyle); _helper.unicode = true; _createFontInternals(fontData); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/arabic_shape_renderer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/arabic_shape_renderer.dart index a99e197af..b282ee41d 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/arabic_shape_renderer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/arabic_shape_renderer.dart @@ -86,7 +86,7 @@ class ArabicShapeRenderer { ['\u06CC', '\uFBFC', '\uFBFD', '\uFBFE', '\uFBFF'], ['\u06D0', '\uFBE4', '\uFBE5', '\uFBE6', '\uFBE7'], ['\u06D2', '\uFBAE', '\uFBAF'], - ['\u06D3', '\uFBB0', '\uFBB1'] + ['\u06D3', '\uFBB0', '\uFBB1'], ]; /// internal field diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/bidi.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/bidi.dart index 691a113f0..4f79df994 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/bidi.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/rtl/bidi.dart @@ -95,7 +95,7 @@ class Bidi { } return { 'rtlText': renderedString, - 'orderedIndexes': indexes + 'orderedIndexes': indexes, }; } @@ -155,8 +155,9 @@ class Bidi { for (int i = 0; i < text.length; i++) { if (((indexLevels[i] & 1) == 1) && mirroringShapeCharacters.containsKey(text[i].codeUnitAt(0))) { - result.write(String.fromCharCode( - mirroringShapeCharacters[text[i].codeUnitAt(0)]!)); + result.write( + String.fromCharCode(mirroringShapeCharacters[text[i].codeUnitAt(0)]!), + ); } else { result.write(text[i]); } @@ -580,8 +581,11 @@ class _RTLCharacters { // Specifies the resultant levels. late List levels; //sbyte // Specifies the RTL character types. - List rtlCharacterTypes = - List.filled(65536, 0, growable: true); //sbyte + List rtlCharacterTypes = List.filled( + 65536, + 0, + growable: true, + ); //sbyte // Left-to-Right (Non-European or non-Arabic digits). static const int l = 0; @@ -2352,7 +2356,7 @@ class _RTLCharacters { otn, 65534, 65535, - l + l, ]; // Implementations. @@ -2360,8 +2364,11 @@ class _RTLCharacters { types = getCharacterCode(inputText); textOrder = isRTL ? lre : l; doVisualOrder(); - final List result = - List.filled(this.result.length, 0, growable: true); + final List result = List.filled( + this.result.length, + 0, + growable: true, + ); for (int i = 0; i < levels.length; i++) { result[i] = levels[i].toUnsigned(8); } @@ -2369,8 +2376,11 @@ class _RTLCharacters { } List getCharacterCode(String text) { - final List characterCodes = - List.filled(text.length, 0, growable: true); + final List characterCodes = List.filled( + text.length, + 0, + growable: true, + ); for (int i = 0; i < text.length; i++) { characterCodes[i] = rtlCharacterTypes[text[i].codeUnitAt(0)]; } @@ -2497,7 +2507,12 @@ class _RTLCharacters { } void checkEuropeanDigits( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index; i < length; ++i) { if (result[i] == en) { for (int j = i - 1; j >= index; --j) { @@ -2514,7 +2529,12 @@ class _RTLCharacters { } void checkArabicCharacters( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index; i < length; ++i) { if (result[i] == al) { result[i] = r; @@ -2524,7 +2544,12 @@ class _RTLCharacters { } void checkEuropeanNumberSeparator( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index + 1; i < length - 1; ++i) { if (result[i] == es || result[i] == cs) { final int preview = result[i - 1]; @@ -2540,7 +2565,12 @@ class _RTLCharacters { } void checkEuropeanNumberTerminator( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index; i < length; ++i) { if (result[i] == et) { final int s = i; @@ -2575,7 +2605,12 @@ class _RTLCharacters { } void checkOtherNeutrals( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index; i < length; ++i) { if (result[i] == es || result[i] == et || result[i] == cs) { result[i] = otn; @@ -2585,7 +2620,12 @@ class _RTLCharacters { } void checkOtherCharacters( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index; i < length; ++i) { if (result[i] == en) { int pst = startType; @@ -2604,7 +2644,12 @@ class _RTLCharacters { } void checkCommanCharacters( - int index, int length, int level, int startType, int endType) { + int index, + int length, + int level, + int startType, + int endType, + ) { for (int i = index; i < length; ++i) { if (result[i] == ws || result[i] == otn || diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/ttf_reader.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/ttf_reader.dart index aed8f067e..07c26cfef 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/ttf_reader.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/ttf_reader.dart @@ -23,7 +23,7 @@ class TtfReader { 'hmtx', 'loca', 'maxp', - 'prep' + 'prep', ]; final List _entrySelectors = [ 0, @@ -46,7 +46,7 @@ class TtfReader { 4, 4, 4, - 4 + 4, ]; //Fields @@ -345,18 +345,21 @@ class TtfReader { } void _initializeMetrics( - _TtfNameTable nameTable, - _TtfHeadTable headTable, - _TtfHorizontalHeaderTable horizontalHeadTable, - _TtfOS2Table os2Table, - _TtfPostTable postTable, - List<_TtfCmapSubTable> cmapTables) { + _TtfNameTable nameTable, + _TtfHeadTable headTable, + _TtfHorizontalHeaderTable horizontalHeadTable, + _TtfOS2Table os2Table, + _TtfPostTable postTable, + List<_TtfCmapSubTable> cmapTables, + ) { _initializeFontName(nameTable); bool bSymbol = false; for (int i = 0; i < cmapTables.length; i++) { final _TtfCmapSubTable subTable = cmapTables[i]; - final _TtfCmapEncoding encoding = - _getCmapEncoding(subTable.platformID, subTable.encodingID); + final _TtfCmapEncoding encoding = _getCmapEncoding( + subTable.platformID, + subTable.encodingID, + ); if (encoding == _TtfCmapEncoding.symbol) { bSymbol = true; break; @@ -369,12 +372,14 @@ class TtfReader { final double factor = 1000 / headTable.unitsPerEm!; metrics!.winAscent = os2Table.sTypoAscender * factor; metrics!.macAscent = horizontalHeadTable.ascender * factor; - metrics!.capHeight = (os2Table.sCapHeight != 0) - ? os2Table.sCapHeight!.toDouble() - : 0.7 * headTable.unitsPerEm! * factor; + metrics!.capHeight = + (os2Table.sCapHeight != 0) + ? os2Table.sCapHeight!.toDouble() + : 0.7 * headTable.unitsPerEm! * factor; metrics!.winDescent = os2Table.sTypoDescender * factor; metrics!.macDescent = horizontalHeadTable.descender * factor; - metrics!.leading = (os2Table.sTypoAscender - + metrics!.leading = + (os2Table.sTypoAscender - os2Table.sTypoDescender + os2Table.sTypoLineGap) * factor; @@ -418,8 +423,10 @@ class TtfReader { final _TtfTableInfo tableInfo = _getTable('cmap')!; currentOffset = tableInfo.offset! + subTable.offset; final _TtfCmapFormat format = _getCmapFormat(_readUInt16(currentOffset!)); - final _TtfCmapEncoding encoding = - _getCmapEncoding(subTable.platformID, subTable.encodingID); + final _TtfCmapEncoding encoding = _getCmapEncoding( + subTable.platformID, + subTable.encodingID, + ); if (encoding != _TtfCmapEncoding.unknown) { switch (format) { case _TtfCmapFormat.apple: @@ -439,7 +446,9 @@ class TtfReader { } void _readUCS4CmapTable( - _TtfCmapSubTable subTable, _TtfCmapEncoding encoding) { + _TtfCmapSubTable subTable, + _TtfCmapEncoding encoding, + ) { final _TtfTableInfo tableInfo = _getTable('cmap')!; currentOffset = tableInfo.offset! + subTable.offset + 12; final int count = _readInt32(currentOffset!); @@ -459,7 +468,9 @@ class TtfReader { } void _readAppleCmapTable( - _TtfCmapSubTable subTable, _TtfCmapEncoding encoding) { + _TtfCmapSubTable subTable, + _TtfCmapEncoding encoding, + ) { final _TtfTableInfo tableInfo = _getTable('cmap')!; currentOffset = tableInfo.offset! + subTable.offset; final _TtfAppleCmapSubTable table = _TtfAppleCmapSubTable(); @@ -480,7 +491,9 @@ class TtfReader { } void _readMicrosoftCmapTable( - _TtfCmapSubTable subTable, _TtfCmapEncoding encoding) { + _TtfCmapSubTable subTable, + _TtfCmapEncoding encoding, + ) { final _TtfTableInfo tableInfo = _getTable('cmap')!; currentOffset = tableInfo.offset! + subTable.offset; final Map? collection = @@ -505,18 +518,21 @@ class TtfReader { int codeOffset = 0; int index = 0; for (int j = 0; j < segCount; j++) { - for (int k = table.startCount[j]; - k <= table.endCount[j] && k != 65535; - k++) { + for ( + int k = table.startCount[j]; + k <= table.endCount[j] && k != 65535; + k++ + ) { if (table.idRangeOffset[j] == 0) { codeOffset = (k + table.idDelta[j]) & 65535; } else { - index = (j + - table.idRangeOffset[j] / 2 - - segCount + - k - - table.startCount[j]) - .toInt(); + index = + (j + + table.idRangeOffset[j] / 2 - + segCount + + k - + table.startCount[j]) + .toInt(); if (index >= table.glyphID.length) { continue; } @@ -525,9 +541,10 @@ class TtfReader { final TtfGlyphInfo glyph = TtfGlyphInfo(); glyph.index = codeOffset; glyph.width = _getWidth(glyph.index); - final int id = (encoding == _TtfCmapEncoding.symbol) - ? ((k & 0xff00) == 0xf000 ? k & 0xff : k) - : k; + final int id = + (encoding == _TtfCmapEncoding.symbol) + ? ((k & 0xff00) == 0xf000 ? k & 0xff : k) + : k; glyph.charCode = id; collection![id] = glyph; _addGlyph(glyph, encoding); @@ -536,7 +553,9 @@ class TtfReader { } void _readTrimmedCmapTable( - _TtfCmapSubTable subTable, _TtfCmapEncoding encoding) { + _TtfCmapSubTable subTable, + _TtfCmapEncoding encoding, + ) { final _TtfTableInfo tableInfo = _getTable('cmap')!; currentOffset = tableInfo.offset! + subTable.offset; final _TtfTrimmedCmapSubTable table = _TtfTrimmedCmapSubTable(); @@ -605,15 +624,19 @@ class TtfReader { /// internal method double getCharWidth(String code) { TtfGlyphInfo? glyphInfo = getGlyph(char: code); - glyphInfo = (glyphInfo != null && !glyphInfo.empty) - ? glyphInfo - : _getDefaultGlyph(); + glyphInfo = + (glyphInfo != null && !glyphInfo.empty) + ? glyphInfo + : _getDefaultGlyph(); return (!glyphInfo!.empty) ? glyphInfo.width.toDouble() : 0; } /// internal method - TtfGlyphInfo? getGlyph( - {int? charCode, String? char, bool? isSetSymbol = false}) { + TtfGlyphInfo? getGlyph({ + int? charCode, + String? char, + bool? isSetSymbol = false, + }) { if (charCode != null) { TtfGlyphInfo? glyphInfo; if (!metrics!.isSymbol && _microsoftGlyphs != null) { @@ -647,7 +670,8 @@ class TtfReader { } if (_isLowSurrogate(code)) { if (_isSurrogatePair(_surrogateHigh, code)) { - code = (((_surrogateHigh >> 6) & ((1 << 5) - 1)) + 1) << 16 | + code = + (((_surrogateHigh >> 6) & ((1 << 5) - 1)) + 1) << 16 | ((_surrogateHigh & ((1 << 6) - 1)) << 10 | code & ((1 << 10) - 1)); if (_unicodeUCS4GlyphCollection!.containsKey(code)) { @@ -726,10 +750,18 @@ class TtfReader { final _TtfOS2Table os2Table = _readOS2Table(); final _TtfPostTable postTable = _readPostTable(); _width = _readWidthTable( - horizontalHeadTable.numberOfHMetrics, headTable.unitsPerEm); + horizontalHeadTable.numberOfHMetrics, + headTable.unitsPerEm, + ); final List<_TtfCmapSubTable> subTables = _readCmapTable(); - _initializeMetrics(nameTable, headTable, horizontalHeadTable, os2Table, - postTable, subTables); + _initializeMetrics( + nameTable, + headTable, + horizontalHeadTable, + os2Table, + postTable, + subTables, + ); } _TtfCmapFormat _getCmapFormat(int format) { @@ -866,7 +898,11 @@ class TtfReader { final int? newLocaSize = result['newLocaSize'] as int?; final List newLocaUpdated = result['newLocaUpdated'] as List; final List? fontProgram = _getFontProgram( - newLocaUpdated, newGlyphTable, glyphTableSize, newLocaSize); + newLocaUpdated, + newGlyphTable, + glyphTableSize, + newLocaSize, + ); return fontProgram; } @@ -891,7 +927,10 @@ class TtfReader { } dynamic _updateLocaTable( - List newLocaTable, bool isLocaShort, List? newLocaTableOut) { + List newLocaTable, + bool isLocaShort, + List? newLocaTableOut, + ) { final int size = isLocaShort ? newLocaTable.length * 2 : newLocaTable.length * 4; final int count = _align(size); @@ -907,7 +946,7 @@ class TtfReader { } return { 'newLocaUpdated': writer.data, - 'newLocaSize': size + 'newLocaSize': size, }; } @@ -926,7 +965,10 @@ class TtfReader { } void _processCompositeGlyph( - Map glyphChars, int glyph, List offsets) { + Map glyphChars, + int glyph, + List offsets, + ) { if (glyph < offsets.length - 1) { final int glyphOffset = offsets[glyph]; if (glyphOffset != offsets[glyph + 1]) { @@ -964,8 +1006,12 @@ class TtfReader { } } - dynamic _generateGlyphTable(Map glyphChars, List offsets, - List? newLocaTable, List? newGlyphTable) { + dynamic _generateGlyphTable( + Map glyphChars, + List offsets, + List? newLocaTable, + List? newGlyphTable, + ) { newLocaTable = []; final List activeGlyphs = glyphChars.keys.toList(); activeGlyphs.sort((int a, int b) => a - b); @@ -1004,7 +1050,7 @@ class TtfReader { return { 'glyphTableSize': glyphSize, 'newLocaTable': newLocaTable, - 'newGlyphTable': newGlyphTable + 'newGlyphTable': newGlyphTable, }; } @@ -1012,10 +1058,17 @@ class TtfReader { return (value + 3) & (~3); } - List? _getFontProgram(List newLocaTableOut, List newGlyphTable, - int? glyphTableSize, int? locaTableSize) { - final dynamic result = - _getFontProgramLength(newLocaTableOut, newGlyphTable, 0); + List? _getFontProgram( + List newLocaTableOut, + List newGlyphTable, + int? glyphTableSize, + int? locaTableSize, + ) { + final dynamic result = _getFontProgramLength( + newLocaTableOut, + newGlyphTable, + 0, + ); final int fontProgramLength = result['fontProgramLength'] as int; final int numTables = result['numTables'] as int; final BigEndianWriter writer = BigEndianWriter(fontProgramLength); @@ -1025,14 +1078,23 @@ class TtfReader { writer.writeShort((1 << (entrySelector & 31)) * 16); writer.writeShort(entrySelector); writer.writeShort((numTables - (1 << (entrySelector & 31))) * 16); - _writeCheckSums(writer, numTables, newLocaTableOut, newGlyphTable, - glyphTableSize, locaTableSize); + _writeCheckSums( + writer, + numTables, + newLocaTableOut, + newGlyphTable, + glyphTableSize, + locaTableSize, + ); _writeGlyphs(writer, newLocaTableOut, newGlyphTable); return writer.data; } dynamic _getFontProgramLength( - List newLocaTableOut, List newGlyphTable, int numTables) { + List newLocaTableOut, + List newGlyphTable, + int numTables, + ) { numTables = 2; final List tableNames = _tableNames; int fontProgramLength = 0; @@ -1052,17 +1114,18 @@ class TtfReader { fontProgramLength += usedTablesSize; return { 'fontProgramLength': fontProgramLength, - 'numTables': numTables + 'numTables': numTables, }; } void _writeCheckSums( - BigEndianWriter writer, - int numTables, - List newLocaTableOut, - List newGlyphTable, - int? glyphTableSize, - int? locaTableSize) { + BigEndianWriter writer, + int numTables, + List newLocaTableOut, + List newGlyphTable, + int? glyphTableSize, + int? locaTableSize, + ) { final List tableNames = _tableNames; int usedTablesSize = numTables * 16 + (3 * 4); int? nextTableSize = 0; @@ -1107,7 +1170,10 @@ class TtfReader { } void _writeGlyphs( - BigEndianWriter writer, List newLocaTable, List newGlyphTable) { + BigEndianWriter writer, + List newLocaTable, + List newGlyphTable, + ) { final List tableNames = _tableNames; for (int i = 0; i < tableNames.length; i++) { final String tableName = tableNames[i]; @@ -1230,9 +1296,11 @@ class TtfReader { int written = 0; int read = 0; do { - for (int i = 0; - i < count - written && currentOffset! + i < _fontData.length; - i++) { + for ( + int i = 0; + i < count - written && currentOffset! + i < _fontData.length; + i++ + ) { buffer[index + i] = _fontData[currentOffset! + i]; } read = count - written; @@ -1690,7 +1758,7 @@ enum _TtfCmapFormat { trimmed, /// This is the Microsoft standard character-to-glyph-index mapping table for fonts supporting Unicode supplementary-plane characters (U+10000 to U+10FFFF). - microsoftExt + microsoftExt, } /// Enumerator that implements CMAP encodings. @@ -1708,7 +1776,7 @@ enum _TtfCmapEncoding { macintosh, /// When building a Unicode font for Windows (plane characters). - unicodeUCS4 + unicodeUCS4, } /// Ttf platform ID. @@ -1723,7 +1791,7 @@ enum _TtfPlatformID { iso, /// Microsoft platform. - microsoft + microsoft, } /// Microsoft encoding ID. @@ -1735,7 +1803,7 @@ enum _TtfMicrosoftEncodingID { unicode, /// Unicode UCS4. - unicodeUCS4 + unicodeUCS4, } /// Macintosh encoding ID. @@ -1747,5 +1815,5 @@ enum _TtfMacintoshEncodingID { japanese, /// Chinese encoding. - chinese + chinese, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/unicode_true_type_font.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/unicode_true_type_font.dart index 46c7a834d..11eb4c6f7 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/unicode_true_type_font.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/fonts/unicode_true_type_font.dart @@ -158,17 +158,20 @@ class UnicodeTrueTypeFont { void _createDescendantFont() { _descendantFont!.beginSave = _descendantFontBeginSave; - _descendantFont![PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.font); - _descendantFont![PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.cidFontType2); + _descendantFont![PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.font, + ); + _descendantFont![PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.cidFontType2, + ); _descendantFont![PdfDictionaryProperties.baseFont] = PdfName(_subsetName); - _descendantFont![PdfDictionaryProperties.cidToGIDMap] = - PdfName(PdfDictionaryProperties.identity); + _descendantFont![PdfDictionaryProperties.cidToGIDMap] = PdfName( + PdfDictionaryProperties.identity, + ); _descendantFont![PdfDictionaryProperties.dw] = PdfNumber(1000); _fontDescriptor = _createFontDescriptor(); - _descendantFont![PdfDictionaryProperties.fontDescriptor] = - PdfReferenceHolder(_fontDescriptor); + _descendantFont![PdfDictionaryProperties + .fontDescriptor] = PdfReferenceHolder(_fontDescriptor); _descendantFont![PdfDictionaryProperties.cidSystemInfo] = _createSystemInfo(); } @@ -176,30 +179,42 @@ class UnicodeTrueTypeFont { PdfDictionary _createFontDescriptor() { final PdfDictionary descriptor = PdfDictionary(); final TtfMetrics metrics = reader.metrics!; - descriptor[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.fontDescriptor); + descriptor[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.fontDescriptor, + ); descriptor[PdfDictionaryProperties.fontName] = PdfName(_subsetName); - descriptor[PdfDictionaryProperties.flags] = - PdfNumber(_getDescriptorFlags()); + descriptor[PdfDictionaryProperties.flags] = PdfNumber( + _getDescriptorFlags(), + ); final PdfRectangle rect = reader.metrics!.fontBox; - descriptor[PdfDictionaryProperties.fontBBox] = PdfArray( - [rect.x, rect.y + rect.height, rect.width, -rect.height]); - descriptor[PdfDictionaryProperties.missingWidth] = - PdfNumber(metrics.widthTable[32]); + descriptor[PdfDictionaryProperties.fontBBox] = PdfArray([ + rect.x, + rect.y + rect.height, + rect.width, + -rect.height, + ]); + descriptor[PdfDictionaryProperties.missingWidth] = PdfNumber( + metrics.widthTable[32], + ); descriptor[PdfDictionaryProperties.stemV] = PdfNumber(metrics.stemV); - descriptor[PdfDictionaryProperties.italicAngle] = - PdfNumber(metrics.italicAngle!); - descriptor[PdfDictionaryProperties.capHeight] = - PdfNumber(metrics.capHeight); + descriptor[PdfDictionaryProperties.italicAngle] = PdfNumber( + metrics.italicAngle!, + ); + descriptor[PdfDictionaryProperties.capHeight] = PdfNumber( + metrics.capHeight, + ); descriptor[PdfDictionaryProperties.ascent] = PdfNumber(metrics.winAscent); descriptor[PdfDictionaryProperties.descent] = PdfNumber(metrics.winDescent); descriptor[PdfDictionaryProperties.leading] = PdfNumber(metrics.leading); - descriptor[PdfDictionaryProperties.avgWidth] = - PdfNumber(metrics.widthTable[32]); - descriptor[PdfDictionaryProperties.fontFile2] = - PdfReferenceHolder(_fontProgram); - descriptor[PdfDictionaryProperties.maxWidth] = - PdfNumber(metrics.widthTable[32]); + descriptor[PdfDictionaryProperties.avgWidth] = PdfNumber( + metrics.widthTable[32], + ); + descriptor[PdfDictionaryProperties.fontFile2] = PdfReferenceHolder( + _fontProgram, + ); + descriptor[PdfDictionaryProperties.maxWidth] = PdfNumber( + metrics.widthTable[32], + ); descriptor[PdfDictionaryProperties.xHeight] = PdfNumber(0); descriptor[PdfDictionaryProperties.stemH] = PdfNumber(0); return descriptor; @@ -228,8 +243,9 @@ class UnicodeTrueTypeFont { IPdfPrimitive _createSystemInfo() { final PdfDictionary systemInfo = PdfDictionary(); systemInfo[PdfDictionaryProperties.registry] = PdfString('Adobe'); - systemInfo[PdfDictionaryProperties.ordering] = - PdfString(PdfDictionaryProperties.identity); + systemInfo[PdfDictionaryProperties.ordering] = PdfString( + PdfDictionaryProperties.identity, + ); systemInfo[PdfDictionaryProperties.supplement] = PdfNumber(0); return systemInfo; } @@ -251,13 +267,16 @@ class UnicodeTrueTypeFont { void _createFontDictionary() { fontDictionary!.beginSave = _fontDictionaryBeginSave; - fontDictionary![PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.font); + fontDictionary![PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.font, + ); fontDictionary![PdfDictionaryProperties.baseFont] = PdfName(_subsetName); - fontDictionary![PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.type0); - fontDictionary![PdfDictionaryProperties.encoding] = - PdfName(PdfDictionaryProperties.identityH); + fontDictionary![PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.type0, + ); + fontDictionary![PdfDictionaryProperties.encoding] = PdfName( + PdfDictionaryProperties.identityH, + ); final PdfArray descFonts = PdfArray(); final PdfReferenceHolder reference = PdfReferenceHolder(_descendantFont); descFonts.add(reference); @@ -268,8 +287,9 @@ class UnicodeTrueTypeFont { if (_usedChars != null && _usedChars!.isNotEmpty && !fontDictionary!.containsKey(PdfDictionaryProperties.toUnicode)) { - fontDictionary![PdfDictionaryProperties.toUnicode] = - PdfReferenceHolder(_cmap); + fontDictionary![PdfDictionaryProperties.toUnicode] = PdfReferenceHolder( + _cmap, + ); } } @@ -285,8 +305,9 @@ class UnicodeTrueTypeFont { } glyphInfo.add(glyph); } - glyphInfo - .sort((TtfGlyphInfo a, TtfGlyphInfo b) => a.index.compareTo(b.index)); + glyphInfo.sort( + (TtfGlyphInfo a, TtfGlyphInfo b) => a.index.compareTo(b.index), + ); int firstGlyphIndex = 0; int lastGlyphIndex = 0; bool firstGlyphIndexWasSet = false; @@ -327,7 +348,8 @@ class UnicodeTrueTypeFont { keys.sort(); final int first = keys[0]; final int last = keys[keys.length - 1]; - final String middlePart = _getHexString(first, false) + + final String middlePart = + _getHexString(first, false) + _getHexString(last, false) + PdfOperators.newLine; String builder = ''; @@ -433,8 +455,9 @@ class UnicodeTrueTypeFont { void _fontDescriptorBeginSave(Object sender, SavePdfPrimitiveArgs? ars) { if ((_usedChars != null && _usedChars!.isNotEmpty) && !_fontDescriptor!.containsKey(PdfDictionaryProperties.cidSet)) { - _fontDescriptor![PdfDictionaryProperties.cidSet] = - PdfReferenceHolder(_cidStream); + _fontDescriptor![PdfDictionaryProperties.cidSet] = PdfReferenceHolder( + _cidStream, + ); } } @@ -448,7 +471,7 @@ class UnicodeTrueTypeFont { 0x08, 0x04, 0x02, - 0x01 + 0x01, ]; if (_usedChars != null && _usedChars!.isNotEmpty) { final Map glyphChars = reader.getGlyphChars(_usedChars!); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/image_decoder.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/image_decoder.dart index 5c96e9ee9..8d9044d54 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/image_decoder.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/image_decoder.dart @@ -97,7 +97,11 @@ abstract class ImageDecoder { /// internal method Map read( - List stream, int? streamOffset, List? buffer, int length) { + List stream, + int? streamOffset, + List? buffer, + int length, + ) { int result = 0; if (length <= stream.length && stream.length - streamOffset! >= length) { for (int i = 0; i < length; i++) { @@ -109,7 +113,7 @@ abstract class ImageDecoder { return { 'offset': streamOffset, 'outputBuffer': buffer, - 'length': result + 'length': result, }; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/jpeg_decoder.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/jpeg_decoder.dart index e5e427b3e..c03d15622 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/jpeg_decoder.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/jpeg_decoder.dart @@ -51,7 +51,7 @@ class JpegDecoder extends ImageDecoder { 46, 48, 47, - 0 + 0, ]; //Fields @@ -122,18 +122,23 @@ class JpegDecoder extends ImageDecoder { _imageStream!.data = imageData; _imageStream!.compress = false; - _imageStream![PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.xObject); - _imageStream![PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.image); + _imageStream![PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.xObject, + ); + _imageStream![PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.image, + ); _imageStream![PdfDictionaryProperties.width] = PdfNumber(width); _imageStream![PdfDictionaryProperties.height] = PdfNumber(height); - _imageStream![PdfDictionaryProperties.bitsPerComponent] = - PdfNumber(bitsPerComponent!); - _imageStream![PdfDictionaryProperties.filter] = - PdfName(PdfDictionaryProperties.dctDecode); - _imageStream![PdfDictionaryProperties.colorSpace] = - PdfName(_getColorSpace()); + _imageStream![PdfDictionaryProperties.bitsPerComponent] = PdfNumber( + bitsPerComponent!, + ); + _imageStream![PdfDictionaryProperties.filter] = PdfName( + PdfDictionaryProperties.dctDecode, + ); + _imageStream![PdfDictionaryProperties.colorSpace] = PdfName( + _getColorSpace(), + ); _imageStream![PdfDictionaryProperties.decodeParms] = _getDecodeParams(); return _imageStream; @@ -145,8 +150,9 @@ class JpegDecoder extends ImageDecoder { decodeParams[PdfDictionaryProperties.blackIs1] = PdfBoolean(true); decodeParams[PdfDictionaryProperties.k] = PdfNumber(-1); decodeParams[PdfDictionaryProperties.predictor] = PdfNumber(15); - decodeParams[PdfDictionaryProperties.bitsPerComponent] = - PdfNumber(bitsPerComponent!); + decodeParams[PdfDictionaryProperties.bitsPerComponent] = PdfNumber( + bitsPerComponent!, + ); return decodeParams; } @@ -156,7 +162,7 @@ class JpegDecoder extends ImageDecoder { if (_convertToUShort(_readJpegBytes(2)) != 0xFFD8) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } int? jpegMarkerStart; @@ -170,14 +176,14 @@ class JpegDecoder extends ImageDecoder { if (offset != jpegPosition || offset > imageData.length) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } } if (jpegMarkerStart != 0xFF || jpegMarkerNum != 0xE1) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } else { seek(2); @@ -185,7 +191,7 @@ class JpegDecoder extends ImageDecoder { _convertToUShort(_readJpegBytes(2)) != 0) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } final int tiffTypeHeaderStart = offset; @@ -194,15 +200,17 @@ class JpegDecoder extends ImageDecoder { if (_convertToUShort(_readJpegBytes(2)) != 0x002A) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } offset = _convertToUInt(_readJpegBytes(4)) + tiffTypeHeaderStart; final int ifdEntryCount = _convertToUShort(_readJpegBytes(2)); int orientationPosition = 0; - for (int currentIfdEntry = 0; - currentIfdEntry < ifdEntryCount; - currentIfdEntry++) { + for ( + int currentIfdEntry = 0; + currentIfdEntry < ifdEntryCount; + currentIfdEntry++ + ) { if (_convertToUShort(_readJpegBytes(2)) == 274) { orientationPosition = offset - 2; } @@ -213,7 +221,7 @@ class JpegDecoder extends ImageDecoder { if (_convertToUShort(_readJpegBytes(2)) != 274) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } seek(6); @@ -228,7 +236,7 @@ class JpegDecoder extends ImageDecoder { if (orientationAngle == 0) { return { 'hasOrientation': false, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } else { imageOrientation = orientationAngle; @@ -237,7 +245,7 @@ class JpegDecoder extends ImageDecoder { } return { 'hasOrientation': true, - 'imageOrientation': imageOrientation + 'imageOrientation': imageOrientation, }; } @@ -344,13 +352,16 @@ class JpegDecoder extends ImageDecoder { if (jfif == 0xE0FF) { while (true) { i += step; - int markerLength = - _convertToUShort([imageData[i + 1], imageData[i]]) - .toSigned(32); + int markerLength = _convertToUShort([ + imageData[i + 1], + imageData[i], + ]).toSigned(32); markerLength = (markerLength >> 8) | (markerLength << 8) & 0xFFFF; i += markerLength; - final int marker = - _convertToUShort([imageData[i + 1], imageData[i]]); + final int marker = _convertToUShort([ + imageData[i + 1], + imageData[i], + ]); if (marker == 0xDAFF) { i += step + 2; switch (imageData[i]) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/png_decoder.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/png_decoder.dart index fbbe779d6..f29f5aba0 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/png_decoder.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/decoders/png_decoder.dart @@ -231,7 +231,8 @@ class PngDecoder extends ImageDecoder { } void _decodeImageData() { - isDecode = (_header.interlace == 1) || + isDecode = + (_header.interlace == 1) || (_header.bitDepth == 16) || ((_header.colorType & 4) != 0) || _shades; @@ -267,8 +268,11 @@ class PngDecoder extends ImageDecoder { int? numRead = 0; final List outputData = []; do { - final Map result = - deflateStream.read(buffer, 0, buffer.length); + final Map result = deflateStream.read( + buffer, + 0, + buffer.length, + ); numRead = result['count'] as int?; buffer = result['data'] as List; for (int i = 0; i < numRead!; i++) { @@ -293,7 +297,13 @@ class PngDecoder extends ImageDecoder { } void _decodeData( - int xOffset, int yOffset, int xStep, int yStep, int? width, int? height) { + int xOffset, + int yOffset, + int xStep, + int yStep, + int? width, + int? height, + ) { if ((width == 0) || (height == 0)) { return; } else { @@ -301,13 +311,19 @@ class PngDecoder extends ImageDecoder { (_inputBands * width! * _header.bitDepth + 7) ~/ 8; List current = List.filled(bytesPerRow, 0); List prior = List.filled(bytesPerRow, 0); - for (int sourceY = 0, destinationY = yOffset; - sourceY < height!; - sourceY++, destinationY += yStep) { + for ( + int sourceY = 0, destinationY = yOffset; + sourceY < height!; + sourceY++, destinationY += yStep + ) { final int filter = _dataStream[_dataStreamOffset!]; _dataStreamOffset = _dataStreamOffset! + 1; - _dataStreamOffset = - _readStream(_dataStream, _dataStreamOffset, current, bytesPerRow); + _dataStreamOffset = _readStream( + _dataStream, + _dataStreamOffset, + current, + bytesPerRow, + ); switch (_getFilterType(filter)) { case _PngFilterTypes.none: break; @@ -333,7 +349,11 @@ class PngDecoder extends ImageDecoder { } int? _readStream( - List stream, int? streamOffset, List? data, int count) { + List stream, + int? streamOffset, + List? data, + int count, + ) { final dynamic result = read(stream, streamOffset, data, count); data = result['outputBuffer'] as List?; streamOffset = result['offset'] as int?; @@ -359,8 +379,16 @@ class PngDecoder extends ImageDecoder { final int depth = (_header.bitDepth == 16) ? 8 : _header.bitDepth; final int yStep = (size * width! * depth + 7) ~/ 8; for (sourceX = 0; sourceX < width; sourceX++) { - _decodedImageData = _setPixel(_decodedImageData, pixel, - _inputBands * sourceX, size, destX, y, _header.bitDepth, yStep); + _decodedImageData = _setPixel( + _decodedImageData, + pixel, + _inputBands * sourceX, + size, + destX, + y, + _header.bitDepth, + yStep, + ); destX += step; } } @@ -376,8 +404,16 @@ class PngDecoder extends ImageDecoder { final int? yStep = width; destX = x; for (sourceX = 0; sourceX < width!; sourceX++) { - _maskData = _setPixel(_maskData, pixel, _inputBands * sourceX + size, - 1, destX, y, 8, yStep); + _maskData = _setPixel( + _maskData, + pixel, + _inputBands * sourceX + size, + 1, + destX, + y, + 8, + yStep, + ); destX += step; } } else { @@ -406,16 +442,21 @@ class PngDecoder extends ImageDecoder { } return pixel; } else if (_header.bitDepth == 16) { - final List pixel = - List.filled(data.length ~/ 2, 0, growable: true); + final List pixel = List.filled( + data.length ~/ 2, + 0, + growable: true, + ); for (int i = 0; i < pixel.length; ++i) { pixel[i] = ((data[i * 2] & 0xff) << 8) + (data[i * 2 + 1] & 0xff); } return pixel; } else { final List pixel = List.filled( - data.length * 8 ~/ _header.bitDepth, 0, - growable: true); + data.length * 8 ~/ _header.bitDepth, + 0, + growable: true, + ); int index = 0; final int p = 8 ~/ _header.bitDepth; final int mask = (1 << _header.bitDepth) - 1; @@ -431,8 +472,16 @@ class PngDecoder extends ImageDecoder { } } - List? _setPixel(List? imageData, List data, int offset, - int size, int x, int y, int? bitDepth, int? bpr) { + List? _setPixel( + List? imageData, + List data, + int offset, + int size, + int x, + int y, + int? bitDepth, + int? bpr, + ) { if (bitDepth == 8) { final int position = bpr! * y + size * x; for (int i = 0; i < size; ++i) { @@ -445,7 +494,8 @@ class PngDecoder extends ImageDecoder { } } else { final int position = bpr! * y + x ~/ (8 / bitDepth!); - final int t = data[offset] << + final int t = + data[offset] << (8 - bitDepth * (x % (8 / bitDepth)) - bitDepth).toInt(); imageData![position] = imageData[position] | t.toUnsigned(8); } @@ -568,21 +618,25 @@ class PngDecoder extends ImageDecoder { const double greenY = 0.6; const double bX = 0.15; const double bY = 0.06; - const double t = wpY * + const double t = + wpY * ((greenX - bX) * redY - (redX - bX) * greenY + (redX - greenX) * bY); - const double alphaY = redY * + const double alphaY = + redY * ((greenX - bX) * wpY - (wpX - bX) * greenY + (wpX - greenX) * bY) / t; const double alphaX = alphaY * redX / redY; const double alphaZ = alphaY * ((1 - redX) / redY - 1); - const double blueY = -greenY * + const double blueY = + -greenY * ((redX - bX) * wpY - (wpX - bX) * redY + (wpX - redX) * bY) / t; const double blueX = blueY * greenX / greenY; const double blueZ = blueY * ((1 - greenX) / greenY - 1); - const double colorY = bY * + const double colorY = + bY * ((redX - greenX) * wpY - (wpX - greenX) * wpY + (wpX - redX) * greenY) / @@ -610,7 +664,9 @@ class PngDecoder extends ImageDecoder { calRGB.setProperty(PdfName(PdfDictionaryProperties.matrix), matrix); } calRGB.setProperty( - PdfName(PdfDictionaryProperties.whitePoint), whitePoint); + PdfName(PdfDictionaryProperties.whitePoint), + whitePoint, + ); colorspace.add(PdfName(PdfDictionaryProperties.calRGB)); colorspace.add(calRGB); return colorspace; @@ -621,22 +677,28 @@ class PngDecoder extends ImageDecoder { if (_maskData != null && _maskData!.isNotEmpty) { final PdfStream stream = PdfStream(); stream.data = _maskData; - stream[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.xObject); - stream[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.image); + stream[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.xObject, + ); + stream[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.image, + ); stream[PdfDictionaryProperties.width] = PdfNumber(width); stream[PdfDictionaryProperties.height] = PdfNumber(height); if (bitsPerComponent == 16) { stream[PdfDictionaryProperties.bitsPerComponent] = PdfNumber(8); } else { - stream[PdfDictionaryProperties.bitsPerComponent] = - PdfNumber(bitsPerComponent!); + stream[PdfDictionaryProperties.bitsPerComponent] = PdfNumber( + bitsPerComponent!, + ); } - stream[PdfDictionaryProperties.colorSpace] = - PdfName(PdfDictionaryProperties.deviceGray); + stream[PdfDictionaryProperties.colorSpace] = PdfName( + PdfDictionaryProperties.deviceGray, + ); imageStream.setProperty( - PdfName(PdfDictionaryProperties.sMask), PdfReferenceHolder(stream)); + PdfName(PdfDictionaryProperties.sMask), + PdfReferenceHolder(stream), + ); } } @@ -645,8 +707,9 @@ class PngDecoder extends ImageDecoder { decodeParams[PdfDictionaryProperties.columns] = PdfNumber(width); decodeParams[PdfDictionaryProperties.colors] = PdfNumber(_colors); decodeParams[PdfDictionaryProperties.predictor] = PdfNumber(15); - decodeParams[PdfDictionaryProperties.bitsPerComponent] = - PdfNumber(bitsPerComponent!); + decodeParams[PdfDictionaryProperties.bitsPerComponent] = PdfNumber( + bitsPerComponent!, + ); return decodeParams; } @@ -677,28 +740,34 @@ class PngDecoder extends ImageDecoder { } else { imageStream.compress = false; } - imageStream[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.xObject); - imageStream[PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.image); + imageStream[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.xObject, + ); + imageStream[PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.image, + ); imageStream[PdfDictionaryProperties.width] = PdfNumber(width); imageStream[PdfDictionaryProperties.height] = PdfNumber(height); if (bitsPerComponent == 16) { imageStream[PdfDictionaryProperties.bitsPerComponent] = PdfNumber(8); } else { - imageStream[PdfDictionaryProperties.bitsPerComponent] = - PdfNumber(bitsPerComponent!); + imageStream[PdfDictionaryProperties.bitsPerComponent] = PdfNumber( + bitsPerComponent!, + ); } if (!isDecode || !_ideateDecode) { - imageStream[PdfDictionaryProperties.filter] = - PdfName(PdfDictionaryProperties.flateDecode); + imageStream[PdfDictionaryProperties.filter] = PdfName( + PdfDictionaryProperties.flateDecode, + ); } if ((_header.colorType & 2) == 0) { - imageStream[PdfDictionaryProperties.colorSpace] = - PdfName(PdfDictionaryProperties.deviceGray); + imageStream[PdfDictionaryProperties.colorSpace] = PdfName( + PdfDictionaryProperties.deviceGray, + ); } else { - imageStream[PdfDictionaryProperties.colorSpace] = - PdfName(PdfDictionaryProperties.deviceRGB); + imageStream[PdfDictionaryProperties.colorSpace] = PdfName( + PdfDictionaryProperties.deviceRGB, + ); } if (!isDecode || _shades && !_ideateDecode) { imageStream[PdfDictionaryProperties.decodeParms] = _getDecodeParams(); @@ -745,7 +814,7 @@ enum _PngChunkTypes { sRGB, iCCP, iTXt, - unknown + unknown, } enum _PngFilterTypes { none, sub, up, average, paeth } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/enum.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/enum.dart index a381550eb..9c06b0129 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/enum.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/enum.dart @@ -4,5 +4,5 @@ enum ImageType { jpeg, /// PNG image format - png + png, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/pdf_bitmap.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/pdf_bitmap.dart index b7c908192..8743c97f1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/pdf_bitmap.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/images/pdf_bitmap.dart @@ -187,7 +187,9 @@ class PdfBitmap extends PdfImage { _width = _decoder!.width; } PdfImageHelper.setJpegOrientationAngle( - this, _decoder!.jpegDecoderOrientationAngle); + this, + _decoder!.jpegDecoderOrientationAngle, + ); _imageStatus = false; } else { throw UnsupportedError('Invalid/Unsupported image stream'); @@ -209,21 +211,38 @@ class PdfBitmap extends PdfImage { } switch (_helper.colorSpace) { case PdfColorSpace.cmyk: - stream[PdfDictionaryProperties.decode] = - PdfArray([1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]); - stream[PdfDictionaryProperties.colorSpace] = - PdfName(PdfDictionaryProperties.deviceCMYK); + stream[PdfDictionaryProperties.decode] = PdfArray([ + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + ]); + stream[PdfDictionaryProperties.colorSpace] = PdfName( + PdfDictionaryProperties.deviceCMYK, + ); break; case PdfColorSpace.grayScale: stream[PdfDictionaryProperties.decode] = PdfArray([0.0, 1.0]); - stream[PdfDictionaryProperties.colorSpace] = - PdfName(PdfDictionaryProperties.deviceGray); + stream[PdfDictionaryProperties.colorSpace] = PdfName( + PdfDictionaryProperties.deviceGray, + ); break; case PdfColorSpace.rgb: - stream[PdfDictionaryProperties.decode] = - PdfArray([0.0, 1.0, 0.0, 1.0, 0.0, 1.0]); - stream[PdfDictionaryProperties.colorSpace] = - PdfName(PdfDictionaryProperties.deviceRGB); + stream[PdfDictionaryProperties.decode] = PdfArray([ + 0.0, + 1.0, + 0.0, + 1.0, + 0.0, + 1.0, + ]); + stream[PdfDictionaryProperties.colorSpace] = PdfName( + PdfDictionaryProperties.deviceRGB, + ); break; case PdfColorSpace.indexed: stream[PdfDictionaryProperties.colorSpace] = @@ -257,7 +276,9 @@ class PdfBitmapHelper { if (!bitmap._imageStatus) { bitmap._imageStatus = true; PdfImageHelper.setImageStream( - bitmap, bitmap._decoder!.getImageDictionary()); + bitmap, + bitmap._decoder!.getImageDictionary(), + ); if (bitmap._decoder!.format == ImageType.png) { final PngDecoder? decoder = bitmap._decoder as PngDecoder?; if (decoder != null && decoder.isDecode) { @@ -275,8 +296,10 @@ class PdfBitmapHelper { /// internal method void drawInternal(PdfGraphics graphics, PdfRectangle bounds) { - graphics.drawImage(bitmap, - Rect.fromLTWH(0, 0, bitmap._width * 0.75, bitmap._height * 0.75)); + graphics.drawImage( + bitmap, + Rect.fromLTWH(0, 0, bitmap._width * 0.75, bitmap._height * 0.75), + ); } /// internal method diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_color.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_color.dart index 1dcc4d5ad..1a3316352 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_color.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_color.dart @@ -350,8 +350,10 @@ class PdfColorHelper { } /// internal method - static PdfArray toArray(PdfColor color, - [PdfColorSpace colorSpace = PdfColorSpace.rgb]) { + static PdfArray toArray( + PdfColor color, [ + PdfColorSpace colorSpace = PdfColorSpace.rgb, + ]) { return color._toArray(colorSpace); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_graphics.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_graphics.dart index efe6f5a97..a9e2d520a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_graphics.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_graphics.dart @@ -266,7 +266,9 @@ class PdfGraphics { } else { if (state._graphics != this) { throw ArgumentError.value( - this, 'The graphics state belongs to another graphics object'); + this, + 'The graphics state belongs to another graphics object', + ); } if (_graphicsState.contains(state)) { while (true) { @@ -304,8 +306,14 @@ class PdfGraphics { /// //Dispose the document. /// doc.dispose(); /// ``` - void drawString(String s, PdfFont font, - {PdfPen? pen, PdfBrush? brush, Rect? bounds, PdfStringFormat? format}) { + void drawString( + String s, + PdfFont font, { + PdfPen? pen, + PdfBrush? brush, + Rect? bounds, + PdfStringFormat? format, + }) { PdfRectangle layoutRectangle; if (bounds != null) { layoutRectangle = PdfRectangle.fromRect(bounds); @@ -318,11 +326,14 @@ class PdfGraphics { s = _normalizeText(font, s); - _helper.layoutString(s, font, - pen: pen, - brush: brush, - layoutRectangle: layoutRectangle, - format: format); + _helper.layoutString( + s, + font, + pen: pen, + brush: brush, + layoutRectangle: layoutRectangle, + format: format, + ); } /// Draws a line connecting the two points specified by the coordinate pairs. @@ -347,8 +358,9 @@ class PdfGraphics { _helper.streamWriter!.appendLineSegment(point2.dx, point2.dy); _helper.streamWriter!.strokePath(); _helper.endMarkContent(); - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.pdf); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.pdf, + ); } /// Draws a rectangle specified by a pen, a brush and a Rect structure. @@ -370,12 +382,17 @@ class PdfGraphics { void drawRectangle({PdfPen? pen, PdfBrush? brush, required Rect bounds}) { _helper._beginMarkContent(); _helper._stateControl(pen, brush, null, null); - _helper.streamWriter! - .appendRectangle(bounds.left, bounds.top, bounds.width, bounds.height); + _helper.streamWriter!.appendRectangle( + bounds.left, + bounds.top, + bounds.width, + bounds.height, + ); _drawPath(pen, brush, PdfFillMode.winding, false); _helper.endMarkContent(); - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.pdf); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.pdf, + ); } /// Draws a template at the specified location and size. @@ -438,8 +455,11 @@ class PdfGraphics { /// //Dispose the document. /// doc.dispose(); /// ``` - void setTransparency(double alpha, - {double? alphaBrush, PdfBlendMode mode = PdfBlendMode.normal}) { + void setTransparency( + double alpha, { + double? alphaBrush, + PdfBlendMode mode = PdfBlendMode.normal, + }) { if (alpha < 0 || alpha > 1) { ArgumentError.value(alpha, 'alpha', 'invalid alpha value'); } @@ -469,12 +489,18 @@ class PdfGraphics { if (bounds != null) { mode ??= PdfFillMode.winding; _helper.streamWriter!.appendRectangle( - bounds.left, bounds.top, bounds.width, bounds.height); + bounds.left, + bounds.top, + bounds.width, + bounds.height, + ); _helper.streamWriter!.clipPath(mode == PdfFillMode.alternate); } else if (path != null) { mode ??= PdfPathHelper.getHelper(path).fillMode; - _buildUpPath(PdfPathHelper.getHelper(path).points, - PdfPathHelper.getHelper(path).pathTypes); + _buildUpPath( + PdfPathHelper.getHelper(path).points, + PdfPathHelper.getHelper(path).pathTypes, + ); _helper.streamWriter!.clipPath(mode == PdfFillMode.alternate); } } @@ -496,15 +522,25 @@ class PdfGraphics { /// //Dispose the document. /// doc.dispose(); /// ``` - void drawBezier(Offset startPoint, Offset firstControlPoint, - Offset secondControlPoint, Offset endPoint, - {PdfPen? pen}) { + void drawBezier( + Offset startPoint, + Offset firstControlPoint, + Offset secondControlPoint, + Offset endPoint, { + PdfPen? pen, + }) { _helper._beginMarkContent(); _helper._stateControl(pen, null, null, null); final PdfStreamWriter sw = _helper.streamWriter!; sw.beginPath(startPoint.dx, startPoint.dy); - sw.appendBezierSegment(firstControlPoint.dx, firstControlPoint.dy, - secondControlPoint.dx, secondControlPoint.dy, endPoint.dx, endPoint.dy); + sw.appendBezierSegment( + firstControlPoint.dx, + firstControlPoint.dy, + secondControlPoint.dx, + secondControlPoint.dy, + endPoint.dx, + endPoint.dy, + ); sw.strokePath(); _helper.endMarkContent(); } @@ -532,8 +568,10 @@ class PdfGraphics { void drawPath(PdfPath path, {PdfPen? pen, PdfBrush? brush}) { _helper._beginMarkContent(); _helper._stateControl(pen, brush, null, null); - _buildUpPath(PdfPathHelper.getHelper(path).points, - PdfPathHelper.getHelper(path).pathTypes); + _buildUpPath( + PdfPathHelper.getHelper(path).points, + PdfPathHelper.getHelper(path).pathTypes, + ); _drawPath(pen, brush, PdfPathHelper.getHelper(path).fillMode, false); _helper.endMarkContent(); } @@ -555,15 +593,28 @@ class PdfGraphics { /// //Dispose the document. /// doc.dispose(); /// ``` - void drawPie(Rect bounds, double startAngle, double sweepAngle, - {PdfPen? pen, PdfBrush? brush}) { + void drawPie( + Rect bounds, + double startAngle, + double sweepAngle, { + PdfPen? pen, + PdfBrush? brush, + }) { if (sweepAngle != 0) { _helper._beginMarkContent(); _helper._stateControl(pen, brush, null, null); - _constructArcPath(bounds.left, bounds.top, bounds.left + bounds.width, - bounds.top + bounds.height, startAngle, sweepAngle); + _constructArcPath( + bounds.left, + bounds.top, + bounds.left + bounds.width, + bounds.top + bounds.height, + startAngle, + sweepAngle, + ); _helper.streamWriter!.appendLineSegment( - bounds.left + bounds.width / 2, bounds.top + bounds.height / 2); + bounds.left + bounds.width / 2, + bounds.top + bounds.height / 2, + ); _drawPath(pen, brush, PdfFillMode.winding, true); _helper.endMarkContent(); } @@ -589,7 +640,13 @@ class PdfGraphics { _helper._beginMarkContent(); _helper._stateControl(pen, brush, null, null); _constructArcPath( - bounds.left, bounds.top, bounds.right, bounds.bottom, 0, 360); + bounds.left, + bounds.top, + bounds.right, + bounds.bottom, + 0, + 360, + ); _drawPath(pen, brush, PdfFillMode.winding, true); _helper.endMarkContent(); } @@ -610,13 +667,23 @@ class PdfGraphics { /// //Dispose the document. /// doc.dispose(); /// ``` - void drawArc(Rect bounds, double startAngle, double sweepAngle, - {PdfPen? pen}) { + void drawArc( + Rect bounds, + double startAngle, + double sweepAngle, { + PdfPen? pen, + }) { if (sweepAngle != 0) { _helper._beginMarkContent(); _helper._stateControl(pen, null, null, null); - _constructArcPath(bounds.left, bounds.top, bounds.left + bounds.width, - bounds.top + bounds.height, startAngle, sweepAngle); + _constructArcPath( + bounds.left, + bounds.top, + bounds.left + bounds.width, + bounds.top + bounds.height, + startAngle, + sweepAngle, + ); _drawPath(pen, null, PdfFillMode.winding, false); _helper.endMarkContent(); } @@ -645,12 +712,16 @@ class PdfGraphics { return; } _helper._stateControl(pen, brush, null, null); - _helper.streamWriter! - .beginPath(points.elementAt(0).dx, points.elementAt(0).dy); + _helper.streamWriter!.beginPath( + points.elementAt(0).dx, + points.elementAt(0).dy, + ); for (int i = 1; i < points.length; ++i) { - _helper.streamWriter! - .appendLineSegment(points.elementAt(i).dx, points.elementAt(i).dy); + _helper.streamWriter!.appendLineSegment( + points.elementAt(i).dx, + points.elementAt(i).dy, + ); } _drawPath(pen, brush, PdfFillMode.winding, true); _helper.endMarkContent(); @@ -694,17 +765,23 @@ class PdfGraphics { _helper._previousTextScaling = -100.0; _helper.clipBounds = PdfRectangle(0, 0, size.width, size.height); _graphicsState = []; - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.pdf); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.pdf, + ); } void _drawImage(PdfImage image, Rect rectangle) { _helper._beginMarkContent(); final PdfRectangle bounds = PdfRectangle.fromRect( - (rectangle.width <= 0 && rectangle.height <= 0) - ? Rect.fromLTWH(rectangle.left, rectangle.top, image.width * 0.75, - image.height * 0.75) - : rectangle); + (rectangle.width <= 0 && rectangle.height <= 0) + ? Rect.fromLTWH( + rectangle.left, + rectangle.top, + image.width * 0.75, + image.height * 0.75, + ) + : rectangle, + ); PdfGraphicsState? beforeOrientation; final int angle = PdfImageHelper.getJpegOrientationAngle(image)!.toInt(); if (angle > 0) { @@ -760,21 +837,30 @@ class PdfGraphics { restore(beforeOrientation); } _helper.endMarkContent(); - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.grayScaleImage); - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.colorImage); - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.indexedImage); - (_helper._getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.text); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.grayScaleImage, + ); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.colorImage, + ); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.indexedImage, + ); + (_helper._getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.text, + ); } void _drawPath( - PdfPen? pen, PdfBrush? brush, PdfFillMode fillMode, bool needClosing) { + PdfPen? pen, + PdfBrush? brush, + PdfFillMode fillMode, + bool needClosing, + ) { final bool isPen = pen != null && PdfColorHelper.getHelper(pen.color).isFilled; - final bool isBrush = brush != null && + final bool isBrush = + brush != null && PdfColorHelper.getHelper((brush as PdfSolidBrush).color).isFilled; final bool isEvenOdd = fillMode == PdfFillMode.alternate; if (isPen && isBrush) { @@ -807,8 +893,8 @@ class PdfGraphics { if (_helper.layer != null && PdfPageHelper.getHelper(_helper.page!).document != null && PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).document!) - .conformanceLevel != + PdfPageHelper.getHelper(_helper.page!).document!, + ).conformanceLevel != PdfConformanceLevel.none && PdfGraphicsHelper.getHelper(template.graphics!)._currentFont != null && (PdfGraphicsHelper.getHelper(template.graphics!)._currentFont @@ -816,54 +902,61 @@ class PdfGraphics { PdfGraphicsHelper.getHelper(template.graphics!)._currentFont is PdfCjkStandardFont)) { throw ArgumentError( - 'All the fonts must be embedded in ${PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_helper.page!).document!).conformanceLevel} document.'); + 'All the fonts must be embedded in ${PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_helper.page!).document!).conformanceLevel} document.', + ); } else if (_helper.layer != null && PdfPageHelper.getHelper(_helper.page!).document != null && PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).document!) - .conformanceLevel == + PdfPageHelper.getHelper(_helper.page!).document!, + ).conformanceLevel == PdfConformanceLevel.a1b && PdfGraphicsHelper.getHelper(template.graphics!)._currentFont != null && PdfGraphicsHelper.getHelper(template.graphics!)._currentFont is PdfTrueTypeFont) { PdfTrueTypeFontHelper.getHelper( - PdfGraphicsHelper.getHelper(template.graphics!)._currentFont! - as PdfTrueTypeFont) - .fontInternal - .initializeCidSet(); + PdfGraphicsHelper.getHelper(template.graphics!)._currentFont! + as PdfTrueTypeFont, + ).fontInternal.initializeCidSet(); } if ((_helper.layer != null || _helper._documentLayer != null) && PdfTemplateHelper.getHelper(template).isLoadedPageTemplate) { PdfCrossTable? crossTable; if (PdfPageHelper.getHelper(_helper.page!).isLoadedPage) { if (PdfPageHelper.getHelper(_helper.page!).section != null) { - crossTable = PdfDocumentHelper.getHelper(PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).section!) - .document!) - .crossTable; + crossTable = + PdfDocumentHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(_helper.page!).section!, + ).document!, + ).crossTable; } else { - crossTable = PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).document!) - .crossTable; + crossTable = + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_helper.page!).document!, + ).crossTable; } } else { if (PdfPageHelper.getHelper(_helper.page!).section != null) { - crossTable = (PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).section!) - .document != - null) - ? PdfDocumentHelper.getHelper(PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).section!) - .document!) - .crossTable - : PdfDocumentHelper.getHelper(PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).section!) - .pdfDocument!) - .crossTable; + crossTable = + (PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(_helper.page!).section!, + ).document != + null) + ? PdfDocumentHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(_helper.page!).section!, + ).document!, + ).crossTable + : PdfDocumentHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(_helper.page!).section!, + ).pdfDocument!, + ).crossTable; } else { - crossTable = PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(_helper.page!).document!) - .crossTable; + crossTable = + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_helper.page!).document!, + ).crossTable; } } if ((PdfTemplateHelper.getHelper(template).isReadonly) || @@ -895,17 +988,21 @@ class PdfGraphics { PdfArray? cropBox; PdfArray? mediaBox; if (dictionary[PdfDictionaryProperties.cropBox] is PdfReferenceHolder) { - cropBox = (dictionary[PdfDictionaryProperties.cropBox]! - as PdfReferenceHolder) - .object as PdfArray?; + cropBox = + (dictionary[PdfDictionaryProperties.cropBox]! + as PdfReferenceHolder) + .object + as PdfArray?; } else { cropBox = dictionary[PdfDictionaryProperties.cropBox] as PdfArray?; } if (dictionary[PdfDictionaryProperties.mediaBox] is PdfReferenceHolder) { - mediaBox = (dictionary[PdfDictionaryProperties.mediaBox]! - as PdfReferenceHolder) - .object as PdfArray?; + mediaBox = + (dictionary[PdfDictionaryProperties.mediaBox]! + as PdfReferenceHolder) + .object + as PdfArray?; } else { mediaBox = dictionary[PdfDictionaryProperties.mediaBox] as PdfArray?; } @@ -919,9 +1016,11 @@ class PdfGraphics { PdfArray? mBox; if (dictionary[PdfDictionaryProperties.mediaBox] is PdfReferenceHolder) { - mBox = (dictionary[PdfDictionaryProperties.mediaBox]! - as PdfReferenceHolder) - .object as PdfArray?; + mBox = + (dictionary[PdfDictionaryProperties.mediaBox]! + as PdfReferenceHolder) + .object + as PdfArray?; } else { mBox = dictionary[PdfDictionaryProperties.mediaBox] as PdfArray?; } @@ -947,8 +1046,9 @@ class PdfGraphics { location.dx == 0 && location.dy == 0) { matrix.translate( - location.dx - PdfTemplateHelper.getHelper(template).origin.dx, - -(location.dy + size.height)); + location.dx - PdfTemplateHelper.getHelper(template).origin.dx, + -(location.dy + size.height), + ); } else { matrix.translate(location.dx, -(location.dy + size.height)); } @@ -966,20 +1066,29 @@ class PdfGraphics { final PdfGraphics? g = template.graphics; if (g != null) { - for (final Object? fieldInfo in PdfObjectCollectionHelper.getHelper( - PdfGraphicsHelper.getHelper(g).autoFields!) - .list) { + for (final Object? fieldInfo + in PdfObjectCollectionHelper.getHelper( + PdfGraphicsHelper.getHelper(g).autoFields!, + ).list) { if (fieldInfo is PdfAutomaticFieldInfo) { final PdfPoint newLocation = PdfPoint( - fieldInfo.location.x + location.dx, - fieldInfo.location.y + location.dy); + fieldInfo.location.x + location.dx, + fieldInfo.location.y + location.dy, + ); final double scalingX = template.size.width == 0 ? 0 : size.width / template.size.width; - final double scalingY = template.size.height == 0 - ? 0 - : size.height / template.size.height; - _helper.autoFields!.add(PdfAutomaticFieldInfo( - fieldInfo.field, newLocation, scalingX, scalingY)); + final double scalingY = + template.size.height == 0 + ? 0 + : size.height / template.size.height; + _helper.autoFields!.add( + PdfAutomaticFieldInfo( + fieldInfo.field, + newLocation, + scalingX, + scalingY, + ), + ); PdfPageHelper.getHelper(_helper.page!).dictionary!.modify(); } } @@ -1017,14 +1126,25 @@ class PdfGraphics { case PathPointType.bezier3: Offset? p2, p3; - final Map returnValue = - _getBezierPoints(points, types, i, p2, p3); + final Map returnValue = _getBezierPoints( + points, + types, + i, + p2, + p3, + ); i = returnValue['i'] as int; final List p = returnValue['points'] as List; p2 = p.first; p3 = p.last; _helper.streamWriter!.appendBezierSegment( - point.dx, point.dy, p2.dx, p2.dy, p3.dx, p3.dy); + point.dx, + point.dy, + p2.dx, + p2.dy, + p3.dx, + p3.dy, + ); break; case PathPointType.line: @@ -1038,8 +1158,13 @@ class PdfGraphics { } } - Map _getBezierPoints(List points, - List types, int i, Offset? p2, Offset? p3) { + Map _getBezierPoints( + List points, + List types, + int i, + Offset? p2, + Offset? p3, + ) { const String errorMsg = 'Malforming path.'; ++i; if (types[i] == PathPointType.bezier3) { @@ -1055,14 +1180,26 @@ class PdfGraphics { } return { 'i': i, - 'points': [p2, p3] + 'points': [p2, p3], }; } - void _constructArcPath(double x1, double y1, double x2, double y2, - double startAng, double sweepAngle) { - final List> points = - _getBezierArcPoints(x1, y1, x2, y2, startAng, sweepAngle); + void _constructArcPath( + double x1, + double y1, + double x2, + double y2, + double startAng, + double sweepAngle, + ) { + final List> points = _getBezierArcPoints( + x1, + y1, + x2, + y2, + startAng, + sweepAngle, + ); if (points.isEmpty) { return; } @@ -1070,13 +1207,25 @@ class PdfGraphics { _helper.streamWriter!.beginPath(pt[0], pt[1]); for (int i = 0; i < points.length; ++i) { pt = points.elementAt(i); - _helper.streamWriter! - .appendBezierSegment(pt[2], pt[3], pt[4], pt[5], pt[6], pt[7]); - } - } - - static List> _getBezierArcPoints(double x1, double y1, double x2, - double y2, double startAng, double extent) { + _helper.streamWriter!.appendBezierSegment( + pt[2], + pt[3], + pt[4], + pt[5], + pt[6], + pt[7], + ); + } + } + + static List> _getBezierArcPoints( + double x1, + double y1, + double x2, + double y2, + double startAng, + double extent, + ) { if (x1 > x2) { double tmp; tmp = x1; @@ -1123,7 +1272,7 @@ class PdfGraphics { xCen + rx * (cos1 + kappa * sin1), yCen - ry * (sin1 - kappa * cos1), xCen + rx * cos1, - yCen - ry * sin1 + yCen - ry * sin1, ]); } else { pointList.add([ @@ -1134,7 +1283,7 @@ class PdfGraphics { xCen + rx * (cos1 - kappa * sin1), yCen - ry * (sin1 + kappa * cos1), xCen + rx * cos1, - yCen - ry * sin1 + yCen - ry * sin1, ]); } } @@ -1142,7 +1291,10 @@ class PdfGraphics { } PdfTransformationMatrix _getSkewTransform( - double angleX, double angleY, PdfTransformationMatrix input) { + double angleX, + double angleY, + PdfTransformationMatrix input, + ) { input.skew(-angleX, -angleY); return input; } @@ -1318,7 +1470,7 @@ class PdfGraphicsHelper { PdfColorSpace.rgb: 'RGB', PdfColorSpace.cmyk: 'CMYK', PdfColorSpace.grayScale: 'GrayScale', - PdfColorSpace.indexed: 'Indexed' + PdfColorSpace.indexed: 'Indexed', }; PdfPen? _currentPen; bool _isItalic = false; @@ -1348,19 +1500,27 @@ class PdfGraphicsHelper { void applyTransparency(double alpha, double alphaBrush, PdfBlendMode mode) { _trasparencies ??= <_TransparencyData, PdfTransparency>{}; PdfTransparency? transparency; - final _TransparencyData transparencyData = - _TransparencyData(alpha, alphaBrush, mode); + final _TransparencyData transparencyData = _TransparencyData( + alpha, + alphaBrush, + mode, + ); if (_trasparencies!.containsKey(transparencyData)) { transparency = _trasparencies![transparencyData]; } if (transparency == null) { - transparency = PdfTransparency(alpha, alphaBrush, mode, - conformance: layer != null && - PdfPageHelper.getHelper(page!).document != null && - PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(page!).document!) - .conformanceLevel == - PdfConformanceLevel.a1b); + transparency = PdfTransparency( + alpha, + alphaBrush, + mode, + conformance: + layer != null && + PdfPageHelper.getHelper(page!).document != null && + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page!).document!, + ).conformanceLevel == + PdfConformanceLevel.a1b, + ); _trasparencies![transparencyData] = transparency; } final PdfResources resources = _getResources!() as PdfResources; @@ -1372,18 +1532,30 @@ class PdfGraphicsHelper { } /// internal method - void layoutString(String s, PdfFont font, - {PdfPen? pen, - PdfBrush? brush, - required PdfRectangle layoutRectangle, - PdfStringFormat? format}) { + void layoutString( + String s, + PdfFont font, { + PdfPen? pen, + PdfBrush? brush, + required PdfRectangle layoutRectangle, + PdfStringFormat? format, + }) { final PdfStringLayouter layouter = PdfStringLayouter(); PdfStringLayoutResult result; - result = layouter.layout(s, font, format, - width: layoutRectangle.width, height: layoutRectangle.height); + result = layouter.layout( + s, + font, + format, + width: layoutRectangle.width, + height: layoutRectangle.height, + ); if (!result.isEmpty) { final PdfRectangle rectangle = checkCorrectLayoutRectangle( - result.size, layoutRectangle.x, layoutRectangle.y, format); + result.size, + layoutRectangle.x, + layoutRectangle.y, + format, + ); if (layoutRectangle.width <= 0) { layoutRectangle.x = rectangle.x; layoutRectangle.width = rectangle.width; @@ -1397,74 +1569,86 @@ class PdfGraphicsHelper { } drawStringLayoutResult(result, font, pen, brush, layoutRectangle, format); stringLayoutResult = result; - (_getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.text); + (_getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.text, + ); } } /// internal method void drawStringLayoutResult( - PdfStringLayoutResult result, - PdfFont font, - PdfPen? pen, - PdfBrush? brush, - PdfRectangle layoutRectangle, - PdfStringFormat? format) { + PdfStringLayoutResult result, + PdfFont font, + PdfPen? pen, + PdfBrush? brush, + PdfRectangle layoutRectangle, + PdfStringFormat? format, + ) { if (!result.isEmpty) { _beginMarkContent(); PdfGraphicsState? gState; if (font is PdfTrueTypeFont && PdfTrueTypeFontHelper.getHelper(font).fontInternal.ttfMetrics != null && - !PdfTrueTypeFontHelper.getHelper(font) - .fontInternal - .ttfMetrics! - .isItalic && + !PdfTrueTypeFontHelper.getHelper( + font, + ).fontInternal.ttfMetrics!.isItalic && PdfFontHelper.getHelper(font).isItalic) { gState = base.save(); _isItalic = true; } _applyStringSettings(font, pen, brush, format, layoutRectangle); - final double textScaling = format != null - ? PdfStringFormatHelper.getHelper(format).scalingFactor - : 100.0; + final double textScaling = + format != null + ? PdfStringFormatHelper.getHelper(format).scalingFactor + : 100.0; if (textScaling != _previousTextScaling) { streamWriter!.setTextScaling(textScaling); _previousTextScaling = textScaling; } double verticalAlignShift = getTextVerticalAlignShift( - result.size.height, layoutRectangle.height, format); + result.size.height, + layoutRectangle.height, + format, + ); double? height; if (_isItalic) { - height = (format == null || format.lineSpacing == 0) - ? font.height - : format.lineSpacing + font.height; - final bool subScript = format != null && + height = + (format == null || format.lineSpacing == 0) + ? font.height + : format.lineSpacing + font.height; + final bool subScript = + format != null && format.subSuperscript == PdfSubSuperscript.subscript; - final double shift = subScript - ? height - - (font.height + - PdfFontHelper.getHelper(font).metrics!.getDescent(format)) - : (height - - PdfFontHelper.getHelper(font).metrics!.getAscent(format)); - base.translateTransform(layoutRectangle.left + font.size / 5, - layoutRectangle.top - shift + verticalAlignShift); + final double shift = + subScript + ? height - + (font.height + + PdfFontHelper.getHelper( + font, + ).metrics!.getDescent(format)) + : (height - + PdfFontHelper.getHelper(font).metrics!.getAscent(format)); + base.translateTransform( + layoutRectangle.left + font.size / 5, + layoutRectangle.top - shift + verticalAlignShift, + ); base.skewTransform(0, -11); } if (!_isItalic) { final PdfTransformationMatrix matrix = PdfTransformationMatrix(); matrix.translate( - layoutRectangle.x, - (-(layoutRectangle.y + font.height) - - (PdfFontHelper.getHelper(font).metrics!.getDescent(format) > - 0 - ? -PdfFontHelper.getHelper(font) - .metrics! - .getDescent(format) - : PdfFontHelper.getHelper(font) - .metrics! - .getDescent(format))) - - verticalAlignShift); + layoutRectangle.x, + (-(layoutRectangle.y + font.height) - + (PdfFontHelper.getHelper(font).metrics!.getDescent(format) > 0 + ? -PdfFontHelper.getHelper( + font, + ).metrics!.getDescent(format) + : PdfFontHelper.getHelper( + font, + ).metrics!.getDescent(format))) - + verticalAlignShift, + ); streamWriter!.modifyTransformationMatrix(matrix); } else { streamWriter!.startNextLine(0, 0); @@ -1482,8 +1666,10 @@ class PdfGraphicsHelper { } _drawLayoutResult(result, font, format, layoutRectangle); if (verticalAlignShift != 0) { - streamWriter! - .startNextLine(0, -(verticalAlignShift - result.lineHeight)); + streamWriter!.startNextLine( + 0, + -(verticalAlignShift - result.lineHeight), + ); } streamWriter!.endText(); if (gState != null) { @@ -1491,40 +1677,62 @@ class PdfGraphicsHelper { _isItalic = false; } _underlineStrikeoutText( - pen, brush, result, font, layoutRectangle, format); + pen, + brush, + result, + font, + layoutRectangle, + format, + ); endMarkContent(); } } - void _drawLayoutResult(PdfStringLayoutResult result, PdfFont font, - PdfStringFormat? format, PdfRectangle layoutRectangle) { + void _drawLayoutResult( + PdfStringLayoutResult result, + PdfFont font, + PdfStringFormat? format, + PdfRectangle layoutRectangle, + ) { bool? unicode = false; if (font is PdfTrueTypeFont) { unicode = PdfTrueTypeFontHelper.getHelper(font).unicode; } final List lines = result.lines!; - final double height = (format == null || format.lineSpacing == 0) - ? font.height - : format.lineSpacing + font.height; + final double height = + (format == null || format.lineSpacing == 0) + ? font.height + : format.lineSpacing + font.height; for (int i = 0; i < lines.length; i++) { final LineInfo lineInfo = lines[i]; final String? line = lineInfo.text; final double? lineWidth = lineInfo.width; if ((line == null || line.isEmpty) && !_isItalic) { final double verticalAlignShift = getTextVerticalAlignShift( - result.size.height, layoutRectangle.height, format); + result.size.height, + layoutRectangle.height, + format, + ); final PdfTransformationMatrix matrix = PdfTransformationMatrix(); - double baseline = (-(layoutRectangle.y + font.height) - + double baseline = + (-(layoutRectangle.y + font.height) - PdfFontHelper.getHelper(font).metrics!.getDescent(format)) - verticalAlignShift; baseline -= height * (i + 1); matrix.translate(layoutRectangle.x, baseline); streamWriter!.modifyTransformationMatrix(matrix); } else { - double horizontalAlignShift = - _getHorizontalAlignShift(lineWidth, layoutRectangle.width, format); - final double? lineIndent = - _getLineIndent(lineInfo, format, layoutRectangle, i == 0); + double horizontalAlignShift = _getHorizontalAlignShift( + lineWidth, + layoutRectangle.width, + format, + ); + final double? lineIndent = _getLineIndent( + lineInfo, + format, + layoutRectangle, + i == 0, + ); horizontalAlignShift += (!_rightToLeft(format)) ? lineIndent! : 0; if (horizontalAlignShift != 0) { @@ -1541,9 +1749,13 @@ class PdfGraphicsHelper { if (i + 1 != lines.length) { if (!_isItalic) { final double verticalAlignShift = getTextVerticalAlignShift( - result.size.height, layoutRectangle.height, format); + result.size.height, + layoutRectangle.height, + format, + ); final PdfTransformationMatrix matrix = PdfTransformationMatrix(); - double baseline = (-(layoutRectangle.y + font.height) - + double baseline = + (-(layoutRectangle.y + font.height) - PdfFontHelper.getHelper(font).metrics!.getDescent(format)) - verticalAlignShift; baseline -= height * (i + 1); @@ -1551,14 +1763,17 @@ class PdfGraphicsHelper { streamWriter!.modifyTransformationMatrix(matrix); } else { //tan(11) = 0.19486, theta value for italic skewAngle (11 degree). - streamWriter! - .startNextLine(font.height * 0.19486 - horizontalAlignShift, 0); + streamWriter!.startNextLine( + font.height * 0.19486 - horizontalAlignShift, + 0, + ); } } } } - (_getResources!() as PdfResources) - .requireProcset(PdfDictionaryProperties.text); + (_getResources!() as PdfResources).requireProcset( + PdfDictionaryProperties.text, + ); } bool _rightToLeft(PdfStringFormat? format) { @@ -1571,7 +1786,10 @@ class PdfGraphicsHelper { } double _getHorizontalAlignShift( - double? lineWidth, double boundsWidth, PdfStringFormat? format) { + double? lineWidth, + double boundsWidth, + PdfStringFormat? format, + ) { double shift = 0; if (boundsWidth >= 0 && format != null && @@ -1591,16 +1809,24 @@ class PdfGraphicsHelper { return shift; } - void _drawAsciiLine(LineInfo lineInfo, PdfRectangle layoutRectangle, - PdfFont font, PdfStringFormat? format) { + void _drawAsciiLine( + LineInfo lineInfo, + PdfRectangle layoutRectangle, + PdfFont font, + PdfStringFormat? format, + ) { _justifyLine(lineInfo, layoutRectangle.width, format); final PdfString str = PdfString(lineInfo.text!); str.isAsciiEncode = true; streamWriter!.showNextLineText(str); } - void _drawCjkString(LineInfo lineInfo, PdfRectangle layoutRectangle, - PdfFont font, PdfStringFormat? format) { + void _drawCjkString( + LineInfo lineInfo, + PdfRectangle layoutRectangle, + PdfFont font, + PdfStringFormat? format, + ) { _justifyLine(lineInfo, layoutRectangle.width, format); final String line = lineInfo.text!; final List str = _getCjkString(line); @@ -1617,8 +1843,9 @@ class PdfGraphicsHelper { if (format != null) { internalFont.setSymbols(line, ttfReader.internalUsedChars); } else { - PdfTrueTypeFontHelper.getHelper(font) - .setSymbols(text, ttfReader.internalUsedChars); + PdfTrueTypeFontHelper.getHelper( + font, + ).setSymbols(text, ttfReader.internalUsedChars); } ttfReader.internalUsedChars = null; final List bytes = PdfString.toUnicodeArray(text); @@ -1626,23 +1853,34 @@ class PdfGraphicsHelper { return text; } - void _drawUnicodeLine(LineInfo lineInfo, PdfRectangle layoutRectangle, - PdfFont font, PdfStringFormat? format) { + void _drawUnicodeLine( + LineInfo lineInfo, + PdfRectangle layoutRectangle, + PdfFont font, + PdfStringFormat? format, + ) { final String? line = lineInfo.text; - final bool useWordSpace = format != null && + final bool useWordSpace = + format != null && (format.wordSpacing != 0 || format.alignment == PdfTextAlignment.justify); final PdfTrueTypeFont ttfFont = font as PdfTrueTypeFont; - final double wordSpacing = - _justifyLine(lineInfo, layoutRectangle.width, format); + final double wordSpacing = _justifyLine( + lineInfo, + layoutRectangle.width, + format, + ); if (format != null && format.textDirection != PdfTextDirection.none) { final ArabicShapeRenderer renderer = ArabicShapeRenderer(); final String txt = renderer.shape(line!.split(''), 0); final Bidi bidi = Bidi(); bidi.isVisualOrder = false; - final String result = bidi.getLogicalToVisualString(txt, - format.textDirection == PdfTextDirection.rightToLeft)['rtlText'] - as String; + final String result = + bidi.getLogicalToVisualString( + txt, + format.textDirection == PdfTextDirection.rightToLeft, + )['rtlText'] + as String; bidi.isVisualOrder = true; final List blocks = []; if (useWordSpace) { @@ -1672,8 +1910,13 @@ class PdfGraphicsHelper { } } - void _drawUnicodeBlocks(List blocks, List words, - PdfTrueTypeFont font, PdfStringFormat? format, double wordSpacing) { + void _drawUnicodeBlocks( + List blocks, + List words, + PdfTrueTypeFont font, + PdfStringFormat? format, + double wordSpacing, + ) { streamWriter!.startNextLine(); double x = 0; double xShift = 0; @@ -1689,7 +1932,7 @@ class PdfGraphicsHelper { } double spaceWidth = PdfTrueTypeFontHelper.getHelper(font).getCharWidth(' ', format) + - wordSpacing; + wordSpacing; final double characterSpacing = format != null ? format.characterSpacing : 0; final double wordSpace = @@ -1727,7 +1970,10 @@ class PdfGraphicsHelper { } dynamic _breakUnicodeLine( - String line, PdfTrueTypeFont ttfFont, List? words) { + String line, + PdfTrueTypeFont ttfFont, + List? words, + ) { words = line.split(' '); final List tokens = []; for (int i = 0; i < words.length; i++) { @@ -1747,7 +1993,10 @@ class PdfGraphicsHelper { } int _getTextRenderingMode( - PdfPen? pen, PdfBrush? brush, PdfStringFormat? format) { + PdfPen? pen, + PdfBrush? brush, + PdfStringFormat? format, + ) { int tm = _TextRenderingMode.none; if (pen != null && brush != null) { tm = _TextRenderingMode.fillStroke; @@ -1762,16 +2011,20 @@ class PdfGraphicsHelper { return tm; } - void _applyStringSettings(PdfFont font, PdfPen? pen, PdfBrush? brush, - PdfStringFormat? format, PdfRectangle bounds) { + void _applyStringSettings( + PdfFont font, + PdfPen? pen, + PdfBrush? brush, + PdfStringFormat? format, + PdfRectangle bounds, + ) { int renderingMode = _getTextRenderingMode(pen, brush, format); bool setLineWidth = false; if (font is PdfTrueTypeFont && PdfTrueTypeFontHelper.getHelper(font).fontInternal.ttfMetrics != null && - !PdfTrueTypeFontHelper.getHelper(font) - .fontInternal - .ttfMetrics! - .isBold && + !PdfTrueTypeFontHelper.getHelper( + font, + ).fontInternal.ttfMetrics!.isBold && PdfFontHelper.getHelper(font).isBold) { if (pen == null && brush != null && brush is PdfSolidBrush) { pen = PdfPen(brush.color); @@ -1802,14 +2055,19 @@ class PdfGraphicsHelper { } void _stateControl( - PdfPen? pen, PdfBrush? brush, PdfFont? font, PdfStringFormat? format) { + PdfPen? pen, + PdfBrush? brush, + PdfFont? font, + PdfStringFormat? format, + ) { if (brush != null) { if (layer != null) { if (!PdfPageHelper.getHelper(page!).isLoadedPage && - !PdfDocumentHelper.getHelper(PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(page!).section!) - .pdfDocument!) - .isLoadedDocument) { + !PdfDocumentHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page!).section!, + ).pdfDocument!, + ).isLoadedDocument) { if (_colorSpaceChanged == false) { if (page != null) { base.colorSpace = @@ -1823,10 +2081,11 @@ class PdfGraphicsHelper { } else if (pen != null) { if (layer != null) { if (!PdfPageHelper.getHelper(page!).isLoadedPage && - !PdfDocumentHelper.getHelper(PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(page!).section!) - .pdfDocument!) - .isLoadedDocument) { + !PdfDocumentHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page!).section!, + ).pdfDocument!, + ).isLoadedDocument) { base.colorSpace = PdfPageHelper.getHelper(page!).document!.colorSpace; } } @@ -1840,9 +2099,13 @@ class PdfGraphicsHelper { void _initCurrentColorSpace(PdfColorSpace? colorspace) { if (!_isColorSpaceInitialized) { streamWriter!.setColorSpace( - PdfName('Device${_colorSpaces[base.colorSpace]!}'), true); + PdfName('Device${_colorSpaces[base.colorSpace]!}'), + true, + ); streamWriter!.setColorSpace( - PdfName('Device${_colorSpaces[base.colorSpace]!}'), false); + PdfName('Device${_colorSpaces[base.colorSpace]!}'), + false, + ); _isColorSpaceInitialized = true; } } @@ -1851,16 +2114,28 @@ class PdfGraphicsHelper { if (pen != null) { _currentPen = pen; base.colorSpace = PdfColorSpace.rgb; - PdfPenHelper.getHelper(pen).monitorChanges(_currentPen, streamWriter!, - _getResources, saveState, base.colorSpace, matrix); + PdfPenHelper.getHelper(pen).monitorChanges( + _currentPen, + streamWriter!, + _getResources, + saveState, + base.colorSpace, + matrix, + ); _currentPen = pen; } } void _brushControl(PdfBrush? brush, bool saveState) { if (brush != null) { - PdfBrushHelper.monitorChanges(brush as PdfSolidBrush, _currentBrush, - streamWriter, _getResources, saveState, base.colorSpace); + PdfBrushHelper.monitorChanges( + brush as PdfSolidBrush, + _currentBrush, + streamWriter, + _getResources, + saveState, + base.colorSpace, + ); _currentBrush = brush; brush = null; } @@ -1871,30 +2146,37 @@ class PdfGraphicsHelper { if ((font is PdfStandardFont || font is PdfCjkStandardFont) && layer != null && PdfPageHelper.getHelper(page!).document != null && - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!) - .conformanceLevel != + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page!).document!, + ).conformanceLevel != PdfConformanceLevel.none) { throw ArgumentError( - 'All the fonts must be embedded in ${PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!).conformanceLevel} document.'); + 'All the fonts must be embedded in ${PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!).conformanceLevel} document.', + ); } else if (font is PdfTrueTypeFont && layer != null && PdfPageHelper.getHelper(page!).document != null && - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page!).document!) - .conformanceLevel == + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page!).document!, + ).conformanceLevel == PdfConformanceLevel.a1b) { PdfTrueTypeFontHelper.getHelper(font).fontInternal.initializeCidSet(); } final PdfSubSuperscript current = format != null ? format.subSuperscript : PdfSubSuperscript.none; - final PdfSubSuperscript privious = currentStringFormat != null - ? currentStringFormat!.subSuperscript - : PdfSubSuperscript.none; + final PdfSubSuperscript privious = + currentStringFormat != null + ? currentStringFormat!.subSuperscript + : PdfSubSuperscript.none; if (saveState || font != _currentFont || current != privious) { final PdfResources resources = _getResources!() as PdfResources; _currentFont = font; currentStringFormat = format; - streamWriter!.setFont(font, resources.getName(font), - PdfFontHelper.getHelper(font).metrics!.getSize(format)!); + streamWriter!.setFont( + font, + resources.getName(font), + PdfFontHelper.getHelper(font).metrics!.getSize(format)!, + ); } } } @@ -1910,9 +2192,11 @@ class PdfGraphicsHelper { if (_documentLayer != null) { if (PdfLayerHelper.getHelper(_documentLayer!).isEndState && PdfLayerHelper.getHelper(_documentLayer!).parentLayer.isNotEmpty) { - for (int i = 0; - i < PdfLayerHelper.getHelper(_documentLayer!).parentLayer.length; - i++) { + for ( + int i = 0; + i < PdfLayerHelper.getHelper(_documentLayer!).parentLayer.length; + i++ + ) { streamWriter!.write('EMC\n'); } } @@ -1924,9 +2208,17 @@ class PdfGraphicsHelper { /// internal method PdfRectangle checkCorrectLayoutRectangle( - PdfSize textSize, double? x, double? y, PdfStringFormat? format) { - final PdfRectangle layoutedRectangle = - PdfRectangle(x!, y!, textSize.width, textSize.width); + PdfSize textSize, + double? x, + double? y, + PdfStringFormat? format, + ) { + final PdfRectangle layoutedRectangle = PdfRectangle( + x!, + y!, + textSize.width, + textSize.width, + ); if (format != null) { switch (format.alignment) { case PdfTextAlignment.center: @@ -1954,24 +2246,34 @@ class PdfGraphicsHelper { } void _underlineStrikeoutText( - PdfPen? pen, - PdfBrush? brush, - PdfStringLayoutResult result, - PdfFont font, - PdfRectangle layoutRectangle, - PdfStringFormat? format) { + PdfPen? pen, + PdfBrush? brush, + PdfStringLayoutResult result, + PdfFont font, + PdfRectangle layoutRectangle, + PdfStringFormat? format, + ) { if (PdfFontHelper.getHelper(font).isUnderline | PdfFontHelper.getHelper(font).isStrikeout) { - final PdfPen? linePen = - _createUnderlineStikeoutPen(pen, brush, font, format); + final PdfPen? linePen = _createUnderlineStikeoutPen( + pen, + brush, + font, + format, + ); if (linePen != null) { final double verticalShift = getTextVerticalAlignShift( - result.size.height, layoutRectangle.height, format); - double underlineYOffset = layoutRectangle.y + + result.size.height, + layoutRectangle.height, + format, + ); + double underlineYOffset = + layoutRectangle.y + verticalShift + PdfFontHelper.getHelper(font).metrics!.getAscent(format) + 1.5 * linePen.width; - double strikeoutYOffset = layoutRectangle.y + + double strikeoutYOffset = + layoutRectangle.y + verticalShift + PdfFontHelper.getHelper(font).metrics!.getHeight(format) / 2 + 1.5 * linePen.width; @@ -1980,9 +2282,16 @@ class PdfGraphicsHelper { final LineInfo lineInfo = lines![i]; final double? lineWidth = lineInfo.width; double horizontalShift = _getHorizontalAlignShift( - lineWidth, layoutRectangle.width, format); - final double? lineIndent = - _getLineIndent(lineInfo, format, layoutRectangle, i == 0); + lineWidth, + layoutRectangle.width, + format, + ); + final double? lineIndent = _getLineIndent( + lineInfo, + format, + layoutRectangle, + i == 0, + ); horizontalShift += (!_rightToLeft(format)) ? lineIndent! : 0; final double x1 = layoutRectangle.x + horizontalShift; final double x2 = @@ -1990,13 +2299,19 @@ class PdfGraphicsHelper { ? x1 + lineWidth! - lineIndent! : x1 + layoutRectangle.width - lineIndent!; if (PdfFontHelper.getHelper(font).isUnderline) { - base.drawLine(linePen, Offset(x1, underlineYOffset), - Offset(x2, underlineYOffset)); + base.drawLine( + linePen, + Offset(x1, underlineYOffset), + Offset(x2, underlineYOffset), + ); underlineYOffset += result.lineHeight; } if (PdfFontHelper.getHelper(font).isStrikeout) { - base.drawLine(linePen, Offset(x1, strikeoutYOffset), - Offset(x2, strikeoutYOffset)); + base.drawLine( + linePen, + Offset(x1, strikeoutYOffset), + Offset(x2, strikeoutYOffset), + ); strikeoutYOffset += result.lineHeight; } } @@ -2005,7 +2320,11 @@ class PdfGraphicsHelper { } PdfPen? _createUnderlineStikeoutPen( - PdfPen? pen, PdfBrush? brush, PdfFont font, PdfStringFormat? format) { + PdfPen? pen, + PdfBrush? brush, + PdfFont font, + PdfStringFormat? format, + ) { final double lineWidth = PdfFontHelper.getHelper(font).metrics!.getSize(format)! / 20; PdfPen? linePen; @@ -2054,7 +2373,11 @@ class PdfGraphicsHelper { this.clipBounds = clipBounds; streamWriter!.writeComment('Clip margins.'); streamWriter!.appendRectangle( - clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height); + clipBounds.x, + clipBounds.y, + clipBounds.width, + clipBounds.height, + ); streamWriter!.closePath(); streamWriter!.clipPath(false); streamWriter!.writeComment('Translate co-ordinate system.'); @@ -2062,14 +2385,28 @@ class PdfGraphicsHelper { } /// internal method - void clipTranslateMargins(double x, double y, double left, double top, - double right, double bottom) { - final PdfRectangle clipArea = PdfRectangle(left, top, - base.size.width - left - right, base.size.height - top - bottom); + void clipTranslateMargins( + double x, + double y, + double left, + double top, + double right, + double bottom, + ) { + final PdfRectangle clipArea = PdfRectangle( + left, + top, + base.size.width - left - right, + base.size.height - top - bottom, + ); clipBounds = clipArea; streamWriter!.writeComment('Clip margins.'); streamWriter!.appendRectangle( - clipBounds.x, clipBounds.y, clipBounds.width, clipBounds.height); + clipBounds.x, + clipBounds.y, + clipBounds.width, + clipBounds.height, + ); streamWriter!.closePath(); streamWriter!.clipPath(false); streamWriter!.writeComment('Translate co-ordinate system.'); @@ -2093,10 +2430,11 @@ class PdfGraphicsHelper { in PdfObjectCollectionHelper.getHelper(_automaticFields!).list) { if (fieldInfo is PdfAutomaticFieldInfo) { PdfAutomaticFieldHelper.getHelper(fieldInfo.field).performDraw( - base, - fieldInfo.location, - fieldInfo.scalingX, - fieldInfo.scalingY); + base, + fieldInfo.location, + fieldInfo.scalingX, + fieldInfo.scalingY, + ); } } } @@ -2125,7 +2463,10 @@ class PdfGraphicsHelper { /// internal method double getTextVerticalAlignShift( - double? textHeight, double boundsHeight, PdfStringFormat? format) { + double? textHeight, + double boundsHeight, + PdfStringFormat? format, + ) { double shift = 0; if (boundsHeight >= 0 && format != null && @@ -2145,20 +2486,35 @@ class PdfGraphicsHelper { } /// internal method - Rect getLineBounds(int lineIndex, PdfStringLayoutResult result, PdfFont font, - PdfRectangle layoutRectangle, PdfStringFormat? format) { + Rect getLineBounds( + int lineIndex, + PdfStringLayoutResult result, + PdfFont font, + PdfRectangle layoutRectangle, + PdfStringFormat? format, + ) { PdfRectangle bounds = PdfRectangle.empty; if (!result.isEmpty && lineIndex < result.lineCount && lineIndex >= 0) { final LineInfo line = result.lines![lineIndex]; final double verticalShift = getTextVerticalAlignShift( - result.size.height, layoutRectangle.height, format); + result.size.height, + layoutRectangle.height, + format, + ); final double y = verticalShift + layoutRectangle.y + (result.lineHeight * lineIndex); final double? lineWidth = line.width; - double horizontalShift = - _getHorizontalAlignShift(lineWidth, layoutRectangle.width, format); - final double? lineIndent = - _getLineIndent(line, format, layoutRectangle, lineIndex == 0); + double horizontalShift = _getHorizontalAlignShift( + lineWidth, + layoutRectangle.width, + format, + ); + final double? lineIndent = _getLineIndent( + line, + format, + layoutRectangle, + lineIndex == 0, + ); horizontalShift += (!_rightToLeft(format)) ? lineIndent! : 0; final double x = layoutRectangle.x + horizontalShift; final double width = @@ -2171,19 +2527,28 @@ class PdfGraphicsHelper { return bounds.rect; } - double? _getLineIndent(LineInfo lineInfo, PdfStringFormat? format, - PdfRectangle layoutBounds, bool firstLine) { + double? _getLineIndent( + LineInfo lineInfo, + PdfStringFormat? format, + PdfRectangle layoutBounds, + bool firstLine, + ) { double? lineIndent = 0; - final bool firstParagraphLine = (lineInfo.lineType & + final bool firstParagraphLine = + (lineInfo.lineType & PdfStringLayouter.getLineTypeValue(LineType.firstParagraphLine)!) > 0; if (format != null && firstParagraphLine) { - lineIndent = firstLine - ? PdfStringFormatHelper.getHelper(format).firstLineIndent - : format.paragraphIndent; - lineIndent = (layoutBounds.width > 0) - ? (layoutBounds.width <= lineIndent ? layoutBounds.width : lineIndent) - : lineIndent; + lineIndent = + firstLine + ? PdfStringFormatHelper.getHelper(format).firstLineIndent + : format.paragraphIndent; + lineIndent = + (layoutBounds.width > 0) + ? (layoutBounds.width <= lineIndent + ? layoutBounds.width + : lineIndent) + : lineIndent; } return lineIndent; } @@ -2193,8 +2558,9 @@ class PdfGraphicsHelper { final TtfReader ttfReader = PdfTrueTypeFontHelper.getHelper(font).fontInternal.reader; token = ttfReader.convertString(text); - PdfTrueTypeFontHelper.getHelper(font) - .setSymbols(text, ttfReader.internalUsedChars); + PdfTrueTypeFontHelper.getHelper( + font, + ).setSymbols(text, ttfReader.internalUsedChars); ttfReader.internalUsedChars = null; final List bytes = PdfString.toUnicodeArray(token); token = PdfString.byteToString(bytes); @@ -2208,13 +2574,18 @@ class PdfGraphicsHelper { } double _justifyLine( - LineInfo lineInfo, double boundsWidth, PdfStringFormat? format) { + LineInfo lineInfo, + double boundsWidth, + PdfStringFormat? format, + ) { final String line = lineInfo.text!; double? lineWidth = lineInfo.width; final bool shouldJustify = _shouldJustify(lineInfo, boundsWidth, format); final bool hasWordSpacing = format != null && format.wordSpacing != 0; - final int whitespacesCount = - StringTokenizer.getCharacterCount(line, StringTokenizer.spaces); + final int whitespacesCount = StringTokenizer.getCharacterCount( + line, + StringTokenizer.spaces, + ); double wordSpace = 0; if (shouldJustify) { if (hasWordSpacing) { @@ -2230,17 +2601,23 @@ class PdfGraphicsHelper { } bool _shouldJustify( - LineInfo lineInfo, double boundsWidth, PdfStringFormat? format) { + LineInfo lineInfo, + double boundsWidth, + PdfStringFormat? format, + ) { final String line = lineInfo.text!; final double? lineWidth = lineInfo.width; final bool justifyStyle = format != null && format.alignment == PdfTextAlignment.justify; final bool goodWidth = boundsWidth >= 0 && lineWidth! < boundsWidth; - final int whitespacesCount = - StringTokenizer.getCharacterCount(line, StringTokenizer.spaces); + final int whitespacesCount = StringTokenizer.getCharacterCount( + line, + StringTokenizer.spaces, + ); final bool hasSpaces = whitespacesCount > 0 && line[0] != StringTokenizer.whiteSpace; - final bool goodLineBreakStyle = (lineInfo.lineType & + final bool goodLineBreakStyle = + (lineInfo.lineType & PdfStringLayouter.getLineTypeValue(LineType.layoutBreak)!) > 0; final bool shouldJustify = @@ -2249,8 +2626,14 @@ class PdfGraphicsHelper { } /// internal method - static List> getBezierArcPoints(double x1, double y1, double x2, - double y2, double startAng, double extent) { + static List> getBezierArcPoints( + double x1, + double y1, + double x2, + double y2, + double startAng, + double extent, + ) { return PdfGraphics._getBezierArcPoints(x1, y1, x2, y2, startAng, extent); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pen.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pen.dart index c91a0e3e9..2d22693ea 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pen.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pen.dart @@ -35,11 +35,13 @@ class PdfPen { /// //Close the document. /// doc.dispose(); /// ``` - PdfPen(PdfColor pdfColor, - {double width = 1.0, - PdfDashStyle dashStyle = PdfDashStyle.solid, - PdfLineCap lineCap = PdfLineCap.flat, - PdfLineJoin lineJoin = PdfLineJoin.miter}) { + PdfPen( + PdfColor pdfColor, { + double width = 1.0, + PdfDashStyle dashStyle = PdfDashStyle.solid, + PdfLineCap lineCap = PdfLineCap.flat, + PdfLineJoin lineJoin = PdfLineJoin.miter, + }) { _helper = PdfPenHelper(this); _color = pdfColor; _initialize(width, dashStyle, lineCap, lineJoin); @@ -59,11 +61,13 @@ class PdfPen { /// //Close the document. /// doc.dispose(); /// ``` - PdfPen.fromBrush(PdfBrush brush, - {double width = 1.0, - PdfDashStyle dashStyle = PdfDashStyle.solid, - PdfLineCap lineCap = PdfLineCap.flat, - PdfLineJoin lineJoin = PdfLineJoin.miter}) { + PdfPen.fromBrush( + PdfBrush brush, { + double width = 1.0, + PdfDashStyle dashStyle = PdfDashStyle.solid, + PdfLineCap lineCap = PdfLineCap.flat, + PdfLineJoin lineJoin = PdfLineJoin.miter, + }) { _helper = PdfPenHelper(this); _setBrush(brush); _width = width; @@ -179,7 +183,8 @@ class PdfPen { set dashPattern(List value) { if (dashStyle == PdfDashStyle.solid) { UnsupportedError( - 'This operation is not allowed. Set Custom dash style to change the pattern.'); + 'This operation is not allowed. Set Custom dash style to change the pattern.', + ); } _checkImmutability(); _dashPattern = value; @@ -344,8 +349,12 @@ class PdfPen { } } - void _initialize(double width, PdfDashStyle dashStyle, PdfLineCap lineCap, - PdfLineJoin lineJoin) { + void _initialize( + double width, + PdfDashStyle dashStyle, + PdfLineCap lineCap, + PdfLineJoin lineJoin, + ) { _width = width; _colorSpace = PdfColorSpace.rgb; _dashOffset = 0; @@ -390,12 +399,13 @@ class PdfPenHelper { /// internal method bool monitorChanges( - PdfPen? currentPen, - PdfStreamWriter streamWriter, - Function? getResources, - bool saveState, - PdfColorSpace? currentColorSpace, - PdfTransformationMatrix? matrix) { + PdfPen? currentPen, + PdfStreamWriter streamWriter, + Function? getResources, + bool saveState, + PdfColorSpace? currentColorSpace, + PdfTransformationMatrix? matrix, + ) { bool diff = false; saveState = true; if (currentPen == null) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pens.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pens.dart index 0c8795a7c..04bf34579 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pens.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_pens.dart @@ -3208,8 +3208,9 @@ class PdfPens { static PdfPen _getPen(KnownColor kColor) { final ColorHelper color = ColorHelper(kColor); - final PdfPen pen = - PdfPenHelper.immutable(PdfColor(color.r, color.g, color.b, color.a)); + final PdfPen pen = PdfPenHelper.immutable( + PdfColor(color.r, color.g, color.b, color.a), + ); _pens[kColor] = pen; return pen; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_resources.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_resources.dart index c67936ce5..9054a6838 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_resources.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_resources.dart @@ -113,8 +113,9 @@ class PdfResources extends PdfDictionary { PdfDictionary? xObjects; final PdfName xobjectName = PdfName(PdfDictionaryProperties.xObject); if (this[xobjectName] is PdfReferenceHolder) { - xObjects = (this[xobjectName] as PdfReferenceHolder?)?.object - as PdfDictionary?; + xObjects = + (this[xobjectName] as PdfReferenceHolder?)?.object + as PdfDictionary?; } else if (this[xobjectName] is PdfDictionary) { xObjects = this[xobjectName] as PdfDictionary?; } @@ -139,7 +140,8 @@ class PdfResources extends PdfDictionary { } if (dictionary != null) { dictionary.items!.forEach( - (PdfName? name, IPdfPrimitive? value) => _addName(name, value)); + (PdfName? name, IPdfPrimitive? value) => _addName(name, value), + ); } } return _resourceNames; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transformation_matrix.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transformation_matrix.dart index 6477f5f93..ab629a1d3 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transformation_matrix.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transformation_matrix.dart @@ -32,7 +32,8 @@ class PdfTransformationMatrix { /// internal method void rotate(double angle) { angle = double.parse( - (angle * 3.1415926535897931 / 180).toStringAsExponential(9)); + (angle * 3.1415926535897931 / 180).toStringAsExponential(9), + ); matrix.elements[0] = cos(angle); matrix.elements[1] = sin(angle); matrix.elements[2] = -sin(angle); @@ -41,14 +42,16 @@ class PdfTransformationMatrix { /// internal method void skew(double angleX, double angleY) { - matrix.multiply(Matrix([ - 1, - tan((pi / 180) * angleX), - tan((pi / 180) * angleY), - 1, - 0, - 0 - ])); + matrix.multiply( + Matrix([ + 1, + tan((pi / 180) * angleX), + tan((pi / 180) * angleY), + 1, + 0, + 0, + ]), + ); } /// internal method @@ -118,9 +121,11 @@ class Matrix { (elements[2] * matrix.elements[0]) + (elements[3] * matrix.elements[2]); tempMatrix[3] = (elements[2] * matrix.elements[1]) + (elements[3] * matrix.elements[3]); - tempMatrix[4] = (_offsetX! * matrix.elements[0]) + + tempMatrix[4] = + (_offsetX! * matrix.elements[0]) + (_offsetY! * matrix.elements[2] + matrix._offsetX!); - tempMatrix[5] = (_offsetX! * matrix.elements[1]) + + tempMatrix[5] = + (_offsetX! * matrix.elements[1]) + (_offsetY! * matrix.elements[3] + matrix._offsetY!); for (int i = 0; i < tempMatrix.length; i++) { elements[i] = tempMatrix[i]; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transparency.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transparency.dart index 959e551ba..087cec332 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transparency.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/graphics/pdf_transparency.dart @@ -9,16 +9,26 @@ import 'enums.dart'; class PdfTransparency implements IPdfWrapper { //Constructor /// internal constructor - PdfTransparency(double stroke, double fill, PdfBlendMode mode, - {bool conformance = false}) { + PdfTransparency( + double stroke, + double fill, + PdfBlendMode mode, { + bool conformance = false, + }) { dictionary = PdfDictionary(); if (stroke < 0) { throw ArgumentError.value( - stroke, 'stroke', 'The value cannot be less then zero.'); + stroke, + 'stroke', + 'The value cannot be less then zero.', + ); } if (fill < 0) { throw ArgumentError.value( - fill, 'fill', 'The value cannot be less then zero.'); + fill, + 'fill', + 'The value cannot be less then zero.', + ); } //NOTE : This is needed to attain PDF/A conformance. Since PDF/A1B //does not support transparency key. diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/big_endian_writer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/big_endian_writer.dart index 843e04a38..b3397f55c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/big_endian_writer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/big_endian_writer.dart @@ -37,7 +37,7 @@ class BigEndianWriter { void writeShort(int value) { final List bytes = [ (value & 0x0000ff00) >> 8, - value & 0x000000ff + value & 0x000000ff, ]; _flush(bytes); } @@ -56,7 +56,7 @@ class BigEndianWriter { (value & 0xff000000) >> 24, (value & 0x00ff0000) >> 16, (value & 0x0000ff00) >> 8, - value & 0x000000ff + value & 0x000000ff, ]; _flush(bytes); } @@ -67,7 +67,7 @@ class BigEndianWriter { (value & 0xff000000) >> 24, (value & 0x00ff0000) >> 16, (value & 0x0000ff00) >> 8, - value & 0x000000ff + value & 0x000000ff, ]; _flush(buff); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/cross_table.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/cross_table.dart index 69be7e5e6..08324b35a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/cross_table.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/cross_table.dart @@ -119,7 +119,9 @@ class CrossTable { final int startingOffset = _checkJunk(); if (startingOffset < 0) { ArgumentError.value( - startingOffset, 'Could not find valid signature (%PDF-)'); + startingOffset, + 'Could not find valid signature (%PDF-)', + ); } objects = {}; PdfReader reader = this.reader; @@ -156,8 +158,9 @@ class CrossTable { startCrossReference = position; _parser!.setOffset(position); if (_whiteSpace != 0) { - final int crossReferencePosition = - reader.searchForward(PdfOperators.crossReference); + final int crossReferencePosition = reader.searchForward( + PdfOperators.crossReference, + ); if (crossReferencePosition == -1) { isForwardSearch = false; position += _whiteSpace; @@ -198,8 +201,10 @@ class CrossTable { } reader.position = position; try { - final Map tempResult = - parser.parseCrossReferenceTable(objects, this); + final Map tempResult = parser.parseCrossReferenceTable( + objects, + this, + ); trailer = tempResult['object'] as PdfDictionary?; objects = tempResult['objects'] as Map; } catch (e) { @@ -213,9 +218,9 @@ class CrossTable { number.value = number.value! + _whiteSpace; _isStructureAltered = true; } - position = (trailerObj[PdfDictionaryProperties.prev]! as PdfNumber) - .value! - .toInt(); + position = + (trailerObj[PdfDictionaryProperties.prev]! as PdfNumber).value! + .toInt(); final PdfReader tokenReader = PdfReader(_reader!.streamReader.data); tokenReader.position = position; String? token = tokenReader.getNextToken(); @@ -227,8 +232,8 @@ class CrossTable { token = tokenReader.getNextToken(); if (token == PdfDictionaryProperties.obj) { parser.setOffset(position); - final Map tempResults = - parser.parseCrossReferenceTable(objects, this); + final Map tempResults = parser + .parseCrossReferenceTable(objects, this); trailerObj = tempResults['object'] as PdfDictionary; objects = tempResults['objects'] as Map; parser.setOffset(position); @@ -239,8 +244,8 @@ class CrossTable { break; } else { parser.setOffset(position); - final Map tempResults = - parser.parseCrossReferenceTable(objects, this); + final Map tempResults = parser + .parseCrossReferenceTable(objects, this); trailerObj = tempResults['object'] as PdfDictionary; objects = tempResults['objects'] as Map; if (trailerObj.containsKey(PdfDictionaryProperties.size) && @@ -259,8 +264,11 @@ class CrossTable { for (int i = 0; i < objKey.length; i++) { final int key = objKey[i]; final ObjectInformation info = objects[key]!; - objects[key] = - ObjectInformation(info._offset! + _whiteSpace, null, this); + objects[key] = ObjectInformation( + info._offset! + _whiteSpace, + null, + this, + ); } _isStructureAltered = true; } else if (_whiteSpace != 0 && _whiteSpace > 0 && !_isStructureAltered) { @@ -319,7 +327,9 @@ class CrossTable { /// internal method Map? parseNewTable( - PdfStream? stream, Map? objects) { + PdfStream? stream, + Map? objects, + ) { if (stream == null) { throw ArgumentError.value(stream, 'Invalid format'); } @@ -328,8 +338,12 @@ class CrossTable { int? ssIndex = 0; for (int i = 0; i < subSections.length; i++) { final _SubSection ss = subSections[i]; - final Map result = - _parseWithHashTable(stream, ss, objects, ssIndex); + final Map result = _parseWithHashTable( + stream, + ss, + objects, + ssIndex, + ); ssIndex = result['index'] as int?; objects = result['objects'] as Map?; } @@ -337,10 +351,11 @@ class CrossTable { } Map _parseWithHashTable( - PdfStream stream, - _SubSection subsection, - Map? table, - int? startIndex) { + PdfStream stream, + _SubSection subsection, + Map? table, + int? startIndex, + ) { int? index = startIndex; final IPdfPrimitive? entry = getObject(stream[PdfDictionaryProperties.w]); if (entry is PdfArray) { @@ -505,8 +520,9 @@ class CrossTable { do { final int length = _data.length - position < 1024 ? (_data.length - position) : 1024; - final String header = - String.fromCharCodes(_data.sublist(position, length)); + final String header = String.fromCharCodes( + _data.sublist(position, length), + ); index = header.indexOf('%PDF-'); position += length; } while (index < 0 && position != _data.length); @@ -560,7 +576,10 @@ class ObjectInformation { //Constructor /// internal constructor ObjectInformation( - int offset, ArchiveInformation? arciveInfo, CrossTable? crossTable) { + int offset, + ArchiveInformation? arciveInfo, + CrossTable? crossTable, + ) { _offset = offset; _archive = arciveInfo; _crossTable = crossTable; @@ -594,8 +613,11 @@ class ObjectInformation { if (archieveNumber != null) { pairs = archieveNumber.value!.toInt(); } - final List indices = - List.filled(pairs * 2, 0, growable: true); + final List indices = List.filled( + pairs * 2, + 0, + growable: true, + ); for (int i = 0; i < pairs; ++i) { PdfNumber? obj = parser.simple() as PdfNumber?; if (obj != null) { @@ -609,7 +631,9 @@ class ObjectInformation { final int index = _archive!._index; if (index * 2 >= indices.length) { throw ArgumentError.value( - _archive!._archiveNumber, 'Missing indexes in archive'); + _archive!._archiveNumber, + 'Missing indexes in archive', + ); } _offset = indices[index * 2 + 1]; final int first = diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/decode_big_endian.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/decode_big_endian.dart index 7e68d754c..724d63a98 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/decode_big_endian.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/decode_big_endian.dart @@ -6,12 +6,19 @@ String decodeBigEndian(List? bytes, [int offset = 0, int? length]) { return String.fromCharCodes(result); } -List _convertCodeUnitsToCodePoints(List codeUnits, - [int offset = 0, int? length]) { - final UtfCodeUnitDecoder decoder = - UtfCodeUnitDecoder(ByteRange(codeUnits, offset, length)); - final List codePoints = - List.filled(decoder.byteRange.remaining, 0, growable: true); +List _convertCodeUnitsToCodePoints( + List codeUnits, [ + int offset = 0, + int? length, +]) { + final UtfCodeUnitDecoder decoder = UtfCodeUnitDecoder( + ByteRange(codeUnits, offset, length), + ); + final List codePoints = List.filled( + decoder.byteRange.remaining, + 0, + growable: true, + ); int i = 0; while (decoder.moveNext) { codePoints[i++] = decoder._current!; @@ -177,8 +184,11 @@ class UtfCodeUnitDecoder { /// internal method List encodeBigEndian(String content) { final List codeUnits = _codePointsToCodeUnits(content.codeUnits); - final List encodedBytes = - List.filled(2 * codeUnits.length, 0, growable: true); + final List encodedBytes = List.filled( + 2 * codeUnits.length, + 0, + growable: true, + ); int i = 0; for (final int value in codeUnits) { encodedBytes[i++] = (value & 0xff00) >> 8; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/enums.dart index ba480f31f..e83a88334 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/enums.dart @@ -5,7 +5,7 @@ enum PdfObjectStatus { none, /// internal enumerator - registered + registered, } /// Represents a type of an object. @@ -15,9 +15,9 @@ enum PdfObjectType { /// internal enumerator normal, -// ignore: unused_field + // ignore: unused_field /// internal enumerator - packed + packed, } /// internal enumerator @@ -104,5 +104,5 @@ enum PdfTokenType { hexStringWeirdEscape, /// internal enumerator - whiteSpace + whiteSpace, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/object_info.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/object_info.dart index ee2d6f9e5..4f18ef9a1 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/object_info.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/object_info.dart @@ -41,7 +41,9 @@ class PdfObjectInfo { void setReference(PdfReference reference) { if (this.reference != null) { throw ArgumentError.value( - this.reference, 'The object has the reference bound to it.'); + this.reference, + 'The object has the reference bound to it.', + ); } this.reference = reference; } @@ -50,7 +52,9 @@ class PdfObjectInfo { Future setReferenceAsync(PdfReference reference) async { if (this.reference != null) { throw ArgumentError.value( - this.reference, 'The object has the reference bound to it.'); + this.reference, + 'The object has the reference bound to it.', + ); } this.reference = reference; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_archive_stream.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_archive_stream.dart index 4055f8dc8..366c39dbe 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_archive_stream.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_archive_stream.dart @@ -18,16 +18,16 @@ class PdfArchiveStream extends PdfStream { PdfArchiveStream(PdfDocument? document) : super() { ArgumentError.notNull('document'); _document = document; - _objects = []; - _objectWriter = PdfWriter(_objects); - _objectWriter!.document = _document; + _objects = PdfBytesBuilder(); _indices = {}; + _objectWriter = PdfWriter(null, _objects); + _objectWriter!.document = _document; } // Fields PdfDocument? _document; IPdfWriter? _objectWriter; - late List _objects; + late PdfBytesBuilder _objects; Map? _indices; late PdfArchiveStreamWriter _writer; @@ -49,12 +49,11 @@ class PdfArchiveStream extends PdfStream { // Implementation @override void save(IPdfWriter? writer) { - final List data = []; - _writer = PdfArchiveStreamWriter(data); + _writer = PdfArchiveStreamWriter([]); _saveIndices(); this[PdfDictionaryProperties.first] = PdfNumber(_writer.position!); _saveObjects(); - super.data = _writer._buffer; + super.data = _writer._builder!.takeBytes(); this[PdfDictionaryProperties.n] = PdfNumber(_indices!.length); this[PdfDictionaryProperties.type] = PdfName('ObjStm'); super.save(writer); @@ -63,7 +62,7 @@ class PdfArchiveStream extends PdfStream { void _saveIndices() { for (final Object? position in _indices!.keys) { if (position is int) { - _writer = PdfArchiveStreamWriter(_writer._buffer!); + _writer = PdfArchiveStreamWriter(_writer._builder!.takeBytes()); _writer.write(_indices![position]); _writer.write(PdfOperators.whiteSpace); _writer.write(position); @@ -73,7 +72,7 @@ class PdfArchiveStream extends PdfStream { } void _saveObjects() { - _writer._buffer!.addAll(_objects); + _writer._builder!.add(_objects.takeBytes()); } /// internal method @@ -91,7 +90,9 @@ class PdfArchiveStream extends PdfStream { /// internal method Future saveObjectAsync( - IPdfPrimitive obj, PdfReference reference) async { + IPdfPrimitive obj, + PdfReference reference, + ) async { final int? position = _objectWriter!.position; _indices![position] = reference.objNum; final PdfEncryptor encryptor = @@ -108,24 +109,25 @@ class PdfArchiveStream extends PdfStream { class PdfArchiveStreamWriter extends IPdfWriter { // Constructor /// internal constructor - PdfArchiveStreamWriter(List buffer) { - _buffer = buffer; - length = buffer.length; - position = buffer.length; + PdfArchiveStreamWriter(List? data) { + _builder = PdfBytesBuilder(); + if (data != null) { + _builder!.add(data); + } + length = _builder!.length; + position = _builder!.length; } //Fields - List? _buffer; + PdfBytesBuilder? _builder; @override // ignore: avoid_renaming_method_parameters void write(dynamic data) { if (data is List) { - for (int i = 0; i < data.length; i++) { - _buffer!.add(data[i]); - } - length = _buffer!.length; - position = _buffer!.length; + _builder!.add(data); + length = _builder!.length; + position = _builder!.length; } else if (data is String) { write(utf8.encode(data)); } else if (data is int) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_cross_table.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_cross_table.dart index a0b9bd001..444bc483c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_cross_table.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_cross_table.dart @@ -46,8 +46,11 @@ class PdfCrossTable { } /// internal constructor - PdfCrossTable.fromCatalog(int tableCount, PdfDictionary? encryptionDictionary, - this.pdfDocumentCatalog) { + PdfCrossTable.fromCatalog( + int tableCount, + PdfDictionary? encryptionDictionary, + this.pdfDocumentCatalog, + ) { _storedCount = tableCount; _encryptorDictionary = encryptionDictionary; _bForceNew = true; @@ -132,8 +135,9 @@ class PdfCrossTable { PdfDictionary? get encryptorDictionary { if (_encryptorDictionary == null && trailer!.containsKey(PdfDictionaryProperties.encrypt)) { - final IPdfPrimitive? primitive = - dereference(trailer![PdfDictionaryProperties.encrypt]); + final IPdfPrimitive? primitive = dereference( + trailer![PdfDictionaryProperties.encrypt], + ); if (primitive is PdfDictionary) { _encryptorDictionary = primitive; } @@ -196,9 +200,9 @@ class PdfCrossTable { trailer!.items!.forEach((PdfName? name, IPdfPrimitive? element) { if (element is PdfReferenceHolder) { final PdfReferenceHolder rh = element; - if (!PdfDocumentHelper.getHelper(document!) - .objects - .contains(rh.object!)) { + if (!PdfDocumentHelper.getHelper( + document!, + ).objects.contains(rh.object!)) { PdfDocumentHelper.getHelper(document!).objects.add(rh.object); } } @@ -209,9 +213,9 @@ class PdfCrossTable { trailer!.items!.forEach((PdfName? name, IPdfPrimitive? element) { if (element is PdfReferenceHolder) { final PdfReferenceHolder rh = element; - if (!PdfDocumentHelper.getHelper(document!) - .objects - .contains(rh.object!)) { + if (!PdfDocumentHelper.getHelper( + document!, + ).objects.contains(rh.object!)) { PdfDocumentHelper.getHelper(document!).objects.add(rh.object); } } @@ -242,7 +246,10 @@ class PdfCrossTable { if (_isCrossReferenceStream(writer.document)) { PdfReference? xRefReference; final Map returnedValue = _prepareXRefStream( - prevXRef.toDouble(), referencePosition!.toDouble(), xRefReference); + prevXRef.toDouble(), + referencePosition!.toDouble(), + xRefReference, + ); final PdfStream xRefStream = returnedValue['xRefStream']! as PdfStream; xRefReference = returnedValue['reference'] as PdfReference?; xRefStream.blockEncryption = true; @@ -278,8 +285,11 @@ class PdfCrossTable { if (await _isCrossReferenceStreamAsync(writer.document)) { await _saveArchivesAsync(writer); } - await _registerObjectAsync(PdfReference(0, -1), - position: 0, isFreeType: true); + await _registerObjectAsync( + PdfReference(0, -1), + position: 0, + isFreeType: true, + ); final int? referencePosition = writer.position; final int prevXRef = crossTable == null ? 0 : crossTable!.startCrossReference; @@ -287,8 +297,10 @@ class PdfCrossTable { PdfReference? xRefReference; PdfStream? xRefStream; await _prepareXRefStreamAsync( - prevXRef.toDouble(), referencePosition!.toDouble(), xRefReference) - .then((Map returnedValue) { + prevXRef.toDouble(), + referencePosition!.toDouble(), + xRefReference, + ).then((Map returnedValue) { xRefStream = returnedValue['xRefStream']! as PdfStream; xRefReference = returnedValue['reference'] as PdfReference?; }); @@ -325,8 +337,9 @@ class PdfCrossTable { final String version = await _generateFileVersionAsync(writer.document!); await writer.writeAsync(version).then((_) async { await writer.writeAsync(PdfOperators.newLine).then((_) async { - await writer - .writeAsync([0x25, 0x83, 0x92, 0xfa, 0xfe]).then((_) async { + await writer.writeAsync([0x25, 0x83, 0x92, 0xfa, 0xfe]).then(( + _, + ) async { await writer.writeAsync(PdfOperators.newLine); }); }); @@ -417,16 +430,17 @@ class PdfCrossTable { PdfDocumentHelper.getHelper(document!).objects.add(securityDictionary); securityDictionary.position = -1; } - securityDictionary = PdfSecurityHelper.getHelper(security) - .encryptor - .saveToDictionary(securityDictionary); + securityDictionary = PdfSecurityHelper.getHelper( + security, + ).encryptor.saveToDictionary(securityDictionary); trailer![PdfDictionaryProperties.id] = PdfSecurityHelper.getHelper(security).encryptor.fileID; - trailer![PdfDictionaryProperties.encrypt] = - PdfReferenceHolder(securityDictionary); - } else if (!PdfSecurityHelper.getHelper(security) - .encryptor - .encryptOnlyAttachment) { + trailer![PdfDictionaryProperties.encrypt] = PdfReferenceHolder( + securityDictionary, + ); + } else if (!PdfSecurityHelper.getHelper( + security, + ).encryptor.encryptOnlyAttachment) { if (trailer!.containsKey(PdfDictionaryProperties.encrypt)) { trailer!.remove(PdfDictionaryProperties.encrypt); } @@ -448,16 +462,17 @@ class PdfCrossTable { PdfDocumentHelper.getHelper(document!).objects.add(securityDictionary); securityDictionary.position = -1; } - securityDictionary = await PdfSecurityHelper.getHelper(security) - .encryptor - .saveToDictionaryAsync(securityDictionary); + securityDictionary = await PdfSecurityHelper.getHelper( + security, + ).encryptor.saveToDictionaryAsync(securityDictionary); trailer![PdfDictionaryProperties.id] = PdfSecurityHelper.getHelper(security).encryptor.fileID; - trailer![PdfDictionaryProperties.encrypt] = - PdfReferenceHolder(securityDictionary); - } else if (!PdfSecurityHelper.getHelper(security) - .encryptor - .encryptOnlyAttachment) { + trailer![PdfDictionaryProperties.encrypt] = PdfReferenceHolder( + securityDictionary, + ); + } else if (!PdfSecurityHelper.getHelper( + security, + ).encryptor.encryptOnlyAttachment) { if (trailer!.containsKey(PdfDictionaryProperties.encrypt)) { trailer!.remove(PdfDictionaryProperties.encrypt); } @@ -513,7 +528,9 @@ class PdfCrossTable { } Future _saveIndirectObjectAsync( - IPdfPrimitive object, PdfWriter writer) async { + IPdfPrimitive object, + PdfWriter writer, + ) async { await getReferenceAsync(object).then((PdfReference reference) async { if (object is PdfCatalog) { trailer![PdfDictionaryProperties.root] = reference; @@ -549,8 +566,9 @@ class PdfCrossTable { !sigFlag) { await _doArchiveObjectAsync(object, reference, writer); } else { - await _registerObjectAsync(reference, position: writer.position) - .then((_) async { + await _registerObjectAsync(reference, position: writer.position).then(( + _, + ) async { await _doSaveObjectAsync(object, reference, writer).then((_) { if (object == _archive) { _archive = null; @@ -583,17 +601,16 @@ class PdfCrossTable { if (items!.count > 0 && object.objectCollectionIndex! > 0 && items!.count > object.objectCollectionIndex! - 1) { - final Map result = - PdfDocumentHelper.getHelper(document!) - .objects - .getReference(object, wasNew); + final Map result = PdfDocumentHelper.getHelper( + document!, + ).objects.getReference(object, wasNew); wasNew = result['isNew'] as bool?; reference = result['reference']; } } else { - final Map result = PdfDocumentHelper.getHelper(document!) - .objects - .getReference(object, wasNew); + final Map result = PdfDocumentHelper.getHelper( + document!, + ).objects.getReference(object, wasNew); wasNew = result['isNew'] as bool?; reference = result['reference']; } @@ -608,17 +625,17 @@ class PdfCrossTable { } if (_bForceNew) { if (reference == null) { - int maxObj = (_storedCount > 0) - ? _storedCount++ - : PdfDocumentHelper.getHelper(document!).objects.count; + int maxObj = + (_storedCount > 0) + ? _storedCount++ + : PdfDocumentHelper.getHelper(document!).objects.count; if (maxObj <= 0) { maxObj = -1; _storedCount = 2; } - while (PdfDocumentHelper.getHelper(document!) - .objects - .mainObjectCollection! - .containsKey(maxObj)) { + while (PdfDocumentHelper.getHelper( + document!, + ).objects.mainObjectCollection!.containsKey(maxObj)) { maxObj++; } reference = PdfReference(maxObj, 0); @@ -635,10 +652,9 @@ class PdfCrossTable { objectNumber = nextObjectNumber; } } - if (PdfDocumentHelper.getHelper(document!) - .objects - .mainObjectCollection! - .containsKey(objectNumber)) { + if (PdfDocumentHelper.getHelper( + document!, + ).objects.mainObjectCollection!.containsKey(objectNumber)) { reference = PdfReference(nextObjectNumber, 0); } else { PdfNumber? trailerCount; @@ -657,27 +673,31 @@ class PdfCrossTable { (object as IPdfChangable).changed = true; } PdfDocumentHelper.getHelper(document!).objects.add(object); - PdfDocumentHelper.getHelper(document!) - .objects - .trySetReference(object, reference); + PdfDocumentHelper.getHelper( + document!, + ).objects.trySetReference(object, reference); final int tempIndex = PdfDocumentHelper.getHelper(document!).objects.count - 1; - final int? tempkey = PdfDocumentHelper.getHelper(document!) - .objects - .objectCollection![tempIndex] - .reference! - .objNum; + final int? tempkey = + PdfDocumentHelper.getHelper( + document!, + ).objects.objectCollection![tempIndex].reference!.objNum; final PdfObjectInfo tempvalue = - PdfDocumentHelper.getHelper(document!).objects.objectCollection![ - PdfDocumentHelper.getHelper(document!).objects.count - 1]; - PdfDocumentHelper.getHelper(document!) - .objects - .mainObjectCollection![tempkey] = tempvalue; + PdfDocumentHelper.getHelper( + document!, + ).objects.objectCollection![PdfDocumentHelper.getHelper( + document!, + ).objects.count - + 1]; + PdfDocumentHelper.getHelper( + document!, + ).objects.mainObjectCollection![tempkey] = + tempvalue; object.position = -1; } else { - PdfDocumentHelper.getHelper(document!) - .objects - .trySetReference(object, reference); + PdfDocumentHelper.getHelper( + document!, + ).objects.trySetReference(object, reference); } object.objectCollectionIndex = reference.objNum as int?; object.status = PdfObjectStatus.none; @@ -708,22 +728,20 @@ class PdfCrossTable { if (items!.count > 0 && object.objectCollectionIndex! > 0 && items!.count > object.objectCollectionIndex! - 1) { - await PdfDocumentHelper.getHelper(document!) - .objects + await PdfDocumentHelper.getHelper(document!).objects .getReferenceAsync(object, wasNew) .then((Map result) { - wasNew = result['isNew'] as bool?; - reference = result['reference']; - }); + wasNew = result['isNew'] as bool?; + reference = result['reference']; + }); } } else { - await PdfDocumentHelper.getHelper(document!) - .objects + await PdfDocumentHelper.getHelper(document!).objects .getReferenceAsync(object, wasNew) .then((Map result) { - wasNew = result['isNew'] as bool?; - reference = result['reference']; - }); + wasNew = result['isNew'] as bool?; + reference = result['reference']; + }); } if (reference == null) { if (object.status == PdfObjectStatus.registered) { @@ -736,17 +754,17 @@ class PdfCrossTable { } if (_bForceNew) { if (reference == null) { - int maxObj = (_storedCount > 0) - ? _storedCount++ - : PdfDocumentHelper.getHelper(document!).objects.count; + int maxObj = + (_storedCount > 0) + ? _storedCount++ + : PdfDocumentHelper.getHelper(document!).objects.count; if (maxObj <= 0) { maxObj = -1; _storedCount = 2; } - while (PdfDocumentHelper.getHelper(document!) - .objects - .mainObjectCollection! - .containsKey(maxObj)) { + while (PdfDocumentHelper.getHelper( + document!, + ).objects.mainObjectCollection!.containsKey(maxObj)) { maxObj++; } reference = PdfReference(maxObj, 0); @@ -763,10 +781,9 @@ class PdfCrossTable { objectNumber = nextObjectNumber; } } - if (PdfDocumentHelper.getHelper(document!) - .objects - .mainObjectCollection! - .containsKey(objectNumber)) { + if (PdfDocumentHelper.getHelper( + document!, + ).objects.mainObjectCollection!.containsKey(objectNumber)) { reference = PdfReference(nextObjectNumber, 0); } else { PdfNumber? trailerCount; @@ -785,27 +802,31 @@ class PdfCrossTable { (object as IPdfChangable).changed = true; } await PdfDocumentHelper.getHelper(document!).objects.addAsync(object); - await PdfDocumentHelper.getHelper(document!) - .objects - .trySetReferenceAsync(object, reference); + await PdfDocumentHelper.getHelper( + document!, + ).objects.trySetReferenceAsync(object, reference); final int tempIndex = PdfDocumentHelper.getHelper(document!).objects.count - 1; - final int? tempkey = PdfDocumentHelper.getHelper(document!) - .objects - .objectCollection![tempIndex] - .reference! - .objNum; + final int? tempkey = + PdfDocumentHelper.getHelper( + document!, + ).objects.objectCollection![tempIndex].reference!.objNum; final PdfObjectInfo tempvalue = - PdfDocumentHelper.getHelper(document!).objects.objectCollection![ - PdfDocumentHelper.getHelper(document!).objects.count - 1]; - PdfDocumentHelper.getHelper(document!) - .objects - .mainObjectCollection![tempkey] = tempvalue; + PdfDocumentHelper.getHelper( + document!, + ).objects.objectCollection![PdfDocumentHelper.getHelper( + document!, + ).objects.count - + 1]; + PdfDocumentHelper.getHelper( + document!, + ).objects.mainObjectCollection![tempkey] = + tempvalue; object.position = -1; } else { - await PdfDocumentHelper.getHelper(document!) - .objects - .trySetReferenceAsync(object, reference); + await PdfDocumentHelper.getHelper( + document!, + ).objects.trySetReferenceAsync(object, reference); } object.objectCollectionIndex = reference.objNum as int?; object.status = PdfObjectStatus.none; @@ -816,9 +837,10 @@ class PdfCrossTable { /// internal method PdfReference getMappedReference(PdfReference reference) { _mappedReferences ??= {}; - PdfReference? mref = _mappedReferences!.containsKey(reference) - ? _mappedReferences![reference] - : null; + PdfReference? mref = + _mappedReferences!.containsKey(reference) + ? _mappedReferences![reference] + : null; if (mref == null) { mref = PdfReference(nextObjectNumber, 0); _mappedReferences![reference] = mref; @@ -829,9 +851,10 @@ class PdfCrossTable { /// internal method Future getMappedReferenceAsync(PdfReference reference) async { _mappedReferences ??= {}; - PdfReference? mref = _mappedReferences!.containsKey(reference) - ? _mappedReferences![reference] - : null; + PdfReference? mref = + _mappedReferences!.containsKey(reference) + ? _mappedReferences![reference] + : null; if (mref == null) { mref = PdfReference(nextObjectNumber, 0); _mappedReferences![reference] = mref; @@ -839,44 +862,67 @@ class PdfCrossTable { return mref; } - void _registerObject(PdfReference reference, - {int? position, PdfArchiveStream? archive, bool? isFreeType}) { + void _registerObject( + PdfReference reference, { + int? position, + PdfArchiveStream? archive, + bool? isFreeType, + }) { if (isFreeType == null) { if (position != null) { _objects![reference.objNum] = _RegisteredObject(position, reference); _maxGenNumIndex = max(_maxGenNumIndex, reference.genNum!.toDouble()); } else { - _objects![reference.objNum] = - _RegisteredObject.fromArchive(this, archive, reference); + _objects![reference.objNum] = _RegisteredObject.fromArchive( + this, + archive, + reference, + ); _maxGenNumIndex = max(_maxGenNumIndex, archive!.count.toDouble()); } } else { - _objects![reference.objNum] = - _RegisteredObject(position, reference, isFreeType); + _objects![reference.objNum] = _RegisteredObject( + position, + reference, + isFreeType, + ); _maxGenNumIndex = max(_maxGenNumIndex, reference.genNum!.toDouble()); } } - Future _registerObjectAsync(PdfReference reference, - {int? position, PdfArchiveStream? archive, bool? isFreeType}) async { + Future _registerObjectAsync( + PdfReference reference, { + int? position, + PdfArchiveStream? archive, + bool? isFreeType, + }) async { if (isFreeType == null) { if (position != null) { _objects![reference.objNum] = _RegisteredObject(position, reference); _maxGenNumIndex = max(_maxGenNumIndex, reference.genNum!.toDouble()); } else { - _objects![reference.objNum] = - _RegisteredObject.fromArchive(this, archive, reference); + _objects![reference.objNum] = _RegisteredObject.fromArchive( + this, + archive, + reference, + ); _maxGenNumIndex = max(_maxGenNumIndex, archive!.count.toDouble()); } } else { - _objects![reference.objNum] = - _RegisteredObject(position, reference, isFreeType); + _objects![reference.objNum] = _RegisteredObject( + position, + reference, + isFreeType, + ); _maxGenNumIndex = max(_maxGenNumIndex, reference.genNum!.toDouble()); } } void _doSaveObject( - IPdfPrimitive object, PdfReference reference, PdfWriter writer) { + IPdfPrimitive object, + PdfReference reference, + PdfWriter writer, + ) { writer.write(reference.objNum); writer.write(PdfOperators.whiteSpace); writer.write(reference.genNum); @@ -892,7 +938,10 @@ class PdfCrossTable { } Future _doSaveObjectAsync( - IPdfPrimitive object, PdfReference reference, PdfWriter writer) async { + IPdfPrimitive object, + PdfReference reference, + PdfWriter writer, + ) async { await writer.writeAsync(reference.objNum).then((_) async { await writer.writeAsync(PdfOperators.whiteSpace).then((_) async { await writer.writeAsync(reference.genNum).then((_) async { @@ -932,8 +981,9 @@ class PdfCrossTable { int objectNumber = 0; int? count = 0; do { - await _prepareSubsectionAsync(objectNumber) - .then((Map result) { + await _prepareSubsectionAsync(objectNumber).then(( + Map result, + ) { count = result['count']; objectNumber = result['objectNumber']!; }); @@ -951,12 +1001,13 @@ class PdfCrossTable { total = PdfDocumentHelper.getHelper(document!).objects.count + 1; } if (total < - PdfDocumentHelper.getHelper(document!) - .objects - .maximumReferenceObjectNumber!) { - total = PdfDocumentHelper.getHelper(document!) - .objects - .maximumReferenceObjectNumber!; + PdfDocumentHelper.getHelper( + document!, + ).objects.maximumReferenceObjectNumber!) { + total = + PdfDocumentHelper.getHelper( + document!, + ).objects.maximumReferenceObjectNumber!; _isIndexOutOfRange = true; } if (objectNumber >= total) { @@ -985,12 +1036,13 @@ class PdfCrossTable { total = PdfDocumentHelper.getHelper(document!).objects.count + 1; } if (total < - PdfDocumentHelper.getHelper(document!) - .objects - .maximumReferenceObjectNumber!) { - total = PdfDocumentHelper.getHelper(document!) - .objects - .maximumReferenceObjectNumber!; + PdfDocumentHelper.getHelper( + document!, + ).objects.maximumReferenceObjectNumber!) { + total = + PdfDocumentHelper.getHelper( + document!, + ).objects.maximumReferenceObjectNumber!; _isIndexOutOfRange = true; } if (objectNumber >= total) { @@ -1030,7 +1082,10 @@ class PdfCrossTable { } Future _saveSubsectionAsync( - IPdfWriter writer, int? objectNumber, int tempCount) async { + IPdfWriter writer, + int? objectNumber, + int tempCount, + ) async { if (tempCount <= 0 || objectNumber! >= count && !_isIndexOutOfRange) { return; } @@ -1066,14 +1121,18 @@ class PdfCrossTable { result = '${result}0'; } result = '$result$generationNumber '; - result = result + + result = + result + (isFreeType ? PdfOperators.f : PdfOperators.n) + PdfOperators.newLine; return result; } Future _getItemAsync( - int? offset, int generationNumber, bool isFreeType) async { + int? offset, + int generationNumber, + bool isFreeType, + ) async { String result = ''; final int offsetLength = 10 - offset.toString().length; if (generationNumber <= 0) { @@ -1091,7 +1150,8 @@ class PdfCrossTable { result = '${result}0'; } result = '$result$generationNumber '; - result = result + + result = + result + (isFreeType ? PdfOperators.f : PdfOperators.n) + PdfOperators.newLine; return result; @@ -1111,7 +1171,10 @@ class PdfCrossTable { } Future _saveTrailerAsync( - IPdfWriter writer, int count, int prevCrossReference) async { + IPdfWriter writer, + int count, + int prevCrossReference, + ) async { writer.write(PdfOperators.trailer); writer.write(PdfOperators.newLine); PdfDictionary trailerDictionary = trailer!; @@ -1125,18 +1188,22 @@ class PdfCrossTable { } void _saveEnd(IPdfWriter writer, int? position) { - writer.write(PdfOperators.newLine + - PdfOperators.startCrossReference + - PdfOperators.newLine); + writer.write( + PdfOperators.newLine + + PdfOperators.startCrossReference + + PdfOperators.newLine, + ); writer.write(position.toString() + PdfOperators.newLine); writer.write(PdfOperators.endOfFileMarker); writer.write(PdfOperators.newLine); } Future _saveEndAsync(IPdfWriter writer, int? position) async { - writer.write(PdfOperators.newLine + - PdfOperators.startCrossReference + - PdfOperators.newLine); + writer.write( + PdfOperators.newLine + + PdfOperators.startCrossReference + + PdfOperators.newLine, + ); writer.write(position.toString() + PdfOperators.newLine); writer.write(PdfOperators.endOfFileMarker); writer.write(PdfOperators.newLine); @@ -1232,11 +1299,12 @@ class PdfCrossTable { final PdfName type = getObject(objType)! as PdfName; if (type.name == 'Page') { if (!dic.containsKey(PdfDictionaryProperties.kids)) { - if (PdfDocumentHelper.getHelper(_pdfDocument!) - .isLoadedDocument) { - final PdfPage lPage = - PdfPageCollectionHelper.getHelper(_pdfDocument!.pages) - .getPage(dic); + if (PdfDocumentHelper.getHelper( + _pdfDocument!, + ).isLoadedDocument) { + final PdfPage lPage = PdfPageCollectionHelper.getHelper( + _pdfDocument!.pages, + ).getPage(dic); obj = IPdfWrapper.getElement(lPage); final PdfMainObjectCollection items = PdfDocumentHelper.getHelper(_pdfDocument!).objects; @@ -1263,7 +1331,8 @@ class PdfCrossTable { result = true; } } else { - result = document!.fileStructure.crossReferenceType == + result = + document!.fileStructure.crossReferenceType == PdfCrossReferenceType.crossReferenceStream; } return result; @@ -1277,7 +1346,8 @@ class PdfCrossTable { result = true; } } else { - result = document!.fileStructure.crossReferenceType == + result = + document!.fileStructure.crossReferenceType == PdfCrossReferenceType.crossReferenceStream; } return result; @@ -1307,8 +1377,9 @@ class PdfCrossTable { ai._reference = reference; } PdfDocumentHelper.getHelper(document!).currentSavingObject = reference; - await _registerObjectAsync(reference, position: writer.position) - .then((_) async { + await _registerObjectAsync(reference, position: writer.position).then(( + _, + ) async { await _doSaveObjectAsync(ai._archive!, reference!, writer); }); } @@ -1316,7 +1387,10 @@ class PdfCrossTable { } void _doArchiveObject( - IPdfPrimitive obj, PdfReference reference, PdfWriter writer) { + IPdfPrimitive obj, + PdfReference reference, + PdfWriter writer, + ) { if (_archive == null) { _archive = PdfArchiveStream(document); _saveArchive(writer); @@ -1329,7 +1403,10 @@ class PdfCrossTable { } Future _doArchiveObjectAsync( - IPdfPrimitive obj, PdfReference reference, PdfWriter writer) async { + IPdfPrimitive obj, + PdfReference reference, + PdfWriter writer, + ) async { if (_archive == null) { _archive = PdfArchiveStream(document); await _saveArchiveAsync(writer); @@ -1355,7 +1432,10 @@ class PdfCrossTable { } Map _prepareXRefStream( - double prevXRef, double position, PdfReference? reference) { + double prevXRef, + double position, + PdfReference? reference, + ) { PdfStream? xRefStream; xRefStream = _trailer as PdfStream?; if (xRefStream == null) { @@ -1411,12 +1491,15 @@ class PdfCrossTable { xRefStream.encrypt = false; return { 'xRefStream': xRefStream, - 'reference': reference + 'reference': reference, }; } Future> _prepareXRefStreamAsync( - double prevXRef, double position, PdfReference? reference) async { + double prevXRef, + double position, + PdfReference? reference, + ) async { PdfStream? xRefStream; xRefStream = _trailer as PdfStream?; if (xRefStream == null) { @@ -1432,13 +1515,16 @@ class PdfCrossTable { double objectNum = 0; double count = 0; final List paramsFormat = [1, 8, 1]; - paramsFormat[1] = max(await _getSizeAsync(position), - await _getSizeAsync(this.count.toDouble())); + paramsFormat[1] = max( + await _getSizeAsync(position), + await _getSizeAsync(this.count.toDouble()), + ); paramsFormat[2] = await _getSizeAsync(_maxGenNumIndex); final List ms = []; while (true) { - await _prepareSubsectionAsync(objectNum.toInt()) - .then((Map result) { + await _prepareSubsectionAsync(objectNum.toInt()).then(( + Map result, + ) { count = result['count']!.toDouble(); objectNum = result['objectNumber']!.toDouble(); }); @@ -1447,8 +1533,9 @@ class PdfCrossTable { } else { sectionIndeces.add(PdfNumber(objectNum)); sectionIndeces.add(PdfNumber(count)); - await _saveSubSectionAsync(ms, objectNum, count, paramsFormat) - .then((_) { + await _saveSubSectionAsync(ms, objectNum, count, paramsFormat).then(( + _, + ) { objectNum += count; }); } @@ -1477,7 +1564,7 @@ class PdfCrossTable { xRefStream.encrypt = false; return { 'xRefStream': xRefStream, - 'reference': reference + 'reference': reference, }; } @@ -1528,7 +1615,11 @@ class PdfCrossTable { } void _saveSubSection( - List xRefStream, double objectNum, double count, List format) { + List xRefStream, + double objectNum, + double count, + List format, + ) { for (int i = objectNum.toInt(); i < objectNum + count; ++i) { final _RegisteredObject obj = _objects![i]!; xRefStream.add(obj._type!.index.toUnsigned(8)); @@ -1555,15 +1646,22 @@ class PdfCrossTable { } } - Future _saveSubSectionAsync(List xRefStream, double objectNum, - double count, List format) async { + Future _saveSubSectionAsync( + List xRefStream, + double objectNum, + double count, + List format, + ) async { for (int i = objectNum.toInt(); i < objectNum + count; ++i) { final _RegisteredObject obj = _objects![i]!; xRefStream.add(obj._type!.index.toUnsigned(8)); switch (obj._type) { case PdfObjectType.free: await _saveLongAsync( - xRefStream, obj._objectNumber!.toInt(), format[1]); + xRefStream, + obj._objectNumber!.toInt(), + format[1], + ); await _saveLongAsync(xRefStream, obj._generationNumber, format[2]); break; @@ -1574,7 +1672,10 @@ class PdfCrossTable { case PdfObjectType.packed: await _saveLongAsync( - xRefStream, obj._objectNumber!.toInt(), format[1]); + xRefStream, + obj._objectNumber!.toInt(), + format[1], + ); await _saveLongAsync(xRefStream, obj.offset, format[2]); break; @@ -1593,7 +1694,10 @@ class PdfCrossTable { } Future _saveLongAsync( - List xRefStream, int? number, int count) async { + List xRefStream, + int? number, + int count, + ) async { for (int i = count - 1; i >= 0; --i) { final int b = (number! >> (i << 3) & 255).toUnsigned(8); xRefStream.add(b); @@ -1616,7 +1720,8 @@ class PdfCrossTable { } Future _findArchiveReferenceAsync( - PdfArchiveStream archive) async { + PdfArchiveStream archive, + ) async { int i = 0; late _ArchiveInfo ai; for (final int count = _archives!.length; i < count; ++i) { @@ -1683,13 +1788,15 @@ class PdfCrossTable { /// Checks the dictionary if it is an outline type. bool _checkForOutlinesAndDestination(PdfDictionary dictionary) { if (dictionary.containsKey(PdfDictionaryProperties.parent)) { - final IPdfPrimitive? outline = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.parent]); + final IPdfPrimitive? outline = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.parent], + ); if (outline != null && outline is PdfDictionary) { if (documentCatalog != null && documentCatalog!.containsKey(PdfDictionaryProperties.outlines)) { final IPdfPrimitive? dict = PdfCrossTable.dereference( - documentCatalog![PdfDictionaryProperties.outlines]); + documentCatalog![PdfDictionaryProperties.outlines], + ); if (dict != null && dict is PdfDictionary && dict == outline) { return true; } else { @@ -1718,8 +1825,11 @@ class _RegisteredObject { } } - _RegisteredObject.fromArchive(PdfCrossTable xrefTable, - PdfArchiveStream? archive, PdfReference reference) { + _RegisteredObject.fromArchive( + PdfCrossTable xrefTable, + PdfArchiveStream? archive, + PdfReference reference, + ) { _xrefTable = xrefTable; _archive = archive; _offset = reference.objNum; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_lexer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_lexer.dart index 6d932c75a..967f7e0f5 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_lexer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_lexer.dart @@ -208,14 +208,25 @@ class PdfLexer { notAccept, notAccept, notAccept, - notAccept + notAccept, ]; - cMap = _unpackFromString(1, 258, - '3,17:8,3,11,17,3,4,17:18,3,17:4,1,17:2,7,2,17,26,17,26,28,16,27:10,17:2,5,17,6,17:2,13:6,17:11,35,17:8,14,12,15,17:3,23,30,13,33,21,22,17:2,36,31,17,24,34,32,29,17:2,19,25,18,20,17:2,37,17:2,10,17,10,17:128,8,9,0:2')[0]; - rMap = _unpackFromString(1, 88, - '0,1,2,1:2,3,4,1:2,5,6,7,1:3,8,1:18,9,1,10,11,12,13,14,15,16,17,18,19,20,21,7,8:2,22,23,24,25,13,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57')[0]; - next = _unpackFromString(58, 38, - '1,2,3,4:2,5,37,6,3:3,4,3:2,7,8,9,3,42,3:2,44,10,3:2,46,48,11,50,52,3:2,38,3:2,12,3,54,-1:39,2:3,-1,2:6,-1,2:26,-1:5,13,-1:40,36,-1:37,9:2,-1:2,9:2,-1:3,9:21,-1:23,45,-1:41,11,49,-1:36,15,-1:11,35:3,84,35:33,-1:9,55,-1:34,14,-1:51,85,-1:18,63,17,63:8,64,63:26,-1,30:3,82,30:33,-1:20,56,-1:2,57,-1:33,41,-1:51,58,-1:36,43,-1:29,59,-1:31,47,-1:38,86,-1:3,60,-1:45,16,-1:36,51,-1:28,62,-1:35,53,-1:39,18,-1:52,65,-1:26,66,-1:3,67,-1:33,56,-1:31,87,-1:42,19,-1:35,20,-1:16,55:3,-1,55:6,-1,-1:26,-1,64,39,64,63,64:33,-1:24,69,-1:31,70,-1:49,71,-1:30,72,-1:35,74,-1:35,75,-1:49,21,-1:40,22,-1:40,76,-1:19,23,-1:39,77,-1:35,78,-1:41,79,-1:35,80,-1:50,24,-1:25,25,-1:15,1,26:2,27:2,26,28,26:4,27,40,29,26:7,29:3,26:3,29,26:2,29,26:2,29,26:4,-1:11,30,-1:26,1,31,32,31:4,33,31:4,34,31:25,-1:11,35,-1:50,61,-1:34,68,-1:34,73,-1:19'); + cMap = + _unpackFromString( + 1, + 258, + '3,17:8,3,11,17,3,4,17:18,3,17:4,1,17:2,7,2,17,26,17,26,28,16,27:10,17:2,5,17,6,17:2,13:6,17:11,35,17:8,14,12,15,17:3,23,30,13,33,21,22,17:2,36,31,17,24,34,32,29,17:2,19,25,18,20,17:2,37,17:2,10,17,10,17:128,8,9,0:2', + )[0]; + rMap = + _unpackFromString( + 1, + 88, + '0,1,2,1:2,3,4,1:2,5,6,7,1:3,8,1:18,9,1,10,11,12,13,14,15,16,17,18,19,20,21,7,8:2,22,23,24,25,13,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57', + )[0]; + next = _unpackFromString( + 58, + 38, + '1,2,3,4:2,5,37,6,3:3,4,3:2,7,8,9,3,42,3:2,44,10,3:2,46,48,11,50,52,3:2,38,3:2,12,3,54,-1:39,2:3,-1,2:6,-1,2:26,-1:5,13,-1:40,36,-1:37,9:2,-1:2,9:2,-1:3,9:21,-1:23,45,-1:41,11,49,-1:36,15,-1:11,35:3,84,35:33,-1:9,55,-1:34,14,-1:51,85,-1:18,63,17,63:8,64,63:26,-1,30:3,82,30:33,-1:20,56,-1:2,57,-1:33,41,-1:51,58,-1:36,43,-1:29,59,-1:31,47,-1:38,86,-1:3,60,-1:45,16,-1:36,51,-1:28,62,-1:35,53,-1:39,18,-1:52,65,-1:26,66,-1:3,67,-1:33,56,-1:31,87,-1:42,19,-1:35,20,-1:16,55:3,-1,55:6,-1,-1:26,-1,64,39,64,63,64:33,-1:24,69,-1:31,70,-1:49,71,-1:30,72,-1:35,74,-1:35,75,-1:49,21,-1:40,22,-1:40,76,-1:19,23,-1:39,77,-1:35,78,-1:41,79,-1:35,80,-1:50,24,-1:25,25,-1:15,1,26:2,27:2,26,28,26:4,27,40,29,26:7,29:3,26:3,29,26:2,29,26:2,29,26:4,-1:11,30,-1:26,1,31,32,31:4,33,31:4,34,31:25,-1:11,35,-1:50,61,-1:34,68,-1:34,73,-1:19', + ); } List> _unpackFromString(int size1, int size2, String text) { @@ -226,7 +237,9 @@ class PdfLexer { int commaIndex; String workString; final List> res = List>.generate( - size1, (int i) => List.generate(size2, (int j) => 0)); + size1, + (int i) => List.generate(size2, (int j) => 0), + ); for (int i = 0; i < size1; ++i) { for (int j = 0; j < size2; ++j) { if (sequenceLength != 0) { @@ -363,8 +376,11 @@ class PdfLexer { } int _read() { - final int nextRead = - _reader.readData(buffer, bufferRead, buffer.length - bufferRead); + final int nextRead = _reader.readData( + buffer, + bufferRead, + buffer.length - bufferRead, + ); if (nextRead > 0) { bufferRead += nextRead; } @@ -406,7 +422,8 @@ class PdfLexer { void _toMark() { bufferIndex = bufferEnd; - atBool = (bufferEnd > bufferStart) && + atBool = + (bufferEnd > bufferStart) && (13 == buffer[bufferEnd - 1] || 10 == buffer[bufferEnd - 1] || 2028 == buffer[bufferEnd - 1] || @@ -873,8 +890,10 @@ class PdfLexer { void _error(_Error code, bool fatal) { if (fatal) { if (objectName != null) { - throw ArgumentError.value(code, - 'Fatal Error occurred at $position.\n When reading object type of ${objectName!}'); + throw ArgumentError.value( + code, + 'Fatal Error occurred at $position.\n When reading object type of ${objectName!}', + ); } else { throw ArgumentError.value(code, 'Fatal Error occurred at $position'); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_main_object_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_main_object_collection.dart index 662fe0249..8ac908d88 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_main_object_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_main_object_collection.dart @@ -135,7 +135,9 @@ class PdfMainObjectCollection { /// internal method Future> getReferenceAsync( - IPdfPrimitive object, bool? isNew) async { + IPdfPrimitive object, + bool? isNew, + ) async { _index = await lookForAsync(object); PdfReference? reference; if (_index! < 0 || _index! > count) { @@ -166,8 +168,9 @@ class PdfMainObjectCollection { for (int i = count - 1; i >= 0; i--) { final PdfObjectInfo objectInfo = objectCollection![i]; final IPdfPrimitive? primitive = objectInfo.object; - final bool isValidType = !((primitive is PdfName && obj is! PdfName) || - (primitive is! PdfName && obj is PdfName)); + final bool isValidType = + !((primitive is PdfName && obj is! PdfName) || + (primitive is! PdfName && obj is PdfName)); if (isValidType && primitive == obj) { index = i; break; @@ -190,8 +193,9 @@ class PdfMainObjectCollection { for (int i = count - 1; i >= 0; i--) { final PdfObjectInfo objectInfo = objectCollection![i]; final IPdfPrimitive? primitive = objectInfo.object; - final bool isValidType = !((primitive is PdfName && obj is! PdfName) || - (primitive is! PdfName && obj is PdfName)); + final bool isValidType = + !((primitive is PdfName && obj is! PdfName) || + (primitive is! PdfName && obj is PdfName)); if (isValidType && primitive == obj) { index = i; break; @@ -257,7 +261,9 @@ class PdfMainObjectCollection { /// internal method Future trySetReferenceAsync( - IPdfPrimitive object, PdfReference reference) async { + IPdfPrimitive object, + PdfReference reference, + ) async { bool result = true; _index = await lookForAsync(object); if (_index! < 0 || _index! >= objectCollection!.length) { @@ -286,7 +292,10 @@ class PdfMainObjectCollection { void reregisterReference(int oldObjIndex, IPdfPrimitive newObj) { if (oldObjIndex < 0 || oldObjIndex > count) { throw ArgumentError.value( - oldObjIndex, 'oldObjIndex', 'index out of range'); + oldObjIndex, + 'oldObjIndex', + 'index out of range', + ); } final PdfObjectInfo oi = objectCollection![oldObjIndex]; if (oi.object != newObj) { @@ -299,10 +308,15 @@ class PdfMainObjectCollection { /// internal method Future reregisterReferenceAsync( - int oldObjIndex, IPdfPrimitive newObj) async { + int oldObjIndex, + IPdfPrimitive newObj, + ) async { if (oldObjIndex < 0 || oldObjIndex > count) { throw ArgumentError.value( - oldObjIndex, 'oldObjIndex', 'index out of range'); + oldObjIndex, + 'oldObjIndex', + 'index out of range', + ); } final PdfObjectInfo oi = objectCollection![oldObjIndex]; if (oi.object != newObj) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_parser.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_parser.dart index 6199da3db..b62208810 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_parser.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_parser.dart @@ -87,7 +87,7 @@ class PdfParser { ' ', '¡', '¢', - '£' + '£', ]; return _windows1252MapTable; } @@ -168,8 +168,10 @@ class PdfParser { if (_next == PdfTokenType.number) { final PdfNumber? integer2 = _parseInteger(); if (_next == PdfTokenType.reference) { - final PdfReference reference = - PdfReference(integer!.value!.toInt(), integer2!.value!.toInt()); + final PdfReference reference = PdfReference( + integer!.value!.toInt(), + integer2!.value!.toInt(), + ); obj = PdfReferenceHolder.fromReference(reference, _crossTable); advance(); } else { @@ -200,7 +202,9 @@ class PdfParser { /// internal method Map parseCrossReferenceTable( - Map? objects, CrossTable cTable) { + Map? objects, + CrossTable cTable, + ) { IPdfPrimitive? obj; advance(); if (_next == PdfTokenType.xRef) { @@ -241,14 +245,16 @@ class PdfParser { try { int xrefStreamPosition = 0; final PdfDictionary trailerDictionary = obj; - final IPdfPrimitive? pdfNumber = - PdfCrossTable.dereference(trailerDictionary['XRefStm']); + final IPdfPrimitive? pdfNumber = PdfCrossTable.dereference( + trailerDictionary['XRefStm'], + ); if (pdfNumber != null && pdfNumber is PdfNumber) { xrefStreamPosition = pdfNumber.value!.toInt(); } cTable.parser.setOffset(xrefStreamPosition); - final IPdfPrimitive? xrefStream = - cTable.parser.parseOffset(xrefStreamPosition); + final IPdfPrimitive? xrefStream = cTable.parser.parseOffset( + xrefStreamPosition, + ); if (xrefStream != null && xrefStream is PdfStream) { objects = cTable.parseNewTable(xrefStream, objects); } @@ -369,7 +375,9 @@ class PdfParser { /// internal method void rebuildXrefTable( - Map newObjects, CrossTable? crosstable) { + Map newObjects, + CrossTable? crosstable, + ) { final PdfReader reader = PdfReader(_reader.streamReader.data); reader.position = 0; newObjects.clear(); @@ -389,10 +397,10 @@ class PdfParser { final List tokens = str.split(''); final bool previousObject = previoursToken[0].codeUnitAt(0) >= '0'.codeUnitAt(0) && - previoursToken[0].codeUnitAt(0) <= '9'.codeUnitAt(0) && - tokens.length > 1 && - tokens[1].codeUnitAt(0) >= '0'.codeUnitAt(0) && - tokens[1].codeUnitAt(0) <= '9'.codeUnitAt(0); + previoursToken[0].codeUnitAt(0) <= '9'.codeUnitAt(0) && + tokens.length > 1 && + tokens[1].codeUnitAt(0) >= '0'.codeUnitAt(0) && + tokens[1].codeUnitAt(0) <= '9'.codeUnitAt(0); if (tokens[0].codeUnitAt(0) >= '0'.codeUnitAt(0) && tokens[0].codeUnitAt(0) <= '9'.codeUnitAt(0) || previousObject) { @@ -409,8 +417,11 @@ class PdfParser { marker = int.tryParse(words[1]); if (marker != null) { if (marker == 0 && words[2] == PdfDictionaryProperties.obj) { - final ObjectInformation objectInfo = - ObjectInformation(previousPosition, null, crosstable); + final ObjectInformation objectInfo = ObjectInformation( + previousPosition, + null, + crosstable, + ); if (!newObjects.containsKey(objNumber)) { newObjects[objNumber] = objectInfo; } @@ -544,26 +555,20 @@ class PdfParser { result.add(next); break; default: - if (next < 48 || next > 55) { + if (next >= 48 && next <= 55) { + int octal = next - 48; + for (int j = 0; j < 2 && i + 1 < data.length; j++) { + next = data[i + 1]; + if (next < 48 || next > 55) { + break; + } + i++; + octal = (octal << 3) + (next - 48); + } + result.add(octal & 0xFF); + } else { result.add(next); - break; - } - int octal = next - 48; - next = data[++i]; - if (next < 48 || next > 55) { - --i; - result.add(octal); - break; - } - octal = (octal << 3) + next - 48; - next = data[++i]; - if (next < 48 || next > 55) { - --i; - result.add(octal); - break; } - octal = (octal << 3) + next - 48; - result.add(octal & 0xff); break; } } else { @@ -796,7 +801,8 @@ class PdfParser { _error(_ErrorType.badlyFormedDictionary, 'next should be a name.'); } if (name!.name == PdfDictionaryProperties.u || - name.name == PdfDictionaryProperties.o) { + name.name == PdfDictionaryProperties.o || + name.name == PdfDictionaryProperties.id) { _isPassword = true; } obj = simple(); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_reader.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_reader.dart index 3c4796e6c..091cced9e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_reader.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_reader.dart @@ -43,7 +43,7 @@ class PdfReader { '\u000b', '\u000c', '\u000d', - '\u0085' + '\u0085', ]; late int _peekedByte; late bool _bytePeeked; @@ -65,8 +65,8 @@ class PdfReader { int value; do { value = _read(); - } while ( - value != -1 && _spaceCharacters.contains(String.fromCharCode(value))); + } while (value != -1 && + _spaceCharacters.contains(String.fromCharCode(value))); position = value == -1 ? streamReader.length! : (position - 1); } } @@ -185,9 +185,11 @@ class PdfReader { throw ArgumentError.value(index, 'Invalid index to read'); } final int pos = position; - for (int i = pos; - i < length! && i < (pos + count) && index < buffer.length; - i++) { + for ( + int i = pos; + i < length! && i < (pos + count) && index < buffer.length; + i++ + ) { buffer[index] = _read(); index++; } @@ -263,8 +265,11 @@ class PdfReader { if (buf[0] == token.codeUnitAt(0)) { if (!isStartXref) { pos = position - 1; - final Map result = - copyBytes(buf, 1, token.length - 1); + final Map result = copyBytes( + buf, + 1, + token.length - 1, + ); final int length = result['next'] as int; buf = result['buffer'] as List?; position = pos; @@ -281,10 +286,15 @@ class PdfReader { pos = position - 1; position = pos; int newPosition = pos; - List? buff = - List.filled(PdfOperators.startCrossReference.length, 0); - final Map result = - copyBytes(buff, 1, PdfOperators.startCrossReference.length); + List? buff = List.filled( + PdfOperators.startCrossReference.length, + 0, + ); + final Map result = copyBytes( + buff, + 1, + PdfOperators.startCrossReference.length, + ); buff = result['buffer'] as List?; if (PdfOperators.startCrossReference == String.fromCharCodes(buff!)) { isStartXref = true; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_stream_writer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_stream_writer.dart index 193a718aa..678093434 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_stream_writer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_stream_writer.dart @@ -125,10 +125,14 @@ class PdfStreamWriter implements IPdfWriter { /// internal method void setColorAndSpace( - PdfColor color, PdfColorSpace? colorSpace, bool forStroking) { + PdfColor color, + PdfColorSpace? colorSpace, + bool forStroking, + ) { if (!color.isEmpty) { stream!.write( - PdfColorHelper.getHelper(color).getString(colorSpace, forStroking)); + PdfColorHelper.getHelper(color).getString(colorSpace, forStroking), + ); stream!.write(PdfOperators.newLine); } } @@ -137,9 +141,11 @@ class PdfStreamWriter implements IPdfWriter { void setColorSpace(PdfName name, bool forStroking) { stream!.write(name.toString()); stream!.write(PdfOperators.whiteSpace); - stream!.write(forStroking - ? PdfOperators.selectColorSpaceForStroking - : PdfOperators.selectColorSpaceForNonStroking); + stream!.write( + forStroking + ? PdfOperators.selectColorSpaceForStroking + : PdfOperators.selectColorSpaceForNonStroking, + ); stream!.write(PdfOperators.newLine); } @@ -225,7 +231,10 @@ class PdfStreamWriter implements IPdfWriter { void setGraphicsState(PdfName name) { if (name.name!.isEmpty) { throw ArgumentError.value( - name, 'name', 'dictionary name cannot be empty'); + name, + 'name', + 'dictionary name cannot be empty', + ); } stream!.write(name.toString()); stream!.write(PdfOperators.whiteSpace); @@ -305,7 +314,13 @@ class PdfStreamWriter implements IPdfWriter { /// internal method void appendBezierSegment( - double x1, double y1, double x2, double y2, double x3, double y3) { + double x1, + double y1, + double x2, + double y2, + double x3, + double y3, + ) { writePoint(x1, y1); writePoint(x2, y2); writePoint(x3, y3); @@ -325,7 +340,9 @@ class PdfStreamWriter implements IPdfWriter { //ignore:unused_element set document(PdfDocument? value) { throw ArgumentError.value( - value, 'The method or operation is not implemented'); + value, + 'The method or operation is not implemented', + ); } @override @@ -336,7 +353,9 @@ class PdfStreamWriter implements IPdfWriter { //ignore:unused_element set length(int? value) { throw ArgumentError.value( - value, 'The method or operation is not implemented'); + value, + 'The method or operation is not implemented', + ); } @override @@ -346,7 +365,9 @@ class PdfStreamWriter implements IPdfWriter { //ignore:unused_element set position(int? value) { throw ArgumentError.value( - value, 'The method or operation is not implemented'); + value, + 'The method or operation is not implemented', + ); } @override @@ -371,7 +392,9 @@ class PdfStreamWriter implements IPdfWriter { stream!.write(pdfObject); } else { throw ArgumentError.value( - pdfObject, 'The method or operation is not implemented'); + pdfObject, + 'The method or operation is not implemented', + ); } } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_writer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_writer.dart index 82bc67f8b..f185a55a0 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_writer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/io/pdf_writer.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:typed_data'; import '../../interfaces/pdf_interface.dart'; import '../pdf_document/pdf_document.dart'; @@ -7,15 +8,23 @@ import '../pdf_document/pdf_document.dart'; class PdfWriter implements IPdfWriter { //Constructor /// internal constructor - PdfWriter(this.buffer) { - length = buffer!.length; - position = buffer!.length; + PdfWriter(this.buffer, [PdfBytesBuilder? bytesBuilder]) { + if (bytesBuilder != null) { + this.bytesBuilder = bytesBuilder; + length = this.bytesBuilder!.length; + position = this.bytesBuilder!.length; + isBytesBuilder = true; + } else { + length = buffer!.length; + position = buffer!.length; + } } //Fields /// internal field List? buffer; - + PdfBytesBuilder? bytesBuilder; + bool isBytesBuilder = false; //IPdfWriter members @override PdfDocument? document; @@ -55,13 +64,32 @@ class PdfWriter implements IPdfWriter { length = length! + tempLength; position = position! + tempLength; if (end == null) { - buffer!.addAll(data); + if (isBytesBuilder) { + bytesBuilder!.add(data); + } else { + _addDataInChunks(data); + //buffer!.addAll(data); + } } else { - buffer!.addAll(data.take(end)); + if (isBytesBuilder) { + bytesBuilder!.add(data.take(end).toList()); + } else { + _addDataInChunks(data.take(end).toList()); + //buffer!.addAll(data.take(end)); + } } } } + void _addDataInChunks(List data) { + const int chunkSize = 8190; + for (int i = 0; i < data.length; i += chunkSize) { + final int end = + (i + chunkSize < data.length) ? i + chunkSize : data.length; + buffer!.addAll(data.sublist(i, end)); + } + } + /// Internal method Future writeAsync(dynamic data, [int? end]) async { if (data == null) { @@ -93,10 +121,57 @@ class PdfWriter implements IPdfWriter { length = length! + tempLength; position = position! + tempLength; if (end == null) { - buffer!.addAll(data); + if (isBytesBuilder) { + bytesBuilder!.add(data); + } else { + _addDataInChunks(data); + //buffer!.addAll(data); + } } else { - buffer!.addAll(data.take(end)); + if (isBytesBuilder) { + bytesBuilder!.add(data.take(end).toList()); + } else { + _addDataInChunks(data.take(end).toList()); + //buffer!.addAll(data.take(end)); + } } } } } + +///Helper class to write the PDF document data. +class PdfBytesBuilder { + /// internal fields + final List _chunks = []; + int _length = 0; + + /// get the length of the data + int get length => _length; + + /// add the data + void add(List data) { + if (data.isEmpty) { + return; + } + final Uint8List chunk = Uint8List.fromList(data); + _chunks.add(chunk); + _length += chunk.length; + } + + /// get the bytes + Uint8List takeBytes() { + final Uint8List result = Uint8List(_length); + int offset = 0; + for (final Uint8List chunk in _chunks) { + result.setRange(offset, offset + chunk.length, chunk); + offset += chunk.length; + } + return result; + } + + /// clear the data + void clear() { + _chunks.clear(); + _length = 0; + } +} diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/enum.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/enum.dart index 784c62ef5..4e96f022a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/enum.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/enum.dart @@ -20,7 +20,7 @@ enum PdfPageRotateAngle { rotateAngle180, /// The page is rotated as 270 angle. - rotateAngle270 + rotateAngle270, } /// Specifies the docking style of the page template. @@ -41,7 +41,7 @@ enum PdfDockStyle { right, /// The page template stretch on full page. - fill + fill, } /// Specifies how the page template is aligned relative to the template area. @@ -95,7 +95,7 @@ enum PdfNumberStyle { upperLatin, /// Uppercase roman numerals. - upperRoman + upperRoman, } /// Specifies tab order types for form fields @@ -131,5 +131,5 @@ enum TemplateType { left, /// Page template is used as Right. - right + right, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer.dart index 87fe5a9c6..620cb5fc6 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer.dart @@ -54,8 +54,10 @@ class PdfLayer implements IPdfWrapper { set name(String? value) { _name = value; if (_helper.dictionary != null && _name != null && _name != '') { - _helper.dictionary! - .setProperty(PdfDictionaryProperties.name, PdfString(_name!)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.name, + PdfString(_name!), + ); } } @@ -76,12 +78,15 @@ class PdfLayer implements IPdfWrapper { if (_helper.dictionary != null) { _helper.dictionary![PdfDictionaryProperties.visible] = PdfBoolean(value); } + _helper._setVisibility(_visible); } /// Gets the collection of child [PdfLayer] PdfLayerCollection get layers { - _layerCollection ??= - PdfLayerCollectionHelper.withLayer(_helper.document, _helper.layer); + _layerCollection ??= PdfLayerCollectionHelper.withLayer( + _helper.document, + _helper.layer, + ); return _layerCollection!; } @@ -90,9 +95,9 @@ class PdfLayer implements IPdfWrapper { PdfGraphics createGraphics(PdfPage page) { _helper.page = page; if (_graphics == null) { - PdfPageHelper.getHelper(page) - .contents - .add(PdfReferenceHolder(_helper.layer)); + PdfPageHelper.getHelper( + page, + ).contents.add(PdfReferenceHolder(_helper.layer)); } final PdfResources? resource = PdfPageHelper.getHelper(page).getResources(); if (PdfLayerHelper.getHelper(_helper.layer!).layerId == null || @@ -125,19 +130,21 @@ class PdfLayer implements IPdfWrapper { if (_graphics == null) { final Function resources = PdfPageHelper.getHelper(page).getResources; bool isPageHasMediaBox = false; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfName(PdfDictionaryProperties.mediaBox))) { + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfName(PdfDictionaryProperties.mediaBox))) { isPageHasMediaBox = true; } double llx = 0; double lly = 0; double urx = 0; double ury = 0; - final PdfArray? mediaBox = PdfPageHelper.getHelper(page) - .dictionary! - .getValue(PdfDictionaryProperties.mediaBox, - PdfDictionaryProperties.parent) as PdfArray?; + final PdfArray? mediaBox = + PdfPageHelper.getHelper(page).dictionary!.getValue( + PdfDictionaryProperties.mediaBox, + PdfDictionaryProperties.parent, + ) + as PdfArray?; if (mediaBox != null) { // Lower Left X co-ordinate Value. llx = (mediaBox[0]! as PdfNumber).value!.toDouble(); @@ -149,12 +156,15 @@ class PdfLayer implements IPdfWrapper { ury = (mediaBox[3]! as PdfNumber).value!.toDouble(); } PdfArray? cropBox; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.cropBox)) { - cropBox = PdfPageHelper.getHelper(page).dictionary!.getValue( - PdfDictionaryProperties.cropBox, PdfDictionaryProperties.parent) - as PdfArray?; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.cropBox)) { + cropBox = + PdfPageHelper.getHelper(page).dictionary!.getValue( + PdfDictionaryProperties.cropBox, + PdfDictionaryProperties.parent, + ) + as PdfArray?; final double cropX = (cropBox![0]! as PdfNumber).value!.toDouble(); final double cropY = (cropBox[1]! as PdfNumber).value!.toDouble(); final double cropRX = (cropBox[2]! as PdfNumber).value!.toDouble(); @@ -162,40 +172,57 @@ class PdfLayer implements IPdfWrapper { if ((cropX < 0 || cropY < 0 || cropRX < 0 || cropRY < 0) && (cropY.abs().floor() == page.size.height.abs().floor()) && (cropX.abs().floor()) == page.size.width.abs().floor()) { - final Size pageSize = Size([cropX, cropRX].reduce(max), - [cropY, cropRY].reduce(max)); - _graphics = - PdfGraphicsHelper.load(pageSize, resources, _helper._content!); + final Size pageSize = Size( + [cropX, cropRX].reduce(max), + [cropY, cropRY].reduce(max), + ); + _graphics = PdfGraphicsHelper.load( + pageSize, + resources, + _helper._content!, + ); } else { - _graphics = - PdfGraphicsHelper.load(page.size, resources, _helper._content!); + _graphics = PdfGraphicsHelper.load( + page.size, + resources, + _helper._content!, + ); PdfGraphicsHelper.getHelper(_graphics!).cropBox = cropBox; } } else if ((llx < 0 || lly < 0 || urx < 0 || ury < 0) && (lly.abs().floor() == page.size.height.abs().floor()) && (urx.abs().floor() == page.size.width.abs().floor())) { final Size pageSize = Size( - [llx, urx].reduce(max), [lly, ury].reduce(max)); + [llx, urx].reduce(max), + [lly, ury].reduce(max), + ); if (pageSize.width <= 0 || pageSize.height <= 0) { - _graphics = - PdfGraphicsHelper.load(pageSize, resources, _helper._content!); + _graphics = PdfGraphicsHelper.load( + pageSize, + resources, + _helper._content!, + ); } } else { - _graphics = - PdfGraphicsHelper.load(page.size, resources, _helper._content!); + _graphics = PdfGraphicsHelper.load( + page.size, + resources, + _helper._content!, + ); } if (isPageHasMediaBox) { PdfGraphicsHelper.getHelper(_graphics!).mediaBoxUpperRightBound = ury; } if (!PdfPageHelper.getHelper(page).isLoadedPage) { final PdfSectionCollection? sectionCollection = - PdfSectionHelper.getHelper(PdfPageHelper.getHelper(page).section!) - .parent; + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).parent; if (sectionCollection != null) { _graphics!.colorSpace = - PdfSectionCollectionHelper.getHelper(sectionCollection) - .document! - .colorSpace; + PdfSectionCollectionHelper.getHelper( + sectionCollection, + ).document!.colorSpace; } } if (!_graphicsMap.containsKey(_graphics)) { @@ -213,9 +240,9 @@ class PdfLayer implements IPdfWrapper { return _graphics!; } } - PdfGraphicsHelper.getHelper(_graphics!) - .streamWriter! - .write(PdfOperators.newLine); + PdfGraphicsHelper.getHelper( + _graphics!, + ).streamWriter!.write(PdfOperators.newLine); _graphics!.save(); PdfGraphicsHelper.getHelper(_graphics!).initializeCoordinates(); if (PdfGraphicsHelper.getHelper(_graphics!).hasTransparencyBrush) { @@ -223,39 +250,44 @@ class PdfLayer implements IPdfWrapper { } if (PdfPageHelper.getHelper(page).isLoadedPage && (page.rotation != PdfPageRotateAngle.rotateAngle0 || - PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.rotate))) { + PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.rotate))) { PdfArray? cropBox; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.cropBox)) { - cropBox = PdfPageHelper.getHelper(page).dictionary!.getValue( - PdfDictionaryProperties.cropBox, PdfDictionaryProperties.parent) - as PdfArray?; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.cropBox)) { + cropBox = + PdfPageHelper.getHelper(page).dictionary!.getValue( + PdfDictionaryProperties.cropBox, + PdfDictionaryProperties.parent, + ) + as PdfArray?; } _updatePageRotation(page, _graphics, cropBox); } if (!PdfPageHelper.getHelper(page).isLoadedPage) { - final PdfRectangle clipRect = - PdfSectionHelper.getHelper(PdfPageHelper.getHelper(page).section!) - .getActualBounds(page, true); + final PdfRectangle clipRect = PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).getActualBounds(page, true); if (_clipPageTemplates) { if (PdfPageHelper.getHelper(page).origin.dx >= 0 && PdfPageHelper.getHelper(page).origin.dy >= 0) { - PdfGraphicsHelper.getHelper(_graphics!) - .clipTranslateMarginsWithBounds(clipRect); + PdfGraphicsHelper.getHelper( + _graphics!, + ).clipTranslateMarginsWithBounds(clipRect); } } else { final PdfMargins margins = PdfPageHelper.getHelper(page).section!.pageSettings.margins; PdfGraphicsHelper.getHelper(_graphics!).clipTranslateMargins( - clipRect.x, - clipRect.y, - margins.left, - margins.top, - margins.right, - margins.bottom); + clipRect.x, + clipRect.y, + margins.left, + margins.top, + margins.right, + margins.bottom, + ); } } if (!_helper.pages.contains(page)) { @@ -266,16 +298,26 @@ class PdfLayer implements IPdfWrapper { } void _updatePageRotation( - PdfPage page, PdfGraphics? graphics, PdfArray? cropBox) { + PdfPage page, + PdfGraphics? graphics, + PdfArray? cropBox, + ) { PdfNumber? rotation; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.rotate)) { - rotation = PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.rotate] as PdfNumber?; - rotation ??= rotation = PdfCrossTable.dereference( - PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.rotate]) as PdfNumber?; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.rotate)) { + rotation = + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .rotate] + as PdfNumber?; + rotation ??= + rotation = + PdfCrossTable.dereference( + PdfPageHelper.getHelper( + page, + ).dictionary![PdfDictionaryProperties.rotate], + ) + as PdfNumber?; } else if (page.rotation != PdfPageRotateAngle.rotateAngle0) { if (page.rotation == PdfPageRotateAngle.rotateAngle90) { rotation = PdfNumber(90); @@ -291,25 +333,29 @@ class PdfLayer implements IPdfWrapper { if (cropBox != null) { final double height = (cropBox[3]! as PdfNumber).value!.toDouble(); final Size cropBoxSize = Size( - (cropBox[2]! as PdfNumber).value!.toDouble(), - height != 0 - ? height - : (cropBox[1]! as PdfNumber).value!.toDouble()); + (cropBox[2]! as PdfNumber).value!.toDouble(), + height != 0 ? height : (cropBox[1]! as PdfNumber).value!.toDouble(), + ); final Offset cropBoxOffset = Offset( - (cropBox[0]! as PdfNumber).value!.toDouble(), - (cropBox[1]! as PdfNumber).value!.toDouble()); + (cropBox[0]! as PdfNumber).value!.toDouble(), + (cropBox[1]! as PdfNumber).value!.toDouble(), + ); if (page.size.height < cropBoxSize.height) { PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( - page.size.height - cropBoxOffset.dy, - cropBoxSize.width - cropBoxOffset.dx); + page.size.height - cropBoxOffset.dy, + cropBoxSize.width - cropBoxOffset.dx, + ); } else { PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( - cropBoxSize.height - cropBoxOffset.dy, - cropBoxSize.width - cropBoxOffset.dx); + cropBoxSize.height - cropBoxOffset.dy, + cropBoxSize.width - cropBoxOffset.dx, + ); } } else { - PdfGraphicsHelper.getHelper(graphics).clipBounds.size = - PdfSize(page.size.height, page.size.width); + PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( + page.size.height, + page.size.width, + ); } } else if (rotation.value == 180) { graphics!.translateTransform(page.size.width, page.size.height); @@ -317,15 +363,20 @@ class PdfLayer implements IPdfWrapper { } else if (rotation.value == 270) { graphics!.translateTransform(page.size.width, 0); graphics.rotateTransform(-270); - PdfGraphicsHelper.getHelper(graphics).clipBounds.size = - PdfSize(page.size.height, page.size.width); + PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( + page.size.height, + page.size.width, + ); } } void _graphicsContent(PdfPage page) { final PdfStream stream = PdfStream(); _graphics = PdfGraphicsHelper.load( - page.size, PdfPageHelper.getHelper(page).getResources, stream); + page.size, + PdfPageHelper.getHelper(page).getResources, + stream, + ); PdfPageHelper.getHelper(page).contents.add(PdfReferenceHolder(stream)); stream.beginSave = _beginSaveContent; if (!_graphicsMap.containsKey(_graphics)) { @@ -346,9 +397,9 @@ class PdfLayer implements IPdfWrapper { _helper.beginLayer(_graphics); PdfGraphicsHelper.getHelper(_graphics!).endMarkContent(); } - PdfGraphicsHelper.getHelper(_graphics!) - .streamWriter! - .write(PdfOperators.restoreState + PdfOperators.newLine); + PdfGraphicsHelper.getHelper( + _graphics!, + ).streamWriter!.write(PdfOperators.restoreState + PdfOperators.newLine); keyValue = key; flag = true; } @@ -439,13 +490,14 @@ class PdfLayerHelper { if (parentLayer.isNotEmpty) { for (int i = 0; i < parentLayer.length; i++) { PdfGraphicsHelper.getHelper(base._graphics!).streamWriter!.write( - '/OC /${PdfLayerHelper.getHelper(parentLayer[i]).layerId!} BDC\n'); + '/OC /${PdfLayerHelper.getHelper(parentLayer[i]).layerId!} BDC\n', + ); } } if (base.name != null && base.name != '') { - PdfGraphicsHelper.getHelper(base._graphics!) - .streamWriter! - .write('/OC /${layerId!} BDC\n'); + PdfGraphicsHelper.getHelper( + base._graphics!, + ).streamWriter!.write('/OC /${layerId!} BDC\n'); isEndState = true; } else { _content!.write('/OC /${layerId!} BDC\n'); @@ -463,17 +515,24 @@ class PdfLayerHelper { PdfPageHelper.getHelper(document!.pages[i]).dictionary!; final PdfPage page = document!.pages[i]; if (pageDictionary.containsKey(PdfDictionaryProperties.resources)) { - final PdfDictionary? resources = PdfCrossTable.dereference( - pageDictionary[PdfDictionaryProperties.resources]) - as PdfDictionary?; + final PdfDictionary? resources = + PdfCrossTable.dereference( + pageDictionary[PdfDictionaryProperties.resources], + ) + as PdfDictionary?; if (resources != null && (resources.containsKey(PdfDictionaryProperties.properties)) || (resources!.containsKey(PdfDictionaryProperties.xObject))) { - final PdfDictionary? properties = PdfCrossTable.dereference( - resources[PdfDictionaryProperties.properties]) - as PdfDictionary?; - final PdfDictionary? xObject = PdfCrossTable.dereference( - resources[PdfDictionaryProperties.xObject]) as PdfDictionary?; + final PdfDictionary? properties = + PdfCrossTable.dereference( + resources[PdfDictionaryProperties.properties], + ) + as PdfDictionary?; + final PdfDictionary? xObject = + PdfCrossTable.dereference( + resources[PdfDictionaryProperties.xObject], + ) + as PdfDictionary?; if (properties != null) { properties.items!.forEach((PdfName? key, IPdfPrimitive? value) { if (value is PdfReferenceHolder) { @@ -493,14 +552,15 @@ class PdfLayerHelper { if (dictionary.containsKey('OC')) { final PdfName? layerID = key; reference = dictionary['OC']! as PdfReferenceHolder; - dictionary = PdfCrossTable.dereference(dictionary['OC'])! - as PdfDictionary; + dictionary = + PdfCrossTable.dereference(dictionary['OC'])! + as PdfDictionary; final bool isPresent = _parsingDictionary(dictionary, reference, page, layerID)!; if (isPresent) { - PdfLayerHelper.getHelper(layer!) - .xobject - .add(layerID!.name!); + PdfLayerHelper.getHelper( + layer!, + ).xobject.add(layerID!.name!); } } }); @@ -514,8 +574,12 @@ class PdfLayerHelper { } } - bool? _parsingDictionary(PdfDictionary? dictionary, - PdfReferenceHolder? reference, PdfPage? page, PdfName? layerID) { + bool? _parsingDictionary( + PdfDictionary? dictionary, + PdfReferenceHolder? reference, + PdfPage? page, + PdfName? layerID, + ) { if (base._isPresent == null || !base._isPresent!) { base._isPresent = false; if (!dictionary!.containsKey(PdfDictionaryProperties.name) && @@ -527,8 +591,11 @@ class PdfLayerHelper { if (pdfArray == null) { reference = dictionary[PdfDictionaryProperties.ocg] as PdfReferenceHolder?; - dictionary = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.ocg]) as PdfDictionary?; + dictionary = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.ocg], + ) + as PdfDictionary?; if (dictionary != null && dictionary.containsKey(PdfDictionaryProperties.name)) { base._isPresent = _setLayerPage(reference, page, layerID); @@ -553,13 +620,20 @@ class PdfLayerHelper { } bool _setLayerPage( - PdfReferenceHolder? reference, PdfPage? page, PdfName? layerID) { + PdfReferenceHolder? reference, + PdfPage? page, + PdfName? layerID, + ) { bool isPresent = false; if (PdfLayerHelper.getHelper(layer!).referenceHolder != null) { if (identical( - PdfLayerHelper.getHelper(layer!).referenceHolder, reference) || - identical(PdfLayerHelper.getHelper(layer!).referenceHolder!.object, - reference!.object) || + PdfLayerHelper.getHelper(layer!).referenceHolder, + reference, + ) || + identical( + PdfLayerHelper.getHelper(layer!).referenceHolder!.object, + reference!.object, + ) || PdfLayerHelper.getHelper(layer!).referenceHolder?.reference?.objNum == reference.reference?.objNum) { PdfLayerHelper.getHelper(layer!).pageParsed = true; @@ -574,6 +648,81 @@ class PdfLayerHelper { return isPresent; } + void _setVisibility(bool? value) { + PdfDictionary? oCProperties; + if (PdfDocumentHelper.getHelper( + document!, + ).catalog.containsKey(PdfDictionaryProperties.ocProperties)) { + oCProperties = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; + } + if (oCProperties != null) { + PdfDictionary? defaultView; + if (oCProperties.containsKey(PdfDictionaryProperties.defaultView)) { + final value = oCProperties[PdfDictionaryProperties.defaultView]; + if (value is PdfReferenceHolder) { + defaultView = PdfCrossTable.dereference(value) as PdfDictionary?; + } else if (value is PdfDictionary) { + defaultView = value; + } + } + if (defaultView != null) { + PdfArray? ocgON = + defaultView[PdfDictionaryProperties.ocgOn] as PdfArray?; + PdfArray? ocgOFF = + defaultView[PdfDictionaryProperties.ocgOff] as PdfArray?; + if (referenceHolder != null) { + if (value == false) { + if (ocgON != null) { + _removeContent(ocgON, referenceHolder); + } + if (ocgOFF == null) { + ocgOFF = PdfArray(); + defaultView.items![PdfName(PdfDictionaryProperties.ocgOff)] = + ocgOFF; + } + ocgOFF.insert(ocgOFF.count, referenceHolder!); + } else if (value ?? true) { + if (ocgOFF != null) { + _removeContent(ocgOFF, referenceHolder); + } + if (ocgON == null) { + ocgON = PdfArray(); + defaultView.items![PdfName(PdfDictionaryProperties.ocgOn)] = + ocgON; + } + ocgON.insert(ocgON.count, referenceHolder!); + } + } + } + } + } + + void _removeContent(PdfArray content, PdfReferenceHolder? referenceHolder) { + bool flag = false; + for (int i = 0; i < content.count; i++) { + final IPdfPrimitive? primitive = content.elements[i]; + if (primitive != null && primitive is PdfReferenceHolder) { + final PdfReferenceHolder holder = primitive; + if (holder.reference != null && referenceHolder!.reference != null) { + if (holder.reference!.objNum == referenceHolder.reference!.objNum) { + content.elements.removeAt(i); + flag = true; + i--; + } + } + } + } + if (flag) { + content.changed = true; + } + } + /// internal property IPdfPrimitive? get element => _content; //ignore: unused_element diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer_collection.dart index f5e0d8d5a..50d1a3e11 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_layer_collection.dart @@ -45,8 +45,11 @@ class PdfLayerCollection extends PdfObjectCollection { } /// Removes layer from the collection by using layer or layer name and may also remove graphical content, if isRemoveGraphicalContent is true. - void remove( - {PdfLayer? layer, String? name, bool isRemoveGraphicalContent = false}) { + void remove({ + PdfLayer? layer, + String? name, + bool isRemoveGraphicalContent = false, + }) { _helper.remove(layer, name, isRemoveGraphicalContent); } @@ -65,7 +68,7 @@ class PdfLayerCollection extends PdfObjectCollection { class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfLayerCollectionHelper(this.layerCollection, PdfDocument document) - : super(layerCollection) { + : super(layerCollection) { _document = document; _sublayer = false; if (PdfDocumentHelper.getHelper(document).isLoadedDocument) { @@ -75,8 +78,10 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfLayerCollectionHelper._( - this.layerCollection, PdfDocument? document, PdfLayer? layer) - : super(layerCollection) { + this.layerCollection, + PdfDocument? document, + PdfLayer? layer, + ) : super(layerCollection) { _document = document; _parent = layer; _sublayer = true; @@ -148,7 +153,8 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { void removeAt(int index, bool isRemoveGraphicalContent) { if (index < 0 || index > list.length - 1) { ArgumentError.value( - '$index Value can not be less 0 and greater List.Count - 1'); + '$index Value can not be less 0 and greater List.Count - 1', + ); } final PdfLayer layer = layerCollection[index]; list.removeAt(index); @@ -176,31 +182,34 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { void _createLayer(PdfLayer layer) { final PdfDictionary ocProperties = PdfDictionary(); - ocProperties[PdfDictionaryProperties.ocg] = - _createOptionalContentDictionary(layer); - ocProperties[PdfDictionaryProperties.defaultView] = - _createOptionalContentViews(layer); - PdfDocumentHelper.getHelper(_document!) - .catalog[PdfDictionaryProperties.ocProperties] = ocProperties; - PdfDocumentHelper.getHelper(_document!) - .catalog - .setProperty(PdfDictionaryProperties.ocProperties, ocProperties); + ocProperties[PdfDictionaryProperties + .ocg] = _createOptionalContentDictionary(layer); + ocProperties[PdfDictionaryProperties + .defaultView] = _createOptionalContentViews(layer); + PdfDocumentHelper.getHelper(_document!).catalog[PdfDictionaryProperties + .ocProperties] = + ocProperties; + PdfDocumentHelper.getHelper( + _document!, + ).catalog.setProperty(PdfDictionaryProperties.ocProperties, ocProperties); } IPdfPrimitive? _createOptionalContentDictionary(PdfLayer layer) { final PdfDictionary dictionary = PdfDictionary(); dictionary[PdfDictionaryProperties.name] = PdfString(layer.name!); dictionary[PdfDictionaryProperties.type] = PdfName('OCG'); - dictionary[PdfDictionaryProperties.layerID] = - PdfName(PdfLayerHelper.getHelper(layer).layerId); + dictionary[PdfDictionaryProperties.layerID] = PdfName( + PdfLayerHelper.getHelper(layer).layerId, + ); dictionary[PdfDictionaryProperties.visible] = PdfBoolean(layer.visible); PdfLayerHelper.getHelper(layer).usage = _setPrintOption(layer); - dictionary[PdfDictionaryProperties.usage] = - PdfReferenceHolder(PdfLayerHelper.getHelper(layer).usage); - PdfDocumentHelper.getHelper(_document!) - .printLayer! - .add(PdfReferenceHolder(dictionary)); + dictionary[PdfDictionaryProperties.usage] = PdfReferenceHolder( + PdfLayerHelper.getHelper(layer).usage, + ); + PdfDocumentHelper.getHelper( + _document!, + ).printLayer!.add(PdfReferenceHolder(dictionary)); final PdfReferenceHolder reference = PdfReferenceHolder(dictionary); PdfDocumentHelper.getHelper(_document!).pdfPrimitive!.add(reference); @@ -208,9 +217,13 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { PdfLayerHelper.getHelper(layer).dictionary = dictionary; // Order of the layers - final PdfDictionary? ocProperties = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(_document!) - .catalog[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + final PdfDictionary? ocProperties = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + _document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; _createSublayer(ocProperties, reference, layer); if (layer.visible) { PdfDocumentHelper.getHelper(_document!).on!.add(reference); @@ -223,24 +236,33 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { PdfDictionary _setPrintOption(PdfLayer layer) { final PdfDictionary usage = PdfDictionary(); PdfLayerHelper.getHelper(layer).printOption = PdfDictionary(); - PdfLayerHelper.getHelper(layer) - .printOption![PdfDictionaryProperties.subtype] = PdfName('Print'); - usage[PdfDictionaryProperties.print] = - PdfReferenceHolder(PdfLayerHelper.getHelper(layer).printOption); + PdfLayerHelper.getHelper(layer).printOption![PdfDictionaryProperties + .subtype] = PdfName('Print'); + usage[PdfDictionaryProperties.print] = PdfReferenceHolder( + PdfLayerHelper.getHelper(layer).printOption, + ); return usage; } - void _createSublayer(PdfDictionary? ocProperties, - PdfReferenceHolder reference, PdfLayer layer) { + void _createSublayer( + PdfDictionary? ocProperties, + PdfReferenceHolder reference, + PdfLayer layer, + ) { if (_sublayer == false) { if (ocProperties != null) { PdfArray? order; - final PdfDictionary? defaultview = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) - as PdfDictionary?; + final PdfDictionary? defaultview = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultview != null) { - order = PdfCrossTable.dereference( - defaultview[PdfDictionaryProperties.ocgOrder]) as PdfArray?; + order = + PdfCrossTable.dereference( + defaultview[PdfDictionaryProperties.ocgOrder], + ) + as PdfArray?; } if (PdfDocumentHelper.getHelper(_document!).order != null && order != null) { @@ -254,12 +276,17 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { PdfLayerHelper.getHelper(layer).parent = _parent; if (ocProperties != null) { PdfArray? order; - final PdfDictionary? defaultview = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) - as PdfDictionary?; + final PdfDictionary? defaultview = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultview != null) { - order = PdfCrossTable.dereference( - defaultview[PdfDictionaryProperties.ocgOrder]) as PdfArray?; + order = + PdfCrossTable.dereference( + defaultview[PdfDictionaryProperties.ocgOrder], + ) + as PdfArray?; } if (PdfDocumentHelper.getHelper(_document!).order != null && order != null) { @@ -268,59 +295,66 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } if (PdfLayerHelper.getHelper(_parent!).child.isEmpty) { PdfLayerHelper.getHelper(_parent!).sublayer.add(reference); - } else if (PdfDocumentHelper.getHelper(_document!) - .order! - .contains(PdfLayerHelper.getHelper(_parent!).referenceHolder!)) { - final int position = PdfDocumentHelper.getHelper(_document!) - .order! - .indexOf(PdfLayerHelper.getHelper(_parent!).referenceHolder!); + } else if (PdfDocumentHelper.getHelper( + _document!, + ).order!.contains(PdfLayerHelper.getHelper(_parent!).referenceHolder!)) { + final int position = PdfDocumentHelper.getHelper( + _document!, + ).order!.indexOf(PdfLayerHelper.getHelper(_parent!).referenceHolder!); PdfDocumentHelper.getHelper(_document!).order!.removeAt(position + 1); PdfLayerHelper.getHelper(_parent!).sublayer.add(reference); } else { PdfLayerHelper.getHelper(_parent!).sublayer.add(reference); } - if (PdfDocumentHelper.getHelper(_document!) - .order! - .contains(PdfLayerHelper.getHelper(_parent!).referenceHolder!)) { - final int position = PdfDocumentHelper.getHelper(_document!) - .order! - .indexOf(PdfLayerHelper.getHelper(_parent!).referenceHolder!); - PdfDocumentHelper.getHelper(_document!) - .order! - .insert(position + 1, PdfLayerHelper.getHelper(_parent!).sublayer); + if (PdfDocumentHelper.getHelper( + _document!, + ).order!.contains(PdfLayerHelper.getHelper(_parent!).referenceHolder!)) { + final int position = PdfDocumentHelper.getHelper( + _document!, + ).order!.indexOf(PdfLayerHelper.getHelper(_parent!).referenceHolder!); + PdfDocumentHelper.getHelper(_document!).order!.insert( + position + 1, + PdfLayerHelper.getHelper(_parent!).sublayer, + ); } else { if (PdfLayerHelper.getHelper(_parent!).parent != null) { if (PdfLayerHelper.getHelper( - PdfLayerHelper.getHelper(_parent!).parent!) - .sublayer - .contains(PdfLayerHelper.getHelper(_parent!).referenceHolder!)) { + PdfLayerHelper.getHelper(_parent!).parent!, + ).sublayer.contains( + PdfLayerHelper.getHelper(_parent!).referenceHolder!, + )) { int position = PdfLayerHelper.getHelper( - PdfLayerHelper.getHelper(_parent!).parent!) - .sublayer - .indexOf(PdfLayerHelper.getHelper(_parent!).referenceHolder!); + PdfLayerHelper.getHelper(_parent!).parent!, + ).sublayer.indexOf( + PdfLayerHelper.getHelper(_parent!).referenceHolder!, + ); if (PdfLayerHelper.getHelper(_parent!).sublayer.count == 1) { PdfLayerHelper.getHelper( - PdfLayerHelper.getHelper(_parent!).parent!) - .sublayer - .insert(position + 1, - PdfLayerHelper.getHelper(_parent!).sublayer); + PdfLayerHelper.getHelper(_parent!).parent!, + ).sublayer.insert( + position + 1, + PdfLayerHelper.getHelper(_parent!).sublayer, + ); } if (PdfDocumentHelper.getHelper(_document!).order!.contains( - PdfLayerHelper.getHelper( - PdfLayerHelper.getHelper(_parent!).parent!) - .referenceHolder!)) { + PdfLayerHelper.getHelper( + PdfLayerHelper.getHelper(_parent!).parent!, + ).referenceHolder!, + )) { position = PdfDocumentHelper.getHelper(_document!).order!.indexOf( - PdfLayerHelper.getHelper( - PdfLayerHelper.getHelper(_parent!).parent!) - .referenceHolder!); - PdfDocumentHelper.getHelper(_document!) - .order! - .removeAt(position + 1); + PdfLayerHelper.getHelper( + PdfLayerHelper.getHelper(_parent!).parent!, + ).referenceHolder!, + ); + PdfDocumentHelper.getHelper( + _document!, + ).order!.removeAt(position + 1); PdfDocumentHelper.getHelper(_document!).order!.insert( - position + 1, - PdfLayerHelper.getHelper( - PdfLayerHelper.getHelper(_parent!).parent!) - .sublayer); + position + 1, + PdfLayerHelper.getHelper( + PdfLayerHelper.getHelper(_parent!).parent!, + ).sublayer, + ); } } } @@ -331,15 +365,17 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { if (PdfLayerHelper.getHelper(_parent!).parentLayer.isEmpty) { PdfLayerHelper.getHelper(layer).parentLayer.add(_parent!); } else { - for (int i = 0; - i < PdfLayerHelper.getHelper(_parent!).parentLayer.length; - i++) { - if (!PdfLayerHelper.getHelper(layer) - .parentLayer - .contains(PdfLayerHelper.getHelper(_parent!).parentLayer[i])) { - PdfLayerHelper.getHelper(layer) - .parentLayer - .add(PdfLayerHelper.getHelper(_parent!).parentLayer[i]); + for ( + int i = 0; + i < PdfLayerHelper.getHelper(_parent!).parentLayer.length; + i++ + ) { + if (!PdfLayerHelper.getHelper(layer).parentLayer.contains( + PdfLayerHelper.getHelper(_parent!).parentLayer[i], + )) { + PdfLayerHelper.getHelper(layer).parentLayer.add( + PdfLayerHelper.getHelper(_parent!).parentLayer[i], + ); } } PdfLayerHelper.getHelper(layer).parentLayer.add(_parent!); @@ -372,16 +408,23 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { void _getDocumentLayer(PdfDocument document) { PdfDictionary? layerDictionary; PdfReferenceHolder layerReference; - if (PdfDocumentHelper.getHelper(_document!) - .catalog - .containsKey(PdfDictionaryProperties.ocProperties)) { - final PdfDictionary? ocProperties = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(_document!) - .catalog[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + if (PdfDocumentHelper.getHelper( + _document!, + ).catalog.containsKey(PdfDictionaryProperties.ocProperties)) { + final PdfDictionary? ocProperties = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + _document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; if (ocProperties != null) { if (ocProperties.containsKey(PdfDictionaryProperties.ocg)) { - final PdfArray ocGroup = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.ocg])! as PdfArray; + final PdfArray ocGroup = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.ocg], + )! + as PdfArray; for (int i = 0; i < ocGroup.count; i++) { if (ocGroup[i] is PdfReferenceHolder) { layerReference = ocGroup[i]! as PdfReferenceHolder; @@ -389,25 +432,33 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { final PdfLayer layer = PdfLayerHelper.internal(); if (layerDictionary != null && layerDictionary.containsKey(PdfDictionaryProperties.name)) { - final PdfString layerName = PdfCrossTable.dereference( - layerDictionary[PdfDictionaryProperties.name])! - as PdfString; + final PdfString layerName = + PdfCrossTable.dereference( + layerDictionary[PdfDictionaryProperties.name], + )! + as PdfString; layer.name = layerName.value; PdfLayerHelper.getHelper(layer).dictionary = layerDictionary; PdfLayerHelper.getHelper(layer).referenceHolder = layerReference; final IPdfPrimitive? layerId = PdfCrossTable.dereference( - layerDictionary[PdfDictionaryProperties.layerID]); + layerDictionary[PdfDictionaryProperties.layerID], + ); if (layerId != null) { PdfLayerHelper.getHelper(layer).layerId = layerId.toString(); } - final PdfDictionary? usage = PdfCrossTable.dereference( - layerDictionary[PdfDictionaryProperties.usage]) - as PdfDictionary?; + final PdfDictionary? usage = + PdfCrossTable.dereference( + layerDictionary[PdfDictionaryProperties.usage], + ) + as PdfDictionary?; if (usage != null) { - final PdfDictionary? printOption = PdfCrossTable.dereference( - usage[PdfDictionaryProperties.print]) as PdfDictionary?; + final PdfDictionary? printOption = + PdfCrossTable.dereference( + usage[PdfDictionaryProperties.print], + ) + as PdfDictionary?; if (printOption != null) { PdfLayerHelper.getHelper(layer).printOption = printOption; @@ -432,16 +483,22 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { void _checkLayerVisible(PdfDictionary ocProperties) { PdfArray? visible; - if (PdfDocumentHelper.getHelper(_document!) - .catalog - .containsKey(PdfDictionaryProperties.ocProperties)) { - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) as PdfDictionary?; + if (PdfDocumentHelper.getHelper( + _document!, + ).catalog.containsKey(PdfDictionaryProperties.ocProperties)) { + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null && defaultView.containsKey(PdfDictionaryProperties.ocgOff)) { - visible = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOff]) as PdfArray?; + visible = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOff], + ) + as PdfArray?; } if (visible != null) { for (int i = 0; i < visible.count; i++) { @@ -450,11 +507,13 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { if (pdfLayer != null) { pdfLayer.visible = false; if (PdfLayerHelper.getHelper(pdfLayer).dictionary != null && - PdfLayerHelper.getHelper(pdfLayer) - .dictionary! - .containsKey(PdfDictionaryProperties.visible)) { + PdfLayerHelper.getHelper( + pdfLayer, + ).dictionary!.containsKey(PdfDictionaryProperties.visible)) { PdfLayerHelper.getHelper(pdfLayer).dictionary!.setProperty( - PdfDictionaryProperties.visible, PdfBoolean(false)); + PdfDictionaryProperties.visible, + PdfBoolean(false), + ); } } } @@ -463,11 +522,17 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } void _checkParentLayer(PdfDictionary ocProperties) { - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) as PdfDictionary?; + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null) { - final PdfArray? array = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOrder]) as PdfArray?; + final PdfArray? array = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOrder], + ) + as PdfArray?; if (array != null) { _parsingLayerOrder(array, _layerDictionary); } @@ -476,12 +541,18 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { void _checkLayerLock(PdfDictionary ocProperties) { PdfArray? locked; - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) as PdfDictionary?; + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null && defaultView.containsKey(PdfDictionaryProperties.ocgLock)) { - locked = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgLock]) as PdfArray?; + locked = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgLock], + ) + as PdfArray?; } if (locked != null) { for (int i = 0; i < locked.count; i++) { @@ -495,8 +566,11 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } void _createLayerHierarchical(PdfDictionary ocProperties) { - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) as PdfDictionary?; + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null && defaultView.containsKey(PdfDictionaryProperties.ocgOrder)) { if (_layerDictionary.isNotEmpty) { @@ -510,17 +584,12 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { _addChildlayer(PdfLayerHelper.getHelper(pdfLayer).parent!); } else if (PdfLayerHelper.getHelper(pdfLayer).parent != null && PdfLayerHelper.getHelper(pdfLayer).child.isEmpty && - !PdfLayerHelper.getHelper(pdfLayer) - .parent! - .layers - ._helper - .list - .contains(pdfLayer)) { - PdfLayerHelper.getHelper(pdfLayer) - .parent! - .layers - ._helper - ._addNestedLayer(pdfLayer); + !PdfLayerHelper.getHelper( + pdfLayer, + ).parent!.layers._helper.list.contains(pdfLayer)) { + PdfLayerHelper.getHelper( + pdfLayer, + ).parent!.layers._helper._addNestedLayer(pdfLayer); } }); } @@ -543,8 +612,10 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } void _parsingLayerOrder( - PdfArray array, Map layerDictionary, - [PdfLayer? parent]) { + PdfArray array, + Map layerDictionary, [ + PdfLayer? parent, + ]) { PdfReferenceHolder reference; PdfLayer? layer; for (int i = 0; i < array.count; i++) { @@ -563,14 +634,17 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { PdfLayerHelper.getHelper(parent).parentLayer.add(parent); PdfLayerHelper.getHelper(layer!).parent = parent; } else { - for (int j = 0; - j < PdfLayerHelper.getHelper(parent).parentLayer.length; - j++) { + for ( + int j = 0; + j < PdfLayerHelper.getHelper(parent).parentLayer.length; + j++ + ) { if (!PdfLayerHelper.getHelper(layer!).parentLayer.contains( - PdfLayerHelper.getHelper(parent).parentLayer[j])) { - PdfLayerHelper.getHelper(layer!) - .parentLayer - .add(PdfLayerHelper.getHelper(parent).parentLayer[j]); + PdfLayerHelper.getHelper(parent).parentLayer[j], + )) { + PdfLayerHelper.getHelper(layer!).parentLayer.add( + PdfLayerHelper.getHelper(parent).parentLayer[j], + ); } } PdfLayerHelper.getHelper(layer!).parentLayer.add(parent); @@ -597,8 +671,11 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { _parsingLayerOrder(subarray, layerDictionary, parent); } else { parent = null; - _parsingLayerOrder(PdfCrossTable.dereference(array[i])! as PdfArray, - layerDictionary, parent); + _parsingLayerOrder( + PdfCrossTable.dereference(array[i])! as PdfArray, + layerDictionary, + parent, + ); } } } @@ -609,55 +686,84 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { if (_document != null) { dictionary = PdfDocumentHelper.getHelper(_document!).catalog; if (dictionary.containsKey(PdfDictionaryProperties.ocProperties)) { - final PdfDictionary? ocPropertie = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + final PdfDictionary? ocPropertie = + PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; if (ocPropertie != null) { - final PdfArray? ocGroup = PdfCrossTable.dereference( - ocPropertie[PdfDictionaryProperties.ocg]) as PdfArray?; + final PdfArray? ocGroup = + PdfCrossTable.dereference( + ocPropertie[PdfDictionaryProperties.ocg], + ) + as PdfArray?; if (ocGroup != null) { _removeOCProperties( - ocGroup, PdfLayerHelper.getHelper(layer).referenceHolder); + ocGroup, + PdfLayerHelper.getHelper(layer).referenceHolder, + ); } if (ocPropertie.containsKey(PdfDictionaryProperties.defaultView)) { - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocPropertie[PdfDictionaryProperties.defaultView]) - as PdfDictionary?; + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocPropertie[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null) { PdfArray? on, off; if (defaultView.containsKey(PdfDictionaryProperties.ocgOrder)) { - final PdfArray? order = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOrder]) as PdfArray?; + final PdfArray? order = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOrder], + ) + as PdfArray?; if (order != null) { _removeOrder(layer, order, []); // _removeOCProperties(order, layer.referenceHolder); } } if (defaultView.containsKey(PdfDictionaryProperties.ocgLock)) { - final PdfArray? locked = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgLock]) as PdfArray?; + final PdfArray? locked = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgLock], + ) + as PdfArray?; if (locked != null) { _removeOCProperties( - locked, PdfLayerHelper.getHelper(layer).referenceHolder); + locked, + PdfLayerHelper.getHelper(layer).referenceHolder, + ); } } if (defaultView.containsKey(PdfDictionaryProperties.ocgOff)) { - off = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOff]) as PdfArray?; + off = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOff], + ) + as PdfArray?; } if (defaultView.containsKey(PdfDictionaryProperties.ocgOn)) { - on = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOn]) as PdfArray?; + on = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOn], + ) + as PdfArray?; } else if (defaultView.containsKey('ON')) { on = PdfCrossTable.dereference(defaultView['ON']) as PdfArray?; } - if (defaultView - .containsKey(PdfDictionaryProperties.usageApplication)) { - final PdfArray? usage = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.usageApplication]) - as PdfArray?; + if (defaultView.containsKey( + PdfDictionaryProperties.usageApplication, + )) { + final PdfArray? usage = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.usageApplication], + ) + as PdfArray?; if (usage != null) { _removeOCProperties( - usage, PdfLayerHelper.getHelper(layer).referenceHolder); + usage, + PdfLayerHelper.getHelper(layer).referenceHolder, + ); } } _removeVisible(layer, on, off); @@ -675,12 +781,16 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { if (layer.visible) { if (on != null) { _removeOCProperties( - on, PdfLayerHelper.getHelper(layer).referenceHolder); + on, + PdfLayerHelper.getHelper(layer).referenceHolder, + ); } } else { if (off != null) { _removeOCProperties( - off, PdfLayerHelper.getHelper(layer).referenceHolder); + off, + PdfLayerHelper.getHelper(layer).referenceHolder, + ); } } } @@ -690,10 +800,14 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { for (int i = 0; i < order.count; i++) { if (order[i] is PdfReferenceHolder) { final PdfReferenceHolder holder = order[i]! as PdfReferenceHolder; - if (identical(holder.object, - PdfLayerHelper.getHelper(layer).referenceHolder!.object) || - identical(holder.reference, - PdfLayerHelper.getHelper(layer).referenceHolder!.reference)) { + if (identical( + holder.object, + PdfLayerHelper.getHelper(layer).referenceHolder!.object, + ) || + identical( + holder.reference, + PdfLayerHelper.getHelper(layer).referenceHolder!.reference, + )) { if (i != order.count - 1) { if (order[i + 1] is PdfArray) { order.removeAt(i); @@ -726,7 +840,9 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } void _removeOCProperties( - PdfArray content, PdfReferenceHolder? referenceHolder) { + PdfArray content, + PdfReferenceHolder? referenceHolder, + ) { bool isChange = false; for (int i = 0; i < content.count; i++) { final IPdfPrimitive? primitive = content.elements[i]; @@ -767,17 +883,28 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } if (PdfLayerHelper.getHelper(layer).pages.isNotEmpty) { for (int i = 0; i < PdfLayerHelper.getHelper(layer).pages.length; i++) { - final PdfDictionary? resource = PdfCrossTable.dereference(PdfPageHelper - .getHelper(PdfLayerHelper.getHelper(layer).pages[i]) - .dictionary![PdfDictionaryProperties.resources]) as PdfDictionary?; + final PdfDictionary? resource = + PdfCrossTable.dereference( + PdfPageHelper.getHelper( + PdfLayerHelper.getHelper(layer).pages[i], + ).dictionary![PdfDictionaryProperties.resources], + ) + as PdfDictionary?; if (resource != null) { - properties = PdfCrossTable.dereference( - resource[PdfDictionaryProperties.properties]) as PdfDictionary?; - xObject = PdfCrossTable.dereference( - resource[PdfDictionaryProperties.xObject]) as PdfDictionary?; + properties = + PdfCrossTable.dereference( + resource[PdfDictionaryProperties.properties], + ) + as PdfDictionary?; + xObject = + PdfCrossTable.dereference( + resource[PdfDictionaryProperties.xObject], + ) + as PdfDictionary?; if (properties != null) { - if (properties - .containsKey(PdfLayerHelper.getHelper(layer).layerId)) { + if (properties.containsKey( + PdfLayerHelper.getHelper(layer).layerId, + )) { properties.remove(PdfLayerHelper.getHelper(layer).layerId); } } @@ -793,16 +920,17 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } } final PdfArray content = - PdfPageHelper.getHelper(PdfLayerHelper.getHelper(layer).pages[i]) - .contents; + PdfPageHelper.getHelper( + PdfLayerHelper.getHelper(layer).pages[i], + ).contents; for (int m = 0; m < content.count; m++) { List? stream = []; final PdfStream data = PdfStream(); final PdfStream pageContent = PdfCrossTable.dereference(content[m])! as PdfStream; if (PdfPageHelper.getHelper( - PdfLayerHelper.getHelper(layer).pages[i]) - .isLoadedPage) { + PdfLayerHelper.getHelper(layer).pages[i], + ).isLoadedPage) { pageContent.decompress(); } stream = pageContent.dataStream; @@ -814,13 +942,18 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { if (mOperator == 'BMC' || mOperator == 'EMC' || mOperator == 'BDC') { - _processBeginMarkContent(layer, mOperator, - recordCollection.recordCollection[j].operands, data); + _processBeginMarkContent( + layer, + mOperator, + recordCollection.recordCollection[j].operands, + data, + ); isSkip = true; } if (mOperator == PdfOperators.paintXObject) { if (PdfLayerHelper.getHelper(layer).xobject.contains( - recordCollection.recordCollection[j].operands![0])) { + recordCollection.recordCollection[j].operands![0], + )) { isSkip = true; } } @@ -837,12 +970,20 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { mOperator == PdfOperators.selectColorSpaceForNonStroking || mOperator == PdfOperators.selectColorSpaceForStroking) { if (!isSkip) { - _streamWrite(recordCollection.recordCollection[j].operands, - mOperator, false, data); + _streamWrite( + recordCollection.recordCollection[j].operands, + mOperator, + false, + data, + ); } } else if (!isSkip) { - _streamWrite(recordCollection.recordCollection[j].operands, - mOperator, true, data); + _streamWrite( + recordCollection.recordCollection[j].operands, + mOperator, + true, + data, + ); } isSkip = false; } @@ -859,8 +1000,12 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } } - void _processBeginMarkContent(PdfLayer parser, String? mOperator, - List? operands, PdfStream data) { + void _processBeginMarkContent( + PdfLayer parser, + String? mOperator, + List? operands, + PdfStream data, + ) { if ('BDC' == mOperator) { String? operand; if (operands!.length > 1 && ((operands[0]) == '/OC')) { @@ -882,7 +1027,11 @@ class PdfLayerCollectionHelper extends PdfObjectCollectionHelper { } void _streamWrite( - List? operands, String? mOperator, bool skip, PdfStream data) { + List? operands, + String? mOperator, + bool skip, + PdfStream data, + ) { PdfString pdfString; if (skip && _bdcCount > 0) { return; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page.dart index 4e89a0a0f..5f48e3f82 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page.dart @@ -66,8 +66,11 @@ class PdfPage implements IPdfWrapper { _initialize(); } - PdfPage._fromDictionary(PdfDocument document, PdfCrossTable crossTable, - PdfDictionary dictionary) { + PdfPage._fromDictionary( + PdfDocument document, + PdfCrossTable crossTable, + PdfDictionary dictionary, + ) { _helper = PdfPageHelper(this); _helper._pdfDocument = document; _helper.dictionary = dictionary; @@ -105,9 +108,13 @@ class PdfPage implements IPdfWrapper { double width = 0; double height = 0; final IPdfPrimitive? mBox = _helper.dictionary!.getValue( - PdfDictionaryProperties.mediaBox, PdfDictionaryProperties.parent); + PdfDictionaryProperties.mediaBox, + PdfDictionaryProperties.parent, + ); final IPdfPrimitive? cBox = _helper.dictionary!.getValue( - PdfDictionaryProperties.cropBox, PdfDictionaryProperties.parent); + PdfDictionaryProperties.cropBox, + PdfDictionaryProperties.parent, + ); if (cBox != null && cBox is PdfArray) { final num c0 = (cBox[0]! as PdfNumber).value!; final num? c1 = (cBox[1]! as PdfNumber).value; @@ -154,11 +161,13 @@ class PdfPage implements IPdfWrapper { _helper._annotations = PdfAnnotationCollection(this); if (!_helper.dictionary!.containsKey(PdfDictionaryProperties.annots)) { _helper.dictionary![PdfDictionaryProperties.annots] = - PdfAnnotationCollectionHelper.getHelper(_helper._annotations!) - .internalAnnotations; + PdfAnnotationCollectionHelper.getHelper( + _helper._annotations!, + ).internalAnnotations; } - PdfAnnotationCollectionHelper.getHelper(_helper._annotations!) - .internalAnnotations = + PdfAnnotationCollectionHelper.getHelper( + _helper._annotations!, + ).internalAnnotations = _helper.dictionary![PdfDictionaryProperties.annots] as PdfArray?; } } else { @@ -167,9 +176,9 @@ class PdfPage implements IPdfWrapper { _helper.createAnnotations(_helper.getWidgetReferences()); } if (_helper._annotations == null || - (PdfAnnotationCollectionHelper.getHelper(_helper._annotations!) - .internalAnnotations - .count == + (PdfAnnotationCollectionHelper.getHelper( + _helper._annotations!, + ).internalAnnotations.count == 0 && _helper._annotations!.count != 0)) { _helper._annotations = PdfAnnotationCollectionHelper.load(this); @@ -306,8 +315,9 @@ class PdfPage implements IPdfWrapper { set rotation(PdfPageRotateAngle angle) { if (_helper.isLoadedPage && rotation != angle) { _rotation = angle; - _helper.dictionary![PdfDictionaryProperties.rotate] = - PdfNumber(PdfSectionCollectionHelper.rotateFactor * angle.index); + _helper.dictionary![PdfDictionaryProperties.rotate] = PdfNumber( + PdfSectionCollectionHelper.rotateFactor * angle.index, + ); } } @@ -334,10 +344,9 @@ class PdfPage implements IPdfWrapper { Size getClientSize() { return _helper.isLoadedPage ? size - : PdfSectionHelper.getHelper(_helper.section!) - .getActualBounds(this, true) - .size - .size; + : PdfSectionHelper.getHelper( + _helper.section!, + ).getActualBounds(this, true).size.size; } /// Creates a template from the page content. @@ -378,30 +387,38 @@ class PdfPage implements IPdfWrapper { void _drawPageTemplates(PdfDocument doc) { // Draw Background templates. - final bool hasBackTemplates = PdfSectionHelper.getHelper(_helper.section!) - .containsTemplates(doc, this, false); + final bool hasBackTemplates = PdfSectionHelper.getHelper( + _helper.section!, + ).containsTemplates(doc, this, false); if (hasBackTemplates) { - final PdfPageLayer backLayer = - PdfPageLayerHelper.fromClipPageTemplate(this, false); + final PdfPageLayer backLayer = PdfPageLayerHelper.fromClipPageTemplate( + this, + false, + ); final PdfPageLayerCollection layer = PdfPageLayerCollection(this); _layers = layer; _layers!.addLayer(backLayer); - PdfSectionHelper.getHelper(_helper.section!) - .drawTemplates(this, backLayer, doc, false); + PdfSectionHelper.getHelper( + _helper.section!, + ).drawTemplates(this, backLayer, doc, false); } // Draw Foreground templates. - final bool hasFrontTemplates = PdfSectionHelper.getHelper(_helper.section!) - .containsTemplates(doc, this, true); + final bool hasFrontTemplates = PdfSectionHelper.getHelper( + _helper.section!, + ).containsTemplates(doc, this, true); if (hasFrontTemplates) { - final PdfPageLayer frontLayer = - PdfPageLayerHelper.fromClipPageTemplate(this, false); + final PdfPageLayer frontLayer = PdfPageLayerHelper.fromClipPageTemplate( + this, + false, + ); final PdfPageLayerCollection layer = PdfPageLayerCollection(this); _layers = layer; _layers!.addLayer(frontLayer); - PdfSectionHelper.getHelper(_helper.section!) - .drawTemplates(this, frontLayer, doc, true); + PdfSectionHelper.getHelper( + _helper.section!, + ).drawTemplates(this, frontLayer, doc, true); } } @@ -413,7 +430,8 @@ class PdfPage implements IPdfWrapper { if (parent[PdfDictionaryProperties.rotate] is PdfReferenceHolder) { angle = (parent[PdfDictionaryProperties.rotate]! as PdfReferenceHolder) - .object as PdfNumber?; + .object + as PdfNumber?; } else { angle = parent[PdfDictionaryProperties.rotate] as PdfNumber?; } @@ -422,9 +440,10 @@ class PdfPage implements IPdfWrapper { IPdfPrimitive? parentPrimitive = parent[PdfDictionaryProperties.parent]; if (parentPrimitive != null) { parentPrimitive = PdfCrossTable.dereference(parentPrimitive); - parent = parentPrimitive != null && parentPrimitive is PdfDictionary - ? parentPrimitive - : null; + parent = + parentPrimitive != null && parentPrimitive is PdfDictionary + ? parentPrimitive + : null; } else { parent = null; } @@ -436,8 +455,9 @@ class PdfPage implements IPdfWrapper { if (angle.value!.toInt() < 0) { angle.value = 360 + angle.value!.toInt(); } - final PdfPageRotateAngle rotateAngle = - _getRotationFromAngle(angle.value! ~/ 90); + final PdfPageRotateAngle rotateAngle = _getRotationFromAngle( + angle.value! ~/ 90, + ); return rotateAngle; } @@ -481,8 +501,11 @@ class PdfPageHelper { } /// internal method - static PdfPage fromDictionary(PdfDocument document, PdfCrossTable crossTable, - PdfDictionary dictionary) { + static PdfPage fromDictionary( + PdfDocument document, + PdfCrossTable crossTable, + PdfDictionary dictionary, + ) { return PdfPage._fromDictionary(document, crossTable, dictionary); } @@ -535,9 +558,9 @@ class PdfPageHelper { /// internal method Offset get origin { if (section != null) { - return PdfPageSettingsHelper.getHelper(section!.pageSettings) - .origin - .offset; + return PdfPageSettingsHelper.getHelper( + section!.pageSettings, + ).origin.offset; } else { return Offset.zero; } @@ -551,8 +574,8 @@ class PdfPageHelper { if (section != null) { if (PdfSectionHelper.getHelper(section!).parent != null) { return PdfSectionCollectionHelper.getHelper( - PdfSectionHelper.getHelper(section!).parent!) - .document; + PdfSectionHelper.getHelper(section!).parent!, + ).document; } else if (PdfSectionHelper.getHelper(section!).document != null) { return PdfSectionHelper.getHelper(section!).document; } else { @@ -572,12 +595,15 @@ class PdfPageHelper { Rect get cropBox { if (_cBox.isEmpty) { final IPdfPrimitive? cBox = dictionary!.getValue( - PdfDictionaryProperties.cropBox, PdfDictionaryProperties.parent); + PdfDictionaryProperties.cropBox, + PdfDictionaryProperties.parent, + ); if (cBox != null && cBox is PdfArray) { final double width = (cBox[2]! as PdfNumber).value!.toDouble(); - final double height = (cBox[3]! as PdfNumber).value != 0 - ? (cBox[3]! as PdfNumber).value!.toDouble() - : (cBox[1]! as PdfNumber).value!.toDouble(); + final double height = + (cBox[3]! as PdfNumber).value != 0 + ? (cBox[3]! as PdfNumber).value!.toDouble() + : (cBox[1]! as PdfNumber).value!.toDouble(); final double x = (cBox[0]! as PdfNumber).value!.toDouble(); final double y = (cBox[1]! as PdfNumber).value!.toDouble(); _cBox = _calculateBounds(x, y, width, height); @@ -590,12 +616,15 @@ class PdfPageHelper { Rect get mediaBox { if (_mBox.isEmpty) { final IPdfPrimitive? mBox = dictionary!.getValue( - PdfDictionaryProperties.mediaBox, PdfDictionaryProperties.parent); + PdfDictionaryProperties.mediaBox, + PdfDictionaryProperties.parent, + ); if (mBox != null && mBox is PdfArray) { final double width = (mBox[2]! as PdfNumber).value!.toDouble(); - final double height = (mBox[3]! as PdfNumber).value != 0 - ? (mBox[3]! as PdfNumber).value!.toDouble() - : (mBox[1]! as PdfNumber).value!.toDouble(); + final double height = + (mBox[3]! as PdfNumber).value != 0 + ? (mBox[3]! as PdfNumber).value!.toDouble() + : (mBox[1]! as PdfNumber).value!.toDouble(); final double x = (mBox[0]! as PdfNumber).value!.toDouble(); final double y = (mBox[1]! as PdfNumber).value!.toDouble(); _mBox = _calculateBounds(x, y, width, height); @@ -683,15 +712,17 @@ class PdfPageHelper { dictionary![PdfDictionaryProperties.resources] = obj; _resources = PdfResources(obj); final PdfDictionary xobjects = PdfDictionary(); - if (_resources! - .containsKey(PdfDictionaryProperties.xObject)) { + if (_resources!.containsKey( + PdfDictionaryProperties.xObject, + )) { final PdfDictionary? xObject = _resources![PdfDictionaryProperties.xObject] as PdfDictionary?; if (xObject != null) { final IPdfPrimitive? content = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.contents]); + dictionary![PdfDictionaryProperties.contents], + ); if (content != null) { if (content is PdfArray) { for (int i = 0; i < content.count; i++) { @@ -705,7 +736,9 @@ class PdfPageHelper { } } _resources!.setProperty( - PdfDictionaryProperties.xObject, xobjects); + PdfDictionaryProperties.xObject, + xobjects, + ); setResources(_resources); } } @@ -718,8 +751,9 @@ class PdfPageHelper { _resources!.items!.isEmpty) { for (final PdfName? key in _resources!.items!.keys) { if (pageSourceDictionary.items!.containsKey(key)) { - if (pageSourceDictionary.items! - .containsValue(_resources![key])) { + if (pageSourceDictionary.items!.containsValue( + _resources![key], + )) { isValueEqual = true; } } else { @@ -745,8 +779,11 @@ class PdfPageHelper { _resources = PdfResources(dic); dictionary![PdfDictionaryProperties.resources] = _resources; if (dictionary!.containsKey(PdfDictionaryProperties.parent)) { - final PdfDictionary? parentDic = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.parent]) as PdfDictionary?; + final PdfDictionary? parentDic = + PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.parent], + ) + as PdfDictionary?; if (parentDic != null && parentDic.containsKey(PdfDictionaryProperties.resources)) { final IPdfPrimitive? resource = @@ -780,8 +817,9 @@ class PdfPageHelper { void createAnnotations(List widgetReferences) { IPdfPrimitive? annots; if (dictionary!.containsKey(PdfDictionaryProperties.annots)) { - annots = - crossTable!.getObject(dictionary![PdfDictionaryProperties.annots]); + annots = crossTable!.getObject( + dictionary![PdfDictionaryProperties.annots], + ); if (annots != null && annots is PdfArray) { for (int count = 0; count < annots.count; ++count) { PdfDictionary? annotDictionary; @@ -797,14 +835,15 @@ class PdfPageHelper { if (document != null && PdfDocumentHelper.getHelper(document!).crossTable.encryptor != null && - PdfDocumentHelper.getHelper(document!) - .crossTable - .encryptor! - .encryptAttachmentOnly!) { + PdfDocumentHelper.getHelper( + document!, + ).crossTable.encryptor!.encryptAttachmentOnly!) { if (annotDictionary != null && annotDictionary.containsKey(PdfDictionaryProperties.subtype)) { - final IPdfPrimitive? primitive = annotDictionary - .items![PdfName(PdfDictionaryProperties.subtype)]; + final IPdfPrimitive? primitive = + annotDictionary.items![PdfName( + PdfDictionaryProperties.subtype, + )]; if (primitive is PdfName && primitive.name == 'FileAttachment' && annotDictionary.containsKey(PdfDictionaryProperties.fs)) { @@ -814,8 +853,9 @@ class PdfPageHelper { final IPdfPrimitive? streamDictionary = file.object; if (streamDictionary != null && streamDictionary is PdfDictionary && - streamDictionary - .containsKey(PdfDictionaryProperties.ef)) { + streamDictionary.containsKey( + PdfDictionaryProperties.ef, + )) { PdfDictionary? attachmentStream; IPdfPrimitive? holder = streamDictionary[PdfDictionaryProperties.ef]; @@ -828,38 +868,44 @@ class PdfPageHelper { attachmentStream = holder; } if (attachmentStream != null && - attachmentStream - .containsKey(PdfDictionaryProperties.f)) { + attachmentStream.containsKey( + PdfDictionaryProperties.f, + )) { holder = attachmentStream[PdfDictionaryProperties.f]; if (holder != null && holder is PdfReferenceHolder) { final PdfReference? reference = holder.reference; holder = holder.object; if (holder != null && holder is PdfStream) { final PdfStream encryptedObj = holder; - if (PdfDocumentHelper.getHelper(document!) - .isLoadedDocument) { + if (PdfDocumentHelper.getHelper( + document!, + ).isLoadedDocument) { if (document!.onPdfPassword != null && - PdfDocumentHelper.getHelper(document!) - .password == + PdfDocumentHelper.getHelper( + document!, + ).password == '') { final PdfPasswordArgs args = PdfPasswordArgsHelper.load(); - PdfDocumentHelper.getHelper(document!) - .setUserPassword(args); + PdfDocumentHelper.getHelper( + document!, + ).setUserPassword(args); PdfDocumentHelper.getHelper(document!).password = args.attachmentOpenPassword; } - PdfDocumentHelper.getHelper(document!) - .checkEncryption( - PdfDocumentHelper.getHelper(document!) - .crossTable - .encryptor! - .encryptAttachmentOnly); + PdfDocumentHelper.getHelper( + document!, + ).checkEncryption( + PdfDocumentHelper.getHelper( + document!, + ).crossTable.encryptor!.encryptAttachmentOnly, + ); encryptedObj.decrypt( - PdfDocumentHelper.getHelper(document!) - .crossTable - .encryptor!, - reference!.objNum); + PdfDocumentHelper.getHelper( + document!, + ).crossTable.encryptor!, + reference!.objNum, + ); } } } @@ -871,45 +917,53 @@ class PdfPageHelper { } if (annotDictionary != null && annotDictionary.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName? name = annotDictionary - .items![PdfName(PdfDictionaryProperties.subtype)] as PdfName?; + final PdfName? name = + annotDictionary.items![PdfName(PdfDictionaryProperties.subtype)] + as PdfName?; if (name != null && name.name.toString() != 'Widget') { if (!terminalAnnotation.contains(annotDictionary)) { terminalAnnotation.add(annotDictionary); } } else if (name != null && name.name.toString() == 'Widget') { if (annotDictionary.containsKey(PdfDictionaryProperties.parent)) { - final PdfDictionary? annotParentDictionary = (annotDictionary - .items![PdfName(PdfDictionaryProperties.parent)]! - as PdfReferenceHolder) - .object as PdfDictionary?; + final PdfDictionary? annotParentDictionary = + (annotDictionary.items![PdfName( + PdfDictionaryProperties.parent, + )]! + as PdfReferenceHolder) + .object + as PdfDictionary?; if (annotParentDictionary != null) { - if (!annotParentDictionary - .containsKey(PdfDictionaryProperties.fields)) { + if (!annotParentDictionary.containsKey( + PdfDictionaryProperties.fields, + )) { if (annotReference != null && annotReference.reference != null && - !widgetReferences - .contains(annotReference.reference!.objNum)) { - if (!PdfFormHelper.getHelper(document!.form) - .terminalFields - .contains(annotParentDictionary)) { - PdfFormHelper.getHelper(document!.form) - .terminalFields - .add(annotParentDictionary); + !widgetReferences.contains( + annotReference.reference!.objNum, + )) { + if (!PdfFormHelper.getHelper( + document!.form, + ).terminalFields.contains(annotParentDictionary)) { + PdfFormHelper.getHelper( + document!.form, + ).terminalFields.add(annotParentDictionary); } - } else if (annotParentDictionary - .containsKey(PdfDictionaryProperties.kids) && + } else if (annotParentDictionary.containsKey( + PdfDictionaryProperties.kids, + ) && annotParentDictionary.count == 1) { annotDictionary.remove(PdfDictionaryProperties.parent); } - } else if (!annotParentDictionary - .containsKey(PdfDictionaryProperties.kids)) { + } else if (!annotParentDictionary.containsKey( + PdfDictionaryProperties.kids, + )) { annotDictionary.remove(PdfDictionaryProperties.parent); } } - } else if (!PdfFormHelper.getHelper(document!.form) - .terminalFields - .contains(annotDictionary)) { + } else if (!PdfFormHelper.getHelper( + document!.form, + ).terminalFields.contains(annotDictionary)) { Map>? widgetDictionary = PdfFormHelper.getHelper(document!.form).widgetDictionary; if (widgetDictionary == null) { @@ -919,21 +973,22 @@ class PdfPageHelper { PdfFormHelper.getHelper(document!.form).widgetDictionary; } if (annotDictionary.containsKey(PdfDictionaryProperties.t)) { - final String? fieldName = (annotDictionary - .items![PdfName(PdfDictionaryProperties.t)]! - as PdfString) - .value; + final String? fieldName = + (annotDictionary.items![PdfName( + PdfDictionaryProperties.t, + )]! + as PdfString) + .value; if (widgetDictionary!.containsKey(fieldName)) { final List dict = widgetDictionary[fieldName]!; dict.add(annotDictionary); } else { if (!PdfFormFieldCollectionHelper.getHelper( - document!.form.fields) - .addedFieldNames - .contains(fieldName)) { + document!.form.fields, + ).addedFieldNames.contains(fieldName)) { widgetDictionary[fieldName] = [ - annotDictionary + annotDictionary, ]; } } @@ -954,9 +1009,12 @@ class PdfPageHelper { final PdfFieldHelper helper = PdfFieldHelper.getHelper(field); if (helper.isLoadedField) { final IPdfPrimitive widget = helper.getWidgetAnnotation( - helper.dictionary!, helper.crossTable); - final PdfReference widgetReference = - crossTable!.getReference(widget); + helper.dictionary!, + helper.crossTable, + ); + final PdfReference widgetReference = crossTable!.getReference( + widget, + ); if (annotReference.reference!.objNum == widgetReference.objNum && annotReference.reference!.genNum == @@ -967,8 +1025,9 @@ class PdfPageHelper { } } if (annotDictionary != null && annotReference.reference != null) { - if (!widgetReferences - .contains(annotReference.reference!.objNum) && + if (!widgetReferences.contains( + annotReference.reference!.objNum, + ) && !skip) { if (!terminalAnnotation.contains(annotDictionary)) { terminalAnnotation.add(annotDictionary); @@ -987,12 +1046,22 @@ class PdfPageHelper { PdfTemplate _getContent() { final List combinedData = - PdfPageLayerCollectionHelper.getHelper(base.layers) - .combineContent(false)!; - final PdfDictionary? resources = PdfCrossTable.dereference( - dictionary![PdfDictionaryProperties.resources]) as PdfDictionary?; + PdfPageLayerCollectionHelper.getHelper( + base.layers, + ).combineContent(false)!; + final PdfDictionary? resources = + PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.resources], + ) + as PdfDictionary?; final PdfTemplate template = PdfTemplateHelper.internal( - origin, base.size, combinedData, resources!, isLoadedPage, this); + origin, + base.size, + combinedData, + resources!, + isLoadedPage, + this, + ); return template; } @@ -1004,16 +1073,20 @@ class PdfPageHelper { final PdfField field = collection[i]; final PdfFieldHelper helper = PdfFieldHelper.getHelper(field); if (helper.isLoadedField) { - final IPdfPrimitive widget = - helper.getWidgetAnnotation(helper.dictionary!, helper.crossTable); + final IPdfPrimitive widget = helper.getWidgetAnnotation( + helper.dictionary!, + helper.crossTable, + ); final Map widgetReference = - PdfDocumentHelper.getHelper(document!) - .objects - .getReference(widget, false); - widgetReferences.add(((widgetReference['isNew'] as bool) - ? crossTable!.getReference(widget).objNum - : (widgetReference['reference'] as PdfReference).objNum)! - .toSigned(64)); + PdfDocumentHelper.getHelper( + document!, + ).objects.getReference(widget, false); + widgetReferences.add( + ((widgetReference['isNew'] as bool) + ? crossTable!.getReference(widget).objNum + : (widgetReference['reference'] as PdfReference).objNum)! + .toSigned(64), + ); widgetReference.clear(); } } @@ -1023,7 +1096,9 @@ class PdfPageHelper { /// internal method PdfArray? obtainAnnotations() { final IPdfPrimitive? obj = dictionary!.getValue( - PdfDictionaryProperties.annots, PdfDictionaryProperties.parent); + PdfDictionaryProperties.annots, + PdfDictionaryProperties.parent, + ); return (obj != null && obj is PdfReferenceHolder ? obj.object : obj) as PdfArray?; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_collection.dart index 27d88e5f0..88023c38f 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_collection.dart @@ -37,7 +37,9 @@ class PdfPageCollection { } PdfPageCollection._fromCrossTable( - PdfDocument document, PdfCrossTable crossTable) { + PdfDocument document, + PdfCrossTable crossTable, + ) { _helper = PdfPageCollectionHelper(this); _helper.document = document; _helper._crossTable = crossTable; @@ -65,8 +67,10 @@ class PdfPageCollection { int get count { if (PdfDocumentHelper.getHelper(_helper.document!).isLoadedDocument) { int tempCount = 0; - final IPdfPrimitive? obj = PdfDocumentHelper.getHelper(_helper.document!) - .catalog[PdfDictionaryProperties.pages]; + final IPdfPrimitive? obj = + PdfDocumentHelper.getHelper( + _helper.document!, + ).catalog[PdfDictionaryProperties.pages]; final PdfDictionary? node = PdfCrossTable.dereference(obj) as PdfDictionary?; if (node != null) { @@ -137,18 +141,21 @@ class PdfPageCollection { /// [margins] - The page margin. /// [rotation] - The PDF page rotation angle. /// [orientation] - The PDF page orientation. - PdfPage insert(int index, - [Size? size, - PdfMargins? margins, - PdfPageRotateAngle? rotation, - PdfPageOrientation? orientation]) { + PdfPage insert( + int index, [ + Size? size, + PdfMargins? margins, + PdfPageRotateAngle? rotation, + PdfPageOrientation? orientation, + ]) { if (size == null || size.isEmpty) { size = PdfPageSize.a4; } rotation ??= PdfPageRotateAngle.rotateAngle0; - orientation ??= (size.width > size.height) - ? PdfPageOrientation.landscape - : PdfPageOrientation.portrait; + orientation ??= + (size.width > size.height) + ? PdfPageOrientation.landscape + : PdfPageOrientation.portrait; final PdfPage page = PdfPage(); final PdfPageSettings settings = PdfPageSettings(size, orientation); if (margins == null) { @@ -162,8 +169,11 @@ class PdfPageCollection { PdfSectionHelper.getHelper(sec).add(page); PdfDictionary dic = IPdfWrapper.getElement(sec)! as PdfDictionary; int? localIndex = 0; - final Map result = - _getValidParent(index, localIndex, false); + final Map result = _getValidParent( + index, + localIndex, + false, + ); final PdfDictionary parent = result['node'] as PdfDictionary; localIndex = result['index'] as int?; if (parent.containsKey(PdfDictionaryProperties.rotate)) { @@ -172,9 +182,8 @@ class PdfPageCollection { parent[PdfDictionaryProperties.rotate]! as PdfNumber; if (parentRotation.value!.toInt() != rotationValue && (!dic.containsKey(PdfDictionaryProperties.rotate))) { - PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.rotate] = - PdfNumber(rotationValue); + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .rotate] = PdfNumber(rotationValue); } } dic[PdfDictionaryProperties.parent] = PdfReferenceHolder(parent); @@ -185,8 +194,9 @@ class PdfPageCollection { _helper._pageCache![dic] = page; page.graphics.colorSpace = _helper.document!.colorSpace; PdfPageLayerHelper.getHelper( - PdfGraphicsHelper.getHelper(page.graphics).layer!) - .colorSpace = _helper.document!.colorSpace; + PdfGraphicsHelper.getHelper(page.graphics).layer!, + ).colorSpace = + _helper.document!.colorSpace; return page; } @@ -227,8 +237,9 @@ class PdfPageCollection { //Implementation int _getNodeCount(PdfDictionary node) { - final PdfNumber? number = _helper._crossTable! - .getObject(node[PdfDictionaryProperties.count]) as PdfNumber?; + final PdfNumber? number = + _helper._crossTable!.getObject(node[PdfDictionaryProperties.count]) + as PdfNumber?; return (number == null) ? 0 : number.value!.toInt(); } @@ -264,8 +275,9 @@ class PdfPageCollection { return _helper.getPage(node); } else { if (_helper._section != null) { - return PdfSectionHelper.getHelper(_helper._section!) - .getPageByIndex(index); + return PdfSectionHelper.getHelper( + _helper._section!, + ).getPageByIndex(index); } else { if (index < 0 || index >= count) { throw ArgumentError.value('index', 'out of range'); @@ -279,8 +291,9 @@ class PdfPageCollection { sectionCount = PdfSectionHelper.getHelper(section).count; pageIndex = index - sectionStartIndex; if (index >= sectionStartIndex && pageIndex < sectionCount) { - page = - PdfSectionHelper.getHelper(section).getPageByIndex(pageIndex); + page = PdfSectionHelper.getHelper( + section, + ).getPageByIndex(pageIndex); break; } sectionStartIndex += sectionCount; @@ -294,18 +307,24 @@ class PdfPageCollection { while (parent != null) { final int count = _getNodeCount(parent) + 1; parent[PdfDictionaryProperties.count] = PdfNumber(count); - parent = PdfCrossTable.dereference(parent[PdfDictionaryProperties.parent]) - as PdfDictionary?; + parent = + PdfCrossTable.dereference(parent[PdfDictionaryProperties.parent]) + as PdfDictionary?; } } Map _getValidParent( - int index, int? localIndex, bool zeroValid) { + int index, + int? localIndex, + bool zeroValid, + ) { if (index < 0 && index > count) { throw ArgumentError.value(index, 'page index is not within range'); } - final IPdfPrimitive? obj = PdfDocumentHelper.getHelper(_helper.document!) - .catalog[PdfDictionaryProperties.pages]; + final IPdfPrimitive? obj = + PdfDocumentHelper.getHelper( + _helper.document!, + ).catalog[PdfDictionaryProperties.pages]; PdfDictionary node = _helper._crossTable!.getObject(obj)! as PdfDictionary; int lowIndex = 0; localIndex = _getNodeCount(node); @@ -384,8 +403,10 @@ class PdfPageCollection { if (index < 0 && index > count) { throw ArgumentError.value(index, 'page index is not within range'); } - _pageCatalog ??= PdfDocumentHelper.getHelper(_helper.document!) - .catalog[PdfDictionaryProperties.pages]; + _pageCatalog ??= + PdfDocumentHelper.getHelper( + _helper.document!, + ).catalog[PdfDictionaryProperties.pages]; bool isNodeChanged = false; PdfDictionary? node; if (_nodeDictionary == null) { @@ -448,21 +469,42 @@ class PdfPageCollection { int? tempLocalIndex = 0; if (kids!.count == count) { - Map returnValue = _getParentNode(kidStartIndex, kids, - 0, index, tempNode, tempLocalIndex, isParentNodeFetched); + Map returnValue = _getParentNode( + kidStartIndex, + kids, + 0, + index, + tempNode, + tempLocalIndex, + isParentNodeFetched, + ); tempNode = returnValue['tempNode'] as PdfDictionary?; tempLocalIndex = returnValue['tempLocalIndex'] as int?; isParentNodeFetched = returnValue['isParentNodeFetched'] as bool?; if (!isParentNodeFetched!) { returnValue = _getParentNode( - 0, kids, 0, index, tempNode, tempLocalIndex, isParentNodeFetched); + 0, + kids, + 0, + index, + tempNode, + tempLocalIndex, + isParentNodeFetched, + ); tempNode = returnValue['tempNode'] as PdfDictionary?; tempLocalIndex = returnValue['tempLocalIndex'] as int?; isParentNodeFetched = returnValue['isParentNodeFetched'] as bool?; } } else { final Map returnValue = _getParentNode( - 0, kids, 0, index, tempNode, tempLocalIndex, isParentNodeFetched); + 0, + kids, + 0, + index, + tempNode, + tempLocalIndex, + isParentNodeFetched, + ); tempNode = returnValue['tempNode'] as PdfDictionary?; tempLocalIndex = returnValue['tempLocalIndex'] as int?; isParentNodeFetched = returnValue['isParentNodeFetched'] as bool?; @@ -488,13 +530,14 @@ class PdfPageCollection { } Map _getParentNode( - int kidStartIndex, - PdfArray kids, - int lowIndex, - int pageIndex, - PdfDictionary? node, - int? localIndex, - bool? isParentFetched) { + int kidStartIndex, + PdfArray kids, + int lowIndex, + int pageIndex, + PdfDictionary? node, + int? localIndex, + bool? isParentFetched, + ) { isParentFetched = false; node = null; localIndex = -1; @@ -536,7 +579,7 @@ class PdfPageCollection { return { 'tempNode': node, 'tempLocalIndex': localIndex, - 'isParentNodeFetched': isParentFetched + 'isParentNodeFetched': isParentFetched, }; } @@ -547,12 +590,14 @@ class PdfPageCollection { int _countPages() { final PdfSectionCollection sectionCollection = _helper.document!.sections!; int count = 0; - for (int i = 0; - i < - PdfSectionCollectionHelper.getHelper(sectionCollection) - .sections - .length; - i++) { + for ( + int i = 0; + i < + PdfSectionCollectionHelper.getHelper( + sectionCollection, + ).sections.length; + i++ + ) { final PdfSection section = sectionCollection[i]; count += PdfSectionHelper.getHelper(section).count; } @@ -563,8 +608,9 @@ class PdfPageCollection { if (PdfDocumentHelper.getHelper(_helper.document!).isLoadedDocument && index > -1) { final Map? pageToBookmarkDic = - PdfDocumentHelper.getHelper(_helper.document!) - .createBookmarkDestinationDictionary(); + PdfDocumentHelper.getHelper( + _helper.document!, + ).createBookmarkDestinationDictionary(); if (pageToBookmarkDic != null) { List? bookmarks; if (pageToBookmarkDic.containsKey(page)) { @@ -574,19 +620,19 @@ class PdfPageCollection { for (int i = 0; i < bookmarks.length; i++) { if (bookmarks[i] is PdfBookmarkBase) { final PdfBookmarkBase current = bookmarks[i] as PdfBookmarkBase; - if (PdfBookmarkBaseHelper.getHelper(current) - .dictionary! - .containsKey(PdfDictionaryProperties.a)) { - PdfBookmarkBaseHelper.getHelper(current) - .dictionary! - .remove(PdfDictionaryProperties.a); + if (PdfBookmarkBaseHelper.getHelper( + current, + ).dictionary!.containsKey(PdfDictionaryProperties.a)) { + PdfBookmarkBaseHelper.getHelper( + current, + ).dictionary!.remove(PdfDictionaryProperties.a); } - if (PdfBookmarkBaseHelper.getHelper(current) - .dictionary! - .containsKey(PdfDictionaryProperties.dest)) { - PdfBookmarkBaseHelper.getHelper(current) - .dictionary! - .remove(PdfDictionaryProperties.dest); + if (PdfBookmarkBaseHelper.getHelper( + current, + ).dictionary!.containsKey(PdfDictionaryProperties.dest)) { + PdfBookmarkBaseHelper.getHelper( + current, + ).dictionary!.remove(PdfDictionaryProperties.dest); } } } @@ -694,8 +740,8 @@ class PdfPageCollection { void _removeFormFields(PdfReferenceHolder pageHolder) { if (PdfDocumentHelper.getHelper(_helper.document!).isLoadedDocument) { PdfFormFieldCollectionHelper.getHelper( - PdfPageCollectionHelper.getHelper(this).document!.form.fields) - .removeContainingField(pageHolder); + PdfPageCollectionHelper.getHelper(this).document!.form.fields, + ).removeContainingField(pageHolder); } } @@ -704,8 +750,9 @@ class PdfPageCollection { int count = _getNodeCount(parent) - 1; if (count == 0) { final PdfDictionary node = parent; - final IPdfPrimitive? result = - PdfCrossTable.dereference(parent[PdfDictionaryProperties.parent]); + final IPdfPrimitive? result = PdfCrossTable.dereference( + parent[PdfDictionaryProperties.parent], + ); if (result != null && result is PdfDictionary) { final IPdfPrimitive? kids = result[PdfDictionaryProperties.kids]; if (kids != null && kids is PdfArray) { @@ -715,8 +762,9 @@ class PdfPageCollection { } count = _getNodeCount(parent) - 1; parent[PdfDictionaryProperties.count] = PdfNumber(count); - final IPdfPrimitive? primitive = - PdfCrossTable.dereference(parent[PdfDictionaryProperties.parent]); + final IPdfPrimitive? primitive = PdfCrossTable.dereference( + parent[PdfDictionaryProperties.parent], + ); parent = (primitive != null && primitive is PdfDictionary) ? primitive : null; } @@ -743,7 +791,9 @@ class PdfPageCollectionHelper { /// internal method static PdfPageCollection fromCrossTable( - PdfDocument document, PdfCrossTable crossTable) { + PdfDocument document, + PdfCrossTable crossTable, + ) { return PdfPageCollection._fromCrossTable(document, crossTable); } @@ -775,16 +825,15 @@ class PdfPageCollectionHelper { PdfSection _getLastSection() { final PdfSectionCollection sectionCollection = document!.sections!; - if (PdfSectionCollectionHelper.getHelper(sectionCollection) - .sections - .isEmpty) { + if (PdfSectionCollectionHelper.getHelper( + sectionCollection, + ).sections.isEmpty) { sectionCollection.add(); } - return sectionCollection[ - PdfSectionCollectionHelper.getHelper(sectionCollection) - .sections - .length - - 1]; + return sectionCollection[PdfSectionCollectionHelper.getHelper( + sectionCollection, + ).sections.length - + 1]; } bool _checkPageSettings(PdfPageSettings sectionSettings) { @@ -804,8 +853,9 @@ class PdfPageCollectionHelper { } else { bool value = false; for (int i = 0; i < document!.sections!.count; i++) { - value |= PdfPageCollectionHelper.getHelper(document!.sections![i].pages) - .contains(page); + value |= PdfPageCollectionHelper.getHelper( + document!.sections![i].pages, + ).contains(page); } return value; } @@ -824,10 +874,12 @@ class PdfPageCollectionHelper { PdfSectionHelper.getHelper(_section!).remove(page); } else { for (int i = 0; i < document!.sections!.count; i++) { - if (PdfPageCollectionHelper.getHelper(document!.sections![i].pages) - .contains(page)) { - PdfPageCollectionHelper.getHelper(document!.sections![i].pages) - .remove(page); + if (PdfPageCollectionHelper.getHelper( + document!.sections![i].pages, + ).contains(page)) { + PdfPageCollectionHelper.getHelper( + document!.sections![i].pages, + ).remove(page); break; } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer.dart index f768a3f0d..6595a777a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer.dart @@ -34,8 +34,10 @@ class PdfPageLayer implements IPdfWrapper { _initialize(pdfPage, true); } - PdfPageLayer._fromClipPageTemplate(PdfPage pdfPage, - [bool? clipPageTemplates]) { + PdfPageLayer._fromClipPageTemplate( + PdfPage pdfPage, [ + bool? clipPageTemplates, + ]) { _helper = PdfPageLayerHelper(this); _initialize(pdfPage, clipPageTemplates); } @@ -113,19 +115,21 @@ class PdfPageLayer implements IPdfWrapper { final Function resources = PdfPageHelper.getHelper(page!).getResources; bool isPageHasMediaBox = false; bool isInvalidSize = false; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfName(PdfDictionaryProperties.mediaBox))) { + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfName(PdfDictionaryProperties.mediaBox))) { isPageHasMediaBox = true; } double llx = 0; double lly = 0; double urx = 0; double ury = 0; - final PdfArray? mediaBox = PdfPageHelper.getHelper(page) - .dictionary! - .getValue(PdfDictionaryProperties.mediaBox, - PdfDictionaryProperties.parent) as PdfArray?; + final PdfArray? mediaBox = + PdfPageHelper.getHelper(page).dictionary!.getValue( + PdfDictionaryProperties.mediaBox, + PdfDictionaryProperties.parent, + ) + as PdfArray?; final PdfReferenceHolder referenceHolder = PdfReferenceHolder(this); if (mediaBox != null) { // Lower Left X co-ordinate Value. @@ -138,12 +142,15 @@ class PdfPageLayer implements IPdfWrapper { ury = (mediaBox[3]! as PdfNumber).value!.toDouble(); } PdfArray? cropBox; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.cropBox)) { - cropBox = PdfPageHelper.getHelper(page).dictionary!.getValue( - PdfDictionaryProperties.cropBox, PdfDictionaryProperties.parent) - as PdfArray?; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.cropBox)) { + cropBox = + PdfPageHelper.getHelper(page).dictionary!.getValue( + PdfDictionaryProperties.cropBox, + PdfDictionaryProperties.parent, + ) + as PdfArray?; final double cropX = (cropBox![0]! as PdfNumber).value!.toDouble(); final double cropY = (cropBox[1]! as PdfNumber).value!.toDouble(); final double cropRX = (cropBox[2]! as PdfNumber).value!.toDouble(); @@ -151,28 +158,40 @@ class PdfPageLayer implements IPdfWrapper { if ((cropX < 0 || cropY < 0 || cropRX < 0 || cropRY < 0) && (cropY.abs().floor() == page.size.height.abs().floor()) && (cropX.abs().floor()) == page.size.width.abs().floor()) { - final Size pageSize = Size([cropX, cropRX].reduce(max), - [cropY, cropRY].reduce(max)); - _helper.graphics = - PdfGraphicsHelper.load(pageSize, resources, _helper._content!); - if (!PdfPageHelper.getHelper(page) - .contents - .contains(referenceHolder) && + final Size pageSize = Size( + [cropX, cropRX].reduce(max), + [cropY, cropRY].reduce(max), + ); + _helper.graphics = PdfGraphicsHelper.load( + pageSize, + resources, + _helper._content!, + ); + if (!PdfPageHelper.getHelper( + page, + ).contents.contains(referenceHolder) && !PdfPageHelper.getHelper(page).isDefaultGraphics && !_isContainsPageContent( - PdfPageHelper.getHelper(page).contents, referenceHolder)) { + PdfPageHelper.getHelper(page).contents, + referenceHolder, + )) { PdfPageHelper.getHelper(page).contents.add(referenceHolder); } } else { - _helper.graphics = - PdfGraphicsHelper.load(page.size, resources, _helper._content!); + _helper.graphics = PdfGraphicsHelper.load( + page.size, + resources, + _helper._content!, + ); PdfGraphicsHelper.getHelper(_helper.graphics!).cropBox = cropBox; - if (!PdfPageHelper.getHelper(page) - .contents - .contains(referenceHolder) && + if (!PdfPageHelper.getHelper( + page, + ).contents.contains(referenceHolder) && !PdfPageHelper.getHelper(page).isDefaultGraphics && !_isContainsPageContent( - PdfPageHelper.getHelper(page).contents, referenceHolder)) { + PdfPageHelper.getHelper(page).contents, + referenceHolder, + )) { PdfPageHelper.getHelper(page).contents.add(referenceHolder); } } @@ -180,7 +199,9 @@ class PdfPageLayer implements IPdfWrapper { (lly.abs().floor() == page.size.height.abs().floor()) && (urx.abs().floor() == page.size.width.abs().floor())) { Size pageSize = Size( - [llx, urx].reduce(max), [lly, ury].reduce(max)); + [llx, urx].reduce(max), + [lly, ury].reduce(max), + ); if (pageSize.width <= 0 || pageSize.height <= 0) { isInvalidSize = true; if (llx < 0) { @@ -194,25 +215,37 @@ class PdfPageLayer implements IPdfWrapper { ury = -ury; } pageSize = Size( - [llx, urx].reduce(max), [lly, ury].reduce(max)); - _helper.graphics = - PdfGraphicsHelper.load(pageSize, resources, _helper._content!); - if (!PdfPageHelper.getHelper(page) - .contents - .contains(referenceHolder) && + [llx, urx].reduce(max), + [lly, ury].reduce(max), + ); + _helper.graphics = PdfGraphicsHelper.load( + pageSize, + resources, + _helper._content!, + ); + if (!PdfPageHelper.getHelper( + page, + ).contents.contains(referenceHolder) && !PdfPageHelper.getHelper(page).isDefaultGraphics && !_isContainsPageContent( - PdfPageHelper.getHelper(page).contents, referenceHolder)) { + PdfPageHelper.getHelper(page).contents, + referenceHolder, + )) { PdfPageHelper.getHelper(page).contents.add(referenceHolder); } } } else { - _helper.graphics = - PdfGraphicsHelper.load(page.size, resources, _helper._content!); + _helper.graphics = PdfGraphicsHelper.load( + page.size, + resources, + _helper._content!, + ); if (!PdfPageHelper.getHelper(page).contents.contains(referenceHolder) && !PdfPageHelper.getHelper(page).isDefaultGraphics && !_isContainsPageContent( - PdfPageHelper.getHelper(page).contents, referenceHolder)) { + PdfPageHelper.getHelper(page).contents, + referenceHolder, + )) { PdfPageHelper.getHelper(page).contents.add(referenceHolder); } } @@ -223,69 +256,76 @@ class PdfPageLayer implements IPdfWrapper { } if (!PdfPageHelper.getHelper(page).isLoadedPage) { final PdfSectionCollection? sectionCollection = - PdfSectionHelper.getHelper(PdfPageHelper.getHelper(page).section!) - .parent; + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).parent; if (sectionCollection != null) { _helper.graphics!.colorSpace = - PdfSectionCollectionHelper.getHelper(sectionCollection) - .document! - .colorSpace; + PdfSectionCollectionHelper.getHelper( + sectionCollection, + ).document!.colorSpace; _helper.colorSpace = - PdfSectionCollectionHelper.getHelper(sectionCollection) - .document! - .colorSpace; + PdfSectionCollectionHelper.getHelper( + sectionCollection, + ).document!.colorSpace; } } _helper._content!.beginSave = _beginSaveContent; } _graphicsState = _helper.graphics!.save(); if (name != null && name!.isNotEmpty) { - PdfGraphicsHelper.getHelper(_helper.graphics!) - .streamWriter! - .write('/OC /${_helper.layerID!} BDC\n'); + PdfGraphicsHelper.getHelper( + _helper.graphics!, + ).streamWriter!.write('/OC /${_helper.layerID!} BDC\n'); _isEndState = true; } PdfGraphicsHelper.getHelper(_helper.graphics!).initializeCoordinates(); if (PdfGraphicsHelper.getHelper(_helper.graphics!).hasTransparencyBrush) { - PdfGraphicsHelper.getHelper(_helper.graphics!) - .setTransparencyGroup(page!); + PdfGraphicsHelper.getHelper( + _helper.graphics!, + ).setTransparencyGroup(page!); } if (page != null && (!PdfPageHelper.getHelper(page).isLoadedPage) && (page.rotation != PdfPageRotateAngle.rotateAngle0 || - PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.rotate))) { + PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.rotate))) { PdfArray? cropBox; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.cropBox)) { - cropBox = PdfPageHelper.getHelper(page).dictionary!.getValue( - PdfDictionaryProperties.cropBox, PdfDictionaryProperties.parent) - as PdfArray?; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.cropBox)) { + cropBox = + PdfPageHelper.getHelper(page).dictionary!.getValue( + PdfDictionaryProperties.cropBox, + PdfDictionaryProperties.parent, + ) + as PdfArray?; } _updatePageRotation(page, _helper.graphics, cropBox); } if (page != null && !PdfPageHelper.getHelper(page).isLoadedPage) { - final PdfRectangle clipRect = - PdfSectionHelper.getHelper(PdfPageHelper.getHelper(page).section!) - .getActualBounds(page, true); + final PdfRectangle clipRect = PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).getActualBounds(page, true); if (_clipPageTemplates!) { if (PdfPageHelper.getHelper(page).origin.dx >= 0 && PdfPageHelper.getHelper(page).origin.dy >= 0) { - PdfGraphicsHelper.getHelper(_helper.graphics!) - .clipTranslateMarginsWithBounds(clipRect); + PdfGraphicsHelper.getHelper( + _helper.graphics!, + ).clipTranslateMarginsWithBounds(clipRect); } } else { final PdfMargins margins = PdfPageHelper.getHelper(page).section!.pageSettings.margins; PdfGraphicsHelper.getHelper(_helper.graphics!).clipTranslateMargins( - clipRect.x, - clipRect.y, - margins.left, - margins.top, - margins.right, - margins.bottom); + clipRect.x, + clipRect.y, + margins.left, + margins.top, + margins.right, + margins.bottom, + ); } } PdfGraphicsHelper.getHelper(_helper.graphics!).setLayer(this); @@ -293,16 +333,26 @@ class PdfPageLayer implements IPdfWrapper { } void _updatePageRotation( - PdfPage page, PdfGraphics? graphics, PdfArray? cropBox) { + PdfPage page, + PdfGraphics? graphics, + PdfArray? cropBox, + ) { PdfNumber? rotation; - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.rotate)) { - rotation = PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.rotate] as PdfNumber?; - rotation ??= rotation = PdfCrossTable.dereference( - PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.rotate]) as PdfNumber?; + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.rotate)) { + rotation = + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .rotate] + as PdfNumber?; + rotation ??= + rotation = + PdfCrossTable.dereference( + PdfPageHelper.getHelper( + page, + ).dictionary![PdfDictionaryProperties.rotate], + ) + as PdfNumber?; } else if (page.rotation != PdfPageRotateAngle.rotateAngle0) { if (page.rotation == PdfPageRotateAngle.rotateAngle90) { rotation = PdfNumber(90); @@ -318,25 +368,29 @@ class PdfPageLayer implements IPdfWrapper { if (cropBox != null) { final double height = (cropBox[3]! as PdfNumber).value!.toDouble(); final Size cropBoxSize = Size( - (cropBox[2]! as PdfNumber).value!.toDouble(), - height != 0 - ? height - : (cropBox[1]! as PdfNumber).value!.toDouble()); + (cropBox[2]! as PdfNumber).value!.toDouble(), + height != 0 ? height : (cropBox[1]! as PdfNumber).value!.toDouble(), + ); final Offset cropBoxOffset = Offset( - (cropBox[0]! as PdfNumber).value!.toDouble(), - (cropBox[1]! as PdfNumber).value!.toDouble()); + (cropBox[0]! as PdfNumber).value!.toDouble(), + (cropBox[1]! as PdfNumber).value!.toDouble(), + ); if (page.size.height < cropBoxSize.height) { PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( - page.size.height - cropBoxOffset.dy, - cropBoxSize.width - cropBoxOffset.dx); + page.size.height - cropBoxOffset.dy, + cropBoxSize.width - cropBoxOffset.dx, + ); } else { PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( - cropBoxSize.height - cropBoxOffset.dy, - cropBoxSize.width - cropBoxOffset.dx); + cropBoxSize.height - cropBoxOffset.dy, + cropBoxSize.width - cropBoxOffset.dx, + ); } } else { - PdfGraphicsHelper.getHelper(graphics).clipBounds.size = - PdfSize(page.size.height, page.size.width); + PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( + page.size.height, + page.size.width, + ); } } else if (rotation.value == 180) { graphics!.translateTransform(page.size.width, page.size.height); @@ -344,17 +398,19 @@ class PdfPageLayer implements IPdfWrapper { } else if (rotation.value == 270) { graphics!.translateTransform(page.size.width, 0); graphics.rotateTransform(-270); - PdfGraphicsHelper.getHelper(graphics).clipBounds.size = - PdfSize(page.size.height, page.size.width); + PdfGraphicsHelper.getHelper(graphics).clipBounds.size = PdfSize( + page.size.height, + page.size.width, + ); } } void _beginSaveContent(Object sender, SavePdfPrimitiveArgs? args) { if (_graphicsState != null) { if (_isEndState) { - PdfGraphicsHelper.getHelper(_helper.graphics!) - .streamWriter! - .write('EMC\n'); + PdfGraphicsHelper.getHelper( + _helper.graphics!, + ).streamWriter!.write('EMC\n'); _isEndState = false; } graphics.restore(_graphicsState); @@ -365,12 +421,16 @@ class PdfPageLayer implements IPdfWrapper { void _setVisibility(bool? value) { PdfDictionary? oCProperties; - if (PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_page).document!) - .catalog - .containsKey(PdfDictionaryProperties.ocProperties)) { - oCProperties = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_page).document!) - .catalog[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + if (PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_page).document!, + ).catalog.containsKey(PdfDictionaryProperties.ocProperties)) { + oCProperties = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_page).document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; } if (oCProperties != null) { final PdfDictionary? defaultView = @@ -408,7 +468,9 @@ class PdfPageLayer implements IPdfWrapper { } bool _isContainsPageContent( - PdfArray content, PdfReferenceHolder referenceHolder) { + PdfArray content, + PdfReferenceHolder referenceHolder, + ) { for (int i = 0; i < content.count; i++) { final IPdfPrimitive? primitive = content.elements[i]; if (primitive != null && primitive is PdfReferenceHolder) { @@ -465,8 +527,10 @@ class PdfPageLayerHelper { } /// internal method - static PdfPageLayer fromClipPageTemplate(PdfPage pdfPage, - [bool? clipPageTemplates]) { + static PdfPageLayer fromClipPageTemplate( + PdfPage pdfPage, [ + bool? clipPageTemplates, + ]) { return PdfPageLayer._fromClipPageTemplate(pdfPage, clipPageTemplates); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer_collection.dart index 8ea8cbcc1..382d1ecec 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_layer_collection.dart @@ -73,7 +73,7 @@ class PdfPageLayerCollection extends PdfObjectCollection { class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { /// internal constructor PdfPageLayerCollectionHelper(this.pageLayerCollection, PdfPage page) - : super(pageLayerCollection) { + : super(pageLayerCollection) { _optionalContent = PdfDictionary(); _subLayer = false; _page = page; @@ -95,7 +95,8 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfPageLayerCollectionHelper getHelper( - PdfPageLayerCollection pageLayerCollection) { + PdfPageLayerCollection pageLayerCollection, + ) { return pageLayerCollection._helper; } @@ -118,12 +119,19 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { pdfLoaded = page; } if (pdfLoaded != null) { - propertie = PdfCrossTable.dereference( - resource![PdfDictionaryProperties.properties]) as PdfDictionary?; + propertie = + PdfCrossTable.dereference( + resource![PdfDictionaryProperties.properties], + ) + as PdfDictionary?; if (PdfPageHelper.getHelper(pdfLoaded).document != null) { - ocProperties = PdfCrossTable.dereference(PdfDocumentHelper.getHelper( - PdfPageHelper.getHelper(pdfLoaded).document!) - .catalog[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + ocProperties = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(pdfLoaded).document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; } } @@ -135,8 +143,14 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { PdfCrossTable.dereference(value) as PdfDictionary?; if ((layerDictionary != null && layerReferenceHolder != null) || layerDictionary!.containsKey(PdfDictionaryProperties.ocg)) { - _addLayer(page, layerDictionary, layerReferenceHolder, key!.name, - pageLayerCollection, false); + _addLayer( + page, + layerDictionary, + layerReferenceHolder, + key!.name, + pageLayerCollection, + false, + ); } }); } @@ -170,7 +184,11 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } List _combineProcess( - PdfPage page, bool decompress, List end, bool isTextExtraction) { + PdfPage page, + bool decompress, + List end, + bool isTextExtraction, + ) { final List data = []; for (int i = 0; i < PdfPageHelper.getHelper(page).contents.count; i++) { PdfStream? layerStream; @@ -201,12 +219,16 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { final IPdfPrimitive? ocgroups = _createOptionContentDictionary(layer); bool isPresent = false; if (PdfPageHelper.getHelper(_page).document != null && - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_page).document!) - .catalog - .containsKey(PdfDictionaryProperties.ocProperties)) { - final PdfDictionary? ocDictionary = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_page).document!) - .catalog[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_page).document!, + ).catalog.containsKey(PdfDictionaryProperties.ocProperties)) { + final PdfDictionary? ocDictionary = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_page).document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; if (ocDictionary != null && ocDictionary.containsKey(PdfDictionaryProperties.ocg)) { final PdfArray? ocgsList = @@ -214,10 +236,13 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { as PdfArray?; if (ocgsList != null) { isPresent = true; - if (!ocgsList - .contains(PdfPageLayerHelper.getHelper(layer).referenceHolder!)) { - ocgsList.insert(ocgsList.count, - PdfPageLayerHelper.getHelper(layer).referenceHolder!); + if (!ocgsList.contains( + PdfPageLayerHelper.getHelper(layer).referenceHolder!, + )) { + ocgsList.insert( + ocgsList.count, + PdfPageLayerHelper.getHelper(layer).referenceHolder!, + ); } } if (ocDictionary.containsKey(PdfDictionaryProperties.defaultView)) { @@ -225,15 +250,26 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { ocDictionary[PdfDictionaryProperties.defaultView] as PdfDictionary?; if (defaultView != null) { - PdfArray? on = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOn]) as PdfArray?; - final PdfArray? order = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOrder]) as PdfArray?; - PdfArray? off = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOff]) as PdfArray?; - final PdfArray? usage = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.usageApplication]) - as PdfArray?; + PdfArray? on = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOn], + ) + as PdfArray?; + final PdfArray? order = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOrder], + ) + as PdfArray?; + PdfArray? off = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOff], + ) + as PdfArray?; + final PdfArray? usage = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.usageApplication], + ) + as PdfArray?; if (on == null) { on = PdfArray(); @@ -265,8 +301,11 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { PdfCrossTable.dereference(usage[0]) as PdfDictionary?; if (asDictionary != null && asDictionary.containsKey(PdfDictionaryProperties.ocg)) { - final PdfArray? usageOcGroup = PdfCrossTable.dereference( - asDictionary[PdfDictionaryProperties.ocg]) as PdfArray?; + final PdfArray? usageOcGroup = + PdfCrossTable.dereference( + asDictionary[PdfDictionaryProperties.ocg], + ) + as PdfArray?; if (usageOcGroup != null && !usageOcGroup.contains(referenceHolder)) { usageOcGroup.insert(usageOcGroup.count, referenceHolder); @@ -279,11 +318,11 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } if (!isPresent && PdfPageHelper.getHelper(_page).document != null) { ocProperties[PdfDictionaryProperties.ocg] = ocgroups; - ocProperties[PdfDictionaryProperties.defaultView] = - _createOptionalContentViews(layer); - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_page).document!) - .catalog - .setProperty(PdfDictionaryProperties.ocProperties, ocProperties); + ocProperties[PdfDictionaryProperties + .defaultView] = _createOptionalContentViews(layer); + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_page).document!, + ).catalog.setProperty(PdfDictionaryProperties.ocProperties, ocProperties); } } @@ -291,17 +330,20 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { final PdfDictionary optionalContent = PdfDictionary(); optionalContent[PdfDictionaryProperties.name] = PdfString(layer.name!); optionalContent[PdfDictionaryProperties.type] = PdfName('OCG'); - optionalContent[PdfDictionaryProperties.layerID] = - PdfName(PdfPageLayerHelper.getHelper(layer).layerID); - optionalContent[PdfDictionaryProperties.visible] = - PdfBoolean(layer.visible); + optionalContent[PdfDictionaryProperties.layerID] = PdfName( + PdfPageLayerHelper.getHelper(layer).layerID, + ); + optionalContent[PdfDictionaryProperties.visible] = PdfBoolean( + layer.visible, + ); PdfPageLayerHelper.getHelper(layer).usage = _setPrintOption(layer); - optionalContent[PdfDictionaryProperties.usage] = - PdfReferenceHolder(PdfPageLayerHelper.getHelper(layer).usage); + optionalContent[PdfDictionaryProperties.usage] = PdfReferenceHolder( + PdfPageLayerHelper.getHelper(layer).usage, + ); final PdfDocument document = PdfPageHelper.getHelper(_page).document!; - PdfDocumentHelper.getHelper(document) - .printLayer! - .add(PdfReferenceHolder(optionalContent)); + PdfDocumentHelper.getHelper( + document, + ).printLayer!.add(PdfReferenceHolder(optionalContent)); final PdfReferenceHolder reference = PdfReferenceHolder(optionalContent); PdfDocumentHelper.getHelper(document).pdfPrimitive!.add(reference); PdfPageLayerHelper.getHelper(layer).dictionary = optionalContent; @@ -347,10 +389,11 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { PdfDictionary _setPrintOption(PdfPageLayer layer) { final PdfDictionary usage = PdfDictionary(); PdfPageLayerHelper.getHelper(layer).printOption = PdfDictionary(); - PdfPageLayerHelper.getHelper(layer) - .printOption![PdfDictionaryProperties.subtype] = PdfName('Print'); - usage[PdfDictionaryProperties.print] = - PdfReferenceHolder(PdfPageLayerHelper.getHelper(layer).printOption); + PdfPageLayerHelper.getHelper(layer).printOption![PdfDictionaryProperties + .subtype] = PdfName('Print'); + usage[PdfDictionaryProperties.print] = PdfReferenceHolder( + PdfPageLayerHelper.getHelper(layer).printOption, + ); return usage; } @@ -383,12 +426,13 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } void _addLayer( - PdfPage page, - PdfDictionary dictionary, - PdfReferenceHolder? reference, - String? key, - Map pageLayerCollection, - bool isResourceLayer) { + PdfPage page, + PdfDictionary dictionary, + PdfReferenceHolder? reference, + String? key, + Map pageLayerCollection, + bool isResourceLayer, + ) { final PdfPageLayer layer = PdfPageLayer(page); list.add(layer); if (!pageLayerCollection.containsKey(reference)) { @@ -408,10 +452,15 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } } - void _checkVisible(PdfDictionary ocproperties, - Map layerDictionary) { - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocproperties[PdfDictionaryProperties.defaultView]) as PdfDictionary?; + void _checkVisible( + PdfDictionary ocproperties, + Map layerDictionary, + ) { + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocproperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null) { final PdfArray? visible = PdfCrossTable.dereference(defaultView[PdfDictionaryProperties.ocgOff]) @@ -424,11 +473,13 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { if (pdfLayer != null) { pdfLayer.visible = false; if (PdfPageLayerHelper.getHelper(pdfLayer).dictionary != null && - PdfPageLayerHelper.getHelper(pdfLayer) - .dictionary! - .containsKey(PdfDictionaryProperties.visible)) { + PdfPageLayerHelper.getHelper( + pdfLayer, + ).dictionary!.containsKey(PdfDictionaryProperties.visible)) { PdfPageLayerHelper.getHelper(pdfLayer).dictionary!.setProperty( - PdfDictionaryProperties.visible, PdfBoolean(false)); + PdfDictionaryProperties.visible, + PdfBoolean(false), + ); } } } @@ -440,12 +491,18 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { void _removeLayer(PdfPageLayer layer) { PdfDictionary? ocProperties; _removeLayerContent(layer); - final PdfDictionary? resource = PdfCrossTable.dereference( - PdfPageHelper.getHelper(_page) - .dictionary![PdfDictionaryProperties.resources]) as PdfDictionary?; + final PdfDictionary? resource = + PdfCrossTable.dereference( + PdfPageHelper.getHelper(_page).dictionary![PdfDictionaryProperties + .resources], + ) + as PdfDictionary?; if (resource != null) { - final PdfDictionary? properties = PdfCrossTable.dereference( - resource[PdfDictionaryProperties.properties]) as PdfDictionary?; + final PdfDictionary? properties = + PdfCrossTable.dereference( + resource[PdfDictionaryProperties.properties], + ) + as PdfDictionary?; if (properties != null && PdfPageLayerHelper.getHelper(layer).layerID != null && properties.containsKey(PdfPageLayerHelper.getHelper(layer).layerID)) { @@ -454,12 +511,16 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } final PdfPage page = _page; if (PdfPageHelper.getHelper(page).document != null && - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page).document!) - .catalog - .containsKey(PdfDictionaryProperties.ocProperties)) { - ocProperties = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(page).document!) - .catalog[PdfDictionaryProperties.ocProperties]) as PdfDictionary?; + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page).document!, + ).catalog.containsKey(PdfDictionaryProperties.ocProperties)) { + ocProperties = + PdfCrossTable.dereference( + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(page).document!, + ).catalog[PdfDictionaryProperties.ocProperties], + ) + as PdfDictionary?; } if (ocProperties != null) { final PdfArray? ocGroup = @@ -467,19 +528,36 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { as PdfArray?; if (ocGroup != null) { _removeContent( - ocGroup, PdfPageLayerHelper.getHelper(layer).referenceHolder); + ocGroup, + PdfPageLayerHelper.getHelper(layer).referenceHolder, + ); } - final PdfDictionary? defaultView = PdfCrossTable.dereference( - ocProperties[PdfDictionaryProperties.defaultView]) as PdfDictionary?; + final PdfDictionary? defaultView = + PdfCrossTable.dereference( + ocProperties[PdfDictionaryProperties.defaultView], + ) + as PdfDictionary?; if (defaultView != null) { - final PdfArray? on = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOn]) as PdfArray?; - final PdfArray? order = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOrder]) as PdfArray?; - final PdfArray? off = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.ocgOff]) as PdfArray?; - final PdfArray? usage = PdfCrossTable.dereference( - defaultView[PdfDictionaryProperties.usageApplication]) as PdfArray?; + final PdfArray? on = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOn], + ) + as PdfArray?; + final PdfArray? order = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOrder], + ) + as PdfArray?; + final PdfArray? off = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.ocgOff], + ) + as PdfArray?; + final PdfArray? usage = + PdfCrossTable.dereference( + defaultView[PdfDictionaryProperties.usageApplication], + ) + as PdfArray?; if (usage != null && usage.count > 0) { for (int i = 0; i < usage.count; i++) { @@ -490,22 +568,30 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { final PdfArray? usageOcGroup = usageDictionary[PdfDictionaryProperties.ocg] as PdfArray?; if (usageOcGroup != null) { - _removeContent(usageOcGroup, - PdfPageLayerHelper.getHelper(layer).referenceHolder); + _removeContent( + usageOcGroup, + PdfPageLayerHelper.getHelper(layer).referenceHolder, + ); } } } } if (order != null) { _removeContent( - order, PdfPageLayerHelper.getHelper(layer).referenceHolder); + order, + PdfPageLayerHelper.getHelper(layer).referenceHolder, + ); } if (layer.visible && on != null) { _removeContent( - on, PdfPageLayerHelper.getHelper(layer).referenceHolder); + on, + PdfPageLayerHelper.getHelper(layer).referenceHolder, + ); } else if (off != null) { _removeContent( - off, PdfPageLayerHelper.getHelper(layer).referenceHolder); + off, + PdfPageLayerHelper.getHelper(layer).referenceHolder, + ); } } } @@ -529,8 +615,9 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { flag = true; i--; } else if (identical( - (content.elements[i]! as PdfReferenceHolder).object, - referenceHolder!.object)) { + (content.elements[i]! as PdfReferenceHolder).object, + referenceHolder!.object, + )) { content.elements.removeAt(i); flag = true; i--; @@ -573,12 +660,13 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { recordCollection.recordCollection[j].operatorName; if (mOperator == 'BMC' || mOperator == 'EMC' || mOperator == 'BDC') { final Map returnedValue = _processBeginMarkContent( - layer, - mOperator, - recordCollection.recordCollection[j].operands, - data, - isNewContentStream, - removePageContent); + layer, + mOperator, + recordCollection.recordCollection[j].operands, + data, + isNewContentStream, + removePageContent, + ); removePageContent = returnedValue['removePageContent']; isSkip = true; if (removePageContent!) { @@ -607,12 +695,20 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { mOperator == PdfOperators.selectColorSpaceForNonStroking || mOperator == PdfOperators.selectColorSpaceForStroking) { if (!isSkip) { - _streamWrite(recordCollection.recordCollection[j].operands, - mOperator, false, data); + _streamWrite( + recordCollection.recordCollection[j].operands, + mOperator, + false, + data, + ); } } else if (!isSkip) { - _streamWrite(recordCollection.recordCollection[j].operands, mOperator, - true, data); + _streamWrite( + recordCollection.recordCollection[j].operands, + mOperator, + true, + data, + ); } isSkip = false; } @@ -624,20 +720,24 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { pageContent.clear(); } if (removePageContent!) { - _removeContent(PdfPageHelper.getHelper(_page).contents, - PdfPageLayerHelper.getHelper(layer).referenceHolder); + _removeContent( + PdfPageHelper.getHelper(_page).contents, + PdfPageLayerHelper.getHelper(layer).referenceHolder, + ); if (PdfPageLayerHelper.getHelper(layer).graphics != null && PdfGraphicsHelper.getHelper( - PdfPageLayerHelper.getHelper(layer).graphics!) - .streamWriter != + PdfPageLayerHelper.getHelper(layer).graphics!, + ).streamWriter != null) { - final PdfStream? lcontent = PdfGraphicsHelper.getHelper( - PdfPageLayerHelper.getHelper(layer).graphics!) - .streamWriter! - .stream; + final PdfStream? lcontent = + PdfGraphicsHelper.getHelper( + PdfPageLayerHelper.getHelper(layer).graphics!, + ).streamWriter!.stream; if (lcontent != null) { - _removeContent(PdfPageHelper.getHelper(_page).contents, - PdfReferenceHolder(lcontent)); + _removeContent( + PdfPageHelper.getHelper(_page).contents, + PdfReferenceHolder(lcontent), + ); } } } @@ -645,12 +745,13 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } Map _processBeginMarkContent( - PdfPageLayer parser, - String? mOperator, - List? operands, - PdfStream data, - bool isNewContentStream, - bool? removePageContent) { + PdfPageLayer parser, + String? mOperator, + List? operands, + PdfStream data, + bool isNewContentStream, + bool? removePageContent, + ) { removePageContent = false; if ('BDC' == mOperator) { String? operand; @@ -680,7 +781,11 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { } void _streamWrite( - List? operands, String? mOperator, bool skip, PdfStream data) { + List? operands, + String? mOperator, + bool skip, + PdfStream data, + ) { PdfString pdfString; if (skip && _bdcCount > 0) { return; @@ -728,12 +833,14 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { _createLayerLoadedPage(layer); } else { final PdfDictionary ocProperties = PdfDictionary(); - ocProperties[PdfDictionaryProperties.ocg] = - _createOptionContentDictionary(layer); - ocProperties[PdfDictionaryProperties.defaultView] = - _createOptionalContentViews(layer); - PdfDocumentHelper.getHelper(PdfPageHelper.getHelper(_page).document!) - .catalog[PdfDictionaryProperties.ocProperties] = ocProperties; + ocProperties[PdfDictionaryProperties + .ocg] = _createOptionContentDictionary(layer); + ocProperties[PdfDictionaryProperties + .defaultView] = _createOptionalContentViews(layer); + PdfDocumentHelper.getHelper( + PdfPageHelper.getHelper(_page).document!, + ).catalog[PdfDictionaryProperties.ocProperties] = + ocProperties; } } return listIndex; @@ -771,7 +878,8 @@ class PdfPageLayerCollectionHelper extends PdfObjectCollectionHelper { void removeAt(int index) { if (index < 0 || index > list.length - 1) { ArgumentError.value( - '$index Value can not be less 0 and greater List.Count - 1'); + '$index Value can not be less 0 and greater List.Count - 1', + ); } final PdfPageLayer layer = pageLayerCollection[index]; _removeLayer(layer); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_settings.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_settings.dart index c1ae3fd8e..11bf127dd 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_settings.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_settings.dart @@ -248,8 +248,9 @@ class PdfPageSettings { void setMargins(double all, [double? top, double? right, double? bottom]) { if (!_helper.isPageAdded) { if (top != null && right != null && bottom != null) { - PdfMarginsHelper.getHelper(margins) - .setMarginsAll(all, top, right, bottom); + PdfMarginsHelper.getHelper( + margins, + ).setMarginsAll(all, top, right, bottom); } else if (top != null && right == null) { PdfMarginsHelper.getHelper(margins).setMarginsLT(all, top); } else if (top == null && bottom != null) { @@ -308,8 +309,10 @@ class PdfPageSettingsHelper { /// internal method Size getActualSize() { - return Size(base.width - (base.margins.left + base.margins.right), - base.height - (base.margins.top + base.margins.bottom)); + return Size( + base.width - (base.margins.left + base.margins.right), + base.height - (base.margins.top + base.margins.bottom), + ); } /// internal method diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_template_element.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_template_element.dart index 26042a5bf..3b07de8cb 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_template_element.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_page_template_element.dart @@ -415,31 +415,36 @@ class PdfPageTemplateElement { bool canBeSet = false; switch (dock) { case PdfDockStyle.left: - canBeSet = alignment == PdfAlignmentStyle.topLeft || + canBeSet = + alignment == PdfAlignmentStyle.topLeft || alignment == PdfAlignmentStyle.middleLeft || alignment == PdfAlignmentStyle.bottomLeft || alignment == PdfAlignmentStyle.none; break; case PdfDockStyle.top: - canBeSet = alignment == PdfAlignmentStyle.topLeft || + canBeSet = + alignment == PdfAlignmentStyle.topLeft || alignment == PdfAlignmentStyle.topCenter || alignment == PdfAlignmentStyle.topRight || alignment == PdfAlignmentStyle.none; break; case PdfDockStyle.right: - canBeSet = alignment == PdfAlignmentStyle.topRight || + canBeSet = + alignment == PdfAlignmentStyle.topRight || alignment == PdfAlignmentStyle.middleRight || alignment == PdfAlignmentStyle.bottomRight || alignment == PdfAlignmentStyle.none; break; case PdfDockStyle.bottom: - canBeSet = alignment == PdfAlignmentStyle.bottomLeft || + canBeSet = + alignment == PdfAlignmentStyle.bottomLeft || alignment == PdfAlignmentStyle.bottomCenter || alignment == PdfAlignmentStyle.bottomRight || alignment == PdfAlignmentStyle.none; break; case PdfDockStyle.fill: - canBeSet = alignment == PdfAlignmentStyle.middleCenter || + canBeSet = + alignment == PdfAlignmentStyle.middleCenter || alignment == PdfAlignmentStyle.none; break; case PdfDockStyle.none: @@ -537,8 +542,9 @@ class PdfPageTemplateElementHelper { Rect _getSimpleAlignmentBounds(PdfPage page, PdfDocument document) { final Rect result = base.bounds; final PdfSection section = PdfPageHelper.getHelper(page).section!; - final PdfRectangle actualBounds = PdfSectionHelper.getHelper(section) - .getActualBounds(page, false, document); + final PdfRectangle actualBounds = PdfSectionHelper.getHelper( + section, + ).getActualBounds(page, false, document); double x = base.location.dx; double y = base.location.dy; @@ -626,8 +632,9 @@ class PdfPageTemplateElementHelper { Rect _getSimpleDockBounds(PdfPage page, PdfDocument document) { Rect result = base.bounds; final PdfSection section = PdfPageHelper.getHelper(page).section!; - final PdfRectangle actualBounds = PdfSectionHelper.getHelper(section) - .getActualBounds(page, false, document); + final PdfRectangle actualBounds = PdfSectionHelper.getHelper( + section, + ).getActualBounds(page, false, document); double x = base.location.dx; double y = base.location.dy; double? width = base.width; @@ -682,10 +689,12 @@ class PdfPageTemplateElementHelper { Rect _getTemplateDockBounds(PdfPage page, PdfDocument document) { final PdfSection section = PdfPageHelper.getHelper(page).section!; - final PdfRectangle actualBounds = PdfSectionHelper.getHelper(section) - .getActualBounds(page, false, document); + final PdfRectangle actualBounds = PdfSectionHelper.getHelper( + section, + ).getActualBounds(page, false, document); final PdfSize actualSize = PdfSize.fromSize( - PdfPageSettingsHelper.getHelper(section.pageSettings).getActualSize()); + PdfPageSettingsHelper.getHelper(section.pageSettings).getActualSize(), + ); double x = base.location.dx; double y = base.location.dy; double? width = base.width; @@ -711,9 +720,11 @@ class PdfPageTemplateElementHelper { break; case PdfDockStyle.right: - x = actualBounds.width + - PdfSectionHelper.getHelper(section) - .getRightIndentWidth(document, page, false) - + x = + actualBounds.width + + PdfSectionHelper.getHelper( + section, + ).getRightIndentWidth(document, page, false) - base.width; y = 0.0; width = base.width; @@ -722,9 +733,11 @@ class PdfPageTemplateElementHelper { case PdfDockStyle.bottom: x = -actualBounds.x; - y = actualBounds.height + - PdfSectionHelper.getHelper(section) - .getBottomIndentHeight(document, page, false) - + y = + actualBounds.height + + PdfSectionHelper.getHelper( + section, + ).getBottomIndentHeight(document, page, false) - base.height; width = actualSize.width; height = base.height; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section.dart index d1270149b..ac18a2623 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section.dart @@ -47,13 +47,15 @@ class PdfSection implements IPdfWrapper { _helper._section!.beginSave = _helper.beginSave; _helper._pageCount = PdfNumber(0); _helper._section![PdfDictionaryProperties.count] = _helper._pageCount; - _helper._section![PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.pages); + _helper._section![PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.pages, + ); _helper._section![PdfDictionaryProperties.kids] = _helper.pageReferences; _helper.pdfDocument = document; - _helper.settings = settings != null - ? PdfPageSettingsHelper.getHelper(settings).clone() - : PdfPageSettingsHelper.getHelper(document!.pageSettings).clone(); + _helper.settings = + settings != null + ? PdfPageSettingsHelper.getHelper(settings).clone() + : PdfPageSettingsHelper.getHelper(document!.pageSettings).clone(); } /// Event rises when the new page has been added @@ -234,10 +236,8 @@ class PdfSectionHelper { final PdfSectionCollection? sectionCollection = parent; if (sectionCollection != null) { PdfPageCollectionHelper.getHelper( - PdfSectionCollectionHelper.getHelper(sectionCollection) - .document! - .pages) - .onPageAdded(args); + PdfSectionCollectionHelper.getHelper(sectionCollection).document!.pages, + ).onPageAdded(args); } _pageCount!.value = count; } @@ -271,35 +271,47 @@ class PdfSectionHelper { } /// internal method - PdfRectangle getActualBounds(PdfPage page, bool includeMargins, - [PdfDocument? document]) { + PdfRectangle getActualBounds( + PdfPage page, + bool includeMargins, [ + PdfDocument? document, + ]) { if (document == null) { if (parent != null) { final PdfDocument? pdfDocument = PdfSectionCollectionHelper.getHelper(parent!).document; return getActualBounds(page, includeMargins, pdfDocument); } else { - final PdfSize size = includeMargins - ? PdfSize.fromSize( - PdfPageSettingsHelper.getHelper(base.pageSettings) - .getActualSize()) - : base.pageSettings.size as PdfSize; + final PdfSize size = + includeMargins + ? PdfSize.fromSize( + PdfPageSettingsHelper.getHelper( + base.pageSettings, + ).getActualSize(), + ) + : base.pageSettings.size as PdfSize; final double left = includeMargins ? base.pageSettings.margins.left : 0; final double top = includeMargins ? base.pageSettings.margins.top : 0; return PdfRectangle(left, top, size.width, size.height); } } else { final PdfRectangle bounds = PdfRectangle.empty; - final Size size = includeMargins - ? base.pageSettings.size - : PdfPageSettingsHelper.getHelper(base.pageSettings).getActualSize(); + final Size size = + includeMargins + ? base.pageSettings.size + : PdfPageSettingsHelper.getHelper( + base.pageSettings, + ).getActualSize(); bounds.width = size.width; bounds.height = size.height; final double left = getLeftIndentWidth(document, page, includeMargins); final double top = getTopIndentHeight(document, page, includeMargins); final double right = getRightIndentWidth(document, page, includeMargins); - final double bottom = - getBottomIndentHeight(document, page, includeMargins); + final double bottom = getBottomIndentHeight( + document, + page, + includeMargins, + ); bounds.x += left; bounds.y += top; bounds.width -= left + right; @@ -310,100 +322,121 @@ class PdfSectionHelper { /// internal method double getLeftIndentWidth( - PdfDocument document, PdfPage page, bool includeMargins) { + PdfDocument document, + PdfPage page, + bool includeMargins, + ) { double value = includeMargins ? base.pageSettings.margins.left : 0; final double templateWidth = PdfDocumentTemplateHelper.getHelper(base.template).getLeft(page) != null - ? PdfDocumentTemplateHelper.getHelper(base.template) - .getLeft(page)! - .width + ? PdfDocumentTemplateHelper.getHelper( + base.template, + ).getLeft(page)!.width : 0; final double docTemplateWidth = PdfDocumentTemplateHelper.getHelper(document.template).getLeft(page) != null - ? PdfDocumentTemplateHelper.getHelper(document.template) - .getLeft(page)! - .width + ? PdfDocumentTemplateHelper.getHelper( + document.template, + ).getLeft(page)!.width : 0; - value += base.template.leftTemplate - ? (templateWidth >= docTemplateWidth ? templateWidth : docTemplateWidth) - : templateWidth; + value += + base.template.leftTemplate + ? (templateWidth >= docTemplateWidth + ? templateWidth + : docTemplateWidth) + : templateWidth; return value; } /// internal method double getTopIndentHeight( - PdfDocument document, PdfPage page, bool includeMargins) { + PdfDocument document, + PdfPage page, + bool includeMargins, + ) { double value = includeMargins ? base.pageSettings.margins.top : 0; final double templateHeight = PdfDocumentTemplateHelper.getHelper(base.template).getTop(page) != null - ? PdfDocumentTemplateHelper.getHelper(base.template) - .getTop(page)! - .height + ? PdfDocumentTemplateHelper.getHelper( + base.template, + ).getTop(page)!.height : 0; final double docTemplateHeight = PdfDocumentTemplateHelper.getHelper(document.template).getTop(page) != null - ? PdfDocumentTemplateHelper.getHelper(document.template) - .getTop(page)! - .height + ? PdfDocumentTemplateHelper.getHelper( + document.template, + ).getTop(page)!.height : 0; - value += base.template.topTemplate - ? (templateHeight >= docTemplateHeight - ? templateHeight - : docTemplateHeight) - : templateHeight; + value += + base.template.topTemplate + ? (templateHeight >= docTemplateHeight + ? templateHeight + : docTemplateHeight) + : templateHeight; return value; } /// internal method double getRightIndentWidth( - PdfDocument document, PdfPage page, bool includeMargins) { + PdfDocument document, + PdfPage page, + bool includeMargins, + ) { double value = includeMargins ? base.pageSettings.margins.right : 0; final double templateWidth = PdfDocumentTemplateHelper.getHelper(base.template).getRight(page) != null - ? PdfDocumentTemplateHelper.getHelper(base.template) - .getRight(page)! - .width + ? PdfDocumentTemplateHelper.getHelper( + base.template, + ).getRight(page)!.width : 0; final double docTemplateWidth = PdfDocumentTemplateHelper.getHelper(document.template).getRight(page) != null - ? PdfDocumentTemplateHelper.getHelper(document.template) - .getRight(page)! - .width + ? PdfDocumentTemplateHelper.getHelper( + document.template, + ).getRight(page)!.width : 0; - value += base.template.rightTemplate - ? (templateWidth >= docTemplateWidth ? templateWidth : docTemplateWidth) - : templateWidth; + value += + base.template.rightTemplate + ? (templateWidth >= docTemplateWidth + ? templateWidth + : docTemplateWidth) + : templateWidth; return value; } /// internal method double getBottomIndentHeight( - PdfDocument document, PdfPage page, bool includeMargins) { + PdfDocument document, + PdfPage page, + bool includeMargins, + ) { double value = includeMargins ? base.pageSettings.margins.bottom : 0; final double templateHeight = PdfDocumentTemplateHelper.getHelper(base.template).getBottom(page) != null - ? PdfDocumentTemplateHelper.getHelper(base.template) - .getBottom(page)! - .height + ? PdfDocumentTemplateHelper.getHelper( + base.template, + ).getBottom(page)!.height : 0; final double docTemplateHeight = - PdfDocumentTemplateHelper.getHelper(document.template) - .getBottom(page) != + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getBottom(page) != null - ? PdfDocumentTemplateHelper.getHelper(document.template) - .getBottom(page)! - .height + ? PdfDocumentTemplateHelper.getHelper( + document.template, + ).getBottom(page)!.height : 0; - value += base.template.bottomTemplate - ? (templateHeight >= docTemplateHeight - ? templateHeight - : docTemplateHeight) - : templateHeight; + value += + base.template.bottomTemplate + ? (templateHeight >= docTemplateHeight + ? templateHeight + : docTemplateHeight) + : templateHeight; return value; } @@ -418,45 +451,56 @@ class PdfSectionHelper { } } - void _setPageSettings(PdfDictionary container, - [PdfPageSettings? parentSettings]) { + void _setPageSettings( + PdfDictionary container, [ + PdfPageSettings? parentSettings, + ]) { if (parentSettings == null || base.pageSettings.size != parentSettings.size) { final PdfRectangle bounds = PdfRectangle( - PdfPageSettingsHelper.getHelper(settings).origin.x, - PdfPageSettingsHelper.getHelper(settings).origin.y, - settings.size.width, - settings.size.height); - container[PdfDictionaryProperties.mediaBox] = - PdfArray.fromRectangle(bounds); + PdfPageSettingsHelper.getHelper(settings).origin.x, + PdfPageSettingsHelper.getHelper(settings).origin.y, + settings.size.width, + settings.size.height, + ); + container[PdfDictionaryProperties.mediaBox] = PdfArray.fromRectangle( + bounds, + ); } if (parentSettings == null || base.pageSettings.rotate != parentSettings.rotate) { int rotate = 0; if (_sectionCollection != null) { if (PdfPageSettingsHelper.getHelper(base.pageSettings).isRotation && - !PdfPageSettingsHelper.getHelper(document!.pageSettings) - .isRotation) { - rotate = PdfSectionCollectionHelper.rotateFactor * + !PdfPageSettingsHelper.getHelper( + document!.pageSettings, + ).isRotation) { + rotate = + PdfSectionCollectionHelper.rotateFactor * base.pageSettings.rotate.index; } else { - if (!PdfPageSettingsHelper.getHelper(document!.pageSettings) - .isRotation && + if (!PdfPageSettingsHelper.getHelper( + document!.pageSettings, + ).isRotation && base.pageSettings.rotate != PdfPageRotateAngle.rotateAngle0) { - rotate = PdfSectionCollectionHelper.rotateFactor * + rotate = + PdfSectionCollectionHelper.rotateFactor * base.pageSettings.rotate.index; } else { if (PdfPageSettingsHelper.getHelper(base.pageSettings).isRotation) { - rotate = PdfSectionCollectionHelper.rotateFactor * + rotate = + PdfSectionCollectionHelper.rotateFactor * base.pageSettings.rotate.index; } else if (parentSettings != null) { - rotate = PdfSectionCollectionHelper.rotateFactor * + rotate = + PdfSectionCollectionHelper.rotateFactor * parentSettings.rotate.index; } } } } else { - rotate = PdfSectionCollectionHelper.rotateFactor * + rotate = + PdfSectionCollectionHelper.rotateFactor * base.pageSettings.rotate.index; } final PdfNumber angle = PdfNumber(rotate); @@ -477,15 +521,26 @@ class PdfSectionHelper { /// internal method bool containsTemplates(PdfDocument document, PdfPage page, bool foreground) { - final List documentHeaders = - _getDocumentTemplates(document, page, true, foreground); + final List documentHeaders = _getDocumentTemplates( + document, + page, + true, + foreground, + ); final List documentTemplates = _getDocumentTemplates(document, page, false, foreground); - final List sectionHeaders = - _getSectionTemplates(page, true, foreground); - final List sectionTemplates = - _getSectionTemplates(page, false, foreground); - final bool contains = documentHeaders.isNotEmpty || + final List sectionHeaders = _getSectionTemplates( + page, + true, + foreground, + ); + final List sectionTemplates = _getSectionTemplates( + page, + false, + foreground, + ); + final bool contains = + documentHeaders.isNotEmpty || documentTemplates.isNotEmpty || sectionHeaders.isNotEmpty || sectionTemplates.isNotEmpty; @@ -493,51 +548,66 @@ class PdfSectionHelper { } List _getDocumentTemplates( - PdfDocument document, PdfPage page, bool headers, bool foreground) { + PdfDocument document, + PdfPage page, + bool headers, + bool foreground, + ) { final List templates = []; if (headers) { if (base.template.topTemplate && PdfDocumentTemplateHelper.getHelper(document.template).getTop(page) != null && - PdfDocumentTemplateHelper.getHelper(document.template) - .getTop(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getTop(page)!.foreground == foreground) { - templates.add(PdfDocumentTemplateHelper.getHelper(document.template) - .getTop(page)!); + templates.add( + PdfDocumentTemplateHelper.getHelper(document.template).getTop(page)!, + ); } if (base.template.bottomTemplate && - PdfDocumentTemplateHelper.getHelper(document.template) - .getBottom(page) != + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getBottom(page) != null && - PdfDocumentTemplateHelper.getHelper(document.template) - .getBottom(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getBottom(page)!.foreground == foreground) { - templates.add(PdfDocumentTemplateHelper.getHelper(document.template) - .getBottom(page)!); + templates.add( + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getBottom(page)!, + ); } if (base.template.leftTemplate && - PdfDocumentTemplateHelper.getHelper(document.template) - .getLeft(page) != + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getLeft(page) != null && - PdfDocumentTemplateHelper.getHelper(document.template) - .getLeft(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getLeft(page)!.foreground == foreground) { - templates.add(PdfDocumentTemplateHelper.getHelper(document.template) - .getLeft(page)!); + templates.add( + PdfDocumentTemplateHelper.getHelper(document.template).getLeft(page)!, + ); } if (base.template.rightTemplate && - PdfDocumentTemplateHelper.getHelper(document.template) - .getRight(page) != + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getRight(page) != null && - PdfDocumentTemplateHelper.getHelper(document.template) - .getRight(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getRight(page)!.foreground == foreground) { - templates.add(PdfDocumentTemplateHelper.getHelper(document.template) - .getRight(page)!); + templates.add( + PdfDocumentTemplateHelper.getHelper( + document.template, + ).getRight(page)!, + ); } } else if (base.template.stamp) { final List list = @@ -554,44 +624,51 @@ class PdfSectionHelper { } List _getSectionTemplates( - PdfPage page, bool headers, bool foreground) { + PdfPage page, + bool headers, + bool foreground, + ) { final List templates = []; if (headers) { if (PdfDocumentTemplateHelper.getHelper(base.template).getTop(page) != null && - PdfDocumentTemplateHelper.getHelper(base.template) - .getTop(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + base.template, + ).getTop(page)!.foreground == foreground) { templates.add( - PdfDocumentTemplateHelper.getHelper(base.template).getTop(page)!); + PdfDocumentTemplateHelper.getHelper(base.template).getTop(page)!, + ); } if (PdfDocumentTemplateHelper.getHelper(base.template).getBottom(page) != null && - PdfDocumentTemplateHelper.getHelper(base.template) - .getBottom(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + base.template, + ).getBottom(page)!.foreground == foreground) { - templates.add(PdfDocumentTemplateHelper.getHelper(base.template) - .getBottom(page)!); + templates.add( + PdfDocumentTemplateHelper.getHelper(base.template).getBottom(page)!, + ); } if (PdfDocumentTemplateHelper.getHelper(base.template).getLeft(page) != null && - PdfDocumentTemplateHelper.getHelper(base.template) - .getLeft(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + base.template, + ).getLeft(page)!.foreground == foreground) { templates.add( - PdfDocumentTemplateHelper.getHelper(base.template).getLeft(page)!); + PdfDocumentTemplateHelper.getHelper(base.template).getLeft(page)!, + ); } if (PdfDocumentTemplateHelper.getHelper(base.template).getRight(page) != null && - PdfDocumentTemplateHelper.getHelper(base.template) - .getRight(page)! - .foreground == + PdfDocumentTemplateHelper.getHelper( + base.template, + ).getRight(page)!.foreground == foreground) { templates.add( - PdfDocumentTemplateHelper.getHelper(base.template).getRight(page)!); + PdfDocumentTemplateHelper.getHelper(base.template).getRight(page)!, + ); } } else { final List list = @@ -608,15 +685,29 @@ class PdfSectionHelper { /// internal method void drawTemplates( - PdfPage page, PdfPageLayer layer, PdfDocument document, bool foreground) { - final List documentHeaders = - _getDocumentTemplates(document, page, true, foreground); + PdfPage page, + PdfPageLayer layer, + PdfDocument document, + bool foreground, + ) { + final List documentHeaders = _getDocumentTemplates( + document, + page, + true, + foreground, + ); final List documentTemplates = _getDocumentTemplates(document, page, false, foreground); - final List sectionHeaders = - _getSectionTemplates(page, true, foreground); - final List sectionTemplates = - _getSectionTemplates(page, false, foreground); + final List sectionHeaders = _getSectionTemplates( + page, + true, + foreground, + ); + final List sectionTemplates = _getSectionTemplates( + page, + false, + foreground, + ); if (foreground) { _internaldrawTemplates(layer, document, sectionHeaders); _internaldrawTemplates(layer, document, sectionTemplates); @@ -630,8 +721,11 @@ class PdfSectionHelper { } } - void _internaldrawTemplates(PdfPageLayer layer, PdfDocument document, - List templates) { + void _internaldrawTemplates( + PdfPageLayer layer, + PdfDocument document, + List templates, + ) { if (templates.isNotEmpty) { for (final PdfPageTemplateElement template in templates) { PdfPageTemplateElementHelper.getHelper(template).draw(layer, document); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section_collection.dart index 46d540307..9e7757142 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pages/pdf_section_collection.dart @@ -113,17 +113,20 @@ class PdfSectionCollectionHelper { } void _setPageSettings( - PdfDictionary dictionary, PdfPageSettings pageSettings) { + PdfDictionary dictionary, + PdfPageSettings pageSettings, + ) { final List list = [ 0, 0, pageSettings.size.width, - pageSettings.size.height + pageSettings.size.height, ]; dictionary[PdfDictionaryProperties.mediaBox] = PdfArray(list); if (pageSettings.rotate != PdfPageRotateAngle.rotateAngle0) { - dictionary[PdfDictionaryProperties.rotate] = - PdfNumber(rotateFactor * pageSettings.rotate.index); + dictionary[PdfDictionaryProperties.rotate] = PdfNumber( + rotateFactor * pageSettings.rotate.index, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment.dart index cc4751f04..7a67400ce 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment.dart @@ -12,8 +12,12 @@ class PdfAttachment extends PdfEmbeddedFileSpecification { //Constructor. /// Initializes a new instance of the [PdfAttachment] class with specified /// file name and byte data to be attached. - PdfAttachment(super.fileName, super.data, - {String? description, String? mimeType}) { + PdfAttachment( + super.fileName, + super.data, { + String? description, + String? mimeType, + }) { _embeddedFile = PdfEmbeddedFileSpecificationHelper.getHelper(this).embeddedFile; _updateValues(description, mimeType); @@ -21,9 +25,12 @@ class PdfAttachment extends PdfEmbeddedFileSpecification { /// Initializes a new instance of the [PdfAttachment] class with specified /// file name and byte data as base64 String to be attached. - PdfAttachment.fromBase64String(String fileName, String base64String, - {String? description, String? mimeType}) - : super(fileName, base64.decode(base64String)) { + PdfAttachment.fromBase64String( + String fileName, + String base64String, { + String? description, + String? mimeType, + }) : super(fileName, base64.decode(base64String)) { _embeddedFile = PdfEmbeddedFileSpecificationHelper.getHelper(this).embeddedFile; _updateValues(description, mimeType); @@ -80,9 +87,13 @@ class PdfAttachment extends PdfEmbeddedFileSpecification { set relationship(PdfAttachmentRelationship value) { PdfEmbeddedFileSpecificationHelper.getHelper(this).relationship = value; PdfFileSpecificationBaseHelper.getHelper(this).dictionary!.setProperty( - PdfDictionaryProperties.afRelationship, - PdfName(PdfEmbeddedFileSpecificationHelper.getHelper(this).getEnumName( - PdfEmbeddedFileSpecificationHelper.getHelper(this).relationship))); + PdfDictionaryProperties.afRelationship, + PdfName( + PdfEmbeddedFileSpecificationHelper.getHelper(this).getEnumName( + PdfEmbeddedFileSpecificationHelper.getHelper(this).relationship, + ), + ), + ); } void _updateValues(String? desc, String? mime) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment_collection.dart index 37d01ba81..685254b8b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/attachments/pdf_attachment_collection.dart @@ -26,7 +26,9 @@ class PdfAttachmentCollection extends PdfObjectCollection } PdfAttachmentCollection._( - PdfDictionary dictionary, PdfCrossTable? crossTable) { + PdfDictionary dictionary, + PdfCrossTable? crossTable, + ) { _helper = PdfAttachmentCollectionHelper._(this, dictionary, crossTable); } @@ -81,7 +83,7 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { dictionary.setProperty(PdfDictionaryProperties.names, _array); } PdfAttachmentCollectionHelper._(this.base, this.dictionary, this.crossTable) - : super(base) { + : super(base) { _initializeAttachmentCollection(); } @@ -110,7 +112,9 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { /// internal method static PdfAttachmentCollection load( - PdfDictionary attachmentDictionary, PdfCrossTable? crossTable) { + PdfDictionary attachmentDictionary, + PdfCrossTable? crossTable, + ) { return PdfAttachmentCollection._(attachmentDictionary, crossTable); } @@ -139,7 +143,8 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { int add(PdfAttachment attachment) { if (conformance) { throw ArgumentError( - 'Attachment is not allowed for this conformance level.'); + 'Attachment is not allowed for this conformance level.', + ); } final int position = _doAdd(attachment); dictionary.modify(); @@ -172,9 +177,10 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { if (kids.count != 0) { for (int l = 0; l < kids.count; l++) { if (kids[l] is PdfReferenceHolder || kids[l] is PdfDictionary) { - embedDictionary = kids[l] is PdfDictionary - ? kids[l]! as PdfDictionary - : (kids[l]! as PdfReferenceHolder).object != null && + embedDictionary = + kids[l] is PdfDictionary + ? kids[l]! as PdfDictionary + : (kids[l]! as PdfReferenceHolder).object != null && (kids[l]! as PdfReferenceHolder).object is PdfDictionary ? (kids[l]! as PdfReferenceHolder).object @@ -212,8 +218,9 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { if (streamDictionary.containsKey(PdfDictionaryProperties.ef)) { if (streamDictionary[PdfDictionaryProperties.ef] is PdfDictionary) { - attachmentStream = streamDictionary[PdfDictionaryProperties.ef] - as PdfDictionary?; + attachmentStream = + streamDictionary[PdfDictionaryProperties.ef] + as PdfDictionary?; } else if (streamDictionary[PdfDictionaryProperties.ef] is PdfReferenceHolder) { final PdfReferenceHolder streamHolder = @@ -243,12 +250,14 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { stream.decompress(); if (streamDictionary.containsKey('F')) { attachment = PdfAttachment( - (streamDictionary['F']! as PdfString).value!, - stream.dataStream!); + (streamDictionary['F']! as PdfString).value!, + stream.dataStream!, + ); final IPdfPrimitive fileStream = stream; if (fileStream is PdfDictionary) { final IPdfPrimitive? subtype = PdfCrossTable.dereference( - fileStream[PdfDictionaryProperties.subtype]); + fileStream[PdfDictionaryProperties.subtype], + ); if (subtype is PdfName) { attachment.mimeType = subtype.name! .replaceAll('#23', '#') @@ -258,33 +267,42 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { } if (fileStream is PdfDictionary && fileStream.containsKey(PdfDictionaryProperties.params)) { - final IPdfPrimitive? mParams = PdfCrossTable.dereference( - fileStream[PdfDictionaryProperties.params]) - as PdfDictionary?; + final IPdfPrimitive? mParams = + PdfCrossTable.dereference( + fileStream[PdfDictionaryProperties.params], + ) + as PdfDictionary?; if (mParams is PdfDictionary) { final IPdfPrimitive? creationDate = PdfCrossTable.dereference( - mParams[PdfDictionaryProperties.creationDate]); + mParams[PdfDictionaryProperties.creationDate], + ); final IPdfPrimitive? modifiedDate = PdfCrossTable.dereference( - mParams[PdfDictionaryProperties.modificationDate]); + mParams[PdfDictionaryProperties.modificationDate], + ); if (creationDate is PdfString) { - attachment.creationDate = - mParams.getDateTime(creationDate); + attachment.creationDate = mParams.getDateTime( + creationDate, + ); } if (modifiedDate is PdfString) { - attachment.modificationDate = - mParams.getDateTime(modifiedDate); + attachment.modificationDate = mParams.getDateTime( + modifiedDate, + ); } } } - if (streamDictionary - .containsKey(PdfDictionaryProperties.afRelationship)) { + if (streamDictionary.containsKey( + PdfDictionaryProperties.afRelationship, + )) { final IPdfPrimitive? relationShip = PdfCrossTable.dereference( - streamDictionary[PdfDictionaryProperties.afRelationship]); + streamDictionary[PdfDictionaryProperties.afRelationship], + ); if (relationShip is PdfName) { - attachment.relationship = - _obtainRelationShip(relationShip.name); + attachment.relationship = _obtainRelationShip( + relationShip.name, + ); } } if (streamDictionary.containsKey('Desc')) { @@ -293,16 +311,21 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { } } else { attachment = PdfAttachment( - (streamDictionary['Desc']! as PdfString).value!, - stream.dataStream!); + (streamDictionary['Desc']! as PdfString).value!, + stream.dataStream!, + ); } } else { if (streamDictionary.containsKey('Desc')) { attachment = PdfAttachment( - (streamDictionary['Desc']! as PdfString).value!, []); + (streamDictionary['Desc']! as PdfString).value!, + [], + ); } else { attachment = PdfAttachment( - (streamDictionary['F']! as PdfString).value!, []); + (streamDictionary['F']! as PdfString).value!, + [], + ); } } list.add(attachment); @@ -342,9 +365,10 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { //Adds the attachment. int _doAdd(PdfAttachment attachment) { final String fileName = attachment.fileName; - final String converted = utf8.encode(fileName).length != fileName.length - ? 'Attachment ${_count++}' - : fileName; + final String converted = + utf8.encode(fileName).length != fileName.length + ? 'Attachment ${_count++}' + : fileName; if (_dic.isEmpty && _array!.count > 0) { for (int i = 0; i < _array!.count; i += 2) { if (!_dic.containsKey((_array![i]! as PdfString).value)) { @@ -376,8 +400,9 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { index = list.indexOf(attachment); } _array!.removeAt(2 * index!); - IPdfPrimitive? attachmentDictionay = - PdfCrossTable.dereference(_array![2 * index]); + IPdfPrimitive? attachmentDictionay = PdfCrossTable.dereference( + _array![2 * index], + ); if (attachmentDictionay is PdfDictionary) { _removeAttachementObjects(attachmentDictionay); attachmentDictionay = null; @@ -396,11 +421,13 @@ class PdfAttachmentCollectionHelper extends PdfObjectCollectionHelper { if (objectCollection != null) { if (attachmentDictionary.containsKey(PdfDictionaryProperties.ef)) { final IPdfPrimitive? embedded = PdfCrossTable.dereference( - attachmentDictionary[PdfDictionaryProperties.ef]); + attachmentDictionary[PdfDictionaryProperties.ef], + ); if (embedded is PdfDictionary) { if (embedded.containsKey(PdfDictionaryProperties.f)) { - final IPdfPrimitive? stream = - PdfCrossTable.dereference(embedded[PdfDictionaryProperties.f]); + final IPdfPrimitive? stream = PdfCrossTable.dereference( + embedded[PdfDictionaryProperties.f], + ); if (stream != null) { if (objectCollection.contains(stream)) { final int index = objectCollection.lookFor(stream)!; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field.dart index 60dc96206..a87977db4 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field.dart @@ -23,8 +23,12 @@ import 'pdf_static_field.dart'; /// Represents a fields which is calculated before the document saves. abstract class PdfAutomaticField { /// Initialize [PdfAutomaticField] object - void _internal(PdfFont? font, - {Rect? bounds, PdfBrush? brush, PdfAutomaticFieldHelper? helper}) { + void _internal( + PdfFont? font, { + Rect? bounds, + PdfBrush? brush, + PdfAutomaticFieldHelper? helper, + }) { _helper = helper!; this.font = font ?? PdfStandardFont(PdfFontFamily.helvetica, 8); if (bounds != null) { @@ -296,9 +300,9 @@ abstract class PdfAutomaticField { ///``` void draw(PdfGraphics graphics, [Offset? location]) { location ??= Offset.zero; - PdfGraphicsHelper.getHelper(graphics) - .autoFields! - .add(PdfAutomaticFieldInfo(this, PdfPoint.fromOffset(location))); + PdfGraphicsHelper.getHelper(graphics).autoFields!.add( + PdfAutomaticFieldInfo(this, PdfPoint.fromOffset(location)), + ); } } @@ -433,40 +437,71 @@ class PdfAutomaticFieldHelper { String? getValue(PdfGraphics graphics) { if (base is PdfCompositeField) { return PdfCompositeFieldHelper.getValue( - base as PdfCompositeField, graphics); + base as PdfCompositeField, + graphics, + ); } else if (base is PdfDateTimeField) { return PdfDateTimeFieldHelper.getValue( - base as PdfDateTimeField, graphics); + base as PdfDateTimeField, + graphics, + ); } else if (base is PdfDestinationPageNumberField) { return PdfDestinationPageNumberFieldHelper.getValue( - base as PdfDestinationPageNumberField, graphics); + base as PdfDestinationPageNumberField, + graphics, + ); } else if (base is PdfPageNumberField) { - return PdfPageNumberFieldHelper.getHelper(base as PdfPageNumberField) - .getValue(graphics); + return PdfPageNumberFieldHelper.getHelper( + base as PdfPageNumberField, + ).getValue(graphics); } else if (base is PdfPageCountField) { return PdfPageCountFieldHelper.getValue( - base as PdfPageCountField, graphics); + base as PdfPageCountField, + graphics, + ); } return graphics as String; } /// internal method - void performDraw(PdfGraphics graphics, PdfPoint? location, double scalingX, - double scalingY) { + void performDraw( + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { if (base.bounds.height == 0 || base.bounds.width == 0) { final String text = getValue(graphics)!; - _templateSize = base.font.measureString(text, - layoutArea: base.bounds.size, format: base.stringFormat); + _templateSize = base.font.measureString( + text, + layoutArea: base.bounds.size, + format: base.stringFormat, + ); } if (base is PdfStaticField) { PdfStaticFieldHelper.performDraw( - base as PdfStaticField, graphics, location, scalingX, scalingY); + base as PdfStaticField, + graphics, + location, + scalingX, + scalingY, + ); } else if (base is PdfSingleValueField) { PdfSingleValueFieldHelper.performDraw( - base as PdfSingleValueField, graphics, location, scalingX, scalingY); + base as PdfSingleValueField, + graphics, + location, + scalingX, + scalingY, + ); } else if (base is PdfMultipleValueField) { - PdfMultipleValueFieldHelper.performDraw(base as PdfMultipleValueField, - graphics, location, scalingX, scalingY); + PdfMultipleValueFieldHelper.performDraw( + base as PdfMultipleValueField, + graphics, + location, + scalingX, + scalingY, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field_info.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field_info.dart index f3af96f1d..4df42076a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field_info.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_automatic_field_info.dart @@ -5,8 +5,12 @@ import 'pdf_automatic_field.dart'; class PdfAutomaticFieldInfo { // constructor /// internal constructor - PdfAutomaticFieldInfo(this.field, - [PdfPoint? location, double scalingX = 1, double scalingY = 1]) { + PdfAutomaticFieldInfo( + this.field, [ + PdfPoint? location, + double scalingX = 1, + double scalingY = 1, + ]) { this.location = location ?? PdfPoint.empty; scalingX = scalingX; scalingY = scalingY; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_composite_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_composite_field.dart index 933315bac..b3c9d1c76 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_composite_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_composite_field.dart @@ -77,11 +77,12 @@ class PdfCompositeField extends PdfMultipleValueField { /// //Dispose the document. /// document.dispose(); /// ``` - PdfCompositeField( - {super.font, - super.brush, - String? text, - List? fields}) { + PdfCompositeField({ + super.font, + super.brush, + String? text, + List? fields, + }) { this.text = (text == null) ? '' : text; if (fields != null) { this.fields = fields; @@ -189,8 +190,10 @@ class PdfCompositeField extends PdfMultipleValueField { if (fields.isNotEmpty) { copyText = text; for (int i = 0; i < fields.length; i++) { - copyText = copyText!.replaceAll('{$i}', - PdfAutomaticFieldHelper.getHelper(fields[i]).getValue(graphics)!); + copyText = copyText!.replaceAll( + '{$i}', + PdfAutomaticFieldHelper.getHelper(fields[i]).getValue(graphics)!, + ); } } return (copyText == null) ? text : copyText; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_destination_page_number_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_destination_page_number_field.dart index 1e691b452..025eab1fb 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_destination_page_number_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_destination_page_number_field.dart @@ -11,8 +11,12 @@ class PdfDestinationPageNumberField extends PdfPageNumberField { // constructor /// Initializes a new instance of the [PdfDestinationPageNumberField] class /// may include with [PdfFont], [PdfBrush] and [Rect]. - PdfDestinationPageNumberField( - {PdfPage? page, super.font, super.brush, super.bounds}) { + PdfDestinationPageNumberField({ + PdfPage? page, + super.font, + super.brush, + super.bounds, + }) { if (page != null) { this.page = page; } @@ -32,7 +36,9 @@ class PdfDestinationPageNumberField extends PdfPageNumberField { class PdfDestinationPageNumberFieldHelper { /// internal method static String getValue( - PdfDestinationPageNumberField field, PdfGraphics graphics) { + PdfDestinationPageNumberField field, + PdfGraphics graphics, + ) { return field._getValue(graphics); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_multiple_value_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_multiple_value_field.dart index 897c668de..a10d94b0e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_multiple_value_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_multiple_value_field.dart @@ -18,42 +18,57 @@ abstract class PdfMultipleValueField extends PdfDynamicField { {}; // implementation - void _performDraw(PdfGraphics graphics, PdfPoint? location, double scalingX, - double scalingY) { - final String? value = - PdfAutomaticFieldHelper.getHelper(this).getValue(graphics); + void _performDraw( + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { + final String? value = PdfAutomaticFieldHelper.getHelper( + this, + ).getValue(graphics); if (_list.containsKey(graphics)) { final PdfTemplateValuePair pair = _list[graphics]!; if (pair.value != value) { final Size size = PdfAutomaticFieldHelper.getHelper(this).obtainSize(); pair.template.reset(size.width, size.height); - pair.template.graphics!.drawString(value!, font, - pen: pen, - brush: brush, - bounds: Rect.fromLTWH(0, 0, size.width, size.height), - format: stringFormat); + pair.template.graphics!.drawString( + value!, + font, + pen: pen, + brush: brush, + bounds: Rect.fromLTWH(0, 0, size.width, size.height), + format: stringFormat, + ); } } else { final PdfTemplate template = PdfTemplate( - PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().height); + PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, + PdfAutomaticFieldHelper.getHelper(this).obtainSize().height, + ); _list[graphics] = PdfTemplateValuePair(template, value!); - template.graphics!.drawString(value, font, - pen: pen, - brush: brush, - bounds: Rect.fromLTWH( - 0, - 0, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().height), - format: stringFormat); - final Offset drawLocation = - Offset(location!.x + bounds.left, location.y + bounds.top); + template.graphics!.drawString( + value, + font, + pen: pen, + brush: brush, + bounds: Rect.fromLTWH( + 0, + 0, + PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, + PdfAutomaticFieldHelper.getHelper(this).obtainSize().height, + ), + format: stringFormat, + ); + final Offset drawLocation = Offset( + location!.x + bounds.left, + location.y + bounds.top, + ); graphics.drawPdfTemplate( - template, - drawLocation, - Size( - template.size.width * scalingX, template.size.height * scalingY)); + template, + drawLocation, + Size(template.size.width * scalingX, template.size.height * scalingY), + ); } } } @@ -62,8 +77,13 @@ abstract class PdfMultipleValueField extends PdfDynamicField { /// [PdfMultipleValueField] helper class PdfMultipleValueFieldHelper { /// internal method - static void performDraw(PdfMultipleValueField field, PdfGraphics graphics, - PdfPoint? location, double scalingX, double scalingY) { + static void performDraw( + PdfMultipleValueField field, + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { field._performDraw(graphics, location, scalingX, scalingY); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_count_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_count_field.dart index 7c76e88f8..467af91ca 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_count_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_count_field.dart @@ -93,9 +93,12 @@ class PdfPageCountField extends PdfSingleValueField { /// //Dispose the document. /// document.dispose(); /// ``` - PdfPageCountField( - {PdfFont? font, PdfBrush? brush, Rect? bounds, bool? isSectionPageCount}) - : super(font, brush, bounds) { + PdfPageCountField({ + PdfFont? font, + PdfBrush? brush, + Rect? bounds, + bool? isSectionPageCount, + }) : super(font, brush, bounds) { _isSectionPageCount = isSectionPageCount != null && isSectionPageCount; } @@ -153,11 +156,12 @@ class PdfPageCountField extends PdfSingleValueField { final int count = PdfSectionHelper.getHelper(section).count; return PdfAutomaticFieldHelper.convert(count, numberStyle); } else { - final PdfDocument document = PdfSectionCollectionHelper.getHelper( - PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(page).section!) - .parent!) - .document!; + final PdfDocument document = + PdfSectionCollectionHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).parent!, + ).document!; final int number = document.pages.count; return PdfAutomaticFieldHelper.convert(number, numberStyle); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_number_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_number_field.dart index c4bb78108..244c536b4 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_number_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_page_number_field.dart @@ -92,8 +92,12 @@ class PdfPageNumberField extends PdfMultipleValueField { /// //Dispose the document. /// document.dispose(); /// ``` - PdfPageNumberField( - {super.font, super.brush, super.bounds, bool? isSectionPageNumber}) { + PdfPageNumberField({ + super.font, + super.brush, + super.bounds, + bool? isSectionPageNumber, + }) { _helper = PdfPageNumberFieldHelper(this); _helper._isSectionPageNumber = isSectionPageNumber != null && isSectionPageNumber; @@ -175,11 +179,12 @@ class PdfPageNumberFieldHelper { final int index = PdfSectionHelper.getHelper(section).indexOf(page) + 1; return PdfAutomaticFieldHelper.convert(index, base.numberStyle); } else { - final PdfDocument document = PdfSectionCollectionHelper.getHelper( - PdfSectionHelper.getHelper( - PdfPageHelper.getHelper(page!).section!) - .parent!) - .document!; + final PdfDocument document = + PdfSectionCollectionHelper.getHelper( + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page!).section!, + ).parent!, + ).document!; final int pageIndex = document.pages.indexOf(page) + 1; return PdfAutomaticFieldHelper.convert(pageIndex, base.numberStyle); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_single_value_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_single_value_field.dart index 3d2d5b60f..35baa71d9 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_single_value_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_single_value_field.dart @@ -16,7 +16,7 @@ abstract class PdfSingleValueField extends PdfDynamicField { // constructor /// internal constructor PdfSingleValueField([PdfFont? font, PdfBrush? brush, Rect? bounds]) - : super(font: font, bounds: bounds, brush: brush); + : super(font: font, bounds: bounds, brush: brush); // field final Map _list = @@ -24,13 +24,18 @@ abstract class PdfSingleValueField extends PdfDynamicField { final List _painterGraphics = []; // implementation - void _performDraw(PdfGraphics graphics, PdfPoint? location, double scalingX, - double scalingY) { + void _performDraw( + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { if (PdfGraphicsHelper.getHelper(graphics).page is PdfPage) { final PdfPage page = PdfDynamicField.getPageFromGraphics(graphics); final PdfDocument? document = PdfPageHelper.getHelper(page).document; - final String? value = - PdfAutomaticFieldHelper.getHelper(this).getValue(graphics); + final String? value = PdfAutomaticFieldHelper.getHelper( + this, + ).getValue(graphics); if (_list.containsKey(document)) { final PdfTemplateValuePair pair = _list[document]!; @@ -38,42 +43,63 @@ abstract class PdfSingleValueField extends PdfDynamicField { final Size size = PdfAutomaticFieldHelper.getHelper(this).obtainSize(); pair.template.reset(size.width, size.height); - pair.template.graphics!.drawString(value!, font, - pen: pen, - brush: brush, - bounds: bounds.topLeft & size, - format: stringFormat); + pair.template.graphics!.drawString( + value!, + font, + pen: pen, + brush: brush, + bounds: bounds.topLeft & size, + format: stringFormat, + ); } if (!_painterGraphics.contains(graphics)) { - final Offset drawLocation = - Offset(location!.x + bounds.left, location.y + bounds.top); + final Offset drawLocation = Offset( + location!.x + bounds.left, + location.y + bounds.top, + ); graphics.drawPdfTemplate( - pair.template, - drawLocation, - Size(pair.template.size.width * scalingX, - pair.template.size.height * scalingY)); + pair.template, + drawLocation, + Size( + pair.template.size.width * scalingX, + pair.template.size.height * scalingY, + ), + ); _painterGraphics.add(graphics); } } else { final PdfTemplate template = PdfTemplate( - PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().height); + PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, + PdfAutomaticFieldHelper.getHelper(this).obtainSize().height, + ); _list[document] = PdfTemplateValuePair(template, value!); final PdfTemplateValuePair pair = _list[document]!; - template.graphics!.drawString(value, font, - pen: pen, - brush: brush, - bounds: Rect.fromLTWH( - bounds.left, bounds.top, bounds.width, bounds.height), - format: stringFormat); - final Offset drawLocation = - Offset(location!.x + bounds.left, location.y + bounds.top); + template.graphics!.drawString( + value, + font, + pen: pen, + brush: brush, + bounds: Rect.fromLTWH( + bounds.left, + bounds.top, + bounds.width, + bounds.height, + ), + format: stringFormat, + ); + final Offset drawLocation = Offset( + location!.x + bounds.left, + location.y + bounds.top, + ); graphics.drawPdfTemplate( - pair.template, - drawLocation, - Size(pair.template.size.width * scalingX, - pair.template.size.height * scalingY)); + pair.template, + drawLocation, + Size( + pair.template.size.width * scalingX, + pair.template.size.height * scalingY, + ), + ); _painterGraphics.add(graphics); } } @@ -84,8 +110,13 @@ abstract class PdfSingleValueField extends PdfDynamicField { /// [PdfSingleValueField] value class PdfSingleValueFieldHelper { /// internal method - static void performDraw(PdfSingleValueField field, PdfGraphics graphics, - PdfPoint? location, double scalingX, double scalingY) { + static void performDraw( + PdfSingleValueField field, + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { field._performDraw(graphics, location, scalingX, scalingY); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_static_field.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_static_field.dart index 7033a69af..709ac225b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_static_field.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/automatic_fields/pdf_static_field.dart @@ -21,39 +21,57 @@ abstract class PdfStaticField extends PdfAutomaticField { final List _graphicsList = []; // implementation - void _performDraw(PdfGraphics graphics, PdfPoint? location, double scalingX, - double scalingY) { - final String? value = - PdfAutomaticFieldHelper.getHelper(this).getValue(graphics); - final Offset drawLocation = - Offset(location!.x + bounds.left, location.y + bounds.top); + void _performDraw( + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { + final String? value = PdfAutomaticFieldHelper.getHelper( + this, + ).getValue(graphics); + final Offset drawLocation = Offset( + location!.x + bounds.left, + location.y + bounds.top, + ); if (_template == null) { _template = PdfTemplate( + PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, + PdfAutomaticFieldHelper.getHelper(this).obtainSize().height, + ); + _template!.graphics!.drawString( + value!, + font, + pen: pen, + brush: brush, + bounds: Rect.fromLTWH( + 0, + 0, PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().height); - _template!.graphics!.drawString(value!, font, - pen: pen, - brush: brush, - bounds: Rect.fromLTWH( - 0, - 0, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().width, - PdfAutomaticFieldHelper.getHelper(this).obtainSize().height), - format: stringFormat); + PdfAutomaticFieldHelper.getHelper(this).obtainSize().height, + ), + format: stringFormat, + ); graphics.drawPdfTemplate( - _template!, - drawLocation, - Size(_template!.size.width * scalingX, - _template!.size.height * scalingY)); + _template!, + drawLocation, + Size( + _template!.size.width * scalingX, + _template!.size.height * scalingY, + ), + ); _graphicsList.add(graphics); } else { if (!_graphicsList.contains(graphics)) { graphics.drawPdfTemplate( - _template!, - drawLocation, - Size(_template!.size.width * scalingX, - _template!.size.height * scalingY)); + _template!, + drawLocation, + Size( + _template!.size.width * scalingX, + _template!.size.height * scalingY, + ), + ); _graphicsList.add(graphics); } } @@ -64,8 +82,13 @@ abstract class PdfStaticField extends PdfAutomaticField { /// [PdfStaticField] helper class PdfStaticFieldHelper { /// internal method - static void performDraw(PdfStaticField staticField, PdfGraphics graphics, - PdfPoint? location, double scalingX, double scalingY) { + static void performDraw( + PdfStaticField staticField, + PdfGraphics graphics, + PdfPoint? location, + double scalingX, + double scalingY, + ) { staticField._performDraw(graphics, location, scalingX, scalingY); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/enums.dart index 05689556d..e20616b36 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/enums.dart @@ -25,7 +25,7 @@ enum PdfVersion { version1_7, /// PDF version 2.0. - version2_0 + version2_0, } /// Specifies the type of the PDF cross-reference. @@ -46,7 +46,7 @@ enum PdfCrossReferenceType { /// and a data stream. This leads to more compact representation of the file /// data especially along with the compression enabled. /// This format is supported by PDF 1.5 version and higher only. - crossReferenceStream + crossReferenceStream, } /// Specifies the PDF document's conformance-level. @@ -85,7 +85,7 @@ enum PdfAttachmentRelationship { supplement, ///Relationship is not known or cannot be described using one of the other values - unspecified + unspecified, } /// Compression level. @@ -106,5 +106,5 @@ enum PdfCompressionLevel { aboveNormal, /// Use best compression, slow enough - best + best, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/outlines/pdf_outline.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/outlines/pdf_outline.dart index c240a07c9..0fa9c5b2a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/outlines/pdf_outline.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/outlines/pdf_outline.dart @@ -40,18 +40,23 @@ import 'enums.dart'; class PdfBookmark extends PdfBookmarkBase { //Constructor /// Initializes a new instance of the [PdfBookmark] class. - PdfBookmark._internal(String title, PdfBookmarkBase parent, - PdfBookmark? previous, PdfBookmark? next, - {bool isExpanded = false, - PdfColor? color, - PdfDestination? destination, - PdfNamedDestination? namedDestination, - PdfAction? action, - List? textStyle}) - : super._internal() { + PdfBookmark._internal( + String title, + PdfBookmarkBase parent, + PdfBookmark? previous, + PdfBookmark? next, { + bool isExpanded = false, + PdfColor? color, + PdfDestination? destination, + PdfNamedDestination? namedDestination, + PdfAction? action, + List? textStyle, + }) : super._internal() { _parent = parent; _helper.dictionary!.setProperty( - PdfDictionaryProperties.parent, PdfReferenceHolder(parent)); + PdfDictionaryProperties.parent, + PdfReferenceHolder(parent), + ); _previous = previous; _next = next; this.title = title; @@ -74,7 +79,7 @@ class PdfBookmark extends PdfBookmarkBase { } PdfBookmark._load(super.dictionary, PdfCrossTable super.crossTable) - : super._load(); + : super._load(); //Fields /// Internal variable to store destination. @@ -358,7 +363,7 @@ class PdfBookmark extends PdfBookmarkBase { 252, 253, 254, - 255 + 255, ]; //Properties @@ -431,11 +436,17 @@ class PdfBookmark extends PdfBookmarkBase { _namedDestination = value; final PdfDictionary dictionary = PdfDictionary(); dictionary.setProperty( - PdfDictionaryProperties.d, PdfString(_namedDestination!.title)); + PdfDictionaryProperties.d, + PdfString(_namedDestination!.title), + ); dictionary.setProperty( - PdfDictionaryProperties.s, PdfName(PdfDictionaryProperties.goTo)); + PdfDictionaryProperties.s, + PdfName(PdfDictionaryProperties.goTo), + ); dictionary.setProperty( - PdfDictionaryProperties.a, PdfReferenceHolder(dictionary)); + PdfDictionaryProperties.a, + PdfReferenceHolder(dictionary), + ); } } @@ -565,8 +576,10 @@ class PdfBookmark extends PdfBookmarkBase { set action(PdfAction? value) { if (value != null && _action != value) { _action = value; - _helper.dictionary!.setProperty(PdfDictionaryProperties.a, - PdfReferenceHolder(PdfActionHelper.getHelper(_action!).dictionary)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.a, + PdfReferenceHolder(PdfActionHelper.getHelper(_action!).dictionary), + ); } } @@ -603,8 +616,10 @@ class PdfBookmark extends PdfBookmarkBase { set _previous(PdfBookmark? value) { if (_previousBookmark != value) { _previousBookmark = value; - _helper.dictionary! - .setProperty(PdfDictionaryProperties.prev, PdfReferenceHolder(value)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.prev, + PdfReferenceHolder(value), + ); } } @@ -621,8 +636,10 @@ class PdfBookmark extends PdfBookmarkBase { set _next(PdfBookmark? value) { if (_nextBookmark != value) { _nextBookmark = value; - _helper.dictionary! - .setProperty(PdfDictionaryProperties.next, PdfReferenceHolder(value)); + _helper.dictionary!.setProperty( + PdfDictionaryProperties.next, + PdfReferenceHolder(value), + ); } } @@ -646,8 +663,9 @@ class PdfBookmark extends PdfBookmarkBase { if (array != null && _color.isEmpty) { _helper.dictionary!.remove(PdfDictionaryProperties.c); } else { - _helper.dictionary![PdfDictionaryProperties.c] = - PdfColorHelper.toArray(_color); + _helper.dictionary![PdfDictionaryProperties.c] = PdfColorHelper.toArray( + _color, + ); } } @@ -667,17 +685,22 @@ class PdfBookmark extends PdfBookmarkBase { String _obtainTitle() { String title = ''; if (_helper.dictionary!.containsKey(PdfDictionaryProperties.title)) { - final PdfString? str = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.title]) as PdfString?; + final PdfString? str = + PdfCrossTable.dereference( + _helper.dictionary![PdfDictionaryProperties.title], + ) + as PdfString?; if (str != null && str.value != null) { title = str.value!; if (_regex.hasMatch(title)) { for (int i = 0; i < title.length; i++) { if (_regex.hasMatch(title[i])) { title = title.replaceAll( - title[i], - String.fromCharCode( - _pdfEncodingByteToChar[title.codeUnitAt(i) & 0xff])); + title[i], + String.fromCharCode( + _pdfEncodingByteToChar[title.codeUnitAt(i) & 0xff], + ), + ); } } } @@ -689,8 +712,11 @@ class PdfBookmark extends PdfBookmarkBase { PdfColor _obtainColor() { PdfColor color = PdfColor(0, 0, 0); if (_helper.dictionary!.containsKey(PdfDictionaryProperties.c)) { - final PdfArray? colours = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.c]) as PdfArray?; + final PdfArray? colours = + PdfCrossTable.dereference( + _helper.dictionary![PdfDictionaryProperties.c], + ) + as PdfArray?; if (colours != null && colours.count > 2) { double? red = 0; double green = 0; @@ -717,8 +743,11 @@ class PdfBookmark extends PdfBookmarkBase { PdfTextStyle _obtainTextStyle() { PdfTextStyle style = PdfTextStyle.regular; if (_helper.dictionary!.containsKey(PdfDictionaryProperties.f)) { - final PdfNumber? flag = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.f]) as PdfNumber?; + final PdfNumber? flag = + PdfCrossTable.dereference( + _helper.dictionary![PdfDictionaryProperties.f], + ) + as PdfNumber?; int flagValue = 0; if (flag != null) { flagValue = flag.value!.toInt() - 1; @@ -736,9 +765,11 @@ class PdfBookmark extends PdfBookmarkBase { nextBookmark = _parent!._list[index] as PdfBookmark?; } else { if (_helper.dictionary!.containsKey(PdfDictionaryProperties.next)) { - final PdfDictionary? next = _helper._crossTable - .getObject(_helper.dictionary![PdfDictionaryProperties.next]) - as PdfDictionary?; + final PdfDictionary? next = + _helper._crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.next], + ) + as PdfDictionary?; nextBookmark = PdfBookmark._load(next, _helper._crossTable); } } @@ -753,9 +784,11 @@ class PdfBookmark extends PdfBookmarkBase { prevBookmark = _helper._bookmarkList[index] as PdfBookmark?; } else { if (_helper.dictionary!.containsKey(PdfDictionaryProperties.prev)) { - final PdfDictionary? prev = _helper._crossTable - .getObject(_helper.dictionary![PdfDictionaryProperties.prev]) - as PdfDictionary?; + final PdfDictionary? prev = + _helper._crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.prev], + ) + as PdfDictionary?; prevBookmark = PdfBookmark._load(prev, _helper._crossTable); } } @@ -766,7 +799,7 @@ class PdfBookmark extends PdfBookmarkBase { final List rgb = [ color.r.toDouble(), color.g.toDouble(), - color.b.toDouble() + color.b.toDouble(), ]; final PdfArray colors = PdfArray(rgb); _helper.dictionary!.setProperty(PdfDictionaryProperties.c, colors); @@ -790,16 +823,22 @@ class PdfBookmark extends PdfBookmarkBase { IPdfPrimitive? destination; if (namedCollection != null) { if (_helper.dictionary!.containsKey(PdfDictionaryProperties.a)) { - final PdfDictionary? action = PdfCrossTable.dereference( - _helper.dictionary![PdfDictionaryProperties.a]) as PdfDictionary?; + final PdfDictionary? action = + PdfCrossTable.dereference( + _helper.dictionary![PdfDictionaryProperties.a], + ) + as PdfDictionary?; if (action != null && action.containsKey(PdfDictionaryProperties.d)) { - destination = - PdfCrossTable.dereference(action[PdfDictionaryProperties.d]); + destination = PdfCrossTable.dereference( + action[PdfDictionaryProperties.d], + ); } - } else if (_helper.dictionary! - .containsKey(PdfDictionaryProperties.dest)) { - destination = _helper._crossTable - .getObject(_helper.dictionary![PdfDictionaryProperties.dest]); + } else if (_helper.dictionary!.containsKey( + PdfDictionaryProperties.dest, + )) { + destination = _helper._crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.dest], + ); } if (destination != null) { @@ -828,8 +867,9 @@ class PdfBookmark extends PdfBookmarkBase { PdfDestination? _obtainDestination() { if (_helper.dictionary!.containsKey(PdfDictionaryProperties.dest) && (_destination == null)) { - final IPdfPrimitive? obj = _helper._crossTable - .getObject(_helper.dictionary![PdfDictionaryProperties.dest]); + final IPdfPrimitive? obj = _helper._crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.dest], + ); PdfArray? array = obj as PdfArray?; final PdfName? name = (obj is PdfName) ? obj as PdfName? : null; final PdfDocument? ldDoc = _helper._crossTable.document; @@ -867,17 +907,22 @@ class PdfBookmark extends PdfBookmarkBase { zoom = array[4]; } if (page != null) { - final double topValue = (top != null && top is PdfNumber) - ? page.size.height - top.value! - : 0; - final double leftValue = (left != null && left is PdfNumber) - ? left.value! as double - : 0; - _destination = - PdfDestination(page, Offset(leftValue, topValue)); - _destination!.zoom = (zoom != null && zoom is PdfNumber) - ? zoom.value!.toDouble() - : 0; + final double topValue = + (top != null && top is PdfNumber) + ? page.size.height - top.value! + : 0; + final double leftValue = + (left != null && left is PdfNumber) + ? left.value! as double + : 0; + _destination = PdfDestination( + page, + Offset(leftValue, topValue), + ); + _destination!.zoom = + (zoom != null && zoom is PdfNumber) + ? zoom.value!.toDouble() + : 0; } } else { if (mode.name == PdfDictionaryProperties.fitR) { @@ -899,20 +944,22 @@ class PdfBookmark extends PdfBookmarkBase { } if (page != null) { _destination = PdfDestinationHelper.getDestination( - page, - PdfRectangle( - (left != null && left is PdfNumber) - ? left.value!.toDouble() - : 0, - (bottom != null && bottom is PdfNumber) - ? bottom.value!.toDouble() - : 0, - (right != null && right is PdfNumber) - ? right.value!.toDouble() - : 0, - (top != null && top is PdfNumber) - ? top.value!.toDouble() - : 0)); + page, + PdfRectangle( + (left != null && left is PdfNumber) + ? left.value!.toDouble() + : 0, + (bottom != null && bottom is PdfNumber) + ? bottom.value!.toDouble() + : 0, + (right != null && right is PdfNumber) + ? right.value!.toDouble() + : 0, + (top != null && top is PdfNumber) + ? top.value!.toDouble() + : 0, + ), + ); _destination!.mode = PdfDestinationMode.fitR; } } else if (mode.name == PdfDictionaryProperties.fitBH || @@ -922,9 +969,10 @@ class PdfBookmark extends PdfBookmarkBase { top = array[2]; } if (page != null) { - final double topValue = (top != null && top is PdfNumber) - ? page.size.height - top.value! - : 0; + final double topValue = + (top != null && top is PdfNumber) + ? page.size.height - top.value! + : 0; _destination = PdfDestination(page, Offset(0, topValue)); _destination!.mode = PdfDestinationMode.fitH; } @@ -945,8 +993,9 @@ class PdfBookmark extends PdfBookmarkBase { } } else if (_helper.dictionary!.containsKey(PdfDictionaryProperties.a) && (_destination == null)) { - IPdfPrimitive? obj = _helper._crossTable - .getObject(_helper.dictionary![PdfDictionaryProperties.a]); + IPdfPrimitive? obj = _helper._crossTable.getObject( + _helper.dictionary![PdfDictionaryProperties.a], + ); PdfDictionary? destDic; if (obj is PdfDictionary) { destDic = obj; @@ -986,9 +1035,10 @@ class PdfBookmark extends PdfBookmarkBase { top = array[2]; } if (page != null) { - final double topValue = (top != null && top is PdfNumber) - ? page.size.height - top.value! - : 0; + final double topValue = + (top != null && top is PdfNumber) + ? page.size.height - top.value! + : 0; _destination = PdfDestination(page, Offset(0, topValue)); _destination!.mode = PdfDestinationMode.fitH; } @@ -1006,16 +1056,19 @@ class PdfBookmark extends PdfBookmarkBase { zoom = array[4]; } if (page != null) { - final double topValue = (top != null && top is PdfNumber) - ? page.size.height - top.value! - : 0; - final double leftValue = (left != null && left is PdfNumber) - ? left.value! as double - : 0; + final double topValue = + (top != null && top is PdfNumber) + ? page.size.height - top.value! + : 0; + final double leftValue = + (left != null && left is PdfNumber) + ? left.value! as double + : 0; _destination = PdfDestination(page, Offset(leftValue, topValue)); - _destination!.zoom = (zoom != null && zoom is PdfNumber) - ? zoom.value!.toDouble() - : 0; + _destination!.zoom = + (zoom != null && zoom is PdfNumber) + ? zoom.value!.toDouble() + : 0; } } else { if (page != null && mode.name == PdfDictionaryProperties.fit) { @@ -1169,16 +1222,22 @@ class PdfBookmarkBase implements IPdfWrapper { /// //Dispose the document. /// document.dispose(); /// ``` - PdfBookmark add(String title, - {bool isExpanded = false, - PdfColor? color, - PdfDestination? destination, - PdfNamedDestination? namedDestination, - PdfAction? action, - List? textStyle}) { + PdfBookmark add( + String title, { + bool isExpanded = false, + PdfColor? color, + PdfDestination? destination, + PdfNamedDestination? namedDestination, + PdfAction? action, + List? textStyle, + }) { final PdfBookmark? previous = (count < 1) ? null : this[count - 1]; - final PdfBookmark outline = - PdfBookmark._internal(title, this, previous, null); + final PdfBookmark outline = PdfBookmark._internal( + title, + this, + previous, + null, + ); if (previous != null) { previous._next = outline; } @@ -1265,10 +1324,13 @@ class PdfBookmarkBase implements IPdfWrapper { } final PdfBookmark current = _bookmark![index]; if (index == 0) { - if (current._helper.dictionary! - .containsKey(PdfDictionaryProperties.next)) { - _helper.dictionary!.setProperty(PdfDictionaryProperties.first, - current._helper.dictionary![PdfDictionaryProperties.next]); + if (current._helper.dictionary!.containsKey( + PdfDictionaryProperties.next, + )) { + _helper.dictionary!.setProperty( + PdfDictionaryProperties.first, + current._helper.dictionary![PdfDictionaryProperties.next], + ); } else { _helper.dictionary!.remove(PdfDictionaryProperties.first); _helper.dictionary!.remove(PdfDictionaryProperties.last); @@ -1277,19 +1339,23 @@ class PdfBookmarkBase implements IPdfWrapper { (current._previous != null) && (current._next != null)) { current._previous!._helper.dictionary!.setProperty( - PdfDictionaryProperties.next, - current._helper.dictionary![PdfDictionaryProperties.next]); + PdfDictionaryProperties.next, + current._helper.dictionary![PdfDictionaryProperties.next], + ); current._next!._helper.dictionary!.setProperty( - PdfDictionaryProperties.prev, - current._helper.dictionary![PdfDictionaryProperties.prev]); + PdfDictionaryProperties.prev, + current._helper.dictionary![PdfDictionaryProperties.prev], + ); } else if ((current._parent != null) && (current._previous != null) && (current._next == null)) { - current._previous!._helper.dictionary! - .remove(PdfDictionaryProperties.next); + current._previous!._helper.dictionary!.remove( + PdfDictionaryProperties.next, + ); current._parent!._helper.dictionary!.setProperty( - PdfDictionaryProperties.last, - current._helper.dictionary![PdfDictionaryProperties.prev]); + PdfDictionaryProperties.last, + current._helper.dictionary![PdfDictionaryProperties.prev], + ); } if (current._parent != null) { current._parent!._list.remove(current); @@ -1362,9 +1428,13 @@ class PdfBookmarkBase implements IPdfWrapper { final int newCount = _isExpanded ? _list.length : -_list.length; _helper.dictionary![PdfDictionaryProperties.count] = PdfNumber(newCount); _helper.dictionary!.setProperty( - PdfDictionaryProperties.first, PdfReferenceHolder(this[0])); + PdfDictionaryProperties.first, + PdfReferenceHolder(this[0]), + ); _helper.dictionary!.setProperty( - PdfDictionaryProperties.last, PdfReferenceHolder(this[count - 1])); + PdfDictionaryProperties.last, + PdfReferenceHolder(this[count - 1]), + ); } else { _helper.dictionary!.clear(); } @@ -1380,21 +1450,30 @@ class PdfBookmarkBase implements IPdfWrapper { /// [PdfBookmark] helper class PdfBookmarkHelper { /// internal method - static PdfBookmark internal(String title, PdfBookmarkBase parent, - PdfBookmark? previous, PdfBookmark? next, - {bool isExpanded = false, - PdfColor? color, - PdfDestination? destination, - PdfNamedDestination? namedDestination, - PdfAction? action, - List? textStyle}) { - return PdfBookmark._internal(title, parent, previous, next, - isExpanded: isExpanded, - color: color, - destination: destination, - namedDestination: namedDestination, - action: action, - textStyle: textStyle); + static PdfBookmark internal( + String title, + PdfBookmarkBase parent, + PdfBookmark? previous, + PdfBookmark? next, { + bool isExpanded = false, + PdfColor? color, + PdfDestination? destination, + PdfNamedDestination? namedDestination, + PdfAction? action, + List? textStyle, + }) { + return PdfBookmark._internal( + title, + parent, + previous, + next, + isExpanded: isExpanded, + color: color, + destination: destination, + namedDestination: namedDestination, + action: action, + textStyle: textStyle, + ); } /// internal method @@ -1439,7 +1518,9 @@ class PdfBookmarkBaseHelper { /// internal method static PdfBookmarkBase loaded( - PdfDictionary? dictionary, PdfCrossTable crossTable) { + PdfDictionary? dictionary, + PdfCrossTable crossTable, + ) { return PdfBookmarkBase._load(dictionary, crossTable); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog.dart index e13acf475..a92930328 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog.dart @@ -25,10 +25,11 @@ class PdfCatalog extends PdfDictionary { /// internal constructor PdfCatalog.fromDocument(PdfDocument this.document, PdfDictionary? catalog) - : super(catalog) { + : super(catalog) { if (containsKey(PdfDictionaryProperties.names)) { - final IPdfPrimitive? obj = - PdfCrossTable.dereference(this[PdfDictionaryProperties.names]); + final IPdfPrimitive? obj = PdfCrossTable.dereference( + this[PdfDictionaryProperties.names], + ); if (obj is PdfDictionary) { _catalogNames = PdfCatalogNames(obj); } @@ -60,8 +61,9 @@ class PdfCatalog extends PdfDictionary { PdfDictionary? get destinations { PdfDictionary? dests; if (containsKey(PdfDictionaryProperties.dests)) { - dests = PdfCrossTable.dereference(this[PdfDictionaryProperties.dests]) - as PdfDictionary?; + dests = + PdfCrossTable.dereference(this[PdfDictionaryProperties.dests]) + as PdfDictionary?; } return dests; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog_names.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog_names.dart index 282f7bdf9..009da509e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog_names.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_catalog_names.dart @@ -34,8 +34,9 @@ class PdfCatalogNames implements IPdfWrapper { //Gets the destinations. /// internal property PdfDictionary? get destinations { - final IPdfPrimitive? obj = - PdfCrossTable.dereference(dictionary![PdfDictionaryProperties.dests]); + final IPdfPrimitive? obj = PdfCrossTable.dereference( + dictionary![PdfDictionaryProperties.dests], + ); final PdfDictionary? dests = obj as PdfDictionary?; return dests; } @@ -45,8 +46,10 @@ class PdfCatalogNames implements IPdfWrapper { set embeddedFiles(PdfAttachmentCollection value) { if (_attachments != value) { _attachments = value; - dictionary!.setProperty(PdfDictionaryProperties.embeddedFiles, - PdfReferenceHolder(_attachments)); + dictionary!.setProperty( + PdfDictionaryProperties.embeddedFiles, + PdfReferenceHolder(_attachments), + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document.dart index 7fd2c6bb6..d620f3d3a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document.dart @@ -1,5 +1,6 @@ import 'dart:collection'; import 'dart:convert'; +import 'dart:typed_data'; import 'package:xml/xml.dart'; @@ -81,10 +82,11 @@ class PdfDocument { /// //Dispose the document. /// document.dispose(); /// ``` - PdfDocument( - {List? inputBytes, - PdfConformanceLevel? conformanceLevel, - String? password}) { + PdfDocument({ + List? inputBytes, + PdfConformanceLevel? conformanceLevel, + String? password, + }) { _helper = PdfDocumentHelper(this); _helper.isLoadedDocument = inputBytes != null; _helper.password = password; @@ -344,10 +346,13 @@ class PdfDocument { if (_bookmark == null) { if (_helper.catalog.containsKey(PdfDictionaryProperties.outlines)) { final IPdfPrimitive? outlines = PdfCrossTable.dereference( - _helper.catalog[PdfDictionaryProperties.outlines]); + _helper.catalog[PdfDictionaryProperties.outlines], + ); if (outlines != null && outlines is PdfDictionary) { - _bookmark = - PdfBookmarkBaseHelper.loaded(outlines, _helper.crossTable); + _bookmark = PdfBookmarkBaseHelper.loaded( + outlines, + _helper.crossTable, + ); PdfBookmarkBaseHelper.getHelper(_bookmark!).reproduceTree(); } else { _bookmark = _createBookmarkRoot(); @@ -360,8 +365,9 @@ class PdfDocument { } else { if (_outlines == null) { _outlines = PdfBookmarkBaseHelper.loadInternal(); - _helper.catalog[PdfDictionaryProperties.outlines] = - PdfReferenceHolder(_outlines); + _helper.catalog[PdfDictionaryProperties.outlines] = PdfReferenceHolder( + _outlines, + ); } return _outlines!; } @@ -373,10 +379,15 @@ class PdfDocument { if (_namedDestinations == null) { if (_helper.catalog.containsKey(PdfDictionaryProperties.names) && (_namedDestinations == null)) { - final PdfDictionary? namedDestinations = PdfCrossTable.dereference( - _helper.catalog[PdfDictionaryProperties.names]) as PdfDictionary?; + final PdfDictionary? namedDestinations = + PdfCrossTable.dereference( + _helper.catalog[PdfDictionaryProperties.names], + ) + as PdfDictionary?; _namedDestinations = PdfNamedDestinationCollectionHelper.load( - namedDestinations, _helper.crossTable); + namedDestinations, + _helper.crossTable, + ); } _namedDestinations ??= _createNamedDestinations(); } @@ -384,15 +395,18 @@ class PdfDocument { } else { if (_namedDestinations == null) { _namedDestinations = PdfNamedDestinationCollection(); - _helper.catalog[PdfDictionaryProperties.names] = - PdfReferenceHolder(_namedDestinations); - final PdfReferenceHolder? names = _helper - .catalog[PdfDictionaryProperties.names] as PdfReferenceHolder?; + _helper.catalog[PdfDictionaryProperties.names] = PdfReferenceHolder( + _namedDestinations, + ); + final PdfReferenceHolder? names = + _helper.catalog[PdfDictionaryProperties.names] + as PdfReferenceHolder?; if (names != null) { final PdfDictionary? dic = names.object as PdfDictionary?; if (dic != null) { - dic[PdfDictionaryProperties.dests] = - PdfReferenceHolder(_namedDestinations); + dic[PdfDictionaryProperties.dests] = PdfReferenceHolder( + _namedDestinations, + ); } } } @@ -410,23 +424,29 @@ class PdfDocument { final PdfDictionary? entry = PdfCrossTable.dereference(trailer[PdfDictionaryProperties.info]) as PdfDictionary?; - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - dictionary: entry, - isLoaded: true, - conformance: _helper.conformanceLevel); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + dictionary: entry, + isLoaded: true, + conformance: _helper.conformanceLevel, + ); } else { - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - conformance: _helper.conformanceLevel); - _helper.crossTable.trailer![PdfDictionaryProperties.info] = - PdfReferenceHolder(_documentInfo); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + conformance: _helper.conformanceLevel, + ); + _helper.crossTable.trailer![PdfDictionaryProperties + .info] = PdfReferenceHolder(_documentInfo); } // Read document's info dictionary if present. _readDocumentInfo(); } else { - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - conformance: _helper.conformanceLevel); - _helper.crossTable.trailer![PdfDictionaryProperties.info] = - PdfReferenceHolder(_documentInfo); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + conformance: _helper.conformanceLevel, + ); + _helper.crossTable.trailer![PdfDictionaryProperties + .info] = PdfReferenceHolder(_documentInfo); } } return _documentInfo!; @@ -459,13 +479,17 @@ class PdfDocument { _helper.checkEncryption(_helper._isAttachOnlyEncryption); } final IPdfPrimitive? attachmentDictionary = PdfCrossTable.dereference( - _helper.catalog[PdfDictionaryProperties.names]); + _helper.catalog[PdfDictionaryProperties.names], + ); if (attachmentDictionary != null && attachmentDictionary is PdfDictionary && - attachmentDictionary - .containsKey(PdfDictionaryProperties.embeddedFiles)) { + attachmentDictionary.containsKey( + PdfDictionaryProperties.embeddedFiles, + )) { _attachments = PdfAttachmentCollectionHelper.load( - attachmentDictionary, _helper.crossTable); + attachmentDictionary, + _helper.crossTable, + ); } else { _attachments = PdfAttachmentCollection(); _helper.catalog.names!.embeddedFiles = _attachments!; @@ -481,7 +505,8 @@ class PdfDocument { if (_form == null) { if (_helper.catalog.containsKey(PdfDictionaryProperties.acroForm)) { final IPdfPrimitive? formDictionary = PdfCrossTable.dereference( - _helper.catalog[PdfDictionaryProperties.acroForm]); + _helper.catalog[PdfDictionaryProperties.acroForm], + ); if (formDictionary is PdfDictionary) { _form = PdfFormHelper.internal(_helper.crossTable, formDictionary); if (_form != null && _form!.fields.count != 0) { @@ -489,52 +514,76 @@ class PdfDocument { List? widgetReference; if (PdfFormHelper.getHelper(_form!).crossTable!.document != null) { - for (int i = 0; - i < - PdfFormHelper.getHelper(_form!) - .crossTable! - .document! - .pages - .count; - i++) { - final PdfPage page = PdfFormHelper.getHelper(_form!) - .crossTable! - .document! - .pages[i]; + for ( + int i = 0; + i < + PdfFormHelper.getHelper( + _form!, + ).crossTable!.document!.pages.count; + i++ + ) { + final PdfPage page = + PdfFormHelper.getHelper( + _form!, + ).crossTable!.document!.pages[i]; widgetReference ??= PdfPageHelper.getHelper(page).getWidgetReferences(); if (widgetReference.isNotEmpty) { - PdfPageHelper.getHelper(page) - .createAnnotations(widgetReference); + PdfPageHelper.getHelper( + page, + ).createAnnotations(widgetReference); } } if (widgetReference != null) { widgetReference.clear(); } if (!PdfFormHelper.getHelper(_form!).formHasKids) { - PdfFormFieldCollectionHelper.getHelper(_form!.fields) - .createFormFieldsFromWidgets(_form!.fields.count); + PdfFormFieldCollectionHelper.getHelper( + _form!.fields, + ).createFormFieldsFromWidgets(_form!.fields.count); } } } + return _form!; } - } else { - _form = PdfFormHelper.internal(_helper.crossTable); - _helper.catalog.setProperty( - PdfDictionaryProperties.acroForm, PdfReferenceHolder(_form)); - _helper.catalog.form = _form; - return _form!; } + _form = PdfFormHelper.internal(_helper.crossTable); + _helper.catalog.setProperty( + PdfDictionaryProperties.acroForm, + PdfReferenceHolder(_form), + ); + _helper.catalog.form = _form; + return _form!; } else { return _form!; } } else { return _helper.catalog.form ??= PdfForm(); } - return _form!; } //Public methods + /// Saves the document and return the saved bytes as Uint8List. + /// ```dart + /// //Create a PDF document instance. + /// PdfDocument document = PdfDocument(); + /// //Get the page and draw text. + /// document.pages.add().graphics.drawString( + /// 'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 12), + /// brush: PdfBrushes.black, bounds: Rect.fromLTWH(0, 0, 0, 0)); + /// //Save and dispose document. + /// Uint8List bytes = document.saveAsBytesSync(); + /// document.dispose(); + /// ``` + Uint8List saveAsBytesSync() { + final PdfBytesBuilder buffer = PdfBytesBuilder(); + final PdfWriter writer = PdfWriter(null, buffer); + _saveDocument(writer); + final Uint8List bytes = buffer.takeBytes(); + buffer.clear(); + return bytes; + } + /// Saves the document and return the saved bytes as list of int. /// /// ```dart @@ -551,16 +600,25 @@ class PdfDocument { List saveSync() { final List buffer = []; final PdfWriter writer = PdfWriter(buffer); + _saveDocument(writer); + return writer.buffer!; + } + + /// Internal method to save the PDF document. + void _saveDocument(PdfWriter writer) { writer.document = this; _checkPages(); if (_helper.isLoadedDocument && _bookmark != null && _bookmark!.count > 0 && _helper.crossTable.documentCatalog != null && - !_helper.crossTable.documentCatalog! - .containsKey(PdfDictionaryProperties.outlines)) { + !_helper.crossTable.documentCatalog!.containsKey( + PdfDictionaryProperties.outlines, + )) { _helper.catalog.setProperty( - PdfDictionaryProperties.outlines, PdfReferenceHolder(_bookmark)); + PdfDictionaryProperties.outlines, + PdfReferenceHolder(_bookmark), + ); } else if (_bookmark != null && _bookmark!.count < 1 && _helper.catalog.containsKey(PdfDictionaryProperties.outlines)) { @@ -569,17 +627,18 @@ class PdfDocument { if (PdfSecurityHelper.getHelper(security).encryptAttachments && security.userPassword == '') { throw ArgumentError.value( - 'User password cannot be empty for encrypt only attachment.'); + 'User password cannot be empty for encrypt only attachment.', + ); } if (_helper.isLoadedDocument) { if (_helper._security != null) { - if (PdfSecurityHelper.getHelper(_helper._security!) - .encryptAttachments) { + if (PdfSecurityHelper.getHelper( + _helper._security!, + ).encryptAttachments) { fileStructure.incrementalUpdate = false; - if (PdfSecurityHelper.getHelper(_helper._security!) - .encryptor - .userPassword - .isEmpty) { + if (PdfSecurityHelper.getHelper( + _helper._security!, + ).encryptor.userPassword.isEmpty) { PdfSecurityHelper.getHelper(_helper._security!) .encryptor .encryptOnlyAttachment = false; @@ -589,22 +648,25 @@ class PdfDocument { if (fileStructure.incrementalUpdate && (_helper._security == null || (_helper._security != null && - !PdfSecurityHelper.getHelper(_helper._security!) - .modifiedSecurity && + !PdfSecurityHelper.getHelper( + _helper._security!, + ).modifiedSecurity && !PdfPermissionsHelper.isModifiedPermissions( - _helper._security!.permissions)))) { + _helper._security!.permissions, + )))) { _copyOldStream(writer); if (_helper.catalog.changed!) { _readDocumentInfo(); } } else { _helper.crossTable = PdfCrossTable.fromCatalog( - _helper.crossTable.count, - _helper.crossTable.encryptorDictionary, - _helper.crossTable.pdfDocumentCatalog); + _helper.crossTable.count, + _helper.crossTable.encryptorDictionary, + _helper.crossTable.pdfDocumentCatalog, + ); _helper.crossTable.document = this; - _helper.crossTable.trailer![PdfDictionaryProperties.info] = - PdfReferenceHolder(documentInformation); + _helper.crossTable.trailer![PdfDictionaryProperties + .info] = PdfReferenceHolder(documentInformation); } _appendDocument(writer); } else { @@ -615,21 +677,25 @@ class PdfDocument { if (_helper.conformanceLevel == PdfConformanceLevel.a3b && _helper.catalog.names != null && attachments.count > 0) { - final PdfName fileRelationShip = - PdfName(PdfDictionaryProperties.afRelationship); + final PdfName fileRelationShip = PdfName( + PdfDictionaryProperties.afRelationship, + ); final PdfArray fileAttachmentAssociationArray = PdfArray(); for (int i = 0; i < attachments.count; i++) { - if (!PdfFileSpecificationBaseHelper.getHelper(attachments[i]) - .dictionary! - .items! - .containsKey(fileRelationShip)) { - PdfFileSpecificationBaseHelper.getHelper(attachments[i]) - .dictionary! - .items![fileRelationShip] = PdfName('Alternative'); + if (!PdfFileSpecificationBaseHelper.getHelper( + attachments[i], + ).dictionary!.items!.containsKey(fileRelationShip)) { + PdfFileSpecificationBaseHelper.getHelper( + attachments[i], + ).dictionary!.items![fileRelationShip] = PdfName('Alternative'); } - fileAttachmentAssociationArray.add(PdfReferenceHolder( - PdfFileSpecificationBaseHelper.getHelper(attachments[i]) - .dictionary)); + fileAttachmentAssociationArray.add( + PdfReferenceHolder( + PdfFileSpecificationBaseHelper.getHelper( + attachments[i], + ).dictionary, + ), + ); } _helper.catalog.items![PdfName(PdfDictionaryProperties.af)] = fileAttachmentAssociationArray; @@ -639,7 +705,27 @@ class PdfDocument { final DocumentSavedArgs argsSaved = DocumentSavedArgs(writer); _onDocumentSaved(argsSaved); } - return writer.buffer!; + } + + /// Saves the document and return the saved bytes as feature Uint8List. + /// ```dart + /// //Create a PDF document instance. + /// PdfDocument document = PdfDocument(); + /// //Get the page and draw text. + /// document.pages.add().graphics.drawString( + /// 'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 12), + /// brush: PdfBrushes.black, bounds: Rect.fromLTWH(0, 0, 0, 0)); + /// //Save and dispose document. + /// Uint8List bytes = await document.saveAsBytes(); + /// document.dispose(); + /// ``` + Future saveAsBytes() async { + final PdfBytesBuilder buffer = PdfBytesBuilder(); + final PdfWriter writer = PdfWriter(null, buffer); + await _saveDocumentAsync(writer); + final Uint8List bytes = buffer.takeBytes(); + buffer.clear(); + return bytes; } /// Saves the document and return the saved bytes as future list of int. @@ -657,16 +743,25 @@ class PdfDocument { Future> save() async { final List buffer = []; final PdfWriter writer = PdfWriter(buffer); + await _saveDocumentAsync(writer); + return writer.buffer!; + } + + /// Internal method to save the PDF document + Future _saveDocumentAsync(PdfWriter writer) async { writer.document = this; await _checkPagesAsync(); if (_helper.isLoadedDocument && _bookmark != null && _bookmark!.count > 0 && _helper.crossTable.documentCatalog != null && - !_helper.crossTable.documentCatalog! - .containsKey(PdfDictionaryProperties.outlines)) { + !_helper.crossTable.documentCatalog!.containsKey( + PdfDictionaryProperties.outlines, + )) { _helper.catalog.setProperty( - PdfDictionaryProperties.outlines, PdfReferenceHolder(_bookmark)); + PdfDictionaryProperties.outlines, + PdfReferenceHolder(_bookmark), + ); } else if (_outlines != null && _outlines!.count < 1 && _helper.catalog.containsKey(PdfDictionaryProperties.outlines)) { @@ -675,17 +770,18 @@ class PdfDocument { if (PdfSecurityHelper.getHelper(security).encryptAttachments && security.userPassword == '') { throw ArgumentError.value( - 'User password cannot be empty for encrypt only attachment.'); + 'User password cannot be empty for encrypt only attachment.', + ); } if (_helper.isLoadedDocument) { if (_helper._security != null) { - if (PdfSecurityHelper.getHelper(_helper._security!) - .encryptAttachments) { + if (PdfSecurityHelper.getHelper( + _helper._security!, + ).encryptAttachments) { fileStructure.incrementalUpdate = false; - if (PdfSecurityHelper.getHelper(_helper._security!) - .encryptor - .userPassword - .isEmpty) { + if (PdfSecurityHelper.getHelper( + _helper._security!, + ).encryptor.userPassword.isEmpty) { PdfSecurityHelper.getHelper(_helper._security!) .encryptor .encryptOnlyAttachment = false; @@ -695,10 +791,12 @@ class PdfDocument { if (fileStructure.incrementalUpdate && (_helper._security == null || (_helper._security != null && - !PdfSecurityHelper.getHelper(_helper._security!) - .modifiedSecurity && + !PdfSecurityHelper.getHelper( + _helper._security!, + ).modifiedSecurity && !PdfPermissionsHelper.isModifiedPermissions( - _helper._security!.permissions)))) { + _helper._security!.permissions, + )))) { await _copyOldStreamAsync(writer).then((_) { if (_helper.catalog.changed!) { _readDocumentInfoAsync(); @@ -706,12 +804,13 @@ class PdfDocument { }); } else { _helper.crossTable = PdfCrossTable.fromCatalog( - _helper.crossTable.count, - _helper.crossTable.encryptorDictionary, - _helper.crossTable.pdfDocumentCatalog); + _helper.crossTable.count, + _helper.crossTable.encryptorDictionary, + _helper.crossTable.pdfDocumentCatalog, + ); _helper.crossTable.document = this; - _helper.crossTable.trailer![PdfDictionaryProperties.info] = - PdfReferenceHolder(documentInformation); + _helper.crossTable.trailer![PdfDictionaryProperties + .info] = PdfReferenceHolder(documentInformation); } await _appendDocumentAsync(writer); } else { @@ -722,21 +821,25 @@ class PdfDocument { if (_helper.conformanceLevel == PdfConformanceLevel.a3b && _helper.catalog.names != null && attachments.count > 0) { - final PdfName fileRelationShip = - PdfName(PdfDictionaryProperties.afRelationship); + final PdfName fileRelationShip = PdfName( + PdfDictionaryProperties.afRelationship, + ); final PdfArray fileAttachmentAssociationArray = PdfArray(); for (int i = 0; i < attachments.count; i++) { - if (!PdfFileSpecificationBaseHelper.getHelper(attachments[i]) - .dictionary! - .items! - .containsKey(fileRelationShip)) { - PdfFileSpecificationBaseHelper.getHelper(attachments[i]) - .dictionary! - .items![fileRelationShip] = PdfName('Alternative'); + if (!PdfFileSpecificationBaseHelper.getHelper( + attachments[i], + ).dictionary!.items!.containsKey(fileRelationShip)) { + PdfFileSpecificationBaseHelper.getHelper( + attachments[i], + ).dictionary!.items![fileRelationShip] = PdfName('Alternative'); } - fileAttachmentAssociationArray.add(PdfReferenceHolder( - PdfFileSpecificationBaseHelper.getHelper(attachments[i]) - .dictionary)); + fileAttachmentAssociationArray.add( + PdfReferenceHolder( + PdfFileSpecificationBaseHelper.getHelper( + attachments[i], + ).dictionary, + ), + ); } _helper.catalog.items![PdfName(PdfDictionaryProperties.af)] = fileAttachmentAssociationArray; @@ -746,7 +849,6 @@ class PdfDocument { final DocumentSavedArgs argsSaved = DocumentSavedArgs(writer); await _onDocumentSavedAsync(argsSaved); } - return writer.buffer!; } void _checkPages() { @@ -804,21 +906,35 @@ class PdfDocument { /// //Dispose the document. /// document.dispose(); /// ``` - List exportAnnotation(PdfAnnotationDataFormat format, - {String? fileName, - List? exportList, - List? exportTypes, - bool exportAppearance = false}) { + List exportAnnotation( + PdfAnnotationDataFormat format, { + String? fileName, + List? exportList, + List? exportTypes, + bool exportAppearance = false, + }) { List bytes = []; if (format == PdfAnnotationDataFormat.xfdf) { bytes = _helper.exportXfdf( - fileName, exportList, exportTypes, exportAppearance); + fileName, + exportList, + exportTypes, + exportAppearance, + ); } else if (format == PdfAnnotationDataFormat.fdf) { bytes = _helper.exportFdf( - fileName, exportList, exportTypes, exportAppearance); + fileName, + exportList, + exportTypes, + exportAppearance, + ); } else if (format == PdfAnnotationDataFormat.json) { bytes = _helper.exportJson( - fileName, exportList, exportTypes, exportAppearance); + fileName, + exportList, + exportTypes, + exportAppearance, + ); } return bytes; } @@ -859,20 +975,25 @@ class PdfDocument { final PdfCatalog catalog = _getCatalogValue(); if (catalog.containsKey(PdfDictionaryProperties.pages) && !catalog.containsKey(PdfDictionaryProperties.type)) { - catalog.addItems(PdfDictionaryProperties.type, - PdfName(PdfDictionaryProperties.catalog)); + catalog.addItems( + PdfDictionaryProperties.type, + PdfName(PdfDictionaryProperties.catalog), + ); } if (catalog.containsKey(PdfDictionaryProperties.type)) { - if (!(catalog[PdfDictionaryProperties.type]! as PdfName) - .name! - .contains(PdfDictionaryProperties.catalog)) { - catalog[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.catalog); + if (!(catalog[PdfDictionaryProperties.type]! as PdfName).name!.contains( + PdfDictionaryProperties.catalog, + )) { + catalog[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.catalog, + ); } _setCatalog(catalog); } else { throw ArgumentError.value( - catalog, 'Cannot find the PDF catalog information'); + catalog, + 'Cannot find the PDF catalog information', + ); } bool hasVersion = false; if (catalog.containsKey(PdfDictionaryProperties.version)) { @@ -982,8 +1103,10 @@ class PdfDocument { } PdfCatalog _getCatalogValue() { - final PdfCatalog catalog = - PdfCatalog.fromDocument(this, _helper.crossTable.documentCatalog); + final PdfCatalog catalog = PdfCatalog.fromDocument( + this, + _helper.crossTable.documentCatalog, + ); final int index = _helper.objects.lookFor(_helper.crossTable.documentCatalog!)!; _helper.objects.reregisterReference(index, catalog); @@ -994,8 +1117,9 @@ class PdfDocument { void _setCatalog(PdfCatalog catalog) { _helper.catalog = catalog; if (_helper.catalog.containsKey(PdfDictionaryProperties.outlines)) { - final PdfReferenceHolder? outlines = _helper - .catalog[PdfDictionaryProperties.outlines] as PdfReferenceHolder?; + final PdfReferenceHolder? outlines = + _helper.catalog[PdfDictionaryProperties.outlines] + as PdfReferenceHolder?; PdfDictionary? dic; if (outlines == null) { dic = @@ -1017,9 +1141,10 @@ class PdfDocument { } PdfPageCollection _getPageCollection() { - _pages ??= _helper.isLoadedDocument - ? PdfPageCollectionHelper.fromCrossTable(this, _helper.crossTable) - : PdfPageCollectionHelper.load(this); + _pages ??= + _helper.isLoadedDocument + ? PdfPageCollectionHelper.fromCrossTable(this, _helper.crossTable) + : PdfPageCollectionHelper.load(this); return _pages!; } @@ -1038,12 +1163,16 @@ class PdfDocument { final PdfDictionary? catalogNames = catalogReference.object as PdfDictionary?; if (catalogNames != null) { - catalogNames.setProperty(PdfDictionaryProperties.dests, - PdfReferenceHolder(_namedDestinations)); + catalogNames.setProperty( + PdfDictionaryProperties.dests, + PdfReferenceHolder(_namedDestinations), + ); } } else { - _helper.catalog.setProperty(PdfDictionaryProperties.names, - PdfReferenceHolder(_namedDestinations)); + _helper.catalog.setProperty( + PdfDictionaryProperties.names, + PdfReferenceHolder(_namedDestinations), + ); } _helper.catalog.modify(); return _namedDestinations; @@ -1051,30 +1180,38 @@ class PdfDocument { void _readDocumentInfo() { // Read document's info if present. - final PdfDictionary? info = PdfCrossTable.dereference( - _helper.crossTable.trailer![PdfDictionaryProperties.info]) - as PdfDictionary?; + final PdfDictionary? info = + PdfCrossTable.dereference( + _helper.crossTable.trailer![PdfDictionaryProperties.info], + ) + as PdfDictionary?; if (info != null && _documentInfo == null) { - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - dictionary: info, - isLoaded: true, - conformance: _helper.conformanceLevel); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + dictionary: info, + isLoaded: true, + conformance: _helper.conformanceLevel, + ); } if (info != null && !info.changed! && _helper.crossTable.trailer![PdfDictionaryProperties.info] is PdfReferenceHolder) { - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - dictionary: info, - isLoaded: true, - conformance: _helper.conformanceLevel); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + dictionary: info, + isLoaded: true, + conformance: _helper.conformanceLevel, + ); if (_helper.catalog.changed!) { _documentInfo!.modificationDate = DateTime.now(); } if (_helper.objects.lookFor(IPdfWrapper.getElement(_documentInfo!)!)! > -1) { - _helper.objects.reregisterReference(_helper.objects.lookFor(info)!, - IPdfWrapper.getElement(_documentInfo!)!); + _helper.objects.reregisterReference( + _helper.objects.lookFor(info)!, + IPdfWrapper.getElement(_documentInfo!)!, + ); IPdfWrapper.getElement(_documentInfo!)!.position = -1; } } @@ -1082,32 +1219,40 @@ class PdfDocument { Future _readDocumentInfoAsync() async { // Read document's info if present. - final PdfDictionary? info = PdfCrossTable.dereference( - _helper.crossTable.trailer![PdfDictionaryProperties.info]) - as PdfDictionary?; + final PdfDictionary? info = + PdfCrossTable.dereference( + _helper.crossTable.trailer![PdfDictionaryProperties.info], + ) + as PdfDictionary?; if (info != null && _documentInfo == null) { - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - dictionary: info, - isLoaded: true, - conformance: _helper.conformanceLevel); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + dictionary: info, + isLoaded: true, + conformance: _helper.conformanceLevel, + ); } if (info != null && !info.changed! && _helper.crossTable.trailer![PdfDictionaryProperties.info] is PdfReferenceHolder) { - _documentInfo = PdfDocumentInformationHelper.load(_helper.catalog, - dictionary: info, - isLoaded: true, - conformance: _helper.conformanceLevel); + _documentInfo = PdfDocumentInformationHelper.load( + _helper.catalog, + dictionary: info, + isLoaded: true, + conformance: _helper.conformanceLevel, + ); if (_helper.catalog.changed!) { _documentInfo!.modificationDate = DateTime.now(); } - if ((await _helper.objects - .lookForAsync(IPdfWrapper.getElement(_documentInfo!)!))! > + if ((await _helper.objects.lookForAsync( + IPdfWrapper.getElement(_documentInfo!)!, + ))! > -1) { await _helper.objects.reregisterReferenceAsync( - (await _helper.objects.lookForAsync(info))!, - IPdfWrapper.getElement(_documentInfo!)!); + (await _helper.objects.lookForAsync(info))!, + IPdfWrapper.getElement(_documentInfo!)!, + ); IPdfWrapper.getElement(_documentInfo!)!.position = -1; } } @@ -1187,8 +1332,8 @@ class PdfDocument { /// args.attachmentOpenPassword = 'syncfusion'; /// } /// ``` -typedef PdfPasswordCallback = void Function( - PdfDocument sender, PdfPasswordArgs args); +typedef PdfPasswordCallback = + void Function(PdfDocument sender, PdfPasswordArgs args); /// Arguments of Pdf Password. /// @@ -1375,8 +1520,11 @@ class PdfDocumentHelper { encryption = false; } if (!encryptor.checkPassword(password!, key, encryption)) { - throw ArgumentError.value(password, 'password', - 'Cannot open an encrypted document. The password is invalid.'); + throw ArgumentError.value( + password, + 'password', + 'Cannot open an encrypted document. The password is invalid.', + ); } encryptionDict.encrypt = false; final PdfSecurity security = PdfSecurityHelper.getSecurity(); @@ -1409,8 +1557,10 @@ class PdfDocumentHelper { final PdfCatalogNames? names = catalog.names; if (names != null) { destinations = names.destinations; - final IPdfPrimitive? name = - names.getNamedObjectFromTree(destinations, obj); + final IPdfPrimitive? name = names.getNamedObjectFromTree( + destinations, + obj, + ); destination = _extractDestination(name); } } @@ -1446,8 +1596,9 @@ class PdfDocumentHelper { if (_bookmarkHashTable == null) { _bookmarkHashTable = {}; final Queue stack = Queue(); - CurrentNodeInfo ni = - CurrentNodeInfo(PdfBookmarkBaseHelper.getList(current)); + CurrentNodeInfo ni = CurrentNodeInfo( + PdfBookmarkBaseHelper.getList(current), + ); do { for (; ni.index < ni.kids.length;) { current = ni.kids[ni.index]; @@ -1470,9 +1621,10 @@ class PdfDocumentHelper { final PdfDestination? dest = (current as PdfBookmark).destination; if (dest != null) { final PdfPage page = dest.page; - List? list = _bookmarkHashTable!.containsKey(page) - ? _bookmarkHashTable![page] as List? - : null; + List? list = + _bookmarkHashTable!.containsKey(page) + ? _bookmarkHashTable![page] as List? + : null; if (list == null) { list = []; _bookmarkHashTable![page] = list; @@ -1524,8 +1676,12 @@ class PdfDocumentHelper { } /// Exports annotation to FDF file bytes. - List exportFdf(String? fileName, List? exportAnnotation, - List? exportTypes, bool exportAppearance) { + List exportFdf( + String? fileName, + List? exportAnnotation, + List? exportTypes, + bool exportAppearance, + ) { const String genNumber = '${PdfOperators.whiteSpace}0${PdfOperators.whiteSpace}'; const String startDictionary = '<<${PdfOperators.slash}'; @@ -1538,22 +1694,25 @@ class PdfDocumentHelper { if (exportAnnotation != null && exportAnnotation.isNotEmpty) { for (int i = 0; i < exportAnnotation.length; i++) { final PdfAnnotation annotation = exportAnnotation[i]; - final PdfAnnotationHelper helper = - PdfAnnotationHelper.getHelper(annotation); + final PdfAnnotationHelper helper = PdfAnnotationHelper.getHelper( + annotation, + ); if (helper.isLoadedAnnotation && (annotType.isEmpty || annotType.contains(_getAnnotationType(helper.dictionary!))) && !(annotation is PdfLinkAnnotation || annotation is PdfTextWebLink) && annotation.page != null) { - final FdfDocument fdfDocument = - FdfDocument(helper.dictionary!, annotation.page!); + final FdfDocument fdfDocument = FdfDocument( + helper.dictionary!, + annotation.page!, + ); final Map result = fdfDocument.exportAnnotations( - currentID, - annotID, - base.pages.indexOf(annotation.page!), - _checkForStamp(helper.dictionary!) == 'Stamp' || - exportAppearance); + currentID, + annotID, + base.pages.indexOf(annotation.page!), + _checkForStamp(helper.dictionary!) == 'Stamp' || exportAppearance, + ); fdfBytes.addAll(result['exportData'] as List); currentID = result['currentID'] as int; } @@ -1567,17 +1726,21 @@ class PdfDocumentHelper { final PdfDictionary annotationDictionary = pageHelper.terminalAnnotation[j]; if ((annotType.isEmpty || - annotType - .contains(_getAnnotationType(annotationDictionary))) && + annotType.contains( + _getAnnotationType(annotationDictionary), + )) && !isLinkAnnotation(annotationDictionary)) { - final FdfDocument fdfDocument = - FdfDocument(annotationDictionary, page); + final FdfDocument fdfDocument = FdfDocument( + annotationDictionary, + page, + ); final Map result = fdfDocument.exportAnnotations( - currentID, - annotID, - i, - _checkForStamp(annotationDictionary) == 'Stamp' || - exportAppearance); + currentID, + annotID, + i, + _checkForStamp(annotationDictionary) == 'Stamp' || + exportAppearance, + ); fdfBytes.addAll(result['exportData'] as List); currentID = result['currentID'] as int; } @@ -1587,23 +1750,39 @@ class PdfDocumentHelper { fileName ??= ''; if (currentID != 2) { const String root = '1$genNumber'; - fdfBytes.addAll(utf8.encode( - '${'$root${PdfOperators.obj}${PdfOperators.newLine}${startDictionary}FDF$startDictionary${PdfDictionaryProperties.annots}'}[')); + fdfBytes.addAll( + utf8.encode( + '${'$root${PdfOperators.obj}${PdfOperators.newLine}${startDictionary}FDF$startDictionary${PdfDictionaryProperties.annots}'}[', + ), + ); for (int i = 0; i < annotID.length - 1; i++) { - fdfBytes.addAll(utf8.encode( - '${annotID[i]}$genNumber${PdfDictionaryProperties.r}${PdfOperators.whiteSpace}')); + fdfBytes.addAll( + utf8.encode( + '${annotID[i]}$genNumber${PdfDictionaryProperties.r}${PdfOperators.whiteSpace}', + ), + ); } - fdfBytes.addAll(utf8.encode( - '${annotID[annotID.length - 1]}$genNumber${PdfDictionaryProperties.r}]${PdfOperators.slash}${PdfDictionaryProperties.f}($fileName)${PdfOperators.slash}${PdfDictionaryProperties.uf}($fileName)>>${PdfOperators.slash}${PdfDictionaryProperties.type}${PdfOperators.slash}${PdfDictionaryProperties.catalog}>>${PdfOperators.newLine}${PdfOperators.endobj}${PdfOperators.newLine}')); - fdfBytes.addAll(utf8.encode( - '${PdfOperators.trailer}${PdfOperators.newLine}$startDictionary${PdfDictionaryProperties.root}${PdfOperators.whiteSpace}$root${PdfDictionaryProperties.r}>>${PdfOperators.newLine}${PdfOperators.endOfFileMarker}${PdfOperators.newLine}')); + fdfBytes.addAll( + utf8.encode( + '${annotID[annotID.length - 1]}$genNumber${PdfDictionaryProperties.r}]${PdfOperators.slash}${PdfDictionaryProperties.f}($fileName)${PdfOperators.slash}${PdfDictionaryProperties.uf}($fileName)>>${PdfOperators.slash}${PdfDictionaryProperties.type}${PdfOperators.slash}${PdfDictionaryProperties.catalog}>>${PdfOperators.newLine}${PdfOperators.endobj}${PdfOperators.newLine}', + ), + ); + fdfBytes.addAll( + utf8.encode( + '${PdfOperators.trailer}${PdfOperators.newLine}$startDictionary${PdfDictionaryProperties.root}${PdfOperators.whiteSpace}$root${PdfDictionaryProperties.r}>>${PdfOperators.newLine}${PdfOperators.endOfFileMarker}${PdfOperators.newLine}', + ), + ); } return fdfBytes; } /// Exports annotation to JSON file bytes. - List exportJson(String? fileName, List? exportAnnotation, - List? exportTypes, bool exportAppearance) { + List exportJson( + String? fileName, + List? exportAnnotation, + List? exportTypes, + bool exportAppearance, + ) { String json = '{"pdfAnnotation":{'; bool isAnnotationAdded = false; JsonDocument? jsonDocument = JsonDocument(base); @@ -1627,10 +1806,11 @@ class PdfDocumentHelper { tempJson = '"$pageIndex":{ "shapeAnnotation":['; } jsonDocument.exportAnnotationData( - table, - exportAppearance, - base.pages.indexOf(exportAnnotation[j].page!), - annotationDictionary); + table, + exportAppearance, + base.pages.indexOf(exportAnnotation[j].page!), + annotationDictionary, + ); tempJson += jsonDocument.convertToJson(table); table1[pageIndex] = tempJson; table.clear(); @@ -1658,7 +1838,11 @@ class PdfDocumentHelper { if (annotType.isEmpty || annotType.contains(_getAnnotationType(annotationDictionary))) { jsonDocument.exportAnnotationData( - table, exportAppearance, i, annotationDictionary); + table, + exportAppearance, + i, + annotationDictionary, + ); json += jsonDocument.convertToJson(table); if (j < pageHelper.terminalAnnotation.length - 1) { json += ','; @@ -1677,8 +1861,12 @@ class PdfDocumentHelper { } /// Exports annotation to XFDF file bytes. - List exportXfdf(String? fileName, List? exportAnnotation, - List? exportTypes, bool exportAppearance) { + List exportXfdf( + String? fileName, + List? exportAnnotation, + List? exportTypes, + bool exportAppearance, + ) { final XFdfDocument xfdf = XFdfDocument(fileName ?? ''); final List elements = []; final List annotType = []; @@ -1686,14 +1874,17 @@ class PdfDocumentHelper { if (exportAnnotation != null && exportAnnotation.isNotEmpty) { for (int j = 0; j < exportAnnotation.length; j++) { if (annotType.isEmpty || - annotType.contains(_getAnnotationType( - PdfAnnotationHelper.getHelper(exportAnnotation[j]) - .dictionary!))) { + annotType.contains( + _getAnnotationType( + PdfAnnotationHelper.getHelper(exportAnnotation[j]).dictionary!, + ), + )) { final XmlElement? element = xfdf.exportAnnotationData( - PdfAnnotationHelper.getHelper(exportAnnotation[j]).dictionary!, - base.pages.indexOf(exportAnnotation[j].page!), - exportAppearance, - base); + PdfAnnotationHelper.getHelper(exportAnnotation[j]).dictionary!, + base.pages.indexOf(exportAnnotation[j].page!), + exportAppearance, + base, + ); if (element != null) { elements.add(element); } @@ -1709,7 +1900,11 @@ class PdfDocumentHelper { if (annotType.isEmpty || annotType.contains(_getAnnotationType(annotationDictionary))) { final XmlElement? element = xfdf.exportAnnotationData( - annotationDictionary, i, exportAppearance, base); + annotationDictionary, + i, + exportAppearance, + base, + ); if (element != null) { elements.add(element); } @@ -1721,7 +1916,9 @@ class PdfDocumentHelper { } void _getExportTypes( - List? types, List annotType) { + List? types, + List annotType, + ) { if (types != null && types.isNotEmpty) { for (int i = 0; i < types.length; i++) { String annotationType = getEnumName(types[i]); @@ -1746,12 +1943,20 @@ class PdfDocumentHelper { String _getAnnotationType(PdfDictionary dictionary) { if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { - final PdfName name = PdfAnnotationHelper.getValue( - dictionary, crossTable, PdfDictionaryProperties.subtype, true)! - as PdfName; + final PdfName name = + PdfAnnotationHelper.getValue( + dictionary, + crossTable, + PdfDictionaryProperties.subtype, + true, + )! + as PdfName; final PdfAnnotationTypes type = PdfAnnotationCollectionHelper.getAnnotationType( - name, dictionary, crossTable); + name, + dictionary, + crossTable, + ); return getEnumName(type); } return ''; @@ -1760,7 +1965,8 @@ class PdfDocumentHelper { String _checkForStamp(PdfDictionary dictionary) { if (dictionary.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? name = PdfCrossTable.dereference( - dictionary[PdfDictionaryProperties.subtype]); + dictionary[PdfDictionaryProperties.subtype], + ); if (name != null && name is PdfName) { return name.name ?? ''; } @@ -1772,7 +1978,8 @@ class PdfDocumentHelper { static bool isLinkAnnotation(PdfDictionary annotationDictionary) { if (annotationDictionary.containsKey(PdfDictionaryProperties.subtype)) { final IPdfPrimitive? name = PdfCrossTable.dereference( - annotationDictionary[PdfDictionaryProperties.subtype]); + annotationDictionary[PdfDictionaryProperties.subtype], + ); if (name != null && name is PdfName) { return name.name == 'Link'; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_information.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_information.dart index e27bec1c7..f9c05d66b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_information.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_information.dart @@ -11,10 +11,12 @@ import 'pdf_catalog.dart'; /// A class containing the information about the document. class PdfDocumentInformation implements IPdfWrapper { //Constructor - PdfDocumentInformation._(PdfCatalog catalog, - {PdfDictionary? dictionary, - bool isLoaded = false, - PdfConformanceLevel? conformance}) { + PdfDocumentInformation._( + PdfCatalog catalog, { + PdfDictionary? dictionary, + bool isLoaded = false, + PdfConformanceLevel? conformance, + }) { _helper = PdfDocumentInformationHelper(this); _helper._catalog = catalog; if (conformance != null) { @@ -27,7 +29,9 @@ class PdfDocumentInformation implements IPdfWrapper { _helper._dictionary = PdfDictionary(); if (_helper.conformance != PdfConformanceLevel.a1b) { _helper._dictionary!.setDateTime( - PdfDictionaryProperties.creationDate, _helper.creationDate); + PdfDictionaryProperties.creationDate, + _helper.creationDate, + ); } } } @@ -45,12 +49,15 @@ class PdfDocumentInformation implements IPdfWrapper { /// Gets the creation date of the PDF document DateTime get creationDate { - if (_helper._dictionary! - .containsKey(PdfDictionaryProperties.creationDate) && + if (_helper._dictionary!.containsKey( + PdfDictionaryProperties.creationDate, + ) && _helper._dictionary![PdfDictionaryProperties.creationDate] is PdfString) { - return _helper.creationDate = _helper._dictionary!.getDateTime(_helper - ._dictionary![PdfDictionaryProperties.creationDate]! as PdfString); + return _helper.creationDate = _helper._dictionary!.getDateTime( + _helper._dictionary![PdfDictionaryProperties.creationDate]! + as PdfString, + ); } return _helper.creationDate = DateTime.now(); } @@ -60,19 +67,23 @@ class PdfDocumentInformation implements IPdfWrapper { if (_helper.creationDate != value) { _helper.creationDate = value; _helper._dictionary!.setDateTime( - PdfDictionaryProperties.creationDate, _helper.creationDate); + PdfDictionaryProperties.creationDate, + _helper.creationDate, + ); } } /// Gets the modification date of the PDF document DateTime get modificationDate { - if (_helper._dictionary! - .containsKey(PdfDictionaryProperties.modificationDate) && + if (_helper._dictionary!.containsKey( + PdfDictionaryProperties.modificationDate, + ) && _helper._dictionary![PdfDictionaryProperties.modificationDate] is PdfString) { return _helper.modificationDate = _helper._dictionary!.getDateTime( - _helper._dictionary![PdfDictionaryProperties.modificationDate]! - as PdfString); + _helper._dictionary![PdfDictionaryProperties.modificationDate]! + as PdfString, + ); } return _helper.modificationDate = DateTime.now(); } @@ -81,17 +92,19 @@ class PdfDocumentInformation implements IPdfWrapper { set modificationDate(DateTime value) { _helper.modificationDate = value; _helper._dictionary!.setDateTime( - PdfDictionaryProperties.modificationDate, _helper.modificationDate); + PdfDictionaryProperties.modificationDate, + _helper.modificationDate, + ); } /// Gets the title. String get title { if (_helper._dictionary!.containsKey(PdfDictionaryProperties.title) && _helper._dictionary![PdfDictionaryProperties.title] is PdfString) { - return _title = - (_helper._dictionary![PdfDictionaryProperties.title]! as PdfString) - .value! - .replaceAll('\u0000', ''); + return _title = (_helper._dictionary![PdfDictionaryProperties.title]! + as PdfString) + .value! + .replaceAll('\u0000', ''); } return _title = ''; } @@ -160,8 +173,10 @@ class PdfDocumentInformation implements IPdfWrapper { set keywords(String value) { if (_keywords != value) { _keywords = value; - _helper._dictionary! - .setString(PdfDictionaryProperties.keywords, _keywords); + _helper._dictionary!.setString( + PdfDictionaryProperties.keywords, + _keywords, + ); } if (_helper._catalog != null && _helper._catalog!.metadata != null) { _helper._xmp = _helper.xmpMetadata; @@ -204,29 +219,35 @@ class PdfDocumentInformation implements IPdfWrapper { set producer(String value) { if (_producer != value) { _producer = value; - _helper._dictionary! - .setString(PdfDictionaryProperties.producer, _producer); + _helper._dictionary!.setString( + PdfDictionaryProperties.producer, + _producer, + ); } } /// Remove the modification date from existing document. void removeModificationDate() { if (_helper._dictionary != null && - _helper._dictionary! - .containsKey(PdfDictionaryProperties.modificationDate)) { + _helper._dictionary!.containsKey( + PdfDictionaryProperties.modificationDate, + )) { _helper._dictionary!.remove(PdfDictionaryProperties.modificationDate); if (_helper._dictionary!.changed! && !_helper._catalog!.changed!) { PdfDocumentInformationHelper.getHelper( - _helper._catalog!.document!.documentInformation) - ._dictionary! - .remove(PdfDictionaryProperties.modificationDate); + _helper._catalog!.document!.documentInformation, + )._dictionary!.remove(PdfDictionaryProperties.modificationDate); PdfDocumentInformationHelper.getHelper( - _helper._catalog!.document!.documentInformation) - .isRemoveModifyDate = true; - _helper._xmp = - XmpMetadata(_helper._catalog!.document!.documentInformation); + _helper._catalog!.document!.documentInformation, + ).isRemoveModifyDate = + true; + _helper._xmp = XmpMetadata( + _helper._catalog!.document!.documentInformation, + ); _helper._catalog!.setProperty( - PdfDictionaryProperties.metadata, PdfReferenceHolder(_helper._xmp)); + PdfDictionaryProperties.metadata, + PdfReferenceHolder(_helper._xmp), + ); } } } @@ -246,12 +267,18 @@ class PdfDocumentInformationHelper { } /// internal method - static PdfDocumentInformation load(PdfCatalog catalog, - {PdfDictionary? dictionary, - bool isLoaded = false, - PdfConformanceLevel? conformance}) { - return PdfDocumentInformation._(catalog, - dictionary: dictionary, isLoaded: isLoaded, conformance: conformance); + static PdfDocumentInformation load( + PdfCatalog catalog, { + PdfDictionary? dictionary, + bool isLoaded = false, + PdfConformanceLevel? conformance, + }) { + return PdfDocumentInformation._( + catalog, + dictionary: dictionary, + isLoaded: isLoaded, + conformance: conformance, + ); } /// internal field @@ -284,27 +311,36 @@ class PdfDocumentInformationHelper { if (_xmp == null) { if (_catalog!.metadata == null && _catalog!.pages != null) { _xmp = XmpMetadata( - PdfSectionCollectionHelper.getHelper(_catalog!.pages!) - .document! - .documentInformation); + PdfSectionCollectionHelper.getHelper( + _catalog!.pages!, + ).document!.documentInformation, + ); _catalog!.setProperty( - PdfDictionaryProperties.metadata, PdfReferenceHolder(_xmp)); + PdfDictionaryProperties.metadata, + PdfReferenceHolder(_xmp), + ); } else { if (_dictionary!.changed! && !_catalog!.changed!) { _xmp = XmpMetadata(_catalog!.document!.documentInformation); _catalog!.setProperty( - PdfDictionaryProperties.metadata, PdfReferenceHolder(_xmp)); + PdfDictionaryProperties.metadata, + PdfReferenceHolder(_xmp), + ); } else { _xmp = _catalog!.metadata; _catalog!.setProperty( - PdfDictionaryProperties.metadata, PdfReferenceHolder(_xmp)); + PdfDictionaryProperties.metadata, + PdfReferenceHolder(_xmp), + ); } } } else if (_catalog!.metadata != null && _catalog!.document != null) { if (_dictionary!.changed! && !_catalog!.changed!) { _xmp = XmpMetadata(_catalog!.document!.documentInformation); _catalog!.setProperty( - PdfDictionaryProperties.metadata, PdfReferenceHolder(_xmp)); + PdfDictionaryProperties.metadata, + PdfReferenceHolder(_xmp), + ); } } return _xmp; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_template.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_template.dart index 9ab931f72..4fc1484ed 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_template.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/pdf_document/pdf_document_template.dart @@ -9,23 +9,37 @@ import '../pages/pdf_section.dart'; class PdfDocumentTemplate { //Constructors /// Initializes a new instance of the [PdfDocumentTemplate] class. - PdfDocumentTemplate( - {PdfPageTemplateElement? left, - PdfPageTemplateElement? top, - PdfPageTemplateElement? right, - PdfPageTemplateElement? bottom, - PdfPageTemplateElement? evenLeft, - PdfPageTemplateElement? evenTop, - PdfPageTemplateElement? evenRight, - PdfPageTemplateElement? evenBottom, - PdfPageTemplateElement? oddLeft, - PdfPageTemplateElement? oddTop, - PdfPageTemplateElement? oddRight, - PdfPageTemplateElement? oddBottom, - PdfStampCollection? stamps}) { + PdfDocumentTemplate({ + PdfPageTemplateElement? left, + PdfPageTemplateElement? top, + PdfPageTemplateElement? right, + PdfPageTemplateElement? bottom, + PdfPageTemplateElement? evenLeft, + PdfPageTemplateElement? evenTop, + PdfPageTemplateElement? evenRight, + PdfPageTemplateElement? evenBottom, + PdfPageTemplateElement? oddLeft, + PdfPageTemplateElement? oddTop, + PdfPageTemplateElement? oddRight, + PdfPageTemplateElement? oddBottom, + PdfStampCollection? stamps, + }) { _helper = PdfDocumentTemplateHelper(this); - _intialize(left, top, right, bottom, evenLeft, evenTop, evenRight, - evenBottom, oddLeft, oddTop, oddRight, oddBottom, stamps); + _intialize( + left, + top, + right, + bottom, + evenLeft, + evenTop, + evenRight, + evenBottom, + oddLeft, + oddTop, + oddRight, + oddBottom, + stamps, + ); } //Fields @@ -149,19 +163,20 @@ class PdfDocumentTemplate { //Implementation void _intialize( - PdfPageTemplateElement? left, - PdfPageTemplateElement? top, - PdfPageTemplateElement? right, - PdfPageTemplateElement? bottom, - PdfPageTemplateElement? evenLeft, - PdfPageTemplateElement? evenTop, - PdfPageTemplateElement? evenRight, - PdfPageTemplateElement? evenBottom, - PdfPageTemplateElement? oddLeft, - PdfPageTemplateElement? oddTop, - PdfPageTemplateElement? oddRight, - PdfPageTemplateElement? oddBottom, - PdfStampCollection? stamps) { + PdfPageTemplateElement? left, + PdfPageTemplateElement? top, + PdfPageTemplateElement? right, + PdfPageTemplateElement? bottom, + PdfPageTemplateElement? evenLeft, + PdfPageTemplateElement? evenTop, + PdfPageTemplateElement? evenRight, + PdfPageTemplateElement? evenBottom, + PdfPageTemplateElement? oddLeft, + PdfPageTemplateElement? oddTop, + PdfPageTemplateElement? oddRight, + PdfPageTemplateElement? oddBottom, + PdfStampCollection? stamps, + ) { if (left != null) { this.left = left; } @@ -204,12 +219,16 @@ class PdfDocumentTemplate { } PdfPageTemplateElement? _checkElement( - PdfPageTemplateElement? templateElement, TemplateType type) { + PdfPageTemplateElement? templateElement, + TemplateType type, + ) { if (templateElement != null) { if (PdfPageTemplateElementHelper.getHelper(templateElement).type != TemplateType.none) { - throw ArgumentError.value(type, - "Can't reassign the template element. Please, create new one."); + throw ArgumentError.value( + type, + "Can't reassign the template element. Please, create new one.", + ); } PdfPageTemplateElementHelper.getHelper(templateElement).type = type; } @@ -317,16 +336,16 @@ class PdfDocumentTemplateHelper { bool _isEven(PdfPage page) { final PdfPageCollection pages = - PdfSectionHelper.getHelper(PdfPageHelper.getHelper(page).section!) - .document! - .pages; + PdfSectionHelper.getHelper( + PdfPageHelper.getHelper(page).section!, + ).document!.pages; int index = 0; - if (PdfPageCollectionHelper.getHelper(pages) - .pageCollectionIndex - .containsKey(page)) { + if (PdfPageCollectionHelper.getHelper( + pages, + ).pageCollectionIndex.containsKey(page)) { index = PdfPageCollectionHelper.getHelper(pages).pageCollectionIndex[page]! + - 1; + 1; } else { index = pages.indexOf(page) + 1; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_array.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_array.dart index 94cb8da16..2bc2728bc 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_array.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_array.dart @@ -7,6 +7,7 @@ import '../io/pdf_constants.dart'; import '../io/pdf_cross_table.dart'; import '../io/pdf_parser.dart'; import '../primitives/pdf_dictionary.dart'; +import '../primitives/pdf_null.dart'; import '../primitives/pdf_number.dart'; /// internal class @@ -96,7 +97,7 @@ class PdfArray implements IPdfPrimitive, IPdfChangable { rectangle.left, rectangle.top, rectangle.right, - rectangle.bottom + rectangle.bottom, ]; return PdfArray(list); } @@ -196,9 +197,11 @@ class PdfArray implements IPdfPrimitive, IPdfChangable { if (writer != null) { writer.write(startMark); for (int i = 0; i < count; i++) { - this[i]!.save(writer); - if (i + 1 != count) { - writer.write(PdfOperators.whiteSpace); + if (this[i] != null && this[i] is! PdfNull) { + this[i]!.save(writer); + if (i + 1 != count) { + writer.write(PdfOperators.whiteSpace); + } } } writer.write(endMark); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_dictionary.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_dictionary.dart index 40aa315bd..2a4ef2cfd 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_dictionary.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_dictionary.dart @@ -103,8 +103,9 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { /// internal method void copyDictionary(PdfDictionary? dictionary) { if (dictionary != null) { - dictionary.items! - .forEach((PdfName? k, IPdfPrimitive? v) => addItems(k, v)); + dictionary.items!.forEach( + (PdfName? k, IPdfPrimitive? v) => addItems(k, v), + ); freezeChanges(this); } } @@ -256,9 +257,11 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { final List fieldCollection = []; if (fields is PdfArray) { for (int k = 0; k < fields.count; k++) { - final PdfReferenceHolder fieldReference = - fields.elements[k]! as PdfReferenceHolder; - fieldCollection.add(fieldReference); + if (fields.elements[k] is PdfReferenceHolder) { + final PdfReferenceHolder referenceHolder = + fields.elements[k]! as PdfReferenceHolder; + fieldCollection.add(referenceHolder); + } } for (int i = 0; i < fields.count; i++) { if (fields.elements[i]! is PdfReferenceHolder) { @@ -268,13 +271,15 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { refHolder.referenceObject as PdfDictionary?; if (field != null) { if (field.beginSave != null) { - final SavePdfPrimitiveArgs args = - SavePdfPrimitiveArgs(writer); + final SavePdfPrimitiveArgs args = SavePdfPrimitiveArgs( + writer, + ); field.beginSave!(field, args); } if (!field.containsKey(PdfName(PdfDictionaryProperties.kids))) { - if (field.items! - .containsKey(PdfName(PdfDictionaryProperties.ft))) { + if (field.items!.containsKey( + PdfName(PdfDictionaryProperties.ft), + )) { final IPdfPrimitive? value = field.items![PdfName(PdfDictionaryProperties.ft)]; if (value != null && @@ -289,9 +294,11 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { final PdfDictionary field1 = fieldRef.object! as PdfDictionary; if (field1.items!.containsKey( - PdfName(PdfDictionaryProperties.t)) && + PdfName(PdfDictionaryProperties.t), + ) && field.items!.containsKey( - PdfName(PdfDictionaryProperties.t))) { + PdfName(PdfDictionaryProperties.t), + )) { final PdfString parentSignatureName = field1.items![PdfName(PdfDictionaryProperties.t)]! as PdfString; @@ -334,8 +341,9 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { /// internal method int getInt(String propertyName) { - final IPdfPrimitive? primitive = - PdfCrossTable.dereference(this[propertyName]); + final IPdfPrimitive? primitive = PdfCrossTable.dereference( + this[propertyName], + ); return (primitive != null && primitive is PdfNumber) ? primitive.value!.toInt() : 0; @@ -343,8 +351,9 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { /// internal method PdfString? getString(String propertyName) { - final IPdfPrimitive? primitive = - PdfCrossTable.dereference(this[propertyName]); + final IPdfPrimitive? primitive = PdfCrossTable.dereference( + this[propertyName], + ); return (primitive != null && primitive is PdfString) ? primitive : null; } @@ -405,7 +414,8 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { modify(); } else { this[key] = PdfString( - "D:${dateFormat.format(dateTime)}+$offsetHours'$offsetMinutes'"); + "D:${dateFormat.format(dateTime)}+$offsetHours'$offsetMinutes'", + ); } } @@ -419,24 +429,33 @@ class PdfDictionary implements IPdfPrimitive, IPdfChangable { value = dateTimeString.value!; } while (value[value.length - 1].contains(RegExp('[:-D-(-)]'))) { - dateTimeString.value = - value.replaceRange(value.length - 1, value.length, ''); + dateTimeString.value = value.replaceRange( + value.length - 1, + value.length, + '', + ); } if (dateTimeString.value!.startsWith('191')) { dateTimeString.value = dateTimeString.value!.replaceFirst('191', '20'); } final bool containPrefixD = dateTimeString.value!.contains(prefixD); const String dateTimeFormat = 'yyyyMMddHHmmss'; - dateTimeString.value = - dateTimeString.value!.padRight(dateTimeFormat.length, '0'); + dateTimeString.value = dateTimeString.value!.padRight( + dateTimeFormat.length, + '0', + ); String localTime = ''.padRight(dateTimeFormat.length); if (dateTimeString.value!.isEmpty) { return DateTime.now(); } if (dateTimeString.value!.length >= localTime.length) { - localTime = containPrefixD - ? dateTimeString.value!.substring(prefixD.length, localTime.length) - : dateTimeString.value!.substring(0, localTime.length); + localTime = + containPrefixD + ? dateTimeString.value!.substring( + prefixD.length, + localTime.length, + ) + : dateTimeString.value!.substring(0, localTime.length); } final String dateWithT = '${localTime.substring(0, 8)}T${localTime.substring(8)}'; @@ -618,5 +637,5 @@ class SavePdfPrimitiveArgs { } /// internal type definition -typedef SavePdfPrimitiveCallback = void Function( - Object sender, SavePdfPrimitiveArgs? args); +typedef SavePdfPrimitiveCallback = + void Function(Object sender, SavePdfPrimitiveArgs? args); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_number.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_number.dart index 1df7cd020..bc3d8494c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_number.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_number.dart @@ -72,8 +72,9 @@ class PdfNumber implements IPdfPrimitive { @override void save(IPdfWriter? writer) { if (value is double) { - String numberValue = - value!.toStringAsFixed(10).replaceAll(RegExp(r'0*$'), ''); + String numberValue = value! + .toStringAsFixed(10) + .replaceAll(RegExp(r'0*$'), ''); if (numberValue.endsWith('.')) { numberValue = numberValue.replaceAll('.', ''); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_reference_holder.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_reference_holder.dart index af95b30c0..1a1ca63ac 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_reference_holder.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_reference_holder.dart @@ -24,7 +24,8 @@ class PdfReferenceHolder implements IPdfPrimitive { object = obj; } else { throw ArgumentError.value( - 'argument is not set to an instance of an object'); + 'argument is not set to an instance of an object', + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_stream.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_stream.dart index c4f5a62fe..c4c5cbcf9 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_stream.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_stream.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:typed_data'; import '../../interfaces/pdf_interface.dart'; import '../compression/compressed_stream_writer.dart'; @@ -86,15 +87,20 @@ class PdfStream extends PdfDictionary { } List? _compressContent(PdfDocument? document) { - final List? data = (crossTable != null && - crossTable!.encryptor != null && - crossTable!.encryptor!.encryptAttachmentOnly!) - ? this.data - : dataStream; + final List? data = + (crossTable != null && + crossTable!.encryptor != null && + crossTable!.encryptor!.encryptAttachmentOnly!) + ? this.data + : dataStream; if (compress! && document!.compressionLevel != PdfCompressionLevel.none) { final List outputStream = []; final CompressedStreamWriter compressedWriter = CompressedStreamWriter( - outputStream, false, document.compressionLevel, false); + outputStream, + false, + document.compressionLevel, + false, + ); compressedWriter.write(data!, 0, data.length, false); compressedWriter.close(); addFilter(PdfDictionaryProperties.flateDecode); @@ -106,15 +112,20 @@ class PdfStream extends PdfDictionary { } List? _compressStream() { - final List? streamData = (crossTable != null && - crossTable!.encryptor != null && - crossTable!.encryptor!.encryptAttachmentOnly!) - ? data - : dataStream; + final List? streamData = + (crossTable != null && + crossTable!.encryptor != null && + crossTable!.encryptor!.encryptAttachmentOnly!) + ? data + : dataStream; final List outputStream = []; if (streamData != null && streamData.isNotEmpty) { CompressedStreamWriter( - outputStream, false, PdfCompressionLevel.best, false) + outputStream, + false, + PdfCompressionLevel.best, + false, + ) ..write(streamData, 0, streamData.length, false) ..close(); if (outputStream.isNotEmpty) { @@ -344,7 +355,9 @@ class PdfStream extends PdfDictionary { _modify(); } else { throw ArgumentError.value( - pdfObject, 'The method or operation is not implemented'); + pdfObject, + 'The method or operation is not implemented', + ); } } @@ -361,15 +374,16 @@ class PdfStream extends PdfDictionary { //IPdfPrimitive members @override void save(IPdfWriter? writer) { - final SavePdfPrimitiveArgs beginSaveArguments = - SavePdfPrimitiveArgs(writer); + final SavePdfPrimitiveArgs beginSaveArguments = SavePdfPrimitiveArgs( + writer, + ); onBeginSave(beginSaveArguments); List? data = _compressContent(writer!.document); final PdfSecurity security = writer.document!.security; if (PdfSecurityHelper.getHelper(security).encryptor.encrypt && - PdfSecurityHelper.getHelper(security) - .encryptor - .encryptAttachmentOnly!) { + PdfSecurityHelper.getHelper( + security, + ).encryptor.encryptAttachmentOnly!) { bool attachmentEncrypted = false; if (containsKey(PdfDictionaryProperties.type)) { final IPdfPrimitive? primitive = this[PdfDictionaryProperties.type]; @@ -387,13 +401,15 @@ class PdfStream extends PdfDictionary { if ((isArray == null && isString == null) || !isArray! || (isArray && - (filterPrimitive! as PdfArray) - .contains(PdfName(PdfDictionaryProperties.crypt)))) { + (filterPrimitive! as PdfArray).contains( + PdfName(PdfDictionaryProperties.crypt), + ))) { if (_compress! || !containsKey(PdfDictionaryProperties.filter) || (isArray! && (filterPrimitive! as PdfArray).contains( - PdfName(PdfDictionaryProperties.flateDecode)) || + PdfName(PdfDictionaryProperties.flateDecode), + ) || (isString! && (filterPrimitive! as PdfString).value == PdfDictionaryProperties.flateDecode))) { @@ -406,8 +422,9 @@ class PdfStream extends PdfDictionary { if (!containsKey(PdfDictionaryProperties.decodeParms)) { final PdfArray decode = PdfArray(); final PdfDictionary decodeparms = PdfDictionary(); - decodeparms[PdfDictionaryProperties.name] = - PdfName(PdfDictionaryProperties.stdCF); + decodeparms[PdfDictionaryProperties.name] = PdfName( + PdfDictionaryProperties.stdCF, + ); decode.add(decodeparms); decode.add(PdfNull()); this[PdfName(PdfDictionaryProperties.decodeParms)] = decode; @@ -458,17 +475,18 @@ class PdfStream extends PdfDictionary { if (!containsKey(PdfDictionaryProperties.decodeParms)) { final PdfArray decode = PdfArray(); final PdfDictionary decodeparms = PdfDictionary(); - decodeparms[PdfDictionaryProperties.name] = - PdfName(PdfDictionaryProperties.stdCF); + decodeparms[PdfDictionaryProperties.name] = PdfName( + PdfDictionaryProperties.stdCF, + ); decode.add(decodeparms); decode.add(PdfNull()); this[PdfName(PdfDictionaryProperties.decodeParms)] = decode; } } } - } else if (!PdfSecurityHelper.getHelper(security) - .encryptor - .encryptOnlyMetadata! && + } else if (!PdfSecurityHelper.getHelper( + security, + ).encryptor.encryptOnlyMetadata! && containsKey(PdfDictionaryProperties.type)) { final IPdfPrimitive? primitive = this[PdfDictionaryProperties.type]; if (primitive != null && primitive is PdfName) { @@ -481,11 +499,13 @@ class PdfStream extends PdfDictionary { data = _encryptContent(data, writer); } - this[PdfDictionaryProperties.length] = PdfNumber(data!.length); + this[PdfDictionaryProperties.length] = PdfNumber( + data != null ? data.length : 0, + ); super.saveDictionary(writer, false); writer.write(prefix); writer.write(PdfOperators.newLine); - if (data.isNotEmpty) { + if (data != null && data.isNotEmpty) { writer.write(data); writer.write(PdfOperators.newLine); } @@ -500,10 +520,14 @@ class PdfStream extends PdfDictionary { @override void dispose() { - if (dataStream != null && dataStream!.isNotEmpty) { - dataStream!.clear(); + if (dataStream != null) { + if (dataStream is List && dataStream is! Uint8List) { + dataStream!.clear(); + } data = null; } + _clonedObject = null; + objNumber = null; } @override @@ -535,9 +559,10 @@ class PdfStream extends PdfDictionary { PdfSecurityHelper.getHelper(doc.security).encryptor; if (encryptor.encrypt && !blockEncryption) { data = encryptor.encryptData( - PdfDocumentHelper.getHelper(doc).currentSavingObject!.objNum, - data!, - true); + PdfDocumentHelper.getHelper(doc).currentSavingObject!.objNum, + data!, + true, + ); } return data; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_string.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_string.dart index 2f3fdb7a5..8151c6936 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_string.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/primitives/pdf_string.dart @@ -97,9 +97,12 @@ class PdfString implements IPdfPrimitive { /// internal method List pdfEncode(PdfDocument? document) { final List result = []; - result.add(isHex! - ? PdfString.hexStringMark.codeUnitAt(0) - : PdfString.stringMark.codeUnitAt(0)); + final PdfSecurity? security = (document == null) ? null : document.security; + result.add( + isHex! + ? PdfString.hexStringMark.codeUnitAt(0) + : PdfString.stringMark.codeUnitAt(0), + ); if ((data == null || data!.isEmpty) && !isNullOrEmpty(value)) { data = []; for (int i = 0; i < value!.length; i++) { @@ -124,7 +127,10 @@ class PdfString implements IPdfPrimitive { for (int i = 0; i < value!.length; i++) { tempData.add(value!.codeUnitAt(i).toUnsigned(8)); } - tempData = escapeSymbols(tempData); + if (security == null || + !PdfSecurityHelper.getHelper(security).encryptor.encrypt) { + tempData = escapeSymbols(tempData); + } } bool hex = false; tempData = _encryptIfNeeded(tempData, document); @@ -143,9 +149,11 @@ class PdfString implements IPdfPrimitive { } result.addAll(tempData); } - result.add(isHex! - ? PdfString.hexStringMark.codeUnitAt(1) - : PdfString.stringMark.codeUnitAt(1)); + result.add( + isHex! + ? PdfString.hexStringMark.codeUnitAt(1) + : PdfString.stringMark.codeUnitAt(1), + ); return result; } @@ -339,13 +347,9 @@ class PdfString implements IPdfPrimitive { @override void dispose() { - if (data != null) { - data!.clear(); - data = null; - } - if (_status != null) { - _status = null; - } + data = data?.map((_) => 0).toList(); + data = null; + _status = null; } @override @@ -367,15 +371,16 @@ class PdfString implements IPdfPrimitive { final PdfSecurity? security = (document == null) ? null : document.security; if (security == null || (!PdfSecurityHelper.getHelper(security).encryptor.encrypt || - PdfSecurityHelper.getHelper(security) - .encryptor - .encryptAttachmentOnly!)) { + PdfSecurityHelper.getHelper( + security, + ).encryptor.encryptAttachmentOnly!)) { return data; } else { data = PdfSecurityHelper.getHelper(security).encryptor.encryptData( - PdfDocumentHelper.getHelper(document!).currentSavingObject!.objNum, - data, - true); + PdfDocumentHelper.getHelper(document!).currentSavingObject!.objNum, + data, + true, + ); } return escapeSymbols(data); } @@ -391,8 +396,11 @@ class PdfString implements IPdfPrimitive { !encryptor.encryptAttachmentOnly!) { decrypted = true; value = byteToString(data!); - final List bytes = - encryptor.encryptData(currentObjectNumber, data!, false); + final List bytes = encryptor.encryptData( + currentObjectNumber, + data!, + false, + ); value = byteToString(bytes); const String bigEndianPreambleString = 'þÿ'; if (value!.length > 1 && @@ -414,5 +422,5 @@ enum ForceEncoding { ascii, /// internal enumerator - unicode + unicode, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1.dart index cd9c3564d..9b6564ce8 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1.dart @@ -313,10 +313,12 @@ abstract class Asn1 extends Asn1Encode { /// internal method static BigInt leToUInt32(List bs, int off) { - return BigInt.from(bs[off].toUnsigned(32) | - bs[off + 1].toUnsigned(32) << 8 | - bs[off + 2].toUnsigned(32) << 16 | - bs[off + 3].toUnsigned(32) << 24); + return BigInt.from( + bs[off].toUnsigned(32) | + bs[off + 1].toUnsigned(32) << 8 | + bs[off + 2].toUnsigned(32) << 16 | + bs[off + 3].toUnsigned(32) << 24, + ); } /// internal method @@ -420,7 +422,7 @@ class Asn1EncodeCollection { class Asn1Octet extends Asn1 implements IAsn1Octet { /// internal constructor Asn1Octet(this.value) - : super([Asn1UniversalTags.octetString]); + : super([Asn1UniversalTags.octetString]); /// internal constructor Asn1Octet.fromObject(Asn1Encode obj) { @@ -528,10 +530,10 @@ class Asn1Sequence extends Asn1 { //Constructor /// internal constructor Asn1Sequence() - : super([ - Asn1UniversalTags.sequence, - Asn1UniversalTags.constructed - ]) { + : super([ + Asn1UniversalTags.sequence, + Asn1UniversalTags.constructed, + ]) { objects = []; } //Fields @@ -571,7 +573,8 @@ class Asn1Sequence extends Asn1 { result = Asn1Sequence.getSequence(obj.getAsn1()); } else if (obj is List) { result = Asn1Sequence.getSequence( - Asn1Stream(PdfStreamReader(obj)).readAsn1()); + Asn1Stream(PdfStreamReader(obj)).readAsn1(), + ); } else if (obj is Asn1Encode) { final Asn1? primitive = obj.getAsn1(); if (primitive != null && primitive is Asn1Sequence) { @@ -585,7 +588,10 @@ class Asn1Sequence extends Asn1 { if (explicitly) { if (!obj.explicit!) { throw ArgumentError.value( - explicitly, 'explicitly', 'Invalid entry in sequence'); + explicitly, + 'explicitly', + 'Invalid entry in sequence', + ); } result = inner as Asn1Sequence?; } else if (obj.explicit!) { @@ -725,8 +731,10 @@ class Asn1SequenceCollection extends Asn1Encode { Asn1Set? attributes; @override Asn1 getAsn1() { - final Asn1EncodeCollection collection = - Asn1EncodeCollection([id, DerTag(0, value)]); + final Asn1EncodeCollection collection = Asn1EncodeCollection([ + id, + DerTag(0, value), + ]); if (attributes != null) { collection.encodableObjects.add(attributes); } @@ -772,9 +780,10 @@ class Asn1SequenceHelper implements IAsn1Collection { class Asn1Set extends Asn1 { /// internal constructor Asn1Set([int? capacity]) { - objects = capacity != null - ? List.generate(capacity, (dynamic i) => null) - : []; + objects = + capacity != null + ? List.generate(capacity, (dynamic i) => null) + : []; } //Fields /// internal field @@ -898,8 +907,9 @@ class Asn1Set extends Asn1 { } else if (obj is IAsn1SetHelper) { result = Asn1Set.getAsn1Set(obj.getAsn1()); } else if (obj is List) { - result = - Asn1Set.getAsn1Set(Asn1Stream(PdfStreamReader(obj)).readAsn1()); + result = Asn1Set.getAsn1Set( + Asn1Stream(PdfStreamReader(obj)).readAsn1(), + ); } else if (obj is Asn1Encode) { final Asn1? asn1 = obj.getAsn1(); if (asn1 != null && asn1 is Asn1Set) { @@ -922,9 +932,9 @@ class Asn1Set extends Asn1 { } else if (inner is Asn1Sequence) { final Asn1EncodeCollection collection = Asn1EncodeCollection(); // ignore: avoid_function_literals_in_foreach_calls - inner.objects! - .toList() - .forEach((dynamic entry) => collection.encodableObjects.add(entry)); + inner.objects!.toList().forEach( + (dynamic entry) => collection.encodableObjects.add(entry), + ); result = DerSet(collection: collection, isSort: false); } else { throw ArgumentError.value(obj, 'obj', 'Invalid entry in sequence'); @@ -1060,7 +1070,10 @@ class Asn1Tag extends Asn1 implements IAsn1Tag { return getObject(); } throw ArgumentError.value( - tagNumber, 'tagNumber', 'Implicit tagging is not supported'); + tagNumber, + 'tagNumber', + 'Implicit tagging is not supported', + ); } } @@ -1080,7 +1093,7 @@ class Asn1DerStream extends DerStream { class Asn1Integer extends Asn1 { /// internal constructor Asn1Integer(this._value) - : super([Asn1UniversalTags.integer]); + : super([Asn1UniversalTags.integer]); /// internal field late final int _value; @@ -1098,7 +1111,9 @@ class Asn1Integer extends Asn1 { @override void encode(DerStream derOut) { derOut.writeEncoded( - getTagValue([Asn1UniversalTags.integer]), null); + getTagValue([Asn1UniversalTags.integer]), + null, + ); } List _getBytesFromLong(int value) { @@ -1114,7 +1129,7 @@ class Asn1Integer extends Asn1 { class Asn1Boolean extends Asn1 { /// internal constructor Asn1Boolean(this._value) - : super([Asn1UniversalTags.boolean]); + : super([Asn1UniversalTags.boolean]); /// internal field late final bool _value; @@ -1132,8 +1147,9 @@ class Asn1Boolean extends Asn1 { @override void encode(DerStream derOut) { derOut.writeEncoded( - getTagValue([Asn1UniversalTags.boolean]), - _toArray()); + getTagValue([Asn1UniversalTags.boolean]), + _toArray(), + ); } } @@ -1141,7 +1157,7 @@ class Asn1Boolean extends Asn1 { class Asn1Identifier extends Asn1 { /// internal constructor Asn1Identifier(this._id) - : super([Asn1UniversalTags.objectIdentifier]); + : super([Asn1UniversalTags.objectIdentifier]); /// internal field late final String _id; @@ -1217,8 +1233,9 @@ class Asn1Identifier extends Asn1 { @override void encode(DerStream derOut) { derOut.writeEncoded( - getTagValue([Asn1UniversalTags.objectIdentifier]), - _toArray()); + getTagValue([Asn1UniversalTags.objectIdentifier]), + _toArray(), + ); } } @@ -1345,5 +1362,5 @@ enum Asn1UniversalTags { bmpString, constructed, application, - tagged + tagged, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_parser.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_parser.dart index bff05eb19..b5d3c707a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_parser.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_parser.dart @@ -39,17 +39,26 @@ class Asn1Parser { } else { switch (tagNumber) { case Asn1Tags.setTag: - throw ArgumentError.value(tagNumber, 'tagNumber', - 'Constructed encoding is not used in the set'); + throw ArgumentError.value( + tagNumber, + 'tagNumber', + 'Constructed encoding is not used in the set', + ); case Asn1Tags.sequence: - throw ArgumentError.value(tagNumber, 'tagNumber', - 'Constructed encoding is not used in the sequence'); + throw ArgumentError.value( + tagNumber, + 'tagNumber', + 'Constructed encoding is not used in the sequence', + ); case Asn1Tags.octetString: return DerOctetHelper(_stream as Asn1StreamHelper?); } } throw ArgumentError.value( - tagNumber, 'tagNumber', 'Implicit tagging is not supported'); + tagNumber, + 'tagNumber', + 'Implicit tagging is not supported', + ); } /// internal method @@ -78,7 +87,10 @@ class Asn1Parser { return BerSequenceHelper(this); default: throw ArgumentError.value( - tagValue, 'tagValue', 'Invalid entry in sequence'); + tagValue, + 'tagValue', + 'Invalid entry in sequence', + ); } } @@ -122,20 +134,26 @@ class Asn1Parser { } else { final Asn1StreamHelper stream = Asn1StreamHelper(_stream, length); if ((tag & Asn1Tags.tagged) != 0) { - return BerTagHelper(isConstructed, tagNumber, - Asn1Parser(stream, Asn1Stream.getLimit(stream))); + return BerTagHelper( + isConstructed, + tagNumber, + Asn1Parser(stream, Asn1Stream.getLimit(stream)), + ); } if (isConstructed) { switch (tagNumber) { case Asn1Tags.octetString: return BerOctetHelper( - Asn1Parser(stream, Asn1Stream.getLimit(stream))); + Asn1Parser(stream, Asn1Stream.getLimit(stream)), + ); case Asn1Tags.sequence: return DerSequenceHelper( - Asn1Parser(stream, Asn1Stream.getLimit(stream))); + Asn1Parser(stream, Asn1Stream.getLimit(stream)), + ); case Asn1Tags.setTag: return DerSetHelper( - Asn1Parser(stream, Asn1Stream.getLimit(stream))); + Asn1Parser(stream, Asn1Stream.getLimit(stream)), + ); default: return null; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_stream.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_stream.dart index 8630b8700..4e53adb17 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_stream.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/asn1_stream.dart @@ -30,7 +30,10 @@ class Asn1Stream { /// internal method static Asn1? getPrimitiveObject( - int tagNumber, Asn1StreamHelper stream, List>? buffers) { + int tagNumber, + Asn1StreamHelper stream, + List>? buffers, + ) { switch (tagNumber) { case Asn1Tags.boolean: return DerBoolean.fromBytes(getBytes(stream, buffers!)); @@ -145,8 +148,9 @@ class Asn1Stream { if (isConstructed) { switch (tagNumber) { case Asn1Tags.octetString: - return BerOctet(getBytesfromAsn1EncodeCollection( - getDerEncodableCollection(stream))); + return BerOctet( + getBytesfromAsn1EncodeCollection(getDerEncodableCollection(stream)), + ); case Asn1Tags.sequence: return createDerSequence(stream); case Asn1Tags.setTag: @@ -176,10 +180,15 @@ class Asn1Stream { if (length < 0) { if (!isConstructed) { throw ArgumentError.value( - length, 'length', 'Encodeing length is invalid'); + length, + 'length', + 'Encodeing length is invalid', + ); } - final Asn1Parser sp = - Asn1Parser(Asn1LengthStream(_stream, _limit), _limit); + final Asn1Parser sp = Asn1Parser( + Asn1LengthStream(_stream, _limit), + _limit, + ); if ((tag & Asn1Tags.tagged) != 0) { return BerTagHelper(true, tagNumber, sp).getAsn1(); } @@ -190,7 +199,10 @@ class Asn1Stream { return BerSequenceHelper(sp).getAsn1(); default: throw ArgumentError.value( - tagNumber, 'tag', 'Invalid object in the sequence'); + tagNumber, + 'tag', + 'Invalid object in the sequence', + ); } } else { return buildObject(tag, tagNumber, length); @@ -293,7 +305,7 @@ class Asn1BaseStream extends PdfStreamReader { class Asn1StreamHelper extends Asn1BaseStream { /// internal constructor Asn1StreamHelper(PdfStreamReader? stream, int length) - : super(stream, length) { + : super(stream, length) { if (length < 0) { throw Exception('Invalid length specified.'); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/ber.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/ber.dart index 43a8eb286..98071e0a3 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/ber.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/ber.dart @@ -12,7 +12,7 @@ class BerOctet extends DerOctet { /// internal constructor BerOctet.fromCollection(List octets) - : super(BerOctet.getBytes(octets)) { + : super(BerOctet.getBytes(octets)) { _octets = octets; } @@ -30,10 +30,15 @@ class BerOctet extends DerOctet { final List collection = []; for (int i = 0; i < value!.length; i += 1000) { final int endIndex = min(value!.length, i + 1000); - collection.add(DerOctet(List.generate( - endIndex - i, - (int index) => - ((i + index) < value!.length) ? value![i + index] : 0))); + collection.add( + DerOctet( + List.generate( + endIndex - i, + (int index) => + ((i + index) < value!.length) ? value![i + index] : 0, + ), + ), + ); } return collection; } @@ -144,7 +149,10 @@ class BerTagHelper implements IAsn1Tag { if (isExplicit) { if (!_isConstructed!) { throw ArgumentError.value( - isExplicit, 'isExplicit', 'Implicit tags identified'); + isExplicit, + 'isExplicit', + 'Implicit tags identified', + ); } return _helper.readObject(); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/der.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/der.dart index 549011d0b..f9900a48a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/der.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/asn1/der.dart @@ -181,7 +181,7 @@ class DerBitString extends DerString { 'C', 'D', 'E', - 'F' + 'F', ]; } @@ -207,8 +207,10 @@ class DerBitString extends DerString { @override // ignore: avoid_renaming_method_parameters void encode(DerStream stream) { - final List bytes = - List.generate(getBytes()!.length + 1, (int i) => 0); + final List bytes = List.generate( + getBytes()!.length + 1, + (int i) => 0, + ); bytes[0] = extra!; List.copyRange(bytes, 1, getBytes()!, 0, bytes.length - 1); stream.writeEncoded(Asn1Tags.bitString, bytes); @@ -277,8 +279,9 @@ class DerBmpString extends DerString { DerBmpString(List bytes) { String result = ''; for (int i = 0; i != (bytes.length ~/ 2); i++) { - result += - String.fromCharCode((bytes[2 * i] << 8) | (bytes[2 * i + 1] & 0xff)); + result += String.fromCharCode( + (bytes[2 * i] << 8) | (bytes[2 * i + 1] & 0xff), + ); } _value = result; } @@ -309,8 +312,10 @@ class DerBmpString extends DerString { @override // ignore: avoid_renaming_method_parameters void encode(DerStream stream) { - final List bytes = - List.generate(_value!.length * 2, (int i) => 0); + final List bytes = List.generate( + _value!.length * 2, + (int i) => 0, + ); for (int i = 0; i != _value!.length; i++) { bytes[2 * i] = (_value!.codeUnitAt(i) >> 8).toUnsigned(8); bytes[2 * i + 1] = _value!.codeUnitAt(i).toUnsigned(8); @@ -536,8 +541,10 @@ class DerObjectID extends Asn1 { String? id; // ignore: prefer_final_fields - static List _objects = - List.generate(1024, (int i) => null); + static List _objects = List.generate( + 1024, + (int i) => null, + ); //Implemnetation /// internal method List? getBytes() { @@ -555,8 +562,10 @@ class DerObjectID extends Asn1 { if (token.length <= 18) { stream = writeField(stream, fieldValue: first + int.parse(token)); } else { - stream = writeField(stream, - numberValue: BigInt.parse(token) + BigInt.from(first)); + stream = writeField( + stream, + numberValue: BigInt.parse(token) + BigInt.from(first), + ); } while (oidToken.hasMoreTokens) { token = oidToken.nextToken()!; @@ -570,8 +579,11 @@ class DerObjectID extends Asn1 { } /// internal method - List writeField(List stream, - {int? fieldValue, BigInt? numberValue}) { + List writeField( + List stream, { + int? fieldValue, + BigInt? numberValue, + }) { if (fieldValue != null) { final List result = []; result.add((fieldValue & 0x7f).toUnsigned(8)); @@ -756,7 +768,7 @@ class DerOctet extends Asn1Octet { class DerSequence extends Asn1Sequence { /// internal constructor DerSequence({List? array, Asn1EncodeCollection? collection}) - : super() { + : super() { if (array != null) { // ignore: prefer_foreach for (final Asn1Encode? entry in array) { @@ -788,7 +800,9 @@ class DerSequence extends Asn1Sequence { // ignore: avoid_function_literals_in_foreach_calls objects!.forEach((dynamic asn1) => stream.writeObject(asn1)); outputStream.writeEncoded( - Asn1Tags.sequence | Asn1Tags.constructed, stream.stream); + Asn1Tags.sequence | Asn1Tags.constructed, + stream.stream, + ); } } @@ -816,11 +830,11 @@ class DerSequenceHelper implements IAsn1Collection { class DerSet extends Asn1Set { //Constructor /// internal constructor - DerSet( - {List? array, - Asn1EncodeCollection? collection, - bool? isSort}) - : super() { + DerSet({ + List? array, + Asn1EncodeCollection? collection, + bool? isSort, + }) : super() { if (array != null) { // ignore: avoid_function_literals_in_foreach_calls array.forEach((Asn1Encode? asn1) => addObject(asn1)); @@ -843,7 +857,9 @@ class DerSet extends Asn1Set { // ignore: avoid_function_literals_in_foreach_calls objects.forEach((dynamic entry) => stream.writeObject(entry)); outputStream.writeEncoded( - Asn1Tags.setTag | Asn1Tags.constructed, stream.stream); + Asn1Tags.setTag | Asn1Tags.constructed, + stream.stream, + ); } } @@ -958,7 +974,10 @@ class DerTag extends Asn1Tag { final List? bytes = object!.getDerEncoded(); if (explicit!) { stream.writeEncoded( - tagNumber, bytes, Asn1Tags.constructed | Asn1Tags.tagged); + tagNumber, + bytes, + Asn1Tags.constructed | Asn1Tags.tagged, + ); } else { final int flag = (bytes![0] & Asn1Tags.constructed) | Asn1Tags.tagged; stream.writeTag(flag, tagNumber!); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_cipher.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_cipher.dart index ea4869bd0..346b5623e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_cipher.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_cipher.dart @@ -1,33 +1,57 @@ +import 'dart:typed_data'; + import 'aes_engine.dart'; import 'buffered_block_padding_base.dart'; import 'cipher_block_chaining_mode.dart'; +import 'ipadding.dart'; /// internal class class AesCipher { //Constructor /// internal constructor AesCipher(bool isEncryption, List key, List iv) { - _bp = BufferedCipher(CipherBlockChainingMode(AesEngine())); - final InvalidParameter ip = InvalidParameter(KeyParameter(key), iv); - _bp.initialize(isEncryption, ip); + cipher = PaddedCipherMode( + Pkcs7Padding(), + CipherBlockChainingMode(AesEngine()), + ); + final params = + BlockCipherPaddedParameters( + InvalidParameter( + KeyParameter(Uint8List.fromList(key)), + Uint8List.fromList(iv), + ), + null, + ); + cipher.initialize(isEncryption, params); } //Fields - late BufferedCipher _bp; + late PaddedCipherMode cipher; //Implementation /// internal method List? update(List input, int inputOffset, int inputLength) { - int length = _bp.getUpdateOutputSize(inputLength); - List? output; - if (length > 0) { - output = List.filled(length, 0, growable: true); - } else { - length = 0; + final blockSize = cipher.blockSize; + if (input.length % blockSize != 0) { + throw ArgumentError.value( + 'Data length is not a multiple of block size: ${input.length}', + ); + } + + final output = Uint8List(input.length); + int inOffset = 0; + int outOffset = 0; + + while (inOffset < input.length) { + cipher.processingBlock( + Uint8List.fromList(input), + inOffset, + output, + outOffset, + ); + inOffset += blockSize; + outOffset += blockSize; } - final Map result = - _bp.processBytes(input, inputOffset, inputLength, output, 0); - output = result['output'] as List?; return output; } } @@ -36,9 +60,9 @@ class AesCipher { class AesCipherNoPadding { //Constructor /// internal constructor - AesCipherNoPadding(bool isEncryption, List key) { + AesCipherNoPadding(bool isEncryption, KeyParameter parameters) { _cbc = CipherBlockChainingMode(AesEngine()); - _cbc.initialize(isEncryption, KeyParameter(key)); + _cbc.initialize(isEncryption, parameters); } //Fields @@ -46,1101 +70,24 @@ class AesCipherNoPadding { //Implementation /// internal method - List? processBlock(List? input, int offset, int length) { - if ((length % _cbc.blockSize!) != 0) { - throw ArgumentError.value('Not multiple of block: $length'); - } - List? output = List.filled(length, 0, growable: true); - int tempOffset = 0; - while (length > 0) { - final Map result = - _cbc.processBlock(input, offset, output, tempOffset); - output = result['output'] as List?; - length -= _cbc.blockSize!; - tempOffset += _cbc.blockSize!; - offset += _cbc.blockSize!; - } - return output; - } -} - -/// internal class -class AesEncryptor { - /// internal constructor - AesEncryptor(List key, List iv, bool isEncryption) { - initialize(); - _aes = - Aes(key.length == _blockSize ? KeySize.bits128 : KeySize.bits256, key); - List.copyRange(_buf, 0, iv, 0, iv.length); - List.copyRange(_cbcV!, 0, iv, 0, iv.length); - if (isEncryption) { - _ivOff = _buf.length; - } - _isEncryption = isEncryption; - } - - //Fields - int? _blockSize; - late Aes _aes; - late bool _isEncryption; - late List _buf; - List? _cbcV; - int? _ivOff; - List? _nextBlockVector; - - //Implementation - /// internal method - void initialize() { - _blockSize = 16; - _ivOff = 0; - _buf = List.filled(_blockSize!, 0, growable: true); - _cbcV = List.filled(_blockSize!, 0, growable: true); - _nextBlockVector = List.filled(_blockSize!, 0, growable: true); - } - - /// internal method - int getBlockSize(int length) { - final int total = length + _ivOff!; - final int leftOver = total % _buf.length; - return total - (leftOver == 0 ? _buf.length : leftOver); - } - - /// internal method - void processBytes( - List input, int inOff, int length, List output, int outOff) { - if (length < 0) { - throw ArgumentError.value(length, 'length cannot be negative'); - } - int resultLen = 0; - final int bytesLeft = _buf.length - _ivOff!; - if (length > bytesLeft) { - List.copyRange(_buf, _ivOff!, input, inOff, inOff + bytesLeft); - resultLen += processBlock(_buf, 0, output, outOff); - _ivOff = 0; - length -= bytesLeft; - inOff += bytesLeft; - while (length > _buf.length) { - resultLen += processBlock(input, inOff, output, outOff + resultLen); - length -= _blockSize!; - inOff += _blockSize!; - } - } - List.copyRange(_buf, _ivOff!, input, inOff, inOff + length); - _ivOff = _ivOff! + length; - } - - /// internal method - int processBlock(List input, int inOff, List outBytes, int outOff) { - int length = 0; - if ((inOff + _blockSize!) > input.length) { - throw ArgumentError.value('input buffer length is too short'); - } - if (_isEncryption) { - for (int i = 0; i < _blockSize!; i++) { - _cbcV![i] ^= input[inOff + i]; - } - length = _aes._cipher(_cbcV, outBytes, outOff); - List.copyRange(_cbcV!, 0, outBytes, outOff, outOff + _cbcV!.length); - } else { - List.copyRange(_nextBlockVector!, 0, input, inOff, inOff + _blockSize!); - length = _aes._invCipher(_nextBlockVector, outBytes, outOff); - for (int i = 0; i < _blockSize!; i++) { - outBytes[outOff + i] ^= _cbcV![i]; - } - final List? tmp = _cbcV; - _cbcV = _nextBlockVector; - _nextBlockVector = tmp; - } - return length; - } - - /// internal method - int calculateOutputSize() { - final int total = _ivOff!; - final int leftOver = total % _buf.length; - return leftOver == 0 - ? (_isEncryption ? (total + _buf.length) : total) - : (total - leftOver + _buf.length); - } - - /// internal method - int finalize(List output) { - int resultLen = 0; - const int outOff = 0; - if (_isEncryption) { - if (_ivOff == _blockSize) { - resultLen = processBlock(_buf, 0, output, outOff); - _ivOff = 0; - } - _ivOff = _addPadding(_buf, _ivOff!); - resultLen += processBlock(_buf, 0, output, outOff + resultLen); - } else { - if (_ivOff == _blockSize) { - resultLen = processBlock(_buf, 0, output, 0); - _ivOff = 0; - } - resultLen -= _checkPadding(output); + Uint8List process(Uint8List data) { + final blockSize = _cbc.blockSize!; + if (data.length % blockSize != 0) { + throw ArgumentError.value( + 'Data length is not a multiple of block size: ${data.length}', + ); } - return resultLen; - } - - int _addPadding(List input, int offset) { - final int data = (input.length - offset).toUnsigned(8); - while (offset < input.length) { - input[offset] = data; - offset++; - } - return offset; - } - int _checkPadding(List input) { - int count = input[input.length - 1] & 0xff; - for (int i = 1; i <= count; i++) { - if (input[input.length - i] != count) { - count = 0; - } - } - return count; - } -} + final output = Uint8List(data.length); + int inOffset = 0; + int outOffset = 0; -/// internal class -class Aes { - /// internal constructor - // ignore: library_private_types_in_public_api - Aes(KeySize keySize, List keyBytes) { - _keySize = keySize; - nb = 4; - if (_keySize == KeySize.bits128) { - nk = 4; - nr = 10; - } else if (_keySize == KeySize.bits192) { - nk = 6; - nr = 12; - } else if (_keySize == KeySize.bits256) { - nk = 8; - nr = 14; + while (inOffset < data.length) { + _cbc.processingBlock(data, inOffset, output, outOffset); + inOffset += blockSize; + outOffset += blockSize; } - key = List.filled(nk * 4, 0, growable: true); - List.copyRange(key, 0, keyBytes, 0, key.length); - initialize(); - } - - //Fields - KeySize? _keySize; - /// internal field - late int nb; - - /// internal field - late int nk; - - /// internal field - int? nr; - - /// internal field - late List key; - - /// internal field - late List> sBox; - - /// internal field - late List> iBox; - - /// internal field - late List> rCon; - - /// internal field - late List> keySheduleArray; - - /// internal field - late List> state; - - //Implemenation - /// internal method - void initialize() { - _buildSubstitutionBox(); - _buildInverseSubBox(); - _buildRoundConstants(); - _keyExpansion(); - } - - void _keyExpansion() { - keySheduleArray = List>.generate( - nb * (nr! + 1), (int i) => List.generate(4, (int j) => 0)); - for (int row = 0; row < nk; ++row) { - keySheduleArray[row][0] = key[4 * row]; - keySheduleArray[row][1] = key[(4 * row) + 1]; - keySheduleArray[row][2] = key[(4 * row) + 2]; - keySheduleArray[row][3] = key[(4 * row) + 3]; - } - List temp = List.filled(4, 0, growable: true); - for (int row = nk; row < nb * (nr! + 1); ++row) { - temp[0] = keySheduleArray[row - 1][0]; - temp[1] = keySheduleArray[row - 1][1]; - temp[2] = keySheduleArray[row - 1][2]; - temp[3] = keySheduleArray[row - 1][3]; - if (row % nk == 0) { - temp = _subWord(_rotWord(temp)); - temp[0] = (temp[0].toSigned(32) ^ rCon[row ~/ nk][0].toSigned(32)) - .toUnsigned(8); - temp[1] = (temp[1].toSigned(32) ^ rCon[row ~/ nk][1].toSigned(32)) - .toUnsigned(8); - temp[2] = (temp[2].toSigned(32) ^ rCon[row ~/ nk][2].toSigned(32)) - .toUnsigned(8); - temp[3] = (temp[3].toSigned(32) ^ rCon[row ~/ nk][3].toSigned(32)) - .toUnsigned(8); - } else if (nk > 6 && (row % nk == 4)) { - temp = _subWord(temp); - } - keySheduleArray[row][0] = - (keySheduleArray[row - nk][0].toSigned(32) ^ temp[0].toSigned(32)) - .toUnsigned(8); - keySheduleArray[row][1] = - (keySheduleArray[row - nk][1].toSigned(32) ^ temp[1].toSigned(32)) - .toUnsigned(8); - keySheduleArray[row][2] = - (keySheduleArray[row - nk][2].toSigned(32) ^ temp[2].toSigned(32)) - .toUnsigned(8); - keySheduleArray[row][3] = - (keySheduleArray[row - nk][3].toSigned(32) ^ temp[3].toSigned(32)) - .toUnsigned(8); - } - } - - List _subWord(List word) { - final List result = List.filled(4, 0, growable: true); - result[0] = sBox[word[0] >> 4][word[0] & 0x0f]; - result[1] = sBox[word[1] >> 4][word[1] & 0x0f]; - result[2] = sBox[word[2] >> 4][word[2] & 0x0f]; - result[3] = sBox[word[3] >> 4][word[3] & 0x0f]; - return result; - } - - List _rotWord(List word) { - final List result = List.filled(4, 0, growable: true); - result[0] = word[1]; - result[1] = word[2]; - result[2] = word[3]; - result[3] = word[0]; - return result; - } - - int _cipher(List? input, List output, int outOff) { - initialize(); - state = List>.generate( - 4, (int i) => List.generate(nb, (int j) => 0)); - for (int i = 0; i < (4 * nb); ++i) { - state[i % 4][i ~/ 4] = input![i]; - } - _addRoundKey(0); - for (int round = 1; round <= (nr! - 1); ++round) { - _subBytes(); - _shiftRows(); - _mixColumns(); - _addRoundKey(round); - } - _subBytes(); - _shiftRows(); - _addRoundKey(nr); - for (int i = 0; i < (4 * nb); ++i) { - output[outOff++] = state[i % 4][i ~/ 4]; - } - return 16; - } - - int _invCipher(List? input, List output, int outOff) { - state = List>.generate( - 4, (int i) => List.generate(nb, (int j) => 0)); - for (int i = 0; i < (4 * nb); ++i) { - state[i % 4][i ~/ 4] = input![i]; - } - _addRoundKey(nr); - for (int round = nr! - 1; round >= 1; --round) { - _invShiftRows(); - _invSubBytes(); - _addRoundKey(round); - _invMixColumns(); - } - _invShiftRows(); - _invSubBytes(); - _addRoundKey(0); - for (int i = 0; i < (4 * nb); ++i) { - output[outOff++] = state[i % 4][i ~/ 4]; - } - return 16; - } - - void _mixColumns() { - final List> temp = List>.generate( - 4, (int i) => List.generate(4, (int j) => 0)); - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - temp[r][c] = state[r][c]; - } - } - for (int c = 0; c < 4; ++c) { - state[0][c] = (_gfmultby02(temp[0][c]).toSigned(32) ^ - _gfmultby03(temp[1][c]).toSigned(32) ^ - temp[2][c].toSigned(32) ^ - temp[3][c].toSigned(32)) - .toUnsigned(8); - state[1][c] = (temp[0][c].toSigned(32) ^ - _gfmultby02(temp[1][c]).toSigned(32) ^ - _gfmultby03(temp[2][c]).toSigned(32) ^ - temp[3][c].toSigned(32)) - .toUnsigned(8); - state[2][c] = (temp[0][c].toSigned(32) ^ - temp[1][c].toSigned(32) ^ - _gfmultby02(temp[2][c]).toSigned(32) ^ - _gfmultby03(temp[3][c]).toSigned(32)) - .toUnsigned(8); - state[3][c] = (_gfmultby03(temp[0][c]).toSigned(32) ^ - temp[1][c].toSigned(32) ^ - temp[2][c].toSigned(32) ^ - _gfmultby02(temp[3][c]).toSigned(32)) - .toUnsigned(8); - } - } - - void _invMixColumns() { - final List temp = List.filled(4, 0); - for (int c = 0; c < 4; ++c) { - temp[0] = state[0][c]; - temp[1] = state[1][c]; - temp[2] = state[2][c]; - temp[3] = state[3][c]; - - state[0][c] = (_gfmultby0e(temp[0]) ^ - _gfmultby0b(temp[1]) ^ - _gfmultby0d(temp[2]) ^ - _gfmultby09(temp[3])) - .toUnsigned(8); - state[1][c] = (_gfmultby09(temp[0]) ^ - _gfmultby0e(temp[1]) ^ - _gfmultby0b(temp[2]) ^ - _gfmultby0d(temp[3])) - .toUnsigned(8); - state[2][c] = (_gfmultby0d(temp[0]) ^ - _gfmultby09(temp[1]) ^ - _gfmultby0e(temp[2]) ^ - _gfmultby0b(temp[3])) - .toUnsigned(8); - state[3][c] = (_gfmultby0b(temp[0]) ^ - _gfmultby0d(temp[1]) ^ - _gfmultby09(temp[2]) ^ - _gfmultby0e(temp[3])) - .toUnsigned(8); - } - } - - int _gfmultby0d(int b) { - return (_gfmultby02(_gfmultby02(_gfmultby02(b))).toSigned(32) ^ - _gfmultby02(_gfmultby02(b)).toSigned(32) ^ - b.toSigned(32)) - .toUnsigned(8); - } - - int _gfmultby09(int b) { - return (_gfmultby02(_gfmultby02(_gfmultby02(b))).toSigned(32) ^ - b.toSigned(32)) - .toUnsigned(8); - } - - int _gfmultby0b(int b) { - return (_gfmultby02(_gfmultby02(_gfmultby02(b))).toSigned(32) ^ - _gfmultby02(b).toSigned(32) ^ - b.toSigned(32)) - .toUnsigned(8); - } - - int _gfmultby0e(int b) { - return (_gfmultby02(_gfmultby02(_gfmultby02(b))).toSigned(32) ^ - _gfmultby02(_gfmultby02(b)).toSigned(32) ^ - _gfmultby02(b).toSigned(32)) - .toUnsigned(8); - } - - int _gfmultby02(int b) { - return (b < 0x80 - ? (b << 1).toSigned(32) - : ((b << 1).toSigned(32) ^ 0x1b.toSigned(32))) - .toUnsigned(8); - } - - int _gfmultby03(int b) { - return (_gfmultby02(b).toSigned(32) ^ b.toSigned(32)).toUnsigned(8); - } - - void _shiftRows() { - final List> temp = List>.generate( - 4, (int i) => List.generate(4, (int j) => 0)); - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - temp[r][c] = state[r][c]; - } - } - for (int r = 1; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - state[r][c] = temp[r][(c + r) % nb]; - } - } - } - - void _invShiftRows() { - final List> temp = List>.generate( - 4, (int i) => List.generate(4, (int j) => 0)); - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - temp[r][c] = state[r][c]; - } - } - for (int r = 1; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - state[r][(c + r) % nb] = temp[r][c]; - } - } - } - - void _subBytes() { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - state[r][c] = sBox[(state[r][c] >> 4)][(state[r][c] & 0x0f)]; - } - } - } - - void _invSubBytes() { - for (int r = 0; r < 4; ++r) { - for (int c = 0; c < 4; ++c) { - state[r][c] = iBox[state[r][c] >> 4][state[r][c] & 0x0f]; - } - } - } - - void _addRoundKey(int? round) { - if (round != null) { - final int baseIndex = round * 4; - for (int c = 0; c < 4; ++c) { - final keyColumn = keySheduleArray[baseIndex + c]; - for (int r = 0; r < 4; ++r) { - state[r][c] = (state[r][c] ^ keyColumn[r]).toUnsigned(8); - } - } - } - } - - void _buildRoundConstants() { - rCon = >[ - [0x00, 0x00, 0x00, 0x00], - [0x01, 0x00, 0x00, 0x00], - [0x02, 0x00, 0x00, 0x00], - [0x04, 0x00, 0x00, 0x00], - [0x08, 0x00, 0x00, 0x00], - [0x10, 0x00, 0x00, 0x00], - [0x20, 0x00, 0x00, 0x00], - [0x40, 0x00, 0x00, 0x00], - [0x80, 0x00, 0x00, 0x00], - [0x1b, 0x00, 0x00, 0x00], - [0x36, 0x00, 0x00, 0x00] - ]; - } - - void _buildInverseSubBox() { - iBox = >[ - [ - 0x52, - 0x09, - 0x6a, - 0xd5, - 0x30, - 0x36, - 0xa5, - 0x38, - 0xbf, - 0x40, - 0xa3, - 0x9e, - 0x81, - 0xf3, - 0xd7, - 0xfb - ], - [ - 0x7c, - 0xe3, - 0x39, - 0x82, - 0x9b, - 0x2f, - 0xff, - 0x87, - 0x34, - 0x8e, - 0x43, - 0x44, - 0xc4, - 0xde, - 0xe9, - 0xcb - ], - [ - 0x54, - 0x7b, - 0x94, - 0x32, - 0xa6, - 0xc2, - 0x23, - 0x3d, - 0xee, - 0x4c, - 0x95, - 0x0b, - 0x42, - 0xfa, - 0xc3, - 0x4e - ], - [ - 0x08, - 0x2e, - 0xa1, - 0x66, - 0x28, - 0xd9, - 0x24, - 0xb2, - 0x76, - 0x5b, - 0xa2, - 0x49, - 0x6d, - 0x8b, - 0xd1, - 0x25 - ], - [ - 0x72, - 0xf8, - 0xf6, - 0x64, - 0x86, - 0x68, - 0x98, - 0x16, - 0xd4, - 0xa4, - 0x5c, - 0xcc, - 0x5d, - 0x65, - 0xb6, - 0x92 - ], - [ - 0x6c, - 0x70, - 0x48, - 0x50, - 0xfd, - 0xed, - 0xb9, - 0xda, - 0x5e, - 0x15, - 0x46, - 0x57, - 0xa7, - 0x8d, - 0x9d, - 0x84 - ], - [ - 0x90, - 0xd8, - 0xab, - 0x00, - 0x8c, - 0xbc, - 0xd3, - 0x0a, - 0xf7, - 0xe4, - 0x58, - 0x05, - 0xb8, - 0xb3, - 0x45, - 0x06 - ], - [ - 0xd0, - 0x2c, - 0x1e, - 0x8f, - 0xca, - 0x3f, - 0x0f, - 0x02, - 0xc1, - 0xaf, - 0xbd, - 0x03, - 0x01, - 0x13, - 0x8a, - 0x6b - ], - [ - 0x3a, - 0x91, - 0x11, - 0x41, - 0x4f, - 0x67, - 0xdc, - 0xea, - 0x97, - 0xf2, - 0xcf, - 0xce, - 0xf0, - 0xb4, - 0xe6, - 0x73 - ], - [ - 0x96, - 0xac, - 0x74, - 0x22, - 0xe7, - 0xad, - 0x35, - 0x85, - 0xe2, - 0xf9, - 0x37, - 0xe8, - 0x1c, - 0x75, - 0xdf, - 0x6e - ], - [ - 0x47, - 0xf1, - 0x1a, - 0x71, - 0x1d, - 0x29, - 0xc5, - 0x89, - 0x6f, - 0xb7, - 0x62, - 0x0e, - 0xaa, - 0x18, - 0xbe, - 0x1b - ], - [ - 0xfc, - 0x56, - 0x3e, - 0x4b, - 0xc6, - 0xd2, - 0x79, - 0x20, - 0x9a, - 0xdb, - 0xc0, - 0xfe, - 0x78, - 0xcd, - 0x5a, - 0xf4 - ], - [ - 0x1f, - 0xdd, - 0xa8, - 0x33, - 0x88, - 0x07, - 0xc7, - 0x31, - 0xb1, - 0x12, - 0x10, - 0x59, - 0x27, - 0x80, - 0xec, - 0x5f - ], - [ - 0x60, - 0x51, - 0x7f, - 0xa9, - 0x19, - 0xb5, - 0x4a, - 0x0d, - 0x2d, - 0xe5, - 0x7a, - 0x9f, - 0x93, - 0xc9, - 0x9c, - 0xef - ], - [ - 0xa0, - 0xe0, - 0x3b, - 0x4d, - 0xae, - 0x2a, - 0xf5, - 0xb0, - 0xc8, - 0xeb, - 0xbb, - 0x3c, - 0x83, - 0x53, - 0x99, - 0x61 - ], - [ - 0x17, - 0x2b, - 0x04, - 0x7e, - 0xba, - 0x77, - 0xd6, - 0x26, - 0xe1, - 0x69, - 0x14, - 0x63, - 0x55, - 0x21, - 0x0c, - 0x7d - ] - ]; - } - - void _buildSubstitutionBox() { - sBox = >[ - [ - 0x63, - 0x7c, - 0x77, - 0x7b, - 0xf2, - 0x6b, - 0x6f, - 0xc5, - 0x30, - 0x01, - 0x67, - 0x2b, - 0xfe, - 0xd7, - 0xab, - 0x76 - ], - [ - 0xca, - 0x82, - 0xc9, - 0x7d, - 0xfa, - 0x59, - 0x47, - 0xf0, - 0xad, - 0xd4, - 0xa2, - 0xaf, - 0x9c, - 0xa4, - 0x72, - 0xc0 - ], - [ - 0xb7, - 0xfd, - 0x93, - 0x26, - 0x36, - 0x3f, - 0xf7, - 0xcc, - 0x34, - 0xa5, - 0xe5, - 0xf1, - 0x71, - 0xd8, - 0x31, - 0x15 - ], - [ - 0x04, - 0xc7, - 0x23, - 0xc3, - 0x18, - 0x96, - 0x05, - 0x9a, - 0x07, - 0x12, - 0x80, - 0xe2, - 0xeb, - 0x27, - 0xb2, - 0x75 - ], - [ - 0x09, - 0x83, - 0x2c, - 0x1a, - 0x1b, - 0x6e, - 0x5a, - 0xa0, - 0x52, - 0x3b, - 0xd6, - 0xb3, - 0x29, - 0xe3, - 0x2f, - 0x84 - ], - [ - 0x53, - 0xd1, - 0x00, - 0xed, - 0x20, - 0xfc, - 0xb1, - 0x5b, - 0x6a, - 0xcb, - 0xbe, - 0x39, - 0x4a, - 0x4c, - 0x58, - 0xcf - ], - [ - 0xd0, - 0xef, - 0xaa, - 0xfb, - 0x43, - 0x4d, - 0x33, - 0x85, - 0x45, - 0xf9, - 0x02, - 0x7f, - 0x50, - 0x3c, - 0x9f, - 0xa8 - ], - [ - 0x51, - 0xa3, - 0x40, - 0x8f, - 0x92, - 0x9d, - 0x38, - 0xf5, - 0xbc, - 0xb6, - 0xda, - 0x21, - 0x10, - 0xff, - 0xf3, - 0xd2 - ], - [ - 0xcd, - 0x0c, - 0x13, - 0xec, - 0x5f, - 0x97, - 0x44, - 0x17, - 0xc4, - 0xa7, - 0x7e, - 0x3d, - 0x64, - 0x5d, - 0x19, - 0x73 - ], - [ - 0x60, - 0x81, - 0x4f, - 0xdc, - 0x22, - 0x2a, - 0x90, - 0x88, - 0x46, - 0xee, - 0xb8, - 0x14, - 0xde, - 0x5e, - 0x0b, - 0xdb - ], - [ - 0xe0, - 0x32, - 0x3a, - 0x0a, - 0x49, - 0x06, - 0x24, - 0x5c, - 0xc2, - 0xd3, - 0xac, - 0x62, - 0x91, - 0x95, - 0xe4, - 0x79 - ], - [ - 0xe7, - 0xc8, - 0x37, - 0x6d, - 0x8d, - 0xd5, - 0x4e, - 0xa9, - 0x6c, - 0x56, - 0xf4, - 0xea, - 0x65, - 0x7a, - 0xae, - 0x08 - ], - [ - 0xba, - 0x78, - 0x25, - 0x2e, - 0x1c, - 0xa6, - 0xb4, - 0xc6, - 0xe8, - 0xdd, - 0x74, - 0x1f, - 0x4b, - 0xbd, - 0x8b, - 0x8a - ], - [ - 0x70, - 0x3e, - 0xb5, - 0x66, - 0x48, - 0x03, - 0xf6, - 0x0e, - 0x61, - 0x35, - 0x57, - 0xb9, - 0x86, - 0xc1, - 0x1d, - 0x9e - ], - [ - 0xe1, - 0xf8, - 0x98, - 0x11, - 0x69, - 0xd9, - 0x8e, - 0x94, - 0x9b, - 0x1e, - 0x87, - 0xe9, - 0xce, - 0x55, - 0x28, - 0xdf - ], - [ - 0x8c, - 0xa1, - 0x89, - 0x0d, - 0xbf, - 0xe6, - 0x42, - 0x68, - 0x41, - 0x99, - 0x2d, - 0x0f, - 0xb0, - 0x54, - 0xbb, - 0x16 - ] - ]; + return output; } } - -/// Specifies the key size of AES. -enum KeySize { - /// 128 Bit. - bits128, - - /// 192 Bit. - bits192, - - /// 256 Bit. - bits256 -} diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_engine.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_engine.dart index 6e933cc49..67912dc5c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_engine.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/aes_engine.dart @@ -1,17 +1,27 @@ +import 'dart:typed_data'; +import 'cipher_block_chaining_mode.dart'; import 'ipadding.dart'; /// internal class -class AesEngine implements ICipher { +class AesEngine extends IBlockCipher { //Constructor /// internal constructor AesEngine() { _initializeConstants(); } - //Fields + static const _blockSize = 16; + static const int _m1 = 0x80808080; + static const int _m2 = 0x7f7f7f7f; + static const int _m3 = 0x0000001b; + static const int _m4 = 0xC0C0C0C0; + static const int _m5 = 0x3f3f3f3f; + @override - int? blockSize; - List>? _key; + int get blockSize => _blockSize; + + /// internal field + late List>? _key; /// internal field late int rounds; @@ -81,336 +91,516 @@ class AesEngine implements ICipher { @override bool get isBlock => false; + List _s = List.empty(); + //Initialize @override - void initialize(bool? isEncryption, ICipherParameter? parameter) { + void initialize(bool? isEncryption, covariant KeyParameter? parameter) { if (parameter != null) { - _key = _generateKey(parameter.keys!, isEncryption!); + _key = _generateKey(parameter, isEncryption!); _isEncryption = isEncryption; } + if (_isEncryption!) { + _s = List.from(sBox); + } else { + _s = List.from(sinv); + } } - List> _generateKey(List keys, bool isEncryption) { - final int keyLength = keys.length ~/ 4; - if ((keyLength != 4 && keyLength != 6 && keyLength != 8) || - keyLength * 4 != keys.length) { - throw ArgumentError.value( - keyLength, 'keyLength', 'Key length not 128/192/256 bits.'); + int _removeBlock(dynamic inp, int offset, Endian endian) { + if (inp is! ByteData) { + inp = ByteData.view(inp.buffer, inp.offsetInBytes, inp.length); } - rounds = keyLength + 6; - final List> newKey = List>.generate( - rounds + 1, (int i) => List.generate(4, (int j) => 0)); - int t = 0; - for (int i = 0; i < keys.length; t++) { - newKey[t >> 2][t & 3] = _convertToUnsignedInt32(keys, i); - i += 4; + return inp.getUint32(offset, endian); + } + + List> _generateKey(KeyParameter params, bool isEncryption) { + final key = params.keys; + final keyLen = key.length; + if (keyLen < 16 || keyLen > 32 || (keyLen & 7) != 0) { + throw ArgumentError('Invalid key length : $keyLen'); } - final int k = (rounds + 1) << 2; - for (int i = keyLength; i < k; i++) { - int temp = newKey[(i - 1) >> 2][(i - 1) & 3]; - if (i % keyLength == 0) { - temp = _subWord(_shift(temp, 8)) ^ rcon[(i ~/ keyLength) - 1]; - } else if (keyLength > 6 && (i % keyLength) == 4) { - temp = _subWord(temp); - } - newKey[i >> 2][i & 3] = - newKey[(i - keyLength) >> 2][(i - keyLength) & 3] ^ temp; + final kc = _shiftRight32(keyLen, 2); + rounds = kc + 6; + final w = List.generate(rounds + 1, (int i) => List.filled(4, 0)); + switch (kc) { + case 4: + var col0 = _removeBlock(key, 0, Endian.little); + w[0][0] = col0; + var col1 = _removeBlock(key, 4, Endian.little); + w[0][1] = col1; + var col2 = _removeBlock(key, 8, Endian.little); + w[0][2] = col2; + var col3 = _removeBlock(key, 12, Endian.little); + w[0][3] = col3; + for (var i = 1; i <= 10; ++i) { + final colx = _subWord(_shift(col3, 8)) ^ rcon[i - 1]; + col0 ^= colx; + w[i][0] = col0; + col1 ^= col0; + w[i][1] = col1; + col2 ^= col1; + w[i][2] = col2; + col3 ^= col2; + w[i][3] = col3; + } + break; + case 6: + var col0 = _removeBlock(key, 0, Endian.little); + w[0][0] = col0; + var col1 = _removeBlock(key, 4, Endian.little); + w[0][1] = col1; + var col2 = _removeBlock(key, 8, Endian.little); + w[0][2] = col2; + var col3 = _removeBlock(key, 12, Endian.little); + w[0][3] = col3; + var col4 = _removeBlock(key, 16, Endian.little); + var col5 = _removeBlock(key, 20, Endian.little); + int i = 1, rcon = 1, colx; + for (;;) { + w[i][0] = col4; + w[i][1] = col5; + colx = _subWord(_shift(col5, 8)) ^ rcon; + rcon <<= 1; + col0 ^= colx; + w[i][2] = col0; + col1 ^= col0; + w[i][3] = col1; + col2 ^= col1; + w[i + 1][0] = col2; + col3 ^= col2; + w[i + 1][1] = col3; + col4 ^= col3; + w[i + 1][2] = col4; + col5 ^= col4; + w[i + 1][3] = col5; + colx = _subWord(_shift(col5, 8)) ^ rcon; + rcon <<= 1; + col0 ^= colx; + w[i + 2][0] = col0; + col1 ^= col0; + w[i + 2][1] = col1; + col2 ^= col1; + w[i + 2][2] = col2; + col3 ^= col2; + w[i + 2][3] = col3; + if ((i += 3) >= 13) { + break; + } + col4 ^= col3; + col5 ^= col4; + } + break; + case 8: + { + var col0 = _removeBlock(key, 0, Endian.little); + w[0][0] = col0; + var col1 = _removeBlock(key, 4, Endian.little); + w[0][1] = col1; + var col2 = _removeBlock(key, 8, Endian.little); + w[0][2] = col2; + var col3 = _removeBlock(key, 12, Endian.little); + w[0][3] = col3; + var col4 = _removeBlock(key, 16, Endian.little); + w[1][0] = col4; + var col5 = _removeBlock(key, 20, Endian.little); + w[1][1] = col5; + var col6 = _removeBlock(key, 24, Endian.little); + w[1][2] = col6; + var col7 = _removeBlock(key, 28, Endian.little); + w[1][3] = col7; + int i = 2, rcon = 1, colx; + for (;;) { + colx = _subWord(_shift(col7, 8)) ^ rcon; + rcon <<= 1; + col0 ^= colx; + w[i][0] = col0; + col1 ^= col0; + w[i][1] = col1; + col2 ^= col1; + w[i][2] = col2; + col3 ^= col2; + w[i][3] = col3; + ++i; + if (i >= 15) { + break; + } + colx = _subWord(col3); + col4 ^= colx; + w[i][0] = col4; + col5 ^= col4; + w[i][1] = col5; + col6 ^= col5; + w[i][2] = col6; + col7 ^= col6; + w[i][3] = col7; + ++i; + } + break; + } + default: + { + throw StateError('Invalid key length: ${key.lengthInBytes}'); + } } if (!isEncryption) { - for (int j = 1; j < rounds; j++) { - final List w = newKey[j]; - for (int i = 0; i < 4; i++) { - w[i] = _inverseMultiply(w[i]).toUnsigned(32); + for (var j = 1; j < rounds; j++) { + for (var i = 0; i < 4; i++) { + w[j][i] = _inverseMultiply(w[j][i]); } } } - return newKey; + return w; } @override - Map processBlock( - [List? input, - int? inputOffset, - List? output, - int? outputOffset]) { - ArgumentError.checkNotNull(_key); - _unPackBlock(input!, inputOffset!); + int processingBlock([ + Uint8List? inputBytes, + int? inputOffset, + //need to be unit8list + Uint8List? outputBytes, + //List? output, + int? outputOffset, + ]) { + if ((inputOffset! + (32 / 2)) > inputBytes!.lengthInBytes) { + throw ArgumentError( + 'Invalid length in input buffer : ${inputBytes.lengthInBytes}', + ); + } + + if ((outputOffset! + (32 / 2)) > outputBytes!.lengthInBytes) { + throw ArgumentError( + 'Invalid length in output buffer : ${outputBytes.lengthInBytes}', + ); + } if (_isEncryption!) { - encryptBlock(); + encryptBlock(inputBytes, inputOffset, outputBytes, outputOffset, _key!); } else { - decryptBlock(); + decryptBlock(inputBytes, inputOffset, outputBytes, outputOffset, _key!); } - output = _packBlock(output!, outputOffset!); - return {'length': blockSize, 'output': output}; + + return _blockSize; } @override void reset() {} /// internal method - void encryptBlock() { - final List> keys = _key!; - int r = 0; - List kw = keys[r]; - c0 ^= kw[0]; - c1 ^= kw[1]; - c2 ^= kw[2]; - c3 ^= kw[3]; - int r4; - int r5; - int r6; - int r7; - while (r < (rounds - 2)) { - kw = keys[++r]; - r4 = r0[c0 & 255] ^ - r1[(c1 >> 8) & 255] ^ - r2[(c2 >> 16) & 255] ^ - r3[c3 >> 24] ^ - kw[0]; - r5 = r0[c1 & 255] ^ - r1[(c2 >> 8) & 255] ^ - r2[(c3 >> 16) & 255] ^ - r3[c0 >> 24] ^ - kw[1]; - r6 = r0[c2 & 255] ^ - r1[(c3 >> 8) & 255] ^ - r2[(c0 >> 16) & 255] ^ - r3[c1 >> 24] ^ - kw[2]; - r7 = r0[c3 & 255] ^ - r1[(c0 >> 8) & 255] ^ - r2[(c1 >> 16) & 255] ^ - r3[c2 >> 24] ^ - kw[3]; - kw = keys[++r]; - c0 = r0[r4 & 255] ^ - r1[(r5 >> 8) & 255] ^ - r2[(r6 >> 16) & 255] ^ - r3[r7 >> 24] ^ - kw[0]; - c1 = r0[r5 & 255] ^ - r1[(r6 >> 8) & 255] ^ - r2[(r7 >> 16) & 255] ^ - r3[r4 >> 24] ^ - kw[1]; - c2 = r0[r6 & 255] ^ - r1[(r7 >> 8) & 255] ^ - r2[(r4 >> 16) & 255] ^ - r3[r5 >> 24] ^ - kw[2]; - c3 = r0[r7 & 255] ^ - r1[(r4 >> 8) & 255] ^ - r2[(r5 >> 16) & 255] ^ - r3[r6 >> 24] ^ - kw[3]; + void encryptBlock( + input, + int inOff, + Uint8List out, + int outOff, + List> kw, + ) { + var c0 = _removeBlock(input, inOff + 0, Endian.little); + var c1 = _removeBlock(input, inOff + 4, Endian.little); + var c2 = _removeBlock(input, inOff + 8, Endian.little); + var c3 = _removeBlock(input, inOff + 12, Endian.little); + + var t0 = c0 ^ kw[0][0]; + var t1 = c1 ^ kw[0][1]; + var t2 = c2 ^ kw[0][2]; + + int r = 1, r01, r1, r2, r3 = c3 ^ kw[0][3]; + + while (r < rounds - 1) { + r01 = + r0[t0 & 255] ^ + _shift(r0[(t1 >> 8) & 255], 24) ^ + _shift(r0[(t2 >> 16) & 255], 16) ^ + _shift(r0[(r3 >> 24) & 255], 8) ^ + kw[r][0]; + r1 = + r0[t1 & 255] ^ + _shift(r0[(t2 >> 8) & 255], 24) ^ + _shift(r0[(r3 >> 16) & 255], 16) ^ + _shift(r0[(t0 >> 24) & 255], 8) ^ + kw[r][1]; + r2 = + r0[t2 & 255] ^ + _shift(r0[(r3 >> 8) & 255], 24) ^ + _shift(r0[(t0 >> 16) & 255], 16) ^ + _shift(r0[(t1 >> 24) & 255], 8) ^ + kw[r][2]; + r3 = + r0[r3 & 255] ^ + _shift(r0[(t0 >> 8) & 255], 24) ^ + _shift(r0[(t1 >> 16) & 255], 16) ^ + _shift(r0[(t2 >> 24) & 255], 8) ^ + kw[r++][3]; + t0 = + r0[r01 & 255] ^ + _shift(r0[(r1 >> 8) & 255], 24) ^ + _shift(r0[(r2 >> 16) & 255], 16) ^ + _shift(r0[(r3 >> 24) & 255], 8) ^ + kw[r][0]; + t1 = + r0[r1 & 255] ^ + _shift(r0[(r2 >> 8) & 255], 24) ^ + _shift(r0[(r3 >> 16) & 255], 16) ^ + _shift(r0[(r01 >> 24) & 255], 8) ^ + kw[r][1]; + t2 = + r0[r2 & 255] ^ + _shift(r0[(r3 >> 8) & 255], 24) ^ + _shift(r0[(r01 >> 16) & 255], 16) ^ + _shift(r0[(r1 >> 24) & 255], 8) ^ + kw[r][2]; + r3 = + r0[r3 & 255] ^ + _shift(r0[(r01 >> 8) & 255], 24) ^ + _shift(r0[(r1 >> 16) & 255], 16) ^ + _shift(r0[(r2 >> 24) & 255], 8) ^ + kw[r++][3]; } - kw = keys[++r]; - r4 = r0[c0 & 255] ^ - r1[(c1 >> 8) & 255] ^ - r2[(c2 >> 16) & 255] ^ - r3[c3 >> 24] ^ - kw[0]; - r5 = r0[c1 & 255] ^ - r1[(c2 >> 8) & 255] ^ - r2[(c3 >> 16) & 255] ^ - r3[c0 >> 24] ^ - kw[1]; - r6 = r0[c2 & 255] ^ - r1[(c3 >> 8) & 255] ^ - r2[(c0 >> 16) & 255] ^ - r3[c1 >> 24] ^ - kw[2]; - r7 = r0[c3 & 255] ^ - r1[(c0 >> 8) & 255] ^ - r2[(c1 >> 16) & 255] ^ - r3[c2 >> 24] ^ - kw[3]; - kw = keys[++r]; - c0 = sBox[r4 & 255] ^ - (sBox[(r5 >> 8) & 255].toUnsigned(32) << 8) ^ - (sBox[(r6 >> 16) & 255].toUnsigned(32) << 16) ^ - (sBox[r7 >> 24].toUnsigned(32) << 24) ^ - kw[0]; - c1 = sBox[r5 & 255] ^ - (sBox[(r6 >> 8) & 255].toUnsigned(32) << 8) ^ - (sBox[(r7 >> 16) & 255].toUnsigned(32) << 16) ^ - (sBox[r4 >> 24].toUnsigned(32) << 24) ^ - kw[1]; - c2 = sBox[r6 & 255] ^ - (sBox[(r7 >> 8) & 255].toUnsigned(32) << 8) ^ - (sBox[(r4 >> 16) & 255].toUnsigned(32) << 16) ^ - (sBox[r5 >> 24].toUnsigned(32) << 24) ^ - kw[2]; - c3 = sBox[r7 & 255] ^ - (sBox[(r4 >> 8) & 255].toUnsigned(32) << 8) ^ - (sBox[(r5 >> 16) & 255].toUnsigned(32) << 16) ^ - (sBox[r6 >> 24].toUnsigned(32) << 24) ^ - kw[3]; + + r01 = + r0[t0 & 255] ^ + _shift(r0[(t1 >> 8) & 255], 24) ^ + _shift(r0[(t2 >> 16) & 255], 16) ^ + _shift(r0[(r3 >> 24) & 255], 8) ^ + kw[r][0]; + r1 = + r0[t1 & 255] ^ + _shift(r0[(t2 >> 8) & 255], 24) ^ + _shift(r0[(r3 >> 16) & 255], 16) ^ + _shift(r0[(t0 >> 24) & 255], 8) ^ + kw[r][1]; + r2 = + r0[t2 & 255] ^ + _shift(r0[(r3 >> 8) & 255], 24) ^ + _shift(r0[(t0 >> 16) & 255], 16) ^ + _shift(r0[(t1 >> 24) & 255], 8) ^ + kw[r][2]; + r3 = + r0[r3 & 255] ^ + _shift(r0[(t0 >> 8) & 255], 24) ^ + _shift(r0[(t1 >> 16) & 255], 16) ^ + _shift(r0[(t2 >> 24) & 255], 8) ^ + kw[r++][3]; + + c0 = + (sBox[r01 & 255] & 255) ^ + ((sBox[(r1 >> 8) & 255] & 255) << 8) ^ + ((_s[(r2 >> 16) & 255] & 255) << 16) ^ + (_s[(r3 >> 24) & 255] << 24) ^ + kw[r][0]; + c1 = + (_s[r1 & 255] & 255) ^ + ((sBox[(r2 >> 8) & 255] & 255) << 8) ^ + ((sBox[(r3 >> 16) & 255] & 255) << 16) ^ + (_s[(r01 >> 24) & 255] << 24) ^ + kw[r][1]; + c2 = + (_s[r2 & 255] & 255) ^ + ((sBox[(r3 >> 8) & 255] & 255) << 8) ^ + ((sBox[(r01 >> 16) & 255] & 255) << 16) ^ + (sBox[(r1 >> 24) & 255] << 24) ^ + kw[r][2]; + c3 = + (_s[r3 & 255] & 255) ^ + ((_s[(r01 >> 8) & 255] & 255) << 8) ^ + ((_s[(r1 >> 16) & 255] & 255) << 16) ^ + (sBox[(r2 >> 24) & 255] << 24) ^ + kw[r][3]; + + _addBlock(c0, out, outOff + 0, Endian.little); + _addBlock(c1, out, outOff + 4, Endian.little); + _addBlock(c2, out, outOff + 8, Endian.little); + _addBlock(c3, out, outOff + 12, Endian.little); } /// internal method - void decryptBlock() { - final List> keys = _key!; - int r = rounds; - List kw = keys[r]; - c0 ^= kw[0]; - c1 ^= kw[1]; - c2 ^= kw[2]; - c3 ^= kw[3]; - int r4; - int r5; - int r6; - int r7; - while (r > 2) { - kw = keys[--r]; - r4 = rinv0[c0 & 255] ^ - rinv1[(c3 >> 8) & 255] ^ - rinv2[(c2 >> 16) & 255] ^ - rinv3[c1 >> 24] ^ - kw[0]; - r5 = rinv0[c1 & 255] ^ - rinv1[(c0 >> 8) & 255] ^ - rinv2[(c3 >> 16) & 255] ^ - rinv3[c2 >> 24] ^ - kw[1]; - r6 = rinv0[c2 & 255] ^ - rinv1[(c1 >> 8) & 255] ^ - rinv2[(c0 >> 16) & 255] ^ - rinv3[c3 >> 24] ^ - kw[2]; - r7 = rinv0[c3 & 255] ^ - rinv1[(c2 >> 8) & 255] ^ - rinv2[(c1 >> 16) & 255] ^ - rinv3[c0 >> 24] ^ - kw[3]; - kw = keys[--r]; - c0 = rinv0[r4 & 255] ^ - rinv1[(r7 >> 8) & 255] ^ - rinv2[(r6 >> 16) & 255] ^ - rinv3[r5 >> 24] ^ - kw[0]; - c1 = rinv0[r5 & 255] ^ - rinv1[(r4 >> 8) & 255] ^ - rinv2[(r7 >> 16) & 255] ^ - rinv3[r6 >> 24] ^ - kw[1]; - c2 = rinv0[r6 & 255] ^ - rinv1[(r5 >> 8) & 255] ^ - rinv2[(r4 >> 16) & 255] ^ - rinv3[r7 >> 24] ^ - kw[2]; - c3 = rinv0[r7 & 255] ^ - rinv1[(r6 >> 8) & 255] ^ - rinv2[(r5 >> 16) & 255] ^ - rinv3[r4 >> 24] ^ - kw[3]; + void decryptBlock( + input, + int inOff, + Uint8List out, + int outOff, + List> kw, + ) { + var c0 = _removeBlock(input, inOff + 0, Endian.little); + var c1 = _removeBlock(input, inOff + 4, Endian.little); + var c2 = _removeBlock(input, inOff + 8, Endian.little); + var c3 = _removeBlock(input, inOff + 12, Endian.little); + + var t0 = c0 ^ kw[rounds][0]; + var t1 = c1 ^ kw[rounds][1]; + var t2 = c2 ^ kw[rounds][2]; + + int r = rounds - 1, r01, r1, r2, r3 = c3 ^ kw[rounds][3]; + + while (r > 1) { + r01 = + rinv0[t0 & 255] ^ + _shift(rinv0[(r3 >> 8) & 255], 24) ^ + _shift(rinv0[(t2 >> 16) & 255], 16) ^ + _shift(rinv0[(t1 >> 24) & 255], 8) ^ + kw[r][0]; + r1 = + rinv0[t1 & 255] ^ + _shift(rinv0[(t0 >> 8) & 255], 24) ^ + _shift(rinv0[(r3 >> 16) & 255], 16) ^ + _shift(rinv0[(t2 >> 24) & 255], 8) ^ + kw[r][1]; + r2 = + rinv0[t2 & 255] ^ + _shift(rinv0[(t1 >> 8) & 255], 24) ^ + _shift(rinv0[(t0 >> 16) & 255], 16) ^ + _shift(rinv0[(r3 >> 24) & 255], 8) ^ + kw[r][2]; + r3 = + rinv0[r3 & 255] ^ + _shift(rinv0[(t2 >> 8) & 255], 24) ^ + _shift(rinv0[(t1 >> 16) & 255], 16) ^ + _shift(rinv0[(t0 >> 24) & 255], 8) ^ + kw[r--][3]; + t0 = + rinv0[r01 & 255] ^ + _shift(rinv0[(r3 >> 8) & 255], 24) ^ + _shift(rinv0[(r2 >> 16) & 255], 16) ^ + _shift(rinv0[(r1 >> 24) & 255], 8) ^ + kw[r][0]; + t1 = + rinv0[r1 & 255] ^ + _shift(rinv0[(r01 >> 8) & 255], 24) ^ + _shift(rinv0[(r3 >> 16) & 255], 16) ^ + _shift(rinv0[(r2 >> 24) & 255], 8) ^ + kw[r][1]; + t2 = + rinv0[r2 & 255] ^ + _shift(rinv0[(r1 >> 8) & 255], 24) ^ + _shift(rinv0[(r01 >> 16) & 255], 16) ^ + _shift(rinv0[(r3 >> 24) & 255], 8) ^ + kw[r][2]; + r3 = + rinv0[r3 & 255] ^ + _shift(rinv0[(r2 >> 8) & 255], 24) ^ + _shift(rinv0[(r1 >> 16) & 255], 16) ^ + _shift(rinv0[(r01 >> 24) & 255], 8) ^ + kw[r--][3]; } - kw = keys[--r]; - r4 = rinv0[c0 & 255] ^ - rinv1[(c3 >> 8) & 255] ^ - rinv2[(c2 >> 16) & 255] ^ - rinv3[c1 >> 24] ^ - kw[0]; - r5 = rinv0[c1 & 255] ^ - rinv1[(c0 >> 8) & 255] ^ - rinv2[(c3 >> 16) & 255] ^ - rinv3[c2 >> 24] ^ - kw[1]; - r6 = rinv0[c2 & 255] ^ - rinv1[(c1 >> 8) & 255] ^ - rinv2[(c0 >> 16) & 255] ^ - rinv3[c3 >> 24] ^ - kw[2]; - r7 = rinv0[c3 & 255] ^ - rinv1[(c2 >> 8) & 255] ^ - rinv2[(c1 >> 16) & 255] ^ - rinv3[c0 >> 24] ^ - kw[3]; + r01 = + rinv0[t0 & 255] ^ + _shift(rinv0[(r3 >> 8) & 255], 24) ^ + _shift(rinv0[(t2 >> 16) & 255], 16) ^ + _shift(rinv0[(t1 >> 24) & 255], 8) ^ + kw[r][0]; + r1 = + rinv0[t1 & 255] ^ + _shift(rinv0[(t0 >> 8) & 255], 24) ^ + _shift(rinv0[(r3 >> 16) & 255], 16) ^ + _shift(rinv0[(t2 >> 24) & 255], 8) ^ + kw[r][1]; + r2 = + rinv0[t2 & 255] ^ + _shift(rinv0[(t1 >> 8) & 255], 24) ^ + _shift(rinv0[(t0 >> 16) & 255], 16) ^ + _shift(rinv0[(r3 >> 24) & 255], 8) ^ + kw[r][2]; + r3 = + rinv0[r3 & 255] ^ + _shift(rinv0[(t2 >> 8) & 255], 24) ^ + _shift(rinv0[(t1 >> 16) & 255], 16) ^ + _shift(rinv0[(t0 >> 24) & 255], 8) ^ + kw[r][3]; + + c0 = + (sinv[r01 & 255] & 255) ^ + ((_s[(r3 >> 8) & 255] & 255) << 8) ^ + ((_s[(r2 >> 16) & 255] & 255) << 16) ^ + (sinv[(r1 >> 24) & 255] << 24) ^ + kw[0][0]; + c1 = + (_s[r1 & 255] & 255) ^ + ((_s[(r01 >> 8) & 255] & 255) << 8) ^ + ((sinv[(r3 >> 16) & 255] & 255) << 16) ^ + (_s[(r2 >> 24) & 255] << 24) ^ + kw[0][1]; + c2 = + (_s[r2 & 255] & 255) ^ + ((sinv[(r1 >> 8) & 255] & 255) << 8) ^ + ((sinv[(r01 >> 16) & 255] & 255) << 16) ^ + (_s[(r3 >> 24) & 255] << 24) ^ + kw[0][2]; + c3 = + (sinv[r3 & 255] & 255) ^ + ((_s[(r2 >> 8) & 255] & 255) << 8) ^ + ((_s[(r1 >> 16) & 255] & 255) << 16) ^ + (_s[(r01 >> 24) & 255] << 24) ^ + kw[0][3]; - kw = keys[--r]; - c0 = sinv[r4 & 255].toUnsigned(32) ^ - (sinv[(r7 >> 8) & 255].toUnsigned(32) << 8) ^ - (sinv[(r6 >> 16) & 255].toUnsigned(32) << 16) ^ - (sinv[r5 >> 24].toUnsigned(32) << 24) ^ - kw[0]; - c1 = sinv[r5 & 255].toUnsigned(32) ^ - (sinv[(r4 >> 8) & 255].toUnsigned(32) << 8) ^ - (sinv[(r7 >> 16) & 255].toUnsigned(32) << 16) ^ - (sinv[r6 >> 24].toUnsigned(32) << 24) ^ - kw[1]; - c2 = sinv[r6 & 255].toUnsigned(32) ^ - (sinv[(r5 >> 8) & 255].toUnsigned(32) << 8) ^ - (sinv[(r4 >> 16) & 255].toUnsigned(32) << 16) ^ - (sinv[r7 >> 24].toUnsigned(32) << 24) ^ - kw[2]; - c3 = sinv[r7 & 255].toUnsigned(32) ^ - (sinv[(r6 >> 8) & 255].toUnsigned(32) << 8) ^ - (sinv[(r5 >> 16) & 255].toUnsigned(32) << 16) ^ - (sinv[r4 >> 24].toUnsigned(32) << 24) ^ - kw[3]; + _addBlock(c0, out, outOff + 0, Endian.little); + _addBlock(c1, out, outOff + 4, Endian.little); + _addBlock(c2, out, outOff + 8, Endian.little); + _addBlock(c3, out, outOff + 12, Endian.little); } - int _convertToUnsignedInt32(List bytes, int offset) { - return bytes[offset].toUnsigned(32) | - (bytes[offset + 1].toUnsigned(32) << 8) | - (bytes[offset + 2].toUnsigned(32) << 16) | - (bytes[offset + 3].toUnsigned(32) << 24); + void _addBlock(int x, dynamic out, int offset, Endian endian) { + assert((x >= 0) && (x <= _mask_32)); + if (out is! ByteData) { + out = ByteData.view( + out.buffer as ByteBuffer, + out.offsetInBytes, + out.length, + ); + } + out.setUint32(offset, x, endian); } - List _convertFromUnsignedInt32(int n, List bytes, int offset) { - bytes[offset] = n.toUnsigned(8); - bytes[offset + 1] = (n >> 8).toUnsigned(8); - bytes[offset + 2] = (n >> 16).toUnsigned(8); - bytes[offset + 3] = (n >> 24).toUnsigned(8); - return bytes; + int _shift(int r, int shift) => _rotateRight32(r, shift); + + int _rotateRight32(int x, int n) { + assert(n >= 0); + assert((x >= 0) && (x <= _mask_32)); + n &= _mask_5; + return (x >> n) | _shiftLeft32(x, 32 - n); } - int _shift(int r, int shift) { - return (r >> shift).toSigned(32) | (r << (32 - shift)).toSigned(32); + int _shiftRight32(int x, int n) { + assert((x >= 0) && (x <= _mask_32)); + n &= _mask_5; + return x >> n; } - int _subWord(int x) { - return sBox[x & 255].toUnsigned(32) | - (sBox[(x >> 8) & 255].toUnsigned(32) << 8) | - (sBox[(x >> 16) & 255].toUnsigned(32) << 16) | - (sBox[(x >> 24) & 255].toUnsigned(32) << 24); + int _shiftLeft32(int x, int n) { + assert((x >= 0) && (x <= _mask_32)); + n &= _mask_5; + x &= _mask_bits[n]; + return (x << n) & _mask_32; } - int _inverseMultiply(int x) { - final int x1 = _mulX(x); - final int x2 = _mulX(x1); - final int x3 = _mulX(x2); - final int x4 = x ^ x3; - return x1 ^ - x2 ^ - x3 ^ - _shift(x1 ^ x4, 8) ^ - _shift(x2 ^ x4, 16) ^ - _shift(x4, 24); + int _subWord(int x) { + return sBox[x & 255] & 255 | + ((sBox[(x >> 8) & 255] & 255) << 8) | + ((sBox[(x >> 16) & 255] & 255) << 16) | + sBox[(x >> 24) & 255] << 24; } - int _mulX(int x) { - return ((x & mix2) << 1) ^ (((x & mix1) >> 7) * mix3); + int _inverseMultiply(int x) { + int t0, t1; + t0 = x; + t1 = t0 ^ _shift(t0, 8); + t0 ^= _xMultiply(t1); + t1 ^= _x2Multiply(t0); + t0 ^= t1 ^ _shift(t1, 16); + return t0; } - void _unPackBlock(List bytes, int offset) { - c0 = _convertToUnsignedInt32(bytes, offset); - c1 = _convertToUnsignedInt32(bytes, offset + 4); - c2 = _convertToUnsignedInt32(bytes, offset + 8); - c3 = _convertToUnsignedInt32(bytes, offset + 12); + int _xMultiply(int x) { + final lsr = _shiftRight32(x & _m1, 7); + return ((x & _m2) << 1) ^ lsr * _m3; } - List _packBlock(List bytes, int offset) { - bytes = _convertFromUnsignedInt32(c0, bytes, offset); - bytes = _convertFromUnsignedInt32(c1, bytes, offset + 4); - bytes = _convertFromUnsignedInt32(c2, bytes, offset + 8); - bytes = _convertFromUnsignedInt32(c3, bytes, offset + 12); - return bytes; + int _x2Multiply(int x) { + final t0 = _shiftLeft32(x & _m5, 2); + var t1 = x & _m4; + t1 ^= _shiftRight32(t1, 1); + return t0 ^ _shiftRight32(t1, 2) ^ _shiftRight32(t1, 5); } void _initializeConstants() { - blockSize = 16; rounds = 0; _isEncryption = false; mix1 = 0x80808080; @@ -450,7 +640,7 @@ class AesEngine implements ICipher { 0xfa, 0xef, 0xc5, - 0x91 + 0x91, ]; sBox = [ 99, @@ -708,7 +898,7 @@ class AesEngine implements ICipher { 176, 84, 187, - 22 + 22, ]; r0 = [ 0xa56363c6, @@ -966,7 +1156,7 @@ class AesEngine implements ICipher { 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, - 0x3a16162c + 0x3a16162c, ]; r1 = [ 0x6363c6a5, @@ -1224,7 +1414,7 @@ class AesEngine implements ICipher { 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, - 0x16162c3a + 0x16162c3a, ]; r2 = [ 0x63c6a563, @@ -1482,7 +1672,7 @@ class AesEngine implements ICipher { 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, - 0x162c3a16 + 0x162c3a16, ]; r3 = [ 0xc6a56363, @@ -1740,7 +1930,7 @@ class AesEngine implements ICipher { 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, - 0x2c3a1616 + 0x2c3a1616, ]; sinv = [ 82, @@ -1998,7 +2188,7 @@ class AesEngine implements ICipher { 85, 33, 12, - 125 + 125, ]; rinv0 = [ 0x50a7f451, @@ -2256,7 +2446,7 @@ class AesEngine implements ICipher { 0x6184cb7b, 0x70b632d5, 0x745c6c48, - 0x4257b8d0 + 0x4257b8d0, ]; rinv1 = [ 0xa7f45150, @@ -2514,7 +2704,7 @@ class AesEngine implements ICipher { 0x84cb7b61, 0xb632d570, 0x5c6c4874, - 0x57b8d042 + 0x57b8d042, ]; rinv2 = [ 0xf45150a7, @@ -2772,7 +2962,7 @@ class AesEngine implements ICipher { 0xcb7b6184, 0x32d570b6, 0x6c48745c, - 0xb8d04257 + 0xb8d04257, ]; rinv3 = [ 0x5150a7f4, @@ -3030,7 +3220,45 @@ class AesEngine implements ICipher { 0x7b6184cb, 0xd570b632, 0x48745c6c, - 0xd04257b8 + 0xd04257b8, ]; } } + +const _mask_32 = 0xFFFFFFFF; +const _mask_5 = 0x1F; +const _mask_bits = [ + 0xFFFFFFFF, + 0x7FFFFFFF, + 0x3FFFFFFF, + 0x1FFFFFFF, + 0x0FFFFFFF, + 0x07FFFFFF, + 0x03FFFFFF, + 0x01FFFFFF, + 0x00FFFFFF, + 0x007FFFFF, + 0x003FFFFF, + 0x001FFFFF, + 0x000FFFFF, + 0x0007FFFF, + 0x0003FFFF, + 0x0001FFFF, + 0x0000FFFF, + 0x00007FFF, + 0x00003FFF, + 0x00001FFF, + 0x00000FFF, + 0x000007FF, + 0x000003FF, + 0x000001FF, + 0x000000FF, + 0x0000007F, + 0x0000003F, + 0x0000001F, + 0x0000000F, + 0x00000007, + 0x00000003, + 0x00000001, + 0x00000000, +]; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/buffered_block_padding_base.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/buffered_block_padding_base.dart index 31806f23d..e83b1dff8 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/buffered_block_padding_base.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/buffered_block_padding_base.dart @@ -1,10 +1,9 @@ -import 'dart:math'; +import 'dart:typed_data'; import '../asn1/asn1.dart'; import 'ipadding.dart'; -/// internal class -abstract class BufferedBlockPaddingBase implements IBufferedCipher { +abstract class BufferedBlockPaddingBase extends IBufferedCipher { /// internal constructor BufferedBlockPaddingBase(); //Fields @@ -52,13 +51,21 @@ abstract class BufferedBlockPaddingBase implements IBufferedCipher { List? readBytes(List input, int inOff, int length); @override Map processByteFromValues( - List input, List output, int outOff) { + List input, + List output, + int outOff, + ) { return processBytes(input, 0, input.length, output, outOff); } @override Map processBytes( - List input, int inOff, int length, List? output, int outOff) { + List input, + int inOff, + int length, + List? output, + int outOff, + ) { final List? outBytes = readBytes(input, inOff, length); if (outBytes == null) { return {'length': 0, 'output': output}; @@ -99,15 +106,28 @@ abstract class BufferedBlockPaddingBase implements IBufferedCipher { @override Map copyFinal( - List input, List output, int outOff) { + List input, + List output, + int outOff, + ) { return readFinalValues(input, 0, input.length, output, outOff); } @override Map readFinalValues( - List input, int inOff, int length, List? output, int outOff) { - Map result = - processBytes(input, inOff, length, output, outOff); + List input, + int inOff, + int length, + List? output, + int outOff, + ) { + Map result = processBytes( + input, + inOff, + length, + output, + outOff, + ); int len = result['length'] as int; output = result['output'] as List?; result = writeFinal(output!, outOff + len); @@ -205,8 +225,13 @@ class BufferedCipher extends BufferedBlockPaddingBase { final int outLength = getUpdateOutputSize(length); List? outBytes = outLength > 0 ? List.generate(outLength, (int i) => 0) : null; - final Map result = - processBytes(input, inOff, length, outBytes, 0); + final Map result = processBytes( + input, + inOff, + length, + outBytes, + 0, + ); final int? position = result['length'] as int?; outBytes = result['output'] as List?; if (outLength > 0 && position! < outLength) { @@ -219,8 +244,13 @@ class BufferedCipher extends BufferedBlockPaddingBase { /// internal method @override - Map processBytes(List? input, int inOffset, int length, - List? output, int outOffset) { + Map processBytes( + List? input, + int inOffset, + int length, + List? output, + int outOffset, + ) { Map? result; if (length < 1) { return {'length': 0, 'output': output}; @@ -239,7 +269,11 @@ class BufferedCipher extends BufferedBlockPaddingBase { inOffset += gapLength; while (length > _bytes!.length) { result = _cipher.processBlock( - input, inOffset, output, outOffset + resultLength); + input, + inOffset, + output, + outOffset + resultLength, + ); resultLength = resultLength + result!['length']! as int; output = result['output'] as List?; length -= blockSize!; @@ -249,8 +283,12 @@ class BufferedCipher extends BufferedBlockPaddingBase { List.copyRange(_bytes!, _offset!, input!, inOffset, inOffset + length); _offset = _offset! + length; if (_offset == _bytes!.length) { - result = - _cipher.processBlock(_bytes, 0, output, outOffset + resultLength); + result = _cipher.processBlock( + _bytes, + 0, + output, + outOffset + resultLength, + ); resultLength = resultLength + result!['length']! as int; output = result['output'] as List?; _offset = 0; @@ -299,8 +337,10 @@ class BufferedCipher extends BufferedBlockPaddingBase { position = position! + result['length']! as int; outBytes = result['output'] as List?; if (position < outBytes!.length) { - final List tempBytes = - List.generate(position, (int i) => 0); + final List tempBytes = List.generate( + position, + (int i) => 0, + ); List.copyRange(tempBytes, 0, outBytes, 0, position); outBytes = tempBytes; } @@ -327,7 +367,6 @@ class BufferedCipher extends BufferedBlockPaddingBase { } } -/// internal class class BufferedBlockPadding extends BufferedCipher { /// internal constructor BufferedBlockPadding(ICipher cipher, [IPadding? padding]) : super(cipher) { @@ -342,10 +381,9 @@ class BufferedBlockPadding extends BufferedCipher { @override void initialize(bool isEncryption, ICipherParameter? parameters) { _isEncryption = isEncryption; - Random? initRandom; reset(); - _padding.initialize(initRandom); _cipher.initialize(isEncryption, parameters); + _padding.initialize(parameters); } @override @@ -387,8 +425,13 @@ class BufferedBlockPadding extends BufferedCipher { } @override - Map processBytes(List? input, int inOffset, int length, - List? output, int outOffset) { + Map processBytes( + List? input, + int inOffset, + int length, + List? output, + int outOffset, + ) { if (length < 0) { throw ArgumentError.value(length, 'length', 'Invalid length'); } @@ -412,7 +455,11 @@ class BufferedBlockPadding extends BufferedCipher { inOffset += gapLength; while (length > _bytes!.length) { result = _cipher.processBlock( - input, inOffset, output, outOffset + resultLength); + input, + inOffset, + output, + outOffset + resultLength, + ); resultLength += result!['length']! as int; output = result['output'] as List?; length -= blockSize!; @@ -434,14 +481,17 @@ class BufferedBlockPadding extends BufferedCipher { if ((outOff! + 2 * blockSize!) > output!.length) { reset(); throw ArgumentError.value( - output, 'output', 'output buffer too short'); + output, + 'output', + 'output buffer too short', + ); } result = _cipher.processBlock(_bytes, 0, output, outOff); resultLen = result!['length'] as int; output = result['output'] as List?; _offset = 0; } - _padding.addPadding(_bytes, _offset); + _padding.addPadding(Uint8List.fromList(_bytes!), _offset!); result = _cipher.processBlock(_bytes, 0, output, outOff! + resultLen); resultLen += result!['length'] as int; output = result['output'] as List?; @@ -457,7 +507,7 @@ class BufferedBlockPadding extends BufferedCipher { throw ArgumentError.value(output, 'output', 'incomplete in decryption'); } try { - resultLen -= _padding.count(_bytes)!; + resultLen -= _padding.count(Uint8List.fromList(_bytes!)); List.copyRange(output!, outOff!, _bytes!, 0, resultLen); } finally { reset(); @@ -467,6 +517,119 @@ class BufferedBlockPadding extends BufferedCipher { } } +class PaddedCipherMode extends IBufferedCipher { + /// internal constructor + PaddedCipherMode(this.padding, this.cipher); + @override + final IPadding padding; + @override + final ICipher cipher; + + @override + String get algorithmName => '${cipher.algorithmName}/${padding.paddingName}'; + + @override + int get blockSize => cipher.blockSize!; + + bool? _isEncryption; + + @override + void reset() { + _isEncryption = null; + cipher.reset(); + } + + //Implemntation + @override + void initialize( + bool forEncryption, + covariant BlockCipherPaddedParameters parameters, + ) { + _isEncryption = forEncryption; + cipher.initialize(forEncryption, parameters.underlyingKeyParameters); + padding.initialize(parameters.paddingCipherParameters); + } + + @override + Uint8List process(Uint8List data) { + final inputBlocks = (data.length + blockSize - 1) ~/ blockSize; + int outputBlocks; + if (_isEncryption ?? false) { + outputBlocks = (data.length + blockSize) ~/ blockSize; + } else { + if ((data.length % blockSize) != 0) { + throw ArgumentError( + 'Input data length is not a multiple of the size of cipher block', + ); + } + outputBlocks = inputBlocks; + } + final out = Uint8List(outputBlocks * blockSize); + for (var i = 0; i < (inputBlocks - 1); i++) { + final offset = i * blockSize; + processingBlock(data, offset, out, offset); + } + final lastBlockOffset = (inputBlocks - 1) * blockSize; + final lastBlockSize = doFinalProcess( + data, + lastBlockOffset, + out, + lastBlockOffset, + ); + return out.sublist(0, lastBlockOffset + lastBlockSize); + } + + @override + int? processingBlock( + Uint8List inputBytes, + int inputOffset, + Uint8List outputBytes, + int outputOffset, + ) { + return cipher.processingBlock( + inputBytes, + inputOffset, + outputBytes, + outputOffset, + ); + } + + @override + int doFinalProcess( + Uint8List inputBytes, + int inputOffset, + Uint8List outputBytes, + int outputOffset, + ) { + if (_isEncryption ?? false) { + final lastBlock = Uint8List(blockSize) + ..setAll(0, inputBytes.sublist(inputOffset)); + final remainderBlock = inputBytes.length - inputOffset; + + if (remainderBlock < blockSize) { + padding.addPadding(lastBlock, inputBytes.length - inputOffset); + processingBlock(lastBlock, 0, outputBytes, outputOffset); + return blockSize; + } else { + processingBlock(inputBytes, inputOffset, outputBytes, outputOffset); + padding.addPadding(lastBlock, 0); + processingBlock(lastBlock, 0, outputBytes, outputOffset + blockSize); + return 2 * blockSize; + } + } else { + processingBlock(inputBytes, inputOffset, outputBytes, outputOffset); + final padCount = padding.count(outputBytes.sublist(outputOffset)); + final padOffsetInBlock = blockSize - padCount; + outputBytes.fillRange( + outputOffset + padOffsetInBlock, + outputBytes.length, + 0, + ); + return padOffsetInBlock; + } + } +} + /// internal class class Pkcs7Padding implements IPadding { /// internal constructor @@ -476,11 +639,11 @@ class Pkcs7Padding implements IPadding { String get paddingName => Asn1.pkcs7; //Implementation @override - void initialize(Random? random) {} + void initialize([ICipherParameter? params]) {} @override - int addPadding(List? bytes, int? offset) { - final int code = (bytes!.length - offset!).toUnsigned(8); - while (offset! < bytes.length) { + int addPadding(Uint8List bytes, int offset) { + final int code = bytes.length - offset; + while (offset < bytes.length) { bytes[offset] = code; offset++; } @@ -488,8 +651,8 @@ class Pkcs7Padding implements IPadding { } @override - int count(List? input) { - final int count = input![input.length - 1].toSigned(32); + int count(Uint8List input) { + final int count = _clipByte(input[input.length - 1]); if (count < 1 || count > input.length) { throw ArgumentError.value(input, 'input', 'Invalid pad'); } @@ -501,3 +664,19 @@ class Pkcs7Padding implements IPadding { return count; } } + +int _clipByte(int x) => x & _mask_8; +const _mask_8 = 0xFF; + +class BlockCipherPaddedParameters< + KeyCipherParameters extends ICipherParameter?, + PaddingCipherParameters extends ICipherParameter? +> + implements ICipherParameter { + BlockCipherPaddedParameters( + this.underlyingKeyParameters, + this.paddingCipherParameters, + ); + final KeyCipherParameters? underlyingKeyParameters; + final PaddingCipherParameters? paddingCipherParameters; +} diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/cipher_block_chaining_mode.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/cipher_block_chaining_mode.dart index fa386be6d..c8a01cea4 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/cipher_block_chaining_mode.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/cipher_block_chaining_mode.dart @@ -1,73 +1,91 @@ +import 'dart:typed_data'; import 'ipadding.dart'; /// internal class -class CipherBlockChainingMode implements ICipher { +class CipherBlockChainingMode extends IBlockCipher { //Constructor /// internal constructor CipherBlockChainingMode(ICipher? cipher) { _cipher = cipher; _size = _cipher!.blockSize; - _bytes = List.filled(_size!, 0, growable: true); - _cbcBytes = List.filled(_size!, 0, growable: true); - _cbcNextBytes = List.filled(_size!, 0, growable: true); + + _bytes = Uint8List(_size!); + _cbcBytes = Uint8List(_size!); + _cbcNextBytes = Uint8List(_size!); + _isEncryption = false; } //Fields ICipher? _cipher; int? _size; - late List _bytes; - List? _cbcBytes; - List? _cbcNextBytes; + late Uint8List _bytes; + Uint8List? _cbcBytes; + Uint8List? _cbcNextBytes; bool? _isEncryption; //Fields @override int? get blockSize => _cipher!.blockSize; @override - String get algorithmName => '${_cipher!.algorithmName!}/CBC'; + String get algorithmName => '${_cipher!.algorithmName}/CBC'; @override bool get isBlock => false; //Implementation @override - void initialize(bool? isEncryption, ICipherParameter? parameters) { + void initialize(bool isEncryption, ICipherParameter? parameters) { final bool? oldEncryption = _isEncryption; _isEncryption = isEncryption; - if (parameters is InvalidParameter) { - final List bytes = parameters.keys; - if (bytes.length != _size) { - throw ArgumentError.value(parameters, 'Invalid size in block'); - } - List.copyRange(_bytes, 0, bytes, 0, bytes.length); - parameters = parameters.parameters; - } - reset(); if (parameters != null) { - _cipher!.initialize(_isEncryption, parameters); + if (parameters is InvalidParameter) { + final List iv = parameters.keys!; + if (iv.length != blockSize) { + throw ArgumentError.value( + iv, + 'Initialization vector must be the same length as block size', + ); + } + _bytes.setAll(0, iv); + _cipher!.initialize(isEncryption, parameters.parameters); + } else { + _cipher!.initialize(isEncryption, parameters); + } + reset(); } else if (oldEncryption != _isEncryption) { - throw ArgumentError.value(oldEncryption, - 'cannot change encrypting state without providing key.'); + throw ArgumentError.value( + oldEncryption, + 'cannot change encrypting state without providing key.', + ); } } @override void reset() { - _cbcBytes = List.from(_bytes); - _cbcNextBytes = List.filled(_size!, 0, growable: true); + _cbcBytes!.setAll(0, _bytes); + _cbcNextBytes!.fillRange(0, _cbcNextBytes!.length, 0); + _cipher!.reset(); } @override - Map processBlock(List? inputBytes, int inputOffset, - List? outputBytes, int? outputOffset) { + Map processBlock( + List? inBytes, + int inOffset, + List? outBytes, + int? outOffset, + ) { return _isEncryption! - ? encryptBlock(inputBytes!, inputOffset, outputBytes, outputOffset!) - : decryptBlock(inputBytes!, inputOffset, outputBytes, outputOffset); + ? encryptionBlock(inBytes!, inOffset, outBytes, outOffset!) + : decryptionBlock(inBytes!, inOffset, outBytes, outOffset); } /// internal method - Map encryptBlock(List inputBytes, int inputOffset, - List? outputBytes, int outputOffset) { + Map encryptionBlock( + List inputBytes, + int inputOffset, + List? outputBytes, + int outputOffset, + ) { if ((inputOffset + _size!) > inputBytes.length) { throw ArgumentError.value('Invalid length in input bytes'); } @@ -77,90 +95,162 @@ class CipherBlockChainingMode implements ICipher { final Map result = _cipher!.processBlock(_cbcBytes, 0, outputBytes, outputOffset)!; outputBytes = result['output'] as List?; - List.copyRange(_cbcBytes!, 0, outputBytes!, outputOffset, - outputOffset + _cbcBytes!.length); + List.copyRange( + _cbcBytes!, + 0, + outputBytes!, + outputOffset, + outputOffset + _cbcBytes!.length, + ); return result; } /// internal method - Map decryptBlock(List inputBytes, int inputOffset, - List? outputBytes, int? outputOffset) { + Map decryptionBlock( + List inputBytes, + int inputOffset, + List? outputBytes, + int? outputOffset, + ) { if ((inputOffset + _size!) > inputBytes.length) { throw ArgumentError.value('Invalid length in input bytes'); } List.copyRange( - _cbcNextBytes!, 0, inputBytes, inputOffset, inputOffset + _size!); - final Map result = _cipher! - .processBlock(inputBytes, inputOffset, outputBytes, outputOffset)!; - outputBytes = result['output'] as List?; + _cbcNextBytes!, + 0, + inputBytes, + inputOffset, + inputOffset + _size!, + ); + final Map? result = _cipher!.processBlock( + inputBytes, + inputOffset, + outputBytes, + outputOffset, + ); + outputBytes = result!['output'] as List?; for (int i = 0; i < _size!; i++) { outputBytes![outputOffset! + i] ^= _cbcBytes![i]; } - final List? tempBytes = _cbcBytes; + final Uint8List? tempBytes = _cbcBytes; _cbcBytes = _cbcNextBytes; _cbcNextBytes = tempBytes; return {'length': result['length'], 'output': outputBytes}; } + + @override + int processingBlock( + Uint8List inputBytes, + int inputOffset, + Uint8List outputBytes, + int outputOffset, + ) { + return _isEncryption! + ? encryptBlock(inputBytes, inputOffset, outputBytes, outputOffset) + : decryptBlock(inputBytes, inputOffset, outputBytes, outputOffset); + } + + /// internal method + int encryptBlock( + Uint8List? inputBytes, + int inputOffset, + Uint8List? outputBytes, + int outputOffset, + ) { + if ((inputOffset + _size!) > inputBytes!.length) { + throw ArgumentError.value('Invalid length in input bytes'); + } + for (int i = 0; i < _size!; i++) { + _cbcBytes![i] ^= inputBytes[inputOffset + i]; + } + final result = _cipher!.processingBlock( + _cbcBytes!, + 0, + outputBytes!, + outputOffset, + ); + _cbcBytes!.setRange( + 0, + _size!, + Uint8List.view( + outputBytes.buffer, + outputBytes.offsetInBytes + outputOffset, + _size, + ), + ); + return result!; + } + + /// internal method + int decryptBlock( + Uint8List inputBytes, + int inputOffset, + Uint8List outputBytes, + int outputOffset, + ) { + if ((inputOffset + _size!) > inputBytes.length) { + throw ArgumentError.value('Invalid length in input bytes'); + } + _cbcNextBytes!.setRange( + 0, + _size!, + Uint8List.view( + inputBytes.buffer, + inputBytes.offsetInBytes + inputOffset, + blockSize, + ), + ); + final result = _cipher!.processingBlock( + inputBytes, + inputOffset, + outputBytes, + outputOffset, + ); + for (int i = 0; i < _size!; i++) { + outputBytes[outputOffset + i] ^= _cbcBytes![i]; + } + final Uint8List? tempBytes = _cbcBytes; + _cbcBytes = _cbcNextBytes; + _cbcNextBytes = tempBytes; + return result!; + } } /// internal class -class InvalidParameter implements ICipherParameter { +class InvalidParameter + implements ICipherParameter { //Constructor /// internal constructor - InvalidParameter(this.parameters, List bytes, - [int? offset, int? length]) { - length ??= bytes.length; - offset ??= 0; - this.bytes = List.filled(length, 0, growable: true); - List.copyRange(this.bytes!, 0, bytes, offset, offset + length); - } + InvalidParameter(this.parameters, this.keys); //Fields /// internal field - ICipherParameter? parameters; + UnderlyingKeyParameters? parameters; /// internal field - List? bytes; - - //Properties - @override - List get keys => List.from(bytes!); - @override - set keys(List? value) { - bytes = value; - } + Uint8List? keys; } /// internal class -class KeyParameter implements ICipherParameter { - //Constructor - /// internal constructor - KeyParameter(List bytes) { - this.bytes = List.from(bytes); - } +class KeyParameter extends ICipherParameter { + KeyParameter(this.keys); - /// internal constructor - KeyParameter.fromLengthValue(List bytes, int offset, int length) { - if (offset < 0 || offset > bytes.length) { - throw ArgumentError.value(offset, 'offset', 'Out of range'); - } - if (length < 0 || (offset + length) > bytes.length) { - throw ArgumentError.value(length, 'length', 'Out of range'); - } - this.bytes = List.generate(length, (int i) => 0); - List.copyRange(this.bytes!, 0, bytes, offset, offset + length); + KeyParameter.fromLengthValue(Uint8List keys, int keyOff, int keyLen) { + this.keys = Uint8List(keyLen); + copyArray(keys, keyOff, this.keys, 0, keyLen); } + late Uint8List keys; +} - //Fields - /// internal field - List? bytes; - - //Properties - @override - List get keys => List.from(bytes!); - @override - set keys(List? value) { - bytes = value; +void copyArray( + Uint8List? sourceArr, + int sourcePos, + Uint8List? outArr, + int outPos, + int len, +) { + for (var i = 0; i < len; i++) { + outArr![outPos + i] = sourceArr![sourcePos + i]; } } @@ -175,9 +265,7 @@ class CipherParameter implements ICipherParameter { /// internal property bool? get isPrivate => _privateKey; - @override List? get keys => null; - @override set keys(List? value) {} @override // ignore: avoid_equals_and_hash_code_on_mutable_classes @@ -236,9 +324,16 @@ class RsaKeyParam extends CipherParameter { /// internal class class RsaPrivateKeyParam extends RsaKeyParam { /// internal constructor - RsaPrivateKeyParam(BigInt? modulus, this.publicExponent, - BigInt? privateExponent, this.p, this.q, this.dP, this.dQ, this.inverse) - : super(true, modulus, privateExponent) { + RsaPrivateKeyParam( + BigInt? modulus, + this.publicExponent, + BigInt? privateExponent, + this.p, + this.q, + this.dP, + this.dQ, + this.inverse, + ) : super(true, modulus, privateExponent) { validateValue(publicExponent!); validateValue(p!); validateValue(q!); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/ipadding.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/ipadding.dart index 36c1b513c..1ce939dba 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/ipadding.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/ipadding.dart @@ -1,31 +1,33 @@ -import 'dart:math'; +import 'dart:typed_data'; /// internal class -class IPadding { +abstract class IPadding { /// internal method - void initialize(Random? random) {} + void initialize([ICipherParameter? params]) {} /// internal property String? get paddingName => null; /// internal method - int? addPadding(List? bytes, int? offset) => null; + int addPadding(Uint8List data, int offset); /// internal method - int? count(List? bytes) => null; + int count(Uint8List data); } /// internal class -class IBufferedCipher { - /// internal property - String? get algorithmName => null; +class IBufferedCipher extends ICipher { + IPadding? get padding => null; + + ICipher? get cipher => null; + + @override + Uint8List? process(Uint8List data) => null; /// internal method + @override void initialize(bool forEncryption, ICipherParameter? parameters) {} - /// internal property - int? get blockSize => null; - /// internal method int? getOutputSize(int inputLen) => null; @@ -47,17 +49,30 @@ class IBufferedCipher { /// internal method Map? processByteFromValues( - List input, List output, int outOff) => - null; + List input, + List output, + int outOff, + ) => null; /// internal method - Map? processBytes(List input, int inOff, int length, - List output, int outOff) => - null; + Map? processBytes( + List input, + int inOff, + int length, + List output, + int outOff, + ) => null; /// internal method List? doFinal() => null; + int? doFinalProcess( + Uint8List inputBytes, + int inputOffset, + Uint8List outputBytes, + int outputOffset, + ) => null; + /// internal method List? doFinalFromInput(List? input) => null; @@ -69,25 +84,31 @@ class IBufferedCipher { /// internal method Map? copyFinal( - List input, List output, int outOff) => - null; + List input, + List output, + int outOff, + ) => null; /// internal method - Map? readFinalValues(List input, int inOff, int length, - List output, int outOff) => - null; + Map? readFinalValues( + List input, + int inOff, + int length, + List output, + int outOff, + ) => null; /// internal method + @override void reset() {} } /// internal class -class ICipher { - /// internal property +abstract class ICipher { String? get algorithmName => null; - /// internal method - void initialize(bool? isEncryption, ICipherParameter? parameters) {} + /// Initialize the cipher + void initialize(bool isEncryption, ICipherParameter? parameters); /// internal property int? get blockSize => null; @@ -95,13 +116,34 @@ class ICipher { /// internal property bool? get isBlock => null; - /// internal method - Map? processBlock(List? inBytes, int inOffset, - List? outBytes, int? outOffset) => - null; + /// Process a full block + int? processingBlock( + Uint8List inputBytes, + int inputOffset, + Uint8List outputBytes, + int outputOffset, + ) => null; + + Map? processBlock( + List? inBytes, + int inOffset, + List? outBytes, + int? outOffset, + ) => null; + + /// Reset cipher + void reset(); + + Uint8List? process(Uint8List data) => null; +} - /// internal method - void reset() {} +abstract class IBlockCipher extends ICipher { + @override + Uint8List process(Uint8List data) { + final out = Uint8List(blockSize!); + final len = processingBlock(data, 0, out, 0); + return out.sublist(0, len); + } } /// internal class @@ -123,10 +165,7 @@ class ICipherBlock { } /// internal class -class ICipherParameter { - /// internal field - List? keys; -} +abstract class ICipherParameter {} /// internal class class ISigner { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/message_digest_utils.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/message_digest_utils.dart index e608f1e0e..c531da415 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/message_digest_utils.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/message_digest_utils.dart @@ -62,14 +62,20 @@ class MessageDigestFinder { return doFinal(digest); } else { throw ArgumentError.value( - algorithm, 'hashAlgorithm', 'Invalid message digest algorithm'); + algorithm, + 'hashAlgorithm', + 'Invalid message digest algorithm', + ); } } /// Internal method List doFinal(IMessageDigest digest) { - final List bytes = - List.filled(digest.messageDigestSize!, 0, growable: true); + final List bytes = List.filled( + digest.messageDigestSize!, + 0, + growable: true, + ); digest.doFinal(bytes, 0); return bytes; } @@ -236,7 +242,8 @@ class RIPEMD160MessageDigest extends MessageDigest { @override void processWord(List input, int inOff) { - _x[_xOffset++] = (input[inOff] & 0xff) | + _x[_xOffset++] = + (input[inOff] & 0xff) | ((input[inOff + 1] & 0xff) << 8) | ((input[inOff + 2] & 0xff) << 16) | ((input[inOff + 3] & 0xff) << 24); @@ -311,523 +318,907 @@ class RIPEMD160MessageDigest extends MessageDigest { a = getRightToLeft(a + getBitLevelEXOR(b, c, d) + _x[15], 8) + e; c = getRightToLeft(c, 10); - f = getRightToLeft( - f + getBitlevelReverseNegative(g, h, i) + _x[5] + 1352829926, 8) + + f = + getRightToLeft( + f + getBitlevelReverseNegative(g, h, i) + _x[5] + 1352829926, + 8, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelReverseNegative(f, g, h) + _x[14] + 1352829926, 9) + + j = + getRightToLeft( + j + getBitlevelReverseNegative(f, g, h) + _x[14] + 1352829926, + 9, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelReverseNegative(j, f, g) + _x[7] + 1352829926, 9) + + i = + getRightToLeft( + i + getBitlevelReverseNegative(j, f, g) + _x[7] + 1352829926, + 9, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelReverseNegative(i, j, f) + _x[0] + 1352829926, 11) + + h = + getRightToLeft( + h + getBitlevelReverseNegative(i, j, f) + _x[0] + 1352829926, + 11, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelReverseNegative(h, i, j) + _x[9] + 1352829926, 13) + + g = + getRightToLeft( + g + getBitlevelReverseNegative(h, i, j) + _x[9] + 1352829926, + 13, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelReverseNegative(g, h, i) + _x[2] + 1352829926, 15) + + f = + getRightToLeft( + f + getBitlevelReverseNegative(g, h, i) + _x[2] + 1352829926, + 15, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelReverseNegative(f, g, h) + _x[11] + 1352829926, 15) + + j = + getRightToLeft( + j + getBitlevelReverseNegative(f, g, h) + _x[11] + 1352829926, + 15, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelReverseNegative(j, f, g) + _x[4] + 1352829926, 5) + + i = + getRightToLeft( + i + getBitlevelReverseNegative(j, f, g) + _x[4] + 1352829926, + 5, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelReverseNegative(i, j, f) + _x[13] + 1352829926, 7) + + h = + getRightToLeft( + h + getBitlevelReverseNegative(i, j, f) + _x[13] + 1352829926, + 7, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelReverseNegative(h, i, j) + _x[6] + 1352829926, 7) + + g = + getRightToLeft( + g + getBitlevelReverseNegative(h, i, j) + _x[6] + 1352829926, + 7, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelReverseNegative(g, h, i) + _x[15] + 1352829926, 8) + + f = + getRightToLeft( + f + getBitlevelReverseNegative(g, h, i) + _x[15] + 1352829926, + 8, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelReverseNegative(f, g, h) + _x[8] + 1352829926, 11) + + j = + getRightToLeft( + j + getBitlevelReverseNegative(f, g, h) + _x[8] + 1352829926, + 11, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelReverseNegative(j, f, g) + _x[1] + 1352829926, 14) + + i = + getRightToLeft( + i + getBitlevelReverseNegative(j, f, g) + _x[1] + 1352829926, + 14, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelReverseNegative(i, j, f) + _x[10] + 1352829926, 14) + + h = + getRightToLeft( + h + getBitlevelReverseNegative(i, j, f) + _x[10] + 1352829926, + 14, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelReverseNegative(h, i, j) + _x[3] + 1352829926, 12) + + g = + getRightToLeft( + g + getBitlevelReverseNegative(h, i, j) + _x[3] + 1352829926, + 12, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelReverseNegative(g, h, i) + _x[12] + 1352829926, 6) + + f = + getRightToLeft( + f + getBitlevelReverseNegative(g, h, i) + _x[12] + 1352829926, + 6, + ) + j; h = getRightToLeft(h, 10); - e = getRightToLeft( - e + getBitlevelMultiplexer(a, b, c) + _x[7] + 1518500249, 7) + + e = + getRightToLeft( + e + getBitlevelMultiplexer(a, b, c) + _x[7] + 1518500249, + 7, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelMultiplexer(e, a, b) + _x[4] + 1518500249, 6) + + d = + getRightToLeft( + d + getBitlevelMultiplexer(e, a, b) + _x[4] + 1518500249, + 6, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelMultiplexer(d, e, a) + _x[13] + 1518500249, 8) + + c = + getRightToLeft( + c + getBitlevelMultiplexer(d, e, a) + _x[13] + 1518500249, + 8, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelMultiplexer(c, d, e) + _x[1] + 1518500249, 13) + + b = + getRightToLeft( + b + getBitlevelMultiplexer(c, d, e) + _x[1] + 1518500249, + 13, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelMultiplexer(b, c, d) + _x[10] + 1518500249, 11) + + a = + getRightToLeft( + a + getBitlevelMultiplexer(b, c, d) + _x[10] + 1518500249, + 11, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelMultiplexer(a, b, c) + _x[6] + 1518500249, 9) + + e = + getRightToLeft( + e + getBitlevelMultiplexer(a, b, c) + _x[6] + 1518500249, + 9, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelMultiplexer(e, a, b) + _x[15] + 1518500249, 7) + + d = + getRightToLeft( + d + getBitlevelMultiplexer(e, a, b) + _x[15] + 1518500249, + 7, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelMultiplexer(d, e, a) + _x[3] + 1518500249, 15) + + c = + getRightToLeft( + c + getBitlevelMultiplexer(d, e, a) + _x[3] + 1518500249, + 15, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelMultiplexer(c, d, e) + _x[12] + 1518500249, 7) + + b = + getRightToLeft( + b + getBitlevelMultiplexer(c, d, e) + _x[12] + 1518500249, + 7, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelMultiplexer(b, c, d) + _x[0] + 1518500249, 12) + + a = + getRightToLeft( + a + getBitlevelMultiplexer(b, c, d) + _x[0] + 1518500249, + 12, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelMultiplexer(a, b, c) + _x[9] + 1518500249, 15) + + e = + getRightToLeft( + e + getBitlevelMultiplexer(a, b, c) + _x[9] + 1518500249, + 15, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelMultiplexer(e, a, b) + _x[5] + 1518500249, 9) + + d = + getRightToLeft( + d + getBitlevelMultiplexer(e, a, b) + _x[5] + 1518500249, + 9, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelMultiplexer(d, e, a) + _x[2] + 1518500249, 11) + + c = + getRightToLeft( + c + getBitlevelMultiplexer(d, e, a) + _x[2] + 1518500249, + 11, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelMultiplexer(c, d, e) + _x[14] + 1518500249, 7) + + b = + getRightToLeft( + b + getBitlevelMultiplexer(c, d, e) + _x[14] + 1518500249, + 7, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelMultiplexer(b, c, d) + _x[11] + 1518500249, 13) + + a = + getRightToLeft( + a + getBitlevelMultiplexer(b, c, d) + _x[11] + 1518500249, + 13, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelMultiplexer(a, b, c) + _x[8] + 1518500249, 12) + + e = + getRightToLeft( + e + getBitlevelMultiplexer(a, b, c) + _x[8] + 1518500249, + 12, + ) + d; b = getRightToLeft(b, 10); - j = getRightToLeft( - j + getBitlevelDemultiplexer(f, g, h) + _x[6] + 1548603684, 9) + + j = + getRightToLeft( + j + getBitlevelDemultiplexer(f, g, h) + _x[6] + 1548603684, + 9, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelDemultiplexer(j, f, g) + _x[11] + 1548603684, 13) + + i = + getRightToLeft( + i + getBitlevelDemultiplexer(j, f, g) + _x[11] + 1548603684, + 13, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelDemultiplexer(i, j, f) + _x[3] + 1548603684, 15) + + h = + getRightToLeft( + h + getBitlevelDemultiplexer(i, j, f) + _x[3] + 1548603684, + 15, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelDemultiplexer(h, i, j) + _x[7] + 1548603684, 7) + + g = + getRightToLeft( + g + getBitlevelDemultiplexer(h, i, j) + _x[7] + 1548603684, + 7, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelDemultiplexer(g, h, i) + _x[0] + 1548603684, 12) + + f = + getRightToLeft( + f + getBitlevelDemultiplexer(g, h, i) + _x[0] + 1548603684, + 12, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelDemultiplexer(f, g, h) + _x[13] + 1548603684, 8) + + j = + getRightToLeft( + j + getBitlevelDemultiplexer(f, g, h) + _x[13] + 1548603684, + 8, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelDemultiplexer(j, f, g) + _x[5] + 1548603684, 9) + + i = + getRightToLeft( + i + getBitlevelDemultiplexer(j, f, g) + _x[5] + 1548603684, + 9, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelDemultiplexer(i, j, f) + _x[10] + 1548603684, 11) + + h = + getRightToLeft( + h + getBitlevelDemultiplexer(i, j, f) + _x[10] + 1548603684, + 11, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelDemultiplexer(h, i, j) + _x[14] + 1548603684, 7) + + g = + getRightToLeft( + g + getBitlevelDemultiplexer(h, i, j) + _x[14] + 1548603684, + 7, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelDemultiplexer(g, h, i) + _x[15] + 1548603684, 7) + + f = + getRightToLeft( + f + getBitlevelDemultiplexer(g, h, i) + _x[15] + 1548603684, + 7, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelDemultiplexer(f, g, h) + _x[8] + 1548603684, 12) + + j = + getRightToLeft( + j + getBitlevelDemultiplexer(f, g, h) + _x[8] + 1548603684, + 12, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelDemultiplexer(j, f, g) + _x[12] + 1548603684, 7) + + i = + getRightToLeft( + i + getBitlevelDemultiplexer(j, f, g) + _x[12] + 1548603684, + 7, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelDemultiplexer(i, j, f) + _x[4] + 1548603684, 6) + + h = + getRightToLeft( + h + getBitlevelDemultiplexer(i, j, f) + _x[4] + 1548603684, + 6, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelDemultiplexer(h, i, j) + _x[9] + 1548603684, 15) + + g = + getRightToLeft( + g + getBitlevelDemultiplexer(h, i, j) + _x[9] + 1548603684, + 15, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelDemultiplexer(g, h, i) + _x[1] + 1548603684, 13) + + f = + getRightToLeft( + f + getBitlevelDemultiplexer(g, h, i) + _x[1] + 1548603684, + 13, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelDemultiplexer(f, g, h) + _x[2] + 1548603684, 11) + + j = + getRightToLeft( + j + getBitlevelDemultiplexer(f, g, h) + _x[2] + 1548603684, + 11, + ) + i; g = getRightToLeft(g, 10); - d = getRightToLeft( - d + getBitlevelNegative(e, a, b) + _x[3] + 1859775393, 11) + + d = + getRightToLeft( + d + getBitlevelNegative(e, a, b) + _x[3] + 1859775393, + 11, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelNegative(d, e, a) + _x[10] + 1859775393, 13) + + c = + getRightToLeft( + c + getBitlevelNegative(d, e, a) + _x[10] + 1859775393, + 13, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelNegative(c, d, e) + _x[14] + 1859775393, 6) + + b = + getRightToLeft( + b + getBitlevelNegative(c, d, e) + _x[14] + 1859775393, + 6, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelNegative(b, c, d) + _x[4] + 1859775393, 7) + + a = + getRightToLeft( + a + getBitlevelNegative(b, c, d) + _x[4] + 1859775393, + 7, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelNegative(a, b, c) + _x[9] + 1859775393, 14) + + e = + getRightToLeft( + e + getBitlevelNegative(a, b, c) + _x[9] + 1859775393, + 14, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelNegative(e, a, b) + _x[15] + 1859775393, 9) + + d = + getRightToLeft( + d + getBitlevelNegative(e, a, b) + _x[15] + 1859775393, + 9, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelNegative(d, e, a) + _x[8] + 1859775393, 13) + + c = + getRightToLeft( + c + getBitlevelNegative(d, e, a) + _x[8] + 1859775393, + 13, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelNegative(c, d, e) + _x[1] + 1859775393, 15) + + b = + getRightToLeft( + b + getBitlevelNegative(c, d, e) + _x[1] + 1859775393, + 15, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelNegative(b, c, d) + _x[2] + 1859775393, 14) + + a = + getRightToLeft( + a + getBitlevelNegative(b, c, d) + _x[2] + 1859775393, + 14, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelNegative(a, b, c) + _x[7] + 1859775393, 8) + + e = + getRightToLeft( + e + getBitlevelNegative(a, b, c) + _x[7] + 1859775393, + 8, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelNegative(e, a, b) + _x[0] + 1859775393, 13) + + d = + getRightToLeft( + d + getBitlevelNegative(e, a, b) + _x[0] + 1859775393, + 13, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelNegative(d, e, a) + _x[6] + 1859775393, 6) + + c = + getRightToLeft( + c + getBitlevelNegative(d, e, a) + _x[6] + 1859775393, + 6, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelNegative(c, d, e) + _x[13] + 1859775393, 5) + + b = + getRightToLeft( + b + getBitlevelNegative(c, d, e) + _x[13] + 1859775393, + 5, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelNegative(b, c, d) + _x[11] + 1859775393, 12) + + a = + getRightToLeft( + a + getBitlevelNegative(b, c, d) + _x[11] + 1859775393, + 12, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelNegative(a, b, c) + _x[5] + 1859775393, 7) + + e = + getRightToLeft( + e + getBitlevelNegative(a, b, c) + _x[5] + 1859775393, + 7, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelNegative(e, a, b) + _x[12] + 1859775393, 5) + + d = + getRightToLeft( + d + getBitlevelNegative(e, a, b) + _x[12] + 1859775393, + 5, + ) + c; a = getRightToLeft(a, 10); - i = getRightToLeft( - i + getBitlevelNegative(j, f, g) + _x[15] + 1836072691, 9) + + i = + getRightToLeft( + i + getBitlevelNegative(j, f, g) + _x[15] + 1836072691, + 9, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelNegative(i, j, f) + _x[5] + 1836072691, 7) + + h = + getRightToLeft( + h + getBitlevelNegative(i, j, f) + _x[5] + 1836072691, + 7, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelNegative(h, i, j) + _x[1] + 1836072691, 15) + + g = + getRightToLeft( + g + getBitlevelNegative(h, i, j) + _x[1] + 1836072691, + 15, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelNegative(g, h, i) + _x[3] + 1836072691, 11) + + f = + getRightToLeft( + f + getBitlevelNegative(g, h, i) + _x[3] + 1836072691, + 11, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelNegative(f, g, h) + _x[7] + 1836072691, 8) + + j = + getRightToLeft( + j + getBitlevelNegative(f, g, h) + _x[7] + 1836072691, + 8, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelNegative(j, f, g) + _x[14] + 1836072691, 6) + + i = + getRightToLeft( + i + getBitlevelNegative(j, f, g) + _x[14] + 1836072691, + 6, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelNegative(i, j, f) + _x[6] + 1836072691, 6) + + h = + getRightToLeft( + h + getBitlevelNegative(i, j, f) + _x[6] + 1836072691, + 6, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelNegative(h, i, j) + _x[9] + 1836072691, 14) + + g = + getRightToLeft( + g + getBitlevelNegative(h, i, j) + _x[9] + 1836072691, + 14, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelNegative(g, h, i) + _x[11] + 1836072691, 12) + + f = + getRightToLeft( + f + getBitlevelNegative(g, h, i) + _x[11] + 1836072691, + 12, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelNegative(f, g, h) + _x[8] + 1836072691, 13) + + j = + getRightToLeft( + j + getBitlevelNegative(f, g, h) + _x[8] + 1836072691, + 13, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelNegative(j, f, g) + _x[12] + 1836072691, 5) + + i = + getRightToLeft( + i + getBitlevelNegative(j, f, g) + _x[12] + 1836072691, + 5, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelNegative(i, j, f) + _x[2] + 1836072691, 14) + + h = + getRightToLeft( + h + getBitlevelNegative(i, j, f) + _x[2] + 1836072691, + 14, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelNegative(h, i, j) + _x[10] + 1836072691, 13) + + g = + getRightToLeft( + g + getBitlevelNegative(h, i, j) + _x[10] + 1836072691, + 13, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelNegative(g, h, i) + _x[0] + 1836072691, 13) + + f = + getRightToLeft( + f + getBitlevelNegative(g, h, i) + _x[0] + 1836072691, + 13, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelNegative(f, g, h) + _x[4] + 1836072691, 7) + + j = + getRightToLeft( + j + getBitlevelNegative(f, g, h) + _x[4] + 1836072691, + 7, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelNegative(j, f, g) + _x[13] + 1836072691, 5) + + i = + getRightToLeft( + i + getBitlevelNegative(j, f, g) + _x[13] + 1836072691, + 5, + ) + h; f = getRightToLeft(f, 10); - c = getRightToLeft( - c + getBitlevelDemultiplexer(d, e, a) + _x[1] - 1894007588, 11) + + c = + getRightToLeft( + c + getBitlevelDemultiplexer(d, e, a) + _x[1] - 1894007588, + 11, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelDemultiplexer(c, d, e) + _x[9] - 1894007588, 12) + + b = + getRightToLeft( + b + getBitlevelDemultiplexer(c, d, e) + _x[9] - 1894007588, + 12, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelDemultiplexer(b, c, d) + _x[11] - 1894007588, 14) + + a = + getRightToLeft( + a + getBitlevelDemultiplexer(b, c, d) + _x[11] - 1894007588, + 14, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelDemultiplexer(a, b, c) + _x[10] - 1894007588, 15) + + e = + getRightToLeft( + e + getBitlevelDemultiplexer(a, b, c) + _x[10] - 1894007588, + 15, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelDemultiplexer(e, a, b) + _x[0] - 1894007588, 14) + + d = + getRightToLeft( + d + getBitlevelDemultiplexer(e, a, b) + _x[0] - 1894007588, + 14, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelDemultiplexer(d, e, a) + _x[8] - 1894007588, 15) + + c = + getRightToLeft( + c + getBitlevelDemultiplexer(d, e, a) + _x[8] - 1894007588, + 15, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelDemultiplexer(c, d, e) + _x[12] - 1894007588, 9) + + b = + getRightToLeft( + b + getBitlevelDemultiplexer(c, d, e) + _x[12] - 1894007588, + 9, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelDemultiplexer(b, c, d) + _x[4] - 1894007588, 8) + + a = + getRightToLeft( + a + getBitlevelDemultiplexer(b, c, d) + _x[4] - 1894007588, + 8, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelDemultiplexer(a, b, c) + _x[13] - 1894007588, 9) + + e = + getRightToLeft( + e + getBitlevelDemultiplexer(a, b, c) + _x[13] - 1894007588, + 9, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelDemultiplexer(e, a, b) + _x[3] - 1894007588, 14) + + d = + getRightToLeft( + d + getBitlevelDemultiplexer(e, a, b) + _x[3] - 1894007588, + 14, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelDemultiplexer(d, e, a) + _x[7] - 1894007588, 5) + + c = + getRightToLeft( + c + getBitlevelDemultiplexer(d, e, a) + _x[7] - 1894007588, + 5, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelDemultiplexer(c, d, e) + _x[15] - 1894007588, 6) + + b = + getRightToLeft( + b + getBitlevelDemultiplexer(c, d, e) + _x[15] - 1894007588, + 6, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelDemultiplexer(b, c, d) + _x[14] - 1894007588, 8) + + a = + getRightToLeft( + a + getBitlevelDemultiplexer(b, c, d) + _x[14] - 1894007588, + 8, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelDemultiplexer(a, b, c) + _x[5] - 1894007588, 6) + + e = + getRightToLeft( + e + getBitlevelDemultiplexer(a, b, c) + _x[5] - 1894007588, + 6, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelDemultiplexer(e, a, b) + _x[6] - 1894007588, 5) + + d = + getRightToLeft( + d + getBitlevelDemultiplexer(e, a, b) + _x[6] - 1894007588, + 5, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelDemultiplexer(d, e, a) + _x[2] - 1894007588, 12) + + c = + getRightToLeft( + c + getBitlevelDemultiplexer(d, e, a) + _x[2] - 1894007588, + 12, + ) + b; e = getRightToLeft(e, 10); - h = getRightToLeft( - h + getBitlevelMultiplexer(i, j, f) + _x[8] + 2053994217, 15) + + h = + getRightToLeft( + h + getBitlevelMultiplexer(i, j, f) + _x[8] + 2053994217, + 15, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelMultiplexer(h, i, j) + _x[6] + 2053994217, 5) + + g = + getRightToLeft( + g + getBitlevelMultiplexer(h, i, j) + _x[6] + 2053994217, + 5, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelMultiplexer(g, h, i) + _x[4] + 2053994217, 8) + + f = + getRightToLeft( + f + getBitlevelMultiplexer(g, h, i) + _x[4] + 2053994217, + 8, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelMultiplexer(f, g, h) + _x[1] + 2053994217, 11) + + j = + getRightToLeft( + j + getBitlevelMultiplexer(f, g, h) + _x[1] + 2053994217, + 11, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelMultiplexer(j, f, g) + _x[3] + 2053994217, 14) + + i = + getRightToLeft( + i + getBitlevelMultiplexer(j, f, g) + _x[3] + 2053994217, + 14, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelMultiplexer(i, j, f) + _x[11] + 2053994217, 14) + + h = + getRightToLeft( + h + getBitlevelMultiplexer(i, j, f) + _x[11] + 2053994217, + 14, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelMultiplexer(h, i, j) + _x[15] + 2053994217, 6) + + g = + getRightToLeft( + g + getBitlevelMultiplexer(h, i, j) + _x[15] + 2053994217, + 6, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelMultiplexer(g, h, i) + _x[0] + 2053994217, 14) + + f = + getRightToLeft( + f + getBitlevelMultiplexer(g, h, i) + _x[0] + 2053994217, + 14, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelMultiplexer(f, g, h) + _x[5] + 2053994217, 6) + + j = + getRightToLeft( + j + getBitlevelMultiplexer(f, g, h) + _x[5] + 2053994217, + 6, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelMultiplexer(j, f, g) + _x[12] + 2053994217, 9) + + i = + getRightToLeft( + i + getBitlevelMultiplexer(j, f, g) + _x[12] + 2053994217, + 9, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelMultiplexer(i, j, f) + _x[2] + 2053994217, 12) + + h = + getRightToLeft( + h + getBitlevelMultiplexer(i, j, f) + _x[2] + 2053994217, + 12, + ) + g; j = getRightToLeft(j, 10); - g = getRightToLeft( - g + getBitlevelMultiplexer(h, i, j) + _x[13] + 2053994217, 9) + + g = + getRightToLeft( + g + getBitlevelMultiplexer(h, i, j) + _x[13] + 2053994217, + 9, + ) + f; i = getRightToLeft(i, 10); - f = getRightToLeft( - f + getBitlevelMultiplexer(g, h, i) + _x[9] + 2053994217, 12) + + f = + getRightToLeft( + f + getBitlevelMultiplexer(g, h, i) + _x[9] + 2053994217, + 12, + ) + j; h = getRightToLeft(h, 10); - j = getRightToLeft( - j + getBitlevelMultiplexer(f, g, h) + _x[7] + 2053994217, 5) + + j = + getRightToLeft( + j + getBitlevelMultiplexer(f, g, h) + _x[7] + 2053994217, + 5, + ) + i; g = getRightToLeft(g, 10); - i = getRightToLeft( - i + getBitlevelMultiplexer(j, f, g) + _x[10] + 2053994217, 15) + + i = + getRightToLeft( + i + getBitlevelMultiplexer(j, f, g) + _x[10] + 2053994217, + 15, + ) + h; f = getRightToLeft(f, 10); - h = getRightToLeft( - h + getBitlevelMultiplexer(i, j, f) + _x[14] + 2053994217, 8) + + h = + getRightToLeft( + h + getBitlevelMultiplexer(i, j, f) + _x[14] + 2053994217, + 8, + ) + g; j = getRightToLeft(j, 10); - b = getRightToLeft( - b + getBitlevelReverseNegative(c, d, e) + _x[4] - 1454113458, 9) + + b = + getRightToLeft( + b + getBitlevelReverseNegative(c, d, e) + _x[4] - 1454113458, + 9, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelReverseNegative(b, c, d) + _x[0] - 1454113458, 15) + + a = + getRightToLeft( + a + getBitlevelReverseNegative(b, c, d) + _x[0] - 1454113458, + 15, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelReverseNegative(a, b, c) + _x[5] - 1454113458, 5) + + e = + getRightToLeft( + e + getBitlevelReverseNegative(a, b, c) + _x[5] - 1454113458, + 5, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelReverseNegative(e, a, b) + _x[9] - 1454113458, 11) + + d = + getRightToLeft( + d + getBitlevelReverseNegative(e, a, b) + _x[9] - 1454113458, + 11, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelReverseNegative(d, e, a) + _x[7] - 1454113458, 6) + + c = + getRightToLeft( + c + getBitlevelReverseNegative(d, e, a) + _x[7] - 1454113458, + 6, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelReverseNegative(c, d, e) + _x[12] - 1454113458, 8) + + b = + getRightToLeft( + b + getBitlevelReverseNegative(c, d, e) + _x[12] - 1454113458, + 8, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelReverseNegative(b, c, d) + _x[2] - 1454113458, 13) + + a = + getRightToLeft( + a + getBitlevelReverseNegative(b, c, d) + _x[2] - 1454113458, + 13, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelReverseNegative(a, b, c) + _x[10] - 1454113458, 12) + + e = + getRightToLeft( + e + getBitlevelReverseNegative(a, b, c) + _x[10] - 1454113458, + 12, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelReverseNegative(e, a, b) + _x[14] - 1454113458, 5) + + d = + getRightToLeft( + d + getBitlevelReverseNegative(e, a, b) + _x[14] - 1454113458, + 5, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelReverseNegative(d, e, a) + _x[1] - 1454113458, 12) + + c = + getRightToLeft( + c + getBitlevelReverseNegative(d, e, a) + _x[1] - 1454113458, + 12, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelReverseNegative(c, d, e) + _x[3] - 1454113458, 13) + + b = + getRightToLeft( + b + getBitlevelReverseNegative(c, d, e) + _x[3] - 1454113458, + 13, + ) + a; d = getRightToLeft(d, 10); - a = getRightToLeft( - a + getBitlevelReverseNegative(b, c, d) + _x[8] - 1454113458, 14) + + a = + getRightToLeft( + a + getBitlevelReverseNegative(b, c, d) + _x[8] - 1454113458, + 14, + ) + e; c = getRightToLeft(c, 10); - e = getRightToLeft( - e + getBitlevelReverseNegative(a, b, c) + _x[11] - 1454113458, 11) + + e = + getRightToLeft( + e + getBitlevelReverseNegative(a, b, c) + _x[11] - 1454113458, + 11, + ) + d; b = getRightToLeft(b, 10); - d = getRightToLeft( - d + getBitlevelReverseNegative(e, a, b) + _x[6] - 1454113458, 8) + + d = + getRightToLeft( + d + getBitlevelReverseNegative(e, a, b) + _x[6] - 1454113458, + 8, + ) + c; a = getRightToLeft(a, 10); - c = getRightToLeft( - c + getBitlevelReverseNegative(d, e, a) + _x[15] - 1454113458, 5) + + c = + getRightToLeft( + c + getBitlevelReverseNegative(d, e, a) + _x[15] - 1454113458, + 5, + ) + b; e = getRightToLeft(e, 10); - b = getRightToLeft( - b + getBitlevelReverseNegative(c, d, e) + _x[13] - 1454113458, 6) + + b = + getRightToLeft( + b + getBitlevelReverseNegative(c, d, e) + _x[13] - 1454113458, + 6, + ) + a; d = getRightToLeft(d, 10); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/pkcs1_encoding.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/pkcs1_encoding.dart index 6cb99b73c..6820302ab 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/pkcs1_encoding.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/pkcs1_encoding.dart @@ -54,7 +54,9 @@ class Pkcs1Encoding implements ICipherBlock { } } else { block = List.generate( - _cipher!.inputBlock!, (int i) => _random.nextInt(256)); + _cipher!.inputBlock!, + (int i) => _random.nextInt(256), + ); block[0] = 0x02; for (int i = 1; i != block.length - inLen - 1; i++) { while (block[i] == 0) { @@ -72,7 +74,10 @@ class Pkcs1Encoding implements ICipherBlock { final List block = _cipher!.processBlock(input, inOff, inLen)!; if (block.length < outputBlock!) { throw ArgumentError.value( - inLen, 'inLen', 'Invalid block. Block truncated'); + inLen, + 'inLen', + 'Invalid block. Block truncated', + ); } final int type = block[0]; if (type != 1 && type != 2) { @@ -95,8 +100,10 @@ class Pkcs1Encoding implements ICipherBlock { if (start > block.length || start < 10) { throw ArgumentError.value(start, 'start', 'no data in block'); } - final List result = - List.generate(block.length - start, (int i) => 0); + final List result = List.generate( + block.length - start, + (int i) => 0, + ); List.copyRange(result, 0, block, start, start + result.length); return result; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/rsa_algorithm.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/rsa_algorithm.dart index 0e4ad0a69..9298470b6 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/rsa_algorithm.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/rsa_algorithm.dart @@ -42,8 +42,11 @@ class RsaAlgorithm implements ICipherBlock { final BigInt? e = (_key! as RsaPrivateKeyParam).publicExponent; if (e != null) { final BigInt m = _key!.modulus!; - final BigInt r = - createRandomInRange(BigInt.one, m - BigInt.one, _random); + final BigInt r = createRandomInRange( + BigInt.one, + m - BigInt.one, + _random, + ); final BigInt blindedInput = getMod(r.modPow(e, m) * input, m); final BigInt blindedResult = _rsaCoreEngine.processBlock(blindedInput); final BigInt reverse = r.modInverse(m); @@ -117,8 +120,10 @@ class _RsaCoreAlgorithm { if (length > maxLength) { throw ArgumentError.value(length, 'length', 'Invalid length in inputs'); } - final BigInt input = - bigIntFromBytes(bytes.sublist(offset, offset + length), 1); + final BigInt input = bigIntFromBytes( + bytes.sublist(offset, offset + length), + 1, + ); if (input.compareTo(_key.modulus!) >= 0) { throw ArgumentError.value(length, 'length', 'Invalid length in inputs'); } @@ -132,9 +137,11 @@ class _RsaCoreAlgorithm { if (output.length < outSize) { final List bytes = List.generate(outSize, (int i) => 0); int j = 0; - for (int i = bytes.length - output.length; - j < output.length && i < bytes.length; - i++) { + for ( + int i = bytes.length - output.length; + j < output.length && i < bytes.length; + i++ + ) { bytes[i] = output[j]; j += 1; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/signature_utilities.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/signature_utilities.dart index bb775f252..44df4f9e8 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/signature_utilities.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/cryptography/signature_utilities.dart @@ -97,8 +97,10 @@ BigInt bigIntFromRamdom(int value, Random? random) { result = BigInt.from(0); } else { final int nBytes = (value + 8 - 1) ~/ 8; - final List b = - List.generate(nBytes, (int i) => random!.nextInt(256)); + final List b = List.generate( + nBytes, + (int i) => random!.nextInt(256), + ); final int xBits = 8 * nBytes - value; b[0] &= (255 >> xBits).toUnsigned(8); result = bigIntFromBytes(b); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_certificate.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_certificate.dart index cc9d05e70..b936ecb6b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_certificate.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_certificate.dart @@ -82,16 +82,21 @@ class PdfCertificate { } void _loadDetails(X509Certificate certificate) { - _issuerName = - _getDistinguishedAttributes(certificate.c!.issuer.toString(), 'CN'); - _subjectName = - _getDistinguishedAttributes(certificate.c!.subject.toString(), 'CN'); + _issuerName = _getDistinguishedAttributes( + certificate.c!.issuer.toString(), + 'CN', + ); + _subjectName = _getDistinguishedAttributes( + certificate.c!.subject.toString(), + 'CN', + ); _validFrom = certificate.c!.startDate!.toDateTime(); _validTo = certificate.c!.endDate!.toDateTime(); _version = certificate.c!.version; - final List serialNumber = [] - // ignore: prefer_spread_collections - ..addAll(certificate.c!.serialNumber!.intValue!.reversed.toList()); + final List serialNumber = + [] + // ignore: prefer_spread_collections + ..addAll(certificate.c!.serialNumber!.intValue!.reversed.toList()); _serialNumber = serialNumber; } @@ -144,8 +149,10 @@ class PdfCertificate { void _addStringToDictionary(String name, Map? dictionary) { int index = name.indexOf('='); if (index > 0) { - final List keyNameArray = - List.generate(2, (int i) => null); + final List keyNameArray = List.generate( + 2, + (int i) => null, + ); keyNameArray[0] = name.substring(0, index).trimLeft().trimRight(); index++; keyNameArray[1] = @@ -172,7 +179,9 @@ class PdfCertificateHelper { /// internal method static void setPkcsCertificate( - PdfCertificate certificate, PdfPKCSCertificate pkcsCertificate) { + PdfCertificate certificate, + PdfPKCSCertificate pkcsCertificate, + ) { certificate._pkcsCertificate = pkcsCertificate; } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_pkcs_certificate.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_pkcs_certificate.dart index d5a194da8..5a0eb325c 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_pkcs_certificate.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_pkcs_certificate.dart @@ -1,4 +1,5 @@ import 'dart:convert'; +import 'dart:typed_data'; import 'package:convert/convert.dart'; import 'package:crypto/crypto.dart'; @@ -44,8 +45,9 @@ class PdfPKCSCertificate { //Implementation void _loadCertificate(List certificateBytes, String password) { - final Asn1Sequence sequence = Asn1Stream(PdfStreamReader(certificateBytes)) - .readAsn1()! as Asn1Sequence; + final Asn1Sequence sequence = + Asn1Stream(PdfStreamReader(certificateBytes)).readAsn1()! + as Asn1Sequence; final _PfxData pfxData = _PfxData(sequence); final _ContentInformation information = pfxData._contentInformation!; bool isUnmarkedKey = false; @@ -59,8 +61,9 @@ class PdfPKCSCertificate { final List<_ContentInformation?> contentInformation = <_ContentInformation?>[]; for (int i = 0; i < asn1Sequence.count; i++) { - contentInformation - .add(_ContentInformation.getInformation(asn1Sequence[i])); + contentInformation.add( + _ContentInformation.getInformation(asn1Sequence[i]), + ); } // ignore: avoid_function_literals_in_foreach_calls contentInformation.forEach((_ContentInformation? entry) { @@ -78,27 +81,34 @@ class PdfPKCSCertificate { PkcsObjectId.pkcs8ShroudedKeyBag.id) { final EncryptedPrivateKey encryptedInformation = EncryptedPrivateKey.getEncryptedPrivateKeyInformation( - subSequenceCollection.value); + subSequenceCollection.value, + ); final KeyInformation privateKeyInformation = createPrivateKeyInfo( - password, isInvalidPassword, encryptedInformation)!; + password, + isInvalidPassword, + encryptedInformation, + )!; RsaPrivateKeyParam? rsaparam; if (privateKeyInformation._algorithms!.id!.id == PkcsObjectId.rsaEncryption.id || privateKeyInformation._algorithms!.id!.id == X509Objects.idEARsa.id) { final _RsaKey keyStructure = _RsaKey.fromSequence( - Asn1Sequence.getSequence( - privateKeyInformation._privateKey)!); + Asn1Sequence.getSequence( + privateKeyInformation._privateKey, + )!, + ); rsaparam = RsaPrivateKeyParam( - keyStructure._modulus, - keyStructure._publicExponent, - keyStructure._privateExponent, - keyStructure._prime1, - keyStructure._prime2, - keyStructure._exponent1, - keyStructure._exponent2, - keyStructure._coefficient); + keyStructure._modulus, + keyStructure._publicExponent, + keyStructure._privateExponent, + keyStructure._prime1, + keyStructure._prime2, + keyStructure._exponent1, + keyStructure._exponent2, + keyStructure._coefficient, + ); } final CipherParameter? privateKey = rsaparam; final Map attributes = {}; @@ -110,16 +120,20 @@ class PdfPKCSCertificate { for (int i = 0; i < sq.objects.length; i++) { final Asn1Encode? entry = sq.objects[i] as Asn1Encode?; if (entry is Asn1Sequence) { - final DerObjectID? algorithmId = - DerObjectID.getID(entry[0]); + final DerObjectID? algorithmId = DerObjectID.getID( + entry[0], + ); final Asn1Set attributeSet = entry[1]! as Asn1Set; Asn1Encode? attribute; if (attributeSet.objects.isNotEmpty) { attribute = attributeSet[0]; if (attributes.containsKey(algorithmId!.id)) { if (attributes[algorithmId.id] != attribute) { - throw ArgumentError.value(attributes, 'attributes', - 'attempt to add existing attribute with different value'); + throw ArgumentError.value( + attributes, + 'attributes', + 'attempt to add existing attribute with different value', + ); } } else { attributes[algorithmId.id] = attribute; @@ -138,8 +152,9 @@ class PdfPKCSCertificate { } } if (localId != null) { - final String name = - PdfString.bytesToHex(localId.getOctets()!); + final String name = PdfString.bytesToHex( + localId.getOctets()!, + ); if (localIdentifier == null) { _keys.setValue(name, key); } else { @@ -159,13 +174,19 @@ class PdfPKCSCertificate { final Asn1Sequence sequence1 = entry._content! as Asn1Sequence; if (sequence1.count != 2) { throw ArgumentError.value( - entry, 'sequence', 'Invalid length of the sequence'); + entry, + 'sequence', + 'Invalid length of the sequence', + ); } final int version = (sequence1[0]! as DerInteger).value.toSigned(32).toInt(); if (version != 0) { throw ArgumentError.value( - version, 'version', 'Invalid sequence version'); + version, + 'version', + 'Invalid sequence version', + ); } final Asn1Sequence data = sequence1[1]! as Asn1Sequence; Asn1Octet? content; @@ -174,11 +195,12 @@ class PdfPKCSCertificate { content = Asn1Octet.getOctetString(taggedObject, false); } final List? octets = getCryptographicData( - false, - Algorithms.getAlgorithms(data[1])!, - password, - isInvalidPassword, - content!.getOctets()); + false, + Algorithms.getAlgorithms(data[1])!, + password, + isInvalidPassword, + content!.getOctets(), + ); final Asn1Sequence seq = Asn1Stream(PdfStreamReader(octets)).readAsn1()! as Asn1Sequence; // ignore: avoid_function_literals_in_foreach_calls @@ -191,25 +213,32 @@ class PdfPKCSCertificate { PkcsObjectId.pkcs8ShroudedKeyBag.id) { final EncryptedPrivateKey encryptedPrivateKeyInformation = EncryptedPrivateKey.getEncryptedPrivateKeyInformation( - subSequenceCollection.value); - final KeyInformation privateInformation = createPrivateKeyInfo( - password, isInvalidPassword, encryptedPrivateKeyInformation)!; + subSequenceCollection.value, + ); + final KeyInformation privateInformation = + createPrivateKeyInfo( + password, + isInvalidPassword, + encryptedPrivateKeyInformation, + )!; RsaPrivateKeyParam? rsaParameter; if (privateInformation._algorithms!.id!.id == PkcsObjectId.rsaEncryption.id || privateInformation._algorithms!.id!.id == X509Objects.idEARsa.id) { final _RsaKey keyStructure = _RsaKey.fromSequence( - Asn1Sequence.getSequence(privateInformation._privateKey)!); + Asn1Sequence.getSequence(privateInformation._privateKey)!, + ); rsaParameter = RsaPrivateKeyParam( - keyStructure._modulus, - keyStructure._publicExponent, - keyStructure._privateExponent, - keyStructure._prime1, - keyStructure._prime2, - keyStructure._exponent1, - keyStructure._exponent2, - keyStructure._coefficient); + keyStructure._modulus, + keyStructure._publicExponent, + keyStructure._privateExponent, + keyStructure._prime1, + keyStructure._prime2, + keyStructure._exponent1, + keyStructure._exponent2, + keyStructure._coefficient, + ); } final CipherParameter? privateKey = rsaParameter; final Map attributes = {}; @@ -225,8 +254,11 @@ class PdfPKCSCertificate { attribute = attributeSet.objects[0] as Asn1Encode?; if (attributes.containsKey(asn1Id!.id)) { if (!(attributes[asn1Id.id] == attribute)) { - throw ArgumentError.value(attributes, 'attributes', - 'attempt to add existing attribute with different value'); + throw ArgumentError.value( + attributes, + 'attributes', + 'attempt to add existing attribute with different value', + ); } } else { attributes[asn1Id.id] = attribute; @@ -239,8 +271,9 @@ class PdfPKCSCertificate { } } }); - final String name = - PdfString.bytesToHex(localIdentity!.getOctets()!); + final String name = PdfString.bytesToHex( + localIdentity!.getOctets()!, + ); if (key == null) { _keys.setValue(name, keyEntry); } else { @@ -255,17 +288,18 @@ class PdfPKCSCertificate { privateKeyInformation._algorithms!.id!.id == X509Objects.idEARsa.id) { final _RsaKey keyStructure = _RsaKey.fromSequence( - Asn1Sequence.getSequence( - privateKeyInformation._privateKey)!); + Asn1Sequence.getSequence(privateKeyInformation._privateKey)!, + ); rsaParameter = RsaPrivateKeyParam( - keyStructure._modulus, - keyStructure._publicExponent, - keyStructure._privateExponent, - keyStructure._prime1, - keyStructure._prime2, - keyStructure._exponent1, - keyStructure._exponent2, - keyStructure._coefficient); + keyStructure._modulus, + keyStructure._publicExponent, + keyStructure._privateExponent, + keyStructure._prime1, + keyStructure._prime2, + keyStructure._exponent1, + keyStructure._exponent2, + keyStructure._coefficient, + ); } final CipherParameter? privateKey = rsaParameter; String? key; @@ -282,8 +316,11 @@ class PdfPKCSCertificate { if (attributes.containsKey(id!.id)) { final Asn1Encode? attr = attributes[id.id] as Asn1Encode?; if (attr != null && attr != attribute) { - throw ArgumentError.value(sq, 'sequence', - 'attempt to add existing attribute with different value'); + throw ArgumentError.value( + sq, + 'sequence', + 'attempt to add existing attribute with different value', + ); } } else { attributes[id.id] = attribute; @@ -330,8 +367,11 @@ class PdfPKCSCertificate { final Asn1Encode? attr = attrSet[0]; if (attributes.containsKey(aOid!.id)) { if (attributes[aOid.id] != attr) { - throw ArgumentError.value(attributes, 'attributes', - 'attempt to add existing attribute with different value'); + throw ArgumentError.value( + attributes, + 'attributes', + 'attempt to add existing attribute with different value', + ); } } else { attributes[aOid.id] = attr; @@ -344,10 +384,12 @@ class PdfPKCSCertificate { } } } - final _CertificateIdentifier certId = - _CertificateIdentifier(pubKey: certificate.getPublicKey()); - final X509Certificates certificateCollection = - X509Certificates(certificate); + final _CertificateIdentifier certId = _CertificateIdentifier( + pubKey: certificate.getPublicKey(), + ); + final X509Certificates certificateCollection = X509Certificates( + certificate, + ); _chainCertificates[certId] = certificateCollection; if (isUnmarkedKey) { if (_keyCertificates.isEmpty) { @@ -370,8 +412,13 @@ class PdfPKCSCertificate { } /// internal method - static List? getCryptographicData(bool forEncryption, Algorithms id, - String password, bool isZero, List? data) { + static List? getCryptographicData( + bool forEncryption, + Algorithms id, + String password, + bool isZero, + List? data, + ) { final _PasswordUtility utility = _PasswordUtility(); final IBufferedCipher? cipher = utility.createEncoder(id.id) as IBufferedCipher?; @@ -381,27 +428,42 @@ class PdfPKCSCertificate { final _Pkcs12PasswordParameter parameter = _Pkcs12PasswordParameter.getPbeParameter(id.parameters); final ICipherParameter? parameters = utility.generateCipherParameters( - id.id!.id!, password, isZero, parameter); + id.id!.id!, + password, + isZero, + parameter, + ); cipher.initialize(forEncryption, parameters); return cipher.doFinalFromInput(data); } /// internal method KeyInformation? createPrivateKeyInfo( - String passPhrase, bool isPkcs12empty, EncryptedPrivateKey encInfo) { + String passPhrase, + bool isPkcs12empty, + EncryptedPrivateKey encInfo, + ) { final Algorithms algID = encInfo._algorithms!; final _PasswordUtility pbeU = _PasswordUtility(); final IBufferedCipher? cipher = pbeU.createEncoder(algID) as IBufferedCipher?; if (cipher == null) { throw ArgumentError.value( - cipher, 'cipher', 'Unknown encryption algorithm'); + cipher, + 'cipher', + 'Unknown encryption algorithm', + ); } final ICipherParameter? cipherParameters = pbeU.generateCipherParameters( - algID.id!.id!, passPhrase, isPkcs12empty, algID.parameters); + algID.id!.id!, + passPhrase, + isPkcs12empty, + algID.parameters, + ); cipher.initialize(false, cipherParameters); - final List? keyBytes = - cipher.doFinalFromInput(encInfo._octet!.getOctets()); + final List? keyBytes = cipher.doFinalFromInput( + encInfo._octet!.getOctets(), + ); return KeyInformation.getInformation(keyBytes); } @@ -410,8 +472,9 @@ class PdfPKCSCertificate { SubjectKeyID result; if (publicKey is RsaKeyParam) { final PublicKeyInformation information = PublicKeyInformation( - Algorithms(PkcsObjectId.rsaEncryption, DerNull.value), - RsaPublicKey(publicKey.modulus, publicKey.exponent).getAsn1()); + Algorithms(PkcsObjectId.rsaEncryption, DerNull.value), + RsaPublicKey(publicKey.modulus, publicKey.exponent).getAsn1(), + ); result = SubjectKeyID(information); } else { throw ArgumentError.value(publicKey, 'publicKey', 'Invalid Key'); @@ -473,15 +536,17 @@ class PdfPKCSCertificate { } if (id != null) { if (_keyCertificates.containsKey(id)) { - certificates = _keyCertificates[id] is X509Certificates - ? _keyCertificates[id] - : null; + certificates = + _keyCertificates[id] is X509Certificates + ? _keyCertificates[id] + : null; } } else { if (_keyCertificates.containsKey(key)) { - certificates = _keyCertificates[key] is X509Certificates - ? _keyCertificates[key] - : null; + certificates = + _keyCertificates[key] is X509Certificates + ? _keyCertificates[key] + : null; } } return certificates as X509Certificates?; @@ -500,15 +565,17 @@ class PdfPKCSCertificate { } if (id != null) { if (_keyCertificates.containsKey(id)) { - certificates = _keyCertificates[id] is X509Certificates - ? _keyCertificates[id] - : null; + certificates = + _keyCertificates[id] is X509Certificates + ? _keyCertificates[id] + : null; } } else { if (_keyCertificates.containsKey(key)) { - certificates = _keyCertificates[key] is X509Certificates - ? _keyCertificates[key] - : null; + certificates = + _keyCertificates[key] is X509Certificates + ? _keyCertificates[key] + : null; } } return certificates as X509Certificates?; @@ -527,15 +594,17 @@ class PdfPKCSCertificate { while (certificates != null) { final X509Certificate x509Certificate = certificates.certificate!; X509Certificates? nextCertificate; - final Asn1Octet? x509Extension = - x509Certificate.getExtension(X509Extensions.authorityKeyIdentifier); + final Asn1Octet? x509Extension = x509Certificate.getExtension( + X509Extensions.authorityKeyIdentifier, + ); if (x509Extension != null) { final _KeyIdentifier id = _KeyIdentifier.getKeyIdentifier( - Asn1Stream(PdfStreamReader(x509Extension.getOctets())) - .readAsn1()); + Asn1Stream(PdfStreamReader(x509Extension.getOctets())).readAsn1(), + ); if (id.keyID != null) { - if (_chainCertificates - .containsKey(_CertificateIdentifier(id: id.keyID))) { + if (_chainCertificates.containsKey( + _CertificateIdentifier(id: id.keyID), + )) { nextCertificate = _chainCertificates[_CertificateIdentifier(id: id.keyID)]; } @@ -575,7 +644,9 @@ class PdfPKCSCertificate { } } return List.generate( - certificateList.length, (int i) => certificateList[i]); + certificateList.length, + (int i) => certificateList[i], + ); } return null; } @@ -593,15 +664,17 @@ class PdfPKCSCertificate { while (certificates != null) { final X509Certificate x509Certificate = certificates.certificate!; X509Certificates? nextCertificate; - final Asn1Octet? x509Extension = x509Certificate - .getExtension(X509Extensions.authorityKeyIdentifier); + final Asn1Octet? x509Extension = x509Certificate.getExtension( + X509Extensions.authorityKeyIdentifier, + ); if (x509Extension != null) { final _KeyIdentifier id = _KeyIdentifier.getKeyIdentifier( - Asn1Stream(PdfStreamReader(x509Extension.getOctets())) - .readAsn1()); + Asn1Stream(PdfStreamReader(x509Extension.getOctets())).readAsn1(), + ); if (id.keyID != null) { - if (_chainCertificates - .containsKey(_CertificateIdentifier(id: id.keyID))) { + if (_chainCertificates.containsKey( + _CertificateIdentifier(id: id.keyID), + )) { nextCertificate = _chainCertificates[_CertificateIdentifier(id: id.keyID)]; } @@ -641,7 +714,9 @@ class PdfPKCSCertificate { } } x509Certificates = List.generate( - certificateList.length, (int i) => certificateList[i]); + certificateList.length, + (int i) => certificateList[i], + ); } }); return x509Certificates; @@ -721,9 +796,10 @@ class _CertificateTable { class _CertificateIdentifier { _CertificateIdentifier({CipherParameter? pubKey, List? id}) { - this.id = pubKey != null - ? PdfPKCSCertificate.createSubjectKeyID(pubKey)._bytes - : id; + this.id = + pubKey != null + ? PdfPKCSCertificate.createSubjectKeyID(pubKey)._bytes + : id; } //Fields List? id; @@ -873,8 +949,12 @@ class _PasswordUtility { return result; } - ICipherParameter? generateCipherParameters(String algorithm, String password, - bool isWrong, Asn1Encode? pbeParameters) { + ICipherParameter? generateCipherParameters( + String algorithm, + String password, + bool isWrong, + Asn1Encode? pbeParameters, + ) { final String mechanism = getAlgorithmFromUpeerInvariant(algorithm)!; late List keyBytes; List? salt; @@ -889,8 +969,14 @@ class _PasswordUtility { ICipherParameter? parameters; _PasswordGenerator generator; if (mechanism.startsWith('PBEwithSHA-1')) { - generator = getEncoder(_type[mechanism], DigestAlgorithms.sha1, keyBytes, - salt!, iterationCount, password); + generator = getEncoder( + _type[mechanism], + DigestAlgorithms.sha1, + keyBytes, + salt!, + iterationCount, + password, + ); if (mechanism == 'PBEwithSHA-1and128bitAES-CBC-BC') { parameters = generator.generateParam(128, 'AES', 128); } else if (mechanism == 'PBEwithSHA-1and192bitAES-CBC-BC') { @@ -915,8 +1001,14 @@ class _PasswordUtility { parameters = generator.generateParam(64, 'RC2', 64); } } else if (mechanism.startsWith('PBEwithSHA-256')) { - generator = getEncoder(_type[mechanism], DigestAlgorithms.sha256, - keyBytes, salt!, iterationCount, password); + generator = getEncoder( + _type[mechanism], + DigestAlgorithms.sha256, + keyBytes, + salt!, + iterationCount, + password, + ); if (mechanism == 'PBEwithSHA-256and128bitAES-CBC-BC') { parameters = generator.generateParam(128, 'AES', 128); } else if (mechanism == 'PBEwithSHA-256and192bitAES-CBC-BC') { @@ -925,10 +1017,17 @@ class _PasswordUtility { parameters = generator.generateParam(256, 'AES', 128); } } else if (mechanism.startsWith('PBEwithHmac')) { - final String digest = - getDigest(mechanism.substring('PBEwithHmac'.length)); + final String digest = getDigest( + mechanism.substring('PBEwithHmac'.length), + ); generator = getEncoder( - _type[mechanism], digest, keyBytes, salt!, iterationCount, password); + _type[mechanism], + digest, + keyBytes, + salt!, + iterationCount, + password, + ); final int? bitLen = getBlockSize(digest); parameters = generator.generateParam(bitLen); } @@ -964,14 +1063,17 @@ class _PasswordUtility { } ICipherParameter? fixDataEncryptionParity( - String mechanism, ICipherParameter? parameters) { + String mechanism, + ICipherParameter? parameters, + ) { if (!mechanism.endsWith('DES-CBC') & !mechanism.endsWith('DESEDE-CBC')) { return parameters; } if (parameters is InvalidParameter) { return InvalidParameter( - fixDataEncryptionParity(mechanism, parameters.parameters), - parameters.bytes!); + fixDataEncryptionParity(mechanism, parameters.parameters), + parameters.keys, + ); } final KeyParameter kParam = parameters! as KeyParameter; final List keyBytes = kParam.keys; @@ -989,7 +1091,7 @@ class _PasswordUtility { 0x01)) .toUnsigned(8); } - return KeyParameter(keyBytes); + return KeyParameter(Uint8List.fromList(keyBytes)); } bool isPkcs12(String algorithm) { @@ -1020,14 +1122,23 @@ class _PasswordUtility { return digest; } - _PasswordGenerator getEncoder(String? type, String digest, List key, - List salt, int iterationCount, String password) { + _PasswordGenerator getEncoder( + String? type, + String digest, + List key, + List salt, + int iterationCount, + String password, + ) { _PasswordGenerator generator; if (type == _pkcs12) { generator = _Pkcs12AlgorithmGenerator(digest, password); } else { throw ArgumentError.value( - type, 'type', 'Invalid Password Based Encryption type'); + type, + 'type', + 'Invalid Password Based Encryption type', + ); } generator.init(key, salt, iterationCount); return generator; @@ -1062,8 +1173,10 @@ abstract class _PasswordGenerator { if (password.isEmpty) { return isWrong ? List.generate(2, (int i) => 0) : []; } - final List bytes = - List.generate((password.length + 1) * 2, (int i) => 0); + final List bytes = List.generate( + (password.length + 1) * 2, + (int i) => 0, + ); final List tempBytes = encodeBigEndian(password); int i = 0; // ignore: avoid_function_literals_in_foreach_calls @@ -1120,10 +1233,14 @@ class _Pkcs12AlgorithmGenerator extends _PasswordGenerator { keySize = keySize! ~/ 8; final List bytes = generateDerivedKey(_keyMaterial, keySize); final _ParamUtility util = _ParamUtility(); - final KeyParameter key = - util.createKeyParameter(algorithm!, bytes, 0, keySize); + final KeyParameter key = util.createKeyParameter( + algorithm!, + bytes, + 0, + keySize, + ); final List iv = generateDerivedKey(_invaidMaterial, size); - return InvalidParameter(key, iv, 0, size); + return InvalidParameter(key, Uint8List.fromList(iv)); } else if (algorithm != null) { keySize = keySize! ~/ 8; final List bytes = generateDerivedKey(_keyMaterial, keySize); @@ -1132,7 +1249,11 @@ class _Pkcs12AlgorithmGenerator extends _PasswordGenerator { } else { keySize = keySize! ~/ 8; final List bytes = generateDerivedKey(_keyMaterial, keySize); - return KeyParameter.fromLengthValue(bytes, 0, keySize); + return KeyParameter.fromLengthValue( + Uint8List.fromList(bytes), + 0, + keySize, + ); } } @@ -1145,8 +1266,9 @@ class _Pkcs12AlgorithmGenerator extends _PasswordGenerator { List s; if (_value != null && _value!.isNotEmpty) { s = List.generate( - _length * ((_value!.length + _length - 1) ~/ _length), - (int index) => 0); + _length * ((_value!.length + _length - 1) ~/ _length), + (int index) => 0, + ); for (int index = 0; index != s.length; index++) { s[index] = _value![index % _value!.length]; } @@ -1156,16 +1278,19 @@ class _Pkcs12AlgorithmGenerator extends _PasswordGenerator { List password; if (_password != null && _password!.isNotEmpty) { password = List.generate( - _length * ((_password!.length + _length - 1) ~/ _length), - (int index) => 0); + _length * ((_password!.length + _length - 1) ~/ _length), + (int index) => 0, + ); for (int index = 0; index != password.length; index++) { password[index] = _password![index % _password!.length]; } } else { password = []; } - List tempBytes = - List.generate(s.length + password.length, (int index) => 0); + List tempBytes = List.generate( + s.length + password.length, + (int index) => 0, + ); List.copyRange(tempBytes, 0, s, 0, s.length); List.copyRange(tempBytes, s.length, password, 0, password.length); final List b = List.generate(_length, (int index) => 0); @@ -1188,8 +1313,13 @@ class _Pkcs12AlgorithmGenerator extends _PasswordGenerator { tempBytes = adjust(tempBytes, j * _length, b); } if (i == c) { - List.copyRange(derivedKey, (i - 1) * _size!, a!, 0, - derivedKey.length - ((i - 1) * _size!)); + List.copyRange( + derivedKey, + (i - 1) * _size!, + a!, + 0, + derivedKey.length - ((i - 1) * _size!), + ); } else { List.copyRange(derivedKey, (i - 1) * _size!, a!, 0, a.length); } @@ -1214,7 +1344,10 @@ class _Pkcs12PasswordParameter extends Asn1Encode { _Pkcs12PasswordParameter(Asn1Sequence sequence) { if (sequence.count != 2) { throw ArgumentError.value( - sequence, 'sequence', 'Invalid length in sequence'); + sequence, + 'sequence', + 'Invalid length in sequence', + ); } _octet = Asn1Octet.getOctetStringFromObject(sequence[0]); _iterations = DerInteger.getNumber(sequence[1]); @@ -1248,11 +1381,13 @@ class _ParamUtility { 'DESEDEWRAP', 'TDEA', DerObjectID('1.3.14.3.2.17'), - PkcsObjectId.idAlgCms3DesWrap + PkcsObjectId.idAlgCms3DesWrap, ]); addAlgorithm('DESEDE3', [PkcsObjectId.desEde3Cbc]); - addAlgorithm( - 'RC2', [PkcsObjectId.rc2Cbc, PkcsObjectId.idAlgCmsRC2Wrap]); + addAlgorithm('RC2', [ + PkcsObjectId.rc2Cbc, + PkcsObjectId.idAlgCmsRC2Wrap, + ]); } //Fields @@ -1272,7 +1407,11 @@ class _ParamUtility { } KeyParameter createKeyParameter( - String algorithm, List bytes, int offset, int? length) { + String algorithm, + List bytes, + int offset, + int? length, + ) { String? name; final String lower = algorithm.toLowerCase(); _algorithms.forEach((String key, String value) { @@ -1282,7 +1421,10 @@ class _ParamUtility { }); if (name == null) { throw ArgumentError.value( - algorithm, 'algorithm', 'Invalid entry. Algorithm'); + algorithm, + 'algorithm', + 'Invalid entry. Algorithm', + ); } if (name == 'DES') { return _DataEncryptionParameter.fromLengthValue(bytes, offset, length!); @@ -1290,23 +1432,35 @@ class _ParamUtility { if (name == 'DESEDE' || name == 'DESEDE3') { return _DesedeAlgorithmParameter(bytes, offset, length); } - return KeyParameter.fromLengthValue(bytes, offset, length!); + return KeyParameter.fromLengthValue( + Uint8List.fromList(bytes), + offset, + length!, + ); } } class _DataEncryptionParameter extends KeyParameter { - _DataEncryptionParameter(List keys) : super(keys) { + _DataEncryptionParameter(List keys) : super(Uint8List.fromList(keys)) { if (checkKey(keys, 0)) { throw ArgumentError.value( - keys, 'keys', 'Invalid Data Encryption keys creation'); + keys, + 'keys', + 'Invalid Data Encryption keys creation', + ); } } _DataEncryptionParameter.fromLengthValue( - List keys, int offset, int length) - : super.fromLengthValue(keys, offset, length) { + List keys, + int offset, + int length, + ) : super.fromLengthValue(Uint8List.fromList(keys), offset, length) { if (checkKey(keys, 0)) { throw ArgumentError.value( - keys, 'keys', 'Invalid Data Encryption keys creation'); + keys, + 'keys', + 'Invalid Data Encryption keys creation', + ); } } static List dataEncryptionWeekKeys = [ @@ -1437,7 +1591,7 @@ class _DataEncryptionParameter extends KeyParameter { 254, 241, 254, - 241 + 241, ]; static bool checkKey(List bytes, int offset) { @@ -1458,18 +1612,11 @@ class _DataEncryptionParameter extends KeyParameter { } return false; } - - @override - List get keys => List.from(bytes!); - @override - set keys(List? value) { - bytes = value; - } } class _DesedeAlgorithmParameter extends _DataEncryptionParameter { _DesedeAlgorithmParameter(List key, int keyOffset, int? keyLength) - : super(fixKey(key, keyOffset, keyLength)); + : super(fixKey(key, keyOffset, keyLength)); //Implementation static List fixKey(List key, int keyOffset, int? keyLength) { final List tmp = List.generate(24, (int i) => 0); @@ -1483,11 +1630,17 @@ class _DesedeAlgorithmParameter extends _DataEncryptionParameter { break; default: throw ArgumentError.value( - keyLength, 'keyLen', 'Bad length for DESede key'); + keyLength, + 'keyLen', + 'Bad length for DESede key', + ); } if (checkKeyValue(tmp, 0, tmp.length)) { throw ArgumentError.value( - key, 'key', 'Attempt to create weak DESede key'); + key, + 'key', + 'Attempt to create weak DESede key', + ); } return tmp; } @@ -1500,13 +1653,6 @@ class _DesedeAlgorithmParameter extends _DataEncryptionParameter { } return false; } - - @override - List get keys => List.from(bytes!); - @override - set keys(List? value) { - bytes = value; - } } class _CipherUtils { @@ -1580,8 +1726,11 @@ class _CipherUtils { break; // ignore: no_default_cases default: - throw ArgumentError.value(cipherPadding, 'cpiher padding algorithm', - 'Invalid cipher algorithm'); + throw ArgumentError.value( + cipherPadding, + 'cpiher padding algorithm', + 'Invalid cipher algorithm', + ); } } String mode = ''; @@ -1620,7 +1769,10 @@ class _CipherUtils { return BufferedBlockPadding(blockCipher); } throw ArgumentError.value( - blockCipher, 'Cipher Algorithm', 'Invalid cipher algorithm'); + blockCipher, + 'Cipher Algorithm', + 'Invalid cipher algorithm', + ); } _CipherAlgorithm getAlgorithm(String name) { @@ -1723,7 +1875,7 @@ enum _CipherPaddingType { pkcs7, pkcs7Padding, withCipherTextStealing, - x923Padding + x923Padding, } class _KeyIdentifier extends Asn1Encode { @@ -1742,7 +1894,10 @@ class _KeyIdentifier extends Asn1Encode { break; default: throw ArgumentError.value( - sequence, 'sequence', 'Invalid entry in sequence'); + sequence, + 'sequence', + 'Invalid entry in sequence', + ); } } }); @@ -1805,8 +1960,11 @@ class _DesEdeAlogorithm extends _DataEncryption { } final List keyMaster = parameters.keys; if (keyMaster.length != 24 && keyMaster.length != 16) { - throw ArgumentError.value(parameters, 'parameters', - 'Invalid key size. Size must be 16 or 24 bytes.'); + throw ArgumentError.value( + parameters, + 'parameters', + 'Invalid key size. Size must be 16 or 24 bytes.', + ); } _isEncryption = forEncryption; final List key1 = List.generate(8, (int i) => 0); @@ -1825,19 +1983,26 @@ class _DesEdeAlogorithm extends _DataEncryption { } @override - Map processBlock( - [List? inputBytes, - int? inOffset, - List? outputBytes, - int? outOffset]) { + Map processBlock([ + List? inputBytes, + int? inOffset, + List? outputBytes, + int? outOffset, + ]) { ArgumentError.checkNotNull(_key1); if ((inOffset! + _blockSize!) > inputBytes!.length) { throw ArgumentError.value( - inOffset, 'inOffset', 'Invalid length in input bytes'); + inOffset, + 'inOffset', + 'Invalid length in input bytes', + ); } if ((outOffset! + _blockSize!) > outputBytes!.length) { throw ArgumentError.value( - inOffset, 'inOffset', 'Invalid length in output bytes'); + inOffset, + 'inOffset', + 'Invalid length in output bytes', + ); } final List tempBytes = List.generate(_blockSize!, (int i) => 0); if (_isEncryption!) { @@ -1856,7 +2021,7 @@ class _DesEdeAlogorithm extends _DataEncryption { void reset() {} } -class _DataEncryption implements ICipher { +class _DataEncryption extends ICipher { _DataEncryption() { _blockSize = 8; byteBit = [128, 64, 32, 16, 8, 4, 2, 1]; @@ -1884,7 +2049,7 @@ class _DataEncryption implements ICipher { 0x8, 0x4, 0x2, - 0x1 + 0x1, ]; pc1 = [ 56, @@ -1942,7 +2107,7 @@ class _DataEncryption implements ICipher { 27, 19, 11, - 3 + 3, ]; toTrot = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; pc2 = [ @@ -1993,7 +2158,7 @@ class _DataEncryption implements ICipher { 49, 35, 28, - 31 + 31, ]; sp1 = [ 0x01010400, @@ -2059,7 +2224,7 @@ class _DataEncryption implements ICipher { 0x00010004, 0x00010400, 0x00000000, - 0x01010004 + 0x01010004, ]; sp2 = [ 0x80108020, @@ -2125,7 +2290,7 @@ class _DataEncryption implements ICipher { 0x80000000, 0x80100020, 0x80108020, - 0x00108000 + 0x00108000, ]; sp3 = [ 0x00000208, @@ -2191,7 +2356,7 @@ class _DataEncryption implements ICipher { 0x00020208, 0x00000008, 0x08020008, - 0x00020200 + 0x00020200, ]; sp4 = [ 0x00802001, @@ -2257,7 +2422,7 @@ class _DataEncryption implements ICipher { 0x00000080, 0x00800000, 0x00002000, - 0x00802080 + 0x00802080, ]; sp5 = [ 0x00000100, @@ -2323,7 +2488,7 @@ class _DataEncryption implements ICipher { 0x00000000, 0x40080000, 0x02080100, - 0x40000100 + 0x40000100, ]; sp6 = [ 0x20000010, @@ -2389,7 +2554,7 @@ class _DataEncryption implements ICipher { 0x20404000, 0x20000000, 0x00400010, - 0x20004010 + 0x20004010, ]; sp7 = [ 0x00200000, @@ -2455,7 +2620,7 @@ class _DataEncryption implements ICipher { 0x04000002, 0x04000800, 0x00000800, - 0x00200002 + 0x00200002, ]; sp8 = [ 0x10001040, @@ -2521,7 +2686,7 @@ class _DataEncryption implements ICipher { 0x00001040, 0x00040040, 0x10000000, - 0x10041000 + 0x10041000, ]; } @@ -2562,15 +2727,25 @@ class _DataEncryption implements ICipher { @override Map processBlock( - List? inBytes, int inOffset, List? outBytes, int? outOffset) { + List? inBytes, + int inOffset, + List? outBytes, + int? outOffset, + ) { ArgumentError.checkNotNull(_keys); if ((inOffset + _blockSize!) > inBytes!.length) { throw ArgumentError.value( - inOffset, 'inOffset', 'Invalid length in input bytes'); + inOffset, + 'inOffset', + 'Invalid length in input bytes', + ); } if ((outOffset! + _blockSize!) > outBytes!.length) { throw ArgumentError.value( - outOffset, 'outOffset', 'Invalid length in output bytes'); + outOffset, + 'outOffset', + 'Invalid length in output bytes', + ); } encryptData(_keys, inBytes, inOffset, outBytes, outOffset); return {'length': _blockSize, 'output': outBytes}; @@ -2641,8 +2816,13 @@ class _DataEncryption implements ICipher { return newKeys; } - void encryptData(List? keys, List inputBytes, int inOffset, - List outBytes, int outOffset) { + void encryptData( + List? keys, + List inputBytes, + int inOffset, + List outBytes, + int outOffset, + ) { int left = Asn1.beToUInt32(inputBytes, inOffset); int right = Asn1.beToUInt32(inputBytes, inOffset + 4); int data = (((left >> 4) ^ right) & 0x0f0f0f0f).toUnsigned(32); @@ -2710,7 +2890,7 @@ class _DataEncryption implements ICipher { } } -class _Rc2Algorithm implements ICipher { +class _Rc2Algorithm extends ICipher { _Rc2Algorithm() { _piTable = [ 217, @@ -2968,7 +3148,7 @@ class _Rc2Algorithm implements ICipher { 254, 127, 193, - 173 + 173, ]; _blockSize = 8; } @@ -3030,7 +3210,11 @@ class _Rc2Algorithm implements ICipher { @override Map processBlock( - List? input, int inOff, List? output, int? outOff) { + List? input, + int inOff, + List? output, + int? outOff, + ) { if (_isEncrypt!) { encryptBlock(input!, inOff, output!, outOff!); } else { @@ -3045,7 +3229,11 @@ class _Rc2Algorithm implements ICipher { } void encryptBlock( - List input, int inOff, List outBytes, int outOff) { + List input, + int inOff, + List outBytes, + int outOff, + ) { int x76 = ((input[inOff + 7] & 0xff) << 8) + (input[inOff + 6] & 0xff); int x54 = ((input[inOff + 5] & 0xff) << 8) + (input[inOff + 4] & 0xff); int x32 = ((input[inOff + 3] & 0xff) << 8) + (input[inOff + 2] & 0xff); @@ -3087,7 +3275,11 @@ class _Rc2Algorithm implements ICipher { } void decryptBlock( - List input, int inOff, List outBytes, int outOff) { + List input, + int inOff, + List outBytes, + int outOff, + ) { int x76 = ((input[inOff + 7] & 0xff) << 8) + (input[inOff + 6] & 0xff); int x54 = ((input[inOff + 5] & 0xff) << 8) + (input[inOff + 4] & 0xff); int x32 = ((input[inOff + 3] & 0xff) << 8) + (input[inOff + 2] & 0xff); @@ -3151,7 +3343,7 @@ class _PfxData extends Asn1Encode { Asn1 getAsn1() { final Asn1EncodeCollection collection = Asn1EncodeCollection([ DerInteger(bigIntToBytes(BigInt.from(3))), - _contentInformation + _contentInformation, ]); if (_macInformation != null) { collection.encodableObjects.add(_macInformation); @@ -3164,7 +3356,10 @@ class _ContentInformation extends Asn1Encode { _ContentInformation(Asn1Sequence sequence) { if (sequence.count < 1 || sequence.count > 2) { throw ArgumentError.value( - sequence, 'sequence', 'Invalid length in sequence'); + sequence, + 'sequence', + 'Invalid length in sequence', + ); } _contentType = sequence[0] as DerObjectID?; if (sequence.count > 1) { @@ -3193,8 +3388,9 @@ class _ContentInformation extends Asn1Encode { @override Asn1 getAsn1() { - final Asn1EncodeCollection collection = - Asn1EncodeCollection([_contentType]); + final Asn1EncodeCollection collection = Asn1EncodeCollection([ + _contentType, + ]); if (_content != null) { collection.encodableObjects.add(DerTag(0, _content)); } @@ -3231,8 +3427,10 @@ class _MacInformation extends Asn1Encode { @override Asn1 getAsn1() { - final Asn1EncodeCollection collection = - Asn1EncodeCollection([_digest, DerOctet(_value!)]); + final Asn1EncodeCollection collection = Asn1EncodeCollection([ + _digest, + DerOctet(_value!), + ]); if (_count != BigInt.one) { collection.encodableObjects.add(DerInteger.fromNumber(_count)); } @@ -3244,7 +3442,10 @@ class EncryptedPrivateKey extends Asn1Encode { EncryptedPrivateKey(Asn1Sequence sequence) { if (sequence.count != 2) { throw ArgumentError.value( - sequence, 'sequence', 'Invalid length in sequence'); + sequence, + 'sequence', + 'Invalid length in sequence', + ); } _algorithms = Algorithms.getAlgorithms(sequence[0]); _octet = Asn1Octet.getOctetStringFromObject(sequence[1]); @@ -3272,8 +3473,11 @@ class EncryptedPrivateKey extends Asn1Encode { } class KeyInformation extends Asn1Encode { - KeyInformation(Algorithms algorithms, Asn1 privateKey, - [Asn1Set? attributes]) { + KeyInformation( + Algorithms algorithms, + Asn1 privateKey, [ + Asn1Set? attributes, + ]) { _privateKey = privateKey; _algorithms = algorithms; if (attributes != null) { @@ -3287,8 +3491,10 @@ class KeyInformation extends Asn1Encode { _algorithms = Algorithms.getAlgorithms(objects[1]); final dynamic privateKeyValue = objects[2]; try { - _privateKey = Asn1Stream(PdfStreamReader(privateKeyValue.getOctets())) - .readAsn1(); + _privateKey = + Asn1Stream( + PdfStreamReader(privateKeyValue.getOctets()), + ).readAsn1(); } catch (e) { throw ArgumentError.value(sequence, 'sequence', 'Invalid sequence'); } @@ -3322,7 +3528,7 @@ class KeyInformation extends Asn1Encode { final Asn1EncodeCollection v = Asn1EncodeCollection([ DerInteger.fromNumber(BigInt.from(0)), _algorithms, - DerOctet.fromObject(_privateKey!) + DerOctet.fromObject(_privateKey!), ]); if (_attributes != null) { v.encodableObjects.add(DerTag(0, _attributes, false)); @@ -3333,14 +3539,15 @@ class KeyInformation extends Asn1Encode { class _RsaKey extends Asn1Encode { _RsaKey( - BigInt modulus, - BigInt publicExponent, - BigInt privateExponent, - BigInt prime1, - BigInt prime2, - BigInt exponent1, - BigInt exponent2, - BigInt coefficient) { + BigInt modulus, + BigInt publicExponent, + BigInt privateExponent, + BigInt prime1, + BigInt prime2, + BigInt exponent1, + BigInt exponent2, + BigInt coefficient, + ) { _modulus = modulus; _publicExponent = publicExponent; _privateExponent = privateExponent; @@ -3374,17 +3581,19 @@ class _RsaKey extends Asn1Encode { BigInt? _coefficient; @override Asn1 getAsn1() { - return DerSequence(array: [ - DerInteger.fromNumber(BigInt.from(0)), - DerInteger.fromNumber(_modulus), - DerInteger.fromNumber(_publicExponent), - DerInteger.fromNumber(_privateExponent), - DerInteger.fromNumber(_prime1), - DerInteger.fromNumber(_prime2), - DerInteger.fromNumber(_exponent1), - DerInteger.fromNumber(_exponent2), - DerInteger.fromNumber(_coefficient) - ]); + return DerSequence( + array: [ + DerInteger.fromNumber(BigInt.from(0)), + DerInteger.fromNumber(_modulus), + DerInteger.fromNumber(_publicExponent), + DerInteger.fromNumber(_privateExponent), + DerInteger.fromNumber(_prime1), + DerInteger.fromNumber(_prime2), + DerInteger.fromNumber(_exponent1), + DerInteger.fromNumber(_exponent2), + DerInteger.fromNumber(_coefficient), + ], + ); } } @@ -3407,8 +3616,9 @@ class SubjectKeyID extends Asn1Encode { static PublicKeyInformation createSubjectKeyID(CipherParameter publicKey) { if (publicKey is RsaKeyParam) { final PublicKeyInformation information = PublicKeyInformation( - Algorithms(PkcsObjectId.rsaEncryption, DerNull.value), - RsaPublicKey(publicKey.modulus, publicKey.exponent).getAsn1()); + Algorithms(PkcsObjectId.rsaEncryption, DerNull.value), + RsaPublicKey(publicKey.modulus, publicKey.exponent).getAsn1(), + ); return information; } else { throw ArgumentError.value(publicKey, 'publicKey', 'Invalid Key'); @@ -3424,29 +3634,41 @@ class SubjectKeyID extends Asn1Encode { /// Internal class class CertificateIdentity { /// Internal constructor - CertificateIdentity(String hashAlgorithm, X509Certificate issuerCert, - DerInteger serialNumber) { - final Algorithms algorithms = - Algorithms(DerObjectID(hashAlgorithm), DerNull.value); + CertificateIdentity( + String hashAlgorithm, + X509Certificate issuerCert, + DerInteger serialNumber, + ) { + final Algorithms algorithms = Algorithms( + DerObjectID(hashAlgorithm), + DerNull.value, + ); try { final String algorithm = algorithms.id!.id!; - final X509Name? issuerName = SingnedCertificate.getCertificate( - Asn1.fromByteArray(issuerCert.getTbsCertificate()!))! - .subject; + final X509Name? issuerName = + SingnedCertificate.getCertificate( + Asn1.fromByteArray(issuerCert.getTbsCertificate()!), + )!.subject; MessageDigestFinder utilities = MessageDigestFinder(); - final List issuerNameHash = - utilities.getDigest(algorithm, issuerName!.getEncoded()!); + final List issuerNameHash = utilities.getDigest( + algorithm, + issuerName!.getEncoded()!, + ); final CipherParameter issuerKey = issuerCert.getPublicKey(); - final PublicKeyInformation info = - SubjectKeyID.createSubjectKeyID(issuerKey); + final PublicKeyInformation info = SubjectKeyID.createSubjectKeyID( + issuerKey, + ); utilities = MessageDigestFinder(); - final List issuerKeyHash = - utilities.getDigest(algorithm, info.publicKey!.getBytes()!); + final List issuerKeyHash = utilities.getDigest( + algorithm, + info.publicKey!.getBytes()!, + ); id = CertificateIdentityHelper( - hash: algorithms, - issuerName: DerOctet(issuerNameHash), - issuerKey: DerOctet(issuerKeyHash), - serialNumber: serialNumber); + hash: algorithms, + issuerName: DerOctet(issuerNameHash), + issuerKey: DerOctet(issuerKeyHash), + serialNumber: serialNumber, + ); } catch (e) { throw Exception('Invalid certificate ID'); } @@ -3462,11 +3684,12 @@ class CertificateIdentity { /// Internal class class CertificateIdentityHelper extends Asn1Encode { /// Internal constructor - CertificateIdentityHelper( - {Algorithms? hash, - Asn1Octet? issuerName, - Asn1Octet? issuerKey, - DerInteger? serialNumber}) { + CertificateIdentityHelper({ + Algorithms? hash, + Asn1Octet? issuerName, + Asn1Octet? issuerKey, + DerInteger? serialNumber, + }) { _hash = hash; _issuerName = issuerName; _issuerKey = issuerKey; @@ -3482,6 +3705,7 @@ class CertificateIdentityHelper extends Asn1Encode { @override Asn1 getAsn1() { return DerSequence( - array: [_hash!, _issuerName!, _issuerKey!, _serialNumber!]); + array: [_hash!, _issuerName!, _issuerKey!, _serialNumber!], + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature.dart index 98544e613..e8d0e7268 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature.dart @@ -34,29 +34,31 @@ import 'x509/x509_certificates.dart'; class PdfSignature { //Constructor /// Initializes a new instance of the [PdfSignature] class with the page and the signature name. - PdfSignature( - {String? signedName, - String? locationInfo, - String? reason, - String? contactInfo, - List? documentPermissions, - CryptographicStandard cryptographicStandard = CryptographicStandard.cms, - DigestAlgorithm digestAlgorithm = DigestAlgorithm.sha256, - PdfCertificate? certificate, - TimestampServer? timestampServer, - DateTime? signedDate}) { + PdfSignature({ + String? signedName, + String? locationInfo, + String? reason, + String? contactInfo, + List? documentPermissions, + CryptographicStandard cryptographicStandard = CryptographicStandard.cms, + DigestAlgorithm digestAlgorithm = DigestAlgorithm.sha256, + PdfCertificate? certificate, + TimestampServer? timestampServer, + DateTime? signedDate, + }) { _helper = PdfSignatureHelper(this); _init( - signedName, - locationInfo, - reason, - contactInfo, - documentPermissions, - cryptographicStandard, - digestAlgorithm, - certificate, - signedDate, - timestampServer); + signedName, + locationInfo, + reason, + contactInfo, + documentPermissions, + cryptographicStandard, + digestAlgorithm, + certificate, + signedDate, + timestampServer, + ); } //Fields @@ -66,7 +68,7 @@ class PdfSignature { //Properties /// Gets or sets the permission for certificated document. List documentPermissions = [ - PdfCertificationFlags.forbidChanges + PdfCertificationFlags.forbidChanges, ]; /// Gets or sets reason of signing. @@ -133,16 +135,17 @@ class PdfSignature { //Implementations void _init( - String? signedName, - String? locationInfo, - String? reason, - String? contactInfo, - List? documentPermissions, - CryptographicStandard cryptographicStandard, - DigestAlgorithm digestAlgorithm, - PdfCertificate? pdfCertificate, - DateTime? signedDate, - TimestampServer? timestampServer) { + String? signedName, + String? locationInfo, + String? reason, + String? contactInfo, + List? documentPermissions, + CryptographicStandard cryptographicStandard, + DigestAlgorithm digestAlgorithm, + PdfCertificate? pdfCertificate, + DateTime? signedDate, + TimestampServer? timestampServer, + ) { this.cryptographicStandard = cryptographicStandard; this.digestAlgorithm = digestAlgorithm; if (signedName != null) { @@ -173,15 +176,19 @@ class PdfSignature { /// Add external signer for signature. void addExternalSigner( - IPdfExternalSigner signer, List> publicCertificatesData) { + IPdfExternalSigner signer, + List> publicCertificatesData, + ) { _helper.externalSigner = signer; _externalRootCert = publicCertificatesData; if (_externalRootCert != null) { final X509CertificateParser parser = X509CertificateParser(); _helper.externalChain = []; - _externalRootCert!.toList().forEach((List certRawData) => _helper - .externalChain! - .add(parser.readCertificate(PdfStreamReader(certRawData)))); + _externalRootCert!.toList().forEach( + (List certRawData) => _helper.externalChain!.add( + parser.readCertificate(PdfStreamReader(certRawData)), + ), + ); } } @@ -204,10 +211,11 @@ class PdfSignature { /// // Dispose the document. /// document.dispose(); /// ``` - Future createLongTermValidity( - {List>? publicCertificatesData, - RevocationType type = RevocationType.ocspAndCrl, - bool includePublicCertificates = false}) async { + Future createLongTermValidity({ + List>? publicCertificatesData, + RevocationType type = RevocationType.ocspAndCrl, + bool includePublicCertificates = false, + }) async { final List x509CertificateList = []; if (publicCertificatesData != null) { final X509CertificateParser parser = X509CertificateParser(); @@ -217,9 +225,10 @@ class PdfSignature { x509CertificateList.add(certificate); } } else { - final List? certChain = timestampServer != null - ? await _helper.getTimestampCertificateChain() - : _helper.getCertificateChain(); + final List? certChain = + timestampServer != null + ? await _helper.getTimestampCertificateChain() + : _helper.getCertificateChain(); if (certChain != null) { for (final X509Certificate? certificate in certChain) { if (certificate != null) { @@ -231,7 +240,10 @@ class PdfSignature { } if (x509CertificateList.isNotEmpty) { return _helper.getDSSDetails( - x509CertificateList, type, includePublicCertificates); + x509CertificateList, + type, + includePublicCertificates, + ); } else { return false; } @@ -283,25 +295,30 @@ class PdfSignatureHelper { /// internal method /// To check annotation last elements have signature field void checkAnnotationElementsContainsSignature( - PdfPage page, String? signatureName) { - if (PdfPageHelper.getHelper(page) - .dictionary! - .containsKey(PdfDictionaryProperties.annots)) { + PdfPage page, + String? signatureName, + ) { + if (PdfPageHelper.getHelper( + page, + ).dictionary!.containsKey(PdfDictionaryProperties.annots)) { final IPdfPrimitive? annotationElements = PdfCrossTable.dereference( - PdfPageHelper.getHelper(page) - .dictionary![PdfDictionaryProperties.annots]); + PdfPageHelper.getHelper(page).dictionary![PdfDictionaryProperties + .annots], + ); IPdfPrimitive? lastElement; if (annotationElements != null && annotationElements is PdfArray && annotationElements.elements.isNotEmpty) { lastElement = PdfCrossTable.dereference( - annotationElements[annotationElements.elements.length - 1]); + annotationElements[annotationElements.elements.length - 1], + ); } if (lastElement != null && lastElement is PdfDictionary && lastElement.containsKey(PdfDictionaryProperties.t)) { - final IPdfPrimitive? name = - PdfCrossTable.dereference(lastElement[PdfDictionaryProperties.t]); + final IPdfPrimitive? name = PdfCrossTable.dereference( + lastElement[PdfDictionaryProperties.t], + ); String tempName = ''; if (name != null && name is PdfString) { tempName = utf8.decode(name.data!, allowMalformed: true); @@ -310,8 +327,9 @@ class PdfSignatureHelper { annotationElements != null && annotationElements is PdfArray && annotationElements.elements.isNotEmpty) { - annotationElements.elements - .removeAt(annotationElements.elements.length - 1); + annotationElements.elements.removeAt( + annotationElements.elements.length - 1, + ); } } } @@ -321,18 +339,22 @@ class PdfSignatureHelper { void catalogBeginSave(Object sender, SavePdfPrimitiveArgs? ars) { if (certificated) { IPdfPrimitive? permission = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(document!) - .catalog[PdfDictionaryProperties.perms]); + PdfDocumentHelper.getHelper(document!).catalog[PdfDictionaryProperties + .perms], + ); if (permission == null) { permission = PdfDictionary(); - (permission as PdfDictionary)[PdfDictionaryProperties.docMDP] = - PdfReferenceHolder(signatureDictionary); - PdfDocumentHelper.getHelper(document!) - .catalog[PdfDictionaryProperties.perms] = permission; + (permission as PdfDictionary)[PdfDictionaryProperties + .docMDP] = PdfReferenceHolder(signatureDictionary); + PdfDocumentHelper.getHelper(document!).catalog[PdfDictionaryProperties + .perms] = + permission; } else if (permission is PdfDictionary && !permission.containsKey(PdfDictionaryProperties.docMDP)) { - permission.setProperty(PdfDictionaryProperties.docMDP, - PdfReferenceHolder(signatureDictionary)); + permission.setProperty( + PdfDictionaryProperties.docMDP, + PdfReferenceHolder(signatureDictionary), + ); } } } @@ -343,8 +365,10 @@ class PdfSignatureHelper { final PdfFieldHelper helper = PdfFieldHelper.getHelper(field!); helper.dictionary!.encrypt = PdfSecurityHelper.getHelper(document!.security).encryptor.encrypt; - helper.dictionary! - .setProperty(PdfDictionaryProperties.ap, field!.appearance); + helper.dictionary!.setProperty( + PdfDictionaryProperties.ap, + field!.appearance, + ); } } @@ -413,8 +437,11 @@ class PdfSignatureHelper { } /// internal method - Future getDSSDetails(List certificates, - RevocationType type, bool includePublicCertificates) async { + Future getDSSDetails( + List certificates, + RevocationType type, + bool includePublicCertificates, + ) async { final List> crlCollection = >[]; final List> ocspCollection = >[]; final List> certCollection = >[]; @@ -429,7 +456,9 @@ class PdfSignatureHelper { (crlCollection.isEmpty && type == RevocationType.ocspOrCrl)) { final Ocsp ocsp = Ocsp(); final List? ocspBytes = await ocsp.getEncodedOcspResponse( - certificates[k], getRoot(certificates[k], certificates)); + certificates[k], + getRoot(certificates[k], certificates), + ); if (ocspBytes != null) { ocspCollection.add(buildOCSPResponse(ocspBytes)); } @@ -437,8 +466,9 @@ class PdfSignatureHelper { if (type == RevocationType.crl || type == RevocationType.ocspAndCrl || (ocspCollection.isEmpty && type == RevocationType.ocspOrCrl)) { - final List> cim = - await RevocationList().getEncoded(certificates[k]); + final List> cim = await RevocationList().getEncoded( + certificates[k], + ); if (cim.isNotEmpty) { for (final List crl in cim) { bool duplicate = false; @@ -456,7 +486,10 @@ class PdfSignatureHelper { } } return initializeDssDictionary( - crlCollection, ocspCollection, certCollection); + crlCollection, + ocspCollection, + certCollection, + ); } bool _listsAreEqual(List list1, List list2) { @@ -472,8 +505,11 @@ class PdfSignatureHelper { } /// internal method - bool initializeDssDictionary(List> crlCollection, - List> ocspCollection, List> certCollection) { + bool initializeDssDictionary( + List> crlCollection, + List> ocspCollection, + List> certCollection, + ) { if (crlCollection.isEmpty && ocspCollection.isEmpty && certCollection.isEmpty) { @@ -484,7 +520,8 @@ class PdfSignatureHelper { final PdfDocumentHelper helper = PdfDocumentHelper.getHelper(document!); if (helper.catalog.containsKey(PdfDictionaryProperties.dss)) { final IPdfPrimitive? dss = PdfCrossTable.dereference( - helper.catalog[PdfDictionaryProperties.dss]); + helper.catalog[PdfDictionaryProperties.dss], + ); if (dss != null && dss is PdfDictionary) { dssDictionary = dss; } @@ -498,29 +535,33 @@ class PdfSignatureHelper { PdfArray cetrsArray = PdfArray(); if (dssDictionary.containsKey(PdfDictionaryProperties.ocsps)) { final IPdfPrimitive? dssOcsp = PdfCrossTable.dereference( - dssDictionary[PdfDictionaryProperties.ocsps]); + dssDictionary[PdfDictionaryProperties.ocsps], + ); if (dssOcsp != null && dssOcsp is PdfArray) { ocspArray = dssOcsp; } } if (dssDictionary.containsKey(PdfDictionaryProperties.crls)) { final IPdfPrimitive? dsscrl = PdfCrossTable.dereference( - dssDictionary[PdfDictionaryProperties.crls]); + dssDictionary[PdfDictionaryProperties.crls], + ); if (dsscrl != null && dsscrl is PdfArray) { crlArray = dsscrl; } } PdfDictionary vriDictionary = PdfDictionary(); if (dssDictionary.containsKey(PdfDictionaryProperties.vri)) { - final IPdfPrimitive? dssVri = - PdfCrossTable.dereference(dssDictionary[PdfDictionaryProperties.vri]); + final IPdfPrimitive? dssVri = PdfCrossTable.dereference( + dssDictionary[PdfDictionaryProperties.vri], + ); if (dssVri != null && dssVri is PdfDictionary) { vriDictionary = dssVri; } } if (dssDictionary.containsKey(PdfDictionaryProperties.certs)) { final IPdfPrimitive? dssCerts = PdfCrossTable.dereference( - dssDictionary[PdfDictionaryProperties.certs]); + dssDictionary[PdfDictionaryProperties.certs], + ); if (dssCerts != null && dssCerts is PdfArray) { cetrsArray = dssCerts; } @@ -551,14 +592,16 @@ class PdfSignatureHelper { final String vriName = getVRIName().toUpperCase(); PdfDictionary vriDataDictionary = PdfDictionary(); if (vriDictionary.containsKey(vriName)) { - final IPdfPrimitive? dssVriData = - PdfCrossTable.dereference(vriDictionary[vriName]); + final IPdfPrimitive? dssVriData = PdfCrossTable.dereference( + vriDictionary[vriName], + ); if (dssVriData != null && dssVriData is PdfDictionary) { vriDataDictionary = dssVriData; } if (vriDataDictionary.containsKey(PdfDictionaryProperties.ocsp)) { final IPdfPrimitive? vriOCSP = PdfCrossTable.dereference( - vriDataDictionary[PdfDictionaryProperties.ocsp]); + vriDataDictionary[PdfDictionaryProperties.ocsp], + ); if (vriOCSP != null && vriOCSP is PdfArray) { for (int i = 0; i < ocspVRI.count; i++) { if (!vriOCSP.contains(ocspVRI[i]!)) { @@ -569,7 +612,8 @@ class PdfSignatureHelper { } if (vriDataDictionary.containsKey(PdfDictionaryProperties.crl)) { final IPdfPrimitive? vriCRL = PdfCrossTable.dereference( - vriDataDictionary[PdfDictionaryProperties.crl]); + vriDataDictionary[PdfDictionaryProperties.crl], + ); if (vriCRL != null && vriCRL is PdfArray) { for (int i = 0; i < crlVRI.count; i++) { if (!vriCRL.contains(crlVRI[i]!)) { @@ -579,27 +623,33 @@ class PdfSignatureHelper { } } } else { - vriDataDictionary.items![PdfName(PdfDictionaryProperties.ocsp)] = - PdfReferenceHolder(ocspArray); - vriDataDictionary.items![PdfName(PdfDictionaryProperties.crl)] = - PdfReferenceHolder(crlArray); - vriDictionary.items![PdfName(getVRIName().toUpperCase())] = - PdfReferenceHolder(vriDataDictionary); + vriDataDictionary.items![PdfName( + PdfDictionaryProperties.ocsp, + )] = PdfReferenceHolder(ocspArray); + vriDataDictionary.items![PdfName( + PdfDictionaryProperties.crl, + )] = PdfReferenceHolder(crlArray); + vriDictionary.items![PdfName( + getVRIName().toUpperCase(), + )] = PdfReferenceHolder(vriDataDictionary); } vriDictionary.modify(); - dssDictionary.items![PdfName(PdfDictionaryProperties.ocsps)] = - PdfReferenceHolder(ocspArray); - dssDictionary.items![PdfName(PdfDictionaryProperties.crls)] = - PdfReferenceHolder(crlArray); - dssDictionary.items![PdfName(PdfDictionaryProperties.vri)] = - PdfReferenceHolder(vriDictionary); + dssDictionary.items![PdfName( + PdfDictionaryProperties.ocsps, + )] = PdfReferenceHolder(ocspArray); + dssDictionary.items![PdfName( + PdfDictionaryProperties.crls, + )] = PdfReferenceHolder(crlArray); + dssDictionary.items![PdfName( + PdfDictionaryProperties.vri, + )] = PdfReferenceHolder(vriDictionary); if (certCollection.isNotEmpty) { - dssDictionary.items![PdfName(PdfDictionaryProperties.certs)] = - PdfReferenceHolder(cetrsArray); + dssDictionary.items![PdfName( + PdfDictionaryProperties.certs, + )] = PdfReferenceHolder(cetrsArray); } - PdfDocumentHelper.getHelper(document!) - .catalog[PdfDictionaryProperties.dss] = - PdfReferenceHolder(dssDictionary); + PdfDocumentHelper.getHelper(document!).catalog[PdfDictionaryProperties + .dss] = PdfReferenceHolder(dssDictionary); dssDictionary.modify(); return true; } @@ -622,16 +672,19 @@ class PdfSignatureHelper { /// internal method String getVRIName() { if (_nameData == null && field != null) { - final PdfSignatureFieldHelper helper = - PdfSignatureFieldHelper.getHelper(field!); + final PdfSignatureFieldHelper helper = PdfSignatureFieldHelper.getHelper( + field!, + ); if (helper.dictionary!.containsKey(PdfDictionaryProperties.v)) { final IPdfPrimitive? v = PdfCrossTable.dereference( - helper.dictionary![PdfDictionaryProperties.v]); + helper.dictionary![PdfDictionaryProperties.v], + ); if (v != null && v is PdfDictionary && v.containsKey(PdfDictionaryProperties.contents)) { - final IPdfPrimitive? contents = - PdfCrossTable.dereference(v[PdfDictionaryProperties.contents]); + final IPdfPrimitive? contents = PdfCrossTable.dereference( + v[PdfDictionaryProperties.contents], + ); if (contents != null && contents is PdfString) { _nameData = contents.data; } @@ -654,9 +707,10 @@ class PdfSignatureHelper { if (i == 8 || i == 12 || i == 16 || i == 20) { buffer.write('-'); } - final int digit = i == 12 - ? 4 // Specifies the version (4) for UUID v4 - : (i == 16 ? (random.nextInt(4) + 8) : random.nextInt(16)); + final int digit = + i == 12 + ? 4 // Specifies the version (4) for UUID v4 + : (i == 16 ? (random.nextInt(4) + 8) : random.nextInt(16)); buffer.write(digit.toRadixString(16)); } return buffer.toString(); @@ -670,18 +724,20 @@ class PdfSignatureHelper { PdfSignatureFieldHelper.getHelper(field!); if (helper.dictionary!.containsKey(PdfDictionaryProperties.v)) { final IPdfPrimitive? v = PdfCrossTable.dereference( - helper.dictionary![PdfDictionaryProperties.v]); + helper.dictionary![PdfDictionaryProperties.v], + ); if (v != null && v is PdfDictionary && v.containsKey(PdfDictionaryProperties.contents)) { - final IPdfPrimitive? contents = - PdfCrossTable.dereference(v[PdfDictionaryProperties.contents]); + final IPdfPrimitive? contents = PdfCrossTable.dereference( + v[PdfDictionaryProperties.contents], + ); if (contents != null && contents is PdfString) { final List? sigByte = contents.data; if (sigByte != null) { final X509CertificateParser parser = X509CertificateParser(); - final List? certificateChain = - parser.getCertificateChain(PdfStreamReader(sigByte)); + final List? certificateChain = parser + .getCertificateChain(PdfStreamReader(sigByte)); if (certificateChain != null) { return certificateChain; } @@ -705,19 +761,22 @@ class PdfSignatureHelper { input.add(base64.decode('VABlAHMAdAAgAGQAYQB0AGEA')); //Test unicode data input.close(); final List hash = output.events.single.bytes as List; - final List asnEncodedTimestampRequest = - TimeStampRequestCreator().getAsnEncodedTimestampRequest(hash); + final List asnEncodedTimestampRequest = TimeStampRequestCreator() + .getAsnEncodedTimestampRequest(hash); final List? timeStampResponse = await fetchData( - base.timestampServer!.uri, 'POST', - contentType: 'application/timestamp-query', - userName: base.timestampServer!.userName, - password: base.timestampServer!.password, - data: asnEncodedTimestampRequest, - timeOutDuration: base.timestampServer!.timeOut); + base.timestampServer!.uri, + 'POST', + contentType: 'application/timestamp-query', + userName: base.timestampServer!.userName, + password: base.timestampServer!.password, + data: asnEncodedTimestampRequest, + timeOutDuration: base.timestampServer!.timeOut, + ); if (timeStampResponse != null) { List? encoded; - final Asn1Stream stream = - Asn1Stream(PdfStreamReader(timeStampResponse)); + final Asn1Stream stream = Asn1Stream( + PdfStreamReader(timeStampResponse), + ); final Asn1? asn1 = stream.readAsn1(); if (asn1 != null && asn1 is Asn1Sequence && @@ -732,8 +791,8 @@ class PdfSignatureHelper { } if (encoded != null) { final X509CertificateParser parser = X509CertificateParser(); - final List? certificateChain = - parser.getCertificateChain(PdfStreamReader(encoded)); + final List? certificateChain = parser + .getCertificateChain(PdfStreamReader(encoded)); if (certificateChain != null) { return certificateChain; } @@ -759,5 +818,5 @@ enum RevocationType { ocspAndCrl, /// Embeds OCSP or CRL data to the PDF document. - ocspOrCrl + ocspOrCrl, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature_dictionary.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature_dictionary.dart index 7ea4374fb..ac3d63ed3 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature_dictionary.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pdf_signature_dictionary.dart @@ -120,36 +120,47 @@ class PdfSignatureDictionary implements IPdfWrapper { if (_sig != null) { if (_sig!.reason != null) { dictionary!.setProperty( - PdfDictionaryProperties.reason, PdfString(_sig!.reason!)); + PdfDictionaryProperties.reason, + PdfString(_sig!.reason!), + ); } if (_sig!.locationInfo != null) { dictionary!.setProperty( - PdfDictionaryProperties.location, PdfString(_sig!.locationInfo!)); + PdfDictionaryProperties.location, + PdfString(_sig!.locationInfo!), + ); } if (_sig!.contactInfo != null) { dictionary!.setProperty( - PdfDictionaryProperties.contactInfo, PdfString(_sig!.contactInfo!)); + PdfDictionaryProperties.contactInfo, + PdfString(_sig!.contactInfo!), + ); } if (_sig!.signedName != null) { dictionary!.setString(PdfDictionaryProperties.name, _sig!.signedName); final PdfDictionary tempDictionary = PdfDictionary(); final PdfDictionary appDictionary = PdfDictionary(); tempDictionary.setName( - PdfName(PdfDictionaryProperties.name), _sig!.signedName); + PdfName(PdfDictionaryProperties.name), + _sig!.signedName, + ); appDictionary.setProperty('App', PdfReferenceHolder(tempDictionary)); dictionary!.setProperty( - PdfName('Prop_Build'), PdfReferenceHolder(appDictionary)); + PdfName('Prop_Build'), + PdfReferenceHolder(appDictionary), + ); } } } bool _allowMDP() { final IPdfPrimitive? perms = PdfCrossTable.dereference( - PdfDocumentHelper.getHelper(_doc) - .catalog[PdfDictionaryProperties.perms]); + PdfDocumentHelper.getHelper(_doc).catalog[PdfDictionaryProperties.perms], + ); if (perms != null && perms is PdfDictionary) { - final IPdfPrimitive? docMDP = - PdfCrossTable.dereference(perms[PdfDictionaryProperties.docMDP]); + final IPdfPrimitive? docMDP = PdfCrossTable.dereference( + perms[PdfDictionaryProperties.docMDP], + ); final IPdfPrimitive dicSig = dictionary!; return dicSig == docMDP; } @@ -162,8 +173,10 @@ class PdfSignatureDictionary implements IPdfWrapper { final PdfArray array = PdfArray(); trans[PdfDictionaryProperties.v] = PdfName('1.2'); trans[PdfDictionaryProperties.p] = PdfNumber( - PdfSignatureHelper.getHelper(_sig!) - .getCertificateFlagResult(_sig!.documentPermissions)); + PdfSignatureHelper.getHelper( + _sig!, + ).getCertificateFlagResult(_sig!.documentPermissions), + ); trans[PdfDictionaryProperties.type] = PdfName(_transParam); reference[PdfDictionaryProperties.transformMethod] = PdfName(_docMdp); reference[PdfDictionaryProperties.type] = PdfName('SigRef'); @@ -174,8 +187,10 @@ class PdfSignatureDictionary implements IPdfWrapper { void _addType() { if (_sig != null && _sig!.timestampServer != null && _cert == null) { - dictionary! - .setName(PdfName(PdfDictionaryProperties.type), 'DocTimeStamp'); + dictionary!.setName( + PdfName(PdfDictionaryProperties.type), + 'DocTimeStamp', + ); } else { dictionary!.setName(PdfName(PdfDictionaryProperties.type), 'Sig'); } @@ -198,33 +213,42 @@ class PdfSignatureDictionary implements IPdfWrapper { offsetHours = '0$offsetHours'; } dictionary!.setProperty( - PdfDictionaryProperties.m, - PdfString( - "D:${dateFormat.format(dateTime)}+$offsetHours'$offsetMinutes'")); + PdfDictionaryProperties.m, + PdfString( + "D:${dateFormat.format(dateTime)}+$offsetHours'$offsetMinutes'", + ), + ); } void _addFilter() { - dictionary! - .setName(PdfName(PdfDictionaryProperties.filter), 'Adobe.PPKLite'); + dictionary!.setName( + PdfName(PdfDictionaryProperties.filter), + 'Adobe.PPKLite', + ); } void _addSubFilter() { if (_sig != null && _sig!.timestampServer != null && _cert == null) { - dictionary! - .setName(PdfName(PdfDictionaryProperties.subFilter), _rfcFilterType); + dictionary!.setName( + PdfName(PdfDictionaryProperties.subFilter), + _rfcFilterType, + ); } else { dictionary!.setName( - PdfName(PdfDictionaryProperties.subFilter), - _sig!.cryptographicStandard == CryptographicStandard.cades - ? _cadasFilterType - : _cmsFilterType); + PdfName(PdfDictionaryProperties.subFilter), + _sig!.cryptographicStandard == CryptographicStandard.cades + ? _cadasFilterType + : _cmsFilterType, + ); } } void _addContents(IPdfWriter writer) { - writer.write(PdfOperators.slash + - PdfDictionaryProperties.contents + - PdfOperators.whiteSpace); + writer.write( + PdfOperators.slash + + PdfDictionaryProperties.contents + + PdfOperators.whiteSpace, + ); _firstRangeLength = writer.position; int length = _estimatedSize * 2; if (_sig != null && _cert != null) { @@ -233,18 +257,23 @@ class PdfSignatureDictionary implements IPdfWrapper { length += 4192; } } - final List contents = - List.filled(length * 2 + 2, 0, growable: true); + final List contents = List.filled( + length * 2 + 2, + 0, + growable: true, + ); writer.write(contents); _secondRangeIndex = writer.position; writer.write(PdfOperators.newLine); } void _addRange(IPdfWriter writer) { - writer.write(PdfOperators.slash + - PdfDictionaryProperties.byteRange + - PdfOperators.whiteSpace + - PdfArray.startMark); + writer.write( + PdfOperators.slash + + PdfDictionaryProperties.byteRange + + PdfOperators.whiteSpace + + PdfArray.startMark, + ); _startPositionByteRange = writer.position; for (int i = 0; i < 32; i++) { writer.write(PdfOperators.whiteSpace); @@ -263,8 +292,10 @@ class PdfSignatureDictionary implements IPdfWrapper { PdfDictionary trans = PdfDictionary(); trans[PdfDictionaryProperties.v] = PdfName('1.2'); trans[PdfDictionaryProperties.p] = PdfNumber( - PdfSignatureHelper.getHelper(_sig!) - .getCertificateFlagResult(_sig!.documentPermissions)); + PdfSignatureHelper.getHelper( + _sig!, + ).getCertificateFlagResult(_sig!.documentPermissions), + ); trans[PdfDictionaryProperties.type] = PdfName(_transParam); writer.write(trans); writer.write(PdfName(PdfDictionaryProperties.transformMethod)); @@ -274,8 +305,9 @@ class PdfSignatureDictionary implements IPdfWrapper { writer.write(PdfName('DigestValue')); int position = writer.position!; // _docDigestPosition = position; - writer - .write(PdfString.fromBytes(List.filled(16, 0, growable: true))); + writer.write( + PdfString.fromBytes(List.filled(16, 0, growable: true)), + ); PdfArray digestLocation = PdfArray(); digestLocation.add(PdfNumber(position)); digestLocation.add(PdfNumber(34)); @@ -305,8 +337,9 @@ class PdfSignatureDictionary implements IPdfWrapper { writer.write(PdfName('DigestValue')); position = writer.position!; // _fieldsDigestPosition = position; - writer - .write(PdfString.fromBytes(List.filled(16, 0, growable: true))); + writer.write( + PdfString.fromBytes(List.filled(16, 0, growable: true)), + ); digestLocation = PdfArray(); digestLocation.add(PdfNumber(position)); digestLocation.add(PdfNumber(34)); @@ -341,16 +374,26 @@ class PdfSignatureDictionary implements IPdfWrapper { _stream = writer.buffer; final String text = PdfString.bytesToHex(getPkcs7Content()!); _stream!.replaceRange( - _firstRangeLength!, _firstRangeLength! + 1, utf8.encode('<')); + _firstRangeLength!, + _firstRangeLength! + 1, + utf8.encode('<'), + ); final int newPos = _firstRangeLength! + 1 + text.length; _stream!.replaceRange(_firstRangeLength! + 1, newPos, utf8.encode(text)); final int num3 = (_secondRangeIndex! - newPos) ~/ 2; - final String emptyText = - PdfString.bytesToHex(List.generate(num3, (int i) => 0)); + final String emptyText = PdfString.bytesToHex( + List.generate(num3, (int i) => 0), + ); + _stream!.replaceRange( + newPos, + newPos + emptyText.length, + utf8.encode(emptyText), + ); _stream!.replaceRange( - newPos, newPos + emptyText.length, utf8.encode(emptyText)); - _stream!.replaceRange(newPos + emptyText.length, - newPos + emptyText.length + 1, utf8.encode('>')); + newPos + emptyText.length, + newPos + emptyText.length + 1, + utf8.encode('>'), + ); PdfSecurityHelper.getHelper(_doc.security).encryptor.encrypt = enabled; } @@ -364,19 +407,25 @@ class PdfSignatureDictionary implements IPdfWrapper { final String str2 = '$_firstRangeLength '; final String str3 = '$_secondRangeIndex '; final String str4 = number.toString(); - await _saveRangeItemAsync(writer, str, _startPositionByteRange!) - .then((int startPosition) async { - await _saveRangeItemAsync(writer, str2, startPosition) - .then((int startPosition) async { - await _saveRangeItemAsync(writer, str3, startPosition) - .then((int startPosition) async { - await _saveRangeItemAsync(e.writer! as PdfWriter, str4, startPosition) - .then((int startPosition) async { + await _saveRangeItemAsync(writer, str, _startPositionByteRange!).then(( + int startPosition, + ) async { + await _saveRangeItemAsync(writer, str2, startPosition).then(( + int startPosition, + ) async { + await _saveRangeItemAsync(writer, str3, startPosition).then(( + int startPosition, + ) async { + await _saveRangeItemAsync( + e.writer! as PdfWriter, + str4, + startPosition, + ).then((int startPosition) async { _range = [ 0, int.parse(str2), int.parse(str3), - int.parse(str4) + int.parse(str4), ]; _stream = writer.buffer; if (_cert != null || @@ -384,21 +433,34 @@ class PdfSignatureDictionary implements IPdfWrapper { PdfSignatureHelper.getHelper(_sig!).externalSigner != null)) { await getPkcs7ContentAsync().then((List? value) async { - await PdfString.bytesToHexAsync(value!) - .then((String text) async { - _stream!.replaceRange(_firstRangeLength!, - _firstRangeLength! + 1, utf8.encode('<')); + await PdfString.bytesToHexAsync(value!).then(( + String text, + ) async { + _stream!.replaceRange( + _firstRangeLength!, + _firstRangeLength! + 1, + utf8.encode('<'), + ); final int newPos = _firstRangeLength! + 1 + text.length; _stream!.replaceRange( - _firstRangeLength! + 1, newPos, utf8.encode(text)); + _firstRangeLength! + 1, + newPos, + utf8.encode(text), + ); final int num3 = (_secondRangeIndex! - newPos) ~/ 2; await PdfString.bytesToHexAsync( - List.generate(num3, (int i) => 0)) - .then((String emptyText) async { - _stream!.replaceRange(newPos, newPos + emptyText.length, - utf8.encode(emptyText)); - _stream!.replaceRange(newPos + emptyText.length, - newPos + emptyText.length + 1, utf8.encode('>')); + List.generate(num3, (int i) => 0), + ).then((String emptyText) async { + _stream!.replaceRange( + newPos, + newPos + emptyText.length, + utf8.encode(emptyText), + ); + _stream!.replaceRange( + newPos + emptyText.length, + newPos + emptyText.length + 1, + utf8.encode('>'), + ); PdfSecurityHelper.getHelper(_doc.security) .encryptor .encrypt = enabled; @@ -407,21 +469,34 @@ class PdfSignatureDictionary implements IPdfWrapper { }); } else if (_sig != null && _sig!.timestampServer != null) { await _getPKCS7TimeStampContent().then((List? value) async { - await PdfString.bytesToHexAsync(value!) - .then((String text) async { - _stream!.replaceRange(_firstRangeLength!, - _firstRangeLength! + 1, utf8.encode('<')); + await PdfString.bytesToHexAsync(value!).then(( + String text, + ) async { + _stream!.replaceRange( + _firstRangeLength!, + _firstRangeLength! + 1, + utf8.encode('<'), + ); final int newPos = _firstRangeLength! + 1 + text.length; _stream!.replaceRange( - _firstRangeLength! + 1, newPos, utf8.encode(text)); + _firstRangeLength! + 1, + newPos, + utf8.encode(text), + ); final int num3 = (_secondRangeIndex! - newPos) ~/ 2; await PdfString.bytesToHexAsync( - List.generate(num3, (int i) => 0)) - .then((String emptyText) async { - _stream!.replaceRange(newPos, newPos + emptyText.length, - utf8.encode(emptyText)); - _stream!.replaceRange(newPos + emptyText.length, - newPos + emptyText.length + 1, utf8.encode('>')); + List.generate(num3, (int i) => 0), + ).then((String emptyText) async { + _stream!.replaceRange( + newPos, + newPos + emptyText.length, + utf8.encode(emptyText), + ); + _stream!.replaceRange( + newPos + emptyText.length, + newPos + emptyText.length + 1, + utf8.encode('>'), + ); PdfSecurityHelper.getHelper(_doc.security) .encryptor .encrypt = enabled; @@ -453,45 +528,54 @@ class PdfSignatureDictionary implements IPdfWrapper { externalSignature = pks; } else { String certificateAlias = ''; - final List keys = PdfCertificateHelper.getPkcsCertificate(_cert!) - .getContentTable() - .keys - .toList(); + final List keys = + PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getContentTable().keys.toList(); bool isContinue = true; // ignore: avoid_function_literals_in_foreach_calls keys.forEach((String key) { if (isContinue && PdfCertificateHelper.getPkcsCertificate(_cert!).isKey(key) && - PdfCertificateHelper.getPkcsCertificate(_cert!) - .getKey(key)! - .key! - .isPrivate!) { + PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getKey(key)!.key!.isPrivate!) { certificateAlias = key; isContinue = false; } }); - final KeyEntry pk = PdfCertificateHelper.getPkcsCertificate(_cert!) - .getKey(certificateAlias)!; + final KeyEntry pk = + PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getKey(certificateAlias)!; final List certificates = - PdfCertificateHelper.getPkcsCertificate(_cert!) - .getCertificateChain(certificateAlias)!; + PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getCertificateChain(certificateAlias)!; // ignore: avoid_function_literals_in_foreach_calls certificates.forEach((X509Certificates c) { chain!.add(c.certificate); }); final RsaPrivateKeyParam? parameters = pk.key as RsaPrivateKeyParam?; - final String digest = _sig != null - ? getDigestAlgorithm(_sig!.digestAlgorithm) - : MessageDigestAlgorithms.secureHash256; + final String digest = + _sig != null + ? getDigestAlgorithm(_sig!.digestAlgorithm) + : MessageDigestAlgorithms.secureHash256; final _SignaturePrivateKey pks = _SignaturePrivateKey(digest, parameters); hashAlgorithm = pks.getHashAlgorithm(); externalSignature = pks; } - final _PdfCmsSigner pkcs7 = - _PdfCmsSigner(null, chain, hashAlgorithm!, false); + final _PdfCmsSigner pkcs7 = _PdfCmsSigner( + null, + chain, + hashAlgorithm!, + false, + ); final IRandom source = getUnderlyingSource(); - final List sources = - List.generate(_range.length ~/ 2, (int i) => null); + final List sources = List.generate( + _range.length ~/ 2, + (int i) => null, + ); for (int j = 0; j < _range.length; j += 2) { sources[j ~/ 2] = _WindowRandom(source, _range[j], _range[j + 1]); } @@ -499,7 +583,11 @@ class PdfSignatureDictionary implements IPdfWrapper { final List hash = pkcs7._digestAlgorithm.digest(data, hashAlgorithm)!; final List? sh = pkcs7 .getSequenceDataSet( - hash, ocspByte, crlBytes, _sig!.cryptographicStandard) + hash, + ocspByte, + crlBytes, + _sig!.cryptographicStandard, + ) .getEncoded(Asn1.der); List? extSignature; if (externalSigner != null) { @@ -509,7 +597,10 @@ class PdfSignatureDictionary implements IPdfWrapper { } if (extSignature != null) { pkcs7.setSignedData( - extSignature, null, externalSignature.getEncryptionAlgorithm()); + extSignature, + null, + externalSignature.getEncryptionAlgorithm(), + ); } else { return List.filled(_estimatedSize, 0, growable: true); } @@ -517,9 +608,19 @@ class PdfSignatureDictionary implements IPdfWrapper { extSignature = externalSignature.sign(sh!); } pkcs7.setSignedData( - extSignature!, null, externalSignature.getEncryptionAlgorithm()); - return pkcs7.sign(hash, _sig!.timestampServer, null, ocspByte, crlBytes, - _sig!.cryptographicStandard, hashAlgorithm); + extSignature!, + null, + externalSignature.getEncryptionAlgorithm(), + ); + return pkcs7.sign( + hash, + _sig!.timestampServer, + null, + ocspByte, + crlBytes, + _sig!.cryptographicStandard, + hashAlgorithm, + ); } /// internal method @@ -541,109 +642,143 @@ class PdfSignatureDictionary implements IPdfWrapper { externalSignature = pks; } else { String certificateAlias = ''; - await PdfCertificateHelper.getPkcsCertificate(_cert!) - .getContentTableAsync() - .then((Map contentTable) async { + await PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getContentTableAsync().then((Map contentTable) async { final List keys = contentTable.keys.toList(); bool isContinue = true; // ignore: avoid_function_literals_in_foreach_calls keys.forEach((String key) { if (isContinue && PdfCertificateHelper.getPkcsCertificate(_cert!).isKey(key) && - PdfCertificateHelper.getPkcsCertificate(_cert!) - .getKey(key)! - .key! - .isPrivate!) { + PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getKey(key)!.key!.isPrivate!) { certificateAlias = key; isContinue = false; } }); - final KeyEntry pk = PdfCertificateHelper.getPkcsCertificate(_cert!) - .getKey(certificateAlias)!; - await PdfCertificateHelper.getPkcsCertificate(_cert!) - .getCertificateChainAsync(certificateAlias) - .then((List? certificates) { + final KeyEntry pk = + PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getKey(certificateAlias)!; + await PdfCertificateHelper.getPkcsCertificate( + _cert!, + ).getCertificateChainAsync(certificateAlias).then(( + List? certificates, + ) { // ignore: avoid_function_literals_in_foreach_calls certificates!.forEach((X509Certificates c) { chain!.add(c.certificate); }); final RsaPrivateKeyParam? parameters = pk.key as RsaPrivateKeyParam?; - final String digest = _sig != null - ? getDigestAlgorithm(_sig!.digestAlgorithm) - : MessageDigestAlgorithms.secureHash256; - final _SignaturePrivateKey pks = - _SignaturePrivateKey(digest, parameters); + final String digest = + _sig != null + ? getDigestAlgorithm(_sig!.digestAlgorithm) + : MessageDigestAlgorithms.secureHash256; + final _SignaturePrivateKey pks = _SignaturePrivateKey( + digest, + parameters, + ); hashAlgorithm = pks.getHashAlgorithm(); externalSignature = pks; }); }); } - final _PdfCmsSigner pkcs7 = - _PdfCmsSigner(null, chain, hashAlgorithm!, false); + final _PdfCmsSigner pkcs7 = _PdfCmsSigner( + null, + chain, + hashAlgorithm!, + false, + ); final IRandom source = getUnderlyingSource(); - final List sources = - List.generate(_range.length ~/ 2, (int i) => null); + final List sources = List.generate( + _range.length ~/ 2, + (int i) => null, + ); for (int j = 0; j < _range.length; j += 2) { sources[j ~/ 2] = _WindowRandom(source, _range[j], _range[j + 1]); } final PdfStreamReader data = _RandomStream(_RandomGroup(sources)); - await pkcs7._digestAlgorithm - .digestAsync(data, hashAlgorithm) - .then((List? hash) async { + await pkcs7._digestAlgorithm.digestAsync(data, hashAlgorithm).then(( + List? hash, + ) async { await pkcs7 .getSequenceDataSetAsync( - hash!, ocspByte, crlBytes, _sig!.cryptographicStandard) + hash!, + ocspByte, + crlBytes, + _sig!.cryptographicStandard, + ) .then((DerSet derSet) async { - await derSet.getEncodedAsync(Asn1.der).then((List? sh) async { - List? extSignature; - if (externalSigner != null) { - await externalSigner - .sign(sh!) - .then((SignerResult? signerResult) async { - signerResult ??= externalSigner.signSync(sh); - if (signerResult != null && signerResult.signedData.isNotEmpty) { - extSignature = signerResult.signedData; - } - if (extSignature != null) { - await pkcs7.setSignedDataAsync(extSignature!, null, - externalSignature!.getEncryptionAlgorithm()); + await derSet.getEncodedAsync(Asn1.der).then((List? sh) async { + List? extSignature; + if (externalSigner != null) { + await externalSigner.sign(sh!).then(( + SignerResult? signerResult, + ) async { + signerResult ??= externalSigner.signSync(sh); + if (signerResult != null && + signerResult.signedData.isNotEmpty) { + extSignature = signerResult.signedData; + } + if (extSignature != null) { + await pkcs7.setSignedDataAsync( + extSignature!, + null, + externalSignature!.getEncryptionAlgorithm(), + ); + } else { + pkcs7Content = List.filled( + _estimatedSize, + 0, + growable: true, + ); + } + }); } else { - pkcs7Content = - List.filled(_estimatedSize, 0, growable: true); + await externalSignature! + .signAsync(sh!) + .then((List? value) => extSignature = value); + } + if (pkcs7Content == null) { + await pkcs7.setSignedDataAsync( + extSignature!, + null, + externalSignature!.getEncryptionAlgorithm(), + ); + pkcs7Content = await pkcs7.signAsync( + hash, + _sig!.timestampServer, + null, + ocspByte, + crlBytes, + _sig!.cryptographicStandard, + hashAlgorithm, + ); } }); - } else { - await externalSignature! - .signAsync(sh!) - .then((List? value) => extSignature = value); - } - if (pkcs7Content == null) { - await pkcs7.setSignedDataAsync(extSignature!, null, - externalSignature!.getEncryptionAlgorithm()); - pkcs7Content = await pkcs7.signAsync( - hash, - _sig!.timestampServer, - null, - ocspByte, - crlBytes, - _sig!.cryptographicStandard, - hashAlgorithm); - } - }); - }); + }); }); return pkcs7Content; } Future?> _getPKCS7TimeStampContent() async { - final _SignaturePrivateKey externalSignature = - _SignaturePrivateKey(MessageDigestAlgorithms.secureHash256); + final _SignaturePrivateKey externalSignature = _SignaturePrivateKey( + MessageDigestAlgorithms.secureHash256, + ); final String? hashAlgorithm = externalSignature.getHashAlgorithm(); - final _PdfCmsSigner pkcs7 = - _PdfCmsSigner(null, null, hashAlgorithm!, false); + final _PdfCmsSigner pkcs7 = _PdfCmsSigner( + null, + null, + hashAlgorithm!, + false, + ); final IRandom source = getUnderlyingSource(); - final List sources = - List.filled(_range.length ~/ 2, null); + final List sources = List.filled( + _range.length ~/ 2, + null, + ); for (int j = 0; j < _range.length; j += 2) { sources[j ~/ 2] = _WindowRandom(source, _range[j], _range[j + 1]); } @@ -652,7 +787,10 @@ class PdfSignatureDictionary implements IPdfWrapper { final List? hash = alg.digest(data, hashAlgorithm); if (hash != null) { pkcs7.setSignedData( - hash, null, externalSignature.getEncryptionAlgorithm()); + hash, + null, + externalSignature.getEncryptionAlgorithm(), + ); return pkcs7.getEncodedTimestamp(hash, _sig!.timestampServer!); } return null; @@ -686,16 +824,25 @@ class PdfSignatureDictionary implements IPdfWrapper { int _saveRangeItem(PdfWriter writer, String str, int startPosition) { final List date = utf8.encode(str); - writer.buffer! - .replaceRange(startPosition, startPosition + date.length, date); + writer.buffer!.replaceRange( + startPosition, + startPosition + date.length, + date, + ); return startPosition + str.length; } Future _saveRangeItemAsync( - PdfWriter writer, String str, int startPosition) async { + PdfWriter writer, + String str, + int startPosition, + ) async { final List date = utf8.encode(str); - writer.buffer! - .replaceRange(startPosition, startPosition + date.length, date); + writer.buffer!.replaceRange( + startPosition, + startPosition + date.length, + date, + ); return startPosition + str.length; } @@ -832,7 +979,10 @@ class MessageDigestAlgorithms { result = md5; } else { throw ArgumentError.value( - hashAlgorithm, 'hashAlgorithm', 'Invalid message digest algorithm'); + hashAlgorithm, + 'hashAlgorithm', + 'Invalid message digest algorithm', + ); } return result; } @@ -862,7 +1012,10 @@ class MessageDigestAlgorithms { result = md5; } else { throw ArgumentError.value( - hashAlgorithm, 'hashAlgorithm', 'Invalid message digest algorithm'); + hashAlgorithm, + 'hashAlgorithm', + 'Invalid message digest algorithm', + ); } return result; } @@ -888,11 +1041,14 @@ class MessageDigestAlgorithms { /// internal method Future?> digestAsync( - PdfStreamReader data, dynamic hashAlgorithm) async { + PdfStreamReader data, + dynamic hashAlgorithm, + ) async { dynamic algorithm; - algorithm = hashAlgorithm is String - ? await getMessageDigestAsync(hashAlgorithm) - : hashAlgorithm; + algorithm = + hashAlgorithm is String + ? await getMessageDigestAsync(hashAlgorithm) + : hashAlgorithm; final dynamic output = AccumulatorSink(); final dynamic input = algorithm.startChunkedConversion(output); int? count; @@ -1064,13 +1220,20 @@ class SignerUtilities { } class _PdfCmsSigner { - _PdfCmsSigner(ICipherParameter? privateKey, List? certChain, - String hashAlgorithm, bool hasRSAdata) { + _PdfCmsSigner( + ICipherParameter? privateKey, + List? certChain, + String hashAlgorithm, + bool hasRSAdata, + ) { _digestAlgorithm = MessageDigestAlgorithms(); _digestAlgorithmOid = _digestAlgorithm.getAllowedDigests(hashAlgorithm); if (_digestAlgorithmOid == null) { throw ArgumentError.value( - hashAlgorithm, 'hashAlgorithm', 'Unknown Hash Algorithm'); + hashAlgorithm, + 'hashAlgorithm', + 'Unknown Hash Algorithm', + ); } _version = 1; _signerVersion = 1; @@ -1078,7 +1241,9 @@ class _PdfCmsSigner { _digestOid[_digestAlgorithmOid] = null; if (certChain != null) { _certificates = List.generate( - certChain.length, (int i) => certChain[i]); + certChain.length, + (int i) => certChain[i], + ); _signCert = _certificates[0]; } if (privateKey != null) { @@ -1086,7 +1251,10 @@ class _PdfCmsSigner { _encryptionAlgorithmOid = _DigitalIdentifiers.rsa; } else { throw ArgumentError.value( - privateKey, 'privateKey', 'Unknown key algorithm'); + privateKey, + 'privateKey', + 'Unknown key algorithm', + ); } } if (hasRSAdata) { @@ -1116,13 +1284,18 @@ class _PdfCmsSigner { } //Implementation - DerSet getSequenceDataSet(List secondDigest, List? ocsp, - List>? crlBytes, CryptographicStandard? sigtype) { + DerSet getSequenceDataSet( + List secondDigest, + List? ocsp, + List>? crlBytes, + CryptographicStandard? sigtype, + ) { final Asn1EncodeCollection attribute = Asn1EncodeCollection(); Asn1EncodeCollection v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_DigitalIdentifiers.contentType)); - v.encodableObjects.add(DerSet( - array: [DerObjectID(_DigitalIdentifiers.pkcs7Data)])); + v.encodableObjects.add( + DerSet(array: [DerObjectID(_DigitalIdentifiers.pkcs7Data)]), + ); attribute.encodableObjects.add(DerSequence(collection: v)); v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_DigitalIdentifiers.messageDigest)); @@ -1130,24 +1303,33 @@ class _PdfCmsSigner { attribute.encodableObjects.add(DerSequence(collection: v)); if (sigtype == CryptographicStandard.cades) { v = Asn1EncodeCollection(); - v.encodableObjects - .add(DerObjectID(_DigitalIdentifiers.aaSigningCertificateV2)); + v.encodableObjects.add( + DerObjectID(_DigitalIdentifiers.aaSigningCertificateV2), + ); final Asn1EncodeCollection aaV2 = Asn1EncodeCollection(); final MessageDigestAlgorithms alg = MessageDigestAlgorithms(); - final String? sha256Oid = - alg.getAllowedDigests(MessageDigestAlgorithms.secureHash256); + final String? sha256Oid = alg.getAllowedDigests( + MessageDigestAlgorithms.secureHash256, + ); if (sha256Oid != _digestAlgorithmOid) { aaV2.encodableObjects.add(Algorithms(DerObjectID(_digestAlgorithmOid))); } - final List dig = alg - .getMessageDigest(hashAlgorithm!) - .convert(_signCert!.c!.getEncoded(Asn1.der)) - .bytes as List; + final List dig = + alg + .getMessageDigest(hashAlgorithm!) + .convert(_signCert!.c!.getEncoded(Asn1.der)) + .bytes + as List; aaV2.encodableObjects.add(DerOctet(dig)); - v.encodableObjects.add(DerSet(array: [ - DerSequence.fromObject( - DerSequence.fromObject(DerSequence(collection: aaV2))) - ])); + v.encodableObjects.add( + DerSet( + array: [ + DerSequence.fromObject( + DerSequence.fromObject(DerSequence(collection: aaV2)), + ), + ], + ), + ); attribute.encodableObjects.add(DerSequence(collection: v)); } return DerSet(collection: attribute); @@ -1155,15 +1337,17 @@ class _PdfCmsSigner { //Implementation Future getSequenceDataSetAsync( - List secondDigest, - List? ocsp, - List>? crlBytes, - CryptographicStandard? sigtype) async { + List secondDigest, + List? ocsp, + List>? crlBytes, + CryptographicStandard? sigtype, + ) async { final Asn1EncodeCollection attribute = Asn1EncodeCollection(); Asn1EncodeCollection v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_DigitalIdentifiers.contentType)); - v.encodableObjects.add(DerSet( - array: [DerObjectID(_DigitalIdentifiers.pkcs7Data)])); + v.encodableObjects.add( + DerSet(array: [DerObjectID(_DigitalIdentifiers.pkcs7Data)]), + ); attribute.encodableObjects.add(DerSequence(collection: v)); v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_DigitalIdentifiers.messageDigest)); @@ -1171,34 +1355,49 @@ class _PdfCmsSigner { attribute.encodableObjects.add(DerSequence(collection: v)); if (sigtype == CryptographicStandard.cades) { v = Asn1EncodeCollection(); - v.encodableObjects - .add(DerObjectID(_DigitalIdentifiers.aaSigningCertificateV2)); + v.encodableObjects.add( + DerObjectID(_DigitalIdentifiers.aaSigningCertificateV2), + ); final Asn1EncodeCollection aaV2 = Asn1EncodeCollection(); final MessageDigestAlgorithms alg = MessageDigestAlgorithms(); await alg .getAllowedDigestsAsync(MessageDigestAlgorithms.secureHash256) .then((String? sha256Oid) async { - if (sha256Oid != _digestAlgorithmOid) { - aaV2.encodableObjects - .add(Algorithms(DerObjectID(_digestAlgorithmOid))); - } - await alg.getMessageDigestAsync(hashAlgorithm!).then((dynamic value) { - aaV2.encodableObjects.add(DerOctet(value - .convert(_signCert!.c!.getEncoded(Asn1.der)) - .bytes as List)); - v.encodableObjects.add(DerSet(array: [ - DerSequence.fromObject( - DerSequence.fromObject(DerSequence(collection: aaV2))) - ])); - attribute.encodableObjects.add(DerSequence(collection: v)); - }); - }); + if (sha256Oid != _digestAlgorithmOid) { + aaV2.encodableObjects.add( + Algorithms(DerObjectID(_digestAlgorithmOid)), + ); + } + await alg.getMessageDigestAsync(hashAlgorithm!).then(( + dynamic value, + ) { + aaV2.encodableObjects.add( + DerOctet( + value.convert(_signCert!.c!.getEncoded(Asn1.der)).bytes + as List, + ), + ); + v.encodableObjects.add( + DerSet( + array: [ + DerSequence.fromObject( + DerSequence.fromObject(DerSequence(collection: aaV2)), + ), + ], + ), + ); + attribute.encodableObjects.add(DerSequence(collection: v)); + }); + }); } return DerSet(collection: attribute); } void setSignedData( - List digest, List? rsaData, String? digestEncryptionAlgorithm) { + List digest, + List? rsaData, + String? digestEncryptionAlgorithm, + ) { _signedData = digest; _signedRsaData = rsaData; if (digestEncryptionAlgorithm != null) { @@ -1210,13 +1409,19 @@ class _PdfCmsSigner { _encryptionAlgorithmOid = _DigitalIdentifiers.ecdsa; } else { throw ArgumentError.value( - digestEncryptionAlgorithm, 'algorithm', 'Invalid entry'); + digestEncryptionAlgorithm, + 'algorithm', + 'Invalid entry', + ); } } } - Future setSignedDataAsync(List digest, List? rsaData, - String? digestEncryptionAlgorithm) async { + Future setSignedDataAsync( + List digest, + List? rsaData, + String? digestEncryptionAlgorithm, + ) async { _signedData = digest; _signedRsaData = rsaData; if (digestEncryptionAlgorithm != null) { @@ -1228,19 +1433,23 @@ class _PdfCmsSigner { _encryptionAlgorithmOid = _DigitalIdentifiers.ecdsa; } else { throw ArgumentError.value( - digestEncryptionAlgorithm, 'algorithm', 'Invalid entry'); + digestEncryptionAlgorithm, + 'algorithm', + 'Invalid entry', + ); } } } List? sign( - List secondDigest, - TimestampServer? server, - List? timeStampResponse, - List? ocsp, - List>? crls, - CryptographicStandard? sigtype, - String? hashAlgorithm) { + List secondDigest, + TimestampServer? server, + List? timeStampResponse, + List? ocsp, + List>? crls, + CryptographicStandard? sigtype, + String? hashAlgorithm, + ) { if (_signedData != null) { _digest = _signedData; if (_rsaData != null) { @@ -1267,25 +1476,29 @@ class _PdfCmsSigner { // ignore: avoid_function_literals_in_foreach_calls _certificates.forEach((X509Certificate? xcert) { v.encodableObjects.add( - Asn1Stream(PdfStreamReader(xcert!.c!.getEncoded(Asn1.der))) - .readAsn1()); + Asn1Stream(PdfStreamReader(xcert!.c!.getEncoded(Asn1.der))).readAsn1(), + ); }); final DerSet dercertificates = DerSet(collection: v); final Asn1EncodeCollection signerinfo = Asn1EncodeCollection(); - signerinfo.encodableObjects - .add(DerInteger(bigIntToBytes(BigInt.from(_signerVersion)))); + signerinfo.encodableObjects.add( + DerInteger(bigIntToBytes(BigInt.from(_signerVersion))), + ); v = Asn1EncodeCollection(); - v.encodableObjects - .add(getIssuer(_signCert!.c!.tbsCertificate!.getEncoded(Asn1.der))); - v.encodableObjects - .add(DerInteger(bigIntToBytes(_signCert!.c!.serialNumber!.value))); + v.encodableObjects.add( + getIssuer(_signCert!.c!.tbsCertificate!.getEncoded(Asn1.der)), + ); + v.encodableObjects.add( + DerInteger(bigIntToBytes(_signCert!.c!.serialNumber!.value)), + ); signerinfo.encodableObjects.add(DerSequence(collection: v)); v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_digestAlgorithmOid)); v.encodableObjects.add(DerNull.value); signerinfo.encodableObjects.add(DerSequence(collection: v)); - signerinfo.encodableObjects.add(DerTag( - 0, getSequenceDataSet(secondDigest, ocsp, crls, sigtype), false)); + signerinfo.encodableObjects.add( + DerTag(0, getSequenceDataSet(secondDigest, ocsp, crls, sigtype), false), + ); v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_encryptionAlgorithmOid)); v.encodableObjects.add(DerNull.value); @@ -1296,11 +1509,13 @@ class _PdfCmsSigner { body.encodableObjects.add(DerSet(collection: digestAlgorithms)); body.encodableObjects.add(contentinfo); body.encodableObjects.add(DerTag(0, dercertificates, false)); - body.encodableObjects - .add(DerSet(array: [DerSequence(collection: signerinfo)])); + body.encodableObjects.add( + DerSet(array: [DerSequence(collection: signerinfo)]), + ); final Asn1EncodeCollection whole = Asn1EncodeCollection(); - whole.encodableObjects - .add(DerObjectID(_DigitalIdentifiers.pkcs7SignedData)); + whole.encodableObjects.add( + DerObjectID(_DigitalIdentifiers.pkcs7SignedData), + ); whole.encodableObjects.add(DerTag(0, DerSequence(collection: body))); final Asn1DerStream dout = Asn1DerStream([]); dout.writeObject(DerSequence(collection: whole)); @@ -1315,7 +1530,7 @@ class _PdfCmsSigner { final Asn1? seq = tempstream.readAsn1(); if (seq != null && seq is Asn1Sequence) { asn1Encode.add([ - DerSet(array: [seq]) + DerSet(array: [seq]), ]); attributes.add([DerSequence(collection: asn1Encode)]); } @@ -1323,13 +1538,14 @@ class _PdfCmsSigner { } Future?> signAsync( - List secondDigest, - TimestampServer? server, - List? timeStampResponse, - List? ocsp, - List>? crls, - CryptographicStandard? sigtype, - String? hashAlgorithm) async { + List secondDigest, + TimestampServer? server, + List? timeStampResponse, + List? ocsp, + List>? crls, + CryptographicStandard? sigtype, + String? hashAlgorithm, + ) async { if (_signedData != null) { _digest = _signedData; if (_rsaData != null) { @@ -1356,25 +1572,29 @@ class _PdfCmsSigner { // ignore: avoid_function_literals_in_foreach_calls _certificates.forEach((X509Certificate? xcert) { v.encodableObjects.add( - Asn1Stream(PdfStreamReader(xcert!.c!.getEncoded(Asn1.der))) - .readAsn1()); + Asn1Stream(PdfStreamReader(xcert!.c!.getEncoded(Asn1.der))).readAsn1(), + ); }); final DerSet dercertificates = DerSet(collection: v); final Asn1EncodeCollection signerinfo = Asn1EncodeCollection(); - signerinfo.encodableObjects - .add(DerInteger(bigIntToBytes(BigInt.from(_signerVersion)))); + signerinfo.encodableObjects.add( + DerInteger(bigIntToBytes(BigInt.from(_signerVersion))), + ); v = Asn1EncodeCollection(); - v.encodableObjects - .add(getIssuer(_signCert!.c!.tbsCertificate!.getEncoded(Asn1.der))); - v.encodableObjects - .add(DerInteger(bigIntToBytes(_signCert!.c!.serialNumber!.value))); + v.encodableObjects.add( + getIssuer(_signCert!.c!.tbsCertificate!.getEncoded(Asn1.der)), + ); + v.encodableObjects.add( + DerInteger(bigIntToBytes(_signCert!.c!.serialNumber!.value)), + ); signerinfo.encodableObjects.add(DerSequence(collection: v)); v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_digestAlgorithmOid)); v.encodableObjects.add(DerNull.value); signerinfo.encodableObjects.add(DerSequence(collection: v)); - signerinfo.encodableObjects.add(DerTag( - 0, getSequenceDataSet(secondDigest, ocsp, crls, sigtype), false)); + signerinfo.encodableObjects.add( + DerTag(0, getSequenceDataSet(secondDigest, ocsp, crls, sigtype), false), + ); v = Asn1EncodeCollection(); v.encodableObjects.add(DerObjectID(_encryptionAlgorithmOid)); v.encodableObjects.add(DerNull.value); @@ -1386,17 +1606,21 @@ class _PdfCmsSigner { input.add(_digest); input.close(); final List hash = output.events.single.bytes as List; - final List asnEncodedTimestampRequest = - TimeStampRequestCreator().getAsnEncodedTimestampRequest(hash); - timeStampResponse = await fetchData(server.uri, 'POST', - contentType: 'application/timestamp-query', - userName: server.userName, - password: server.password, - data: asnEncodedTimestampRequest, - timeOutDuration: server.timeOut); + final List asnEncodedTimestampRequest = TimeStampRequestCreator() + .getAsnEncodedTimestampRequest(hash); + timeStampResponse = await fetchData( + server.uri, + 'POST', + contentType: 'application/timestamp-query', + userName: server.userName, + password: server.password, + data: asnEncodedTimestampRequest, + timeOutDuration: server.timeOut, + ); if (timeStampResponse != null) { - final Asn1Stream stream = - Asn1Stream(PdfStreamReader(timeStampResponse)); + final Asn1Stream stream = Asn1Stream( + PdfStreamReader(timeStampResponse), + ); final Asn1? asn1 = stream.readAsn1(); if (asn1 != null && asn1 is Asn1Sequence && @@ -1412,11 +1636,13 @@ class _PdfCmsSigner { } } if (timeStampResponse != null) { - final Asn1EncodeCollection? timeAsn1Encoded = - getAttributes(timeStampResponse); + final Asn1EncodeCollection? timeAsn1Encoded = getAttributes( + timeStampResponse, + ); if (timeAsn1Encoded != null) { - signerinfo.add( - [DerTag(1, DerSet(collection: timeAsn1Encoded), false)]); + signerinfo.add([ + DerTag(1, DerSet(collection: timeAsn1Encoded), false), + ]); } } final Asn1EncodeCollection body = Asn1EncodeCollection(); @@ -1424,11 +1650,13 @@ class _PdfCmsSigner { body.encodableObjects.add(DerSet(collection: digestAlgorithms)); body.encodableObjects.add(contentinfo); body.encodableObjects.add(DerTag(0, dercertificates, false)); - body.encodableObjects - .add(DerSet(array: [DerSequence(collection: signerinfo)])); + body.encodableObjects.add( + DerSet(array: [DerSequence(collection: signerinfo)]), + ); final Asn1EncodeCollection whole = Asn1EncodeCollection(); - whole.encodableObjects - .add(DerObjectID(_DigitalIdentifiers.pkcs7SignedData)); + whole.encodableObjects.add( + DerObjectID(_DigitalIdentifiers.pkcs7SignedData), + ); whole.encodableObjects.add(DerTag(0, DerSequence(collection: body))); final Asn1DerStream dout = Asn1DerStream([]); dout.writeObject(DerSequence(collection: whole)); @@ -1443,16 +1671,21 @@ class _PdfCmsSigner { /// Internal method Future?> getEncodedTimestamp( - List secondDigest, TimestampServer server) async { + List secondDigest, + TimestampServer server, + ) async { List? encoded; - final List asnEncodedTimestampRequest = - TimeStampRequestCreator().getAsnEncodedTimestampRequest(secondDigest); - final List? respBytes = await fetchData(server.uri, 'POST', - contentType: 'application/timestamp-query', - userName: server.userName, - password: server.password, - data: asnEncodedTimestampRequest, - timeOutDuration: server.timeOut); + final List asnEncodedTimestampRequest = TimeStampRequestCreator() + .getAsnEncodedTimestampRequest(secondDigest); + final List? respBytes = await fetchData( + server.uri, + 'POST', + contentType: 'application/timestamp-query', + userName: server.userName, + password: server.password, + data: asnEncodedTimestampRequest, + timeOutDuration: server.timeOut, + ); if (respBytes != null) { final Asn1Stream stream = Asn1Stream(PdfStreamReader(respBytes)); final Asn1? asn1 = stream.readAsn1(); @@ -1635,7 +1868,7 @@ class _SourceEntry { class _RandomStream extends PdfStreamReader { _RandomStream(IRandom source) - : super(List.generate(source.length!, (int i) => 0)) { + : super(List.generate(source.length!, (int i) => 0)) { _random = source; } //Fields @@ -1818,20 +2051,22 @@ class NistObjectIds { // ignore: public_member_api_docs static DerObjectID ripeMD160 = DerObjectID('${tttAlgorithm.id!}.2.1'); // ignore: public_member_api_docs - static DerObjectID tttRsaSignatureAlgorithm = - DerObjectID('${tttAlgorithm.id!}.3.1'); + static DerObjectID tttRsaSignatureAlgorithm = DerObjectID( + '${tttAlgorithm.id!}.3.1', + ); // ignore: public_member_api_docs - static DerObjectID rsaSignatureWithRipeMD160 = - DerObjectID('${tttRsaSignatureAlgorithm.id!}.2'); + static DerObjectID rsaSignatureWithRipeMD160 = DerObjectID( + '${tttRsaSignatureAlgorithm.id!}.2', + ); } /// internal type definition -typedef DocumentSavedHandler = void Function( - Object sender, DocumentSavedArgs args); +typedef DocumentSavedHandler = + void Function(Object sender, DocumentSavedArgs args); /// internal type definition -typedef DocumentSavedHandlerAsync = Future Function( - Object sender, DocumentSavedArgs args); +typedef DocumentSavedHandlerAsync = + Future Function(Object sender, DocumentSavedArgs args); /// internal class class DocumentSavedArgs { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pkcs/pfx_data.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pkcs/pfx_data.dart index 6fa4044af..bbd6aea3d 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pkcs/pfx_data.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/pkcs/pfx_data.dart @@ -61,8 +61,9 @@ class Algorithms extends Asn1Encode { @override Asn1 getAsn1() { - final Asn1EncodeCollection collection = - Asn1EncodeCollection([id]); + final Asn1EncodeCollection collection = Asn1EncodeCollection([ + id, + ]); if (_parametersDefined) { collection.encodableObjects.add(parameters ?? DerNull.value); } @@ -201,12 +202,14 @@ class PkcsObjectId { static DerObjectID pbeWithShaAnd40BitRC4 = DerObjectID('$pkcs12PbeIds.2'); /// internal field - static DerObjectID pbeWithShaAnd3KeyTripleDesCbc = - DerObjectID('$pkcs12PbeIds.3'); + static DerObjectID pbeWithShaAnd3KeyTripleDesCbc = DerObjectID( + '$pkcs12PbeIds.3', + ); /// internal field - static DerObjectID pbeWithShaAnd2KeyTripleDesCbc = - DerObjectID('$pkcs12PbeIds.4'); + static DerObjectID pbeWithShaAnd2KeyTripleDesCbc = DerObjectID( + '$pkcs12PbeIds.4', + ); /// internal field static DerObjectID pbeWithShaAnd128BitRC2Cbc = DerObjectID('$pkcs12PbeIds.5'); @@ -215,8 +218,9 @@ class PkcsObjectId { static DerObjectID pbewithShaAnd40BitRC2Cbc = DerObjectID('$pkcs12PbeIds.6'); /// internal field - static DerObjectID idAlgCms3DesWrap = - DerObjectID('1.2.840.113549.1.9.16.3.6'); + static DerObjectID idAlgCms3DesWrap = DerObjectID( + '1.2.840.113549.1.9.16.3.6', + ); /// internal field static DerObjectID idAlgCmsRC2Wrap = DerObjectID('1.2.840.113549.1.9.16.3.7'); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/time_stamp_server/time_stamp_server.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/time_stamp_server/time_stamp_server.dart index 534f9d9ae..23ec8b107 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/time_stamp_server/time_stamp_server.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/time_stamp_server/time_stamp_server.dart @@ -92,14 +92,17 @@ class TimestampServer { input.add(base64.decode('VABlAHMAdAAgAGQAYQB0AGEA')); //Test unicode data input.close(); final List hash = output.events.single.bytes as List; - final List asnEncodedTimestampRequest = - TimeStampRequestCreator().getAsnEncodedTimestampRequest(hash); - final List? timeStampResponse = await fetchData(uri, 'POST', - contentType: 'application/timestamp-query', - userName: userName, - password: password, - data: asnEncodedTimestampRequest, - timeOutDuration: timeOut); + final List asnEncodedTimestampRequest = TimeStampRequestCreator() + .getAsnEncodedTimestampRequest(hash); + final List? timeStampResponse = await fetchData( + uri, + 'POST', + contentType: 'application/timestamp-query', + userName: userName, + password: password, + data: asnEncodedTimestampRequest, + timeOutDuration: timeOut, + ); if (timeStampResponse != null && timeStampResponse.length > 2) { if (timeStampResponse[0] == 0x30 && timeStampResponse[1] == 0x82) { isValid = true; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/ocsp_utils.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/ocsp_utils.dart index b065511ab..282df90cc 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/ocsp_utils.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/ocsp_utils.dart @@ -19,10 +19,14 @@ import 'x509_name.dart'; /// internal class class Ocsp { /// internal method - Future?> getEncodedOcspResponse(X509Certificate? checkCertificate, - X509Certificate? rootCertificate) async { - final OcspResponseHelper? helper = - await getOcspResponse(checkCertificate, rootCertificate); + Future?> getEncodedOcspResponse( + X509Certificate? checkCertificate, + X509Certificate? rootCertificate, + ) async { + final OcspResponseHelper? helper = await getOcspResponse( + checkCertificate, + rootCertificate, + ); if (helper != null) { return helper.getResponseBytes(); } @@ -30,8 +34,10 @@ class Ocsp { } /// internal method - Future getOcspResponse(X509Certificate? checkCertificate, - X509Certificate? rootCertificate) async { + Future getOcspResponse( + X509Certificate? checkCertificate, + X509Certificate? rootCertificate, + ) async { if (checkCertificate == null || rootCertificate == null) { return null; } @@ -40,14 +46,19 @@ class Ocsp { if (url == null) { return null; } - final OcspRequestHelper request = - generateOcspRequest(rootCertificate, checkCertificate.c!.serialNumber!); + final OcspRequestHelper request = generateOcspRequest( + rootCertificate, + checkCertificate.c!.serialNumber!, + ); final List? requestBody = request.getEncoded(); if (requestBody != null) { - final List? data = await fetchData(url, 'POST', - data: requestBody, - contentType: 'application/ocsp-request', - timeOutDuration: const Duration(milliseconds: 5000)); + final List? data = await fetchData( + url, + 'POST', + data: requestBody, + contentType: 'application/ocsp-request', + timeOutDuration: const Duration(milliseconds: 5000), + ); if (data != null) { return OcspResponseHelper(data); } @@ -57,15 +68,22 @@ class Ocsp { /// internal method OcspRequestHelper generateOcspRequest( - X509Certificate issuerCertificate, DerInteger serialNumber) { + X509Certificate issuerCertificate, + DerInteger serialNumber, + ) { final CertificateIdentity id = CertificateIdentity( - CertificateIdentity.sha1, issuerCertificate, serialNumber); + CertificateIdentity.sha1, + issuerCertificate, + serialNumber, + ); final OcspRequestCreator requestCreator = OcspRequestCreator(); requestCreator.addRequest(id); final Map extensions = {}; extensions[OcspConstants.ocspNonce] = X509Extension( - false, DerOctet(DerOctet(createDocumentId()).getEncoded()!)); + false, + DerOctet(DerOctet(createDocumentId()).getEncoded()!), + ); requestCreator.requestExtensions = X509Extensions(extensions); return requestCreator.createRequest(); } @@ -101,8 +119,11 @@ class RevocationList { List? data; for (final String entry in urls) { try { - data = await fetchData(entry, 'GET', - timeOutDuration: const Duration(milliseconds: 5000)); + data = await fetchData( + entry, + 'GET', + timeOutDuration: const Duration(milliseconds: 5000), + ); } catch (e) { // } @@ -235,7 +256,9 @@ class RevocationDistributionType extends Asn1Encode { /// Internal method RevocationDistributionType? getDistributionType( - Asn1Tag tag, bool isExplicit) { + Asn1Tag tag, + bool isExplicit, + ) { return getDistributionTypeFromObj(Asn1Tag.getTag(tag, true)); } @@ -326,10 +349,14 @@ class OcspTag extends Asn1Encode { return OcspTag(tagNumber, Asn1Sequence.getSequence(tag, false)); case 1: return OcspTag( - tagNumber, DerAsciiString.getAsciiString(tag, false)); + tagNumber, + DerAsciiString.getAsciiString(tag, false), + ); case 2: return OcspTag( - tagNumber, DerAsciiString.getAsciiString(tag, false)); + tagNumber, + DerAsciiString.getAsciiString(tag, false), + ); case 3: throw Exception('Invalid tag number specified: $tagNumber'); case 4: @@ -338,7 +365,9 @@ class OcspTag extends Asn1Encode { return OcspTag(tagNumber, Asn1Sequence.getSequence(tag, false)); case 6: return OcspTag( - tagNumber, DerAsciiString.getAsciiString(tag, false)); + tagNumber, + DerAsciiString.getAsciiString(tag, false), + ); case 7: return OcspTag(tagNumber, Asn1Octet.getOctetString(tag, false)); case 8: @@ -369,7 +398,9 @@ class CertificateUtililty { final List urls = []; try { final Asn1? obj = getExtensionValue( - certificate, X509Extensions.crlDistributionPoints.id!); + certificate, + X509Extensions.crlDistributionPoints.id!, + ); if (obj == null) { return null; } @@ -397,7 +428,9 @@ class CertificateUtililty { } final DerAsciiString? asciiString = DerAsciiString.getAsciiString( - name.getAsn1() as Asn1Tag, false); + name.getAsn1() as Asn1Tag, + false, + ); if (asciiString != null) { final String? url = asciiString.getString(); if (url != null && url.toLowerCase().endsWith('.crl') || @@ -420,7 +453,9 @@ class CertificateUtililty { String? getOcspUrl(X509Certificate certificate) { try { final Asn1? asn1 = getExtensionValue( - certificate, X509Extensions.authorityInfoAccess.id!); + certificate, + X509Extensions.authorityInfoAccess.id!, + ); if (asn1 == null) { return null; } @@ -518,7 +553,10 @@ class OcspRequestCreator { } } final OcspRequestCollection requestList = OcspRequestCollection( - _requestorName, DerSequence(collection: requests), requestExtensions!); + _requestorName, + DerSequence(collection: requests), + requestExtensions!, + ); return OcspRequestHelper(RevocationListRequest(requestList)); } } @@ -546,7 +584,10 @@ class OcspRequestHelper extends X509ExtensionBase { class OcspRequestCollection extends Asn1Encode { /// Internal constructor OcspRequestCollection( - this._requestorName, this._requestList, this._requestExtensions) { + this._requestorName, + this._requestList, + this._requestExtensions, + ) { _version = DerInteger([0]); versionSet = false; } @@ -587,7 +628,8 @@ class RevocationListRequest extends Asn1Encode { @override Asn1 getAsn1() { return DerSequence( - collection: Asn1EncodeCollection([_requests])); + collection: Asn1EncodeCollection([_requests]), + ); } } @@ -596,7 +638,8 @@ class OcspResponseHelper { /// Internal constructor OcspResponseHelper(List data) { _response = OcspResponse( - Asn1Stream(PdfStreamReader(data)).readAsn1()! as Asn1Sequence); + Asn1Stream(PdfStreamReader(data)).readAsn1()! as Asn1Sequence, + ); } /// Internal field @@ -624,8 +667,10 @@ class OcspResponse extends Asn1Encode { /// Internal constructor OcspResponse(Asn1Sequence sequence) { if (sequence.count == 2) { - responseBytes = RevocationResponseBytes() - .getResponseBytes(sequence[1]! as Asn1Tag, true); + responseBytes = RevocationResponseBytes().getResponseBytes( + sequence[1]! as Asn1Tag, + true, + ); } } @@ -635,7 +680,7 @@ class OcspResponse extends Asn1Encode { @override Asn1 getAsn1() { final Asn1EncodeCollection collection = Asn1EncodeCollection([ - DerCatalogue([0]) + DerCatalogue([0]), ]); if (responseBytes != null) { collection.add([DerTag(0, responseBytes, true)]); @@ -666,7 +711,8 @@ class RevocationResponseBytes extends Asn1Encode { /// Internal method RevocationResponseBytes? getResponseBytes(Asn1Tag tag, bool isExplicit) { return getResponseBytesFromObject( - Asn1Sequence.getSequence(tag, isExplicit)); + Asn1Sequence.getSequence(tag, isExplicit), + ); } /// Internal method @@ -712,8 +758,9 @@ class RevocationRequest extends Asn1Encode { @override Asn1 getAsn1() { - final Asn1EncodeCollection collection = - Asn1EncodeCollection([_certificateID]); + final Asn1EncodeCollection collection = Asn1EncodeCollection([ + _certificateID, + ]); if (_singleRequestExtensions != null) { collection.add([DerTag(0, _singleRequestExtensions, true)]); } @@ -729,8 +776,10 @@ class TimeStampRequestCreator extends Asn1 { /// Internal method List getAsnEncodedTimestampRequest(List hash) { final Asn1Identifier digestAlgOid = Asn1Identifier(_idSHA256); - final Algorithms algID = - Algorithms.fromAsn1Sequence(digestAlgOid, DerNull.value); + final Algorithms algID = Algorithms.fromAsn1Sequence( + digestAlgOid, + DerNull.value, + ); final Asn1Sequence seq = Asn1Sequence(); seq.objects!.add(algID); seq.objects!.add(Asn1Octet(hash)); @@ -777,12 +826,15 @@ class OcspConstants { } /// Send the data to the server and get the response. -Future?> fetchData(dynamic uri, String method, - {String? contentType, - String? userName, - String? password, - List? data, - Duration? timeOutDuration}) async { +Future?> fetchData( + dynamic uri, + String method, { + String? contentType, + String? userName, + String? password, + List? data, + Duration? timeOutDuration, +}) async { final http.Client client = http.Client(); try { if (uri is String) { @@ -795,15 +847,16 @@ Future?> fetchData(dynamic uri, String method, if (password != null && userName != null) { request.headers.addAll({ 'Authorization': - 'Basic ${base64Encode(utf8.encode('$userName:$password'))}' + 'Basic ${base64Encode(utf8.encode('$userName:$password'))}', }); } if (data != null) { request.bodyBytes = data; } - final http.StreamedResponse response = await ((timeOutDuration != null) - ? client.send(request).timeout(timeOutDuration) - : client.send(request)); + final http.StreamedResponse response = + await ((timeOutDuration != null) + ? client.send(request).timeout(timeOutDuration) + : client.send(request)); final List responseBytes = await response.stream.toBytes(); return (response.statusCode == 200) ? responseBytes : null; } catch (e) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_certificates.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_certificates.dart index 16f1c491c..c1b4b647a 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_certificates.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_certificates.dart @@ -92,8 +92,10 @@ class X509Extension { /// internal class class X509Extensions extends Asn1Encode { /// internal constructor - X509Extensions(Map extensions, - [List? ordering]) { + X509Extensions( + Map extensions, [ + List? ordering, + ]) { _extensions = {}; if (ordering == null) { final List der = []; @@ -120,13 +122,17 @@ class X509Extensions extends Asn1Encode { final Asn1Sequence s = Asn1Sequence.getSequence(ae.getAsn1())!; if (s.count < 2 || s.count > 3) { throw ArgumentError.value( - seq, 'count', 'Bad sequence size: ${s.count}'); + seq, + 'count', + 'Bad sequence size: ${s.count}', + ); } final DerObjectID? oid = DerObjectID.getID(s[0]!.getAsn1()); final bool isCritical = s.count == 3 && (s[1]!.getAsn1()! as DerBoolean).isTrue; - final Asn1Octet? octets = - Asn1Octet.getOctetStringFromObject(s[s.count - 1]!.getAsn1()); + final Asn1Octet? octets = Asn1Octet.getOctetStringFromObject( + s[s.count - 1]!.getAsn1(), + ); _extensions[oid] = X509Extension(isCritical, octets); _ordering.add(oid); } @@ -194,12 +200,16 @@ class X509Certificate extends X509ExtensionBase { try { final Asn1Octet? str = getExtension(DerObjectID('2.5.29.15')); if (str != null) { - final DerBitString bits = DerBitString.getDetBitString( - Asn1Stream(PdfStreamReader(str.getOctets())).readAsn1())!; + final DerBitString bits = + DerBitString.getDetBitString( + Asn1Stream(PdfStreamReader(str.getOctets())).readAsn1(), + )!; final List bytes = bits.getBytes()!; final int length = (bytes.length * 8) - bits.extra!; - _keyUsage = - List.generate((length < 9) ? 9 : length, (int i) => false); + _keyUsage = List.generate( + (length < 9) ? 9 : length, + (int i) => false, + ); for (int i = 0; i != length; i++) { _keyUsage![i] = (bytes[i ~/ 8] & (0x80 >> (i % 8))) != 0; } @@ -208,7 +218,10 @@ class X509Certificate extends X509ExtensionBase { } } catch (e) { throw ArgumentError.value( - e, 'ArgumentError', 'cannot construct KeyUsage'); + e, + 'ArgumentError', + 'cannot construct KeyUsage', + ); } } //Fields @@ -248,7 +261,10 @@ class X509Certificate extends X509ExtensionBase { result = RsaKeyParam(false, pubKey.modulus, pubKey.publicExponent); } else { throw ArgumentError.value( - keyInfo, 'keyInfo', 'algorithm identifier in key not recognised'); + keyInfo, + 'keyInfo', + 'algorithm identifier in key not recognised', + ); } return result; } @@ -373,11 +389,14 @@ class SingnedCertificate extends Asn1Encode { _startDate = X509Time.getTime(dates[0]); _endDate = X509Time.getTime(dates[1]); _subject = X509Name.getName(sequence[seqStart + 5]); - _publicKeyInformation = - PublicKeyInformation.getPublicKeyInformation(sequence[seqStart + 6]); - for (int extras = sequence.count - (seqStart + 6) - 1; - extras > 0; - extras--) { + _publicKeyInformation = PublicKeyInformation.getPublicKeyInformation( + sequence[seqStart + 6], + ); + for ( + int extras = sequence.count - (seqStart + 6) - 1; + extras > 0; + extras-- + ) { final Asn1Tag extra = sequence[seqStart + 6 + extras]! as Asn1Tag; switch (extra.tagNumber) { case 1: @@ -469,7 +488,10 @@ class PublicKeyInformation extends Asn1Encode { PublicKeyInformation.fromSequence(Asn1Sequence sequence) { if (sequence.count != 2) { throw ArgumentError.value( - sequence, 'sequence', 'Invalid length in sequence'); + sequence, + 'sequence', + 'Invalid length in sequence', + ); } _algorithms = Algorithms.getAlgorithms(sequence[0]); _publicKey = DerBitString.getDetBitString(sequence[1]); @@ -543,10 +565,12 @@ class RsaPublicKey extends Asn1Encode { @override Asn1 getAsn1() { - return DerSequence(array: [ - DerInteger.fromNumber(modulus), - DerInteger.fromNumber(publicExponent) - ]); + return DerSequence( + array: [ + DerInteger.fromNumber(modulus), + DerInteger.fromNumber(publicExponent), + ], + ); } } @@ -615,7 +639,8 @@ class X509CertificateParser { _sDataObjectCount = _sDataObjectCount! + 1; if (obj is Asn1Sequence) { return createX509Certificate( - X509CertificateStructure.getInstance(obj)); + X509CertificateStructure.getInstance(obj), + ); } } } @@ -657,7 +682,8 @@ class X509CertificateParser { _sDataObjectCount = _sDataObjectCount! + 1; if (obj is Asn1Sequence) { certList.add( - createX509Certificate(X509CertificateStructure.getInstance(obj))); + createX509Certificate(X509CertificateStructure.getInstance(obj)), + ); } } } @@ -689,7 +715,7 @@ class X509CertificateParser { } } return [ - createX509Certificate(X509CertificateStructure.getInstance(seq)) + createX509Certificate(X509CertificateStructure.getInstance(seq)), ]; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_name.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_name.dart index e4133cb44..e7428e74e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_name.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/digital_signature/x509/x509_name.dart @@ -16,7 +16,10 @@ class X509Name extends Asn1Encode { Asn1Sequence.getSequence(asn1Set[i]!.getAsn1())!; if (asn1Sequence.count != 2) { throw ArgumentError.value( - sequence, 'sequence', 'Invalid length in sequence'); + sequence, + 'sequence', + 'Invalid length in sequence', + ); } _ordering.add(DerObjectID.getID(asn1Sequence[0]!.getAsn1())); final Asn1? asn1 = asn1Sequence[1]!.getAsn1(); @@ -210,11 +213,19 @@ class X509Name extends Asn1Encode { if (_added[i] as bool) { result = '+'; result = appendValue( - result, symbols, _ordering[i] as DerObjectID?, _values[i]); + result, + symbols, + _ordering[i] as DerObjectID?, + _values[i], + ); } else { result = ''; result = appendValue( - result, symbols, _ordering[i] as DerObjectID?, _values[i]); + result, + symbols, + _ordering[i] as DerObjectID?, + _values[i], + ); components.add(result); } } @@ -233,8 +244,12 @@ class X509Name extends Asn1Encode { } /// internal method - String appendValue(String builder, Map symbols, - DerObjectID? id, String value) { + String appendValue( + String builder, + Map symbols, + DerObjectID? id, + String value, + ) { final String? symbol = symbols[id!]; if (symbol != null) { builder += symbol; @@ -257,7 +272,8 @@ class X509Name extends Asn1Encode { (builder[index] == '<') || (builder[index] == '>') || (builder[index] == ';')) { - builder = builder.substring(0, index) + + builder = + builder.substring(0, index) + r'\' + builder.substring(index, builder.length); index++; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/enum.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/enum.dart index ca0690326..4eb93ad7b 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/enum.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/enum.dart @@ -7,7 +7,7 @@ enum PdfEncryptionOptions { encryptAllContentsExceptMetadata, /// To encrypt atttachment files only. - encryptOnlyAttachments + encryptOnlyAttachments, } /// Specifies the type of encryption algorithm. @@ -25,7 +25,7 @@ enum PdfEncryptionAlgorithm { aesx256Bit, /// AES encryption algorithm - 256-bit key with revision 6. - aesx256BitRevision6 + aesx256BitRevision6, } /// Specifies the type of PDF permissions. @@ -55,7 +55,7 @@ enum PdfPermissionsFlags { assembleDocument, /// Full quality print. - fullQualityPrint + fullQualityPrint, } /// Specifies the available permissions on certificated document. @@ -67,7 +67,7 @@ enum PdfCertificationFlags { allowFormFill, /// Only allow commenting and form fill-in actions on this document. - allowComments + allowComments, } /// Specifies the cryptographic standard. @@ -76,7 +76,7 @@ enum CryptographicStandard { cms, /// CMS Advanced Electronic Signatures - cades + cades, } /// Specifies the digestion algorithm. @@ -91,5 +91,5 @@ enum DigestAlgorithm { sha384, /// SHA512 message digest algorithm - sha512 + sha512, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_encryptor.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_encryptor.dart index ce71c4536..93a2f0c96 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_encryptor.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_encryptor.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:math'; +import 'dart:typed_data'; import 'package:crypto/crypto.dart'; @@ -13,6 +14,10 @@ import '../primitives/pdf_name.dart'; import '../primitives/pdf_number.dart'; import '../primitives/pdf_string.dart'; import 'digital_signature/cryptography/aes_cipher.dart'; +import 'digital_signature/cryptography/aes_engine.dart'; +import 'digital_signature/cryptography/buffered_block_padding_base.dart'; +import 'digital_signature/cryptography/cipher_block_chaining_mode.dart'; +import 'digital_signature/cryptography/ipadding.dart'; import 'enum.dart'; /// internal class @@ -103,7 +108,9 @@ class PdfEncryptor { if (_randomBytes == null) { final Random random = Random.secure(); _randomBytes = List.generate( - _randomBytesAmount!, (int i) => random.nextInt(256)); + _randomBytesAmount!, + (int i) => random.nextInt(256), + ); } return _randomBytes; } @@ -116,7 +123,8 @@ class PdfEncryptor { set permissions(List value) { changed = true; _permissions = value; - _permissionValue = (_getPermissionValue(_permissions!) | _permissionSet!) & + _permissionValue = + (_getPermissionValue(_permissions!) | _permissionSet!) & _permissionCleared!; if (revisionNumber! > 2) { _permissionValue = _permissionValue! & _permissionRevisionTwoMask!; @@ -129,8 +137,8 @@ class PdfEncryptor { final List perm = permissions; final bool bEncrypt = (!(perm.length == 1 && perm.contains(PdfPermissionsFlags.none))) || - _userPassword!.isNotEmpty || - _ownerPassword!.isNotEmpty; + _userPassword!.isNotEmpty || + _ownerPassword!.isNotEmpty; return isEncrypt! && bEncrypt; } @@ -241,7 +249,7 @@ class PdfEncryptor { 0x000100, 0x000200, 0x000400, - 0x000800 + 0x000800, ]; permissions = [PdfPermissionsFlags.none]; encryptionOptions = PdfEncryptionOptions.encryptAllContents; @@ -277,7 +285,7 @@ class PdfEncryptor { 100, 83, 105, - 122 + 122, ]; customArray = List.filled(_bytesAmount!, 0, growable: true); changed = false; @@ -319,7 +327,10 @@ class PdfEncryptor { List _create40BitUserPassword() { ArgumentError.checkNotNull(_encryptionKey); return _encryptDataByCustom( - List.from(paddingBytes!), _encryptionKey, _encryptionKey!.length); + List.from(paddingBytes!), + _encryptionKey, + _encryptionKey!.length, + ); } List _create128BitUserPassword() { @@ -328,22 +339,32 @@ class PdfEncryptor { data.addAll(paddingBytes!); data.addAll(randomBytes!); final List resultBytes = md5.convert(data).bytes; - final List dataForCustom = - List.generate(_randomBytesAmount!, (int i) => resultBytes[i]); + final List dataForCustom = List.generate( + _randomBytesAmount!, + (int i) => resultBytes[i], + ); List dataFromCustom = _encryptDataByCustom( - dataForCustom, _encryptionKey, _encryptionKey!.length); + dataForCustom, + _encryptionKey, + _encryptionKey!.length, + ); for (int i = 1; i < _ownerLoopNum2!; i++) { final List currentKey = _getKeyWithOwnerPassword(_encryptionKey!, i); - dataFromCustom = - _encryptDataByCustom(dataFromCustom, currentKey, currentKey.length); + dataFromCustom = _encryptDataByCustom( + dataFromCustom, + currentKey, + currentKey.length, + ); } return _padTrancateString(dataFromCustom); } List _create256BitUserPassword() { final Random random = Random.secure(); - _userRandomBytes = - List.generate(_randomBytesAmount!, (int i) => random.nextInt(256)); + _userRandomBytes = List.generate( + _randomBytesAmount!, + (int i) => random.nextInt(256), + ); final List userPasswordBytes = utf8.encode(_userPassword!); final List hash = []; hash.addAll(userPasswordBytes); @@ -358,15 +379,22 @@ class PdfEncryptor { final String password = ownerPassword.isEmpty ? userPassword : ownerPassword; final List customKey = _getKeyFromOwnerPassword(password); - final List userPasswordBytes = - _padTrancateString(utf8.encode(userPassword)); - List dataFromCustom = - _encryptDataByCustom(userPasswordBytes, customKey, customKey.length); + final List userPasswordBytes = _padTrancateString( + utf8.encode(userPassword), + ); + List dataFromCustom = _encryptDataByCustom( + userPasswordBytes, + customKey, + customKey.length, + ); if (revisionNumber! > 2) { for (int i = 1; i < _ownerLoopNum2!; i++) { final List currentKey = _getKeyWithOwnerPassword(customKey, i); - dataFromCustom = - _encryptDataByCustom(dataFromCustom, currentKey, currentKey.length); + dataFromCustom = _encryptDataByCustom( + dataFromCustom, + currentKey, + currentKey.length, + ); } } return dataFromCustom; @@ -374,8 +402,10 @@ class PdfEncryptor { List _create256BitOwnerPassword() { final Random random = Random.secure(); - _ownerRandomBytes = - List.generate(_randomBytesAmount!, (int i) => random.nextInt(256)); + _ownerRandomBytes = List.generate( + _randomBytesAmount!, + (int i) => random.nextInt(256), + ); final String password = ownerPassword.isEmpty ? userPassword : ownerPassword; final List ownerPasswordBytes = utf8.encode(password); @@ -394,8 +424,10 @@ class PdfEncryptor { hash.addAll(utf8.encode(userPassword)); hash.addAll(List.generate(8, (int i) => _userRandomBytes![i + 8])); final List hashBytes = sha256.convert(hash).bytes; - return AesCipherNoPadding(true, hashBytes) - .processBlock(_fileEncryptionKey, 0, _fileEncryptionKey!.length); + return AesCipherNoPadding( + true, + KeyParameter(Uint8List.fromList(hashBytes)), + ).process(Uint8List.fromList(_fileEncryptionKey!)); } List? _createOwnerEncryptionKey() { @@ -406,8 +438,10 @@ class PdfEncryptor { hash.addAll(List.generate(8, (int i) => _ownerRandomBytes![i + 8])); hash.addAll(_userPasswordOut!); final List hashBytes = sha256.convert(hash).bytes; - return AesCipherNoPadding(true, hashBytes) - .processBlock(_fileEncryptionKey, 0, _fileEncryptionKey!.length); + return AesCipherNoPadding( + true, + KeyParameter(Uint8List.fromList(hashBytes)), + ).process(Uint8List.fromList(_fileEncryptionKey!)); } List? _createPermissionFlag() { @@ -428,19 +462,25 @@ class PdfEncryptor { 98, 98, 98, - 98 + 98, ]; - return AesCipherNoPadding(true, _fileEncryptionKey!) - .processBlock(permissionFlagBytes, 0, permissionFlagBytes.length); + return AesCipherNoPadding( + true, + KeyParameter(Uint8List.fromList(_fileEncryptionKey!)), + ).process(Uint8List.fromList(permissionFlagBytes)); } void _createAcrobatX256BitUserPassword() { final List userPasswordBytes = utf8.encode(_userPassword!); final Random random = Random.secure(); - final List userValidationSalt = - List.generate(8, (int i) => random.nextInt(256)); - final List userKeySalt = - List.generate(8, (int i) => random.nextInt(256)); + final List userValidationSalt = List.generate( + 8, + (int i) => random.nextInt(256), + ); + final List userKeySalt = List.generate( + 8, + (int i) => random.nextInt(256), + ); List hash = []; hash.addAll(userPasswordBytes); hash.addAll(userValidationSalt); @@ -453,8 +493,10 @@ class PdfEncryptor { hash.addAll(userPasswordBytes); hash.addAll(userKeySalt); hash = _acrobatXComputeHash(hash, userPasswordBytes, null); - _userEncryptionKeyOut = AesCipherNoPadding(true, hash) - .processBlock(_fileEncryptionKey, 0, _fileEncryptionKey!.length); + _userEncryptionKeyOut = AesCipherNoPadding( + true, + KeyParameter(Uint8List.fromList(hash)), + ).process(Uint8List.fromList(_fileEncryptionKey!)); } void _createAcrobatX256BitOwnerPassword() { @@ -462,17 +504,26 @@ class PdfEncryptor { ownerPassword.isEmpty ? userPassword : ownerPassword; final List ownerPasswordBytes = utf8.encode(password); final Random random = Random.secure(); - final List ownerValidationSalt = - List.generate(8, (int i) => random.nextInt(256)); - final List ownerKeySalt = - List.generate(8, (int i) => random.nextInt(256)); + final List ownerValidationSalt = List.generate( + 8, + (int i) => random.nextInt(256), + ); + final List ownerKeySalt = List.generate( + 8, + (int i) => random.nextInt(256), + ); final List owenrPasswordOut = []; owenrPasswordOut.addAll(ownerPasswordBytes); owenrPasswordOut.addAll(ownerValidationSalt); owenrPasswordOut.addAll(_userPasswordOut!); _ownerPasswordOut = []; - _ownerPasswordOut!.addAll(_acrobatXComputeHash( - owenrPasswordOut, ownerPasswordBytes, _userPasswordOut)); + _ownerPasswordOut!.addAll( + _acrobatXComputeHash( + owenrPasswordOut, + ownerPasswordBytes, + _userPasswordOut, + ), + ); _ownerPasswordOut!.addAll(ownerValidationSalt); _ownerPasswordOut!.addAll(ownerKeySalt); List hash = []; @@ -480,8 +531,10 @@ class PdfEncryptor { hash.addAll(ownerKeySalt); hash.addAll(_userPasswordOut!); hash = _acrobatXComputeHash(hash, ownerPasswordBytes, _userPasswordOut); - _ownerEncryptionKeyOut = AesCipherNoPadding(true, hash) - .processBlock(_fileEncryptionKey, 0, _fileEncryptionKey!.length); + _ownerEncryptionKeyOut = AesCipherNoPadding( + true, + KeyParameter(Uint8List.fromList(hash)), + ).process(Uint8List.fromList(_fileEncryptionKey!)); } void _createFileEncryptionKey() { @@ -490,7 +543,10 @@ class PdfEncryptor { } List _encryptDataByCustom( - List data, List? key, int keyLength) { + List data, + List? key, + int keyLength, + ) { final List buffer = List.filled(data.length, 0, growable: true); _recreateCustomArray(key, keyLength); keyLength = data.length; @@ -502,16 +558,20 @@ class PdfEncryptor { final int temp = customArray![tmp1]; customArray![tmp1] = customArray![tmp2]; customArray![tmp2] = temp; - final int byteXor = customArray![ - (customArray![tmp1] + customArray![tmp2]) % _bytesAmount!]; + final int byteXor = + customArray![(customArray![tmp1] + customArray![tmp2]) % + _bytesAmount!]; buffer[i] = (data[i] ^ byteXor).toUnsigned(8); } return buffer; } void _recreateCustomArray(List? key, int keyLength) { - final List tempArray = - List.filled(_bytesAmount!, 0, growable: true); + final List tempArray = List.filled( + _bytesAmount!, + 0, + growable: true, + ); for (int i = 0; i < _bytesAmount!; i++) { tempArray[i] = key![i % keyLength]; customArray![i] = i.toUnsigned(8); @@ -531,11 +591,14 @@ class PdfEncryptor { final int? length = _getKeyLength(); if (revisionNumber! > 2) { for (int i = 0; i < _ownerLoopNum!; i++) { - currentHash = md5 - .convert(currentHash.length == length - ? currentHash - : List.generate(length!, (int i) => currentHash[i])) - .bytes; + currentHash = + md5 + .convert( + currentHash.length == length + ? currentHash + : List.generate(length!, (int i) => currentHash[i]), + ) + .bytes; } } return currentHash.length == length @@ -560,15 +623,19 @@ class PdfEncryptor { passwordBytes.addAll(source); } if (source.length < _stringLength!) { - passwordBytes.addAll(paddingBytes! - .getRange(0, paddingBytes!.length - passwordBytes.length)); + passwordBytes.addAll( + paddingBytes!.getRange(0, paddingBytes!.length - passwordBytes.length), + ); } return List.generate(_stringLength!, (int i) => passwordBytes[i]); } List _getKeyWithOwnerPassword(List originalKey, int index) { - final List result = - List.filled(originalKey.length, 0, growable: true); + final List result = List.filled( + originalKey.length, + 0, + growable: true, + ); for (int i = 0; i < originalKey.length; i++) { result[i] = (originalKey[i] ^ index).toUnsigned(8); } @@ -576,9 +643,12 @@ class PdfEncryptor { } List _createEncryptionKey( - String inputPassword, List ownerPasswordBytes) { - final List passwordBytes = - _padTrancateString(utf8.encode(inputPassword)); + String inputPassword, + List ownerPasswordBytes, + ) { + final List passwordBytes = _padTrancateString( + utf8.encode(inputPassword), + ); final List encryptionKeyData = []; encryptionKeyData.addAll(passwordBytes); encryptionKeyData.addAll(ownerPasswordBytes); @@ -586,7 +656,7 @@ class PdfEncryptor { _permissionValue!.toUnsigned(8), (_permissionValue! >> 8).toUnsigned(8), (_permissionValue! >> 16).toUnsigned(8), - (_permissionValue! >> 24).toUnsigned(8) + (_permissionValue! >> 24).toUnsigned(8), ]); encryptionKeyData.addAll(randomBytes!); int? revisionNumber; @@ -605,11 +675,14 @@ class PdfEncryptor { final int? length = _getKeyLength(); if (this.revisionNumber! > 2) { for (int i = 0; i < _ownerLoopNum!; i++) { - currentHash = md5 - .convert(currentHash.length == length - ? currentHash - : List.generate(length!, (int i) => currentHash[i])) - .bytes; + currentHash = + md5 + .convert( + currentHash.length == length + ? currentHash + : List.generate(length!, (int i) => currentHash[i]), + ) + .bytes; } } return currentHash.length == length @@ -618,18 +691,24 @@ class PdfEncryptor { } List _acrobatXComputeHash( - List input, List password, List? key) { + List input, + List password, + List? key, + ) { List hash = sha256.convert(input).bytes; List? finalHashKey; - for (int i = 0; - i < 64 || (finalHashKey![finalHashKey.length - 1] & 0xFF) > i - 32; - i++) { + for ( + int i = 0; + i < 64 || (finalHashKey![finalHashKey.length - 1] & 0xFF) > i - 32; + i++ + ) { final List roundHash = List.filled( - (key != null && key.length >= 48) - ? 64 * (password.length + hash.length + 48) - : 64 * (password.length + hash.length), - 0, - growable: true); + (key != null && key.length >= 48) + ? 64 * (password.length + hash.length + 48) + : 64 * (password.length + hash.length), + 0, + growable: true, + ); int position = 0; for (int j = 0; j < 64; j++) { List.copyRange(roundHash, position, password, 0, password.length); @@ -642,14 +721,21 @@ class PdfEncryptor { } } final List hashFirst = List.generate(16, (int i) => hash[i]); - final List hashSecond = - List.generate(16, (int i) => hash[i + 16]); + final List hashSecond = List.generate( + 16, + (int i) => hash[i + 16], + ); final AesCipher encrypt = AesCipher(true, hashFirst, hashSecond); finalHashKey = encrypt.update(roundHash, 0, roundHash.length); - final List finalHashKeyFirst = - List.generate(16, (int i) => finalHashKey![i]); - final BigInt finalKeyBigInteger = - _readBigIntFromBytes(finalHashKeyFirst, 0, finalHashKeyFirst.length); + final List finalHashKeyFirst = List.generate( + 16, + (int i) => finalHashKey![i], + ); + final BigInt finalKeyBigInteger = _readBigIntFromBytes( + finalHashKeyFirst, + 0, + finalHashKeyFirst.length, + ); final BigInt divisior = BigInt.parse('3'); final BigInt algorithmNumber = finalKeyBigInteger % divisior; final int algorithmIndex = algorithmNumber.toInt(); @@ -684,14 +770,17 @@ class PdfEncryptor { void readFromDictionary(PdfDictionary dictionary) { IPdfPrimitive? obj; if (dictionary.containsKey(PdfDictionaryProperties.filter)) { - obj = - PdfCrossTable.dereference(dictionary[PdfDictionaryProperties.filter]); + obj = PdfCrossTable.dereference( + dictionary[PdfDictionaryProperties.filter], + ); } if (obj != null && obj is PdfName && obj.name != PdfDictionaryProperties.standard) { throw ArgumentError.value( - obj, 'Invalid Format: Unsupported security filter'); + obj, + 'Invalid Format: Unsupported security filter', + ); } _permissionValue = dictionary.getInt(PdfDictionaryProperties.p); _updatePermissions(_permissionValue! & ~_permissionSet!); @@ -703,7 +792,8 @@ class PdfEncryptor { int keySize = dictionary.getInt(PdfDictionaryProperties.v); if (keySize == 4 && keySize != _revisionNumberOut) { throw ArgumentError.value( - 'Invalid Format: V and R entries of the Encryption dictionary does not match.'); + 'Invalid Format: V and R entries of the Encryption dictionary does not match.', + ); } if (keySize == 5) { _userEncryptionKeyOut = @@ -715,9 +805,10 @@ class PdfEncryptor { } _userPasswordOut = dictionary.getString(PdfDictionaryProperties.u)!.data; _ownerPasswordOut = dictionary.getString(PdfDictionaryProperties.o)!.data; - keyLength = dictionary.containsKey(PdfDictionaryProperties.length) - ? dictionary.getInt(PdfDictionaryProperties.length) - : (keySize == 1 ? 40 : (keySize == 2 ? 128 : 256)); + keyLength = + dictionary.containsKey(PdfDictionaryProperties.length) + ? dictionary.getInt(PdfDictionaryProperties.length) + : (keySize == 1 ? 40 : (keySize == 2 ? 128 : 256)); if (keyLength == 128 && _revisionNumberOut! < 4) { keySize = 2; encryptionAlgorithm = PdfEncryptionAlgorithm.rc4x128Bit; @@ -739,9 +830,10 @@ class PdfEncryptor { (standardCryptFilter[PdfDictionaryProperties.cfm]! as PdfName).name; if (keyLength == 128) { keySize = 2; - encryptionAlgorithm = filterName != 'V2' - ? PdfEncryptionAlgorithm.aesx128Bit - : PdfEncryptionAlgorithm.rc4x128Bit; + encryptionAlgorithm = + filterName != 'V2' + ? PdfEncryptionAlgorithm.aesx128Bit + : PdfEncryptionAlgorithm.rc4x128Bit; } else { keySize = 3; encryptionAlgorithm = PdfEncryptionAlgorithm.aesx256Bit; @@ -767,7 +859,8 @@ class PdfEncryptor { keyLength! % 8 != 0 && (keySize == 1 || keySize == 2 || keySize == 3)) { throw ArgumentError.value( - 'Invalid format: Invalid/Unsupported security dictionary.'); + 'Invalid format: Invalid/Unsupported security dictionary.', + ); } hasComputedPasswordValues = true; } @@ -832,8 +925,11 @@ class PdfEncryptor { return _authenticate256BitUserPassword(password); } else { _encryptionKey = _createEncryptionKey(password, _ownerPasswordOut!); - return _compareByteArrays(_createUserPassword(), _userPasswordOut, - revisionNumber == 2 ? null : 0x10); + return _compareByteArrays( + _createUserPassword(), + _userPasswordOut, + revisionNumber == 2 ? null : 0x10, + ); } } @@ -845,13 +941,18 @@ class PdfEncryptor { _encryptionKey = _getKeyFromOwnerPassword(password); List? buff = _ownerPasswordOut; if (revisionNumber == 2) { - buff = - _encryptDataByCustom(buff!, _encryptionKey, _encryptionKey!.length); + buff = _encryptDataByCustom( + buff!, + _encryptionKey, + _encryptionKey!.length, + ); } else if (revisionNumber! > 2) { buff = _ownerPasswordOut; for (int i = 0; i < _ownerLoopNum2!; ++i) { final List currKey = _getKeyWithOwnerPassword( - _encryptionKey!, _ownerLoopNum2! - i - 1); + _encryptionKey!, + _ownerLoopNum2! - i - 1, + ); buff = _encryptDataByCustom(buff!, currKey, currKey.length); } } @@ -893,33 +994,63 @@ class PdfEncryptor { List.copyRange(hashProvided, 0, _userPasswordOut!, 0, 32); List.copyRange(userValidationSalt, 0, _userPasswordOut!, 32, 40); final List combinedUserpassword = List.filled( - userPassword.length + userValidationSalt.length, 0, - growable: true); + userPassword.length + userValidationSalt.length, + 0, + growable: true, + ); List.copyRange( - combinedUserpassword, 0, userPassword, 0, userPassword.length); - List.copyRange(combinedUserpassword, userPassword.length, - userValidationSalt, 0, userValidationSalt.length); + combinedUserpassword, + 0, + userPassword, + 0, + userPassword.length, + ); + List.copyRange( + combinedUserpassword, + userPassword.length, + userValidationSalt, + 0, + userValidationSalt.length, + ); hash = _acrobatXComputeHash(combinedUserpassword, userPassword, null); _advanceXUserFileEncryptionKey(password); return _compareByteArrays(hash, hashProvided); } else { List.copyRange( - hashProvided, 0, _userPasswordOut!, 0, hashProvided.length); + hashProvided, + 0, + _userPasswordOut!, + 0, + hashProvided.length, + ); List.copyRange(_userRandomBytes!, 0, _userPasswordOut!, 32, 48); - List.copyRange(userValidationSalt, 0, _userRandomBytes!, 0, - userValidationSalt.length); List.copyRange( - userKeySalt, - 0, - _userRandomBytes!, - userValidationSalt.length, - userKeySalt.length + userValidationSalt.length); + userValidationSalt, + 0, + _userRandomBytes!, + 0, + userValidationSalt.length, + ); + List.copyRange( + userKeySalt, + 0, + _userRandomBytes!, + userValidationSalt.length, + userKeySalt.length + userValidationSalt.length, + ); hash = List.filled( - userPassword.length + userValidationSalt.length, 0, - growable: true); + userPassword.length + userValidationSalt.length, + 0, + growable: true, + ); List.copyRange(hash, 0, userPassword, 0, userPassword.length); - List.copyRange(hash, userPassword.length, userValidationSalt, 0, - userValidationSalt.length); + List.copyRange( + hash, + userPassword.length, + userValidationSalt, + 0, + userValidationSalt.length, + ); final List hashFound = sha256.convert(hash).bytes; bool bEqual = false; if (hashFound.length == hashProvided.length) { @@ -939,8 +1070,11 @@ class PdfEncryptor { } bool _authenticate256BitOwnerPassword(String password) { - final List ownerValidationSalt = - List.filled(8, 0, growable: true); + final List ownerValidationSalt = List.filled( + 8, + 0, + growable: true, + ); final List ownerKeySalt = List.filled(8, 0, growable: true); final List hashProvided = List.filled(32, 0, growable: true); _ownerRandomBytes = List.filled(16, 0, growable: true); @@ -955,20 +1089,36 @@ class PdfEncryptor { userKeyLength = _userPasswordOut!.length; } final List mixedOwnerPassword = List.filled( - ownerPassword.length + ownerValidationSalt.length + userKeyLength, 0, - growable: true); + ownerPassword.length + ownerValidationSalt.length + userKeyLength, + 0, + growable: true, + ); List.copyRange( - mixedOwnerPassword, 0, ownerPassword, 0, ownerPassword.length); - List.copyRange(mixedOwnerPassword, ownerPassword.length, - ownerValidationSalt, 0, ownerValidationSalt.length); + mixedOwnerPassword, + 0, + ownerPassword, + 0, + ownerPassword.length, + ); List.copyRange( - mixedOwnerPassword, - ownerPassword.length + ownerValidationSalt.length, - _userPasswordOut!, - 0, - userKeyLength); + mixedOwnerPassword, + ownerPassword.length, + ownerValidationSalt, + 0, + ownerValidationSalt.length, + ); + List.copyRange( + mixedOwnerPassword, + ownerPassword.length + ownerValidationSalt.length, + _userPasswordOut!, + 0, + userKeyLength, + ); hash = _acrobatXComputeHash( - mixedOwnerPassword, ownerPassword, _userPasswordOut); + mixedOwnerPassword, + ownerPassword, + _userPasswordOut, + ); _acrobatXOwnerFileEncryptionKey(password); oEqual = _compareByteArrays(hash, hashProvided); if (oEqual == true) { @@ -989,23 +1139,49 @@ class PdfEncryptor { final List userPasswordOut = List.filled(48, 0, growable: true); List.copyRange(userPasswordOut, 0, _userPasswordOut!, 0, 48); List.copyRange( - hashProvided, 0, _ownerPasswordOut!, 0, hashProvided.length); + hashProvided, + 0, + _ownerPasswordOut!, + 0, + hashProvided.length, + ); List.copyRange(_ownerRandomBytes!, 0, _ownerPasswordOut!, 32, 48); - List.copyRange(ownerValidationSalt, 0, _ownerRandomBytes!, 0, - ownerValidationSalt.length); - List.copyRange(ownerKeySalt, 0, _ownerRandomBytes!, - ownerValidationSalt.length, ownerKeySalt.length); + List.copyRange( + ownerValidationSalt, + 0, + _ownerRandomBytes!, + 0, + ownerValidationSalt.length, + ); + List.copyRange( + ownerKeySalt, + 0, + _ownerRandomBytes!, + ownerValidationSalt.length, + ownerKeySalt.length, + ); hash = List.filled( - ownerPassword.length + - ownerValidationSalt.length + - userPasswordOut.length, - 0, - growable: true); + ownerPassword.length + + ownerValidationSalt.length + + userPasswordOut.length, + 0, + growable: true, + ); List.copyRange(hash, 0, ownerPassword, 0, ownerPassword.length); - List.copyRange(hash, ownerPassword.length, ownerValidationSalt, 0, - ownerValidationSalt.length); - List.copyRange(hash, ownerPassword.length + ownerValidationSalt.length, - userPasswordOut, 0, userPasswordOut.length); + List.copyRange( + hash, + ownerPassword.length, + ownerValidationSalt, + 0, + ownerValidationSalt.length, + ); + List.copyRange( + hash, + ownerPassword.length + ownerValidationSalt.length, + userPasswordOut, + 0, + userPasswordOut.length, + ); final List hashFound = sha256.convert(hash).bytes; bool bEqual = false; if (hashFound.length == hashProvided.length) { @@ -1037,8 +1213,11 @@ class PdfEncryptor { late List hashFound; List? forDecryption; if (_ownerRandomBytes != null) { - final List ownerValidationSalt = - List.filled(8, 0, growable: true); + final List ownerValidationSalt = List.filled( + 8, + 0, + growable: true, + ); final List ownerKeySalt = List.filled(8, 0, growable: true); final List ownerPassword = utf8.encode(password); final List userPasswordOut = List.filled(48, 0, growable: true); @@ -1046,35 +1225,59 @@ class PdfEncryptor { List.copyRange(ownerValidationSalt, 0, _ownerRandomBytes!, 0, 8); List.copyRange(ownerKeySalt, 0, _ownerRandomBytes!, 8, 16); hash = List.filled( - ownerPassword.length + - ownerValidationSalt.length + - userPasswordOut.length, - 0, - growable: true); + ownerPassword.length + + ownerValidationSalt.length + + userPasswordOut.length, + 0, + growable: true, + ); List.copyRange(hash, 0, ownerPassword, 0, ownerPassword.length); List.copyRange( - hash, ownerPassword.length, ownerKeySalt, 0, ownerKeySalt.length); - List.copyRange(hash, ownerPassword.length + ownerValidationSalt.length, - userPasswordOut, 0, userPasswordOut.length); + hash, + ownerPassword.length, + ownerKeySalt, + 0, + ownerKeySalt.length, + ); + List.copyRange( + hash, + ownerPassword.length + ownerValidationSalt.length, + userPasswordOut, + 0, + userPasswordOut.length, + ); hashFound = sha256.convert(hash).bytes; forDecryption = _ownerEncryptionKeyOut; } else if (_userRandomBytes != null) { - final List userValidationSalt = - List.filled(8, 0, growable: true); + final List userValidationSalt = List.filled( + 8, + 0, + growable: true, + ); final List userKeySalt = List.filled(8, 0, growable: true); final List userPassword = utf8.encode(password); List.copyRange(userValidationSalt, 0, _userRandomBytes!, 0, 8); List.copyRange(userKeySalt, 0, _userRandomBytes!, 8, 16); - hash = List.filled(userPassword.length + userKeySalt.length, 0, - growable: true); + hash = List.filled( + userPassword.length + userKeySalt.length, + 0, + growable: true, + ); List.copyRange(hash, 0, userPassword, 0, userPassword.length); List.copyRange( - hash, userPassword.length, userKeySalt, 0, userKeySalt.length); + hash, + userPassword.length, + userKeySalt, + 0, + userKeySalt.length, + ); hashFound = sha256.convert(hash).bytes; forDecryption = _userEncryptionKeyOut; } - _fileEncryptionKey = AesCipherNoPadding(false, hashFound) - .processBlock(forDecryption, 0, forDecryption!.length); + _fileEncryptionKey = AesCipherNoPadding( + false, + KeyParameter(Uint8List.fromList(hashFound)), + ).process(Uint8List.fromList(forDecryption!)); } bool _compareByteArrays(List array1, List? array2, [int? size]) { @@ -1097,7 +1300,8 @@ class PdfEncryptor { result = array1 == array2; } else if (array1.length < size || array2.length < size) { throw ArgumentError.value( - 'Size of one of the arrays are less then requisted size.'); + 'Size of one of the arrays are less then requisted size.', + ); } else if (array1.length != array2.length) { result = false; } else { @@ -1113,8 +1317,11 @@ class PdfEncryptor { } void _acrobatXOwnerFileEncryptionKey(String password) { - final List ownerValidationSalt = - List.filled(8, 0, growable: true); + final List ownerValidationSalt = List.filled( + 8, + 0, + growable: true, + ); final List ownerPassword = utf8.encode(password); List.copyRange(ownerValidationSalt, 0, _ownerPasswordOut!, 40, 48); int userKeyLength = 48; @@ -1122,22 +1329,35 @@ class PdfEncryptor { userKeyLength = _userPasswordOut!.length; } final List combinedPassword = List.filled( - ownerPassword.length + ownerValidationSalt.length + userKeyLength, 0, - growable: true); + ownerPassword.length + ownerValidationSalt.length + userKeyLength, + 0, + growable: true, + ); List.copyRange(combinedPassword, 0, ownerPassword, 0, ownerPassword.length); - List.copyRange(combinedPassword, ownerPassword.length, ownerValidationSalt, - 0, ownerValidationSalt.length); List.copyRange( - combinedPassword, - ownerPassword.length + ownerValidationSalt.length, - _userPasswordOut!, - 0, - userKeyLength); - final List hash = - _acrobatXComputeHash(combinedPassword, ownerPassword, _userPasswordOut); + combinedPassword, + ownerPassword.length, + ownerValidationSalt, + 0, + ownerValidationSalt.length, + ); + List.copyRange( + combinedPassword, + ownerPassword.length + ownerValidationSalt.length, + _userPasswordOut!, + 0, + userKeyLength, + ); + final List hash = _acrobatXComputeHash( + combinedPassword, + ownerPassword, + _userPasswordOut, + ); final List fileEncryptionKey = List.from(_ownerEncryptionKeyOut!); - _fileEncryptionKey = AesCipherNoPadding(false, hash) - .processBlock(fileEncryptionKey, 0, fileEncryptionKey.length); + _fileEncryptionKey = AesCipherNoPadding( + false, + KeyParameter(Uint8List.fromList(hash)), + ).process(Uint8List.fromList(fileEncryptionKey)); } void _advanceXUserFileEncryptionKey(String password) { @@ -1145,22 +1365,34 @@ class PdfEncryptor { List.copyRange(userKeySalt, 0, _userPasswordOut!, 40, 48); final List userpassword = utf8.encode(password); final List combinedUserPassword = List.filled( - userpassword.length + userKeySalt.length, 0, - growable: true); + userpassword.length + userKeySalt.length, + 0, + growable: true, + ); + List.copyRange( + combinedUserPassword, + 0, + userpassword, + 0, + userpassword.length, + ); List.copyRange( - combinedUserPassword, 0, userpassword, 0, userpassword.length); - List.copyRange(combinedUserPassword, userpassword.length, userKeySalt, 0, - userKeySalt.length); - final List hash = - _acrobatXComputeHash(combinedUserPassword, userpassword, null); + combinedUserPassword, + userpassword.length, + userKeySalt, + 0, + userKeySalt.length, + ); + final List hash = _acrobatXComputeHash( + combinedUserPassword, + userpassword, + null, + ); final List fileEncryptionKey = List.from(_userEncryptionKeyOut!); - _fileEncryptionKey = AesCipherNoPadding(false, hash) - .processBlock(fileEncryptionKey, 0, fileEncryptionKey.length); - } - - List _generateInitVector() { - final Random random = Random.secure(); - return List.generate(16, (int i) => random.nextInt(256)); + _fileEncryptionKey = AesCipherNoPadding( + false, + KeyParameter(Uint8List.fromList(hash)), + ).process(Uint8List.fromList(fileEncryptionKey)); } /// internal method @@ -1171,24 +1403,30 @@ class PdfEncryptor { _revision = 0; keyLength = 0; } - dictionary[PdfDictionaryProperties.filter] = - PdfName(PdfDictionaryProperties.standard); + dictionary[PdfDictionaryProperties.filter] = PdfName( + PdfDictionaryProperties.standard, + ); dictionary[PdfDictionaryProperties.p] = PdfNumber(_permissionValue!); - dictionary[PdfDictionaryProperties.u] = - PdfString.fromBytes(userPasswordOut); - dictionary[PdfDictionaryProperties.o] = - PdfString.fromBytes(ownerPasswordOut); + dictionary[PdfDictionaryProperties.u] = PdfString.fromBytes( + userPasswordOut, + ); + dictionary[PdfDictionaryProperties.o] = PdfString.fromBytes( + ownerPasswordOut, + ); if (dictionary.containsKey(PdfDictionaryProperties.length)) { keyLength = 0; } - dictionary[PdfDictionaryProperties.length] = - PdfNumber(_getKeyLength()! * 8); + dictionary[PdfDictionaryProperties.length] = PdfNumber( + _getKeyLength()! * 8, + ); const bool isAes4Dict = false; if (encryptAttachmentOnly! && (encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x40Bit)) { - throw ArgumentError.value(encryptionAlgorithm, - 'Encrypt only attachment is supported in AES algorithm with 128, 256 and 256Revision6 encryptions only.'); + throw ArgumentError.value( + encryptionAlgorithm, + 'Encrypt only attachment is supported in AES algorithm with 128, 256 and 256Revision6 encryptions only.', + ); } if (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || @@ -1203,27 +1441,34 @@ class PdfEncryptor { dictionary[PdfDictionaryProperties.r] = PdfNumber(5); } if (encryptAttachmentOnly!) { - dictionary[PdfDictionaryProperties.stmF] = - PdfName(PdfDictionaryProperties.identity); - dictionary[PdfDictionaryProperties.strF] = - PdfName(PdfDictionaryProperties.identity); - dictionary[PdfDictionaryProperties.eff] = - PdfName(PdfDictionaryProperties.stdCF); - dictionary[PdfDictionaryProperties.encryptMetadata] = - PdfBoolean(encryptOnlyMetadata); + dictionary[PdfDictionaryProperties.stmF] = PdfName( + PdfDictionaryProperties.identity, + ); + dictionary[PdfDictionaryProperties.strF] = PdfName( + PdfDictionaryProperties.identity, + ); + dictionary[PdfDictionaryProperties.eff] = PdfName( + PdfDictionaryProperties.stdCF, + ); + dictionary[PdfDictionaryProperties.encryptMetadata] = PdfBoolean( + encryptOnlyMetadata, + ); } else { - dictionary[PdfDictionaryProperties.stmF] = - PdfName(PdfDictionaryProperties.stdCF); - dictionary[PdfDictionaryProperties.strF] = - PdfName(PdfDictionaryProperties.stdCF); + dictionary[PdfDictionaryProperties.stmF] = PdfName( + PdfDictionaryProperties.stdCF, + ); + dictionary[PdfDictionaryProperties.strF] = PdfName( + PdfDictionaryProperties.stdCF, + ); if (dictionary.containsKey(PdfDictionaryProperties.eff)) { dictionary.remove(PdfDictionaryProperties.eff); } } if (!encryptOnlyMetadata!) { if (!dictionary.containsKey(PdfDictionaryProperties.encryptMetadata)) { - dictionary[PdfDictionaryProperties.encryptMetadata] = - PdfBoolean(encryptOnlyMetadata); + dictionary[PdfDictionaryProperties.encryptMetadata] = PdfBoolean( + encryptOnlyMetadata, + ); } } else if (!encryptOnlyAttachment) { if (dictionary.containsKey(PdfDictionaryProperties.encryptMetadata)) { @@ -1233,22 +1478,27 @@ class PdfEncryptor { dictionary[PdfDictionaryProperties.cf] = _getCryptFilterDictionary(); if (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256BitRevision6) { - dictionary[PdfDictionaryProperties.ue] = - PdfString.fromBytes(_userEncryptionKeyOut); - dictionary[PdfDictionaryProperties.oe] = - PdfString.fromBytes(_ownerEncryptionKeyOut); - dictionary[PdfDictionaryProperties.perms] = - PdfString.fromBytes(_permissionFlag); + dictionary[PdfDictionaryProperties.ue] = PdfString.fromBytes( + _userEncryptionKeyOut, + ); + dictionary[PdfDictionaryProperties.oe] = PdfString.fromBytes( + _ownerEncryptionKeyOut, + ); + dictionary[PdfDictionaryProperties.perms] = PdfString.fromBytes( + _permissionFlag, + ); } } else { dictionary[PdfDictionaryProperties.r] = PdfNumber( - (_revisionNumberOut! > 0 && !isAes4Dict) - ? _revisionNumberOut! - : (_getKeySize() + 2)); + (_revisionNumberOut! > 0 && !isAes4Dict) + ? _revisionNumberOut! + : (_getKeySize() + 2), + ); dictionary[PdfDictionaryProperties.v] = PdfNumber( - (_versionNumberOut! > 0 && !isAes4Dict) - ? _versionNumberOut! - : (_getKeySize() + 1)); + (_versionNumberOut! > 0 && !isAes4Dict) + ? _versionNumberOut! + : (_getKeySize() + 1), + ); } dictionary.archive = false; return dictionary; @@ -1262,24 +1512,30 @@ class PdfEncryptor { _revision = 0; keyLength = 0; } - dictionary[PdfDictionaryProperties.filter] = - PdfName(PdfDictionaryProperties.standard); + dictionary[PdfDictionaryProperties.filter] = PdfName( + PdfDictionaryProperties.standard, + ); dictionary[PdfDictionaryProperties.p] = PdfNumber(_permissionValue!); - dictionary[PdfDictionaryProperties.u] = - PdfString.fromBytes(userPasswordOut); - dictionary[PdfDictionaryProperties.o] = - PdfString.fromBytes(ownerPasswordOut); + dictionary[PdfDictionaryProperties.u] = PdfString.fromBytes( + userPasswordOut, + ); + dictionary[PdfDictionaryProperties.o] = PdfString.fromBytes( + ownerPasswordOut, + ); if (dictionary.containsKey(PdfDictionaryProperties.length)) { keyLength = 0; } - dictionary[PdfDictionaryProperties.length] = - PdfNumber(_getKeyLength()! * 8); + dictionary[PdfDictionaryProperties.length] = PdfNumber( + _getKeyLength()! * 8, + ); const bool isAes4Dict = false; if (encryptAttachmentOnly! && (encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x40Bit)) { - throw ArgumentError.value(encryptionAlgorithm, - 'Encrypt only attachment is supported in AES algorithm with 128, 256 and 256Revision6 encryptions only.'); + throw ArgumentError.value( + encryptionAlgorithm, + 'Encrypt only attachment is supported in AES algorithm with 128, 256 and 256Revision6 encryptions only.', + ); } if (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || @@ -1294,27 +1550,34 @@ class PdfEncryptor { dictionary[PdfDictionaryProperties.r] = PdfNumber(5); } if (encryptAttachmentOnly!) { - dictionary[PdfDictionaryProperties.stmF] = - PdfName(PdfDictionaryProperties.identity); - dictionary[PdfDictionaryProperties.strF] = - PdfName(PdfDictionaryProperties.identity); - dictionary[PdfDictionaryProperties.eff] = - PdfName(PdfDictionaryProperties.stdCF); - dictionary[PdfDictionaryProperties.encryptMetadata] = - PdfBoolean(encryptOnlyMetadata); + dictionary[PdfDictionaryProperties.stmF] = PdfName( + PdfDictionaryProperties.identity, + ); + dictionary[PdfDictionaryProperties.strF] = PdfName( + PdfDictionaryProperties.identity, + ); + dictionary[PdfDictionaryProperties.eff] = PdfName( + PdfDictionaryProperties.stdCF, + ); + dictionary[PdfDictionaryProperties.encryptMetadata] = PdfBoolean( + encryptOnlyMetadata, + ); } else { - dictionary[PdfDictionaryProperties.stmF] = - PdfName(PdfDictionaryProperties.stdCF); - dictionary[PdfDictionaryProperties.strF] = - PdfName(PdfDictionaryProperties.stdCF); + dictionary[PdfDictionaryProperties.stmF] = PdfName( + PdfDictionaryProperties.stdCF, + ); + dictionary[PdfDictionaryProperties.strF] = PdfName( + PdfDictionaryProperties.stdCF, + ); if (dictionary.containsKey(PdfDictionaryProperties.eff)) { dictionary.remove(PdfDictionaryProperties.eff); } } if (!encryptOnlyMetadata!) { if (!dictionary.containsKey(PdfDictionaryProperties.encryptMetadata)) { - dictionary[PdfDictionaryProperties.encryptMetadata] = - PdfBoolean(encryptOnlyMetadata); + dictionary[PdfDictionaryProperties.encryptMetadata] = PdfBoolean( + encryptOnlyMetadata, + ); } } else if (!encryptOnlyAttachment) { if (dictionary.containsKey(PdfDictionaryProperties.encryptMetadata)) { @@ -1325,22 +1588,27 @@ class PdfEncryptor { await _getCryptFilterDictionaryAsync(); if (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256BitRevision6) { - dictionary[PdfDictionaryProperties.ue] = - PdfString.fromBytes(_userEncryptionKeyOut); - dictionary[PdfDictionaryProperties.oe] = - PdfString.fromBytes(_ownerEncryptionKeyOut); - dictionary[PdfDictionaryProperties.perms] = - PdfString.fromBytes(_permissionFlag); + dictionary[PdfDictionaryProperties.ue] = PdfString.fromBytes( + _userEncryptionKeyOut, + ); + dictionary[PdfDictionaryProperties.oe] = PdfString.fromBytes( + _ownerEncryptionKeyOut, + ); + dictionary[PdfDictionaryProperties.perms] = PdfString.fromBytes( + _permissionFlag, + ); } } else { dictionary[PdfDictionaryProperties.r] = PdfNumber( - (_revisionNumberOut! > 0 && !isAes4Dict) - ? _revisionNumberOut! - : (_getKeySize() + 2)); + (_revisionNumberOut! > 0 && !isAes4Dict) + ? _revisionNumberOut! + : (_getKeySize() + 2), + ); dictionary[PdfDictionaryProperties.v] = PdfNumber( - (_versionNumberOut! > 0 && !isAes4Dict) - ? _versionNumberOut! - : (_getKeySize() + 1)); + (_versionNumberOut! > 0 && !isAes4Dict) + ? _versionNumberOut! + : (_getKeySize() + 1), + ); } dictionary.archive = false; return dictionary; @@ -1350,36 +1618,40 @@ class PdfEncryptor { final PdfDictionary standardCryptFilter = PdfDictionary(); if (!standardCryptFilter.containsKey(PdfDictionaryProperties.cfm)) { if (encryptAttachmentOnly!) { - standardCryptFilter[PdfDictionaryProperties.cfm] = - PdfName(PdfDictionaryProperties.aesv2); - standardCryptFilter[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.cryptFilter); + standardCryptFilter[PdfDictionaryProperties.cfm] = PdfName( + PdfDictionaryProperties.aesv2, + ); + standardCryptFilter[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.cryptFilter, + ); } else { standardCryptFilter[PdfDictionaryProperties.cfm] = PdfName( - (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || - encryptionAlgorithm == - PdfEncryptionAlgorithm.aesx256BitRevision6) - ? PdfDictionaryProperties.aesv3 - : (encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) - ? 'V2' - : PdfDictionaryProperties.aesv2); + (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || + encryptionAlgorithm == + PdfEncryptionAlgorithm.aesx256BitRevision6) + ? PdfDictionaryProperties.aesv3 + : (encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) + ? 'V2' + : PdfDictionaryProperties.aesv2, + ); } } if (!standardCryptFilter.containsKey(PdfDictionaryProperties.authEvent)) { standardCryptFilter[PdfDictionaryProperties.authEvent] = PdfName( - encryptAttachmentOnly! - ? PdfDictionaryProperties.efOpen - : PdfDictionaryProperties.docOpen); + encryptAttachmentOnly! + ? PdfDictionaryProperties.efOpen + : PdfDictionaryProperties.docOpen, + ); } standardCryptFilter[PdfDictionaryProperties.length] = PdfNumber( - (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || - encryptionAlgorithm == - PdfEncryptionAlgorithm.aesx256BitRevision6) - ? _key256! - : ((encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit || - encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) - ? _key128! - : 128)); + (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || + encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256BitRevision6) + ? _key256! + : ((encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit || + encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) + ? _key128! + : 128), + ); final PdfDictionary cryptFilterDictionary = PdfDictionary(); cryptFilterDictionary[PdfDictionaryProperties.stdCF] = standardCryptFilter; return cryptFilterDictionary; @@ -1389,36 +1661,40 @@ class PdfEncryptor { final PdfDictionary standardCryptFilter = PdfDictionary(); if (!standardCryptFilter.containsKey(PdfDictionaryProperties.cfm)) { if (encryptAttachmentOnly!) { - standardCryptFilter[PdfDictionaryProperties.cfm] = - PdfName(PdfDictionaryProperties.aesv2); - standardCryptFilter[PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.cryptFilter); + standardCryptFilter[PdfDictionaryProperties.cfm] = PdfName( + PdfDictionaryProperties.aesv2, + ); + standardCryptFilter[PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.cryptFilter, + ); } else { standardCryptFilter[PdfDictionaryProperties.cfm] = PdfName( - (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || - encryptionAlgorithm == - PdfEncryptionAlgorithm.aesx256BitRevision6) - ? PdfDictionaryProperties.aesv3 - : (encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) - ? 'V2' - : PdfDictionaryProperties.aesv2); + (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || + encryptionAlgorithm == + PdfEncryptionAlgorithm.aesx256BitRevision6) + ? PdfDictionaryProperties.aesv3 + : (encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) + ? 'V2' + : PdfDictionaryProperties.aesv2, + ); } } if (!standardCryptFilter.containsKey(PdfDictionaryProperties.authEvent)) { standardCryptFilter[PdfDictionaryProperties.authEvent] = PdfName( - encryptAttachmentOnly! - ? PdfDictionaryProperties.efOpen - : PdfDictionaryProperties.docOpen); + encryptAttachmentOnly! + ? PdfDictionaryProperties.efOpen + : PdfDictionaryProperties.docOpen, + ); } standardCryptFilter[PdfDictionaryProperties.length] = PdfNumber( - (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || - encryptionAlgorithm == - PdfEncryptionAlgorithm.aesx256BitRevision6) - ? _key256! - : ((encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit || - encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) - ? _key128! - : 128)); + (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || + encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256BitRevision6) + ? _key256! + : ((encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit || + encryptionAlgorithm == PdfEncryptionAlgorithm.rc4x128Bit) + ? _key128! + : 128), + ); final PdfDictionary cryptFilterDictionary = PdfDictionary(); cryptFilterDictionary[PdfDictionaryProperties.stdCF] = standardCryptFilter; return cryptFilterDictionary; @@ -1457,7 +1733,10 @@ class PdfEncryptor { /// internal method List encryptData( - int? currentObjectNumber, List data, bool isEncryption) { + int? currentObjectNumber, + List data, + bool isEncryption, + ) { if (encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256BitRevision6) { return isEncryption @@ -1469,8 +1748,11 @@ class PdfEncryptor { int keyLen = 0; List newKey; if (_encryptionKey!.length == 5) { - newKey = List.filled(_encryptionKey!.length + _newKeyOffset!, 0, - growable: true); + newKey = List.filled( + _encryptionKey!.length + _newKeyOffset!, + 0, + growable: true, + ); for (int i = 0; i < _encryptionKey!.length; ++i) { newKey[i] = _encryptionKey![i]; } @@ -1484,15 +1766,16 @@ class PdfEncryptor { newKey = _prepareKeyForEncryption(newKey); } else { newKey = List.filled( - _encryptionKey!.length + - ((encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || - encryptionAlgorithm == - PdfEncryptionAlgorithm.aesx256BitRevision6 || - encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit) - ? 9 - : 5), - 0, - growable: true); + _encryptionKey!.length + + ((encryptionAlgorithm == PdfEncryptionAlgorithm.aesx256Bit || + encryptionAlgorithm == + PdfEncryptionAlgorithm.aesx256BitRevision6 || + encryptionAlgorithm == PdfEncryptionAlgorithm.aesx128Bit) + ? 9 + : 5), + 0, + growable: true, + ); List.copyRange(newKey, 0, _encryptionKey!, 0, _encryptionKey!.length); int j = _encryptionKey!.length - 1; newKey[++j] = currentObjectNumber!.toUnsigned(8); @@ -1519,52 +1802,64 @@ class PdfEncryptor { } List _aesEncrypt(List data, List key) { - final List result = []; - final List iv = _generateInitVector(); - final AesEncryptor encryptor = AesEncryptor(key, iv, true); - int lengthNeeded = encryptor.getBlockSize(data.length); - final List output = List.filled(lengthNeeded, 0, growable: true); - encryptor.processBytes(data, 0, data.length, output, 0); - result.addAll(output); - lengthNeeded = encryptor.calculateOutputSize(); - final List tempOutput = - List.filled(lengthNeeded, 0, growable: true); - encryptor.finalize(tempOutput); - result.addAll(tempOutput); - return result; + if (key.isEmpty) { + return data; + } + final iv = Uint8List(16); + final Random random = Random.secure(); + for (int i = 0; i < iv.length; i++) { + iv[i] = random.nextInt(256); + } + + final cipher = PaddedCipherMode( + Pkcs7Padding(), + CipherBlockChainingMode(AesEngine()), + ); + + final params = + BlockCipherPaddedParameters( + InvalidParameter(KeyParameter(Uint8List.fromList(key)), iv), + null, + ); + cipher.initialize(true, params); + + try { + final encrypted = cipher.process(Uint8List.fromList(data)); + final results = Uint8List(iv.length + encrypted.length); + results.setRange(0, iv.length, iv); + results.setRange(iv.length, results.length, encrypted); + + return results; + } catch (e) { + return []; + } } List _aesDecrypt(List data, List? key) { - final List result = []; - final List iv = List.filled(16, 0, growable: true); - int length = data.length; - int ivPtr = 0; - final int minBlock = min(iv.length - ivPtr, length); - List.copyRange(iv, ivPtr, data, 0, minBlock); - length -= minBlock; - ivPtr += minBlock; - if (ivPtr == iv.length && length > 0) { - final AesEncryptor decryptor = AesEncryptor(key!, iv, false); - int lengthNeeded = decryptor.getBlockSize(length); - final List output = - List.filled(lengthNeeded, 0, growable: true); - decryptor.processBytes(data, ivPtr, length, output, 0); - result.addAll(output); - lengthNeeded = decryptor.calculateOutputSize(); - final List tempOutput = - List.filled(lengthNeeded, 0, growable: true); - length = decryptor.finalize(tempOutput); - if (tempOutput.length != length) { - final List temp = List.filled(length, 0, growable: true); - List.copyRange(temp, 0, tempOutput, 0, length); - result.addAll(temp); - } else { - result.addAll(tempOutput); - } - } else { + if (key == null || key.isEmpty || data.length < 16) { return data; } - return result; + + final ivBytes = Uint8List.fromList(data.take(16).toList()); + final encryptedData = Uint8List.fromList(data.skip(16).toList()); + + final cipher = PaddedCipherMode( + Pkcs7Padding(), + CipherBlockChainingMode(AesEngine()), + ); + + final params = + BlockCipherPaddedParameters( + InvalidParameter(KeyParameter(Uint8List.fromList(key)), ivBytes), + null, + ); + + cipher.initialize(false, params); + try { + return cipher.process(encryptedData); + } catch (e) { + return []; + } } /// internal method @@ -1585,10 +1880,15 @@ class PdfEncryptor { final int keyLen = originalKey.length; final List newKey = md5.convert(originalKey).bytes; if (keyLen > _randomBytesAmount!) { - final int newKeyLength = - min(_getKeyLength()! + _newKeyOffset!, _randomBytesAmount!); - final List result = - List.filled(newKeyLength, 0, growable: true); + final int newKeyLength = min( + _getKeyLength()! + _newKeyOffset!, + _randomBytesAmount!, + ); + final List result = List.filled( + newKeyLength, + 0, + growable: true, + ); List.copyRange(result, 0, newKey, 0, newKeyLength); return result; } else { @@ -1598,52 +1898,56 @@ class PdfEncryptor { /// internal method PdfEncryptor clone() { - final PdfEncryptor encryptor = PdfEncryptor() - .._stringLength = _cloneInt(_stringLength) - .._revisionNumber40Bit = _cloneInt(_revisionNumber40Bit) - .._revisionNumber128Bit = _cloneInt(_revisionNumber128Bit) - .._ownerLoopNum2 = _cloneInt(_ownerLoopNum2) - .._ownerLoopNum = _cloneInt(_ownerLoopNum) - ..paddingBytes = _cloneList(paddingBytes) - .._bytesAmount = _cloneInt(_bytesAmount) - .._permissionSet = _cloneInt(_permissionSet) - .._permissionCleared = _cloneInt(_permissionCleared) - .._permissionRevisionTwoMask = _cloneInt(_permissionRevisionTwoMask) - .._revisionNumberOut = _cloneInt(_revisionNumberOut) - .._versionNumberOut = _cloneInt(_versionNumberOut) - .._permissionValue = _cloneInt(_permissionValue) - .._randomBytes = _cloneList(_randomBytes) - .._key40 = _cloneInt(_key40) - .._key128 = _cloneInt(_key128) - .._key256 = _cloneInt(_key256) - .._randomBytesAmount = _cloneInt(_randomBytesAmount) - .._newKeyOffset = _cloneInt(_newKeyOffset) - ..isEncrypt = _cloneBool(isEncrypt) - ..changed = _cloneBool(changed) - ..hasComputedPasswordValues = _cloneBool(hasComputedPasswordValues) - .._revision = _cloneInt(_revision) - .._ownerPasswordOut = _cloneList(_ownerPasswordOut) - .._userPasswordOut = _cloneList(_userPasswordOut) - .._encryptionKey = _cloneList(_encryptionKey) - ..keyLength = _cloneInt(keyLength) - ..customArray = _cloneList(customArray) - .._permissionFlagValues = _cloneList(_permissionFlagValues) - .._fileEncryptionKey = _cloneList(_fileEncryptionKey) - .._userEncryptionKeyOut = _cloneList(_userEncryptionKeyOut) - .._ownerEncryptionKeyOut = _cloneList(_ownerEncryptionKeyOut) - .._permissionFlag = _cloneList(_permissionFlag) - .._userRandomBytes = _cloneList(_userRandomBytes) - .._ownerRandomBytes = _cloneList(_ownerRandomBytes) - ..encryptOnlyMetadata = _cloneBool(encryptOnlyMetadata) - ..encryptAttachmentOnly = _cloneBool(encryptAttachmentOnly) - ..encryptionAlgorithm = encryptionAlgorithm - .._userPassword = _userPassword - .._ownerPassword = _ownerPassword - ..encryptionOptions = encryptionOptions; - encryptor._permissions = _permissions != null - ? List.generate( - _permissions!.length, (int i) => _permissions![i]) - : null; + final PdfEncryptor encryptor = + PdfEncryptor() + .._stringLength = _cloneInt(_stringLength) + .._revisionNumber40Bit = _cloneInt(_revisionNumber40Bit) + .._revisionNumber128Bit = _cloneInt(_revisionNumber128Bit) + .._ownerLoopNum2 = _cloneInt(_ownerLoopNum2) + .._ownerLoopNum = _cloneInt(_ownerLoopNum) + ..paddingBytes = _cloneList(paddingBytes) + .._bytesAmount = _cloneInt(_bytesAmount) + .._permissionSet = _cloneInt(_permissionSet) + .._permissionCleared = _cloneInt(_permissionCleared) + .._permissionRevisionTwoMask = _cloneInt(_permissionRevisionTwoMask) + .._revisionNumberOut = _cloneInt(_revisionNumberOut) + .._versionNumberOut = _cloneInt(_versionNumberOut) + .._permissionValue = _cloneInt(_permissionValue) + .._randomBytes = _cloneList(_randomBytes) + .._key40 = _cloneInt(_key40) + .._key128 = _cloneInt(_key128) + .._key256 = _cloneInt(_key256) + .._randomBytesAmount = _cloneInt(_randomBytesAmount) + .._newKeyOffset = _cloneInt(_newKeyOffset) + ..isEncrypt = _cloneBool(isEncrypt) + ..changed = _cloneBool(changed) + ..hasComputedPasswordValues = _cloneBool(hasComputedPasswordValues) + .._revision = _cloneInt(_revision) + .._ownerPasswordOut = _cloneList(_ownerPasswordOut) + .._userPasswordOut = _cloneList(_userPasswordOut) + .._encryptionKey = _cloneList(_encryptionKey) + ..keyLength = _cloneInt(keyLength) + ..customArray = _cloneList(customArray) + .._permissionFlagValues = _cloneList(_permissionFlagValues) + .._fileEncryptionKey = _cloneList(_fileEncryptionKey) + .._userEncryptionKeyOut = _cloneList(_userEncryptionKeyOut) + .._ownerEncryptionKeyOut = _cloneList(_ownerEncryptionKeyOut) + .._permissionFlag = _cloneList(_permissionFlag) + .._userRandomBytes = _cloneList(_userRandomBytes) + .._ownerRandomBytes = _cloneList(_ownerRandomBytes) + ..encryptOnlyMetadata = _cloneBool(encryptOnlyMetadata) + ..encryptAttachmentOnly = _cloneBool(encryptAttachmentOnly) + ..encryptionAlgorithm = encryptionAlgorithm + .._userPassword = _userPassword + .._ownerPassword = _ownerPassword + ..encryptionOptions = encryptionOptions; + encryptor._permissions = + _permissions != null + ? List.generate( + _permissions!.length, + (int i) => _permissions![i], + ) + : null; return encryptor; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_security.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_security.dart index 73d214638..cba5cf2a2 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_security.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/security/pdf_security.dart @@ -110,7 +110,8 @@ class PdfSecurity { set ownerPassword(String value) { if (_helper.conformance) { throw ArgumentError( - 'Document encryption is not allowed with Conformance documents.'); + 'Document encryption is not allowed with Conformance documents.', + ); } _helper.encryptor.ownerPassword = value; _helper.encryptor.encrypt = true; @@ -156,7 +157,8 @@ class PdfSecurity { set userPassword(String value) { if (_helper.conformance) { throw ArgumentError( - 'Document encryption is not allowed with Conformance documents.'); + 'Document encryption is not allowed with Conformance documents.', + ); } _helper.encryptor.userPassword = value; _helper.encryptor.encrypt = true; @@ -183,8 +185,10 @@ class PdfSecurity { /// document.dispose(); /// ``` PdfPermissions get permissions { - _permissions ??= - PdfPermissions._(_helper.encryptor, _helper.encryptor.permissions); + _permissions ??= PdfPermissions._( + _helper.encryptor, + _helper.encryptor.permissions, + ); return _permissions!; } @@ -216,7 +220,8 @@ class PdfSecurity { set encryptionOptions(PdfEncryptionOptions value) { if (_helper.conformance) { throw ArgumentError( - 'Document encryption is not allowed with Conformance documents.'); + 'Document encryption is not allowed with Conformance documents.', + ); } if (_helper.encryptor.encryptionOptions != value) { _helper.encryptor.encryptionOptions = value; @@ -311,7 +316,9 @@ class PdfSecurityHelper { class PdfPermissions { //constructor PdfPermissions._( - PdfEncryptor encryptor, List permissions) { + PdfEncryptor encryptor, + List permissions, + ) { _encryptor = encryptor; _permissions = permissions; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/enums.dart index d05cf3f5f..4ed00fb69 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/enums.dart @@ -11,7 +11,7 @@ enum PdfGridImagePosition { stretch, /// The image is rendered by tile mode. - tile + tile, } /// internal enumerator @@ -31,7 +31,7 @@ enum PdfGridStretchOption { uniformToFill, /// The content preserves its original size. - none + none, } /// Describe the possible values of [PdfHorizontalOverflowType]. @@ -42,7 +42,7 @@ enum PdfHorizontalOverflowType { nextPage, /// Draws the overflowing grid as last page - lastPage + lastPage, } /// Specifies the values of the border overlap style. @@ -369,5 +369,5 @@ enum PdfGridBuiltInStyle { tableGridLight, /// Specifies the grid to render Table Grid style. - tableGrid + tableGrid, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/layouting/pdf_grid_layouter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/layouting/pdf_grid_layouter.dart index 80620fffe..4458a229d 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/layouting/pdf_grid_layouter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/layouting/pdf_grid_layouter.dart @@ -40,6 +40,7 @@ class PdfGridLayouter extends ElementLayouter { List>? _columnRanges; late int _cellEndIndex; late int _cellStartIndex; + late double userHeight; /// internal field static int repeatRowIndex = -1; @@ -87,13 +88,14 @@ class PdfGridLayouter extends ElementLayouter { _currentGraphics = graphics; if (PdfGraphicsHelper.getHelper(_currentGraphics!).layer != null && PdfGraphicsHelper.getHelper(_currentGraphics!).page != null) { - final int index = PdfSectionHelper.getHelper(PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - .section!) - .indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(index)) { + final int index = PdfSectionHelper.getHelper( + PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).section!, + ).indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(index)) { PdfGridHelper.getHelper(_grid!).listOfNavigatePages.add(index); } } @@ -148,13 +150,19 @@ class PdfGridLayouter extends ElementLayouter { _cellEndIndex = range[1]; if (_currentPage != null) { final Map pageLayoutResult = _raiseBeforePageLayout( - _currentPage, _currentBounds.rect, _currentRowIndex); - _currentBounds = - PdfRectangle.fromRect(pageLayoutResult['currentBounds']); + _currentPage, + _currentBounds.rect, + _currentRowIndex, + ); + _currentBounds = PdfRectangle.fromRect( + pageLayoutResult['currentBounds'], + ); _currentRowIndex = pageLayoutResult['currentRow'] as int; if (pageLayoutResult['cancel'] as bool) { - result = - PdfLayoutResultHelper.load(_currentPage!, _currentBounds.rect); + result = PdfLayoutResultHelper.load( + _currentPage!, + _currentBounds.rect, + ); break; } } @@ -164,7 +172,8 @@ class PdfGridLayouter extends ElementLayouter { if (PdfGridHelper.getHelper(_grid!).gridBuiltinStyle != PdfGridBuiltInStyle.tableGrid) { PdfGridHelper.getHelper(_grid!).applyBuiltinStyles( - PdfGridHelper.getHelper(_grid!).gridBuiltinStyle); + PdfGridHelper.getHelper(_grid!).gridBuiltinStyle, + ); } } for (int rowIndex = 0; rowIndex < _grid!.headers.count; rowIndex++) { @@ -210,27 +219,33 @@ class PdfGridLayouter extends ElementLayouter { _cellEndIndex = _cellStartIndex = PdfGridHelper.getHelper(_grid!).parentCellIndex; _parentCellIndexList = []; - _parentCellIndexList - .add(PdfGridHelper.getHelper(_grid!).parentCellIndex); + _parentCellIndexList.add( + PdfGridHelper.getHelper(_grid!).parentCellIndex, + ); PdfGridCellHelper.getHelper(PdfGridHelper.getHelper(_grid!).parentCell!) .present = true; - PdfGrid parentGrid = PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid; + PdfGrid parentGrid = + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid; while (PdfGridHelper.getHelper(parentGrid).parentCell != null) { - _parentCellIndexList - .add(PdfGridHelper.getHelper(parentGrid).parentCellIndex); + _parentCellIndexList.add( + PdfGridHelper.getHelper(parentGrid).parentCellIndex, + ); _cellEndIndex = PdfGridHelper.getHelper(parentGrid).parentCellIndex; _cellStartIndex = PdfGridHelper.getHelper(parentGrid).parentCellIndex; PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(parentGrid).parentCell!) - .present = true; - parentGrid = PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(parentGrid).parentCell!) - .row!) - .grid; + PdfGridHelper.getHelper(parentGrid).parentCell!, + ).present = + true; + parentGrid = + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(parentGrid).parentCell!, + ).row!, + ).grid; if (PdfGridHelper.getHelper(parentGrid).parentCell == null) { _parentCellIndexList.removeAt(_parentCellIndexList.length - 1); } @@ -238,20 +253,23 @@ class PdfGridLayouter extends ElementLayouter { PdfSection section = PdfPageHelper.getHelper(_currentPage!).section!; int index = PdfSectionHelper.getHelper(section).indexOf(_currentPage!); if ((!PdfGridHelper.getHelper(parentGrid).isDrawn) || - (!PdfGridHelper.getHelper(parentGrid) - .listOfNavigatePages - .contains(index))) { - section = PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - .section!; + (!PdfGridHelper.getHelper( + parentGrid, + ).listOfNavigatePages.contains(index))) { + section = + PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).section!; index = PdfSectionHelper.getHelper(section).indexOf(_currentPage!); PdfGridHelper.getHelper(parentGrid).isDrawn = true; for (int rowIndex = 0; rowIndex < parentGrid.rows.count; rowIndex++) { final PdfGridRow row = parentGrid.rows[rowIndex]; final PdfGridCell cell = row.cells[_cellStartIndex]; cell.value = ''; - final PdfPoint location = - PdfPoint(_currentBounds.x, _currentBounds.y); + final PdfPoint location = PdfPoint( + _currentBounds.x, + _currentBounds.y, + ); double width = parentGrid.columns[_cellStartIndex].width; if (width > _currentGraphics!.clientSize.width) { width = _currentGraphics!.clientSize.width - 2 * location.x; @@ -260,8 +278,11 @@ class PdfGridLayouter extends ElementLayouter { if (row.height > cell.height) { height = row.height; } - PdfGridCellHelper.getHelper(cell).draw(_currentGraphics, - PdfRectangle(location.x, location.y, width, height), false); + PdfGridCellHelper.getHelper(cell).draw( + _currentGraphics, + PdfRectangle(location.x, location.y, width, height), + false, + ); _currentBounds.y = _currentBounds.y + height; } _currentBounds.y = 0; @@ -279,43 +300,52 @@ class PdfGridLayouter extends ElementLayouter { startPage = _currentPage; repeatRowIndex = -1; if (flag && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid!) { + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid!) { startingHeight = originalHeight; flag = false; } - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid! && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell! - .rowSpan > + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell!.rowSpan > 1 && (startingHeight! + _childHeight).toInt() < (_currentBounds.y + row.height).toInt()) { if (_grid!.rows.count > i) { - final PdfGrid temp = PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row).grid) - .parentCell!) - .row!) - .grid; - for (int tempRowIndex = 0; - tempRowIndex < temp.rows.count; - tempRowIndex++) { + final PdfGrid temp = + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell!, + ).row!, + ).grid; + for ( + int tempRowIndex = 0; + tempRowIndex < temp.rows.count; + tempRowIndex++ + ) { final PdfGridRow tempRow = temp.rows[tempRowIndex]; if (tempRow.cells[PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row).grid) - .parentCellIndex] == - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell) { - final dynamic grid = tempRow - .cells[PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row).grid) - .parentCellIndex] - .value; + PdfGridRowHelper.getHelper(row).grid, + ).parentCellIndex] == + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell) { + final dynamic grid = + tempRow + .cells[PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCellIndex] + .value; if (grid is PdfGrid) { - PdfGridRowCollectionHelper.getRows(grid.rows) - .removeRange(0, i - 1); + PdfGridRowCollectionHelper.getRows( + grid.rows, + ).removeRange(0, i - 1); } } } @@ -332,22 +362,25 @@ class PdfGridLayouter extends ElementLayouter { row.cells[l].value is PdfGrid) { final PdfGrid grid = row.cells[l].value as PdfGrid; for (int m = grid.rows.count; 0 < m; m--) { - if (PdfGridRowHelper.getHelper(grid.rows[m - 1]) - .rowBreakHeight > + if (PdfGridRowHelper.getHelper( + grid.rows[m - 1], + ).rowBreakHeight > 0) { isNestedRowBreak = true; break; } - if (PdfGridRowHelper.getHelper(grid.rows[m - 1]) - .isRowBreaksNextPage) { + if (PdfGridRowHelper.getHelper( + grid.rows[m - 1], + ).isRowBreaksNextPage) { PdfGridRowHelper.getHelper(row).rowBreakHeight = - PdfGridRowHelper.getHelper(grid.rows[m - 1]) - .rowBreakHeight; + PdfGridRowHelper.getHelper( + grid.rows[m - 1], + ).rowBreakHeight; break; } PdfGridRowHelper.getHelper(row).rowBreakHeight = PdfGridRowHelper.getHelper(row).rowBreakHeight + - grid.rows[m - 1].height; + grid.rows[m - 1].height; } } if (isNestedRowBreak) { @@ -361,33 +394,38 @@ class PdfGridLayouter extends ElementLayouter { PdfPage page = getNextPage(_currentPage!)!; final PdfSection section = PdfPageHelper.getHelper(_currentPage!).section!; - final int index = - PdfSectionHelper.getHelper(section).indexOf(page); - for (int k = 0; - k < - (PdfSectionHelper.getHelper(section) - .pageReferences! - .count - - 1) - - index; - k++) { + final int index = PdfSectionHelper.getHelper( + section, + ).indexOf(page); + for ( + int k = 0; + k < + (PdfSectionHelper.getHelper(section).pageReferences!.count - + 1) - + index; + k++ + ) { rect = PdfRectangle( - x, - 0, - PdfGridRowHelper.getHelper(row).grid.columns[j].width, - page.getClientSize().height); + x, + 0, + PdfGridRowHelper.getHelper(row).grid.columns[j].width, + page.getClientSize().height, + ); repeatRowIndex = -1; - PdfGridCellHelper.getHelper(row.cells[j]) - .draw(page.graphics, rect, false); + PdfGridCellHelper.getHelper( + row.cells[j], + ).draw(page.graphics, rect, false); page = getNextPage(page)!; } rect = PdfRectangle( - x, - 0, - PdfGridRowHelper.getHelper(row).grid.columns[j].width, - PdfGridRowHelper.getHelper(row).rowBreakHeight); - PdfGridCellHelper.getHelper(row.cells[j]) - .draw(page.graphics, rect, false); + x, + 0, + PdfGridRowHelper.getHelper(row).grid.columns[j].width, + PdfGridRowHelper.getHelper(row).rowBreakHeight, + ); + PdfGridCellHelper.getHelper( + row.cells[j], + ).draw(page.graphics, rect, false); } x += PdfGridRowHelper.getHelper(row).grid.columns[j].width; } @@ -402,39 +440,40 @@ class PdfGridLayouter extends ElementLayouter { while (!rowResult.isFinish && startPage != null) { final PdfLayoutResult tempResult = _getLayoutResult(); if (startPage != _currentPage) { - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid! && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell != + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell != null) { final PdfRectangle bounds = PdfRectangle( - format.paginateBounds.left, - format.paginateBounds.top, - param.bounds!.width, - tempResult.bounds.height); + format.paginateBounds.left, + format.paginateBounds.top, + param.bounds!.width, + tempResult.bounds.height, + ); bounds.x = bounds.x + param.bounds!.x; - bounds.y = bounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .top; + bounds.y = + bounds.y + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.top; if (bounds.height > _currentPageBounds.height) { bounds.height = _currentPageBounds.height - bounds.y; - bounds.height = bounds.height - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom; + bounds.height = + bounds.height - + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; } for (int c = 0; c < row.cells.count; c++) { final PdfGridCell cell = row.cells[c]; @@ -445,14 +484,17 @@ class PdfGridLayouter extends ElementLayouter { PdfGridRowHelper.getHelper(row).grid.columns[c].width; } } else { - cellWidth = max(cell.width, - PdfGridRowHelper.getHelper(row).grid.columns[c].width); + cellWidth = max( + cell.width, + PdfGridRowHelper.getHelper(row).grid.columns[c].width, + ); } - _currentGraphics = PdfGridCellHelper.getHelper(cell) - .drawCellBorders( - _currentGraphics!, - PdfRectangle( - bounds.x, bounds.y, cellWidth, bounds.height)); + _currentGraphics = PdfGridCellHelper.getHelper( + cell, + ).drawCellBorders( + _currentGraphics!, + PdfRectangle(bounds.x, bounds.y, cellWidth, bounds.height), + ); bounds.x = bounds.x + cellWidth; c += cell.columnSpan - 1; } @@ -468,8 +510,9 @@ class PdfGridLayouter extends ElementLayouter { _currentPage = _getNextPage(format); originalHeight = _currentBounds.y; final PdfPoint location = PdfPoint( - PdfGridHelper.getHelper(_grid!).defaultBorder.right.width / 2, - PdfGridHelper.getHelper(_grid!).defaultBorder.top.width / 2); + PdfGridHelper.getHelper(_grid!).defaultBorder.right.width / 2, + PdfGridHelper.getHelper(_grid!).defaultBorder.top.width / 2, + ); if (PdfRectangle.fromRect(format.paginateBounds) == PdfRectangle.empty && _startLocation == location) { @@ -477,75 +520,77 @@ class PdfGridLayouter extends ElementLayouter { _currentBounds.y = _currentBounds.y + _startLocation.y; } if (PdfGridHelper.getHelper(_grid!).isChildGrid! && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell != + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell != null) { - if (PdfGridStyleHelper.getPadding(PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style) != + if (PdfGridStyleHelper.getPadding( + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style, + ) != null) { if (PdfGridRowHelper.getHelper(row).rowBreakHeight + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .top < - _currentBounds.height) { - _currentBounds.y = PdfGridRowHelper.getHelper( + PdfGridRowHelper.getHelper( PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .top; + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top < + _currentBounds.height) { + _currentBounds.y = + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top; } } } - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell != + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell != null) { - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row).grid) - .parentCell!) - .row!) - .isRowBreaksNextPage = true; - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell!) - .row!) - .rowBreakHeight = + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell!, + ).row!, + ).isRowBreaksNextPage = + true; + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell!, + ).row!, + ).rowBreakHeight = PdfGridRowHelper.getHelper(row).rowBreakHeight + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .top + - PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(PdfGridHelper.getHelper(_grid!).parentCell!).row!) - .grid - .style - .cellPadding - .bottom; + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; } if (PdfGridRowHelper.getHelper(row).noOfPageCount > 1) { final double temp = PdfGridRowHelper.getHelper(row).rowBreakHeight; - for (int j = 1; - j < PdfGridRowHelper.getHelper(row).noOfPageCount; - j++) { + for ( + int j = 1; + j < PdfGridRowHelper.getHelper(row).noOfPageCount; + j++ + ) { PdfGridRowHelper.getHelper(row).rowBreakHeight = 0; row.height = (PdfGridRowHelper.getHelper(row).noOfPageCount - 1) * - _currentPage!.getClientSize().height; + _currentPage!.getClientSize().height; _drawRow(row); _currentPage = _getNextPage(format); startPage = _currentPage; @@ -578,9 +623,9 @@ class PdfGridLayouter extends ElementLayouter { } } if (isWidthGreaterthanParent && - PdfGridCellHelper.getHelper(_grid! - .rows[j].cells[_rowBreakPageHeightCellIndex]) - .pageCount > + PdfGridCellHelper.getHelper( + _grid!.rows[j].cells[_rowBreakPageHeightCellIndex], + ).pageCount > 0) { isAddNextPage = true; } @@ -596,20 +641,23 @@ class PdfGridLayouter extends ElementLayouter { PdfSectionHelper.getHelper(section).isNewPageSection = false; _currentGraphics = _currentPage!.graphics; final Size clientSize = _currentPage!.getClientSize(); - _currentBounds = - PdfRectangle(0, 0, clientSize.width, clientSize.height); + _currentBounds = PdfRectangle( + 0, + 0, + clientSize.width, + clientSize.height, + ); final int pageindex = PdfSectionHelper.getHelper( - PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!) - .page!) - .section!) - .indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(pageindex)) { - PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .add(pageindex); + PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).section!, + ).indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(pageindex)) { + PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.add(pageindex); } } else { if (endArgs.nextPage == null) { @@ -618,24 +666,30 @@ class PdfGridLayouter extends ElementLayouter { _currentPage = endArgs.nextPage; _currentGraphics = endArgs.nextPage!.graphics; _currentBounds = PdfRectangle( - 0, - 0, - _currentGraphics!.clientSize.width, - _currentGraphics!.clientSize.height); + 0, + 0, + _currentGraphics!.clientSize.width, + _currentGraphics!.clientSize.height, + ); } } final bool isSameSection = PdfPageHelper.getHelper(_currentPage!).section == - PdfPageHelper.getHelper(param.page!).section; - _currentBounds.y = format.paginateBounds.top == 0 - ? PdfGridHelper.getHelper(_grid!).defaultBorder.top.width / 2 - : format.paginateBounds.top; + PdfPageHelper.getHelper(param.page!).section; + _currentBounds.y = + format.paginateBounds.top == 0 + ? PdfGridHelper.getHelper(_grid!).defaultBorder.top.width / 2 + : format.paginateBounds.top; if (_currentPage != null) { final Map pageLayoutResult = _raiseBeforePageLayout( - _currentPage, _currentBounds.rect, _currentRowIndex); - _currentBounds = - PdfRectangle.fromRect(pageLayoutResult['currentBounds']); + _currentPage, + _currentBounds.rect, + _currentRowIndex, + ); + _currentBounds = PdfRectangle.fromRect( + pageLayoutResult['currentBounds'], + ); _currentRowIndex = pageLayoutResult['currentRow'] as int; if (pageLayoutResult['cancel'] as bool) { break; @@ -659,9 +713,11 @@ class PdfGridLayouter extends ElementLayouter { _currentBounds.y = _currentBounds.y + _startLocation.x; } if (_grid!.repeatHeader) { - for (int headerIndex = 0; - headerIndex < _grid!.headers.count; - headerIndex++) { + for ( + int headerIndex = 0; + headerIndex < _grid!.headers.count; + headerIndex++ + ) { _drawRow(_grid!.headers[headerIndex]); } } @@ -675,8 +731,9 @@ class PdfGridLayouter extends ElementLayouter { _currentPage = PdfGridRowHelper.getHelper(row).gridResult!.page; _currentGraphics = _currentPage!.graphics; _startLocation = PdfPoint( - PdfGridRowHelper.getHelper(row).gridResult!.bounds.left, - PdfGridRowHelper.getHelper(row).gridResult!.bounds.top); + PdfGridRowHelper.getHelper(row).gridResult!.bounds.left, + PdfGridRowHelper.getHelper(row).gridResult!.bounds.top, + ); _currentBounds.y = PdfGridRowHelper.getHelper(row).gridResult!.bounds.bottom; if (startPage != _currentPage) { @@ -684,34 +741,45 @@ class PdfGridLayouter extends ElementLayouter { PdfPageHelper.getHelper(_currentPage!).section!; final int startIndex = PdfSectionHelper.getHelper(secion).indexOf(startPage!) + 1; - final int endIndex = - PdfSectionHelper.getHelper(secion).indexOf(_currentPage!); + final int endIndex = PdfSectionHelper.getHelper( + secion, + ).indexOf(_currentPage!); for (int page = startIndex; page < endIndex + 1; page++) { - PdfGraphics pageGraphics = PdfSectionHelper.getHelper(secion) - .getPageByIndex(page)! - .graphics; + PdfGraphics pageGraphics = + PdfSectionHelper.getHelper( + secion, + ).getPageByIndex(page)!.graphics; final PdfPoint location = PdfPoint( - format.paginateBounds.left, format.paginateBounds.top); + format.paginateBounds.left, + format.paginateBounds.top, + ); if (location == PdfPoint.empty && _currentBounds.x > location.x && - !PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid! && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell == + !PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell == null) { location.x = _currentBounds.x; } - double height = page == endIndex - ? (PdfGridRowHelper.getHelper(row).gridResult!.bounds.height - - param.bounds!.y) - : (_currentBounds.height - location.y); + double height = + page == endIndex + ? (PdfGridRowHelper.getHelper( + row, + ).gridResult!.bounds.height - + param.bounds!.y) + : (_currentBounds.height - location.y); if (height <= pageGraphics.clientSize.height) { height += param.bounds!.y; } - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid! && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .parentCell != + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).parentCell != null) { location.x = location.x + param.bounds!.x; } @@ -725,21 +793,27 @@ class PdfGridLayouter extends ElementLayouter { PdfGridRowHelper.getHelper(row).grid.columns[c].width; } } else { - cellWidth = PdfGridHelper.getHelper(_grid!).isWidthSet - ? min(cell.width, - PdfGridRowHelper.getHelper(row).grid.columns[c].width) - : max( - cell.width, - PdfGridRowHelper.getHelper(row) - .grid - .columns[c] - .width); + cellWidth = + PdfGridHelper.getHelper(_grid!).isWidthSet + ? min( + cell.width, + PdfGridRowHelper.getHelper( + row, + ).grid.columns[c].width, + ) + : max( + cell.width, + PdfGridRowHelper.getHelper( + row, + ).grid.columns[c].width, + ); } - pageGraphics = PdfGridCellHelper.getHelper(cell) - .drawCellBorders( - pageGraphics, - PdfRectangle( - location.x, location.y, cellWidth, height)); + pageGraphics = PdfGridCellHelper.getHelper( + cell, + ).drawCellBorders( + pageGraphics, + PdfRectangle(location.x, location.y, cellWidth, height), + ); location.x = location.x + cellWidth; c += cell.columnSpan - 1; } @@ -753,8 +827,10 @@ class PdfGridLayouter extends ElementLayouter { if (cellBounds.isNotEmpty) { maximumCellBoundsWidth = cellBounds[0]!; } - final List> largeNavigatePage = - List>.filled(1, List.filled(2, 0)); + final List> largeNavigatePage = List>.filled( + 1, + List.filled(2, 0), + ); for (int c = 0; c < _grid!.rows.count; c++) { if (_cellEndIndex != -1 && _grid!.rows[c].cells[_cellEndIndex].value is PdfGrid) { @@ -765,10 +841,10 @@ class PdfGridLayouter extends ElementLayouter { isPdfGrid = true; if (largeNavigatePage[0][0]! < PdfGridHelper.getHelper(grid).listOfNavigatePages.length) { - largeNavigatePage[0][0] = PdfGridHelper.getHelper(grid) - .listOfNavigatePages - .length - .toDouble(); + largeNavigatePage[0][0] = + PdfGridHelper.getHelper( + grid, + ).listOfNavigatePages.length.toDouble(); largeNavigatePage[0][1] = cellBounds[c]; } else if ((largeNavigatePage[0][0] == PdfGridHelper.getHelper(grid).listOfNavigatePages.length) && @@ -796,12 +872,14 @@ class PdfGridLayouter extends ElementLayouter { if (largeNavigatePage[0][0]!.toInt() != 0) { final PdfSection section = PdfPageHelper.getHelper(_currentPage!).section!; - final int pageIndex = - PdfSectionHelper.getHelper(section).indexOf(_currentPage!); + final int pageIndex = PdfSectionHelper.getHelper( + section, + ).indexOf(_currentPage!); if (PdfSectionHelper.getHelper(section).count > pageIndex + largeNavigatePage[0][0]!.toInt()) { - _currentPage = PdfSectionHelper.getHelper(section) - .getPageByIndex(pageIndex + largeNavigatePage[0][0]!.toInt()); + _currentPage = PdfSectionHelper.getHelper( + section, + ).getPageByIndex(pageIndex + largeNavigatePage[0][0]!.toInt()); } else { _currentPage = PdfPage(); PdfSectionHelper.getHelper(section).isNewPageSection = true; @@ -810,26 +888,28 @@ class PdfGridLayouter extends ElementLayouter { } _currentGraphics = _currentPage!.graphics; _currentBounds = PdfRectangle( - 0, - 0, - _currentGraphics!.clientSize.width, - _currentGraphics!.clientSize.height); + 0, + 0, + _currentGraphics!.clientSize.width, + _currentGraphics!.clientSize.height, + ); final int pageindex = PdfSectionHelper.getHelper( - PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - .section!) - .indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(pageindex)) { + PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).section!, + ).indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(pageindex)) { PdfGridHelper.getHelper(_grid!).listOfNavigatePages.add(pageindex); } } else { _currentPage = _getNextPage(format); } final PdfPoint location = PdfPoint( - PdfGridHelper.getHelper(_grid!).defaultBorder.right.width / 2, - PdfGridHelper.getHelper(_grid!).defaultBorder.top.width / 2); + PdfGridHelper.getHelper(_grid!).defaultBorder.right.width / 2, + PdfGridHelper.getHelper(_grid!).defaultBorder.top.width / 2, + ); if (PdfRectangle.fromRect(format.paginateBounds) == PdfRectangle.empty && _startLocation == location) { @@ -867,14 +947,18 @@ class PdfGridLayouter extends ElementLayouter { } final double height = row.height > cell.height ? row.height : cell.height; if (_isChildGrid!) { - PdfGridCellHelper.getHelper(cell).draw(_currentGraphics, - PdfRectangle(location.x, location.y, width, height), false); + PdfGridCellHelper.getHelper(cell).draw( + _currentGraphics, + PdfRectangle(location.x, location.y, width, height), + false, + ); } _currentBounds.y = _currentBounds.y + height; } for (int j = 0; j < grid.rows.count; j++) { - if (PdfGridCellHelper.getHelper(grid.rows[j].cells[_cellStartIndex]) - .present) { + if (PdfGridCellHelper.getHelper( + grid.rows[j].cells[_cellStartIndex], + ).present) { present = true; if (grid.rows[j].cells[_cellStartIndex].value is PdfGrid) { final PdfGrid? childGrid = @@ -886,7 +970,8 @@ class PdfGridLayouter extends ElementLayouter { _currentBounds.y = y!; } else { if (j == 0) { - _currentBounds.y = _currentBounds.y - + _currentBounds.y = + _currentBounds.y - PdfGridHelper.getHelper(grid).size.height; } else { int k = j; @@ -898,10 +983,12 @@ class PdfGridLayouter extends ElementLayouter { } PdfGridHelper.getHelper(childGrid!).isDrawn = true; grid.rows[j].cells[_cellStartIndex].value = childGrid; - _currentBounds.x = _currentBounds.x + + _currentBounds.x = + _currentBounds.x + grid.style.cellPadding.left + grid.style.cellPadding.right; - _currentBounds.y = _currentBounds.y + + _currentBounds.y = + _currentBounds.y + grid.style.cellPadding.top + grid.style.cellPadding.bottom; _currentBounds.width = _currentBounds.width - 2 * _currentBounds.x; @@ -914,15 +1001,18 @@ class PdfGridLayouter extends ElementLayouter { _parentCellIndexList.removeAt(_parentCellIndexList.length - 1); } _currentBounds.y = y!; - _currentBounds.x = _currentBounds.x + + _currentBounds.x = + _currentBounds.x + grid.style.cellPadding.left + grid.style.cellPadding.right; - _currentBounds.y = _currentBounds.y + + _currentBounds.y = + _currentBounds.y + grid.style.cellPadding.top + grid.style.cellPadding.bottom; final bool isPresent = _drawParentGridRow(childGrid!); if (!isPresent) { - _currentBounds.y = _currentBounds.y - + _currentBounds.y = + _currentBounds.y - PdfGridHelper.getHelper(childGrid).size.height; } _isChildGrid = false; @@ -938,8 +1028,11 @@ class PdfGridLayouter extends ElementLayouter { return present; } - _RowLayoutResult? _drawRow(PdfGridRow? row, - [_RowLayoutResult? result, double? height]) { + _RowLayoutResult? _drawRow( + PdfGridRow? row, [ + _RowLayoutResult? result, + double? height, + ]) { if (result == null && height == null) { _RowLayoutResult result = _RowLayoutResult(); double rowHeightWithSpan = 0; @@ -948,8 +1041,9 @@ class PdfGridLayouter extends ElementLayouter { int currRowIndex = PdfGridRowCollectionHelper.indexOf(_grid!.rows, row); int maxSpan = PdfGridRowHelper.getHelper(row).maximumRowSpan; if (currRowIndex == -1) { - currRowIndex = PdfGridHeaderCollectionHelper.getHelper(_grid!.headers) - .indexOf(row); + currRowIndex = PdfGridHeaderCollectionHelper.getHelper( + _grid!.headers, + ).indexOf(row); if (currRowIndex != -1) { isHeader = true; } @@ -973,9 +1067,11 @@ class PdfGridLayouter extends ElementLayouter { _currentPageBounds.height) { rowHeightWithSpan -= isHeader ? _grid!.headers[i].height : _grid!.rows[i].height; - for (int j = 0; - j < _grid!.rows[currRowIndex].cells.count; - j++) { + for ( + int j = 0; + j < _grid!.rows[currRowIndex].cells.count; + j++ + ) { final int newSpan = i - currRowIndex; if (!isHeader && (_grid!.rows[currRowIndex].cells[j].rowSpan == maxSpan)) { @@ -1042,84 +1138,81 @@ class PdfGridLayouter extends ElementLayouter { } } } - double? height = PdfGridRowHelper.getHelper(row).rowBreakHeight > 0.0 - ? PdfGridRowHelper.getHelper(row).rowBreakHeight - : row.height; + double? height = + PdfGridRowHelper.getHelper(row).rowBreakHeight > 0.0 + ? PdfGridRowHelper.getHelper(row).rowBreakHeight + : row.height; if (PdfGridHelper.getHelper(_grid!).isChildGrid! && PdfGridHelper.getHelper(_grid!).parentCell != null) { if (height + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(PdfGridHelper.getHelper(_grid!).parentCell!).row!) - .grid - .style - .cellPadding - .bottom + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(PdfGridHelper.getHelper(_grid!).parentCell!).row!) - .grid - .style - .cellPadding - .top > + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top > _currentPageBounds.height) { + userHeight = _startLocation.y; if (_grid!.allowRowBreakingAcrossPages) { result.isFinish = true; if (PdfGridHelper.getHelper(_grid!).isChildGrid! && PdfGridRowHelper.getHelper(row).rowBreakHeight > 0) { - _currentBounds.y = _currentBounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .top; + _currentBounds.y = + _currentBounds.y + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top; _currentBounds.x = _startLocation.x; } result.bounds = _currentBounds; result = _drawRowWithBreak(row, result, height); } else { - _currentBounds.y = _currentBounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .top; - height = _currentBounds.height - + _currentBounds.y = + _currentBounds.y + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top; + height = + _currentBounds.height - _currentBounds.y - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom; + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; result.isFinish = false; _drawRow(row, result, height); } } else if (_currentBounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(PdfGridHelper.getHelper(_grid!).parentCell!).row!) - .grid - .style - .cellPadding - .bottom + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom + height > _currentPageBounds.height || _currentBounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(PdfGridHelper.getHelper(_grid!).parentCell!).row!) - .grid - .style - .cellPadding - .bottom + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom + height > _currentBounds.height || _currentBounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom + rowHeightWithSpan > _currentPageBounds.height) { if (repeatRowIndex > -1 && @@ -1128,14 +1221,13 @@ class PdfGridLayouter extends ElementLayouter { result.isFinish = true; if (PdfGridHelper.getHelper(_grid!).isChildGrid! && PdfGridRowHelper.getHelper(row).rowBreakHeight > 0) { - _currentBounds.y = _currentBounds.y + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .top; + _currentBounds.y = + _currentBounds.y + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.top; _currentBounds.x = _startLocation.x; } @@ -1152,13 +1244,12 @@ class PdfGridLayouter extends ElementLayouter { result.isFinish = true; if (PdfGridHelper.getHelper(_grid!).isChildGrid! && PdfGridRowHelper.getHelper(row).rowBreakHeight > 0) { - height += PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper(_grid!).parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom; + height += + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper(_grid!).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; } _drawRow(row, result, height); } @@ -1172,7 +1263,7 @@ class PdfGridLayouter extends ElementLayouter { _drawRow(row, result, height); } } else if (_currentBounds.y + height > _currentPageBounds.height || - _currentBounds.y + height > _currentBounds.height || + (_currentBounds.y + height) - userHeight > _currentBounds.height || _currentBounds.y + rowHeightWithSpan > _currentPageBounds.height) { if (repeatRowIndex > -1 && repeatRowIndex == PdfGridRowHelper.getHelper(row).index) { @@ -1195,8 +1286,9 @@ class PdfGridLayouter extends ElementLayouter { } else { bool? skipcell = false; final PdfPoint location = _currentBounds.location; - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isChildGrid! && + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isChildGrid! && PdfGridRowHelper.getHelper(row).grid.allowRowBreakingAcrossPages && _startLocation.x != _currentBounds.x && PdfGridRowHelper.getHelper(row).getWidth() < @@ -1231,15 +1323,16 @@ class PdfGridLayouter extends ElementLayouter { PdfGridCellStyle cellstyle = row.cells[i].style; final Map bclResult = _raiseBeforeCellLayout( - _currentGraphics, - PdfGridRowHelper.getHelper(row).isHeaderRow - ? _currentHeaderRowIndex - : _currentRowIndex, - i, - PdfRectangle(location.x, location.y, size.width, size.height), - (row.cells[i].value is String) ? row.cells[i].value.toString() : '', - cellstyle, - PdfGridRowHelper.getHelper(row).isHeaderRow); + _currentGraphics, + PdfGridRowHelper.getHelper(row).isHeaderRow + ? _currentHeaderRowIndex + : _currentRowIndex, + i, + PdfRectangle(location.x, location.y, size.width, size.height), + (row.cells[i].value is String) ? row.cells[i].value.toString() : '', + cellstyle, + PdfGridRowHelper.getHelper(row).isHeaderRow, + ); cellstyle = bclResult['style'] as PdfGridCellStyle; final PdfGridBeginCellLayoutArgs? gridbclArgs = bclResult['args'] as PdfGridBeginCellLayoutArgs?; @@ -1254,51 +1347,52 @@ class PdfGridLayouter extends ElementLayouter { } final PdfStringLayoutResult? stringResult = PdfGridCellHelper.getHelper(row.cells[i]).draw( - _currentGraphics, - PdfRectangle(location.x, location.y, size.width, size.height), - cancelSpans); - if (PdfGridRowHelper.getHelper(row) - .grid - .style - .allowHorizontalOverflow && + _currentGraphics, + PdfRectangle(location.x, location.y, size.width, size.height), + cancelSpans, + ); + if (PdfGridRowHelper.getHelper( + row, + ).grid.style.allowHorizontalOverflow && (row.cells[i].columnSpan > _cellEndIndex || i + row.cells[i].columnSpan > _cellEndIndex + 1) && _cellEndIndex < row.cells.count - 1) { PdfGridRowHelper.getHelper(row).rowOverflowIndex = _cellEndIndex; } - if (PdfGridRowHelper.getHelper(row) - .grid - .style - .allowHorizontalOverflow && + if (PdfGridRowHelper.getHelper( + row, + ).grid.style.allowHorizontalOverflow && (PdfGridRowHelper.getHelper(row).rowOverflowIndex >= 0 && (row.cells[i].columnSpan > _cellEndIndex || i + row.cells[i].columnSpan > _cellEndIndex + 1)) && row.cells[i].columnSpan - _cellEndIndex + i - 1 > 0) { - row.cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] - .value = - stringResult != null && stringResult.remainder != null + row + .cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] + .value = stringResult != null && stringResult.remainder != null ? stringResult.remainder : ''; - row.cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] + row + .cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] .stringFormat = row.cells[i].stringFormat; - row.cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] + row + .cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] .style = row.cells[i].style; - row.cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] + row + .cells[PdfGridRowHelper.getHelper(row).rowOverflowIndex + 1] .columnSpan = row.cells[i].columnSpan - _cellEndIndex + i - 1; } } if (!cancelSpans) { _raiseAfterCellLayout( - _currentGraphics, - _currentRowIndex, - i, - PdfRectangle(location.x, location.y, size.width, size.height), - (row.cells[i].value is String) - ? row.cells[i].value.toString() - : '', - row.cells[i].style, - PdfGridRowHelper.getHelper(row).isHeaderRow); + _currentGraphics, + _currentRowIndex, + i, + PdfRectangle(location.x, location.y, size.width, size.height), + (row.cells[i].value is String) ? row.cells[i].value.toString() : '', + row.cells[i].style, + PdfGridRowHelper.getHelper(row).isHeaderRow, + ); } if (row.cells[i].value is PdfGrid) { @@ -1306,17 +1400,19 @@ class PdfGridLayouter extends ElementLayouter { PdfGridCellHelper.getHelper(row.cells[i]).pageCount = PdfGridHelper.getHelper(grid).listOfNavigatePages.length; _rowBreakPageHeightCellIndex = i; - for (int k = 0; - k < PdfGridHelper.getHelper(grid).listOfNavigatePages.length; - k++) { + for ( + int k = 0; + k < PdfGridHelper.getHelper(grid).listOfNavigatePages.length; + k++ + ) { final int pageIndex = PdfGridHelper.getHelper(grid).listOfNavigatePages[k]; - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(pageIndex)) { - PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .add(pageIndex); + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(pageIndex)) { + PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.add(pageIndex); } } if (_grid!.columns[i].width >= _currentGraphics!.clientSize.width) { @@ -1334,7 +1430,11 @@ class PdfGridLayouter extends ElementLayouter { _currentBounds.y = _currentBounds.y + height; } result.bounds = PdfRectangle( - result.bounds.x, result.bounds.y, location.x, location.y); + result.bounds.x, + result.bounds.y, + location.x, + location.y, + ); return null; } } @@ -1343,31 +1443,38 @@ class PdfGridLayouter extends ElementLayouter { double newHeight = 0.0; for (int i = _cellStartIndex; i <= _cellEndIndex; i++) { if (PdfGridCellHelper.getHelper(row!.cells[i]).remainingString != null && - PdfGridCellHelper.getHelper(row.cells[i]) - .remainingString! - .isNotEmpty) { - newHeight = max(newHeight, - PdfGridCellHelper.getHelper(row.cells[i]).measureHeight()); + PdfGridCellHelper.getHelper( + row.cells[i], + ).remainingString!.isNotEmpty) { + newHeight = max( + newHeight, + PdfGridCellHelper.getHelper(row.cells[i]).measureHeight(), + ); } } return max(height, newHeight); } _RowLayoutResult _drawRowWithBreak( - PdfGridRow row, _RowLayoutResult result, double? height) { + PdfGridRow row, + _RowLayoutResult result, + double? height, + ) { final PdfPoint location = _currentBounds.location; - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid! && + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid! && PdfGridRowHelper.getHelper(row).grid.allowRowBreakingAcrossPages && _startLocation.x != _currentBounds.x) { location.x = _startLocation.x; } result.bounds = PdfRectangle(location.x, location.y, 0, 0); - _newheight = PdfGridRowHelper.getHelper(row).rowBreakHeight > 0 - ? _currentBounds.height < _currentPageBounds.height - ? _currentBounds.height - : _currentPageBounds.height - : 0; + _newheight = + PdfGridRowHelper.getHelper(row).rowBreakHeight > 0 + ? _currentBounds.height < _currentPageBounds.height + ? _currentBounds.height + : _currentPageBounds.height + : 0; if (PdfGridRowHelper.getHelper(row).grid.style.cellPadding.top + _currentBounds.y + PdfGridRowHelper.getHelper(row).grid.style.cellPadding.bottom < @@ -1382,9 +1489,10 @@ class PdfGridLayouter extends ElementLayouter { for (int cellIndex = 0; cellIndex < row.cells.count; cellIndex++) { final PdfGridCell cell = row.cells[cellIndex]; if (PdfGridCellHelper.getHelper(cell).measureHeight() == height) { - PdfGridRowHelper.getHelper(row).rowBreakHeight = cell.value is PdfGrid - ? 0 - : _currentBounds.y + height - _currentBounds.height < + PdfGridRowHelper.getHelper(row).rowBreakHeight = + cell.value is PdfGrid + ? 0 + : _currentBounds.y + height - _currentBounds.height < _currentPageBounds.height ? _currentBounds.height : _currentPageBounds.height; @@ -1393,7 +1501,7 @@ class PdfGridLayouter extends ElementLayouter { for (int i = _cellStartIndex; i <= _cellEndIndex; i++) { final bool cancelSpans = row.cells[i].columnSpan + i > _cellEndIndex + 1 && - row.cells[i].columnSpan > 1; + row.cells[i].columnSpan > 1; if (!cancelSpans) { for (int j = 1; j < row.cells[i].columnSpan; j++) { PdfGridCellHelper.getHelper(row.cells[i + j]).isCellMergeContinue = @@ -1401,12 +1509,13 @@ class PdfGridLayouter extends ElementLayouter { } } PdfSize size = PdfSize( - _grid!.columns[i].width, - _newheight > 0.0 - ? _newheight - : _currentBounds.height < _currentPageBounds.height - ? _currentBounds.height - : _currentPageBounds.height); + _grid!.columns[i].width, + _newheight > 0.0 + ? _newheight + : _currentBounds.height < _currentPageBounds.height + ? _currentBounds.height + : _currentPageBounds.height, + ); if (size.width == 0) { size = PdfSize(row.cells[i].width, size.height); } @@ -1416,15 +1525,16 @@ class PdfGridLayouter extends ElementLayouter { } PdfGridCellStyle cellstyle = row.cells[i].style; final Map cellLayoutResult = _raiseBeforeCellLayout( - _currentGraphics, - PdfGridRowHelper.getHelper(row).isHeaderRow - ? _currentHeaderRowIndex - : _currentRowIndex, - i, - PdfRectangle(location.x, location.y, size.width, size.height), - row.cells[i].value is String ? row.cells[i].value.toString() : '', - cellstyle, - PdfGridRowHelper.getHelper(row).isHeaderRow); + _currentGraphics, + PdfGridRowHelper.getHelper(row).isHeaderRow + ? _currentHeaderRowIndex + : _currentRowIndex, + i, + PdfRectangle(location.x, location.y, size.width, size.height), + row.cells[i].value is String ? row.cells[i].value.toString() : '', + cellstyle, + PdfGridRowHelper.getHelper(row).isHeaderRow, + ); cellstyle = cellLayoutResult['style'] as PdfGridCellStyle; final PdfGridBeginCellLayoutArgs? bclArgs = cellLayoutResult['args'] as PdfGridBeginCellLayoutArgs?; @@ -1433,17 +1543,19 @@ class PdfGridLayouter extends ElementLayouter { PdfStringLayoutResult? stringResult; if (!skipcell) { stringResult = PdfGridCellHelper.getHelper(row.cells[i]).draw( - _currentGraphics, - PdfRectangle(location.x, location.y, size.width, size.height), - cancelSpans); + _currentGraphics, + PdfRectangle(location.x, location.y, size.width, size.height), + cancelSpans, + ); } if (PdfGridRowHelper.getHelper(row).rowBreakHeight > 0.0) { if (stringResult != null) { PdfGridCellHelper.getHelper(row.cells[i]).finished = false; PdfGridCellHelper.getHelper(row.cells[i]).remainingString = stringResult.remainder ?? ''; - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row).grid) - .isChildGrid!) { + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row).grid, + ).isChildGrid!) { PdfGridRowHelper.getHelper(row).rowBreakHeight = height - stringResult.size.height; } @@ -1451,32 +1563,36 @@ class PdfGridLayouter extends ElementLayouter { PdfGridCellHelper.getHelper(row.cells[i]).finished = false; } } - result.isFinish = (!result.isFinish) - ? result.isFinish - : PdfGridCellHelper.getHelper(row.cells[i]).finished; + result.isFinish = + (!result.isFinish) + ? result.isFinish + : PdfGridCellHelper.getHelper(row.cells[i]).finished; if (!cancelSpans) { _raiseAfterCellLayout( - _currentGraphics, - _currentRowIndex, - i, - PdfRectangle(location.x, location.y, size.width, size.height), - (row.cells[i].value is String) ? row.cells[i].value.toString() : '', - row.cells[i].style, - PdfGridRowHelper.getHelper(row).isHeaderRow); + _currentGraphics, + _currentRowIndex, + i, + PdfRectangle(location.x, location.y, size.width, size.height), + (row.cells[i].value is String) ? row.cells[i].value.toString() : '', + row.cells[i].style, + PdfGridRowHelper.getHelper(row).isHeaderRow, + ); } if (row.cells[i].value is PdfGrid) { final PdfGrid grid = row.cells[i].value as PdfGrid; _rowBreakPageHeightCellIndex = i; PdfGridCellHelper.getHelper(row.cells[i]).pageCount = PdfGridHelper.getHelper(grid).listOfNavigatePages.length; - for (int i = 0; - i < PdfGridHelper.getHelper(grid).listOfNavigatePages.length; - i++) { + for ( + int i = 0; + i < PdfGridHelper.getHelper(grid).listOfNavigatePages.length; + i++ + ) { final int pageIndex = PdfGridHelper.getHelper(grid).listOfNavigatePages[i]; - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(pageIndex)) { + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(pageIndex)) { PdfGridHelper.getHelper(_grid!).listOfNavigatePages.add(pageIndex); } } @@ -1492,8 +1608,12 @@ class PdfGridLayouter extends ElementLayouter { } _currentBounds.y = _currentBounds.y + (_newheight > 0.0 ? _newheight : height); - result.bounds = - PdfRectangle(result.bounds.x, result.bounds.y, location.x, location.y); + result.bounds = PdfRectangle( + result.bounds.x, + result.bounds.y, + location.x, + location.y, + ); return result; } @@ -1528,9 +1648,11 @@ class PdfGridLayouter extends ElementLayouter { PdfPageCollectionHelper.getHelper(document!.pages).remove(page); } for (int i = 0; i < layoutedPages.length; i++) { - for (int j = i; - j < layoutedPages.length; - j += layoutedPages.length ~/ _columnRanges!.length) { + for ( + int j = i; + j < layoutedPages.length; + j += layoutedPages.length ~/ _columnRanges!.length + ) { final PdfPage page = pages[j]!; if (document!.pages.indexOf(page) == -1) { PdfPageCollectionHelper.getHelper(document.pages).addPage(page); @@ -1586,8 +1708,9 @@ class PdfGridLayouter extends ElementLayouter { PdfPage? _getNextPage(PdfLayoutFormat format) { final PdfSection section = PdfPageHelper.getHelper(_currentPage!).section!; PdfPage? nextPage; - final int index = - PdfSectionHelper.getHelper(section).indexOf(_currentPage!); + final int index = PdfSectionHelper.getHelper( + section, + ).indexOf(_currentPage!); if (PdfPageHelper.getHelper(_currentPage!).document!.pages.count > 1 && _hType == PdfHorizontalOverflowType.nextPage && flag && @@ -1605,17 +1728,22 @@ class PdfGridLayouter extends ElementLayouter { nextPage = PdfSectionHelper.getHelper(section).getPageByIndex(index + 1); } _currentGraphics = nextPage!.graphics; - final int pageindex = PdfSectionHelper.getHelper(PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - .section!) - .indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(pageindex)) { + final int pageindex = PdfSectionHelper.getHelper( + PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).section!, + ).indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!); + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(pageindex)) { PdfGridHelper.getHelper(_grid!).listOfNavigatePages.add(pageindex); } - _currentBounds = PdfRectangle(0, 0, _currentGraphics!.clientSize.width, - _currentGraphics!.clientSize.height); + _currentBounds = PdfRectangle( + 0, + 0, + _currentGraphics!.clientSize.width, + _currentGraphics!.clientSize.height, + ); if (PdfRectangle.fromRect(format.paginateBounds) != PdfRectangle.empty) { _currentBounds.x = format.paginateBounds.left; _currentBounds.y = format.paginateBounds.top; @@ -1634,31 +1762,49 @@ class PdfGridLayouter extends ElementLayouter { } } } - final Rect bounds = _isChanged - ? Rect.fromLTWH(_currentLocation.x, _currentLocation.y, - _currentBounds.width, _currentBounds.y - _currentLocation.y) - : Rect.fromLTWH(_startLocation.x, _startLocation.y, - _currentBounds.width, _currentBounds.y - _startLocation.y); + final Rect bounds = + _isChanged + ? Rect.fromLTWH( + _currentLocation.x, + _currentLocation.y, + _currentBounds.width, + _currentBounds.y - _currentLocation.y, + ) + : Rect.fromLTWH( + _startLocation.x, + _startLocation.y, + _currentBounds.width, + _currentBounds.y - _startLocation.y, + ); return PdfLayoutResultHelper.load(_currentPage!, bounds); } Map _raiseBeforePageLayout( - PdfPage? currentPage, Rect currentBounds, int? currentRow) { + PdfPage? currentPage, + Rect currentBounds, + int? currentRow, + ) { bool cancel = false; if (PdfLayoutElementHelper.getHelper(element!).raiseBeginPageLayout) { final PdfGridBeginPageLayoutArgs args = PdfGridBeginPageLayoutArgsHelper.load( - currentBounds, currentPage!, currentRow); + currentBounds, + currentPage!, + currentRow, + ); PdfLayoutElementHelper.getHelper(element!).onBeginPageLayout(args); if (PdfRectangle.fromRect(currentBounds) != PdfRectangle.fromRect(args.bounds)) { _isChanged = true; _currentLocation = PdfPoint(args.bounds.left, args.bounds.top); - PdfGridHelper.getHelper(_grid!).measureColumnsWidth(PdfRectangle( + PdfGridHelper.getHelper(_grid!).measureColumnsWidth( + PdfRectangle( args.bounds.left, args.bounds.top, args.bounds.width + args.bounds.left, - args.bounds.height)); + args.bounds.height, + ), + ); } cancel = args.cancel; currentBounds = args.bounds; @@ -1667,13 +1813,14 @@ class PdfGridLayouter extends ElementLayouter { return { 'cancel': cancel, 'currentBounds': currentBounds, - 'currentRow': currentRow + 'currentRow': currentRow, }; } PdfGridEndPageLayoutArgs _raisePageLayouted(PdfLayoutResult result) { - final PdfGridEndPageLayoutArgs args = - PdfGridEndPageLayoutArgsHelper.load(result); + final PdfGridEndPageLayoutArgs args = PdfGridEndPageLayoutArgsHelper.load( + result, + ); if (PdfLayoutElementHelper.getHelper(element!).raisePageLayouted) { PdfLayoutElementHelper.getHelper(element!).onEndPageLayout(args); } @@ -1681,17 +1828,25 @@ class PdfGridLayouter extends ElementLayouter { } Map _raiseBeforeCellLayout( - PdfGraphics? graphics, - int rowIndex, - int cellIndex, - PdfRectangle bounds, - String value, - PdfGridCellStyle? style, - bool isHeaderRow) { + PdfGraphics? graphics, + int rowIndex, + int cellIndex, + PdfRectangle bounds, + String value, + PdfGridCellStyle? style, + bool isHeaderRow, + ) { PdfGridBeginCellLayoutArgs? args; if (PdfGridHelper.getHelper(_grid!).raiseBeginCellLayout) { args = PdfGridBeginCellLayoutArgsHelper.load( - graphics!, rowIndex, cellIndex, bounds, value, style, isHeaderRow); + graphics!, + rowIndex, + cellIndex, + bounds, + value, + style, + isHeaderRow, + ); PdfGridHelper.getHelper(_grid!).onBeginCellLayout(args); style = args.style; } @@ -1699,17 +1854,25 @@ class PdfGridLayouter extends ElementLayouter { } void _raiseAfterCellLayout( - PdfGraphics? graphics, - int rowIndex, - int cellIndex, - PdfRectangle bounds, - String value, - PdfGridCellStyle? cellstyle, - bool isHeaderRow) { + PdfGraphics? graphics, + int rowIndex, + int cellIndex, + PdfRectangle bounds, + String value, + PdfGridCellStyle? cellstyle, + bool isHeaderRow, + ) { PdfGridEndCellLayoutArgs args; if (PdfGridHelper.getHelper(_grid!).raiseEndCellLayout) { - args = PdfGridEndCellLayoutArgsHelper.load(graphics!, rowIndex, cellIndex, - bounds, value, cellstyle, isHeaderRow); + args = PdfGridEndCellLayoutArgsHelper.load( + graphics!, + rowIndex, + cellIndex, + bounds, + value, + cellstyle, + isHeaderRow, + ); PdfGridHelper.getHelper(_grid!).onEndCellLayout(args); } } @@ -1738,40 +1901,44 @@ class PdfGridLayouter extends ElementLayouter { _currentGraphics = _currentPage!.graphics; } if (PdfGraphicsHelper.getHelper(_currentGraphics!).layer != null) { - final int index = !PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - .isLoadedPage - ? PdfSectionHelper.getHelper(PdfPageHelper.getHelper( - PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - .section!) - .indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!) - : PdfGraphicsHelper.getHelper(_currentGraphics!) - .page! - .defaultLayerIndex; - if (!PdfGridHelper.getHelper(_grid!) - .listOfNavigatePages - .contains(index)) { + final int index = + !PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).isLoadedPage + ? PdfSectionHelper.getHelper( + PdfPageHelper.getHelper( + PdfGraphicsHelper.getHelper(_currentGraphics!).page!, + ).section!, + ).indexOf(PdfGraphicsHelper.getHelper(_currentGraphics!).page!) + : PdfGraphicsHelper.getHelper( + _currentGraphics!, + ).page!.defaultLayerIndex; + if (!PdfGridHelper.getHelper( + _grid!, + ).listOfNavigatePages.contains(index)) { PdfGridHelper.getHelper(_grid!).listOfNavigatePages.add(index); } } _currentBounds = PdfRectangle( - param.bounds!.x, - param.bounds!.y, - format.breakType == PdfLayoutBreakType.fitColumnsToPage - ? PdfGridColumnCollectionHelper.getHelper(_grid!.columns) - .columnWidth - : _currentGraphics!.clientSize.width, - _currentGraphics!.clientSize.height); + param.bounds!.x, + param.bounds!.y, + format.breakType == PdfLayoutBreakType.fitColumnsToPage + ? PdfGridColumnCollectionHelper.getHelper(_grid!.columns).columnWidth + : _currentGraphics!.clientSize.width, + _currentGraphics!.clientSize.height, + ); if (_grid!.rows.count != 0) { - _currentBounds.width = (param.bounds!.width > 0) - ? param.bounds!.width - : (_currentBounds.width - - _grid!.rows[0].cells[0].style.borders.left.width / 2); + _currentBounds.width = + (param.bounds!.width > 0) + ? param.bounds!.width + : (_currentBounds.width - + _grid!.rows[0].cells[0].style.borders.left.width / 2); } else if (_grid!.headers.count != 0) { - _currentBounds.width = (param.bounds!.width > 0) - ? param.bounds!.width - : (_currentBounds.width - - _grid!.headers[0].cells[0].style.borders.left.width / 2); + _currentBounds.width = + (param.bounds!.width > 0) + ? param.bounds!.width + : (_currentBounds.width - + _grid!.headers[0].cells[0].style.borders.left.width / 2); } _startLocation = param.bounds!.location; if (_grid!.style.allowHorizontalOverflow && @@ -1812,6 +1979,7 @@ class PdfGridLayouter extends ElementLayouter { } } } + userHeight = _startLocation.y; return _layoutOnPage(param); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid.dart index 58b00f4af..b5052d403 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid.dart @@ -528,22 +528,27 @@ class PdfGrid extends PdfLayoutElement { /// document.dispose(); /// ``` @override - PdfLayoutResult? draw( - {Rect? bounds, - PdfLayoutFormat? format, - PdfGraphics? graphics, - PdfPage? page}) { + PdfLayoutResult? draw({ + Rect? bounds, + PdfLayoutFormat? format, + PdfGraphics? graphics, + PdfPage? page, + }) { final PdfRectangle rectangle = bounds != null ? PdfRectangle.fromRect(bounds) : PdfRectangle.empty; - _helper.initialWidth = rectangle.width == 0 - ? page != null - ? page.getClientSize().width - : graphics!.clientSize.width - : rectangle.width; + _helper.initialWidth = + rectangle.width == 0 + ? page != null + ? page.getClientSize().width + : graphics!.clientSize.width + : rectangle.width; _helper.isWidthSet = true; if (page != null) { - final PdfLayoutResult? result = - super.draw(page: page, bounds: bounds, format: format); + final PdfLayoutResult? result = super.draw( + page: page, + bounds: bounds, + format: format, + ); _helper.isComplete = true; return result; } else if (graphics != null) { @@ -591,13 +596,17 @@ class PdfGrid extends PdfLayoutElement { /// //Dispose the document. /// document.dispose(); /// ``` - void applyBuiltInStyle(PdfGridBuiltInStyle gridStyle, - {PdfGridBuiltInStyleSettings? settings}) { + void applyBuiltInStyle( + PdfGridBuiltInStyle gridStyle, { + PdfGridBuiltInStyleSettings? settings, + }) { _intializeBuiltInStyle(gridStyle, settings: settings); } - void _intializeBuiltInStyle(PdfGridBuiltInStyle gridStyle, - {PdfGridBuiltInStyleSettings? settings}) { + void _intializeBuiltInStyle( + PdfGridBuiltInStyle gridStyle, { + PdfGridBuiltInStyleSettings? settings, + }) { if (settings != null) { _headerRow = settings.applyStyleForHeaderRow; _totalRow = settings.applyStyleForLastRow; @@ -619,17 +628,21 @@ class PdfGrid extends PdfLayoutElement { _boldFontCache ??= {}; if (font is PdfStandardFont) { final PdfStandardFont standardFont = font; - return PdfStandardFont(standardFont.fontFamily, font.size, - style: PdfFontStyle.bold); + return PdfStandardFont( + standardFont.fontFamily, + font.size, + style: PdfFontStyle.bold, + ); } else { if (_boldFontCache!.containsKey(font)) { return _boldFontCache![font as PdfTrueTypeFont]; } else { final PdfTrueTypeFont trueTypeFont = font as PdfTrueTypeFont; final PdfFont boldStyleFont = PdfTrueTypeFont( - PdfTrueTypeFontHelper.getHelper(trueTypeFont).fontInternal.fontData, - font.size, - style: PdfFontStyle.bold); + PdfTrueTypeFontHelper.getHelper(trueTypeFont).fontInternal.fontData, + font.size, + style: PdfFontStyle.bold, + ); _boldFontCache![font] = boldStyleFont as PdfTrueTypeFont; return boldStyleFont; } @@ -640,17 +653,21 @@ class PdfGrid extends PdfLayoutElement { _regularFontCache ??= {}; if (font is PdfStandardFont) { final PdfStandardFont standardFont = font; - return PdfStandardFont(standardFont.fontFamily, font.size, - style: PdfFontStyle.regular); + return PdfStandardFont( + standardFont.fontFamily, + font.size, + style: PdfFontStyle.regular, + ); } else { if (_regularFontCache!.containsKey(font)) { return _regularFontCache![font as PdfTrueTypeFont]; } else { final PdfTrueTypeFont trueTypeFont = font as PdfTrueTypeFont; final PdfFont ttfFont = PdfTrueTypeFont( - PdfTrueTypeFontHelper.getHelper(trueTypeFont).fontInternal.fontData, - font.size, - style: PdfFontStyle.regular); + PdfTrueTypeFontHelper.getHelper(trueTypeFont).fontInternal.fontData, + font.size, + style: PdfFontStyle.regular, + ); _regularFontCache![font] = ttfFont as PdfTrueTypeFont; return ttfFont; } @@ -661,17 +678,21 @@ class PdfGrid extends PdfLayoutElement { _italicFontCache ??= {}; if (font is PdfStandardFont) { final PdfStandardFont standardFont = font; - return PdfStandardFont(standardFont.fontFamily, font.size, - style: PdfFontStyle.italic); + return PdfStandardFont( + standardFont.fontFamily, + font.size, + style: PdfFontStyle.italic, + ); } else { if (_italicFontCache!.containsKey(font)) { return _italicFontCache![font! as PdfTrueTypeFont]; } else { final PdfTrueTypeFont trueTypeFont = font! as PdfTrueTypeFont; final PdfFont italicStyleFont = PdfTrueTypeFont( - PdfTrueTypeFontHelper.getHelper(trueTypeFont).fontInternal.fontData, - font.size, - style: PdfFontStyle.italic); + PdfTrueTypeFontHelper.getHelper(trueTypeFont).fontInternal.fontData, + font.size, + style: PdfFontStyle.italic, + ); _italicFontCache![font as PdfTrueTypeFont] = italicStyleFont as PdfTrueTypeFont; return italicStyleFont; @@ -690,7 +711,10 @@ class PdfGrid extends PdfLayoutElement { } PdfBrush? _applyBandedColStyle( - bool firstColumn, PdfColor backColor, int cellIndex) { + bool firstColumn, + PdfColor backColor, + int cellIndex, + ) { PdfBrush? backBrush; if (firstColumn) { if (cellIndex.isEven) { @@ -705,7 +729,10 @@ class PdfGrid extends PdfLayoutElement { } PdfBrush? _applyBandedRowStyle( - bool headerRow, PdfColor backColor, int rowIndex) { + bool headerRow, + PdfColor backColor, + int rowIndex, + ) { PdfBrush? backBrush; if (headerRow) { if (rowIndex.isOdd) { @@ -750,15 +777,19 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = borderPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); cell.style.borders.all = borderPen; if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; @@ -770,7 +801,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -783,7 +815,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = backBrush; } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -801,7 +834,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = borderPen; if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -810,28 +844,44 @@ class PdfGrid extends PdfLayoutElement { } if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); - } - final PdfFont font = cell.style.font ?? + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); + } + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -840,7 +890,8 @@ class PdfGrid extends PdfLayoutElement { } if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -848,8 +899,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.top = PdfPen(borderColor); if (_bandedColumn) { if (!(_lastColumn && j == row.cells.count)) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } } } @@ -873,7 +927,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = borderPen; } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -891,7 +946,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.bottom = borderPen; } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -899,7 +955,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.left = emptyPen; } if (_lastColumn && j == row.cells.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -929,7 +986,8 @@ class PdfGrid extends PdfLayoutElement { } if (i == rows.count && _totalRow) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -942,7 +1000,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -954,7 +1013,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -980,11 +1040,15 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = whitePen; if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1012,7 +1076,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1024,7 +1089,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = borderPen; } if (_lastColumn && j == row.cells.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1054,11 +1120,17 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = whitePen; if (_bandedRow && _bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; } @@ -1067,8 +1139,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; @@ -1079,8 +1154,11 @@ class PdfGrid extends PdfLayoutElement { } } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; } @@ -1094,7 +1172,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = whitePen; } cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1104,8 +1183,11 @@ class PdfGrid extends PdfLayoutElement { cell.value = cellvalue.toUpperCase(); } if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; @@ -1115,7 +1197,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1129,7 +1212,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1141,8 +1225,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = null; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } cell.style.borders.all = whitePen; } else if (_bandedColumn) { @@ -1168,11 +1255,15 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = whitePen; if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1182,8 +1273,11 @@ class PdfGrid extends PdfLayoutElement { cell.value = cellvalue.toUpperCase(); } if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; @@ -1195,7 +1289,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1212,7 +1307,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = backBrush; } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1235,7 +1331,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = whitePen; if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1247,28 +1344,44 @@ class PdfGrid extends PdfLayoutElement { } } if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); - } - final PdfFont font = cell.style.font ?? + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); + } + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1282,7 +1395,8 @@ class PdfGrid extends PdfLayoutElement { } if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1297,8 +1411,11 @@ class PdfGrid extends PdfLayoutElement { } if (_bandedColumn) { if (!(_lastColumn && j == row.cells.count)) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } } } @@ -1319,7 +1436,8 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = whitePen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1331,8 +1449,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; @@ -1354,7 +1475,8 @@ class PdfGrid extends PdfLayoutElement { if (_firstColumn && j == 1) { cell.style.borders.all = whitePen; cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1364,7 +1486,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = borderPen; } if (_lastColumn && j == row.cells.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1384,10 +1507,16 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = whitePen; if (_bandedRow && _bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; @@ -1397,8 +1526,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; @@ -1408,8 +1540,11 @@ class PdfGrid extends PdfLayoutElement { } } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (_firstColumn && j == 2) { cell.style.borders.left = borderPen; } else { @@ -1421,7 +1556,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = PdfPen(PdfColor.empty); cell.style.backgroundBrush = null; cell.style.borders.top = borderPen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1433,7 +1569,8 @@ class PdfGrid extends PdfLayoutElement { if (!(_totalRow && i == rows.count)) { cell.style.borders.all = whitePen; cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1445,7 +1582,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1473,21 +1611,24 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = borderPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); } else { if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); } if (_lastColumn && j == row.cells.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1509,7 +1650,8 @@ class PdfGrid extends PdfLayoutElement { if (_totalRow) { if (i == rows.count) { cell.style.borders.top = PdfPen(headerBottomColor); - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1518,7 +1660,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1527,7 +1670,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1557,24 +1701,26 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = emptyPen; } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); cell.style.borders.all = PdfPen(PdfColor.empty); if (PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(cell).row!) - .grid - .style - .cellSpacing > + PdfGridCellHelper.getHelper(cell).row!, + ).grid.style.cellSpacing > 0) { cell.style.borders.bottom = headerBorder; } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (j == 1) { cell.style.borders.left = backColorPen; @@ -1596,7 +1742,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1617,7 +1764,8 @@ class PdfGrid extends PdfLayoutElement { } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1639,10 +1787,16 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = emptyPen; } if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); - cell.style.backgroundBrush ??= - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); + cell.style.backgroundBrush ??= _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (j == 1) { cell.style.borders.left = backColorPen; @@ -1652,8 +1806,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { if (j == 1) { @@ -1664,8 +1821,11 @@ class PdfGrid extends PdfLayoutElement { } } if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (j == 1) { cell.style.borders.left = backColorPen; @@ -1676,7 +1836,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_totalRow && i == rows.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1687,7 +1848,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1696,15 +1858,19 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); cell.style.backgroundBrush = null; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush == null) { cell.style.borders.right = emptyPen; } @@ -1734,7 +1900,8 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = borderPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1742,8 +1909,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = whitePen; } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { if (i % 2 != 0) { @@ -1753,7 +1923,8 @@ class PdfGrid extends PdfLayoutElement { if (_firstColumn && j == 1) { cell.style.backgroundBrush = null; cell.style.borders.all = whitePen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1762,7 +1933,8 @@ class PdfGrid extends PdfLayoutElement { if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; cell.style.borders.all = whitePen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1780,23 +1952,36 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = borderPen; if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } } if (_totalRow && i == rows.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1808,7 +1993,8 @@ class PdfGrid extends PdfLayoutElement { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; cell.style.borders.all = whitePen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1824,7 +2010,8 @@ class PdfGrid extends PdfLayoutElement { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; cell.style.borders.all = whitePen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1841,7 +2028,10 @@ class PdfGrid extends PdfLayoutElement { } void _applyGridTable4( - PdfColor borderColor, PdfColor backColor, PdfColor headerBackColor) { + PdfColor borderColor, + PdfColor backColor, + PdfColor headerBackColor, + ) { final PdfPen borderPen = PdfPen(borderColor, width: 0.5); final PdfBrush backBrush = PdfSolidBrush(backColor); final PdfPen headerBackColorPen = PdfPen(headerBackColor, width: 0.5); @@ -1852,7 +2042,8 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = borderPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1862,8 +2053,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = PdfSolidBrush(headerBackColor); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { if (i % 2 != 0) { @@ -1871,7 +2065,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1880,10 +2075,14 @@ class PdfGrid extends PdfLayoutElement { if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1901,7 +2100,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = borderPen; if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1910,28 +2110,44 @@ class PdfGrid extends PdfLayoutElement { } if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } } if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1942,11 +2158,15 @@ class PdfGrid extends PdfLayoutElement { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1965,8 +2185,11 @@ class PdfGrid extends PdfLayoutElement { } } - void _applyGridTable5Dark(PdfColor headerBackColor, PdfColor oddRowBackColor, - PdfColor evenRowBackColor) { + void _applyGridTable5Dark( + PdfColor headerBackColor, + PdfColor oddRowBackColor, + PdfColor evenRowBackColor, + ) { final PdfPen whitePen = PdfPen(PdfColor(255, 255, 255), width: 0.5); final PdfBrush evenRowBrush = PdfSolidBrush(evenRowBackColor); final PdfBrush oddRowBrush = PdfSolidBrush(oddRowBackColor); @@ -1981,7 +2204,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = whitePen; cell.style.backgroundBrush = evenRowBrush; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -1996,8 +2220,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, oddRowBackColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + oddRowBackColor, + j, + ); cell.style.backgroundBrush ??= evenRowBrush; } @@ -2009,7 +2236,8 @@ class PdfGrid extends PdfLayoutElement { if ((_firstColumn && j == 1) || (_lastColumn && j == row.cells.count)) { cell.style.backgroundBrush = headerBrush; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2029,30 +2257,43 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = evenRowBrush; if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, oddRowBackColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + oddRowBackColor, + j, + ); if (cell.style.backgroundBrush == null) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, oddRowBackColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + oddRowBackColor, + i, + ); cell.style.backgroundBrush ??= evenRowBrush; } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, oddRowBackColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + oddRowBackColor, + j, + ); cell.style.backgroundBrush ??= evenRowBrush; } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, oddRowBackColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + oddRowBackColor, + i, + ); cell.style.backgroundBrush ??= evenRowBrush; } } if (_totalRow && i == rows.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2070,7 +2311,8 @@ class PdfGrid extends PdfLayoutElement { if ((_firstColumn && j == 1) || (_lastColumn && j == row.cells.count)) { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = headerBrush; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2083,7 +2325,10 @@ class PdfGrid extends PdfLayoutElement { } void _applyGridTable6Colorful( - PdfColor borderColor, PdfColor backColor, PdfColor textColor) { + PdfColor borderColor, + PdfColor backColor, + PdfColor textColor, + ) { final PdfPen borderPen = PdfPen(borderColor, width: 0.5); final PdfBrush backBrush = PdfSolidBrush(backColor); final PdfPen headerBottomPen = PdfPen(borderColor); @@ -2096,11 +2341,15 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = borderPen; cell.style.textBrush = textBrush; if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2115,7 +2364,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2126,7 +2376,8 @@ class PdfGrid extends PdfLayoutElement { if (i % 2 != 0) { cell.style.backgroundBrush = backBrush; } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2145,28 +2396,44 @@ class PdfGrid extends PdfLayoutElement { cell.style.textBrush = textBrush; if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } } if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; if (_bandedColumn && (!(_lastColumn && j == row.cells.count))) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - } - final PdfFont font = cell.style.font ?? + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + } + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2175,7 +2442,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2186,10 +2454,14 @@ class PdfGrid extends PdfLayoutElement { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); - } - final PdfFont font = cell.style.font ?? + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); + } + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2205,7 +2477,10 @@ class PdfGrid extends PdfLayoutElement { } void _applyGridTable7Colorful( - PdfColor borderColor, PdfColor backColor, PdfColor textColor) { + PdfColor borderColor, + PdfColor backColor, + PdfColor textColor, + ) { final PdfPen borderPen = PdfPen(borderColor, width: 0.5); final PdfBrush backBrush = PdfSolidBrush(backColor); final PdfBrush textBrush = PdfSolidBrush(textColor); @@ -2219,7 +2494,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.textBrush = textBrush; cell.style.borders.all = borderPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2227,8 +2503,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = PdfPen(PdfColor(255, 255, 255)); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { @@ -2239,7 +2518,8 @@ class PdfGrid extends PdfLayoutElement { if (_firstColumn && j == 1) { cell.style.backgroundBrush = null; cell.style.borders.all = whitePen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2248,7 +2528,8 @@ class PdfGrid extends PdfLayoutElement { if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; cell.style.borders.all = whitePen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2267,24 +2548,37 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = borderPen; cell.style.textBrush = textBrush; if (_bandedRow && _bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); } } if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2298,7 +2592,8 @@ class PdfGrid extends PdfLayoutElement { if (i == 1 && _headerRow) { cell.style.borders.top = borderPen; } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2316,7 +2611,8 @@ class PdfGrid extends PdfLayoutElement { if (i == 1 && _headerRow) { cell.style.borders.top = borderPen; } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2342,7 +2638,8 @@ class PdfGrid extends PdfLayoutElement { final PdfGridCell cell = row.cells[j - 1]; cell.style.borders.all = emptyPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2353,8 +2650,11 @@ class PdfGrid extends PdfLayoutElement { } if (_bandedColumn) { if (_lastColumn && j == rows.count) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (cell.style.backgroundBrush != null) { cell.style.borders.all = backBrushPen; @@ -2366,8 +2666,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backBrushPen; } @@ -2381,7 +2684,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2393,7 +2697,8 @@ class PdfGrid extends PdfLayoutElement { if (_bandedRow && i % 2 != 0) { cell.style.backgroundBrush = backBrush; } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2411,25 +2716,37 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = emptyPen; if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backBrushPen; } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backBrushPen; } } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backBrushPen; } @@ -2437,7 +2754,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2451,10 +2769,14 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = null; cell.style.borders.all = emptyPen; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); - } - final PdfFont font = cell.style.font ?? + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); + } + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2464,15 +2786,19 @@ class PdfGrid extends PdfLayoutElement { if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; cell.style.borders.all = emptyPen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); if (_bandedColumn) { if (!(_lastColumn && j == row.cells.count)) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (cell.style.backgroundBrush != null) { cell.style.borders.all = backBrushPen; @@ -2504,14 +2830,18 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.bottom = borderPen; cell.style.borders.top = borderPen; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; } @@ -2522,8 +2852,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.right = backColorPen; cell.style.borders.left = backColorPen; @@ -2537,7 +2870,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2554,7 +2888,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = backColorPen; } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2573,27 +2908,39 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.bottom = borderPen; cell.style.borders.top = borderPen; if (_bandedRow && _bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.right = backColorPen; cell.style.borders.left = backColorPen; } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.right = backColorPen; cell.style.borders.left = backColorPen; } } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.left = backColorPen; cell.style.borders.right = backColorPen; @@ -2606,7 +2953,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.top = borderPen; cell.style.borders.bottom = borderPen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2614,8 +2962,11 @@ class PdfGrid extends PdfLayoutElement { if (_bandedColumn) { if (!(j == row.cells.count && _lastColumn)) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (cell.style.backgroundBrush != null) { cell.style.borders.right = backColorPen; @@ -2625,7 +2976,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2638,13 +2990,17 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.left = emptyPen; cell.style.borders.right = emptyPen; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.right = backColorPen; } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2672,7 +3028,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = backColorPen; } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2682,14 +3039,16 @@ class PdfGrid extends PdfLayoutElement { cell.style.textBrush = PdfSolidBrush(PdfColor(255, 255, 255)); } else { if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); } if (_lastColumn && j == row.cells.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2726,7 +3085,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.top = backColorPen; } if (_totalRow && i == rows.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2735,7 +3095,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2744,7 +3105,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2756,7 +3118,10 @@ class PdfGrid extends PdfLayoutElement { } void _applyListTable4( - PdfColor borderColor, PdfColor headerBackColor, PdfColor bandRowColor) { + PdfColor borderColor, + PdfColor headerBackColor, + PdfColor bandRowColor, + ) { final PdfPen borderColorPen = PdfPen(borderColor, width: 0.5); final PdfBrush headerBrush = PdfSolidBrush(headerBackColor); final PdfBrush bandRowBrush = PdfSolidBrush(bandRowColor); @@ -2775,7 +3140,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = borderColorPen; } if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2785,8 +3151,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.textBrush = PdfSolidBrush(PdfColor(255, 255, 255)); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, bandRowColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + bandRowColor, + j, + ); } if (_bandedRow) { if (i % 2 != 0) { @@ -2794,7 +3163,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2806,7 +3176,8 @@ class PdfGrid extends PdfLayoutElement { if (_bandedRow && i % 2 != 0) { cell.style.backgroundBrush = bandRowBrush; } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2829,23 +3200,36 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.right = borderColorPen; } if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, bandRowColor, j); - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, bandRowColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + bandRowColor, + j, + ); + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + bandRowColor, + i, + ); } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, bandRowColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + bandRowColor, + j, + ); } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, bandRowColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + bandRowColor, + i, + ); } } if (_totalRow && i == rows.count) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2853,14 +3237,18 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.top = PdfPen(borderColor); if (_bandedColumn) { if (!(_lastColumn && j == rows.count)) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, bandRowColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + bandRowColor, + j, + ); } } } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2870,9 +3258,13 @@ class PdfGrid extends PdfLayoutElement { if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, bandRowColor, i); - final PdfFont font = cell.style.font ?? + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + bandRowColor, + i, + ); + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2902,15 +3294,18 @@ class PdfGrid extends PdfLayoutElement { cell.style.textBrush = whiteBrush; cell.style.backgroundBrush = backColorBrush; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); cell.style.backgroundBrush = backColorBrush; cell.style.textBrush = whiteBrush; - cell.style.borders.bottom = - PdfPen(PdfColor(255, 255, 255), width: 2); + cell.style.borders.bottom = PdfPen( + PdfColor(255, 255, 255), + width: 2, + ); if (_bandedColumn) { if (j > 1) { cell.style.borders.left = whitePen; @@ -2919,7 +3314,8 @@ class PdfGrid extends PdfLayoutElement { } else { if (_firstColumn) { if (j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2937,7 +3333,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.top = whitePen; } if (_lastColumn && j == row.cells.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2959,7 +3356,8 @@ class PdfGrid extends PdfLayoutElement { if (_firstColumn) { if (!(_totalRow && i == rows.count)) { if (j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2978,7 +3376,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.top = whitePen; } if (_totalRow && i == rows.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -2995,7 +3394,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3008,7 +3408,10 @@ class PdfGrid extends PdfLayoutElement { } void _applyListTable6Colorful( - PdfColor borderColor, PdfColor backColor, PdfColor textColor) { + PdfColor borderColor, + PdfColor backColor, + PdfColor textColor, + ) { final PdfBrush backColorBrush = PdfSolidBrush(backColor); final PdfPen borderColorPen = PdfPen(borderColor, width: 0.5); final PdfPen backColorPen = PdfPen(backColor, width: 0.5); @@ -3026,8 +3429,11 @@ class PdfGrid extends PdfLayoutElement { if (_headerRow) { if (_bandedColumn) { if (!(_lastColumn && j == row.cells.count)) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); } if (cell.style.backgroundBrush != null) { cell.style.borders.left = backColorPen; @@ -3035,7 +3441,8 @@ class PdfGrid extends PdfLayoutElement { } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3043,8 +3450,11 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.bottom = borderColorPen; } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { if (i == 1 && _headerRow) { cell.style.borders.top = borderColorPen; @@ -3065,7 +3475,8 @@ class PdfGrid extends PdfLayoutElement { } } if (_firstColumn && j == 1) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3080,7 +3491,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = backColorBrush; } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3106,11 +3518,17 @@ class PdfGrid extends PdfLayoutElement { } if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { if (j == 1) { cell.style.borders.left = backColorPen; @@ -3123,8 +3541,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.left = backColorPen; cell.style.borders.right = backColorPen; @@ -3134,8 +3555,11 @@ class PdfGrid extends PdfLayoutElement { } } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (j == 1) { cell.style.borders.left = backColorPen; } else if (j == row.cells.count) { @@ -3148,7 +3572,8 @@ class PdfGrid extends PdfLayoutElement { } if (_firstColumn && j == 1) { if (!(_totalRow && i == rows.count)) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3161,14 +3586,18 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.left = emptyPen; cell.style.borders.right = emptyPen; if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.right = backColorPen; } } - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3184,15 +3613,19 @@ class PdfGrid extends PdfLayoutElement { cell.style.backgroundBrush = null; cell.style.borders.left = emptyPen; cell.style.borders.right = emptyPen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; cell.style.font = _changeFontStyle(font); cell.style.borders.top = PdfPen(borderColor); if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; } @@ -3207,7 +3640,10 @@ class PdfGrid extends PdfLayoutElement { } void _applyListTable7Colorful( - PdfColor borderColor, PdfColor backColor, PdfColor textColor) { + PdfColor borderColor, + PdfColor backColor, + PdfColor textColor, + ) { final PdfPen borderPen = PdfPen(borderColor, width: 0.5); final PdfPen emptyPen = PdfPen(PdfColor.empty); final PdfBrush backBrush = PdfSolidBrush(backColor); @@ -3222,7 +3658,8 @@ class PdfGrid extends PdfLayoutElement { cell.style.borders.all = emptyPen; cell.style.textBrush = textBrush; if (_headerRow) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3234,8 +3671,11 @@ class PdfGrid extends PdfLayoutElement { } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backColorPen; } @@ -3249,7 +3689,8 @@ class PdfGrid extends PdfLayoutElement { if (_firstColumn && j == 1) { cell.style.backgroundBrush = null; cell.style.borders.all = emptyPen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3258,7 +3699,8 @@ class PdfGrid extends PdfLayoutElement { } if (_lastColumn && j == row.cells.count) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3283,25 +3725,37 @@ class PdfGrid extends PdfLayoutElement { cell.style.textBrush = textBrush; if (_bandedColumn && _bandedRow) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); - - cell.style.backgroundBrush ??= - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); + + cell.style.backgroundBrush ??= _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backColorPen; } } else { if (_bandedColumn) { - cell.style.backgroundBrush = - _applyBandedColStyle(_firstColumn, backColor, j); + cell.style.backgroundBrush = _applyBandedColStyle( + _firstColumn, + backColor, + j, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backColorPen; } } if (_bandedRow) { - cell.style.backgroundBrush = - _applyBandedRowStyle(_headerRow, backColor, i); + cell.style.backgroundBrush = _applyBandedRowStyle( + _headerRow, + backColor, + i, + ); if (cell.style.backgroundBrush != null) { cell.style.borders.all = backColorPen; } @@ -3311,7 +3765,8 @@ class PdfGrid extends PdfLayoutElement { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; cell.style.borders.all = emptyPen; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3326,7 +3781,8 @@ class PdfGrid extends PdfLayoutElement { } if (_totalRow && i == rows.count) { - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3340,7 +3796,8 @@ class PdfGrid extends PdfLayoutElement { if (_lastColumn && j == row.cells.count) { if (!(_totalRow && i == rows.count)) { cell.style.backgroundBrush = null; - final PdfFont font = cell.style.font ?? + final PdfFont font = + cell.style.font ?? row.style.font ?? PdfGridRowHelper.getHelper(row).grid.style.font ?? _helper.defaultFont; @@ -3474,11 +3931,13 @@ class PdfGridHelper { (cell.columnSpan > 1 || cell.rowSpan > 1)) { if (cell.columnSpan + j > row.cells.count) { throw ArgumentError.value( - 'Invalid span specified at row $j column $i'); + 'Invalid span specified at row $j column $i', + ); } if (cell.rowSpan + i > base.headers.count) { throw ArgumentError.value( - 'Invalid span specified at row $j column $i'); + 'Invalid span specified at row $j column $i', + ); } if (cell.columnSpan > 1 && cell.rowSpan > 1) { colSpan = cell.columnSpan; @@ -3499,20 +3958,24 @@ class PdfGridHelper { while (rowSpan > 1) { currentRowIndex++; PdfGridCellHelper.getHelper( - base.headers[currentRowIndex].cells[j]) - .isRowMergeContinue = true; + base.headers[currentRowIndex].cells[j], + ).isRowMergeContinue = + true; PdfGridCellHelper.getHelper( - base.headers[currentRowIndex].cells[currentCellIndex]) - .isRowMergeContinue = true; + base.headers[currentRowIndex].cells[currentCellIndex], + ).isRowMergeContinue = + true; rowSpan--; while (colSpan > 1) { currentCellIndex++; PdfGridCellHelper.getHelper( - base.headers[currentRowIndex].cells[currentCellIndex]) - .isCellMergeContinue = true; + base.headers[currentRowIndex].cells[currentCellIndex], + ).isCellMergeContinue = + true; PdfGridCellHelper.getHelper( - base.headers[currentRowIndex].cells[currentCellIndex]) - .isRowMergeContinue = true; + base.headers[currentRowIndex].cells[currentCellIndex], + ).isRowMergeContinue = + true; colSpan--; } colSpan = cell.columnSpan; @@ -3533,8 +3996,9 @@ class PdfGridHelper { while (rowSpan > 1) { currentRowIndex++; PdfGridCellHelper.getHelper( - base.headers[currentRowIndex].cells[j]) - .isRowMergeContinue = true; + base.headers[currentRowIndex].cells[j], + ).isRowMergeContinue = + true; rowSpan--; } } @@ -3556,11 +4020,13 @@ class PdfGridHelper { (cell.columnSpan > 1 || cell.rowSpan > 1)) { if (cell.columnSpan + j > row.cells.count) { throw ArgumentError.value( - 'Invalid span specified at row $j column $i'); + 'Invalid span specified at row $j column $i', + ); } if (cell.rowSpan + i > base.rows.count) { throw ArgumentError.value( - 'Invalid span specified at row $j column $i'); + 'Invalid span specified at row $j column $i', + ); } if (cell.columnSpan > 1 && cell.rowSpan > 1) { colSpan = cell.columnSpan; @@ -3582,19 +4048,24 @@ class PdfGridHelper { PdfGridCellHelper.getHelper(base.rows[currentRowIndex].cells[j]) .isRowMergeContinue = true; PdfGridCellHelper.getHelper( - base.rows[currentRowIndex].cells[currentCellIndex]) - .isRowMergeContinue = true; + base.rows[currentRowIndex].cells[currentCellIndex], + ).isRowMergeContinue = + true; rowSpan--; while (colSpan > 1) { currentCellIndex++; PdfGridCellHelper.getHelper( - PdfGridRowHelper.getHelper(base.rows[currentRowIndex]) - .cells![currentCellIndex]) - .isCellMergeContinue = true; + PdfGridRowHelper.getHelper( + base.rows[currentRowIndex], + ).cells![currentCellIndex], + ).isCellMergeContinue = + true; PdfGridCellHelper.getHelper( - PdfGridRowHelper.getHelper(base.rows[currentRowIndex]) - .cells![currentCellIndex]) - .isRowMergeContinue = true; + PdfGridRowHelper.getHelper( + base.rows[currentRowIndex], + ).cells![currentCellIndex], + ).isRowMergeContinue = + true; colSpan--; } colSpan = cell.columnSpan; @@ -3635,10 +4106,11 @@ class PdfGridHelper { for (int i = 0; i < base.headers[0].cells.count; i++) { for (int j = 0; j < base.headers.count; j++) { cellWidth = max( - cellWidth, - initialWidth > 0.0 - ? min(initialWidth, base.headers[j].cells[i].width) - : base.headers[j].cells[i].width); + cellWidth, + initialWidth > 0.0 + ? min(initialWidth, base.headers[j].cells[i].width) + : base.headers[j].cells[i].width, + ); } widths[i] = cellWidth; } @@ -3646,41 +4118,39 @@ class PdfGridHelper { cellWidth = 0; for (int i = 0; i < base.columns.count; i++) { for (int j = 0; j < base.rows.count; j++) { - final bool isGrid = base.rows[j].cells[i].value != null && + final bool isGrid = + base.rows[j].cells[i].value != null && base.rows[j].cells[i].value is PdfGrid; if ((base.rows[j].cells[i].columnSpan == 1 && - !PdfGridCellHelper.getHelper(base.rows[j].cells[i]) - .isCellMergeContinue) || + !PdfGridCellHelper.getHelper( + base.rows[j].cells[i], + ).isCellMergeContinue) || isGrid) { if (isGrid && - !PdfGridRowHelper.getHelper(base.rows[j]) - .grid - .style - .allowHorizontalOverflow && + !PdfGridRowHelper.getHelper( + base.rows[j], + ).grid.style.allowHorizontalOverflow && initialWidth != 0) { PdfGridHelper.getHelper(base.rows[j].cells[i].value as PdfGrid) - .initialWidth = - initialWidth - - (PdfGridRowHelper.getHelper(base.rows[j]) - .grid - .style - .cellPadding - .right + - PdfGridRowHelper.getHelper(base.rows[j]) - .grid - .style - .cellPadding - .left + - base.rows[j].cells[i].style.borders.left.width / 2 + - base._gridLocation.x); + .initialWidth = initialWidth - + (PdfGridRowHelper.getHelper( + base.rows[j], + ).grid.style.cellPadding.right + + PdfGridRowHelper.getHelper( + base.rows[j], + ).grid.style.cellPadding.left + + base.rows[j].cells[i].style.borders.left.width / 2 + + base._gridLocation.x); } cellWidth = max( - widths[i]!, - max( - cellWidth, - initialWidth > 0.0 - ? min(initialWidth, base.rows[j].cells[i].width) - : base.rows[j].cells[i].width)); + widths[i]!, + max( + cellWidth, + initialWidth > 0.0 + ? min(initialWidth, base.rows[j].cells[i].width) + : base.rows[j].cells[i].width, + ), + ); cellWidth = max(base.columns[i].width, cellWidth); } } @@ -3707,21 +4177,23 @@ class PdfGridHelper { } } if (isChildGrid! && initialWidth != 0) { - widths = PdfGridColumnCollectionHelper.getHelper(base.columns) - .getDefaultWidths(initialWidth); + widths = PdfGridColumnCollectionHelper.getHelper( + base.columns, + ).getDefaultWidths(initialWidth); } for (int i = 0; i < base.columns.count; i++) { if (base.columns[i].width < 0 || (base.columns[i].width > 0 && - !PdfGridColumnHelper.getHelper(base.columns[i]) - .isCustomWidth)) { + !PdfGridColumnHelper.getHelper( + base.columns[i], + ).isCustomWidth)) { PdfGridColumnHelper.getHelper(base.columns[i]).width = widths[i]!; } } } else { - List widths = - PdfGridColumnCollectionHelper.getHelper(base.columns) - .getDefaultWidths(bounds.width - bounds.x); + List widths = PdfGridColumnCollectionHelper.getHelper( + base.columns, + ).getDefaultWidths(bounds.width - bounds.x); for (int i = 0; i < base.columns.count; i++) { if (base.columns[i].width < 0) { PdfGridColumnHelper.getHelper(base.columns[i]).width = widths[i]!; @@ -3735,36 +4207,29 @@ class PdfGridHelper { if (parentCell != null && (!base.style.allowHorizontalOverflow) && (!PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(parentCell!).row!) - .grid - .style - .allowHorizontalOverflow)) { + PdfGridCellHelper.getHelper(parentCell!).row!, + ).grid.style.allowHorizontalOverflow)) { double padding = 0; double columnWidth = 0; int columnCount = base.columns.count; if (parentCell!.style.cellPadding != null) { - padding += parentCell!.style.cellPadding!.left + + padding += + parentCell!.style.cellPadding!.left + parentCell!.style.cellPadding!.right; } else { - padding += PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(parentCell!).row!) - .grid - .style - .cellPadding - .left + + padding += + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(parentCell!).row!, + ).grid.style.cellPadding.left + PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(parentCell!).row!) - .grid - .style - .cellPadding - .right; + PdfGridCellHelper.getHelper(parentCell!).row!, + ).grid.style.cellPadding.right; } for (int i = 0; i < parentCell!.columnSpan; i++) { - columnWidth += PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(parentCell!).row!) - .grid - .columns[parentCellIndex + i] - .width; + columnWidth += + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(parentCell!).row!, + ).grid.columns[parentCellIndex + i].width; } for (int i = 0; i < base.columns.count; i++) { if (base.columns[i].width > 0 && @@ -3779,8 +4244,9 @@ class PdfGridHelper { if (parentCell != null && parentCell!.stringFormat.alignment != PdfTextAlignment.right) { for (int j = 0; j < base.columns.count; j++) { - if (!PdfGridColumnHelper.getHelper(base.columns[j]) - .isCustomWidth) { + if (!PdfGridColumnHelper.getHelper( + base.columns[j], + ).isCustomWidth) { PdfGridColumnHelper.getHelper(base.columns[j]).width = childGridColumnWidth; } @@ -3790,16 +4256,17 @@ class PdfGridHelper { } if (parentCell != null && PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(parentCell!).row!) - .getWidth() > + PdfGridCellHelper.getHelper(parentCell!).row!, + ).getWidth() > 0) { if (isChildGrid! && size.width > PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(parentCell!).row!) - .getWidth()) { - widths = PdfGridColumnCollectionHelper.getHelper(base.columns) - .getDefaultWidths(bounds.width); + PdfGridCellHelper.getHelper(parentCell!).row!, + ).getWidth()) { + widths = PdfGridColumnCollectionHelper.getHelper( + base.columns, + ).getDefaultWidths(bounds.width); for (int i = 0; i < base.columns.count; i++) { base.columns[i].width = widths[i]!; } @@ -3865,7 +4332,9 @@ class PdfGridHelper { case PdfGridBuiltInStyle.plainTable1: base._applyPlainTable1( - PdfColor(191, 191, 191), PdfColor(242, 242, 242)); + PdfColor(191, 191, 191), + PdfColor(242, 242, 242), + ); break; case PdfGridBuiltInStyle.plainTable2: @@ -3874,7 +4343,9 @@ class PdfGridHelper { case PdfGridBuiltInStyle.plainTable3: base._applyPlainTable3( - PdfColor(127, 127, 127), PdfColor(242, 242, 242)); + PdfColor(127, 127, 127), + PdfColor(242, 242, 242), + ); break; case PdfGridBuiltInStyle.plainTable4: @@ -3883,41 +4354,57 @@ class PdfGridHelper { case PdfGridBuiltInStyle.plainTable5: base._applyPlainTable5( - PdfColor(127, 127, 127), PdfColor(242, 242, 242)); + PdfColor(127, 127, 127), + PdfColor(242, 242, 242), + ); break; case PdfGridBuiltInStyle.gridTable1Light: base._applyGridTable1Light( - PdfColor(153, 153, 153), PdfColor(102, 102, 102)); + PdfColor(153, 153, 153), + PdfColor(102, 102, 102), + ); break; case PdfGridBuiltInStyle.gridTable1LightAccent1: base._applyGridTable1Light( - PdfColor(189, 214, 238), PdfColor(156, 194, 229)); + PdfColor(189, 214, 238), + PdfColor(156, 194, 229), + ); break; case PdfGridBuiltInStyle.gridTable1LightAccent2: base._applyGridTable1Light( - PdfColor(247, 202, 172), PdfColor(244, 176, 131)); + PdfColor(247, 202, 172), + PdfColor(244, 176, 131), + ); break; case PdfGridBuiltInStyle.gridTable1LightAccent3: base._applyGridTable1Light( - PdfColor(219, 219, 219), PdfColor(201, 201, 201)); + PdfColor(219, 219, 219), + PdfColor(201, 201, 201), + ); break; case PdfGridBuiltInStyle.gridTable1LightAccent4: base._applyGridTable1Light( - PdfColor(255, 229, 153), PdfColor(255, 217, 102)); + PdfColor(255, 229, 153), + PdfColor(255, 217, 102), + ); break; case PdfGridBuiltInStyle.gridTable1LightAccent5: base._applyGridTable1Light( - PdfColor(180, 198, 231), PdfColor(142, 170, 219)); + PdfColor(180, 198, 231), + PdfColor(142, 170, 219), + ); break; case PdfGridBuiltInStyle.gridTable1LightAccent6: base._applyGridTable1Light( - PdfColor(192, 224, 179), PdfColor(168, 208, 141)); + PdfColor(192, 224, 179), + PdfColor(168, 208, 141), + ); break; case PdfGridBuiltInStyle.gridTable2: @@ -3977,177 +4464,275 @@ class PdfGridHelper { break; case PdfGridBuiltInStyle.gridTable4: - base._applyGridTable4(PdfColor(102, 102, 102), PdfColor(204, 204, 204), - PdfColor(0, 0, 0)); + base._applyGridTable4( + PdfColor(102, 102, 102), + PdfColor(204, 204, 204), + PdfColor(0, 0, 0), + ); break; case PdfGridBuiltInStyle.gridTable4Accent1: - base._applyGridTable4(PdfColor(156, 194, 229), PdfColor(222, 234, 246), - PdfColor(91, 155, 213)); + base._applyGridTable4( + PdfColor(156, 194, 229), + PdfColor(222, 234, 246), + PdfColor(91, 155, 213), + ); break; case PdfGridBuiltInStyle.gridTable4Accent2: - base._applyGridTable4(PdfColor(244, 176, 131), PdfColor(251, 228, 213), - PdfColor(237, 125, 49)); + base._applyGridTable4( + PdfColor(244, 176, 131), + PdfColor(251, 228, 213), + PdfColor(237, 125, 49), + ); break; case PdfGridBuiltInStyle.gridTable4Accent3: - base._applyGridTable4(PdfColor(201, 201, 201), PdfColor(237, 237, 237), - PdfColor(165, 165, 165)); + base._applyGridTable4( + PdfColor(201, 201, 201), + PdfColor(237, 237, 237), + PdfColor(165, 165, 165), + ); break; case PdfGridBuiltInStyle.gridTable4Accent4: - base._applyGridTable4(PdfColor(255, 217, 102), PdfColor(255, 242, 204), - PdfColor(255, 192, 0)); + base._applyGridTable4( + PdfColor(255, 217, 102), + PdfColor(255, 242, 204), + PdfColor(255, 192, 0), + ); break; case PdfGridBuiltInStyle.gridTable4Accent5: - base._applyGridTable4(PdfColor(142, 170, 219), PdfColor(217, 226, 243), - PdfColor(68, 114, 196)); + base._applyGridTable4( + PdfColor(142, 170, 219), + PdfColor(217, 226, 243), + PdfColor(68, 114, 196), + ); break; case PdfGridBuiltInStyle.gridTable4Accent6: - base._applyGridTable4(PdfColor(168, 208, 141), PdfColor(226, 239, 217), - PdfColor(112, 173, 71)); + base._applyGridTable4( + PdfColor(168, 208, 141), + PdfColor(226, 239, 217), + PdfColor(112, 173, 71), + ); break; case PdfGridBuiltInStyle.gridTable5Dark: - base._applyGridTable5Dark(PdfColor(0, 0, 0), PdfColor(153, 153, 153), - PdfColor(204, 204, 204)); + base._applyGridTable5Dark( + PdfColor(0, 0, 0), + PdfColor(153, 153, 153), + PdfColor(204, 204, 204), + ); break; case PdfGridBuiltInStyle.gridTable5DarkAccent1: - base._applyGridTable5Dark(PdfColor(91, 155, 213), - PdfColor(189, 214, 238), PdfColor(222, 234, 246)); + base._applyGridTable5Dark( + PdfColor(91, 155, 213), + PdfColor(189, 214, 238), + PdfColor(222, 234, 246), + ); break; case PdfGridBuiltInStyle.gridTable5DarkAccent2: - base._applyGridTable5Dark(PdfColor(237, 125, 49), - PdfColor(247, 202, 172), PdfColor(251, 228, 213)); + base._applyGridTable5Dark( + PdfColor(237, 125, 49), + PdfColor(247, 202, 172), + PdfColor(251, 228, 213), + ); break; case PdfGridBuiltInStyle.gridTable5DarkAccent3: - base._applyGridTable5Dark(PdfColor(165, 165, 165), - PdfColor(219, 219, 219), PdfColor(237, 237, 237)); + base._applyGridTable5Dark( + PdfColor(165, 165, 165), + PdfColor(219, 219, 219), + PdfColor(237, 237, 237), + ); break; case PdfGridBuiltInStyle.gridTable5DarkAccent4: - base._applyGridTable5Dark(PdfColor(255, 192, 0), - PdfColor(255, 229, 153), PdfColor(255, 242, 204)); + base._applyGridTable5Dark( + PdfColor(255, 192, 0), + PdfColor(255, 229, 153), + PdfColor(255, 242, 204), + ); break; case PdfGridBuiltInStyle.gridTable5DarkAccent5: - base._applyGridTable5Dark(PdfColor(68, 114, 196), - PdfColor(180, 198, 231), PdfColor(217, 226, 243)); + base._applyGridTable5Dark( + PdfColor(68, 114, 196), + PdfColor(180, 198, 231), + PdfColor(217, 226, 243), + ); break; case PdfGridBuiltInStyle.gridTable5DarkAccent6: - base._applyGridTable5Dark(PdfColor(112, 171, 71), - PdfColor(197, 224, 179), PdfColor(226, 239, 217)); + base._applyGridTable5Dark( + PdfColor(112, 171, 71), + PdfColor(197, 224, 179), + PdfColor(226, 239, 217), + ); break; case PdfGridBuiltInStyle.gridTable6Colorful: - base._applyGridTable6Colorful(PdfColor(102, 102, 102), - PdfColor(204, 204, 204), PdfColor(0, 0, 0)); + base._applyGridTable6Colorful( + PdfColor(102, 102, 102), + PdfColor(204, 204, 204), + PdfColor(0, 0, 0), + ); break; case PdfGridBuiltInStyle.gridTable6ColorfulAccent1: - base._applyGridTable6Colorful(PdfColor(156, 194, 229), - PdfColor(222, 234, 246), PdfColor(46, 116, 181)); + base._applyGridTable6Colorful( + PdfColor(156, 194, 229), + PdfColor(222, 234, 246), + PdfColor(46, 116, 181), + ); break; case PdfGridBuiltInStyle.gridTable6ColorfulAccent2: - base._applyGridTable6Colorful(PdfColor(244, 176, 131), - PdfColor(251, 228, 213), PdfColor(196, 89, 17)); + base._applyGridTable6Colorful( + PdfColor(244, 176, 131), + PdfColor(251, 228, 213), + PdfColor(196, 89, 17), + ); break; case PdfGridBuiltInStyle.gridTable6ColorfulAccent3: - base._applyGridTable6Colorful(PdfColor(201, 201, 201), - PdfColor(237, 237, 237), PdfColor(123, 123, 123)); + base._applyGridTable6Colorful( + PdfColor(201, 201, 201), + PdfColor(237, 237, 237), + PdfColor(123, 123, 123), + ); break; case PdfGridBuiltInStyle.gridTable6ColorfulAccent4: - base._applyGridTable6Colorful(PdfColor(255, 217, 102), - PdfColor(255, 242, 204), PdfColor(191, 143, 0)); + base._applyGridTable6Colorful( + PdfColor(255, 217, 102), + PdfColor(255, 242, 204), + PdfColor(191, 143, 0), + ); break; case PdfGridBuiltInStyle.gridTable6ColorfulAccent5: - base._applyGridTable6Colorful(PdfColor(142, 170, 219), - PdfColor(217, 226, 243), PdfColor(47, 84, 150)); + base._applyGridTable6Colorful( + PdfColor(142, 170, 219), + PdfColor(217, 226, 243), + PdfColor(47, 84, 150), + ); break; case PdfGridBuiltInStyle.gridTable6ColorfulAccent6: - base._applyGridTable6Colorful(PdfColor(168, 208, 141), - PdfColor(226, 239, 217), PdfColor(83, 129, 53)); + base._applyGridTable6Colorful( + PdfColor(168, 208, 141), + PdfColor(226, 239, 217), + PdfColor(83, 129, 53), + ); break; case PdfGridBuiltInStyle.gridTable7Colorful: - base._applyGridTable7Colorful(PdfColor(102, 102, 102), - PdfColor(204, 204, 204), PdfColor(0, 0, 0)); + base._applyGridTable7Colorful( + PdfColor(102, 102, 102), + PdfColor(204, 204, 204), + PdfColor(0, 0, 0), + ); break; case PdfGridBuiltInStyle.gridTable7ColorfulAccent1: - base._applyGridTable7Colorful(PdfColor(156, 194, 229), - PdfColor(222, 234, 246), PdfColor(46, 116, 181)); + base._applyGridTable7Colorful( + PdfColor(156, 194, 229), + PdfColor(222, 234, 246), + PdfColor(46, 116, 181), + ); break; case PdfGridBuiltInStyle.gridTable7ColorfulAccent2: - base._applyGridTable7Colorful(PdfColor(244, 176, 131), - PdfColor(251, 228, 213), PdfColor(196, 89, 17)); + base._applyGridTable7Colorful( + PdfColor(244, 176, 131), + PdfColor(251, 228, 213), + PdfColor(196, 89, 17), + ); break; case PdfGridBuiltInStyle.gridTable7ColorfulAccent3: - base._applyGridTable7Colorful(PdfColor(201, 201, 201), - PdfColor(237, 237, 237), PdfColor(123, 123, 123)); + base._applyGridTable7Colorful( + PdfColor(201, 201, 201), + PdfColor(237, 237, 237), + PdfColor(123, 123, 123), + ); break; case PdfGridBuiltInStyle.gridTable7ColorfulAccent4: - base._applyGridTable7Colorful(PdfColor(255, 217, 102), - PdfColor(255, 242, 204), PdfColor(191, 143, 0)); + base._applyGridTable7Colorful( + PdfColor(255, 217, 102), + PdfColor(255, 242, 204), + PdfColor(191, 143, 0), + ); break; case PdfGridBuiltInStyle.gridTable7ColorfulAccent5: - base._applyGridTable7Colorful(PdfColor(142, 170, 219), - PdfColor(217, 226, 243), PdfColor(47, 84, 150)); + base._applyGridTable7Colorful( + PdfColor(142, 170, 219), + PdfColor(217, 226, 243), + PdfColor(47, 84, 150), + ); break; case PdfGridBuiltInStyle.gridTable7ColorfulAccent6: - base._applyGridTable7Colorful(PdfColor(168, 208, 141), - PdfColor(226, 239, 217), PdfColor(83, 129, 53)); + base._applyGridTable7Colorful( + PdfColor(168, 208, 141), + PdfColor(226, 239, 217), + PdfColor(83, 129, 53), + ); break; case PdfGridBuiltInStyle.listTable1Light: base._applyListTable1Light( - PdfColor(102, 102, 102), PdfColor(204, 204, 204)); + PdfColor(102, 102, 102), + PdfColor(204, 204, 204), + ); break; case PdfGridBuiltInStyle.listTable1LightAccent1: base._applyListTable1Light( - PdfColor(156, 194, 229), PdfColor(222, 234, 246)); + PdfColor(156, 194, 229), + PdfColor(222, 234, 246), + ); break; case PdfGridBuiltInStyle.listTable1LightAccent2: base._applyListTable1Light( - PdfColor(244, 176, 131), PdfColor(251, 228, 213)); + PdfColor(244, 176, 131), + PdfColor(251, 228, 213), + ); break; case PdfGridBuiltInStyle.listTable1LightAccent3: base._applyListTable1Light( - PdfColor(201, 201, 201), PdfColor(237, 237, 237)); + PdfColor(201, 201, 201), + PdfColor(237, 237, 237), + ); break; case PdfGridBuiltInStyle.listTable1LightAccent4: base._applyListTable1Light( - PdfColor(255, 217, 102), PdfColor(255, 242, 204)); + PdfColor(255, 217, 102), + PdfColor(255, 242, 204), + ); break; case PdfGridBuiltInStyle.listTable1LightAccent5: base._applyListTable1Light( - PdfColor(142, 170, 219), PdfColor(217, 226, 243)); + PdfColor(142, 170, 219), + PdfColor(217, 226, 243), + ); break; case PdfGridBuiltInStyle.listTable1LightAccent6: base._applyListTable1Light( - PdfColor(168, 208, 141), PdfColor(226, 239, 217)); + PdfColor(168, 208, 141), + PdfColor(226, 239, 217), + ); break; case PdfGridBuiltInStyle.listTable2: @@ -4207,38 +4792,59 @@ class PdfGridHelper { break; case PdfGridBuiltInStyle.listTable4: - base._applyListTable4(PdfColor(102, 102, 102), PdfColor(0, 0, 0), - PdfColor(204, 204, 204)); + base._applyListTable4( + PdfColor(102, 102, 102), + PdfColor(0, 0, 0), + PdfColor(204, 204, 204), + ); break; case PdfGridBuiltInStyle.listTable4Accent1: - base._applyListTable4(PdfColor(156, 194, 229), PdfColor(91, 155, 213), - PdfColor(222, 234, 246)); + base._applyListTable4( + PdfColor(156, 194, 229), + PdfColor(91, 155, 213), + PdfColor(222, 234, 246), + ); break; case PdfGridBuiltInStyle.listTable4Accent2: - base._applyListTable4(PdfColor(244, 176, 131), PdfColor(237, 125, 49), - PdfColor(251, 228, 213)); + base._applyListTable4( + PdfColor(244, 176, 131), + PdfColor(237, 125, 49), + PdfColor(251, 228, 213), + ); break; case PdfGridBuiltInStyle.listTable4Accent3: - base._applyListTable4(PdfColor(201, 201, 201), PdfColor(165, 165, 165), - PdfColor(237, 237, 237)); + base._applyListTable4( + PdfColor(201, 201, 201), + PdfColor(165, 165, 165), + PdfColor(237, 237, 237), + ); break; case PdfGridBuiltInStyle.listTable4Accent4: - base._applyListTable4(PdfColor(255, 217, 102), PdfColor(255, 192, 0), - PdfColor(255, 242, 204)); + base._applyListTable4( + PdfColor(255, 217, 102), + PdfColor(255, 192, 0), + PdfColor(255, 242, 204), + ); break; case PdfGridBuiltInStyle.listTable4Accent5: - base._applyListTable4(PdfColor(142, 170, 219), PdfColor(68, 114, 196), - PdfColor(217, 226, 243)); + base._applyListTable4( + PdfColor(142, 170, 219), + PdfColor(68, 114, 196), + PdfColor(217, 226, 243), + ); break; case PdfGridBuiltInStyle.listTable4Accent6: - base._applyListTable4(PdfColor(168, 208, 141), PdfColor(112, 173, 71), - PdfColor(226, 239, 217)); + base._applyListTable4( + PdfColor(168, 208, 141), + PdfColor(112, 173, 71), + PdfColor(226, 239, 217), + ); break; case PdfGridBuiltInStyle.listTable5Dark: @@ -4270,73 +4876,115 @@ class PdfGridHelper { break; case PdfGridBuiltInStyle.listTable6Colorful: - base._applyListTable6Colorful(PdfColor(102, 102, 102), - PdfColor(204, 204, 204), PdfColor(0, 0, 0)); + base._applyListTable6Colorful( + PdfColor(102, 102, 102), + PdfColor(204, 204, 204), + PdfColor(0, 0, 0), + ); break; case PdfGridBuiltInStyle.listTable6ColorfulAccent1: - base._applyListTable6Colorful(PdfColor(91, 155, 213), - PdfColor(222, 234, 246), PdfColor(46, 116, 181)); + base._applyListTable6Colorful( + PdfColor(91, 155, 213), + PdfColor(222, 234, 246), + PdfColor(46, 116, 181), + ); break; case PdfGridBuiltInStyle.listTable6ColorfulAccent2: - base._applyListTable6Colorful(PdfColor(237, 125, 49), - PdfColor(251, 228, 213), PdfColor(196, 89, 17)); + base._applyListTable6Colorful( + PdfColor(237, 125, 49), + PdfColor(251, 228, 213), + PdfColor(196, 89, 17), + ); break; case PdfGridBuiltInStyle.listTable6ColorfulAccent3: - base._applyListTable6Colorful(PdfColor(165, 165, 165), - PdfColor(237, 237, 237), PdfColor(123, 123, 123)); + base._applyListTable6Colorful( + PdfColor(165, 165, 165), + PdfColor(237, 237, 237), + PdfColor(123, 123, 123), + ); break; case PdfGridBuiltInStyle.listTable6ColorfulAccent4: - base._applyListTable6Colorful(PdfColor(255, 192, 0), - PdfColor(255, 242, 204), PdfColor(191, 143, 0)); + base._applyListTable6Colorful( + PdfColor(255, 192, 0), + PdfColor(255, 242, 204), + PdfColor(191, 143, 0), + ); break; case PdfGridBuiltInStyle.listTable6ColorfulAccent5: - base._applyListTable6Colorful(PdfColor(68, 114, 196), - PdfColor(217, 226, 243), PdfColor(47, 84, 150)); + base._applyListTable6Colorful( + PdfColor(68, 114, 196), + PdfColor(217, 226, 243), + PdfColor(47, 84, 150), + ); break; case PdfGridBuiltInStyle.listTable6ColorfulAccent6: - base._applyListTable6Colorful(PdfColor(112, 173, 71), - PdfColor(226, 239, 217), PdfColor(83, 129, 53)); + base._applyListTable6Colorful( + PdfColor(112, 173, 71), + PdfColor(226, 239, 217), + PdfColor(83, 129, 53), + ); break; case PdfGridBuiltInStyle.listTable7Colorful: - base._applyListTable7Colorful(PdfColor(102, 102, 102), - PdfColor(204, 204, 204), PdfColor(0, 0, 0)); + base._applyListTable7Colorful( + PdfColor(102, 102, 102), + PdfColor(204, 204, 204), + PdfColor(0, 0, 0), + ); break; case PdfGridBuiltInStyle.listTable7ColorfulAccent1: - base._applyListTable7Colorful(PdfColor(91, 155, 213), - PdfColor(222, 234, 246), PdfColor(46, 116, 181)); + base._applyListTable7Colorful( + PdfColor(91, 155, 213), + PdfColor(222, 234, 246), + PdfColor(46, 116, 181), + ); break; case PdfGridBuiltInStyle.listTable7ColorfulAccent2: - base._applyListTable7Colorful(PdfColor(237, 125, 49), - PdfColor(251, 228, 213), PdfColor(196, 89, 17)); + base._applyListTable7Colorful( + PdfColor(237, 125, 49), + PdfColor(251, 228, 213), + PdfColor(196, 89, 17), + ); break; case PdfGridBuiltInStyle.listTable7ColorfulAccent3: - base._applyListTable7Colorful(PdfColor(165, 165, 165), - PdfColor(237, 237, 237), PdfColor(123, 123, 123)); + base._applyListTable7Colorful( + PdfColor(165, 165, 165), + PdfColor(237, 237, 237), + PdfColor(123, 123, 123), + ); break; case PdfGridBuiltInStyle.listTable7ColorfulAccent4: - base._applyListTable7Colorful(PdfColor(255, 192, 0), - PdfColor(255, 242, 204), PdfColor(191, 143, 0)); + base._applyListTable7Colorful( + PdfColor(255, 192, 0), + PdfColor(255, 242, 204), + PdfColor(191, 143, 0), + ); break; case PdfGridBuiltInStyle.listTable7ColorfulAccent5: - base._applyListTable7Colorful(PdfColor(68, 114, 196), - PdfColor(217, 226, 243), PdfColor(47, 84, 150)); + base._applyListTable7Colorful( + PdfColor(68, 114, 196), + PdfColor(217, 226, 243), + PdfColor(47, 84, 150), + ); break; case PdfGridBuiltInStyle.listTable7ColorfulAccent6: - base._applyListTable7Colorful(PdfColor(112, 173, 71), - PdfColor(226, 239, 217), PdfColor(83, 129, 53)); + base._applyListTable7Colorful( + PdfColor(112, 173, 71), + PdfColor(226, 239, 217), + PdfColor(83, 129, 53), + ); break; // ignore: no_default_cases @@ -4346,25 +4994,25 @@ class PdfGridHelper { } /// Delegate for handling StartCellLayoutEvent. -typedef PdfGridBeginCellLayoutCallback = void Function( - Object sender, PdfGridBeginCellLayoutArgs args); +typedef PdfGridBeginCellLayoutCallback = + void Function(Object sender, PdfGridBeginCellLayoutArgs args); /// Delegate for handling EndCellLayoutEvent. -typedef PdfGridEndCellLayoutCallback = void Function( - Object sender, PdfGridEndCellLayoutArgs args); +typedef PdfGridEndCellLayoutCallback = + void Function(Object sender, PdfGridEndCellLayoutArgs args); /// Represents arguments of StartCellLayout Event. class PdfGridBeginCellLayoutArgs extends GridCellLayoutArgs { //Constructor PdfGridBeginCellLayoutArgs._( - PdfGraphics graphics, - int rowIndex, - int cellInder, - PdfRectangle bounds, - String value, - PdfGridCellStyle? style, - bool isHeaderRow) - : super._(graphics, rowIndex, cellInder, bounds, value, isHeaderRow) { + PdfGraphics graphics, + int rowIndex, + int cellInder, + PdfRectangle bounds, + String value, + PdfGridCellStyle? style, + bool isHeaderRow, + ) : super._(graphics, rowIndex, cellInder, bounds, value, isHeaderRow) { if (style != null) { this.style = style; } @@ -4422,15 +5070,23 @@ class PdfGridBeginCellLayoutArgs extends GridCellLayoutArgs { class PdfGridBeginCellLayoutArgsHelper { /// internal method static PdfGridBeginCellLayoutArgs load( - PdfGraphics graphics, - int rowIndex, - int cellInder, - PdfRectangle bounds, - String value, - PdfGridCellStyle? style, - bool isHeaderRow) { + PdfGraphics graphics, + int rowIndex, + int cellInder, + PdfRectangle bounds, + String value, + PdfGridCellStyle? style, + bool isHeaderRow, + ) { return PdfGridBeginCellLayoutArgs._( - graphics, rowIndex, cellInder, bounds, value, style, isHeaderRow); + graphics, + rowIndex, + cellInder, + bounds, + value, + style, + isHeaderRow, + ); } } @@ -4438,14 +5094,14 @@ class PdfGridBeginCellLayoutArgsHelper { class PdfGridEndCellLayoutArgs extends GridCellLayoutArgs { //Constructor PdfGridEndCellLayoutArgs._( - PdfGraphics graphics, - int rowIndex, - int cellInder, - PdfRectangle bounds, - String value, - PdfGridCellStyle? style, - bool isHeaderRow) - : super._(graphics, rowIndex, cellInder, bounds, value, isHeaderRow) { + PdfGraphics graphics, + int rowIndex, + int cellInder, + PdfRectangle bounds, + String value, + PdfGridCellStyle? style, + bool isHeaderRow, + ) : super._(graphics, rowIndex, cellInder, bounds, value, isHeaderRow) { if (style != null) { this.style = style; } @@ -4460,15 +5116,23 @@ class PdfGridEndCellLayoutArgs extends GridCellLayoutArgs { class PdfGridEndCellLayoutArgsHelper { /// internal method static PdfGridEndCellLayoutArgs load( - PdfGraphics graphics, - int rowIndex, - int cellInder, - PdfRectangle bounds, - String value, - PdfGridCellStyle? style, - bool isHeaderRow) { + PdfGraphics graphics, + int rowIndex, + int cellInder, + PdfRectangle bounds, + String value, + PdfGridCellStyle? style, + bool isHeaderRow, + ) { return PdfGridEndCellLayoutArgs._( - graphics, rowIndex, cellInder, bounds, value, style, isHeaderRow); + graphics, + rowIndex, + cellInder, + bounds, + value, + style, + isHeaderRow, + ); } } @@ -4476,8 +5140,14 @@ class PdfGridEndCellLayoutArgsHelper { abstract class GridCellLayoutArgs { //Constructors /// Initializes a new instance of the [StartCellLayoutArgs] class. - GridCellLayoutArgs._(PdfGraphics graphics, int rowIndex, int cellIndex, - PdfRectangle bounds, String value, bool isHeaderRow) { + GridCellLayoutArgs._( + PdfGraphics graphics, + int rowIndex, + int cellIndex, + PdfRectangle bounds, + String value, + bool isHeaderRow, + ) { _rowIndex = rowIndex; _cellIndex = cellIndex; _value = value; @@ -4819,7 +5489,10 @@ class PdfGridBeginPageLayoutArgs extends BeginPageLayoutArgs { class PdfGridBeginPageLayoutArgsHelper { /// internal method static PdfGridBeginPageLayoutArgs load( - Rect bounds, PdfPage page, int? startRow) { + Rect bounds, + PdfPage page, + int? startRow, + ) { return PdfGridBeginPageLayoutArgs._(bounds, page, startRow); } } @@ -4843,13 +5516,14 @@ class PdfGridEndPageLayoutArgsHelper { class PdfGridBuiltInStyleSettings { // Constructor /// Represents the grid built-in style settings. - PdfGridBuiltInStyleSettings( - {this.applyStyleForBandedColumns = false, - this.applyStyleForBandedRows = true, - this.applyStyleForFirstColumn = false, - this.applyStyleForHeaderRow = true, - this.applyStyleForLastColumn = false, - this.applyStyleForLastRow = false}); + PdfGridBuiltInStyleSettings({ + this.applyStyleForBandedColumns = false, + this.applyStyleForBandedRows = true, + this.applyStyleForFirstColumn = false, + this.applyStyleForHeaderRow = true, + this.applyStyleForLastColumn = false, + this.applyStyleForLastRow = false, + }); //Fields /// Gets or sets a value indicating whether to apply style bands to the columns in a table. diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_cell.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_cell.dart index 5d99f75df..cfeccca84 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_cell.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_cell.dart @@ -118,12 +118,13 @@ class PdfGridCell { /// //Dispose the document. /// document.dispose(); /// ``` - PdfGridCell( - {PdfGridCellStyle? style, - PdfStringFormat? format, - PdfGridRow? row, - int? rowSpan, - int? columnSpan}) { + PdfGridCell({ + PdfGridCellStyle? style, + PdfStringFormat? format, + PdfGridRow? row, + int? rowSpan, + int? columnSpan, + }) { _helper = PdfGridCellHelper(this); _initialize(style, format, row, rowSpan, columnSpan); } @@ -201,8 +202,9 @@ class PdfGridCell { /// ``` double get width { if (_width == -1 || - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(_helper.row!).grid) - .isComplete) { + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(_helper.row!).grid, + ).isComplete) { _width = _measureWidth(); } return double.parse(_width.toStringAsFixed(4)); @@ -316,8 +318,11 @@ class PdfGridCell { int get rowSpan => _rowSpan; set rowSpan(int value) { if (value < 1) { - throw ArgumentError.value('value', 'row span', - 'Invalid span specified, must be greater than or equal to 1'); + throw ArgumentError.value( + 'value', + 'row span', + 'Invalid span specified, must be greater than or equal to 1', + ); } if (value > 1) { _rowSpan = value; @@ -385,8 +390,11 @@ class PdfGridCell { int get columnSpan => _columnSpan; set columnSpan(int value) { if (value < 1) { - throw ArgumentError.value('value', 'column span', - 'Invalid span specified, must be greater than or equal to 1'); + throw ArgumentError.value( + 'value', + 'column span', + 'Invalid span specified, must be greater than or equal to 1', + ); } if (value > 1) { _columnSpan = value; @@ -605,8 +613,13 @@ class PdfGridCell { } //Implementation - void _initialize(PdfGridCellStyle? style, PdfStringFormat? format, - PdfGridRow? row, int? rowSpan, int? columnSpan) { + void _initialize( + PdfGridCellStyle? style, + PdfStringFormat? format, + PdfGridRow? row, + int? rowSpan, + int? columnSpan, + ) { if (row != null) { _helper.row = row; } @@ -664,8 +677,9 @@ class PdfGridCell { return style.font ?? _helper.row!.style.font ?? PdfGridRowHelper.getHelper(_helper.row!).grid.style.font ?? - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(_helper.row!).grid) - .defaultFont; + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(_helper.row!).grid, + ).defaultFont; } PdfBrush? _getTextBrush() { @@ -696,8 +710,12 @@ class PdfGridCell { defaultWidth = _getColumnWidth(); } final PdfStringLayoutResult result = layouter.layout( - value, _getTextFont()!, stringFormat, - width: defaultWidth, height: _maxValue); + value, + _getTextFont()!, + stringFormat, + width: defaultWidth, + height: _maxValue, + ); width += result.size.width; width += (style.borders.left.width + style.borders.right.width) * 2; } else if (value is PdfGrid) { @@ -710,14 +728,19 @@ class PdfGridCell { final PdfTextElement element = value as PdfTextElement; String? temp = element.text; if (!_helper.finished) { - temp = (_helper.remainingString != null && - _helper.remainingString!.isNotEmpty) - ? _helper.remainingString - : value as String; + temp = + (_helper.remainingString != null && + _helper.remainingString!.isNotEmpty) + ? _helper.remainingString + : value as String; } final PdfStringLayoutResult result = layouter.layout( - temp!, element.font, element.stringFormat ?? stringFormat, - width: defaultWidth, height: _maxValue); + temp!, + element.font, + element.stringFormat ?? stringFormat, + width: defaultWidth, + height: _maxValue, + ); width += result.size.width; width += (style.borders.left.width + style.borders.right.width) * 2; } @@ -725,22 +748,18 @@ class PdfGridCell { PdfGridRowHelper.getHelper(_helper.row!).grid.style.cellSpacing + (style.cellPadding != null ? (style.cellPadding!.left + style.cellPadding!.right) - : (PdfGridRowHelper.getHelper(_helper.row!) - .grid - .style - .cellPadding - .left + - PdfGridRowHelper.getHelper(_helper.row!) - .grid - .style - .cellPadding - .right)); + : (PdfGridRowHelper.getHelper( + _helper.row!, + ).grid.style.cellPadding.left + + PdfGridRowHelper.getHelper( + _helper.row!, + ).grid.style.cellPadding.right)); } double _getColumnWidth() { double defaultWidth = PdfGridCellHelper.getHelper(_parent!)._calculateWidth()! / - PdfGridRowHelper.getHelper(_helper.row!).grid.columns.count; + PdfGridRowHelper.getHelper(_helper.row!).grid.columns.count; if (defaultWidth <= 0) { defaultWidth = _maxValue; } @@ -787,7 +806,8 @@ class PdfGridCellHelper { /// internal method double measureHeight() { - final double width = _calculateWidth()! - + final double width = + _calculateWidth()! - (base.style.cellPadding == null ? (PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.right + PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.left) @@ -802,27 +822,39 @@ class PdfGridCellHelper { final PdfTextElement element = base.value as PdfTextElement; String? temp = element.text; if (!finished) { - temp = (remainingString != null && remainingString!.isNotEmpty) - ? remainingString - : base.value as String; + temp = + (remainingString != null && remainingString!.isNotEmpty) + ? remainingString + : base.value as String; } final PdfStringLayoutResult result = layouter.layout( - temp!, element.font, element.stringFormat ?? base.stringFormat, - width: width, height: base._maxValue); - height += result.size.height + + temp!, + element.font, + element.stringFormat ?? base.stringFormat, + width: width, + height: base._maxValue, + ); + height += + result.size.height + ((base.style.borders.top.width + base.style.borders.bottom.width) * 2); } else if (base.value is String || remainingString is String) { String? currentValue = base.value as String; if (!finished) { - currentValue = (remainingString != null && remainingString!.isNotEmpty) - ? remainingString - : base.value as String; + currentValue = + (remainingString != null && remainingString!.isNotEmpty) + ? remainingString + : base.value as String; } final PdfStringLayoutResult result = layouter.layout( - currentValue!, base._getTextFont()!, base.stringFormat, - width: width, height: base._maxValue); - height += result.size.height + + currentValue!, + base._getTextFont()!, + base.stringFormat, + width: width, + height: base._maxValue, + ); + height += + result.size.height + ((base.style.borders.top.width + base.style.borders.bottom.width) * 2); } else if (base.value is PdfGrid) { @@ -831,10 +863,11 @@ class PdfGridCellHelper { final PdfImage img = base._value as PdfImage; height = img.height / (96 / 72); } - height += base.style.cellPadding == null - ? (PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.top + - PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.bottom) - : (base.style.cellPadding!.top + base.style.cellPadding!.bottom); + height += + base.style.cellPadding == null + ? (PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.top + + PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.bottom) + : (base.style.cellPadding!.top + base.style.cellPadding!.bottom); height += PdfGridRowHelper.getHelper(row!).grid.style.cellSpacing; return height; } @@ -849,27 +882,28 @@ class PdfGridCellHelper { } if (base._parent != null && PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(base._parent!).row!) - .getWidth() > + PdfGridCellHelper.getHelper(base._parent!).row!, + ).getWidth() > 0 && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isChildGrid! && (PdfGridRowHelper.getHelper(row!).getWidth() > PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(base._parent!).row!) - .getWidth())) { + PdfGridCellHelper.getHelper(base._parent!).row!, + ).getWidth())) { width = 0; for (int j = 0; j < base._parent!.columnSpan; j++) { - width += PdfGridRowHelper.getHelper( - PdfGridCellHelper.getHelper(base._parent!).row!) - .grid - .columns[j] - .width; + width += + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(base._parent!).row!, + ).grid.columns[j].width; } width = width / row!.cells.count; } else if (base._parent != null && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isChildGrid! && width == -1) { width = _findGridColumnWidth(base._parent!); width = width / row!.cells.count; @@ -918,8 +952,10 @@ class PdfGridCellHelper { pen = base._style!.borders.right; if (bounds.x + bounds.width > graphics.clientSize.width - pen.width / 2) { p1 = Offset(graphics.clientSize.width - pen.width / 2, bounds.y); - p2 = Offset(graphics.clientSize.width - pen.width / 2, - bounds.y + bounds.height); + p2 = Offset( + graphics.clientSize.width - pen.width / 2, + bounds.y + bounds.height, + ); } if (base._style!.borders.right.dashStyle == PdfDashStyle.solid && !PdfPenHelper.getHelper(pen).isImmutable) { @@ -943,8 +979,10 @@ class PdfGridCellHelper { pen = base._style!.borders.bottom; if (bounds.y + bounds.height > graphics.clientSize.height - pen.width / 2) { - p1 = Offset(bounds.x + bounds.width, - graphics.clientSize.height - pen.width / 2); + p1 = Offset( + bounds.x + bounds.width, + graphics.clientSize.height - pen.width / 2, + ); p2 = Offset(bounds.x, graphics.clientSize.height - pen.width / 2); } if (base._style!.borders.bottom.dashStyle == PdfDashStyle.solid && @@ -965,20 +1003,26 @@ class PdfGridCellHelper { /// internal method PdfStringLayoutResult? draw( - PdfGraphics? graphics, PdfRectangle bounds, bool cancelSubsequentSpans) { + PdfGraphics? graphics, + PdfRectangle bounds, + bool cancelSubsequentSpans, + ) { bool isrowbreak = false; - if (!PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isSingleGrid) { + if (!PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isSingleGrid) { if ((remainingString != null) || (PdfGridLayouter.repeatRowIndex != -1)) { _drawParentCells(graphics!, bounds, true); } else if (PdfGridRowHelper.getHelper(row!).grid.rows.count > 1) { - for (int i = 0; - i < PdfGridRowHelper.getHelper(row!).grid.rows.count; - i++) { + for ( + int i = 0; + i < PdfGridRowHelper.getHelper(row!).grid.rows.count; + i++ + ) { if (row == PdfGridRowHelper.getHelper(row!).grid.rows[i]) { if (PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[i]) - .rowBreakHeight > + PdfGridRowHelper.getHelper(row!).grid.rows[i], + ).rowBreakHeight > 0) { isrowbreak = true; } @@ -992,9 +1036,11 @@ class PdfGridCellHelper { PdfStringLayoutResult? result; if (cancelSubsequentSpans) { final int currentCellIndex = row!.cells.indexOf(base); - for (int i = currentCellIndex + 1; - i <= currentCellIndex + base._columnSpan; - i++) { + for ( + int i = currentCellIndex + 1; + i <= currentCellIndex + base._columnSpan; + i++ + ) { PdfGridCellHelper.getHelper(row!.cells[i]).isCellMergeContinue = false; PdfGridCellHelper.getHelper(row!.cells[i]).isRowMergeContinue = false; } @@ -1026,18 +1072,18 @@ class PdfGridCellHelper { if (PdfGridRowHelper.getHelper(row!).grid.allowRowBreakingAcrossPages) { innerLayoutArea.height = innerLayoutArea.height - innerLayoutArea.y; bounds.height = bounds.height - bounds.y; - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isChildGrid!) { - innerLayoutArea.height = innerLayoutArea.height - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom; + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isChildGrid!) { + innerLayoutArea.height = + innerLayoutArea.height - + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; } } else { innerLayoutArea.height = graphics.clientSize.height; @@ -1054,11 +1100,14 @@ class PdfGridCellHelper { PdfGridHelper.getHelper(childGrid).listOfNavigatePages = []; PdfGridLayouter layouter = PdfGridLayouter(childGrid); PdfLayoutFormat? format = PdfLayoutFormat(); - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .layoutFormat != + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).layoutFormat != null) { - format = PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .layoutFormat; + format = + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).layoutFormat; } else { format.layoutType = PdfLayoutType.paginate; } @@ -1087,12 +1136,14 @@ class PdfGridCellHelper { final String textElementString = textelement.text; PdfTextLayoutResult? textlayoutresult; if (finished) { - textlayoutresult = textelement.draw( - page: page, bounds: innerLayoutArea.rect) as PdfTextLayoutResult?; + textlayoutresult = + textelement.draw(page: page, bounds: innerLayoutArea.rect) + as PdfTextLayoutResult?; } else { textelement.text = remainingString!; - textlayoutresult = textelement.draw( - page: page, bounds: innerLayoutArea.rect) as PdfTextLayoutResult?; + textlayoutresult = + textelement.draw(page: page, bounds: innerLayoutArea.rect) + as PdfTextLayoutResult?; } if (textlayoutresult!.remainder != null && textlayoutresult.remainder!.isNotEmpty) { @@ -1107,69 +1158,68 @@ class PdfGridCellHelper { String? temp; PdfRectangle layoutRectangle; if (innerLayoutArea.height < font!.height) { - layoutRectangle = PdfRectangle(innerLayoutArea.x, innerLayoutArea.y, - innerLayoutArea.width, font.height); + layoutRectangle = PdfRectangle( + innerLayoutArea.x, + innerLayoutArea.y, + innerLayoutArea.width, + font.height, + ); } else { layoutRectangle = innerLayoutArea; } if (innerLayoutArea.height < font.height && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isChildGrid! && - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .parentCell != + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isChildGrid! && + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).parentCell != null) { - final double height = layoutRectangle.height - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom - + final double height = + layoutRectangle.height - + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom - PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.bottom; if (height > 0 && height < font.height) { layoutRectangle.height = height; } else if (height + - PdfGridRowHelper.getHelper(row!) - .grid - .style - .cellPadding - .bottom > + PdfGridRowHelper.getHelper( + row!, + ).grid.style.cellPadding.bottom > 0 && height + - PdfGridRowHelper.getHelper(row!) - .grid - .style - .cellPadding - .bottom < + PdfGridRowHelper.getHelper( + row!, + ).grid.style.cellPadding.bottom < font.height) { - layoutRectangle.height = height + + layoutRectangle.height = + height + PdfGridRowHelper.getHelper(row!).grid.style.cellPadding.bottom; } else if (bounds.height < font.height) { layoutRectangle.height = bounds.height; } else if (bounds.height - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom < + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom < font.height) { - layoutRectangle.height = bounds.height - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom; + layoutRectangle.height = + bounds.height - + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; } } if (base.style.cellPadding != null && @@ -1177,41 +1227,49 @@ class PdfGridCellHelper { base.style.cellPadding!.left == 0 && base.style.cellPadding!.right == 0 && base.style.cellPadding!.top == 0) { - layoutRectangle.width = layoutRectangle.width - + layoutRectangle.width = + layoutRectangle.width - base.style.borders.left.width + base.style.borders.right.width; } if (finished) { - temp = remainingString != null && remainingString!.isEmpty - ? remainingString - : base.value as String; - graphics.drawString(temp!, font, - pen: textPen, - brush: textBrush, - bounds: layoutRectangle.rect, - format: strFormat); + temp = + remainingString != null && remainingString!.isEmpty + ? remainingString + : base.value as String; + graphics.drawString( + temp!, + font, + pen: textPen, + brush: textBrush, + bounds: layoutRectangle.rect, + format: strFormat, + ); } else { - graphics.drawString(remainingString!, font, - pen: textPen, - brush: textBrush, - bounds: layoutRectangle.rect, - format: strFormat); + graphics.drawString( + remainingString!, + font, + pen: textPen, + brush: textBrush, + bounds: layoutRectangle.rect, + format: strFormat, + ); } result = PdfGraphicsHelper.getHelper(graphics).stringLayoutResult; - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .isChildGrid! && + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).isChildGrid! && PdfGridRowHelper.getHelper(row!).rowBreakHeight > 0 && result != null) { - bounds.height = bounds.height - - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper( - PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid) - .parentCell!) - .row!) - .grid - .style - .cellPadding - .bottom; + bounds.height = + bounds.height - + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper( + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).parentCell!, + ).row!, + ).grid.style.cellPadding.bottom; } } else if (base._value is PdfImage) { if (base.style.cellPadding != null && @@ -1219,19 +1277,21 @@ class PdfGridCellHelper { PdfPaddings(left: 0, right: 0, top: 0, bottom: 0)) { final PdfPaddings padding = base.style.cellPadding!; bounds = PdfRectangle( - bounds.x + padding.left, - bounds.y + padding.top, - bounds.width - (padding.left + padding.right), - bounds.height - (padding.top + padding.bottom)); + bounds.x + padding.left, + bounds.y + padding.top, + bounds.width - (padding.left + padding.right), + bounds.height - (padding.top + padding.bottom), + ); } else if (PdfGridRowHelper.getHelper(row!).grid.style.cellPadding != PdfPaddings(left: 0, right: 0, top: 0, bottom: 0)) { final PdfPaddings padding = PdfGridRowHelper.getHelper(row!).grid.style.cellPadding; bounds = PdfRectangle( - bounds.x + padding.left, - bounds.y + padding.top, - bounds.width - (padding.left + padding.right), - bounds.height - (padding.top + padding.bottom)); + bounds.x + padding.left, + bounds.y + padding.top, + bounds.width - (padding.left + padding.right), + bounds.height - (padding.top + padding.bottom), + ); } final PdfImage img = base.value as PdfImage; double? imgWidth = img.width.toDouble(); @@ -1285,14 +1345,21 @@ class PdfGridCellHelper { final PdfPage graphicsPage = PdfGraphicsHelper.getHelper(graphics).page!; final PdfGraphicsState st = graphicsPage.graphics.save(); - graphicsPage.graphics - .setClip(bounds: bounds.rect, mode: PdfFillMode.winding); + graphicsPage.graphics.setClip( + bounds: bounds.rect, + mode: PdfFillMode.winding, + ); graphicsPage.graphics.drawImage( - img, Rect.fromLTWH(bounds.x, bounds.y, imgWidth, imgHeight)); + img, + Rect.fromLTWH(bounds.x, bounds.y, imgWidth, imgHeight), + ); graphicsPage.graphics.restore(st); } else { - graphics = _setImagePosition(graphics, img, - PdfRectangle(bounds.x, bounds.y, imgWidth, imgHeight)); + graphics = _setImagePosition( + graphics, + img, + PdfRectangle(bounds.x, bounds.y, imgWidth, imgHeight), + ); } graphics!.save(); } @@ -1302,56 +1369,57 @@ class PdfGridCellHelper { void _drawParentCells(PdfGraphics graphics, PdfRectangle bounds, bool b) { final PdfPoint location = PdfPoint( - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .defaultBorder - .right - .width / - 2, - PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .defaultBorder - .top - .width / - 2); + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).defaultBorder.right.width / + 2, + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).defaultBorder.top.width / + 2, + ); if ((bounds.height < graphics.clientSize.height) && (b == true)) { bounds.height = bounds.height + bounds.y - location.y; } - final PdfRectangle rect = - PdfRectangle(location.x, location.y, bounds.width, bounds.height); + final PdfRectangle rect = PdfRectangle( + location.x, + location.y, + bounds.width, + bounds.height, + ); if (b == false) { rect.y = bounds.y; rect.height = bounds.height; } PdfGridCell? c = base; if (base._parent != null) { - if ((PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(c).row!) - .grid - .rows - .count == + if ((PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(c).row!, + ).grid.rows.count == 1) && - (PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(c).row!) - .grid - .rows[0] - .cells - .count == + (PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(c).row!, + ).grid.rows[0].cells.count == 1)) { PdfGridCellHelper.getHelper( - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(c).row!) - .grid - .rows[0] - .cells[0]) - .present = true; + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(c).row!, + ).grid.rows[0].cells[0], + ).present = + true; } else { - for (int rowIndex = 0; - rowIndex < - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(c).row!) - .grid - .rows - .count; - rowIndex++) { + for ( + int rowIndex = 0; + rowIndex < + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(c).row!, + ).grid.rows.count; + rowIndex++ + ) { final PdfGridRow r = - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(c).row!) - .grid - .rows[rowIndex]; + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(c).row!, + ).grid.rows[rowIndex]; if (r == PdfGridCellHelper.getHelper(c).row) { for (int cellIndex = 0; cellIndex < row!.cells.count; cellIndex++) { final PdfGridCell cell = row!.cells[cellIndex]; @@ -1366,12 +1434,11 @@ class PdfGridCellHelper { while (c!._parent != null) { c = c._parent; PdfGridCellHelper.getHelper(c!).present = true; - rect.x = rect.x + - PdfGridRowHelper.getHelper(PdfGridCellHelper.getHelper(c).row!) - .grid - .style - .cellPadding - .left; + rect.x = + rect.x + + PdfGridRowHelper.getHelper( + PdfGridCellHelper.getHelper(c).row!, + ).grid.style.cellPadding.left; } } if (bounds.x >= rect.x) { @@ -1397,13 +1464,14 @@ class PdfGridCellHelper { } rect.width = PdfGridRowHelper.getHelper(pdfGrid.rows[i]).getWidth() - - cellwidth; + cellwidth; final PdfGrid? grid = pdfGrid.rows[i].cells[j].value as PdfGrid?; if (grid != null) { for (int l = 0; l < grid.rows.count; l++) { for (int m = 0; m < grid.rows[l].cells.count; m++) { - if ((PdfGridCellHelper.getHelper(grid.rows[l].cells[m]) - .present) && + if ((PdfGridCellHelper.getHelper( + grid.rows[l].cells[m], + ).present) && m > 0) { rect.width = grid.rows[l].cells[m].width; cellcount = m; @@ -1463,19 +1531,21 @@ class PdfGridCellHelper { PdfPaddings(left: 0, right: 0, top: 0, bottom: 0)) { final PdfPaddings padding = base.style.cellPadding!; bounds = PdfRectangle( - bounds.x + padding.left, - bounds.y + padding.top, - bounds.width - (padding.left + padding.right), - bounds.height - (padding.top + padding.bottom)); + bounds.x + padding.left, + bounds.y + padding.top, + bounds.width - (padding.left + padding.right), + bounds.height - (padding.top + padding.bottom), + ); } else if (PdfGridRowHelper.getHelper(row!).grid.style.cellPadding != PdfPaddings(left: 0, right: 0, top: 0, bottom: 0)) { final PdfPaddings padding = PdfGridRowHelper.getHelper(row!).grid.style.cellPadding; bounds = PdfRectangle( - bounds.x + padding.left, - bounds.y + padding.top, - bounds.width - (padding.left + padding.right), - bounds.height - (padding.top + padding.bottom)); + bounds.x + padding.left, + bounds.y + padding.top, + bounds.width - (padding.left + padding.right), + bounds.height - (padding.top + padding.bottom), + ); } return _setImagePosition(graphics, image, bounds); } @@ -1543,8 +1613,12 @@ class PdfGridCellHelper { final double cellSpacing = PdfGridRowHelper.getHelper(row!).grid.style.cellSpacing; if (cellSpacing > 0) { - bounds = PdfRectangle(bounds.x + cellSpacing, bounds.y + cellSpacing, - bounds.width - cellSpacing, bounds.height - cellSpacing); + bounds = PdfRectangle( + bounds.x + cellSpacing, + bounds.y + cellSpacing, + bounds.width - cellSpacing, + bounds.height - cellSpacing, + ); } final int currentColIndex = row!.cells.indexOf(base); if (base.columnSpan > 1 || @@ -1554,9 +1628,11 @@ class PdfGridCellHelper { isCellMergeContinue)) { int span = base.columnSpan; if (span == 1 && isCellMergeContinue) { - for (int j = currentColIndex + 1; - j < PdfGridRowHelper.getHelper(row!).grid.columns.count; - j++) { + for ( + int j = currentColIndex + 1; + j < PdfGridRowHelper.getHelper(row!).grid.columns.count; + j++ + ) { if (PdfGridCellHelper.getHelper(row!.cells[j]).isCellMergeContinue) { span++; } else { @@ -1566,29 +1642,30 @@ class PdfGridCellHelper { } double totalWidth = 0; for (int i = currentColIndex; i < currentColIndex + span; i++) { - if (PdfGridRowHelper.getHelper(row!) - .grid - .style - .allowHorizontalOverflow) { + if (PdfGridRowHelper.getHelper( + row!, + ).grid.style.allowHorizontalOverflow) { double width; - final double compWidth = PdfGridHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid) - .size - .width < - g!.clientSize.width - ? PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .size - .width - : g.clientSize.width; - if (PdfGridHelper.getHelper(PdfGridRowHelper.getHelper(row!).grid) - .size - .width > + final double compWidth = + PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).size.width < + g!.clientSize.width + ? PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).size.width + : g.clientSize.width; + if (PdfGridHelper.getHelper( + PdfGridRowHelper.getHelper(row!).grid, + ).size.width > g.clientSize.width) { - width = bounds.x + + width = + bounds.x + totalWidth + PdfGridRowHelper.getHelper(row!).grid.columns[i].width; } else { - width = totalWidth + + width = + totalWidth + PdfGridRowHelper.getHelper(row!).grid.columns[i].width; } if (width > compWidth) { @@ -1603,30 +1680,34 @@ class PdfGridCellHelper { if (base.rowSpan > 1 || PdfGridRowHelper.getHelper(row!).rowSpanExists) { int span = base.rowSpan; int currentRowIndex = PdfGridRowCollectionHelper.indexOf( - PdfGridRowHelper.getHelper(row!).grid.rows, row); + PdfGridRowHelper.getHelper(row!).grid.rows, + row, + ); if (currentRowIndex == -1) { currentRowIndex = PdfGridHeaderCollectionHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.headers) - .indexOf(row!); + PdfGridRowHelper.getHelper(row!).grid.headers, + ).indexOf(row!); if (currentRowIndex != -1) { isHeader = true; } } if (span == 1 && isCellMergeContinue) { - for (int j = currentRowIndex + 1; - j < PdfGridRowHelper.getHelper(row!).grid.rows.count; - j++) { + for ( + int j = currentRowIndex + 1; + j < PdfGridRowHelper.getHelper(row!).grid.rows.count; + j++ + ) { if (isHeader - ? PdfGridCellHelper.getHelper(PdfGridRowHelper.getHelper(row!) - .grid - .headers[j] - .cells[currentColIndex]) - .isCellMergeContinue - : PdfGridCellHelper.getHelper(PdfGridRowHelper.getHelper(row!) - .grid - .rows[j] - .cells[currentColIndex]) - .isCellMergeContinue) { + ? PdfGridCellHelper.getHelper( + PdfGridRowHelper.getHelper( + row!, + ).grid.headers[j].cells[currentColIndex], + ).isCellMergeContinue + : PdfGridCellHelper.getHelper( + PdfGridRowHelper.getHelper( + row!, + ).grid.rows[j].cells[currentColIndex], + ).isCellMergeContinue) { span++; } else { break; @@ -1645,42 +1726,50 @@ class PdfGridCellHelper { } else { for (int i = currentRowIndex; i < currentRowIndex + span; i++) { if (!PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[i]) - .isRowSpanRowHeightSet) { + PdfGridRowHelper.getHelper(row!).grid.rows[i], + ).isRowSpanRowHeightSet) { PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[i]) - .isRowHeightSet = false; + PdfGridRowHelper.getHelper(row!).grid.rows[i], + ).isRowHeightSet = + false; } - totalHeight += isHeader - ? PdfGridRowHelper.getHelper(row!).grid.headers[i].height - : PdfGridRowHelper.getHelper(row!).grid.rows[i].height; + totalHeight += + isHeader + ? PdfGridRowHelper.getHelper(row!).grid.headers[i].height + : PdfGridRowHelper.getHelper(row!).grid.rows[i].height; final PdfGridRow gridRow = PdfGridRowHelper.getHelper(row!).grid.rows[i]; final int rowIndex = PdfGridRowCollectionHelper.indexOf( - PdfGridRowHelper.getHelper(row!).grid.rows, gridRow); + PdfGridRowHelper.getHelper(row!).grid.rows, + gridRow, + ); if (base.rowSpan > 1) { - for (int cellIndex = 0; - cellIndex < gridRow.cells.count; - cellIndex++) { + for ( + int cellIndex = 0; + cellIndex < gridRow.cells.count; + cellIndex++ + ) { final PdfGridCell cell = gridRow.cells[cellIndex]; if (cell.rowSpan > 1) { double tempHeight = 0; for (int j = i; j < i + cell.rowSpan; j++) { if (!PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[j]) - .isRowSpanRowHeightSet) { + PdfGridRowHelper.getHelper(row!).grid.rows[j], + ).isRowSpanRowHeightSet) { PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[j]) - .isRowHeightSet = false; + PdfGridRowHelper.getHelper(row!).grid.rows[j], + ).isRowHeightSet = + false; } tempHeight += PdfGridRowHelper.getHelper(row!).grid.rows[j].height; if (!PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[j]) - .isRowSpanRowHeightSet) { + PdfGridRowHelper.getHelper(row!).grid.rows[j], + ).isRowSpanRowHeightSet) { PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[j]) - .isRowHeightSet = true; + PdfGridRowHelper.getHelper(row!).grid.rows[j], + ).isRowHeightSet = + true; } } if (cell.height > tempHeight) { @@ -1691,43 +1780,47 @@ class PdfGridCellHelper { max += base._tempRowSpanRemainingHeight; } final int index = gridRow.cells.indexOf(cell); - PdfGridCellHelper.getHelper(PdfGridRowHelper.getHelper(row!) - .grid - .rows[(rowIndex + cell.rowSpan) - 1] - .cells[index]) - .rowSpanRemainingHeight = max; + PdfGridCellHelper.getHelper( + PdfGridRowHelper.getHelper(row!) + .grid + .rows[(rowIndex + cell.rowSpan) - 1] + .cells[index], + ).rowSpanRemainingHeight = + max; base._tempRowSpanRemainingHeight = PdfGridCellHelper.getHelper( - PdfGridRowHelper.getHelper(row!) - .grid - .rows[(rowIndex + cell.rowSpan) - 1] - .cells[index]) - .rowSpanRemainingHeight; + PdfGridRowHelper.getHelper(row!) + .grid + .rows[(rowIndex + cell.rowSpan) - 1] + .cells[index], + ).rowSpanRemainingHeight; } } } } } if (!PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[i]) - .isRowSpanRowHeightSet) { + PdfGridRowHelper.getHelper(row!).grid.rows[i], + ).isRowSpanRowHeightSet) { PdfGridRowHelper.getHelper( - PdfGridRowHelper.getHelper(row!).grid.rows[i]) - .isRowHeightSet = true; + PdfGridRowHelper.getHelper(row!).grid.rows[i], + ).isRowHeightSet = + true; } } final int cellIndex = row!.cells.indexOf(base); totalHeight -= PdfGridRowHelper.getHelper(row!).grid.style.cellSpacing; if (row!.cells[cellIndex].height > totalHeight && - (!PdfGridRowHelper.getHelper(PdfGridRowHelper.getHelper(row!) - .grid - .rows[(currentRowIndex + span) - 1]) - .isRowHeightSet)) { - PdfGridCellHelper.getHelper(PdfGridRowHelper.getHelper(row!) - .grid - .rows[(currentRowIndex + span) - 1] - .cells[cellIndex]) - .rowSpanRemainingHeight = + (!PdfGridRowHelper.getHelper( + PdfGridRowHelper.getHelper( + row!, + ).grid.rows[(currentRowIndex + span) - 1], + ).isRowHeightSet)) { + PdfGridCellHelper.getHelper( + PdfGridRowHelper.getHelper( + row!, + ).grid.rows[(currentRowIndex + span) - 1].cells[cellIndex], + ).rowSpanRemainingHeight = row!.cells[cellIndex].height - totalHeight; totalHeight = row!.cells[cellIndex].height; bounds.height = totalHeight; @@ -1743,7 +1836,10 @@ class PdfGridCellHelper { } PdfGraphics? _setImagePosition( - PdfGraphics? graphics, PdfImage? image, PdfRectangle bounds) { + PdfGraphics? graphics, + PdfImage? image, + PdfRectangle bounds, + ) { if (base._imagePosition == PdfGridImagePosition.stretch) { graphics!.drawImage(image!, bounds.rect); } else if (base._imagePosition == PdfGridImagePosition.center) { @@ -1752,9 +1848,14 @@ class PdfGridCellHelper { gridCentreX = bounds.x + (bounds.width / 4); gridCentreY = bounds.y + (bounds.height / 4); graphics!.drawImage( - image!, - Rect.fromLTWH( - gridCentreX, gridCentreY, bounds.width / 2, bounds.height / 2)); + image!, + Rect.fromLTWH( + gridCentreX, + gridCentreY, + bounds.width / 2, + bounds.height / 2, + ), + ); } else if (base._imagePosition == PdfGridImagePosition.fit) { final double imageWidth = image!.physicalDimension.width; final double imageHeight = image.physicalDimension.height; @@ -1764,12 +1865,16 @@ class PdfGridCellHelper { y = bounds.y; x = bounds.x + bounds.width / 4; graphics!.drawImage( - image, Rect.fromLTWH(x, y, bounds.width / 2, bounds.height)); + image, + Rect.fromLTWH(x, y, bounds.width / 2, bounds.height), + ); } else { x = bounds.x; y = bounds.y + (bounds.height / 4); graphics!.drawImage( - image, Rect.fromLTWH(x, y, bounds.width, bounds.height / 2)); + image, + Rect.fromLTWH(x, y, bounds.width, bounds.height / 2), + ); } } else if (base._imagePosition == PdfGridImagePosition.tile) { final double cellLeft = bounds.x; @@ -1781,8 +1886,10 @@ class PdfGridCellHelper { for (; y < bounds.bottom;) { for (x = cellLeft; x! < bounds.right;) { if (x + pWidth > bounds.right && y + pHeight > bounds.bottom) { - final PdfTemplate template = - PdfTemplate(bounds.right - x, bounds.bottom - y); + final PdfTemplate template = PdfTemplate( + bounds.right - x, + bounds.bottom - y, + ); template.graphics!.drawImage(image!, Rect.zero); graphics!.drawPdfTemplate(template, Offset(x, y)); } else if (x + pWidth > bounds.right) { diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_row.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_row.dart index 12e28d0b8..de03b4e42 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_row.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/pdf_grid_row.dart @@ -281,8 +281,9 @@ class PdfGridRow { bool isHeader = false; double rowHeight = cells[0].rowSpan > 1 ? 0 : cells[0].height; double maxHeight = 0; - if (PdfGridHeaderCollectionHelper.getHelper(_helper.grid.headers) - .indexOf(this) != + if (PdfGridHeaderCollectionHelper.getHelper( + _helper.grid.headers, + ).indexOf(this) != -1) { isHeader = true; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/pdf_borders.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/pdf_borders.dart index f080cd800..802ef6ed7 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/pdf_borders.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/pdf_borders.dart @@ -111,7 +111,10 @@ class PdfPaddings { set all(double value) { if (value < 0) { ArgumentError.value( - value, 'all', 'value should greater than or equal to zero'); + value, + 'all', + 'value should greater than or equal to zero', + ); } _left = _right = _bottom = _top = value; } @@ -123,7 +126,10 @@ class PdfPaddings { set left(double value) { if (value < 0) { ArgumentError.value( - value, 'left', 'value should greater than or equal to zero'); + value, + 'left', + 'value should greater than or equal to zero', + ); } _left = value; } @@ -135,7 +141,10 @@ class PdfPaddings { set right(double value) { if (value < 0) { ArgumentError.value( - value, 'right', 'value should greater than or equal to zero'); + value, + 'right', + 'value should greater than or equal to zero', + ); } _right = value; } @@ -147,7 +156,10 @@ class PdfPaddings { set top(double value) { if (value < 0) { ArgumentError.value( - value, 'top', 'value should greater than or equal to zero'); + value, + 'top', + 'value should greater than or equal to zero', + ); } _top = value; } @@ -159,7 +171,10 @@ class PdfPaddings { set bottom(double value) { if (value < 0) { ArgumentError.value( - value, 'bottom', 'value should greater than or equal to zero'); + value, + 'bottom', + 'value should greater than or equal to zero', + ); } _bottom = value; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/style.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/style.dart index 968fbf462..557d3d295 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/style.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/grid/styles/style.dart @@ -25,17 +25,22 @@ abstract class PdfGridStyleBase { /// Provides customization of the appearance for the [PdfGridRow]. class PdfGridRowStyle extends PdfGridStyleBase { /// Initializes a new instance of the [PdfGridRowStyle] class. - PdfGridRowStyle( - {PdfBrush? backgroundBrush, - PdfBrush? textBrush, - PdfPen? textPen, - PdfFont? font}) { + PdfGridRowStyle({ + PdfBrush? backgroundBrush, + PdfBrush? textBrush, + PdfPen? textPen, + PdfFont? font, + }) { _initializeRowStyle(backgroundBrush, textBrush, textPen, font); } //Implementation - void _initializeRowStyle(PdfBrush? backgroundBrush, PdfBrush? textBrush, - PdfPen? textPen, PdfFont? font) { + void _initializeRowStyle( + PdfBrush? backgroundBrush, + PdfBrush? textBrush, + PdfPen? textPen, + PdfFont? font, + ) { super.backgroundBrush = backgroundBrush; super.textBrush = textBrush; super.textPen = textPen; @@ -46,15 +51,16 @@ class PdfGridRowStyle extends PdfGridStyleBase { /// Provides customization of the appearance for the [PdfGridCell]. class PdfGridCellStyle extends PdfGridRowStyle { /// Initializes a new instance of the [PdfGridCellStyle] class. - PdfGridCellStyle( - {PdfBorders? borders, - PdfStringFormat? format, - PdfImage? backgroundImage, - PdfPaddings? cellPadding, - super.backgroundBrush, - super.textBrush, - super.textPen, - super.font}) { + PdfGridCellStyle({ + PdfBorders? borders, + PdfStringFormat? format, + PdfImage? backgroundImage, + PdfPaddings? cellPadding, + super.backgroundBrush, + super.textBrush, + super.textPen, + super.font, + }) { _initializeCellStyle(borders, format, backgroundImage, cellPadding); } @@ -82,8 +88,12 @@ class PdfGridCellStyle extends PdfGridRowStyle { } //Implementation - void _initializeCellStyle(PdfBorders? borders, PdfStringFormat? format, - PdfImage? backgroundImage, PdfPaddings? cellPadding) { + void _initializeCellStyle( + PdfBorders? borders, + PdfStringFormat? format, + PdfImage? backgroundImage, + PdfPaddings? cellPadding, + ) { this.borders = borders ?? PdfBorders(); stringFormat = format; this.backgroundImage = backgroundImage; @@ -111,16 +121,24 @@ class PdfGridCellStyleHelper { class PdfGridStyle extends PdfGridStyleBase { //Constructor /// Initializes a new instance of the [PdfGridStyle] class. - PdfGridStyle( - {double? cellSpacing, - PdfPaddings? cellPadding, - PdfBorderOverlapStyle? borderOverlapStyle, - PdfBrush? backgroundBrush, - PdfBrush? textBrush, - PdfPen? textPen, - PdfFont? font}) { - _initializeStyle(cellSpacing, cellPadding, borderOverlapStyle, - backgroundBrush, textBrush, textPen, font); + PdfGridStyle({ + double? cellSpacing, + PdfPaddings? cellPadding, + PdfBorderOverlapStyle? borderOverlapStyle, + PdfBrush? backgroundBrush, + PdfBrush? textBrush, + PdfPen? textPen, + PdfFont? font, + }) { + _initializeStyle( + cellSpacing, + cellPadding, + borderOverlapStyle, + backgroundBrush, + textBrush, + textPen, + font, + ); } //Fields /// Gets or sets the cell spacing of the [PdfGrid]. @@ -152,13 +170,14 @@ class PdfGridStyle extends PdfGridStyleBase { //Implementation void _initializeStyle( - double? cellSpacing, - PdfPaddings? cellPadding, - PdfBorderOverlapStyle? borderOverlapStyle, - PdfBrush? backgroundBrush, - PdfBrush? textBrush, - PdfPen? textPen, - PdfFont? font) { + double? cellSpacing, + PdfPaddings? cellPadding, + PdfBorderOverlapStyle? borderOverlapStyle, + PdfBrush? backgroundBrush, + PdfBrush? textBrush, + PdfPen? textPen, + PdfFont? font, + ) { super.backgroundBrush = backgroundBrush; super.textBrush = textBrush; super.textPen = textPen; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/enums.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/enums.dart index f6fa6e94c..2ce2dbaee 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/enums.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/enums.dart @@ -22,7 +22,7 @@ enum PdfListMarkerAlignment { left, /// Right alignment for marker. - right + right, } /// Specifies the marker style. @@ -66,5 +66,5 @@ enum PdfUnorderedMarkerStyle { customImage, /// Marker is custom template. - customTemplate + customTemplate, } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_ordered_marker.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_ordered_marker.dart index d03662eef..5d1285711 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_ordered_marker.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_ordered_marker.dart @@ -43,11 +43,12 @@ class PdfOrderedMarker extends PdfMarker { /// //Dispose the document. /// document.dispose(); /// ``` - PdfOrderedMarker( - {this.style = PdfNumberStyle.none, - PdfFont? font, - String suffix = '', - String delimiter = ''}) { + PdfOrderedMarker({ + this.style = PdfNumberStyle.none, + PdfFont? font, + String suffix = '', + String delimiter = '', + }) { _helper = PdfOrderedMarkerHelper(this); _delimiter = delimiter; _suffix = suffix; @@ -195,6 +196,8 @@ class PdfOrderedMarkerHelper extends PdfMarkerHelper { /// Gets the marker number. String getNumber() { return PdfAutomaticFieldHelper.convert( - _startNumber + currentIndex, base.style); + _startNumber + currentIndex, + base.style, + ); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_unordered_marker.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_unordered_marker.dart index 2a2b7aee4..0d257a0d2 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_unordered_marker.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/bullets/pdf_unordered_marker.dart @@ -51,11 +51,12 @@ class PdfUnorderedMarker extends PdfMarker { /// //Dispose the document. /// document.dispose(); /// ``` - PdfUnorderedMarker( - {this.style = PdfUnorderedMarkerStyle.none, - PdfFont? font, - String? text, - PdfTemplate? template}) { + PdfUnorderedMarker({ + this.style = PdfUnorderedMarkerStyle.none, + PdfFont? font, + String? text, + PdfTemplate? template, + }) { _helper = PdfUnorderedMarkerHelper(this); if (font != null) { this.font = font; @@ -177,22 +178,31 @@ class PdfUnorderedMarkerHelper extends PdfMarkerHelper { late PdfFont unicodeFont; /// Draws the specified graphics. - void draw(PdfGraphics? graphics, Offset point, PdfBrush? brush, PdfPen? pen, - [PdfList? curList]) { + void draw( + PdfGraphics? graphics, + Offset point, + PdfBrush? brush, + PdfPen? pen, [ + PdfList? curList, + ]) { final PdfTemplate templete = PdfTemplate(size!.width, size!.height); Offset offset = Offset(point.dx, point.dy); switch (base.style) { case PdfUnorderedMarkerStyle.customTemplate: - templete.graphics! - .drawPdfTemplate(base._template!, Offset.zero, size!.size); + templete.graphics!.drawPdfTemplate( + base._template!, + Offset.zero, + size!.size, + ); offset = Offset( - point.dx, - point.dy + - ((curList!.font!.height > base.font!.height - ? curList.font!.height - : base.font!.height) / - 2) - - (size!.height / 2)); + point.dx, + point.dy + + ((curList!.font!.height > base.font!.height + ? curList.font!.height + : base.font!.height) / + 2) - + (size!.height / 2), + ); break; case PdfUnorderedMarkerStyle.customImage: // templete.graphics.drawImage( @@ -205,10 +215,13 @@ class PdfUnorderedMarkerHelper extends PdfMarkerHelper { location.x = location.x + pen.width; location.y = location.y + pen.width; } - templete.graphics!.drawString(getStyledText(), unicodeFont, - pen: pen, - brush: brush, - bounds: Rect.fromLTWH(location.x, location.y, 0, 0)); + templete.graphics!.drawString( + getStyledText(), + unicodeFont, + pen: pen, + brush: brush, + bounds: Rect.fromLTWH(location.x, location.y, 0, 0), + ); break; } graphics!.drawPdfTemplate(templete, offset); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list.dart index aacccfb6a..7a783e870 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list.dart @@ -583,8 +583,8 @@ class EndItemLayoutArgsHelper { /// //Dispose the document. /// document.dispose(); /// ``` -typedef BeginItemLayoutCallback = void Function( - Object sender, BeginItemLayoutArgs args); +typedef BeginItemLayoutCallback = + void Function(Object sender, BeginItemLayoutArgs args); /// typedef for handling EndItemLayoutEvent. /// @@ -614,5 +614,5 @@ typedef BeginItemLayoutCallback = void Function( /// //Dispose the document. /// document.dispose(); /// ``` -typedef EndItemLayoutCallback = void Function( - Object sender, EndItemLayoutArgs args); +typedef EndItemLayoutCallback = + void Function(Object sender, EndItemLayoutArgs args); diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item.dart index d7c89efc6..5d45eeddb 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item.dart @@ -42,13 +42,14 @@ class PdfListItem { /// //Dispose the document. /// document.dispose(); /// ``` - PdfListItem( - {this.text = '', - this.font, - PdfStringFormat? format, - this.pen, - this.brush, - this.subList}) { + PdfListItem({ + this.text = '', + this.font, + PdfStringFormat? format, + this.pen, + this.brush, + this.subList, + }) { stringFormat = format; } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item_collection.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item_collection.dart index fb6512044..2fb09c8f2 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item_collection.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_item_collection.dart @@ -256,7 +256,8 @@ class PdfListItemCollectionHelper extends PdfObjectCollectionHelper { PdfListItem getValue(int index) { if (index < 0 || index >= base.count) { throw RangeError( - "The index should be less than item's count or more or equal to 0"); + "The index should be less than item's count or more or equal to 0", + ); } return list[index] as PdfListItem; } @@ -274,7 +275,8 @@ class PdfListItemCollectionHelper extends PdfObjectCollectionHelper { void insert(int index, PdfListItem item, double? itemIndent) { if (index < 0 || index >= base.count) { throw ArgumentError( - "The index should be less than item's count or more or equal to 0, $index"); + "The index should be less than item's count or more or equal to 0, $index", + ); } if (itemIndent != null) { item.textIndent = itemIndent; @@ -294,7 +296,8 @@ class PdfListItemCollectionHelper extends PdfObjectCollectionHelper { void removeAt(int index) { if (index < 0 || index >= base.count) { throw ArgumentError( - "The index should be less than item's count or more or equal to 0, $index"); + "The index should be less than item's count or more or equal to 0, $index", + ); } list.removeAt(index); } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_layouter.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_layouter.dart index d4cf4817f..9523f06a4 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_layouter.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_list_layouter.dart @@ -155,11 +155,17 @@ class PdfListLayouter extends ElementLayouter { } } info.clear(); - final Rect finalBounds = - Rect.fromLTWH(bounds.x, pageResult.y!, bounds.width, resultHeight ?? 0); + final Rect finalBounds = Rect.fromLTWH( + bounds.x, + pageResult.y!, + bounds.width, + resultHeight ?? 0, + ); if (currentPage != null) { - final PdfLayoutResult result = - PdfLayoutResultHelper.load(currentPage!, finalBounds); + final PdfLayoutResult result = PdfLayoutResultHelper.load( + currentPage!, + finalBounds, + ); return result; } else { return null; @@ -183,7 +189,16 @@ class PdfListLayouter extends ElementLayouter { _beforeItemLayout(item, currentPage!); } final Map returnedValue = _drawItem( - pageResult!, x, curList!, index, indent!, info, item, height!, y!); + pageResult!, + x, + curList!, + index, + indent!, + info, + item, + height!, + y!, + ); pageResult = returnedValue['pageResult'] as _PageLayoutResult?; height = returnedValue['height'] as double?; y = returnedValue['y'] as double?; @@ -201,8 +216,11 @@ class PdfListLayouter extends ElementLayouter { if (curList is PdfOrderedList) { final PdfOrderedList oList = curList! as PdfOrderedList; PdfOrderedMarkerHelper.getHelper(oList.marker).currentIndex = index; - final ListInfo listInfo = ListInfo(curList, index, - PdfOrderedMarkerHelper.getHelper(oList.marker).getNumber()); + final ListInfo listInfo = ListInfo( + curList, + index, + PdfOrderedMarkerHelper.getHelper(oList.marker).getNumber(), + ); listInfo.brush = currentBrush; listInfo.font = currentFont; listInfo.format = currentFormat; @@ -219,8 +237,10 @@ class PdfListLayouter extends ElementLayouter { } curList = item.subList; if (curList is PdfOrderedList) { - markerMaxWidth = - _getMarkerMaxWidth(curList! as PdfOrderedList, info); + markerMaxWidth = _getMarkerMaxWidth( + curList! as PdfOrderedList, + info, + ); } index = -1; indent = indent! + curList!.indent; @@ -251,15 +271,16 @@ class PdfListLayouter extends ElementLayouter { /// Draws the item. Map _drawItem( - _PageLayoutResult pageResult, - double x, - PdfList curList, - int index, - double indent, - List listInfo, - PdfListItem item, - double height, - double y) { + _PageLayoutResult pageResult, + double x, + PdfList curList, + int index, + double indent, + List listInfo, + PdfListItem item, + double height, + double y, + ) { final PdfStringLayouter layouter = PdfStringLayouter(); PdfStringLayoutResult? markerResult; PdfStringLayoutResult? result; @@ -325,9 +346,13 @@ class PdfListLayouter extends ElementLayouter { if (markerText != null && ((marker is PdfUnorderedMarker) && (marker.style == PdfUnorderedMarkerStyle.customString))) { - markerResult = layouter.layout(markerText, _getMarkerFont(marker, item)!, - _getMarkerFormat(marker, item), - width: size.width, height: size.height); + markerResult = layouter.layout( + markerText, + _getMarkerFont(marker, item)!, + _getMarkerFormat(marker, item), + width: size.width, + height: size.height, + ); posX += markerResult.size.width; pageResult.markerWidth = markerResult.size.width; markerHeight = markerResult.size.height; @@ -353,9 +378,10 @@ class PdfListLayouter extends ElementLayouter { canDrawMarker = false; } } else { - posX += PdfUnorderedMarkerHelper.getHelper(marker as PdfUnorderedMarker) - .size! - .width; + posX += + PdfUnorderedMarkerHelper.getHelper( + marker as PdfUnorderedMarker, + ).size!.width; pageResult.markerWidth = PdfUnorderedMarkerHelper.getHelper(marker).size!.width; markerHeight = PdfUnorderedMarkerHelper.getHelper(marker).size!.height; @@ -383,7 +409,8 @@ class PdfListLayouter extends ElementLayouter { if (((itemSize.width <= 0) || (itemSize.width < itemFont!.size)) && currentPage != null) { throw Exception( - 'There is not enough space to layout the item text. Marker is too long or there is no enough space to draw it.'); + 'There is not enough space to layout the item text. Marker is too long or there is no enough space to draw it.', + ); } double itemX = posX; @@ -410,12 +437,27 @@ class PdfListLayouter extends ElementLayouter { } } - result = layouter.layout(text, itemFont!, itemFormat, - width: itemSize.width, height: itemSize.height); - final PdfRectangle rect = - PdfRectangle(itemX, posY, itemSize.width, itemSize.height); + result = layouter.layout( + text, + itemFont!, + itemFormat, + width: itemSize.width, + height: itemSize.height, + ); + final PdfRectangle rect = PdfRectangle( + itemX, + posY, + itemSize.width, + itemSize.height, + ); PdfGraphicsHelper.getHelper(graphics!).drawStringLayoutResult( - result, itemFont, itemPen, itemBrush, rect, itemFormat); + result, + itemFont, + itemPen, + itemBrush, + rect, + itemFormat, + ); y = posY; itemHeight = result.size.height; } @@ -478,31 +520,41 @@ class PdfListLayouter extends ElementLayouter { if ((marker is PdfUnorderedMarker) && marker.style == PdfUnorderedMarkerStyle.customString) { if (markerResult != null) { - wroteMaker = - _drawMarker(curList, item, markerResult, posY, pageResult.markerX); + wroteMaker = _drawMarker( + curList, + item, + markerResult, + posY, + pageResult.markerX, + ); pageResult.markerWrote = true; pageResult.markerWidth = markerResult.size.width; } } else { if (canDrawMarker && !pageResult.markerWrote) { - wroteMaker = - _drawMarker(curList, item, markerResult, posY, pageResult.markerX); + wroteMaker = _drawMarker( + curList, + item, + markerResult, + posY, + pageResult.markerX, + ); pageResult.markerWrote = wroteMaker; if (curList is PdfOrderedList) { pageResult.markerWidth = markerResult!.size.width; } else { pageResult.markerWidth = - PdfUnorderedMarkerHelper.getHelper(marker as PdfUnorderedMarker) - .size! - .width; + PdfUnorderedMarkerHelper.getHelper( + marker as PdfUnorderedMarker, + ).size!.width; } } } return { 'pageResult': pageResult, 'height': height, - 'y': y + 'y': y, }; } @@ -528,7 +580,12 @@ class PdfListLayouter extends ElementLayouter { for (int i = 0; i < list.items.count; i++) { final PdfStringLayoutResult result = _createOrderedMarkerResult( - list, list.items[i], i + list.marker.startNumber, info, true); + list, + list.items[i], + i + list.marker.startNumber, + info, + true, + ); if (width! < result.size.width) { width = result.size.width; @@ -538,8 +595,13 @@ class PdfListLayouter extends ElementLayouter { } /// Creates the ordered marker result. - PdfStringLayoutResult _createOrderedMarkerResult(PdfList list, - PdfListItem? item, int index, List info, bool findMaxWidth) { + PdfStringLayoutResult _createOrderedMarkerResult( + PdfList list, + PdfListItem? item, + int index, + List info, + bool findMaxWidth, + ) { PdfOrderedList orderedList = list as PdfOrderedList; PdfOrderedMarker marker = orderedList.marker; PdfOrderedMarkerHelper.getHelper(marker).currentIndex = index; @@ -547,7 +609,8 @@ class PdfListLayouter extends ElementLayouter { String text = ''; if (orderedList.marker.style != PdfNumberStyle.none) { - text = PdfOrderedMarkerHelper.getHelper(orderedList.marker).getNumber() + + text = + PdfOrderedMarkerHelper.getHelper(orderedList.marker).getNumber() + orderedList.marker.suffix; } if (orderedList.markerHierarchy) { @@ -579,8 +642,12 @@ class PdfListLayouter extends ElementLayouter { markerFormat = _setMarkerStringFormat(marker, markerFormat); } final PdfStringLayoutResult result = layouter.layout( - text, markerFont, markerFormat, - width: markerSize.width, height: markerSize.height); + text, + markerFont, + markerFormat, + width: markerSize.width, + height: markerSize.height, + ); return result; } @@ -611,10 +678,13 @@ class PdfListLayouter extends ElementLayouter { /// Sets the marker alingment. PdfStringFormat _setMarkerStringFormat( - PdfOrderedMarker marker, PdfStringFormat? markerFormat) { - markerFormat = markerFormat == null - ? PdfStringFormat() - : _markerFormatClone(markerFormat); + PdfOrderedMarker marker, + PdfStringFormat? markerFormat, + ) { + markerFormat = + markerFormat == null + ? PdfStringFormat() + : _markerFormatClone(markerFormat); if (marker.stringFormat == null) { markerFormat.alignment = PdfTextAlignment.right; if (PdfMarkerHelper.getHelper(marker).rightToLeft) { @@ -629,7 +699,9 @@ class PdfListLayouter extends ElementLayouter { PdfStringFormat _markerFormatClone(PdfStringFormat format) { final PdfStringFormat markerFormat = PdfStringFormat( - alignment: format.alignment, lineAlignment: format.lineAlignment); + alignment: format.alignment, + lineAlignment: format.lineAlignment, + ); markerFormat.lineSpacing = format.lineSpacing; markerFormat.characterSpacing = format.characterSpacing; markerFormat.clipPath = format.clipPath; @@ -648,12 +720,18 @@ class PdfListLayouter extends ElementLayouter { /// Before the page layout. bool _beforePageLayout( - Rect currentBounds, PdfPage? currentPage, PdfList list) { + Rect currentBounds, + PdfPage? currentPage, + PdfList list, + ) { bool cancel = false; if (PdfLayoutElementHelper.getHelper(element!).raiseBeginPageLayout && currentPage != null) { - final ListBeginPageLayoutArgs args = - ListBeginPageLayoutArgs._(currentBounds, currentPage, list); + final ListBeginPageLayoutArgs args = ListBeginPageLayoutArgs._( + currentBounds, + currentPage, + list, + ); PdfLayoutElementHelper.getHelper(element!).onBeginPageLayout(args); cancel = args.cancel; @@ -665,12 +743,17 @@ class PdfListLayouter extends ElementLayouter { /// After the page layouted. ListEndPageLayoutArgs? _afterPageLayouted( - Rect bounds, PdfPage? currentPage, PdfList list) { + Rect bounds, + PdfPage? currentPage, + PdfList list, + ) { ListEndPageLayoutArgs? args; if (PdfLayoutElementHelper.getHelper(element!).raisePageLayouted && currentPage != null) { - final PdfLayoutResult result = - PdfLayoutResultHelper.load(currentPage, bounds); + final PdfLayoutResult result = PdfLayoutResultHelper.load( + currentPage, + bounds, + ); args = ListEndPageLayoutArgs._internal(result, list); PdfLayoutElementHelper.getHelper(element!).onEndPageLayout(args); } @@ -679,8 +762,10 @@ class PdfListLayouter extends ElementLayouter { /// Before the item layout. void _beforeItemLayout(PdfListItem item, PdfPage page) { - final BeginItemLayoutArgs args = - BeginItemLayoutArgsHelper.internal(item, page); + final BeginItemLayoutArgs args = BeginItemLayoutArgsHelper.internal( + item, + page, + ); PdfListHelper.getHelper(element!).onBeginItemLayout(args); } @@ -691,8 +776,13 @@ class PdfListLayouter extends ElementLayouter { } /// Draws the marker. - bool _drawMarker(PdfList curList, PdfListItem item, - PdfStringLayoutResult? markerResult, double posY, double posX) { + bool _drawMarker( + PdfList curList, + PdfListItem item, + PdfStringLayoutResult? markerResult, + double posY, + double posX, + ) { if (curList is PdfOrderedList) { if (markerResult != null) { if (curList.font != null && @@ -704,10 +794,11 @@ class PdfListLayouter extends ElementLayouter { _drawOrderedMarker(curList, markerResult!, item, posX, posY); } else if (curList is PdfUnorderedList) { if (curList.marker.font != null && markerResult != null) { - final PdfFont font = curList.font != null && - curList.font!.size > curList.marker.font!.size - ? curList.font! - : curList.marker.font!; + final PdfFont font = + curList.font != null && + curList.font!.size > curList.marker.font!.size + ? curList.font! + : curList.marker.font!; if (font.size > markerResult.size.height) { posY += (font.height / 2) - (markerResult.size.height / 2); markerResult.size.height = markerResult.size.height + posY; @@ -720,33 +811,45 @@ class PdfListLayouter extends ElementLayouter { /// Draws the ordered marker. PdfStringLayoutResult _drawOrderedMarker( - PdfList curList, - PdfStringLayoutResult markerResult, - PdfListItem item, - double posX, - double posY) { + PdfList curList, + PdfStringLayoutResult markerResult, + PdfListItem item, + double posX, + double posY, + ) { final PdfOrderedList oList = curList as PdfOrderedList; final PdfOrderedMarker marker = oList.marker; final PdfFont markerFont = _getMarkerFont(marker, item)!; PdfStringFormat? markerFormat = _getMarkerFormat(marker, item); final PdfPen? markerPen = _getMarkerPen(marker, item); final PdfBrush? markerBrush = _getMarkerBrush(marker, item); - final PdfRectangle rect = PdfRectangle(posX - markerMaxWidth!, posY, - markerResult.size.width, markerResult.size.height); + final PdfRectangle rect = PdfRectangle( + posX - markerMaxWidth!, + posY, + markerResult.size.width, + markerResult.size.height, + ); rect.width = markerMaxWidth! as double; markerFormat = _setMarkerStringFormat(marker, markerFormat); PdfGraphicsHelper.getHelper(graphics!).drawStringLayoutResult( - markerResult, markerFont, markerPen, markerBrush, rect, markerFormat); + markerResult, + markerFont, + markerPen, + markerBrush, + rect, + markerFormat, + ); return markerResult; } /// Draws the unordered marker. PdfStringLayoutResult? _drawUnorderedMarker( - PdfList curList, - PdfStringLayoutResult? markerResult, - PdfListItem item, - double posX, - double posY) { + PdfList curList, + PdfStringLayoutResult? markerResult, + PdfListItem item, + double posX, + double posY, + ) { final PdfUnorderedList uList = curList as PdfUnorderedList; final PdfUnorderedMarker marker = uList.marker; final PdfFont? markerFont = _getMarkerFont(marker, item); @@ -757,27 +860,36 @@ class PdfListLayouter extends ElementLayouter { final PdfPoint location = PdfPoint(posX - markerResult.size.width, posY); PdfUnorderedMarkerHelper.getHelper(marker).size = markerResult.size; if (marker.style == PdfUnorderedMarkerStyle.customString) { - final PdfRectangle rect = PdfRectangle(location.x, location.y, - markerResult.size.width, markerResult.size.height); + final PdfRectangle rect = PdfRectangle( + location.x, + location.y, + markerResult.size.width, + markerResult.size.height, + ); PdfGraphicsHelper.getHelper(graphics!).drawStringLayoutResult( - markerResult, - markerFont!, - markerPen, - markerBrush, - rect, - markerFormat); + markerResult, + markerFont!, + markerPen, + markerBrush, + rect, + markerFormat, + ); } else { PdfUnorderedMarkerHelper.getHelper(marker).unicodeFont = PdfStandardFont(PdfFontFamily.zapfDingbats, markerFont!.size); - PdfUnorderedMarkerHelper.getHelper(marker) - .draw(graphics, location.offset, markerBrush, markerPen); + PdfUnorderedMarkerHelper.getHelper( + marker, + ).draw(graphics, location.offset, markerBrush, markerPen); } } else { - PdfUnorderedMarkerHelper.getHelper(marker).size = - PdfSize(markerFont!.size, markerFont.size); + PdfUnorderedMarkerHelper.getHelper(marker).size = PdfSize( + markerFont!.size, + markerFont.size, + ); final PdfPoint location = PdfPoint(posX - markerFont.size, posY); - PdfUnorderedMarkerHelper.getHelper(marker) - .draw(graphics, location.offset, markerBrush, markerPen, curList); + PdfUnorderedMarkerHelper.getHelper( + marker, + ).draw(graphics, location.offset, markerBrush, markerPen, curList); } return null; } @@ -808,11 +920,20 @@ class PdfListLayouter extends ElementLayouter { /// Creates the marker result. PdfStringLayoutResult? _createMarkerResult( - int index, PdfList curList, List listInfo, PdfListItem item) { + int index, + PdfList curList, + List listInfo, + PdfListItem item, + ) { PdfStringLayoutResult? markerResult; if (curList is PdfOrderedList) { - markerResult = - _createOrderedMarkerResult(curList, item, index, info, false); + markerResult = _createOrderedMarkerResult( + curList, + item, + index, + info, + false, + ); } else { final PdfSize markerSize = PdfSize.empty; markerResult = _createUnorderedMarkerResult(curList, item, markerSize); @@ -822,7 +943,10 @@ class PdfListLayouter extends ElementLayouter { /// Creates the unordered marker result. PdfStringLayoutResult? _createUnorderedMarkerResult( - PdfList curList, PdfListItem item, PdfSize markerSize) { + PdfList curList, + PdfListItem item, + PdfSize markerSize, + ) { final PdfUnorderedMarker marker = (curList as PdfUnorderedList).marker; PdfStringLayoutResult? result; final PdfFont? markerFont = _getMarkerFont(marker, item); @@ -838,23 +962,33 @@ class PdfListLayouter extends ElementLayouter { PdfUnorderedMarkerHelper.getHelper(marker).size = markerSize; break; case PdfUnorderedMarkerStyle.customString: - result = layouter.layout(marker.text!, markerFont!, markerFormat, - width: size.width, height: size.height); + result = layouter.layout( + marker.text!, + markerFont!, + markerFormat, + width: size.width, + height: size.height, + ); break; // ignore: no_default_cases default: - final PdfStandardFont uFont = - PdfStandardFont(PdfFontFamily.zapfDingbats, markerFont!.size); + final PdfStandardFont uFont = PdfStandardFont( + PdfFontFamily.zapfDingbats, + markerFont!.size, + ); result = layouter.layout( - PdfUnorderedMarkerHelper.getHelper(marker).getStyledText(), - uFont, - null, - width: size.width, - height: size.height); + PdfUnorderedMarkerHelper.getHelper(marker).getStyledText(), + uFont, + null, + width: size.width, + height: size.height, + ); PdfUnorderedMarkerHelper.getHelper(marker).size = result.size; if (marker.pen != null) { - result.size = PdfSize(result.size.width + 2 * marker.pen!.width, - result.size.height + 2 * marker.pen!.width); + result.size = PdfSize( + result.size.width + 2 * marker.pen!.width, + result.size.height + 2 * marker.pen!.width, + ); } break; } @@ -930,7 +1064,10 @@ class ListBeginPageLayoutArgs extends BeginPageLayoutArgs { class ListBeginPageLayoutArgsHelper { /// internal method static ListBeginPageLayoutArgs internal( - Rect bounds, PdfPage page, PdfList list) { + Rect bounds, + PdfPage page, + PdfList list, + ) { return ListBeginPageLayoutArgs._(bounds, page, list); } } diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_ordered_list.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_ordered_list.dart index 393628624..4cecb78fb 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_ordered_list.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_ordered_list.dart @@ -51,17 +51,17 @@ class PdfOrderedList extends PdfList { /// //Dispose the document. /// document.dispose(); /// ``` - PdfOrderedList( - {PdfOrderedMarker? marker, - PdfListItemCollection? items, - String? text, - PdfFont? font, - PdfNumberStyle style = PdfNumberStyle.numeric, - PdfStringFormat? format, - this.markerHierarchy = false, - double indent = 10, - double textIndent = 5}) - : super() { + PdfOrderedList({ + PdfOrderedMarker? marker, + PdfListItemCollection? items, + String? text, + PdfFont? font, + PdfNumberStyle style = PdfNumberStyle.numeric, + PdfStringFormat? format, + this.markerHierarchy = false, + double indent = 10, + double textIndent = 5, + }) : super() { final PdfListHelper helper = PdfListHelper(this); this.marker = marker ?? _createMarker(style); stringFormat = format; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_unordered_list.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_unordered_list.dart index c812282c9..10643424e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_unordered_list.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/structured_elements/lists/pdf_unordered_list.dart @@ -49,16 +49,16 @@ class PdfUnorderedList extends PdfList { /// //Dispose the document. /// document.dispose(); /// ``` - PdfUnorderedList( - {PdfUnorderedMarker? marker, - PdfListItemCollection? items, - String? text, - PdfFont? font, - PdfUnorderedMarkerStyle style = PdfUnorderedMarkerStyle.disk, - PdfStringFormat? format, - double indent = 10, - double textIndent = 5}) - : super() { + PdfUnorderedList({ + PdfUnorderedMarker? marker, + PdfListItemCollection? items, + String? text, + PdfFont? font, + PdfUnorderedMarkerStyle style = PdfUnorderedMarkerStyle.disk, + PdfStringFormat? format, + double indent = 10, + double textIndent = 5, + }) : super() { final PdfListHelper helper = PdfListHelper(this); this.marker = marker ?? _createMarker(style); stringFormat = format; diff --git a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/xmp/xmp_metadata.dart b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/xmp/xmp_metadata.dart index 548346a68..9eda7fc0e 100644 --- a/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/xmp/xmp_metadata.dart +++ b/packages/syncfusion_flutter_pdf/lib/src/pdf/implementation/xmp/xmp_metadata.dart @@ -72,7 +72,8 @@ class XmpMetadata implements IPdfWrapper { count++; if (count > 1) { throw ArgumentError( - 'More than one element satisfies the specified condition'); + 'More than one element satisfies the specified condition', + ); } } } @@ -114,10 +115,12 @@ class XmpMetadata implements IPdfWrapper { void _initializeStream() { _stream!.beginSave = beginSave; _stream!.endSave = endSave; - _stream![PdfDictionaryProperties.type] = - PdfName(PdfDictionaryProperties.metadata); - _stream![PdfDictionaryProperties.subtype] = - PdfName(PdfDictionaryProperties.xml); + _stream![PdfDictionaryProperties.type] = PdfName( + PdfDictionaryProperties.metadata, + ); + _stream![PdfDictionaryProperties.subtype] = PdfName( + PdfDictionaryProperties.xml, + ); _stream!.compress = false; } @@ -159,67 +162,118 @@ class XmpMetadata implements IPdfWrapper { final XmlElement rdf = _createElement('rdf', 'RDF', _rdfUri); _addNamespace('rdf', _rdfUri); if (!_isNullOrEmpty(info.producer) || !_isNullOrEmpty(info.keywords)) { - final String? pdfNamespace = - _addNamespace('pdf', 'http://ns.adobe.com/pdf/1.3/'); - final XmlElement rdfDescription = - _createElement('rdf', 'Description', _rdfUri); + final String? pdfNamespace = _addNamespace( + 'pdf', + 'http://ns.adobe.com/pdf/1.3/', + ); + final XmlElement rdfDescription = _createElement( + 'rdf', + 'Description', + _rdfUri, + ); rdfDescription.setAttribute('rdf:about', ' '); if (!_isNullOrEmpty(info.producer)) { - rdfDescription.children.add(XmlElement( - XmlName('Producer', 'pdf'), [ - XmlAttribute(XmlName('pdf', 'xmlns'), pdfNamespace!) - ], [ - XmlText(info.producer) - ])); + rdfDescription.children.add( + XmlElement( + XmlName('Producer', 'pdf'), + [ + XmlAttribute(XmlName('pdf', 'xmlns'), pdfNamespace!), + ], + [XmlText(info.producer)], + ), + ); } if (!_isNullOrEmpty(info.keywords)) { - rdfDescription.children.add(XmlElement( - XmlName('Keywords', 'pdf'), [ - XmlAttribute(XmlName('pdf', 'xmlns'), pdfNamespace!) - ], [ - XmlText(info.keywords) - ])); + rdfDescription.children.add( + XmlElement( + XmlName('Keywords', 'pdf'), + [ + XmlAttribute(XmlName('pdf', 'xmlns'), pdfNamespace!), + ], + [XmlText(info.keywords)], + ), + ); } rdf.children.add(rdfDescription); } if (!_isNullOrEmpty(info.creator)) { - final XmlElement xmpDescription = - _createElement('rdf', 'Description', _rdfUri); + final XmlElement xmpDescription = _createElement( + 'rdf', + 'Description', + _rdfUri, + ); xmpDescription.setAttribute('rdf:about', ' '); final String? xmpNamespace = _addNamespace('xmp', _xap); xmpDescription.setAttribute('xmlns:xmp', xmpNamespace); if (!_isNullOrEmpty(info.creator)) { - xmpDescription.children.add(XmlElement(XmlName('CreatorTool', 'xmp'), - [], [XmlText(info.creator)])); + xmpDescription.children.add( + XmlElement(XmlName('CreatorTool', 'xmp'), [], [ + XmlText(info.creator), + ]), + ); } final String createDate = _getDateTime( - PdfDocumentInformationHelper.getHelper(info).creationDate); - xmpDescription.children.add(XmlElement(XmlName('CreateDate', 'xmp'), - [], [XmlText(createDate)])); + PdfDocumentInformationHelper.getHelper(info).creationDate, + ); + xmpDescription.children.add( + XmlElement(XmlName('CreateDate', 'xmp'), [], [ + XmlText(createDate), + ]), + ); if (!PdfDocumentInformationHelper.getHelper(info).isRemoveModifyDate) { final String modificationDate = _getDateTime( - PdfDocumentInformationHelper.getHelper(info).modificationDate); - xmpDescription.children.add(XmlElement(XmlName('ModifyDate', 'xmp'), - [], [XmlText(modificationDate)])); + PdfDocumentInformationHelper.getHelper(info).modificationDate, + ); + xmpDescription.children.add( + XmlElement(XmlName('ModifyDate', 'xmp'), [], [ + XmlText(modificationDate), + ]), + ); } rdf.children.add(xmpDescription); } //Dublin Core Schema final String? dublinNamespace = _addNamespace('dc', _dublinSchema); - final XmlElement dublinDescription = - _createElement('rdf', 'Description', _rdfUri); + final XmlElement dublinDescription = _createElement( + 'rdf', + 'Description', + _rdfUri, + ); dublinDescription.setAttribute('rdf:about', ' '); dublinDescription.setAttribute('xmlns:dc', dublinNamespace); - dublinDescription.children.add(XmlElement(XmlName('format', 'dc'), - [], [XmlText('application/pdf')])); + dublinDescription.children.add( + XmlElement(XmlName('format', 'dc'), [], [ + XmlText('application/pdf'), + ]), + ); _createDublinCoreContainer( - dublinDescription, 'title', info.title, true, 'Alt'); + dublinDescription, + 'title', + info.title, + true, + 'Alt', + ); _createDublinCoreContainer( - dublinDescription, 'description', info.subject, true, 'Alt'); + dublinDescription, + 'description', + info.subject, + true, + 'Alt', + ); _createDublinCoreContainer( - dublinDescription, 'subject', info.keywords, false, 'Bag'); + dublinDescription, + 'subject', + info.keywords, + false, + 'Bag', + ); _createDublinCoreContainer( - dublinDescription, 'creator', info.author, false, 'Seq'); + dublinDescription, + 'creator', + info.author, + false, + 'Seq', + ); rdf.children.add(dublinDescription); if (PdfDocumentInformationHelper.getHelper(_documentInfo!).conformance == PdfConformanceLevel.a1b || @@ -227,15 +281,18 @@ class XmpMetadata implements IPdfWrapper { PdfConformanceLevel.a2b || PdfDocumentInformationHelper.getHelper(_documentInfo!).conformance == PdfConformanceLevel.a3b) { - final String? pdfaid = - _addNamespace('pdfaid', 'http://www.aiim.org/pdfa/ns/id/'); + final String? pdfaid = _addNamespace( + 'pdfaid', + 'http://www.aiim.org/pdfa/ns/id/', + ); final XmlElement pdfA = _createElement('rdf', 'Description', _rdfUri); pdfA.setAttribute('rdf:about', ' '); if (PdfDocumentInformationHelper.getHelper(_documentInfo!).conformance == PdfConformanceLevel.a1b) { pdfA.setAttribute('pdfaid:part', '1'); - } else if (PdfDocumentInformationHelper.getHelper(_documentInfo!) - .conformance == + } else if (PdfDocumentInformationHelper.getHelper( + _documentInfo!, + ).conformance == PdfConformanceLevel.a2b) { pdfA.setAttribute('pdfaid:part', '2'); } else { @@ -255,19 +312,24 @@ class XmpMetadata implements IPdfWrapper { } XmlElement _createElement( - String prefix, String localName, String namespaceURI) { + String prefix, + String localName, + String namespaceURI, + ) { XmlElement element; if (!_namespaceCollection.containsKey(prefix) && prefix != 'xml' && prefix != 'xmlns') { element = XmlElement( - XmlName(localName, prefix), - [XmlAttribute(XmlName(prefix, 'xmlns'), namespaceURI)], - [], - false); + XmlName(localName, prefix), + [XmlAttribute(XmlName(prefix, 'xmlns'), namespaceURI)], + [], + false, + ); } else { - element = - XmlElement(XmlName(localName, prefix == 'xap' ? 'xmp' : prefix)); + element = XmlElement( + XmlName(localName, prefix == 'xap' ? 'xmp' : prefix), + ); } _addNamespace(prefix, namespaceURI); return element; @@ -302,11 +364,19 @@ class XmpMetadata implements IPdfWrapper { } //Creates a Dublin core containers. - void _createDublinCoreContainer(XmlElement dublinDesc, String containerName, - String? value, bool defaultLang, String element) { + void _createDublinCoreContainer( + XmlElement dublinDesc, + String containerName, + String? value, + bool defaultLang, + String element, + ) { if (!_isNullOrEmpty(value)) { - final XmlElement title = - _createElement('dc', containerName, _dublinSchema); + final XmlElement title = _createElement( + 'dc', + containerName, + _dublinSchema, + ); _addNamespace('rdf', _rdfUri); final XmlElement alt = _createElement('rdf', element, _rdfUri); XmlElement li = _createElement('rdf', 'li', _rdfUri); diff --git a/packages/syncfusion_flutter_pdf/pubspec.yaml b/packages/syncfusion_flutter_pdf/pubspec.yaml index 12ff09f7c..827da5db3 100644 --- a/packages/syncfusion_flutter_pdf/pubspec.yaml +++ b/packages/syncfusion_flutter_pdf/pubspec.yaml @@ -1,10 +1,10 @@ name: syncfusion_flutter_pdf description: The Flutter PDF is a library written natively in Dart for creating, reading, editing, and securing PDF files in Android, iOS, and web platforms. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_pdf environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_pdfviewer/CHANGELOG.md b/packages/syncfusion_flutter_pdfviewer/CHANGELOG.md index be90410f2..7ce0ced74 100644 --- a/packages/syncfusion_flutter_pdfviewer/CHANGELOG.md +++ b/packages/syncfusion_flutter_pdfviewer/CHANGELOG.md @@ -2,6 +2,48 @@ **General** +* The compatible version of our Flutter PDF Viewer widget has been updated to Flutter SDK 3.32.0. + +**Features** + +* Linux platform support has been provided. +* Added support for rendering pages using the open-source PDFium library through an optional package (`syncfusion_pdfviewer_android`). + +**Bugs** + +* Now, read-only form fields are rendered with the specified background color, or with a transparent background if no color is set. +* Now, screen readers read the selected text in PDF documents when accessibility mode is enabled. + +## [29.2.8] - 06/03/2025 + +**Bugs** + +* Now, in single page layout mode, the page changes only when swiped in the scroll direction, and not when slightly panned. +* Now, the `SfPdfViewer` widget will no longer crash with an Out of Memory exception when viewing a PDF document with large page dimensions. +* Now, in single-page layout mode, setting the zoom level in the onPageChanged callback will not cause the page to move to the bottom in the vertical scroll direction or to the right in the horizontal scroll direction. +* Now, the sticky note icon will maintain the same size on all pages, and the icon size is improved on mobile platforms. + +## [29.1.41] - 05/06/2025 + +**Bugs** + +* Improved the performance in loading large password-protected documents by leveraging the password parameter supported in the native (platform) PDF rendering APIs. +* Now, the pages will be centered in single-page layout mode when switching between pages in a PDF document with different page sizes. + +## [29.1.39] - 04/22/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +**Bugs** + +* Now, the page no longer jumps to a previous one when scrolling to the top or left edge in single page layout mode. + +## [29.1.33] - 03/25/2025 + +**General** + * The compatible version of our Flutter PDF Viewer widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter PDF Viewer example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * Provided support for [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in iOS and macOS platforms. diff --git a/packages/syncfusion_flutter_pdfviewer/android/src/main/java/com/syncfusion/flutter/pdfviewer/SyncfusionFlutterPdfViewerPlugin.java b/packages/syncfusion_flutter_pdfviewer/android/src/main/java/com/syncfusion/flutter/pdfviewer/SyncfusionFlutterPdfViewerPlugin.java index f6019f4ab..50a9d68a3 100644 --- a/packages/syncfusion_flutter_pdfviewer/android/src/main/java/com/syncfusion/flutter/pdfviewer/SyncfusionFlutterPdfViewerPlugin.java +++ b/packages/syncfusion_flutter_pdfviewer/android/src/main/java/com/syncfusion/flutter/pdfviewer/SyncfusionFlutterPdfViewerPlugin.java @@ -7,28 +7,20 @@ import android.graphics.Rect; import android.graphics.pdf.PdfRenderer; import android.os.Build; -import android.os.Handler; -import android.os.Looper; import android.os.ParcelFileDescriptor; -import android.util.DisplayMetrics; -import android.view.Display; -import android.view.WindowManager; import androidx.annotation.NonNull; import androidx.annotation.RequiresApi; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; +import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.nio.ByteBuffer; -import java.lang.Math; import io.flutter.embedding.engine.plugins.FlutterPlugin; import io.flutter.plugin.common.MethodCall; @@ -36,204 +28,229 @@ import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; -/** - * SyncfusionFlutterPdfViewerPlugin - */ +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public class SyncfusionFlutterPdfViewerPlugin implements FlutterPlugin, MethodCallHandler { - /// The MethodChannel that will the communication between Flutter and native Android - /// - /// This local reference serves to register the plugin with the Flutter Engine and unregister it - /// when the Flutter Engine is detached from the Activity - private MethodChannel channel; - /// Pdf result. - private Result resultPdf; - double viewportWidth; - private Context context; - /// Width collections of rendered pages - private double[] pageWidth; - /// Height collections of rendered pages - private double[] pageHeight; - /// Document repository. - Map documentRepo = new HashMap<>(); - - @Override - public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { - channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "syncfusion_flutter_pdfviewer"); - channel.setMethodCallHandler(this); - context = flutterPluginBinding.getApplicationContext(); - } - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - @Override - public void onMethodCall(@NonNull final MethodCall call, @NonNull final Result result) { - resultPdf = result; - switch (call.method) { - case "getPage": - getPage( - Integer.parseInt(Objects.requireNonNull(call.argument("index")).toString()), - Integer.parseInt(Objects.requireNonNull(call.argument("width")).toString()), - Integer.parseInt(Objects.requireNonNull(call.argument("height")).toString()), - (String) call.argument("documentID")); - break; - case "getTileImage": - getTileImage(Integer.parseInt(Objects.requireNonNull(call.argument("pageNumber")).toString()), - Double.parseDouble(Objects.requireNonNull(call.argument("scale")).toString()), - Double.parseDouble(Objects.requireNonNull(call.argument("x")).toString()), - Double.parseDouble(Objects.requireNonNull(call.argument("y")).toString()), - Double.parseDouble(Objects.requireNonNull(call.argument("width")).toString()), - Double.parseDouble(Objects.requireNonNull(call.argument("height")).toString()), - (String) call.argument("documentID")); - break; - case "initializePdfRenderer": - result.success(initializePdfRenderer((byte[]) call.argument("documentBytes"), - (String) call.argument("documentID"))); - break; - case "getPagesWidth": - result.success(getPagesWidth((String) call.arguments)); - break; - case "getPagesHeight": - result.success(getPagesHeight((String) call.arguments)); - break; - case "closeDocument": - result.success(closeDocument((String) call.arguments)); - break; - default: - result.notImplemented(); - break; + private MethodChannel channel; + private Context context; + private Map documentRepo = new HashMap<>(); + private ExecutorService executorService; + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { + channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "syncfusion_flutter_pdfviewer"); + channel.setMethodCallHandler(this); + context = flutterPluginBinding.getApplicationContext(); + executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); } - } - - @Override - public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { - channel.setMethodCallHandler(null); - } - - // Initializes the PDF Renderer and returns the page count. - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - String initializePdfRenderer(byte[] path, String documentID) { - try { - File file = File.createTempFile( - ".syncfusion", ".pdf" - ); - OutputStream stream = new FileOutputStream(file); - stream.write(path); - stream.close(); - ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); - PdfRenderer renderer = new PdfRenderer(fileDescriptor); - PdfFileRenderer fileRenderer = new PdfFileRenderer(fileDescriptor, renderer); - documentRepo.put(documentID, fileRenderer); - int pageCount = renderer.getPageCount(); - file.delete(); - return String.valueOf(pageCount); - } catch (Exception e) { - return e.toString(); + + @Override + public void onMethodCall(@NonNull final MethodCall call, @NonNull final Result result) { + switch (call.method) { + case "getPage": + getPage(call, result); + break; + case "getTileImage": + getTileImage(call, result); + break; + case "initializePdfRenderer": + initializePdfRenderer(call, result); + break; + case "getPagesWidth": + getPagesWidth(call, result); + break; + case "getPagesHeight": + getPagesHeight(call, result); + break; + case "closeDocument": + closeDocument(call, result); + break; + default: + result.notImplemented(); + break; + } } - } - - // Returns the height collection of rendered pages. - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - double[] getPagesHeight(String documentID) { - try { - int count = Objects.requireNonNull(documentRepo.get(documentID)).renderer.getPageCount(); - pageHeight = new double[count]; - pageWidth = new double[count]; - for (int i = 0; i < count; i++) { - PdfRenderer.Page page = Objects.requireNonNull(documentRepo.get(documentID)).renderer.openPage(i); - pageHeight[i] = page.getHeight(); - pageWidth[i] = page.getWidth(); - page.close(); - } - return pageHeight; - } catch (Exception e) { - return null; + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + channel.setMethodCallHandler(null); + executorService.shutdown(); } - } - - // Returns the width collection of rendered pages. - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - double[] getPagesWidth(String documentID) { - try { - if (pageWidth == null) { - int count = Objects.requireNonNull(documentRepo.get(documentID)).renderer.getPageCount(); - pageWidth = new double[count]; - for (int i = 0; i < count; i++) { - PdfRenderer.Page page = Objects.requireNonNull(documentRepo.get(documentID)).renderer.openPage(i); - pageWidth[i] = page.getWidth(); + + private void getPage(MethodCall call, Result result) { + int pageIndex = call.argument("index"); + int width = call.argument("width"); + int height = call.argument("height"); + String documentID = call.argument("documentID"); + try { + PdfRenderer.Page page = Objects.requireNonNull(documentRepo.get(documentID)).renderer.openPage(pageIndex - 1); + final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); + bitmap.eraseColor(Color.WHITE); + final Rect rect = new Rect(0, 0, width, height); + page.render(bitmap, rect, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); page.close(); - } - } - return pageWidth; - } catch (Exception e) { - return null; + ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount()); + bitmap.copyPixelsToBuffer(buffer); + bitmap.recycle(); + final byte[] imageBytes = buffer.array(); + buffer.clear(); + result.success(imageBytes); + } catch (Exception e) { + result.error(e.getMessage(), e.getLocalizedMessage(), e.getMessage()); + } } - } - - // Gets the specific page from PdfRenderer - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - void getPage(int pageIndex, int width, int height, String documentID) { - try { - PdfRenderer.Page page = Objects.requireNonNull(documentRepo.get(documentID)).renderer.openPage(pageIndex - 1); - double scale = Math.min(width / pageWidth[pageIndex - 1], height / pageHeight[pageIndex - 1]); - final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); - bitmap.eraseColor(Color.WHITE); - final Rect rect = new Rect(0, 0, width, height); - page.render(bitmap, rect, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); - page.close(); - ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount()); - bitmap.copyPixelsToBuffer(buffer); - bitmap.recycle(); - final byte[] imageBytes = buffer.array(); - buffer.clear(); - resultPdf.success(imageBytes); - } catch (Exception e) { - resultPdf.error(e.getMessage(), e.getLocalizedMessage(), e.getMessage()); + + private void getTileImage(MethodCall call, Result result) { + int pageNumber = call.argument("pageNumber"); + double scale = call.argument("scale"); + double x = call.argument("x"); + double y = call.argument("y"); + double width = call.argument("width"); + double height = call.argument("height"); + String documentID = call.argument("documentID"); + try { + PdfRenderer.Page page = Objects.requireNonNull(documentRepo.get(documentID)).renderer.openPage(pageNumber - 1); + final Bitmap bitmap = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888); + bitmap.eraseColor(Color.WHITE); + Matrix matrix = new Matrix(); + matrix.postTranslate((float) -x, (float) -y); + matrix.postScale((float) (scale), (float) (scale)); + final Rect rect = new Rect(0, 0, (int) width, (int) height); + page.render(bitmap, rect, matrix, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); + page.close(); + ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount()); + bitmap.copyPixelsToBuffer(buffer); + bitmap.recycle(); + final byte[] imageBytes = buffer.array(); + buffer.clear(); + result.success(imageBytes); + } catch (Exception e) { + result.error(e.getMessage(), e.getLocalizedMessage(), e.getMessage()); + } } - } - - void getTileImage(int pageNumber, double scale, double x, double y, double width, double height, String documentID) { - try { - PdfRenderer.Page page = Objects.requireNonNull(documentRepo.get(documentID)).renderer.openPage(pageNumber - 1); - final Bitmap bitmap = Bitmap.createBitmap((int)width, (int)height, Bitmap.Config.ARGB_8888); - bitmap.eraseColor(Color.WHITE); - Matrix matrix = new Matrix(); - matrix.postTranslate((float)-x, (float)-y); - matrix.postScale((float)(scale), (float)(scale)); - final Rect rect = new Rect(0, 0, (int)width, (int)height); - page.render(bitmap, rect, matrix, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY); - page.close(); - ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount()); - bitmap.copyPixelsToBuffer(buffer); - bitmap.recycle(); - final byte[] imageBytes = buffer.array(); - buffer.clear(); - resultPdf.success(imageBytes); - } catch (Exception e) { - resultPdf.error(e.getMessage(), e.getLocalizedMessage(), e.getMessage()); + + private void initializePdfRenderer(MethodCall call, Result result) { + executorService.execute(() -> { + byte[] bytes = call.argument("documentBytes"); + String documentID = call.argument("documentID"); + String password = call.argument("password"); + + try { + File file = File.createTempFile(".syncfusion", ".pdf", context.getCacheDir()); + try (FileOutputStream stream = new FileOutputStream(file)) { + stream.write(bytes); + } + + ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); + + PdfRenderer renderer; + + if (Build.VERSION.SDK_INT >= 35 && password != null) { + renderer = createPdfRendererWithPassword(fileDescriptor, password); + } else { + renderer = new PdfRenderer(fileDescriptor); + } + + PdfFileRenderer fileRenderer = new PdfFileRenderer(fileDescriptor, renderer); + documentRepo.put(documentID, fileRenderer); + int pageCount = renderer.getPageCount(); + file.delete(); + result.success(String.valueOf(pageCount)); + } catch (SecurityException e) { + result.error("PASSWORD_ERROR", "Incorrect password or document is encrypted", null); + } catch (Exception e) { + result.error("PDF_RENDERER_ERROR", e.getMessage(), null); + } + }); } - } - - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - boolean closeDocument(String documentID) { - try { - Objects.requireNonNull(documentRepo.get(documentID)).renderer.close(); - Objects.requireNonNull(documentRepo.get(documentID)).fileDescriptor.close(); - documentRepo.remove(documentID); - } catch (IOException e) { - e.printStackTrace(); - } catch (IllegalStateException e) { - e.printStackTrace(); + + private PdfRenderer createPdfRendererWithPassword(ParcelFileDescriptor fileDescriptor, String password) throws Exception { + Class loadParamsBuilderClass = Class.forName("android.graphics.pdf.LoadParams$Builder"); + Constructor builderConstructor = loadParamsBuilderClass.getDeclaredConstructor(); + Object builder = builderConstructor.newInstance(); + + Method setPasswordMethod = loadParamsBuilderClass.getMethod("setPassword", String.class); + setPasswordMethod.invoke(builder, password); + + Method buildMethod = loadParamsBuilderClass.getMethod("build"); + Object loadParams = buildMethod.invoke(builder); + + Class pdfRendererClass = PdfRenderer.class; + Constructor pdfRendererConstructor = pdfRendererClass.getDeclaredConstructor(ParcelFileDescriptor.class, loadParams.getClass()); + return (PdfRenderer) pdfRendererConstructor.newInstance(fileDescriptor, loadParams); + } + + private void getPagesWidth(MethodCall call, Result result) { + String documentID = (String) call.arguments; + PdfFileRenderer fileRenderer = documentRepo.get(documentID); + if (fileRenderer == null) { + result.error("DOCUMENT_NOT_FOUND", "Document with ID " + documentID + " not found", null); + return; + } + executorService.execute(() -> { + try { + int count = fileRenderer.renderer.getPageCount(); + double[] pageWidth = new double[count]; + for (int i = 0; i < count; i++) { + try (PdfRenderer.Page page = fileRenderer.renderer.openPage(i)) { + pageWidth[i] = page.getWidth(); + } + } + result.success(pageWidth); + } catch (Exception e) { + result.error("PAGE_WIDTH_ERROR", e.getMessage(), null); + } + }); + } + + private void getPagesHeight(MethodCall call, Result result) { + String documentID = (String) call.arguments; + PdfFileRenderer fileRenderer = documentRepo.get(documentID); + if (fileRenderer == null) { + result.error("DOCUMENT_NOT_FOUND", "Document with ID " + documentID + " not found", null); + return; + } + executorService.execute(() -> { + try { + int count = fileRenderer.renderer.getPageCount(); + double[] pageHeight = new double[count]; + for (int i = 0; i < count; i++) { + try (PdfRenderer.Page page = fileRenderer.renderer.openPage(i)) { + pageHeight[i] = page.getHeight(); + } + } + result.success(pageHeight); + } catch (Exception e) { + result.error("PAGE_HEIGHT_ERROR", e.getMessage(), null); + } + }); + } + + private void closeDocument(MethodCall call, Result result) { + String documentID = (String) call.arguments; + PdfFileRenderer fileRenderer = documentRepo.remove(documentID); + if (fileRenderer != null) { + try { + fileRenderer.renderer.close(); + fileRenderer.fileDescriptor.close(); + result.success(true); + } catch (IOException e) { + result.error("CLOSE_ERROR", e.getMessage(), null); + } + } else { + result.success(false); + } } - return true; - } } -/// Represents class which holds PdfRenderer and FileDescriptor. class PdfFileRenderer { - public PdfRenderer renderer; - public ParcelFileDescriptor fileDescriptor; + public PdfRenderer renderer; + public ParcelFileDescriptor fileDescriptor; - PdfFileRenderer(ParcelFileDescriptor fileDescriptor, PdfRenderer renderer) { - this.renderer = renderer; - this.fileDescriptor = fileDescriptor; - } -} + PdfFileRenderer(ParcelFileDescriptor fileDescriptor, PdfRenderer renderer) { + this.renderer = renderer; + this.fileDescriptor = fileDescriptor; + } +} \ No newline at end of file diff --git a/packages/syncfusion_flutter_pdfviewer/example/.gitignore b/packages/syncfusion_flutter_pdfviewer/example/.gitignore new file mode 100644 index 000000000..79c113f9b --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/syncfusion_flutter_pdfviewer/example/analysis_options.yaml b/packages/syncfusion_flutter_pdfviewer/example/analysis_options.yaml new file mode 100644 index 000000000..b08414c80 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_flutter_pdfviewer/example/lib/main.dart b/packages/syncfusion_flutter_pdfviewer/example/lib/main.dart index 4c59e84c8..7dca5f295 100644 --- a/packages/syncfusion_flutter_pdfviewer/example/lib/main.dart +++ b/packages/syncfusion_flutter_pdfviewer/example/lib/main.dart @@ -2,10 +2,9 @@ import 'package:flutter/material.dart'; import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; void main() { - runApp(const MaterialApp( - title: 'Syncfusion PDF Viewer Demo', - home: HomePage(), - )); + runApp( + const MaterialApp(title: 'Syncfusion PDF Viewer Demo', home: HomePage()), + ); } /// Represents Homepage for Navigation diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/.gitignore b/packages/syncfusion_flutter_pdfviewer/example/linux/.gitignore new file mode 100644 index 000000000..d3896c984 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/CMakeLists.txt b/packages/syncfusion_flutter_pdfviewer/example/linux/CMakeLists.txt new file mode 100644 index 000000000..7a9a314f9 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.example") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/CMakeLists.txt b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000..d5bd01648 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugin_registrant.cc b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 000000000..409cfa602 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) syncfusion_pdfviewer_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "SyncfusionPdfviewerLinuxPlugin"); + syncfusion_pdfviewer_linux_plugin_register_with_registrar(syncfusion_pdfviewer_linux_registrar); + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); +} diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugin_registrant.h b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 000000000..e0f0a47bc --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugins.cmake b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugins.cmake new file mode 100644 index 000000000..7cb59559a --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/flutter/generated_plugins.cmake @@ -0,0 +1,25 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + syncfusion_pdfviewer_linux + url_launcher_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/runner/CMakeLists.txt b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/CMakeLists.txt new file mode 100644 index 000000000..e97dabc70 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/runner/main.cc b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/main.cc new file mode 100644 index 000000000..e7c5c5437 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/runner/my_application.cc b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/my_application.cc new file mode 100644 index 000000000..6c8108238 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/my_application.cc @@ -0,0 +1,130 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "example"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/packages/syncfusion_flutter_pdfviewer/example/linux/runner/my_application.h b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/my_application.h new file mode 100644 index 000000000..72271d5e4 --- /dev/null +++ b/packages/syncfusion_flutter_pdfviewer/example/linux/runner/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/syncfusion_flutter_pdfviewer/example/pubspec.yaml b/packages/syncfusion_flutter_pdfviewer/example/pubspec.yaml index c34491e49..4da2444a6 100644 --- a/packages/syncfusion_flutter_pdfviewer/example/pubspec.yaml +++ b/packages/syncfusion_flutter_pdfviewer/example/pubspec.yaml @@ -1,35 +1,19 @@ name: syncfusion_flutter_pdfviewer_example description: Demonstrates how to use the syncfusion_flutter_pdfviewer plugin. - -# The following line prevents the package from being accidentally published to -# pub.dev using `pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev +publish_to: 'none' environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter - syncfusion_flutter_pdfviewer: path: ../ - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.5 - dev_dependencies: flutter_test: sdk: flutter -# 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. 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 diff --git a/packages/syncfusion_flutter_pdfviewer/example/web/index.html b/packages/syncfusion_flutter_pdfviewer/example/web/index.html index 47a180f9f..e4bdf5fb7 100644 --- a/packages/syncfusion_flutter_pdfviewer/example/web/index.html +++ b/packages/syncfusion_flutter_pdfviewer/example/web/index.html @@ -37,16 +37,16 @@ application and load in syncfusion_flutter_pdfviewer widget --> - + - + diff --git a/packages/syncfusion_flutter_pdfviewer/ios/syncfusion_flutter_pdfviewer/Sources/syncfusion_flutter_pdfviewer/SyncfusionFlutterPdfViewerPlugin.swift b/packages/syncfusion_flutter_pdfviewer/ios/syncfusion_flutter_pdfviewer/Sources/syncfusion_flutter_pdfviewer/SyncfusionFlutterPdfViewerPlugin.swift index e1ce249bb..9615e260a 100644 --- a/packages/syncfusion_flutter_pdfviewer/ios/syncfusion_flutter_pdfviewer/Sources/syncfusion_flutter_pdfviewer/SyncfusionFlutterPdfViewerPlugin.swift +++ b/packages/syncfusion_flutter_pdfviewer/ios/syncfusion_flutter_pdfviewer/Sources/syncfusion_flutter_pdfviewer/SyncfusionFlutterPdfViewerPlugin.swift @@ -55,10 +55,18 @@ public class SyncfusionFlutterPdfViewerPlugin: NSObject, FlutterPlugin { guard let args = argument as? [String: Any] else {return} guard let documentBytes = args["documentBytes"] as? FlutterStandardTypedData else {return} guard let documentID = args["documentID"] as? String else {return} + let password = args["password"] as? String let byte = [UInt8](documentBytes.data) guard let cfData = CFDataCreate(nil, byte, byte.count) else {return} guard let dataProvider = CGDataProvider(data: cfData) else {return} guard let document = CGPDFDocument(dataProvider) else {return} + if let password = password, document.isEncrypted { + let unlocked = document.unlockWithPassword(password) + if !unlocked { + result(FlutterError(code: "PDF_UNLOCK_FAILED", message: "Failed to unlock the PDF with the provided password", details: nil)) + return + } + } self.documentRepo[documentID] = document let pageCount = NSNumber(value: document.numberOfPages) result(pageCount.stringValue); @@ -228,4 +236,4 @@ public class SyncfusionFlutterPdfViewerPlugin: NSObject, FlutterPlugin { return nil } } -} \ No newline at end of file +} diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation.dart index d2a59b9c0..1ec2b41c0 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation.dart @@ -6,16 +6,17 @@ import 'annotation_view.dart'; import 'text_markup.dart'; /// Callback definition for annotation property change. -typedef AnnotationPropertyChangedCallback = void Function( - Annotation annotation, - String propertyName, - Object oldValue, - Object newValue, -); +typedef AnnotationPropertyChangedCallback = + void Function( + Annotation annotation, + String propertyName, + Object oldValue, + Object newValue, + ); /// Callback definition for annotation property change. -typedef AnnotationPropertyChangingCallback = bool Function( - Annotation annotation, String propertyName); +typedef AnnotationPropertyChangingCallback = + bool Function(Annotation annotation, String propertyName); /// Represents a PDF annotation. abstract class Annotation extends ChangeNotifier { @@ -99,9 +100,10 @@ extension AnnotationExtension on Annotation { Rect get boundingBox => _boundingBox; /// Returns the [Rect] bounds of the [Annotation]. - Rect get uiBounds => isSelected - ? _intermediateBounds.inflate(selectionBorderMargin) - : _boundingBox.inflate(selectionBorderMargin); + Rect get uiBounds => + isSelected + ? _intermediateBounds.inflate(selectionBorderMargin) + : _boundingBox.inflate(selectionBorderMargin); /// Return the global bounds of the [Annotation]. Rect get globalRect => _globalRect; diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_container.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_container.dart index aeb1665ca..b4b842d07 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_container.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_container.dart @@ -75,7 +75,9 @@ class _AnnotationContainerState extends State { List annotations = []; if (_selectedAnnotation != null && _selectedAnnotation!.pageNumber == widget.pageNumber) { - _updateAnnotationGlobalRect(_selectedAnnotation!); + WidgetsBinding.instance.addPostFrameCallback((_) { + _updateAnnotationGlobalRect(_selectedAnnotation!); + }); for (final Annotation annotation in widget.annotations) { if (annotation != _selectedAnnotation) { annotations.add(annotation); @@ -123,10 +125,8 @@ class _AnnotationContainerState extends State { return Positioned( left: annotation.uiBounds.left / widget.heightPercentage, top: annotation.uiBounds.top / widget.heightPercentage, - width: (annotation.uiBounds.width / widget.zoomLevel) / - widget.heightPercentage, - height: (annotation.uiBounds.height / widget.zoomLevel) / - widget.heightPercentage, + width: annotation.uiBounds.width / widget.zoomLevel, + height: annotation.uiBounds.height / widget.zoomLevel, child: Visibility( visible: !widget.isZooming, child: _getAnnotationView(annotation), @@ -186,9 +186,10 @@ class _AnnotationContainerState extends State { annotation: annotation, isSelected: annotation == _selectedAnnotation, heightPercentage: widget.heightPercentage, - selectorColor: _isLocked(annotation) - ? widget.annotationSettings.selector.lockedColor - : widget.annotationSettings.selector.color, + selectorColor: + _isLocked(annotation) + ? widget.annotationSettings.selector.lockedColor + : widget.annotationSettings.selector.color, ); } else if (annotation is StickyNoteAnnotation) { final bool isLocked = _isLocked(annotation); @@ -196,13 +197,13 @@ class _AnnotationContainerState extends State { key: ValueKey(annotation), annotation: annotation, isSelected: annotation == _selectedAnnotation, - heightPercentage: widget.heightPercentage * widget.zoomLevel, + zoomLevel: widget.zoomLevel, canEdit: !isLocked, - selectorColor: isLocked - ? widget.annotationSettings.selector.lockedColor - : widget.annotationSettings.selector.color, - selectorStorkeWidth: selectionBorderThickness / - (widget.heightPercentage * widget.zoomLevel), + selectorColor: + isLocked + ? widget.annotationSettings.selector.lockedColor + : widget.annotationSettings.selector.color, + selectorStorkeWidth: selectionBorderThickness / widget.zoomLevel, onAnnotationMoved: annotation.isSelected ? onAnnotationMoved : null, onAnnotationMoving: annotation.isSelected ? onAnnotationMoving : null, onTap: () { @@ -256,18 +257,22 @@ class _AnnotationContainerState extends State { if (newPosition.dy < 0) { newPosition = Offset(newPosition.dx, 0); } - if (newPosition.dx + annotation.intermediateBounds.width > + if (newPosition.dx + + (annotation.intermediateBounds.width * widget.heightPercentage) > widget.pageSize.width) { newPosition = Offset( - widget.pageSize.width - annotation.intermediateBounds.width, + widget.pageSize.width - + (annotation.intermediateBounds.width * widget.heightPercentage), newPosition.dy, ); } - if (newPosition.dy + annotation.intermediateBounds.height > + if (newPosition.dy + + (annotation.intermediateBounds.height * widget.heightPercentage) > widget.pageSize.height) { newPosition = Offset( newPosition.dx, - widget.pageSize.height - annotation.intermediateBounds.height, + widget.pageSize.height - + (annotation.intermediateBounds.height * widget.heightPercentage), ); } if (annotation is StickyNoteAnnotation) { @@ -277,14 +282,20 @@ class _AnnotationContainerState extends State { void _updateAnnotationGlobalRect(Annotation annotation) { if (annotation is StickyNoteAnnotation) { + if (!mounted) { + return; + } final renderObject = context.findRenderObject(); if (renderObject is RenderBox) { + final Rect scaledRect = + annotation.uiBounds.topLeft & + annotation.uiBounds.size * widget.heightPercentage; annotation.globalRect = Rect.fromPoints( renderObject.localToGlobal( - annotation.uiBounds.topLeft / widget.heightPercentage, + scaledRect.topLeft / widget.heightPercentage, ), renderObject.localToGlobal( - annotation.uiBounds.bottomRight / widget.heightPercentage, + scaledRect.bottomRight / widget.heightPercentage, ), ); } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_settings.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_settings.dart index 9e44e200c..5c0a802fb 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_settings.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_settings.dart @@ -52,25 +52,26 @@ class PdfAnnotationSettings extends PdfBaseAnnotationSettings { String author = ''; /// Gets or sets the default settings for highlight annotations. The default color is yellow - PdfTextMarkupAnnotationSettings highlight = PdfTextMarkupAnnotationSettings() - ..color = Colors.yellow; + PdfTextMarkupAnnotationSettings highlight = + PdfTextMarkupAnnotationSettings()..color = Colors.yellow; /// Gets or sets the default settings for underline annotations. The default color is green. - PdfTextMarkupAnnotationSettings underline = PdfTextMarkupAnnotationSettings() - ..color = Colors.green; + PdfTextMarkupAnnotationSettings underline = + PdfTextMarkupAnnotationSettings()..color = Colors.green; /// Gets or sets the default settings for strikethrough annotations. The default color is red. PdfTextMarkupAnnotationSettings strikethrough = PdfTextMarkupAnnotationSettings()..color = Colors.red; /// Gets or sets the default settings for squiggly annotations. The default color is green. - PdfTextMarkupAnnotationSettings squiggly = PdfTextMarkupAnnotationSettings() - ..color = Colors.green; + PdfTextMarkupAnnotationSettings squiggly = + PdfTextMarkupAnnotationSettings()..color = Colors.green; /// Gets or sets the default settings for sticky note annotations. The default color is yellow. Default icon is Comment - PdfStickyNoteAnnotationSettings stickyNote = PdfStickyNoteAnnotationSettings() - ..color = Colors.yellow - ..icon = PdfStickyNoteIcon.comment; + PdfStickyNoteAnnotationSettings stickyNote = + PdfStickyNoteAnnotationSettings() + ..color = Colors.yellow + ..icon = PdfStickyNoteIcon.comment; /// Gets or sets the default settings for the annotation selector. PdfAnnotationSelectorSettings selector = PdfAnnotationSelectorSettings(); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_view.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_view.dart index d3593e320..39b17c1d2 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_view.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/annotation_view.dart @@ -126,19 +126,21 @@ class RenderInteractiveGraphicsView extends RenderBox { _selectorColor = selectorColor; _selectorStorkeWidth = selectorStorkeWidth; - tapGestureRecognizer = TapGestureRecognizer() - ..onTap = onTap - ..onTapDown = onTapDown - ..onTapUp = onTapUp - ..onTapCancel = onTapCancel; - - panGestureRecognizer = PanGestureRecognizer() - ..onDown = onDragDown - ..onStart = onDragStart - ..onEnd = onDragEnd - ..onUpdate = onDragUpdate - ..onCancel = onDragCancel - ..gestureSettings = const DeviceGestureSettings(touchSlop: 0.0); + tapGestureRecognizer = + TapGestureRecognizer() + ..onTap = onTap + ..onTapDown = onTapDown + ..onTapUp = onTapUp + ..onTapCancel = onTapCancel; + + panGestureRecognizer = + PanGestureRecognizer() + ..onDown = onDragDown + ..onStart = onDragStart + ..onEnd = onDragEnd + ..onUpdate = onDragUpdate + ..onCancel = onDragCancel + ..gestureSettings = const DeviceGestureSettings(touchSlop: 0.0); } late Color _color; @@ -272,10 +274,11 @@ class RenderInteractiveGraphicsView extends RenderBox { size.width, size.height, ); - final Paint selectorPaint = Paint() - ..color = selectorColor - ..strokeWidth = selectorStorkeWidth - ..style = PaintingStyle.stroke; + final Paint selectorPaint = + Paint() + ..color = selectorColor + ..strokeWidth = selectorStorkeWidth + ..style = PaintingStyle.stroke; canvas.drawRect(selectorBounds, selectorPaint); } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/sticky_notes.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/sticky_notes.dart index c00ede1ed..52e8133ad 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/sticky_notes.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/sticky_notes.dart @@ -133,22 +133,22 @@ class StickyNoteAnnotationView extends InteractiveGraphicsView bool canEdit = true, Color selectorColor = defaultSelectorColor, double selectorStorkeWidth = 1, - double heightPercentage = 1, + double zoomLevel = 1, }) : super( - key: key, - color: annotation.color, - strokeWidth: 1, - opacity: annotation.opacity, - isSelected: isSelected, - selectorColor: selectorColor, - canMove: canEdit, - selectorStorkeWidth: selectorStorkeWidth, - ) { - _heightPercentage = heightPercentage; + key: key, + color: annotation.color, + strokeWidth: 1, + opacity: annotation.opacity, + isSelected: isSelected, + selectorColor: selectorColor, + canMove: canEdit, + selectorStorkeWidth: selectorStorkeWidth, + ) { + _zoomLevel = zoomLevel; } - /// Height percentage of the pdf page. - late final double _heightPercentage; + /// Zoom level of the pdf page. + late final double _zoomLevel; /// Called when the annotation is moved. final AnnotationMoveEndedCallback? onAnnotationMoved; @@ -171,7 +171,7 @@ class StickyNoteAnnotationView extends InteractiveGraphicsView isSelected: isSelected, selectorColor: selectorColor, selectorStorkeWidth: selectorStorkeWidth, - heightPercentage: _heightPercentage, + zoomLevel: _zoomLevel, onAnnotationMoved: onAnnotationMoved, onAnnotationMoving: onAnnotationMoving, onDoubleTap: onDoubleTap, @@ -186,7 +186,7 @@ class StickyNoteAnnotationView extends InteractiveGraphicsView ) { if (renderObject is RenderStickyNoteAnnotationView) { renderObject - ..heightPercentage = _heightPercentage + ..zoomLevel = _zoomLevel ..selectorStorkeWidth = selectorStorkeWidth ..onAnnotationMoved = onAnnotationMoved ..onAnnotationMoving = onAnnotationMoving @@ -214,23 +214,24 @@ class RenderStickyNoteAnnotationView extends RenderInteractiveGraphicsView { this.onAnnotationMoving, VoidCallback? onTap, void Function()? onDoubleTap, - double heightPercentage = 1, - }) : _onDoubleTap = onDoubleTap, - super( - strokeColor: color, - opacity: opacity, - strokeWidth: 1, - isSelected: isSelected, - selectorColor: selectorColor, - selectorStorkeWidth: selectorStorkeWidth, - ) { + double zoomLevel = 1, + }) : _onDoubleTap = onDoubleTap, + super( + strokeColor: color, + opacity: opacity, + strokeWidth: 1, + isSelected: isSelected, + selectorColor: selectorColor, + selectorStorkeWidth: selectorStorkeWidth, + ) { _onTap = onTap; - _heightPercentage = heightPercentage; + _zoomLevel = zoomLevel; _selectorStorkeWidth = selectorStorkeWidth; - _doubleTapGestureRecognizer = DoubleTapGestureRecognizer() - ..onDoubleTap = _onDoubleTap - ..gestureSettings = const DeviceGestureSettings(touchSlop: 0.0); + _doubleTapGestureRecognizer = + DoubleTapGestureRecognizer() + ..onDoubleTap = _onDoubleTap + ..gestureSettings = const DeviceGestureSettings(touchSlop: 0.0); super.tapGestureRecognizer.gestureSettings = const DeviceGestureSettings( touchSlop: 0.0, ); @@ -238,19 +239,19 @@ class RenderStickyNoteAnnotationView extends RenderInteractiveGraphicsView { _fillPath = Path(); } - late double _heightPercentage; + late double _zoomLevel; late DoubleTapGestureRecognizer _doubleTapGestureRecognizer; late Path _fillPath; late Path _strokePath; late double _selectorStorkeWidth; - /// The height percentage. - double get heightPercentage => _heightPercentage; - set heightPercentage(double value) { - if (_heightPercentage == value) { + /// The zoom level + double get zoomLevel => _zoomLevel; + set zoomLevel(double value) { + if (_zoomLevel == value) { return; } - _heightPercentage = value; + _zoomLevel = value; markNeedsPaint(); } @@ -297,10 +298,10 @@ class RenderStickyNoteAnnotationView extends RenderInteractiveGraphicsView { Rect _getPaintRect(Rect rect, Offset offset) { final Rect localRect = rect.translate(-_bounds.left, -_bounds.top); final Offset globalOffset = Offset( - offset.dx + localRect.left / heightPercentage, - offset.dy + localRect.top / heightPercentage, + offset.dx + (localRect.left / zoomLevel), + offset.dy + (localRect.top / zoomLevel), ); - return globalOffset & (localRect.size / heightPercentage); + return globalOffset & (localRect.size / zoomLevel); } void _applyRotationTransform(Canvas canvas, int rotation, Offset offset) { @@ -317,10 +318,11 @@ class RenderStickyNoteAnnotationView extends RenderInteractiveGraphicsView { fillPaint.color = color.withValues(alpha: opacity); fillPaint.style = PaintingStyle.fill; - final Paint strokePaint = Paint() - ..color = Colors.black.withValues(alpha: opacity) - ..strokeWidth = 1.5 - ..style = PaintingStyle.stroke; + final Paint strokePaint = + Paint() + ..color = Colors.black.withValues(alpha: opacity) + ..strokeWidth = 1.5 + ..style = PaintingStyle.stroke; final Rect paintRect = _getPaintRect( stickyNoteAnnotation.isSelected @@ -335,168 +337,182 @@ class RenderStickyNoteAnnotationView extends RenderInteractiveGraphicsView { switch (stickyNoteAnnotation.icon) { case PdfStickyNoteIcon.comment: - _fillPath = Path() - ..moveTo(0, 3) - ..cubicTo(0, 0.89543, 0.89543, 0, 3, 0) - ..lineTo(23, 0) - ..cubicTo(24.1046, 0, 25, 0.89543, 25, 3) - ..lineTo(25, 24) - ..lineTo(20.7868, 19.7499) - ..cubicTo(20.4113, 19.371, 19.8999, 19.1579, 19.3665, 19.1579) - ..lineTo(3, 19.1579) - ..cubicTo(0.89543, 19.1579, 0, 18.2625, 0, 17.1579) - ..lineTo(0, 3) - ..close(); - _strokePath = Path() - ..moveTo(5, 7) - ..lineTo(21, 7) - ..moveTo(5, 12) - ..lineTo(21, 12) - ..moveTo(25, 24) - ..lineTo(25, 3) - ..cubicTo(25, 0.89543, 24.1046, 0, 23, 0) - ..lineTo(3, 0) - ..cubicTo(0.89543, 0, 0, 0.89543, 0, 3) - ..lineTo(0, 17.1579) - ..cubicTo(0, 18.2625, 0.89543, 19.1579, 3, 19.1579) - ..lineTo(19.3665, 19.1579) - ..cubicTo(19.8999, 19.1579, 20.4113, 19.371, 20.7868, 19.7499) - ..lineTo(25, 24) - ..close(); + _fillPath = + Path() + ..moveTo(0, 3) + ..cubicTo(0, 0.89543, 0.89543, 0, 3, 0) + ..lineTo(23, 0) + ..cubicTo(24.1046, 0, 25, 0.89543, 25, 3) + ..lineTo(25, 24) + ..lineTo(20.7868, 19.7499) + ..cubicTo(20.4113, 19.371, 19.8999, 19.1579, 19.3665, 19.1579) + ..lineTo(3, 19.1579) + ..cubicTo(0.89543, 19.1579, 0, 18.2625, 0, 17.1579) + ..lineTo(0, 3) + ..close(); + _strokePath = + Path() + ..moveTo(5, 7) + ..lineTo(21, 7) + ..moveTo(5, 12) + ..lineTo(21, 12) + ..moveTo(25, 24) + ..lineTo(25, 3) + ..cubicTo(25, 0.89543, 24.1046, 0, 23, 0) + ..lineTo(3, 0) + ..cubicTo(0.89543, 0, 0, 0.89543, 0, 3) + ..lineTo(0, 17.1579) + ..cubicTo(0, 18.2625, 0.89543, 19.1579, 3, 19.1579) + ..lineTo(19.3665, 19.1579) + ..cubicTo(19.8999, 19.1579, 20.4113, 19.371, 20.7868, 19.7499) + ..lineTo(25, 24) + ..close(); break; case PdfStickyNoteIcon.note: - _fillPath = Path() - ..moveTo(0, 23) - ..lineTo(0, 0) - ..lineTo(23, 0) - ..lineTo(23, 13) - ..lineTo(13, 23) - ..lineTo(0, 23) - ..close(); - _strokePath = Path() - ..moveTo(13, 23) - ..lineTo(0, 23) - ..lineTo(0, 0) - ..lineTo(23, 0) - ..lineTo(23, 13) - ..moveTo(13, 23) - ..lineTo(23, 13) - ..moveTo(13, 23) - ..lineTo(13, 13) - ..lineTo(23, 13); + _fillPath = + Path() + ..moveTo(0, 23) + ..lineTo(0, 0) + ..lineTo(23, 0) + ..lineTo(23, 13) + ..lineTo(13, 23) + ..lineTo(0, 23) + ..close(); + _strokePath = + Path() + ..moveTo(13, 23) + ..lineTo(0, 23) + ..lineTo(0, 0) + ..lineTo(23, 0) + ..lineTo(23, 13) + ..moveTo(13, 23) + ..lineTo(23, 13) + ..moveTo(13, 23) + ..lineTo(13, 13) + ..lineTo(23, 13); break; case PdfStickyNoteIcon.help: - _fillPath = Path() - ..moveTo(23, 12) - ..cubicTo(23, 18.0751, 18.0751, 23, 12, 23) - ..cubicTo(5.92487, 23, 0, 18.0751, 0, 12) - ..cubicTo(0, 5.92487, 5.92487, 0, 12, 0) - ..cubicTo(18.0751, 0, 23, 5.92487, 23, 12) - ..close(); - _strokePath = Path() - ..moveTo(8.5, 10) - ..cubicTo(8.5, 8.93913, 8.86875, 7.92172, 9.52513, 7.17157) - ..cubicTo(10.1815, 6.42143, 11.0717, 6, 12, 6) - ..cubicTo(12.9283, 6, 13.8185, 6.42143, 14.4749, 7.17157) - ..cubicTo(15.1313, 7.92172, 15.5, 8.5, 15.5, 9.5) - ..cubicTo(15.5, 12.5, 12, 11.7106, 12, 14) - ..lineTo(12, 15) - ..moveTo(12, 19) - ..lineTo(12, 17) - ..moveTo(23, 12) - ..cubicTo(23, 18.0751, 18.0751, 23, 12, 23) - ..cubicTo(5.92487, 23, 0, 18.0751, 0, 12) - ..cubicTo(0, 5.92487, 5.92487, 0, 12, 0) - ..cubicTo(18.0751, 0, 23, 5.92487, 23, 12) - ..close(); + _fillPath = + Path() + ..moveTo(23, 12) + ..cubicTo(23, 18.0751, 18.0751, 23, 12, 23) + ..cubicTo(5.92487, 23, 0, 18.0751, 0, 12) + ..cubicTo(0, 5.92487, 5.92487, 0, 12, 0) + ..cubicTo(18.0751, 0, 23, 5.92487, 23, 12) + ..close(); + _strokePath = + Path() + ..moveTo(8.5, 10) + ..cubicTo(8.5, 8.93913, 8.86875, 7.92172, 9.52513, 7.17157) + ..cubicTo(10.1815, 6.42143, 11.0717, 6, 12, 6) + ..cubicTo(12.9283, 6, 13.8185, 6.42143, 14.4749, 7.17157) + ..cubicTo(15.1313, 7.92172, 15.5, 8.5, 15.5, 9.5) + ..cubicTo(15.5, 12.5, 12, 11.7106, 12, 14) + ..lineTo(12, 15) + ..moveTo(12, 19) + ..lineTo(12, 17) + ..moveTo(23, 12) + ..cubicTo(23, 18.0751, 18.0751, 23, 12, 23) + ..cubicTo(5.92487, 23, 0, 18.0751, 0, 12) + ..cubicTo(0, 5.92487, 5.92487, 0, 12, 0) + ..cubicTo(18.0751, 0, 23, 5.92487, 23, 12) + ..close(); break; case PdfStickyNoteIcon.insert: - _fillPath = Path() - ..moveTo(0, 40) - ..lineTo(20, 0) - ..lineTo(40, 40) - ..close(); - _strokePath = Path() - ..moveTo(0, 40) - ..lineTo(20, 0) - ..lineTo(40, 40) - ..close(); + _fillPath = + Path() + ..moveTo(0, 40) + ..lineTo(20, 0) + ..lineTo(40, 40) + ..close(); + _strokePath = + Path() + ..moveTo(0, 40) + ..lineTo(20, 0) + ..lineTo(40, 40) + ..close(); break; case PdfStickyNoteIcon.key: - _fillPath = _strokePath = Path() - ..moveTo(7, 0) - ..cubicTo(3.68629, 0, 0, 3.68629, 0, 7) - ..cubicTo(0, 9.22085, 2.2066, 11.1599, 4, 12.1973) - ..lineTo(4, 21) - ..lineTo(7, 22.5) - ..lineTo(9, 21) - ..lineTo(8.5, 19.5) - ..lineTo(9.5, 18.5) - ..lineTo(8.5, 16.5) - ..lineTo(10, 15) - ..lineTo(10, 12.1973) - ..cubicTo(11.7934, 11.1599, 13, 9.22085, 13, 7) - ..cubicTo(13, 3.68629, 10.3137, 0, 7, 0) - ..close(); + _fillPath = + _strokePath = + Path() + ..moveTo(7, 0) + ..cubicTo(3.68629, 0, 0, 3.68629, 0, 7) + ..cubicTo(0, 9.22085, 2.2066, 11.1599, 4, 12.1973) + ..lineTo(4, 21) + ..lineTo(7, 22.5) + ..lineTo(9, 21) + ..lineTo(8.5, 19.5) + ..lineTo(9.5, 18.5) + ..lineTo(8.5, 16.5) + ..lineTo(10, 15) + ..lineTo(10, 12.1973) + ..cubicTo(11.7934, 11.1599, 13, 9.22085, 13, 7) + ..cubicTo(13, 3.68629, 10.3137, 0, 7, 0) + ..close(); break; case PdfStickyNoteIcon.newParagraph: - _fillPath = Path() - ..moveTo(22, 14) - ..lineTo(0, 14) - ..lineTo(12, 0) - ..lineTo(22, 14) - ..close(); - _strokePath = Path() - ..moveTo(15, 24) - ..lineTo(15, 21) - ..moveTo(15, 21) - ..lineTo(15, 18) - ..lineTo(17.5, 18) - ..cubicTo(18.3284, 18, 19, 18.6716, 19, 19.5) - ..cubicTo(19, 20.3284, 18.3284, 21, 17.5, 21) - ..lineTo(15, 21) - ..moveTo(5, 24) - ..lineTo(5, 18) - ..moveTo(5, 18) - ..lineTo(5, 17) - ..moveTo(5, 18) - ..lineTo(10, 23) - ..moveTo(10, 23) - ..lineTo(10, 17) - ..moveTo(10, 23) - ..lineTo(10, 24) - ..moveTo(0, 14) - ..lineTo(22, 14) - ..lineTo(12, 0) - ..lineTo(0, 14) - ..close(); + _fillPath = + Path() + ..moveTo(22, 14) + ..lineTo(0, 14) + ..lineTo(12, 0) + ..lineTo(22, 14) + ..close(); + _strokePath = + Path() + ..moveTo(15, 24) + ..lineTo(15, 21) + ..moveTo(15, 21) + ..lineTo(15, 18) + ..lineTo(17.5, 18) + ..cubicTo(18.3284, 18, 19, 18.6716, 19, 19.5) + ..cubicTo(19, 20.3284, 18.3284, 21, 17.5, 21) + ..lineTo(15, 21) + ..moveTo(5, 24) + ..lineTo(5, 18) + ..moveTo(5, 18) + ..lineTo(5, 17) + ..moveTo(5, 18) + ..lineTo(10, 23) + ..moveTo(10, 23) + ..lineTo(10, 17) + ..moveTo(10, 23) + ..lineTo(10, 24) + ..moveTo(0, 14) + ..lineTo(22, 14) + ..lineTo(12, 0) + ..lineTo(0, 14) + ..close(); break; case PdfStickyNoteIcon.paragraph: - _fillPath = Path() - ..moveTo(11, 14) - ..lineTo(7.5, 14) - ..cubicTo(3.91015, 14, 0, 11.0899, 0, 7.5) - ..cubicTo(0, 3.91015, 3.91015, 0, 7.5, 0) - ..lineTo(11, 0) - ..lineTo(11, 14) - ..close(); - _strokePath = Path() - ..moveTo(11, 14) - ..lineTo(7.5, 14) - ..cubicTo(3.91015, 14, 0, 11.0899, 0, 7.5) - ..cubicTo(0, 3.91015, 3.91015, 0, 7.5, 0) - ..lineTo(11, 0) - ..moveTo(11, 14) - ..lineTo(11, 24) - ..moveTo(11, 14) - ..lineTo(11, 0) - ..moveTo(24, 0) - ..lineTo(17, 0) - ..moveTo(17, 0) - ..lineTo(17, 24) - ..moveTo(17, 0) - ..lineTo(11, 0) - ..close(); + _fillPath = + Path() + ..moveTo(11, 14) + ..lineTo(7.5, 14) + ..cubicTo(3.91015, 14, 0, 11.0899, 0, 7.5) + ..cubicTo(0, 3.91015, 3.91015, 0, 7.5, 0) + ..lineTo(11, 0) + ..lineTo(11, 14) + ..close(); + _strokePath = + Path() + ..moveTo(11, 14) + ..lineTo(7.5, 14) + ..cubicTo(3.91015, 14, 0, 11.0899, 0, 7.5) + ..cubicTo(0, 3.91015, 3.91015, 0, 7.5, 0) + ..lineTo(11, 0) + ..moveTo(11, 14) + ..lineTo(11, 24) + ..moveTo(11, 14) + ..lineTo(11, 0) + ..moveTo(24, 0) + ..lineTo(17, 0) + ..moveTo(17, 0) + ..lineTo(17, 24) + ..moveTo(17, 0) + ..lineTo(11, 0) + ..close(); break; } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/text_markup.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/text_markup.dart index fcf1f5d63..efcd45ade 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/text_markup.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/annotation/text_markup.dart @@ -11,9 +11,9 @@ class HighlightAnnotation extends Annotation { /// /// The [textBoundsCollection] represents the bounds collection of the highlight annotations that are added in the multiple lines of text. HighlightAnnotation({required List textBoundsCollection}) - : assert(textBoundsCollection.isNotEmpty), - assert(_checkTextMarkupRects(textBoundsCollection)), - super(pageNumber: textBoundsCollection.first.pageNumber) { + : assert(textBoundsCollection.isNotEmpty), + assert(_checkTextMarkupRects(textBoundsCollection)), + super(pageNumber: textBoundsCollection.first.pageNumber) { _textMarkupRects = []; double minX = textBoundsCollection.first.bounds.left, @@ -42,9 +42,9 @@ class StrikethroughAnnotation extends Annotation { /// /// The [textBoundsCollection] represents the bounds collection of the strikethrough annotations that are added in the multiple lines of text. StrikethroughAnnotation({required List textBoundsCollection}) - : assert(textBoundsCollection.isNotEmpty), - assert(_checkTextMarkupRects(textBoundsCollection)), - super(pageNumber: textBoundsCollection.first.pageNumber) { + : assert(textBoundsCollection.isNotEmpty), + assert(_checkTextMarkupRects(textBoundsCollection)), + super(pageNumber: textBoundsCollection.first.pageNumber) { _textMarkupRects = []; double minX = textBoundsCollection.first.bounds.left, @@ -73,9 +73,9 @@ class UnderlineAnnotation extends Annotation { /// /// The [textBoundsCollection] represents the bounds collection of the underline annotations that are added in the multiple lines of text. UnderlineAnnotation({required List textBoundsCollection}) - : assert(textBoundsCollection.isNotEmpty), - assert(_checkTextMarkupRects(textBoundsCollection)), - super(pageNumber: textBoundsCollection.first.pageNumber) { + : assert(textBoundsCollection.isNotEmpty), + assert(_checkTextMarkupRects(textBoundsCollection)), + super(pageNumber: textBoundsCollection.first.pageNumber) { _textMarkupRects = []; double minX = textBoundsCollection.first.bounds.left, @@ -104,9 +104,9 @@ class SquigglyAnnotation extends Annotation { /// /// The [textBoundsCollection] represents the bounds collection of the squiggly annotations that are added in the multiple lines of text. SquigglyAnnotation({required List textBoundsCollection}) - : assert(textBoundsCollection.isNotEmpty), - assert(_checkTextMarkupRects(textBoundsCollection)), - super(pageNumber: textBoundsCollection.first.pageNumber) { + : assert(textBoundsCollection.isNotEmpty), + assert(_checkTextMarkupRects(textBoundsCollection)), + super(pageNumber: textBoundsCollection.first.pageNumber) { _textMarkupRects = []; double minX = textBoundsCollection.first.bounds.left, @@ -140,21 +140,22 @@ class TextMarkupAnnotationView extends InteractiveGraphicsView Color selectorColor = defaultSelectorColor, double heightPercentage = 1, }) : super( - key: key, - color: annotation.color, - strokeWidth: 1, - opacity: annotation.opacity, - isSelected: isSelected, - canMove: false, - selectorColor: selectorColor, - ) { - _textMarkupType = annotation is HighlightAnnotation - ? TextMarkupType.highlight - : annotation is StrikethroughAnnotation + key: key, + color: annotation.color, + strokeWidth: 1, + opacity: annotation.opacity, + isSelected: isSelected, + canMove: false, + selectorColor: selectorColor, + ) { + _textMarkupType = + annotation is HighlightAnnotation + ? TextMarkupType.highlight + : annotation is StrikethroughAnnotation ? TextMarkupType.strikethrough : annotation is UnderlineAnnotation - ? TextMarkupType.underline - : TextMarkupType.squiggly; + ? TextMarkupType.underline + : TextMarkupType.squiggly; _heightPercentage = heightPercentage; } @@ -202,12 +203,12 @@ class RenderTextMarkupAnnotationView extends RenderInteractiveGraphicsView { required Color selectorColor, double heightPercentage = 1, }) : super( - strokeColor: color, - opacity: opacity, - strokeWidth: 1, - isSelected: isSelected, - selectorColor: selectorColor, - ) { + strokeColor: color, + opacity: opacity, + strokeWidth: 1, + isSelected: isSelected, + selectorColor: selectorColor, + ) { _textMarkupType = textMarkupType; _heightPercentage = heightPercentage; } @@ -335,9 +336,11 @@ class RenderTextMarkupAnnotationView extends RenderInteractiveGraphicsView { final double spacing = height * 0.18; final Path squigglyPath = Path(); squigglyPath.moveTo(x, y); - for (double distance = 0; - distance + spacing < length; - distance += spacing) { + for ( + double distance = 0; + distance + spacing < length; + distance += spacing + ) { if (showUnderlineAtStart) { squigglyPath.lineTo(x + distance + spacing, y); } else { diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_item.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_item.dart index 19c5d5992..5c4ae2fad 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_item.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_item.dart @@ -114,10 +114,12 @@ class _BookmarkItemState extends State { @override void didChangeDependencies() { _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); - _color = _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); + _color = + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white @@ -133,7 +135,8 @@ class _BookmarkItemState extends State { } void _handleBackToParent() { - _color = _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? + _color = + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white @@ -142,7 +145,8 @@ class _BookmarkItemState extends State { } void _handleExpandBookmarkList() { - _color = _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? + _color = + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white @@ -163,7 +167,8 @@ class _BookmarkItemState extends State { if (kIsDesktop && !widget.isMobileWebView) { _color = const Color(0xFF000000).withValues(alpha: 0.08); } else { - _color = _pdfViewerThemeData!.bookmarkViewStyle?.selectionColor! ?? + _color = + _pdfViewerThemeData!.bookmarkViewStyle?.selectionColor! ?? _effectiveThemeData!.bookmarkViewStyle?.selectionColor! ?? ((Theme.of(context).colorScheme.brightness == Brightness.light) ? const Color.fromRGBO(0, 0, 0, 0.08) @@ -178,7 +183,8 @@ class _BookmarkItemState extends State { void _handleCancelSelectionColor() { setState(() { - _color = _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? + _color = + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white @@ -197,22 +203,26 @@ class _BookmarkItemState extends State { child: Container( height: widget.height, color: _color, - foregroundDecoration: widget.isBorderEnabled - ? BoxDecoration( - border: Border( - bottom: BorderSide( - color: _pdfViewerThemeData! - .bookmarkViewStyle?.titleSeparatorColor ?? - _effectiveThemeData! - .bookmarkViewStyle?.titleSeparatorColor ?? - ((Theme.of(context).colorScheme.brightness == - Brightness.light) - ? const Color.fromRGBO(0, 0, 0, 0.16) - : const Color.fromRGBO(255, 255, 255, 0.16)), + foregroundDecoration: + widget.isBorderEnabled + ? BoxDecoration( + border: Border( + bottom: BorderSide( + color: + _pdfViewerThemeData! + .bookmarkViewStyle + ?.titleSeparatorColor ?? + _effectiveThemeData! + .bookmarkViewStyle + ?.titleSeparatorColor ?? + ((Theme.of(context).colorScheme.brightness == + Brightness.light) + ? const Color.fromRGBO(0, 0, 0, 0.16) + : const Color.fromRGBO(255, 255, 255, 0.16)), + ), ), - ), - ) - : const BoxDecoration(), + ) + : const BoxDecoration(), child: Stack( children: [ Visibility( @@ -227,8 +237,8 @@ class _BookmarkItemState extends State { child: Icon( Icons.arrow_back, size: _kPdfBackIconSize, - color: _pdfViewerThemeData! - .bookmarkViewStyle?.backIconColor ?? + color: + _pdfViewerThemeData!.bookmarkViewStyle?.backIconColor ?? _effectiveThemeData!.bookmarkViewStyle?.backIconColor ?? Theme.of( context, @@ -245,14 +255,13 @@ class _BookmarkItemState extends State { child: Text( widget.title, overflow: TextOverflow.ellipsis, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData!.bookmarkViewStyle?.titleTextStyle, @@ -271,10 +280,13 @@ class _BookmarkItemState extends State { child: Icon( Icons.arrow_forward_ios, size: _kPdfExpandIconSize, - color: _pdfViewerThemeData! - .bookmarkViewStyle?.navigationIconColor ?? + color: + _pdfViewerThemeData! + .bookmarkViewStyle + ?.navigationIconColor ?? _effectiveThemeData! - .bookmarkViewStyle?.navigationIconColor ?? + .bookmarkViewStyle + ?.navigationIconColor ?? Theme.of( context, ).colorScheme.onSurface.withValues(alpha: 0.54), @@ -292,16 +304,18 @@ class _BookmarkItemState extends State { cursor: SystemMouseCursors.click, onEnter: (PointerEnterEvent details) { setState(() { - _color = Theme.of(context).useMaterial3 - ? Theme.of( - context, - ).colorScheme.onSurface.withValues(alpha: 0.08) - : const Color(0xFF000000).withValues(alpha: 0.04); + _color = + Theme.of(context).useMaterial3 + ? Theme.of( + context, + ).colorScheme.onSurface.withValues(alpha: 0.08) + : const Color(0xFF000000).withValues(alpha: 0.04); }); }, onExit: (PointerExitEvent details) { setState(() { - _color = _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? + _color = + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_toolbar.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_toolbar.dart index 6ceeac8ec..4beec8dd9 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_toolbar.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_toolbar.dart @@ -62,9 +62,10 @@ class _BookmarkToolbarState extends State { void didChangeDependencies() { _pdfViewerThemeData = SfPdfViewerTheme.of(context); _isMaterial3 = Theme.of(context).useMaterial3; - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _localizations = SfLocalizations.of(context); super.didChangeDependencies(); } @@ -98,19 +99,21 @@ class _BookmarkToolbarState extends State { height: _kPdfHeaderBarHeight, margin: const EdgeInsets.only(bottom: 3), decoration: BoxDecoration( - color: _pdfViewerThemeData!.bookmarkViewStyle?.headerBarColor ?? + color: + _pdfViewerThemeData!.bookmarkViewStyle?.headerBarColor ?? _effectiveThemeData!.bookmarkViewStyle?.headerBarColor ?? ((Theme.of(context).colorScheme.brightness == Brightness.light) ? const Color(0xFFFAFAFA) : const Color(0xFF424242)), boxShadow: _isMaterial3 ? null : boxShadows, - border: _isMaterial3 - ? Border( - bottom: BorderSide( - color: Theme.of(context).colorScheme.outlineVariant, - ), - ) - : null, + border: + _isMaterial3 + ? Border( + bottom: BorderSide( + color: Theme.of(context).colorScheme.outlineVariant, + ), + ) + : null, ), child: Stack( children: [ @@ -121,19 +124,19 @@ class _BookmarkToolbarState extends State { height: _kPdfHeaderTextHeight, child: Text( _localizations!.pdfBookmarksLabel, - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData!.bookmarkViewStyle?.headerTextStyle ?? _effectiveThemeData! - .bookmarkViewStyle?.headerTextStyle, + .bookmarkViewStyle + ?.headerTextStyle, ), semanticsLabel: '', ), @@ -151,8 +154,8 @@ class _BookmarkToolbarState extends State { child: Icon( Icons.close, size: _kPdfCloseIconSize, - color: _pdfViewerThemeData! - .bookmarkViewStyle?.closeIconColor ?? + color: + _pdfViewerThemeData!.bookmarkViewStyle?.closeIconColor ?? _effectiveThemeData!.bookmarkViewStyle?.closeIconColor ?? Theme.of( context, diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_view.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_view.dart index b5c3c518a..819c96cc5 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_view.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/bookmark/bookmark_view.dart @@ -78,9 +78,10 @@ class BookmarkViewControllerState extends State { void didChangeDependencies() { _useMaterial3 = Theme.of(context).useMaterial3; _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _localizations = SfLocalizations.of(context); super.didChangeDependencies(); } @@ -204,9 +205,10 @@ class BookmarkViewControllerState extends State { title: _isExpanded ? _childBookmark![i].title : _bookmarkBase![i].title, isMobileWebView: !_isTablet, textDirection: widget.textDirection, - isExpandIconVisible: _isExpanded - ? _childBookmark![i].count != 0 - : _bookmarkBase![i].count != 0, + isExpandIconVisible: + _isExpanded + ? _childBookmark![i].count != 0 + : _bookmarkBase![i].count != 0, onNavigate: () { final PdfBookmark bookmark = _isExpanded ? _childBookmark![i] : _bookmarkBase![i]; @@ -253,23 +255,24 @@ class BookmarkViewControllerState extends State { alignment: _isTablet ? Alignment.topRight : Alignment.center, child: Container( decoration: BoxDecoration( - boxShadow: _useMaterial3 - ? const [ - BoxShadow( - color: Color(0x4D000000), - offset: Offset(0, 1), - blurRadius: 3, - ), - BoxShadow( - color: Color(0x26000000), - offset: Offset(0, 4), - blurRadius: 8, - spreadRadius: 3, - ), - ] - : null, - color: _pdfViewerThemeData! - .bookmarkViewStyle?.backgroundColor ?? + boxShadow: + _useMaterial3 + ? const [ + BoxShadow( + color: Color(0x4D000000), + offset: Offset(0, 1), + blurRadius: 3, + ), + BoxShadow( + color: Color(0x26000000), + offset: Offset(0, 4), + blurRadius: 8, + spreadRadius: 3, + ), + ] + : null, + color: + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? (Theme.of(context).useMaterial3 ? Theme.of(context).colorScheme.surface @@ -283,46 +286,47 @@ class BookmarkViewControllerState extends State { children: [ BookmarkToolbar(_handleClose, widget.textDirection), Expanded( - child: hasBookmark - ? _useMaterial3 - ? BookmarkTree( - pdfDocument: widget.pdfDocument, - onNavigate: _handleTap, - key: _bookmarkTreeKey, - textDirection: widget.textDirection, - ) - : ListView.builder( - itemCount: _listCount, - itemBuilder: ( - BuildContext context, - int index, - ) { - return _bookmarkList![index]; - }, - ) - : Center( - child: Text( - _localizations!.pdfNoBookmarksLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! - .copyWith( - fontSize: 14, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues( - alpha: 0.87, - ) - : Colors.white.withValues( - alpha: 0.87, - ), - ) - .merge( - _pdfViewerThemeData! - .bookmarkViewStyle?.titleTextStyle, - ), + child: + hasBookmark + ? _useMaterial3 + ? BookmarkTree( + pdfDocument: widget.pdfDocument, + onNavigate: _handleTap, + key: _bookmarkTreeKey, + textDirection: widget.textDirection, + ) + : ListView.builder( + itemCount: _listCount, + itemBuilder: ( + BuildContext context, + int index, + ) { + return _bookmarkList![index]; + }, + ) + : Center( + child: Text( + _localizations!.pdfNoBookmarksLabel, + style: Theme.of(context).textTheme.bodyMedium! + .copyWith( + fontSize: 14, + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues( + alpha: 0.87, + ) + : Colors.white.withValues( + alpha: 0.87, + ), + ) + .merge( + _pdfViewerThemeData! + .bookmarkViewStyle + ?.titleTextStyle, + ), + ), ), - ), ), ], ), @@ -392,9 +396,10 @@ class BookmarkTreeState extends State { @override void didChangeDependencies() { _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); super.didChangeDependencies(); } @@ -484,7 +489,8 @@ class BookmarkTreeState extends State { Widget _bookMarkItems(PdfBookmark bookmark) { final icon = Icon( Icons.expand_more, - color: _pdfViewerThemeData!.bookmarkViewStyle?.navigationIconColor ?? + color: + _pdfViewerThemeData!.bookmarkViewStyle?.navigationIconColor ?? _effectiveThemeData!.bookmarkViewStyle?.navigationIconColor ?? Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.54), size: 18, @@ -495,37 +501,41 @@ class BookmarkTreeState extends State { itemBuilder: (context, index) { final node = bookmarkList[index]; return Material( - color: _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? + color: + _pdfViewerThemeData!.bookmarkViewStyle?.backgroundColor ?? _effectiveThemeData!.bookmarkViewStyle?.backgroundColor ?? Theme.of(context).colorScheme.surface, child: InkWell( - splashColor: _pdfViewerThemeData! - .bookmarkViewStyle?.selectionColor! ?? + splashColor: + _pdfViewerThemeData!.bookmarkViewStyle?.selectionColor! ?? _effectiveThemeData!.bookmarkViewStyle?.selectionColor! ?? ((Theme.of(context).colorScheme.brightness == Brightness.light) ? const Color.fromRGBO(0, 0, 0, 0.08) : const Color.fromRGBO(255, 255, 255, 0.12)), - hoverColor: Theme.of(context).useMaterial3 - ? Theme.of( - context, - ).colorScheme.onSurface.withValues(alpha: 0.08) - : const Color(0xFF000000).withValues(alpha: 0.04), + hoverColor: + Theme.of(context).useMaterial3 + ? Theme.of( + context, + ).colorScheme.onSurface.withValues(alpha: 0.08) + : const Color(0xFF000000).withValues(alpha: 0.04), onTap: () { if (node.pdfBookmark != null) { _handleTap(node.pdfBookmark!); } }, child: Padding( - padding: widget.textDirection == TextDirection.rtl - ? EdgeInsets.only(right: node.level * 25.0) - : EdgeInsets.only(left: node.level * 25.0), + padding: + widget.textDirection == TextDirection.rtl + ? EdgeInsets.only(right: node.level * 25.0) + : EdgeInsets.only(left: node.level * 25.0), child: Row( children: [ if (node.children.isNotEmpty) Padding( - padding: widget.textDirection == TextDirection.rtl - ? const EdgeInsets.only(right: 16.0) - : const EdgeInsets.only(left: 16.0), + padding: + widget.textDirection == TextDirection.rtl + ? const EdgeInsets.only(right: 16.0) + : const EdgeInsets.only(left: 16.0), child: GestureDetector( onTap: () { _toggleExpand(node, index); @@ -533,11 +543,12 @@ class BookmarkTreeState extends State { child: SizedBox( height: 40, child: RotatedBox( - quarterTurns: !node.isExpanded - ? widget.textDirection == TextDirection.rtl - ? 1 - : 3 - : 0, + quarterTurns: + !node.isExpanded + ? widget.textDirection == TextDirection.rtl + ? 1 + : 3 + : 0, child: icon, ), ), @@ -548,24 +559,25 @@ class BookmarkTreeState extends State { child: SizedBox( height: 40, child: Padding( - padding: (!node.children.isNotEmpty) - ? widget.textDirection == TextDirection.rtl - ? const EdgeInsets.only(right: 45.0) - : const EdgeInsets.only(left: 45.0) - : EdgeInsets.zero, + padding: + (!node.children.isNotEmpty) + ? widget.textDirection == TextDirection.rtl + ? const EdgeInsets.only(right: 45.0) + : const EdgeInsets.only(left: 45.0) + : EdgeInsets.zero, child: Align( - alignment: widget.textDirection == TextDirection.rtl - ? Alignment.centerRight - : Alignment.centerLeft, + alignment: + widget.textDirection == TextDirection.rtl + ? Alignment.centerRight + : Alignment.centerLeft, child: Text( node.title, - textAlign: widget.textDirection == TextDirection.rtl - ? TextAlign.right - : TextAlign.left, + textAlign: + widget.textDirection == TextDirection.rtl + ? TextAlign.right + : TextAlign.left, overflow: TextOverflow.ellipsis, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, color: @@ -573,7 +585,8 @@ class BookmarkTreeState extends State { ) .merge( _pdfViewerThemeData! - .bookmarkViewStyle?.titleTextStyle, + .bookmarkViewStyle + ?.titleTextStyle, ), ), ), diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/common/mobile_helper.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/common/mobile_helper.dart index a8e59a1cc..3d06f649f 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/common/mobile_helper.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/common/mobile_helper.dart @@ -1,3 +1,4 @@ +import 'dart:ffi' as ffi; import 'dart:io'; /// Checks whether focus node of pdf page view has primary focus. @@ -13,3 +14,20 @@ void enableDefaultMenu() {} String getPlatformType() { return Platform.operatingSystem; } + +/// To check whether pdfium is loaded or not on Android platform +bool isPdfiumLoaded() { + if (!Platform.isAndroid) { + return false; + } + + try { + final ffi.DynamicLibrary library = ffi.DynamicLibrary.open('libpdfium.so'); + if (library.handle != ffi.nullptr) { + library.close(); + } + return true; + } catch (e) { + return false; + } +} diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_provider.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_provider.dart index 67f461995..5e033d1f6 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_provider.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_provider.dart @@ -29,7 +29,7 @@ class NetworkPdf extends PdfProvider { /// /// The arguments [url] must not be null. NetworkPdf(String url, Map? headers) - : assert(url.isNotEmpty) { + : assert(url.isNotEmpty) { _url = url; _headers = headers; } @@ -87,7 +87,7 @@ class AssetPdf extends PdfProvider { /// /// [assetName] must not be null. AssetPdf(String assetName, AssetBundle? bundle) - : assert(assetName.isNotEmpty) { + : assert(assetName.isNotEmpty) { _pdfPath = assetName; _bundle = bundle; } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_source.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_source.dart index 977a0b45a..1c7d4edca 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_source.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdf_source.dart @@ -42,7 +42,7 @@ class URLPDFSource extends PDFSource { /// The [url] parameter must not be null or empty. /// The [headers] parameter can be used to add custom HTTP headers to the request. URLPDFSource(String url, {Map? headers}) - : assert(url.isNotEmpty) { + : assert(url.isNotEmpty) { _url = url; _headers = headers; } @@ -98,7 +98,7 @@ class AssetPDFSource extends PDFSource { /// The [assetPath] parameter must not be null or empty. /// The [bundle] parameter is optional. If not provided, the default asset bundle will be used. AssetPDFSource(String assetPath, {AssetBundle? bundle}) - : assert(assetPath.isNotEmpty) { + : assert(assetPath.isNotEmpty) { _pdfPath = assetPath; _bundle = bundle; } @@ -111,9 +111,10 @@ class AssetPDFSource extends PDFSource { @override Future getBytes(BuildContext context) async { if (_documentBytes == null) { - final ByteData bytes = await ((_bundle != null) - ? _bundle!.load(_pdfPath) - : DefaultAssetBundle.of(context).load(_pdfPath)); + final ByteData bytes = + await ((_bundle != null) + ? _bundle!.load(_pdfPath) + : DefaultAssetBundle.of(context).load(_pdfPath)); _documentBytes = bytes.buffer.asUint8List(); } return Future.value(_documentBytes); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_helper.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_helper.dart index 2e6626112..d70628e04 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_helper.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_helper.dart @@ -10,7 +10,8 @@ import 'mobile_helper.dart' as helper; /// Indicates whether the current environment is running in Desktop -bool kIsDesktop = kIsWeb || Platform.isMacOS || Platform.isWindows; +bool kIsDesktop = + kIsWeb || Platform.isMacOS || Platform.isWindows || Platform.isLinux; /// Indicates whether the current environment is running in macOS bool kIsMacOS = helper.getPlatformType() == 'macos'; diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_plugin.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_plugin.dart index c3246fe19..b9d38d8d8 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_plugin.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/common/pdfviewer_plugin.dart @@ -12,10 +12,13 @@ class PdfViewerPlugin { String? _documentID; /// Initialize the PDF renderer. - Future initializePdfRenderer(Uint8List documentBytes) async { + Future initializePdfRenderer( + Uint8List documentBytes, + String? password, + ) async { _documentID = const Uuid().v1(); final String? pageCount = await PdfViewerPlatform.instance - .initializePdfRenderer(documentBytes, _documentID!); + .initializePdfRenderer(documentBytes, _documentID!, password); _pageCount = int.parse(pageCount!); return _pageCount; } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/common/web_helper.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/common/web_helper.dart index 857819ba8..55913f79a 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/common/web_helper.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/common/web_helper.dart @@ -5,9 +5,10 @@ import 'package:web/web.dart' as web; bool hasPrimaryFocus = false; /// Context Menu Event Listener variable. -JSFunction _contextMenuListener = (web.MouseEvent e) { - e.preventDefault(); -}.toJS; +JSFunction _contextMenuListener = + (web.MouseEvent e) { + e.preventDefault(); + }.toJS; /// Keyboard Event Listener variable. JSFunction _keyDownListener = _preventSpecificDefaultMenu.toJS; @@ -45,3 +46,6 @@ String getPlatformType() { } return web.window.navigator.platform.toLowerCase(); } + +/// In web, pdfium cannot loaded. +bool isPdfiumLoaded() => false; diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/desktop_scrollbar.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/desktop_scrollbar.dart index 7da3680b7..6fc7f54ec 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/desktop_scrollbar.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/desktop_scrollbar.dart @@ -204,9 +204,11 @@ class _DesktopScrollbarState extends State final Offset offset = widget.controller.toScene(Offset.zero); // Determine if scrollbars should be visible based on content and viewport sizes - _canShowVerticalScrollbar = widget.canShowVerticalScrollbar && + _canShowVerticalScrollbar = + widget.canShowVerticalScrollbar && widget.contentSize.height * scale > widget.viewportSize.height; - _canShowHorizontalScrollbar = widget.canShowHorizontalScrollbar && + _canShowHorizontalScrollbar = + widget.canShowHorizontalScrollbar && widget.contentSize.width * scale > widget.viewportSize.width; Widget verticalScrollbar = const SizedBox.shrink(); @@ -230,7 +232,7 @@ class _DesktopScrollbarState extends State // Calculate position ratio for scrollbar movement _widthRatio = (widget.viewportSize.width - _horizontalScrollbarLength) / - _horizontalLimit; + _horizontalLimit; // Calculate left position of the scrollbar _left = (offset.dx * _widthRatio).clamp( @@ -246,8 +248,8 @@ class _DesktopScrollbarState extends State onHorizontalDragUpdate: (DragUpdateDetails details) { // Convert drag delta to content scroll delta final double dx = details.primaryDelta! / _widthRatio; - widget.controller.value = widget.controller.value.clone() - ..translate(-dx); + widget.controller.value = + widget.controller.value.clone()..translate(-dx); widget.onHorizontalDragUpdate?.call(details); }, child: Container( @@ -289,7 +291,7 @@ class _DesktopScrollbarState extends State // Calculate position ratio for scrollbar movement _heightRatio = (widget.viewportSize.height - _verticalScrollbarLength) / - _verticalLimit; + _verticalLimit; // Calculate top position of the scrollbar _top = (offset.dy * _heightRatio).clamp( @@ -305,8 +307,8 @@ class _DesktopScrollbarState extends State onVerticalDragUpdate: (DragUpdateDetails details) { // Convert drag delta to content scroll delta final double dy = details.primaryDelta! / _heightRatio; - widget.controller.value = widget.controller.value.clone() - ..translate(0.0, -dy); + widget.controller.value = + widget.controller.value.clone()..translate(0.0, -dy); widget.onVerticalDragUpdate?.call(details); }, child: Container( diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_page_view.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_page_view.dart index 7a62ad1a4..c6b7efc92 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_page_view.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_page_view.dart @@ -270,9 +270,10 @@ class PdfPageViewState extends State { helper.hasPrimaryFocus = focusNode.hasFocus; }); } - _formFields = widget.formFields - .where((formField) => formField.pageNumber == widget.pageIndex + 1) - .toList(); + _formFields = + widget.formFields + .where((formField) => formField.pageNumber == widget.pageIndex + 1) + .toList(); super.initState(); } @@ -280,9 +281,10 @@ class PdfPageViewState extends State { void didChangeDependencies() { _dpr = MediaQuery.devicePixelRatioOf(context); _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); super.didChangeDependencies(); } @@ -326,97 +328,112 @@ class PdfPageViewState extends State { width: widget.width + widthSpacing, color: Colors.white, alignment: Alignment.topCenter, - child: widget.scrollDirection == PdfScrollDirection.vertical - ? Column( - children: [ - Stack( - children: [ - SizedBox( - width: widget.width, - height: widget.height, - child: Semantics( - label: widget.semanticLabel, - child: _pdfPage, - ), - ), - if (_tileImageCache != null && _tileImage != null) - Positioned( - top: _tileImageCache!.visibleRect.top / - _heightPercentage, - left: _tileImageCache!.visibleRect.left / - _heightPercentage, - width: _tileImageCache!.visibleRect.width / - _heightPercentage, - height: _tileImageCache!.visibleRect.height / - _heightPercentage, - child: SizedBox( - width: _tileImageCache!.imageSize.width, - height: _tileImageCache!.imageSize.height, - child: _tileImage, + child: + widget.scrollDirection == PdfScrollDirection.vertical + ? Column( + children: [ + Stack( + children: [ + SizedBox( + width: widget.width, + height: widget.height, + child: Semantics( + label: widget.semanticLabel, + child: _pdfPage, ), ), - ], - ), - Container( - height: widget.isSinglePageView ? 0.0 : pageSpacing, - color: _pdfViewerThemeData!.backgroundColor ?? - _effectiveThemeData!.backgroundColor ?? - (Theme.of(context).colorScheme.brightness == - Brightness.light - ? const Color(0xFFD6D6D6) - : const Color(0xFF303030)), - ), - ], - ) - : Row( - children: [ - Stack( - children: [ - SizedBox( - width: widget.width, - height: widget.height, - child: _pdfPage, - ), - if (_tileImageCache != null && _tileImage != null) - Positioned( - top: _tileImageCache!.visibleRect.top / - _heightPercentage, - left: _tileImageCache!.visibleRect.left / - _heightPercentage, - width: _tileImageCache!.visibleRect.width / - _heightPercentage, - height: _tileImageCache!.visibleRect.height / - _heightPercentage, - child: SizedBox( - width: _tileImageCache!.imageSize.width, - height: _tileImageCache!.imageSize.height, - child: _tileImage, + if (_tileImageCache != null && _tileImage != null) + Positioned( + top: + _tileImageCache!.visibleRect.top / + _heightPercentage, + left: + _tileImageCache!.visibleRect.left / + _heightPercentage, + width: + _tileImageCache!.visibleRect.width / + _heightPercentage, + height: + _tileImageCache!.visibleRect.height / + _heightPercentage, + child: SizedBox( + width: _tileImageCache!.imageSize.width, + height: _tileImageCache!.imageSize.height, + child: _tileImage, + ), + ), + ], + ), + Container( + height: widget.isSinglePageView ? 0.0 : pageSpacing, + color: + _pdfViewerThemeData!.backgroundColor ?? + _effectiveThemeData!.backgroundColor ?? + (Theme.of(context).colorScheme.brightness == + Brightness.light + ? const Color(0xFFD6D6D6) + : const Color(0xFF303030)), + ), + ], + ) + : Row( + children: [ + Stack( + children: [ + SizedBox( + width: widget.width, + height: widget.height, + child: Semantics( + label: widget.semanticLabel, + child: _pdfPage, ), ), - ], - ), - Container( - width: widget.isSinglePageView ? 0.0 : pageSpacing, - color: _pdfViewerThemeData!.backgroundColor ?? - _effectiveThemeData!.backgroundColor ?? - (Theme.of(context).colorScheme.brightness == - Brightness.light - ? const Color(0xFFD6D6D6) - : const Color(0xFF303030)), - ), - ], - ), + if (_tileImageCache != null && _tileImage != null) + Positioned( + top: + _tileImageCache!.visibleRect.top / + _heightPercentage, + left: + _tileImageCache!.visibleRect.left / + _heightPercentage, + width: + _tileImageCache!.visibleRect.width / + _heightPercentage, + height: + _tileImageCache!.visibleRect.height / + _heightPercentage, + child: SizedBox( + width: _tileImageCache!.imageSize.width, + height: _tileImageCache!.imageSize.height, + child: _tileImage, + ), + ), + ], + ), + Container( + width: widget.isSinglePageView ? 0.0 : pageSpacing, + color: + _pdfViewerThemeData!.backgroundColor ?? + _effectiveThemeData!.backgroundColor ?? + (Theme.of(context).colorScheme.brightness == + Brightness.light + ? const Color(0xFFD6D6D6) + : const Color(0xFF303030)), + ), + ], + ), ); final PdfAnnotationMode annotationMode = widget.pdfViewerController.annotationMode; - _interactionMode = (annotationMode == PdfAnnotationMode.highlight || - annotationMode == PdfAnnotationMode.strikethrough || - annotationMode == PdfAnnotationMode.underline || - annotationMode == PdfAnnotationMode.squiggly) - ? PdfInteractionMode.selection - : widget.interactionMode; + _interactionMode = + (annotationMode == PdfAnnotationMode.highlight || + annotationMode == PdfAnnotationMode.strikethrough || + annotationMode == PdfAnnotationMode.underline || + annotationMode == PdfAnnotationMode.squiggly) + ? PdfInteractionMode.selection + : widget.interactionMode; final Widget canvasContainer = Container( height: _isRotatedTo90or270 ? widget.width : widget.height, @@ -454,292 +471,302 @@ class PdfPageViewState extends State { widget.onAnnotationSelectionChanged, ), ); - final Widget canvas = (kIsDesktop && !widget.isMobileWebView) - ? RotatedBox( - quarterTurns: _quarterTurns, - child: Listener( - onPointerSignal: (PointerSignalEvent details) { - if (widget.isSinglePageView && - details is PointerScrollEvent) { - widget.singlePageViewStateKey.currentState?.jumpTo( - yOffset: widget.pdfViewerController.scrollOffset.dy + - (details.scrollDelta.dy.isNegative - ? -_jumpOffset - : _jumpOffset), - ); - } - canvasRenderBox?.updateContextMenuPosition(); - }, - onPointerDown: (PointerDownEvent details) { - _numberOfActivePointers++; - widget.onPdfPagePointerDown(details); - if (kIsDesktop && !widget.isMobileWebView) { - final int now = DateTime.now().millisecondsSinceEpoch; - if (now - _lastTap <= 500) { - _consecutiveTaps++; - if (_consecutiveTaps == 2 && - details.buttons != kSecondaryButton) { - focusNode.requestFocus(); - canvasRenderBox?.handleDoubleTapDown(details); - } - if (_consecutiveTaps == 3 && - details.buttons != kSecondaryButton) { - focusNode.requestFocus(); - canvasRenderBox?.handleTripleTapDown(details); + final Widget canvas = + (kIsDesktop && !widget.isMobileWebView) + ? RotatedBox( + quarterTurns: _quarterTurns, + child: Listener( + onPointerSignal: (PointerSignalEvent details) { + if (widget.isSinglePageView && + details is PointerScrollEvent) { + widget.singlePageViewStateKey.currentState?.jumpTo( + yOffset: + widget.pdfViewerController.scrollOffset.dy + + (details.scrollDelta.dy.isNegative + ? -_jumpOffset + : _jumpOffset), + ); + } + canvasRenderBox?.updateContextMenuPosition(); + }, + onPointerDown: (PointerDownEvent details) { + _numberOfActivePointers++; + widget.onPdfPagePointerDown(details); + if (kIsDesktop && !widget.isMobileWebView) { + final int now = DateTime.now().millisecondsSinceEpoch; + if (now - _lastTap <= 500) { + _consecutiveTaps++; + if (_consecutiveTaps == 2 && + details.buttons != kSecondaryButton) { + focusNode.requestFocus(); + canvasRenderBox?.handleDoubleTapDown(details); + } + if (_consecutiveTaps == 3 && + details.buttons != kSecondaryButton) { + focusNode.requestFocus(); + canvasRenderBox?.handleTripleTapDown(details); + } + } else { + _consecutiveTaps = 1; } - } else { - _consecutiveTaps = 1; + _lastTap = now; } - _lastTap = now; - } - }, - onPointerMove: (PointerMoveEvent details) { - if (_numberOfActivePointers > 1 && - details.delta != Offset.zero && - !_isZooming && - mounted) { - setState(() { - _isZooming = true; - }); - } - focusNode.requestFocus(); - widget.onPdfPagePointerMove(details); - if (_interactionMode == PdfInteractionMode.pan) { - _cursor = SystemMouseCursors.grabbing; - } - }, - onPointerUp: (PointerUpEvent details) { - _numberOfActivePointers--; - if (_numberOfActivePointers <= 1 && mounted) { - setState(() { - _isZooming = false; - }); - } - - widget.onPdfPagePointerUp(details); - _onPageTapped(details.localPosition); - if (_interactionMode == PdfInteractionMode.pan) { - _cursor = SystemMouseCursors.grab; - } - if (widget.pdfViewerController.annotationMode == - PdfAnnotationMode.highlight || - widget.pdfViewerController.annotationMode == - PdfAnnotationMode.underline || - widget.pdfViewerController.annotationMode == - PdfAnnotationMode.strikethrough || - widget.pdfViewerController.annotationMode == - PdfAnnotationMode.squiggly) { - if (_consecutiveTaps > 1) { - Future.delayed( - const Duration(milliseconds: 300), - () { - _addTextMarkupAnnotation( - widget.pdfViewerController.annotationMode - .toString() - .split('.') - .last, - ); - }, - ); + }, + onPointerMove: (PointerMoveEvent details) { + if (_numberOfActivePointers > 1 && + details.delta != Offset.zero && + !_isZooming && + mounted) { + setState(() { + _isZooming = true; + }); } - } - }, - child: KeyboardListener( - focusNode: focusNode, - onKeyEvent: (KeyEvent event) { - final bool isPrimaryKeyPressed = kIsMacOS - ? HardwareKeyboard.instance.isMetaPressed - : HardwareKeyboard.instance.isControlPressed; - if (canvasRenderBox != null && - (canvasRenderBox! - .getSelectionDetails() - .mouseSelectionEnabled || - canvasRenderBox! - .getSelectionDetails() - .selectionEnabled) && - isPrimaryKeyPressed && - event.logicalKey == LogicalKeyboardKey.keyC) { - Clipboard.setData( - ClipboardData( - text: canvasRenderBox! - .getSelectionDetails() - .copiedText ?? - '', - ), - ); + focusNode.requestFocus(); + widget.onPdfPagePointerMove(details); + if (_interactionMode == PdfInteractionMode.pan) { + _cursor = SystemMouseCursors.grabbing; } - if (isPrimaryKeyPressed && - event.logicalKey == LogicalKeyboardKey.digit0) { - widget.pdfViewerController.zoomLevel = 1.0; + }, + onPointerUp: (PointerUpEvent details) { + _numberOfActivePointers--; + if (_numberOfActivePointers <= 1 && mounted) { + setState(() { + _isZooming = false; + }); } - if (isPrimaryKeyPressed && - event.logicalKey == LogicalKeyboardKey.minus) { - if (event is KeyDownEvent) { - double zoomLevel = widget.pdfViewerController.zoomLevel; - if (zoomLevel > 1) { - zoomLevel = zoomLevel - 0.5; - } - widget.pdfViewerController.zoomLevel = zoomLevel; - } + + widget.onPdfPagePointerUp(details); + _onPageTapped(details.localPosition); + if (_interactionMode == PdfInteractionMode.pan) { + _cursor = SystemMouseCursors.grab; } - if (isPrimaryKeyPressed && - event.logicalKey == LogicalKeyboardKey.equal) { - if (event is KeyDownEvent) { - double zoomLevel = widget.pdfViewerController.zoomLevel; - zoomLevel = zoomLevel + 0.5; - widget.pdfViewerController.zoomLevel = zoomLevel; + if (widget.pdfViewerController.annotationMode == + PdfAnnotationMode.highlight || + widget.pdfViewerController.annotationMode == + PdfAnnotationMode.underline || + widget.pdfViewerController.annotationMode == + PdfAnnotationMode.strikethrough || + widget.pdfViewerController.annotationMode == + PdfAnnotationMode.squiggly) { + if (_consecutiveTaps > 1) { + Future.delayed( + const Duration(milliseconds: 300), + () { + _addTextMarkupAnnotation( + widget.pdfViewerController.annotationMode + .toString() + .split('.') + .last, + ); + }, + ); } } - if (event is KeyDownEvent) { - if (event.logicalKey == LogicalKeyboardKey.home || - (kIsMacOS && - event.logicalKey == LogicalKeyboardKey.fn && - event.logicalKey == - LogicalKeyboardKey.arrowLeft)) { - widget.pdfViewerController.jumpToPage(1); - } else if (event.logicalKey == LogicalKeyboardKey.end || - (kIsMacOS && - event.logicalKey == LogicalKeyboardKey.fn && - event.logicalKey == - LogicalKeyboardKey.arrowRight)) { - widget.pdfViewerController.jumpToPage( - widget.pdfViewerController.pageCount, + }, + child: KeyboardListener( + focusNode: focusNode, + onKeyEvent: (KeyEvent event) { + final bool isPrimaryKeyPressed = + kIsMacOS + ? HardwareKeyboard.instance.isMetaPressed + : HardwareKeyboard.instance.isControlPressed; + if (canvasRenderBox != null && + (canvasRenderBox! + .getSelectionDetails() + .mouseSelectionEnabled || + canvasRenderBox! + .getSelectionDetails() + .selectionEnabled) && + isPrimaryKeyPressed && + event.logicalKey == LogicalKeyboardKey.keyC) { + Clipboard.setData( + ClipboardData( + text: + canvasRenderBox! + .getSelectionDetails() + .copiedText ?? + '', + ), ); - } else if (event.logicalKey == - LogicalKeyboardKey.arrowRight) { - widget.pdfViewerController.nextPage(); - } else if (event.logicalKey == - LogicalKeyboardKey.arrowLeft) { - widget.pdfViewerController.previousPage(); - } else if (isPrimaryKeyPressed && - event.logicalKey == LogicalKeyboardKey.keyZ) { - widget.undoController.undo(); - } else if (isPrimaryKeyPressed && - event.logicalKey == LogicalKeyboardKey.keyY) { - widget.undoController.redo(); - } else if (event.logicalKey == - LogicalKeyboardKey.escape) { - widget.onAnnotationSelectionChanged?.call(null); - } else if (event.logicalKey == - LogicalKeyboardKey.delete) { - if (widget.selectedAnnotation != null) { - widget.pdfViewerController.removeAnnotation( - widget.selectedAnnotation!, - ); + } + if (isPrimaryKeyPressed && + event.logicalKey == LogicalKeyboardKey.digit0) { + widget.pdfViewerController.zoomLevel = 1.0; + } + if (isPrimaryKeyPressed && + event.logicalKey == LogicalKeyboardKey.minus) { + if (event is KeyDownEvent) { + double zoomLevel = + widget.pdfViewerController.zoomLevel; + if (zoomLevel > 1) { + zoomLevel = zoomLevel - 0.5; + } + widget.pdfViewerController.zoomLevel = zoomLevel; } } - } - if (event.logicalKey == LogicalKeyboardKey.arrowUp) { - canvasRenderBox?.scroll(true, false); - } - if (event.logicalKey == LogicalKeyboardKey.arrowDown) { - canvasRenderBox?.scroll(false, false); - } - }, - child: MouseRegion( - cursor: _cursor, - onHover: (PointerHoverEvent details) { - setState(() { - if (canvasRenderBox != null && - widget.pdfPages.isNotEmpty) { - final Annotation? annotation = - canvasRenderBox!.findAnnotation( - details.localPosition, - widget.pageIndex + 1, + if (isPrimaryKeyPressed && + event.logicalKey == LogicalKeyboardKey.equal) { + if (event is KeyDownEvent) { + double zoomLevel = + widget.pdfViewerController.zoomLevel; + zoomLevel = zoomLevel + 0.5; + widget.pdfViewerController.zoomLevel = zoomLevel; + } + } + if (event is KeyDownEvent) { + if (event.logicalKey == LogicalKeyboardKey.home || + (kIsMacOS && + event.logicalKey == LogicalKeyboardKey.fn && + event.logicalKey == + LogicalKeyboardKey.arrowLeft)) { + widget.pdfViewerController.jumpToPage(1); + } else if (event.logicalKey == LogicalKeyboardKey.end || + (kIsMacOS && + event.logicalKey == LogicalKeyboardKey.fn && + event.logicalKey == + LogicalKeyboardKey.arrowRight)) { + widget.pdfViewerController.jumpToPage( + widget.pdfViewerController.pageCount, ); - if (_interactionMode == - PdfInteractionMode.selection) { - final bool isText = - canvasRenderBox!.findTextWhileHover( - details.localPosition, - ) != - null; - final bool isTOC = canvasRenderBox!.findTOC( - details.localPosition, + } else if (event.logicalKey == + LogicalKeyboardKey.arrowRight) { + widget.pdfViewerController.nextPage(); + } else if (event.logicalKey == + LogicalKeyboardKey.arrowLeft) { + widget.pdfViewerController.previousPage(); + } else if (isPrimaryKeyPressed && + event.logicalKey == LogicalKeyboardKey.keyZ) { + widget.undoController.undo(); + } else if (isPrimaryKeyPressed && + event.logicalKey == LogicalKeyboardKey.keyY) { + widget.undoController.redo(); + } else if (event.logicalKey == + LogicalKeyboardKey.escape) { + widget.onAnnotationSelectionChanged?.call(null); + } else if (event.logicalKey == + LogicalKeyboardKey.delete) { + if (widget.selectedAnnotation != null) { + widget.pdfViewerController.removeAnnotation( + widget.selectedAnnotation!, ); - if (isTOC) { - _cursor = SystemMouseCursors.click; - } else if (isText && !isTOC && annotation == null) { - if (_isRotatedTo90or270) { - _cursor = SystemMouseCursors.verticalText; + } + } + } + if (event.logicalKey == LogicalKeyboardKey.arrowUp) { + canvasRenderBox?.scroll(true, false); + } + if (event.logicalKey == LogicalKeyboardKey.arrowDown) { + canvasRenderBox?.scroll(false, false); + } + }, + child: MouseRegion( + cursor: _cursor, + onHover: (PointerHoverEvent details) { + setState(() { + if (canvasRenderBox != null && + widget.pdfPages.isNotEmpty) { + final Annotation? annotation = canvasRenderBox! + .findAnnotation( + details.localPosition, + widget.pageIndex + 1, + ); + if (_interactionMode == + PdfInteractionMode.selection) { + final bool isText = + canvasRenderBox!.findTextWhileHover( + details.localPosition, + ) != + null; + final bool isTOC = canvasRenderBox!.findTOC( + details.localPosition, + ); + if (isTOC) { + _cursor = SystemMouseCursors.click; + } else if (isText && + !isTOC && + annotation == null) { + if (_isRotatedTo90or270) { + _cursor = SystemMouseCursors.verticalText; + } else { + _cursor = SystemMouseCursors.text; + } } else { - _cursor = SystemMouseCursors.text; + _cursor = SystemMouseCursors.basic; } } else { - _cursor = SystemMouseCursors.basic; - } - } else { - final bool isTOC = canvasRenderBox!.findTOC( - details.localPosition, - ); - if (isTOC) { - _cursor = SystemMouseCursors.click; - } else if (_cursor != SystemMouseCursors.grab) { - _cursor = SystemMouseCursors.grab; + final bool isTOC = canvasRenderBox!.findTOC( + details.localPosition, + ); + if (isTOC) { + _cursor = SystemMouseCursors.click; + } else if (_cursor != SystemMouseCursors.grab) { + _cursor = SystemMouseCursors.grab; + } } } - } - }); - }, - child: canvasContainer, + }); + }, + child: canvasContainer, + ), ), ), - ), - ) - : RotatedBox( - quarterTurns: _quarterTurns, - child: Listener( - onPointerDown: (PointerDownEvent details) { - _numberOfActivePointers++; - widget.onPdfPagePointerDown(details); - }, - onPointerMove: (PointerMoveEvent details) { - if (_numberOfActivePointers > 1 && - details.delta != Offset.zero && - !_isZooming && - mounted) { - setState(() { - _isZooming = true; - }); - } - widget.onPdfPagePointerMove(details); - }, - onPointerUp: (PointerUpEvent details) { - _numberOfActivePointers--; - if (_numberOfActivePointers <= 1 && mounted) { - setState(() { - _isZooming = false; - }); - } - widget.onPdfPagePointerUp(details); - _onPageTapped(details.localPosition); - }, - child: widget.isAndroidTV - ? KeyboardListener( - focusNode: focusNode, - onKeyEvent: (KeyEvent event) { - if (event is KeyDownEvent) { - if (event.logicalKey == - LogicalKeyboardKey.arrowRight) { - widget.pdfViewerController.nextPage(); - } else if (event.logicalKey == - LogicalKeyboardKey.arrowLeft) { - widget.pdfViewerController.previousPage(); - } - } - if (event.logicalKey == LogicalKeyboardKey.arrowUp) { - canvasRenderBox?.scroll(true, false); - } - if (event.logicalKey == - LogicalKeyboardKey.arrowDown) { - canvasRenderBox?.scroll(false, false); - } - }, - child: canvasContainer, - ) - : canvasContainer, - ), - ); + ) + : RotatedBox( + quarterTurns: _quarterTurns, + child: Listener( + onPointerDown: (PointerDownEvent details) { + _numberOfActivePointers++; + widget.onPdfPagePointerDown(details); + }, + onPointerMove: (PointerMoveEvent details) { + if (_numberOfActivePointers > 1 && + details.delta != Offset.zero && + !_isZooming && + mounted) { + setState(() { + _isZooming = true; + }); + } + widget.onPdfPagePointerMove(details); + }, + onPointerUp: (PointerUpEvent details) { + _numberOfActivePointers--; + if (_numberOfActivePointers <= 1 && mounted) { + setState(() { + _isZooming = false; + }); + } + widget.onPdfPagePointerUp(details); + _onPageTapped(details.localPosition); + }, + child: + widget.isAndroidTV + ? KeyboardListener( + focusNode: focusNode, + onKeyEvent: (KeyEvent event) { + if (event is KeyDownEvent) { + if (event.logicalKey == + LogicalKeyboardKey.arrowRight) { + widget.pdfViewerController.nextPage(); + } else if (event.logicalKey == + LogicalKeyboardKey.arrowLeft) { + widget.pdfViewerController.previousPage(); + } + } + if (event.logicalKey == + LogicalKeyboardKey.arrowUp) { + canvasRenderBox?.scroll(true, false); + } + if (event.logicalKey == + LogicalKeyboardKey.arrowDown) { + canvasRenderBox?.scroll(false, false); + } + }, + child: canvasContainer, + ) + : canvasContainer, + ), + ); Widget? formFieldContainer; if (_formFields.isNotEmpty) { @@ -810,7 +837,8 @@ class PdfPageViewState extends State { } final BorderSide borderSide = BorderSide( width: widget.isSinglePageView ? pageSpacing / 2 : pageSpacing, - color: _pdfViewerThemeData!.backgroundColor ?? + color: + _pdfViewerThemeData!.backgroundColor ?? _effectiveThemeData!.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? const Color(0xFFD6D6D6) @@ -821,9 +849,10 @@ class PdfPageViewState extends State { width: widget.width + widthSpacing, color: Colors.white, foregroundDecoration: BoxDecoration( - border: widget.isSinglePageView - ? Border(left: borderSide, right: borderSide) - : widget.scrollDirection == PdfScrollDirection.horizontal + border: + widget.isSinglePageView + ? Border(left: borderSide, right: borderSide) + : widget.scrollDirection == PdfScrollDirection.horizontal ? widget.textDirection == TextDirection.rtl ? Border(left: borderSide) : Border(right: borderSide) @@ -838,17 +867,18 @@ class PdfPageViewState extends State { _effectiveThemeData!.progressBarColor ?? (Theme.of(context).colorScheme.primary), ), - backgroundColor: _pdfViewerThemeData!.progressBarColor != null - ? _pdfViewerThemeData!.progressBarColor!.withValues( - alpha: 0.2, - ) - : _effectiveThemeData!.progressBarColor != null + backgroundColor: + _pdfViewerThemeData!.progressBarColor != null + ? _pdfViewerThemeData!.progressBarColor!.withValues( + alpha: 0.2, + ) + : _effectiveThemeData!.progressBarColor != null ? _effectiveThemeData!.progressBarColor!.withValues( - alpha: 0.2, - ) + alpha: 0.2, + ) : (Theme.of( - context, - ).colorScheme.primary.withValues(alpha: 0.2)), + context, + ).colorScheme.primary.withValues(alpha: 0.2)), ), ), ), @@ -867,10 +897,12 @@ class PdfPageViewState extends State { } else if (rotatedAngle == PdfPageRotateAngle.rotateAngle270) { _quarterTurns = 3; } - _isRotatedTo90or270 = rotatedAngle == PdfPageRotateAngle.rotateAngle90 || + _isRotatedTo90or270 = + rotatedAngle == PdfPageRotateAngle.rotateAngle90 || rotatedAngle == PdfPageRotateAngle.rotateAngle270; _originalPageSize = widget.pdfDocument!.pages[widget.pageIndex].size; - _heightPercentage = (_isRotatedTo90or270 + _heightPercentage = + (_isRotatedTo90or270 ? _originalPageSize.width : _originalPageSize.height) / widget.pdfPages[widget.pageIndex + 1]!.pageSize.height; @@ -892,8 +924,19 @@ class PdfPageViewState extends State { if (_pdfPage != null) { return; } - _imageWidth = originalPageSize.width.toInt(); - _imageHeight = originalPageSize.height.toInt(); + + // This condition checks if the original image size in bytes (width * height * 4) is + // less than or equal to 5 MB (5 * 1024 * 1024 bytes). The factor of 4 accounts for + // the RGBA channels (4 bytes per pixel). If the image size is within this limit, + // we use the original dimensions; otherwise, we adjust to the widget's dimensions. + if (originalPageSize.width * originalPageSize.height * 4 <= + 5 * 1024 * 1024) { + _imageWidth = originalPageSize.width.toInt(); + _imageHeight = originalPageSize.height.toInt(); + } else { + _imageWidth = widget.width.toInt(); + _imageHeight = widget.height.toInt(); + } } else { _tileImageCache = null; _isTile = false; @@ -1028,7 +1071,7 @@ class PdfPageViewState extends State { } else { pageBounds = Rect.fromLTWH( 0, - y, + 0, widget.width * zoomLevel * _heightPercentage, widget.height * zoomLevel * _heightPercentage, ); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_scrollable.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_scrollable.dart index f65770e0a..873f2ee72 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_scrollable.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdf_scrollable.dart @@ -292,14 +292,19 @@ class PdfScrollableState extends State { void _handleInteractionEnd(ScaleEndDetails details) { paddingWidthScale = 0; paddingHeightScale = 0; - final double totalPdfPageWidth = (widget.textDirection == - TextDirection.rtl && - widget.scrollDirection == PdfScrollDirection.horizontal) - // In RTL direction, the last page is rendered at Offset.zero and the first page is rendered at the end. - ? widget.pdfPages[1]!.pageOffset + widget.pdfPages[1]!.pageSize.width - : widget.pdfPages[widget.pdfViewerController.pageCount]!.pageOffset + - widget - .pdfPages[widget.pdfViewerController.pageCount]!.pageSize.width; + final double totalPdfPageWidth = + (widget.textDirection == TextDirection.rtl && + widget.scrollDirection == PdfScrollDirection.horizontal) + // In RTL direction, the last page is rendered at Offset.zero and the first page is rendered at the end. + ? widget.pdfPages[1]!.pageOffset + + widget.pdfPages[1]!.pageSize.width + : widget + .pdfPages[widget.pdfViewerController.pageCount]! + .pageOffset + + widget + .pdfPages[widget.pdfViewerController.pageCount]! + .pageSize + .width; if (_currentScale != widget.pdfViewerController.zoomLevel && _currentScale != null && _currentScale != 0.0 && @@ -378,7 +383,8 @@ class PdfScrollableState extends State { widget.pdfViewerController.zoomLevel) { offset = Offset(offset.dx, 0); } - final double widthFactor = widget.pdfDimension.width - + final double widthFactor = + widget.pdfDimension.width - (widget.viewportDimension.width / widget.pdfViewerController.zoomLevel); offset = Offset( @@ -425,7 +431,8 @@ class PdfScrollableState extends State { if (!mounted) { return; } - final double widthFactor = widget.pdfDimension.width - + final double widthFactor = + widget.pdfDimension.width - (widget.viewportDimension.width / widget.pdfViewerController.zoomLevel); offset = Offset( offset.dx.clamp(-widthFactor, widthFactor.abs()), diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdfviewer_canvas.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdfviewer_canvas.dart index 62dc63438..d0d461273 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdfviewer_canvas.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/pdfviewer_canvas.dart @@ -234,26 +234,29 @@ class CanvasRenderBox extends RenderBox { this.onAnnotationSelectionChanged, ) { final GestureArenaTeam team = GestureArenaTeam(); - _tapRecognizer = TapGestureRecognizer() - ..onTapUp = handleTapUp - ..onTapDown = handleTapDown; - _longPressRecognizer = LongPressGestureRecognizer() - ..onLongPressStart = handleLongPressStart; - _dragRecognizer = HorizontalDragGestureRecognizer() - ..team = team - ..onStart = handleDragStart - ..onUpdate = handleDragUpdate - ..onEnd = handleDragEnd - ..onDown = handleDragDown; + _tapRecognizer = + TapGestureRecognizer() + ..onTapUp = handleTapUp + ..onTapDown = handleTapDown; + _longPressRecognizer = + LongPressGestureRecognizer()..onLongPressStart = handleLongPressStart; + _dragRecognizer = + HorizontalDragGestureRecognizer() + ..team = team + ..onStart = handleDragStart + ..onUpdate = handleDragUpdate + ..onEnd = handleDragEnd + ..onDown = handleDragDown; _dragRecognizer.gestureSettings = const DeviceGestureSettings( touchSlop: 10, ); - _verticalDragRecognizer = VerticalDragGestureRecognizer() - ..team = team - ..onStart = handleDragStart - ..onUpdate = handleDragUpdate - ..onEnd = handleDragEnd - ..onDown = handleDragDown; + _verticalDragRecognizer = + VerticalDragGestureRecognizer() + ..team = team + ..onStart = handleDragStart + ..onUpdate = handleDragUpdate + ..onEnd = handleDragEnd + ..onDown = handleDragDown; _verticalDragRecognizer.gestureSettings = const DeviceGestureSettings( touchSlop: 10, ); @@ -467,9 +470,10 @@ class CanvasRenderBox extends RenderBox { Future _showMobileHyperLinkDialog(Uri url) { _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _themeData = Theme.of(context); final bool isMaterial3 = _themeData.useMaterial3; _localizations = SfLocalizations.of(context); @@ -482,14 +486,16 @@ class CanvasRenderBox extends RenderBox { child: AlertDialog( scrollable: true, insetPadding: EdgeInsets.zero, - contentPadding: orientation == Orientation.portrait - ? const EdgeInsets.all(24) - : const EdgeInsets.all(15), - buttonPadding: orientation == Orientation.portrait - ? const EdgeInsets.all(8) - : const EdgeInsets.all(6), - backgroundColor: _pdfViewerThemeData! - .hyperlinkDialogStyle?.backgroundColor ?? + contentPadding: + orientation == Orientation.portrait + ? const EdgeInsets.all(24) + : const EdgeInsets.all(15), + buttonPadding: + orientation == Orientation.portrait + ? const EdgeInsets.all(8) + : const EdgeInsets.all(6), + backgroundColor: + _pdfViewerThemeData!.hyperlinkDialogStyle?.backgroundColor ?? _effectiveThemeData.hyperlinkDialogStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white @@ -499,35 +505,36 @@ class CanvasRenderBox extends RenderBox { children: [ Text( _localizations.pdfHyperlinkLabel, - style: isMaterial3 - ? Theme.of(context) - .textTheme - .headlineMedium! - .copyWith( - fontSize: 24, - color: - Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), - ) - .merge( - _pdfViewerThemeData! - .hyperlinkDialogStyle?.headerTextStyle, - ) - : Theme.of(context) - .textTheme - .headlineMedium! - .copyWith( - fontSize: 20, - color: - Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), - ) - .merge( - _pdfViewerThemeData! - .hyperlinkDialogStyle?.headerTextStyle, - ), + style: + isMaterial3 + ? Theme.of(context).textTheme.headlineMedium! + .copyWith( + fontSize: 24, + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), + ) + .merge( + _pdfViewerThemeData! + .hyperlinkDialogStyle + ?.headerTextStyle, + ) + : Theme.of(context).textTheme.headlineMedium! + .copyWith( + fontSize: 20, + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), + ) + .merge( + _pdfViewerThemeData! + .hyperlinkDialogStyle + ?.headerTextStyle, + ), ), SizedBox( height: isMaterial3 ? 40 : 36, @@ -537,17 +544,21 @@ class CanvasRenderBox extends RenderBox { Navigator.of(context).pop(); _isHyperLinkTapped = false; }, - shape: isMaterial3 - ? RoundedRectangleBorder( - borderRadius: BorderRadius.circular(40), - ) - : const RoundedRectangleBorder(), + shape: + isMaterial3 + ? RoundedRectangleBorder( + borderRadius: BorderRadius.circular(40), + ) + : const RoundedRectangleBorder(), child: Icon( Icons.clear, - color: _pdfViewerThemeData! - .hyperlinkDialogStyle?.closeIconColor ?? + color: + _pdfViewerThemeData! + .hyperlinkDialogStyle + ?.closeIconColor ?? _effectiveThemeData - .hyperlinkDialogStyle?.closeIconColor ?? + .hyperlinkDialogStyle + ?.closeIconColor ?? _themeData.colorScheme.onSurface.withValues( alpha: 0.6, ), @@ -557,67 +568,72 @@ class CanvasRenderBox extends RenderBox { ), ], ), - shape: isMaterial3 - ? null - : const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), + shape: + isMaterial3 + ? null + : const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), content: SingleChildScrollView( child: SizedBox( width: 296, child: Column( children: [ Align( - alignment: textDirection == TextDirection.rtl - ? Alignment.centerRight - : Alignment.centerLeft, + alignment: + textDirection == TextDirection.rtl + ? Alignment.centerRight + : Alignment.centerLeft, child: Padding( - padding: orientation == Orientation.portrait - ? const EdgeInsets.fromLTRB(2, 0, 0, 8) - : const EdgeInsets.fromLTRB(10, 0, 0, 8), + padding: + orientation == Orientation.portrait + ? const EdgeInsets.fromLTRB(2, 0, 0, 8) + : const EdgeInsets.fromLTRB(10, 0, 0, 8), child: Text( _localizations.pdfHyperlinkContentLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.contentTextStyle, + .hyperlinkDialogStyle + ?.contentTextStyle, ), ), ), ), Align( - alignment: textDirection == TextDirection.rtl - ? Alignment.centerRight - : Alignment.centerLeft, + alignment: + textDirection == TextDirection.rtl + ? Alignment.centerRight + : Alignment.centerLeft, child: Padding( - padding: orientation == Orientation.portrait - ? const EdgeInsets.fromLTRB(2, 0, 0, 0) - : const EdgeInsets.fromLTRB(10, 0, 0, 4), + padding: + orientation == Orientation.portrait + ? const EdgeInsets.fromLTRB(2, 0, 0, 0) + : const EdgeInsets.fromLTRB(10, 0, 0, 4), child: Text( '$url?', textDirection: TextDirection.ltr, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.contentTextStyle, + .hyperlinkDialogStyle + ?.contentTextStyle, ), ), ), @@ -632,31 +648,32 @@ class CanvasRenderBox extends RenderBox { Navigator.of(context).pop(); _isHyperLinkTapped = false; }, - style: isMaterial3 - ? ButtonStyle( - padding: WidgetStateProperty.all( - const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, + style: + isMaterial3 + ? ButtonStyle( + padding: WidgetStateProperty.all( + const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), ), - ), - ) - : null, + ) + : null, child: Text( _localizations.pdfHyperlinkDialogCancelLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.cancelTextStyle, + .hyperlinkDialogStyle + ?.cancelTextStyle, ), ), ), @@ -667,21 +684,20 @@ class CanvasRenderBox extends RenderBox { Navigator.of(context).pop(); await launchUrl(url, mode: LaunchMode.externalApplication); }, - style: isMaterial3 - ? ButtonStyle( - padding: WidgetStateProperty.all( - const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, + style: + isMaterial3 + ? ButtonStyle( + padding: WidgetStateProperty.all( + const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), ), - ), - ) - : null, + ) + : null, child: Text( _localizations.pdfHyperlinkDialogOpenLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -689,7 +705,8 @@ class CanvasRenderBox extends RenderBox { ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.openTextStyle, + .hyperlinkDialogStyle + ?.openTextStyle, ), ), ), @@ -704,9 +721,10 @@ class CanvasRenderBox extends RenderBox { Future _showDesktopHyperLinkDialog(Uri url) { _pdfViewerThemeData = SfPdfViewerTheme.of(context); final bool isMaterial3 = Theme.of(context).useMaterial3; - _effectiveThemeData = isMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + isMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _themeData = Theme.of(context); _localizations = SfLocalizations.of(context); return showDialog( @@ -721,8 +739,8 @@ class CanvasRenderBox extends RenderBox { contentPadding: isMaterial3 ? null : const EdgeInsets.symmetric(horizontal: 16), buttonPadding: const EdgeInsets.all(24), - backgroundColor: _pdfViewerThemeData! - .hyperlinkDialogStyle?.backgroundColor ?? + backgroundColor: + _pdfViewerThemeData!.hyperlinkDialogStyle?.backgroundColor ?? _effectiveThemeData.hyperlinkDialogStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white @@ -732,20 +750,21 @@ class CanvasRenderBox extends RenderBox { children: [ Text( _localizations.pdfHyperlinkLabel, - style: Theme.of(context) - .textTheme - .headlineMedium! + style: Theme.of(context).textTheme.headlineMedium! .copyWith( fontSize: isMaterial3 ? 24 : 20, - color: isMaterial3 - ? Theme.of(context).colorScheme.onSurface - : Theme.of(context).brightness == Brightness.light + color: + isMaterial3 + ? Theme.of(context).colorScheme.onSurface + : Theme.of(context).brightness == + Brightness.light ? Colors.black.withValues(alpha: 0.87) : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.headerTextStyle, + .hyperlinkDialogStyle + ?.headerTextStyle, ), ), SizedBox( @@ -756,17 +775,21 @@ class CanvasRenderBox extends RenderBox { Navigator.of(context).pop(); _isHyperLinkTapped = false; }, - shape: isMaterial3 - ? RoundedRectangleBorder( - borderRadius: BorderRadius.circular(40), - ) - : const RoundedRectangleBorder(), + shape: + isMaterial3 + ? RoundedRectangleBorder( + borderRadius: BorderRadius.circular(40), + ) + : const RoundedRectangleBorder(), child: Icon( Icons.clear, - color: _pdfViewerThemeData! - .hyperlinkDialogStyle?.closeIconColor ?? + color: + _pdfViewerThemeData! + .hyperlinkDialogStyle + ?.closeIconColor ?? _effectiveThemeData - .hyperlinkDialogStyle?.closeIconColor ?? + .hyperlinkDialogStyle + ?.closeIconColor ?? _themeData.colorScheme.onSurface.withValues( alpha: 0.6, ), @@ -782,54 +805,57 @@ class CanvasRenderBox extends RenderBox { child: Column( children: [ Align( - alignment: textDirection == TextDirection.rtl - ? Alignment.centerRight - : Alignment.centerLeft, + alignment: + textDirection == TextDirection.rtl + ? Alignment.centerRight + : Alignment.centerLeft, child: Padding( - padding: isMaterial3 - ? const EdgeInsets.fromLTRB(2, 0, 0, 2) - : const EdgeInsets.fromLTRB(2, 0, 0, 8), + padding: + isMaterial3 + ? const EdgeInsets.fromLTRB(2, 0, 0, 2) + : const EdgeInsets.fromLTRB(2, 0, 0, 8), child: Text( _localizations.pdfHyperlinkContentLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.contentTextStyle, + .hyperlinkDialogStyle + ?.contentTextStyle, ), ), ), ), Align( - alignment: textDirection == TextDirection.rtl - ? Alignment.centerRight - : Alignment.centerLeft, + alignment: + textDirection == TextDirection.rtl + ? Alignment.centerRight + : Alignment.centerLeft, child: Padding( padding: const EdgeInsets.fromLTRB(2, 0, 0, 0), child: Text( '$url?', textDirection: TextDirection.ltr, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.contentTextStyle, + .hyperlinkDialogStyle + ?.contentTextStyle, ), ), ), @@ -844,30 +870,31 @@ class CanvasRenderBox extends RenderBox { Navigator.of(context).pop(); _isHyperLinkTapped = false; }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations.pdfHyperlinkDialogCancelLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.cancelTextStyle, + .hyperlinkDialogStyle + ?.cancelTextStyle, ), ), ), @@ -876,20 +903,19 @@ class CanvasRenderBox extends RenderBox { Navigator.of(context).pop(); await launchUrl(url, mode: LaunchMode.externalApplication); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations.pdfHyperlinkDialogOpenLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -897,7 +923,8 @@ class CanvasRenderBox extends RenderBox { ) .merge( _pdfViewerThemeData! - .hyperlinkDialogStyle?.openTextStyle, + .hyperlinkDialogStyle + ?.openTextStyle, ), ), ), @@ -959,21 +986,23 @@ class CanvasRenderBox extends RenderBox { r'^.+@[a-zA-Z]+\.{1}[a-zA-Z]+(\.{0,1}[a-zA-Z]+)$', ).hasMatch(_pdfTextWebLink!.url); final bool isTel = _pdfTextWebLink!.url.startsWith('tel:'); - final String scheme = isMailID - ? !_pdfTextWebLink!.url.contains('mailto') - ? 'mailto' - : '' - : isTel + final String scheme = + isMailID + ? !_pdfTextWebLink!.url.contains('mailto') + ? 'mailto' + : '' + : isTel ? 'tel' : (!_pdfTextWebLink!.url.contains('https') && - !_pdfTextWebLink!.url.contains('http')) - ? 'https' - : ''; - final Uri url = !_pdfTextWebLink!.url.contains(scheme) - ? scheme.contains('mailto') || scheme.contains('tel') - ? Uri(scheme: scheme, path: _pdfTextWebLink!.url) - : Uri(scheme: scheme, host: _pdfTextWebLink!.url) - : Uri.parse(_pdfTextWebLink!.url); + !_pdfTextWebLink!.url.contains('http')) + ? 'https' + : ''; + final Uri url = + !_pdfTextWebLink!.url.contains(scheme) + ? scheme.contains('mailto') || scheme.contains('tel') + ? Uri(scheme: scheme, path: _pdfTextWebLink!.url) + : Uri(scheme: scheme, host: _pdfTextWebLink!.url) + : Uri.parse(_pdfTextWebLink!.url); _showHyperLinkDialog(url); markNeedsPaint(); break; @@ -1075,12 +1104,13 @@ class CanvasRenderBox extends RenderBox { final double heightPercentage = pdfDocument!.pages[pageIndex].size.height / height; - final List annotations = pdfViewerController - .getAnnotations() - .where( - (Annotation annotation) => annotation.pageNumber == pageNumber, - ) - .toList(); + final List annotations = + pdfViewerController + .getAnnotations() + .where( + (Annotation annotation) => annotation.pageNumber == pageNumber, + ) + .toList(); annotations.sort( (Annotation b, Annotation a) => a.zOrder.compareTo(b.zOrder), @@ -1141,7 +1171,8 @@ class CanvasRenderBox extends RenderBox { } if (annotation is StickyNoteAnnotation) { - final Rect scaledBounds = annotation.boundingBox.topLeft & + final Rect scaledBounds = + annotation.boundingBox.topLeft * heightPercentage & (annotation.boundingBox.size / pdfViewerController.zoomLevel); if (scaledBounds.contains(tappedPagePosition)) { return true; @@ -1318,21 +1349,31 @@ class CanvasRenderBox extends RenderBox { pdfDocument!, ).extractTextLines(startPageIndex: pageIndex); } - for (int textLineIndex = 0; - textLineIndex < _textSelectionHelper.textLines!.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < _textSelectionHelper.textLines!.length; + textLineIndex++ + ) { final double heightPercentage = pdfDocument!.pages[_textSelectionHelper.viewId!].size.height / height; - for (int wordIndex = 0; - wordIndex < - _textSelectionHelper - .textLines![textLineIndex].wordCollection.length; - wordIndex++) { - final TextWord textWord = _textSelectionHelper - .textLines![textLineIndex].wordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int wordIndex = 0; + wordIndex < + _textSelectionHelper + .textLines![textLineIndex] + .wordCollection + .length; + wordIndex++ + ) { + final TextWord textWord = + _textSelectionHelper + .textLines![textLineIndex] + .wordCollection[wordIndex]; + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph textGlyph = textWord.glyphs[glyphIndex]; Rect glyphBounds = textGlyph.bounds; if (pdfViewerController.annotationMode != PdfAnnotationMode.none) { @@ -1390,7 +1431,7 @@ class CanvasRenderBox extends RenderBox { } final double heightPercentage = pdfDocument!.pages[_textSelectionHelper.viewId!].size.height / - height; + height; if (gestureType == 'DragStart' && _textSelectionHelper.mouseSelectionEnabled) { _textSelectionHelper.endBubbleX = @@ -1402,21 +1443,31 @@ class CanvasRenderBox extends RenderBox { _textSelectionHelper.startBubbleY = (details.localPosition.dy as double) * heightPercentage; } - for (int textLineIndex = 0; - textLineIndex < _textSelectionHelper.textLines!.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < _textSelectionHelper.textLines!.length; + textLineIndex++ + ) { final TextLine textLine = _textSelectionHelper.textLines![textLineIndex]; - for (int wordIndex = 0; - wordIndex < - _textSelectionHelper - .textLines![textLineIndex].wordCollection.length; - wordIndex++) { - final TextWord textWord = _textSelectionHelper - .textLines![textLineIndex].wordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int wordIndex = 0; + wordIndex < + _textSelectionHelper + .textLines![textLineIndex] + .wordCollection + .length; + wordIndex++ + ) { + final TextWord textWord = + _textSelectionHelper + .textLines![textLineIndex] + .wordCollection[wordIndex]; + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph textGlyph = textWord.glyphs[glyphIndex]; if (gestureType == 'DragStart') { Rect glyphBounds = textGlyph.bounds; @@ -1579,10 +1630,12 @@ class CanvasRenderBox extends RenderBox { !_textSelectionHelper.isCursorExit) { double endBubbleValue; if (_rotatedAngle == PdfPageRotateAngle.rotateAngle180) { - endBubbleValue = -(_textSelectionHelper.finalScrollOffset - - _textSelectionHelper.initialScrollOffset); + endBubbleValue = + -(_textSelectionHelper.finalScrollOffset - + _textSelectionHelper.initialScrollOffset); } else { - endBubbleValue = _textSelectionHelper.finalScrollOffset - + endBubbleValue = + _textSelectionHelper.finalScrollOffset - _textSelectionHelper.initialScrollOffset; } final double heightPercentage = @@ -1634,7 +1687,8 @@ class CanvasRenderBox extends RenderBox { _textSelectionHelper.endBubbleY = _textSelectionHelper.endBubbleY! + endBubbleValue; } - final double position = pdfViewerController.scrollOffset.dy + + final double position = + pdfViewerController.scrollOffset.dy + (isReachedTop ? -_jumpOffset : _jumpOffset); if (isSelectionScroll) { @@ -1658,9 +1712,11 @@ class CanvasRenderBox extends RenderBox { /// Check the tap position same as the start bubble position. bool _checkStartBubblePosition(Offset details) { if (_textSelectionHelper.selectionEnabled) { - final double startBubbleX = _textSelectionHelper.startBubbleX! / + final double startBubbleX = + _textSelectionHelper.startBubbleX! / _textSelectionHelper.heightPercentage!; - final double startBubbleY = _textSelectionHelper.startBubbleY! / + final double startBubbleY = + _textSelectionHelper.startBubbleY! / _textSelectionHelper.heightPercentage!; if (details.dx >= startBubbleX - (_bubbleSize * _maximumZoomLevel) && details.dx <= startBubbleX && @@ -1675,9 +1731,11 @@ class CanvasRenderBox extends RenderBox { /// Check the tap position same as the end bubble position. bool _checkEndBubblePosition(Offset details) { if (_textSelectionHelper.selectionEnabled) { - final double endBubbleX = _textSelectionHelper.endBubbleX! / + final double endBubbleX = + _textSelectionHelper.endBubbleX! / _textSelectionHelper.heightPercentage!; - final double endBubbleY = _textSelectionHelper.endBubbleY! / + final double endBubbleY = + _textSelectionHelper.endBubbleY! / _textSelectionHelper.heightPercentage!; if (details.dx >= endBubbleX && details.dx <= endBubbleX + (_bubbleSize * _maximumZoomLevel) && @@ -1690,9 +1748,11 @@ class CanvasRenderBox extends RenderBox { } List _sortTextLines(List textLines) { - for (int textLineIndex = 0; - textLineIndex < textLines.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < textLines.length; + textLineIndex++ + ) { for (int index = textLineIndex + 1; index < textLines.length; index++) { if (textLines[textLineIndex].bounds.bottom > textLines[index].bounds.bottom) { @@ -1717,9 +1777,11 @@ class CanvasRenderBox extends RenderBox { ).extractTextLines(startPageIndex: pageIndex); textLines = _sortTextLines(textLines); TextLine? textLine; - for (int textLineIndex = 0; - textLineIndex < textLines.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < textLines.length; + textLineIndex++ + ) { if (textLines[textLineIndex].bounds.topLeft.dy >= offset.dy) { textLine = textLines[textLineIndex]; break; @@ -1862,11 +1924,13 @@ class CanvasRenderBox extends RenderBox { } final double heightPercentage = pdfDocument!.pages[_textSelectionHelper.cursorPageNumber!].size.height / - height; + height; if (_textSelectionHelper.cursorTextLines != null) { - for (int textLineIndex = 0; - textLineIndex < _textSelectionHelper.cursorTextLines!.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < _textSelectionHelper.cursorTextLines!.length; + textLineIndex++ + ) { if (_textSelectionHelper.cursorTextLines![textLineIndex].bounds .contains(details * heightPercentage)) { return _textSelectionHelper.cursorTextLines![textLineIndex]; @@ -1885,13 +1949,14 @@ class CanvasRenderBox extends RenderBox { pdfDocument!.pages[_textSelectionHelper.cursorPageNumber!]; final double heightPercentage = pdfDocument!.pages[_textSelectionHelper.cursorPageNumber!].size.height / - height; + height; final Offset hoverDetails = details * heightPercentage; for (int index = 0; index < page.annotations.count; index++) { final bool hasTOC = page.annotations[index] is PdfDocumentLinkAnnotation && - enableDocumentLinkNavigation; - final bool hasURI = (page.annotations[index] is PdfUriAnnotation || + enableDocumentLinkNavigation; + final bool hasURI = + (page.annotations[index] is PdfUriAnnotation || page.annotations[index] is PdfTextWebLink) && enableHyperlinkNavigation; if (hasTOC) { @@ -2064,9 +2129,10 @@ class CanvasRenderBox extends RenderBox { void _performHyperLinkNavigation(Canvas canvas, Offset offset) { if (pageIndex == _viewId) { if (_isHyperLinkTapped && enableHyperlinkNavigation) { - final Rect bounds = _pdfTextWebLink != null - ? _pdfTextWebLink!.bounds - : _pdfUriAnnotation!.bounds; + final Rect bounds = + _pdfTextWebLink != null + ? _pdfTextWebLink!.bounds + : _pdfUriAnnotation!.bounds; _drawHyperLinkTapColor(canvas, offset, bounds); _isHyperLinkTapped = false; Future.delayed(Duration.zero, () async { @@ -2080,8 +2146,8 @@ class CanvasRenderBox extends RenderBox { void _drawHyperLinkTapColor(Canvas canvas, Offset offset, Rect bounds) { final double heightPercentage = pdfDocument!.pages[_viewId!].size.height / height; - final Paint wordPaint = Paint() - ..color = const Color.fromRGBO(228, 238, 244, 0.75); + final Paint wordPaint = + Paint()..color = const Color.fromRGBO(228, 238, 244, 0.75); canvas.drawRect( offset.translate( bounds.left / heightPercentage, @@ -2101,8 +2167,8 @@ class CanvasRenderBox extends RenderBox { if (_isTOCTapped) { final double heightPercentage = pdfDocument!.pages[_viewId!].size.height / height; - final Paint wordPaint = Paint() - ..color = const Color.fromRGBO(228, 238, 244, 0.75); + final Paint wordPaint = + Paint()..color = const Color.fromRGBO(228, 238, 244, 0.75); canvas.drawRect( offset.translate( _documentLinkAnnotation!.bounds.left / heightPercentage, @@ -2123,13 +2189,14 @@ class CanvasRenderBox extends RenderBox { Offset(_totalPageOffset.dx, _totalPageOffset.dy), ); } else { - final double xOffSet = textDirection == TextDirection.rtl && - scrollDirection == PdfScrollDirection.horizontal && - !isSinglePageView - ? (pdfScrollableStateKey.currentWidget! as PdfScrollable) - .maxScrollExtent - - _totalPageOffset.dx - : _totalPageOffset.dx; + final double xOffSet = + textDirection == TextDirection.rtl && + scrollDirection == PdfScrollDirection.horizontal && + !isSinglePageView + ? (pdfScrollableStateKey.currentWidget! as PdfScrollable) + .maxScrollExtent - + _totalPageOffset.dx + : _totalPageOffset.dx; pdfViewerController.jumpTo( xOffset: xOffSet, yOffset: _totalPageOffset.dy, @@ -2144,10 +2211,10 @@ class CanvasRenderBox extends RenderBox { /// Perform text search. void _performTextSearch(Canvas canvas, Offset offset) { if (textCollection!.isNotEmpty) { - final Paint currentInstancePaint = Paint() - ..color = currentSearchTextHighlightColor; - final Paint otherInstancePaint = Paint() - ..color = otherSearchTextHighlightColor; + final Paint currentInstancePaint = + Paint()..color = currentSearchTextHighlightColor; + final Paint otherInstancePaint = + Paint()..color = otherSearchTextHighlightColor; for (int i = 0; i < textCollection!.length; i++) { final MatchedItem item = textCollection![i]; final double heightPercentage = @@ -2204,9 +2271,11 @@ class CanvasRenderBox extends RenderBox { startPoint: startGlyph.bounds, ); } - for (int textLineIndex = _textSelectionHelper.startIndex; - textLineIndex <= _textSelectionHelper.endIndex; - textLineIndex++) { + for ( + int textLineIndex = _textSelectionHelper.startIndex; + textLineIndex <= _textSelectionHelper.endIndex; + textLineIndex++ + ) { final TextLine line = _textSelectionHelper.textLines![textLineIndex]; final bool isRTLText = intl.Bidi.detectRtlDirectionality(line.text); Rect? startPoint; @@ -2227,13 +2296,17 @@ class CanvasRenderBox extends RenderBox { } } final List textWordCollection = line.wordCollection; - for (int wordIndex = 0; - wordIndex < textWordCollection.length; - wordIndex++) { + for ( + int wordIndex = 0; + wordIndex < textWordCollection.length; + wordIndex++ + ) { final TextWord textWord = textWordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph glyph = textWord.glyphs[glyphIndex]; final bool canSelectGlyph = checkGlyphInRegion( glyph, @@ -2252,7 +2325,8 @@ class CanvasRenderBox extends RenderBox { glyphIndex, ); _textSelectionHelper.copiedText = glyphText; - final Rect textRectOffset = offset.translate( + final Rect textRectOffset = + offset.translate( glyph.bounds.left / heightPercentage, glyph.bounds.top / heightPercentage, ) & @@ -2429,9 +2503,10 @@ class CanvasRenderBox extends RenderBox { final double nextGlyph = textWord.glyphs[glyphIndex + 1].bounds.left; glyphPosition = (currentGlyph - nextGlyph).abs(); } - glyphText = (glyphPosition > 1.0) - ? '$glyphText${glyph.text} ' - : glyphText + glyph.text; + glyphText = + (glyphPosition > 1.0) + ? '$glyphText${glyph.text} ' + : glyphText + glyph.text; } return glyphText; } @@ -2503,9 +2578,11 @@ class CanvasRenderBox extends RenderBox { Offset startPoint = Offset.zero, Rect endPoint = Rect.zero, }) { - for (int textLineIndex = 0; - textLineIndex < _textSelectionHelper.textLines!.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < _textSelectionHelper.textLines!.length; + textLineIndex++ + ) { final TextLine line = _textSelectionHelper.textLines![textLineIndex]; if (textLineIndex < _textSelectionHelper.startIndex || textLineIndex > _textSelectionHelper.endIndex) { @@ -2528,7 +2605,8 @@ class CanvasRenderBox extends RenderBox { top.floor() / heightPercentage >= startPoint.dy.floor() && right.floor() <= endPoint.right.floor() && bottom.floor() <= endPoint.bottom.floor())) { - final Rect lineRectOffset = offset.translate( + final Rect lineRectOffset = + offset.translate( left / heightPercentage, top / heightPercentage, ) & @@ -2556,7 +2634,8 @@ class CanvasRenderBox extends RenderBox { switch (theme.platform) { case TargetPlatform.iOS: case TargetPlatform.macOS: - _selectionColor ??= selectionTheme.selectionColor ?? + _selectionColor ??= + selectionTheme.selectionColor ?? cupertinoTheme.primaryColor.withValues(alpha: 0.40); _selectionHandleColor ??= selectionTheme.selectionHandleColor ?? cupertinoTheme.primaryColor; @@ -2565,7 +2644,8 @@ class CanvasRenderBox extends RenderBox { case TargetPlatform.fuchsia: case TargetPlatform.linux: case TargetPlatform.windows: - _selectionColor ??= selectionTheme.selectionColor ?? + _selectionColor ??= + selectionTheme.selectionColor ?? theme.colorScheme.primary.withValues(alpha: 0.40); _selectionHandleColor ??= selectionTheme.selectionHandleColor ?? theme.colorScheme.primary; @@ -2573,9 +2653,10 @@ class CanvasRenderBox extends RenderBox { } final Paint textPaint = Paint()..color = _selectionColor!; final Paint bubblePaint = Paint()..color = _selectionHandleColor!; - _zoomPercentage = pdfViewerController.zoomLevel > _maximumZoomLevel - ? _maximumZoomLevel - : pdfViewerController.zoomLevel; + _zoomPercentage = + pdfViewerController.zoomLevel > _maximumZoomLevel + ? _maximumZoomLevel + : pdfViewerController.zoomLevel; _performDocumentLinkNavigation(canvas, offset); _performHyperLinkNavigation(canvas, offset); @@ -2597,14 +2678,18 @@ class CanvasRenderBox extends RenderBox { _textSelectionHelper.textLines = PdfTextExtractor( pdfDocument!, ).extractTextLines(startPageIndex: _textSelectionHelper.viewId); - for (int textLineIndex = 0; - textLineIndex < _textSelectionHelper.textLines!.length; - textLineIndex++) { + for ( + int textLineIndex = 0; + textLineIndex < _textSelectionHelper.textLines!.length; + textLineIndex++ + ) { final TextLine line = _textSelectionHelper.textLines![textLineIndex]; final List textWordCollection = line.wordCollection; - for (int wordIndex = 0; - wordIndex < textWordCollection.length; - wordIndex++) { + for ( + int wordIndex = 0; + wordIndex < textWordCollection.length; + wordIndex++ + ) { final TextWord textWord = textWordCollection[wordIndex]; final Rect wordBounds = textWord.bounds; if (_tapDetails != null && @@ -2620,7 +2705,8 @@ class CanvasRenderBox extends RenderBox { _textSelectionHelper.endBubbleY = textWord.bounds.bottomRight.dy; _textSelectionHelper.startBubbleX = textWord.bounds.bottomLeft.dx; _textSelectionHelper.endBubbleX = textWord.bounds.bottomRight.dx; - final Rect textRectOffset = offset.translate( + final Rect textRectOffset = + offset.translate( textWord.bounds.left / heightPercentage, textWord.bounds.top / heightPercentage, ) & @@ -2683,9 +2769,11 @@ class CanvasRenderBox extends RenderBox { _findStartAndEndIndex(_dragDetails!, heightPercentage, false); } if (_isRTLText ? _endBubbleDragging : _startBubbleDragging) { - for (int textLineIndex = _textSelectionHelper.startIndex; - textLineIndex <= _textSelectionHelper.endIndex; - textLineIndex++) { + for ( + int textLineIndex = _textSelectionHelper.startIndex; + textLineIndex <= _textSelectionHelper.endIndex; + textLineIndex++ + ) { final TextLine line = _textSelectionHelper.textLines![textLineIndex]; if (!_isRTLText) { if (_dragDetails != null && @@ -2717,21 +2805,30 @@ class CanvasRenderBox extends RenderBox { _textSelectionHelper.endBubbleY = line.bounds.bottom; } } - for (int wordIndex = 0; - wordIndex < - (_isRTLText - ? _textSelectionHelper - .endBubbleLine!.wordCollection.length - : _textSelectionHelper - .startBubbleLine!.wordCollection.length); - wordIndex++) { - final TextWord textWord = _isRTLText - ? _textSelectionHelper.endBubbleLine!.wordCollection[wordIndex] - : _textSelectionHelper - .startBubbleLine!.wordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int wordIndex = 0; + wordIndex < + (_isRTLText + ? _textSelectionHelper.endBubbleLine!.wordCollection.length + : _textSelectionHelper + .startBubbleLine! + .wordCollection + .length); + wordIndex++ + ) { + final TextWord textWord = + _isRTLText + ? _textSelectionHelper + .endBubbleLine! + .wordCollection[wordIndex] + : _textSelectionHelper + .startBubbleLine! + .wordCollection[wordIndex]; + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph textGlyph = textWord.glyphs[glyphIndex]; if (_startBubbleTapX >= (textGlyph.bounds.bottomLeft.dx / heightPercentage) && @@ -2758,39 +2855,55 @@ class CanvasRenderBox extends RenderBox { heightPercentage)) { _textSelectionHelper.startBubbleX = _textSelectionHelper.startBubbleLine!.bounds.bottomLeft.dx; - _textSelectionHelper.firstSelectedGlyph = _textSelectionHelper - .startBubbleLine!.wordCollection.first.glyphs.first; + _textSelectionHelper.firstSelectedGlyph = + _textSelectionHelper + .startBubbleLine! + .wordCollection + .first + .glyphs + .first; } if (_startBubbleTapX >= (_textSelectionHelper.startBubbleLine!.bounds.bottomRight.dx / heightPercentage)) { - _textSelectionHelper.startBubbleX = _textSelectionHelper - .startBubbleLine! - .wordCollection - .last - .glyphs - .last - .bounds - .bottomLeft - .dx; - _textSelectionHelper.firstSelectedGlyph = _textSelectionHelper - .startBubbleLine!.wordCollection.last.glyphs.last; + _textSelectionHelper.startBubbleX = + _textSelectionHelper + .startBubbleLine! + .wordCollection + .last + .glyphs + .last + .bounds + .bottomLeft + .dx; + _textSelectionHelper.firstSelectedGlyph = + _textSelectionHelper + .startBubbleLine! + .wordCollection + .last + .glyphs + .last; } if (_textSelectionHelper.startBubbleLine!.bounds.bottom / heightPercentage == _textSelectionHelper.endBubbleLine!.bounds.bottom / heightPercentage && _startBubbleTapX >= _endBubbleTapX) { - for (int wordIndex = 0; - wordIndex < - _textSelectionHelper - .startBubbleLine!.wordCollection.length; - wordIndex++) { - final TextWord textWord = _textSelectionHelper - .startBubbleLine!.wordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int wordIndex = 0; + wordIndex < + _textSelectionHelper.startBubbleLine!.wordCollection.length; + wordIndex++ + ) { + final TextWord textWord = + _textSelectionHelper + .startBubbleLine! + .wordCollection[wordIndex]; + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph textGlyph = textWord.glyphs[glyphIndex]; if (textGlyph.bounds.bottomRight.dx / heightPercentage == _textSelectionHelper.endBubbleX! / heightPercentage) { @@ -2818,31 +2931,44 @@ class CanvasRenderBox extends RenderBox { heightPercentage)) { _textSelectionHelper.endBubbleX = _textSelectionHelper.endBubbleLine!.bounds.bottomLeft.dx; - _textSelectionHelper.firstSelectedGlyph = _textSelectionHelper - .endBubbleLine!.wordCollection.first.glyphs.first; + _textSelectionHelper.firstSelectedGlyph = + _textSelectionHelper + .endBubbleLine! + .wordCollection + .first + .glyphs + .first; } if (_endBubbleTapX >= (_textSelectionHelper.endBubbleLine!.bounds.bottomRight.dx / heightPercentage)) { - _textSelectionHelper.endBubbleX = _textSelectionHelper - .endBubbleLine! - .wordCollection - .last - .glyphs - .last - .bounds - .bottomLeft - .dx; - _textSelectionHelper.firstSelectedGlyph = _textSelectionHelper - .endBubbleLine!.wordCollection.last.glyphs.last; + _textSelectionHelper.endBubbleX = + _textSelectionHelper + .endBubbleLine! + .wordCollection + .last + .glyphs + .last + .bounds + .bottomLeft + .dx; + _textSelectionHelper.firstSelectedGlyph = + _textSelectionHelper + .endBubbleLine! + .wordCollection + .last + .glyphs + .last; } } } } } else if (_isRTLText ? _startBubbleDragging : _endBubbleDragging) { - for (int textLineIndex = _textSelectionHelper.startIndex; - textLineIndex <= _textSelectionHelper.endIndex; - textLineIndex++) { + for ( + int textLineIndex = _textSelectionHelper.startIndex; + textLineIndex <= _textSelectionHelper.endIndex; + textLineIndex++ + ) { final TextLine line = _textSelectionHelper.textLines![textLineIndex]; if (_dragDetails != null && !_isRTLText && @@ -2869,21 +2995,33 @@ class CanvasRenderBox extends RenderBox { _textSelectionHelper.startBubbleLine = line; _textSelectionHelper.startBubbleY = line.bounds.bottom; } - for (int wordIndex = 0; - wordIndex < - (_isRTLText - ? _textSelectionHelper - .startBubbleLine!.wordCollection.length - : _textSelectionHelper - .endBubbleLine!.wordCollection.length); - wordIndex++) { - final TextWord textWord = _isRTLText - ? _textSelectionHelper - .startBubbleLine!.wordCollection[wordIndex] - : _textSelectionHelper.endBubbleLine!.wordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int wordIndex = 0; + wordIndex < + (_isRTLText + ? _textSelectionHelper + .startBubbleLine! + .wordCollection + .length + : _textSelectionHelper + .endBubbleLine! + .wordCollection + .length); + wordIndex++ + ) { + final TextWord textWord = + _isRTLText + ? _textSelectionHelper + .startBubbleLine! + .wordCollection[wordIndex] + : _textSelectionHelper + .endBubbleLine! + .wordCollection[wordIndex]; + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph textGlyph = textWord.glyphs[glyphIndex]; if (!_isRTLText && _endBubbleTapX >= @@ -2914,30 +3052,37 @@ class CanvasRenderBox extends RenderBox { (_textSelectionHelper.endBubbleLine!.bounds.bottomLeft.dx / heightPercentage) .floor()) { - _textSelectionHelper.endBubbleX = _textSelectionHelper - .endBubbleLine! - .wordCollection - .first - .glyphs - .first - .bounds - .bottomRight - .dx; + _textSelectionHelper.endBubbleX = + _textSelectionHelper + .endBubbleLine! + .wordCollection + .first + .glyphs + .first + .bounds + .bottomRight + .dx; } if (_textSelectionHelper.endBubbleLine!.bounds.bottom / heightPercentage == _textSelectionHelper.startBubbleLine!.bounds.bottom / heightPercentage && _endBubbleTapX < _startBubbleTapX) { - for (int wordIndex = 0; - wordIndex < - _textSelectionHelper.endBubbleLine!.wordCollection.length; - wordIndex++) { - final TextWord textWord = _textSelectionHelper - .endBubbleLine!.wordCollection[wordIndex]; - for (int glyphIndex = 0; - glyphIndex < textWord.glyphs.length; - glyphIndex++) { + for ( + int wordIndex = 0; + wordIndex < + _textSelectionHelper.endBubbleLine!.wordCollection.length; + wordIndex++ + ) { + final TextWord textWord = + _textSelectionHelper + .endBubbleLine! + .wordCollection[wordIndex]; + for ( + int glyphIndex = 0; + glyphIndex < textWord.glyphs.length; + glyphIndex++ + ) { final TextGlyph textGlyph = textWord.glyphs[glyphIndex]; if (textGlyph.bounds.bottomLeft.dx / heightPercentage == _textSelectionHelper.startBubbleX! / heightPercentage) { @@ -2970,15 +3115,16 @@ class CanvasRenderBox extends RenderBox { (_textSelectionHelper.startBubbleLine!.bounds.bottomLeft.dx / heightPercentage) .floor()) { - _textSelectionHelper.startBubbleX = _textSelectionHelper - .startBubbleLine! - .wordCollection - .first - .glyphs - .first - .bounds - .bottomRight - .dx; + _textSelectionHelper.startBubbleX = + _textSelectionHelper + .startBubbleLine! + .wordCollection + .first + .glyphs + .first + .bounds + .bottomRight + .dx; } } } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head.dart index e0117d9fa..2c55bfc67 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head.dart @@ -66,9 +66,10 @@ class _ScrollHeadState extends State { void didChangeDependencies() { _isMaterial3 = Theme.of(context).useMaterial3; _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = _isMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + _isMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); super.didChangeDependencies(); } @@ -147,13 +148,13 @@ class _ScrollHeadState extends State { final BorderRadius borderRadius = widget.scrollDirection == PdfScrollDirection.horizontal ? const BorderRadius.only( - topRight: Radius.circular(kPdfScrollHeadSize), - topLeft: Radius.circular(kPdfScrollHeadSize), - ) + topRight: Radius.circular(kPdfScrollHeadSize), + topLeft: Radius.circular(kPdfScrollHeadSize), + ) : const BorderRadius.only( - topLeft: Radius.circular(kPdfScrollHeadSize), - bottomLeft: Radius.circular(kPdfScrollHeadSize), - ); + topLeft: Radius.circular(kPdfScrollHeadSize), + bottomLeft: Radius.circular(kPdfScrollHeadSize), + ); final Alignment alignment = widget.scrollDirection == PdfScrollDirection.horizontal ? Alignment.bottomLeft @@ -168,12 +169,14 @@ class _ScrollHeadState extends State { container: true, button: true, child: Align( - alignment: widget.scrollDirection == PdfScrollDirection.horizontal - ? Alignment.bottomCenter - : Alignment.centerRight, + alignment: + widget.scrollDirection == PdfScrollDirection.horizontal + ? Alignment.bottomCenter + : Alignment.centerRight, child: Container( decoration: BoxDecoration( - color: _pdfViewerThemeData!.scrollHeadStyle?.backgroundColor ?? + color: + _pdfViewerThemeData!.scrollHeadStyle?.backgroundColor ?? _effectiveThemeData!.scrollHeadStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light @@ -189,22 +192,23 @@ class _ScrollHeadState extends State { child: Align( child: Text( '${widget.pdfViewerController.pageNumber}', - style: Theme.of(context) - .textTheme - .bodySmall! + style: Theme.of(context).textTheme.bodySmall! .copyWith( fontSize: _isMaterial3 ? 14 : 12, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .scrollHeadStyle?.pageNumberTextStyle, + .scrollHeadStyle + ?.pageNumberTextStyle, ), - semanticsLabel: widget.isBookmarkViewOpen - ? '' - : widget.pdfViewerController.pageNumber.toString(), + semanticsLabel: + widget.isBookmarkViewOpen + ? '' + : widget.pdfViewerController.pageNumber.toString(), ), ), ), diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head_overlay.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head_overlay.dart index 9d261f221..6e49ca08e 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head_overlay.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_head_overlay.dart @@ -189,9 +189,10 @@ class ScrollHeadOverlayState extends State { @override void didChangeDependencies() { _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _themeData = Theme.of(context); _localizations = SfLocalizations.of(context); super.didChangeDependencies(); @@ -214,8 +215,8 @@ class ScrollHeadOverlayState extends State { widget.transformationController!.value.getMaxScaleOnAxis(); final double pdfPageHeight = widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.height; - final double totalPageOffset = widget - .pdfPages[widget.pdfViewerController.pageCount]!.pageOffset + + final double totalPageOffset = + widget.pdfPages[widget.pdfViewerController.pageCount]!.pageOffset + widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.width; if (widget.pdfViewerController.zoomLevel <= 1) { //check if the total page offset less than viewport width in horizontal scroll direction @@ -229,11 +230,12 @@ class ScrollHeadOverlayState extends State { if (kIsDesktop && !widget.isMobileWebView) { if (widget.viewportDimension.width < widget.maxPdfPageWidth * widget.pdfViewerController.zoomLevel) { - final double clampedX = tapPosition.dx > widget.maxPdfPageWidth - ? ((widget.maxPdfPageWidth * 2) - - widget.viewportDimension.width) / - 2 - : 0; + final double clampedX = + tapPosition.dx > widget.maxPdfPageWidth + ? ((widget.maxPdfPageWidth * 2) - + widget.viewportDimension.width) / + 2 + : 0; offset = Offset( (widget.scrollDirection == PdfScrollDirection.vertical) ? clampedX @@ -243,7 +245,8 @@ class ScrollHeadOverlayState extends State { } } } - final double widthFactor = (widget.pdfDimension.width) - + final double widthFactor = + (widget.pdfDimension.width) - (widget.viewportDimension.width / widget.pdfViewerController.zoomLevel); if (widget.viewportDimension.height > pdfPageHeight && (widget.scrollDirection == PdfScrollDirection.horizontal || @@ -257,26 +260,30 @@ class ScrollHeadOverlayState extends State { ? offset.dy + (widget.viewportDimension.height - widget - .pdfPages[ - widget.pdfViewerController.pageNumber]! + .pdfPages[widget + .pdfViewerController + .pageNumber]! .pageSize .height) / 2 : offset.dy / 2) .clamp( - 0, - (((widget.viewportDimension.height - - widget - .pdfPages[ - widget.pdfViewerController.pageNumber]! - .pageSize - .height) / - 2 + - widget.pdfPages[widget.pdfViewerController.pageNumber]! - .pageSize.height) / - 2) - .abs(), - ), + 0, + (((widget.viewportDimension.height - + widget + .pdfPages[widget + .pdfViewerController + .pageNumber]! + .pageSize + .height) / + 2 + + widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize + .height) / + 2) + .abs(), + ), ); } else { if ((widget.viewportDimension.width > totalPageOffset) && @@ -284,10 +291,10 @@ class ScrollHeadOverlayState extends State { offset = Offset( (offset.dx - (widget.viewportDimension.width - totalPageOffset)) .clamp( - 0, - (offset.dx - (widget.viewportDimension.width - totalPageOffset)) - .abs(), - ), + 0, + (offset.dx - (widget.viewportDimension.width - totalPageOffset)) + .abs(), + ), offset.dy, ); } @@ -311,8 +318,8 @@ class ScrollHeadOverlayState extends State { WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) { _updateScrollHeadPosition(); }); - final bool enableDoubleTapZoom = (!kIsDesktop && - widget.enableDoubleTapZooming) || + final bool enableDoubleTapZoom = + (!kIsDesktop && widget.enableDoubleTapZooming) || (kIsDesktop && widget.interactionMode == PdfInteractionMode.pan) || (kIsDesktop && widget.isMobileWebView && widget.enableDoubleTapZooming); final Widget scrollable = Directionality( @@ -357,8 +364,13 @@ class ScrollHeadOverlayState extends State { if (kIsDesktop) _buildDesktopScrollbar(context) else - _buildScrollhead(context, canShowScrollHead, hasBiggerWidth, - hasBiggerHeight, scrollHeadOffset), + _buildScrollhead( + context, + canShowScrollHead, + hasBiggerWidth, + hasBiggerHeight, + scrollHeadOffset, + ), Visibility( visible: isScrollHeadDragged && widget.canShowScrollStatus, child: ScrollStatus(widget.pdfViewerController), @@ -368,8 +380,13 @@ class ScrollHeadOverlayState extends State { } /// Builds the scrollhead for mobile platforms. - Widget _buildScrollhead(BuildContext context, bool canShowScrollHead, - bool hasBiggerWidth, bool hasBiggerHeight, Offset scrollHeadOffset) { + Widget _buildScrollhead( + BuildContext context, + bool canShowScrollHead, + bool hasBiggerWidth, + bool hasBiggerHeight, + Offset scrollHeadOffset, + ) { return GestureDetector( onVerticalDragStart: (DragStartDetails details) { _handleScrollHeadDragStart(details, true); @@ -379,8 +396,8 @@ class ScrollHeadOverlayState extends State { onHorizontalDragStart: (widget.scrollDirection == PdfScrollDirection.horizontal) ? (DragStartDetails details) { - _handleScrollHeadDragStart(details, false); - } + _handleScrollHeadDragStart(details, false); + } : null, onHorizontalDragUpdate: (widget.scrollDirection == PdfScrollDirection.horizontal) @@ -446,8 +463,9 @@ class ScrollHeadOverlayState extends State { }, onVerticalDragEnd: _handleScrollHeadDragEnd, onVerticalDragUpdate: (_) { - final Offset currentOffset = - widget.transformationController!.toScene(Offset.zero); + final Offset currentOffset = widget.transformationController!.toScene( + Offset.zero, + ); widget.onPdfOffsetChanged!(currentOffset); }, onHorizontalDragStart: (DragStartDetails details) { @@ -455,8 +473,9 @@ class ScrollHeadOverlayState extends State { }, onHorizontalDragEnd: _handleScrollHeadDragEnd, onHorizontalDragUpdate: (_) { - final Offset currentOffset = - widget.transformationController!.toScene(Offset.zero); + final Offset currentOffset = widget.transformationController!.toScene( + Offset.zero, + ); widget.onPdfOffsetChanged!(currentOffset); }, ), @@ -480,48 +499,52 @@ class ScrollHeadOverlayState extends State { child: AlertDialog( scrollable: true, insetPadding: EdgeInsets.zero, - contentPadding: isMaterial3 - ? const EdgeInsets.only( - left: 24.0, - right: 24.0, - bottom: 24.0, - ) - : orientation == Orientation.portrait + contentPadding: + isMaterial3 + ? const EdgeInsets.only( + left: 24.0, + right: 24.0, + bottom: 24.0, + ) + : orientation == Orientation.portrait ? const EdgeInsets.all(24) : const EdgeInsets.only(right: 24, left: 24), - buttonPadding: orientation == Orientation.portrait - ? const EdgeInsets.all(8) - : const EdgeInsets.all(4), - backgroundColor: _pdfViewerThemeData! - .paginationDialogStyle?.backgroundColor ?? + buttonPadding: + orientation == Orientation.portrait + ? const EdgeInsets.all(8) + : const EdgeInsets.all(4), + backgroundColor: + _pdfViewerThemeData!.paginationDialogStyle?.backgroundColor ?? _effectiveThemeData!.paginationDialogStyle?.backgroundColor ?? (Theme.of(context).colorScheme.brightness == Brightness.light ? Colors.white : const Color(0xFF424242)), - shape: isMaterial3 - ? null - : const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), + shape: + isMaterial3 + ? null + : const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( _localizations!.pdfGoToPageLabel, - style: Theme.of(context) - .textTheme - .headlineMedium! + style: Theme.of(context).textTheme.headlineMedium! .copyWith( fontSize: isMaterial3 ? 24 : 20, - color: isMaterial3 - ? Theme.of(context).colorScheme.onSurface - : Theme.of(context).brightness == Brightness.light + color: + isMaterial3 + ? Theme.of(context).colorScheme.onSurface + : Theme.of(context).brightness == + Brightness.light ? Colors.black.withValues(alpha: 0.87) : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .paginationDialogStyle?.headerTextStyle, + .paginationDialogStyle + ?.headerTextStyle, ), ), if (isMaterial3) @@ -549,11 +572,10 @@ class ScrollHeadOverlayState extends State { style: Theme.of( context, ).textTheme.bodyLarge!.copyWith( - fontSize: 14, - fontWeight: - isMaterial3 ? FontWeight.w400 : null, - color: Theme.of(context).colorScheme.onSurface, - ), + fontSize: 14, + fontWeight: isMaterial3 ? FontWeight.w400 : null, + color: Theme.of(context).colorScheme.onSurface, + ), ), ), ), @@ -567,20 +589,19 @@ class ScrollHeadOverlayState extends State { _textFieldController.clear(); Navigator.of(context).pop(); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPaginationDialogCancelLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -588,7 +609,8 @@ class ScrollHeadOverlayState extends State { ) .merge( _pdfViewerThemeData! - .paginationDialogStyle?.cancelTextStyle, + .paginationDialogStyle + ?.cancelTextStyle, ), ), ), @@ -596,20 +618,19 @@ class ScrollHeadOverlayState extends State { onPressed: () { _handlePageNumberValidation(); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPaginationDialogOkLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -635,14 +656,13 @@ class ScrollHeadOverlayState extends State { child: SizedBox( width: isMaterial3 ? 312.0 : _kPdfPaginationTextFieldWidth, child: TextFormField( - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData!.paginationDialogStyle?.inputFieldTextStyle, @@ -650,79 +670,89 @@ class ScrollHeadOverlayState extends State { focusNode: _focusNode, decoration: InputDecoration( isDense: true, - border: isMaterial3 - ? OutlineInputBorder( - borderSide: BorderSide( - color: _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - _effectiveThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - _themeData.colorScheme.primary, - ), - ) - : null, - errorBorder: isMaterial3 - ? OutlineInputBorder( - borderRadius: BorderRadius.circular(3.5), - borderSide: BorderSide( - color: _pdfViewerThemeData! - .passwordDialogStyle?.errorBorderColor ?? - _effectiveThemeData! - .passwordDialogStyle?.errorBorderColor ?? - _themeData.colorScheme.error, - ), - ) - : null, - focusedBorder: isMaterial3 - ? OutlineInputBorder( - borderSide: BorderSide( - color: _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - _effectiveThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - _themeData.colorScheme.primary, - width: 2, - ), - ) - : UnderlineInputBorder( - borderSide: BorderSide( - color: _themeData.colorScheme.primary, + border: + isMaterial3 + ? OutlineInputBorder( + borderSide: BorderSide( + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + _themeData.colorScheme.primary, + ), + ) + : null, + errorBorder: + isMaterial3 + ? OutlineInputBorder( + borderRadius: BorderRadius.circular(3.5), + borderSide: BorderSide( + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.errorBorderColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.errorBorderColor ?? + _themeData.colorScheme.error, + ), + ) + : null, + focusedBorder: + isMaterial3 + ? OutlineInputBorder( + borderSide: BorderSide( + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + _themeData.colorScheme.primary, + width: 2, + ), + ) + : UnderlineInputBorder( + borderSide: BorderSide( + color: _themeData.colorScheme.primary, + ), ), - ), - contentPadding: isMaterial3 - ? const EdgeInsets.all(16) - : const EdgeInsets.symmetric(vertical: 6), + contentPadding: + isMaterial3 + ? const EdgeInsets.all(16) + : const EdgeInsets.symmetric(vertical: 6), hintText: _localizations!.pdfEnterPageNumberLabel, - hintStyle: Theme.of(context) - .textTheme - .titleMedium! + hintStyle: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData!.paginationDialogStyle?.hintTextStyle, ), - counterText: isMaterial3 - ? null - : '${widget.pdfViewerController.pageNumber}/${widget.pdfViewerController.pageCount}', - counterStyle: Theme.of(context) - .textTheme - .bodySmall! + counterText: + isMaterial3 + ? null + : '${widget.pdfViewerController.pageNumber}/${widget.pdfViewerController.pageCount}', + counterStyle: Theme.of(context).textTheme.bodySmall! .copyWith( fontSize: 12, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData!.paginationDialogStyle?.pageInfoTextStyle, ), - errorStyle: Theme.of(context) - .textTheme - .bodySmall! + errorStyle: Theme.of(context).textTheme.bodySmall! .copyWith( fontSize: 12, fontWeight: FontWeight.w400, @@ -730,7 +760,8 @@ class ScrollHeadOverlayState extends State { ) .merge( _pdfViewerThemeData! - .paginationDialogStyle?.validationTextStyle, + .paginationDialogStyle + ?.validationTextStyle, ), ), keyboardType: TextInputType.number, @@ -793,7 +824,8 @@ class ScrollHeadOverlayState extends State { _isInteractionEnded = false; if (!widget.viewportDimension.isEmpty) { final double dragOffset = details.delta.dx + _scrollHeadPositionX; - final double scrollHeadPosition = widget.viewportDimension.width - + final double scrollHeadPosition = + widget.viewportDimension.width - (kIsDesktop ? _kPdfScrollBarHeight : _kPdfScrollHeadHeight); if (dragOffset < scrollHeadPosition && dragOffset >= 0) { widget.onPdfOffsetChanged!( @@ -825,7 +857,8 @@ class ScrollHeadOverlayState extends State { void _handleVerticalScrollHeadDragUpdate(DragUpdateDetails details) { if (!widget.viewportDimension.isEmpty) { final double dragOffset = details.delta.dy + _scrollHeadPositionY; - final double scrollHeadPosition = widget.viewportDimension.height - + final double scrollHeadPosition = + widget.viewportDimension.height - (kIsDesktop ? _kPdfScrollBarHeight : _kPdfScrollHeadHeight); if (dragOffset < scrollHeadPosition && dragOffset >= 0) { widget.onPdfOffsetChanged!( @@ -872,14 +905,17 @@ class ScrollHeadOverlayState extends State { _isInteractionEnded = false; } if (details.scale < 1 && widget.pdfViewerController.zoomLevel > 1) { - final double verticalMargin = widget.totalImageSize.height < - widget.viewportDimension.height - ? (widget.viewportDimension.height - widget.totalImageSize.height) / 2 - : 0; - final double horizontalMargin = widget.totalImageSize.width < - widget.viewportDimension.width - ? (widget.viewportDimension.width - widget.totalImageSize.width) / 2 - : 0; + final double verticalMargin = + widget.totalImageSize.height < widget.viewportDimension.height + ? (widget.viewportDimension.height - + widget.totalImageSize.height) / + 2 + : 0; + final double horizontalMargin = + widget.totalImageSize.width < widget.viewportDimension.width + ? (widget.viewportDimension.width - widget.totalImageSize.width) / + 2 + : 0; _boundaryMargin = EdgeInsets.only( top: verticalMargin, bottom: verticalMargin, @@ -913,15 +949,19 @@ class ScrollHeadOverlayState extends State { widget.transformationController!.toScene(Offset.zero).dx; final double currentOffsetY = widget.transformationController!.toScene(Offset.zero).dy; - final double scrollPercentX = currentOffsetX.abs() / + final double scrollPercentX = + currentOffsetX.abs() / (widget.pdfDimension.width - (widget.viewportDimension.width / _scale)); - final double scrollPercentY = currentOffsetY.abs() / + final double scrollPercentY = + currentOffsetY.abs() / (widget.pdfDimension.height - (widget.viewportDimension.height / _scale)); - final double scrollHeadMaxExtentX = widget.viewportDimension.width - + final double scrollHeadMaxExtentX = + widget.viewportDimension.width - (kIsDesktop ? _kPdfScrollBarHeight : _kPdfScrollHeadHeight); - final double scrollHeadMaxExtentY = widget.viewportDimension.height - + final double scrollHeadMaxExtentY = + widget.viewportDimension.height - (kIsDesktop ? _kPdfScrollBarHeight : _kPdfScrollHeadHeight); final double newPositionX = (scrollPercentX * scrollHeadMaxExtentX).clamp( 1, diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_status.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_status.dart index 1e7a44276..08b3db775 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_status.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/scroll_status.dart @@ -36,9 +36,10 @@ class _ScrollStatusState extends State { @override void didChangeDependencies() { _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _localizations = SfLocalizations.of(context); super.didChangeDependencies(); } @@ -72,30 +73,31 @@ class _ScrollStatusState extends State { maxWidth: MediaQuery.of(context).size.width * 0.7, ), decoration: BoxDecoration( - color: _pdfViewerThemeData! - .scrollStatusStyle?.backgroundColor ?? + color: + _pdfViewerThemeData!.scrollStatusStyle?.backgroundColor ?? _effectiveThemeData!.scrollStatusStyle?.backgroundColor ?? const Color(0xFF757575), - borderRadius: Theme.of(context).useMaterial3 - ? const BorderRadius.all(Radius.circular(4.0)) - : const BorderRadius.all(Radius.circular(16.0)), + borderRadius: + Theme.of(context).useMaterial3 + ? const BorderRadius.all(Radius.circular(4.0)) + : const BorderRadius.all(Radius.circular(16.0)), ), child: Text( '${widget.pdfViewerController.pageNumber} ${_localizations!.pdfScrollStatusOfLabel} ${widget.pdfViewerController.pageCount}', textAlign: TextAlign.center, textDirection: TextDirection.ltr, - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: Theme.of(context).useMaterial3 ? 14 : 16, color: Colors.white, ) .merge( _pdfViewerThemeData! - .scrollStatusStyle?.pageInfoTextStyle ?? + .scrollStatusStyle + ?.pageInfoTextStyle ?? _effectiveThemeData! - .scrollStatusStyle?.pageInfoTextStyle, + .scrollStatusStyle + ?.pageInfoTextStyle, ), ), ), diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/single_page_view.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/single_page_view.dart index c64547517..3c42ec67a 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/single_page_view.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/single_page_view.dart @@ -23,12 +23,12 @@ typedef PageChangedCallback = void Function(int newPage); /// Size of the scroll head. const double _kPdfScrollHeadSize = 48.0; -/// The minimum distance to scroll to trigger a page change. -const double _kPaginationSlop = 15; - /// Height of the pagination text field. const double _kPdfPaginationTextFieldWidth = 328.0; +/// A constant threshold value that determines how fast a swipe should be trigger a page change +const double _kSwipeThreshold = 700; + const double _scrollbarPadding = 0.5; const double _defaultDesktopScrollbarWidth = 10; @@ -152,12 +152,10 @@ class SinglePageViewState extends State { SfLocalizations? _localizations; double _scrollHeadPosition = 0; bool _setZoomLevel = false; - late TransformationControllerExt _transformationController; final TextEditingController _textFieldController = TextEditingController(); final GlobalKey _formKey = GlobalKey(); final FocusNode _focusNode = FocusNode(); Size _oldLayoutSize = Size.zero; - double _topMargin = 0; double _panStartOffset = 0.0; double _panUpdateOffset = 0.0; bool _canJumpPrevious = false; @@ -195,25 +193,41 @@ class SinglePageViewState extends State { /// Current offset of single page view Offset currentOffset = Offset.zero; + /// Offset value at the start of the interaction + Offset _offsetWhenInteractionStarts = Offset.zero; + + /// The current page number + int _currentPageNumber = 1; + + /// Transformation controller for the previous page (the page immediately before the current page in view) + TransformationControllerExt _previousPageTransformationController = + TransformationControllerExt(); + + /// Transformation controller for the current page (the page currently in view) + TransformationControllerExt _currentPageTransformationController = + TransformationControllerExt(); + + /// Transformation controller for the next page (the page immediately following the current page) + TransformationControllerExt _nextPageTransformationController = + TransformationControllerExt(); + @override void initState() { - _transformationController = widget.transformationController; super.initState(); + _currentPageTransformationController.addListener(_onTransformationChanged); } @override void didUpdateWidget(covariant SinglePageView oldWidget) { if (oldWidget.viewportDimension != widget.viewportDimension) { - _transformationController.viewSize = widget.viewportDimension; - if (widget.pdfPages[widget.pdfViewerController.pageNumber] != null) { - _transformationController.contentSize = - widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; - } - // Update the transformation controller's value to restirct the page in the ceenter of the viewport. - WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) { - _transformationController.value = - _transformationController.value.clone(); - }); + _previousPageTransformationController.viewSize = + _currentPageTransformationController.viewSize = + _nextPageTransformationController.viewSize = + widget.viewportDimension; + } + if (widget.pdfPages[widget.pdfViewerController.pageNumber] != null) { + _currentPageTransformationController.contentSize = + widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; } super.didUpdateWidget(oldWidget); } @@ -221,20 +235,19 @@ class SinglePageViewState extends State { @override void didChangeDependencies() { _pdfViewerThemeData = SfPdfViewerTheme.of(context); - _effectiveThemeData = Theme.of(context).useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + Theme.of(context).useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _localizations = SfLocalizations.of(context); - _transformationController.viewSize = widget.viewportDimension; + _previousPageTransformationController.viewSize = + _currentPageTransformationController.viewSize = + _nextPageTransformationController.viewSize = + widget.viewportDimension; if (widget.pdfPages[widget.pdfViewerController.pageNumber] != null) { - _transformationController.contentSize = + _currentPageTransformationController.contentSize = widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; } - // Update the transformation controller's value to restirct the page in the ceenter of the viewport. - WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) { - _transformationController.value = _transformationController.value.clone(); - }); - super.didChangeDependencies(); } @@ -244,9 +257,18 @@ class SinglePageViewState extends State { _effectiveThemeData = null; _localizations = null; _focusNode.dispose(); + _currentPageTransformationController.removeListener( + _onTransformationChanged, + ); super.dispose(); } + /// Callback to assign the value to the transformation controller + void _onTransformationChanged() { + widget.transformationController.value = + _currentPageTransformationController.value.clone(); + } + ///Jump to the desired offset. void jumpTo({double? xOffset, double? yOffset}) { xOffset ??= 0.0; @@ -258,7 +280,9 @@ class SinglePageViewState extends State { /// Handles PDF offset changed and updates the matrix translation based on it. void _handlePdfOffsetChanged(Offset offset) { - final Offset currentOffset = _transformationController.toScene(Offset.zero); + final Offset currentOffset = _currentPageTransformationController.toScene( + Offset.zero, + ); final Size pdfDimension = widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; if (pdfDimension.height != 0) { @@ -271,14 +295,18 @@ class SinglePageViewState extends State { pdfDimension.height * widget.pdfViewerController.zoomLevel) { offset = Offset(offset.dx, 0); } - final double widthFactor = pdfDimension.width - + final double widthFactor = + pdfDimension.width - (widget.viewportDimension.width / widget.pdfViewerController.zoomLevel); if (isJumpOnZoomedDocument) { final double actualMargin = greyAreaSize / 2; bool skipY = false; - final double pageHeight = widget - .pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.height; + final double pageHeight = + widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize + .height; if (widget.pdfViewerController.zoomLevel > 1 && pageHeight * widget.pdfViewerController.zoomLevel < widget.viewportDimension.height) { @@ -292,13 +320,13 @@ class SinglePageViewState extends State { skipY ? 0 : offset.dy.clamp( - actualMargin, - ((pdfDimension.height - - (widget.viewportDimension.height / - widget.pdfViewerController.zoomLevel)) + - actualMargin) - .abs(), - ), + actualMargin, + ((pdfDimension.height - + (widget.viewportDimension.height / + widget.pdfViewerController.zoomLevel)) + + actualMargin) + .abs(), + ), ); } else { offset = Offset( @@ -334,44 +362,107 @@ class SinglePageViewState extends State { offset = Offset(0, offset.dy); } } else { - final double greyAreaWidthSize = widget.viewportDimension.width - - (widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize + final double greyAreaWidthSize = + widget.viewportDimension.width - + (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize .width); offset = Offset(greyAreaWidthSize / 2 + offset.dx, offset.dy); } } - final Offset previousOffset = _transformationController.toScene( - Offset.zero, - ); - setState(() { - _transformationController.value = - _transformationController.value.clone() - ..translate( - previousOffset.dx - offset.dx, - previousOffset.dy - offset.dy, - ); - }); + final Offset previousOffset = _currentPageTransformationController + .toScene(Offset.zero); + _currentPageTransformationController.value = + _currentPageTransformationController.value.clone()..translate( + previousOffset.dx - offset.dx, + previousOffset.dy - offset.dy, + ); } widget.onPdfOffsetChanged!.call( - _transformationController.toScene(Offset.zero), + _currentPageTransformationController.toScene(Offset.zero), ); } + /// Get the current state of the transformation controller based on the specified page number. + TransformationControllerExt? _getController(int pageNumber) { + final int currentPageNumber = widget.pdfViewerController.pageNumber; + if (pageNumber == currentPageNumber) { + return _currentPageTransformationController; // Current page's transformation controller + } else if (pageNumber == currentPageNumber + 1) { + return _nextPageTransformationController; // Next page's transformation controller + } else if (pageNumber == currentPageNumber - 1) { + return _previousPageTransformationController; // Previous page's transformation controller + } else { + return null; // The requested page is not currently cached for viewing + } + } + + /// Rotate and assign the transformation controllers to the InteractiveViewer when navigating between pages. + /// The function reorganizes the transformation controllers depending on whether the page navigation is forward or backward. + void _rotateAndAssignControllers(int newPageNumber) { + if (newPageNumber > _currentPageNumber) { + // User navigated to the next page + _currentPageTransformationController.removeListener( + _onTransformationChanged, + ); + + // Shift the controllers forward: current becomes previous, next becomes current + _previousPageTransformationController = + _currentPageTransformationController; + _currentPageTransformationController = _nextPageTransformationController; + _currentPageTransformationController.addListener( + _onTransformationChanged, + ); + + // Prepare the transformation controller for the new next page + if (widget.pdfPages[newPageNumber + 1] != null) { + _nextPageTransformationController = + TransformationControllerExt() + ..viewSize = _oldLayoutSize + ..contentSize = widget.pdfPages[newPageNumber + 1]!.pageSize; + } + } else if (newPageNumber < _currentPageNumber) { + // User navigated to the previous page + _currentPageTransformationController.removeListener( + _onTransformationChanged, + ); + + // Shift the controllers backward: current becomes next, previous becomes current + _nextPageTransformationController = _currentPageTransformationController; + _currentPageTransformationController = + _previousPageTransformationController; + _currentPageTransformationController.addListener( + _onTransformationChanged, + ); + + // Prepare the transformation controller for the new previous page + if (widget.pdfPages[newPageNumber - 1] != null) { + _previousPageTransformationController = + TransformationControllerExt() + ..viewSize = _oldLayoutSize + ..contentSize = widget.pdfPages[newPageNumber - 1]!.pageSize; + } + } + + // Reset transformation states for the next and previous controllers to default + _nextPageTransformationController.value = Matrix4.identity(); + _previousPageTransformationController.value = Matrix4.identity(); + } + @override Widget build(BuildContext context) { - currentOffset = _transformationController.toScene(Offset.zero); - final bool enableDoubleTapZoom = (!kIsDesktop && - widget.enableDoubleTapZooming) || + currentOffset = _currentPageTransformationController.toScene(Offset.zero); + final bool enableDoubleTapZoom = + (!kIsDesktop && widget.enableDoubleTapZooming) || (kIsDesktop && widget.interactionMode == PdfInteractionMode.pan) || (kIsDesktop && widget.isMobileWebView && widget.enableDoubleTapZooming); final List pages = []; if (widget.pdfPages.isNotEmpty) { for (int pageIndex = 0; pageIndex < widget.children.length; pageIndex++) { final Widget page = widget.children[pageIndex]; - _topMargin = (widget.pdfPages[pageIndex + 1]!.pageSize.height - - widget.viewportDimension.height) / - 2; - greyAreaSize = widget.viewportDimension.height - + greyAreaSize = + widget.viewportDimension.height - (widget.pdfPages[pageIndex + 1]!.pageSize.height); pages.add( InteractiveScrollViewer( @@ -385,7 +476,7 @@ class SinglePageViewState extends State { onDoubleTapZoomInvoked: _onDoubleTapZoomInvoked, scaleEnabled: !kIsDesktop || (kIsDesktop && widget.scaleEnabled), enableDoubleTapZooming: enableDoubleTapZoom, - transformationController: _transformationController, + transformationController: _getController(pageIndex + 1), onInteractionStart: (ScaleStartDetails details) { _panStartOffset = widget.scrollDirection == PdfScrollDirection.horizontal @@ -399,6 +490,8 @@ class SinglePageViewState extends State { } previousZoomLevel = widget.pdfViewerController.zoomLevel; } + _offsetWhenInteractionStarts = + _currentPageTransformationController.toScene(Offset.zero); }, onInteractionUpdate: (ScaleUpdateDetails details) { _panUpdateOffset = @@ -416,14 +509,15 @@ class SinglePageViewState extends State { (kIsDesktop && widget.isMobileWebView) || (kIsDesktop && widget.scaleEnabled)) { widget.interactionUpdate( - _transformationController.value.getMaxScaleOnAxis(), + _currentPageTransformationController.value + .getMaxScaleOnAxis(), ); } _isZoomChanged = details.scale != 1; widget.onPdfOffsetChanged!.call( - _transformationController.toScene(Offset.zero), + _currentPageTransformationController.toScene(Offset.zero), ); }, onInteractionEnd: (ScaleEndDetails details) { @@ -434,16 +528,14 @@ class SinglePageViewState extends State { 300 * widget.pdfViewerController.zoomLevel) { if (_canJumpPrevious && widget.pdfViewerController.pageNumber != 1) { - widget.pageController.animateToPage( - widget.pdfViewerController.pageNumber - 2, + widget.pageController.previousPage( duration: const Duration(milliseconds: 500), curve: Curves.ease, ); } else if (_canJumpNext && widget.pdfViewerController.pageNumber != widget.pdfViewerController.pageCount) { - widget.pageController.animateToPage( - widget.pdfViewerController.pageNumber, + widget.pageController.nextPage( duration: const Duration(milliseconds: 500), curve: Curves.ease, ); @@ -456,25 +548,28 @@ class SinglePageViewState extends State { (kIsDesktop && widget.isMobileWebView) || (kIsDesktop && widget.scaleEnabled)) { widget.onZoomLevelChanged( - _transformationController.value.getMaxScaleOnAxis(), + _currentPageTransformationController.value + .getMaxScaleOnAxis(), ); } - currentOffset = _transformationController.toScene(Offset.zero); - _changePage(isMouseWheel: false); + currentOffset = _currentPageTransformationController.toScene( + Offset.zero, + ); + _changePage(isMouseWheel: false, velocity: details.velocity); _canJumpPrevious = false; _canJumpNext = false; _isZoomChanged = false; widget.onInteractionEnd?.call(); - setState(() {}); }, ), ); } } - _scrollHeadPosition = widget.pdfViewerController.pageNumber == 1 - ? 0 - : widget.scrollDirection == PdfScrollDirection.horizontal + _scrollHeadPosition = + widget.pdfViewerController.pageNumber == 1 + ? 0 + : widget.scrollDirection == PdfScrollDirection.horizontal ? (widget.pdfViewerController.pageNumber / widget.pdfViewerController.pageCount) * (widget.viewportDimension.width - _kPdfScrollHeadSize) @@ -500,7 +595,9 @@ class SinglePageViewState extends State { if (widget.visibleViewportDimension == null && _previousVisibleViewportDimension != null && currentOffset.dy.round() > - (widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize + (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize .height - widget.viewportDimension.height / widget.pdfViewerController.zoomLevel) @@ -517,13 +614,14 @@ class SinglePageViewState extends State { builder: (BuildContext context, BoxConstraints constraints) { if (_oldLayoutSize != constraints.biggest && widget.pdfPages.isNotEmpty) { - final Offset previousOffset = _transformationController.toScene( - Offset.zero, - ); - double yPosition = !_oldLayoutSize.isEmpty - ? previousOffset.dy / _oldLayoutSize.height - : 0; - final double greyArea = widget + final Offset previousOffset = _currentPageTransformationController + .toScene(Offset.zero); + double yPosition = + !_oldLayoutSize.isEmpty + ? previousOffset.dy / _oldLayoutSize.height + : 0; + final double greyArea = + widget .pdfPages[widget.pdfViewerController.pageNumber]! .pageSize .height - @@ -538,17 +636,18 @@ class SinglePageViewState extends State { (constraints.biggest.height) - greyArea, ); } - double xPosition = !_oldLayoutSize.isEmpty - ? previousOffset.dx / _oldLayoutSize.width - : 0; + double xPosition = + !_oldLayoutSize.isEmpty + ? previousOffset.dx / _oldLayoutSize.width + : 0; xPosition = MediaQuery.of(context).orientation == Orientation.landscape ? 0 : xPosition * constraints.biggest.width; if (kIsDesktop && !widget.isMobileWebView) { WidgetsBinding.instance.addPostFrameCallback((_) { - _transformationController.value = - _transformationController.value.clone() + _currentPageTransformationController.value = + _currentPageTransformationController.value.clone() ..translate( previousOffset.dx - xPosition, previousOffset.dy - yPosition, @@ -599,18 +698,24 @@ class SinglePageViewState extends State { ? Axis.horizontal : Axis.vertical, reverse: widget.textDirection != TextDirection.ltr, - onPageChanged: (int value) { - widget.onPageChanged(value); - if (widget.pdfPages[widget.pdfViewerController.pageNumber] != - null) { - _transformationController._contentSize = widget - .pdfPages[widget.pdfViewerController.pageNumber]! - .pageSize; + onPageChanged: (int newPageIndex) { + // Reset the zoom level on page change + _currentPageTransformationController.value = + Matrix4.identity(); + final int newPageNumber = newPageIndex + 1; + if (widget.pdfPages[newPageNumber] != null) { + // Reset the content size of the TransformationController with the new page size + _currentPageTransformationController.contentSize = + widget.pdfPages[newPageNumber]!.pageSize; } - _transformationController.value = Matrix4.identity(); + _rotateAndAssignControllers(newPageNumber); + _currentPageNumber = newPageNumber; + widget.onPageChanged(newPageIndex); }, physics: - _transformationController.value.getMaxScaleOnAxis() == 1 && + _currentPageTransformationController.value + .getMaxScaleOnAxis() == + 1 && _fingersInteracting <= 1 ? const BouncingScrollPhysics() : const NeverScrollableScrollPhysics(), @@ -636,7 +741,8 @@ class SinglePageViewState extends State { } }, child: Visibility( - visible: widget.pdfViewerController.pageCount > 1 && + visible: + widget.pdfViewerController.pageCount > 1 && ((widget.canShowScrollHead && !kIsDesktop) || kIsDesktop), child: ScrollHead( _canShowHorizontalScrollBar, @@ -652,31 +758,33 @@ class SinglePageViewState extends State { ), if (kIsDesktop && !widget.isMobileWebView) DesktopScrollbar( - contentSize: widget.pdfPages[widget.pdfViewerController.pageNumber] + contentSize: + widget + .pdfPages[widget.pdfViewerController.pageNumber] ?.pageSize ?? Size.zero, viewportSize: widget.viewportDimension, - controller: _transformationController, + controller: _currentPageTransformationController, onHorizontalDragEnd: (_) { widget.onInteractionEnd?.call(); }, onVerticalDragEnd: (_) { widget.onInteractionEnd?.call(); }, - verticalScrollbarPadding: widget.scrollDirection == - PdfScrollDirection.vertical && - widget.pdfViewerController.pageCount > 1 - ? const EdgeInsets.only( - right: _defaultDesktopScrollbarWidth + _scrollbarPadding, - ) - : const EdgeInsets.only(right: _scrollbarPadding), - horizontalScrollbarPadding: widget.scrollDirection == - PdfScrollDirection.horizontal && - widget.pdfViewerController.pageCount > 1 - ? const EdgeInsets.only( - bottom: _defaultDesktopScrollbarWidth + _scrollbarPadding, - ) - : const EdgeInsets.only(bottom: _scrollbarPadding), + verticalScrollbarPadding: + widget.scrollDirection == PdfScrollDirection.vertical && + widget.pdfViewerController.pageCount > 1 + ? const EdgeInsets.only( + right: _defaultDesktopScrollbarWidth + _scrollbarPadding, + ) + : const EdgeInsets.only(right: _scrollbarPadding), + horizontalScrollbarPadding: + widget.scrollDirection == PdfScrollDirection.horizontal && + widget.pdfViewerController.pageCount > 1 + ? const EdgeInsets.only( + bottom: _defaultDesktopScrollbarWidth + _scrollbarPadding, + ) + : const EdgeInsets.only(bottom: _scrollbarPadding), ), Visibility( visible: isScrollHeadDragged && widget.canShowScrollStatus, @@ -686,129 +794,88 @@ class SinglePageViewState extends State { ); } - void _changePage({required bool isMouseWheel}) { + void _changePage({ + required bool isMouseWheel, + Velocity velocity = Velocity.zero, + }) { final double currentScale = - _transformationController.value.getMaxScaleOnAxis(); - if (currentScale > 1) { - final bool isLandscape = - MediaQuery.of(context).orientation == Orientation.landscape; - - final bool isHeightFitted = _topMargin == 0; - final Size childSize = - widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; - - final double imageHeight = childSize.height * currentScale; - - final double imageWidth = widget - .pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.width * - currentScale; - - final double pannedDistance = (_panStartOffset - _panUpdateOffset).abs(); - - final Offset currentOffset = _transformationController.toScene( - Offset.zero, - ); - - if (widget.scrollDirection == PdfScrollDirection.vertical) { - final double topMargin = (isHeightFitted || isLandscape - ? 0 - : (imageHeight.round() <= - widget.viewportDimension.height.round() - ? (childSize.height - widget.viewportDimension.height) / - 2 - : _topMargin) - .abs()) - .roundToDouble(); - final double pageBottom = (widget - .pdfPages[widget.pdfViewerController.pageNumber]! - .pageSize - .height + - greyAreaSize / 2) - .roundToDouble(); - final double currentBottomOffset = - imageHeight < widget.viewportDimension.height - ? (currentOffset.dy + childSize.height).roundToDouble() - : (currentOffset.dy + - widget.viewportDimension.height / currentScale) - .roundToDouble(); - - if (currentBottomOffset >= pageBottom) { - _goToNextPage = true; - } else if (currentOffset.dy.roundToDouble() <= topMargin) { - _goToPreviousPage = true; - } else { - _goToNextPage = false; - _goToPreviousPage = false; - } - - if (!isMouseWheel && - pannedDistance > kPagingTouchSlop && - (currentBottomOffset == pageBottom || - currentOffset.dy.roundToDouble() == topMargin)) { - _goToNextPage = _canJumpNext; - _goToPreviousPage = _canJumpPrevious; - } - } - - if (widget.scrollDirection == PdfScrollDirection.horizontal) { - final double currentRightOffset = - (imageWidth < widget.viewportDimension.width - ? currentOffset.dx + - childSize.width / (isHeightFitted ? 1 : currentScale) - : currentOffset.dx + - widget.viewportDimension.width / currentScale) - .roundToDouble(); - - if (currentRightOffset > childSize.width.round()) { - _goToNextPage = true; - } else if (currentOffset.dx < 0) { - _goToPreviousPage = true; - } else { - _goToNextPage = false; - _goToPreviousPage = false; - } - if (currentRightOffset == childSize.width.round() || - currentOffset.dx == 0) { - _goToNextPage = _canJumpNext; - _goToPreviousPage = _canJumpPrevious; - } - } + _currentPageTransformationController.value.getMaxScaleOnAxis(); + if (currentScale <= 1) { + return; + } + final Size pageSize = + widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; + final Size imageSize = pageSize * currentScale; + + if (widget.scrollDirection == PdfScrollDirection.vertical) { + final double topMargin = + ((widget.viewportDimension.height - imageSize.height) / 2) + .clamp(0, double.infinity) + .roundToDouble(); + final double pageBottom = pageSize.height.roundToDouble(); + final double currentBottomOffset = + _offsetWhenInteractionStarts.dy + + (widget.viewportDimension.height / currentScale); + + _goToNextPage = + -velocity.pixelsPerSecond.dy >= _kSwipeThreshold && + velocity.pixelsPerSecond.dx.abs() < _kSwipeThreshold && + (currentBottomOffset.roundToDouble() >= pageBottom) && + !isMouseWheel; + _goToPreviousPage = + velocity.pixelsPerSecond.dy >= _kSwipeThreshold && + velocity.pixelsPerSecond.dx.abs() < _kSwipeThreshold && + (_offsetWhenInteractionStarts.dy.roundToDouble() <= topMargin) && + !isMouseWheel; + } else if (widget.scrollDirection == PdfScrollDirection.horizontal) { + final double leftMargin = + ((widget.viewportDimension.width - imageSize.width) / 2) + .clamp(0, double.infinity) + .roundToDouble(); + final double pageRight = pageSize.width.roundToDouble(); + final double currentRightOffset = + _offsetWhenInteractionStarts.dx + + (widget.viewportDimension.width / currentScale); + + _goToNextPage = + -velocity.pixelsPerSecond.dx >= _kSwipeThreshold && + velocity.pixelsPerSecond.dy.abs() < _kSwipeThreshold && + (currentRightOffset.roundToDouble() >= pageRight) && + !isMouseWheel; + _goToPreviousPage = + velocity.pixelsPerSecond.dx >= _kSwipeThreshold && + velocity.pixelsPerSecond.dy.abs() < _kSwipeThreshold && + (_offsetWhenInteractionStarts.dx.roundToDouble() <= leftMargin) && + !isMouseWheel; + } - if (_goToNextPage && - ((_canJumpNext && - !_isZoomChanged && - pannedDistance > _kPaginationSlop) || - (isMouseWheel && - widget.scrollDirection == PdfScrollDirection.vertical))) { - if (widget.pdfViewerController.pageNumber != - widget.pdfViewerController.pageCount) { - widget.pageController.animateToPage( - widget.pdfViewerController.pageNumber, - duration: const Duration(milliseconds: 500), - curve: Curves.ease, - ); - } + if (_goToNextPage && + (!_isZoomChanged || + (isMouseWheel && + widget.scrollDirection == PdfScrollDirection.vertical))) { + if (widget.pdfViewerController.pageNumber != + widget.pdfViewerController.pageCount) { + widget.pageController.nextPage( + duration: const Duration(milliseconds: 500), + curve: Curves.ease, + ); _isPageChangedOnScroll = true; } - - if (_goToPreviousPage && - ((_canJumpPrevious && - !_isZoomChanged && - pannedDistance > _kPaginationSlop) || - (isMouseWheel && - widget.scrollDirection == PdfScrollDirection.vertical))) { - if (widget.pdfViewerController.pageNumber != 1) { - widget.pageController.animateToPage( - widget.pdfViewerController.pageNumber - 2, - duration: const Duration(milliseconds: 500), - curve: Curves.ease, - ); - } + } else if (_goToPreviousPage && + (!_isZoomChanged || + (isMouseWheel && + widget.scrollDirection == PdfScrollDirection.vertical))) { + if (widget.pdfViewerController.pageNumber != 1) { + widget.pageController.previousPage( + duration: const Duration(milliseconds: 500), + curve: Curves.ease, + ); _isPageChangedOnScroll = true; } - _goToNextPage = false; - _goToPreviousPage = false; } + + _goToNextPage = false; + _goToPreviousPage = false; } Offset _onDoubleTapZoomInvoked(Offset offset, Offset tapPosition) { @@ -816,7 +883,7 @@ class SinglePageViewState extends State { previousZoomLevel = widget.pdfViewerController.zoomLevel; _oldPreviousZoomLevel = previousZoomLevel; widget.pdfViewerController.zoomLevel = - _transformationController.value.getMaxScaleOnAxis(); + _currentPageTransformationController.value.getMaxScaleOnAxis(); final double pdfPageWidth = widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.width; @@ -843,7 +910,7 @@ class SinglePageViewState extends State { /// Update the offset after zooming void updateOffset() { widget.onPdfOffsetChanged!.call( - _transformationController.toScene(Offset.zero), + _currentPageTransformationController.toScene(Offset.zero), ); } @@ -855,16 +922,18 @@ class SinglePageViewState extends State { int pageNumber = 0; if (widget.scrollDirection == PdfScrollDirection.horizontal) { _scrollHeadPosition = details.localPosition.dx; - pageNumber = (_scrollHeadPosition / - (widget.viewportDimension.width - _kPdfScrollHeadSize) * - widget.pdfViewerController.pageCount) - .round(); + pageNumber = + (_scrollHeadPosition / + (widget.viewportDimension.width - _kPdfScrollHeadSize) * + widget.pdfViewerController.pageCount) + .round(); } else { _scrollHeadPosition = details.localPosition.dy; - pageNumber = (_scrollHeadPosition / - (widget.viewportDimension.height - _kPdfScrollHeadSize) * - widget.pdfViewerController.pageCount) - .round(); + pageNumber = + (_scrollHeadPosition / + (widget.viewportDimension.height - _kPdfScrollHeadSize) * + widget.pdfViewerController.pageCount) + .round(); } if (pageNumber > 0 && pageNumber != widget.pdfViewerController.pageNumber) { widget.pdfViewerController.jumpToPage(pageNumber); @@ -880,63 +949,68 @@ class SinglePageViewState extends State { /// Scale to PDF double scaleTo(double zoomLevel) { - currentZoomLevel = _transformationController.value.getMaxScaleOnAxis(); + currentZoomLevel = + _currentPageTransformationController.value.getMaxScaleOnAxis(); if (currentZoomLevel != zoomLevel) { previousZoomLevel = currentZoomLevel; _oldPreviousZoomLevel = previousZoomLevel; _setZoomLevel = true; final double zoomChangeFactor = zoomLevel / currentZoomLevel; - final Offset previousOffset = _transformationController.toScene( - Offset.zero, - ); - _transformationController.value.scale(zoomChangeFactor, zoomChangeFactor); - final Offset currentOffset = _transformationController.toScene( + final Offset previousOffset = _currentPageTransformationController + .toScene(Offset.zero); + _currentPageTransformationController.value = + _currentPageTransformationController.value.clone() + ..scale(zoomChangeFactor, zoomChangeFactor); + final Offset currentOffset = _currentPageTransformationController.toScene( Offset.zero, ); if ((kIsDesktop && !widget.isMobileWebView) || - (widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize + (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize .width * zoomLevel < widget.viewportDimension.width)) { - setState(() { - _transformationController.value = - _transformationController.value.clone() - ..translate( - currentOffset.dx, - currentOffset.dy / widget.pdfViewerController.zoomLevel, - ); - }); + _currentPageTransformationController.value = + _currentPageTransformationController.value.clone()..translate( + currentOffset.dx, + currentOffset.dy / widget.pdfViewerController.zoomLevel, + ); } else { - greyAreaSize = widget.viewportDimension.height - - (widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize + greyAreaSize = + widget.viewportDimension.height - + (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize .height); double greyAreaOffset = 0; - setState(() { - if (widget.viewportDimension.height > - widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize - .height * - previousZoomLevel) { - greyAreaOffset = greyAreaSize / 2; - } else { - greyAreaOffset = 0; - } - if (widget.viewportDimension.height > - widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize - .height * - widget.pdfViewerController.zoomLevel) { - _setPixel(Offset(previousOffset.dx, 0)); - } else { - _setPixel( - Offset(previousOffset.dx, previousOffset.dy + greyAreaOffset), - ); - } - }); + if (widget.viewportDimension.height > + widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize + .height * + previousZoomLevel) { + greyAreaOffset = greyAreaSize / 2; + } else { + greyAreaOffset = 0; + } + if (widget.viewportDimension.height > + widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize + .height * + widget.pdfViewerController.zoomLevel) { + _setPixel(Offset(previousOffset.dx, 0)); + } else { + _setPixel( + Offset(previousOffset.dx, previousOffset.dy + greyAreaOffset), + ); + } } } widget.onPdfOffsetChanged!.call( - _transformationController.toScene(Offset.zero), + _currentPageTransformationController.toScene(Offset.zero), ); - return zoomLevel; } @@ -951,7 +1025,9 @@ class SinglePageViewState extends State { widget.pdfViewerController.zoomLevel = currentPreviousZoomLevel; previousZoomLevel = _oldPreviousZoomLevel; if (widget.pdfViewerController.zoomLevel > 1) { - if (widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize + if (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize .width * widget.pdfViewerController.zoomLevel < widget.viewportDimension.width) { @@ -960,23 +1036,24 @@ class SinglePageViewState extends State { } else { if ((!kIsDesktop || kIsDesktop && widget.isMobileWebView) && widget.viewportDimension.height > - (widget.pdfPages[widget.pdfViewerController.pageNumber]! - .pageSize.height * + (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize + .height * widget.pdfViewerController.zoomLevel)) { final Size pdfDimension = widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize; - final double widthFactor = pdfDimension.width - + final double widthFactor = + pdfDimension.width - (widget.viewportDimension.width / widget.pdfViewerController.zoomLevel); - final Offset previousOffset = _transformationController.toScene( - Offset.zero, - ); - _transformationController.value = - _transformationController.value.clone() - ..translate( - previousOffset.dx - offset.dx.clamp(0, widthFactor.abs()), - -(widget.viewportDimension.height - pdfDimension.height) / 2, - ); + final Offset previousOffset = _currentPageTransformationController + .toScene(Offset.zero); + _currentPageTransformationController.value = + _currentPageTransformationController.value.clone()..translate( + previousOffset.dx - offset.dx.clamp(0, widthFactor.abs()), + -(widget.viewportDimension.height - pdfDimension.height) / 2, + ); } else { if (!kIsDesktop || (kIsDesktop && widget.isMobileWebView)) { isJumpOnZoomedDocument = true; @@ -990,14 +1067,16 @@ class SinglePageViewState extends State { } void _setPixel(Offset offset) { - final double widthFactor = widget - .pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.width - + final double widthFactor = + widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize.width - (widget.viewportDimension.width / widget.pdfViewerController.zoomLevel); offset = Offset( offset.dx.clamp(-widthFactor, widthFactor.abs()), offset.dy.clamp( 0, - (widget.pdfPages[widget.pdfViewerController.pageNumber]!.pageSize + (widget + .pdfPages[widget.pdfViewerController.pageNumber]! + .pageSize .height - (widget.viewportDimension.height / widget.pdfViewerController.zoomLevel)) @@ -1005,16 +1084,16 @@ class SinglePageViewState extends State { ), ); - final Offset previousOffset = _transformationController.toScene( + final Offset previousOffset = _currentPageTransformationController.toScene( Offset.zero, ); - _transformationController.value = _transformationController.value.clone() - ..translate( - previousOffset.dx - offset.dx, - previousOffset.dy - offset.dy, - ); + _currentPageTransformationController.value = + _currentPageTransformationController.value.clone()..translate( + previousOffset.dx - offset.dx, + previousOffset.dy - offset.dy, + ); widget.onPdfOffsetChanged!.call( - _transformationController.toScene(Offset.zero), + _currentPageTransformationController.toScene(Offset.zero), ); } @@ -1033,44 +1112,47 @@ class SinglePageViewState extends State { return AlertDialog( scrollable: true, insetPadding: EdgeInsets.zero, - contentPadding: isMaterial3 - ? const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0) - : orientation == Orientation.portrait + contentPadding: + isMaterial3 + ? const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0) + : orientation == Orientation.portrait ? const EdgeInsets.all(24) : const EdgeInsets.only(right: 24, left: 24), - buttonPadding: orientation == Orientation.portrait - ? const EdgeInsets.all(8) - : const EdgeInsets.all(4), + buttonPadding: + orientation == Orientation.portrait + ? const EdgeInsets.all(8) + : const EdgeInsets.all(4), backgroundColor: _pdfViewerThemeData!.paginationDialogStyle?.backgroundColor ?? - _effectiveThemeData!.paginationDialogStyle?.backgroundColor ?? - (Theme.of(context).colorScheme.brightness == Brightness.light - ? Colors.white - : const Color(0xFF424242)), - shape: isMaterial3 - ? null - : const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), + _effectiveThemeData!.paginationDialogStyle?.backgroundColor ?? + (Theme.of(context).colorScheme.brightness == Brightness.light + ? Colors.white + : const Color(0xFF424242)), + shape: + isMaterial3 + ? null + : const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( _localizations!.pdfGoToPageLabel, - style: Theme.of(context) - .textTheme - .headlineMedium! + style: Theme.of(context).textTheme.headlineMedium! .copyWith( fontSize: isMaterial3 ? 24 : 20, - color: isMaterial3 - ? Theme.of(context).colorScheme.onSurface - : Theme.of(context).brightness == Brightness.light + color: + isMaterial3 + ? Theme.of(context).colorScheme.onSurface + : Theme.of(context).brightness == Brightness.light ? Colors.black.withValues(alpha: 0.87) : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .paginationDialogStyle?.headerTextStyle, + .paginationDialogStyle + ?.headerTextStyle, ), ), if (isMaterial3) @@ -1096,10 +1178,10 @@ class SinglePageViewState extends State { child: Text( '1 - ${widget.pdfViewerController.pageCount}', style: Theme.of(context).textTheme.bodyLarge!.copyWith( - fontSize: 14, - fontWeight: isMaterial3 ? FontWeight.w400 : null, - color: Theme.of(context).colorScheme.onSurface, - ), + fontSize: 14, + fontWeight: isMaterial3 ? FontWeight.w400 : null, + color: Theme.of(context).colorScheme.onSurface, + ), ), ), ), @@ -1113,20 +1195,19 @@ class SinglePageViewState extends State { _textFieldController.clear(); Navigator.of(context).pop(); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPaginationDialogCancelLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -1134,7 +1215,8 @@ class SinglePageViewState extends State { ) .merge( _pdfViewerThemeData! - .paginationDialogStyle?.cancelTextStyle, + .paginationDialogStyle + ?.cancelTextStyle, ), ), ), @@ -1142,20 +1224,19 @@ class SinglePageViewState extends State { onPressed: () { _handlePageNumberValidation(); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPaginationDialogOkLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -1180,14 +1261,13 @@ class SinglePageViewState extends State { child: SizedBox( width: isMaterial3 ? 312.0 : _kPdfPaginationTextFieldWidth, child: TextFormField( - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData!.paginationDialogStyle?.inputFieldTextStyle, @@ -1195,79 +1275,89 @@ class SinglePageViewState extends State { focusNode: _focusNode, decoration: InputDecoration( isDense: true, - border: isMaterial3 - ? OutlineInputBorder( - borderSide: BorderSide( - color: _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - _effectiveThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - Theme.of(context).colorScheme.primary, - ), - ) - : null, - errorBorder: isMaterial3 - ? OutlineInputBorder( - borderRadius: BorderRadius.circular(3.5), - borderSide: BorderSide( - color: _pdfViewerThemeData! - .passwordDialogStyle?.errorBorderColor ?? - _effectiveThemeData! - .passwordDialogStyle?.errorBorderColor ?? - Theme.of(context).colorScheme.error, - ), - ) - : null, - focusedBorder: isMaterial3 - ? OutlineInputBorder( - borderSide: BorderSide( - color: _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - _effectiveThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? - Theme.of(context).colorScheme.primary, - width: 2, - ), - ) - : UnderlineInputBorder( - borderSide: BorderSide( - color: Theme.of(context).colorScheme.primary, + border: + isMaterial3 + ? OutlineInputBorder( + borderSide: BorderSide( + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + Theme.of(context).colorScheme.primary, + ), + ) + : null, + errorBorder: + isMaterial3 + ? OutlineInputBorder( + borderRadius: BorderRadius.circular(3.5), + borderSide: BorderSide( + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.errorBorderColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.errorBorderColor ?? + Theme.of(context).colorScheme.error, + ), + ) + : null, + focusedBorder: + isMaterial3 + ? OutlineInputBorder( + borderSide: BorderSide( + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? + Theme.of(context).colorScheme.primary, + width: 2, + ), + ) + : UnderlineInputBorder( + borderSide: BorderSide( + color: Theme.of(context).colorScheme.primary, + ), ), - ), - contentPadding: isMaterial3 - ? const EdgeInsets.all(16) - : const EdgeInsets.symmetric(vertical: 6), + contentPadding: + isMaterial3 + ? const EdgeInsets.all(16) + : const EdgeInsets.symmetric(vertical: 6), hintText: _localizations!.pdfEnterPageNumberLabel, - hintStyle: Theme.of(context) - .textTheme - .titleMedium! + hintStyle: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData!.paginationDialogStyle?.hintTextStyle, ), - counterText: isMaterial3 - ? null - : '${widget.pdfViewerController.pageNumber}/${widget.pdfViewerController.pageCount}', - counterStyle: Theme.of(context) - .textTheme - .bodySmall! + counterText: + isMaterial3 + ? null + : '${widget.pdfViewerController.pageNumber}/${widget.pdfViewerController.pageCount}', + counterStyle: Theme.of(context).textTheme.bodySmall! .copyWith( fontSize: 12, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.6) - : Colors.white.withValues(alpha: 0.6), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.6) + : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData!.paginationDialogStyle?.pageInfoTextStyle, ), - errorStyle: Theme.of(context) - .textTheme - .bodySmall! + errorStyle: Theme.of(context).textTheme.bodySmall! .copyWith( fontSize: 12, fontWeight: FontWeight.w400, @@ -1275,7 +1365,8 @@ class SinglePageViewState extends State { ) .merge( _pdfViewerThemeData! - .paginationDialogStyle?.validationTextStyle, + .paginationDialogStyle + ?.validationTextStyle, ), ), keyboardType: TextInputType.number, @@ -1331,7 +1422,7 @@ class TransformationControllerExt extends TransformationController { set viewSize(Size size) { if (_viewSize != size) { _viewSize = size; - _boundWithinViewportLimits(value); + super.value = _boundWithinViewportLimits(value); } } @@ -1340,7 +1431,7 @@ class TransformationControllerExt extends TransformationController { set contentSize(Size size) { if (_contentSize != size) { _contentSize = size; - _boundWithinViewportLimits(value); + super.value = _boundWithinViewportLimits(value); } } diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/sticky_note_edit_text.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/sticky_note_edit_text.dart index bfb91fed8..db5b941e2 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/sticky_note_edit_text.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/sticky_note_edit_text.dart @@ -161,9 +161,10 @@ class _StickyNoteEditTextState extends State { }); } }, - icon: _isEditing - ? const Icon(Icons.check_outlined) - : const Icon(Icons.edit_outlined), + icon: + _isEditing + ? const Icon(Icons.check_outlined) + : const Icon(Icons.edit_outlined), ), ), IconButton( diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/control/text_selection_menu.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/control/text_selection_menu.dart index 8e446a81f..261c4b172 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/control/text_selection_menu.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/control/text_selection_menu.dart @@ -48,11 +48,12 @@ class _TextSelectionMenuState extends State { return Container( height: kTextSelectionMenuHeight, decoration: ShapeDecoration( - color: widget.themeData!.useMaterial3 - ? (widget.themeData!.colorScheme.brightness == Brightness.light) - ? const Color.fromRGBO(238, 232, 244, 1) - : const Color.fromRGBO(48, 45, 56, 1) - : (widget.themeData!.colorScheme.brightness == Brightness.light) + color: + widget.themeData!.useMaterial3 + ? (widget.themeData!.colorScheme.brightness == Brightness.light) + ? const Color.fromRGBO(238, 232, 244, 1) + : const Color.fromRGBO(48, 45, 56, 1) + : (widget.themeData!.colorScheme.brightness == Brightness.light) ? Colors.white : const Color(0xFF303030), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5)), @@ -105,8 +106,10 @@ class _TextSelectionMenuState extends State { themeData: widget.themeData, ), TextSelectionMenuItem( - title: widget - .localizations!.pdfTextSelectionMenuStrikethroughLabel, + title: + widget + .localizations! + .pdfTextSelectionMenuStrikethroughLabel, mode: 'Strikethrough', onSelected: widget.onSelected, textDirection: widget.textDirection, @@ -169,9 +172,10 @@ class _TextSelectionMenuItemState extends State { onTap: () { widget.onSelected?.call(widget.mode); }, - highlightColor: widget.themeData!.useMaterial3 - ? widget.themeData!.colorScheme.primaryContainer - : (widget.themeData!.colorScheme.brightness == Brightness.light) + highlightColor: + widget.themeData!.useMaterial3 + ? widget.themeData!.colorScheme.primaryContainer + : (widget.themeData!.colorScheme.brightness == Brightness.light) ? Colors.grey.withValues(alpha: 0.2) : Colors.grey.withValues(alpha: 0.5), child: Directionality( @@ -188,9 +192,10 @@ class _TextSelectionMenuItemState extends State { overflow: TextOverflow.ellipsis, style: widget.themeData!.textTheme.bodyMedium!.copyWith( fontSize: 14, - color: widget.themeData!.useMaterial3 - ? widget.themeData!.colorScheme.onSurface - : widget.themeData!.brightness == Brightness.light + color: + widget.themeData!.useMaterial3 + ? widget.themeData!.colorScheme.onSurface + : widget.themeData!.brightness == Brightness.light ? Colors.black.withValues(alpha: 0.87) : Colors.white.withValues(alpha: 0.87), ), @@ -208,9 +213,10 @@ class _TextSelectionMenuItemState extends State { return Icon( Icons.copy, size: 16, - color: (widget.themeData!.colorScheme.brightness == Brightness.light) - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + (widget.themeData!.colorScheme.brightness == Brightness.light) + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ); } mode = mode.toLowerCase().replaceAll(RegExp(r' '), ''); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/form_field_container.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/form_field_container.dart index a25c82f72..d3bdf40df 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/form_field_container.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/form_field_container.dart @@ -51,7 +51,9 @@ class _FormFieldContainerState extends State { final PdfFormFieldHelper helper = PdfFormFieldHelper.getHelper( formField, ); - _updateGlobalRect(helper); + WidgetsBinding.instance.addPostFrameCallback((_) { + _updateGlobalRect(helper); + }); helper.onChanged = () { if (mounted) { setState(() {}); @@ -106,6 +108,9 @@ class _FormFieldContainerState extends State { /// Updates the global rect of the form field. void _updateGlobalRect(PdfFormFieldHelper helper) { + if (!mounted) { + return; + } final renderObject = context.findRenderObject(); if (renderObject is RenderBox && renderObject.hasSize) { helper.globalRect = Rect.fromPoints( diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_checkbox.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_checkbox.dart index 07e578e7b..3a91c145d 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_checkbox.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_checkbox.dart @@ -35,9 +35,10 @@ class PdfCheckboxFormField extends PdfFormField { } /// Gets the child items associated with this [PdfCheckboxFormField]. - List? get children => _children != null - ? List.unmodifiable(_children!) - : null; + List? get children => + _children != null + ? List.unmodifiable(_children!) + : null; } /// Helper class for [PdfCheckboxFormField]. @@ -82,10 +83,12 @@ class PdfCheckboxFormFieldHelper extends PdfFormFieldHelper { /// Creates the checkbox form field object. PdfCheckboxFormField getFormField() { - checkboxFormField = PdfCheckboxFormField._() - .._isChecked = pdfCheckBoxItem != null - ? pdfCheckBoxItem!.checked - : pdfCheckboxField.isChecked; + checkboxFormField = + PdfCheckboxFormField._() + .._isChecked = + pdfCheckBoxItem != null + ? pdfCheckBoxItem!.checked + : pdfCheckboxField.isChecked; super.load(checkboxFormField); return checkboxFormField; @@ -124,9 +127,11 @@ class PdfCheckboxFormFieldHelper extends PdfFormFieldHelper { void _updateChildItems() { if (checkboxFormField._children != null && checkboxFormField._children!.isNotEmpty) { - for (int index = 0; - index < checkboxFormField._children!.length; - index++) { + for ( + int index = 0; + index < checkboxFormField._children!.length; + index++ + ) { final PdfCheckboxFormFieldHelper helper = PdfFormFieldHelper.getHelper(checkboxFormField._children![index]) as PdfCheckboxFormFieldHelper; @@ -155,23 +160,28 @@ class PdfCheckboxFormFieldHelper extends PdfFormFieldHelper { onChanged: invokeValueChanged, heightPercentage: heightPercentage, selectionPadding: selectionPadding, - fillColor: pdfCheckboxField.backColor.isEmpty - ? const Color.fromARGB(255, 221, 228, 255) - : Color.fromRGBO( - pdfCheckboxField.backColor.r, - pdfCheckboxField.backColor.g, - pdfCheckboxField.backColor.b, - 1, - ), - borderColor: pdfCheckboxField.borderColor.isEmpty - ? Colors.transparent - : Color.fromRGBO( - pdfCheckboxField.borderColor.r, - pdfCheckboxField.borderColor.g, - pdfCheckboxField.borderColor.b, - 1, - ), - borderWidth: (pdfCheckboxField.borderWidth == 0 + fillColor: + pdfCheckboxField.backColor.isEmpty + ? pdfCheckboxField.readOnly + ? Colors.transparent + : const Color.fromARGB(255, 221, 228, 255) + : Color.fromRGBO( + pdfCheckboxField.backColor.r, + pdfCheckboxField.backColor.g, + pdfCheckboxField.backColor.b, + 1, + ), + borderColor: + pdfCheckboxField.borderColor.isEmpty + ? Colors.transparent + : Color.fromRGBO( + pdfCheckboxField.borderColor.r, + pdfCheckboxField.borderColor.g, + pdfCheckboxField.borderColor.b, + 1, + ), + borderWidth: + (pdfCheckboxField.borderWidth == 0 ? 1 : pdfCheckboxField.borderWidth) / heightPercentage, @@ -259,13 +269,14 @@ class _PdfCheckboxState extends State { width: widget.borderWidth, ), ), - child: widget.isChecked - ? Icon( - Icons.check_outlined, - size: widget.size - widget.borderWidth * 2, - color: Colors.black, - ) - : Container(), + child: + widget.isChecked + ? Icon( + Icons.check_outlined, + size: widget.size - widget.borderWidth * 2, + color: Colors.black, + ) + : Container(), ), ), ); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_combo_box.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_combo_box.dart index d4a3a2371..138fdfb7b 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_combo_box.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_combo_box.dart @@ -52,13 +52,15 @@ class PdfComboBoxFormFieldHelper extends PdfFormFieldHelper { items.add(pdfComboBoxField.items[index].text); } - final String selectedValue = pdfComboBoxField.selectedIndex != -1 - ? pdfComboBoxField.items[pdfComboBoxField.selectedIndex].text - : ''; - - comboBoxFormField = PdfComboBoxFormField._() - .._items = items - .._selectedItem = selectedValue; + final String selectedValue = + pdfComboBoxField.selectedIndex != -1 + ? pdfComboBoxField.items[pdfComboBoxField.selectedIndex].text + : ''; + + comboBoxFormField = + PdfComboBoxFormField._() + .._items = items + .._selectedItem = selectedValue; super.load(comboBoxFormField); return comboBoxFormField; @@ -111,22 +113,26 @@ class PdfComboBoxFormFieldHelper extends PdfFormFieldHelper { font: pdfComboBoxField.font?.name, textAlign: pdfComboBoxField.textAlignment.textAlign, alignment: pdfComboBoxField.textAlignment.alignmentGeometry, - fillColor: pdfComboBoxField.backColor.isEmpty - ? const Color.fromARGB(255, 221, 228, 255) - : Color.fromRGBO( - pdfComboBoxField.backColor.r, - pdfComboBoxField.backColor.g, - pdfComboBoxField.backColor.b, - 1, - ), - borderColor: pdfComboBoxField.borderColor.isEmpty - ? Colors.transparent - : Color.fromRGBO( - pdfComboBoxField.borderColor.r, - pdfComboBoxField.borderColor.g, - pdfComboBoxField.borderColor.b, - 1, - ), + fillColor: + pdfComboBoxField.backColor.isEmpty + ? pdfComboBoxField.readOnly + ? Colors.transparent + : const Color.fromARGB(255, 221, 228, 255) + : Color.fromRGBO( + pdfComboBoxField.backColor.r, + pdfComboBoxField.backColor.g, + pdfComboBoxField.backColor.b, + 1, + ), + borderColor: + pdfComboBoxField.borderColor.isEmpty + ? Colors.transparent + : Color.fromRGBO( + pdfComboBoxField.borderColor.r, + pdfComboBoxField.borderColor.g, + pdfComboBoxField.borderColor.b, + 1, + ), borderWidth: pdfComboBoxField.borderWidth / heightPercentage, fontSize: (pdfComboBoxField.font?.size ?? 14.0) / heightPercentage, onValueChanged: invokeValueChanged, @@ -214,30 +220,32 @@ class _PdfComboBoxState extends State { child: DropdownButton( alignment: widget.alignment, value: widget.selectedItem.isNotEmpty ? widget.selectedItem : null, - items: widget.items.map((String value) { - return DropdownMenuItem( - alignment: widget.alignment, - value: value, - child: Tooltip( - excludeFromSemantics: true, - message: value, - child: Text( - textAlign: widget.textAlign, - value, - style: const TextStyle(fontSize: 16.0), - overflow: TextOverflow.ellipsis, - ), - ), - ); - }).toList(), + items: + widget.items.map((String value) { + return DropdownMenuItem( + alignment: widget.alignment, + value: value, + child: Tooltip( + excludeFromSemantics: true, + message: value, + child: Text( + textAlign: widget.textAlign, + value, + style: const TextStyle(fontSize: 16.0), + overflow: TextOverflow.ellipsis, + ), + ), + ); + }).toList(), isExpanded: true, - onChanged: widget.readOnly - ? null - : (String? newValue) { - if (widget.onValueChanged != null && newValue != null) { - widget.onValueChanged!(newValue); - } - }, + onChanged: + widget.readOnly + ? null + : (String? newValue) { + if (widget.onValueChanged != null && newValue != null) { + widget.onValueChanged!(newValue); + } + }, style: Theme.of(context).textTheme.bodyMedium, selectedItemBuilder: (BuildContext context) { return widget.items.map((String value) { diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_list_box.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_list_box.dart index 6b1a9c9b6..61f43e642 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_list_box.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_list_box.dart @@ -61,9 +61,10 @@ class PdfListBoxFormFieldHelper extends PdfFormFieldHelper { growable: false, ); - listBoxFormField = PdfListBoxFormField._() - .._items = items - .._selectedItems = selectedItems; + listBoxFormField = + PdfListBoxFormField._() + .._items = items + .._selectedItems = selectedItems; super.load(listBoxFormField); return listBoxFormField; @@ -96,9 +97,10 @@ class PdfListBoxFormFieldHelper extends PdfFormFieldHelper { } } - final List oldValue = listBoxFormField._selectedItems != null - ? List.from(listBoxFormField._selectedItems!) - : List.empty(); + final List oldValue = + listBoxFormField._selectedItems != null + ? List.from(listBoxFormField._selectedItems!) + : List.empty(); setListBoxValue(newValue); if (onValueChanged != null) { @@ -128,23 +130,28 @@ class PdfListBoxFormFieldHelper extends PdfFormFieldHelper { heightPercentage: heightPercentage, selectedItems: listBoxFormField._selectedItems!, items: listBoxFormField._items, + readOnly: listBoxFormField.readOnly, font: pdfListBoxField.font?.name, - fillColor: pdfListBoxField.backColor.isEmpty - ? const Color.fromARGB(255, 221, 228, 255) - : Color.fromRGBO( - pdfListBoxField.backColor.r, - pdfListBoxField.backColor.g, - pdfListBoxField.backColor.b, - 1, - ), - borderColor: pdfListBoxField.borderColor.isEmpty - ? Colors.transparent - : Color.fromRGBO( - pdfListBoxField.borderColor.r, - pdfListBoxField.borderColor.g, - pdfListBoxField.borderColor.b, - 1, - ), + fillColor: + pdfListBoxField.backColor.isEmpty + ? pdfListBoxField.readOnly + ? Colors.transparent + : const Color.fromARGB(255, 221, 228, 255) + : Color.fromRGBO( + pdfListBoxField.backColor.r, + pdfListBoxField.backColor.g, + pdfListBoxField.backColor.b, + 1, + ), + borderColor: + pdfListBoxField.borderColor.isEmpty + ? Colors.transparent + : Color.fromRGBO( + pdfListBoxField.borderColor.r, + pdfListBoxField.borderColor.g, + pdfListBoxField.borderColor.b, + 1, + ), borderWidth: pdfListBoxField.borderWidth / heightPercentage, textAlign: pdfListBoxField.textAlignment.textAlign, fontSize: (pdfListBoxField.font?.size ?? 14.0) / heightPercentage, @@ -243,9 +250,10 @@ class _PdfListBoxState extends State { return Container( padding: const EdgeInsets.only(left: 5), decoration: BoxDecoration( - color: selected - ? const Color.fromARGB(255, 46, 134, 193) - : Colors.transparent, + color: + selected + ? const Color.fromARGB(255, 46, 134, 193) + : Colors.transparent, ), child: Text( widget.items[index], @@ -279,12 +287,14 @@ void _showListBoxDialog( context: context, builder: (BuildContext context) { return AlertDialog( - contentPadding: isMaterial3 - ? const EdgeInsets.only(left: 24.0, right: 16.0, top: 16.0) - : EdgeInsets.zero, - actionsPadding: isMaterial3 - ? const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0) - : null, + contentPadding: + isMaterial3 + ? const EdgeInsets.only(left: 24.0, right: 16.0, top: 16.0) + : EdgeInsets.zero, + actionsPadding: + isMaterial3 + ? const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0) + : null, content: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return SizedBox( @@ -295,52 +305,51 @@ void _showListBoxDialog( itemBuilder: (BuildContext context, int index) { return listBoxHelper.isMultiSelect ? CheckboxListTile( - controlAffinity: ListTileControlAffinity.leading, - title: Text( - listBoxHelper.listBoxFormField._items[index], - ), - value: newItems.contains( - listBoxHelper.listBoxFormField._items[index], - ), - shape: isMaterial3 - ? RoundedRectangleBorder( + controlAffinity: ListTileControlAffinity.leading, + title: Text( + listBoxHelper.listBoxFormField._items[index], + ), + value: newItems.contains( + listBoxHelper.listBoxFormField._items[index], + ), + shape: + isMaterial3 + ? RoundedRectangleBorder( borderRadius: BorderRadius.circular(4.0), ) - : null, - contentPadding: isMaterial3 ? EdgeInsets.zero : null, - onChanged: (bool? value) { - setState(() { - if (value != null) { - if (value) { - newItems.add( - listBoxHelper - .listBoxFormField._items[index], - ); - } else { - newItems.remove( - listBoxHelper - .listBoxFormField._items[index], - ); - } + : null, + contentPadding: isMaterial3 ? EdgeInsets.zero : null, + onChanged: (bool? value) { + setState(() { + if (value != null) { + if (value) { + newItems.add( + listBoxHelper.listBoxFormField._items[index], + ); + } else { + newItems.remove( + listBoxHelper.listBoxFormField._items[index], + ); } - }); - }, - ) + } + }); + }, + ) : RadioListTile( - controlAffinity: ListTileControlAffinity.leading, - title: Text( - listBoxHelper.listBoxFormField._items[index], - ), - value: listBoxHelper.listBoxFormField._items[index], - groupValue: newItems.isEmpty ? null : newItems.first, - onChanged: (String? value) { - setState(() { - if (value != null) { - newItems = [value]; - } - }); - }, - ); + controlAffinity: ListTileControlAffinity.leading, + title: Text( + listBoxHelper.listBoxFormField._items[index], + ), + value: listBoxHelper.listBoxFormField._items[index], + groupValue: newItems.isEmpty ? null : newItems.first, + onChanged: (String? value) { + setState(() { + if (value != null) { + newItems = [value]; + } + }); + }, + ); }, itemCount: listBoxHelper.listBoxFormField._items.length, ), @@ -352,18 +361,19 @@ void _showListBoxDialog( onPressed: () { Navigator.pop(context); }, - style: isMaterial3 - ? TextButton.styleFrom( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20.0), - ), - padding: const EdgeInsets.symmetric( - horizontal: 20.0, - vertical: 10, - ), - fixedSize: const Size(double.infinity, 40), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20.0), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10, + ), + fixedSize: const Size(double.infinity, 40), + ) + : null, child: const Text( 'CANCEL', style: TextStyle( @@ -377,18 +387,19 @@ void _showListBoxDialog( Navigator.pop(context); listBoxHelper.invokeValueChanged(newItems); }, - style: isMaterial3 - ? TextButton.styleFrom( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20.0), - ), - padding: const EdgeInsets.symmetric( - horizontal: 20.0, - vertical: 10, - ), - fixedSize: const Size(74, 40), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20.0), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10, + ), + fixedSize: const Size(74, 40), + ) + : null, child: const Text( 'OK', style: TextStyle( diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_radio_button.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_radio_button.dart index 432cea0b9..44501897b 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_radio_button.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_radio_button.dart @@ -55,13 +55,15 @@ class PdfRadioFormFieldHelper extends PdfFormFieldHelper { for (int index = 0; index < pdfRadioField.items.count; index++) { items.add(pdfRadioField.items[index].value); } - final String selectedValue = pdfRadioField.selectedIndex != -1 - ? items[pdfRadioField.selectedIndex] - : ''; + final String selectedValue = + pdfRadioField.selectedIndex != -1 + ? items[pdfRadioField.selectedIndex] + : ''; canReset = selectedValue == ''; - radioFormField = PdfRadioFormField._() - .._items = items - .._selectedItem = selectedValue; + radioFormField = + PdfRadioFormField._() + .._items = items + .._selectedItem = selectedValue; super.load(radioFormField); return radioFormField; @@ -118,22 +120,26 @@ class PdfRadioFormFieldHelper extends PdfFormFieldHelper { onChanged: invokeValueChanged, heightPercentage: heightPercentage, selectionPadding: selectionPadding, - fillColor: pdfRadioField.items[j].backColor.isEmpty - ? const Color.fromARGB(255, 221, 228, 255) - : Color.fromRGBO( - pdfRadioField.items[j].backColor.r, - pdfRadioField.items[j].backColor.g, - pdfRadioField.items[j].backColor.b, - 1, - ), - borderColor: pdfRadioField.items[j].borderColor.isEmpty - ? Colors.transparent - : Color.fromRGBO( - pdfRadioField.items[j].borderColor.r, - pdfRadioField.items[j].borderColor.g, - pdfRadioField.items[j].borderColor.b, - 1, - ), + fillColor: + pdfRadioField.items[j].backColor.isEmpty + ? pdfRadioField.readOnly + ? Colors.transparent + : const Color.fromARGB(255, 221, 228, 255) + : Color.fromRGBO( + pdfRadioField.items[j].backColor.r, + pdfRadioField.items[j].backColor.g, + pdfRadioField.items[j].backColor.b, + 1, + ), + borderColor: + pdfRadioField.items[j].borderColor.isEmpty + ? Colors.transparent + : Color.fromRGBO( + pdfRadioField.items[j].borderColor.r, + pdfRadioField.items[j].borderColor.g, + pdfRadioField.items[j].borderColor.b, + 1, + ), borderWidth: pdfRadioField.items[j].borderWidth / heightPercentage, size: bounds.height / heightPercentage, ), @@ -226,13 +232,14 @@ class _PdfRadioButtonState extends State { width: widget.borderWidth, ), ), - child: widget.groupValue == widget.value - ? Icon( - Icons.circle, - size: widget.size / 2.0, - color: Colors.black, - ) - : Container(), + child: + widget.groupValue == widget.value + ? Icon( + Icons.circle, + size: widget.size / 2.0, + color: Colors.black, + ) + : Container(), ), ), ); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_signature.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_signature.dart index bdfc3780c..beafc3d1f 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_signature.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_signature.dart @@ -85,9 +85,10 @@ class PdfSignatureFormFieldHelper extends PdfFormFieldHelper { if (!isValid) { return; } - final Uint8List? oldValue = signatureFormField._signature != null - ? Uint8List.fromList(signatureFormField._signature!) - : null; + final Uint8List? oldValue = + signatureFormField._signature != null + ? Uint8List.fromList(signatureFormField._signature!) + : null; signatureFormField._signature = newValue; if (onValueChanged != null) { @@ -124,11 +125,11 @@ class PdfSignatureFormFieldHelper extends PdfFormFieldHelper { } signatureFormField.signature != null ? _showSignatureContextMenu( - context, - this, - details.globalPosition, - bounds.height / heightPercentage, - ) + context, + this, + details.globalPosition, + bounds.height / heightPercentage, + ) : _showSignaturePadDialog(context, this); } @@ -152,22 +153,26 @@ class PdfSignatureFormFieldHelper extends PdfFormFieldHelper { heightPercentage: heightPercentage, signature: signatureFormField.signature, readOnly: signatureFormField.readOnly, - fillColor: pdfSignatureField.backColor.isEmpty - ? const Color.fromARGB(255, 221, 228, 255) - : Color.fromRGBO( - pdfSignatureField.backColor.r, - pdfSignatureField.backColor.g, - pdfSignatureField.backColor.b, - 1, - ), - borderColor: pdfSignatureField.borderColor.isEmpty - ? Colors.transparent - : Color.fromRGBO( - pdfSignatureField.borderColor.r, - pdfSignatureField.borderColor.g, - pdfSignatureField.borderColor.b, - 1, - ), + fillColor: + pdfSignatureField.backColor.isEmpty + ? pdfSignatureField.readOnly + ? Colors.transparent + : const Color.fromARGB(255, 221, 228, 255) + : Color.fromRGBO( + pdfSignatureField.backColor.r, + pdfSignatureField.backColor.g, + pdfSignatureField.backColor.b, + 1, + ), + borderColor: + pdfSignatureField.borderColor.isEmpty + ? Colors.transparent + : Color.fromRGBO( + pdfSignatureField.borderColor.r, + pdfSignatureField.borderColor.g, + pdfSignatureField.borderColor.b, + 1, + ), borderWidth: pdfSignatureField.borderWidth / heightPercentage, onValueChanged: invokeValueChanged, onSignatureFieldTapDown: (TapDownDetails details) { @@ -254,9 +259,10 @@ class _PdfSignatureState extends State { width: widget.borderWidth, ), ), - child: widget.signature != null - ? Image.memory(widget.signature!) - : Container(), + child: + widget.signature != null + ? Image.memory(widget.signature!) + : Container(), ), ); } @@ -381,49 +387,55 @@ void _showSignaturePadDialog( builder: (BuildContext context) { return LayoutBuilder( builder: (BuildContext context, BoxConstraints constraints) { - final double signaturePadWidth = kIsDesktop - ? max(constraints.maxWidth, constraints.maxHeight) * - (isMaterial3 ? 0.27 : 0.25) - : MediaQuery.of(context).size.width < kSignaturePadWidth + final double signaturePadWidth = + kIsDesktop + ? max(constraints.maxWidth, constraints.maxHeight) * + (isMaterial3 ? 0.27 : 0.25) + : MediaQuery.of(context).size.width < kSignaturePadWidth ? MediaQuery.of(context).size.width : kSignaturePadWidth; - final double signaturePadHeight = kIsDesktop - ? signaturePadWidth * (isMaterial3 ? 0.53 : 0.6) - : kSignaturePadHeight; + final double signaturePadHeight = + kIsDesktop + ? signaturePadWidth * (isMaterial3 ? 0.53 : 0.6) + : kSignaturePadHeight; return StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return AlertDialog( - backgroundColor: isMaterial3 - ? Theme.of(context).brightness == Brightness.light - ? const Color(0xFFEEE8F4) - : const Color(0xFF302D38) - : null, + backgroundColor: + isMaterial3 + ? Theme.of(context).brightness == Brightness.light + ? const Color(0xFFEEE8F4) + : const Color(0xFF302D38) + : null, insetPadding: const EdgeInsets.all(12.0), - shape: isMaterial3 - ? RoundedRectangleBorder( - borderRadius: BorderRadius.circular(28.0), - ) - : null, + shape: + isMaterial3 + ? RoundedRectangleBorder( + borderRadius: BorderRadius.circular(28.0), + ) + : null, title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( localizations.pdfSignaturePadDialogHeaderTextLabel, - style: isMaterial3 - ? Theme.of(context).textTheme.bodyLarge!.copyWith( + style: + isMaterial3 + ? Theme.of(context).textTheme.bodyLarge!.copyWith( fontSize: 24, color: Theme.of(context).colorScheme.onSurface, fontWeight: FontWeight.w400, ) - : Theme.of( - context, - ).textTheme.titleMedium!.copyWith( + : Theme.of( + context, + ).textTheme.titleMedium!.copyWith( fontSize: 16, fontFamily: 'Roboto-Medium', - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ), ), InkWell( @@ -440,29 +452,32 @@ void _showSignaturePadDialog( }, borderRadius: isMaterial3 ? BorderRadius.circular(20.0) : null, - child: isMaterial3 - ? SizedBox.square( - dimension: 40, - child: Icon( - Icons.clear, - size: 24, - color: Theme.of( - context, - ).colorScheme.onSurfaceVariant, - ), - ) - : const Icon(Icons.clear, size: 24.0), + child: + isMaterial3 + ? SizedBox.square( + dimension: 40, + child: Icon( + Icons.clear, + size: 24, + color: + Theme.of( + context, + ).colorScheme.onSurfaceVariant, + ), + ) + : const Icon(Icons.clear, size: 24.0), ), ], ), - titlePadding: isMaterial3 - ? const EdgeInsets.only( - left: 24.0, - top: 16.0, - right: 16.0, - bottom: 16, - ) - : const EdgeInsets.all(16.0), + titlePadding: + isMaterial3 + ? const EdgeInsets.only( + left: 24.0, + top: 16.0, + right: 16.0, + bottom: 16, + ) + : const EdgeInsets.all(16.0), content: SingleChildScrollView( child: SizedBox( width: signaturePadWidth, @@ -472,13 +487,15 @@ void _showSignaturePadDialog( Container( height: signaturePadHeight, decoration: BoxDecoration( - border: isMaterial3 - ? Border.all( - color: Theme.of( - context, - ).colorScheme.outlineVariant, - ) - : Border.all(color: Colors.grey[350]!), + border: + isMaterial3 + ? Border.all( + color: + Theme.of( + context, + ).colorScheme.outlineVariant, + ) + : Border.all(color: Colors.grey[350]!), color: Colors.white, borderRadius: isMaterial3 ? BorderRadius.circular(4.0) : null, @@ -504,21 +521,20 @@ void _showSignaturePadDialog( style: Theme.of( context, ).textTheme.bodyMedium!.copyWith( - fontSize: 14, - fontWeight: - isMaterial3 ? FontWeight.w400 : null, - fontFamily: 'Roboto-Regular', - color: isMaterial3 + fontSize: 14, + fontWeight: + isMaterial3 ? FontWeight.w400 : null, + fontFamily: 'Roboto-Regular', + color: + isMaterial3 ? Theme.of( - context, - ).colorScheme.onSurface + context, + ).colorScheme.onSurface : Theme.of(context).brightness == - Brightness.light - ? Colors.black - .withValues(alpha: 0.87) - : Colors.white - .withValues(alpha: 0.87), - ), + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), + ), ), SizedBox( width: 128, @@ -537,91 +553,98 @@ void _showSignaturePadDialog( ), ), ), - contentPadding: isMaterial3 - ? EdgeInsets.symmetric( - horizontal: kIsDesktop ? 20 : 24.0, - ) - : const EdgeInsets.symmetric(horizontal: 12.0), - actionsPadding: isMaterial3 - ? const EdgeInsets.all(24) - : const EdgeInsets.all(8.0), + contentPadding: + isMaterial3 + ? EdgeInsets.symmetric( + horizontal: kIsDesktop ? 20 : 24.0, + ) + : const EdgeInsets.symmetric(horizontal: 12.0), + actionsPadding: + isMaterial3 + ? const EdgeInsets.all(24) + : const EdgeInsets.all(8.0), buttonPadding: EdgeInsets.zero, actions: [ TextButton( - onPressed: !_isSignatureDrawn - ? null - : () { - _handleSignatureClearButtonPressed(); - setState(() { - _isSignatureDrawn = false; - }); - }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20.0), - ), - padding: const EdgeInsets.symmetric( - horizontal: 20.0, - vertical: 10, - ), - ) - : null, + onPressed: + !_isSignatureDrawn + ? null + : () { + _handleSignatureClearButtonPressed(); + setState(() { + _isSignatureDrawn = false; + }); + }, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20.0), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10, + ), + ) + : null, child: Text( localizations.pdfSignaturePadDialogClearLabel, style: Theme.of(context).textTheme.bodyMedium!.copyWith( - fontSize: 14, - fontWeight: isMaterial3 ? FontWeight.w400 : null, - fontFamily: 'Roboto-Medium', - color: themeData.colorScheme.primary, - ), + fontSize: 14, + fontWeight: isMaterial3 ? FontWeight.w400 : null, + fontFamily: 'Roboto-Medium', + color: themeData.colorScheme.primary, + ), ), ), const SizedBox(width: 8.0), TextButton( - onPressed: !_isSignatureDrawn - ? null - : () { - _handleSignatureSaveButtonPressed( - signatureFieldHelper, - ); - Navigator.of(context).pop(); - if (signatureFieldHelper.onFocusChange != null) { - signatureFieldHelper.onFocusChange!( - PdfFormFieldFocusChangeDetails( - signatureFieldHelper.signatureFormField, - false, - ), + onPressed: + !_isSignatureDrawn + ? null + : () { + _handleSignatureSaveButtonPressed( + signatureFieldHelper, ); - } - }, - style: isMaterial3 - ? ElevatedButton.styleFrom( - backgroundColor: - Theme.of(context).colorScheme.primary, - disabledBackgroundColor: - Theme.of(context).colorScheme.primary, - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(20.0), - ), - padding: const EdgeInsets.symmetric( - horizontal: 20.0, - vertical: 10, - ), - fixedSize: const Size(double.infinity, 40), - ) - : null, + Navigator.of(context).pop(); + if (signatureFieldHelper.onFocusChange != null) { + signatureFieldHelper.onFocusChange!( + PdfFormFieldFocusChangeDetails( + signatureFieldHelper.signatureFormField, + false, + ), + ); + } + }, + style: + isMaterial3 + ? ElevatedButton.styleFrom( + backgroundColor: + Theme.of(context).colorScheme.primary, + disabledBackgroundColor: + Theme.of(context).colorScheme.primary, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20.0), + ), + padding: const EdgeInsets.symmetric( + horizontal: 20.0, + vertical: 10, + ), + fixedSize: const Size(double.infinity, 40), + ) + : null, child: Text( localizations.pdfSignaturePadDialogSaveLabel, style: Theme.of(context).textTheme.bodyMedium!.copyWith( - fontSize: 14, - fontWeight: isMaterial3 ? FontWeight.w400 : null, - color: isMaterial3 + fontSize: 14, + fontWeight: isMaterial3 ? FontWeight.w400 : null, + color: + isMaterial3 ? themeData.colorScheme.onPrimary : themeData.colorScheme.primary, - fontFamily: 'Roboto-Medium', - ), + fontFamily: 'Roboto-Medium', + ), ), ), ], @@ -681,13 +704,15 @@ List _addStrokeColorPalettes( shape: BoxShape.circle, ), child: InkWell( - onTap: () => stateChanged(() { - _strokeColor = _strokeColors[i]; - _selectedPenIndex = i; - }), - overlayColor: isMaterial3 - ? const WidgetStatePropertyAll(Colors.transparent) - : null, + onTap: + () => stateChanged(() { + _strokeColor = _strokeColors[i]; + _selectedPenIndex = i; + }), + overlayColor: + isMaterial3 + ? const WidgetStatePropertyAll(Colors.transparent) + : null, child: Center( child: Stack( children: [ @@ -703,18 +728,18 @@ List _addStrokeColorPalettes( if (_selectedPenIndex == i) isMaterial3 ? Icon( - Icons.circle_outlined, - size: 32.0, - color: Theme.of(context).colorScheme.primary, - ) + Icons.circle_outlined, + size: 32.0, + color: Theme.of(context).colorScheme.primary, + ) : const Padding( - padding: EdgeInsets.all(5), - child: Icon( - Icons.check, - size: 15.0, - color: Colors.white, - ), - ) + padding: EdgeInsets.all(5), + child: Icon( + Icons.check, + size: 15.0, + color: Colors.white, + ), + ) else const SizedBox(width: 8), ], diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_text_box.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_text_box.dart index 4658f9748..abd7e2d87 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_text_box.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/form_fields/pdf_text_box.dart @@ -36,9 +36,10 @@ class PdfTextFormField extends PdfFormField { } /// Gets the child items associated with this [PdfTextFormField]. - List? get children => _children != null - ? List.unmodifiable(_children!) - : null; + List? get children => + _children != null + ? List.unmodifiable(_children!) + : null; } /// Helper class for [PdfTextFormField]. @@ -99,13 +100,13 @@ class PdfTextFormFieldHelper extends PdfFormFieldHelper { onKeyEvent: (FocusNode focusNode, KeyEvent event) { final bool isControlOrMeta = HardwareKeyboard.instance.isControlPressed || - HardwareKeyboard.instance.isMetaPressed; + HardwareKeyboard.instance.isMetaPressed; final bool isLogicalOrPhysicalZ = event.logicalKey == LogicalKeyboardKey.keyZ || - event.physicalKey == PhysicalKeyboardKey.keyZ; + event.physicalKey == PhysicalKeyboardKey.keyZ; final bool isLogicalOrPhysicalY = event.logicalKey == LogicalKeyboardKey.keyY || - event.physicalKey == PhysicalKeyboardKey.keyY; + event.physicalKey == PhysicalKeyboardKey.keyY; if (isControlOrMeta && isLogicalOrPhysicalZ) { if (event is KeyDownEvent) { @@ -122,10 +123,10 @@ class PdfTextFormFieldHelper extends PdfFormFieldHelper { } }, )..addListener(() { - if (!focusNode.hasFocus) { - invokeFocusChange(focusNode.hasFocus); - } - }); + if (!focusNode.hasFocus) { + invokeFocusChange(focusNode.hasFocus); + } + }); } /// Updates the text form field. @@ -196,30 +197,35 @@ class PdfTextFormFieldHelper extends PdfFormFieldHelper { font: pdfTextField.font.name, fontSize: pdfTextField.font.size / heightPercentage, isPassword: pdfTextField.isPassword, - fillColor: pdfTextField.backColor.isEmpty - ? const Color.fromARGB(255, 221, 228, 255) - : Color.fromRGBO( - pdfTextField.backColor.r, - pdfTextField.backColor.g, - pdfTextField.backColor.b, - 1, - ), - borderColor: pdfTextField.borderColor.isEmpty - ? Colors.transparent - : Color.fromRGBO( - pdfTextField.borderColor.r, - pdfTextField.borderColor.g, - pdfTextField.borderColor.b, - 1, - ), + fillColor: + pdfTextField.backColor.isEmpty + ? pdfTextField.readOnly + ? Colors.transparent + : const Color.fromARGB(255, 221, 228, 255) + : Color.fromRGBO( + pdfTextField.backColor.r, + pdfTextField.backColor.g, + pdfTextField.backColor.b, + 1, + ), + borderColor: + pdfTextField.borderColor.isEmpty + ? Colors.transparent + : Color.fromRGBO( + pdfTextField.borderColor.r, + pdfTextField.borderColor.g, + pdfTextField.borderColor.b, + 1, + ), borderWidth: pdfTextField.borderWidth / heightPercentage, textAlign: pdfTextField.textAlignment.textAlign, multiline: pdfTextField.multiline, maxLength: pdfTextField.maxLength, - letterSpacing: pdfTextField.insertSpaces && pdfTextField.maxLength > 1 - ? (pdfTextField.bounds.width / pdfTextField.maxLength - 1) / - heightPercentage - : null, + letterSpacing: + pdfTextField.insertSpaces && pdfTextField.maxLength > 1 + ? (pdfTextField.bounds.width / pdfTextField.maxLength - 1) / + heightPercentage + : null, onValueChanged: invokeValueChanged, onFocusChange: invokeFocusChange, ), @@ -323,11 +329,12 @@ class _PdfTextBoxState extends State { cursorColor: Colors.black, obscureText: widget.isPassword, onChanged: widget.onValueChanged, - inputFormatters: widget.maxLength > 0 - ? [ - LengthLimitingTextInputFormatter(widget.maxLength), - ] - : null, + inputFormatters: + widget.maxLength > 0 + ? [ + LengthLimitingTextInputFormatter(widget.maxLength), + ] + : null, keyboardType: widget.multiline ? TextInputType.multiline : TextInputType.text, scrollPhysics: widget.multiline ? const ClampingScrollPhysics() : null, @@ -335,25 +342,28 @@ class _PdfTextBoxState extends State { expands: widget.multiline, textAlignVertical: TextAlignVertical.top, textAlign: widget.textAlign, - style: widget.letterSpacing != null - ? TextStyle( - color: Colors.black, - fontFamily: 'RobotoMono', - package: 'syncfusion_flutter_pdfviewer', - fontSize: widget.fontSize, - letterSpacing: widget.letterSpacing! - widget.fontSize / 2, - ) - : TextStyle( - color: Colors.black, - fontFamily: widget.font, - fontSize: widget.fontSize, - ), + style: + widget.letterSpacing != null + ? TextStyle( + color: Colors.black, + fontFamily: 'RobotoMono', + package: 'syncfusion_flutter_pdfviewer', + fontSize: widget.fontSize, + letterSpacing: widget.letterSpacing! - widget.fontSize / 2, + ) + : TextStyle( + color: Colors.black, + fontFamily: widget.font, + fontSize: widget.fontSize, + ), decoration: InputDecoration( filled: true, fillColor: widget.fillColor, - contentPadding: widget.multiline - ? const EdgeInsets.all(3) - : widget.letterSpacing != null + hoverColor: widget.readOnly ? Colors.transparent : null, + contentPadding: + widget.multiline + ? const EdgeInsets.all(3) + : widget.letterSpacing != null ? EdgeInsets.zero : const EdgeInsets.symmetric(horizontal: 3), enabledBorder: OutlineInputBorder( diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/pdfviewer.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/pdfviewer.dart index c2a428178..2789bc5da 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/pdfviewer.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/pdfviewer.dart @@ -21,7 +21,8 @@ import 'bookmark/bookmark_view.dart'; import 'change_tracker/change_command.dart'; import 'change_tracker/change_tracker.dart'; import 'common/mobile_helper.dart' - if (dart.library.js_interop) 'common/web_helper.dart' as helper; + if (dart.library.js_interop) 'common/web_helper.dart' + as helper; import 'common/pdf_source.dart'; import 'common/pdfviewer_helper.dart'; import 'common/pdfviewer_plugin.dart'; @@ -45,20 +46,20 @@ import 'text_extraction/text_extraction.dart'; import 'theme/theme.dart'; /// Signature for [SfPdfViewer.onTextSelectionChanged] callback. -typedef PdfTextSelectionChangedCallback = void Function( - PdfTextSelectionChangedDetails details); +typedef PdfTextSelectionChangedCallback = + void Function(PdfTextSelectionChangedDetails details); /// Signature for [SfPdfViewer.onHyperlinkClicked] callback. -typedef PdfHyperlinkClickedCallback = void Function( - PdfHyperlinkClickedDetails details); +typedef PdfHyperlinkClickedCallback = + void Function(PdfHyperlinkClickedDetails details); /// Signature for [SfPdfViewer.onDocumentLoaded] callback. -typedef PdfDocumentLoadedCallback = void Function( - PdfDocumentLoadedDetails details); +typedef PdfDocumentLoadedCallback = + void Function(PdfDocumentLoadedDetails details); /// Signature for [SfPdfViewer.onDocumentLoadFailed] callback. -typedef PdfDocumentLoadFailedCallback = void Function( - PdfDocumentLoadFailedDetails details); +typedef PdfDocumentLoadFailedCallback = + void Function(PdfDocumentLoadFailedDetails details); /// Signature for [SfPdfViewer.onZoomLevelChanged] callback. typedef PdfZoomLevelChangedCallback = void Function(PdfZoomDetails details); @@ -73,12 +74,12 @@ typedef _PdfControllerListener = void Function({String? property}); typedef PdfGestureTapCallback = void Function(PdfGestureDetails details); /// Signature for [SfPdfViewer.onFormFieldValueChanged] callback. -typedef PdfFormFieldValueChangedCallback = void Function( - PdfFormFieldValueChangedDetails details); +typedef PdfFormFieldValueChangedCallback = + void Function(PdfFormFieldValueChangedDetails details); /// Signature for [SfPdfViewer.onFormFieldFocusChange] callback. -typedef PdfFormFieldFocusChangeCallback = void Function( - PdfFormFieldFocusChangeDetails details); +typedef PdfFormFieldFocusChangeCallback = + void Function(PdfFormFieldFocusChangeDetails details); /// Signature for [SfPdfViewer.onAnnotationAdded], [SfPdfViewer.onAnnotationSelected], [SfPdfViewer.onAnnotationDeselected], [SfPdfViewer.onAnnotationEdited] and [SfPdfViewer.onAnnotationRemoved] callbacks. typedef PdfAnnotationCallback = void Function(Annotation annotation); @@ -188,11 +189,11 @@ class SfPdfViewer extends StatefulWidget { this.canShowHyperlinkDialog = true, this.enableHyperlinkNavigation = true, this.canShowTextSelectionMenu = true, - }) : _source = source, - assert(pageSpacing >= 0), - assert(!maxZoomLevel.isNaN), - assert(maxZoomLevel >= 1), - super(key: key); + }) : _source = source, + assert(pageSpacing >= 0), + assert(!maxZoomLevel.isNaN), + assert(maxZoomLevel >= 1), + super(key: key); /// Creates a widget that displays the PDF document obtained from an asset bundle. /// @@ -264,11 +265,11 @@ class SfPdfViewer extends StatefulWidget { this.canShowHyperlinkDialog = true, this.enableHyperlinkNavigation = true, this.canShowTextSelectionMenu = true, - }) : _source = AssetPDFSource(name, bundle: bundle), - assert(pageSpacing >= 0), - assert(!maxZoomLevel.isNaN), - assert(maxZoomLevel >= 1), - super(key: key); + }) : _source = AssetPDFSource(name, bundle: bundle), + assert(pageSpacing >= 0), + assert(!maxZoomLevel.isNaN), + assert(maxZoomLevel >= 1), + super(key: key); /// Creates a widget that displays the PDF document obtained from the network. /// @@ -340,11 +341,11 @@ class SfPdfViewer extends StatefulWidget { this.canShowHyperlinkDialog = true, this.enableHyperlinkNavigation = true, this.canShowTextSelectionMenu = true, - }) : _source = URLPDFSource(src, headers: headers), - assert(pageSpacing >= 0), - assert(!maxZoomLevel.isNaN), - assert(maxZoomLevel >= 1), - super(key: key); + }) : _source = URLPDFSource(src, headers: headers), + assert(pageSpacing >= 0), + assert(!maxZoomLevel.isNaN), + assert(maxZoomLevel >= 1), + super(key: key); /// Creates a widget that displays the PDF document obtained from [Uint8List]. /// @@ -415,11 +416,11 @@ class SfPdfViewer extends StatefulWidget { this.canShowHyperlinkDialog = true, this.enableHyperlinkNavigation = true, this.canShowTextSelectionMenu = true, - }) : _source = BytePDFSource(bytes), - assert(pageSpacing >= 0), - assert(!maxZoomLevel.isNaN), - assert(maxZoomLevel >= 1), - super(key: key); + }) : _source = BytePDFSource(bytes), + assert(pageSpacing >= 0), + assert(!maxZoomLevel.isNaN), + assert(maxZoomLevel >= 1), + super(key: key); /// Creates a widget that displays the PDF document obtained from [File]. /// @@ -493,17 +494,17 @@ class SfPdfViewer extends StatefulWidget { this.canShowHyperlinkDialog = true, this.enableHyperlinkNavigation = true, this.canShowTextSelectionMenu = true, - }) : _source = FilePDFSource(file), - // File is not supported on Flutter Web therefore neither this method. - assert( - !kIsWeb, - 'SfPdfViewer.file is not supported on Flutter Web. ' - 'Consider using either SfPdfViewer.asset or SfPdfViewer.memory or SfPdfViewer.network instead.', - ), - assert(pageSpacing >= 0), - assert(!maxZoomLevel.isNaN), - assert(maxZoomLevel >= 1), - super(key: key); + }) : _source = FilePDFSource(file), + // File is not supported on Flutter Web therefore neither this method. + assert( + !kIsWeb, + 'SfPdfViewer.file is not supported on Flutter Web. ' + 'Consider using either SfPdfViewer.asset or SfPdfViewer.memory or SfPdfViewer.network instead.', + ), + assert(pageSpacing >= 0), + assert(!maxZoomLevel.isNaN), + assert(maxZoomLevel >= 1), + super(key: key); /// PDF file provider. final PDFSource _source; @@ -1275,6 +1276,8 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { Isolate? _textSearchIsolate; bool _isTablet = false; bool _isAndroidTV = false; + bool _isAndroid = false; + bool? _isAtLeastApiLevel35; final Map _textBoxFocusNodes = {}; bool _isLoaded = false; @@ -1288,7 +1291,6 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { bool _isTextDirectionChanged = false; Timer? _tileTimer; late TransformationControllerExt _transformationController; - bool _isAccessibilityEnabled = false; /// PdfViewer theme data. SfPdfViewerThemeData? _pdfViewerThemeData; @@ -1343,20 +1345,24 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { /// Instance of [TextSelectionHelper]. final TextSelectionHelper _textSelectionHelper = TextSelectionHelper(); + /// Password used to open the encrypted PDF document. + String? _password; + @override void initState() { super.initState(); if (kIsDesktop && !_isMobileView) { helper.preventDefaultMenu(); } - _transformationController = TransformationControllerExt() - ..addListener(_updateScrollOffset); + _transformationController = + TransformationControllerExt()..addListener(_updateScrollOffset); _plugin = PdfViewerPlugin(); - _scrollDirection = widget.scrollDirection != null - ? widget.scrollDirection! - : (widget.pageLayoutMode == PdfPageLayoutMode.single - ? PdfScrollDirection.horizontal - : PdfScrollDirection.vertical); + _scrollDirection = + widget.scrollDirection != null + ? widget.scrollDirection! + : (widget.pageLayoutMode == PdfPageLayoutMode.single + ? PdfScrollDirection.horizontal + : PdfScrollDirection.vertical); _tempScrollDirection = _scrollDirection; _pageLayoutMode = widget.pageLayoutMode; _pdfViewerController = widget.controller ?? PdfViewerController(); @@ -1367,6 +1373,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _hasError = false; _isLoaded = false; _panEnabled = true; + _isAndroid = !kIsWeb && Platform.isAndroid; _loadPdfDocument(false, false); _previousPageNumber = 1; _maxPdfPageWidth = 0; @@ -1387,11 +1394,12 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _textDirection = newTextDirection; _themeData = Theme.of(context); - _effectiveThemeData = _themeData!.useMaterial3 - ? SfPdfViewerThemeDataM3(context) - : SfPdfViewerThemeDataM2(context); + _effectiveThemeData = + _themeData!.useMaterial3 + ? SfPdfViewerThemeDataM3(context) + : SfPdfViewerThemeDataM2(context); _localizations = SfLocalizations.of(context); - _isAccessibilityEnabled = MediaQuery.accessibleNavigationOf(context); + if (_textSelectionOverlayEntry != null) { Future.delayed(Duration.zero, _checkPositionOfTextSelectionMenu); } @@ -1446,11 +1454,12 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { oldWidget.pageLayoutMode, ); } - _scrollDirection = widget.scrollDirection != null - ? widget.scrollDirection! - : (widget.pageLayoutMode == PdfPageLayoutMode.single - ? PdfScrollDirection.horizontal - : PdfScrollDirection.vertical); + _scrollDirection = + widget.scrollDirection != null + ? widget.scrollDirection! + : (widget.pageLayoutMode == PdfPageLayoutMode.single + ? PdfScrollDirection.horizontal + : PdfScrollDirection.vertical); Future.delayed(Durations.short4, _getTileImage); if (oldWidget.canShowTextSelectionMenu != widget.canShowTextSelectionMenu) { @@ -1489,6 +1498,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { final Uint8List newBytes = await newBytesData; if (!listEquals(oldBytes, newBytes) || (widget.password != null && widget.password != oldPassword)) { + _password = null; _pdfViewerController.clearSelection(); // PDF document gets loaded only when the user changes // the input source of PDF document. @@ -1527,9 +1537,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _stickyNoteFocusNode.dispose(); _document?.dispose(); _document = null; - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.canvasRenderBox + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.canvasRenderBox ?.disposeSelection(); if (widget.onTextSelectionChanged != null) { widget.onTextSelectionChanged!( @@ -1567,9 +1575,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { /// Reset when PDF path is changed. void _reset() { - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.canvasRenderBox + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.canvasRenderBox ?.disposeMouseSelection(); _isLoaded = false; _textExtractionEngine?.dispose(); @@ -1656,12 +1662,13 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { PdfFormFieldHelper.getHelper(textFormField) as PdfTextFormFieldHelper; - final List groupedItems = groupedTextFormFields - .where( - (PdfTextFormField groupedTextFormField) => - groupedTextFormField != textFormField, - ) - .toList(); + final List groupedItems = + groupedTextFormFields + .where( + (PdfTextFormField groupedTextFormField) => + groupedTextFormField != textFormField, + ) + .toList(); helper.textFormFieldChildItems = groupedItems; } @@ -1691,11 +1698,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (item is PdfCheckBoxItem) { final PdfCheckboxFormFieldHelper groupedItemHelper = PdfCheckboxFormFieldHelper( - field, - itemPageIndex, - pdfCheckBoxItem: item, - onValueChanged: _formFieldValueChanged, - ); + field, + itemPageIndex, + pdfCheckBoxItem: item, + onValueChanged: _formFieldValueChanged, + ); groupedItemHelper.bounds = item.bounds; final PdfCheckboxFormField groupedFormField = groupedItemHelper.getFormField(); @@ -1842,14 +1849,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { void _importFormFieldData() { final List formFieldValueChangeRecords = []; - for (int fieldIndex = 0; - fieldIndex < _document!.form.fields.count; - fieldIndex++) { + for ( + int fieldIndex = 0; + fieldIndex < _document!.form.fields.count; + fieldIndex++ + ) { final PdfField field = _document!.form.fields[fieldIndex]; - final List filteredFormFields = _pdfViewerController - ._formFields - .where((PdfFormField formField) => formField.name == field.name) - .toList(); + final List filteredFormFields = + _pdfViewerController._formFields + .where((PdfFormField formField) => formField.name == field.name) + .toList(); FormFieldValueChangeRecord? record; for (final PdfFormField formField in filteredFormFields) { @@ -1882,9 +1891,10 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } if (field is PdfComboBoxField && formField is PdfComboBoxFormField) { if (!formField.readOnly) { - final String selectedItem = field.selectedIndex != -1 - ? field.items[field.selectedIndex].text - : ''; + final String selectedItem = + field.selectedIndex != -1 + ? field.items[field.selectedIndex].text + : ''; record = _updateFormField(formField, selectedItem); } else { field.selectedValue = formField.selectedItem; @@ -1893,9 +1903,10 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (field is PdfRadioButtonListField && formField is PdfRadioFormField) { if (!formField.readOnly) { - final String selectedItem = field.selectedIndex != -1 - ? field.items[field.selectedIndex].value - : ''; + final String selectedItem = + field.selectedIndex != -1 + ? field.items[field.selectedIndex].value + : ''; record = _updateFormField(formField, selectedItem); } else { field.selectedValue = formField.selectedItem; @@ -2000,9 +2011,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { final PdfPage page = _document!.pages[pageIndex]; final int pageNumber = pageIndex + 1; final PdfAnnotationCollection annotations = page.annotations; - for (int annotationIndex = 0; - annotationIndex < annotations.count; - annotationIndex++) { + for ( + int annotationIndex = 0; + annotationIndex < annotations.count; + annotationIndex++ + ) { final PdfAnnotation pdfAnnotation = annotations[annotationIndex]; final Annotation? annotation = _createAnnotation( pdfAnnotation, @@ -2227,12 +2240,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (!_isEncrypted && !isDocumentSaved) { _getPdfFileCancellableOperation = CancelableOperation.fromFuture( - widget._source.getBytes(context), - ); + widget._source.getBytes(context), + ); + } + if (_isAndroid) { + await _getAndroidDeviceDetails(); } - _pdfBytes = _isEncrypted - ? _decryptedBytes - : isDocumentSaved + _pdfBytes = + _isEncrypted + ? _decryptedBytes + : isDocumentSaved ? _pdfBytes : (await _getPdfFileCancellableOperation?.value)!; if (isPdfChanged) { @@ -2253,6 +2270,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } final int pageCount = await _plugin.initializePdfRenderer( _renderDigitalSignatures() ?? _pdfBytes, + _password, ); _pdfViewerController._pageCount = pageCount; if (pageCount > 0) { @@ -2262,13 +2280,13 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _setInitialScrollOffset(); _getHeightCancellableOperation = CancelableOperation?>.fromFuture( - _plugin.getPagesHeight(), - ); + _plugin.getPagesHeight(), + ); _originalHeight = await _getHeightCancellableOperation?.value; _getWidthCancellableOperation = CancelableOperation?>.fromFuture( - _plugin.getPagesWidth(), - ); + _plugin.getPagesWidth(), + ); _originalWidth = await _getWidthCancellableOperation?.value; } catch (e) { _pdfViewerController._reset(); @@ -2398,34 +2416,36 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { final bool isMaterial3 = _themeData!.useMaterial3; return Container( decoration: BoxDecoration( - color: isMaterial3 - ? _themeData!.colorScheme.brightness == Brightness.light - ? const Color(0xFFA19CA5) - : const Color(0xFF221F27) - : (_themeData!.colorScheme.brightness == Brightness.light - ? const Color(0xFFD6D6D6) - : const Color(0xFF303030)), - boxShadow: isMaterial3 - ? [ - const BoxShadow( - offset: Offset(0, 1), - blurRadius: 3, - color: Color(0x4D000000), - ), - const BoxShadow( - offset: Offset(0, 4), - blurRadius: 8, - spreadRadius: 3, - color: Color(0x26000000), - ), - ] - : [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.3), - blurRadius: 3, - offset: const Offset(0, 1), - ), - ], + color: + isMaterial3 + ? _themeData!.colorScheme.brightness == Brightness.light + ? const Color(0xFFA19CA5) + : const Color(0xFF221F27) + : (_themeData!.colorScheme.brightness == Brightness.light + ? const Color(0xFFD6D6D6) + : const Color(0xFF303030)), + boxShadow: + isMaterial3 + ? [ + const BoxShadow( + offset: Offset(0, 1), + blurRadius: 3, + color: Color(0x4D000000), + ), + const BoxShadow( + offset: Offset(0, 4), + blurRadius: 8, + spreadRadius: 3, + color: Color(0x26000000), + ), + ] + : [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.3), + blurRadius: 3, + offset: const Offset(0, 1), + ), + ], ), child: Visibility( visible: _visibility, @@ -2434,58 +2454,67 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { height: isMaterial3 ? 264 : 230, width: isMaterial3 ? 360 : 345, decoration: BoxDecoration( - borderRadius: isMaterial3 - ? BorderRadius.circular(28) - : BorderRadius.circular(4), - color: isMaterial3 - ? _pdfViewerThemeData?.passwordDialogStyle?.backgroundColor ?? - _effectiveThemeData!.passwordDialogStyle?.backgroundColor - : (_themeData!.colorScheme.brightness == Brightness.light) + borderRadius: + isMaterial3 + ? BorderRadius.circular(28) + : BorderRadius.circular(4), + color: + isMaterial3 + ? _pdfViewerThemeData + ?.passwordDialogStyle + ?.backgroundColor ?? + _effectiveThemeData! + .passwordDialogStyle + ?.backgroundColor + : (_themeData!.colorScheme.brightness == Brightness.light) ? Colors.white : const Color(0xFF424242), ), child: Column( - mainAxisAlignment: isMaterial3 - ? MainAxisAlignment.start - : MainAxisAlignment.spaceBetween, + mainAxisAlignment: + isMaterial3 + ? MainAxisAlignment.start + : MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: Padding( - padding: isMaterial3 - ? const EdgeInsets.only(left: 24, top: 24) - : const EdgeInsets.only(left: 16, top: 10), + padding: + isMaterial3 + ? const EdgeInsets.only(left: 24, top: 24) + : const EdgeInsets.only(left: 16, top: 10), child: Text( _localizations!.passwordDialogHeaderTextLabel, - style: Theme.of(context) - .textTheme - .headlineMedium! + style: Theme.of(context).textTheme.headlineMedium! .copyWith( fontSize: isMaterial3 ? 24 : 20, - color: isMaterial3 - ? Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues( - alpha: 0.87, - ) - : Colors.white.withValues( - alpha: 0.87, - ) - : _themeData!.colorScheme.onSurface, + color: + isMaterial3 + ? Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues( + alpha: 0.87, + ) + : Colors.white.withValues( + alpha: 0.87, + ) + : _themeData!.colorScheme.onSurface, ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.headerTextStyle, + .passwordDialogStyle + ?.headerTextStyle, ), ), ), ), Padding( - padding: isMaterial3 - ? const EdgeInsets.fromLTRB(0, 24, 16, 0) - : const EdgeInsets.fromLTRB(0, 10, 16, 0), + padding: + isMaterial3 + ? const EdgeInsets.fromLTRB(0, 24, 16, 0) + : const EdgeInsets.fromLTRB(0, 10, 16, 0), child: SizedBox( height: isMaterial3 ? 40 : 36, width: isMaterial3 ? 40 : 36, @@ -2499,17 +2528,21 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _passwordVisible = true; }); }, - shape: isMaterial3 - ? RoundedRectangleBorder( - borderRadius: BorderRadius.circular(40), - ) - : const RoundedRectangleBorder(), + shape: + isMaterial3 + ? RoundedRectangleBorder( + borderRadius: BorderRadius.circular(40), + ) + : const RoundedRectangleBorder(), child: Icon( Icons.clear, - color: _pdfViewerThemeData - ?.passwordDialogStyle?.closeIconColor ?? + color: + _pdfViewerThemeData + ?.passwordDialogStyle + ?.closeIconColor ?? _effectiveThemeData - ?.passwordDialogStyle?.closeIconColor ?? + ?.passwordDialogStyle + ?.closeIconColor ?? _themeData?.colorScheme.onSurfaceVariant .withValues(alpha: 0.6), size: 24, @@ -2520,40 +2553,44 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { ], ), Padding( - padding: isMaterial3 - ? const EdgeInsets.fromLTRB(24, 8, 24, 4) - : const EdgeInsets.fromLTRB(16, 0, 16, 8), + padding: + isMaterial3 + ? const EdgeInsets.fromLTRB(24, 8, 24, 4) + : const EdgeInsets.fromLTRB(16, 0, 16, 8), child: Text( _localizations!.passwordDialogContentLabel, - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: isMaterial3 ? 14 : 16, - color: isMaterial3 - ? _themeData!.colorScheme.onSurfaceVariant - : Theme.of(context).brightness == Brightness.light + color: + isMaterial3 + ? _themeData!.colorScheme.onSurfaceVariant + : Theme.of(context).brightness == + Brightness.light ? Colors.black.withValues(alpha: 0.6) : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.contentTextStyle, + .passwordDialogStyle + ?.contentTextStyle, ), ), ), Padding( - padding: isMaterial3 - ? const EdgeInsets.fromLTRB(24, 10, 24, 8) - : const EdgeInsets.fromLTRB(16, 0, 16, 0), + padding: + isMaterial3 + ? const EdgeInsets.fromLTRB(24, 10, 24, 8) + : const EdgeInsets.fromLTRB(16, 0, 16, 0), child: _textField(), ), Padding( - padding: isMaterial3 - ? _errorTextPresent - ? const EdgeInsets.fromLTRB(24, 0, 32, 8) - : const EdgeInsets.fromLTRB(24, 19, 32, 8) - : const EdgeInsets.fromLTRB(0, 0, 16, 10), + padding: + isMaterial3 + ? _errorTextPresent + ? const EdgeInsets.fromLTRB(24, 0, 32, 8) + : const EdgeInsets.fromLTRB(24, 19, 32, 8) + : const EdgeInsets.fromLTRB(0, 0, 16, 10), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ @@ -2566,20 +2603,19 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _errorTextPresent = false; }); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPasswordDialogCancelLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: @@ -2588,66 +2624,69 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.cancelTextStyle, + .passwordDialogStyle + ?.cancelTextStyle, ), ), ), TextButton( - onPressed: isMaterial3 - ? (_isPasswordDialogOpenButtonEnabled - ? () { - _passwordValidation( - _textFieldController.text, - ); - } - : null) - : () { - _passwordValidation( - _textFieldController.text, - ); - }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + onPressed: + isMaterial3 + ? (_isPasswordDialogOpenButtonEnabled + ? () { + _passwordValidation( + _textFieldController.text, + ); + } + : null) + : () { + _passwordValidation( + _textFieldController.text, + ); + }, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPasswordDialogOpenLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, - color: isMaterial3 - ? (_isPasswordDialogOpenButtonEnabled - ? Theme.of( - context, - ).colorScheme.primary - : Theme.of(context).brightness == + color: + isMaterial3 + ? (_isPasswordDialogOpenButtonEnabled + ? Theme.of( + context, + ).colorScheme.primary + : Theme.of(context).brightness == Brightness.light ? const Color.fromRGBO( - 28, - 27, - 31, - 1, - ).withValues(alpha: 0.38) + 28, + 27, + 31, + 1, + ).withValues(alpha: 0.38) : const Color.fromRGBO( - 230, - 225, - 229, - 1, - ).withValues(alpha: 0.38)) - : Theme.of(context).colorScheme.primary, + 230, + 225, + 229, + 1, + ).withValues(alpha: 0.38)) + : Theme.of(context).colorScheme.primary, ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.openTextStyle, + .passwordDialogStyle + ?.openTextStyle, ), ), ), @@ -2669,14 +2708,13 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { width: isMaterial3 ? 360 : 296, height: isMaterial3 ? 70 : null, child: TextFormField( - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 17, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData!.passwordDialogStyle?.inputFieldTextStyle, @@ -2684,25 +2722,29 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { obscureText: _passwordVisible, obscuringCharacter: '*', decoration: InputDecoration( - contentPadding: isMaterial3 - ? const EdgeInsets.symmetric(vertical: 20, horizontal: 20) - : null, + contentPadding: + isMaterial3 + ? const EdgeInsets.symmetric(vertical: 20, horizontal: 20) + : null, isDense: true, border: OutlineInputBorder( borderSide: BorderSide( width: isMaterial3 ? 2 : 1, - color: _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? _effectiveThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? + .passwordDialogStyle + ?.inputFieldBorderColor ?? _themeData!.colorScheme.primary, ), ), errorBorder: OutlineInputBorder( borderSide: BorderSide( width: isMaterial3 ? 2 : 1, - color: _pdfViewerThemeData! - .passwordDialogStyle?.errorBorderColor ?? + color: + _pdfViewerThemeData!.passwordDialogStyle?.errorBorderColor ?? _effectiveThemeData!.passwordDialogStyle?.errorBorderColor ?? _themeData!.colorScheme.error, ), @@ -2710,57 +2752,58 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { focusedBorder: OutlineInputBorder( borderSide: BorderSide( width: isMaterial3 ? 2 : 1, - color: _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.inputFieldBorderColor ?? _effectiveThemeData! - .passwordDialogStyle?.inputFieldBorderColor ?? + .passwordDialogStyle + ?.inputFieldBorderColor ?? _themeData!.colorScheme.primary, ), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide( width: isMaterial3 ? 2 : 1, - color: _pdfViewerThemeData! - .passwordDialogStyle?.errorBorderColor ?? + color: + _pdfViewerThemeData!.passwordDialogStyle?.errorBorderColor ?? _effectiveThemeData!.passwordDialogStyle?.errorBorderColor ?? _themeData!.colorScheme.error, ), ), hintText: _localizations!.passwordDialogHintTextLabel, errorText: _errorTextPresent ? 'Invalid Password' : null, - hintStyle: Theme.of(context) - .textTheme - .titleMedium! + hintStyle: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: isMaterial3 - ? _themeData!.colorScheme.onSurfaceVariant - : Theme.of(context).brightness == Brightness.light + color: + isMaterial3 + ? _themeData!.colorScheme.onSurfaceVariant + : Theme.of(context).brightness == Brightness.light ? Colors.black.withValues(alpha: 0.6) : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldHintTextStyle, + .passwordDialogStyle + ?.inputFieldHintTextStyle, ), labelText: isMaterial3 ? null : _localizations!.passwordDialogHintTextLabel, - labelStyle: Theme.of(context) - .textTheme - .headlineMedium! + labelStyle: Theme.of(context).textTheme.headlineMedium! .copyWith( fontSize: 18, - color: Theme.of(context).brightness == Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldLabelTextStyle, + .passwordDialogStyle + ?.inputFieldLabelTextStyle, ), - errorStyle: Theme.of(context) - .textTheme - .bodyMedium! + errorStyle: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: isMaterial3 ? 12 : 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -2778,10 +2821,13 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { : (isMaterial3 ? Icons.visibility_off_outlined : Icons.visibility_off), - color: _pdfViewerThemeData! - .passwordDialogStyle?.visibleIconColor ?? + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.visibleIconColor ?? _effectiveThemeData! - .passwordDialogStyle?.visibleIconColor ?? + .passwordDialogStyle + ?.visibleIconColor ?? Theme.of( context, ).colorScheme.onSurface.withValues(alpha: 0.6), @@ -2802,13 +2848,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { onFieldSubmitted: (String value) { _passwordValidation(value); }, - onChanged: isMaterial3 - ? (String value) { - setState(() { - _isPasswordDialogOpenButtonEnabled = value.isNotEmpty; - }); - } - : null, + onChanged: + isMaterial3 + ? (String value) { + setState(() { + _isPasswordDialogOpenButtonEnabled = value.isNotEmpty; + }); + } + : null, ), ); } @@ -2863,14 +2910,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { child: AlertDialog( scrollable: true, insetPadding: EdgeInsets.zero, - contentPadding: orientation == Orientation.portrait - ? const EdgeInsets.all(24) - : const EdgeInsets.only(right: 24, left: 24), - buttonPadding: orientation == Orientation.portrait - ? const EdgeInsets.all(8) - : const EdgeInsets.all(4), - backgroundColor: _pdfViewerThemeData! - .passwordDialogStyle?.backgroundColor ?? + contentPadding: + orientation == Orientation.portrait + ? const EdgeInsets.all(24) + : const EdgeInsets.only(right: 24, left: 24), + buttonPadding: + orientation == Orientation.portrait + ? const EdgeInsets.all(8) + : const EdgeInsets.all(4), + backgroundColor: + _pdfViewerThemeData!.passwordDialogStyle?.backgroundColor ?? _effectiveThemeData!.passwordDialogStyle?.backgroundColor ?? (isMaterial3 ? _themeData!.colorScheme.brightness == Brightness.light @@ -2886,22 +2935,22 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { Expanded( child: Text( _localizations!.passwordDialogHeaderTextLabel, - style: Theme.of(context) - .textTheme - .headlineMedium! + style: Theme.of(context).textTheme.headlineMedium! .copyWith( fontSize: isMaterial3 ? 24 : 20, fontWeight: isMaterial3 ? FontWeight.w500 : null, - color: isMaterial3 - ? Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87) - : _themeData!.colorScheme.onSurface, + color: + isMaterial3 + ? Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87) + : _themeData!.colorScheme.onSurface, ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.headerTextStyle, + .passwordDialogStyle + ?.headerTextStyle, ), ), ), @@ -2914,17 +2963,21 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _textFieldController.clear(); Navigator.of(context).pop(); }, - shape: isMaterial3 - ? RoundedRectangleBorder( - borderRadius: BorderRadius.circular(40), - ) - : const RoundedRectangleBorder(), + shape: + isMaterial3 + ? RoundedRectangleBorder( + borderRadius: BorderRadius.circular(40), + ) + : const RoundedRectangleBorder(), child: Icon( Icons.clear, - color: _pdfViewerThemeData! - .passwordDialogStyle?.closeIconColor ?? + color: + _pdfViewerThemeData! + .passwordDialogStyle + ?.closeIconColor ?? _effectiveThemeData! - .passwordDialogStyle?.closeIconColor ?? + .passwordDialogStyle + ?.closeIconColor ?? _themeData!.colorScheme.onSurfaceVariant, size: 24, ), @@ -2932,42 +2985,47 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { ), ], ), - shape: isMaterial3 - ? RoundedRectangleBorder( - borderRadius: BorderRadius.circular(28), - ) - : const RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(4.0)), - ), + shape: + isMaterial3 + ? RoundedRectangleBorder( + borderRadius: BorderRadius.circular(28), + ) + : const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(4.0)), + ), content: SizedBox( width: 328, child: Column( children: [ Align( - alignment: textDirection == TextDirection.ltr - ? Alignment.centerLeft - : Alignment.centerRight, + alignment: + textDirection == TextDirection.ltr + ? Alignment.centerLeft + : Alignment.centerRight, child: Padding( - padding: isMaterial3 - ? const EdgeInsets.fromLTRB(0, 0, 0, 8) - : const EdgeInsets.fromLTRB(0, 0, 0, 24), + padding: + isMaterial3 + ? const EdgeInsets.fromLTRB(0, 0, 0, 8) + : const EdgeInsets.fromLTRB(0, 0, 0, 24), child: Text( _localizations!.passwordDialogContentLabel, - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: isMaterial3 ? 14 : 16, - color: isMaterial3 - ? _themeData!.colorScheme.onSurfaceVariant - : Theme.of(context).brightness == + color: + isMaterial3 + ? _themeData! + .colorScheme + .onSurfaceVariant + : Theme.of(context).brightness == Brightness.light ? Colors.black.withValues(alpha: 0.6) : Colors.white.withValues(alpha: 0.6), ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.contentTextStyle, + .passwordDialogStyle + ?.contentTextStyle, ), ), ), @@ -2975,28 +3033,31 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { Form( key: _formKey, child: TextFormField( - style: Theme.of(context) - .textTheme - .titleMedium! + style: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 17, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues(alpha: 0.87), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues(alpha: 0.87), ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.inputFieldTextStyle, + .passwordDialogStyle + ?.inputFieldTextStyle, ), obscureText: _passwordVisible, obscuringCharacter: '*', decoration: InputDecoration( border: OutlineInputBorder( borderSide: BorderSide( - color: _pdfViewerThemeData!.passwordDialogStyle + color: + _pdfViewerThemeData! + .passwordDialogStyle ?.inputFieldBorderColor ?? - _effectiveThemeData!.passwordDialogStyle + _effectiveThemeData! + .passwordDialogStyle ?.inputFieldBorderColor ?? _themeData!.colorScheme.primary, ), @@ -3004,78 +3065,92 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { errorBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(3.5), borderSide: BorderSide( - color: _pdfViewerThemeData!.passwordDialogStyle + color: + _pdfViewerThemeData! + .passwordDialogStyle ?.errorBorderColor ?? - _effectiveThemeData!.passwordDialogStyle + _effectiveThemeData! + .passwordDialogStyle ?.errorBorderColor ?? _themeData!.colorScheme.error, ), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide( - color: _pdfViewerThemeData!.passwordDialogStyle + color: + _pdfViewerThemeData! + .passwordDialogStyle ?.inputFieldBorderColor ?? - _effectiveThemeData!.passwordDialogStyle + _effectiveThemeData! + .passwordDialogStyle ?.inputFieldBorderColor ?? _themeData!.colorScheme.primary, ), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide( - color: _pdfViewerThemeData!.passwordDialogStyle + color: + _pdfViewerThemeData! + .passwordDialogStyle ?.errorBorderColor ?? - _effectiveThemeData!.passwordDialogStyle + _effectiveThemeData! + .passwordDialogStyle ?.errorBorderColor ?? _themeData!.colorScheme.error, ), ), hintText: _localizations!.passwordDialogHintTextLabel, - hintStyle: Theme.of(context) - .textTheme - .titleMedium! + hintStyle: Theme.of(context).textTheme.titleMedium! .copyWith( fontSize: 16, - color: isMaterial3 - ? _themeData!.colorScheme.onSurfaceVariant - : Theme.of(context).brightness == + color: + isMaterial3 + ? _themeData! + .colorScheme + .onSurfaceVariant + : Theme.of(context).brightness == Brightness.light ? Colors.black.withValues(alpha: 0.6) : Colors.white.withValues(alpha: 0.6), ) .merge( - _pdfViewerThemeData!.passwordDialogStyle + _pdfViewerThemeData! + .passwordDialogStyle ?.inputFieldHintTextStyle, ), - labelText: isMaterial3 - ? null - : _localizations!.passwordDialogHintTextLabel, + labelText: + isMaterial3 + ? null + : _localizations! + .passwordDialogHintTextLabel, labelStyle: Theme.of(context) .textTheme .headlineMedium! .copyWith( fontSize: 18, - color: Theme.of(context).brightness == - Brightness.light - ? Colors.black.withValues(alpha: 0.87) - : Colors.white.withValues( - alpha: 0.87, - ), + color: + Theme.of(context).brightness == + Brightness.light + ? Colors.black.withValues(alpha: 0.87) + : Colors.white.withValues( + alpha: 0.87, + ), ) .merge( - _pdfViewerThemeData!.passwordDialogStyle + _pdfViewerThemeData! + .passwordDialogStyle ?.inputFieldLabelTextStyle, ), - errorStyle: Theme.of(context) - .textTheme - .bodyMedium! + errorStyle: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: isMaterial3 ? 12 : 14, color: _themeData!.colorScheme.error, ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.errorTextStyle, + .passwordDialogStyle + ?.errorTextStyle, ), suffixIcon: IconButton( icon: Icon( @@ -3087,13 +3162,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { : (isMaterial3 ? Icons.visibility_off_outlined : Icons.visibility_off), - color: _pdfViewerThemeData!.passwordDialogStyle + color: + _pdfViewerThemeData! + .passwordDialogStyle ?.visibleIconColor ?? - _effectiveThemeData!.passwordDialogStyle + _effectiveThemeData! + .passwordDialogStyle ?.visibleIconColor ?? - Theme.of(context) - .colorScheme - .onSurface + Theme.of(context).colorScheme.onSurface .withValues(alpha: 0.6), ), onPressed: () { @@ -3110,14 +3186,15 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { onFieldSubmitted: (String value) { _handlePasswordValidation(); }, - onChanged: isMaterial3 - ? (String value) { - setState(() { - _isPasswordDialogOpenButtonEnabled = - value.isNotEmpty; - }); - } - : null, + onChanged: + isMaterial3 + ? (String value) { + setState(() { + _isPasswordDialogOpenButtonEnabled = + value.isNotEmpty; + }); + } + : null, validator: (String? value) { try { _decryptedProtectedDocument(_pdfBytes, value); @@ -3160,20 +3237,19 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _textFieldController.clear(); Navigator.of(context).pop(); }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPasswordDialogCancelLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, @@ -3181,63 +3257,66 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.cancelTextStyle, + .passwordDialogStyle + ?.cancelTextStyle, ), ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 0, 8, 0), child: TextButton( - onPressed: isMaterial3 - ? (_isPasswordDialogOpenButtonEnabled - ? () { - _handlePasswordValidation(); - } - : () {}) - : () { - _handlePasswordValidation(); - }, - style: isMaterial3 - ? TextButton.styleFrom( - fixedSize: const Size(double.infinity, 40), - padding: const EdgeInsets.symmetric( - vertical: 10, - horizontal: 20, - ), - ) - : null, + onPressed: + isMaterial3 + ? (_isPasswordDialogOpenButtonEnabled + ? () { + _handlePasswordValidation(); + } + : () {}) + : () { + _handlePasswordValidation(); + }, + style: + isMaterial3 + ? TextButton.styleFrom( + fixedSize: const Size(double.infinity, 40), + padding: const EdgeInsets.symmetric( + vertical: 10, + horizontal: 20, + ), + ) + : null, child: Text( _localizations!.pdfPasswordDialogOpenLabel, - style: Theme.of(context) - .textTheme - .bodyMedium! + style: Theme.of(context).textTheme.bodyMedium! .copyWith( fontSize: 14, fontWeight: isMaterial3 ? FontWeight.w500 : null, - color: isMaterial3 - ? (_isPasswordDialogOpenButtonEnabled - ? Theme.of( - context, - ).colorScheme.primary - : Theme.of(context).brightness == + color: + isMaterial3 + ? (_isPasswordDialogOpenButtonEnabled + ? Theme.of( + context, + ).colorScheme.primary + : Theme.of(context).brightness == Brightness.light ? const Color.fromRGBO( - 28, - 27, - 31, - 1, - ).withValues(alpha: 0.38) + 28, + 27, + 31, + 1, + ).withValues(alpha: 0.38) : const Color.fromRGBO( - 230, - 225, - 229, - 1, - ).withValues(alpha: 0.38)) - : Theme.of(context).colorScheme.primary, + 230, + 225, + 229, + 1, + ).withValues(alpha: 0.38)) + : Theme.of(context).colorScheme.primary, ) .merge( _pdfViewerThemeData! - .passwordDialogStyle?.openTextStyle, + .passwordDialogStyle + ?.openTextStyle, ), ), ), @@ -3259,16 +3338,35 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } } + /// To check whether the Android device version is 35 or more + Future _getAndroidDeviceDetails() async { + if (_isAndroid && _isAtLeastApiLevel35 == null) { + final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); + final AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo; + _isAtLeastApiLevel35 = androidInfo.version.sdkInt >= 35; + } + } + ///Decrypt the password protected document. void _decryptedProtectedDocument(Uint8List pdfBytes, String? password) { final PdfDocument document = PdfDocument( inputBytes: pdfBytes, password: password, ); - document.security.userPassword = ''; - document.security.ownerPassword = ''; - final List bytes = document.saveSync(); - _decryptedBytes = Uint8List.fromList(bytes); + if (_isAndroid && !(_isAtLeastApiLevel35 ??= false)) { + if (helper.isPdfiumLoaded()) { + _decryptedBytes = pdfBytes; + _password = password; + } else { + document.security.userPassword = ''; + document.security.ownerPassword = ''; + _decryptedBytes = document.saveAsBytesSync(); + } + } else { + _decryptedBytes = pdfBytes; + _password = password; + } + document.dispose(); _isEncrypted = true; _loadPdfDocument(true, false); } @@ -3276,7 +3374,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { /// Get the file of the Pdf. Future _getPdfFile(Uint8List? value) async { if (value != null) { - return PdfDocument(inputBytes: value); + return PdfDocument(inputBytes: value, password: _password); } return null; } @@ -3295,12 +3393,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } else if (_layoutChangeOffset != Offset.zero && (!_pdfDimension.isEmpty && _pdfScrollableStateKey.currentState != null)) { - final double xOffset = _scrollDirection != PdfScrollDirection.vertical - ? _pdfPages[_previousSinglePage]!.pageOffset - : 0; - final double yOffset = _scrollDirection == PdfScrollDirection.vertical - ? _pdfPages[_previousSinglePage]!.pageOffset - : 0; + final double xOffset = + _scrollDirection != PdfScrollDirection.vertical + ? _pdfPages[_previousSinglePage]!.pageOffset + : 0; + final double yOffset = + _scrollDirection == PdfScrollDirection.vertical + ? _pdfPages[_previousSinglePage]!.pageOffset + : 0; _pdfScrollableStateKey.currentState!.jumpTo( xOffset: xOffset + _layoutChangeOffset.dx, yOffset: yOffset + _layoutChangeOffset.dy, @@ -3369,7 +3469,8 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (kIsWeb && _isMobileWebView == null) { final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); final WebBrowserInfo webBrowserInfo = await deviceInfo.webBrowserInfo; - _isMobileWebView = defaultTargetPlatform == TargetPlatform.android || + _isMobileWebView = + defaultTargetPlatform == TargetPlatform.android || defaultTargetPlatform == TargetPlatform.iOS || (defaultTargetPlatform == TargetPlatform.macOS && (webBrowserInfo.maxTouchPoints ?? 0) > 0); @@ -3393,8 +3494,9 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { viewportRenderBox = _singlePageViewKey.currentContext!.findRenderObject()! as RenderBox; } else { - viewportRenderBox = _pdfScrollableStateKey.currentContext! - .findRenderObject()! as RenderBox; + viewportRenderBox = + _pdfScrollableStateKey.currentContext!.findRenderObject()! + as RenderBox; } final Offset position = viewportRenderBox.localToGlobal(Offset.zero); if (viewportRenderBox.hasSize) { @@ -3412,7 +3514,8 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { Widget _getEmptyContainer() { return Container( - color: _pdfViewerThemeData!.backgroundColor ?? + color: + _pdfViewerThemeData!.backgroundColor ?? _effectiveThemeData!.backgroundColor ?? (_themeData!.colorScheme.brightness == Brightness.light ? const Color(0xFFD6D6D6) @@ -3449,14 +3552,15 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _effectiveThemeData!.progressBarColor ?? _themeData!.colorScheme.primary, ), - backgroundColor: _pdfViewerThemeData!.progressBarColor != null - ? _pdfViewerThemeData!.progressBarColor!.withValues( - alpha: 0.2, - ) - : _effectiveThemeData!.progressBarColor != null + backgroundColor: + _pdfViewerThemeData!.progressBarColor != null + ? _pdfViewerThemeData!.progressBarColor!.withValues( + alpha: 0.2, + ) + : _effectiveThemeData!.progressBarColor != null ? _effectiveThemeData!.progressBarColor!.withValues( - alpha: 0.2, - ) + alpha: 0.2, + ) : _themeData!.colorScheme.primary.withValues(alpha: 0.2), ), ], @@ -3467,411 +3571,411 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { Widget build(BuildContext context) { /// Find whether device is mobile or Laptop. _findDevice(context); - final bool isPdfLoaded = _pdfViewerController.pageCount > 0 && + final bool isPdfLoaded = + _pdfViewerController.pageCount > 0 && _originalWidth != null && _originalHeight != null; _pdfDimension = _childKey.currentContext?.findRenderObject()?.paintBounds.size ?? - Size.zero; + Size.zero; return isPdfLoaded ? Listener( - onPointerSignal: _handlePointerSignal, - onPointerDown: _handlePointerDown, - onPointerMove: _handlePointerMove, - onPointerUp: _handlePointerUp, - child: Container( - color: _pdfViewerThemeData!.backgroundColor ?? - _effectiveThemeData!.backgroundColor ?? - (_themeData!.colorScheme.brightness == Brightness.light - ? const Color(0xFFD6D6D6) - : const Color(0xFF303030)), - child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - _viewportConstraints = constraints; - if (_viewportSize != _viewportConstraints.biggest) { - _viewportSize = _viewportConstraints.biggest; - _getTileImage(); - } - double totalHeight = 0.0; - _isKeyPadRaised = View.of(context).viewInsets.bottom != 0.0; - Size viewportDimension = _viewportConstraints.biggest; - // Viewport dimension without keypad height. - Size? visibleViewportDimension; - if (_isKeyPadRaised) { - visibleViewportDimension = viewportDimension; - _iskeypadClosed = true; - double keyPadHeight = EdgeInsets.fromViewPadding( - View.of(context).viewInsets, - View.of(context).devicePixelRatio, - ).bottom; - if (keyPadHeight > 0) { - if (viewportDimension.height + keyPadHeight != - _viewportHeight) { - keyPadHeight = - _viewportHeight - viewportDimension.height; - } else { - _viewportHeight = - viewportDimension.height + keyPadHeight; - } + onPointerSignal: _handlePointerSignal, + onPointerDown: _handlePointerDown, + onPointerMove: _handlePointerMove, + onPointerUp: _handlePointerUp, + child: Container( + color: + _pdfViewerThemeData!.backgroundColor ?? + _effectiveThemeData!.backgroundColor ?? + (_themeData!.colorScheme.brightness == Brightness.light + ? const Color(0xFFD6D6D6) + : const Color(0xFF303030)), + child: LayoutBuilder( + builder: (BuildContext context, BoxConstraints constraints) { + _viewportConstraints = constraints; + if (_viewportSize != _viewportConstraints.biggest) { + _viewportSize = _viewportConstraints.biggest; + _getTileImage(); + } + double totalHeight = 0.0; + _isKeyPadRaised = View.of(context).viewInsets.bottom != 0.0; + Size viewportDimension = _viewportConstraints.biggest; + // Viewport dimension without keypad height. + Size? visibleViewportDimension; + if (_isKeyPadRaised) { + visibleViewportDimension = viewportDimension; + _iskeypadClosed = true; + double keyPadHeight = + EdgeInsets.fromViewPadding( + View.of(context).viewInsets, + View.of(context).devicePixelRatio, + ).bottom; + if (keyPadHeight > 0) { + if (viewportDimension.height + keyPadHeight != + _viewportHeight) { + keyPadHeight = _viewportHeight - viewportDimension.height; + } else { + _viewportHeight = viewportDimension.height + keyPadHeight; } + } + viewportDimension = Size( + viewportDimension.width, + viewportDimension.height + keyPadHeight, + ); + } else { + if (_iskeypadClosed) { viewportDimension = Size( viewportDimension.width, - viewportDimension.height + keyPadHeight, + _viewportHeight, ); + _iskeypadClosed = false; } else { - if (_iskeypadClosed) { - viewportDimension = Size( - viewportDimension.width, - _viewportHeight, - ); - _iskeypadClosed = false; - } else { - _viewportHeight = viewportDimension.height; - } + _viewportHeight = viewportDimension.height; } - if (!isBookmarkViewOpen) { - _otherContextHeight ??= MediaQuery.of(context).size.height - - _viewportConstraints.maxHeight; + } + if (!isBookmarkViewOpen) { + _otherContextHeight ??= + MediaQuery.of(context).size.height - + _viewportConstraints.maxHeight; + } + if (_deviceOrientation == Orientation.landscape) { + _viewportHeightInLandscape ??= + MediaQuery.of(context).size.height - _otherContextHeight!; + } + if (!_pdfDimension.isEmpty) { + if (_scrollDirection == PdfScrollDirection.vertical) { + _maxScrollExtent = + _pdfDimension.height - + (viewportDimension.height / + _pdfViewerController.zoomLevel); + } else { + _maxScrollExtent = + _pdfDimension.width - + (viewportDimension.width / + _pdfViewerController.zoomLevel); } - if (_deviceOrientation == Orientation.landscape) { - _viewportHeightInLandscape ??= - MediaQuery.of(context).size.height - - _otherContextHeight!; + } + _viewportGlobalRect = _getViewportGlobalRect(); + Widget child; + final List children = List< + Widget + >.generate(_pdfViewerController.pageCount, (int index) { + if (index == 0) { + totalHeight = 0; } - if (!_pdfDimension.isEmpty) { - if (_scrollDirection == PdfScrollDirection.vertical) { - _maxScrollExtent = _pdfDimension.height - - (viewportDimension.height / - _pdfViewerController.zoomLevel); - } else { - _maxScrollExtent = _pdfDimension.width - - (viewportDimension.width / - _pdfViewerController.zoomLevel); - } + if (_originalWidth!.length != + _pdfViewerController.pageCount) { + return _getEmptyContainer(); } - _viewportGlobalRect = _getViewportGlobalRect(); - Widget child; - final List children = List.generate( - _pdfViewerController.pageCount, (int index) { - if (index == 0) { - totalHeight = 0; - } - if (_originalWidth!.length != - _pdfViewerController.pageCount) { - return _getEmptyContainer(); - } - final int pageIndex = index + 1; - final Size calculatedSize = _calculateSize( - BoxConstraints(maxWidth: _viewportConstraints.maxWidth), - _originalWidth![index].toDouble(), - _originalHeight![index].toDouble(), - _viewportConstraints.maxWidth, - viewportDimension.height, - ); - if (!_pdfPagesKey.containsKey(pageIndex)) { - _pdfPagesKey[pageIndex] = GlobalKey(); - } - if (kIsDesktop && !_isMobileView) { - if (_originalWidth![index].toDouble() > - _maxPdfPageWidth != - null) { - _maxPdfPageWidth = _originalWidth![index].toDouble(); - } - } - - Widget page = PdfPageView( - _pdfPagesKey[pageIndex]!, - _viewportGlobalRect, - viewportDimension, - widget.interactionMode, - _plugin.documentID, - calculatedSize.width, - calculatedSize.height, - widget.pageSpacing, - _document, - _pdfPages, - index, - _pdfViewerController, - _effectiveUndoController, - widget.maxZoomLevel, - widget.enableDocumentLinkAnnotation, - widget.enableTextSelection, - _textSelectionHelper, - _handleTextSelectionChanged, - widget.onHyperlinkClicked, - _handleTextSelectionDragStarted, - _handleTextSelectionDragEnded, - widget.currentSearchTextHighlightColor, - widget.otherSearchTextHighlightColor, - _textCollection, - _isMobileView, - _pdfViewerController._pdfTextSearchResult, - _pdfScrollableStateKey, - _singlePageViewKey, - _scrollDirection, - _handlePdfPagePointerDown, - _handlePdfPagePointerMove, - _handlePdfPagePointerUp, - isBookmarkViewOpen ? '' : _pageTextExtractor[index], - widget.pageLayoutMode == PdfPageLayoutMode.single, - _textDirection!, - widget.canShowHyperlinkDialog, - widget.enableHyperlinkNavigation, - _isAndroidTV, - widget.canShowPageLoadingIndicator, - widget.canShowSignaturePadDialog, - _handlePageTap, - _pdfViewerController._formFields, - _pdfViewerController._annotations, - _selectedAnnotation, - _onAnnotationSelectionChanged, - _onStickyNoteAnnotationDoubleTapped, - ); - final double pageSpacing = - index == _pdfViewerController._pageCount - 1 - ? 0.0 - : widget.pageSpacing; - _pdfPages[pageIndex] = PdfPageInfo( - totalHeight, - calculatedSize, - ); - if (_isMobileWebView ?? false) { - page = Visibility( - visible: _isPageVisible(pageIndex), - replacement: _getReplacementWidget( - pageIndex, - calculatedSize, - ), - child: page, - ); - } - // In RTL direction, the last page is rendered at Offset.zero. - // Hence, the we are interchanging the page offset value of all the pages. - if (_textDirection == TextDirection.rtl && - widget.pageLayoutMode == PdfPageLayoutMode.continuous && - _scrollDirection == PdfScrollDirection.horizontal && - _pdfViewerController.pageCount == pageIndex) { - for (int i = 1; - i <= _pdfViewerController.pageCount; - i++) { - _pdfPages[i]!.pageOffset = - totalHeight - _pdfPages[i]!.pageOffset; - } - } - - if (_scrollDirection == PdfScrollDirection.vertical && - widget.pageLayoutMode != PdfPageLayoutMode.single) { - totalHeight += calculatedSize.height + pageSpacing; - } else { - totalHeight += calculatedSize.width + pageSpacing; + final int pageIndex = index + 1; + final Size calculatedSize = _calculateSize( + BoxConstraints(maxWidth: _viewportConstraints.maxWidth), + _originalWidth![index].toDouble(), + _originalHeight![index].toDouble(), + _viewportConstraints.maxWidth, + viewportDimension.height, + ); + if (!_pdfPagesKey.containsKey(pageIndex)) { + _pdfPagesKey[pageIndex] = GlobalKey(); + } + if (kIsDesktop && !_isMobileView) { + if (_originalWidth![index].toDouble() > _maxPdfPageWidth != + null) { + _maxPdfPageWidth = _originalWidth![index].toDouble(); } - _updateScrollDirectionChange( - _offsetBeforeOrientationChange, - pageIndex, - totalHeight, - ); - _updateOffsetOnOrientationChange( - _offsetBeforeOrientationChange, - pageIndex, - totalHeight, - ); - return page; - }); - Widget? pdfContainer; - if (!_isLoaded) { - Future.delayed(Duration.zero, () async { - if (_document != null && - widget.onDocumentLoaded != null) { - _isDocumentLoadInitiated = false; - widget.onDocumentLoaded!( - PdfDocumentLoadedDetails(_document!), - ); - } - _checkMount(); - _isLoaded = true; - }); } - if (widget.pageLayoutMode == PdfPageLayoutMode.single) { - _pageController = PageController( - initialPage: _pdfViewerController._pageNumber - 1, - ); - pdfContainer = MouseRegion( - cursor: _cursor, - onHover: (PointerHoverEvent details) { - if (widget.interactionMode == PdfInteractionMode.pan && - _cursor != SystemMouseCursors.grab) { - setState(() { - _cursor = SystemMouseCursors.grab; - }); - } else if (widget.interactionMode == - PdfInteractionMode.selection && - _cursor != SystemMouseCursors.basic) { - setState(() { - _cursor = SystemMouseCursors.basic; - }); - } - }, - child: SinglePageView( - _singlePageViewKey, - _pdfViewerController, - _transformationController, - _pageController, - _handleSinglePageViewPageChanged, - _interactionUpdate, - viewportDimension, - visibleViewportDimension, - widget.maxZoomLevel, - widget.canShowPaginationDialog, - widget.canShowScrollHead, - widget.canShowScrollStatus, - _pdfPages, - _isMobileView, - widget.enableDoubleTapZooming, - widget.interactionMode, - _isScaleEnabled, - _handleSinglePageViewZoomLevelChanged, - _handleDoubleTap, - _handlePdfOffsetChanged, - isBookmarkViewOpen, - _textDirection!, - _isTablet, - _scrollDirection, - _getTileImage, - children, + + Widget page = PdfPageView( + _pdfPagesKey[pageIndex]!, + _viewportGlobalRect, + viewportDimension, + widget.interactionMode, + _plugin.documentID, + calculatedSize.width, + calculatedSize.height, + widget.pageSpacing, + _document, + _pdfPages, + index, + _pdfViewerController, + _effectiveUndoController, + widget.maxZoomLevel, + widget.enableDocumentLinkAnnotation, + widget.enableTextSelection, + _textSelectionHelper, + _handleTextSelectionChanged, + widget.onHyperlinkClicked, + _handleTextSelectionDragStarted, + _handleTextSelectionDragEnded, + widget.currentSearchTextHighlightColor, + widget.otherSearchTextHighlightColor, + _textCollection, + _isMobileView, + _pdfViewerController._pdfTextSearchResult, + _pdfScrollableStateKey, + _singlePageViewKey, + _scrollDirection, + _handlePdfPagePointerDown, + _handlePdfPagePointerMove, + _handlePdfPagePointerUp, + isBookmarkViewOpen ? '' : _pageTextExtractor[index], + widget.pageLayoutMode == PdfPageLayoutMode.single, + _textDirection!, + widget.canShowHyperlinkDialog, + widget.enableHyperlinkNavigation, + _isAndroidTV, + widget.canShowPageLoadingIndicator, + widget.canShowSignaturePadDialog, + _handlePageTap, + _pdfViewerController._formFields, + _pdfViewerController._annotations, + _selectedAnnotation, + _onAnnotationSelectionChanged, + _onStickyNoteAnnotationDoubleTapped, + ); + final double pageSpacing = + index == _pdfViewerController._pageCount - 1 + ? 0.0 + : widget.pageSpacing; + _pdfPages[pageIndex] = PdfPageInfo( + totalHeight, + calculatedSize, + ); + if (_isMobileWebView ?? false) { + page = Visibility( + visible: _isPageVisible(pageIndex), + replacement: _getReplacementWidget( + pageIndex, + calculatedSize, ), + child: page, ); - if (_isSinglePageViewPageChanged && - _renderedImages.contains( - _pdfViewerController.pageNumber, - )) { - Future.delayed(Duration.zero, () async { - if (_pageController.hasClients) { - _pdfViewerController._scrollPositionX = 0; - } - if (!_isSearchStarted) { - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.focusNode - .requestFocus(); - } - if (getSelectedTextLines().isNotEmpty && - getSelectedTextLines().first.pageNumber + 1 == - _pdfViewerController.pageNumber) { - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.canvasRenderBox - ?.updateContextMenuPosition(); - } - _isSinglePageViewPageChanged = false; - }); + } + // In RTL direction, the last page is rendered at Offset.zero. + // Hence, the we are interchanging the page offset value of all the pages. + if (_textDirection == TextDirection.rtl && + widget.pageLayoutMode == PdfPageLayoutMode.continuous && + _scrollDirection == PdfScrollDirection.horizontal && + _pdfViewerController.pageCount == pageIndex) { + for (int i = 1; i <= _pdfViewerController.pageCount; i++) { + _pdfPages[i]!.pageOffset = + totalHeight - _pdfPages[i]!.pageOffset; } + } + + if (_scrollDirection == PdfScrollDirection.vertical && + widget.pageLayoutMode != PdfPageLayoutMode.single) { + totalHeight += calculatedSize.height + pageSpacing; } else { - final Size childSize = _getChildSize(viewportDimension); - if (_scrollDirection == PdfScrollDirection.horizontal) { - child = Row( - key: _childKey, - mainAxisAlignment: MainAxisAlignment.center, - children: children, - ); - } else { - child = Column( - key: _childKey, - mainAxisAlignment: MainAxisAlignment.center, - children: children, + totalHeight += calculatedSize.width + pageSpacing; + } + _updateScrollDirectionChange( + _offsetBeforeOrientationChange, + pageIndex, + totalHeight, + ); + _updateOffsetOnOrientationChange( + _offsetBeforeOrientationChange, + pageIndex, + totalHeight, + ); + return page; + }); + Widget? pdfContainer; + if (!_isLoaded) { + Future.delayed(Duration.zero, () async { + if (_document != null && widget.onDocumentLoaded != null) { + _isDocumentLoadInitiated = false; + widget.onDocumentLoaded!( + PdfDocumentLoadedDetails(_document!), ); } - child = MouseRegion( - cursor: _cursor, - onHover: (PointerHoverEvent details) { - if (widget.interactionMode == PdfInteractionMode.pan && - _cursor != SystemMouseCursors.grab) { - setState(() { - _cursor = SystemMouseCursors.grab; - }); - } else if (widget.interactionMode == - PdfInteractionMode.selection && - _cursor != SystemMouseCursors.basic) { - setState(() { - _cursor = SystemMouseCursors.basic; - }); - } - }, - child: SizedBox( - height: childSize.height, - width: childSize.width, - child: child, - ), - ); - pdfContainer = PdfScrollable( - _transformationController, - widget.canShowPaginationDialog, - widget.canShowScrollStatus, - widget.canShowScrollHead, + _checkMount(); + _isLoaded = true; + }); + } + if (widget.pageLayoutMode == PdfPageLayoutMode.single) { + _pageController = PageController( + initialPage: _pdfViewerController._pageNumber - 1, + ); + pdfContainer = MouseRegion( + cursor: _cursor, + onHover: (PointerHoverEvent details) { + if (widget.interactionMode == PdfInteractionMode.pan && + _cursor != SystemMouseCursors.grab) { + setState(() { + _cursor = SystemMouseCursors.grab; + }); + } else if (widget.interactionMode == + PdfInteractionMode.selection && + _cursor != SystemMouseCursors.basic) { + setState(() { + _cursor = SystemMouseCursors.basic; + }); + } + }, + child: SinglePageView( + _singlePageViewKey, _pdfViewerController, - _isMobileView, - _pdfDimension, - _totalImageSize, + _transformationController, + _pageController, + _handleSinglePageViewPageChanged, + _interactionUpdate, viewportDimension, visibleViewportDimension, - _handlePdfOffsetChanged, - _panEnabled, widget.maxZoomLevel, - _minScale, + widget.canShowPaginationDialog, + widget.canShowScrollHead, + widget.canShowScrollStatus, + _pdfPages, + _isMobileView, widget.enableDoubleTapZooming, widget.interactionMode, - _maxPdfPageWidth, _isScaleEnabled, - _maxScrollExtent, - _pdfPages, - _scrollDirection, + _handleSinglePageViewZoomLevelChanged, + _handleDoubleTap, + _handlePdfOffsetChanged, isBookmarkViewOpen, _textDirection!, - child, + _isTablet, + _scrollDirection, _getTileImage, - key: _pdfScrollableStateKey, - onDoubleTap: _handleDoubleTap, + children, + ), + ); + if (_isSinglePageViewPageChanged && + _renderedImages.contains( + _pdfViewerController.pageNumber, + )) { + Future.delayed(Duration.zero, () async { + if (_pageController.hasClients) { + _pdfViewerController._scrollPositionX = 0; + } + if (!_isSearchStarted) { + _pdfPagesKey[_pdfViewerController.pageNumber] + ?.currentState + ?.focusNode + .requestFocus(); + } + if (getSelectedTextLines().isNotEmpty && + getSelectedTextLines().first.pageNumber + 1 == + _pdfViewerController.pageNumber) { + _pdfPagesKey[_pdfViewerController.pageNumber] + ?.currentState + ?.canvasRenderBox + ?.updateContextMenuPosition(); + } + _isSinglePageViewPageChanged = false; + }); + } + } else { + final Size childSize = _getChildSize(viewportDimension); + if (_scrollDirection == PdfScrollDirection.horizontal) { + child = Row( + key: _childKey, + mainAxisAlignment: MainAxisAlignment.center, + children: children, + ); + } else { + child = Column( + key: _childKey, + mainAxisAlignment: MainAxisAlignment.center, + children: children, ); - // Updates current offset when scrollDirection change occurs. - if (_isScrollDirectionChange) { - _pdfScrollableStateKey.currentState?.forcePixels( - _scrollDirectionSwitchOffset, - ); - _isScrollDirectionChange = false; - } } - WidgetsBinding.instance.addPostFrameCallback(( - Duration timeStamp, - ) { - if (super.mounted && context.mounted) { - // call PdfViewerController methods after ScrollController attached. - _isDocumentLoaded(); - - // If the text direction is changed, then jump to the current page to avoid the abrupt change in the view. - if (_isTextDirectionChanged) { - _isTextDirectionChanged = false; - _pdfViewerController.jumpToPage( - _pdfViewerController.pageNumber, - ); + child = MouseRegion( + cursor: _cursor, + onHover: (PointerHoverEvent details) { + if (widget.interactionMode == PdfInteractionMode.pan && + _cursor != SystemMouseCursors.grab) { + setState(() { + _cursor = SystemMouseCursors.grab; + }); + } else if (widget.interactionMode == + PdfInteractionMode.selection && + _cursor != SystemMouseCursors.basic) { + setState(() { + _cursor = SystemMouseCursors.basic; + }); } - } - }); - return Stack( - children: [ - pdfContainer, - BookmarkView( - _bookmarkKey, - _document, - _pdfViewerController, - _handleBookmarkViewChanged, - _textDirection!, - ), - ], + }, + child: SizedBox( + height: childSize.height, + width: childSize.width, + child: child, + ), ); - }, - ), + pdfContainer = PdfScrollable( + _transformationController, + widget.canShowPaginationDialog, + widget.canShowScrollStatus, + widget.canShowScrollHead, + _pdfViewerController, + _isMobileView, + _pdfDimension, + _totalImageSize, + viewportDimension, + visibleViewportDimension, + _handlePdfOffsetChanged, + _panEnabled, + widget.maxZoomLevel, + _minScale, + widget.enableDoubleTapZooming, + widget.interactionMode, + _maxPdfPageWidth, + _isScaleEnabled, + _maxScrollExtent, + _pdfPages, + _scrollDirection, + isBookmarkViewOpen, + _textDirection!, + child, + _getTileImage, + key: _pdfScrollableStateKey, + onDoubleTap: _handleDoubleTap, + ); + // Updates current offset when scrollDirection change occurs. + if (_isScrollDirectionChange) { + _pdfScrollableStateKey.currentState?.forcePixels( + _scrollDirectionSwitchOffset, + ); + _isScrollDirectionChange = false; + } + } + WidgetsBinding.instance.addPostFrameCallback(( + Duration timeStamp, + ) { + if (super.mounted && context.mounted) { + // call PdfViewerController methods after ScrollController attached. + _isDocumentLoaded(); + + // If the text direction is changed, then jump to the current page to avoid the abrupt change in the view. + if (_isTextDirectionChanged) { + _isTextDirectionChanged = false; + _pdfViewerController.jumpToPage( + _pdfViewerController.pageNumber, + ); + } + } + }); + return Stack( + children: [ + pdfContainer, + BookmarkView( + _bookmarkKey, + _document, + _pdfViewerController, + _handleBookmarkViewChanged, + _textDirection!, + ), + ], + ); + }, ), - ) + ), + ) : (_hasError ? _isEncryptedDocument ? _showWebPasswordDialogue() @@ -3886,10 +3990,18 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _renderedImages.clear(); final double zoomLevel = _transformationController.value[0]; if (widget.pageLayoutMode == PdfPageLayoutMode.single) { + if (!_pageTextExtractor.containsKey( + _pdfViewerController.pageNumber - 1, + )) { + _pageTextExtractor[_pdfViewerController.pageNumber - + 1] = _pdfTextExtractor!.extractText( + startPageIndex: _pdfViewerController.pageNumber - 1, + ); + } _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.getPageImage( - _viewportSize, - zoomLevel, - ); + _viewportSize, + zoomLevel, + ); _renderedImages.add(_pdfViewerController.pageNumber); } else { final Offset offset = _transformationController.toScene(Offset.zero); @@ -3903,9 +4015,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _viewportSize.height, ); // Render or clear images from the current page to the last page. - for (int pageNumber = _pdfViewerController.pageNumber; - pageNumber <= _pdfViewerController.pageCount; - pageNumber++) { + for ( + int pageNumber = _pdfViewerController.pageNumber; + pageNumber <= _pdfViewerController.pageCount; + pageNumber++ + ) { final Rect pageRect = Rect.fromLTWH( _scrollDirection == PdfScrollDirection.vertical ? 0 @@ -3919,26 +4033,26 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (!viewportRect.intersect(pageRect).isEmpty) { _renderedImages.add(pageNumber); - // Set semantic text only if assistive technology is enabled. - if (_isAccessibilityEnabled && - (_pageTextExtractor.isEmpty || - !_pageTextExtractor.containsKey(pageNumber - 1))) { + //Extract page text only if it's not already available. + if (!_pageTextExtractor.containsKey(pageNumber - 1)) { _pageTextExtractor[pageNumber - 1] = _pdfTextExtractor!.extractText( startPageIndex: pageNumber - 1, ); } _pdfPagesKey[pageNumber]?.currentState?.getPageImage( - _viewportSize, - zoomLevel, - ); + _viewportSize, + zoomLevel, + ); } else { _pdfPagesKey[pageNumber]?.currentState?.clearPageImage(); } } // Render or clear images from the current page to the first page. - for (int pageNumber = _pdfViewerController.pageNumber - 1; - pageNumber > 0; - pageNumber--) { + for ( + int pageNumber = _pdfViewerController.pageNumber - 1; + pageNumber > 0; + pageNumber-- + ) { final Rect pageRect = Rect.fromLTWH( _scrollDirection == PdfScrollDirection.vertical ? 0 @@ -3952,18 +4066,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (!viewportRect.intersect(pageRect).isEmpty) { _renderedImages.add(pageNumber); - // Set semantic text only if assistive technology is enabled. - if (_isAccessibilityEnabled && - (_pageTextExtractor.isEmpty || - !_pageTextExtractor.containsKey(pageNumber - 1))) { + //Extract page text only if it's not already available. + if (!_pageTextExtractor.containsKey(pageNumber - 1)) { _pageTextExtractor[pageNumber - 1] = _pdfTextExtractor!.extractText( startPageIndex: pageNumber - 1, ); } _pdfPagesKey[pageNumber]?.currentState?.getPageImage( - _viewportSize, - zoomLevel, - ); + _viewportSize, + zoomLevel, + ); } else { _pdfPagesKey[pageNumber]?.currentState?.clearPageImage(); } @@ -3983,10 +4095,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } } else { final Offset offset = _transformationController.toScene(Offset.zero); - final double x = _textDirection == TextDirection.rtl && - _scrollDirection == PdfScrollDirection.horizontal - ? _maxScrollExtent - offset.dx - : offset.dx; + final double x = + _textDirection == TextDirection.rtl && + _scrollDirection == PdfScrollDirection.horizontal + ? _maxScrollExtent - offset.dx + : offset.dx; final double y = offset.dy; final Rect viewportRect = Rect.fromLTWH( @@ -4055,9 +4168,10 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { double childHeight = 0, childWidth = 0; if (_pdfScrollableStateKey.currentState != null) { - widthFactor = _pdfScrollableStateKey.currentState!.paddingWidthScale == 0 - ? _pdfViewerController.zoomLevel - : _pdfScrollableStateKey.currentState!.paddingWidthScale; + widthFactor = + _pdfScrollableStateKey.currentState!.paddingWidthScale == 0 + ? _pdfViewerController.zoomLevel + : _pdfScrollableStateKey.currentState!.paddingWidthScale; heightFactor = _pdfScrollableStateKey.currentState!.paddingHeightScale == 0 ? _pdfViewerController.zoomLevel @@ -4066,11 +4180,12 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (_pdfPages[_pdfViewerController.pageCount] != null) { // In RTL direction, the last page is rendered at Offset.zero and the first page is rendered at the end. // Hence, we are considering the first page as the last page and vice versa. - final PdfPageInfo lastPageInfo = _textDirection == TextDirection.rtl && - widget.pageLayoutMode == PdfPageLayoutMode.continuous && - _scrollDirection == PdfScrollDirection.horizontal - ? _pdfPages[1]! - : _pdfPages[_pdfViewerController.pageCount]!; + final PdfPageInfo lastPageInfo = + _textDirection == TextDirection.rtl && + widget.pageLayoutMode == PdfPageLayoutMode.continuous && + _scrollDirection == PdfScrollDirection.horizontal + ? _pdfPages[1]! + : _pdfPages[_pdfViewerController.pageCount]!; final double zoomLevel = _pdfViewerController.zoomLevel; final Size currentPageSize = _pdfPages[_pdfViewerController.pageNumber]!.pageSize; @@ -4079,20 +4194,23 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (_scrollDirection == PdfScrollDirection.vertical) { totalImageWidth = currentPageSize.width * zoomLevel; } - childWidth = viewportDimension.width > totalImageWidth - ? viewportDimension.width / widthFactor.clamp(1, widget.maxZoomLevel) - : totalImageWidth / widthFactor.clamp(1, widget.maxZoomLevel); + childWidth = + viewportDimension.width > totalImageWidth + ? viewportDimension.width / + widthFactor.clamp(1, widget.maxZoomLevel) + : totalImageWidth / widthFactor.clamp(1, widget.maxZoomLevel); double totalImageHeight = currentPageSize.height * zoomLevel; if (_scrollDirection == PdfScrollDirection.vertical) { totalImageHeight = (lastPageInfo.pageOffset + lastPageInfo.pageSize.height) * - zoomLevel; + zoomLevel; } - childHeight = viewportDimension.height > totalImageHeight - ? viewportDimension.height / - heightFactor.clamp(1, widget.maxZoomLevel) - : totalImageHeight / heightFactor.clamp(1, widget.maxZoomLevel); + childHeight = + viewportDimension.height > totalImageHeight + ? viewportDimension.height / + heightFactor.clamp(1, widget.maxZoomLevel) + : totalImageHeight / heightFactor.clamp(1, widget.maxZoomLevel); _totalImageSize = Size( totalImageWidth / zoomLevel, totalImageHeight / zoomLevel, @@ -4186,9 +4304,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } } if (!isTextFormFieldFocused) { - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.focusNode + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.focusNode .requestFocus(); } } @@ -4197,10 +4313,12 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { final Offset draggedDistance = event.localPosition - _pagePointerDownPosition; if (event.kind == PointerDeviceKind.touch) { - _canInvokeOnTap &= draggedDistance.dx.abs() < kTouchSlop && + _canInvokeOnTap &= + draggedDistance.dx.abs() < kTouchSlop && draggedDistance.dy.abs() < kTouchSlop; } else { - _canInvokeOnTap &= draggedDistance.dx.abs() < kPrecisePointerHitSlop && + _canInvokeOnTap &= + draggedDistance.dx.abs() < kPrecisePointerHitSlop && draggedDistance.dy.abs() < kPrecisePointerHitSlop; } if (widget.interactionMode == PdfInteractionMode.pan) { @@ -4230,28 +4348,31 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { details.timeStamp - _pagePointerDownTimeStamp < kLongPressTimeout; bool isSlopDistanceExceeded = false; if (details.kind == PointerDeviceKind.touch) { - isSlopDistanceExceeded = kTouchSlop > + isSlopDistanceExceeded = + kTouchSlop > (details.localPosition.dx - _pagePointerDownPosition.dx).abs() && kTouchSlop > (details.localPosition.dy - _pagePointerDownPosition.dy).abs(); } else { - isSlopDistanceExceeded = kPrecisePointerHitSlop > + isSlopDistanceExceeded = + kPrecisePointerHitSlop > (details.localPosition.dx - _pagePointerDownPosition.dx).abs() && kPrecisePointerHitSlop > (details.localPosition.dy - _pagePointerDownPosition.dy).abs(); } final bool isLongPressed = (details.timeStamp - _pagePointerDownTimeStamp > kLongPressTimeout) && - isSlopDistanceExceeded; + isSlopDistanceExceeded; Timer(kDoubleTapTimeout, () { if (!_isDoubleTapped && _canInvokeOnTap && !isBookmarkViewOpen) { if (widget.onTap != null) { - final Offset viewportPosition = _textDirection == TextDirection.ltr - ? details.localPosition - : Offset( - _viewportWidth - details.localPosition.dx, - details.localPosition.dy, - ); + final Offset viewportPosition = + _textDirection == TextDirection.ltr + ? details.localPosition + : Offset( + _viewportWidth - details.localPosition.dx, + details.localPosition.dy, + ); widget.onTap!( PdfGestureDetails( _tappedPageNumber, @@ -4291,9 +4412,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (widget.interactionMode == PdfInteractionMode.pan) { _cursor = SystemMouseCursors.grab; } - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.canvasRenderBox + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.canvasRenderBox ?.scrollEnded(); if (_selectedAnnotation != null && _selectedAnnotation is StickyNoteAnnotation) { @@ -4416,14 +4535,13 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (_pageLayoutMode == PdfPageLayoutMode.continuous) { for (final int pageNumber in _renderedImages) { _pdfPagesKey[pageNumber]?.currentState?.getTileImage( - _transformationController, - _viewportSize, - zoomLevel, - ); + _transformationController, + _viewportSize, + zoomLevel, + ); } } else { - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState ?.getTileImage( _transformationController, _viewportSize, @@ -4468,12 +4586,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _pdfViewerController._pdfTextSearchResult.hasResult && _pdfViewerController.pageNumber != (_textCollection![_pdfViewerController - ._pdfTextSearchResult._currentOccurrenceIndex - + ._pdfTextSearchResult + ._currentOccurrenceIndex - 1] .pageIndex + 1)) { - _pdfViewerController._pdfTextSearchResult._currentOccurrenceIndex = - _getInstanceInPage( + _pdfViewerController + ._pdfTextSearchResult + ._currentOccurrenceIndex = _getInstanceInPage( _pdfViewerController.pageNumber, lookForFirst: isNext, ); @@ -4579,10 +4699,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _previousSinglePage = _pdfViewerController.pageNumber; final double greyArea = (_singlePageViewKey.currentState?.greyAreaSize ?? 0) / 2; - final double heightPercentage = (kIsDesktop && !_isMobileView) - ? _document!.pages[_pdfViewerController.pageNumber - 1].size.height / - _pdfPages[_pdfViewerController.pageNumber]!.pageSize.height - : 1.0; + final double heightPercentage = + (kIsDesktop && !_isMobileView) + ? _document! + .pages[_pdfViewerController.pageNumber - 1] + .size + .height / + _pdfPages[_pdfViewerController.pageNumber]!.pageSize.height + : 1.0; Offset singleOffset = _singlePageViewKey.currentState?.currentOffset ?? Offset.zero; @@ -4601,12 +4725,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { double yPosition = scrollOffset.dy; if (_pdfViewerController.pageNumber > 1 && _scrollDirection == PdfScrollDirection.vertical) { - yPosition = scrollOffset.dy - + yPosition = + scrollOffset.dy - _pdfPages[_pdfViewerController.pageNumber]!.pageOffset; } if (_pdfViewerController.pageNumber > 1 && _scrollDirection == PdfScrollDirection.horizontal) { - xPosition = scrollOffset.dx - + xPosition = + scrollOffset.dx - _pdfPages[_pdfViewerController.pageNumber]!.pageOffset; } Future.delayed(Duration.zero, () async { @@ -4614,11 +4740,14 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _pdfViewerController.zoomLevel = 1.0; } _pdfViewerController.zoomLevel = zoomLevel; - final double heightPercentage = (kIsDesktop && !_isMobileView) - ? _document! - .pages[_pdfViewerController.pageNumber - 1].size.height / - _pdfPages[_pdfViewerController.pageNumber]!.pageSize.height - : 1.0; + final double heightPercentage = + (kIsDesktop && !_isMobileView) + ? _document! + .pages[_pdfViewerController.pageNumber - 1] + .size + .height / + _pdfPages[_pdfViewerController.pageNumber]!.pageSize.height + : 1.0; if (widget.pageLayoutMode == PdfPageLayoutMode.single && _singlePageViewKey.currentState != null) { @@ -4695,18 +4824,19 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { widget.pageLayoutMode != PdfPageLayoutMode.single) { final dynamic pageOffset = _pdfPages[_pdfViewerController.pageNumber]!.pageOffset; - final dynamic calculatedOffsetY = pageOffset + + final dynamic calculatedOffsetY = + pageOffset + (initialOffset.dy * _pdfPages[_pdfViewerController.pageNumber]! .pageSize .height); final dynamic calculatedOffsetX = (_pdfScrollableStateKey.currentState!.currentOffset.dx - - _pageOffsetBeforeScrollDirectionChange) * - (_pdfPages[_pdfViewerController.pageNumber]! - .pageSize - .width / - _pageSizeBeforeScrollDirectionChange.width); + _pageOffsetBeforeScrollDirectionChange) * + (_pdfPages[_pdfViewerController.pageNumber]! + .pageSize + .width / + _pageSizeBeforeScrollDirectionChange.width); _scrollDirectionSwitchOffset = Offset( calculatedOffsetX, @@ -4715,18 +4845,19 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } else { final dynamic pageOffset = _pdfPages[_pdfViewerController.pageNumber]!.pageOffset; - final dynamic calculatedOffsetX = pageOffset + + final dynamic calculatedOffsetX = + pageOffset + (initialOffset.dx * _pdfPages[_pdfViewerController.pageNumber]! .pageSize .width); final dynamic calculatedOffsetY = (_pdfScrollableStateKey.currentState!.currentOffset.dy - - _pageOffsetBeforeScrollDirectionChange) / - (_pageSizeBeforeScrollDirectionChange.height / - _pdfPages[_pdfViewerController.pageNumber]! - .pageSize - .height); + _pageOffsetBeforeScrollDirectionChange) / + (_pageSizeBeforeScrollDirectionChange.height / + _pdfPages[_pdfViewerController.pageNumber]! + .pageSize + .height); _scrollDirectionSwitchOffset = Offset( calculatedOffsetX, @@ -4816,7 +4947,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (currentOffset > 0) { _pdfViewerController._pageNumber = _pdfScrollableStateKey.currentState?.getPageNumber(currentOffset) ?? - 0; + 0; } else { if (_textDirection == TextDirection.rtl && _scrollDirection == PdfScrollDirection.horizontal) { @@ -5010,18 +5141,20 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { localizations: _localizations, onSelected: (String value) { if (value != 'Copy') { - final PdfAnnotationMode annotationMode = value == 'Highlight' - ? PdfAnnotationMode.highlight - : value == 'Underline' + final PdfAnnotationMode annotationMode = + value == 'Highlight' + ? PdfAnnotationMode.highlight + : value == 'Underline' ? PdfAnnotationMode.underline : value == 'Strikethrough' - ? PdfAnnotationMode.strikethrough - : PdfAnnotationMode.squiggly; + ? PdfAnnotationMode.strikethrough + : PdfAnnotationMode.squiggly; _addTextMarkupAnnotation(annotationMode); } else if (value == 'Copy') { Clipboard.setData( ClipboardData( - text: _pdfPagesKey[_selectedTextPageNumber] + text: + _pdfPagesKey[_selectedTextPageNumber] ?.currentState ?.canvasRenderBox! .getSelectionDetails() @@ -5229,16 +5362,18 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (pageNumber <= 0 || pageNumber > _document!.pages.count) { return; } - final List annotations = _pdfViewerController - .getAnnotations() - .where( - (Annotation annotation) => annotation.pageNumber == pageNumber, - ) - .toList(); + final List annotations = + _pdfViewerController + .getAnnotations() + .where( + (Annotation annotation) => annotation.pageNumber == pageNumber, + ) + .toList(); for (final Annotation annotation in annotations) { if (annotation is StickyNoteAnnotation) { - final Rect scaledBounds = annotation.boundingBox.topLeft & + final Rect scaledBounds = + annotation.boundingBox.topLeft & (annotation.boundingBox.size / _pdfViewerController.zoomLevel); if (scaledBounds.contains(position)) { return; @@ -5316,10 +5451,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(4.0), ), - backgroundColor: annotation != null - ? annotation.color.getLightenColor(0.85) - : _pdfViewerController.annotationSettings.stickyNote.color - .getLightenColor(0.85), + backgroundColor: + annotation != null + ? annotation.color.getLightenColor(0.85) + : _pdfViewerController.annotationSettings.stickyNote.color + .getLightenColor(0.85), child: Theme( data: ThemeData.light(), child: SizedBox( @@ -5353,9 +5489,10 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } Navigator.pop(context); }, - child: annotation != null - ? const Text('SAVE') - : const Text('INSERT'), + child: + annotation != null + ? const Text('SAVE') + : const Text('INSERT'), ), ), ], @@ -5477,19 +5614,21 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { double yOffset = _pdfPages[index]!.pageOffset; final bool isRotatedTo90or270 = pdfPage.rotation == PdfPageRotateAngle.rotateAngle90 || - pdfPage.rotation == PdfPageRotateAngle.rotateAngle270; + pdfPage.rotation == PdfPageRotateAngle.rotateAngle270; if (bookmark.namedDestination != null) { - heightPercentage = bookmark - .namedDestination!.destination!.page.size.height / + heightPercentage = + bookmark.namedDestination!.destination!.page.size.height / (isRotatedTo90or270 ? revealedOffset.width : revealedOffset.height); - widthPercentage = bookmark - .namedDestination!.destination!.page.size.width / + widthPercentage = + bookmark.namedDestination!.destination!.page.size.width / (isRotatedTo90or270 ? revealedOffset.height : revealedOffset.width); bookmarkOffset = bookmark.namedDestination!.destination!.location; } else { - heightPercentage = bookmark.destination!.page.size.height / + heightPercentage = + bookmark.destination!.page.size.height / (isRotatedTo90or270 ? revealedOffset.width : revealedOffset.height); - widthPercentage = bookmark.destination!.page.size.width / + widthPercentage = + bookmark.destination!.page.size.width / (isRotatedTo90or270 ? revealedOffset.height : revealedOffset.width); bookmarkOffset = bookmark.destination!.location; } @@ -5508,7 +5647,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { widget.pageLayoutMode == PdfPageLayoutMode.continuous) { heightPercentage = _document!.pages[_pdfViewerController.pageNumber - 1].size.height / - _pdfPages[_pdfViewerController.pageNumber]!.pageSize.height; + _pdfPages[_pdfViewerController.pageNumber]!.pageSize.height; } yOffset = yOffset + (bookmarkOffset.dy / heightPercentage); double xOffset = bookmarkOffset.dx / widthPercentage; @@ -5517,7 +5656,8 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { xOffset = _pdfPages[index]!.pageOffset; yOffset = bookmarkOffset.dy / heightPercentage; } else { - xOffset = _pdfPages[index]!.pageOffset + + xOffset = + _pdfPages[index]!.pageOffset + bookmarkOffset.dx / widthPercentage; yOffset = bookmarkOffset.dy / heightPercentage; } @@ -5572,8 +5712,8 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } } else if (property == 'exportFormData') { if (_document != null) { - _pdfViewerController._exportedFormDataBytes = - _document!.form.exportData(_pdfViewerController._exportDataFormat); + _pdfViewerController._exportedFormDataBytes = _document!.form + .exportData(_pdfViewerController._exportDataFormat); setState(() {}); } } else if (property == 'importFormData') { @@ -5674,10 +5814,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { } } else if (!_pdfDimension.isEmpty) { _pdfScrollableStateKey.currentState?.jumpTo( - xOffset: (_textDirection == TextDirection.rtl && - _scrollDirection == PdfScrollDirection.horizontal) - ? (_maxScrollExtent - _pdfViewerController._horizontalOffset) - : _pdfViewerController._horizontalOffset, + xOffset: + (_textDirection == TextDirection.rtl && + _scrollDirection == PdfScrollDirection.horizontal) + ? (_maxScrollExtent - _pdfViewerController._horizontalOffset) + : _pdfViewerController._horizontalOffset, yOffset: _pdfViewerController._verticalOffset, ); } @@ -5825,16 +5966,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (!_changeTracker.changeInProgress) { final int maxZOrder = _pdfViewerController._annotations .where( - (Annotation annotation) => - annotation.pageNumber == newAnnotation.pageNumber, - ) + (Annotation annotation) => + annotation.pageNumber == newAnnotation.pageNumber, + ) .fold(-1, (int previousValue, Annotation annotation) { - if (annotation.zOrder > previousValue) { - return annotation.zOrder; - } else { - return previousValue; - } - }); + if (annotation.zOrder > previousValue) { + return annotation.zOrder; + } else { + return previousValue; + } + }); newAnnotation.zOrder = maxZOrder + 1; if (widget.onAnnotationAdded != null) { widget.onAnnotationAdded!(newAnnotation); @@ -5858,10 +5999,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _document!.pages[annotation.pageNumber - 1].rotation; final bool isRotatedTo90or270 = rotatedAngle == PdfPageRotateAngle.rotateAngle90 || - rotatedAngle == PdfPageRotateAngle.rotateAngle270; + rotatedAngle == PdfPageRotateAngle.rotateAngle270; final Size originalPageSize = _document!.pages[annotation.pageNumber - 1].size; - final double heightPercentage = (isRotatedTo90or270 + final double heightPercentage = + (isRotatedTo90or270 ? originalPageSize.width : originalPageSize.height) / _pdfPages[annotation.pageNumber]!.pageSize.height; @@ -5875,14 +6017,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (_scrollDirection == PdfScrollDirection.horizontal) { _pdfViewerController.jumpTo( - xOffset: _pdfViewerController.scrollOffset.dx + + xOffset: + _pdfViewerController.scrollOffset.dx + rotatedBounds.left / heightPercentage, yOffset: rotatedBounds.top / heightPercentage, ); } else { _pdfViewerController.jumpTo( xOffset: rotatedBounds.left / heightPercentage, - yOffset: _pdfViewerController.scrollOffset.dy + + yOffset: + _pdfViewerController.scrollOffset.dy + rotatedBounds.top / heightPercentage, ); } @@ -6211,10 +6355,12 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { int _getInstanceInPage(int pageNumber, {bool lookForFirst = true}) { int? instance = 0; if (lookForFirst) { - instance = _jumpToNextInstance(pageNumber) ?? + instance = + _jumpToNextInstance(pageNumber) ?? _jumpToPreviousInstance(pageNumber); } else { - instance = _jumpToPreviousInstance(pageNumber) ?? + instance = + _jumpToPreviousInstance(pageNumber) ?? _jumpToNextInstance(pageNumber); } return instance ?? 1; @@ -6244,9 +6390,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _isPageChanged = false; } const int searchInstanceTopMargin = 20; - final int currentInstancePageIndex = _textCollection![ - _pdfViewerController._pdfTextSearchResult.currentInstanceIndex - - 1] + final int currentInstancePageIndex = + _textCollection![_pdfViewerController + ._pdfTextSearchResult + .currentInstanceIndex - + 1] .pageIndex + 1; Offset topOffset = Offset.zero; @@ -6255,34 +6403,38 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { ?.currentState ?.canvasRenderBox != null) { - topOffset = _pdfPagesKey[_pdfViewerController.pageNumber]! - .currentState! - .canvasRenderBox! - .getRotatedTextBounds( - _textCollection![_pdfViewerController - ._pdfTextSearchResult.currentInstanceIndex - - 1] - .bounds, - currentInstancePageIndex - 1, - _document!.pages[currentInstancePageIndex - 1].rotation, - ) - .topLeft; + topOffset = + _pdfPagesKey[_pdfViewerController.pageNumber]! + .currentState! + .canvasRenderBox! + .getRotatedTextBounds( + _textCollection![_pdfViewerController + ._pdfTextSearchResult + .currentInstanceIndex - + 1] + .bounds, + currentInstancePageIndex - 1, + _document!.pages[currentInstancePageIndex - 1].rotation, + ) + .topLeft; } final double heightPercentage = _document!.pages[currentInstancePageIndex - 1].size.height / - _pdfPages[currentInstancePageIndex]!.pageSize.height; + _pdfPages[currentInstancePageIndex]!.pageSize.height; final double widthPercentage = _document!.pages[currentInstancePageIndex - 1].size.width / - _pdfPages[currentInstancePageIndex]!.pageSize.width; + _pdfPages[currentInstancePageIndex]!.pageSize.width; double searchOffsetX = topOffset.dx / widthPercentage; - double searchOffsetY = (_pdfPages[currentInstancePageIndex]!.pageOffset + + double searchOffsetY = + (_pdfPages[currentInstancePageIndex]!.pageOffset + (topOffset.dy / heightPercentage)) - searchInstanceTopMargin; if (_scrollDirection == PdfScrollDirection.horizontal) { - searchOffsetX = _pdfPages[currentInstancePageIndex]!.pageOffset + + searchOffsetX = + _pdfPages[currentInstancePageIndex]!.pageOffset + topOffset.dx / widthPercentage; searchOffsetY = (topOffset.dy / heightPercentage) - searchInstanceTopMargin; @@ -6330,10 +6482,11 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (_pdfScrollableStateKey.currentState != null && !viewport.contains(Offset(searchOffsetX, searchOffsetY))) { _pdfViewerController.jumpTo( - xOffset: _textDirection == TextDirection.rtl && - _scrollDirection == PdfScrollDirection.horizontal - ? (_maxScrollExtent - searchOffsetX) - : searchOffsetX, + xOffset: + _textDirection == TextDirection.rtl && + _scrollDirection == PdfScrollDirection.horizontal + ? (_maxScrollExtent - searchOffsetX) + : searchOffsetX, yOffset: searchOffsetY, ); WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) { @@ -6351,13 +6504,16 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { if (_pdfViewerController._pdfTextSearchResult.hasResult) { if (property == 'nextInstance') { setState(() { - _pdfViewerController._pdfTextSearchResult - ._currentOccurrenceIndex = _pdfViewerController - ._pdfTextSearchResult.currentInstanceIndex < - _pdfViewerController._pdfTextSearchResult._totalInstanceCount - ? _pdfViewerController._pdfTextSearchResult.currentInstanceIndex + - 1 - : 1; + _pdfViewerController._pdfTextSearchResult._currentOccurrenceIndex = + _pdfViewerController._pdfTextSearchResult.currentInstanceIndex < + _pdfViewerController + ._pdfTextSearchResult + ._totalInstanceCount + ? _pdfViewerController + ._pdfTextSearchResult + .currentInstanceIndex + + 1 + : 1; _jumpToSearchInstance(); }); } else if (property == 'previousInstance') { @@ -6365,10 +6521,12 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _pdfViewerController._pdfTextSearchResult._currentOccurrenceIndex = _pdfViewerController._pdfTextSearchResult.currentInstanceIndex > 1 ? _pdfViewerController - ._pdfTextSearchResult.currentInstanceIndex - + ._pdfTextSearchResult + .currentInstanceIndex - 1 : _pdfViewerController - ._pdfTextSearchResult.totalInstanceCount; + ._pdfTextSearchResult + .totalInstanceCount; _jumpToSearchInstance(isNext: false); }); } @@ -6387,9 +6545,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { _pdfViewerController._pdfTextSearchResult._currentOccurrenceIndex = 0; _pdfViewerController._pdfTextSearchResult._totalSearchTextCount = 0; _pdfViewerController._pdfTextSearchResult._updateResult(false); - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.focusNode + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.focusNode .requestFocus(); _checkMount(); return; @@ -6398,9 +6554,7 @@ class SfPdfViewerState extends State with WidgetsBindingObserver { void _handlePdfOffsetChanged(Offset offset) { if (!_isSearchStarted) { - _pdfPagesKey[_pdfViewerController.pageNumber] - ?.currentState - ?.focusNode + _pdfPagesKey[_pdfViewerController.pageNumber]?.currentState?.focusNode .requestFocus(); } if (widget.pageLayoutMode == PdfPageLayoutMode.continuous) { diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/text_extraction/text_extraction.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/text_extraction/text_extraction.dart index b0c25319a..a413536bf 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/text_extraction/text_extraction.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/text_extraction/text_extraction.dart @@ -56,11 +56,12 @@ void _extractText(SendPort sendPort) { final int pageCount = message.pages.count; for (int i = 0; i < pageCount; i++) { - final String text = textExtractor - .extractText(startPageIndex: i) - // Remove the new line characters. - .replaceAll(RegExp(r'\r?\n'), '') - .toLowerCase(); + final String text = + textExtractor + .extractText(startPageIndex: i) + // Remove the new line characters. + .replaceAll(RegExp(r'\r?\n'), '') + .toLowerCase(); textMap[i] = text; } sendPort.send(textMap); diff --git a/packages/syncfusion_flutter_pdfviewer/lib/src/theme/theme.dart b/packages/syncfusion_flutter_pdfviewer/lib/src/theme/theme.dart index ad8c8636d..0eae9cefd 100644 --- a/packages/syncfusion_flutter_pdfviewer/lib/src/theme/theme.dart +++ b/packages/syncfusion_flutter_pdfviewer/lib/src/theme/theme.dart @@ -14,20 +14,23 @@ class SfPdfViewerThemeDataM2 extends SfPdfViewerThemeData { late final SfColorScheme colorScheme = SfTheme.colorScheme(context); late final PdfScrollHeadStyle _scrollHeadStyle = PdfScrollHeadStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? const Color(0xFFFAFAFA) - : const Color(0xFF424242), + backgroundColor: + colorScheme.brightness == Brightness.light + ? const Color(0xFFFAFAFA) + : const Color(0xFF424242), ); late final PdfBookmarkViewStyle _bookmarkViewStyle = PdfBookmarkViewStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? Colors.white - : const Color(0xFF212121), + backgroundColor: + colorScheme.brightness == Brightness.light + ? Colors.white + : const Color(0xFF212121), closeIconColor: colorScheme.onSurfaceVariant[138], backIconColor: colorScheme.onSurfaceVariant[138], - headerBarColor: colorScheme.brightness == Brightness.light - ? const Color(0xFFFAFAFA) - : const Color(0xFF424242), + headerBarColor: + colorScheme.brightness == Brightness.light + ? const Color(0xFFFAFAFA) + : const Color(0xFF424242), navigationIconColor: colorScheme.onSurfaceVariant[138], selectionColor: colorScheme.primaryContainer[20], titleSeparatorColor: colorScheme.outlineVariant[41], @@ -35,32 +38,36 @@ class SfPdfViewerThemeDataM2 extends SfPdfViewerThemeData { late final PdfPaginationDialogStyle _paginationDialogStyle = PdfPaginationDialogStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? Colors.white - : const Color(0xFF424242), - ); + backgroundColor: + colorScheme.brightness == Brightness.light + ? Colors.white + : const Color(0xFF424242), + ); late final PdfHyperlinkDialogStyle _hyperlinkDialogStyle = PdfHyperlinkDialogStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? Colors.white - : const Color(0xFF424242), - closeIconColor: colorScheme.onSurfaceVariant[153], - ); + backgroundColor: + colorScheme.brightness == Brightness.light + ? Colors.white + : const Color(0xFF424242), + closeIconColor: colorScheme.onSurfaceVariant[153], + ); late final PdfPasswordDialogStyle _passwordDialogStyle = PdfPasswordDialogStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? Colors.white - : const Color(0xFF424242), - closeIconColor: colorScheme.onSurfaceVariant[153], - visibleIconColor: colorScheme.onSurfaceVariant[153], - ); + backgroundColor: + colorScheme.brightness == Brightness.light + ? Colors.white + : const Color(0xFF424242), + closeIconColor: colorScheme.onSurfaceVariant[153], + visibleIconColor: colorScheme.onSurfaceVariant[153], + ); @override - Color? get backgroundColor => colorScheme.brightness == Brightness.light - ? const Color(0xFFD6D6D6) - : const Color(0xFF303030); + Color? get backgroundColor => + colorScheme.brightness == Brightness.light + ? const Color(0xFFD6D6D6) + : const Color(0xFF303030); @override PdfScrollHeadStyle get scrollHeadStyle => _scrollHeadStyle; @@ -90,9 +97,10 @@ class SfPdfViewerThemeDataM3 extends SfPdfViewerThemeData { late final SfColorScheme colorScheme = SfTheme.colorScheme(context); late final PdfScrollHeadStyle _scrollHeadStyle = PdfScrollHeadStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(247, 242, 251, 1) - : const Color.fromRGBO(37, 35, 42, 1), + backgroundColor: + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(247, 242, 251, 1) + : const Color.fromRGBO(37, 35, 42, 1), ); late final PdfScrollStatusStyle _scrollStatusStyle = PdfScrollStatusStyle( @@ -101,14 +109,16 @@ class SfPdfViewerThemeDataM3 extends SfPdfViewerThemeData { ); late final PdfBookmarkViewStyle _bookmarkViewStyle = PdfBookmarkViewStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(247, 242, 251, 1) - : const Color.fromRGBO(37, 35, 42, 1), + backgroundColor: + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(247, 242, 251, 1) + : const Color.fromRGBO(37, 35, 42, 1), closeIconColor: colorScheme.onSurfaceVariant[138], backIconColor: colorScheme.onSurfaceVariant[138], - headerBarColor: colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(247, 242, 251, 1) - : const Color.fromRGBO(37, 35, 42, 1), + headerBarColor: + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(247, 242, 251, 1) + : const Color.fromRGBO(37, 35, 42, 1), navigationIconColor: colorScheme.onSurfaceVariant[138], selectionColor: colorScheme.primaryContainer[20], titleSeparatorColor: colorScheme.outlineVariant[41], @@ -116,32 +126,36 @@ class SfPdfViewerThemeDataM3 extends SfPdfViewerThemeData { late final PdfPaginationDialogStyle _paginationDialogStyle = PdfPaginationDialogStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(238, 232, 244, 1) - : const Color.fromRGBO(48, 45, 56, 1), - ); + backgroundColor: + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(238, 232, 244, 1) + : const Color.fromRGBO(48, 45, 56, 1), + ); late final PdfHyperlinkDialogStyle _hyperlinkDialogStyle = PdfHyperlinkDialogStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(238, 232, 244, 1) - : const Color.fromRGBO(48, 45, 56, 1), - closeIconColor: colorScheme.onSurfaceVariant[153], - ); + backgroundColor: + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(238, 232, 244, 1) + : const Color.fromRGBO(48, 45, 56, 1), + closeIconColor: colorScheme.onSurfaceVariant[153], + ); late final PdfPasswordDialogStyle _passwordDialogStyle = PdfPasswordDialogStyle( - backgroundColor: colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(238, 232, 244, 1) - : const Color.fromRGBO(48, 45, 56, 1), - closeIconColor: colorScheme.onSurfaceVariant[153], - visibleIconColor: colorScheme.onSurfaceVariant[153], - ); + backgroundColor: + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(238, 232, 244, 1) + : const Color.fromRGBO(48, 45, 56, 1), + closeIconColor: colorScheme.onSurfaceVariant[153], + visibleIconColor: colorScheme.onSurfaceVariant[153], + ); @override - Color? get backgroundColor => colorScheme.brightness == Brightness.light - ? const Color.fromRGBO(237, 230, 243, 1) - : const Color.fromRGBO(50, 46, 58, 1); + Color? get backgroundColor => + colorScheme.brightness == Brightness.light + ? const Color.fromRGBO(237, 230, 243, 1) + : const Color.fromRGBO(50, 46, 58, 1); @override Color? get progressBarColor => colorScheme.primary; diff --git a/packages/syncfusion_flutter_pdfviewer/pubspec.yaml b/packages/syncfusion_flutter_pdfviewer/pubspec.yaml index 494ee2ca9..70dd92e1f 100644 --- a/packages/syncfusion_flutter_pdfviewer/pubspec.yaml +++ b/packages/syncfusion_flutter_pdfviewer/pubspec.yaml @@ -1,19 +1,14 @@ name: syncfusion_flutter_pdfviewer description: Flutter PDF Viewer library is used to display a PDF document seamlessly and efficiently. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_pdfviewer environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 flutter: '>=1.20.0' flutter: - # This section identifies this Flutter project as a plugin project. - # The 'pluginClass' and Android 'package' identifiers should not ordinarily - # be modified. They are used by the tooling to maintain consistency when - # adding or updating assets for this project. - plugin: platforms: android: @@ -27,6 +22,8 @@ flutter: default_package: syncfusion_pdfviewer_macos windows: default_package: syncfusion_pdfviewer_windows + linux: + default_package: syncfusion_pdfviewer_linux assets: - assets/icons/dark/ @@ -58,6 +55,9 @@ dependencies: syncfusion_pdfviewer_windows: path: ../syncfusion_pdfviewer_windows + + syncfusion_pdfviewer_linux: + path: ../syncfusion_pdfviewer_linux syncfusion_flutter_core: path: ../syncfusion_flutter_core diff --git a/packages/syncfusion_flutter_pdfviewer_platform_interface/example/analysis_options.yaml b/packages/syncfusion_flutter_pdfviewer_platform_interface/example/analysis_options.yaml index 61b6c4de1..b08414c80 100644 --- a/packages/syncfusion_flutter_pdfviewer_platform_interface/example/analysis_options.yaml +++ b/packages/syncfusion_flutter_pdfviewer_platform_interface/example/analysis_options.yaml @@ -1,29 +1,3 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_flutter_pdfviewer_platform_interface/example/lib/main.dart b/packages/syncfusion_flutter_pdfviewer_platform_interface/example/lib/main.dart index 85974b449..f1b6ed12b 100644 --- a/packages/syncfusion_flutter_pdfviewer_platform_interface/example/lib/main.dart +++ b/packages/syncfusion_flutter_pdfviewer_platform_interface/example/lib/main.dart @@ -1,13 +1,13 @@ import 'package:flutter/material.dart'; void main() { - runApp(MaterialApp( - title: 'Syncfusion PDF Viewer Demo for Web', - theme: ThemeData( - useMaterial3: false, + runApp( + MaterialApp( + title: 'Syncfusion PDF Viewer Demo', + theme: ThemeData(useMaterial3: false), + home: const HomePage(), ), - home: const HomePage(), - )); + ); } /// Represents Homepage for Navigation @@ -22,9 +22,7 @@ class _HomePage extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Flutter PDF Viewer'), - ), + appBar: AppBar(title: const Text('Syncfusion Flutter PDF Viewer')), body: const Text('PDF Viewer'), ); } diff --git a/packages/syncfusion_flutter_pdfviewer_platform_interface/example/pubspec.yaml b/packages/syncfusion_flutter_pdfviewer_platform_interface/example/pubspec.yaml index 022e6f9a6..cc6ec2603 100644 --- a/packages/syncfusion_flutter_pdfviewer_platform_interface/example/pubspec.yaml +++ b/packages/syncfusion_flutter_pdfviewer_platform_interface/example/pubspec.yaml @@ -1,76 +1,18 @@ name: syncfusion_pdfviewer_platform_interface_example description: Demonstrates how to use the syncfusion_pdfviewer_platform_interface plugin. - -# 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 +publish_to: 'none' environment: - sdk: ">=2.17.0 <4.0.0" + sdk: ^3.7.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 - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.5 - 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: ^1.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. 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: - # - 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 + \ No newline at end of file diff --git a/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/method_channel_pdfviewer.dart b/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/method_channel_pdfviewer.dart index 27a8a696b..45d4afb6d 100644 --- a/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/method_channel_pdfviewer.dart +++ b/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/method_channel_pdfviewer.dart @@ -9,10 +9,14 @@ class MethodChannelPdfViewer extends PdfViewerPlatform { /// If success, returns page count else returns error message from respective platform @override Future initializePdfRenderer( - Uint8List documentBytes, String documentID) async { + Uint8List documentBytes, + String documentID, [ + String? password, + ]) async { return _channel.invokeMethod('initializePdfRenderer', { 'documentBytes': documentBytes, - 'documentID': documentID + 'documentID': documentID, + 'password': password, }); } @@ -31,19 +35,30 @@ class MethodChannelPdfViewer extends PdfViewerPlatform { /// Gets the image bytes of the specified page from the document at the specified width and height. @override Future getPage( - int pageNumber, int width, int height, String documentID) async { + int pageNumber, + int width, + int height, + String documentID, + ) async { return _channel.invokeMethod('getPage', { 'index': pageNumber, 'width': width, 'height': height, - 'documentID': documentID + 'documentID': documentID, }); } /// Gets the image's bytes information of the specified portion of the page @override - Future getTileImage(int pageNumber, double currentScale, double x, - double y, double width, double height, String documentID) async { + Future getTileImage( + int pageNumber, + double currentScale, + double x, + double y, + double width, + double height, + String documentID, + ) async { return _channel.invokeMethod('getTileImage', { 'pageNumber': pageNumber, 'scale': currentScale, @@ -51,7 +66,7 @@ class MethodChannelPdfViewer extends PdfViewerPlatform { 'y': y, 'width': width, 'height': height, - 'documentID': documentID + 'documentID': documentID, }); } diff --git a/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/pdfviewer_platform_interface.dart b/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/pdfviewer_platform_interface.dart index 22cf99abb..ae7fdcc4c 100644 --- a/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/pdfviewer_platform_interface.dart +++ b/packages/syncfusion_flutter_pdfviewer_platform_interface/lib/src/pdfviewer_platform_interface.dart @@ -35,9 +35,13 @@ abstract class PdfViewerPlatform extends PlatformInterface { /// /// If success, returns page count else returns error message from respective platform Future initializePdfRenderer( - Uint8List documentBytes, String documentID) async { + Uint8List documentBytes, + String documentID, [ + String? password, + ]) async { throw UnimplementedError( - 'initializePdfRenderer() has not been implemented.'); + 'initializePdfRenderer() has not been implemented.', + ); } /// Gets the height of all pages in the document. @@ -52,19 +56,33 @@ abstract class PdfViewerPlatform extends PlatformInterface { /// Gets the image's bytes information of the specified page. Future getImage( - int pageNumber, double scale, String documentID) async { + int pageNumber, + double scale, + String documentID, + ) async { throw UnimplementedError('getImage() has not been implemented.'); } /// Gets the image bytes of the specified page from the document at the specified width and height. Future getPage( - int pageNumber, int width, int height, String documentID) async { + int pageNumber, + int width, + int height, + String documentID, + ) async { throw UnimplementedError('getPage() has not been implemented.'); } /// Gets the image's bytes information of the specified portion of the page. - Future getTileImage(int pageNumber, double scale, double x, - double y, double width, double height, String documentID) async { + Future getTileImage( + int pageNumber, + double scale, + double x, + double y, + double width, + double height, + String documentID, + ) async { throw UnimplementedError('getTileImage() has not been implemented.'); } diff --git a/packages/syncfusion_flutter_pdfviewer_platform_interface/pubspec.yaml b/packages/syncfusion_flutter_pdfviewer_platform_interface/pubspec.yaml index adb0c240b..4eef9f1f4 100644 --- a/packages/syncfusion_flutter_pdfviewer_platform_interface/pubspec.yaml +++ b/packages/syncfusion_flutter_pdfviewer_platform_interface/pubspec.yaml @@ -1,11 +1,11 @@ name: syncfusion_pdfviewer_platform_interface description: A common platform interface for the Flutter PDF Viewer library that lets you view the PDF documents seamlessly and efficiently. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_pdfviewer_platform_interface environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 flutter: '>=1.20.0' dependencies: diff --git a/packages/syncfusion_flutter_signaturepad/CHANGELOG.md b/packages/syncfusion_flutter_signaturepad/CHANGELOG.md index a2c664666..31d80b500 100644 --- a/packages/syncfusion_flutter_signaturepad/CHANGELOG.md +++ b/packages/syncfusion_flutter_signaturepad/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of our Flutter signaturepad widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter signaturepad widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter signaturepad example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter signaturepad example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_signaturepad/example/lib/main.dart b/packages/syncfusion_flutter_signaturepad/example/lib/main.dart index 52279f860..c08ba5152 100644 --- a/packages/syncfusion_flutter_signaturepad/example/lib/main.dart +++ b/packages/syncfusion_flutter_signaturepad/example/lib/main.dart @@ -10,10 +10,7 @@ void main() { class SignaturePadApp extends StatelessWidget { @override Widget build(BuildContext context) { - return MaterialApp( - title: 'SfSignaturePad Demo', - home: _MyHomePage(), - ); + return MaterialApp(title: 'SfSignaturePad Demo', home: _MyHomePage()); } } @@ -37,8 +34,9 @@ class _MyHomePageState extends State<_MyHomePage> { } void _handleSaveButtonPressed() async { - final data = - await signatureGlobalKey.currentState!.toImage(pixelRatio: 3.0); + final data = await signatureGlobalKey.currentState!.toImage( + pixelRatio: 3.0, + ); final bytes = await data.toByteData(format: ui.ImageByteFormat.png); await Navigator.of(context).push( MaterialPageRoute( @@ -60,32 +58,39 @@ class _MyHomePageState extends State<_MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( - body: Column( - children: [ + body: Column( + children: [ Padding( - padding: EdgeInsets.all(10), - child: Container( - child: SfSignaturePad( - key: signatureGlobalKey, - backgroundColor: Colors.white, - strokeColor: Colors.black, - minimumStrokeWidth: 1.0, - maximumStrokeWidth: 4.0), - decoration: - BoxDecoration(border: Border.all(color: Colors.grey)))), - SizedBox(height: 10), - Row(children: [ - TextButton( - child: Text('ToImage'), - onPressed: _handleSaveButtonPressed, + padding: EdgeInsets.all(10), + child: Container( + child: SfSignaturePad( + key: signatureGlobalKey, + backgroundColor: Colors.white, + strokeColor: Colors.black, + minimumStrokeWidth: 1.0, + maximumStrokeWidth: 4.0, + ), + decoration: BoxDecoration(border: Border.all(color: Colors.grey)), ), - TextButton( - child: Text('Clear'), - onPressed: _handleClearButtonPressed, - ) - ], mainAxisAlignment: MainAxisAlignment.spaceEvenly) + ), + SizedBox(height: 10), + Row( + children: [ + TextButton( + child: Text('ToImage'), + onPressed: _handleSaveButtonPressed, + ), + TextButton( + child: Text('Clear'), + onPressed: _handleClearButtonPressed, + ), + ], + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + ), ], - mainAxisAlignment: MainAxisAlignment.center, - crossAxisAlignment: CrossAxisAlignment.center)); + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.center, + ), + ); } } diff --git a/packages/syncfusion_flutter_signaturepad/example/pubspec.yaml b/packages/syncfusion_flutter_signaturepad/example/pubspec.yaml index 065341776..1c87ebbad 100644 --- a/packages/syncfusion_flutter_signaturepad/example/pubspec.yaml +++ b/packages/syncfusion_flutter_signaturepad/example/pubspec.yaml @@ -4,7 +4,7 @@ description: This project demonstrates how to use Syncfusion Flutter SignaturePa version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -18,44 +18,7 @@ dev_dependencies: flutter_test: sdk: flutter -# 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. 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: - # - 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 diff --git a/packages/syncfusion_flutter_signaturepad/lib/signaturepad.dart b/packages/syncfusion_flutter_signaturepad/lib/signaturepad.dart index f55d15f1b..a62052cc4 100644 --- a/packages/syncfusion_flutter_signaturepad/lib/signaturepad.dart +++ b/packages/syncfusion_flutter_signaturepad/lib/signaturepad.dart @@ -162,16 +162,16 @@ class SfSignaturePad extends StatefulWidget { /// print("Signature has been completed in Signature Pad"); /// }); /// ``` - const SfSignaturePad( - {Key? key, - this.minimumStrokeWidth = _kMinimumStrokeWidth, - this.maximumStrokeWidth = _kMaximumStrokeWidth, - this.backgroundColor, - this.strokeColor, - this.onDrawStart, - this.onDraw, - this.onDrawEnd}) - : super(key: key); + const SfSignaturePad({ + Key? key, + this.minimumStrokeWidth = _kMinimumStrokeWidth, + this.maximumStrokeWidth = _kMaximumStrokeWidth, + this.backgroundColor, + this.strokeColor, + this.onDrawStart, + this.onDraw, + this.onDrawEnd, + }) : super(key: key); /// The minimum width of the signature stroke. /// @@ -369,8 +369,9 @@ class SfSignaturePadState extends State { Future toImage({double pixelRatio = 1.0}) { final RenderObject? signatureRenderBox = context.findRenderObject(); // ignore: avoid_as - return (signatureRenderBox! as RenderSignaturePad) - .toImage(pixelRatio: pixelRatio); + return (signatureRenderBox! as RenderSignaturePad).toImage( + pixelRatio: pixelRatio, + ); } /// Clears all the signature strokes in the [SfSignaturePad]. @@ -457,13 +458,14 @@ class SfSignaturePadState extends State { widget.strokeColor ?? (isDarkTheme ? Colors.white : Colors.black); return _SfSignaturePadRenderObjectWidget( - minimumStrokeWidth: widget.minimumStrokeWidth, - maximumStrokeWidth: widget.maximumStrokeWidth, - backgroundColor: backgroundColor, - strokeColor: strokeColor, - onDrawStart: widget.onDrawStart, - onDraw: widget.onDraw, - onDrawEnd: widget.onDrawEnd); + minimumStrokeWidth: widget.minimumStrokeWidth, + maximumStrokeWidth: widget.maximumStrokeWidth, + backgroundColor: backgroundColor, + strokeColor: strokeColor, + onDrawStart: widget.onDrawStart, + onDraw: widget.onDraw, + onDrawEnd: widget.onDrawEnd, + ); } } @@ -490,19 +492,22 @@ class _SfSignaturePadRenderObjectWidget extends LeafRenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return RenderSignaturePad( - minimumStrokeWidth: minimumStrokeWidth, - maximumStrokeWidth: maximumStrokeWidth, - backgroundColor: backgroundColor, - strokeColor: strokeColor, - onDrawEnd: onDrawEnd, - onDraw: onDraw, - onDrawStart: onDrawStart, - gestureSettings: MediaQuery.of(context).gestureSettings); + minimumStrokeWidth: minimumStrokeWidth, + maximumStrokeWidth: maximumStrokeWidth, + backgroundColor: backgroundColor, + strokeColor: strokeColor, + onDrawEnd: onDrawEnd, + onDraw: onDraw, + onDrawStart: onDrawStart, + gestureSettings: MediaQuery.of(context).gestureSettings, + ); } @override void updateRenderObject( - BuildContext context, RenderSignaturePad renderObject) { + BuildContext context, + RenderSignaturePad renderObject, + ) { renderObject ..minimumStrokeWidth = minimumStrokeWidth ..maximumStrokeWidth = maximumStrokeWidth @@ -517,56 +522,61 @@ class _SfSignaturePadRenderObjectWidget extends LeafRenderObjectWidget { /// A render object for [SfSignaturePad] widget. class RenderSignaturePad extends RenderBox { /// Creates a new instance of [RenderSignaturePad]. - RenderSignaturePad( - {required double minimumStrokeWidth, - required double maximumStrokeWidth, - required Color backgroundColor, - required Color strokeColor, - required DeviceGestureSettings gestureSettings, - SignatureOnDrawStartCallback? onDrawStart, - SignatureDrawCallback? onDraw, - VoidCallback? onDrawEnd}) - : _minimumStrokeWidth = minimumStrokeWidth, - _maximumStrokeWidth = maximumStrokeWidth, - _backgroundColor = backgroundColor, - _strokeColor = strokeColor, - _onDrawStart = onDrawStart, - _onDraw = onDraw, - _gestureArenaTeam = GestureArenaTeam(), - _onDrawEnd = onDrawEnd { - _panGestureRecognizer = PanGestureRecognizer() - ..team = _gestureArenaTeam - ..onStart = _handleDragStart - ..onUpdate = _handleDragUpdate - ..onEnd = _handleDragEnd - ..gestureSettings = gestureSettings - ..dragStartBehavior = DragStartBehavior.down; - - _verticalDragGestureRecognizer = VerticalDragGestureRecognizer() - ..team = _gestureArenaTeam - ..gestureSettings = gestureSettings - ..onStart = _dragStart; - - _horizontalDragGestureRecognizer = HorizontalDragGestureRecognizer() - ..team = _gestureArenaTeam - ..gestureSettings = gestureSettings - ..onStart = _dragStart; + RenderSignaturePad({ + required double minimumStrokeWidth, + required double maximumStrokeWidth, + required Color backgroundColor, + required Color strokeColor, + required DeviceGestureSettings gestureSettings, + SignatureOnDrawStartCallback? onDrawStart, + SignatureDrawCallback? onDraw, + VoidCallback? onDrawEnd, + }) : _minimumStrokeWidth = minimumStrokeWidth, + _maximumStrokeWidth = maximumStrokeWidth, + _backgroundColor = backgroundColor, + _strokeColor = strokeColor, + _onDrawStart = onDrawStart, + _onDraw = onDraw, + _gestureArenaTeam = GestureArenaTeam(), + _onDrawEnd = onDrawEnd { + _panGestureRecognizer = + PanGestureRecognizer() + ..team = _gestureArenaTeam + ..onStart = _handleDragStart + ..onUpdate = _handleDragUpdate + ..onEnd = _handleDragEnd + ..gestureSettings = gestureSettings + ..dragStartBehavior = DragStartBehavior.down; + + _verticalDragGestureRecognizer = + VerticalDragGestureRecognizer() + ..team = _gestureArenaTeam + ..gestureSettings = gestureSettings + ..onStart = _dragStart; + + _horizontalDragGestureRecognizer = + HorizontalDragGestureRecognizer() + ..team = _gestureArenaTeam + ..gestureSettings = gestureSettings + ..onStart = _dragStart; _tapGestureRecognizer = TapGestureRecognizer()..onTapUp = _handleTapUp; _gestureArenaTeam.captain = _panGestureRecognizer; - _paintStrokeStyle = Paint() - ..color = _strokeColor - ..strokeWidth = _kMaximumStrokeWidth - ..strokeCap = StrokeCap.round - ..style = PaintingStyle.fill - ..isAntiAlias = true; + _paintStrokeStyle = + Paint() + ..color = _strokeColor + ..strokeWidth = _kMaximumStrokeWidth + ..strokeCap = StrokeCap.round + ..style = PaintingStyle.fill + ..isAntiAlias = true; - _paintBackgroundStyle = Paint() - ..color = backgroundColor - ..style = PaintingStyle.fill - ..isAntiAlias = true; + _paintBackgroundStyle = + Paint() + ..color = backgroundColor + ..style = PaintingStyle.fill + ..isAntiAlias = true; _restrictBezierPathCalculation = _minimumStrokeWidth == _maximumStrokeWidth; _data = >[]; @@ -810,8 +820,10 @@ class RenderSignaturePad extends RenderBox { } void _handleTapUp(TapUpDetails details) { - final _TouchPoint touchPoint = - _TouchPoint(x: details.localPosition.dx, y: details.localPosition.dy); + final _TouchPoint touchPoint = _TouchPoint( + x: details.localPosition.dx, + y: details.localPosition.dy, + ); final List<_TouchPoint> newPointGroup = <_TouchPoint>[touchPoint]; if (onDrawStart != null && onDrawStart!()) { return; @@ -871,12 +883,16 @@ class RenderSignaturePad extends RenderBox { final double x = touchOffset.dx; final double y = touchOffset.dy; - final _TouchPoint point = - _TouchPoint(x: x, y: y, time: DateTime.now().millisecondsSinceEpoch); + final _TouchPoint point = _TouchPoint( + x: x, + y: y, + time: DateTime.now().millisecondsSinceEpoch, + ); final List<_TouchPoint> lastPoints = _data[_data.length - 1]; - final double distance = lastPoints.isNotEmpty - ? _distance(lastPoints[lastPoints.length - 1], point) - : 1; + final double distance = + lastPoints.isNotEmpty + ? _distance(lastPoints[lastPoints.length - 1], point) + : 1; if (distance > 0) { if (!_restrictBezierPathCalculation) { final _Bezier? curve = _calculateBezierPath(point); @@ -908,12 +924,17 @@ class RenderSignaturePad extends RenderBox { final _TouchPoint endPoint = _lastPoints[2]; final double velocity = _velocityFilterWeight * _velocity(startPoint, endPoint) + - (1 - _velocityFilterWeight) * _lastVelocity; - final double newWidth = - max(_maximumStrokeWidth / (velocity + 1), _minimumStrokeWidth); + (1 - _velocityFilterWeight) * _lastVelocity; + final double newWidth = max( + _maximumStrokeWidth / (velocity + 1), + _minimumStrokeWidth, + ); final _Bezier curve = _Bezier.fromPoints( - points: _lastPoints, start: _lastWidth, end: newWidth); + points: _lastPoints, + start: _lastWidth, + end: newWidth, + ); _lastPoints.removeAt(0); _lastVelocity = velocity; _lastWidth = newWidth; @@ -944,8 +965,10 @@ class RenderSignaturePad extends RenderBox { y += 3 * u * tt * curve.control2.y; y += ttt * curve.endPoint.y; - final double width = - min(curve.startWidth + ttt * widthDelta, _maximumStrokeWidth); + final double width = min( + curve.startWidth + ttt * widthDelta, + _maximumStrokeWidth, + ); _bezierPoints.add(_CachePoint(x: x, y: y, width: width)); _currentPath.addArc(Rect.fromLTWH(x, y, width, width), 0, 180); @@ -971,8 +994,10 @@ class RenderSignaturePad extends RenderBox { /// * [renderToContext2D], renders the signature to a HTML canvas. Future toImage({double pixelRatio = 1.0}) async { // ignore: avoid_as - return (layer! as OffsetLayer) - .toImage(Offset.zero & size, pixelRatio: pixelRatio); + return (layer! as OffsetLayer).toImage( + Offset.zero & size, + pixelRatio: pixelRatio, + ); } /// Clears the signature strokes in [RenderSignaturePad]. @@ -1002,7 +1027,10 @@ class RenderSignaturePad extends RenderBox { for (int i = 0; i < points.length; i++) { final _TouchPoint basicPoint = points[i]; final _TouchPoint point = _TouchPoint( - x: basicPoint.x, y: basicPoint.y, time: basicPoint.time); + x: basicPoint.x, + y: basicPoint.y, + time: basicPoint.time, + ); if (i == 0) { _reset(); _currentPath = Path(); @@ -1045,14 +1073,26 @@ class RenderSignaturePad extends RenderBox { for (int i = 0; i < _dotPoints.length; i++) { final Offset point = _dotPoints[i]; context2D.moveTo(point.dx, point.dy); - context2D.arc(point.dx, point.dy, - (_minimumStrokeWidth + _maximumStrokeWidth) / 2, 0, pi * 2, true); + context2D.arc( + point.dx, + point.dy, + (_minimumStrokeWidth + _maximumStrokeWidth) / 2, + 0, + pi * 2, + true, + ); } for (int i = 0; i < _bezierPoints.length; i++) { context2D.moveTo(_bezierPoints[i].x, _bezierPoints[i].y); - context2D.arc(_bezierPoints[i].x, _bezierPoints[i].y, - _bezierPoints[i].width / 2, 0, 2 * pi, false); + context2D.arc( + _bezierPoints[i].x, + _bezierPoints[i].y, + _bezierPoints[i].width / 2, + 0, + 2 * pi, + false, + ); } context2D.fillStyle = 'rgba($strokePenColor)'; @@ -1062,8 +1102,14 @@ class RenderSignaturePad extends RenderBox { if (_data[i].length == 1) { final _TouchPoint point = _data[i][0]; context2D.moveTo(point.x, point.y); - context2D.arc(point.x, point.y, - (_minimumStrokeWidth + _maximumStrokeWidth) / 2, 0, pi * 2, true); + context2D.arc( + point.x, + point.y, + (_minimumStrokeWidth + _maximumStrokeWidth) / 2, + 0, + pi * 2, + true, + ); context2D.fillStyle = 'rgba($strokePenColor)'; context2D.fill(); } else { @@ -1087,52 +1133,61 @@ class RenderSignaturePad extends RenderBox { @override void paint(PaintingContext context, Offset offset) { context.pushClipRect( - needsCompositing, offset, Rect.fromLTWH(0, 0, size.width, size.height), - (PaintingContext context, Offset offset) { - final Canvas canvas = context.canvas; - - //Drawing the background of the SignaturePad - canvas.drawRect( + needsCompositing, + offset, + Rect.fromLTWH(0, 0, size.width, size.height), + (PaintingContext context, Offset offset) { + final Canvas canvas = context.canvas; + + //Drawing the background of the SignaturePad + canvas.drawRect( Rect.fromLTWH(offset.dx, offset.dy, size.width, size.height), - _paintBackgroundStyle); - - if (_restrictBezierPathCalculation) { - _paintStrokeStyle.strokeWidth = _minimumStrokeWidth; - for (int i = 0; i < _data.length; i++) { - if (_data[i].length == 1) { - final _TouchPoint point = _data[i][0]; - canvas.drawCircle( + _paintBackgroundStyle, + ); + + if (_restrictBezierPathCalculation) { + _paintStrokeStyle.strokeWidth = _minimumStrokeWidth; + for (int i = 0; i < _data.length; i++) { + if (_data[i].length == 1) { + final _TouchPoint point = _data[i][0]; + canvas.drawCircle( Offset(point.x, point.y), (_minimumStrokeWidth + _maximumStrokeWidth) / 2, - _paintStrokeStyle); - } else { - final List<_TouchPoint> path = _data[i]; - for (int i = 0; i < path.length; i++) { - if (i < path.length - 1) { - canvas.drawLine( - Offset(path[i].x, path[i].y), - Offset(path[i + 1].x, path[i + 1].y), - _paintStrokeStyle, - ); + _paintStrokeStyle, + ); + } else { + final List<_TouchPoint> path = _data[i]; + for (int i = 0; i < path.length; i++) { + if (i < path.length - 1) { + canvas.drawLine( + Offset(path[i].x, path[i].y), + Offset(path[i + 1].x, path[i + 1].y), + _paintStrokeStyle, + ); + } } } } - } - } else { - if (_dotPoints.isNotEmpty) { - _paintStrokeStyle.strokeWidth = - (_minimumStrokeWidth + _maximumStrokeWidth) / 2; - canvas.drawPoints(ui.PointMode.points, _dotPoints, _paintStrokeStyle); - } + } else { + if (_dotPoints.isNotEmpty) { + _paintStrokeStyle.strokeWidth = + (_minimumStrokeWidth + _maximumStrokeWidth) / 2; + canvas.drawPoints( + ui.PointMode.points, + _dotPoints, + _paintStrokeStyle, + ); + } - if (_pathCollection.isNotEmpty) { - _paintStrokeStyle.strokeWidth = _maximumStrokeWidth; - for (int i = 0; i < _pathCollection.length; i++) { - canvas.drawPath(_pathCollection[i], _paintStrokeStyle); + if (_pathCollection.isNotEmpty) { + _paintStrokeStyle.strokeWidth = _maximumStrokeWidth; + for (int i = 0; i < _pathCollection.length; i++) { + canvas.drawPath(_pathCollection[i], _paintStrokeStyle); + } } } - } - }); + }, + ); } @override @@ -1143,8 +1198,14 @@ class RenderSignaturePad extends RenderBox { } class _Bezier { - _Bezier(this.startPoint, this.control2, this.control1, this.endPoint, - this.startWidth, this.endWidth); + _Bezier( + this.startPoint, + this.control2, + this.control1, + this.endPoint, + this.startWidth, + this.endWidth, + ); final _TouchPoint startPoint; final _TouchPoint control2; @@ -1153,10 +1214,11 @@ class _Bezier { final double startWidth; final double endWidth; - static _Bezier fromPoints( - {required List<_TouchPoint> points, - required double start, - required double end}) { + static _Bezier fromPoints({ + required List<_TouchPoint> points, + required double start, + required double end, + }) { final _TouchPoint c2 = calculateControlPoints(points[0], points[1], points[2])[1]; final _TouchPoint c3 = @@ -1165,16 +1227,23 @@ class _Bezier { } static List<_TouchPoint> calculateControlPoints( - _TouchPoint s1, _TouchPoint s2, _TouchPoint s3) { + _TouchPoint s1, + _TouchPoint s2, + _TouchPoint s3, + ) { final double dx1 = s1.x - s2.x; final double dy1 = s1.y - s2.y; final double dx2 = s2.x - s3.x; final double dy2 = s2.y - s3.y; - final Point m1 = - Point((s1.x + s2.x) / 2.0, (s1.y + s2.y) / 2.0); - final Point m2 = - Point((s2.x + s3.x) / 2.0, (s2.y + s3.y) / 2.0); + final Point m1 = Point( + (s1.x + s2.x) / 2.0, + (s1.y + s2.y) / 2.0, + ); + final Point m2 = Point( + (s2.x + s3.x) / 2.0, + (s2.y + s3.y) / 2.0, + ); final double l1 = sqrt(dx1 * dx1 + dy1 * dy1); final double l2 = sqrt(dx2 * dx2 + dy2 * dy2); @@ -1206,10 +1275,20 @@ class _Bezier { for (int i = 0; i <= steps; i += 1) { final double t = i / steps; - final double cx = - point(t, startPoint.x, control1.x, control2.x, endPoint.x); - final double cy = - point(t, startPoint.y, control1.y, control2.y, endPoint.y); + final double cx = point( + t, + startPoint.x, + control1.x, + control2.x, + endPoint.x, + ); + final double cy = point( + t, + startPoint.y, + control1.y, + control2.y, + endPoint.y, + ); if (i > 0) { final double xDiff = cx - px; diff --git a/packages/syncfusion_flutter_signaturepad/pubspec.yaml b/packages/syncfusion_flutter_signaturepad/pubspec.yaml index 47b87dabd..984cce566 100644 --- a/packages/syncfusion_flutter_signaturepad/pubspec.yaml +++ b/packages/syncfusion_flutter_signaturepad/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_signaturepad description: The Flutter Signature Pad widget allows you to capture smooth and more realistic signatures through drawn gestures and save it as an image. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_signaturepad screenshots: @@ -8,17 +8,12 @@ screenshots: path: screenshots/signature_pad.gif environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: sdk: flutter syncfusion_flutter_core: path: ../syncfusion_flutter_core - - - - - flutter: diff --git a/packages/syncfusion_flutter_sliders/CHANGELOG.md b/packages/syncfusion_flutter_sliders/CHANGELOG.md index d51146b23..429f16d24 100644 --- a/packages/syncfusion_flutter_sliders/CHANGELOG.md +++ b/packages/syncfusion_flutter_sliders/CHANGELOG.md @@ -2,11 +2,48 @@ **General** +* The compatible version of our Flutter sliders widget has been updated to Flutter SDK 3.32.0. + +## Slider + +**Features** + +* #FR49315 - Now, the Slider labels can be customized individually using the `onLabelCreated` property. +* #FR66359 - Now, the Slider support keyboard navigation accessibility using the Left, Right, Up, Down arrow keys, and the Tab key. + +## Range Slider + +**Features** + +* #FR49315 - Now, the Range Slider labels can be customized individually using the `onLabelCreated` property. +* #FR66359 - Now, the Range Slider support keyboard navigation accessibility using the Left, Right, Up, Down arrow keys, and the Tab key. + +## Range Selector + +**Features** + +* #FR49315 - Now, the Range Selector labels can be customized individually using the `onLabelCreated` property. +* #FR66359 - Now, the Range Selector support keyboard navigation accessibility using the Left, Right, Up, Down arrow keys, and the Tab key. + +### Breaking changes + +The `labelFormatterCallback` property has been deprecated. Use `onLabelCreated` instead to customize the label's format and style. + +## [29.1.39] - 04/22/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 03/25/2025 + +**General** + * The compatible version of our Flutter sliders widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter sliders example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter sliders example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. -## [28.2.7] - 25/02/2025 +## [28.2.7] - 02/25/2025 **General** diff --git a/packages/syncfusion_flutter_sliders/assets/fonts/Roboto-Medium.ttf b/packages/syncfusion_flutter_sliders/assets/fonts/Roboto-Medium.ttf new file mode 100644 index 000000000..d629e9848 Binary files /dev/null and b/packages/syncfusion_flutter_sliders/assets/fonts/Roboto-Medium.ttf differ diff --git a/packages/syncfusion_flutter_sliders/assets/images/lake.jpg b/packages/syncfusion_flutter_sliders/assets/images/lake.jpg new file mode 100644 index 000000000..6c685bcc6 Binary files /dev/null and b/packages/syncfusion_flutter_sliders/assets/images/lake.jpg differ diff --git a/packages/syncfusion_flutter_sliders/example/lib/main.dart b/packages/syncfusion_flutter_sliders/example/lib/main.dart index b32ea6c27..f3d92fd06 100644 --- a/packages/syncfusion_flutter_sliders/example/lib/main.dart +++ b/packages/syncfusion_flutter_sliders/example/lib/main.dart @@ -14,10 +14,7 @@ class RangeSelectorApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Range Selector Demo', - home: MyHomePage(), - ); + return const MaterialApp(title: 'Range Selector Demo', home: MyHomePage()); } } @@ -46,60 +43,62 @@ class _MyHomePageState extends State { final DateTime _dateMin = DateTime(2003); final DateTime _dateMax = DateTime(2010); - final SfRangeValues _dateValues = - SfRangeValues(DateTime(2005), DateTime(2008)); + final SfRangeValues _dateValues = SfRangeValues( + DateTime(2005), + DateTime(2008), + ); @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: const Text('Syncfusion Flutter Range Selector'), - ), + appBar: AppBar(title: const Text('Syncfusion Flutter Range Selector')), body: Container( - margin: EdgeInsets.zero, - padding: EdgeInsets.zero, - child: Stack( - children: [ - Padding( - padding: const EdgeInsets.only(top: 10), - child: Center( - // ignore: missing_required_param - child: SfRangeSelector( - min: _dateMin, - max: _dateMax, - initialValues: _dateValues, - labelPlacement: LabelPlacement.betweenTicks, - interval: 1, - dateIntervalType: DateIntervalType.years, - dateFormat: DateFormat.y(), - showTicks: true, - showLabels: true, - child: SizedBox( - height: 200, - child: SfCartesianChart( - margin: EdgeInsets.zero, - primaryXAxis: DateTimeAxis( - minimum: _dateMin, - maximum: _dateMax, - isVisible: false, - ), - primaryYAxis: const NumericAxis( - isVisible: false, - maximum: 4, - ), - series: >[ - SplineAreaSeries( - dataSource: _chartData, - xValueMapper: (Data sales, int index) => sales.x, - yValueMapper: (Data sales, int index) => sales.y) - ], + margin: EdgeInsets.zero, + padding: EdgeInsets.zero, + child: Stack( + children: [ + Padding( + padding: const EdgeInsets.only(top: 10), + child: Center( + // ignore: missing_required_param + child: SfRangeSelector( + min: _dateMin, + max: _dateMax, + initialValues: _dateValues, + labelPlacement: LabelPlacement.betweenTicks, + interval: 1, + dateIntervalType: DateIntervalType.years, + dateFormat: DateFormat.y(), + showTicks: true, + showLabels: true, + child: SizedBox( + height: 200, + child: SfCartesianChart( + margin: EdgeInsets.zero, + primaryXAxis: DateTimeAxis( + minimum: _dateMin, + maximum: _dateMax, + isVisible: false, ), + primaryYAxis: const NumericAxis( + isVisible: false, + maximum: 4, + ), + series: >[ + SplineAreaSeries( + dataSource: _chartData, + xValueMapper: (Data sales, int index) => sales.x, + yValueMapper: (Data sales, int index) => sales.y, + ), + ], ), ), ), ), - ], - )), + ), + ], + ), + ), ); } } diff --git a/packages/syncfusion_flutter_sliders/example/pubspec.yaml b/packages/syncfusion_flutter_sliders/example/pubspec.yaml index 5608bcb21..59c70e0dc 100644 --- a/packages/syncfusion_flutter_sliders/example/pubspec.yaml +++ b/packages/syncfusion_flutter_sliders/example/pubspec.yaml @@ -1,20 +1,10 @@ name: sliders_sample description: A new Flutter project. -# 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 used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -24,53 +14,12 @@ dependencies: syncfusion_flutter_sliders: ^27.1.52 syncfusion_flutter_charts: ^27.1.52 - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: '^1.0.8' dev_dependencies: flutter_test: sdk: flutter - -# 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. 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: - # - 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 diff --git a/packages/syncfusion_flutter_sliders/lib/src/common.dart b/packages/syncfusion_flutter_sliders/lib/src/common.dart index 957ae6db6..6e153067a 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/common.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/common.dart @@ -1,37 +1,112 @@ import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; // ignore_for_file: public_member_api_docs -/// Signature for formatting or changing the whole numeric or date label text. -typedef LabelFormatterCallback = String Function( +/// A label used in [SfSlider] to customize its value labels. +class SliderLabel { + /// Creates a [SliderLabel] with the specified [text] and [textStyle]. + const SliderLabel({required this.text, required this.textStyle}); - /// actualValue will be either [DateTime] or [double] - /// based on given [values]. - dynamic actualValue, + /// Contains the text of the slider label. + final String text; - /// If the actual value is [double], it is formatted by [numberFormat] and - /// if the actual value is [DateTime], it is formatted by [dateFormat]. - String formattedText); + /// The TextStyle to customize the label text. + final TextStyle textStyle; +} -/// Signature for formatting or changing the whole tooltip label text. -typedef TooltipTextFormatterCallback = String Function( +/// A label used in [SfRangeSlider] to customize its value labels. +class RangeSliderLabel extends SliderLabel { + /// Creates a [RangeSliderLabel] with the given [text] and [textStyle]. + const RangeSliderLabel({required super.text, required super.textStyle}); +} - /// actualValue will be either [DateTime] or [double] - /// based on given [values]. - dynamic actualValue, +/// A label used in [SfRangeSelector] to customize its value labels. +class RangeSelectorLabel extends RangeSliderLabel { + /// Creates a [RangeSelectorLabel] with the given [text] and [textStyle]. + const RangeSelectorLabel({required super.text, required super.textStyle}); +} - /// If the actual value is [double], it is formatted by [numberFormat] and - /// if the actual value is [DateTime], it is formatted by [dateFormat]. - String formattedText); +/// Signature for formatting or changing the whole numeric or date label text. +typedef LabelFormatterCallback = + String Function( + /// The actual value, which will be either a [DateTime] or [double] + /// based on given [values]. + dynamic actualValue, + + /// If the actual value is [double], it is formatted by [numberFormat] and + /// if the actual value is [DateTime], it is formatted by [dateFormat]. + String formattedText, + ); + +/// Signature for customizing the appearance of the label by returning a +/// [SliderLabel] widget with the provided text and text style. +typedef SliderLabelCreatedCallback = + SliderLabel Function( + /// The actual value, which will be either a [DateTime] or [double] + /// based on given [values]. + dynamic actualValue, + + /// If the actual value is [double], it is formatted by [numberFormat] and + /// if the actual value is [DateTime], it is formatted by [dateFormat]. + String formattedText, + + /// Customizes the text style of the slider label. + TextStyle textStyle, + ); + +/// Signature for customizing the appearance of the label by returning a +/// [RangeSliderLabel] widget with the provided text and text style. +typedef RangeSliderLabelCreatedCallback = + RangeSliderLabel Function( + /// The actual value, which will be either a [DateTime] or [double] + /// based on given [values]. + dynamic actualValue, + + /// If the actual value is [double], it is formatted by [numberFormat] and + /// if the actual value is [DateTime], it is formatted by [dateFormat]. + String formattedText, + + /// Customizes the text style of the range slider label. + TextStyle textStyle, + ); + +/// Signature for customizing the appearance of the label by returning a +/// [RangeSelectorLabel] widget with the provided text and text style. +typedef RangeSelectorLabelCreatedCallback = + RangeSelectorLabel Function( + /// The actual value, which will be either a [DateTime] or [double] + /// based on given [values]. + dynamic actualValue, + + /// If the actual value is [double], it is formatted by [numberFormat] and + /// if the actual value is [DateTime], it is formatted by [dateFormat]. + String formattedText, + + /// Customizes the text style of the range selector label. + TextStyle textStyle, + ); + +/// Signature for formatting or changing the whole tooltip label text. +typedef TooltipTextFormatterCallback = + String Function( + /// actualValue will be either [DateTime] or [double] + /// based on given [values]. + dynamic actualValue, + + /// If the actual value is [double], it is formatted by [numberFormat] and + /// if the actual value is [DateTime], it is formatted by [dateFormat]. + String formattedText, + ); /// The value will be either [double] or [DateTime] based on the `values`. typedef SfSliderSemanticFormatterCallback = String Function(dynamic value); -typedef RangeSliderSemanticFormatterCallback = String Function( - dynamic value, SfThumb thumb); +typedef RangeSliderSemanticFormatterCallback = + String Function(dynamic value, SfThumb thumb); -typedef RangeSelectorSemanticFormatterCallback = String Function( - dynamic value, SfThumb thumb); +typedef RangeSelectorSemanticFormatterCallback = + String Function(dynamic value, SfThumb thumb); /// Option to place the labels either between the major ticks /// or on the major ticks. @@ -40,7 +115,7 @@ enum LabelPlacement { onTicks, /// betweenTicks places the labels between the major ticks. - betweenTicks + betweenTicks, } /// Placement of edge labels in the axis. @@ -50,7 +125,7 @@ enum EdgeLabelPlacement { /// - EdgeLabelPlacement.inside, shift the edge labels inside the plot area /// bounds. - inside + inside, } /// The type of date interval. It can be years to seconds. @@ -106,7 +181,7 @@ enum DateIntervalType { /// `dateIntervalType` is [seconds] then range slider will render labels for /// `Jan 01, 2000 09:00:00`, `Jan 01, 2000 09:00:20`, `Jan 01, 2000 09:00:40`, /// and `Jan 01, 2000 09:01:00` respectively. - seconds + seconds, } /// Represents the [SfRangeSlider] or [SfRangeSelector] thumbs. @@ -121,7 +196,7 @@ enum SfThumb { both, /// represents none of the thumb. - none + none, } /// Represents the dragging behavior of the [SfRangeSelector] thumbs. @@ -140,7 +215,7 @@ enum SliderDragMode { /// When [SliderDragMode] is set to [SliderDragMode.both], individual thumb /// can be moved by dragging it, and also both the thumbs can be moved /// at the same time by dragging in the area between start and end thumbs. - both + both, } enum SliderTooltipPosition { left, right } @@ -166,14 +241,18 @@ class SfRangeValues extends DiagnosticableTree { // ignore: avoid_as final double value = start as double; return SfRangeValues( - DateTime.fromMillisecondsSinceEpoch(value.toInt()), end ?? this.end); + DateTime.fromMillisecondsSinceEpoch(value.toInt()), + end ?? this.end, + ); } else if (end != null && end.runtimeType == num && this.start.runtimeType == DateTime) { // ignore: avoid_as final double value = end as double; - return SfRangeValues(start ?? this.start, - DateTime.fromMillisecondsSinceEpoch(value.toInt())); + return SfRangeValues( + start ?? this.start, + DateTime.fromMillisecondsSinceEpoch(value.toInt()), + ); } return SfRangeValues(start ?? this.start, end ?? this.end); @@ -196,13 +275,14 @@ class SliderStepDuration extends DiagnosticableTree { /// The discrete position is calculated by adding the arguments /// given in the [SliderStepDuration] object. /// By default, all arguments values are zero. - const SliderStepDuration( - {this.years = 0, - this.months = 0, - this.days = 0, - this.hours = 0, - this.minutes = 0, - this.seconds = 0}); + const SliderStepDuration({ + this.years = 0, + this.months = 0, + this.days = 0, + this.hours = 0, + this.minutes = 0, + this.seconds = 0, + }); /// Moves the thumbs based on years. /// diff --git a/packages/syncfusion_flutter_sliders/lib/src/constants.dart b/packages/syncfusion_flutter_sliders/lib/src/constants.dart index a931dd51a..5be96360f 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/constants.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/constants.dart @@ -1,4 +1,5 @@ import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; // ignore_for_file: public_member_api_docs @@ -41,3 +42,36 @@ enum ChildElements { } enum SliderType { horizontal, vertical } + +enum SliderKeyType { right, left, up, down } + +class SliderKeyIntent extends Intent { + const SliderKeyIntent({required this.type}); + + const SliderKeyIntent.right() : type = SliderKeyType.right; + + const SliderKeyIntent.left() : type = SliderKeyType.left; + + const SliderKeyIntent.up() : type = SliderKeyType.up; + + const SliderKeyIntent.down() : type = SliderKeyType.down; + + final SliderKeyType type; +} + +// Keyboard mapping for a focused slider. +const Map KeyboardNavShortcutMap = + { + SingleActivator(LogicalKeyboardKey.arrowUp): SliderKeyIntent.up(), + SingleActivator(LogicalKeyboardKey.arrowDown): SliderKeyIntent.down(), + SingleActivator(LogicalKeyboardKey.arrowLeft): SliderKeyIntent.left(), + SingleActivator(LogicalKeyboardKey.arrowRight): SliderKeyIntent.right(), + }; + +// Keyboard mapping for a focused slider when using directional navigation. +// The vertical inputs are not handled to allow navigating out of the slider. +const Map KeyboardDirectionalNavShortcutMap = + { + SingleActivator(LogicalKeyboardKey.arrowLeft): SliderKeyIntent.left(), + SingleActivator(LogicalKeyboardKey.arrowRight): SliderKeyIntent.right(), + }; diff --git a/packages/syncfusion_flutter_sliders/lib/src/range_selector.dart b/packages/syncfusion_flutter_sliders/lib/src/range_selector.dart index ea795f396..2cc97b47f 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/range_selector.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/range_selector.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:intl/intl.dart' show DateFormat, NumberFormat; import 'package:syncfusion_flutter_core/core.dart'; import 'package:syncfusion_flutter_core/theme.dart'; @@ -113,56 +114,61 @@ import 'theme.dart'; /// * [SfChart](https://pub.dev/documentation/syncfusion_flutter_charts/latest/charts/charts-library.html) and [RangeController](https://pub.dev/documentation/syncfusion_flutter_core/latest/core/RangeController-class.html), for selection and zooming. class SfRangeSelector extends StatefulWidget { /// Creates a [SfRangeSelector]. - const SfRangeSelector( - {Key? key, - this.min = 0.0, - this.max = 1.0, - this.initialValues, - this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.controller, - this.enabled = true, - this.interval, - this.stepSize, - this.stepDuration, - this.deferredUpdateDelay = 500, - this.minorTicksPerInterval = 0, - this.showTicks = false, - this.showLabels = false, - this.showDividers = false, - this.enableTooltip = false, - this.shouldAlwaysShowTooltip = false, - this.enableIntervalSelection = false, - this.enableDeferredUpdate = false, - this.dragMode = SliderDragMode.onThumb, - this.inactiveColor, - this.activeColor, - this.labelPlacement = LabelPlacement.onTicks, - this.edgeLabelPlacement = EdgeLabelPlacement.auto, - this.numberFormat, - this.dateFormat, - this.dateIntervalType, - this.labelFormatterCallback, - this.tooltipTextFormatterCallback, - this.semanticFormatterCallback, - this.trackShape = const SfTrackShape(), - this.dividerShape = const SfDividerShape(), - this.overlayShape = const SfOverlayShape(), - this.thumbShape = const SfThumbShape(), - this.tickShape = const SfTickShape(), - this.minorTickShape = const SfMinorTickShape(), - this.tooltipShape = const SfRectangularTooltipShape(), - this.startThumbIcon, - this.endThumbIcon, - required this.child}) - : assert(min != max), - assert(interval == null || interval > 0), - assert(stepSize == null || stepSize > 0), - assert(!enableIntervalSelection || - (enableIntervalSelection && (interval != null && interval > 0))), - assert(controller != null || initialValues != null), - super(key: key); + const SfRangeSelector({ + Key? key, + this.min = 0.0, + this.max = 1.0, + this.initialValues, + this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.controller, + this.enabled = true, + this.interval, + this.stepSize, + this.stepDuration, + this.deferredUpdateDelay = 500, + this.minorTicksPerInterval = 0, + this.showTicks = false, + this.showLabels = false, + this.showDividers = false, + this.enableTooltip = false, + this.shouldAlwaysShowTooltip = false, + this.enableIntervalSelection = false, + this.enableDeferredUpdate = false, + this.dragMode = SliderDragMode.onThumb, + this.inactiveColor, + this.activeColor, + this.labelPlacement = LabelPlacement.onTicks, + this.edgeLabelPlacement = EdgeLabelPlacement.auto, + this.numberFormat, + this.dateFormat, + this.dateIntervalType, + // ignore: deprecated_consistency + this.labelFormatterCallback, + this.onLabelCreated, + this.tooltipTextFormatterCallback, + this.semanticFormatterCallback, + this.trackShape = const SfTrackShape(), + this.dividerShape = const SfDividerShape(), + this.overlayShape = const SfOverlayShape(), + this.thumbShape = const SfThumbShape(), + this.tickShape = const SfTickShape(), + this.minorTickShape = const SfMinorTickShape(), + this.tooltipShape = const SfRectangularTooltipShape(), + this.startThumbIcon, + this.endThumbIcon, + + required this.child, + }) : assert(min != max), + assert(interval == null || interval > 0), + assert(stepSize == null || stepSize > 0), + assert( + !enableIntervalSelection || + (enableIntervalSelection && (interval != null && interval > 0)), + ), + assert(controller != null || initialValues != null), + super(key: key); /// The minimum value the user can select. /// @@ -1110,7 +1116,9 @@ class SfRangeSelector extends StatefulWidget { /// ``` /// See also: /// + // ignore: deprecated_member_use_from_same_package /// * [labelFormatterCallback], for formatting the numeric and date labels. + /// * [onLabelCreated], for formatting and styling numeric and date labels. final NumberFormat? numberFormat; /// Formats the date labels. It is mandatory for date [SfRangeSelector]. @@ -1148,7 +1156,9 @@ class SfRangeSelector extends StatefulWidget { /// /// * [interval], for setting the interval. /// * [numberFormat], for formatting the numeric labels. - /// * [labelFormatterCallback], for formatting the numeric and date label. + // ignore: deprecated_member_use_from_same_package + /// * [labelFormatterCallback], for formatting the numeric and date labels. + /// * [onLabelCreated], for formatting and styling numeric and date label. /// * [dateIntervalType], for changing the interval type. final DateFormat? dateFormat; @@ -1213,8 +1223,64 @@ class SfRangeSelector extends StatefulWidget { /// ), /// ) /// ``` + @Deprecated('Use `onLabelCreated` instead') final LabelFormatterCallback? labelFormatterCallback; + /// Signature for customizing the text and style of numeric or date labels. + /// + /// * The actual value without formatting is given by `actualValue`. + /// It is either [DateTime] or [double] based on given [initialValues] or + /// controller start and end values. + /// * The formatted value based on the numeric or date format + /// is given by `formattedText`. + /// * Text styles can be applied to individual labels using the `textStyle` + /// property. + /// + /// This snippet shows how to format and style labels in [SfRangeSelector]. + /// + /// ```dart + /// SfRangeValues _initialValues = const SfRangeValues(3.0, 7.0); + /// + /// SfRangeSelector( + /// min: 3.0, + /// max: 8.0, + /// initialValues: _initialValues, + /// interval: 1, + /// showLabels: true, + /// onChanged: (SfRangeValues newValues) { + /// setState(() { + /// _initialValues = newValues; + /// }); + /// }, + /// onLabelCreated: ( + /// dynamic actualValue, + /// String formattedText, + /// TextStyle textStyle, + /// ) { + /// final int value = actualValue.toInt(); + /// final int startIndex = _initialValues.start.toInt(); + /// final int endIndex = _initialValues.end.toInt(); + /// return RangeSelectorLabel( + /// text: value == startIndex || value == endIndex + /// ? '$formattedText' + /// : '$actualValue', + /// textStyle: value == startIndex || value == endIndex + /// ? const TextStyle( + /// color: Colors.purple, + /// fontSize: 18, + /// fontWeight: FontWeight.bold, + /// ) + /// : textStyle, + /// ); + /// }, + /// child: Container( + /// height: 200, + /// color: Colors.green[100], + /// ), + /// ) + /// ``` + final RangeSelectorLabelCreatedCallback? onLabelCreated; + /// Signature for formatting or changing the whole tooltip label text. /// /// * The actual value without formatting is given by `actualValue`. @@ -1420,21 +1486,21 @@ class SfRangeSelector extends StatefulWidget { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (initialValues != null) { - properties.add( - initialValues!.toDiagnosticsNode(name: 'initialValues'), - ); + properties.add(initialValues!.toDiagnosticsNode(name: 'initialValues')); } properties.add(DiagnosticsProperty('min', min)); properties.add(DiagnosticsProperty('max', max)); if (controller != null) { - properties.add( - controller!.toDiagnosticsNode(name: 'controller'), - ); + properties.add(controller!.toDiagnosticsNode(name: 'controller')); } - properties.add(FlagProperty('enabled', + properties.add( + FlagProperty( + 'enabled', value: enabled, ifTrue: 'Range selector is enabled', - ifFalse: 'Range selector is disabled')); + ifFalse: 'Range selector is disabled', + ), + ); properties.add(DoubleProperty('interval', interval)); properties.add(DoubleProperty('stepSize', stepSize)); if (stepDuration != null) { @@ -1442,66 +1508,137 @@ class SfRangeSelector extends StatefulWidget { } properties.add(IntProperty('minorTicksPerInterval', minorTicksPerInterval)); - properties.add(FlagProperty('showTicks', + properties.add( + FlagProperty( + 'showTicks', value: showTicks, ifTrue: 'Ticks are showing', - ifFalse: 'Ticks are not showing')); - properties.add(FlagProperty('showLabels', + ifFalse: 'Ticks are not showing', + ), + ); + properties.add( + FlagProperty( + 'showLabels', value: showLabels, ifTrue: 'Labels are showing', - ifFalse: 'Labels are not showing')); - properties.add(FlagProperty('showDividers', + ifFalse: 'Labels are not showing', + ), + ); + properties.add( + FlagProperty( + 'showDividers', value: showDividers, ifTrue: 'Dividers are showing', - ifFalse: 'Dividers are not showing')); + ifFalse: 'Dividers are not showing', + ), + ); if (shouldAlwaysShowTooltip) { - properties.add(FlagProperty('shouldAlwaysShowTooltip', - value: shouldAlwaysShowTooltip, ifTrue: 'Tooltip is always visible')); + properties.add( + FlagProperty( + 'shouldAlwaysShowTooltip', + value: shouldAlwaysShowTooltip, + ifTrue: 'Tooltip is always visible', + ), + ); } else { - properties.add(FlagProperty('enableTooltip', + properties.add( + FlagProperty( + 'enableTooltip', value: enableTooltip, ifTrue: 'Tooltip is enabled', - ifFalse: 'Tooltip is disabled')); + ifFalse: 'Tooltip is disabled', + ), + ); } - properties.add(FlagProperty('enableIntervalSelection', + properties.add( + FlagProperty( + 'enableIntervalSelection', value: enableIntervalSelection, ifTrue: 'Interval selection is enabled', - ifFalse: 'Interval selection is disabled')); - properties.add(FlagProperty('enableDeferredUpdate', + ifFalse: 'Interval selection is disabled', + ), + ); + properties.add( + FlagProperty( + 'enableDeferredUpdate', value: enableDeferredUpdate, ifTrue: 'Deferred update is enabled', - ifFalse: 'Deferred update is disabled')); + ifFalse: 'Deferred update is disabled', + ), + ); properties.add(EnumProperty('dragMode', dragMode)); properties.add(ColorProperty('activeColor', activeColor)); properties.add(ColorProperty('inactiveColor', inactiveColor)); - properties - .add(EnumProperty('labelPlacement', labelPlacement)); - properties.add(EnumProperty( - 'edgeLabelPlacement', edgeLabelPlacement)); - properties - .add(DiagnosticsProperty('numberFormat', numberFormat)); + properties.add( + EnumProperty('labelPlacement', labelPlacement), + ); + properties.add( + EnumProperty( + 'edgeLabelPlacement', + edgeLabelPlacement, + ), + ); + properties.add( + DiagnosticsProperty('numberFormat', numberFormat), + ); if (initialValues != null && initialValues!.start.runtimeType == DateTime && dateFormat != null) { - properties.add(StringProperty('dateFormat', - 'Formatted value is ${dateFormat!.format(initialValues!.start)}')); + properties.add( + StringProperty( + 'dateFormat', + 'Formatted value is ${dateFormat!.format(initialValues!.start)}', + ), + ); } - properties.add(ObjectFlagProperty>.has( - 'onChanged', onChanged)); - properties.add(ObjectFlagProperty>.has( - 'onChangeStart', onChangeStart)); - properties.add(ObjectFlagProperty>.has( - 'onChangeEnd', onChangeEnd)); properties.add( - EnumProperty('dateIntervalType', dateIntervalType)); - properties.add(ObjectFlagProperty.has( - 'tooltipTextFormatterCallback', tooltipTextFormatterCallback)); - properties.add(ObjectFlagProperty.has( - 'labelFormatterCallback', labelFormatterCallback)); + ObjectFlagProperty>.has( + 'onChanged', + onChanged, + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'onChangeStart', + onChangeStart, + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'onChangeEnd', + onChangeEnd, + ), + ); + properties.add( + EnumProperty('dateIntervalType', dateIntervalType), + ); + properties.add( + ObjectFlagProperty.has( + 'tooltipTextFormatterCallback', + tooltipTextFormatterCallback, + ), + ); + properties.add( + // ignore: deprecated_member_use_from_same_package + ObjectFlagProperty.has( + 'labelFormatterCallback', + // ignore: deprecated_member_use_from_same_package + labelFormatterCallback, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'onLabelCreated', + onLabelCreated, + ), + ); properties.add( - ObjectFlagProperty.has( - 'semanticFormatterCallback', semanticFormatterCallback)); + ObjectFlagProperty.has( + 'semanticFormatterCallback', + semanticFormatterCallback, + ), + ); } } @@ -1514,13 +1651,86 @@ class _SfRangeSelectorState extends State late AnimationController stateController; late AnimationController tooltipAnimationStartController; late AnimationController tooltipAnimationEndController; - final Duration duration = const Duration(milliseconds: 100); + late Map> _keyboardActionMap; + late FocusNode _focusNode; + bool _focused = false; + SfThumb _focusedThumb = SfThumb.start; + SfRangeValues? _values; + final Duration duration = const Duration(milliseconds: 100); + final GlobalKey _renderObjectKey = GlobalKey(); + FocusNode get rangeSelectorFocusNode => _focusNode; + + void _handleNextFocus(NextFocusIntent intent) { + if (_focusedThumb == SfThumb.start) { + setState(() { + _focusedThumb = SfThumb.end; + }); + } else { + // Reset the _focusedThumb to start position when the focus is + // moved to the next widget. + setState(() { + _focusedThumb = SfThumb.start; + }); + FocusScope.of(context).nextFocus(); + } + } + + void _handlePreviousFocus(PreviousFocusIntent intent) { + if (_focusedThumb == SfThumb.end) { + setState(() { + _focusedThumb = SfThumb.start; + }); + } else { + FocusScope.of(context).previousFocus(); + } + } + + void _handleRangeSelectorFocusChanged(bool newFocused) { + if (newFocused != _focused) { + setState(() { + _focused = newFocused; + }); + } + } + + void _keyboardActionHandler(SliderKeyIntent intent) { + final TextDirection directionality = Directionality.of( + _renderObjectKey.currentContext!, + ); + final bool shouldIncrease = switch (intent.type) { + SliderKeyType.up => true, + SliderKeyType.down => false, + SliderKeyType.left => directionality == TextDirection.rtl, + SliderKeyType.right => directionality == TextDirection.ltr, + }; + + final _RenderRangeSelector rangeSelector = + _renderObjectKey.currentContext!.findRenderObject()! + as _RenderRangeSelector; + if (_focusedThumb == SfThumb.start) { + return shouldIncrease + ? rangeSelector._increaseStartAction() + : rangeSelector._decreaseStartAction(); + } else { + return shouldIncrease + ? rangeSelector._increaseEndAction() + : rangeSelector._decreaseEndAction(); + } + } String _getFormattedLabelText(dynamic actualText, String formattedText) { return formattedText; } + RangeSelectorLabel _handleLabelCreated( + dynamic actualValue, + String formattedText, + TextStyle textStyle, + ) { + return RangeSelectorLabel(text: formattedText, textStyle: textStyle); + } + String _getFormattedTooltipText(dynamic actualText, String formattedText) { return formattedText; } @@ -1529,26 +1739,31 @@ class _SfRangeSelectorState extends State SfRangeSelectorThemeData rangeSelectorThemeData = SfRangeSelectorTheme.of(context)!; final bool isMaterial3 = themeData.useMaterial3; - final SfRangeSelectorThemeData effectiveThemeData = - RangeSelectorThemeData(context); - final Color labelColor = isMaterial3 - ? themeData.colorScheme.onSurfaceVariant - : widget.enabled + final SfRangeSelectorThemeData effectiveThemeData = RangeSelectorThemeData( + context, + ); + final Color labelColor = + isMaterial3 + ? themeData.colorScheme.onSurfaceVariant + : widget.enabled ? themeData.textTheme.bodyLarge!.color!.withValues(alpha: 0.87) : themeData.colorScheme.onSurface.withValues(alpha: 0.32); final double minTrackHeight = math.min( - rangeSelectorThemeData.activeTrackHeight, - rangeSelectorThemeData.inactiveTrackHeight); + rangeSelectorThemeData.activeTrackHeight, + rangeSelectorThemeData.inactiveTrackHeight, + ); final double maxTrackHeight = math.max( - rangeSelectorThemeData.activeTrackHeight, - rangeSelectorThemeData.inactiveTrackHeight); + rangeSelectorThemeData.activeTrackHeight, + rangeSelectorThemeData.inactiveTrackHeight, + ); rangeSelectorThemeData = rangeSelectorThemeData.copyWith( activeTrackHeight: rangeSelectorThemeData.activeTrackHeight, inactiveTrackHeight: rangeSelectorThemeData.inactiveTrackHeight, tickSize: rangeSelectorThemeData.tickSize, minorTickSize: rangeSelectorThemeData.minorTickSize, tickOffset: rangeSelectorThemeData.tickOffset, - labelOffset: rangeSelectorThemeData.labelOffset ?? + labelOffset: + rangeSelectorThemeData.labelOffset ?? (widget.showTicks ? const Offset(0.0, 5.0) : const Offset(0.0, 13.0)), inactiveLabelStyle: themeData.textTheme.bodyLarge! .copyWith(color: labelColor, fontSize: isMaterial3 ? 12 : 14) @@ -1558,79 +1773,96 @@ class _SfRangeSelectorState extends State .merge(rangeSelectorThemeData.activeLabelStyle), tooltipTextStyle: themeData.textTheme.bodyLarge! .copyWith( - fontSize: isMaterial3 ? 12 : 14, - color: isMaterial3 - ? themeData.colorScheme.onPrimary - : themeData.colorScheme.surface) + fontSize: isMaterial3 ? 12 : 14, + color: + isMaterial3 + ? themeData.colorScheme.onPrimary + : themeData.colorScheme.surface, + ) .merge(rangeSelectorThemeData.tooltipTextStyle), - inactiveTrackColor: widget.inactiveColor ?? + inactiveTrackColor: + widget.inactiveColor ?? rangeSelectorThemeData.inactiveTrackColor ?? effectiveThemeData.inactiveTrackColor, - activeTrackColor: widget.activeColor ?? + activeTrackColor: + widget.activeColor ?? rangeSelectorThemeData.activeTrackColor ?? effectiveThemeData.activeTrackColor, - thumbColor: widget.activeColor ?? + thumbColor: + widget.activeColor ?? rangeSelectorThemeData.thumbColor ?? effectiveThemeData.thumbColor, - activeTickColor: rangeSelectorThemeData.activeTickColor ?? + activeTickColor: + rangeSelectorThemeData.activeTickColor ?? effectiveThemeData.activeTickColor, - inactiveTickColor: rangeSelectorThemeData.inactiveTickColor ?? + inactiveTickColor: + rangeSelectorThemeData.inactiveTickColor ?? effectiveThemeData.inactiveTickColor, - disabledActiveTickColor: rangeSelectorThemeData.disabledActiveTickColor ?? + disabledActiveTickColor: + rangeSelectorThemeData.disabledActiveTickColor ?? effectiveThemeData.disabledActiveTickColor, disabledInactiveTickColor: rangeSelectorThemeData.disabledInactiveTickColor ?? - effectiveThemeData.disabledInactiveTickColor, - activeMinorTickColor: rangeSelectorThemeData.activeMinorTickColor ?? + effectiveThemeData.disabledInactiveTickColor, + activeMinorTickColor: + rangeSelectorThemeData.activeMinorTickColor ?? effectiveThemeData.activeMinorTickColor, - inactiveMinorTickColor: rangeSelectorThemeData.inactiveMinorTickColor ?? + inactiveMinorTickColor: + rangeSelectorThemeData.inactiveMinorTickColor ?? effectiveThemeData.inactiveMinorTickColor, disabledActiveMinorTickColor: rangeSelectorThemeData.disabledActiveMinorTickColor ?? - effectiveThemeData.disabledActiveMinorTickColor, + effectiveThemeData.disabledActiveMinorTickColor, // ignore: lines_longer_than_80_chars disabledInactiveMinorTickColor: rangeSelectorThemeData.disabledInactiveMinorTickColor ?? - effectiveThemeData.disabledInactiveMinorTickColor, - overlayColor: widget.activeColor?.withValues(alpha: 0.12) ?? + effectiveThemeData.disabledInactiveMinorTickColor, + overlayColor: + widget.activeColor?.withValues(alpha: 0.12) ?? rangeSelectorThemeData.overlayColor ?? effectiveThemeData.overlayColor, - inactiveDividerColor: widget.activeColor ?? + inactiveDividerColor: + widget.activeColor ?? rangeSelectorThemeData.inactiveDividerColor ?? effectiveThemeData.inactiveDividerColor, - activeDividerColor: widget.inactiveColor ?? + activeDividerColor: + widget.inactiveColor ?? rangeSelectorThemeData.activeDividerColor ?? effectiveThemeData.activeDividerColor, disabledInactiveDividerColor: rangeSelectorThemeData.disabledInactiveDividerColor ?? - effectiveThemeData.disabledInactiveDividerColor, + effectiveThemeData.disabledInactiveDividerColor, disabledActiveDividerColor: rangeSelectorThemeData.disabledActiveDividerColor ?? - effectiveThemeData.disabledActiveDividerColor, + effectiveThemeData.disabledActiveDividerColor, disabledActiveTrackColor: rangeSelectorThemeData.disabledActiveTrackColor ?? - effectiveThemeData.disabledActiveTrackColor, + effectiveThemeData.disabledActiveTrackColor, disabledInactiveTrackColor: rangeSelectorThemeData.disabledInactiveTrackColor ?? - effectiveThemeData.disabledInactiveTrackColor, - disabledThumbColor: rangeSelectorThemeData.disabledThumbColor ?? + effectiveThemeData.disabledInactiveTrackColor, + disabledThumbColor: + rangeSelectorThemeData.disabledThumbColor ?? effectiveThemeData.disabledThumbColor, thumbStrokeColor: rangeSelectorThemeData.thumbStrokeColor, overlappingThumbStrokeColor: rangeSelectorThemeData.overlappingThumbStrokeColor ?? - themeData.colorScheme.surface, + themeData.colorScheme.surface, activeDividerStrokeColor: rangeSelectorThemeData.activeDividerStrokeColor, inactiveDividerStrokeColor: rangeSelectorThemeData.inactiveDividerStrokeColor, overlappingTooltipStrokeColor: rangeSelectorThemeData.overlappingTooltipStrokeColor ?? - themeData.colorScheme.surface, - activeRegionColor: rangeSelectorThemeData.activeRegionColor ?? + themeData.colorScheme.surface, + activeRegionColor: + rangeSelectorThemeData.activeRegionColor ?? effectiveThemeData.activeRegionColor, - inactiveRegionColor: widget.inactiveColor ?? + inactiveRegionColor: + widget.inactiveColor ?? rangeSelectorThemeData.inactiveRegionColor ?? effectiveThemeData.inactiveRegionColor, - tooltipBackgroundColor: rangeSelectorThemeData.tooltipBackgroundColor ?? + tooltipBackgroundColor: + rangeSelectorThemeData.tooltipBackgroundColor ?? effectiveThemeData.tooltipBackgroundColor, trackCornerRadius: rangeSelectorThemeData.trackCornerRadius ?? maxTrackHeight / 2, @@ -1669,25 +1901,57 @@ class _SfRangeSelectorState extends State _values = SfRangeValues(widget.controller!.start, widget.controller!.end); } - overlayStartController = - AnimationController(vsync: this, duration: duration); + overlayStartController = AnimationController( + vsync: this, + duration: duration, + ); overlayEndController = AnimationController(vsync: this, duration: duration); stateController = AnimationController(vsync: this, duration: duration); - startPositionController = - AnimationController(duration: Duration.zero, vsync: this); - endPositionController = - AnimationController(duration: Duration.zero, vsync: this); - tooltipAnimationStartController = - AnimationController(vsync: this, duration: duration); - tooltipAnimationEndController = - AnimationController(vsync: this, duration: duration); + startPositionController = AnimationController( + duration: Duration.zero, + vsync: this, + ); + endPositionController = AnimationController( + duration: Duration.zero, + vsync: this, + ); + tooltipAnimationStartController = AnimationController( + vsync: this, + duration: duration, + ); + tooltipAnimationEndController = AnimationController( + vsync: this, + duration: duration, + ); stateController.value = widget.enabled && (widget.min != widget.max) ? 1.0 : 0.0; + + _keyboardActionMap = >{ + SliderKeyIntent: CallbackAction( + onInvoke: _keyboardActionHandler, + ), + NextFocusIntent: CallbackAction( + onInvoke: _handleNextFocus, + ), + PreviousFocusIntent: CallbackAction( + onInvoke: _handlePreviousFocus, + ), + }; + _focusNode = FocusNode( + skipTraversal: widget.dragMode == SliderDragMode.betweenThumbs, + canRequestFocus: widget.dragMode != SliderDragMode.betweenThumbs, + ); super.initState(); } @override void didUpdateWidget(SfRangeSelector oldWidget) { + if (oldWidget.dragMode != widget.dragMode) { + _focusNode.skipTraversal = + widget.dragMode == SliderDragMode.betweenThumbs; + _focusNode.canRequestFocus = + widget.dragMode != SliderDragMode.betweenThumbs; + } if (oldWidget.shouldAlwaysShowTooltip != widget.shouldAlwaysShowTooltip) { if (widget.shouldAlwaysShowTooltip) { tooltipAnimationStartController.value = 1; @@ -1709,6 +1973,7 @@ class _SfRangeSelectorState extends State tooltipAnimationStartController.dispose(); tooltipAnimationEndController.dispose(); stateController.dispose(); + _focusNode.dispose(); super.dispose(); } @@ -1717,8 +1982,35 @@ class _SfRangeSelectorState extends State Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - return _RangeSelectorRenderObjectWidget( - key: widget.key, + VoidCallback? handleRangeSelectorAccessibilityFocus; + switch (themeData.platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + break; + case TargetPlatform.windows: + handleRangeSelectorAccessibilityFocus = () { + // Automatically activate the slider when it receives a11y focus. + if (!rangeSelectorFocusNode.hasFocus && + rangeSelectorFocusNode.canRequestFocus) { + rangeSelectorFocusNode.requestFocus(); + } + }; + } + final Map keyboardShortcutMap = { + ...switch (MediaQuery.navigationModeOf(context)) { + NavigationMode.directional => KeyboardDirectionalNavShortcutMap, + NavigationMode.traditional => KeyboardNavShortcutMap, + }, + const SingleActivator(LogicalKeyboardKey.tab): const NextFocusIntent(), + const SingleActivator(LogicalKeyboardKey.tab, shift: true): + const PreviousFocusIntent(), + }; + + final Widget result = _RangeSelectorRenderObjectWidget( + key: _renderObjectKey, min: widget.min, max: widget.max, values: _values ?? widget.initialValues, @@ -1738,7 +2030,8 @@ class _SfRangeSelectorState extends State enableIntervalSelection: widget.enableIntervalSelection, deferUpdate: widget.enableDeferredUpdate, dragMode: widget.dragMode, - inactiveColor: widget.inactiveColor ?? + inactiveColor: + widget.inactiveColor ?? themeData.primaryColor.withValues(alpha: 0.24), activeColor: widget.activeColor ?? themeData.primaryColor, labelPlacement: widget.labelPlacement, @@ -1747,7 +2040,9 @@ class _SfRangeSelectorState extends State dateFormat: widget.dateFormat, dateIntervalType: widget.dateIntervalType, labelFormatterCallback: + // ignore: deprecated_member_use_from_same_package widget.labelFormatterCallback ?? _getFormattedLabelText, + onLabelCreated: widget.onLabelCreated ?? _handleLabelCreated, tooltipTextFormatterCallback: widget.tooltipTextFormatterCallback ?? _getFormattedTooltipText, semanticFormatterCallback: widget.semanticFormatterCallback, @@ -1761,9 +2056,22 @@ class _SfRangeSelectorState extends State rangeSelectorThemeData: _getRangeSelectorThemeData(themeData), startThumbIcon: widget.startThumbIcon, endThumbIcon: widget.endThumbIcon, + hasFocus: _focused, + focusedThumb: _focusedThumb, state: this, child: widget.child, ); + + return Semantics( + onDidGainAccessibilityFocus: handleRangeSelectorAccessibilityFocus, + child: FocusableActionDetector( + actions: _keyboardActionMap, + shortcuts: keyboardShortcutMap, + focusNode: rangeSelectorFocusNode, + onShowFocusHighlight: _handleRangeSelectorFocusChanged, + child: result, + ), + ); } } @@ -1797,6 +2105,7 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { required this.dateFormat, required this.dateIntervalType, required this.labelFormatterCallback, + required this.onLabelCreated, required this.tooltipTextFormatterCallback, required this.semanticFormatterCallback, required this.trackShape, @@ -1811,6 +2120,8 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { required this.startThumbIcon, required this.endThumbIcon, required this.state, + required this.hasFocus, + required this.focusedThumb, }) : super(key: key); final dynamic min; @@ -1843,7 +2154,9 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { final DateFormat? dateFormat; final DateIntervalType? dateIntervalType; final SfRangeSelectorThemeData rangeSelectorThemeData; + // ignore: deprecated_member_use_from_same_package final LabelFormatterCallback labelFormatterCallback; + final RangeSelectorLabelCreatedCallback onLabelCreated; final TooltipTextFormatterCallback tooltipTextFormatterCallback; final RangeSelectorSemanticFormatterCallback? semanticFormatterCallback; final SfTrackShape trackShape; @@ -1857,6 +2170,8 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { final Widget? startThumbIcon; final Widget? endThumbIcon; final _SfRangeSelectorState state; + final bool hasFocus; + final SfThumb focusedThumb; @override _RenderRangeSelectorElement createElement() => @@ -1891,6 +2206,7 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { dateFormat: dateFormat, dateIntervalType: dateIntervalType, labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, tooltipTextFormatterCallback: tooltipTextFormatterCallback, semanticFormatterCallback: semanticFormatterCallback, trackShape: trackShape, @@ -1910,7 +2226,9 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { @override void updateRenderObject( - BuildContext context, _RenderRangeSelector renderObject) { + BuildContext context, + _RenderRangeSelector renderObject, + ) { renderObject ..min = min ..max = max @@ -1937,6 +2255,7 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { ..dateFormat = dateFormat ..dateIntervalType = dateIntervalType ..labelFormatterCallback = labelFormatterCallback + ..onLabelCreated = onLabelCreated ..tooltipTextFormatterCallback = tooltipTextFormatterCallback ..semanticFormatterCallback = semanticFormatterCallback ..trackShape = trackShape @@ -1948,13 +2267,15 @@ class _RangeSelectorRenderObjectWidget extends RenderObjectWidget { ..tooltipShape = tooltipShape ..sliderThemeData = rangeSelectorThemeData ..textDirection = Directionality.of(context) - ..mediaQueryData = MediaQuery.of(context); + ..mediaQueryData = MediaQuery.of(context) + ..hasFocus = hasFocus + ..focusedThumb = focusedThumb; } } class _RenderRangeSelectorElement extends RenderObjectElement { _RenderRangeSelectorElement(_RangeSelectorRenderObjectWidget rangeSelector) - : super(rangeSelector); + : super(rangeSelector); final Map _slotToChild = {}; final Map _childToSlot = {}; @@ -2043,7 +2364,10 @@ class _RenderRangeSelectorElement extends RenderObjectElement { @override void moveRenderObjectChild( - RenderObject child, dynamic oldSlot, dynamic newSlot) { + RenderObject child, + dynamic oldSlot, + dynamic newSlot, + ) { assert(false, 'not reachable'); } } @@ -2075,7 +2399,9 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { required NumberFormat numberFormat, required DateFormat? dateFormat, required DateIntervalType? dateIntervalType, + // ignore: deprecated_member_use_from_same_package required LabelFormatterCallback labelFormatterCallback, + required RangeSelectorLabelCreatedCallback onLabelCreated, required TooltipTextFormatterCallback tooltipTextFormatterCallback, required RangeSelectorSemanticFormatterCallback? semanticFormatterCallback, required SfTrackShape trackShape, @@ -2090,49 +2416,52 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { required MediaQueryData mediaQueryData, required _SfRangeSelectorState state, required DeviceGestureSettings gestureSettings, - }) : _state = state, - _isEnabled = enabled, - _deferUpdateDelay = deferUpdateDelay, - _deferUpdate = deferUpdate, - _semanticFormatterCallback = semanticFormatterCallback, - super( - min: min, - max: max, - values: values, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - interval: interval, - stepSize: stepSize, - stepDuration: stepDuration, - minorTicksPerInterval: minorTicksPerInterval, - showTicks: showTicks, - showLabels: showLabels, - showDividers: showDividers, - enableTooltip: enableTooltip, - shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, - isInversed: isInversed, - enableIntervalSelection: enableIntervalSelection, - dragMode: dragMode, - labelPlacement: labelPlacement, - edgeLabelPlacement: edgeLabelPlacement, - numberFormat: numberFormat, - dateFormat: dateFormat, - dateIntervalType: dateIntervalType, - labelFormatterCallback: labelFormatterCallback, - tooltipTextFormatterCallback: tooltipTextFormatterCallback, - trackShape: trackShape, - dividerShape: dividerShape, - overlayShape: overlayShape, - thumbShape: thumbShape, - tickShape: tickShape, - minorTickShape: minorTickShape, - tooltipShape: tooltipShape, - sliderThemeData: rangeSelectorThemeData, - sliderType: SliderType.horizontal, - tooltipPosition: null, - textDirection: textDirection, - mediaQueryData: mediaQueryData, - gestureSettings: gestureSettings) { + }) : _state = state, + _isEnabled = enabled, + _deferUpdateDelay = deferUpdateDelay, + _deferUpdate = deferUpdate, + + _semanticFormatterCallback = semanticFormatterCallback, + super( + min: min, + max: max, + values: values, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + interval: interval, + stepSize: stepSize, + stepDuration: stepDuration, + minorTicksPerInterval: minorTicksPerInterval, + showTicks: showTicks, + showLabels: showLabels, + showDividers: showDividers, + enableTooltip: enableTooltip, + shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, + isInversed: isInversed, + enableIntervalSelection: enableIntervalSelection, + dragMode: dragMode, + labelPlacement: labelPlacement, + edgeLabelPlacement: edgeLabelPlacement, + numberFormat: numberFormat, + dateFormat: dateFormat, + dateIntervalType: dateIntervalType, + labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, + tooltipTextFormatterCallback: tooltipTextFormatterCallback, + trackShape: trackShape, + dividerShape: dividerShape, + overlayShape: overlayShape, + thumbShape: thumbShape, + tickShape: tickShape, + minorTickShape: minorTickShape, + tooltipShape: tooltipShape, + sliderThemeData: rangeSelectorThemeData, + sliderType: SliderType.horizontal, + tooltipPosition: null, + textDirection: textDirection, + mediaQueryData: mediaQueryData, + gestureSettings: gestureSettings, + ) { _inactiveRegionColor = rangeSelectorThemeData.inactiveRegionColor!; _activeRegionColor = rangeSelectorThemeData.activeRegionColor!; } @@ -2208,6 +2537,9 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { @override bool get mounted => _state.mounted; + @override + bool get hasLabelCreated => _state.widget.onLabelCreated != null; + @override AnimationController get overlayStartController => _state.overlayStartController; @@ -2255,19 +2587,22 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { } double get elementsActualHeight => math.max( - 2 * trackOffset.dy, - trackOffset.dy + - maxTrackHeight / 2 + - math.max(actualTickHeight, actualMinorTickHeight) + - actualLabelHeight); + 2 * trackOffset.dy, + trackOffset.dy + + maxTrackHeight / 2 + + math.max(actualTickHeight, actualMinorTickHeight) + + actualLabelHeight, + ); // When the active track height and inactive track height are different, // a small gap is happens between min track height and child // So we adjust track offset to ignore that gap. - double get adjustTrackY => sliderThemeData.activeTrackHeight > - sliderThemeData.inactiveTrackHeight - ? sliderThemeData.activeTrackHeight - sliderThemeData.inactiveTrackHeight - : sliderThemeData.inactiveTrackHeight - sliderThemeData.activeTrackHeight; + double get adjustTrackY => + sliderThemeData.activeTrackHeight > sliderThemeData.inactiveTrackHeight + ? sliderThemeData.activeTrackHeight - + sliderThemeData.inactiveTrackHeight + : sliderThemeData.inactiveTrackHeight - + sliderThemeData.activeTrackHeight; void _updateNewValues(SfRangeValues newValues) { if (_state.widget.onChanged != null) { @@ -2288,8 +2623,9 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { (values.start != _state.widget.controller!.start || values.end != _state.widget.controller!.end)) { values = SfRangeValues( - getActualValue(value: _state.widget.controller!.start), - getActualValue(value: _state.widget.controller!.end)); + getActualValue(value: _state.widget.controller!.start), + getActualValue(value: _state.widget.controller!.end), + ); markNeedsPaint(); } @@ -2301,10 +2637,12 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { if (newValues.start != values.start || newValues.end != values.end) { if (_deferUpdate) { _deferUpdateTimer?.cancel(); - _deferUpdateTimer = - Timer(Duration(milliseconds: _deferUpdateDelay), () { - _updateNewValues(newValues); - }); + _deferUpdateTimer = Timer( + Duration(milliseconds: _deferUpdateDelay), + () { + _updateNewValues(newValues); + }, + ); values = newValues; markNeedsPaint(); } else { @@ -2315,6 +2653,12 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { super.updateValues(newValues); } + @override + bool generateLabelsAndTicks() { + return _state.widget.onLabelCreated != null && + _state.widget.controller == null; + } + @override void updateIntervalTappedAndDeferredUpdateValues(SfRangeValues newValues) { if (isIntervalTapped) { @@ -2332,17 +2676,24 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { } } - void _drawRegions(PaintingContext context, Rect trackRect, Offset offset, - Offset startThumbCenter, Offset endThumbCenter) { - final Paint inactivePaint = Paint() - ..isAntiAlias = true - ..color = _inactiveRegionColor; + void _drawRegions( + PaintingContext context, + Rect trackRect, + Offset offset, + Offset startThumbCenter, + Offset endThumbCenter, + ) { + final Paint inactivePaint = + Paint() + ..isAntiAlias = true + ..color = _inactiveRegionColor; if (child != null && child!.size.height > 1 && child!.size.width > 1) { final double halfActiveTrackHeight = sliderThemeData.activeTrackHeight / 2; final double halfInactiveTrackHeight = sliderThemeData.inactiveTrackHeight / 2; - final bool isMaxActive = sliderThemeData.activeTrackHeight > + final bool isMaxActive = + sliderThemeData.activeTrackHeight > sliderThemeData.inactiveTrackHeight; Offset leftThumbCenter; Offset rightThumbCenter; @@ -2360,27 +2711,45 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { final double activeRegionAdj = !isMaxActive ? halfInactiveTrackHeight - halfActiveTrackHeight : 0; context.canvas.drawRect( - Rect.fromLTRB(trackRect.left, offset.dy, leftThumbCenter.dx, - trackRect.top + inactiveRegionAdj), - inactivePaint); - final Paint activePaint = Paint() - ..isAntiAlias = true - ..color = _activeRegionColor; + Rect.fromLTRB( + trackRect.left, + offset.dy, + leftThumbCenter.dx, + trackRect.top + inactiveRegionAdj, + ), + inactivePaint, + ); + final Paint activePaint = + Paint() + ..isAntiAlias = true + ..color = _activeRegionColor; context.canvas.drawRect( - Rect.fromLTRB(leftThumbCenter.dx, offset.dy, rightThumbCenter.dx, - trackRect.top + activeRegionAdj), - activePaint); + Rect.fromLTRB( + leftThumbCenter.dx, + offset.dy, + rightThumbCenter.dx, + trackRect.top + activeRegionAdj, + ), + activePaint, + ); context.canvas.drawRect( - Rect.fromLTRB(rightThumbCenter.dx, offset.dy, trackRect.right, - trackRect.top + inactiveRegionAdj), - inactivePaint); + Rect.fromLTRB( + rightThumbCenter.dx, + offset.dy, + trackRect.right, + trackRect.top + inactiveRegionAdj, + ), + inactivePaint, + ); } } void _increaseStartAction() { if (isInteractive) { - final SfRangeValues newValues = - SfRangeValues(increasedStartValue, values.end); + final SfRangeValues newValues = SfRangeValues( + increasedStartValue, + values.end, + ); if (getNumerizedValue(newValues.start) <= getNumerizedValue(newValues.end)) { _updateNewValues(newValues); @@ -2402,8 +2771,10 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { void _decreaseEndAction() { if (isInteractive) { - final SfRangeValues newValues = - SfRangeValues(values.start, decreasedEndValue); + final SfRangeValues newValues = SfRangeValues( + values.start, + decreasedEndValue, + ); if (getNumerizedValue(newValues.start) <= (getNumerizedValue(newValues.end))) { _updateNewValues(newValues); @@ -2444,16 +2815,19 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { double childHeight = 0.0; double childWidth = 0.0; final double minTrackHeight = math.min( - sliderThemeData.activeTrackHeight, sliderThemeData.inactiveTrackHeight); + sliderThemeData.activeTrackHeight, + sliderThemeData.inactiveTrackHeight, + ); final Offset trackCenterLeft = trackOffset; final double elementsHeightWithoutChild = elementsActualHeight; double elementsHeightAfterRenderedChild = math.max( - trackCenterLeft.dy + minTrackHeight / 2, - maxTrackHeight / 2 + - minTrackHeight / 2 + - math.max(actualTickHeight, actualMinorTickHeight) + - actualLabelHeight); + trackCenterLeft.dy + minTrackHeight / 2, + maxTrackHeight / 2 + + minTrackHeight / 2 + + math.max(actualTickHeight, actualMinorTickHeight) + + actualLabelHeight, + ); if (constraints.maxHeight < elementsHeightWithoutChild) { final double actualChildHeight = @@ -2463,7 +2837,8 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { // Reduce the [elementsHeightAfterRenderedChild] from the // actual child height and remaining space in actual layout height to // match the given constraints height. - elementsHeightAfterRenderedChild = elementsHeightAfterRenderedChild - + elementsHeightAfterRenderedChild = + elementsHeightAfterRenderedChild - spaceLeftInActualLayoutHeight - actualChildHeight; } @@ -2471,10 +2846,12 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { if (child != null) { final double maxRadius = trackOffset.dx; final BoxConstraints childConstraints = constraints.deflate( - EdgeInsets.only( - left: maxRadius, - right: maxRadius, - bottom: elementsHeightAfterRenderedChild)); + EdgeInsets.only( + left: maxRadius, + right: maxRadius, + bottom: elementsHeightAfterRenderedChild, + ), + ); child!.layout(childConstraints, parentUsesSize: true); // ignore: avoid_as final BoxParentData childParentData = child!.parentData! as BoxParentData; @@ -2484,30 +2861,39 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { } final BoxConstraints contentConstraints = BoxConstraints.tightFor( - width: actualThumbSize.width, height: actualThumbSize.height); + width: actualThumbSize.width, + height: actualThumbSize.height, + ); startThumbIcon?.layout(contentConstraints, parentUsesSize: true); endThumbIcon?.layout(contentConstraints, parentUsesSize: true); - final double actualWidth = childWidth > 0.0 - ? (childWidth + 2 * trackOffset.dx) - : minTrackWidth + 2 * trackOffset.dx; + final double actualWidth = + childWidth > 0.0 + ? (childWidth + 2 * trackOffset.dx) + : minTrackWidth + 2 * trackOffset.dx; final double actualHeight = childHeight + elementsHeightAfterRenderedChild; size = Size( - constraints.hasBoundedWidth && (constraints.maxWidth < actualWidth) - ? constraints.maxWidth - : actualWidth, - constraints.hasBoundedHeight && (constraints.maxHeight < actualHeight) - ? constraints.maxHeight - : actualHeight); + constraints.hasBoundedWidth && (constraints.maxWidth < actualWidth) + ? constraints.maxWidth + : actualWidth, + constraints.hasBoundedHeight && (constraints.maxHeight < actualHeight) + ? constraints.maxHeight + : actualHeight, + ); generateLabelsAndMajorTicks(); generateMinorTicks(); } @override - void drawRegions(PaintingContext context, Rect trackRect, Offset offset, - Offset startThumbCenter, Offset endThumbCenter) { + void drawRegions( + PaintingContext context, + Rect trackRect, + Offset offset, + Offset startThumbCenter, + Offset endThumbCenter, + ) { _drawRegions(context, trackRect, offset, startThumbCenter, endThumbCenter); } @@ -2520,16 +2906,20 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { context.paintChild(child!, childParentData.offset + offset); childHeight = child!.size.height; if (childHeight >= constraints.maxHeight) { - childHeight -= elementsActualHeight - + childHeight -= + elementsActualHeight - math.max(actualOverlaySize.height, actualThumbSize.height) / 2; } } final Offset actualTrackOffset = Offset( - offset.dx, - offset.dy + - math.max(childHeight - adjustTrackY / 2, - trackOffset.dy - maxTrackHeight / 2)); + offset.dx, + offset.dy + + math.max( + childHeight - adjustTrackY / 2, + trackOffset.dy - maxTrackHeight / 2, + ), + ); drawRangeSliderElements(context, offset, actualTrackOffset); } @@ -2573,27 +2963,31 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { assert(children.isEmpty); final SemanticsConfiguration startSemanticsConfiguration = _createSemanticsConfiguration( - values.start, - increasedStartValue, - decreasedStartValue, - SfThumb.start, - _increaseStartAction, - _decreaseStartAction, - ); + values.start, + increasedStartValue, + decreasedStartValue, + SfThumb.start, + _increaseStartAction, + _decreaseStartAction, + ); final SemanticsConfiguration endSemanticsConfiguration = _createSemanticsConfiguration( - values.end, - increasedEndValue, - decreasedEndValue, - SfThumb.end, - _increaseEndAction, - _decreaseEndAction, - ); + values.end, + increasedEndValue, + decreasedEndValue, + SfThumb.end, + _increaseEndAction, + _decreaseEndAction, + ); // Split the semantics node area between the start and end nodes. - final Rect leftRect = - Rect.fromPoints(node.rect.topLeft, node.rect.bottomCenter); - final Rect rightRect = - Rect.fromPoints(node.rect.topCenter, node.rect.bottomRight); + final Rect leftRect = Rect.fromPoints( + node.rect.topLeft, + node.rect.bottomCenter, + ); + final Rect rightRect = Rect.fromPoints( + node.rect.topCenter, + node.rect.bottomRight, + ); startSemanticsNode ??= SemanticsNode(); endSemanticsNode ??= SemanticsNode(); switch (textDirection) { @@ -2634,8 +3028,9 @@ class _RenderRangeSelector extends RenderBaseRangeSlider { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(StringProperty('deferredUpdateDelay', '$_deferUpdateDelay ms')); + properties.add( + StringProperty('deferredUpdateDelay', '$_deferUpdateDelay ms'), + ); debugRangeSliderFillProperties(properties); } } diff --git a/packages/syncfusion_flutter_sliders/lib/src/range_slider.dart b/packages/syncfusion_flutter_sliders/lib/src/range_slider.dart index 5e6600871..98c66ccc0 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/range_slider.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/range_slider.dart @@ -3,6 +3,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:intl/intl.dart' show DateFormat, NumberFormat; import 'package:syncfusion_flutter_core/core.dart'; import 'package:syncfusion_flutter_core/theme.dart'; @@ -112,52 +113,56 @@ import 'theme.dart'; /// * [SfRangeSliderThemeData](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfRangeSliderThemeData-class.html), for customizing the visual appearance of the range slider. class SfRangeSlider extends StatefulWidget { /// Creates a horizontal [SfRangeSlider]. - const SfRangeSlider( - {Key? key, - this.min = 0.0, - this.max = 1.0, - required this.values, - required this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.interval, - this.stepSize, - this.stepDuration, - this.minorTicksPerInterval = 0, - this.showTicks = false, - this.showLabels = false, - this.showDividers = false, - this.enableTooltip = false, - this.shouldAlwaysShowTooltip = false, - this.enableIntervalSelection = false, - this.dragMode = SliderDragMode.onThumb, - this.inactiveColor, - this.activeColor, - this.labelPlacement = LabelPlacement.onTicks, - this.edgeLabelPlacement = EdgeLabelPlacement.auto, - this.numberFormat, - this.dateFormat, - this.dateIntervalType, - this.labelFormatterCallback, - this.tooltipTextFormatterCallback, - this.semanticFormatterCallback, - this.trackShape = const SfTrackShape(), - this.dividerShape = const SfDividerShape(), - this.overlayShape = const SfOverlayShape(), - this.thumbShape = const SfThumbShape(), - this.tickShape = const SfTickShape(), - this.minorTickShape = const SfMinorTickShape(), - this.tooltipShape = const SfRectangularTooltipShape(), - this.startThumbIcon, - this.endThumbIcon}) - : isInversed = false, - _sliderType = SliderType.horizontal, - _tooltipPosition = null, - assert(min != max), - assert(interval == null || interval > 0), - assert(!enableIntervalSelection || - (enableIntervalSelection && (interval != null && interval > 0))), - super(key: key); + const SfRangeSlider({ + Key? key, + this.min = 0.0, + this.max = 1.0, + required this.values, + required this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.interval, + this.stepSize, + this.stepDuration, + this.minorTicksPerInterval = 0, + this.showTicks = false, + this.showLabels = false, + this.showDividers = false, + this.enableTooltip = false, + this.shouldAlwaysShowTooltip = false, + this.enableIntervalSelection = false, + this.dragMode = SliderDragMode.onThumb, + this.inactiveColor, + this.activeColor, + this.labelPlacement = LabelPlacement.onTicks, + this.edgeLabelPlacement = EdgeLabelPlacement.auto, + this.numberFormat, + this.dateFormat, + this.dateIntervalType, + // ignore: deprecated_consistency + this.labelFormatterCallback, + this.onLabelCreated, + this.tooltipTextFormatterCallback, + this.semanticFormatterCallback, + this.trackShape = const SfTrackShape(), + this.dividerShape = const SfDividerShape(), + this.overlayShape = const SfOverlayShape(), + this.thumbShape = const SfThumbShape(), + this.tickShape = const SfTickShape(), + this.minorTickShape = const SfMinorTickShape(), + this.tooltipShape = const SfRectangularTooltipShape(), + this.startThumbIcon, + this.endThumbIcon, + }) : isInversed = false, + _sliderType = SliderType.horizontal, + _tooltipPosition = null, + assert(min != max), + assert(interval == null || interval > 0), + assert( + !enableIntervalSelection || + (enableIntervalSelection && (interval != null && interval > 0)), + ), + super(key: key); /// Creates a vertical [SfRangeSlider]. /// @@ -199,52 +204,54 @@ class SfRangeSlider extends StatefulWidget { /// See also: /// /// * Check the default constructor for horizontal range slider. - const SfRangeSlider.vertical( - {Key? key, - this.min = 0.0, - this.max = 1.0, - required this.values, - required this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.interval, - this.stepSize, - this.stepDuration, - this.minorTicksPerInterval = 0, - this.showTicks = false, - this.showLabels = false, - this.showDividers = false, - this.enableTooltip = false, - this.shouldAlwaysShowTooltip = false, - this.enableIntervalSelection = false, - this.dragMode = SliderDragMode.onThumb, - this.isInversed = false, - this.inactiveColor, - this.activeColor, - this.labelPlacement = LabelPlacement.onTicks, - this.edgeLabelPlacement = EdgeLabelPlacement.auto, - this.numberFormat, - this.dateFormat, - this.dateIntervalType, - this.labelFormatterCallback, - this.tooltipTextFormatterCallback, - this.semanticFormatterCallback, - this.trackShape = const SfTrackShape(), - this.dividerShape = const SfDividerShape(), - this.overlayShape = const SfOverlayShape(), - this.thumbShape = const SfThumbShape(), - this.tickShape = const SfTickShape(), - this.minorTickShape = const SfMinorTickShape(), - this.tooltipShape = const SfRectangularTooltipShape(), - this.startThumbIcon, - this.endThumbIcon, - SliderTooltipPosition tooltipPosition = SliderTooltipPosition.left}) - : _sliderType = SliderType.vertical, - _tooltipPosition = tooltipPosition, - assert(tooltipShape is! SfPaddleTooltipShape), - assert(min != max), - assert(interval == null || interval > 0), - super(key: key); + const SfRangeSlider.vertical({ + Key? key, + this.min = 0.0, + this.max = 1.0, + required this.values, + required this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.interval, + this.stepSize, + this.stepDuration, + this.minorTicksPerInterval = 0, + this.showTicks = false, + this.showLabels = false, + this.showDividers = false, + this.enableTooltip = false, + this.shouldAlwaysShowTooltip = false, + this.enableIntervalSelection = false, + this.dragMode = SliderDragMode.onThumb, + this.isInversed = false, + this.inactiveColor, + this.activeColor, + this.labelPlacement = LabelPlacement.onTicks, + this.edgeLabelPlacement = EdgeLabelPlacement.auto, + this.numberFormat, + this.dateFormat, + this.dateIntervalType, + // ignore: deprecated_consistency + this.labelFormatterCallback, + this.onLabelCreated, + this.tooltipTextFormatterCallback, + this.semanticFormatterCallback, + this.trackShape = const SfTrackShape(), + this.dividerShape = const SfDividerShape(), + this.overlayShape = const SfOverlayShape(), + this.thumbShape = const SfThumbShape(), + this.tickShape = const SfTickShape(), + this.minorTickShape = const SfMinorTickShape(), + this.tooltipShape = const SfRectangularTooltipShape(), + this.startThumbIcon, + this.endThumbIcon, + SliderTooltipPosition tooltipPosition = SliderTooltipPosition.left, + }) : _sliderType = SliderType.vertical, + _tooltipPosition = tooltipPosition, + assert(tooltipShape is! SfPaddleTooltipShape), + assert(min != max), + assert(interval == null || interval > 0), + super(key: key); /// This is used to determine the type of the range slider which is /// horizontal or vertical. @@ -1006,7 +1013,9 @@ class SfRangeSlider extends StatefulWidget { /// /// See also: /// + // ignore: deprecated_member_use_from_same_package /// * [labelFormatterCallback], for formatting the numeric and date labels. + /// * [onLabelCreated], for formatting and styling numeric and date labels. final NumberFormat? numberFormat; /// Formats the date labels. It is mandatory for date [SfRangeSlider]. @@ -1045,7 +1054,9 @@ class SfRangeSlider extends StatefulWidget { /// /// * [interval], for setting the interval. /// * [numberFormat], for formatting the numeric labels. - /// * [labelFormatterCallback], for formatting the numeric and date label. + // ignore: deprecated_member_use_from_same_package + /// * [labelFormatterCallback], for formatting the numeric and date labels. + /// * [onLabelCreated], for formatting and styling numeric and date labels. /// * [dateIntervalType], for changing the interval type. final DateFormat? dateFormat; @@ -1111,8 +1122,60 @@ class SfRangeSlider extends StatefulWidget { /// }, /// ) /// ``` + @Deprecated('Use `onLabelCreated` instead') final LabelFormatterCallback? labelFormatterCallback; + /// Signature for customizing the label text and style of numeric or date + /// values in the [SfRangeSlider]. + /// + /// * The actual value without formatting is given by `actualValue`. + /// It is either [DateTime] or [double] based on given [values]. + /// * The formatted value based on the numeric or date format + /// is given by `formattedText`. + /// * Text styles can be applied to individual labels using the `textStyle` + /// property. + /// + /// This snippet shows how to format and style labels in [SfRangeSlider]. + /// + /// ```dart + /// SfRangeValues _values = const SfRangeValues(3.0, 7.0); + /// + /// SfRangeSlider( + /// min: 0, + /// max: 8, + /// values: _values, + /// interval: 1, + /// showLabels: true, + /// onChanged: (SfRangeValues newValues) { + /// setState(() { + /// _values = newValues; + /// }); + /// }, + /// onLabelCreated: ( + /// dynamic actualValue, + /// String formattedText, + /// TextStyle textStyle, + /// ) { + /// final int value = actualValue.toInt(); + /// final int startIndex = _values.start.toInt(); + /// final int endIndex = _values.end.toInt(); + /// return RangeSliderLabel( + /// text: value == startIndex || value == endIndex + /// ? '$formattedText' + /// : '$actualValue', + /// textStyle: value == startIndex || value == endIndex + /// ? const TextStyle( + /// color: Colors.blue, + /// fontSize: 18, + /// fontWeight: FontWeight.bold, + /// ) + /// : textStyle, + /// ); + /// }, + /// ) + /// ``` + final RangeSliderLabelCreatedCallback? onLabelCreated; + /// Signature for formatting or changing the whole tooltip label text. /// /// * The actual value without formatting is given by `actualValue`. @@ -1307,71 +1370,138 @@ class SfRangeSlider extends StatefulWidget { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add( - values.toDiagnosticsNode(name: 'values'), - ); + properties.add(values.toDiagnosticsNode(name: 'values')); properties.add(DiagnosticsProperty('min', min)); properties.add(DiagnosticsProperty('max', max)); - properties.add(DiagnosticsProperty('isInversed', isInversed, - defaultValue: false)); - properties.add(ObjectFlagProperty>( - 'onChanged', onChanged, - ifNull: 'disabled')); - properties.add(ObjectFlagProperty>.has( - 'onChangeStart', onChangeStart)); - properties.add(ObjectFlagProperty>.has( - 'onChangeEnd', onChangeEnd)); + properties.add( + DiagnosticsProperty('isInversed', isInversed, defaultValue: false), + ); + properties.add( + ObjectFlagProperty>( + 'onChanged', + onChanged, + ifNull: 'disabled', + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'onChangeStart', + onChangeStart, + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'onChangeEnd', + onChangeEnd, + ), + ); properties.add(DoubleProperty('interval', interval)); properties.add(DoubleProperty('stepSize', stepSize)); if (stepDuration != null) { properties.add(stepDuration!.toDiagnosticsNode(name: 'stepDuration')); } properties.add(IntProperty('minorTicksPerInterval', minorTicksPerInterval)); - properties.add(FlagProperty('showTicks', + properties.add( + FlagProperty( + 'showTicks', value: showTicks, ifTrue: 'Ticks are showing', - ifFalse: 'Ticks are not showing')); - properties.add(FlagProperty('showLabels', + ifFalse: 'Ticks are not showing', + ), + ); + properties.add( + FlagProperty( + 'showLabels', value: showLabels, ifTrue: 'Labels are showing', - ifFalse: 'Labels are not showing')); - properties.add(FlagProperty('showDividers', + ifFalse: 'Labels are not showing', + ), + ); + properties.add( + FlagProperty( + 'showDividers', value: showDividers, ifTrue: 'Dividers are showing', - ifFalse: 'Dividers are not showing')); + ifFalse: 'Dividers are not showing', + ), + ); if (shouldAlwaysShowTooltip) { - properties.add(FlagProperty('shouldAlwaysShowTooltip', - value: shouldAlwaysShowTooltip, ifTrue: 'Tooltip is always visible')); + properties.add( + FlagProperty( + 'shouldAlwaysShowTooltip', + value: shouldAlwaysShowTooltip, + ifTrue: 'Tooltip is always visible', + ), + ); } else { - properties.add(FlagProperty('enableTooltip', + properties.add( + FlagProperty( + 'enableTooltip', value: enableTooltip, ifTrue: 'Tooltip is enabled', - ifFalse: 'Tooltip is disabled')); + ifFalse: 'Tooltip is disabled', + ), + ); } - properties.add(FlagProperty('enableIntervalSelection', + properties.add( + FlagProperty( + 'enableIntervalSelection', value: enableIntervalSelection, ifTrue: 'Interval selection is enabled', - ifFalse: 'Interval selection is disabled')); + ifFalse: 'Interval selection is disabled', + ), + ); properties.add(ColorProperty('activeColor', activeColor)); properties.add(ColorProperty('inactiveColor', inactiveColor)); - properties - .add(EnumProperty('labelPlacement', labelPlacement)); - properties.add(EnumProperty( - 'edgeLabelPlacement', edgeLabelPlacement)); - properties - .add(DiagnosticsProperty('numberFormat', numberFormat)); + properties.add( + EnumProperty('labelPlacement', labelPlacement), + ); + properties.add( + EnumProperty( + 'edgeLabelPlacement', + edgeLabelPlacement, + ), + ); + properties.add( + DiagnosticsProperty('numberFormat', numberFormat), + ); if (values.start.runtimeType == DateTime && dateFormat != null) { - properties.add(StringProperty('dateFormat', - 'Formatted value is ${dateFormat!.format(values.start)}')); + properties.add( + StringProperty( + 'dateFormat', + 'Formatted value is ${dateFormat!.format(values.start)}', + ), + ); } properties.add( - EnumProperty('dateIntervalType', dateIntervalType)); - properties.add(ObjectFlagProperty.has( - 'tooltipTextFormatterCallback', tooltipTextFormatterCallback)); - properties.add(ObjectFlagProperty.has( - 'labelFormatterCallback', labelFormatterCallback)); - properties.add(ObjectFlagProperty.has( - 'semanticFormatterCallback', semanticFormatterCallback)); + EnumProperty('dateIntervalType', dateIntervalType), + ); + properties.add( + ObjectFlagProperty.has( + 'tooltipTextFormatterCallback', + tooltipTextFormatterCallback, + ), + ); + properties.add( + // ignore: deprecated_member_use_from_same_package + ObjectFlagProperty.has( + 'labelFormatterCallback', + // ignore: deprecated_member_use_from_same_package + labelFormatterCallback, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'onLabelCreated', + onLabelCreated, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'semanticFormatterCallback', + semanticFormatterCallback, + ), + ); } } @@ -1385,7 +1515,72 @@ class _SfRangeSliderState extends State late AnimationController tooltipAnimationStartController; late AnimationController tooltipAnimationEndController; late RangeController rangeController; + late Map> _keyboardActionMap; + late FocusNode _focusNode; + bool _focused = false; + SfThumb _focusedThumb = SfThumb.start; final Duration duration = const Duration(milliseconds: 100); + final GlobalKey _renderObjectKey = GlobalKey(); + bool get _enabled => widget.onChanged != null; + FocusNode get rangeSliderFocusNode => _focusNode; + + void _handleNextFocus(NextFocusIntent intent) { + if (_focusedThumb == SfThumb.start) { + setState(() { + _focusedThumb = SfThumb.end; + }); + } else { + // Reset the _focusedThumb to start position when the focus is + // moved to the next widget. + setState(() { + _focusedThumb = SfThumb.start; + }); + FocusScope.of(context).nextFocus(); + } + } + + void _handlePreviousFocus(PreviousFocusIntent intent) { + if (_focusedThumb == SfThumb.end) { + setState(() { + _focusedThumb = SfThumb.start; + }); + } else { + FocusScope.of(context).previousFocus(); + } + } + + void _handleRangeSliderFocusChanged(bool newFocused) { + if (newFocused != _focused) { + setState(() { + _focused = newFocused; + }); + } + } + + void _keyboardActionHandler(SliderKeyIntent intent) { + final TextDirection directionality = Directionality.of( + _renderObjectKey.currentContext!, + ); + final bool shouldIncrease = switch (intent.type) { + SliderKeyType.up => true, + SliderKeyType.down => false, + SliderKeyType.left => directionality == TextDirection.rtl, + SliderKeyType.right => directionality == TextDirection.ltr, + }; + + final _RenderRangeSlider rangeSlider = + _renderObjectKey.currentContext!.findRenderObject()! + as _RenderRangeSlider; + if (_focusedThumb == SfThumb.start) { + return shouldIncrease + ? rangeSlider._increaseStartAction() + : rangeSlider._decreaseStartAction(); + } else { + return shouldIncrease + ? rangeSlider._increaseEndAction() + : rangeSlider._decreaseEndAction(); + } + } void _onChanged(SfRangeValues values) { if (values != widget.values) { @@ -1409,28 +1604,42 @@ class _SfRangeSliderState extends State return formattedText; } + RangeSliderLabel _handleLabelCreated( + dynamic actualValue, + String formattedText, + TextStyle textStyle, + ) { + return RangeSliderLabel(text: formattedText, textStyle: textStyle); + } + String _getFormattedTooltipText(dynamic actualText, String formattedText) { return formattedText; } SfRangeSliderThemeData _getRangeSliderThemeData( - ThemeData themeData, bool isActive) { + ThemeData themeData, + bool isActive, + ) { SfRangeSliderThemeData rangeSliderThemeData = SfRangeSliderTheme.of(context)!; final bool isMaterial3 = themeData.useMaterial3; - final SfRangeSliderThemeData effectiveThemeData = - RangeSliderThemeData(context); - final Color labelColor = isMaterial3 - ? themeData.colorScheme.onSurfaceVariant - : isActive + final SfRangeSliderThemeData effectiveThemeData = RangeSliderThemeData( + context, + ); + final Color labelColor = + isMaterial3 + ? themeData.colorScheme.onSurfaceVariant + : isActive ? themeData.textTheme.bodyLarge!.color!.withValues(alpha: 0.87) : themeData.colorScheme.onSurface.withValues(alpha: 0.32); final double minTrackHeight = math.min( - rangeSliderThemeData.activeTrackHeight, - rangeSliderThemeData.inactiveTrackHeight); + rangeSliderThemeData.activeTrackHeight, + rangeSliderThemeData.inactiveTrackHeight, + ); final double maxTrackHeight = math.max( - rangeSliderThemeData.activeTrackHeight, - rangeSliderThemeData.inactiveTrackHeight); + rangeSliderThemeData.activeTrackHeight, + rangeSliderThemeData.inactiveTrackHeight, + ); rangeSliderThemeData = rangeSliderThemeData.copyWith( activeTrackHeight: rangeSliderThemeData.activeTrackHeight, inactiveTrackHeight: rangeSliderThemeData.inactiveTrackHeight, @@ -1443,74 +1652,90 @@ class _SfRangeSliderState extends State .merge(rangeSliderThemeData.activeLabelStyle), tooltipTextStyle: themeData.textTheme.bodyLarge! .copyWith( - fontSize: isMaterial3 ? 12 : 14, - color: isMaterial3 - ? themeData.colorScheme.onPrimary - : themeData.colorScheme.surface) + fontSize: isMaterial3 ? 12 : 14, + color: + isMaterial3 + ? themeData.colorScheme.onPrimary + : themeData.colorScheme.surface, + ) .merge(rangeSliderThemeData.tooltipTextStyle), - inactiveTrackColor: widget.inactiveColor ?? + inactiveTrackColor: + widget.inactiveColor ?? rangeSliderThemeData.inactiveTrackColor ?? effectiveThemeData.inactiveTrackColor, - activeTrackColor: widget.activeColor ?? + activeTrackColor: + widget.activeColor ?? rangeSliderThemeData.activeTrackColor ?? effectiveThemeData.activeTrackColor, - thumbColor: widget.activeColor ?? + thumbColor: + widget.activeColor ?? rangeSliderThemeData.thumbColor ?? effectiveThemeData.thumbColor, - activeTickColor: rangeSliderThemeData.activeTickColor ?? + activeTickColor: + rangeSliderThemeData.activeTickColor ?? effectiveThemeData.activeTickColor, - inactiveTickColor: rangeSliderThemeData.inactiveTickColor ?? + inactiveTickColor: + rangeSliderThemeData.inactiveTickColor ?? effectiveThemeData.inactiveTickColor, - disabledActiveTickColor: rangeSliderThemeData.disabledActiveTickColor ?? + disabledActiveTickColor: + rangeSliderThemeData.disabledActiveTickColor ?? effectiveThemeData.disabledActiveTickColor, disabledInactiveTickColor: rangeSliderThemeData.disabledInactiveTickColor ?? - effectiveThemeData.disabledInactiveTickColor, - activeMinorTickColor: rangeSliderThemeData.activeMinorTickColor ?? + effectiveThemeData.disabledInactiveTickColor, + activeMinorTickColor: + rangeSliderThemeData.activeMinorTickColor ?? effectiveThemeData.activeMinorTickColor, - inactiveMinorTickColor: rangeSliderThemeData.inactiveMinorTickColor ?? + inactiveMinorTickColor: + rangeSliderThemeData.inactiveMinorTickColor ?? effectiveThemeData.disabledInactiveMinorTickColor, disabledActiveMinorTickColor: rangeSliderThemeData.disabledActiveMinorTickColor ?? - effectiveThemeData.disabledActiveMinorTickColor, + effectiveThemeData.disabledActiveMinorTickColor, disabledInactiveMinorTickColor: rangeSliderThemeData.disabledInactiveMinorTickColor ?? - effectiveThemeData.disabledInactiveMinorTickColor, + effectiveThemeData.disabledInactiveMinorTickColor, // ignore: lines_longer_than_80_chars - overlayColor: widget.activeColor?.withValues(alpha: 0.12) ?? + overlayColor: + widget.activeColor?.withValues(alpha: 0.12) ?? rangeSliderThemeData.overlayColor ?? effectiveThemeData.overlayColor, - inactiveDividerColor: widget.activeColor ?? + inactiveDividerColor: + widget.activeColor ?? rangeSliderThemeData.inactiveDividerColor ?? effectiveThemeData.inactiveDividerColor, - activeDividerColor: widget.inactiveColor ?? + activeDividerColor: + widget.inactiveColor ?? rangeSliderThemeData.activeDividerColor ?? effectiveThemeData.activeDividerColor, disabledInactiveDividerColor: rangeSliderThemeData.disabledInactiveDividerColor ?? - effectiveThemeData.disabledInactiveDividerColor, + effectiveThemeData.disabledInactiveDividerColor, disabledActiveDividerColor: rangeSliderThemeData.disabledActiveDividerColor ?? - effectiveThemeData.disabledActiveDividerColor, - disabledActiveTrackColor: rangeSliderThemeData.disabledActiveTrackColor ?? + effectiveThemeData.disabledActiveDividerColor, + disabledActiveTrackColor: + rangeSliderThemeData.disabledActiveTrackColor ?? effectiveThemeData.disabledActiveTrackColor, disabledInactiveTrackColor: rangeSliderThemeData.disabledInactiveTrackColor ?? - effectiveThemeData.disabledInactiveTrackColor, - disabledThumbColor: rangeSliderThemeData.disabledThumbColor ?? + effectiveThemeData.disabledInactiveTrackColor, + disabledThumbColor: + rangeSliderThemeData.disabledThumbColor ?? effectiveThemeData.disabledThumbColor, - tooltipBackgroundColor: rangeSliderThemeData.tooltipBackgroundColor ?? + tooltipBackgroundColor: + rangeSliderThemeData.tooltipBackgroundColor ?? effectiveThemeData.tooltipBackgroundColor, thumbStrokeColor: rangeSliderThemeData.thumbStrokeColor, overlappingThumbStrokeColor: rangeSliderThemeData.overlappingThumbStrokeColor ?? - themeData.colorScheme.surface, + themeData.colorScheme.surface, activeDividerStrokeColor: rangeSliderThemeData.activeDividerStrokeColor, inactiveDividerStrokeColor: rangeSliderThemeData.inactiveDividerStrokeColor, overlappingTooltipStrokeColor: rangeSliderThemeData.overlappingTooltipStrokeColor ?? - themeData.colorScheme.surface, + themeData.colorScheme.surface, trackCornerRadius: rangeSliderThemeData.trackCornerRadius ?? maxTrackHeight / 2, thumbRadius: rangeSliderThemeData.thumbRadius, @@ -1527,46 +1752,82 @@ class _SfRangeSliderState extends State if (widget._sliderType == SliderType.horizontal) { return rangeSliderThemeData.copyWith( - tickSize: rangeSliderThemeData.tickSize ?? const Size(1.0, 8.0), - minorTickSize: - rangeSliderThemeData.minorTickSize ?? const Size(1.0, 5.0), - labelOffset: rangeSliderThemeData.labelOffset ?? - (widget.showTicks - ? const Offset(0.0, 5.0) - : const Offset(0.0, 13.0))); + tickSize: rangeSliderThemeData.tickSize ?? const Size(1.0, 8.0), + minorTickSize: + rangeSliderThemeData.minorTickSize ?? const Size(1.0, 5.0), + labelOffset: + rangeSliderThemeData.labelOffset ?? + (widget.showTicks + ? const Offset(0.0, 5.0) + : const Offset(0.0, 13.0)), + ); } else { return rangeSliderThemeData.copyWith( - tickSize: rangeSliderThemeData.tickSize ?? const Size(8.0, 1.0), - minorTickSize: - rangeSliderThemeData.minorTickSize ?? const Size(5.0, 1.0), - labelOffset: rangeSliderThemeData.labelOffset ?? - (widget.showTicks - ? const Offset(5.0, 0.0) - : const Offset(13.0, 0.0))); + tickSize: rangeSliderThemeData.tickSize ?? const Size(8.0, 1.0), + minorTickSize: + rangeSliderThemeData.minorTickSize ?? const Size(5.0, 1.0), + labelOffset: + rangeSliderThemeData.labelOffset ?? + (widget.showTicks + ? const Offset(5.0, 0.0) + : const Offset(13.0, 0.0)), + ); } } @override void initState() { - overlayStartController = - AnimationController(vsync: this, duration: duration); + overlayStartController = AnimationController( + vsync: this, + duration: duration, + ); overlayEndController = AnimationController(vsync: this, duration: duration); stateController = AnimationController(vsync: this, duration: duration); - startPositionController = - AnimationController(duration: Duration.zero, vsync: this); - endPositionController = - AnimationController(duration: Duration.zero, vsync: this); - tooltipAnimationStartController = - AnimationController(vsync: this, duration: duration); - tooltipAnimationEndController = - AnimationController(vsync: this, duration: duration); + startPositionController = AnimationController( + duration: Duration.zero, + vsync: this, + ); + endPositionController = AnimationController( + duration: Duration.zero, + vsync: this, + ); + tooltipAnimationStartController = AnimationController( + vsync: this, + duration: duration, + ); + tooltipAnimationEndController = AnimationController( + vsync: this, + duration: duration, + ); stateController.value = widget.onChanged != null && (widget.min != widget.max) ? 1.0 : 0.0; + + _keyboardActionMap = >{ + SliderKeyIntent: CallbackAction( + onInvoke: _keyboardActionHandler, + ), + NextFocusIntent: CallbackAction( + onInvoke: _handleNextFocus, + ), + PreviousFocusIntent: CallbackAction( + onInvoke: _handlePreviousFocus, + ), + }; + _focusNode = FocusNode( + skipTraversal: widget.dragMode == SliderDragMode.betweenThumbs, + canRequestFocus: widget.dragMode != SliderDragMode.betweenThumbs, + ); super.initState(); } @override void didUpdateWidget(SfRangeSlider oldWidget) { + if (oldWidget.dragMode != widget.dragMode) { + _focusNode.skipTraversal = + widget.dragMode == SliderDragMode.betweenThumbs; + _focusNode.canRequestFocus = + widget.dragMode != SliderDragMode.betweenThumbs; + } if (oldWidget.shouldAlwaysShowTooltip != widget.shouldAlwaysShowTooltip) { if (widget.shouldAlwaysShowTooltip) { tooltipAnimationStartController.value = 1; @@ -1588,6 +1849,7 @@ class _SfRangeSliderState extends State endPositionController.dispose(); tooltipAnimationStartController.dispose(); tooltipAnimationEndController.dispose(); + _focusNode.dispose(); super.dispose(); } @@ -1597,8 +1859,35 @@ class _SfRangeSliderState extends State widget.onChanged != null && (widget.min != widget.max); final ThemeData themeData = Theme.of(context); - return _RangeSliderRenderObjectWidget( - key: widget.key, + VoidCallback? handleRangeSliderAccessibilityFocus; + switch (themeData.platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + break; + case TargetPlatform.windows: + handleRangeSliderAccessibilityFocus = () { + // Automatically activate the slider when it receives a11y focus. + if (!rangeSliderFocusNode.hasFocus && + rangeSliderFocusNode.canRequestFocus) { + rangeSliderFocusNode.requestFocus(); + } + }; + } + final Map keyboardShortcutMap = { + ...switch (MediaQuery.navigationModeOf(context)) { + NavigationMode.directional => KeyboardDirectionalNavShortcutMap, + NavigationMode.traditional => KeyboardNavShortcutMap, + }, + const SingleActivator(LogicalKeyboardKey.tab): const NextFocusIntent(), + const SingleActivator(LogicalKeyboardKey.tab, shift: true): + const PreviousFocusIntent(), + }; + + final Widget result = _RangeSliderRenderObjectWidget( + key: _renderObjectKey, min: widget.min, max: widget.max, values: widget.values, @@ -1616,10 +1905,12 @@ class _SfRangeSliderState extends State shouldAlwaysShowTooltip: widget.shouldAlwaysShowTooltip, dragMode: widget.dragMode, enableIntervalSelection: widget.enableIntervalSelection, - isInversed: widget._sliderType == SliderType.horizontal && + isInversed: + widget._sliderType == SliderType.horizontal && Directionality.of(context) == TextDirection.rtl || widget.isInversed, - inactiveColor: widget.inactiveColor ?? + inactiveColor: + widget.inactiveColor ?? themeData.primaryColor.withValues(alpha: 0.24), activeColor: widget.activeColor ?? themeData.primaryColor, labelPlacement: widget.labelPlacement, @@ -1628,7 +1919,9 @@ class _SfRangeSliderState extends State dateIntervalType: widget.dateIntervalType, dateFormat: widget.dateFormat, labelFormatterCallback: + // ignore: deprecated_member_use_from_same_package widget.labelFormatterCallback ?? _getFormattedLabelText, + onLabelCreated: widget.onLabelCreated ?? _handleLabelCreated, tooltipTextFormatterCallback: widget.tooltipTextFormatterCallback ?? _getFormattedTooltipText, semanticFormatterCallback: widget.semanticFormatterCallback, @@ -1644,8 +1937,22 @@ class _SfRangeSliderState extends State tooltipPosition: widget._tooltipPosition, startThumbIcon: widget.startThumbIcon, endThumbIcon: widget.endThumbIcon, + hasFocus: _focused, + focusedThumb: _focusedThumb, state: this, ); + + return Semantics( + onDidGainAccessibilityFocus: handleRangeSliderAccessibilityFocus, + child: FocusableActionDetector( + actions: _keyboardActionMap, + shortcuts: keyboardShortcutMap, + focusNode: rangeSliderFocusNode, + enabled: _enabled, + onShowFocusHighlight: _handleRangeSliderFocusChanged, + child: result, + ), + ); } } @@ -1678,6 +1985,7 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { required this.dateFormat, required this.dateIntervalType, required this.labelFormatterCallback, + required this.onLabelCreated, required this.tooltipTextFormatterCallback, required this.semanticFormatterCallback, required this.trackShape, @@ -1693,6 +2001,8 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { required this.tooltipPosition, required this.sliderType, required this.state, + required this.hasFocus, + required this.focusedThumb, }) : super(key: key); final SliderType sliderType; final SliderTooltipPosition? tooltipPosition; @@ -1725,7 +2035,9 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { final DateIntervalType? dateIntervalType; final DateFormat? dateFormat; final SfRangeSliderThemeData rangeSliderThemeData; + // ignore: deprecated_member_use_from_same_package final LabelFormatterCallback labelFormatterCallback; + final RangeSliderLabelCreatedCallback onLabelCreated; final TooltipTextFormatterCallback tooltipTextFormatterCallback; final RangeSliderSemanticFormatterCallback? semanticFormatterCallback; final SfDividerShape dividerShape; @@ -1738,7 +2050,8 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { final Widget? startThumbIcon; final Widget? endThumbIcon; final _SfRangeSliderState state; - + final bool hasFocus; + final SfThumb focusedThumb; @override _RenderRangeSliderElement createElement() => _RenderRangeSliderElement(this); @@ -1769,6 +2082,7 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { dateFormat: dateFormat, dateIntervalType: dateIntervalType, labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, tooltipTextFormatterCallback: tooltipTextFormatterCallback, semanticFormatterCallback: semanticFormatterCallback, trackShape: trackShape, @@ -1790,7 +2104,9 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { @override void updateRenderObject( - BuildContext context, _RenderRangeSlider renderObject) { + BuildContext context, + _RenderRangeSlider renderObject, + ) { renderObject ..min = min ..max = max @@ -1816,6 +2132,7 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { ..dateFormat = dateFormat ..dateIntervalType = dateIntervalType ..labelFormatterCallback = labelFormatterCallback + ..onLabelCreated = onLabelCreated ..tooltipTextFormatterCallback = tooltipTextFormatterCallback ..semanticFormatterCallback = semanticFormatterCallback ..trackShape = trackShape @@ -1828,13 +2145,15 @@ class _RangeSliderRenderObjectWidget extends RenderObjectWidget { ..tooltipPosition = tooltipPosition ..sliderThemeData = rangeSliderThemeData ..textDirection = Directionality.of(context) - ..mediaQueryData = MediaQuery.of(context); + ..mediaQueryData = MediaQuery.of(context) + ..hasFocus = hasFocus + ..focusedThumb = focusedThumb; } } class _RenderRangeSliderElement extends RenderObjectElement { _RenderRangeSliderElement(_RangeSliderRenderObjectWidget rangeSlider) - : super(rangeSlider); + : super(rangeSlider); final Map _slotToChild = {}; @@ -1918,7 +2237,10 @@ class _RenderRangeSliderElement extends RenderObjectElement { @override void moveRenderObjectChild( - RenderObject child, dynamic oldSlot, dynamic newSlot) { + RenderObject child, + dynamic oldSlot, + dynamic newSlot, + ) { assert(false, 'not reachable'); } } @@ -1948,7 +2270,9 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { required NumberFormat numberFormat, required DateFormat? dateFormat, required DateIntervalType? dateIntervalType, + // ignore: deprecated_member_use_from_same_package required LabelFormatterCallback labelFormatterCallback, + required RangeSliderLabelCreatedCallback onLabelCreated, required TooltipTextFormatterCallback tooltipTextFormatterCallback, required RangeSliderSemanticFormatterCallback? semanticFormatterCallback, required SfTrackShape trackShape, @@ -1965,48 +2289,50 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { required MediaQueryData mediaQueryData, required _SfRangeSliderState state, required DeviceGestureSettings gestureSettings, - }) : _state = state, - _onChanged = onChanged, - _semanticFormatterCallback = semanticFormatterCallback, - super( - min: min, - max: max, - values: values, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - interval: interval, - stepSize: stepSize, - stepDuration: stepDuration, - minorTicksPerInterval: minorTicksPerInterval, - showTicks: showTicks, - showLabels: showLabels, - showDividers: showDividers, - enableTooltip: enableTooltip, - shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, - enableIntervalSelection: enableIntervalSelection, - dragMode: dragMode, - isInversed: isInversed, - labelPlacement: labelPlacement, - edgeLabelPlacement: edgeLabelPlacement, - numberFormat: numberFormat, - dateFormat: dateFormat, - dateIntervalType: dateIntervalType, - labelFormatterCallback: labelFormatterCallback, - tooltipTextFormatterCallback: tooltipTextFormatterCallback, - trackShape: trackShape, - dividerShape: dividerShape, - overlayShape: overlayShape, - thumbShape: thumbShape, - tickShape: tickShape, - minorTickShape: minorTickShape, - tooltipShape: tooltipShape, - sliderThemeData: sliderThemeData, - sliderType: sliderType, - tooltipPosition: tooltipPosition, - textDirection: textDirection, - mediaQueryData: mediaQueryData, - gestureSettings: gestureSettings, - ); + }) : _state = state, + _onChanged = onChanged, + + _semanticFormatterCallback = semanticFormatterCallback, + super( + min: min, + max: max, + values: values, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + interval: interval, + stepSize: stepSize, + stepDuration: stepDuration, + minorTicksPerInterval: minorTicksPerInterval, + showTicks: showTicks, + showLabels: showLabels, + showDividers: showDividers, + enableTooltip: enableTooltip, + shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, + enableIntervalSelection: enableIntervalSelection, + dragMode: dragMode, + isInversed: isInversed, + labelPlacement: labelPlacement, + edgeLabelPlacement: edgeLabelPlacement, + numberFormat: numberFormat, + dateFormat: dateFormat, + dateIntervalType: dateIntervalType, + labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, + tooltipTextFormatterCallback: tooltipTextFormatterCallback, + trackShape: trackShape, + dividerShape: dividerShape, + overlayShape: overlayShape, + thumbShape: thumbShape, + tickShape: tickShape, + minorTickShape: minorTickShape, + tooltipShape: tooltipShape, + sliderThemeData: sliderThemeData, + sliderType: sliderType, + tooltipPosition: tooltipPosition, + textDirection: textDirection, + mediaQueryData: mediaQueryData, + gestureSettings: gestureSettings, + ); final _SfRangeSliderState _state; @@ -2071,6 +2397,9 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { @override bool get mounted => _state.mounted; + @override + bool get hasLabelCreated => _state.widget.onLabelCreated != null; + @override void updateValues(SfRangeValues newValues) { if (!isIntervalTapped && @@ -2089,8 +2418,10 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { void _increaseStartAction() { if (isInteractive) { - final SfRangeValues newValues = - SfRangeValues(increasedStartValue, values.end); + final SfRangeValues newValues = SfRangeValues( + increasedStartValue, + values.end, + ); if (getNumerizedValue(newValues.start) <= (getNumerizedValue(newValues.end))) { onChanged!(newValues); @@ -2112,8 +2443,10 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { void _decreaseEndAction() { if (isInteractive) { - final SfRangeValues newValues = - SfRangeValues(values.start, decreasedEndValue); + final SfRangeValues newValues = SfRangeValues( + values.start, + decreasedEndValue, + ); if (getNumerizedValue(newValues.start) <= (getNumerizedValue(newValues.end))) { onChanged!(newValues); @@ -2134,7 +2467,9 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { void performLayout() { super.performLayout(); final BoxConstraints contentConstraints = BoxConstraints.tightFor( - width: actualThumbSize.width, height: actualThumbSize.height); + width: actualThumbSize.width, + height: actualThumbSize.height, + ); startThumbIcon?.layout(contentConstraints, parentUsesSize: true); endThumbIcon?.layout(contentConstraints, parentUsesSize: true); } @@ -2162,19 +2497,22 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { @override void paint(PaintingContext context, Offset offset) { - final Offset actualTrackOffset = sliderType == SliderType.horizontal - ? Offset( - offset.dx, - offset.dy + - (size.height - actualHeight) / 2 + - trackOffset.dy - - maxTrackHeight / 2) - : Offset( - offset.dx + - (size.width - actualHeight) / 2 + - trackOffset.dx - - maxTrackHeight / 2, - offset.dy); + final Offset actualTrackOffset = + sliderType == SliderType.horizontal + ? Offset( + offset.dx, + offset.dy + + (size.height - actualHeight) / 2 + + trackOffset.dy - + maxTrackHeight / 2, + ) + : Offset( + offset.dx + + (size.width - actualHeight) / 2 + + trackOffset.dx - + maxTrackHeight / 2, + offset.dy, + ); drawRangeSliderElements(context, offset, actualTrackOffset); } @@ -2218,29 +2556,31 @@ class _RenderRangeSlider extends RenderBaseRangeSlider { assert(children.isEmpty); final SemanticsConfiguration startSemanticsConfiguration = _createSemanticsConfiguration( - values.start, - increasedStartValue, - decreasedStartValue, - SfThumb.start, - _increaseStartAction, - _decreaseStartAction, - ); + values.start, + increasedStartValue, + decreasedStartValue, + SfThumb.start, + _increaseStartAction, + _decreaseStartAction, + ); final SemanticsConfiguration endSemanticsConfiguration = _createSemanticsConfiguration( - values.end, - increasedEndValue, - decreasedEndValue, - SfThumb.end, - _increaseEndAction, - _decreaseEndAction, - ); + values.end, + increasedEndValue, + decreasedEndValue, + SfThumb.end, + _increaseEndAction, + _decreaseEndAction, + ); // Split the semantics node area between the start and end nodes. - final Rect startRect = sliderType == SliderType.horizontal - ? Rect.fromPoints(node.rect.topLeft, node.rect.bottomCenter) - : Rect.fromPoints(node.rect.bottomRight, node.rect.centerLeft); - final Rect endRect = sliderType == SliderType.horizontal - ? Rect.fromPoints(node.rect.topCenter, node.rect.bottomRight) - : Rect.fromPoints(node.rect.centerLeft, node.rect.topRight); + final Rect startRect = + sliderType == SliderType.horizontal + ? Rect.fromPoints(node.rect.topLeft, node.rect.bottomCenter) + : Rect.fromPoints(node.rect.bottomRight, node.rect.centerLeft); + final Rect endRect = + sliderType == SliderType.horizontal + ? Rect.fromPoints(node.rect.topCenter, node.rect.bottomRight) + : Rect.fromPoints(node.rect.centerLeft, node.rect.topRight); startSemanticsNode ??= SemanticsNode(); endSemanticsNode ??= SemanticsNode(); if (sliderType == SliderType.vertical || diff --git a/packages/syncfusion_flutter_sliders/lib/src/range_slider_base.dart b/packages/syncfusion_flutter_sliders/lib/src/range_slider_base.dart index aabc09886..7ecb5c2ee 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/range_slider_base.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/range_slider_base.dart @@ -42,7 +42,9 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider required NumberFormat numberFormat, required DateFormat? dateFormat, required DateIntervalType? dateIntervalType, + // ignore: deprecated_member_use_from_same_package required LabelFormatterCallback labelFormatterCallback, + required RangeSliderLabelCreatedCallback onLabelCreated, required TooltipTextFormatterCallback tooltipTextFormatterCallback, required SfTrackShape trackShape, required SfDividerShape dividerShape, @@ -58,76 +60,91 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider required MediaQueryData mediaQueryData, required bool isInversed, required DeviceGestureSettings gestureSettings, - }) : _values = values!, - _dragMode = dragMode, - _enableIntervalSelection = enableIntervalSelection, - super( - min: min, - max: max, - interval: interval, - stepSize: stepSize, - stepDuration: stepDuration, - minorTicksPerInterval: minorTicksPerInterval, - showTicks: showTicks, - showLabels: showLabels, - showDividers: showDividers, - enableTooltip: enableTooltip, - shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, - labelPlacement: labelPlacement, - edgeLabelPlacement: edgeLabelPlacement, - numberFormat: numberFormat, - dateFormat: dateFormat, - dateIntervalType: dateIntervalType, - labelFormatterCallback: labelFormatterCallback, - tooltipTextFormatterCallback: tooltipTextFormatterCallback, - trackShape: trackShape, - dividerShape: dividerShape, - overlayShape: overlayShape, - thumbShape: thumbShape, - tickShape: tickShape, - minorTickShape: minorTickShape, - tooltipShape: tooltipShape, - sliderThemeData: sliderThemeData, - sliderType: sliderType, - tooltipPosition: tooltipPosition, - textDirection: textDirection, - mediaQueryData: mediaQueryData, - isInversed: isInversed) { + }) : _values = values!, + _dragMode = dragMode, + _enableIntervalSelection = enableIntervalSelection, + super( + min: min, + max: max, + interval: interval, + stepSize: stepSize, + stepDuration: stepDuration, + minorTicksPerInterval: minorTicksPerInterval, + showTicks: showTicks, + showLabels: showLabels, + showDividers: showDividers, + enableTooltip: enableTooltip, + shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, + labelPlacement: labelPlacement, + edgeLabelPlacement: edgeLabelPlacement, + numberFormat: numberFormat, + dateFormat: dateFormat, + dateIntervalType: dateIntervalType, + labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, + tooltipTextFormatterCallback: tooltipTextFormatterCallback, + trackShape: trackShape, + dividerShape: dividerShape, + overlayShape: overlayShape, + thumbShape: thumbShape, + tickShape: tickShape, + minorTickShape: minorTickShape, + tooltipShape: tooltipShape, + sliderThemeData: sliderThemeData, + sliderType: sliderType, + tooltipPosition: tooltipPosition, + textDirection: textDirection, + mediaQueryData: mediaQueryData, + isInversed: isInversed, + ) { final GestureArenaTeam team = GestureArenaTeam(); if (sliderType == SliderType.horizontal) { - horizontalDragGestureRecognizer = HorizontalDragGestureRecognizer() - ..team = team - ..onDown = _onDragDown - ..onStart = _onDragStart - ..onUpdate = _onDragUpdate - ..onEnd = _onDragEnd - ..onCancel = _onDragCancel - ..gestureSettings = gestureSettings; + horizontalDragGestureRecognizer = + HorizontalDragGestureRecognizer() + ..team = team + ..onDown = _onDragDown + ..onStart = _onDragStart + ..onUpdate = _onDragUpdate + ..onEnd = _onDragEnd + ..onCancel = _onDragCancel + ..gestureSettings = gestureSettings; } if (sliderType == SliderType.vertical) { - verticalDragGestureRecognizer = VerticalDragGestureRecognizer() - ..team = team - ..onStart = _onVerticalDragStart - ..onUpdate = _onVerticalDragUpdate - ..onEnd = _onVerticalDragEnd - ..onCancel = _onVerticalDragCancel - ..gestureSettings = gestureSettings; + verticalDragGestureRecognizer = + VerticalDragGestureRecognizer() + ..team = team + ..onStart = _onVerticalDragStart + ..onUpdate = _onVerticalDragUpdate + ..onEnd = _onVerticalDragEnd + ..onCancel = _onVerticalDragCancel + ..gestureSettings = gestureSettings; } - tapGestureRecognizer = TapGestureRecognizer() - ..team = team - ..onTapDown = _onTapDown - ..onTapUp = _onTapUp; + tapGestureRecognizer = + TapGestureRecognizer() + ..team = team + ..onTapDown = _onTapDown + ..onTapUp = _onTapUp; _overlayStartAnimation = CurvedAnimation( - parent: overlayStartController, curve: Curves.fastOutSlowIn); + parent: overlayStartController, + curve: Curves.fastOutSlowIn, + ); _overlayEndAnimation = CurvedAnimation( - parent: overlayEndController, curve: Curves.fastOutSlowIn); - _stateAnimation = - CurvedAnimation(parent: stateController, curve: Curves.easeInOut); + parent: overlayEndController, + curve: Curves.fastOutSlowIn, + ); + _stateAnimation = CurvedAnimation( + parent: stateController, + curve: Curves.easeInOut, + ); _tooltipStartAnimation = CurvedAnimation( - parent: tooltipAnimationStartController, curve: Curves.fastOutSlowIn); + parent: tooltipAnimationStartController, + curve: Curves.fastOutSlowIn, + ); _tooltipEndAnimation = CurvedAnimation( - parent: tooltipAnimationEndController, curve: Curves.fastOutSlowIn); + parent: tooltipAnimationEndController, + curve: Curves.fastOutSlowIn, + ); if (shouldAlwaysShowTooltip) { tooltipAnimationStartController.value = 1; @@ -136,11 +153,14 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider if (isDateTime) { _valuesInMilliseconds = SfRangeValues( - values.start.millisecondsSinceEpoch.toDouble(), - values.end.millisecondsSinceEpoch.toDouble()); + values.start.millisecondsSinceEpoch.toDouble(), + values.end.millisecondsSinceEpoch.toDouble(), + ); } else { _values = SfRangeValues( - (values.start as num).toDouble(), (values.end as num).toDouble()); + (values.start as num).toDouble(), + (values.end as num).toDouble(), + ); } unformattedLabels = []; updateTextPainter(); @@ -186,8 +206,92 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider // method, which is used to check whether dragging is started or not. double _interactionStartOffset = 0.0; - static const Duration _positionAnimationDuration = - Duration(milliseconds: 500); + static const Duration _positionAnimationDuration = Duration( + milliseconds: 500, + ); + + SfThumb _focusedThumb = SfThumb.start; + bool _hasFocus = false; + + SfThumb get focusedThumb => _focusedThumb; + set focusedThumb(SfThumb value) { + if (_focusedThumb == value) { + return; + } + _focusedThumb = value; + + if (_hasFocus) { + _updateFocusedThumbState(); + } + markNeedsPaint(); + } + + bool get hasFocus => _hasFocus; + set hasFocus(bool value) { + if (value == _hasFocus) { + return; + } + _hasFocus = value; + _updateForFocus(_hasFocus); + markNeedsSemanticsUpdate(); + } + + void _updateForFocus(bool focused) { + if (shouldAlwaysShowTooltip) { + tooltipAnimationStartController.forward(); + tooltipAnimationEndController.forward(); + + if (focused) { + _updateFocusedThumbOverlay(); + } else { + overlayStartController.reverse(); + overlayEndController.reverse(); + } + } else if (focused) { + _updateFocusedThumbState(); + } else { + overlayStartController.reverse(); + overlayEndController.reverse(); + if (enableTooltip && !shouldAlwaysShowTooltip) { + tooltipAnimationStartController.reverse(); + tooltipAnimationEndController.reverse(); + } + } + } + + void _updateFocusedThumbOverlay() { + if (focusedThumb == SfThumb.start) { + overlayStartController.forward(); + overlayEndController.reverse(); + } else { + overlayEndController.forward(); + overlayStartController.reverse(); + } + } + + void _updateFocusedThumbState() { + if (focusedThumb == SfThumb.start) { + overlayStartController.forward(); + overlayEndController.reverse(); + if (enableTooltip) { + willDrawTooltip = true; + tooltipAnimationStartController.forward(); + if (!shouldAlwaysShowTooltip) { + tooltipAnimationEndController.reverse(); + } + } + } else { + overlayEndController.forward(); + overlayStartController.reverse(); + if (enableTooltip) { + willDrawTooltip = true; + tooltipAnimationEndController.forward(); + if (!shouldAlwaysShowTooltip) { + tooltipAnimationStartController.reverse(); + } + } + } + } SfRangeValues get values => _values; late SfRangeValues _values; @@ -195,15 +299,29 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider if (_values == values) { return; } - _values = isDateTime - ? values - : SfRangeValues( - (values.start as num).toDouble(), (values.end as num).toDouble()); + _values = + isDateTime + ? values + : SfRangeValues( + (values.start as num).toDouble(), + (values.end as num).toDouble(), + ); if (isDateTime) { _valuesInMilliseconds = SfRangeValues( - _values.start.millisecondsSinceEpoch.toDouble(), - _values.end.millisecondsSinceEpoch.toDouble()); + _values.start.millisecondsSinceEpoch.toDouble(), + _values.end.millisecondsSinceEpoch.toDouble(), + ); } + + if (generateLabelsAndTicks()) { + // For the range selector, labels and ticks are not generated while moving the thumb. + // After implementing the onLabelCreated callback, the labels are not updated dynamically. + // Therefore, generate labels and ticks if onLabelCreated is not null and the chart’s range + // controller is null. + generateLabelsAndMajorTicks(); + generateMinorTicks(); + } + markNeedsPaint(); } @@ -230,15 +348,21 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider RenderBox? get startThumbIcon => _startThumbIcon; RenderBox? _startThumbIcon; set startThumbIcon(RenderBox? value) { - _startThumbIcon = - updateChild(_startThumbIcon, value, ChildElements.startThumbIcon); + _startThumbIcon = updateChild( + _startThumbIcon, + value, + ChildElements.startThumbIcon, + ); } RenderBox? get endThumbIcon => _endThumbIcon; RenderBox? _endThumbIcon; set endThumbIcon(RenderBox? value) { - _endThumbIcon = - updateChild(_endThumbIcon, value, ChildElements.endThumbIcon); + _endThumbIcon = updateChild( + _endThumbIcon, + value, + ChildElements.endThumbIcon, + ); } @override @@ -270,9 +394,10 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider endPositionController.value = getFactorFromValue(actualValues.end); } - double get minThumbGap => isDiscrete - ? 0 - : sliderType == SliderType.horizontal + double get minThumbGap => + isDiscrete + ? 0 + : sliderType == SliderType.horizontal ? (actualMax - actualMin) * (8 / actualTrackRect.width).clamp(0.0, 1.0) : (actualMax - actualMin) * @@ -282,27 +407,42 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider isDateTime ? _valuesInMilliseconds : _values; dynamic get increasedStartValue { - return getNextSemanticValue(values.start, semanticActionUnit, - actualValue: actualValues.start); + return getNextSemanticValue( + values.start, + semanticActionUnit, + actualValue: actualValues.start, + ); } dynamic get decreasedStartValue { - return getPrevSemanticValue(values.start, semanticActionUnit, - actualValue: actualValues.start); + return getPrevSemanticValue( + values.start, + semanticActionUnit, + actualValue: actualValues.start, + ); } dynamic get increasedEndValue { - return getNextSemanticValue(values.end, semanticActionUnit, - actualValue: actualValues.end); + return getNextSemanticValue( + values.end, + semanticActionUnit, + actualValue: actualValues.end, + ); } dynamic get decreasedEndValue { - return getPrevSemanticValue(values.end, semanticActionUnit, - actualValue: actualValues.end); + return getPrevSemanticValue( + values.end, + semanticActionUnit, + actualValue: actualValues.end, + ); } RenderBox? updateChild( - RenderBox? oldChild, RenderBox? newChild, ChildElements slot) { + RenderBox? oldChild, + RenderBox? newChild, + ChildElements slot, + ) { if (oldChild != null) { dropChild(oldChild); childToSlot.remove(oldChild); @@ -318,9 +458,10 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider void _onTapDown(TapDownDetails details) { currentPointerType = PointerType.down; - _interactionStartOffset = sliderType == SliderType.horizontal - ? globalToLocal(details.globalPosition).dx - : globalToLocal(details.globalPosition).dy; + _interactionStartOffset = + sliderType == SliderType.horizontal + ? globalToLocal(details.globalPosition).dx + : globalToLocal(details.globalPosition).dy; mainAxisOffset = _interactionStartOffset; _beginInteraction(); } @@ -386,10 +527,12 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider // field in [endInteraction] method. isIntervalTapped = false; isInteractionEnd = false; - final double startPosition = - getPositionFromValue(actualValues.start.toDouble()); - final double endPosition = - getPositionFromValue(actualValues.end.toDouble()); + final double startPosition = getPositionFromValue( + actualValues.start.toDouble(), + ); + final double endPosition = getPositionFromValue( + actualValues.end.toDouble(), + ); final double leftThumbWidth = (startPosition - mainAxisOffset).abs(); final double rightThumbWidth = (endPosition - mainAxisOffset).abs(); @@ -442,7 +585,8 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider } bool _tappedBetweenThumbs(double startPosition, double endPosition) { - final double thumbRadius = (sliderType == SliderType.horizontal + final double thumbRadius = + (sliderType == SliderType.horizontal ? actualThumbSize.width : actualThumbSize.height) / 2; @@ -504,21 +648,25 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider final double factor = getFactorFromCurrentPosition(); final double value = lerpDouble(actualMin, actualMax, factor)!; final double start = getNumerizedValue( - isDateTime ? values.start : values.start.toDouble()); - final double end = - getNumerizedValue(isDateTime ? values.end : values.end.toDouble()); + isDateTime ? values.start : values.start.toDouble(), + ); + final double end = getNumerizedValue( + isDateTime ? values.end : values.end.toDouble(), + ); switch (activeThumb!) { case SfThumb.start: final double startValue = math.min(value, end - minThumbGap); - final dynamic actualStartValue = - getActualValue(valueInDouble: startValue); + final dynamic actualStartValue = getActualValue( + valueInDouble: startValue, + ); _newValues = values.copyWith(start: actualStartValue); break; case SfThumb.end: final double endValue = math.max(value, start + minThumbGap); - final dynamic actualEndValue = - getActualValue(valueInDouble: endValue); + final dynamic actualEndValue = getActualValue( + valueInDouble: endValue, + ); _newValues = values.copyWith(end: actualEndValue); break; case SfThumb.both: @@ -533,10 +681,12 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider SfRangeValues _getLockRangeValues(double? delta) { final bool isVertical = sliderType == SliderType.vertical; - double startPosition = - getPositionFromValue(getNumerizedValue(_beginValues.start)); - double endPosition = - getPositionFromValue(getNumerizedValue(_beginValues.end)); + double startPosition = getPositionFromValue( + getNumerizedValue(_beginValues.start), + ); + double endPosition = getPositionFromValue( + getNumerizedValue(_beginValues.end), + ); final double lockedRangeWidth = (!isVertical && isInversed) || (isVertical && !isInversed) ? startPosition - endPosition @@ -568,7 +718,9 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider endPosition = actualTrackRect.bottom - endPosition; } return SfRangeValues( - getValueFromPosition(startPosition), getValueFromPosition(endPosition)); + getValueFromPosition(startPosition), + getValueFromPosition(endPosition), + ); } /// Notify the new values to the users using [onChanged] callback in range @@ -577,13 +729,34 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider markNeedsSemanticsUpdate(); } + @override + bool isActiveLabelValue(currentValue) { + if (currentValue is DateTime && + values.start is DateTime && + values.end is DateTime) { + return currentValue.millisecondsSinceEpoch >= + values.start.millisecondsSinceEpoch && + currentValue.microsecondsSinceEpoch <= + values.end.microsecondsSinceEpoch; + } else { + return currentValue >= values.start && currentValue <= values.end; + } + } + + bool generateLabelsAndTicks() { + return false; + } + void _endInteraction() { if (!isInteractionEnd) { SfRangeValues newValues = values; if (_enableIntervalSelection) { if (isIntervalTapped) { - final double? value = - lerpDouble(actualMin, actualMax, getFactorFromCurrentPosition()); + final double? value = lerpDouble( + actualMin, + actualMax, + getFactorFromCurrentPosition(), + ); newValues = _getSelectedRange(value!); _newValues = newValues; _updatePositionControllerValue(newValues); @@ -631,9 +804,10 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider break; } } else { - start = isDateTime - ? DateTime.fromMillisecondsSinceEpoch(currentLabel.toInt()) - : currentLabel; + start = + isDateTime + ? DateTime.fromMillisecondsSinceEpoch(currentLabel.toInt()) + : currentLabel; // ignore: unnecessary_this end = this.max; rangeValues = SfRangeValues(start, end); @@ -652,25 +826,31 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider // ignore: avoid_as endDate = newValues.end as DateTime; } - final double startValueFactor = getFactorFromValue(isDateTime - ? startDate!.millisecondsSinceEpoch.toDouble() - : newValues.start); - final double endValueFactor = getFactorFromValue(isDateTime - ? endDate!.millisecondsSinceEpoch.toDouble() - : newValues.end); + final double startValueFactor = getFactorFromValue( + isDateTime + ? startDate!.millisecondsSinceEpoch.toDouble() + : newValues.start, + ); + final double endValueFactor = getFactorFromValue( + isDateTime ? endDate!.millisecondsSinceEpoch.toDouble() : newValues.end, + ); final double startDistanceFactor = (startValueFactor - startPositionController.value).abs(); final double endDistanceFactor = (endValueFactor - endPositionController.value).abs(); - startPositionController.duration = startDistanceFactor != 0.0 - ? _positionAnimationDuration * (1.0 / startDistanceFactor) - : Duration.zero; - endPositionController.duration = endDistanceFactor != 0.0 - ? _positionAnimationDuration * (1.0 / endDistanceFactor) - : Duration.zero; - startPositionController.animateTo(startValueFactor, - curve: Curves.easeInOut); + startPositionController.duration = + startDistanceFactor != 0.0 + ? _positionAnimationDuration * (1.0 / startDistanceFactor) + : Duration.zero; + endPositionController.duration = + endDistanceFactor != 0.0 + ? _positionAnimationDuration * (1.0 / endDistanceFactor) + : Duration.zero; + startPositionController.animateTo( + startValueFactor, + curve: Curves.easeInOut, + ); endPositionController.animateTo(endValueFactor, curve: Curves.easeInOut); } @@ -751,17 +931,21 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider void _handleHover(PointerHoverEvent details) { double cursorPosition = 0.0; - final double startThumbPosition = - getPositionFromValue(actualValues.start.toDouble()); - final double endThumbPosition = - getPositionFromValue(actualValues.end.toDouble()); - cursorPosition = sliderType == SliderType.horizontal - ? details.localPosition.dx - : details.localPosition.dy; + final double startThumbPosition = getPositionFromValue( + actualValues.start.toDouble(), + ); + final double endThumbPosition = getPositionFromValue( + actualValues.end.toDouble(), + ); + cursorPosition = + sliderType == SliderType.horizontal + ? details.localPosition.dx + : details.localPosition.dy; final double startThumbDistance = (cursorPosition - startThumbPosition).abs(); final double endThumbDistance = (cursorPosition - endThumbPosition).abs(); - final double thumbRadius = (sliderType == SliderType.horizontal + final double thumbRadius = + (sliderType == SliderType.horizontal ? actualThumbSize.width : actualThumbSize.height) / 2; @@ -866,7 +1050,8 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider // Ignore overlapping thumb stroke for bottom thumb. showOverlappingThumbStroke = false; if (thumbIcon != null) { - (thumbIcon.parentData! as BoxParentData).offset = thumbCenter - + (thumbIcon.parentData! as BoxParentData).offset = + thumbCenter - Offset(thumbIcon.size.width / 2, thumbIcon.size.height / 2) - paintOffset; } @@ -889,20 +1074,24 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider } // Drawing thumb. - thumbShape.paint(context, thumbCenter, - parentBox: this, - child: thumbIcon, - themeData: sliderThemeData, - currentValues: _values, - enableAnimation: _stateAnimation, - textDirection: textDirection, - thumb: isStartThumbActive ? SfThumb.end : SfThumb.start, - paint: null); + thumbShape.paint( + context, + thumbCenter, + parentBox: this, + child: thumbIcon, + themeData: sliderThemeData, + currentValues: _values, + enableAnimation: _stateAnimation, + textDirection: textDirection, + thumb: isStartThumbActive ? SfThumb.end : SfThumb.start, + paint: null, + ); thumbCenter = isStartThumbActive ? startThumbCenter : endThumbCenter; thumbIcon = isStartThumbActive ? _startThumbIcon : _endThumbIcon; if (thumbIcon != null) { - (thumbIcon.parentData! as BoxParentData).offset = thumbCenter - + (thumbIcon.parentData! as BoxParentData).offset = + thumbCenter - Offset(thumbIcon.size.width / 2, thumbIcon.size.height / 2) - paintOffset; } @@ -924,7 +1113,8 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider ); } - showOverlappingThumbStroke = (getFactorFromValue(actualValues.start) - + showOverlappingThumbStroke = + (getFactorFromValue(actualValues.start) - getFactorFromValue(actualValues.end)) .abs() * (sliderType == SliderType.horizontal @@ -933,119 +1123,145 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider actualThumbSize.width; // Drawing thumb. - thumbShape.paint(context, thumbCenter, - parentBox: this, - child: thumbIcon, - themeData: sliderThemeData, - currentValues: _values, - enableAnimation: _stateAnimation, - textDirection: textDirection, - thumb: isStartThumbActive ? SfThumb.start : SfThumb.end, - paint: null); + thumbShape.paint( + context, + thumbCenter, + parentBox: this, + child: thumbIcon, + themeData: sliderThemeData, + currentValues: _values, + enableAnimation: _stateAnimation, + textDirection: textDirection, + thumb: isStartThumbActive ? SfThumb.start : SfThumb.end, + paint: null, + ); } void _drawTooltip( - PaintingContext context, - Offset endThumbCenter, - Offset startThumbCenter, - Offset offset, - Offset actualTrackOffset, - Rect trackRect) { + PaintingContext context, + Offset endThumbCenter, + Offset startThumbCenter, + Offset offset, + Offset actualTrackOffset, + Rect trackRect, + ) { if (willDrawTooltip || shouldAlwaysShowTooltip) { - final Paint paint = Paint() - ..color = sliderThemeData.tooltipBackgroundColor! - ..style = PaintingStyle.fill - ..strokeWidth = 0; + final Paint paint = + Paint() + ..color = sliderThemeData.tooltipBackgroundColor! + ..style = PaintingStyle.fill + ..strokeWidth = 0; final bool isStartThumbActive = activeThumb == SfThumb.start; Offset thumbCenter = isStartThumbActive ? endThumbCenter : startThumbCenter; - dynamic actualText = (sliderType == SliderType.horizontal) - ? getValueFromPosition(thumbCenter.dx - offset.dx) - : getValueFromPosition(trackRect.bottom - thumbCenter.dy); + dynamic actualText = + (sliderType == SliderType.horizontal) + ? getValueFromPosition(thumbCenter.dx - offset.dx) + : getValueFromPosition(trackRect.bottom - thumbCenter.dy); String tooltipText = tooltipTextFormatterCallback( - actualText, getFormattedText(actualText)); - TextSpan textSpan = - TextSpan(text: tooltipText, style: sliderThemeData.tooltipTextStyle); + actualText, + getFormattedText(actualText), + ); + TextSpan textSpan = TextSpan( + text: tooltipText, + style: sliderThemeData.tooltipTextStyle, + ); textPainter.text = textSpan; textPainter.layout(); Rect? bottomTooltipRect; if (tooltipShape is SfPaddleTooltipShape) { bottomTooltipRect = getPaddleTooltipRect( - textPainter, - actualThumbSize.width / 2, - Offset(actualTrackOffset.dx, tooltipStartY), - thumbCenter, - trackRect, - sliderThemeData); + textPainter, + actualThumbSize.width / 2, + Offset(actualTrackOffset.dx, tooltipStartY), + thumbCenter, + trackRect, + sliderThemeData, + ); } else if (tooltipShape is SfRectangularTooltipShape) { bottomTooltipRect = getRectangularTooltipRect( - textPainter, - Offset(actualTrackOffset.dx, tooltipStartY), - thumbCenter, - trackRect, - sliderThemeData); + textPainter, + Offset(actualTrackOffset.dx, tooltipStartY), + thumbCenter, + trackRect, + sliderThemeData, + ); } // Ignore overlapping tooltip stroke for bottom tooltip. showOverlappingTooltipStroke = false; - tooltipShape.paint(context, thumbCenter, - Offset(actualTrackOffset.dx, tooltipStartY), textPainter, - parentBox: this, - sliderThemeData: sliderThemeData, - paint: paint, - animation: isStartThumbActive - ? _tooltipEndAnimation - : _tooltipStartAnimation, - trackRect: trackRect); + tooltipShape.paint( + context, + thumbCenter, + Offset(actualTrackOffset.dx, tooltipStartY), + textPainter, + parentBox: this, + sliderThemeData: sliderThemeData, + paint: paint, + animation: + isStartThumbActive ? _tooltipEndAnimation : _tooltipStartAnimation, + trackRect: trackRect, + ); thumbCenter = isStartThumbActive ? startThumbCenter : endThumbCenter; - actualText = (sliderType == SliderType.horizontal) - ? getValueFromPosition(thumbCenter.dx - offset.dx) - : getValueFromPosition(trackRect.bottom - thumbCenter.dy); + actualText = + (sliderType == SliderType.horizontal) + ? getValueFromPosition(thumbCenter.dx - offset.dx) + : getValueFromPosition(trackRect.bottom - thumbCenter.dy); tooltipText = tooltipTextFormatterCallback( - actualText, getFormattedText(actualText)); - textSpan = - TextSpan(text: tooltipText, style: sliderThemeData.tooltipTextStyle); + actualText, + getFormattedText(actualText), + ); + textSpan = TextSpan( + text: tooltipText, + style: sliderThemeData.tooltipTextStyle, + ); textPainter.text = textSpan; textPainter.layout(); Rect? topTooltipRect; if (tooltipShape is SfPaddleTooltipShape) { topTooltipRect = getPaddleTooltipRect( - textPainter, - actualThumbSize.width / 2, - Offset(actualTrackOffset.dx, tooltipStartY), - thumbCenter, - trackRect, - sliderThemeData); + textPainter, + actualThumbSize.width / 2, + Offset(actualTrackOffset.dx, tooltipStartY), + thumbCenter, + trackRect, + sliderThemeData, + ); } else if (tooltipShape is SfRectangularTooltipShape) { topTooltipRect = getRectangularTooltipRect( - textPainter, - Offset(actualTrackOffset.dx, tooltipStartY), - thumbCenter, - trackRect, - sliderThemeData); + textPainter, + Offset(actualTrackOffset.dx, tooltipStartY), + thumbCenter, + trackRect, + sliderThemeData, + ); } if (bottomTooltipRect != null && topTooltipRect != null) { final Rect overlapRect = topTooltipRect.intersect(bottomTooltipRect); - showOverlappingTooltipStroke = sliderType == SliderType.horizontal - ? overlapRect.right > overlapRect.left - : overlapRect.top < overlapRect.bottom; + showOverlappingTooltipStroke = + sliderType == SliderType.horizontal + ? overlapRect.right > overlapRect.left + : overlapRect.top < overlapRect.bottom; } - tooltipShape.paint(context, thumbCenter, - Offset(actualTrackOffset.dx, tooltipStartY), textPainter, - parentBox: this, - sliderThemeData: sliderThemeData, - paint: paint, - animation: isStartThumbActive - ? _tooltipStartAnimation - : _tooltipEndAnimation, - trackRect: trackRect); + tooltipShape.paint( + context, + thumbCenter, + Offset(actualTrackOffset.dx, tooltipStartY), + textPainter, + parentBox: this, + sliderThemeData: sliderThemeData, + paint: paint, + animation: + isStartThumbActive ? _tooltipStartAnimation : _tooltipEndAnimation, + trackRect: trackRect, + ); } } @@ -1054,8 +1270,13 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider void updateIntervalTappedAndDeferredUpdateValues(SfRangeValues values); /// Used to draw active and inactive regions. - void drawRegions(PaintingContext context, Rect trackRect, Offset offset, - Offset startThumbCenter, Offset endThumbCenter) { + void drawRegions( + PaintingContext context, + Rect trackRect, + Offset offset, + Offset startThumbCenter, + Offset endThumbCenter, + ) { /// This override method declared to draw active and inactive region in /// the [SfRangeSelector]. } @@ -1067,15 +1288,18 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider _overlayStartAnimation.addListener(markNeedsPaint); _overlayEndAnimation.addListener(markNeedsPaint); startPositionController.addListener(markNeedsPaint); - startPositionController - .addStatusListener(_handlePositionControllerStatusChange); + startPositionController.addStatusListener( + _handlePositionControllerStatusChange, + ); endPositionController.addListener(markNeedsPaint); - endPositionController - .addStatusListener(_handlePositionControllerStatusChange); + endPositionController.addStatusListener( + _handlePositionControllerStatusChange, + ); _stateAnimation.addListener(markNeedsPaint); _tooltipStartAnimation.addListener(markNeedsPaint); - _tooltipStartAnimation - .addStatusListener(_handleTooltipAnimationStatusChange); + _tooltipStartAnimation.addStatusListener( + _handleTooltipAnimationStatusChange, + ); _tooltipEndAnimation.addListener(markNeedsPaint); _tooltipEndAnimation.addStatusListener(_handleTooltipAnimationStatusChange); } @@ -1086,18 +1310,22 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider _overlayStartAnimation.removeListener(markNeedsPaint); _overlayEndAnimation.removeListener(markNeedsPaint); startPositionController.removeListener(markNeedsPaint); - startPositionController - .removeStatusListener(_handlePositionControllerStatusChange); + startPositionController.removeStatusListener( + _handlePositionControllerStatusChange, + ); endPositionController.removeListener(markNeedsPaint); - endPositionController - .removeStatusListener(_handlePositionControllerStatusChange); + endPositionController.removeStatusListener( + _handlePositionControllerStatusChange, + ); _stateAnimation.removeListener(markNeedsPaint); _tooltipStartAnimation.removeListener(markNeedsPaint); - _tooltipStartAnimation - .removeStatusListener(_handleTooltipAnimationStatusChange); + _tooltipStartAnimation.removeStatusListener( + _handleTooltipAnimationStatusChange, + ); _tooltipEndAnimation.removeListener(markNeedsPaint); - _tooltipEndAnimation - .removeStatusListener(_handleTooltipAnimationStatusChange); + _tooltipEndAnimation.removeStatusListener( + _handleTooltipAnimationStatusChange, + ); super.detach(); } @@ -1155,7 +1383,8 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider @override void handleEvent(PointerEvent event, HitTestEntry entry) { - final bool isDesktop = kIsWeb || + final bool isDesktop = + kIsWeb || defaultTargetPlatform == TargetPlatform.macOS || defaultTargetPlatform == TargetPlatform.windows || defaultTargetPlatform == TargetPlatform.linux; @@ -1168,57 +1397,97 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider /// This method used to draw all slider elements such as track, tick, /// dividers, thumb, and overlay. void drawRangeSliderElements( - PaintingContext context, Offset offset, Offset actualTrackOffset) { + PaintingContext context, + Offset offset, + Offset actualTrackOffset, + ) { Offset startThumbCenter; Offset endThumbCenter; // Drawing track. - final Rect trackRect = - trackShape.getPreferredRect(this, sliderThemeData, actualTrackOffset); - double thumbStartPosition = isIntervalTapped - ? startPositionController.value - : getFactorFromValue(actualValues.start); - double thumbEndPosition = isIntervalTapped - ? endPositionController.value - : getFactorFromValue(actualValues.end); + final Rect trackRect = trackShape.getPreferredRect( + this, + sliderThemeData, + actualTrackOffset, + ); + double thumbStartPosition = + isIntervalTapped + ? startPositionController.value + : getFactorFromValue(actualValues.start); + double thumbEndPosition = + isIntervalTapped + ? endPositionController.value + : getFactorFromValue(actualValues.end); if (sliderType == SliderType.horizontal) { thumbStartPosition = thumbStartPosition * trackRect.width; thumbEndPosition = thumbEndPosition * trackRect.width; - startThumbCenter = - Offset(trackRect.left + thumbStartPosition, trackRect.center.dy); - endThumbCenter = - Offset(trackRect.left + thumbEndPosition, trackRect.center.dy); + startThumbCenter = Offset( + trackRect.left + thumbStartPosition, + trackRect.center.dy, + ); + endThumbCenter = Offset( + trackRect.left + thumbEndPosition, + trackRect.center.dy, + ); } else { thumbStartPosition = thumbStartPosition * trackRect.height; thumbEndPosition = thumbEndPosition * trackRect.height; - startThumbCenter = - Offset(trackRect.center.dx, trackRect.bottom - thumbStartPosition); - endThumbCenter = - Offset(trackRect.center.dx, trackRect.bottom - thumbEndPosition); + startThumbCenter = Offset( + trackRect.center.dx, + trackRect.bottom - thumbStartPosition, + ); + endThumbCenter = Offset( + trackRect.center.dx, + trackRect.bottom - thumbEndPosition, + ); } trackShape.paint( - context, actualTrackOffset, null, startThumbCenter, endThumbCenter, - parentBox: this, - themeData: sliderThemeData, - currentValues: values, - enableAnimation: _stateAnimation, - textDirection: textDirection, - activePaint: null, - inactivePaint: null); + context, + actualTrackOffset, + null, + startThumbCenter, + endThumbCenter, + parentBox: this, + themeData: sliderThemeData, + currentValues: values, + enableAnimation: _stateAnimation, + textDirection: textDirection, + activePaint: null, + inactivePaint: null, + ); if (showLabels || showTicks || showDividers) { - drawLabelsTicksAndDividers(context, trackRect, offset, null, - startThumbCenter, endThumbCenter, _stateAnimation, null, _values); + drawLabelsTicksAndDividers( + context, + trackRect, + offset, + null, + startThumbCenter, + endThumbCenter, + _stateAnimation, + null, + _values, + ); } drawRegions(context, trackRect, offset, startThumbCenter, endThumbCenter); _drawOverlayAndThumb(context, offset, endThumbCenter, startThumbCenter); // To avoid positioning the tooltip text on the edge, used a 5px margin. final Rect tooltipTargetRect = Rect.fromLTWH( - 5.0, trackRect.top, mediaQueryData.size.width - 5.0, trackRect.height); - _drawTooltip(context, endThumbCenter, startThumbCenter, offset, - actualTrackOffset, tooltipTargetRect); + 5.0, + trackRect.top, + mediaQueryData.size.width - 5.0, + trackRect.height, + ); + _drawTooltip( + context, + endThumbCenter, + startThumbCenter, + offset, + actualTrackOffset, + tooltipTargetRect, + ); } /// Describe the semantics of the start thumb. @@ -1229,23 +1498,45 @@ abstract class RenderBaseRangeSlider extends RenderBaseSlider /// Used to set values to the shape properties in diagnostics tree. void debugRangeSliderFillProperties(DiagnosticPropertiesBuilder properties) { - properties.add(StringProperty( - 'thumbSize', thumbShape.getPreferredSize(sliderThemeData).toString())); - properties.add(StringProperty( + properties.add( + StringProperty( + 'thumbSize', + thumbShape.getPreferredSize(sliderThemeData).toString(), + ), + ); + properties.add( + StringProperty( 'activeDividerSize', dividerShape .getPreferredSize(sliderThemeData, isActive: true) - .toString())); - properties.add(StringProperty( + .toString(), + ), + ); + properties.add( + StringProperty( 'inactiveDividerSize', dividerShape .getPreferredSize(sliderThemeData, isActive: false) - .toString())); - properties.add(StringProperty('overlaySize', - overlayShape.getPreferredSize(sliderThemeData).toString())); - properties.add(StringProperty( - 'tickSize', tickShape.getPreferredSize(sliderThemeData).toString())); - properties.add(StringProperty('minorTickSize', - minorTickShape.getPreferredSize(sliderThemeData).toString())); + .toString(), + ), + ); + properties.add( + StringProperty( + 'overlaySize', + overlayShape.getPreferredSize(sliderThemeData).toString(), + ), + ); + properties.add( + StringProperty( + 'tickSize', + tickShape.getPreferredSize(sliderThemeData).toString(), + ), + ); + properties.add( + StringProperty( + 'minorTickSize', + minorTickShape.getPreferredSize(sliderThemeData).toString(), + ), + ); } } diff --git a/packages/syncfusion_flutter_sliders/lib/src/slider.dart b/packages/syncfusion_flutter_sliders/lib/src/slider.dart index 17a5dcd42..f1e45c0b8 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/slider.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/slider.dart @@ -111,47 +111,49 @@ import 'theme.dart'; /// * [SfSliderThemeData](https://pub.dev/documentation/syncfusion_flutter_core/latest/theme/SfSliderThemeData-class.html), for customizing the visual appearance of the slider. class SfSlider extends StatefulWidget { /// Creates a horizontal [SfSlider]. - const SfSlider( - {Key? key, - this.min = 0.0, - this.max = 1.0, - required this.value, - required this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.interval, - this.stepSize, - this.stepDuration, - this.minorTicksPerInterval = 0, - this.showTicks = false, - this.showLabels = false, - this.showDividers = false, - this.enableTooltip = false, - this.shouldAlwaysShowTooltip = false, - this.activeColor, - this.inactiveColor, - this.labelPlacement = LabelPlacement.onTicks, - this.edgeLabelPlacement = EdgeLabelPlacement.auto, - this.numberFormat, - this.dateFormat, - this.dateIntervalType, - this.labelFormatterCallback, - this.tooltipTextFormatterCallback, - this.semanticFormatterCallback, - this.trackShape = const SfTrackShape(), - this.dividerShape = const SfDividerShape(), - this.overlayShape = const SfOverlayShape(), - this.thumbShape = const SfThumbShape(), - this.tickShape = const SfTickShape(), - this.minorTickShape = const SfMinorTickShape(), - this.tooltipShape = const SfRectangularTooltipShape(), - this.thumbIcon}) - : isInversed = false, - _sliderType = SliderType.horizontal, - _tooltipPosition = null, - assert(min != max), - assert(interval == null || interval > 0), - super(key: key); + const SfSlider({ + Key? key, + this.min = 0.0, + this.max = 1.0, + required this.value, + required this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.interval, + this.stepSize, + this.stepDuration, + this.minorTicksPerInterval = 0, + this.showTicks = false, + this.showLabels = false, + this.showDividers = false, + this.enableTooltip = false, + this.shouldAlwaysShowTooltip = false, + this.activeColor, + this.inactiveColor, + this.labelPlacement = LabelPlacement.onTicks, + this.edgeLabelPlacement = EdgeLabelPlacement.auto, + this.numberFormat, + this.dateFormat, + this.dateIntervalType, + // ignore: deprecated_consistency + this.labelFormatterCallback, + this.onLabelCreated, + this.tooltipTextFormatterCallback, + this.semanticFormatterCallback, + this.trackShape = const SfTrackShape(), + this.dividerShape = const SfDividerShape(), + this.overlayShape = const SfOverlayShape(), + this.thumbShape = const SfThumbShape(), + this.tickShape = const SfTickShape(), + this.minorTickShape = const SfMinorTickShape(), + this.tooltipShape = const SfRectangularTooltipShape(), + this.thumbIcon, + }) : isInversed = false, + _sliderType = SliderType.horizontal, + _tooltipPosition = null, + assert(min != max), + assert(interval == null || interval > 0), + super(key: key); /// Creates a vertical [SfSlider]. /// @@ -195,49 +197,52 @@ class SfSlider extends StatefulWidget { /// See also: /// /// * Check the default constructor for horizontal slider. - const SfSlider.vertical( - {Key? key, - this.min = 0.0, - this.max = 1.0, - required this.value, - required this.onChanged, - this.onChangeStart, - this.onChangeEnd, - this.interval, - this.stepSize, - this.stepDuration, - this.minorTicksPerInterval = 0, - this.showTicks = false, - this.showLabels = false, - this.showDividers = false, - this.enableTooltip = false, - this.shouldAlwaysShowTooltip = false, - this.isInversed = false, - this.activeColor, - this.inactiveColor, - this.labelPlacement = LabelPlacement.onTicks, - this.edgeLabelPlacement = EdgeLabelPlacement.auto, - this.numberFormat, - this.dateFormat, - this.dateIntervalType, - this.labelFormatterCallback, - this.tooltipTextFormatterCallback, - this.semanticFormatterCallback, - this.trackShape = const SfTrackShape(), - this.dividerShape = const SfDividerShape(), - this.overlayShape = const SfOverlayShape(), - this.thumbShape = const SfThumbShape(), - this.tickShape = const SfTickShape(), - this.minorTickShape = const SfMinorTickShape(), - this.tooltipShape = const SfRectangularTooltipShape(), - this.thumbIcon, - SliderTooltipPosition tooltipPosition = SliderTooltipPosition.left}) - : _sliderType = SliderType.vertical, - _tooltipPosition = tooltipPosition, - assert(tooltipShape is! SfPaddleTooltipShape), - assert(min != max), - assert(interval == null || interval > 0), - super(key: key); + const SfSlider.vertical({ + Key? key, + this.min = 0.0, + this.max = 1.0, + required this.value, + required this.onChanged, + this.onChangeStart, + this.onChangeEnd, + this.interval, + this.stepSize, + this.stepDuration, + this.minorTicksPerInterval = 0, + this.showTicks = false, + this.showLabels = false, + this.showDividers = false, + this.enableTooltip = false, + this.shouldAlwaysShowTooltip = false, + this.isInversed = false, + this.activeColor, + this.inactiveColor, + this.labelPlacement = LabelPlacement.onTicks, + this.edgeLabelPlacement = EdgeLabelPlacement.auto, + this.numberFormat, + this.dateFormat, + this.dateIntervalType, + // ignore: deprecated_consistency + this.labelFormatterCallback, + this.onLabelCreated, + this.tooltipTextFormatterCallback, + this.semanticFormatterCallback, + this.trackShape = const SfTrackShape(), + this.dividerShape = const SfDividerShape(), + this.overlayShape = const SfOverlayShape(), + this.thumbShape = const SfThumbShape(), + this.tickShape = const SfTickShape(), + this.minorTickShape = const SfMinorTickShape(), + this.tooltipShape = const SfRectangularTooltipShape(), + this.thumbIcon, + + SliderTooltipPosition tooltipPosition = SliderTooltipPosition.left, + }) : _sliderType = SliderType.vertical, + _tooltipPosition = tooltipPosition, + assert(tooltipShape is! SfPaddleTooltipShape), + assert(min != max), + assert(interval == null || interval > 0), + super(key: key); /// This is used to determine the type of the slider which is horizontal or /// vertical. @@ -911,7 +916,9 @@ class SfSlider extends StatefulWidget { /// /// See also: /// + // ignore: deprecated_member_use_from_same_package /// * [labelFormatterCallback], for formatting the numeric and date labels. + /// * [onLabelCreated], for formatting and styling numeric and date labels. final NumberFormat? numberFormat; /// Formats the date labels. It is mandatory for date [SfSlider]. @@ -949,7 +956,9 @@ class SfSlider extends StatefulWidget { /// /// * [interval], for setting the interval. /// * [numberFormat], for formatting the numeric labels. + // ignore: deprecated_member_use_from_same_package /// * [labelFormatterCallback], for formatting the numeric and date label. + /// * [onLabelCreated], for formatting and styling numeric and date label. /// * [dateIntervalType], for changing the interval type. final DateFormat? dateFormat; @@ -1014,8 +1023,57 @@ class SfSlider extends StatefulWidget { /// }, /// ) /// ``` + @Deprecated('Use `onLabelCreated` instead') final LabelFormatterCallback? labelFormatterCallback; + /// Signature for customizing the label text and style of numeric or date + /// values in the [SfSlider]. + /// + /// * The actual value without formatting is given by `actualValue`. + /// It is either [DateTime] or [double] based on given [value]. + /// * The formatted value based on the numeric or + /// date format is given by `formattedText`. + /// * Text styles can be applied to individual labels using the `textStyle` + /// property. + /// + /// This snippet shows how to format and style labels in [SfSlider]. + /// + /// ```dart + /// double _value = 4.0; + /// + /// SfSlider( + /// min: 0, + /// max: 8, + /// value: _value, + /// showLabels: true, + /// interval: 1, + /// onChanged: (dynamic value) { + /// setState(() { + /// _value = value; + /// }); + /// }, + /// onLabelCreated: ( + /// dynamic actualValue, + /// String formattedText, + /// TextStyle textStyle, + /// ) { + /// return SliderLabel( + /// text: actualValue == _value.toInt() + /// ? '$formattedText' + /// : '$actualValue', + /// textStyle: actualValue == _value.toInt() + /// ? const TextStyle( + /// color: Color.fromARGB(255, 243, 33, 229), + /// fontSize: 18, + /// fontWeight: FontWeight.bold, + /// ) + /// : textStyle, + /// ); + /// }, + /// ) + /// ``` + final SliderLabelCreatedCallback? onLabelCreated; + /// Signature for formatting or changing the whole tooltip label text. /// /// * The actual value without formatting is given by `actualValue`. @@ -1171,62 +1229,124 @@ class SfSlider extends StatefulWidget { properties.add(DiagnosticsProperty('value', value)); properties.add(DiagnosticsProperty('min', min)); properties.add(DiagnosticsProperty('max', max)); - properties.add(DiagnosticsProperty('isInversed', isInversed, - defaultValue: false)); - properties.add(ObjectFlagProperty>( - 'onChanged', onChanged, - ifNull: 'disabled')); - properties.add(ObjectFlagProperty>.has( - 'onChangeStart', onChangeStart)); - properties.add(ObjectFlagProperty>.has( - 'onChangeEnd', onChangeEnd)); + properties.add( + DiagnosticsProperty('isInversed', isInversed, defaultValue: false), + ); + properties.add( + ObjectFlagProperty>( + 'onChanged', + onChanged, + ifNull: 'disabled', + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'onChangeStart', + onChangeStart, + ), + ); + properties.add( + ObjectFlagProperty>.has('onChangeEnd', onChangeEnd), + ); properties.add(DoubleProperty('interval', interval)); properties.add(DoubleProperty('stepSize', stepSize)); if (stepDuration != null) { properties.add(stepDuration!.toDiagnosticsNode(name: 'stepDuration')); } properties.add(IntProperty('minorTicksPerInterval', minorTicksPerInterval)); - properties.add(FlagProperty('showTicks', + properties.add( + FlagProperty( + 'showTicks', value: showTicks, ifTrue: 'Ticks are showing', - ifFalse: 'Ticks are not showing')); - properties.add(FlagProperty('showLabels', + ifFalse: 'Ticks are not showing', + ), + ); + properties.add( + FlagProperty( + 'showLabels', value: showLabels, ifTrue: 'Labels are showing', - ifFalse: 'Labels are not showing')); - properties.add(FlagProperty('showDividers', + ifFalse: 'Labels are not showing', + ), + ); + properties.add( + FlagProperty( + 'showDividers', value: showDividers, ifTrue: 'Dividers are showing', - ifFalse: 'Dividers are not showing')); + ifFalse: 'Dividers are not showing', + ), + ); if (shouldAlwaysShowTooltip) { - properties.add(FlagProperty('shouldAlwaysShowTooltip', - value: shouldAlwaysShowTooltip, ifTrue: 'Tooltip is always visible')); + properties.add( + FlagProperty( + 'shouldAlwaysShowTooltip', + value: shouldAlwaysShowTooltip, + ifTrue: 'Tooltip is always visible', + ), + ); } else { - properties.add(FlagProperty('enableTooltip', + properties.add( + FlagProperty( + 'enableTooltip', value: enableTooltip, ifTrue: 'Tooltip is enabled', - ifFalse: 'Tooltip is disabled')); + ifFalse: 'Tooltip is disabled', + ), + ); } properties.add(ColorProperty('activeColor', activeColor)); properties.add(ColorProperty('inactiveColor', inactiveColor)); - properties - .add(EnumProperty('labelPlacement', labelPlacement)); - properties.add(EnumProperty( - 'edgeLabelPlacement', edgeLabelPlacement)); - properties - .add(DiagnosticsProperty('numberFormat', numberFormat)); + properties.add( + EnumProperty('labelPlacement', labelPlacement), + ); + properties.add( + EnumProperty( + 'edgeLabelPlacement', + edgeLabelPlacement, + ), + ); + properties.add( + DiagnosticsProperty('numberFormat', numberFormat), + ); if (value.runtimeType == DateTime && dateFormat != null) { - properties.add(StringProperty( - 'dateFormat', 'Formatted value is ${dateFormat!.format(value)}')); + properties.add( + StringProperty( + 'dateFormat', + 'Formatted value is ${dateFormat!.format(value)}', + ), + ); } properties.add( - EnumProperty('dateIntervalType', dateIntervalType)); - properties.add(ObjectFlagProperty.has( - 'tooltipTextFormatterCallback', tooltipTextFormatterCallback)); - properties.add(ObjectFlagProperty.has( - 'labelFormatterCallback', labelFormatterCallback)); - properties.add(ObjectFlagProperty>.has( - 'semanticFormatterCallback', semanticFormatterCallback)); + EnumProperty('dateIntervalType', dateIntervalType), + ); + properties.add( + ObjectFlagProperty.has( + 'tooltipTextFormatterCallback', + tooltipTextFormatterCallback, + ), + ); + properties.add( + // ignore: deprecated_member_use_from_same_package + ObjectFlagProperty.has( + 'labelFormatterCallback', + // ignore: deprecated_member_use_from_same_package + labelFormatterCallback, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'onLabelCreated', + onLabelCreated, + ), + ); + properties.add( + ObjectFlagProperty>.has( + 'semanticFormatterCallback', + semanticFormatterCallback, + ), + ); } } @@ -1234,8 +1354,38 @@ class _SfSliderState extends State with TickerProviderStateMixin { late AnimationController overlayController; late AnimationController stateController; late AnimationController tooltipAnimationController; + late Map> _keyboardActionMap; + late FocusNode _focusNode; + bool _focused = false; Timer? tooltipDelayTimer; final Duration duration = const Duration(milliseconds: 100); + final GlobalKey _renderObjectKey = GlobalKey(); + bool get _enabled => widget.onChanged != null; + FocusNode get sliderFocusNode => _focusNode; + + void _handleSliderFocusChanged(bool newFocused) { + if (newFocused != _focused) { + setState(() { + _focused = newFocused; + }); + } + } + + void _keyboardActionHandler(SliderKeyIntent intent) { + final TextDirection directionality = Directionality.of( + _renderObjectKey.currentContext!, + ); + final bool shouldIncrease = switch (intent.type) { + SliderKeyType.up => true, + SliderKeyType.down => false, + SliderKeyType.left => directionality == TextDirection.rtl, + SliderKeyType.right => directionality == TextDirection.ltr, + }; + + final _RenderSlider slider = + _renderObjectKey.currentContext!.findRenderObject()! as _RenderSlider; + return shouldIncrease ? slider.increaseAction() : slider.decreaseAction(); + } void _onChanged(dynamic value) { if (value != widget.value) { @@ -1259,6 +1409,14 @@ class _SfSliderState extends State with TickerProviderStateMixin { return formattedText; } + SliderLabel _handleLabelCreated( + dynamic actualValue, + String formattedText, + TextStyle textStyle, + ) { + return SliderLabel(text: formattedText, textStyle: textStyle); + } + String _getFormattedTooltipText(dynamic actualText, String formattedText) { return formattedText; } @@ -1269,15 +1427,20 @@ class _SfSliderState extends State with TickerProviderStateMixin { /// An instance for SlidersThemeData class final SfSliderThemeData effectiveThemeData = SlidersThemeData(context); final bool isMaterial3 = themeData.useMaterial3; - final Color labelColor = isMaterial3 - ? themeData.colorScheme.onSurfaceVariant - : isActive + final Color labelColor = + isMaterial3 + ? themeData.colorScheme.onSurfaceVariant + : isActive ? themeData.textTheme.bodyLarge!.color!.withValues(alpha: 0.87) : themeData.colorScheme.onSurface.withValues(alpha: 0.32); final double minTrackHeight = math.min( - sliderThemeData.activeTrackHeight, sliderThemeData.inactiveTrackHeight); + sliderThemeData.activeTrackHeight, + sliderThemeData.inactiveTrackHeight, + ); final double maxTrackHeight = math.max( - sliderThemeData.activeTrackHeight, sliderThemeData.inactiveTrackHeight); + sliderThemeData.activeTrackHeight, + sliderThemeData.inactiveTrackHeight, + ); sliderThemeData = sliderThemeData.copyWith( activeTrackHeight: sliderThemeData.activeTrackHeight, inactiveTrackHeight: sliderThemeData.inactiveTrackHeight, @@ -1290,59 +1453,77 @@ class _SfSliderState extends State with TickerProviderStateMixin { .merge(sliderThemeData.activeLabelStyle), tooltipTextStyle: themeData.textTheme.bodyLarge! .copyWith( - fontSize: isMaterial3 ? 12 : 14, - color: isMaterial3 - ? themeData.colorScheme.onPrimary - : themeData.colorScheme.surface) + fontSize: isMaterial3 ? 12 : 14, + color: + isMaterial3 + ? themeData.colorScheme.onPrimary + : themeData.colorScheme.surface, + ) .merge(sliderThemeData.tooltipTextStyle), - inactiveTrackColor: widget.inactiveColor ?? + inactiveTrackColor: + widget.inactiveColor ?? sliderThemeData.inactiveTrackColor ?? effectiveThemeData.inactiveTrackColor, - activeTrackColor: widget.activeColor ?? + activeTrackColor: + widget.activeColor ?? sliderThemeData.activeTrackColor ?? effectiveThemeData.activeTrackColor, - thumbColor: widget.activeColor ?? + thumbColor: + widget.activeColor ?? sliderThemeData.thumbColor ?? effectiveThemeData.thumbColor, activeTickColor: sliderThemeData.activeTickColor ?? effectiveThemeData.activeTickColor, - inactiveTickColor: sliderThemeData.inactiveTickColor ?? + inactiveTickColor: + sliderThemeData.inactiveTickColor ?? effectiveThemeData.inactiveTickColor, - disabledActiveTickColor: sliderThemeData.disabledActiveTickColor ?? + disabledActiveTickColor: + sliderThemeData.disabledActiveTickColor ?? effectiveThemeData.disabledActiveTickColor, - disabledInactiveTickColor: sliderThemeData.disabledInactiveTickColor ?? + disabledInactiveTickColor: + sliderThemeData.disabledInactiveTickColor ?? effectiveThemeData.disabledInactiveTickColor, - activeMinorTickColor: sliderThemeData.activeMinorTickColor ?? + activeMinorTickColor: + sliderThemeData.activeMinorTickColor ?? effectiveThemeData.activeMinorTickColor, - inactiveMinorTickColor: sliderThemeData.inactiveMinorTickColor ?? + inactiveMinorTickColor: + sliderThemeData.inactiveMinorTickColor ?? effectiveThemeData.inactiveMinorTickColor, disabledActiveMinorTickColor: sliderThemeData.disabledActiveMinorTickColor ?? - effectiveThemeData.disabledActiveMinorTickColor, + effectiveThemeData.disabledActiveMinorTickColor, disabledInactiveMinorTickColor: sliderThemeData.disabledInactiveMinorTickColor ?? - effectiveThemeData.disabledInactiveMinorTickColor, - overlayColor: widget.activeColor?.withValues(alpha: 0.12) ?? + effectiveThemeData.disabledInactiveMinorTickColor, + overlayColor: + widget.activeColor?.withValues(alpha: 0.12) ?? sliderThemeData.overlayColor ?? effectiveThemeData.overlayColor, - inactiveDividerColor: widget.activeColor ?? + inactiveDividerColor: + widget.activeColor ?? sliderThemeData.inactiveDividerColor ?? effectiveThemeData.inactiveDividerColor, - activeDividerColor: widget.inactiveColor ?? + activeDividerColor: + widget.inactiveColor ?? sliderThemeData.activeDividerColor ?? effectiveThemeData.activeDividerColor, disabledInactiveDividerColor: sliderThemeData.disabledInactiveDividerColor ?? - effectiveThemeData.disabledInactiveDividerColor, - disabledActiveDividerColor: sliderThemeData.disabledActiveDividerColor ?? + effectiveThemeData.disabledInactiveDividerColor, + disabledActiveDividerColor: + sliderThemeData.disabledActiveDividerColor ?? effectiveThemeData.disabledActiveDividerColor, - disabledActiveTrackColor: sliderThemeData.disabledActiveTrackColor ?? + disabledActiveTrackColor: + sliderThemeData.disabledActiveTrackColor ?? effectiveThemeData.disabledActiveTrackColor, - disabledInactiveTrackColor: sliderThemeData.disabledInactiveTrackColor ?? + disabledInactiveTrackColor: + sliderThemeData.disabledInactiveTrackColor ?? effectiveThemeData.disabledInactiveTrackColor, - disabledThumbColor: sliderThemeData.disabledThumbColor ?? + disabledThumbColor: + sliderThemeData.disabledThumbColor ?? effectiveThemeData.disabledThumbColor, - tooltipBackgroundColor: sliderThemeData.tooltipBackgroundColor ?? + tooltipBackgroundColor: + sliderThemeData.tooltipBackgroundColor ?? effectiveThemeData.tooltipBackgroundColor, thumbStrokeColor: sliderThemeData.thumbStrokeColor, activeDividerStrokeColor: sliderThemeData.activeDividerStrokeColor, @@ -1361,20 +1542,24 @@ class _SfSliderState extends State with TickerProviderStateMixin { ); if (widget._sliderType == SliderType.horizontal) { return sliderThemeData.copyWith( - tickSize: sliderThemeData.tickSize ?? const Size(1.0, 8.0), - minorTickSize: sliderThemeData.minorTickSize ?? const Size(1.0, 5.0), - labelOffset: sliderThemeData.labelOffset ?? - (widget.showTicks - ? const Offset(0.0, 5.0) - : const Offset(0.0, 13.0))); + tickSize: sliderThemeData.tickSize ?? const Size(1.0, 8.0), + minorTickSize: sliderThemeData.minorTickSize ?? const Size(1.0, 5.0), + labelOffset: + sliderThemeData.labelOffset ?? + (widget.showTicks + ? const Offset(0.0, 5.0) + : const Offset(0.0, 13.0)), + ); } else { return sliderThemeData.copyWith( - tickSize: sliderThemeData.tickSize ?? const Size(8.0, 1.0), - minorTickSize: sliderThemeData.minorTickSize ?? const Size(5.0, 1.0), - labelOffset: sliderThemeData.labelOffset ?? - (widget.showTicks - ? const Offset(5.0, 0.0) - : const Offset(13.0, 0.0))); + tickSize: sliderThemeData.tickSize ?? const Size(8.0, 1.0), + minorTickSize: sliderThemeData.minorTickSize ?? const Size(5.0, 1.0), + labelOffset: + sliderThemeData.labelOffset ?? + (widget.showTicks + ? const Offset(5.0, 0.0) + : const Offset(13.0, 0.0)), + ); } } @@ -1395,10 +1580,18 @@ class _SfSliderState extends State with TickerProviderStateMixin { super.initState(); overlayController = AnimationController(vsync: this, duration: duration); stateController = AnimationController(vsync: this, duration: duration); - tooltipAnimationController = - AnimationController(vsync: this, duration: duration); + tooltipAnimationController = AnimationController( + vsync: this, + duration: duration, + ); stateController.value = widget.onChanged != null && (widget.min != widget.max) ? 1.0 : 0.0; + _keyboardActionMap = >{ + SliderKeyIntent: CallbackAction( + onInvoke: _keyboardActionHandler, + ), + }; + _focusNode = FocusNode(); } @override @@ -1406,106 +1599,150 @@ class _SfSliderState extends State with TickerProviderStateMixin { overlayController.dispose(); stateController.dispose(); tooltipAnimationController.dispose(); + _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { + final ThemeData themeData = Theme.of(context); + + VoidCallback? handleSliderAccessibilityFocus; + switch (themeData.platform) { + case TargetPlatform.android: + case TargetPlatform.fuchsia: + case TargetPlatform.iOS: + case TargetPlatform.linux: + case TargetPlatform.macOS: + break; + case TargetPlatform.windows: + handleSliderAccessibilityFocus = () { + // Automatically activate the slider when it receives a11y focus. + if (!sliderFocusNode.hasFocus && sliderFocusNode.canRequestFocus) { + sliderFocusNode.requestFocus(); + } + }; + } + final Map keyboardShortcutMap = + switch (MediaQuery.navigationModeOf(context)) { + NavigationMode.directional => KeyboardDirectionalNavShortcutMap, + NavigationMode.traditional => KeyboardNavShortcutMap, + }; + final bool isActive = widget.onChanged != null && (widget.min != widget.max); - final ThemeData themeData = Theme.of(context); - return _SliderRenderObjectWidget( - key: widget.key, - min: widget.min, - max: widget.max, - value: widget.value, - onChanged: isActive ? _onChanged : null, - onChangeStart: widget.onChangeStart != null ? _onChangeStart : null, - onChangeEnd: widget.onChangeEnd != null ? _onChangeEnd : null, - interval: widget.interval, - stepSize: widget.stepSize, - stepDuration: widget.stepDuration, - minorTicksPerInterval: widget.minorTicksPerInterval, - showTicks: widget.showTicks, - showLabels: widget.showLabels, - showDividers: widget.showDividers, - enableTooltip: widget.enableTooltip, - shouldAlwaysShowTooltip: widget.shouldAlwaysShowTooltip, - isInversed: widget._sliderType == SliderType.horizontal && - Directionality.of(context) == TextDirection.rtl || - widget.isInversed, - inactiveColor: widget.inactiveColor ?? - themeData.primaryColor.withValues(alpha: 0.24), - activeColor: widget.activeColor ?? themeData.primaryColor, - labelPlacement: widget.labelPlacement, - edgeLabelPlacement: widget.edgeLabelPlacement, - numberFormat: widget.numberFormat ?? NumberFormat('#.##'), - dateIntervalType: widget.dateIntervalType, - dateFormat: widget.dateFormat, - labelFormatterCallback: - widget.labelFormatterCallback ?? _getFormattedLabelText, - tooltipTextFormatterCallback: - widget.tooltipTextFormatterCallback ?? _getFormattedTooltipText, - semanticFormatterCallback: widget.semanticFormatterCallback, - trackShape: widget.trackShape, - dividerShape: widget.dividerShape, - overlayShape: widget.overlayShape, - thumbShape: widget.thumbShape, - tickShape: widget.tickShape, - minorTickShape: widget.minorTickShape, - tooltipShape: widget.tooltipShape, - sliderThemeData: _getSliderThemeData(themeData, isActive), - thumbIcon: widget.thumbIcon, - tooltipPosition: widget._tooltipPosition, - sliderType: widget._sliderType, - state: this); + final Widget result = _SliderRenderObjectWidget( + key: _renderObjectKey, + min: widget.min, + max: widget.max, + value: widget.value, + onChanged: isActive ? _onChanged : null, + onChangeStart: widget.onChangeStart != null ? _onChangeStart : null, + onChangeEnd: widget.onChangeEnd != null ? _onChangeEnd : null, + interval: widget.interval, + stepSize: widget.stepSize, + stepDuration: widget.stepDuration, + minorTicksPerInterval: widget.minorTicksPerInterval, + showTicks: widget.showTicks, + showLabels: widget.showLabels, + showDividers: widget.showDividers, + enableTooltip: widget.enableTooltip, + shouldAlwaysShowTooltip: widget.shouldAlwaysShowTooltip, + isInversed: + widget._sliderType == SliderType.horizontal && + Directionality.of(context) == TextDirection.rtl || + widget.isInversed, + inactiveColor: + widget.inactiveColor ?? + themeData.primaryColor.withValues(alpha: 0.24), + activeColor: widget.activeColor ?? themeData.primaryColor, + labelPlacement: widget.labelPlacement, + edgeLabelPlacement: widget.edgeLabelPlacement, + numberFormat: widget.numberFormat ?? NumberFormat('#.##'), + dateIntervalType: widget.dateIntervalType, + dateFormat: widget.dateFormat, + labelFormatterCallback: + // ignore: deprecated_member_use_from_same_package + widget.labelFormatterCallback ?? _getFormattedLabelText, + onLabelCreated: widget.onLabelCreated ?? _handleLabelCreated, + tooltipTextFormatterCallback: + widget.tooltipTextFormatterCallback ?? _getFormattedTooltipText, + semanticFormatterCallback: widget.semanticFormatterCallback, + trackShape: widget.trackShape, + dividerShape: widget.dividerShape, + overlayShape: widget.overlayShape, + thumbShape: widget.thumbShape, + tickShape: widget.tickShape, + minorTickShape: widget.minorTickShape, + tooltipShape: widget.tooltipShape, + sliderThemeData: _getSliderThemeData(themeData, isActive), + thumbIcon: widget.thumbIcon, + tooltipPosition: widget._tooltipPosition, + sliderType: widget._sliderType, + hasFocus: _focused, + state: this, + ); + + return Semantics( + onDidGainAccessibilityFocus: handleSliderAccessibilityFocus, + child: FocusableActionDetector( + actions: _keyboardActionMap, + shortcuts: keyboardShortcutMap, + focusNode: sliderFocusNode, + enabled: _enabled, + onShowFocusHighlight: _handleSliderFocusChanged, + child: result, + ), + ); } } class _SliderRenderObjectWidget extends RenderObjectWidget { - const _SliderRenderObjectWidget( - {Key? key, - required this.min, - required this.max, - required this.value, - required this.onChanged, - required this.onChangeStart, - required this.onChangeEnd, - required this.interval, - required this.stepSize, - required this.stepDuration, - required this.minorTicksPerInterval, - required this.showTicks, - required this.showLabels, - required this.showDividers, - required this.enableTooltip, - required this.shouldAlwaysShowTooltip, - required this.isInversed, - required this.inactiveColor, - required this.activeColor, - required this.labelPlacement, - required this.edgeLabelPlacement, - required this.numberFormat, - required this.dateFormat, - required this.dateIntervalType, - required this.labelFormatterCallback, - required this.tooltipTextFormatterCallback, - required this.semanticFormatterCallback, - required this.trackShape, - required this.dividerShape, - required this.overlayShape, - required this.thumbShape, - required this.tickShape, - required this.minorTickShape, - required this.tooltipShape, - required this.sliderThemeData, - required this.thumbIcon, - required this.state, - required this.sliderType, - required this.tooltipPosition}) - : super(key: key); + const _SliderRenderObjectWidget({ + Key? key, + required this.min, + required this.max, + required this.value, + required this.onChanged, + required this.onChangeStart, + required this.onChangeEnd, + required this.interval, + required this.stepSize, + required this.stepDuration, + required this.minorTicksPerInterval, + required this.showTicks, + required this.showLabels, + required this.showDividers, + required this.enableTooltip, + required this.shouldAlwaysShowTooltip, + required this.isInversed, + required this.inactiveColor, + required this.activeColor, + required this.labelPlacement, + required this.edgeLabelPlacement, + required this.numberFormat, + required this.dateFormat, + required this.dateIntervalType, + required this.labelFormatterCallback, + required this.onLabelCreated, + required this.tooltipTextFormatterCallback, + required this.semanticFormatterCallback, + required this.trackShape, + required this.dividerShape, + required this.overlayShape, + required this.thumbShape, + required this.tickShape, + required this.minorTickShape, + required this.tooltipShape, + required this.sliderThemeData, + required this.thumbIcon, + required this.state, + required this.sliderType, + required this.tooltipPosition, + required this.hasFocus, + }) : super(key: key); final SliderType sliderType; final SliderTooltipPosition? tooltipPosition; @@ -1536,7 +1773,9 @@ class _SliderRenderObjectWidget extends RenderObjectWidget { final DateIntervalType? dateIntervalType; final DateFormat? dateFormat; final SfSliderThemeData sliderThemeData; + // ignore: deprecated_member_use_from_same_package final LabelFormatterCallback labelFormatterCallback; + final SliderLabelCreatedCallback onLabelCreated; final TooltipTextFormatterCallback tooltipTextFormatterCallback; final SfSliderSemanticFormatterCallback? semanticFormatterCallback; final SfDividerShape dividerShape; @@ -1548,6 +1787,7 @@ class _SliderRenderObjectWidget extends RenderObjectWidget { final SfTooltipShape tooltipShape; final Widget? thumbIcon; final _SfSliderState state; + final bool hasFocus; @override _RenderSliderElement createElement() => _RenderSliderElement(this); @@ -1555,44 +1795,47 @@ class _SliderRenderObjectWidget extends RenderObjectWidget { @override RenderObject createRenderObject(BuildContext context) { return _RenderSlider( - min: min, - max: max, - value: value, - onChanged: onChanged, - onChangeStart: onChangeStart, - onChangeEnd: onChangeEnd, - minorTicksPerInterval: minorTicksPerInterval, - interval: interval, - stepSize: stepSize, - stepDuration: stepDuration, - showTicks: showTicks, - showLabels: showLabels, - showDividers: showDividers, - enableTooltip: enableTooltip, - shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, - isInversed: isInversed, - labelPlacement: labelPlacement, - edgeLabelPlacement: edgeLabelPlacement, - numberFormat: numberFormat, - dateFormat: dateFormat, - dateIntervalType: dateIntervalType, - labelFormatterCallback: labelFormatterCallback, - tooltipTextFormatterCallback: tooltipTextFormatterCallback, - semanticFormatterCallback: semanticFormatterCallback, - trackShape: trackShape, - dividerShape: dividerShape, - overlayShape: overlayShape, - thumbShape: thumbShape, - tickShape: tickShape, - minorTickShape: minorTickShape, - tooltipShape: tooltipShape, - sliderThemeData: sliderThemeData, - sliderType: sliderType, - tooltipPosition: tooltipPosition, - textDirection: Directionality.of(context), - mediaQueryData: MediaQuery.of(context), - state: state, - gestureSettings: MediaQuery.of(context).gestureSettings); + min: min, + max: max, + value: value, + onChanged: onChanged, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + minorTicksPerInterval: minorTicksPerInterval, + interval: interval, + stepSize: stepSize, + stepDuration: stepDuration, + showTicks: showTicks, + showLabels: showLabels, + showDividers: showDividers, + enableTooltip: enableTooltip, + shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, + isInversed: isInversed, + labelPlacement: labelPlacement, + edgeLabelPlacement: edgeLabelPlacement, + numberFormat: numberFormat, + dateFormat: dateFormat, + dateIntervalType: dateIntervalType, + labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, + tooltipTextFormatterCallback: tooltipTextFormatterCallback, + semanticFormatterCallback: semanticFormatterCallback, + trackShape: trackShape, + dividerShape: dividerShape, + overlayShape: overlayShape, + thumbShape: thumbShape, + tickShape: tickShape, + minorTickShape: minorTickShape, + tooltipShape: tooltipShape, + sliderThemeData: sliderThemeData, + sliderType: sliderType, + tooltipPosition: tooltipPosition, + textDirection: Directionality.of(context), + mediaQueryData: MediaQuery.of(context), + state: state, + gestureSettings: MediaQuery.of(context).gestureSettings, + hasFocus: hasFocus, + ); } @override @@ -1620,6 +1863,7 @@ class _SliderRenderObjectWidget extends RenderObjectWidget { ..dateFormat = dateFormat ..dateIntervalType = dateIntervalType ..labelFormatterCallback = labelFormatterCallback + ..onLabelCreated = onLabelCreated ..tooltipTextFormatterCallback = tooltipTextFormatterCallback ..semanticFormatterCallback = semanticFormatterCallback ..trackShape = trackShape @@ -1632,7 +1876,8 @@ class _SliderRenderObjectWidget extends RenderObjectWidget { ..sliderThemeData = sliderThemeData ..tooltipPosition = tooltipPosition ..textDirection = Directionality.of(context) - ..mediaQueryData = MediaQuery.of(context); + ..mediaQueryData = MediaQuery.of(context) + ..hasFocus = hasFocus; } } @@ -1716,7 +1961,10 @@ class _RenderSliderElement extends RenderObjectElement { @override void moveRenderObjectChild( - RenderObject child, dynamic oldSlot, dynamic newSlot) { + RenderObject child, + dynamic oldSlot, + dynamic newSlot, + ) { assert(false, 'not reachable'); } } @@ -1744,7 +1992,9 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { required NumberFormat numberFormat, required DateFormat? dateFormat, required DateIntervalType? dateIntervalType, + // ignore: deprecated_member_use_from_same_package required LabelFormatterCallback labelFormatterCallback, + required SliderLabelCreatedCallback onLabelCreated, required TooltipTextFormatterCallback tooltipTextFormatterCallback, required SfSliderSemanticFormatterCallback? semanticFormatterCallback, required SfTrackShape trackShape, @@ -1761,77 +2011,89 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { required MediaQueryData mediaQueryData, required _SfSliderState state, required DeviceGestureSettings gestureSettings, - }) : _state = state, - _value = value, - _semanticFormatterCallback = semanticFormatterCallback, - _onChanged = onChanged, - super( - min: min, - max: max, - sliderType: sliderType, - interval: interval, - stepSize: stepSize, - stepDuration: stepDuration, - minorTicksPerInterval: minorTicksPerInterval, - showTicks: showTicks, - showLabels: showLabels, - showDividers: showDividers, - enableTooltip: enableTooltip, - shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, - isInversed: isInversed, - labelPlacement: labelPlacement, - edgeLabelPlacement: edgeLabelPlacement, - numberFormat: numberFormat, - dateFormat: dateFormat, - dateIntervalType: dateIntervalType, - labelFormatterCallback: labelFormatterCallback, - tooltipTextFormatterCallback: tooltipTextFormatterCallback, - trackShape: trackShape, - dividerShape: dividerShape, - overlayShape: overlayShape, - thumbShape: thumbShape, - tickShape: tickShape, - minorTickShape: minorTickShape, - tooltipShape: tooltipShape, - tooltipPosition: tooltipPosition, - sliderThemeData: sliderThemeData, - textDirection: textDirection, - mediaQueryData: mediaQueryData, - ) { + required bool hasFocus, + }) : _state = state, + _value = value, + _semanticFormatterCallback = semanticFormatterCallback, + _onChanged = onChanged, + _hasFocus = hasFocus, + super( + min: min, + max: max, + sliderType: sliderType, + interval: interval, + stepSize: stepSize, + stepDuration: stepDuration, + minorTicksPerInterval: minorTicksPerInterval, + showTicks: showTicks, + showLabels: showLabels, + showDividers: showDividers, + enableTooltip: enableTooltip, + shouldAlwaysShowTooltip: shouldAlwaysShowTooltip, + isInversed: isInversed, + labelPlacement: labelPlacement, + edgeLabelPlacement: edgeLabelPlacement, + numberFormat: numberFormat, + dateFormat: dateFormat, + dateIntervalType: dateIntervalType, + labelFormatterCallback: labelFormatterCallback, + onLabelCreated: onLabelCreated, + tooltipTextFormatterCallback: tooltipTextFormatterCallback, + trackShape: trackShape, + dividerShape: dividerShape, + overlayShape: overlayShape, + thumbShape: thumbShape, + tickShape: tickShape, + minorTickShape: minorTickShape, + tooltipShape: tooltipShape, + tooltipPosition: tooltipPosition, + sliderThemeData: sliderThemeData, + textDirection: textDirection, + mediaQueryData: mediaQueryData, + ) { final GestureArenaTeam team = GestureArenaTeam(); if (sliderType == SliderType.horizontal) { - horizontalDragGestureRecognizer = HorizontalDragGestureRecognizer() - ..team = team - ..onStart = _onDragStart - ..onUpdate = _onDragUpdate - ..onEnd = _onDragEnd - ..onCancel = _onDragCancel - ..gestureSettings = gestureSettings; + horizontalDragGestureRecognizer = + HorizontalDragGestureRecognizer() + ..team = team + ..onStart = _onDragStart + ..onUpdate = _onDragUpdate + ..onEnd = _onDragEnd + ..onCancel = _onDragCancel + ..gestureSettings = gestureSettings; } if (sliderType == SliderType.vertical) { - verticalDragGestureRecognizer = VerticalDragGestureRecognizer() - ..team = team - ..onStart = _onVerticalDragStart - ..onUpdate = _onVerticalDragUpdate - ..onEnd = _onVerticalDragEnd - ..onCancel = _onVerticalDragCancel - ..gestureSettings = gestureSettings; + verticalDragGestureRecognizer = + VerticalDragGestureRecognizer() + ..team = team + ..onStart = _onVerticalDragStart + ..onUpdate = _onVerticalDragUpdate + ..onEnd = _onVerticalDragEnd + ..onCancel = _onVerticalDragCancel + ..gestureSettings = gestureSettings; } - tapGestureRecognizer = TapGestureRecognizer() - ..team = team - ..onTapDown = _onTapDown - ..onTapUp = _onTapUp; + tapGestureRecognizer = + TapGestureRecognizer() + ..team = team + ..onTapDown = _onTapDown + ..onTapUp = _onTapUp; _overlayAnimation = CurvedAnimation( - parent: _state.overlayController, curve: Curves.fastOutSlowIn); + parent: _state.overlayController, + curve: Curves.fastOutSlowIn, + ); _stateAnimation = CurvedAnimation( - parent: _state.stateController, curve: Curves.easeInOut); + parent: _state.stateController, + curve: Curves.easeInOut, + ); _tooltipAnimation = CurvedAnimation( - parent: _state.tooltipAnimationController, curve: Curves.fastOutSlowIn); + parent: _state.tooltipAnimationController, + curve: Curves.fastOutSlowIn, + ); if (shouldAlwaysShowTooltip) { _state.tooltipAnimationController.value = 1; @@ -1870,6 +2132,9 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { final Map childToSlot = {}; + @override + bool get hasLabelCreated => _state.widget.onLabelCreated != null; + dynamic get value => _value; dynamic _value; @@ -1942,17 +2207,54 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { } dynamic get _increasedValue { - return getNextSemanticValue(value, semanticActionUnit, - actualValue: actualValue); + return getNextSemanticValue( + value, + semanticActionUnit, + actualValue: actualValue, + ); } dynamic get _decreasedValue { - return getPrevSemanticValue(value, semanticActionUnit, - actualValue: actualValue); + return getPrevSemanticValue( + value, + semanticActionUnit, + actualValue: actualValue, + ); + } + + bool get hasFocus => _hasFocus; + bool _hasFocus; + set hasFocus(bool value) { + if (value == _hasFocus) { + return; + } + _hasFocus = value; + + _updateForFocus(_hasFocus); + markNeedsSemanticsUpdate(); + } + + void _updateForFocus(bool focused) { + if (focused) { + _state.overlayController.forward(); + + if (enableTooltip) { + willDrawTooltip = true; + _state.tooltipAnimationController.forward(); + } + } else { + _state.overlayController.reverse(); + if (enableTooltip && !shouldAlwaysShowTooltip) { + _state.tooltipAnimationController.reverse(); + } + } } RenderBox? _updateChild( - RenderBox? oldChild, RenderBox? newChild, ChildElements slot) { + RenderBox? oldChild, + RenderBox? newChild, + ChildElements slot, + ) { if (oldChild != null) { dropChild(oldChild); childToSlot.remove(oldChild); @@ -1968,9 +2270,10 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { void _onTapDown(TapDownDetails details) { currentPointerType = PointerType.down; - mainAxisOffset = sliderType == SliderType.horizontal - ? globalToLocal(details.globalPosition).dx - : globalToLocal(details.globalPosition).dy; + mainAxisOffset = + sliderType == SliderType.horizontal + ? globalToLocal(details.globalPosition).dx + : globalToLocal(details.globalPosition).dy; _beginInteraction(); } @@ -2080,32 +2383,56 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { } } - void _drawTooltip(PaintingContext context, Offset thumbCenter, Offset offset, - Offset actualTrackOffset, Rect trackRect) { + void _drawTooltip( + PaintingContext context, + Offset thumbCenter, + Offset offset, + Offset actualTrackOffset, + Rect trackRect, + ) { if (willDrawTooltip || shouldAlwaysShowTooltip) { - final Paint paint = Paint() - ..color = sliderThemeData.tooltipBackgroundColor! - ..style = PaintingStyle.fill - ..strokeWidth = 0; - - final dynamic actualText = sliderType == SliderType.horizontal - ? getValueFromPosition(thumbCenter.dx - offset.dx) - : getValueFromPosition(trackRect.bottom - thumbCenter.dy); + final Paint paint = + Paint() + ..color = sliderThemeData.tooltipBackgroundColor! + ..style = PaintingStyle.fill + ..strokeWidth = 0; + + final dynamic actualText = + sliderType == SliderType.horizontal + ? getValueFromPosition(thumbCenter.dx - offset.dx) + : getValueFromPosition(trackRect.bottom - thumbCenter.dy); final String tooltipText = tooltipTextFormatterCallback( - actualText, getFormattedText(actualText)); - final TextSpan textSpan = - TextSpan(text: tooltipText, style: sliderThemeData.tooltipTextStyle); + actualText, + getFormattedText(actualText), + ); + final TextSpan textSpan = TextSpan( + text: tooltipText, + style: sliderThemeData.tooltipTextStyle, + ); textPainter.text = textSpan; textPainter.layout(); - tooltipShape.paint(context, thumbCenter, - Offset(actualTrackOffset.dx, tooltipStartY), textPainter, - parentBox: this, - sliderThemeData: sliderThemeData, - paint: paint, - animation: _tooltipAnimation, - trackRect: trackRect); + tooltipShape.paint( + context, + thumbCenter, + Offset(actualTrackOffset.dx, tooltipStartY), + textPainter, + parentBox: this, + sliderThemeData: sliderThemeData, + paint: paint, + animation: _tooltipAnimation, + trackRect: trackRect, + ); + } + } + + @override + bool isActiveLabelValue(currentValue) { + if (currentValue is DateTime && value is DateTime) { + return currentValue.millisecondsSinceEpoch <= + value.millisecondsSinceEpoch; } + return currentValue <= value; } void increaseAction() { @@ -2194,7 +2521,9 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { void performLayout() { super.performLayout(); final BoxConstraints contentConstraints = BoxConstraints.tightFor( - width: actualThumbSize.width, height: actualThumbSize.height); + width: actualThumbSize.width, + height: actualThumbSize.height, + ); _thumbIcon?.layout(contentConstraints, parentUsesSize: true); } @@ -2222,75 +2551,114 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { @override void paint(PaintingContext context, Offset offset) { - final Offset actualTrackOffset = sliderType == SliderType.horizontal - ? Offset( - offset.dx, - offset.dy + - (size.height - actualHeight) / 2 + - trackOffset.dy - - maxTrackHeight / 2) - : Offset( - offset.dx + - (size.width - actualHeight) / 2 + - trackOffset.dx - - maxTrackHeight / 2, - offset.dy); + final Offset actualTrackOffset = + sliderType == SliderType.horizontal + ? Offset( + offset.dx, + offset.dy + + (size.height - actualHeight) / 2 + + trackOffset.dy - + maxTrackHeight / 2, + ) + : Offset( + offset.dx + + (size.width - actualHeight) / 2 + + trackOffset.dx - + maxTrackHeight / 2, + offset.dy, + ); // Drawing track. - final Rect trackRect = - trackShape.getPreferredRect(this, sliderThemeData, actualTrackOffset); - final double thumbPosition = getFactorFromValue(actualValue) * + final Rect trackRect = trackShape.getPreferredRect( + this, + sliderThemeData, + actualTrackOffset, + ); + final double thumbPosition = + getFactorFromValue(actualValue) * (sliderType == SliderType.horizontal ? trackRect.width : trackRect.height); - final Offset thumbCenter = sliderType == SliderType.horizontal - ? Offset(trackRect.left + thumbPosition, trackRect.center.dy) - : Offset(trackRect.center.dx, trackRect.bottom - thumbPosition); - - trackShape.paint(context, actualTrackOffset, thumbCenter, null, null, - parentBox: this, - currentValue: _value, - themeData: sliderThemeData, - enableAnimation: _stateAnimation, - textDirection: textDirection, - activePaint: null, - inactivePaint: null); + final Offset thumbCenter = + sliderType == SliderType.horizontal + ? Offset(trackRect.left + thumbPosition, trackRect.center.dy) + : Offset(trackRect.center.dx, trackRect.bottom - thumbPosition); + + trackShape.paint( + context, + actualTrackOffset, + thumbCenter, + null, + null, + parentBox: this, + currentValue: _value, + themeData: sliderThemeData, + enableAnimation: _stateAnimation, + textDirection: textDirection, + activePaint: null, + inactivePaint: null, + ); if (showLabels || showTicks || showDividers) { - drawLabelsTicksAndDividers(context, trackRect, offset, thumbCenter, null, - null, _stateAnimation, _value, null); + drawLabelsTicksAndDividers( + context, + trackRect, + offset, + thumbCenter, + null, + null, + _stateAnimation, + _value, + null, + ); } // Drawing overlay. - overlayShape.paint(context, thumbCenter, - parentBox: this, - currentValue: _value, - themeData: sliderThemeData, - animation: _overlayAnimation, - thumb: null, - paint: null); + overlayShape.paint( + context, + thumbCenter, + parentBox: this, + currentValue: _value, + themeData: sliderThemeData, + animation: _overlayAnimation, + thumb: null, + paint: null, + ); if (_thumbIcon != null) { - (_thumbIcon!.parentData! as BoxParentData).offset = thumbCenter - + (_thumbIcon!.parentData! as BoxParentData).offset = + thumbCenter - Offset(_thumbIcon!.size.width / 2, _thumbIcon!.size.height / 2) - offset; } // Drawing thumb. - thumbShape.paint(context, thumbCenter, - parentBox: this, - child: _thumbIcon, - currentValue: _value, - themeData: sliderThemeData, - enableAnimation: _stateAnimation, - textDirection: textDirection, - thumb: null, - paint: null); + thumbShape.paint( + context, + thumbCenter, + parentBox: this, + child: _thumbIcon, + currentValue: _value, + themeData: sliderThemeData, + enableAnimation: _stateAnimation, + textDirection: textDirection, + thumb: null, + paint: null, + ); // To avoid positioning the tooltip text on the edge, used a 5px margin. final Rect tooltipTargetRect = Rect.fromLTWH( - 5.0, trackRect.top, mediaQueryData.size.width - 5.0, trackRect.height); + 5.0, + trackRect.top, + mediaQueryData.size.width - 5.0, + trackRect.height, + ); _drawTooltip( - context, thumbCenter, offset, actualTrackOffset, tooltipTargetRect); + context, + thumbCenter, + offset, + actualTrackOffset, + tooltipTargetRect, + ); } @override @@ -2316,23 +2684,45 @@ class _RenderSlider extends RenderBaseSlider implements MouseTrackerAnnotation { @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties.add(StringProperty( - 'thumbSize', thumbShape.getPreferredSize(sliderThemeData).toString())); - properties.add(StringProperty( + properties.add( + StringProperty( + 'thumbSize', + thumbShape.getPreferredSize(sliderThemeData).toString(), + ), + ); + properties.add( + StringProperty( 'activeDividerSize', dividerShape .getPreferredSize(sliderThemeData, isActive: true) - .toString())); - properties.add(StringProperty( + .toString(), + ), + ); + properties.add( + StringProperty( 'inactiveDividerSize', dividerShape .getPreferredSize(sliderThemeData, isActive: false) - .toString())); - properties.add(StringProperty('overlaySize', - overlayShape.getPreferredSize(sliderThemeData).toString())); - properties.add(StringProperty( - 'tickSize', tickShape.getPreferredSize(sliderThemeData).toString())); - properties.add(StringProperty('minorTickSize', - minorTickShape.getPreferredSize(sliderThemeData).toString())); + .toString(), + ), + ); + properties.add( + StringProperty( + 'overlaySize', + overlayShape.getPreferredSize(sliderThemeData).toString(), + ), + ); + properties.add( + StringProperty( + 'tickSize', + tickShape.getPreferredSize(sliderThemeData).toString(), + ), + ); + properties.add( + StringProperty( + 'minorTickSize', + minorTickShape.getPreferredSize(sliderThemeData).toString(), + ), + ); } } diff --git a/packages/syncfusion_flutter_sliders/lib/src/slider_base.dart b/packages/syncfusion_flutter_sliders/lib/src/slider_base.dart index a60c33ba2..24c0b0bc6 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/slider_base.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/slider_base.dart @@ -35,7 +35,9 @@ class RenderBaseSlider extends RenderProxyBox required NumberFormat numberFormat, required DateFormat? dateFormat, required DateIntervalType? dateIntervalType, + // ignore: deprecated_member_use_from_same_package required LabelFormatterCallback labelFormatterCallback, + required SliderLabelCreatedCallback onLabelCreated, required TooltipTextFormatterCallback tooltipTextFormatterCallback, required SfTrackShape trackShape, required SfDividerShape dividerShape, @@ -49,36 +51,37 @@ class RenderBaseSlider extends RenderProxyBox SliderTooltipPosition? tooltipPosition, required TextDirection textDirection, required MediaQueryData mediaQueryData, - }) : _min = min, - _max = max, - _interval = interval, - _stepSize = stepSize, - _stepDuration = stepDuration, - _minorTicksPerInterval = minorTicksPerInterval, - _showTicks = showTicks, - _showLabels = showLabels, - _showDividers = showDividers, - _enableTooltip = enableTooltip, - _shouldAlwaysShowTooltip = shouldAlwaysShowTooltip, - _isInversed = isInversed, - _labelPlacement = labelPlacement, - _edgeLabelPlacement = edgeLabelPlacement, - _numberFormat = numberFormat, - _dateFormat = dateFormat, - _dateIntervalType = dateIntervalType, - _labelFormatterCallback = labelFormatterCallback, - _tooltipTextFormatterCallback = tooltipTextFormatterCallback, - _trackShape = trackShape, - _dividerShape = dividerShape, - _overlayShape = overlayShape, - _thumbShape = thumbShape, - _tickShape = tickShape, - _minorTickShape = minorTickShape, - _tooltipShape = tooltipShape, - _sliderThemeData = sliderThemeData, - _textDirection = textDirection, - _mediaQueryData = mediaQueryData, - _tooltipPosition = tooltipPosition { + }) : _min = min, + _max = max, + _interval = interval, + _stepSize = stepSize, + _stepDuration = stepDuration, + _minorTicksPerInterval = minorTicksPerInterval, + _showTicks = showTicks, + _showLabels = showLabels, + _showDividers = showDividers, + _enableTooltip = enableTooltip, + _shouldAlwaysShowTooltip = shouldAlwaysShowTooltip, + _isInversed = isInversed, + _labelPlacement = labelPlacement, + _edgeLabelPlacement = edgeLabelPlacement, + _numberFormat = numberFormat, + _dateFormat = dateFormat, + _dateIntervalType = dateIntervalType, + _labelFormatterCallback = labelFormatterCallback, + _onLabelCreated = onLabelCreated, + _tooltipTextFormatterCallback = tooltipTextFormatterCallback, + _trackShape = trackShape, + _dividerShape = dividerShape, + _overlayShape = overlayShape, + _thumbShape = thumbShape, + _tickShape = tickShape, + _minorTickShape = minorTickShape, + _tooltipShape = tooltipShape, + _sliderThemeData = sliderThemeData, + _textDirection = textDirection, + _mediaQueryData = mediaQueryData, + _tooltipPosition = tooltipPosition { maxTrackHeight = getMaxTrackHeight(); trackOffset = _getTrackOffset(); @@ -89,12 +92,14 @@ class RenderBaseSlider extends RenderProxyBox _maxInMilliseconds = (max as DateTime).millisecondsSinceEpoch.toDouble(); } - _visibleLabels = []; + _visibleLabels = []; _majorTickPositions = []; _minorTickPositions = []; - thumbElevationTween = - Tween(begin: defaultElevation, end: tappedElevation); + thumbElevationTween = Tween( + begin: defaultElevation, + end: tappedElevation, + ); } final double minTrackWidth = kMinInteractiveDimension * 3; @@ -117,7 +122,7 @@ class RenderBaseSlider extends RenderProxyBox //ignore: prefer_final_fields bool isInteractionEnd = true; - late List _visibleLabels; + late List _visibleLabels; late List _majorTickPositions; @@ -152,6 +157,8 @@ class RenderBaseSlider extends RenderProxyBox PointerType? currentPointerType; + bool hasLabelCreated = false; + dynamic get min => _min; dynamic _min; set min(dynamic value) { @@ -344,8 +351,11 @@ class RenderBaseSlider extends RenderProxyBox markNeedsPaint(); } + // ignore: deprecated_member_use_from_same_package LabelFormatterCallback get labelFormatterCallback => _labelFormatterCallback; + // ignore: deprecated_member_use_from_same_package LabelFormatterCallback _labelFormatterCallback; + // ignore: deprecated_member_use_from_same_package set labelFormatterCallback(LabelFormatterCallback value) { if (_labelFormatterCallback == value) { return; @@ -354,6 +364,16 @@ class RenderBaseSlider extends RenderProxyBox markNeedsSemanticsUpdate(); } + dynamic get onLabelCreated => _onLabelCreated; + dynamic _onLabelCreated; + set onLabelCreated(dynamic value) { + if (_onLabelCreated == value) { + return; + } + _onLabelCreated = value; + markNeedsSemanticsUpdate(); + } + TooltipTextFormatterCallback get tooltipTextFormatterCallback => _tooltipTextFormatterCallback; TooltipTextFormatterCallback _tooltipTextFormatterCallback; @@ -500,8 +520,9 @@ class RenderBaseSlider extends RenderProxyBox _minorTickShape.getPreferredSize(_sliderThemeData); double get maximumFontSize => math.max( - _sliderThemeData.inactiveLabelStyle!.fontSize!, - _sliderThemeData.activeLabelStyle!.fontSize!); + _sliderThemeData.inactiveLabelStyle!.fontSize!, + _sliderThemeData.activeLabelStyle!.fontSize!, + ); // actualLabelSize is applicable only for horizontal sliders Size get actualLabelSize => Size.fromHeight(maximumFontSize); @@ -514,20 +535,22 @@ class RenderBaseSlider extends RenderProxyBox Size get actualOverlaySize => _overlayShape.getPreferredSize(_sliderThemeData); - double get actualTickHeight => _showTicks - ? _sliderThemeData.tickSize!.height + - (_sliderThemeData.tickOffset != null - ? _sliderThemeData.tickOffset!.dy - : 0) - : 0; + double get actualTickHeight => + _showTicks + ? _sliderThemeData.tickSize!.height + + (_sliderThemeData.tickOffset != null + ? _sliderThemeData.tickOffset!.dy + : 0) + : 0; // actualTickWidth is applicable only for vertical sliders - double get actualTickWidth => _showTicks - ? _sliderThemeData.tickSize!.width + - (_sliderThemeData.tickOffset != null - ? _sliderThemeData.tickOffset!.dx - : 0) - : 0; + double get actualTickWidth => + _showTicks + ? _sliderThemeData.tickSize!.width + + (_sliderThemeData.tickOffset != null + ? _sliderThemeData.tickOffset!.dx + : 0) + : 0; double get actualMinorTickHeight => _minorTicksPerInterval > 0 ? actualMinorTickSize.height : 0; @@ -536,32 +559,37 @@ class RenderBaseSlider extends RenderProxyBox double get actualMinorTickWidth => _minorTicksPerInterval > 0 ? actualMinorTickSize.width : 0; - double get actualLabelHeight => _showLabels - ? textPainter.textScaler.scale(actualLabelSize.height) + - (_sliderThemeData.labelOffset != null - ? _sliderThemeData.labelOffset!.dy - : 0) - : 0; + double get actualLabelHeight => + _showLabels + ? textPainter.textScaler.scale(actualLabelSize.height) + + (_sliderThemeData.labelOffset != null + ? _sliderThemeData.labelOffset!.dy + : 0) + : 0; // actualLabelOffset is applicable only for vertical sliders - double get actualLabelOffset => _showLabels - ? _sliderThemeData.labelOffset != null - ? (_sliderThemeData.labelOffset!.dx) - : 0 - : 0; + double get actualLabelOffset => + _showLabels + ? _sliderThemeData.labelOffset != null + ? (_sliderThemeData.labelOffset!.dx) + : 0 + : 0; // Here 10 is a gap between tooltip nose and thumb. - double get tooltipStartY => (sliderType == SliderType.horizontal) - ? _tooltipShape is SfPaddleTooltipShape - ? math.max(actualThumbSize.height, actualTrackRect.height) / 2 - : math.max(actualThumbSize.height, actualTrackRect.height) / 2 + 10 - : math.max(actualThumbSize.width, actualTrackRect.width) / 2 + 10; + double get tooltipStartY => + (sliderType == SliderType.horizontal) + ? _tooltipShape is SfPaddleTooltipShape + ? math.max(actualThumbSize.height, actualTrackRect.height) / 2 + : math.max(actualThumbSize.height, actualTrackRect.height) / 2 + + 10 + : math.max(actualThumbSize.width, actualTrackRect.width) / 2 + 10; double get adjustmentUnit => (actualMax - actualMin) / 10; - dynamic get semanticActionUnit => isDateTime - ? _stepDuration ?? adjustmentUnit - : _stepSize ?? adjustmentUnit; + dynamic get semanticActionUnit => + isDateTime + ? _stepDuration ?? adjustmentUnit + : _stepSize ?? adjustmentUnit; void updateTextPainter() { textPainter @@ -570,19 +598,21 @@ class RenderBaseSlider extends RenderProxyBox } Offset _getTrackOffset() { - final double dx = [ + final double dx = + [ actualOverlaySize.width, actualThumbSize.width, actualTickSize.width, - actualMinorTickSize.width + actualMinorTickSize.width, ].reduce(math.max) / 2; - final double dy = [ + final double dy = + [ actualOverlaySize.height, actualThumbSize.height, _actualDividerSize.height, - maxTrackHeight + maxTrackHeight, ].reduce(math.max) / 2; @@ -590,8 +620,10 @@ class RenderBaseSlider extends RenderProxyBox } double getMaxTrackHeight() { - return math.max(_sliderThemeData.activeTrackHeight, - _sliderThemeData.inactiveTrackHeight); + return math.max( + _sliderThemeData.activeTrackHeight, + _sliderThemeData.inactiveTrackHeight, + ); } String getFormattedText(dynamic value) { @@ -607,10 +639,11 @@ class RenderBaseSlider extends RenderProxyBox // If min and max are equal, the result will be NAN. This creates exception // and widget will not rendered. // So we have checked a condition (actualMax <= actualMin). - final double factor = (value == null || actualMax <= actualMin) - ? 0.0 - // ignore: avoid_as - : (value - actualMin) / (actualMax - actualMin) as double; + final double factor = + (value == null || actualMax <= actualMin) + ? 0.0 + // ignore: avoid_as + : (value - actualMin) / (actualMax - actualMin) as double; if (_isInversed) { return 1.0 - factor; } else { @@ -637,69 +670,125 @@ class RenderBaseSlider extends RenderProxyBox } } + bool isActiveLabelValue(dynamic currentValue) { + return false; + } + void _generateLabelsAndMajorTicksBasedOnInterval() { String label; + SliderLabel labelStyle; double labelPosition; int? valueInMilliseconds; dynamic currentValue = _min; - divisions = (isDateTime - ? _getDateTimeDifference(_min, _max, _dateIntervalType) - : _max - _min) - .toDouble() / - // ignore: avoid_as - _interval as double; + divisions = + (isDateTime + ? _getDateTimeDifference(_min, _max, _dateIntervalType) + : _max - _min) + .toDouble() / + // ignore: avoid_as + _interval + as double; for (int i = 0; i <= divisions!; i++) { - label = - _labelFormatterCallback(currentValue, getFormattedText(currentValue)); + label = _labelFormatterCallback( + currentValue, + getFormattedText(currentValue), + ); + + final TextStyle themeTextStyle = + isActiveLabelValue(currentValue) + ? _sliderThemeData.activeLabelStyle! + : _sliderThemeData.inactiveLabelStyle!; + labelStyle = _onLabelCreated(currentValue, label, themeTextStyle); if (isDateTime) { // ignore: avoid_as valueInMilliseconds = (currentValue as DateTime).millisecondsSinceEpoch; } - _visibleLabels.add(label); - unformattedLabels?.add(isDateTime - ? valueInMilliseconds!.toDouble() - : currentValue.toDouble()); + + _visibleLabels.add( + SliderLabel( + text: labelStyle.text, + textStyle: themeTextStyle.merge(labelStyle.textStyle), + ), + ); + + unformattedLabels?.add( + isDateTime ? valueInMilliseconds!.toDouble() : currentValue.toDouble(), + ); if (sliderType == SliderType.horizontal) { - labelPosition = getFactorFromValue( - isDateTime ? valueInMilliseconds : currentValue) * + labelPosition = + getFactorFromValue( + isDateTime ? valueInMilliseconds : currentValue, + ) * (actualTrackRect.width); } else { - labelPosition = getFactorFromValue( - isDateTime ? valueInMilliseconds : currentValue) * + labelPosition = + getFactorFromValue( + isDateTime ? valueInMilliseconds : currentValue, + ) * (actualTrackRect.height); } if (!_majorTickPositions.contains(labelPosition)) { _majorTickPositions.add(labelPosition); } - currentValue = isDateTime - ? _getNextDate(currentValue, _dateIntervalType, _interval!) - : currentValue + _interval; + currentValue = + isDateTime + ? _getNextDate(currentValue, _dateIntervalType, _interval!) + : currentValue + _interval; } } void _generateEdgeLabelsAndMajorTicks() { String label; + SliderLabel labelStyle; divisions = 1.0; label = _labelFormatterCallback(_min, getFormattedText(_min)); - _visibleLabels.add(label); + TextStyle themeTextStyle = + isActiveLabelValue(_min) + ? _sliderThemeData.activeLabelStyle! + : _sliderThemeData.inactiveLabelStyle!; + labelStyle = _onLabelCreated(_min, label, themeTextStyle); + _visibleLabels.add( + SliderLabel( + text: labelStyle.text, + textStyle: themeTextStyle.merge(labelStyle.textStyle), + ), + ); + unformattedLabels?.add( - isDateTime ? _min.millisecondsSinceEpoch.toDouble() : _min.toDouble()); + isDateTime ? _min.millisecondsSinceEpoch.toDouble() : _min.toDouble(), + ); label = _labelFormatterCallback(_max, getFormattedText(_max)); - _visibleLabels.add(label); + themeTextStyle = + isActiveLabelValue(_max) + ? _sliderThemeData.activeLabelStyle! + : _sliderThemeData.inactiveLabelStyle!; + labelStyle = _onLabelCreated(_max, label, themeTextStyle); + _visibleLabels.add( + SliderLabel( + text: labelStyle.text, + textStyle: themeTextStyle.merge(labelStyle.textStyle), + ), + ); + unformattedLabels?.add( - isDateTime ? _max.millisecondsSinceEpoch.toDouble() : _max.toDouble()); + isDateTime ? _max.millisecondsSinceEpoch.toDouble() : _max.toDouble(), + ); if (sliderType == SliderType.horizontal) { - _majorTickPositions - .add(getFactorFromValue(actualMin) * actualTrackRect.width); - _majorTickPositions - .add(getFactorFromValue(actualMax) * actualTrackRect.width); + _majorTickPositions.add( + getFactorFromValue(actualMin) * actualTrackRect.width, + ); + _majorTickPositions.add( + getFactorFromValue(actualMax) * actualTrackRect.width, + ); } else { - _majorTickPositions - .add(getFactorFromValue(actualMin) * actualTrackRect.height); - _majorTickPositions - .add(getFactorFromValue(actualMax) * actualTrackRect.height); + _majorTickPositions.add( + getFactorFromValue(actualMin) * actualTrackRect.height, + ); + _majorTickPositions.add( + getFactorFromValue(actualMax) * actualTrackRect.height, + ); } } @@ -720,13 +809,20 @@ class RenderBaseSlider extends RenderProxyBox final int majorTicksCount = _majorTickPositions.length; double minorTickPosition; DateTime nextDate = _getNextDate(_min, _dateIntervalType, _interval!); - DateTime currentActualDate = - _getNextDate(nextDate, _dateIntervalType, -_interval!); + DateTime currentActualDate = _getNextDate( + nextDate, + _dateIntervalType, + -_interval!, + ); for (int i = 1; i <= majorTicksCount; i++) { // Need to divide the region based on _minorTicksPerInterval. // So, added 1 with _minorTicksPerInterval. - final double intervalDiff = _getDateTimeDifference( - currentActualDate, nextDate, _dateIntervalType) / + final double intervalDiff = + _getDateTimeDifference( + currentActualDate, + nextDate, + _dateIntervalType, + ) / (_minorTicksPerInterval + 1); // On dividing region equally between two dates, then it will be // equal to 1.0. @@ -734,20 +830,25 @@ class RenderBaseSlider extends RenderProxyBox // To get nextDate of minorTick, need to pass intervals. // So, iteration value is used as interval and is started with 1. for (double j = 1; j <= _minorTicksPerInterval; j++) { - final DateTime nextMinorDate = - _getNextDate(currentActualDate, _dateIntervalType, j); + final DateTime nextMinorDate = _getNextDate( + currentActualDate, + _dateIntervalType, + j, + ); minorTickPosition = _updateMinorTicksPosition( - nextMinorDate.millisecondsSinceEpoch.toDouble()); + nextMinorDate.millisecondsSinceEpoch.toDouble(), + ); _minorTickPositions.add(minorTickPosition); } } else { - final double minorPositionDiff = (nextDate.millisecondsSinceEpoch - + final double minorPositionDiff = + (nextDate.millisecondsSinceEpoch - currentActualDate.millisecondsSinceEpoch) / (_minorTicksPerInterval + 1); for (int j = 1; j <= _minorTicksPerInterval; j++) { minorTickPosition = _updateMinorTicksPosition( - currentActualDate.millisecondsSinceEpoch + - (j * minorPositionDiff)); + currentActualDate.millisecondsSinceEpoch + (j * minorPositionDiff), + ); _minorTickPositions.add(minorTickPosition); } } @@ -766,7 +867,8 @@ class RenderBaseSlider extends RenderProxyBox void _generateNumericMinorTicks() { final int majorTicksCount = _majorTickPositions.length; for (int i = 0; i <= majorTicksCount - 1; i++) { - final double minorPositionDiff = (i + 1 < majorTicksCount + final double minorPositionDiff = + (i + 1 < majorTicksCount ? _majorTickPositions[i + 1] - _majorTickPositions[i] : ((sliderType == SliderType.horizontal ? actualTrackRect.width @@ -785,7 +887,10 @@ class RenderBaseSlider extends RenderProxyBox /// intervalType to find the exact range. // ignore: missing_return int _getDateTimeDifference( - DateTime min, DateTime max, DateIntervalType? intervalType) { + DateTime min, + DateTime max, + DateIntervalType? intervalType, + ) { assert(intervalType != null); final Duration diff = max.difference(min); switch (intervalType!) { @@ -809,7 +914,10 @@ class RenderBaseSlider extends RenderProxyBox /// Get the date time label based on the interval and intervalType. // ignore: missing_return DateTime _getNextDate( - DateTime currentDate, DateIntervalType? intervalType, double interval) { + DateTime currentDate, + DateIntervalType? intervalType, + double interval, + ) { assert(intervalType != null); switch (intervalType!) { case DateIntervalType.months: @@ -820,8 +928,12 @@ class RenderBaseSlider extends RenderProxyBox return DateTime(currentDate.year, currentDate.month, currentDate.day); case DateIntervalType.hours: currentDate = currentDate.add(Duration(hours: interval.ceil())); - return DateTime(currentDate.year, currentDate.month, currentDate.day, - currentDate.hour); + return DateTime( + currentDate.year, + currentDate.month, + currentDate.day, + currentDate.hour, + ); case DateIntervalType.minutes: return currentDate.add(Duration(minutes: interval.ceil())); case DateIntervalType.seconds: @@ -857,7 +969,8 @@ class RenderBaseSlider extends RenderProxyBox if (isDiscrete) { if (!isDateTime) { final double maxMinDiff = getNumerizedValue(_max - _min); - double factorValue = (getFactorFromValue(valueInDouble ?? value) * + double factorValue = + (getFactorFromValue(valueInDouble ?? value) * (maxMinDiff / _stepSize!)) .round() / (maxMinDiff / _stepSize!); @@ -876,12 +989,13 @@ class RenderBaseSlider extends RenderProxyBox for (double i = actualMin; i < actualMax;) { nextDate = DateTime( - currentDate.year + _stepDuration!.years, - currentDate.month + _stepDuration!.months, - currentDate.day + _stepDuration!.days, - currentDate.hour + _stepDuration!.hours, - currentDate.minute + _stepDuration!.minutes, - currentDate.second + _stepDuration!.seconds); + currentDate.year + _stepDuration!.years, + currentDate.month + _stepDuration!.months, + currentDate.day + _stepDuration!.days, + currentDate.hour + _stepDuration!.hours, + currentDate.minute + _stepDuration!.minutes, + currentDate.second + _stepDuration!.seconds, + ); final double currentDateInms = currentDate.millisecondsSinceEpoch.toDouble(); @@ -912,11 +1026,13 @@ class RenderBaseSlider extends RenderProxyBox } double getFactorFromCurrentPosition() { - final double factor = (sliderType == SliderType.horizontal) - ? ((mainAxisOffset - actualTrackRect.left) / actualTrackRect.width) - .clamp(0.0, 1.0) - : ((actualTrackRect.bottom - mainAxisOffset) / actualTrackRect.height) - .clamp(0.0, 1.0); + final double factor = + (sliderType == SliderType.horizontal) + ? ((mainAxisOffset - actualTrackRect.left) / actualTrackRect.width) + .clamp(0.0, 1.0) + : ((actualTrackRect.bottom - mainAxisOffset) / + actualTrackRect.height) + .clamp(0.0, 1.0); if (_isInversed) { return 1.0 - factor; } else { @@ -924,8 +1040,13 @@ class RenderBaseSlider extends RenderProxyBox } } - Rect getRectangularTooltipRect(TextPainter textPainter, Offset offset, - Offset thumbCenter, Rect trackRect, SfSliderThemeData themeData) { + Rect getRectangularTooltipRect( + TextPainter textPainter, + Offset offset, + Offset thumbCenter, + Rect trackRect, + SfSliderThemeData themeData, + ) { final double rectangularTooltipHeight = textPainter.height + tooltipTextPadding.dy > minTooltipHeight ? textPainter.height + tooltipTextPadding.dy @@ -935,19 +1056,23 @@ class RenderBaseSlider extends RenderProxyBox ? (textPainter.width + tooltipTextPadding.dx) / 2 : minTooltipWidth / 2; - double rightLineWidth = thumbCenter.dx + halfTextWidth > trackRect.right - ? trackRect.right - thumbCenter.dx - : halfTextWidth; - final double leftLineWidth = thumbCenter.dx - halfTextWidth < trackRect.left - ? thumbCenter.dx - trackRect.left - : (halfTextWidth * 2) - rightLineWidth; - rightLineWidth = leftLineWidth < halfTextWidth - ? halfTextWidth - leftLineWidth + rightLineWidth - : rightLineWidth; + double rightLineWidth = + thumbCenter.dx + halfTextWidth > trackRect.right + ? trackRect.right - thumbCenter.dx + : halfTextWidth; + final double leftLineWidth = + thumbCenter.dx - halfTextWidth < trackRect.left + ? thumbCenter.dx - trackRect.left + : (halfTextWidth * 2) - rightLineWidth; + rightLineWidth = + leftLineWidth < halfTextWidth + ? halfTextWidth - leftLineWidth + rightLineWidth + : rightLineWidth; final double left = thumbCenter.dx - leftLineWidth; final double right = thumbCenter.dx + rightLineWidth; - final double top = thumbCenter.dy - + final double top = + thumbCenter.dy - rectangularTooltipHeight - offset.dy - tooltipTriangleHeight; @@ -957,12 +1082,13 @@ class RenderBaseSlider extends RenderProxyBox } Rect getPaddleTooltipRect( - TextPainter textPainter, - double thumbRadius, - Offset offset, - Offset thumbCenter, - Rect trackRect, - SfSliderThemeData themeData) { + TextPainter textPainter, + double thumbRadius, + Offset offset, + Offset thumbCenter, + Rect trackRect, + SfSliderThemeData themeData, + ) { final double paddleTooltipRadius = textPainter.height > minPaddleTopCircleRadius ? textPainter.height @@ -973,14 +1099,21 @@ class RenderBaseSlider extends RenderProxyBox ? thumbRadius - neckDifference : 4.0; final double halfTextWidth = textPainter.width / 2 + textPadding; - final double halfPaddleWidth = halfTextWidth > paddleTooltipRadius - ? halfTextWidth - : paddleTooltipRadius; - final double shift = _getAdjustPaddleWidth(thumbCenter, offset, - halfTextWidth - paddleTooltipRadius, paddleTooltipRadius, trackRect); + final double halfPaddleWidth = + halfTextWidth > paddleTooltipRadius + ? halfTextWidth + : paddleTooltipRadius; + final double shift = _getAdjustPaddleWidth( + thumbCenter, + offset, + halfTextWidth - paddleTooltipRadius, + paddleTooltipRadius, + trackRect, + ); final double left = thumbCenter.dx - halfPaddleWidth - shift; final double right = thumbCenter.dx + halfPaddleWidth - shift; - final double top = thumbCenter.dy - + final double top = + thumbCenter.dy - paddleTooltipRadius - paddleTooltipRadius * (1.0 - moveNeckValue) - topNeckRadius - @@ -990,8 +1123,13 @@ class RenderBaseSlider extends RenderProxyBox return Rect.fromLTRB(left, top, right, bottom); } - double _getAdjustPaddleWidth(Offset thumbCenter, Offset offset, - double halfTextWidth, double paddleTopCircleRadius, Rect trackRect) { + double _getAdjustPaddleWidth( + Offset thumbCenter, + Offset offset, + double halfTextWidth, + double paddleTopCircleRadius, + Rect trackRect, + ) { final double leftShiftWidth = thumbCenter.dx - offset.dx - halfTextWidth - paddleTopCircleRadius; // Moving the paddle top circle width from left to right. @@ -1001,35 +1139,38 @@ class RenderBaseSlider extends RenderProxyBox trackRect.right + trackRect.left - offset.dx; // Moving the paddle top circle width from right to left. // When the tooltip leaves to the render box. - shiftPaddleWidth = thumbCenter.dx + halfTextWidth + paddleTopCircleRadius > - rightEndPosition - ? thumbCenter.dx + - halfTextWidth + - paddleTopCircleRadius - - rightEndPosition - : shiftPaddleWidth; + shiftPaddleWidth = + thumbCenter.dx + halfTextWidth + paddleTopCircleRadius > + rightEndPosition + ? thumbCenter.dx + + halfTextWidth + + paddleTopCircleRadius - + rightEndPosition + : shiftPaddleWidth; return shiftPaddleWidth; } void drawLabelsTicksAndDividers( - PaintingContext context, - Rect trackRect, - Offset offset, - Offset? thumbCenter, - Offset? startThumbCenter, - Offset? endThumbCenter, - Animation stateAnimation, - dynamic value, - SfRangeValues? values) { + PaintingContext context, + Rect trackRect, + Offset offset, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, + Animation stateAnimation, + dynamic value, + SfRangeValues? values, + ) { int dateTimePos = 0; bool isActive; final double dx = sliderType == SliderType.horizontal ? trackRect.left : trackRect.bottom; final double dy = sliderType == SliderType.horizontal ? trackRect.top : trackRect.left; - final double halfTrackHeight = sliderType == SliderType.horizontal - ? trackRect.height / 2 - : trackRect.width / 2; + final double halfTrackHeight = + sliderType == SliderType.horizontal + ? trackRect.height / 2 + : trackRect.width / 2; if (startThumbCenter != null) { if (sliderType == SliderType.horizontal) { isActive = @@ -1046,14 +1187,16 @@ class RenderBaseSlider extends RenderProxyBox } } - final double dividerRadius = _dividerShape + final double dividerRadius = + _dividerShape .getPreferredSize(_sliderThemeData, isActive: isActive) .width / 2; - final double tickRadius = sliderType == SliderType.horizontal - ? _tickShape.getPreferredSize(_sliderThemeData).width / 2 - : _tickShape.getPreferredSize(_sliderThemeData).height / 2; + final double tickRadius = + sliderType == SliderType.horizontal + ? _tickShape.getPreferredSize(_sliderThemeData).width / 2 + : _tickShape.getPreferredSize(_sliderThemeData).height / 2; // ignore: avoid_as double textValue = isDateTime ? 0.0 : _min.toDouble() as double; @@ -1069,19 +1212,20 @@ class RenderBaseSlider extends RenderProxyBox // Drawing ticks. if (_showTicks) { _drawTick( - dx, - tickPosition, - dy, - trackRect, - dateTimePos, - tickRadius, - context, - thumbCenter, - startThumbCenter, - endThumbCenter, - value, - values, - stateAnimation); + dx, + tickPosition, + dy, + trackRect, + dateTimePos, + tickRadius, + context, + thumbCenter, + startThumbCenter, + endThumbCenter, + value, + values, + stateAnimation, + ); } if (_interval != null && _interval! > 0) { @@ -1092,53 +1236,58 @@ class RenderBaseSlider extends RenderProxyBox _minorTickPositions[minorTickIndex]; minorTickIndex++; _drawMinorTick( - currentMinorTickPosition, - trackRect, - dx, - dy, - context, - thumbCenter, - startThumbCenter, - endThumbCenter, - value, - values, - stateAnimation); - } - } - - // Drawing dividers. - if (_showDividers) { - _drawDivider( + currentMinorTickPosition, + trackRect, dx, - tickPosition, dy, - halfTrackHeight, - dateTimePos, - dividerRadius, - trackRect, context, thumbCenter, startThumbCenter, endThumbCenter, value, values, - stateAnimation); + stateAnimation, + ); + } + } + + // Drawing dividers. + if (_showDividers) { + _drawDivider( + dx, + tickPosition, + dy, + halfTrackHeight, + dateTimePos, + dividerRadius, + trackRect, + context, + thumbCenter, + startThumbCenter, + endThumbCenter, + value, + values, + stateAnimation, + ); } } // Drawing labels. if (_showLabels) { - final double dx = sliderType == SliderType.horizontal - ? trackRect.left - : trackRect.bottom; + final double dx = + sliderType == SliderType.horizontal + ? trackRect.left + : trackRect.bottom; - double offsetX = sliderType == SliderType.horizontal - ? dx + tickPosition - : dx - tickPosition; + double offsetX = + sliderType == SliderType.horizontal + ? dx + tickPosition + : dx - tickPosition; if (_labelPlacement == LabelPlacement.betweenTicks) { if (sliderType == SliderType.horizontal) { - offsetX += ((dateTimePos + 1 <= divisions! + offsetX += + ((dateTimePos + 1 <= divisions! ? _majorTickPositions[dateTimePos + 1] : (_isInversed ? trackRect.left : trackRect.width)) - tickPosition) / @@ -1158,13 +1307,18 @@ class RenderBaseSlider extends RenderProxyBox } } + final TextStyle textStyle = + hasLabelCreated + ? _visibleLabels[dateTimePos].textStyle + : isInactive + ? _sliderThemeData.inactiveLabelStyle! + : _sliderThemeData.activeLabelStyle!; + if (_edgeLabelPlacement == EdgeLabelPlacement.inside && _labelPlacement == LabelPlacement.onTicks) { final Size labelSize = measureText( - _visibleLabels[dateTimePos], - isInactive - ? sliderThemeData.inactiveLabelStyle! - : sliderThemeData.activeLabelStyle!, + _visibleLabels[dateTimePos].text, + textStyle, ); if (sliderType == SliderType.horizontal) { if (dateTimePos == 0) { @@ -1182,30 +1336,34 @@ class RenderBaseSlider extends RenderProxyBox } _drawLabel( - dateTimePos, - dx, - tickPosition, - trackRect, - dy, - context, - thumbCenter, - startThumbCenter, - endThumbCenter, - value, - values, - stateAnimation, - offsetX); + dateTimePos, + dx, + tickPosition, + trackRect, + dy, + context, + thumbCenter, + startThumbCenter, + endThumbCenter, + value, + values, + stateAnimation, + offsetX, + textStyle, + ); } // When interval is not set but [showLabels], [showTicks] enabled, // we need to show labels/ticks on min, max values. So we used // interval as _max - _min. - final double intervalDiff = (isDateTime - ? 1.0 - : _interval != null && _interval! > 0 - ? _interval - // ignore: avoid_as - : _max.toDouble() - _min.toDouble()) as double; + final double intervalDiff = + (isDateTime + ? 1.0 + : _interval != null && _interval! > 0 + ? _interval + // ignore: avoid_as + : _max.toDouble() - _min.toDouble()) + as double; textValue += intervalDiff; dateTimePos += 1; } @@ -1213,26 +1371,27 @@ class RenderBaseSlider extends RenderProxyBox } void _drawTick( - double dx, - double tickPosition, - double dy, - Rect trackRect, - int dateTimePos, - double tickRadius, - PaintingContext context, - Offset? thumbCenter, - Offset? startThumbCenter, - Offset? endThumbCenter, - dynamic value, - SfRangeValues? values, - Animation stateAnimation) { + double dx, + double tickPosition, + double dy, + Rect trackRect, + int dateTimePos, + double tickRadius, + PaintingContext context, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, + dynamic value, + SfRangeValues? values, + Animation stateAnimation, + ) { Offset actualTickOffset; if (sliderType == SliderType.horizontal) { if (_majorTickPositions[dateTimePos] == 0.0) { actualTickOffset = Offset(dx + tickPosition + tickRadius, dy + trackRect.height) + - (_sliderThemeData.tickOffset ?? Offset.zero); + (_sliderThemeData.tickOffset ?? Offset.zero); } // Due to floating-point operations, last [_majorTickPosition] is greater // than [trackRect.height] or [trackRect.width]. This happens in some @@ -1243,16 +1402,17 @@ class RenderBaseSlider extends RenderProxyBox trackRect.width.toStringAsFixed(8)) { actualTickOffset = Offset(dx + tickPosition - tickRadius, dy + trackRect.height) + - (_sliderThemeData.tickOffset ?? Offset.zero); + (_sliderThemeData.tickOffset ?? Offset.zero); } else { - actualTickOffset = Offset(dx + tickPosition, dy + trackRect.height) + + actualTickOffset = + Offset(dx + tickPosition, dy + trackRect.height) + (_sliderThemeData.tickOffset ?? Offset.zero); } } else { if (_majorTickPositions[dateTimePos] == 0.0) { actualTickOffset = Offset(dy + trackRect.width, dx - tickPosition - tickRadius) + - (_sliderThemeData.tickOffset ?? Offset.zero); + (_sliderThemeData.tickOffset ?? Offset.zero); } // Due to floating-point operations, last [_majorTickPosition] is greater // than [trackRect.height] or [trackRect.width]. This happens in some @@ -1263,77 +1423,93 @@ class RenderBaseSlider extends RenderProxyBox trackRect.height.toStringAsFixed(8)) { actualTickOffset = Offset(dy + trackRect.width, dx - tickPosition + tickRadius) + - (_sliderThemeData.tickOffset ?? Offset.zero); + (_sliderThemeData.tickOffset ?? Offset.zero); } else { - actualTickOffset = Offset(dy + trackRect.width, dx - tickPosition) + + actualTickOffset = + Offset(dy + trackRect.width, dx - tickPosition) + (_sliderThemeData.tickOffset ?? Offset.zero); } } - _tickShape.paint(context, actualTickOffset, thumbCenter, startThumbCenter, - endThumbCenter, - parentBox: this, - themeData: _sliderThemeData, - currentValue: value, - currentValues: values, - enableAnimation: stateAnimation, - textDirection: _textDirection); + _tickShape.paint( + context, + actualTickOffset, + thumbCenter, + startThumbCenter, + endThumbCenter, + parentBox: this, + themeData: _sliderThemeData, + currentValue: value, + currentValues: values, + enableAnimation: stateAnimation, + textDirection: _textDirection, + ); } void _drawMinorTick( - double currentMinorTickPosition, - Rect trackRect, - double dx, - double dy, - PaintingContext context, - Offset? thumbCenter, - Offset? startThumbCenter, - Offset? endThumbCenter, - dynamic value, - SfRangeValues? values, - Animation stateAnimation) { + double currentMinorTickPosition, + Rect trackRect, + double dx, + double dy, + PaintingContext context, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, + dynamic value, + SfRangeValues? values, + Animation stateAnimation, + ) { if (currentMinorTickPosition < (sliderType == SliderType.horizontal ? trackRect.width : trackRect.height) && currentMinorTickPosition > 0) { - final Offset actualTickOffset = sliderType == SliderType.horizontal - ? Offset(dx + currentMinorTickPosition, dy + trackRect.height) + - (_sliderThemeData.tickOffset ?? Offset.zero) - : Offset(dy + trackRect.width, dx - currentMinorTickPosition) + - (_sliderThemeData.tickOffset ?? Offset.zero); - _minorTickShape.paint(context, actualTickOffset, thumbCenter, - startThumbCenter, endThumbCenter, - parentBox: this, - themeData: _sliderThemeData, - currentValue: value, - currentValues: values, - enableAnimation: stateAnimation, - textDirection: _textDirection); + final Offset actualTickOffset = + sliderType == SliderType.horizontal + ? Offset(dx + currentMinorTickPosition, dy + trackRect.height) + + (_sliderThemeData.tickOffset ?? Offset.zero) + : Offset(dy + trackRect.width, dx - currentMinorTickPosition) + + (_sliderThemeData.tickOffset ?? Offset.zero); + _minorTickShape.paint( + context, + actualTickOffset, + thumbCenter, + startThumbCenter, + endThumbCenter, + parentBox: this, + themeData: _sliderThemeData, + currentValue: value, + currentValues: values, + enableAnimation: stateAnimation, + textDirection: _textDirection, + ); } } void _drawDivider( - double dx, - double tickPosition, - double dy, - double halfTrackHeight, - // ignore: no_leading_underscores_for_local_identifiers - int _dateTimePos, - double dividerRadius, - Rect trackRect, - PaintingContext context, - Offset? thumbCenter, - Offset? startThumbCenter, - Offset? endThumbCenter, - dynamic value, - SfRangeValues? values, - Animation stateAnimation) { + double dx, + double tickPosition, + double dy, + double halfTrackHeight, + // ignore: no_leading_underscores_for_local_identifiers + int _dateTimePos, + double dividerRadius, + Rect trackRect, + PaintingContext context, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, + dynamic value, + SfRangeValues? values, + Animation stateAnimation, + ) { Offset dividerCenter; if (sliderType == SliderType.horizontal) { if (_majorTickPositions[_dateTimePos] == 0.0) { - dividerCenter = - Offset(dx + tickPosition + dividerRadius, dy + halfTrackHeight); + dividerCenter = Offset( + dx + tickPosition + dividerRadius, + dy + halfTrackHeight, + ); } // Due to floating-point operations, last [_majorTickPosition] is greater // than [trackRect.height] or [trackRect.width]. This happens in some @@ -1342,15 +1518,19 @@ class RenderBaseSlider extends RenderProxyBox // Current [_majorTickPosition] = 100.0909890121) else if (_majorTickPositions[_dateTimePos].toStringAsFixed(8) == trackRect.width.toStringAsFixed(8)) { - dividerCenter = - Offset(dx + tickPosition - dividerRadius, dy + halfTrackHeight); + dividerCenter = Offset( + dx + tickPosition - dividerRadius, + dy + halfTrackHeight, + ); } else { dividerCenter = Offset(dx + tickPosition, dy + halfTrackHeight); } } else { if (_majorTickPositions[_dateTimePos] == 0.0) { - dividerCenter = - Offset(dy + halfTrackHeight, dx - tickPosition - dividerRadius); + dividerCenter = Offset( + dy + halfTrackHeight, + dx - tickPosition - dividerRadius, + ); } // Due to floating-point operations, last [_majorTickPosition] is greater // than [trackRect.height] or [trackRect.width]. This happens in some @@ -1359,68 +1539,92 @@ class RenderBaseSlider extends RenderProxyBox // Current [_majorTickPosition] = 100.0909890121) else if (_majorTickPositions[_dateTimePos].toStringAsFixed(8) == trackRect.height.toStringAsFixed(8)) { - dividerCenter = - Offset(dy + halfTrackHeight, dx - tickPosition + dividerRadius); + dividerCenter = Offset( + dy + halfTrackHeight, + dx - tickPosition + dividerRadius, + ); } else { dividerCenter = Offset(dy + halfTrackHeight, dx - tickPosition); } } _dividerShape.paint( - context, dividerCenter, thumbCenter, startThumbCenter, endThumbCenter, - parentBox: this, - themeData: _sliderThemeData, - currentValue: value, - currentValues: values, - enableAnimation: stateAnimation, - textDirection: _textDirection, - paint: null); + context, + dividerCenter, + thumbCenter, + startThumbCenter, + endThumbCenter, + parentBox: this, + themeData: _sliderThemeData, + currentValue: value, + currentValues: values, + enableAnimation: stateAnimation, + textDirection: _textDirection, + paint: null, + ); } void _drawLabel( - // ignore: no_leading_underscores_for_local_identifiers - int _dateTimePos, - double dx, - double tickPosition, - Rect trackRect, - double dy, - PaintingContext context, - Offset? thumbCenter, - Offset? startThumbCenter, - Offset? endThumbCenter, - dynamic value, - SfRangeValues? values, - Animation stateAnimation, - double offsetX) { + // ignore: no_leading_underscores_for_local_identifiers + int _dateTimePos, + double dx, + double tickPosition, + Rect trackRect, + double dy, + PaintingContext context, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, + dynamic value, + SfRangeValues? values, + Animation stateAnimation, + double offsetX, + TextStyle labelStyle, + ) { final double dy = sliderType == SliderType.horizontal ? trackRect.top : trackRect.left; - final String labelText = _visibleLabels[_dateTimePos]; - final Offset actualLabelOffset = sliderType == SliderType.horizontal - ? Offset(offsetX, dy + trackRect.height + actualTickHeight) + - (_sliderThemeData.labelOffset ?? Offset.zero) - : Offset(dy + trackRect.width + actualTickWidth, offsetX) + - (_sliderThemeData.labelOffset ?? Offset.zero); - - _drawText(context, actualLabelOffset, thumbCenter, startThumbCenter, - endThumbCenter, labelText, - parentBox: this, - themeData: _sliderThemeData, - currentValue: value, - currentValues: values, - enableAnimation: stateAnimation, - textPainter: textPainter, - textDirection: _textDirection); - } - - void _drawText(PaintingContext context, Offset center, Offset? thumbCenter, - Offset? startThumbCenter, Offset? endThumbCenter, String text, - {required RenderProxyBox parentBox, - required SfSliderThemeData themeData, - dynamic currentValue, - SfRangeValues? currentValues, - required Animation enableAnimation, - required TextPainter textPainter, - required TextDirection textDirection}) { + final String labelText = _visibleLabels[_dateTimePos].text; + final Offset actualLabelOffset = + sliderType == SliderType.horizontal + ? Offset(offsetX, dy + trackRect.height + actualTickHeight) + + (_sliderThemeData.labelOffset ?? Offset.zero) + : Offset(dy + trackRect.width + actualTickWidth, offsetX) + + (_sliderThemeData.labelOffset ?? Offset.zero); + + _drawText( + context, + actualLabelOffset, + thumbCenter, + startThumbCenter, + endThumbCenter, + labelText, + labelStyle, + parentBox: this, + themeData: _sliderThemeData, + currentValue: value, + currentValues: values, + enableAnimation: stateAnimation, + textPainter: textPainter, + textDirection: _textDirection, + ); + } + + void _drawText( + PaintingContext context, + Offset center, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, + String text, + TextStyle textStyle, { + required RenderProxyBox parentBox, + required SfSliderThemeData themeData, + dynamic currentValue, + SfRangeValues? currentValues, + required Animation enableAnimation, + required TextPainter textPainter, + required TextDirection textDirection, + }) { if (sliderType == SliderType.horizontal) { // Added this condition to check whether consider single thumb or // two thumbs for finding inactive range. @@ -1459,39 +1663,51 @@ class RenderBaseSlider extends RenderProxyBox } } - final TextSpan textSpan = TextSpan( - text: text, - style: isInactive - ? themeData.inactiveLabelStyle - : themeData.activeLabelStyle, - ); + final TextStyle labelTextStyle = + hasLabelCreated + ? textStyle + : isInactive + ? themeData.inactiveLabelStyle! + : themeData.activeLabelStyle!; + + final TextSpan textSpan = TextSpan(text: text, style: labelTextStyle); + textPainter.text = textSpan; textPainter.layout(); if (sliderType == SliderType.horizontal) { textPainter.paint( - context.canvas, Offset(center.dx - textPainter.width / 2, center.dy)); + context.canvas, + Offset(center.dx - textPainter.width / 2, center.dy), + ); } else { - textPainter.paint(context.canvas, - Offset(center.dx, center.dy - textPainter.height / 2)); + textPainter.paint( + context.canvas, + Offset(center.dx, center.dy - textPainter.height / 2), + ); } } - dynamic getNextSemanticValue(dynamic value, dynamic semanticActionUnit, - {required double actualValue}) { + dynamic getNextSemanticValue( + dynamic value, + dynamic semanticActionUnit, { + required double actualValue, + }) { if (isDateTime) { if (_stepDuration == null) { return DateTime.fromMillisecondsSinceEpoch( - (actualValue + semanticActionUnit) - .clamp(actualMin, actualMax) - .toInt()); + (actualValue + semanticActionUnit) + .clamp(actualMin, actualMax) + .toInt(), + ); } else { final DateTime nextDate = DateTime( - value.year + semanticActionUnit.years, - value.month + semanticActionUnit.months, - value.day + semanticActionUnit.days, - value.hour + semanticActionUnit.days, - value.minute + semanticActionUnit.minutes, - value.second + semanticActionUnit.seconds); + value.year + semanticActionUnit.years, + value.month + semanticActionUnit.months, + value.day + semanticActionUnit.days, + value.hour + semanticActionUnit.days, + value.minute + semanticActionUnit.minutes, + value.second + semanticActionUnit.seconds, + ); final double nextDateInms = nextDate.millisecondsSinceEpoch.toDouble(); return nextDateInms < actualMax ? nextDate : _max; @@ -1501,22 +1717,27 @@ class RenderBaseSlider extends RenderProxyBox } } - dynamic getPrevSemanticValue(dynamic value, dynamic semanticActionUnit, - {required double actualValue}) { + dynamic getPrevSemanticValue( + dynamic value, + dynamic semanticActionUnit, { + required double actualValue, + }) { if (isDateTime) { if (_stepDuration == null) { return DateTime.fromMillisecondsSinceEpoch( - (actualValue - semanticActionUnit) - .clamp(actualMin, actualMax) - .toInt()); + (actualValue - semanticActionUnit) + .clamp(actualMin, actualMax) + .toInt(), + ); } else { final DateTime prevDate = DateTime( - value.year - semanticActionUnit.years, - value.month - semanticActionUnit.months, - value.day - semanticActionUnit.days, - value.hour - semanticActionUnit.days, - value.minute - semanticActionUnit.minutes, - value.second - semanticActionUnit.seconds); + value.year - semanticActionUnit.years, + value.month - semanticActionUnit.months, + value.day - semanticActionUnit.days, + value.hour - semanticActionUnit.days, + value.minute - semanticActionUnit.minutes, + value.second - semanticActionUnit.seconds, + ); final double prevDateInms = prevDate.millisecondsSinceEpoch.toDouble(); return prevDateInms > actualMin ? prevDate : _min; @@ -1538,10 +1759,10 @@ class RenderBaseSlider extends RenderProxyBox // This method is only applicable for vertical sliders Size _textSize(String text, double fontSize) { final TextPainter textPainter = TextPainter( - text: TextSpan(text: text, style: TextStyle(fontSize: fontSize)), - maxLines: 1, - textDirection: TextDirection.ltr) - ..layout(); + text: TextSpan(text: text, style: TextStyle(fontSize: fontSize)), + maxLines: 1, + textDirection: TextDirection.ltr, + )..layout(); return textPainter.size; } @@ -1550,26 +1771,45 @@ class RenderBaseSlider extends RenderProxyBox double maxLabelWidth = 0.0; if (_showLabels && _interval != null && _interval! > 0) { String label; + SliderLabel labelStyle; dynamic currentValue = _min; double labelLength; - divisions = (isDateTime - ? _getDateTimeDifference(_min, _max, _dateIntervalType) - : _max - _min) - .toDouble() / - // ignore: avoid_as - _interval as double; + divisions = + (isDateTime + ? _getDateTimeDifference( + _min, + _max, + _dateIntervalType, + ) + : _max - _min) + .toDouble() / + // ignore: avoid_as + _interval + as double; for (int i = 0; i <= divisions!.toInt(); i++) { label = _labelFormatterCallback( - currentValue, getFormattedText(currentValue)); - - labelLength = _textSize(label, maximumFontSize).width; + currentValue, + getFormattedText(currentValue), + ); + final TextStyle themeTextStyle = + isActiveLabelValue(currentValue) + ? _sliderThemeData.activeLabelStyle! + : _sliderThemeData.inactiveLabelStyle!; + labelStyle = _onLabelCreated(currentValue, label, themeTextStyle); + + final double maximumLabelFontSize = math.max( + maximumFontSize, + labelStyle.textStyle.fontSize ?? 0, + ); + labelLength = _textSize(labelStyle.text, maximumLabelFontSize).width; if (maxLabelWidth < labelLength) { maxLabelWidth = labelLength; } - currentValue = isDateTime - ? _getNextDate(currentValue, _dateIntervalType, _interval!) - : currentValue + _interval; + currentValue = + isDateTime + ? _getNextDate(currentValue, _dateIntervalType, _interval!) + : currentValue + _interval; } } else if (_showLabels) { maxLabelWidth = _edgeLabelWidth(); @@ -1581,11 +1821,34 @@ class RenderBaseSlider extends RenderProxyBox double _edgeLabelWidth() { String minLabel; String maxLabel; + SliderLabel minLabelStyle; + SliderLabel maxLabelStyle; double maxLabelWidth; minLabel = _labelFormatterCallback(_min, getFormattedText(_min)); + TextStyle themeTextStyle = + isActiveLabelValue(_min) + ? _sliderThemeData.activeLabelStyle! + : _sliderThemeData.inactiveLabelStyle!; + minLabelStyle = _onLabelCreated(_min, minLabel, themeTextStyle); maxLabel = _labelFormatterCallback(_max, getFormattedText(_max)); - final double minLabelLength = _textSize(minLabel, maximumFontSize).width; - final double maxLabelLength = _textSize(maxLabel, maximumFontSize).width; + themeTextStyle = + isActiveLabelValue(_max) + ? _sliderThemeData.activeLabelStyle! + : _sliderThemeData.inactiveLabelStyle!; + maxLabelStyle = _onLabelCreated(_max, maxLabel, themeTextStyle); + + double maxFontFize = math.max( + maximumFontSize, + maxLabelStyle.textStyle.fontSize ?? 0, + ); + final double minLabelLength = + _textSize(minLabelStyle.text, maxFontFize).width; + maxFontFize = math.max( + maximumFontSize, + minLabelStyle.textStyle.fontSize ?? 0, + ); + final double maxLabelLength = + _textSize(maxLabelStyle.text, maxFontFize).width; maxLabelWidth = math.max(minLabelLength, maxLabelLength); return maxLabelWidth; } @@ -1610,30 +1873,34 @@ class RenderBaseSlider extends RenderProxyBox // vertical sliders is also considered as actualHeight. if (sliderType == SliderType.horizontal) { actualHeight = math.max( - 2 * trackOffset.dy, - trackOffset.dy + - maxTrackHeight / 2 + - math.max(actualTickHeight, actualMinorTickHeight) + - actualLabelHeight); + 2 * trackOffset.dy, + trackOffset.dy + + maxTrackHeight / 2 + + math.max(actualTickHeight, actualMinorTickHeight) + + actualLabelHeight, + ); size = Size( - constraints.hasBoundedWidth - ? constraints.maxWidth - : minTrackWidth + 2 * trackOffset.dx, - constraints.hasBoundedHeight ? constraints.maxHeight : actualHeight); + constraints.hasBoundedWidth + ? constraints.maxWidth + : minTrackWidth + 2 * trackOffset.dx, + constraints.hasBoundedHeight ? constraints.maxHeight : actualHeight, + ); } else { actualHeight = math.max( - 2 * trackOffset.dx, - trackOffset.dx + - maxTrackHeight / 2 + - math.max(actualTickWidth, actualMinorTickWidth) + - _maximumLabelWidth() + - actualLabelOffset); + 2 * trackOffset.dx, + trackOffset.dx + + maxTrackHeight / 2 + + math.max(actualTickWidth, actualMinorTickWidth) + + _maximumLabelWidth() + + actualLabelOffset, + ); size = Size( - constraints.hasBoundedWidth ? constraints.maxWidth : actualHeight, - constraints.hasBoundedHeight - ? constraints.maxHeight - : minTrackWidth + 2 * trackOffset.dy); + constraints.hasBoundedWidth ? constraints.maxWidth : actualHeight, + constraints.hasBoundedHeight + ? constraints.maxHeight + : minTrackWidth + 2 * trackOffset.dy, + ); } generateLabelsAndMajorTicks(); diff --git a/packages/syncfusion_flutter_sliders/lib/src/slider_shapes.dart b/packages/syncfusion_flutter_sliders/lib/src/slider_shapes.dart index aafeae745..49ea9dc35 100644 --- a/packages/syncfusion_flutter_sliders/lib/src/slider_shapes.dart +++ b/packages/syncfusion_flutter_sliders/lib/src/slider_shapes.dart @@ -19,36 +19,47 @@ class SfTrackShape { /// Returns the size based on the values passed to it. Rect getPreferredRect( - RenderBox parentBox, SfSliderThemeData themeData, Offset offset, - {bool? isActive}) { + RenderBox parentBox, + SfSliderThemeData themeData, + Offset offset, { + bool? isActive, + }) { final Size overlayPreferredSize = (parentBox as RenderBaseSlider) .overlayShape .getPreferredSize(themeData); - final Size thumbPreferredSize = - parentBox.thumbShape.getPreferredSize(themeData); - final Size tickPreferredSize = - parentBox.tickShape.getPreferredSize(themeData); + final Size thumbPreferredSize = parentBox.thumbShape.getPreferredSize( + themeData, + ); + final Size tickPreferredSize = parentBox.tickShape.getPreferredSize( + themeData, + ); double maxRadius; if (_isVertical(parentBox)) { maxRadius = math.max( - overlayPreferredSize.height / 2, - math.max( - thumbPreferredSize.height / 2, tickPreferredSize.height / 2)); + overlayPreferredSize.height / 2, + math.max(thumbPreferredSize.height / 2, tickPreferredSize.height / 2), + ); } else { - maxRadius = math.max(overlayPreferredSize.width / 2, - math.max(thumbPreferredSize.width / 2, tickPreferredSize.width / 2)); + maxRadius = math.max( + overlayPreferredSize.width / 2, + math.max(thumbPreferredSize.width / 2, tickPreferredSize.width / 2), + ); } - final double maxTrackHeight = - math.max(themeData.activeTrackHeight, themeData.inactiveTrackHeight); + final double maxTrackHeight = math.max( + themeData.activeTrackHeight, + themeData.inactiveTrackHeight, + ); // ignore: avoid_as if (_isVertical(parentBox)) { double left = offset.dx; if (isActive != null) { - left += isActive - ? (maxTrackHeight - themeData.activeTrackHeight) / 2 - : (maxTrackHeight - themeData.inactiveTrackHeight) / 2; + left += + isActive + ? (maxTrackHeight - themeData.activeTrackHeight) / 2 + : (maxTrackHeight - themeData.inactiveTrackHeight) / 2; } - final double right = left + + final double right = + left + (isActive == null ? maxTrackHeight : (isActive @@ -57,74 +68,100 @@ class SfTrackShape { final double top = offset.dy + maxRadius; final double bottom = top + parentBox.size.height - (2 * maxRadius); return Rect.fromLTRB( - math.min(left, right), top, math.max(left, right), bottom); + math.min(left, right), + top, + math.max(left, right), + bottom, + ); } else { final double left = offset.dx + maxRadius; double top = offset.dy; if (isActive != null) { - top += isActive - ? (maxTrackHeight - themeData.activeTrackHeight) / 2 - : (maxTrackHeight - themeData.inactiveTrackHeight) / 2; + top += + isActive + ? (maxTrackHeight - themeData.activeTrackHeight) / 2 + : (maxTrackHeight - themeData.inactiveTrackHeight) / 2; } final double right = left + parentBox.size.width - (2 * maxRadius); - final double bottom = top + + final double bottom = + top + (isActive == null ? maxTrackHeight : (isActive ? themeData.activeTrackHeight : themeData.inactiveTrackHeight)); return Rect.fromLTRB( - math.min(left, right), top, math.max(left, right), bottom); + math.min(left, right), + top, + math.max(left, right), + bottom, + ); } } /// Paints the track based on the values passed to it. - void paint(PaintingContext context, Offset offset, Offset? thumbCenter, - Offset? startThumbCenter, Offset? endThumbCenter, - {required RenderBox parentBox, - required SfSliderThemeData themeData, - SfRangeValues? currentValues, - dynamic currentValue, - required Animation enableAnimation, - required Paint? inactivePaint, - required Paint? activePaint, - required TextDirection textDirection}) { + void paint( + PaintingContext context, + Offset offset, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, { + required RenderBox parentBox, + required SfSliderThemeData themeData, + SfRangeValues? currentValues, + dynamic currentValue, + required Animation enableAnimation, + required Paint? inactivePaint, + required Paint? activePaint, + required TextDirection textDirection, + }) { final Radius radius = Radius.circular(themeData.trackCornerRadius!); - final Rect inactiveTrackRect = - getPreferredRect(parentBox, themeData, offset, isActive: false); - final Rect activeTrackRect = - getPreferredRect(parentBox, themeData, offset, isActive: true); + final Rect inactiveTrackRect = getPreferredRect( + parentBox, + themeData, + offset, + isActive: false, + ); + final Rect activeTrackRect = getPreferredRect( + parentBox, + themeData, + offset, + isActive: true, + ); if (inactivePaint == null) { inactivePaint = Paint(); final ColorTween inactiveTrackColorTween = ColorTween( - begin: themeData.disabledInactiveTrackColor, - end: themeData.inactiveTrackColor); + begin: themeData.disabledInactiveTrackColor, + end: themeData.inactiveTrackColor, + ); inactivePaint.color = inactiveTrackColorTween.evaluate(enableAnimation)!; } if (activePaint == null) { activePaint = Paint(); final ColorTween activeTrackColorTween = ColorTween( - begin: themeData.disabledActiveTrackColor, - end: themeData.activeTrackColor); + begin: themeData.disabledActiveTrackColor, + end: themeData.activeTrackColor, + ); activePaint.color = activeTrackColorTween.evaluate(enableAnimation)!; } _drawTrackRect( - textDirection, - thumbCenter, - startThumbCenter, - endThumbCenter, - activePaint, - inactivePaint, - inactiveTrackRect, - radius, - context, - activeTrackRect, - // ignore: avoid_as - isVertical: _isVertical(parentBox as RenderBaseSlider), - isInversed: parentBox.isInversed); + textDirection, + thumbCenter, + startThumbCenter, + endThumbCenter, + activePaint, + inactivePaint, + inactiveTrackRect, + radius, + context, + activeTrackRect, + // ignore: avoid_as + isVertical: _isVertical(parentBox as RenderBaseSlider), + isInversed: parentBox.isInversed, + ); } void _drawTrackRect( @@ -175,57 +212,98 @@ class SfTrackShape { if (leftThumbCenter != null && rightThumbCenter != null) { // Drawing range slider track. - _drawRangeSliderTrack(inactiveTrackRect, leftThumbCenter, radius, context, - inactivePaint, activeTrackRect, rightThumbCenter, activePaint, - isVertical: isVertical); + _drawRangeSliderTrack( + inactiveTrackRect, + leftThumbCenter, + radius, + context, + inactivePaint, + activeTrackRect, + rightThumbCenter, + activePaint, + isVertical: isVertical, + ); } else { // Drawing slider track. - _drawSliderTrack(leftTrackRect!, thumbCenter!, radius, context, - leftTrackPaint!, rightTrackRect!, rightTrackPaint!, - isVertical: isVertical); + _drawSliderTrack( + leftTrackRect!, + thumbCenter!, + radius, + context, + leftTrackPaint!, + rightTrackRect!, + rightTrackPaint!, + isVertical: isVertical, + ); } } void _drawSliderTrack( - Rect activeTrackRect, - Offset thumbCenter, - Radius radius, - PaintingContext context, - Paint activePaint, - Rect inactiveTrackRect, - Paint inactivePaint, - {required bool isVertical}) { + Rect activeTrackRect, + Offset thumbCenter, + Radius radius, + PaintingContext context, + Paint activePaint, + Rect inactiveTrackRect, + Paint inactivePaint, { + required bool isVertical, + }) { RRect inactiveTrackRRect; if (!isVertical) { // Drawing active track. - Rect trackRect = Rect.fromLTRB(activeTrackRect.left, activeTrackRect.top, - thumbCenter.dx, activeTrackRect.bottom); - final RRect activeTrackRRect = RRect.fromRectAndCorners(trackRect, - topLeft: radius, bottomLeft: radius); + Rect trackRect = Rect.fromLTRB( + activeTrackRect.left, + activeTrackRect.top, + thumbCenter.dx, + activeTrackRect.bottom, + ); + final RRect activeTrackRRect = RRect.fromRectAndCorners( + trackRect, + topLeft: radius, + bottomLeft: radius, + ); context.canvas.drawRRect(activeTrackRRect, activePaint); // Drawing inactive track. trackRect = Rect.fromLTRB( - thumbCenter.dx, - inactiveTrackRect.top, - inactiveTrackRect.width + inactiveTrackRect.left, - inactiveTrackRect.bottom); - inactiveTrackRRect = RRect.fromRectAndCorners(trackRect, - topRight: radius, bottomRight: radius); + thumbCenter.dx, + inactiveTrackRect.top, + inactiveTrackRect.width + inactiveTrackRect.left, + inactiveTrackRect.bottom, + ); + inactiveTrackRRect = RRect.fromRectAndCorners( + trackRect, + topRight: radius, + bottomRight: radius, + ); context.canvas.drawRRect(inactiveTrackRRect, inactivePaint); } else { - Rect trackRect = Rect.fromLTRB(activeTrackRect.left, thumbCenter.dy, - activeTrackRect.right, activeTrackRect.bottom); - final RRect activeTrackRRect = RRect.fromRectAndCorners(trackRect, - bottomRight: radius, bottomLeft: radius); + Rect trackRect = Rect.fromLTRB( + activeTrackRect.left, + thumbCenter.dy, + activeTrackRect.right, + activeTrackRect.bottom, + ); + final RRect activeTrackRRect = RRect.fromRectAndCorners( + trackRect, + bottomRight: radius, + bottomLeft: radius, + ); context.canvas.drawRRect(activeTrackRRect, activePaint); // Drawing inactive track. - trackRect = Rect.fromLTRB(inactiveTrackRect.left, inactiveTrackRect.top, - inactiveTrackRect.right, thumbCenter.dy); - inactiveTrackRRect = RRect.fromRectAndCorners(trackRect, - topLeft: radius, topRight: radius); + trackRect = Rect.fromLTRB( + inactiveTrackRect.left, + inactiveTrackRect.top, + inactiveTrackRect.right, + thumbCenter.dy, + ); + inactiveTrackRRect = RRect.fromRectAndCorners( + trackRect, + topLeft: radius, + topRight: radius, + ); context.canvas.drawRRect(inactiveTrackRRect, inactivePaint); } } @@ -244,47 +322,77 @@ class SfTrackShape { RRect inactiveTrackRRect; if (!isVertical) { // Drawing inactive track. - Rect trackRect = Rect.fromLTRB(inactiveTrackRect.left, - inactiveTrackRect.top, startThumbCenter.dx, inactiveTrackRect.bottom); - inactiveTrackRRect = RRect.fromRectAndCorners(trackRect, - topLeft: radius, bottomLeft: radius); + Rect trackRect = Rect.fromLTRB( + inactiveTrackRect.left, + inactiveTrackRect.top, + startThumbCenter.dx, + inactiveTrackRect.bottom, + ); + inactiveTrackRRect = RRect.fromRectAndCorners( + trackRect, + topLeft: radius, + bottomLeft: radius, + ); context.canvas.drawRRect(inactiveTrackRRect, inactivePaint); // Drawing active track. - final Rect activeTrackRRect = Rect.fromLTRB(startThumbCenter.dx, - activeTrackRect.top, endThumbCenter.dx, activeTrackRect.bottom); + final Rect activeTrackRRect = Rect.fromLTRB( + startThumbCenter.dx, + activeTrackRect.top, + endThumbCenter.dx, + activeTrackRect.bottom, + ); context.canvas.drawRect(activeTrackRRect, activePaint); // Drawing inactive track. trackRect = Rect.fromLTRB( - endThumbCenter.dx, - inactiveTrackRect.top, - inactiveTrackRect.width + inactiveTrackRect.left, - inactiveTrackRect.bottom); - inactiveTrackRRect = RRect.fromRectAndCorners(trackRect, - topRight: radius, bottomRight: radius); + endThumbCenter.dx, + inactiveTrackRect.top, + inactiveTrackRect.width + inactiveTrackRect.left, + inactiveTrackRect.bottom, + ); + inactiveTrackRRect = RRect.fromRectAndCorners( + trackRect, + topRight: radius, + bottomRight: radius, + ); context.canvas.drawRRect(inactiveTrackRRect, inactivePaint); } else { // Drawing inactive track Rect trackRect = Rect.fromLTRB( - inactiveTrackRect.left, - startThumbCenter.dy, - inactiveTrackRect.right, - inactiveTrackRect.bottom); - inactiveTrackRRect = RRect.fromRectAndCorners(trackRect, - bottomLeft: radius, bottomRight: radius); + inactiveTrackRect.left, + startThumbCenter.dy, + inactiveTrackRect.right, + inactiveTrackRect.bottom, + ); + inactiveTrackRRect = RRect.fromRectAndCorners( + trackRect, + bottomLeft: radius, + bottomRight: radius, + ); context.canvas.drawRRect(inactiveTrackRRect, inactivePaint); // Drawing active track. - final Rect activeTrackRRect = Rect.fromLTRB(activeTrackRect.left, - startThumbCenter.dy, activeTrackRect.right, endThumbCenter.dy); + final Rect activeTrackRRect = Rect.fromLTRB( + activeTrackRect.left, + startThumbCenter.dy, + activeTrackRect.right, + endThumbCenter.dy, + ); context.canvas.drawRect(activeTrackRRect, activePaint); // Drawing inactive track. - trackRect = Rect.fromLTRB(inactiveTrackRect.left, inactiveTrackRect.top, - inactiveTrackRect.right, endThumbCenter.dy); - inactiveTrackRRect = RRect.fromRectAndCorners(trackRect, - topLeft: radius, topRight: radius); + trackRect = Rect.fromLTRB( + inactiveTrackRect.left, + inactiveTrackRect.top, + inactiveTrackRect.right, + endThumbCenter.dy, + ); + inactiveTrackRRect = RRect.fromRectAndCorners( + trackRect, + topLeft: radius, + topRight: radius, + ); context.canvas.drawRRect(inactiveTrackRRect, inactivePaint); } } @@ -306,18 +414,22 @@ class SfThumbShape { } /// Paints the thumb based on the values passed to it. - void paint(PaintingContext context, Offset center, - {required RenderBox parentBox, - required RenderBox? child, - required SfSliderThemeData themeData, - SfRangeValues? currentValues, - dynamic currentValue, - required Paint? paint, - required Animation enableAnimation, - required TextDirection textDirection, - required SfThumb? thumb}) { + void paint( + PaintingContext context, + Offset center, { + required RenderBox parentBox, + required RenderBox? child, + required SfSliderThemeData themeData, + SfRangeValues? currentValues, + dynamic currentValue, + required Paint? paint, + required Animation enableAnimation, + required TextDirection textDirection, + required SfThumb? thumb, + }) { final double radius = getPreferredSize(themeData).width / 2; - final bool hasThumbStroke = themeData.thumbStrokeColor != null && + final bool hasThumbStroke = + themeData.thumbStrokeColor != null && themeData.thumbStrokeColor != Colors.transparent && themeData.thumbStrokeWidth != null && themeData.thumbStrokeWidth! > 0; @@ -329,12 +441,13 @@ class SfThumbShape { final Path path = Path(); final bool isThumbActive = (parentRenderBox.activeThumb == thumb || thumb == null) && - parentRenderBox.currentPointerType != null && - parentRenderBox.currentPointerType != PointerType.up; + parentRenderBox.currentPointerType != null && + parentRenderBox.currentPointerType != PointerType.up; path.addOval(Rect.fromCircle(center: center, radius: radius)); - final double thumbElevation = isThumbActive - ? parentRenderBox.thumbElevationTween.evaluate(enableAnimation) - : defaultElevation; + final double thumbElevation = + isThumbActive + ? parentRenderBox.thumbElevationTween.evaluate(enableAnimation) + : defaultElevation; context.canvas.drawShadow(path, shadowColor, thumbElevation, true); } @@ -345,46 +458,55 @@ class SfThumbShape { themeData.thumbColor != Colors.transparent && themeData.overlappingThumbStrokeColor != null) { context.canvas.drawCircle( - center, - radius, - Paint() - ..color = themeData.overlappingThumbStrokeColor! - ..style = PaintingStyle.stroke - ..isAntiAlias = true - ..strokeWidth = 1.0); + center, + radius, + Paint() + ..color = themeData.overlappingThumbStrokeColor! + ..style = PaintingStyle.stroke + ..isAntiAlias = true + ..strokeWidth = 1.0, + ); } if (paint == null) { paint = Paint(); paint.isAntiAlias = true; - paint.color = ColorTween( - begin: themeData.disabledThumbColor, end: themeData.thumbColor) - .evaluate(enableAnimation)!; + paint.color = + ColorTween( + begin: themeData.disabledThumbColor, + end: themeData.thumbColor, + ).evaluate(enableAnimation)!; } context.canvas.drawCircle(center, radius, paint); if (child != null) { context.paintChild( - child, - Offset(center.dx - (child.size.width) / 2, - center.dy - (child.size.height) / 2)); + child, + Offset( + center.dx - (child.size.width) / 2, + center.dy - (child.size.height) / 2, + ), + ); } if (themeData.thumbStrokeColor != null && themeData.thumbStrokeWidth != null && themeData.thumbStrokeWidth! > 0) { - final Paint strokePaint = Paint() - ..color = themeData.thumbStrokeColor! - ..style = PaintingStyle.stroke - ..strokeWidth = themeData.thumbStrokeWidth! > radius - ? radius - : themeData.thumbStrokeWidth!; + final Paint strokePaint = + Paint() + ..color = themeData.thumbStrokeColor! + ..style = PaintingStyle.stroke + ..strokeWidth = + themeData.thumbStrokeWidth! > radius + ? radius + : themeData.thumbStrokeWidth!; context.canvas.drawCircle( - center, - themeData.thumbStrokeWidth! > radius - ? radius / 2 - : radius - themeData.thumbStrokeWidth! / 2, - strokePaint); + center, + themeData.thumbStrokeWidth! > radius + ? radius / 2 + : radius - themeData.thumbStrokeWidth! / 2, + strokePaint, + ); } } } @@ -401,23 +523,30 @@ class SfDividerShape { /// Returns the size based on the values passed to it. Size getPreferredSize(SfSliderThemeData themeData, {bool? isActive}) { - return Size.fromRadius(isActive != null - ? (isActive - ? themeData.activeDividerRadius! - : themeData.inactiveDividerRadius!) - : 0); + return Size.fromRadius( + isActive != null + ? (isActive + ? themeData.activeDividerRadius! + : themeData.inactiveDividerRadius!) + : 0, + ); } /// Paints the dividers based on the values passed to it. - void paint(PaintingContext context, Offset center, Offset? thumbCenter, - Offset? startThumbCenter, Offset? endThumbCenter, - {required RenderBox parentBox, - required SfSliderThemeData themeData, - SfRangeValues? currentValues, - dynamic currentValue, - required Paint? paint, - required Animation enableAnimation, - required TextDirection textDirection}) { + void paint( + PaintingContext context, + Offset center, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, { + required RenderBox parentBox, + required SfSliderThemeData themeData, + SfRangeValues? currentValues, + dynamic currentValue, + required Paint? paint, + required Animation enableAnimation, + required TextDirection textDirection, + }) { late bool isActive; final bool isVertical = _isVertical(parentBox as RenderBaseSlider); @@ -426,10 +555,12 @@ class SfDividerShape { // two thumbs for finding active range. if (startThumbCenter != null) { if (!parentBox.isInversed) { - isActive = center.dx >= startThumbCenter.dx && + isActive = + center.dx >= startThumbCenter.dx && center.dx <= endThumbCenter!.dx; } else { - isActive = center.dx >= endThumbCenter!.dx && + isActive = + center.dx >= endThumbCenter!.dx && center.dx <= startThumbCenter.dx; } } else { @@ -444,10 +575,12 @@ class SfDividerShape { // two thumbs for finding active range. if (startThumbCenter != null) { if (!parentBox.isInversed) { - isActive = center.dy <= startThumbCenter.dy && + isActive = + center.dy <= startThumbCenter.dy && center.dy >= endThumbCenter!.dy; } else { - isActive = center.dy >= startThumbCenter.dy && + isActive = + center.dy >= startThumbCenter.dy && center.dy <= endThumbCenter!.dy; } } else { @@ -461,12 +594,14 @@ class SfDividerShape { if (paint == null) { paint = Paint(); - final Color begin = isActive - ? themeData.disabledActiveDividerColor! - : themeData.disabledInactiveDividerColor!; - final Color end = isActive - ? themeData.activeDividerColor! - : themeData.inactiveDividerColor!; + final Color begin = + isActive + ? themeData.disabledActiveDividerColor! + : themeData.disabledInactiveDividerColor!; + final Color end = + isActive + ? themeData.activeDividerColor! + : themeData.inactiveDividerColor!; paint.color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; @@ -476,28 +611,32 @@ class SfDividerShape { getPreferredSize(themeData, isActive: isActive).width / 2; context.canvas.drawCircle(center, dividerRadius, paint); - final double? dividerStrokeWidth = isActive - ? themeData.activeDividerStrokeWidth - : themeData.inactiveDividerStrokeWidth; - final Color? dividerStrokeColor = isActive - ? themeData.activeDividerStrokeColor - : themeData.inactiveDividerStrokeColor; + final double? dividerStrokeWidth = + isActive + ? themeData.activeDividerStrokeWidth + : themeData.inactiveDividerStrokeWidth; + final Color? dividerStrokeColor = + isActive + ? themeData.activeDividerStrokeColor + : themeData.inactiveDividerStrokeColor; if (dividerStrokeColor != null && dividerStrokeWidth != null && dividerStrokeWidth > 0) { // Drawing divider stroke context.canvas.drawCircle( - center, - dividerStrokeWidth > dividerRadius - ? dividerRadius / 2 - : dividerRadius - dividerStrokeWidth / 2, - paint - ..color = dividerStrokeColor - ..style = PaintingStyle.stroke - ..strokeWidth = dividerStrokeWidth > dividerRadius - ? dividerRadius - : dividerStrokeWidth); + center, + dividerStrokeWidth > dividerRadius + ? dividerRadius / 2 + : dividerRadius - dividerStrokeWidth / 2, + paint + ..color = dividerStrokeColor + ..style = PaintingStyle.stroke + ..strokeWidth = + dividerStrokeWidth > dividerRadius + ? dividerRadius + : dividerStrokeWidth, + ); } } } @@ -514,14 +653,17 @@ class SfOverlayShape { } /// Paints the overlay based on the values passed to it. - void paint(PaintingContext context, Offset center, - {required RenderBox parentBox, - required SfSliderThemeData themeData, - SfRangeValues? currentValues, - dynamic currentValue, - required Paint? paint, - required Animation animation, - required SfThumb? thumb}) { + void paint( + PaintingContext context, + Offset center, { + required RenderBox parentBox, + required SfSliderThemeData themeData, + SfRangeValues? currentValues, + dynamic currentValue, + required Paint? paint, + required Animation animation, + required SfThumb? thumb, + }) { final double radius = getPreferredSize(themeData).width / 2; final Tween tween = Tween(begin: 0.0, end: radius); @@ -549,14 +691,19 @@ class SfTickShape { } /// Paints the major ticks based on the values passed to it. - void paint(PaintingContext context, Offset offset, Offset? thumbCenter, - Offset? startThumbCenter, Offset? endThumbCenter, - {required RenderBox parentBox, - required SfSliderThemeData themeData, - SfRangeValues? currentValues, - dynamic currentValue, - required Animation enableAnimation, - required TextDirection textDirection}) { + void paint( + PaintingContext context, + Offset offset, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, { + required RenderBox parentBox, + required SfSliderThemeData themeData, + SfRangeValues? currentValues, + dynamic currentValue, + required Animation enableAnimation, + required TextDirection textDirection, + }) { bool isInactive = false; final Size tickSize = getPreferredSize(themeData); final bool isVertical = _isVertical(parentBox as RenderBaseSlider); @@ -599,21 +746,31 @@ class SfTickShape { } } - final Color begin = isInactive - ? themeData.disabledInactiveTickColor! - : themeData.disabledActiveTickColor!; + final Color begin = + isInactive + ? themeData.disabledInactiveTickColor! + : themeData.disabledActiveTickColor!; final Color end = isInactive ? themeData.inactiveTickColor! : themeData.activeTickColor!; - final Paint paint = Paint() - ..isAntiAlias = true - ..strokeWidth = _isVertical(parentBox) ? tickSize.height : tickSize.width - ..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; + final Paint paint = + Paint() + ..isAntiAlias = true + ..strokeWidth = + _isVertical(parentBox) ? tickSize.height : tickSize.width + ..color = + ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; if (_isVertical(parentBox)) { context.canvas.drawLine( - offset, Offset(offset.dx + tickSize.width, offset.dy), paint); + offset, + Offset(offset.dx + tickSize.width, offset.dy), + paint, + ); } else { context.canvas.drawLine( - offset, Offset(offset.dx, offset.dy + tickSize.height), paint); + offset, + Offset(offset.dx, offset.dy + tickSize.height), + paint, + ); } } } @@ -624,13 +781,17 @@ abstract class SfTooltipShape { const SfTooltipShape(); /// Draws the tooltip based on the values passed in the arguments. - void paint(PaintingContext context, Offset thumbCenter, Offset offset, - TextPainter textPainter, - {required RenderBox parentBox, - required SfSliderThemeData sliderThemeData, - required Paint paint, - required Animation animation, - required Rect trackRect}); + void paint( + PaintingContext context, + Offset thumbCenter, + Offset offset, + TextPainter textPainter, { + required RenderBox parentBox, + required SfSliderThemeData sliderThemeData, + required Paint paint, + required Animation animation, + required Rect trackRect, + }); } /// Base class for [SfSlider], [SfRangeSlider] and [SfRangeSelector] minor tick @@ -644,14 +805,19 @@ class SfMinorTickShape extends SfTickShape { } @override - void paint(PaintingContext context, Offset offset, Offset? thumbCenter, - Offset? startThumbCenter, Offset? endThumbCenter, - {required RenderBox parentBox, - SfRangeValues? currentValues, - dynamic currentValue, - required SfSliderThemeData themeData, - required Animation enableAnimation, - required TextDirection textDirection}) { + void paint( + PaintingContext context, + Offset offset, + Offset? thumbCenter, + Offset? startThumbCenter, + Offset? endThumbCenter, { + required RenderBox parentBox, + SfRangeValues? currentValues, + dynamic currentValue, + required SfSliderThemeData themeData, + required Animation enableAnimation, + required TextDirection textDirection, + }) { bool isInactive; final Size minorTickSize = getPreferredSize(themeData); final bool isVertical = _isVertical(parentBox as RenderBaseSlider); @@ -694,23 +860,35 @@ class SfMinorTickShape extends SfTickShape { } } - final Color begin = isInactive - ? themeData.disabledInactiveMinorTickColor! - : themeData.disabledActiveMinorTickColor!; - final Color end = isInactive - ? themeData.inactiveMinorTickColor! - : themeData.activeMinorTickColor!; - final Paint paint = Paint() - ..isAntiAlias = true - ..strokeWidth = - _isVertical(parentBox) ? minorTickSize.height : minorTickSize.width - ..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; + final Color begin = + isInactive + ? themeData.disabledInactiveMinorTickColor! + : themeData.disabledActiveMinorTickColor!; + final Color end = + isInactive + ? themeData.inactiveMinorTickColor! + : themeData.activeMinorTickColor!; + final Paint paint = + Paint() + ..isAntiAlias = true + ..strokeWidth = + _isVertical(parentBox) + ? minorTickSize.height + : minorTickSize.width + ..color = + ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; if (_isVertical(parentBox)) { context.canvas.drawLine( - offset, Offset(offset.dx + minorTickSize.width, offset.dy), paint); + offset, + Offset(offset.dx + minorTickSize.width, offset.dy), + paint, + ); } else { context.canvas.drawLine( - offset, Offset(offset.dx, offset.dy + minorTickSize.height), paint); + offset, + Offset(offset.dx, offset.dy + minorTickSize.height), + paint, + ); } } } @@ -726,23 +904,24 @@ class SfPaddleTooltipShape extends SfTooltipShape { } void _drawPaddleTooltip( - RenderBox parentBox, - TextPainter textPainter, - double minPaddleTopCircleRadius, - double neckDifference, - SfSliderThemeData sliderThemeData, - double defaultThumbRadius, - double minBottomNeckRadius, - double textPadding, - Offset offset, - double moveNeckValue, - Offset thumbCenter, - Rect trackRect, - PaintingContext context, - Animation animation, - Paint? paint) { - final double thumbRadius = (parentBox as RenderBaseSlider) - .thumbShape + RenderBox parentBox, + TextPainter textPainter, + double minPaddleTopCircleRadius, + double neckDifference, + SfSliderThemeData sliderThemeData, + double defaultThumbRadius, + double minBottomNeckRadius, + double textPadding, + Offset offset, + double moveNeckValue, + Offset thumbCenter, + Rect trackRect, + PaintingContext context, + Animation animation, + Paint? paint, + ) { + final double thumbRadius = + (parentBox as RenderBaseSlider).thumbShape .getPreferredSize(sliderThemeData) .width / 2; @@ -751,64 +930,76 @@ class SfPaddleTooltipShape extends SfTooltipShape { ? textPainter.height : minPaddleTopCircleRadius; final double topNeckRadius = paddleTopCircleRadius - neckDifference; - final double bottomNeckRadius = thumbRadius > defaultThumbRadius - ? thumbRadius - neckDifference * 2 - : minBottomNeckRadius; + final double bottomNeckRadius = + thumbRadius > defaultThumbRadius + ? thumbRadius - neckDifference * 2 + : minBottomNeckRadius; final double halfTextWidth = textPainter.width / 2 + textPadding; - final double paddleTopCircleX = halfTextWidth > paddleTopCircleRadius - ? halfTextWidth - paddleTopCircleRadius - : 0; + final double paddleTopCircleX = + halfTextWidth > paddleTopCircleRadius + ? halfTextWidth - paddleTopCircleRadius + : 0; final double minPaddleWidth = paddleTopCircleRadius + topNeckRadius + neckDifference / 2; final Offset topNeckCenter = Offset( - topNeckRadius + neckDifference / 2, -offset.dy - bottomNeckRadius); + topNeckRadius + neckDifference / 2, + -offset.dy - bottomNeckRadius, + ); final Offset paddleTopCircleCenter = Offset( - paddleTopCircleX, - -paddleTopCircleRadius * (1.0 - moveNeckValue) - - topNeckRadius - - offset.dy - - bottomNeckRadius); + paddleTopCircleX, + -paddleTopCircleRadius * (1.0 - moveNeckValue) - + topNeckRadius - + offset.dy - + bottomNeckRadius, + ); final Offset bottomNeckCenter = Offset( - bottomNeckRadius + neckDifference / 2, - -thumbRadius - bottomNeckRadius * (1.0 - moveNeckValue)); + bottomNeckRadius + neckDifference / 2, + -thumbRadius - bottomNeckRadius * (1.0 - moveNeckValue), + ); final double leftShiftWidth = thumbCenter.dx - halfTextWidth; double shiftPaddleWidth = leftShiftWidth < trackRect.left ? leftShiftWidth : 0; final double rightShiftWidth = thumbCenter.dx + halfTextWidth; - shiftPaddleWidth = rightShiftWidth > trackRect.right - ? rightShiftWidth - trackRect.right - : shiftPaddleWidth; + shiftPaddleWidth = + rightShiftWidth > trackRect.right + ? rightShiftWidth - trackRect.right + : shiftPaddleWidth; final double leftPaddleWidth = paddleTopCircleRadius + paddleTopCircleCenter.dx + shiftPaddleWidth; final double rightPaddleWidth = paddleTopCircleRadius + paddleTopCircleCenter.dx - shiftPaddleWidth; - final double moveLeftTopNeckY = leftPaddleWidth > paddleTopCircleRadius - ? leftPaddleWidth < minPaddleWidth - ? (leftPaddleWidth - topNeckRadius) * moveNeckValue - : paddleTopCircleRadius * moveNeckValue - : 0; - final double moveLeftTopNeckAngle = leftPaddleWidth > paddleTopCircleRadius - ? leftPaddleWidth < minPaddleWidth - ? moveLeftTopNeckY * math.pi / 180 - : 30 * math.pi / 180 - : 0; - final double moveRightTopNeckY = rightPaddleWidth > paddleTopCircleRadius - ? rightPaddleWidth < minPaddleWidth - ? (rightPaddleWidth - topNeckRadius) * moveNeckValue - : paddleTopCircleRadius * moveNeckValue - : 0; + final double moveLeftTopNeckY = + leftPaddleWidth > paddleTopCircleRadius + ? leftPaddleWidth < minPaddleWidth + ? (leftPaddleWidth - topNeckRadius) * moveNeckValue + : paddleTopCircleRadius * moveNeckValue + : 0; + final double moveLeftTopNeckAngle = + leftPaddleWidth > paddleTopCircleRadius + ? leftPaddleWidth < minPaddleWidth + ? moveLeftTopNeckY * math.pi / 180 + : 30 * math.pi / 180 + : 0; + final double moveRightTopNeckY = + rightPaddleWidth > paddleTopCircleRadius + ? rightPaddleWidth < minPaddleWidth + ? (rightPaddleWidth - topNeckRadius) * moveNeckValue + : paddleTopCircleRadius * moveNeckValue + : 0; final double moveRightTopNeckAngle = rightPaddleWidth > paddleTopCircleRadius ? rightPaddleWidth < minPaddleWidth ? moveRightTopNeckY * math.pi / 180 : 30 * math.pi / 180 : 0; - final double leftNeckStretchValue = leftPaddleWidth < minPaddleWidth - ? (1.0 - (leftPaddleWidth / minPaddleWidth)) - : 0; - final double rightNeckStretchValue = rightPaddleWidth < minPaddleWidth - ? (1.0 - (rightPaddleWidth / minPaddleWidth)) - : 0; + final double leftNeckStretchValue = + leftPaddleWidth < minPaddleWidth + ? (1.0 - (leftPaddleWidth / minPaddleWidth)) + : 0; + final double rightNeckStretchValue = + rightPaddleWidth < minPaddleWidth + ? (1.0 - (rightPaddleWidth / minPaddleWidth)) + : 0; final double adjustPaddleCircleLeftArcAngle = shiftPaddleWidth < 0 && leftPaddleWidth < minPaddleWidth ? (leftNeckStretchValue * (math.pi / 2 + moveLeftTopNeckAngle)) @@ -823,24 +1014,25 @@ class SfPaddleTooltipShape extends SfTooltipShape { adjustPaddleCircleRightArcAngle * (1.0 - moveNeckValue); final Path path = _getPaddleTooltipPath( - neckDifference, - topNeckCenter, - moveRightTopNeckY, - topNeckRadius, - moveRightTopNeckAngle, - adjustRightNeckArcAngle, - paddleTopCircleCenter, - shiftPaddleWidth, - paddleTopCircleRadius, - adjustPaddleCircleRightArcAngle, - adjustPaddleCircleLeftArcAngle, - moveLeftTopNeckY, - moveLeftTopNeckAngle, - adjustLeftNeckArcAngle, - bottomNeckCenter, - bottomNeckRadius, - thumbRadius, - sliderThemeData); + neckDifference, + topNeckCenter, + moveRightTopNeckY, + topNeckRadius, + moveRightTopNeckAngle, + adjustRightNeckArcAngle, + paddleTopCircleCenter, + shiftPaddleWidth, + paddleTopCircleRadius, + adjustPaddleCircleRightArcAngle, + adjustPaddleCircleLeftArcAngle, + moveLeftTopNeckY, + moveLeftTopNeckAngle, + adjustLeftNeckArcAngle, + bottomNeckCenter, + bottomNeckRadius, + thumbRadius, + sliderThemeData, + ); context.canvas.save(); context.canvas.translate(thumbCenter.dx, thumbCenter.dy); @@ -864,113 +1056,145 @@ class SfPaddleTooltipShape extends SfTooltipShape { context.canvas.drawPath(path, strokePaint); context.canvas.drawPath(path, paint!); textPainter.paint( - context.canvas, - Offset(-textPainter.width / 2 - shiftPaddleWidth, - paddleTopCircleCenter.dy - textPainter.height / 2)); + context.canvas, + Offset( + -textPainter.width / 2 - shiftPaddleWidth, + paddleTopCircleCenter.dy - textPainter.height / 2, + ), + ); context.canvas.restore(); } Path _getPaddleTooltipPath( - double neckDifference, - Offset topNeckCenter, - double moveRightTopNeckY, - double topNeckRadius, - double moveRightTopNeckAngle, - double adjustRightNeckArcAngle, - Offset paddleTopCircleCenter, - double shiftPaddleWidth, - double paddleTopCircleRadius, - double adjustPaddleCircleRightArcAngle, - double adjustPaddleCircleLeftArcAngle, - double moveLeftTopNeckY, - double moveLeftTopNeckAngle, - double adjustLeftNeckArcAngle, - Offset bottomNeckCenter, - double bottomNeckRadius, - double thumbRadius, - SfSliderThemeData sliderThemeData) { + double neckDifference, + Offset topNeckCenter, + double moveRightTopNeckY, + double topNeckRadius, + double moveRightTopNeckAngle, + double adjustRightNeckArcAngle, + Offset paddleTopCircleCenter, + double shiftPaddleWidth, + double paddleTopCircleRadius, + double adjustPaddleCircleRightArcAngle, + double adjustPaddleCircleLeftArcAngle, + double moveLeftTopNeckY, + double moveLeftTopNeckAngle, + double adjustLeftNeckArcAngle, + Offset bottomNeckCenter, + double bottomNeckRadius, + double thumbRadius, + SfSliderThemeData sliderThemeData, + ) { final Path path = Path(); path.moveTo( - neckDifference / 2, topNeckCenter.dy + topNeckRadius * moveNeckValue); + neckDifference / 2, + topNeckCenter.dy + topNeckRadius * moveNeckValue, + ); // Drawn top paddle shape. path.arcTo( - Rect.fromCircle( - center: - Offset(topNeckCenter.dx, topNeckCenter.dy + moveRightTopNeckY), - radius: topNeckRadius), - math.pi, - math.pi / 3 + moveRightTopNeckAngle - adjustRightNeckArcAngle, - false); + Rect.fromCircle( + center: Offset(topNeckCenter.dx, topNeckCenter.dy + moveRightTopNeckY), + radius: topNeckRadius, + ), + math.pi, + math.pi / 3 + moveRightTopNeckAngle - adjustRightNeckArcAngle, + false, + ); path.arcTo( - Rect.fromCircle( - center: Offset(paddleTopCircleCenter.dx - shiftPaddleWidth, - paddleTopCircleCenter.dy), - radius: paddleTopCircleRadius), - math.pi / 2 - adjustPaddleCircleRightArcAngle, - -math.pi + adjustPaddleCircleRightArcAngle, - false); + Rect.fromCircle( + center: Offset( + paddleTopCircleCenter.dx - shiftPaddleWidth, + paddleTopCircleCenter.dy, + ), + radius: paddleTopCircleRadius, + ), + math.pi / 2 - adjustPaddleCircleRightArcAngle, + -math.pi + adjustPaddleCircleRightArcAngle, + false, + ); path.arcTo( - Rect.fromCircle( - center: Offset(-paddleTopCircleCenter.dx - shiftPaddleWidth, - paddleTopCircleCenter.dy), - radius: paddleTopCircleRadius), - 3 * math.pi / 2, - -math.pi + adjustPaddleCircleLeftArcAngle, - false); + Rect.fromCircle( + center: Offset( + -paddleTopCircleCenter.dx - shiftPaddleWidth, + paddleTopCircleCenter.dy, + ), + radius: paddleTopCircleRadius, + ), + 3 * math.pi / 2, + -math.pi + adjustPaddleCircleLeftArcAngle, + false, + ); path.arcTo( - Rect.fromCircle( - center: - Offset(-topNeckCenter.dx, topNeckCenter.dy + moveLeftTopNeckY), - radius: topNeckRadius), - 5 * math.pi / 3 - moveLeftTopNeckAngle + adjustLeftNeckArcAngle, - math.pi / 3 + moveLeftTopNeckAngle - adjustLeftNeckArcAngle, - false); + Rect.fromCircle( + center: Offset(-topNeckCenter.dx, topNeckCenter.dy + moveLeftTopNeckY), + radius: topNeckRadius, + ), + 5 * math.pi / 3 - moveLeftTopNeckAngle + adjustLeftNeckArcAngle, + math.pi / 3 + moveLeftTopNeckAngle - adjustLeftNeckArcAngle, + false, + ); // Drawn bottom thumb shape. path.arcTo( - Rect.fromCircle( - center: Offset(-bottomNeckCenter.dx, bottomNeckCenter.dy), - radius: bottomNeckRadius), - 0.0, - math.pi / 3, - false); - path.arcTo(Rect.fromCircle(center: Offset.zero, radius: thumbRadius), - 3 * math.pi / 2, -math.pi, false); - path.arcTo(Rect.fromCircle(center: Offset.zero, radius: thumbRadius), - math.pi / 2, -math.pi, false); + Rect.fromCircle( + center: Offset(-bottomNeckCenter.dx, bottomNeckCenter.dy), + radius: bottomNeckRadius, + ), + 0.0, + math.pi / 3, + false, + ); path.arcTo( - Rect.fromCircle(center: bottomNeckCenter, radius: bottomNeckRadius), - 2 * math.pi / 3, - math.pi / 3, - false); + Rect.fromCircle(center: Offset.zero, radius: thumbRadius), + 3 * math.pi / 2, + -math.pi, + false, + ); + path.arcTo( + Rect.fromCircle(center: Offset.zero, radius: thumbRadius), + math.pi / 2, + -math.pi, + false, + ); + path.arcTo( + Rect.fromCircle(center: bottomNeckCenter, radius: bottomNeckRadius), + 2 * math.pi / 3, + math.pi / 3, + false, + ); return path; } /// Draws the tooltip based on the values passed in the arguments. @override - void paint(PaintingContext context, Offset thumbCenter, Offset offset, - TextPainter textPainter, - {required RenderBox parentBox, - required SfSliderThemeData sliderThemeData, - required Paint paint, - required Animation animation, - required Rect trackRect}) { + void paint( + PaintingContext context, + Offset thumbCenter, + Offset offset, + TextPainter textPainter, { + required RenderBox parentBox, + required SfSliderThemeData sliderThemeData, + required Paint paint, + required Animation animation, + required Rect trackRect, + }) { _drawPaddleTooltip( - parentBox, - textPainter, - minPaddleTopCircleRadius, - neckDifference, - sliderThemeData, - defaultThumbRadius, - minBottomNeckRadius, - textPadding, - offset, - moveNeckValue, - thumbCenter, - trackRect, - context, - animation, - paint); + parentBox, + textPainter, + minPaddleTopCircleRadius, + neckDifference, + sliderThemeData, + defaultThumbRadius, + minBottomNeckRadius, + textPadding, + offset, + moveNeckValue, + thumbCenter, + trackRect, + context, + animation, + paint, + ); } } @@ -993,8 +1217,13 @@ class SfRectangularTooltipShape extends SfTooltipShape { } Path _updateRectangularTooltipWidth( - Size textSize, double tooltipStartY, Rect trackRect, double dx, - {required bool isVertical, bool? isLeftTooltip}) { + Size textSize, + double tooltipStartY, + Rect trackRect, + double dx, { + required bool isVertical, + bool? isLeftTooltip, + }) { final double dy = tooltipStartY + tooltipTriangleHeight; final double tooltipWidth = textSize.width < minTooltipWidth ? minTooltipWidth : textSize.width; @@ -1005,68 +1234,94 @@ class SfRectangularTooltipShape extends SfTooltipShape { const double halfTooltipTriangleWidth = tooltipTriangleWidth / 2; if (isVertical) { if (isLeftTooltip!) { - double topLineHeight = dx - halfTooltipHeight < trackRect.top - ? dx - trackRect.top - : halfTooltipHeight; + double topLineHeight = + dx - halfTooltipHeight < trackRect.top + ? dx - trackRect.top + : halfTooltipHeight; final double bottomLineHeight = dx + halfTooltipHeight > trackRect.bottom ? trackRect.bottom - dx : tooltipHeight - topLineHeight; - topLineHeight = bottomLineHeight < halfTooltipHeight - ? halfTooltipHeight - bottomLineHeight + topLineHeight - : topLineHeight; - return _getRectangularPath(tooltipStartY, topLineHeight, - halfTooltipTriangleWidth, dy, tooltipHeight, bottomLineHeight, - isVertical: isVertical, - toolTipWidth: tooltipWidth, - isLeftTooltip: isLeftTooltip); + topLineHeight = + bottomLineHeight < halfTooltipHeight + ? halfTooltipHeight - bottomLineHeight + topLineHeight + : topLineHeight; + return _getRectangularPath( + tooltipStartY, + topLineHeight, + halfTooltipTriangleWidth, + dy, + tooltipHeight, + bottomLineHeight, + isVertical: isVertical, + toolTipWidth: tooltipWidth, + isLeftTooltip: isLeftTooltip, + ); } else { - double topLineHeight = dx - halfTooltipHeight < trackRect.top - ? dx - trackRect.top - : halfTooltipHeight; + double topLineHeight = + dx - halfTooltipHeight < trackRect.top + ? dx - trackRect.top + : halfTooltipHeight; final double bottomLineHeight = dx + halfTooltipHeight > trackRect.bottom ? trackRect.bottom - dx : tooltipHeight - topLineHeight; - topLineHeight = bottomLineHeight < halfTooltipHeight - ? halfTooltipHeight - bottomLineHeight + topLineHeight - : topLineHeight; - return _getRectangularPath(tooltipStartY, topLineHeight, - halfTooltipTriangleWidth, dy, tooltipHeight, bottomLineHeight, - isVertical: isVertical, - toolTipWidth: tooltipWidth, - isLeftTooltip: isLeftTooltip); + topLineHeight = + bottomLineHeight < halfTooltipHeight + ? halfTooltipHeight - bottomLineHeight + topLineHeight + : topLineHeight; + return _getRectangularPath( + tooltipStartY, + topLineHeight, + halfTooltipTriangleWidth, + dy, + tooltipHeight, + bottomLineHeight, + isVertical: isVertical, + toolTipWidth: tooltipWidth, + isLeftTooltip: isLeftTooltip, + ); } } else { - double rightLineWidth = dx + halfTooltipWidth > trackRect.right - ? trackRect.right - dx - : halfTooltipWidth; - final double leftLineWidth = isVertical - ? tooltipWidth - rightLineWidth - : dx - halfTooltipWidth < trackRect.left + double rightLineWidth = + dx + halfTooltipWidth > trackRect.right + ? trackRect.right - dx + : halfTooltipWidth; + final double leftLineWidth = + isVertical + ? tooltipWidth - rightLineWidth + : dx - halfTooltipWidth < trackRect.left ? dx - trackRect.left : tooltipWidth - rightLineWidth; if (!isVertical) { - rightLineWidth = leftLineWidth < halfTooltipWidth - ? halfTooltipWidth - leftLineWidth + rightLineWidth - : rightLineWidth; + rightLineWidth = + leftLineWidth < halfTooltipWidth + ? halfTooltipWidth - leftLineWidth + rightLineWidth + : rightLineWidth; } - return _getRectangularPath(tooltipStartY, rightLineWidth, - halfTooltipTriangleWidth, dy, tooltipHeight, leftLineWidth, - isVertical: isVertical); + return _getRectangularPath( + tooltipStartY, + rightLineWidth, + halfTooltipTriangleWidth, + dy, + tooltipHeight, + leftLineWidth, + isVertical: isVertical, + ); } } Path _getRectangularPath( - double tooltipStartY, - double rightLineWidth, - double halfTooltipTriangleWidth, - double dy, - double tooltipHeight, - double leftLineWidth, - {required bool isVertical, - double? toolTipWidth, - bool? isLeftTooltip}) { + double tooltipStartY, + double rightLineWidth, + double halfTooltipTriangleWidth, + double dy, + double tooltipHeight, + double leftLineWidth, { + required bool isVertical, + double? toolTipWidth, + bool? isLeftTooltip, + }) { final Path path = Path(); if (isVertical && toolTipWidth != null) { if (isLeftTooltip!) { @@ -1074,29 +1329,33 @@ class SfRectangularTooltipShape extends SfTooltipShape { // / final bool canAdjustTooltipNose = rightLineWidth < halfTooltipTriangleWidth; - path.lineTo(-dy, - canAdjustTooltipNose ? -rightLineWidth : -halfTooltipTriangleWidth); + path.lineTo( + -dy, + canAdjustTooltipNose ? -rightLineWidth : -halfTooltipTriangleWidth, + ); // / // | if (!canAdjustTooltipNose) { path.lineTo(-dy, -rightLineWidth + cornerRadius / 2); } path.quadraticBezierTo( - -dy, - canAdjustTooltipNose - ? -rightLineWidth - : -rightLineWidth + cornerRadius / 2, - -dy - cornerRadius / 2, - -rightLineWidth); + -dy, + canAdjustTooltipNose + ? -rightLineWidth + : -rightLineWidth + cornerRadius / 2, + -dy - cornerRadius / 2, + -rightLineWidth, + ); // / // __________| path.lineTo(-dy - toolTipWidth + cornerRadius / 2, -rightLineWidth); path.quadraticBezierTo( - -dy - toolTipWidth + cornerRadius / 2, - -rightLineWidth, - -dy - toolTipWidth, - -rightLineWidth + cornerRadius / 2); + -dy - toolTipWidth + cornerRadius / 2, + -rightLineWidth, + -dy - toolTipWidth, + -rightLineWidth + cornerRadius / 2, + ); // | // | / // |__________| @@ -1119,8 +1378,12 @@ class SfRectangularTooltipShape extends SfTooltipShape { // | / // |__________| if (leftLineWidth > halfTooltipTriangleWidth) { - path.quadraticBezierTo(-dy - cornerRadius / 2, leftLineWidth, -dy, - leftLineWidth - cornerRadius / 2); + path.quadraticBezierTo( + -dy - cornerRadius / 2, + leftLineWidth, + -dy, + leftLineWidth - cornerRadius / 2, + ); path.lineTo(-dy, halfTooltipTriangleWidth); } // __________ @@ -1135,8 +1398,10 @@ class SfRectangularTooltipShape extends SfTooltipShape { // \ final bool canAdjustTooltipNose = rightLineWidth < halfTooltipTriangleWidth; - path.lineTo(dy, - canAdjustTooltipNose ? -rightLineWidth : -halfTooltipTriangleWidth); + path.lineTo( + dy, + canAdjustTooltipNose ? -rightLineWidth : -halfTooltipTriangleWidth, + ); // \ // | if (!canAdjustTooltipNose) { @@ -1145,21 +1410,23 @@ class SfRectangularTooltipShape extends SfTooltipShape { // \ // |__________ path.quadraticBezierTo( - dy, - canAdjustTooltipNose - ? -rightLineWidth - : -rightLineWidth + cornerRadius / 2, - dy + cornerRadius / 2, - -rightLineWidth); + dy, + canAdjustTooltipNose + ? -rightLineWidth + : -rightLineWidth + cornerRadius / 2, + dy + cornerRadius / 2, + -rightLineWidth, + ); path.lineTo(dy + toolTipWidth - cornerRadius / 2, -rightLineWidth); // | // \ | // |__________| path.quadraticBezierTo( - dy + toolTipWidth - cornerRadius / 2, - -rightLineWidth, - dy + toolTipWidth, - -rightLineWidth + cornerRadius / 2); + dy + toolTipWidth - cornerRadius / 2, + -rightLineWidth, + dy + toolTipWidth, + -rightLineWidth + cornerRadius / 2, + ); path.lineTo(dy + toolTipWidth, leftLineWidth - cornerRadius / 2); // ___________ // | @@ -1179,8 +1446,12 @@ class SfRectangularTooltipShape extends SfTooltipShape { // \ | // |__________| if (leftLineWidth > halfTooltipTriangleWidth) { - path.quadraticBezierTo(dy + cornerRadius / 2, leftLineWidth, dy, - leftLineWidth - cornerRadius / 2); + path.quadraticBezierTo( + dy + cornerRadius / 2, + leftLineWidth, + dy, + leftLineWidth - cornerRadius / 2, + ); path.lineTo(dy, halfTooltipTriangleWidth); } // ___________ @@ -1196,34 +1467,51 @@ class SfRectangularTooltipShape extends SfTooltipShape { final bool canAdjustTooltipNose = rightLineWidth > halfTooltipTriangleWidth + cornerRadius / 2; path.lineTo( - canAdjustTooltipNose ? halfTooltipTriangleWidth : rightLineWidth, - -dy - (canAdjustTooltipNose ? 0 : cornerRadius / 2)); + canAdjustTooltipNose ? halfTooltipTriangleWidth : rightLineWidth, + -dy - (canAdjustTooltipNose ? 0 : cornerRadius / 2), + ); // ___ // / path.lineTo(rightLineWidth - cornerRadius, -dy); // ___| // / path.quadraticBezierTo( - rightLineWidth, -dy, rightLineWidth, -dy - cornerRadius); + rightLineWidth, + -dy, + rightLineWidth, + -dy - cornerRadius, + ); path.lineTo(rightLineWidth, -dy - tooltipHeight + cornerRadius); // _______ // ___| // / - path.quadraticBezierTo(rightLineWidth, -dy - tooltipHeight, - rightLineWidth - cornerRadius, -dy - tooltipHeight); + path.quadraticBezierTo( + rightLineWidth, + -dy - tooltipHeight, + rightLineWidth - cornerRadius, + -dy - tooltipHeight, + ); path.lineTo(-leftLineWidth + cornerRadius, -dy - tooltipHeight); // _______ // | ___| // / - path.quadraticBezierTo(-leftLineWidth, -dy - tooltipHeight, - -leftLineWidth, -dy - tooltipHeight + cornerRadius); + path.quadraticBezierTo( + -leftLineWidth, + -dy - tooltipHeight, + -leftLineWidth, + -dy - tooltipHeight + cornerRadius, + ); path.lineTo(-leftLineWidth, -dy - cornerRadius); // ________ // |___ ___| // / if (leftLineWidth > halfTooltipTriangleWidth) { path.quadraticBezierTo( - -leftLineWidth, -dy, -leftLineWidth + cornerRadius, -dy); + -leftLineWidth, + -dy, + -leftLineWidth + cornerRadius, + -dy, + ); path.lineTo(-halfTooltipTriangleWidth, -dy); } // ________ @@ -1236,24 +1524,37 @@ class SfRectangularTooltipShape extends SfTooltipShape { /// Draws the tooltip based on the values passed in the arguments. @override - void paint(PaintingContext context, Offset thumbCenter, Offset offset, - TextPainter textPainter, - {required RenderBox parentBox, - required SfSliderThemeData sliderThemeData, - required Paint paint, - required Animation animation, - required Rect trackRect}) { + void paint( + PaintingContext context, + Offset thumbCenter, + Offset offset, + TextPainter textPainter, { + required RenderBox parentBox, + required SfSliderThemeData sliderThemeData, + required Paint paint, + required Animation animation, + required Rect trackRect, + }) { final double leftPadding = tooltipTextPadding.dx / 2; final double minLeftX = trackRect.left; // ignore: avoid_as - final Path path = (_isVertical(parentBox as RenderBaseSlider)) - ? _updateRectangularTooltipWidth(textPainter.size + tooltipTextPadding, - offset.dy, trackRect, thumbCenter.dy, - isVertical: _isVertical(parentBox), - isLeftTooltip: _isLeftTooltip(parentBox)) - : _updateRectangularTooltipWidth(textPainter.size + tooltipTextPadding, - offset.dy, trackRect, thumbCenter.dx, - isVertical: _isVertical(parentBox)); + final Path path = + (_isVertical(parentBox as RenderBaseSlider)) + ? _updateRectangularTooltipWidth( + textPainter.size + tooltipTextPadding, + offset.dy, + trackRect, + thumbCenter.dy, + isVertical: _isVertical(parentBox), + isLeftTooltip: _isLeftTooltip(parentBox), + ) + : _updateRectangularTooltipWidth( + textPainter.size + tooltipTextPadding, + offset.dy, + trackRect, + thumbCenter.dx, + isVertical: _isVertical(parentBox), + ); context.canvas.save(); context.canvas.translate(thumbCenter.dx, thumbCenter.dy); @@ -1290,54 +1591,60 @@ class SfRectangularTooltipShape extends SfTooltipShape { final double halfTextPainterHeight = textPainter.height / 2; final double rectTopPosition = thumbCenter.dy - halfPathHeight; if (_isLeftTooltip(parentBox)) { - final double dx = -offset.dy - + final double dx = + -offset.dy - tooltipTriangleHeight - (pathRect.size.width - tooltipTriangleHeight) / 2 - textPainter.width / 2; - final double dy = rectTopPosition >= trackRect.top - ? thumbCenter.dy + halfPathHeight >= trackRect.bottom - ? -halfTextPainterHeight - + final double dy = + rectTopPosition >= trackRect.top + ? thumbCenter.dy + halfPathHeight >= trackRect.bottom + ? -halfTextPainterHeight - + halfPathHeight - + thumbCenter.dy + + trackRect.bottom + : -halfTextPainterHeight + : -halfTextPainterHeight + halfPathHeight - thumbCenter.dy + - trackRect.bottom - : -halfTextPainterHeight - : -halfTextPainterHeight + - halfPathHeight - - thumbCenter.dy + - trackRect.top; + trackRect.top; textPainter.paint(context.canvas, Offset(dx, dy)); } else { - final double dx = offset.dy + + final double dx = + offset.dy + tooltipTriangleHeight + (pathRect.size.width - tooltipTriangleHeight) / 2 - textPainter.width / 2; - final double dy = rectTopPosition >= trackRect.top - ? thumbCenter.dy + halfPathHeight >= trackRect.bottom - ? -halfTextPainterHeight - + final double dy = + rectTopPosition >= trackRect.top + ? thumbCenter.dy + halfPathHeight >= trackRect.bottom + ? -halfTextPainterHeight - + halfPathHeight - + thumbCenter.dy + + trackRect.bottom + : -halfTextPainterHeight + : -halfTextPainterHeight + halfPathHeight - thumbCenter.dy + - trackRect.bottom - : -halfTextPainterHeight - : -halfTextPainterHeight + - halfPathHeight - - thumbCenter.dy + - trackRect.top; + trackRect.top; textPainter.paint(context.canvas, Offset(dx, dy)); } } else { - final double dx = rectLeftPosition >= minLeftX - ? thumbCenter.dx + halfTextPainterWidth + leftPadding > - trackRect.right - ? -halfTextPainterWidth - + final double dx = + rectLeftPosition >= minLeftX + ? thumbCenter.dx + halfTextPainterWidth + leftPadding > + trackRect.right + ? -halfTextPainterWidth - + halfPathWidth + + trackRect.right - + thumbCenter.dx + : -halfTextPainterWidth + : -halfTextPainterWidth + halfPathWidth + - trackRect.right - - thumbCenter.dx - : -halfTextPainterWidth - : -halfTextPainterWidth + - halfPathWidth + - trackRect.left - - thumbCenter.dx; - final double dy = offset.dy + + trackRect.left - + thumbCenter.dx; + final double dy = + offset.dy + tooltipTriangleHeight + (pathRect.size.height - tooltipTriangleHeight) / 2 + textPainter.height / 2; diff --git a/packages/syncfusion_flutter_sliders/pubspec.yaml b/packages/syncfusion_flutter_sliders/pubspec.yaml index a51beede5..534d30a0a 100644 --- a/packages/syncfusion_flutter_sliders/pubspec.yaml +++ b/packages/syncfusion_flutter_sliders/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_sliders description: A Flutter Sliders library for creating highly customizable and UI-rich slider, range slider, and range selector widgets for filtering purposes. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_sliders screenshots: @@ -14,16 +14,22 @@ screenshots: path: screenshots/range_selector_zooming.gif environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: sdk: flutter intl: '>=0.18.1 <0.21.0' syncfusion_flutter_core: - path: ../syncfusion_flutter_core - + path: ../syncfusion_flutter_core +dev_dependencies: + syncfusion_flutter_charts: + path:../syncfusion_flutter_charts + flutter: + assets: + - assets/fonts/Roboto-Medium.ttf + - assets/images/lake.jpg diff --git a/packages/syncfusion_flutter_treemap/CHANGELOG.md b/packages/syncfusion_flutter_treemap/CHANGELOG.md index af74c88c3..6730dedb2 100644 --- a/packages/syncfusion_flutter_treemap/CHANGELOG.md +++ b/packages/syncfusion_flutter_treemap/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of our Flutter treemap widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter treemap widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter treemap example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter treemap example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_treemap/assets/fonts/Roboto-Medium.ttf b/packages/syncfusion_flutter_treemap/assets/fonts/Roboto-Medium.ttf new file mode 100644 index 000000000..d629e9848 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/fonts/Roboto-Medium.ttf differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/facebook.png b/packages/syncfusion_flutter_treemap/assets/images/facebook.png new file mode 100644 index 000000000..86d2e724b Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/facebook.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/instagram.png b/packages/syncfusion_flutter_treemap/assets/images/instagram.png new file mode 100644 index 000000000..af4bdf3d3 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/instagram.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/linkedin.png b/packages/syncfusion_flutter_treemap/assets/images/linkedin.png new file mode 100644 index 000000000..a1ce08c90 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/linkedin.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/snapchat.png b/packages/syncfusion_flutter_treemap/assets/images/snapchat.png new file mode 100644 index 000000000..a7cd07566 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/snapchat.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/telegram.png b/packages/syncfusion_flutter_treemap/assets/images/telegram.png new file mode 100644 index 000000000..3b9926cda Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/telegram.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/treemap_medal.png b/packages/syncfusion_flutter_treemap/assets/images/treemap_medal.png new file mode 100644 index 000000000..9c4e2ff21 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/treemap_medal.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/twitter.png b/packages/syncfusion_flutter_treemap/assets/images/twitter.png new file mode 100644 index 000000000..032a520af Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/twitter.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/we_chat.png b/packages/syncfusion_flutter_treemap/assets/images/we_chat.png new file mode 100644 index 000000000..f63641cc3 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/we_chat.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/whatsapp.png b/packages/syncfusion_flutter_treemap/assets/images/whatsapp.png new file mode 100644 index 000000000..16786577d Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/whatsapp.png differ diff --git a/packages/syncfusion_flutter_treemap/assets/images/youtube.png b/packages/syncfusion_flutter_treemap/assets/images/youtube.png new file mode 100644 index 000000000..95fbe39b7 Binary files /dev/null and b/packages/syncfusion_flutter_treemap/assets/images/youtube.png differ diff --git a/packages/syncfusion_flutter_treemap/example/lib/main.dart b/packages/syncfusion_flutter_treemap/example/lib/main.dart index 9e3097ba2..bc72ed4f9 100644 --- a/packages/syncfusion_flutter_treemap/example/lib/main.dart +++ b/packages/syncfusion_flutter_treemap/example/lib/main.dart @@ -11,10 +11,7 @@ class TreemapApp extends StatelessWidget { @override Widget build(BuildContext context) { - return const MaterialApp( - title: 'Treemap Demo', - home: MyHomePage(), - ); + return const MaterialApp(title: 'Treemap Demo', home: MyHomePage()); } } @@ -70,8 +67,9 @@ class _MyHomePageState extends State { return Padding( padding: const EdgeInsets.all(10), child: Text( - '''Country : ${tile.group}\nSocial media : ${tile.weight}M''', - style: const TextStyle(color: Colors.black)), + '''Country : ${tile.group}\nSocial media : ${tile.weight}M''', + style: const TextStyle(color: Colors.black), + ), ); }, ), diff --git a/packages/syncfusion_flutter_treemap/example/pubspec.yaml b/packages/syncfusion_flutter_treemap/example/pubspec.yaml index ee344e2eb..d8c631e2e 100644 --- a/packages/syncfusion_flutter_treemap/example/pubspec.yaml +++ b/packages/syncfusion_flutter_treemap/example/pubspec.yaml @@ -1,20 +1,10 @@ name: treemap_sample description: A new Flutter project. -# 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 used as CFBundleVersion. -# Read more about iOS versioning at -# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html version: 1.0.0+1 environment: - sdk: '>=3.3.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: @@ -23,53 +13,12 @@ dependencies: syncfusion_flutter_treemap: path: ../ - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: '>=0.1.2 <1.0.7' dev_dependencies: flutter_test: sdk: flutter - -# 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. 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: - # - 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 diff --git a/packages/syncfusion_flutter_treemap/lib/src/animated_border.dart b/packages/syncfusion_flutter_treemap/lib/src/animated_border.dart index a01509314..f8adb272f 100644 --- a/packages/syncfusion_flutter_treemap/lib/src/animated_border.dart +++ b/packages/syncfusion_flutter_treemap/lib/src/animated_border.dart @@ -19,10 +19,11 @@ class AnimatedBorder extends RoundedRectangleBorder { Rect _getRect(Rect rect, double width) { if (scaleSize != null) { return Rect.fromLTRB( - rect.left + (width / scaleSize!.width), - rect.top + (width / scaleSize!.height), - rect.right - (width / scaleSize!.width), - rect.bottom - (width / scaleSize!.height)); + rect.left + (width / scaleSize!.width), + rect.top + (width / scaleSize!.height), + rect.right - (width / scaleSize!.width), + rect.bottom - (width / scaleSize!.height), + ); } return rect; @@ -44,33 +45,43 @@ class AnimatedBorder extends RoundedRectangleBorder { // But we need to reduce the border radius by using the current // border width. currentBorderRadius = BorderRadius.only( - topRight: Radius.elliptical( - currentBorderRadius.topRight.x - borderWidth, - currentBorderRadius.topRight.y - borderHeight), - bottomLeft: Radius.elliptical( - currentBorderRadius.bottomLeft.x - borderWidth, - currentBorderRadius.bottomLeft.y - borderHeight), - bottomRight: Radius.elliptical( - currentBorderRadius.bottomRight.x - borderWidth, - currentBorderRadius.bottomRight.y - borderHeight), - topLeft: Radius.elliptical( - currentBorderRadius.topLeft.x - borderWidth, - currentBorderRadius.topLeft.y - borderHeight)); + topRight: Radius.elliptical( + currentBorderRadius.topRight.x - borderWidth, + currentBorderRadius.topRight.y - borderHeight, + ), + bottomLeft: Radius.elliptical( + currentBorderRadius.bottomLeft.x - borderWidth, + currentBorderRadius.bottomLeft.y - borderHeight, + ), + bottomRight: Radius.elliptical( + currentBorderRadius.bottomRight.x - borderWidth, + currentBorderRadius.bottomRight.y - borderHeight, + ), + topLeft: Radius.elliptical( + currentBorderRadius.topLeft.x - borderWidth, + currentBorderRadius.topLeft.y - borderHeight, + ), + ); } if (width == 0.0) { innerRect = _getRect(rect, width); canvas.drawRRect( - borderRadius.resolve(textDirection).toRRect(innerRect), - side.toPaint()); + borderRadius.resolve(textDirection).toRRect(innerRect), + side.toPaint(), + ); } else { final RRect outer = borderRadius.resolve(textDirection).toRRect(rect); innerRect = _getRect( - Rect.fromLTRB(outer.left, outer.top, outer.right, outer.bottom), - width); - final RRect inner = scaleSize != null - ? currentBorderRadius.resolve(textDirection).toRRect(innerRect) - : outer.deflate(width); + Rect.fromLTRB(outer.left, outer.top, outer.right, outer.bottom), + width, + ); + final RRect inner = + scaleSize != null + ? currentBorderRadius + .resolve(textDirection) + .toRRect(innerRect) + : outer.deflate(width); final Paint paint = Paint()..color = side.color; canvas.drawDRRect(outer, inner, paint); } diff --git a/packages/syncfusion_flutter_treemap/lib/src/layouts.dart b/packages/syncfusion_flutter_treemap/lib/src/layouts.dart index c56a283e2..209425c82 100644 --- a/packages/syncfusion_flutter_treemap/lib/src/layouts.dart +++ b/packages/syncfusion_flutter_treemap/lib/src/layouts.dart @@ -16,31 +16,42 @@ import 'tooltip.dart'; // Combines the two color values and returns a new saturated color. We have // used black color as default mix color. -Color _getSaturatedColor(Color color, double factor, - [Color mix = Colors.black]) { +Color _getSaturatedColor( + Color color, + double factor, [ + Color mix = Colors.black, +]) { return color == Colors.transparent ? color : Color.fromRGBO( - ((1 - factor) * (color.r * 255) + factor * (mix.r * 255)).toInt(), - ((1 - factor) * (color.g * 255) + factor * (mix.g * 255)).toInt(), - ((1 - factor) * (color.b * 255) + factor * (mix.b * 255)).toInt(), - 1, - ); + ((1 - factor) * (color.r * 255) + factor * (mix.r * 255)).toInt(), + ((1 - factor) * (color.g * 255) + factor * (mix.g * 255)).toInt(), + ((1 - factor) * (color.b * 255) + factor * (mix.b * 255)).toInt(), + 1, + ); } /// Ignored scaling to the label builder and item builder and provides the /// opacity animation. Widget _buildAnimatedBuilder( - TreemapTile tile, Size scale, AnimationStatus status, Widget child) { + TreemapTile tile, + Size scale, + AnimationStatus status, + Widget child, +) { Size gap = Size.zero; if (tile.level.border != null) { - gap = Size(tile.level.border!.dimensions.horizontal, - tile.level.border!.dimensions.vertical); + gap = Size( + tile.level.border!.dimensions.horizontal, + tile.level.border!.dimensions.vertical, + ); } if (tile.level.padding != null) { - gap = Size(tile.level.padding!.horizontal + gap.width, - tile.level.padding!.vertical + gap.height); + gap = Size( + tile.level.padding!.horizontal + gap.width, + tile.level.padding!.vertical + gap.height, + ); } child = Transform( @@ -53,12 +64,14 @@ Widget _buildAnimatedBuilder( // We have to increase the label/item builder's size while drilling down // to maintain its position so used [OverflowBox]. if (scale.width < 1 || scale.height < 1) { - width = scale.width < 1 - ? tile._size!.width * scale.width - gap.width - : tile._size!.width - gap.width; - height = scale.height < 1 - ? tile._size!.height * scale.height - gap.height - : tile._size!.height - gap.height; + width = + scale.width < 1 + ? tile._size!.width * scale.width - gap.width + : tile._size!.width - gap.width; + height = + scale.height < 1 + ? tile._size!.height * scale.height - gap.height + : tile._size!.height - gap.height; return Align( alignment: Alignment.topLeft, child: SizedBox( @@ -73,31 +86,35 @@ Widget _buildAnimatedBuilder( ), ); } else { - width = scale.width > 1 - ? tile._size!.width * scale.width - gap.width - : tile._size!.width - gap.width; - height = scale.height > 1 - ? tile._size!.height * scale.height - gap.height - : tile._size!.height - gap.height; + width = + scale.width > 1 + ? tile._size!.width * scale.width - gap.width + : tile._size!.width - gap.width; + height = + scale.height > 1 + ? tile._size!.height * scale.height - gap.height + : tile._size!.height - gap.height; return OverflowBox( - alignment: Alignment.topLeft, - maxHeight: height > 0 ? height : 0.0, - maxWidth: width > 0 ? width : 0.0, - child: child); + alignment: Alignment.topLeft, + maxHeight: height > 0 ? height : 0.0, + maxWidth: width > 0 ? width : 0.0, + child: child, + ); } } Widget? _buildLabeAndItemBuilder( - Widget current, - TreemapTile tile, - int visibleIndex, - AnimationStatus animationStatus, - Animation scalingAndTranslationAnimation, - Animation opacityAnimation, - Tween currentLevelScale, - Tween nextLevelScale, - Tween tileOpacity, - Tween labelAndItemBuilderOpacity) { + Widget current, + TreemapTile tile, + int visibleIndex, + AnimationStatus animationStatus, + Animation scalingAndTranslationAnimation, + Animation opacityAnimation, + Tween currentLevelScale, + Tween nextLevelScale, + Tween tileOpacity, + Tween labelAndItemBuilderOpacity, +) { Size? scaleSize; if (animationStatus == AnimationStatus.forward && visibleIndex == tile._levelIndex) { @@ -108,30 +125,38 @@ Widget? _buildLabeAndItemBuilder( return Opacity( opacity: tileOpacity.evaluate(opacityAnimation), child: _buildAnimatedBuilder( - tile, - currentLevelScale.evaluate(scalingAndTranslationAnimation), - animationStatus, - current), + tile, + currentLevelScale.evaluate(scalingAndTranslationAnimation), + animationStatus, + current, + ), ); } else if (animationStatus == AnimationStatus.reverse) { if (visibleIndex == tile._levelIndex) { scaleSize = nextLevelScale.evaluate(scalingAndTranslationAnimation); - scaleSize = scaleSize.width > scaleSize.height - ? Size(scaleSize.width / scaleSize.width, - scaleSize.height / scaleSize.width) - : Size(scaleSize.width / scaleSize.height, - scaleSize.height / scaleSize.height); + scaleSize = + scaleSize.width > scaleSize.height + ? Size( + scaleSize.width / scaleSize.width, + scaleSize.height / scaleSize.width, + ) + : Size( + scaleSize.width / scaleSize.height, + scaleSize.height / scaleSize.height, + ); return Opacity( - opacity: - labelAndItemBuilderOpacity.evaluate(scalingAndTranslationAnimation), + opacity: labelAndItemBuilderOpacity.evaluate( + scalingAndTranslationAnimation, + ), child: _buildAnimatedBuilder(tile, scaleSize, animationStatus, current), ); } else { current = _buildAnimatedBuilder( - tile, - currentLevelScale.evaluate(scalingAndTranslationAnimation), - animationStatus, - current); + tile, + currentLevelScale.evaluate(scalingAndTranslationAnimation), + animationStatus, + current, + ); if (tile._isDrilled) { current = Opacity( opacity: tileOpacity.evaluate(opacityAnimation), @@ -150,7 +175,7 @@ enum PointerKind { touch, /// Indicates the pointer kind as hover. - hover + hover, } /// The [SfTreemap]'s layout type. @@ -162,7 +187,7 @@ enum LayoutType { slice, /// Dice layout. - dice + dice, } /// Contains information about the treemap tile. @@ -274,19 +299,30 @@ mixin _TreemapMixin { /// Calculates the scale and translation value by using the current /// drilldown tile size and offset. void _computeDrilldownTweenValue( - TreemapTile visibleTile, - AnimationController drilldownAnimationController, - GlobalKey breadcrumbKey, - bool isDrilledIn) { + TreemapTile visibleTile, + AnimationController drilldownAnimationController, + GlobalKey breadcrumbKey, + bool isDrilledIn, + ) { if (isDrilledIn) { - final Size currentScale = Size(size!.width / visibleTile._size!.width, - size!.height / visibleTile._size!.height); - final Offset currentTranslation = - _getTranslation(visibleTile._offset!, currentScale); - _scaleAndTranslationAnimation.curve = - const Interval(0, 0.5, curve: Curves.easeInOut); - _opacityAnimation.curve = - const Interval(0.5, 1.0, curve: Curves.easeInOut); + final Size currentScale = Size( + size!.width / visibleTile._size!.width, + size!.height / visibleTile._size!.height, + ); + final Offset currentTranslation = _getTranslation( + visibleTile._offset!, + currentScale, + ); + _scaleAndTranslationAnimation.curve = const Interval( + 0, + 0.5, + curve: Curves.easeInOut, + ); + _opacityAnimation.curve = const Interval( + 0.5, + 1.0, + curve: Curves.easeInOut, + ); _visibleTileTranslation ..begin = Offset.zero ..end = currentTranslation; @@ -298,8 +334,11 @@ mixin _TreemapMixin { ..end = 0.0; drilldownAnimationController.forward(from: 0.01); } else { - _scaleAndTranslationAnimation.curve = - const Interval(0.5, 1.0, curve: Curves.easeInOut); + _scaleAndTranslationAnimation.curve = const Interval( + 0.5, + 1.0, + curve: Curves.easeInOut, + ); _opacityAnimation.curve = const Interval(0, 0.5, curve: Curves.easeInOut); _computeDrilledOutTweenValue(visibleTile, breadcrumbKey); drilldownAnimationController.reverse(from: 0.99); @@ -309,7 +348,9 @@ mixin _TreemapMixin { } void _computeDrilledOutTweenValue( - TreemapTile tappedTile, GlobalKey breadcrumbKey) { + TreemapTile tappedTile, + GlobalKey breadcrumbKey, + ) { late TreemapTile currentDrilledTile; if (breadcrumbKey.currentState != null) { final _BreadcrumbsState breadcrumbRenderBox = @@ -326,20 +367,27 @@ mixin _TreemapMixin { // It represents which size we need to increase the from scale // value to the current level tiles. final Size currentLevelScale = Size( - size!.width / currentDrilledTile._size!.width, - size!.height / currentDrilledTile._size!.height); + size!.width / currentDrilledTile._size!.width, + size!.height / currentDrilledTile._size!.height, + ); // It represents the offset we need to translate in the animation begin // to the current level tiles. - final Offset currentLevelTranslation = - _getTranslation(currentDrilledTile._offset!, currentLevelScale); + final Offset currentLevelTranslation = _getTranslation( + currentDrilledTile._offset!, + currentLevelScale, + ); // It represents which size we need to increase the from scale // value to the current visible tiles. - final Size nextLevelScale = - Size(1.0 / currentLevelScale.width, 1.0 / currentLevelScale.height); + final Size nextLevelScale = Size( + 1.0 / currentLevelScale.width, + 1.0 / currentLevelScale.height, + ); // It represents the offset we need to translate in the animation begin // to the current visible tiles. - final Offset nextLevelTranslation = - _getTranslation(currentLevelTranslation, nextLevelScale); + final Offset nextLevelTranslation = _getTranslation( + currentLevelTranslation, + nextLevelScale, + ); _nextTileTranslation ..begin = nextLevelTranslation ..end = Offset.zero; @@ -362,14 +410,18 @@ mixin _TreemapMixin { Offset _getTranslation(Offset tileOffset, Size scaleSize) { return -Offset( - tileOffset.dx * scaleSize.width, tileOffset.dy * scaleSize.height); + tileOffset.dx * scaleSize.width, + tileOffset.dy * scaleSize.height, + ); } /// Scales to the current visible level and load its descendants /// with animation. Widget _buildAnimatedTreemap( - AnimationController controller, GlobalKey breadcrumbKey, - {TreemapLayoutDirection direction = TreemapLayoutDirection.topLeft}) { + AnimationController controller, + GlobalKey breadcrumbKey, { + TreemapLayoutDirection direction = TreemapLayoutDirection.topLeft, + }) { late List breadcrumbTiles; if (breadcrumbKey.currentState != null) { final _BreadcrumbsState breadcrumbRenderBox = @@ -377,30 +429,39 @@ mixin _TreemapMixin { breadcrumbTiles = breadcrumbRenderBox._tiles; } - final TreemapTile tile = controller.status == AnimationStatus.reverse - ? _visibleTile - // Gets the previous tapped tiles. - : breadcrumbTiles[breadcrumbTiles.length - 2]; + final TreemapTile tile = + controller.status == AnimationStatus.reverse + ? _visibleTile + // Gets the previous tapped tiles. + : breadcrumbTiles[breadcrumbTiles.length - 2]; return AnimatedBuilder( animation: controller, builder: (BuildContext context, Widget? child) { - final Offset translation = _getLayoutDirectionTranslation(direction, - _visibleTileTranslation.evaluate(_scaleAndTranslationAnimation)); - final Size scaleSize = - _visibleTileScaleSize.evaluate(_scaleAndTranslationAnimation); + final Offset translation = _getLayoutDirectionTranslation( + direction, + _visibleTileTranslation.evaluate(_scaleAndTranslationAnimation), + ); + final Size scaleSize = _visibleTileScaleSize.evaluate( + _scaleAndTranslationAnimation, + ); if (controller.status != AnimationStatus.reverse) { return Stack( children: [ Transform( alignment: _getEffectiveAlignment(direction), - transform: Matrix4.identity() - ..scale(scaleSize.width, scaleSize.height) - ..leftTranslate(translation.dx, translation.dy), + transform: + Matrix4.identity() + ..scale(scaleSize.width, scaleSize.height) + ..leftTranslate(translation.dx, translation.dy), child: Stack( clipBehavior: Clip.none, - children: _buildTiles(tile._descendants!, tile.weight, size!, - canLayoutTiles: false), + children: _buildTiles( + tile._descendants!, + tile.weight, + size!, + canLayoutTiles: false, + ), ), ), if (controller.value > 0.5) @@ -409,65 +470,89 @@ mixin _TreemapMixin { child: Stack( clipBehavior: Clip.none, children: _buildTiles( - _visibleTile._descendants!, _visibleTile.weight, size!), + _visibleTile._descendants!, + _visibleTile.weight, + size!, + ), ), - ) + ), ], ); } else { return _buildDrilledOutAnimatedTiles( - tile, breadcrumbTiles.last, scaleSize, translation, direction); + tile, + breadcrumbTiles.last, + scaleSize, + translation, + direction, + ); } }, ); } Widget _buildDrilledOutAnimatedTiles( - TreemapTile tile, - TreemapTile lastBreadcrumbTile, - Size scaleSize, - Offset translation, - TreemapLayoutDirection direction) { + TreemapTile tile, + TreemapTile lastBreadcrumbTile, + Size scaleSize, + Offset translation, + TreemapLayoutDirection direction, + ) { final Offset descendantsTranslation = _getLayoutDirectionTranslation( - direction, - _nextTileTranslation.evaluate(_scaleAndTranslationAnimation)); - final Size descendantsScaleSize = - _nextTileScaleSize.evaluate(_scaleAndTranslationAnimation); + direction, + _nextTileTranslation.evaluate(_scaleAndTranslationAnimation), + ); + final Size descendantsScaleSize = _nextTileScaleSize.evaluate( + _scaleAndTranslationAnimation, + ); return Stack( children: [ Transform( alignment: _getEffectiveAlignment(direction), - transform: Matrix4.identity() - ..scale(scaleSize.width, scaleSize.height) - ..leftTranslate(translation.dx, translation.dy), + transform: + Matrix4.identity() + ..scale(scaleSize.width, scaleSize.height) + ..leftTranslate(translation.dx, translation.dy), child: Stack( clipBehavior: Clip.none, - children: _buildTiles(tile._descendants!, tile.weight, size!, - canLayoutTiles: false), + children: _buildTiles( + tile._descendants!, + tile.weight, + size!, + canLayoutTiles: false, + ), ), ), Transform( alignment: _getEffectiveAlignment(direction), - transform: Matrix4.identity() - ..scale(descendantsScaleSize.width, descendantsScaleSize.height) - ..leftTranslate( - descendantsTranslation.dx, descendantsTranslation.dy), + transform: + Matrix4.identity() + ..scale(descendantsScaleSize.width, descendantsScaleSize.height) + ..leftTranslate( + descendantsTranslation.dx, + descendantsTranslation.dy, + ), child: Opacity( opacity: 1.0 - _tileOpacity.evaluate(_opacityAnimation), child: Stack( clipBehavior: Clip.none, - children: _buildTiles(lastBreadcrumbTile._descendants!, - lastBreadcrumbTile.weight, size!, - canLayoutTiles: false), + children: _buildTiles( + lastBreadcrumbTile._descendants!, + lastBreadcrumbTile.weight, + size!, + canLayoutTiles: false, + ), ), ), - ) + ), ], ); } Offset _getLayoutDirectionTranslation( - TreemapLayoutDirection layoutDirection, Offset translation) { + TreemapLayoutDirection layoutDirection, + Offset translation, + ) { switch (layoutDirection) { case TreemapLayoutDirection.topLeft: return translation; @@ -481,7 +566,8 @@ mixin _TreemapMixin { } AlignmentGeometry _getEffectiveAlignment( - TreemapLayoutDirection layoutDirection) { + TreemapLayoutDirection layoutDirection, + ) { switch (layoutDirection) { case TreemapLayoutDirection.topLeft: return Alignment.topLeft; @@ -495,9 +581,13 @@ mixin _TreemapMixin { } /// Loads label builder and descendants for the tiles. - Widget? _getDescendants(BuildContext context, TreemapTile tile, - TreemapController controller, bool enableDrilldown, - {AnimationController? animationController}) { + Widget? _getDescendants( + BuildContext context, + TreemapTile tile, + TreemapController controller, + bool enableDrilldown, { + AnimationController? animationController, + }) { Widget? child; // Ignored current tile descendants while enable drilldown. if (enableDrilldown) { @@ -538,20 +628,25 @@ mixin _TreemapMixin { // Therefore we haven't considered [TreemapLevel.padding] and // [TreemapLevel.border] values while passing size to children. child: LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - // To get the actual size of the parent tile, we had taken the - // size of the label builder and subtracted from it. - tile._labelBuilderSize = Size( + builder: (BuildContext context, BoxConstraints constraints) { + // To get the actual size of the parent tile, we had taken the + // size of the label builder and subtracted from it. + tile._labelBuilderSize = Size( tile._size!.width - constraints.maxWidth, - tile._size!.height - constraints.maxHeight); - return Stack( - children: _buildTiles( + tile._size!.height - constraints.maxHeight, + ); + return Stack( + children: _buildTiles( tile._descendants!, tile.weight, - Size(tile._size!.width - tile._labelBuilderSize.width, - tile._size!.height - tile._labelBuilderSize.height)), - ); - }), + Size( + tile._size!.width - tile._labelBuilderSize.width, + tile._size!.height - tile._labelBuilderSize.height, + ), + ), + ); + }, + ), ), ], ); @@ -572,21 +667,26 @@ mixin _TreemapMixin { Widget _buildDescendants(TreemapTile tile) { return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - return Stack( + builder: (BuildContext context, BoxConstraints constraints) { + return Stack( children: _buildTiles( - tile._descendants!, - tile.weight, - constraints.biggest, - )); - }); + tile._descendants!, + tile.weight, + constraints.biggest, + ), + ); + }, + ); } /// Creates the get tiles methods and overrides to the slice, dice /// and squarified class. List _buildTiles( - Map source, double aggregatedWeight, Size size, - {bool canLayoutTiles = true}) { + Map source, + double aggregatedWeight, + Size size, { + bool canLayoutTiles = true, + }) { return []; } } @@ -691,50 +791,54 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { late Future _computeDataSource; _SquarifiedTreemap get _squarified => _SquarifiedTreemap( - dataCount: widget.dataCount, - layoutDirection: widget.layoutDirection, - tooltipKey: _tooltipKey, - breadcrumbKey: _breadcrumbKey, - onSelectionChanged: widget.onSelectionChanged, - selectionSettings: widget.selectionSettings, - enableDrillDown: widget.enableDrilldown, - controller: _controller, - drilldownAnimationController: _drilldownAnimationController, - initialTile: TreemapTile._() - .._group = 'Home' - .._levelIndex = -1 - .._offset = Offset.zero - .._descendants = _dataSource - .._weight = _totalWeight - .._isDrilled = true); + dataCount: widget.dataCount, + layoutDirection: widget.layoutDirection, + tooltipKey: _tooltipKey, + breadcrumbKey: _breadcrumbKey, + onSelectionChanged: widget.onSelectionChanged, + selectionSettings: widget.selectionSettings, + enableDrillDown: widget.enableDrilldown, + controller: _controller, + drilldownAnimationController: _drilldownAnimationController, + initialTile: + TreemapTile._() + .._group = 'Home' + .._levelIndex = -1 + .._offset = Offset.zero + .._descendants = _dataSource + .._weight = _totalWeight + .._isDrilled = true, + ); _SliceAndDiceTreemap get _sliceAndDice => _SliceAndDiceTreemap( - dataCount: widget.dataCount, - sortAscending: widget.sortAscending, - type: widget.layoutType, - tooltipKey: _tooltipKey, - breadcrumbKey: _breadcrumbKey, - onSelectionChanged: widget.onSelectionChanged, - selectionSettings: widget.selectionSettings, - enableDrillDown: widget.enableDrilldown, - controller: _controller, - drilldownAnimationController: _drilldownAnimationController, - initialTile: TreemapTile._() + dataCount: widget.dataCount, + sortAscending: widget.sortAscending, + type: widget.layoutType, + tooltipKey: _tooltipKey, + breadcrumbKey: _breadcrumbKey, + onSelectionChanged: widget.onSelectionChanged, + selectionSettings: widget.selectionSettings, + enableDrillDown: widget.enableDrilldown, + controller: _controller, + drilldownAnimationController: _drilldownAnimationController, + initialTile: + TreemapTile._() .._group = 'Home' .._levelIndex = -1 .._offset = Offset.zero .._descendants = _dataSource .._weight = _totalWeight .._isDrilled = true, - ); + ); TreemapTooltip get _tooltip => TreemapTooltip(key: _tooltipKey, settings: widget.tooltipSettings); Widget _buildTreemap(BuildContext context, bool hasData) { - Widget current = widget.layoutType == LayoutType.squarified - ? _squarified - : _sliceAndDice; + Widget current = + widget.layoutType == LayoutType.squarified + ? _squarified + : _sliceAndDice; if (widget.enableDrilldown) { // ignore: no_leading_underscores_for_local_identifiers @@ -744,13 +848,14 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { controller: _controller, animationController: _drilldownAnimationController!, levels: widget.levels, - initialTile: TreemapTile._() - .._group = 'Home' - .._levelIndex = -1 - .._offset = Offset.zero - .._descendants = _dataSource - .._weight = _totalWeight - .._isDrilled = true, + initialTile: + TreemapTile._() + .._group = 'Home' + .._levelIndex = -1 + .._offset = Offset.zero + .._descendants = _dataSource + .._weight = _totalWeight + .._isDrilled = true, ); switch (widget.breadcrumbs!.position) { case TreemapBreadcrumbPosition.top: @@ -758,7 +863,7 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { crossAxisAlignment: CrossAxisAlignment.start, children: [ _breadcrumbs, - Expanded(child: ClipRect(child: current)) + Expanded(child: ClipRect(child: current)), ], ); break; @@ -851,8 +956,9 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { } void _obtainDataSource() { - _computeDataSource = - _obtainDataSourceAndBindColorMappers().then((bool value) => value); + _computeDataSource = _obtainDataSourceAndBindColorMappers().then( + (bool value) => value, + ); } Future _obtainDataSourceAndBindColorMappers() async { @@ -873,8 +979,12 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { return true; } - void _groupTiles(double weight, int dataIndex, - {int currentLevelIndex = 0, TreemapTile? ancestor}) { + void _groupTiles( + double weight, + int dataIndex, { + int currentLevelIndex = 0, + TreemapTile? ancestor, + }) { final TreemapLevel currentLevel = widget.levels[currentLevelIndex]; final String? groupKey = currentLevel.groupMapper(dataIndex); final Color? color = currentLevel.color; @@ -888,8 +998,12 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { // have group key, here we have considered the [2] as child to the [0]. if (groupKey == null) { if (nextLevelIndex < _levelsLength) { - _groupTiles(weight, dataIndex, - currentLevelIndex: nextLevelIndex, ancestor: ancestor); + _groupTiles( + weight, + dataIndex, + currentLevelIndex: nextLevelIndex, + ancestor: ancestor, + ); } return; } @@ -920,48 +1034,62 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { // checked for the next stages. ((ancestor?._descendants ??= {}) ?? _dataSource) .update( - groupKey, - (TreemapTile tile) { - tile._weight += weight; - tile.indices.add(dataIndex); - tile._levelIndex = currentLevelIndex; - if (nextLevelIndex < _levelsLength) { - _groupTiles(weight, dataIndex, - currentLevelIndex: nextLevelIndex, ancestor: tile); - } - return tile; - }, - ifAbsent: () { - final TreemapTile tile = TreemapTile._() - .._group = groupKey - .._level = currentLevel - .._indices = [dataIndex] - .._weight = weight - .._padding = padding - .._levelIndex = currentLevelIndex - .._hasDescendants = false; - if (color != null) { - tile._color = color; - } + groupKey, + (TreemapTile tile) { + tile._weight += weight; + tile.indices.add(dataIndex); + tile._levelIndex = currentLevelIndex; + if (nextLevelIndex < _levelsLength) { + _groupTiles( + weight, + dataIndex, + currentLevelIndex: nextLevelIndex, + ancestor: tile, + ); + } + return tile; + }, + ifAbsent: () { + final TreemapTile tile = + TreemapTile._() + .._group = groupKey + .._level = currentLevel + .._indices = [dataIndex] + .._weight = weight + .._padding = padding + .._levelIndex = currentLevelIndex + .._hasDescendants = false; + if (color != null) { + tile._color = color; + } - if (nextLevelIndex < _levelsLength) { - _groupTiles(weight, dataIndex, - currentLevelIndex: nextLevelIndex, ancestor: tile); - } - ancestor?._hasDescendants = true; - return tile; - }, - ); + if (nextLevelIndex < _levelsLength) { + _groupTiles( + weight, + dataIndex, + currentLevelIndex: nextLevelIndex, + ancestor: tile, + ); + } + ancestor?._hasDescendants = true; + return tile; + }, + ); } void _bindColorMappersIntoDataSource(Map? source) { if (source != null && source.isNotEmpty) { - final double baseWeight = - source.values.map((TreemapTile tile) => tile._weight).reduce(max); + final double baseWeight = source.values + .map((TreemapTile tile) => tile._weight) + .reduce(max); for (final TreemapTile tile in source.values) { - tile._color = _getColor(tile) ?? + tile._color = + _getColor(tile) ?? _getSaturatedColor( - _baseColor, 1 - (tile._weight / baseWeight), Colors.white); + _baseColor, + 1 - (tile._weight / baseWeight), + Colors.white, + ); _bindColorMappersIntoDataSource(tile._descendants); } } @@ -1001,18 +1129,22 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { Color? _getRangeColor(num value, List colorMappers) { for (final TreemapColorMapper mapper in colorMappers) { - assert(mapper.from != null && - mapper.to != null && - mapper.from! <= mapper.to!); + assert( + mapper.from != null && mapper.to != null && mapper.from! <= mapper.to!, + ); if ((mapper.from != null && mapper.to != null) && (mapper.from! <= value && mapper.to! >= value)) { if (mapper.minSaturation != null && mapper.maxSaturation != null) { return _getSaturatedColor( - mapper.color, - 1 - - lerpDouble(mapper.minSaturation, mapper.maxSaturation, - (value - mapper.from!) / (mapper.to! - mapper.from!))!, - Colors.white); + mapper.color, + 1 - + lerpDouble( + mapper.minSaturation, + mapper.maxSaturation, + (value - mapper.from!) / (mapper.to! - mapper.from!), + )!, + Colors.white, + ); } return mapper.color; } @@ -1040,7 +1172,9 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { _controller = TreemapController(); if (widget.enableDrilldown) { _drilldownAnimationController = AnimationController( - vsync: this, duration: const Duration(milliseconds: 1000)); + vsync: this, + duration: const Duration(milliseconds: 1000), + ); _controller.addDrillDownListener(_handleDrillDown); } _pointerController = PointerController(); @@ -1052,10 +1186,10 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { void didUpdateWidget(Treemap oldWidget) { _canUpdateTileColor = (oldWidget.colorMappers == null && widget.colorMappers != null) || - (oldWidget.colorMappers != null && widget.colorMappers == null) || - (oldWidget.colorMappers != null && - widget.colorMappers != null && - oldWidget.colorMappers!.length != widget.colorMappers!.length); + (oldWidget.colorMappers != null && widget.colorMappers == null) || + (oldWidget.colorMappers != null && + widget.colorMappers != null && + oldWidget.colorMappers!.length != widget.colorMappers!.length); if (_levelsLength != widget.levels.length) { _levelsLength = widget.levels.length; @@ -1082,7 +1216,8 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - _isDesktop = kIsWeb || + _isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; @@ -1090,32 +1225,38 @@ class _TreemapState extends State with SingleTickerProviderStateMixin { future: _computeDataSource, builder: (BuildContext context, AsyncSnapshot snapshot) { return LayoutBuilder( - builder: (BuildContext context, BoxConstraints constraints) { - final Size size = Size( + builder: (BuildContext context, BoxConstraints constraints) { + final Size size = Size( constraints.hasBoundedWidth ? constraints.maxWidth : 300, - constraints.hasBoundedHeight ? constraints.maxHeight : 300); - - // While resizing or changing orientation in an running drill down - // animation, force it to complete. - if (widget.enableDrilldown && - _drilldownAnimationController!.isAnimating) { - _drilldownAnimationController!.value = - _drilldownAnimationController!.status == AnimationStatus.forward - ? 1.0 - : 0.0; - } + constraints.hasBoundedHeight ? constraints.maxHeight : 300, + ); - return SizedBox( - width: size.width, - height: size.height, - child: snapshot.hasData - ? Stack(children: [ - _buildTreemap(context, snapshot.hasData), - if (_isTooltipEnabled) _tooltip, - ]) - : null, - ); - }); + // While resizing or changing orientation in an running drill down + // animation, force it to complete. + if (widget.enableDrilldown && + _drilldownAnimationController!.isAnimating) { + _drilldownAnimationController!.value = + _drilldownAnimationController!.status == + AnimationStatus.forward + ? 1.0 + : 0.0; + } + + return SizedBox( + width: size.width, + height: size.height, + child: + snapshot.hasData + ? Stack( + children: [ + _buildTreemap(context, snapshot.hasData), + if (_isTooltipEnabled) _tooltip, + ], + ) + : null, + ); + }, + ); }, ); } @@ -1162,11 +1303,14 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> // its location and size for its children. @override List _buildTiles( - Map source, double aggregatedWeight, Size size, - {Offset offset = Offset.zero, - int start = 0, - int? end, - bool canLayoutTiles = true}) { + Map source, + double aggregatedWeight, + Size size, { + Offset offset = Offset.zero, + int start = 0, + int? end, + bool canLayoutTiles = true, + }) { final Size widgetSize = size; double groupArea = 0; double referenceArea; @@ -1174,22 +1318,32 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> double? groupInitialTileArea; final List tiles = source.values.toList(); // Sorting the tiles in descending order. - tiles.sort((TreemapTile src, TreemapTile target) => - target.weight.compareTo(src.weight)); + tiles.sort( + (TreemapTile src, TreemapTile target) => + target.weight.compareTo(src.weight), + ); end ??= tiles.length; final List children = []; for (int i = start; i < end; i++) { final TreemapTile tile = tiles[i]; if (!canLayoutTiles) { - children.addAll(_getTileWidgets( - tiles, size, offset, start, tiles.length, - canLayoutTiles: false)); + children.addAll( + _getTileWidgets( + tiles, + size, + offset, + start, + tiles.length, + canLayoutTiles: false, + ), + ); return children; } else { // Area of rectangle = length * width. // Divide the tile weight with aggregatedWeight to get the area factor. // Multiply it with rectangular area to get the actual area of a tile. - tile._area = widgetSize.height * + tile._area = + widgetSize.height * widgetSize.width * (tile.weight / aggregatedWeight); groupInitialTileArea ??= tile._area; @@ -1197,8 +1351,9 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> final double area = (groupArea + tile._area!) / size.shortestSide; referenceArea = groupInitialTileArea! / area; final double currentAspectRatio = max( - _getAspectRatio(referenceArea, area), - _getAspectRatio(tile._area! / area, area)); + _getAspectRatio(referenceArea, area), + _getAspectRatio(tile._area! / area, area), + ); if (prevAspectRatio == null || currentAspectRatio < prevAspectRatio) { prevAspectRatio = currentAspectRatio; groupArea += tile._area!; @@ -1206,29 +1361,47 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> // Aligning the tiles vertically. if (size.width > size.height) { children.addAll( - _getTileWidgets(tiles, Size(groupArea / size.height, size.height), - offset, start, i, - axis: Axis.vertical), + _getTileWidgets( + tiles, + Size(groupArea / size.height, size.height), + offset, + start, + i, + axis: Axis.vertical, + ), ); offset += Offset(groupArea / size.height, 0); - size = - Size(max(0, size.width) - groupArea / size.height, size.height); + size = Size( + max(0, size.width) - groupArea / size.height, + size.height, + ); } // Aligning the tiles horizontally. else { - children.addAll(_getTileWidgets(tiles, - Size(size.width, groupArea / size.width), offset, start, i, - axis: Axis.horizontal)); + children.addAll( + _getTileWidgets( + tiles, + Size(size.width, groupArea / size.width), + offset, + start, + i, + axis: Axis.horizontal, + ), + ); offset += Offset(0, groupArea / size.width); - size = - Size(size.width, max(0, size.height) - groupArea / size.width); + size = Size( + size.width, + max(0, size.height) - groupArea / size.width, + ); } start = i; groupInitialTileArea = groupArea = tile._area!; referenceArea = tile._area! / (groupInitialTileArea / size.shortestSide); - prevAspectRatio = - _getAspectRatio(referenceArea, tile._area! / size.shortestSide); + prevAspectRatio = _getAspectRatio( + referenceArea, + tile._area! / size.shortestSide, + ); } } } @@ -1237,15 +1410,25 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> // the given source. if (size.width > size.height) { children.addAll( - _getTileWidgets(tiles, Size(groupArea / size.height, size.height), - offset, start, end, - axis: Axis.vertical), + _getTileWidgets( + tiles, + Size(groupArea / size.height, size.height), + offset, + start, + end, + axis: Axis.vertical, + ), ); } else { children.addAll( - _getTileWidgets(tiles, Size(groupArea / size.height, size.height), - offset, start, end, - axis: Axis.horizontal), + _getTileWidgets( + tiles, + Size(groupArea / size.height, size.height), + offset, + start, + end, + axis: Axis.horizontal, + ), ); } @@ -1253,8 +1436,14 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> } List _getTileWidgets( - List source, Size size, Offset offset, int start, int end, - {Axis? axis, bool canLayoutTiles = true}) { + List source, + Size size, + Offset offset, + int start, + int end, { + Axis? axis, + bool canLayoutTiles = true, + }) { final List<_Tile> tiles = <_Tile>[]; for (int i = start; i < end; i++) { final TreemapTile tileDetails = source[i]; @@ -1272,20 +1461,26 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> } } - tiles.add(_Tile( - size: tileDetails._size!, - details: tileDetails, - tooltipKey: widget.tooltipKey, - layoutDirection: widget.layoutDirection, - sortAscending: false, - controller: widget.controller, - onSelectionChanged: widget.onSelectionChanged, - selectionSettings: widget.selectionSettings, - drilldownAnimationController: widget.drilldownAnimationController, - child: _getDescendants( - context, tileDetails, widget.controller, widget.enableDrillDown, - animationController: widget.drilldownAnimationController), - )); + tiles.add( + _Tile( + size: tileDetails._size!, + details: tileDetails, + tooltipKey: widget.tooltipKey, + layoutDirection: widget.layoutDirection, + sortAscending: false, + controller: widget.controller, + onSelectionChanged: widget.onSelectionChanged, + selectionSettings: widget.selectionSettings, + drilldownAnimationController: widget.drilldownAnimationController, + child: _getDescendants( + context, + tileDetails, + widget.controller, + widget.enableDrillDown, + animationController: widget.drilldownAnimationController, + ), + ), + ); } return tiles; @@ -1297,8 +1492,12 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> void _handleDrillDown(TreemapTile tile, bool isDrilledIn) { setState(() { - _computeDrilldownTweenValue(tile, widget.drilldownAnimationController!, - widget.breadcrumbKey, isDrilledIn); + _computeDrilldownTweenValue( + tile, + widget.drilldownAnimationController!, + widget.breadcrumbKey, + isDrilledIn, + ); }); } @@ -1318,9 +1517,13 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> _visibleTile = widget.initialTile; if (widget.enableDrillDown) { _scaleAndTranslationAnimation = CurvedAnimation( - parent: widget.drilldownAnimationController!, curve: Curves.linear); + parent: widget.drilldownAnimationController!, + curve: Curves.linear, + ); _opacityAnimation = CurvedAnimation( - parent: widget.drilldownAnimationController!, curve: Curves.linear); + parent: widget.drilldownAnimationController!, + curve: Curves.linear, + ); _tileOpacity = Tween(); _labelAndItemBuilderOpacity = Tween(); _visibleTileTranslation = Tween(); @@ -1328,8 +1531,9 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> _nextTileTranslation = Tween(); _nextTileScaleSize = Tween(); widget.controller.addDrillDownListener(_handleDrillDown); - widget.drilldownAnimationController! - .addStatusListener(_handleAnimationStatusChange); + widget.drilldownAnimationController!.addStatusListener( + _handleAnimationStatusChange, + ); } super.initState(); @@ -1339,8 +1543,9 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> void didUpdateWidget(_SquarifiedTreemap oldWidget) { if (oldWidget.layoutDirection != widget.layoutDirection) { if (widget.tooltipKey.currentContext != null) { - final RenderTooltip tooltipRenderBox = widget.tooltipKey.currentContext! - .findRenderObject()! as RenderTooltip; + final RenderTooltip tooltipRenderBox = + widget.tooltipKey.currentContext!.findRenderObject()! + as RenderTooltip; tooltipRenderBox.hide(immediately: true); } } @@ -1351,8 +1556,9 @@ class _SquarifiedTreemapState extends State<_SquarifiedTreemap> void dispose() { if (widget.enableDrillDown) { widget.controller.removeDrillDownListener(_handleDrillDown); - widget.drilldownAnimationController! - .removeStatusListener(_handleAnimationStatusChange); + widget.drilldownAnimationController!.removeStatusListener( + _handleAnimationStatusChange, + ); } super.dispose(); @@ -1424,56 +1630,69 @@ class _SliceAndDiceTreemapState extends State<_SliceAndDiceTreemap> with SingleTickerProviderStateMixin, _TreemapMixin { @override List _buildTiles( - Map source, double aggregatedWeight, Size size, - {bool canLayoutTiles = true}) { + Map source, + double aggregatedWeight, + Size size, { + bool canLayoutTiles = true, + }) { final List children = []; final List tiles = source.values.toList(); Offset offset = Offset.zero; // Sorting the tiles in ascending/descending order based on the // [sortAscending]. if (widget.sortAscending) { - tiles.sort((TreemapTile src, TreemapTile target) => - src.weight.compareTo(target.weight)); + tiles.sort( + (TreemapTile src, TreemapTile target) => + src.weight.compareTo(target.weight), + ); } else { - tiles.sort((TreemapTile target, TreemapTile src) => - src.weight.compareTo(target.weight)); + tiles.sort( + (TreemapTile target, TreemapTile src) => + src.weight.compareTo(target.weight), + ); } for (final TreemapTile tile in tiles) { if (canLayoutTiles) { if (widget.type == LayoutType.slice) { tile - .._size = - Size(size.width, size.height * (tile.weight / aggregatedWeight)) + .._size = Size( + size.width, + size.height * (tile.weight / aggregatedWeight), + ) .._offset = offset; offset += Offset(0, tile._size!.height); } else { tile - .._size = - Size(size.width * (tile.weight / aggregatedWeight), size.height) + .._size = Size( + size.width * (tile.weight / aggregatedWeight), + size.height, + ) .._offset = offset; offset += Offset(tile._size!.width, 0); } } - children.add(_Tile( - type: widget.type, - size: tile._size!, - details: tile, - tooltipKey: widget.tooltipKey, - layoutDirection: TreemapLayoutDirection.topLeft, - sortAscending: widget.sortAscending, - controller: widget.controller, - onSelectionChanged: widget.onSelectionChanged, - selectionSettings: widget.selectionSettings, - drilldownAnimationController: widget.drilldownAnimationController, - child: _getDescendants( - context, - tile, - widget.controller, - widget.enableDrillDown, - animationController: widget.drilldownAnimationController, + children.add( + _Tile( + type: widget.type, + size: tile._size!, + details: tile, + tooltipKey: widget.tooltipKey, + layoutDirection: TreemapLayoutDirection.topLeft, + sortAscending: widget.sortAscending, + controller: widget.controller, + onSelectionChanged: widget.onSelectionChanged, + selectionSettings: widget.selectionSettings, + drilldownAnimationController: widget.drilldownAnimationController, + child: _getDescendants( + context, + tile, + widget.controller, + widget.enableDrillDown, + animationController: widget.drilldownAnimationController, + ), ), - )); + ); } return children; @@ -1481,8 +1700,12 @@ class _SliceAndDiceTreemapState extends State<_SliceAndDiceTreemap> void _handleDrillDown(TreemapTile tile, bool isDrilledIn) { setState(() { - _computeDrilldownTweenValue(tile, widget.drilldownAnimationController!, - widget.breadcrumbKey, isDrilledIn); + _computeDrilldownTweenValue( + tile, + widget.drilldownAnimationController!, + widget.breadcrumbKey, + isDrilledIn, + ); }); } @@ -1502,9 +1725,13 @@ class _SliceAndDiceTreemapState extends State<_SliceAndDiceTreemap> _visibleTile = widget.initialTile; if (widget.enableDrillDown) { _scaleAndTranslationAnimation = CurvedAnimation( - parent: widget.drilldownAnimationController!, curve: Curves.linear); + parent: widget.drilldownAnimationController!, + curve: Curves.linear, + ); _opacityAnimation = CurvedAnimation( - parent: widget.drilldownAnimationController!, curve: Curves.linear); + parent: widget.drilldownAnimationController!, + curve: Curves.linear, + ); _tileOpacity = Tween(); _labelAndItemBuilderOpacity = Tween(); _visibleTileTranslation = Tween(); @@ -1512,8 +1739,9 @@ class _SliceAndDiceTreemapState extends State<_SliceAndDiceTreemap> _nextTileTranslation = Tween(); _nextTileScaleSize = Tween(); widget.controller.addDrillDownListener(_handleDrillDown); - widget.drilldownAnimationController! - .addStatusListener(_handleAnimationStatusChange); + widget.drilldownAnimationController!.addStatusListener( + _handleAnimationStatusChange, + ); } super.initState(); @@ -1523,8 +1751,9 @@ class _SliceAndDiceTreemapState extends State<_SliceAndDiceTreemap> void dispose() { if (widget.enableDrillDown) { widget.controller.removeDrillDownListener(_handleDrillDown); - widget.drilldownAnimationController! - .removeStatusListener(_handleAnimationStatusChange); + widget.drilldownAnimationController!.removeStatusListener( + _handleAnimationStatusChange, + ); } super.dispose(); @@ -1542,7 +1771,9 @@ class _SliceAndDiceTreemapState extends State<_SliceAndDiceTreemap> if (widget.drilldownAnimationController != null && widget.drilldownAnimationController!.isAnimating) { return _buildAnimatedTreemap( - widget.drilldownAnimationController!, widget.breadcrumbKey); + widget.drilldownAnimationController!, + widget.breadcrumbKey, + ); } return Stack( @@ -1588,9 +1819,10 @@ class _Tile extends StatelessWidget { @override Widget build(BuildContext context) { - final dynamic ancestor = type == LayoutType.squarified - ? context.findAncestorStateOfType<_SquarifiedTreemapState>()! - : context.findAncestorStateOfType<_SliceAndDiceTreemapState>()!; + final dynamic ancestor = + type == LayoutType.squarified + ? context.findAncestorStateOfType<_SquarifiedTreemapState>()! + : context.findAncestorStateOfType<_SliceAndDiceTreemapState>()!; Widget current = _TileDecor( size: size, @@ -1606,8 +1838,9 @@ class _Tile extends StatelessWidget { ); if (details._padding != null) { - EdgeInsets padding = - details._padding!.resolve(Directionality.of(context)); + EdgeInsets padding = details._padding!.resolve( + Directionality.of(context), + ); // if we forward 0 -> 1st level, we need to ignore scaling to the 0th // level tiles only. If we backward 1 -> 0th level we need to ignore // scaling for both levels. @@ -1623,18 +1856,25 @@ class _Tile extends StatelessWidget { // tiles. if (drilldownAnimationController!.status == AnimationStatus.reverse && controller.visibleLevelIndex == details._levelIndex) { - scaleSize = ancestor._nextTileScaleSize! - .evaluate(ancestor._scaleAndTranslationAnimation) as Size; + scaleSize = + ancestor._nextTileScaleSize!.evaluate( + ancestor._scaleAndTranslationAnimation, + ) + as Size; } else { - scaleSize = ancestor._visibleTileScaleSize! - .evaluate(ancestor._scaleAndTranslationAnimation) as Size; + scaleSize = + ancestor._visibleTileScaleSize!.evaluate( + ancestor._scaleAndTranslationAnimation, + ) + as Size; } padding = EdgeInsets.fromLTRB( - padding.left / scaleSize.width, - padding.top / scaleSize.height, - padding.right / scaleSize.width, - padding.bottom / scaleSize.height); + padding.left / scaleSize.width, + padding.top / scaleSize.height, + padding.right / scaleSize.width, + padding.bottom / scaleSize.height, + ); } current = Padding(padding: padding, child: current); @@ -1739,9 +1979,9 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { } if (border != null && widget.details.level.border != null) { return widget.details.level.border!.copyWith( - side: border.side, - borderRadius: - border.borderRadius.resolve(Directionality.of(context))); + side: border.side, + borderRadius: border.borderRadius.resolve(Directionality.of(context)), + ); } return border ?? widget.details.level.border; } @@ -1749,7 +1989,8 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { Widget _buildTileDecor(Widget child, BuildContext context) { Widget current = child; if (_canAddInteractableWidget || _ancestor.enableDrilldown) { - final bool allow = !_ancestor.enableDrilldown || + final bool allow = + !_ancestor.enableDrilldown || (widget.controller.visibleLevelIndex == widget.details._levelIndex && !widget.drilldownAnimationController!.isAnimating); @@ -1767,8 +2008,9 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { widget.controller.hoveredTile = widget.details; } - treemapState - ._updateLegendPointer(widget.details._colorValue?.toDouble()); + treemapState._updateLegendPointer( + widget.details._colorValue?.toDouble(), + ); }, onHover: (PointerHoverEvent event) { // Updating the [widget.controller.hoveredTile] when hover @@ -1834,7 +2076,11 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { widget.tooltipKey.currentContext!.findRenderObject()! as RenderTooltip; tooltipRenderBox.show( - globalPosition, widget.details, referenceTileSize, kind); + globalPosition, + widget.details, + referenceTileSize, + kind, + ); } } @@ -1921,15 +2167,18 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { } else if (_ancestor.tileHoverColor == Colors.transparent) { _colorTween.begin = widget.details.color; } else if (_ancestor.tileHoverColor == null) { - _colorTween.begin = - _getSaturatedColor(widget.details.color, hoverSaturateFactor); + _colorTween.begin = _getSaturatedColor( + widget.details.color, + hoverSaturateFactor, + ); } } else { _colorTween.begin = widget.details.color; } - _colorTween.end = selectionColor == null - ? _getSaturatedColor(widget.details.color, selectionSaturateFactor) - : selectionColor == Colors.transparent + _colorTween.end = + selectionColor == null + ? _getSaturatedColor(widget.details.color, selectionSaturateFactor) + : selectionColor == Colors.transparent ? widget.details.color : selectionColor; } @@ -1940,8 +2189,9 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { } if (widget.details.indices.length < source.indices.length) { - return widget.details.indices - .any((int index) => source.indices.contains(index)); + return widget.details.indices.any( + (int index) => source.indices.contains(index), + ); } else if (widget.details.indices.length == source.indices.length) { for (final int index in widget.details.indices) { final bool hasIndex = source.indices.contains(index); @@ -1978,8 +2228,10 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { } else if (_ancestor.tileHoverColor == Colors.transparent) { _colorTween.end = widget.details.color; } else { - _colorTween.end = - _getSaturatedColor(widget.details.color, _getColorFactor()); + _colorTween.end = _getSaturatedColor( + widget.details.color, + _getColorFactor(), + ); } } @@ -1991,10 +2243,11 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { } else if (widget.drilldownAnimationController!.status == AnimationStatus.reverse) { if (widget.details._isDrilled) { - _colorTween.begin = widget.ancestor._visibleTile._levelIndex + 1 == - widget.details._levelIndex - ? widget.details.color - : Colors.transparent; + _colorTween.begin = + widget.ancestor._visibleTile._levelIndex + 1 == + widget.details._levelIndex + ? widget.details.color + : Colors.transparent; _colorTween.end = Colors.transparent; } } @@ -2009,11 +2262,16 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { return _colorTween.evaluate(_animation)!; } - Widget _buildTileBorder(Widget child, EdgeInsets dimensions, - RoundedRectangleBorder? border, Size? scaleSize) { + Widget _buildTileBorder( + Widget child, + EdgeInsets dimensions, + RoundedRectangleBorder? border, + Size? scaleSize, + ) { if (border != null) { - BorderRadius borderRadius = - border.borderRadius.resolve(Directionality.of(context)); + BorderRadius borderRadius = border.borderRadius.resolve( + Directionality.of(context), + ); if (widget.drilldownAnimationController != null && ((widget.drilldownAnimationController!.status == AnimationStatus.forward && @@ -2028,21 +2286,26 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { if (widget.drilldownAnimationController!.status == AnimationStatus.reverse && widget.controller.visibleLevelIndex == widget.details._levelIndex) { - scaleSize = widget.ancestor._nextTileScaleSize! - .evaluate(widget.ancestor._scaleAndTranslationAnimation) as Size; + scaleSize = + widget.ancestor._nextTileScaleSize!.evaluate( + widget.ancestor._scaleAndTranslationAnimation, + ) + as Size; } borderRadius = _getBorderRadius(borderRadius, scaleSize!); border = AnimatedBorder( - borderRadius: borderRadius, - side: border.side, - scaleSize: scaleSize); + borderRadius: borderRadius, + side: border.side, + scaleSize: scaleSize, + ); dimensions = border.dimensions.resolve(Directionality.of(context)); dimensions = EdgeInsets.fromLTRB( - dimensions.left / scaleSize.width, - dimensions.top / scaleSize.height, - dimensions.right / scaleSize.width, - dimensions.bottom / scaleSize.height); + dimensions.left / scaleSize.width, + dimensions.top / scaleSize.height, + dimensions.right / scaleSize.width, + dimensions.bottom / scaleSize.height, + ); } } @@ -2050,28 +2313,38 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { size: widget.size, foregroundPainter: _BorderPainter(border), child: ClipPath.shape( - shape: border ?? const RoundedRectangleBorder(), - child: Padding(padding: dimensions, child: child)), + shape: border ?? const RoundedRectangleBorder(), + child: Padding(padding: dimensions, child: child), + ), ); } BorderRadius _getBorderRadius(BorderRadius borderRadius, Size scaleSize) { return BorderRadius.only( - topRight: Radius.elliptical(borderRadius.topRight.x / scaleSize.width, - borderRadius.topRight.y / scaleSize.height), - bottomLeft: Radius.elliptical( - borderRadius.bottomLeft.x / scaleSize.width, - borderRadius.bottomLeft.y / scaleSize.height), - bottomRight: Radius.elliptical( - borderRadius.bottomRight.x / scaleSize.width, - borderRadius.bottomRight.y / scaleSize.height), - topLeft: Radius.elliptical(borderRadius.topLeft.x / scaleSize.width, - borderRadius.topLeft.y / scaleSize.height)); + topRight: Radius.elliptical( + borderRadius.topRight.x / scaleSize.width, + borderRadius.topRight.y / scaleSize.height, + ), + bottomLeft: Radius.elliptical( + borderRadius.bottomLeft.x / scaleSize.width, + borderRadius.bottomLeft.y / scaleSize.height, + ), + bottomRight: Radius.elliptical( + borderRadius.bottomRight.x / scaleSize.width, + borderRadius.bottomRight.y / scaleSize.height, + ), + topLeft: Radius.elliptical( + borderRadius.topLeft.x / scaleSize.width, + borderRadius.topLeft.y / scaleSize.height, + ), + ); } Widget? _buildItemBuilder(Widget? current) { - Widget? itemBuilder = - widget.details.level.itemBuilder!(context, widget.details); + Widget? itemBuilder = widget.details.level.itemBuilder!( + context, + widget.details, + ); if (itemBuilder == null) { return current; } @@ -2092,10 +2365,7 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { } if (current != null) { - current = Stack(children: [ - itemBuilder!, - current, - ]); + current = Stack(children: [itemBuilder!, current]); } else { current = itemBuilder; } @@ -2106,16 +2376,21 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { @override void initState() { _mouseIsConnected = RendererBinding.instance.mouseTracker.mouseIsConnected; - RendererBinding.instance.mouseTracker - .addListener(_handleMouseTrackerChange); + RendererBinding.instance.mouseTracker.addListener( + _handleMouseTrackerChange, + ); _controller = AnimationController( - duration: const Duration(milliseconds: 200), vsync: this); + duration: const Duration(milliseconds: 200), + vsync: this, + ); _animation = CurvedAnimation(parent: _controller, curve: Curves.linear); _animation.addListener(_rebuild); - _colorTween = - ColorTween(begin: widget.details.color, end: widget.details.color); + _colorTween = ColorTween( + begin: widget.details.color, + end: widget.details.color, + ); widget.controller ..addSelectionListener(_handleSelectionChange) @@ -2136,11 +2411,14 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { void didUpdateWidget(_TileDecor oldWidget) { if (widget.sortAscending != oldWidget.sortAscending || widget.details.color != oldWidget.details.color) { - _colorTween = - ColorTween(begin: widget.details.color, end: widget.details.color); + _colorTween = ColorTween( + begin: widget.details.color, + end: widget.details.color, + ); if (widget.details.level.tooltipBuilder != null) { - final RenderTooltip tooltipRenderBox = widget.tooltipKey.currentContext! - .findRenderObject()! as RenderTooltip; + final RenderTooltip tooltipRenderBox = + widget.tooltipKey.currentContext!.findRenderObject()! + as RenderTooltip; tooltipRenderBox.hide(immediately: true); } } @@ -2156,8 +2434,9 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { ..removeSelectionListener(_handleSelectionChange) ..removeHoverListener(_handleHover); - RendererBinding.instance.mouseTracker - .removeListener(_handleMouseTrackerChange); + RendererBinding.instance.mouseTracker.removeListener( + _handleMouseTrackerChange, + ); super.dispose(); } @@ -2172,8 +2451,11 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { Size? scaleSize; if (_ancestor.enableDrilldown && widget.ancestor._visibleTileScaleSize.begin != null) { - scaleSize = widget.ancestor._visibleTileScaleSize! - .evaluate(widget.ancestor._scaleAndTranslationAnimation) as Size; + scaleSize = + widget.ancestor._visibleTileScaleSize!.evaluate( + widget.ancestor._scaleAndTranslationAnimation, + ) + as Size; } if (widget.details.level.itemBuilder != null) { @@ -2190,8 +2472,12 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { final RoundedRectangleBorder? border = _getBorder(); final EdgeInsetsGeometry dimensions = border?.dimensions ?? EdgeInsets.zero; if (border != null || widget.onSelectionChanged != null) { - current = _buildTileBorder(current, - dimensions.resolve(Directionality.of(context)), border, scaleSize); + current = _buildTileBorder( + current, + dimensions.resolve(Directionality.of(context)), + border, + scaleSize, + ); } if (!widget.details.hasDescendants || _ancestor.enableDrilldown) { @@ -2207,7 +2493,7 @@ class _TileDecorState extends State<_TileDecor> with TickerProviderStateMixin { if (widget.child != null) _ancestor.enableDrilldown ? widget.child! - : Padding(padding: dimensions, child: widget.child) + : Padding(padding: dimensions, child: widget.child), ], ); } @@ -2288,9 +2574,11 @@ class _BreadcrumbsState extends State<_Breadcrumbs> final int nextLevelIndex = _current._levelIndex + 1; for (int i = 0; i < breadcrumbTilesLength; i++) { - _breadcrumbs.add(i > nextLevelIndex - ? fadeOutBreadcrumb[i] - : widget.settings.builder(context, _tiles[i], i == nextLevelIndex)!); + _breadcrumbs.add( + i > nextLevelIndex + ? fadeOutBreadcrumb[i] + : widget.settings.builder(context, _tiles[i], i == nextLevelIndex)!, + ); } } @@ -2322,7 +2610,9 @@ class _BreadcrumbsState extends State<_Breadcrumbs> _breadcrumbItemKey = GlobalKey(); _opacityAnimation = CurvedAnimation( - parent: widget.animationController, curve: Curves.decelerate); + parent: widget.animationController, + curve: Curves.decelerate, + ); widget.animationController.addStatusListener(_handleStatusChange); widget.controller.addDrillDownListener(_handleDrilldown); @@ -2344,9 +2634,11 @@ class _BreadcrumbsState extends State<_Breadcrumbs> if (_breadcrumbs.isEmpty) { _breadcrumbs.add(widget.settings.builder(context, _current, true)); } - final Color dividerColor = - Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.54); - final Widget divider = widget.settings.divider ?? + final Color dividerColor = Theme.of( + context, + ).colorScheme.onSurface.withValues(alpha: 0.54); + final Widget divider = + widget.settings.divider ?? Icon(Icons.chevron_right, size: 16.0, color: dividerColor); for (int i = 0; i < length; i++) { @@ -2365,17 +2657,19 @@ class _BreadcrumbsState extends State<_Breadcrumbs> final bool canApplyOpacity = (widget.animationController.status == AnimationStatus.forward && - _current._levelIndex == _tiles[i]._levelIndex) || - widget.animationController.status == AnimationStatus.reverse && - _current._levelIndex < _tiles[i]._levelIndex; - - children.add(_Breadcrumb( - tile: _tiles[i], - controller: widget.controller, - animation: _opacityAnimation, - canApplyOpacity: canApplyOpacity, - child: current, - )); + _current._levelIndex == _tiles[i]._levelIndex) || + widget.animationController.status == AnimationStatus.reverse && + _current._levelIndex < _tiles[i]._levelIndex; + + children.add( + _Breadcrumb( + tile: _tiles[i], + controller: widget.controller, + animation: _opacityAnimation, + canApplyOpacity: canApplyOpacity, + child: current, + ), + ); } } @@ -2393,12 +2687,16 @@ class _BreadcrumbsState extends State<_Breadcrumbs> key: _breadcrumbItemKey, duration: const Duration(milliseconds: 1000), padding: EdgeInsets.only( - left: padding.left, top: 11.0, bottom: 9.0, right: padding.right), + left: padding.left, + top: 11.0, + bottom: 9.0, + right: padding.right, + ), child: Stack( alignment: Alignment.centerLeft, children: [ Opacity(opacity: 0.0, child: divider), - if (current != null) current + if (current != null) current, ], ), ); @@ -2408,7 +2706,9 @@ class _BreadcrumbsState extends State<_Breadcrumbs> } return SingleChildScrollView( - scrollDirection: Axis.horizontal, child: current); + scrollDirection: Axis.horizontal, + child: current, + ); } } @@ -2440,9 +2740,10 @@ class _BreadcrumbState extends State<_Breadcrumb> { // State is not preserved, when a widget's visual tree is changed // dynamically. So that gesture widget wrapped into the ignore pointer. current = IgnorePointer( - ignoring: !((widget.animation.isCompleted || - widget.animation.isDismissed) && - widget.tile._levelIndex != widget.controller.visibleLevelIndex - 1), + ignoring: + !((widget.animation.isCompleted || widget.animation.isDismissed) && + widget.tile._levelIndex != + widget.controller.visibleLevelIndex - 1), child: MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( diff --git a/packages/syncfusion_flutter_treemap/lib/src/legend.dart b/packages/syncfusion_flutter_treemap/lib/src/legend.dart index 6040dd4a6..84d2b7de5 100644 --- a/packages/syncfusion_flutter_treemap/lib/src/legend.dart +++ b/packages/syncfusion_flutter_treemap/lib/src/legend.dart @@ -17,8 +17,8 @@ enum _LegendType { } /// Signature to return a [Widget] for the given value. -typedef TreemapLegendPointerBuilder = Widget Function( - BuildContext context, dynamic value); +typedef TreemapLegendPointerBuilder = + Widget Function(BuildContext context, dynamic value); /// Positions the legend in the different directions. enum TreemapLegendPosition { @@ -69,7 +69,7 @@ enum TreemapLabelOverflow { /// It trims the labels based on the available space in their respective /// legend item. - ellipsis + ellipsis, } /// Option to place the labels either between the bars or on the bar in bar @@ -81,7 +81,7 @@ enum TreemapLegendLabelsPlacement { /// [TreemapLegendLabelsPlacement.betweenItems] places labels /// in-between two bars. - betweenItems + betweenItems, } /// Placement of edge labels in the bar legend. @@ -91,7 +91,7 @@ enum TreemapLegendEdgeLabelsPlacement { /// Place the edge labels in the center of the starting position of the /// legend bars. - center + center, } /// Applies gradient or solid color for the bar segments. @@ -100,7 +100,7 @@ enum TreemapLegendPaintingStyle { solid, /// Applies gradient color for bar segments. - gradient + gradient, } /// Shows legend for the data rendered in the treemap. @@ -321,17 +321,17 @@ class TreemapLegend extends DiagnosticableTree { this.textStyle, this.iconType = TreemapIconType.circle, this.iconSize = const Size(8.0, 8.0), - }) : _type = _LegendType.vector, - segmentSize = null, - labelsPlacement = null, - edgeLabelsPlacement = TreemapLegendEdgeLabelsPlacement.inside, - labelOverflow = TreemapLabelOverflow.visible, - segmentPaintingStyle = TreemapLegendPaintingStyle.solid, - showPointerOnHover = false, - pointerBuilder = null, - pointerColor = null, - pointerSize = const Size(16, 12), - assert(spacing >= 0); + }) : _type = _LegendType.vector, + segmentSize = null, + labelsPlacement = null, + edgeLabelsPlacement = TreemapLegendEdgeLabelsPlacement.inside, + labelOverflow = TreemapLabelOverflow.visible, + segmentPaintingStyle = TreemapLegendPaintingStyle.solid, + showPointerOnHover = false, + pointerBuilder = null, + pointerColor = null, + pointerSize = const Size(16, 12), + assert(spacing >= 0); /// Creates a bar type legend for the tree map. /// @@ -442,10 +442,10 @@ class TreemapLegend extends DiagnosticableTree { this.pointerBuilder, this.pointerColor, this.pointerSize = const Size(16, 12), - }) : _type = _LegendType.bar, - iconType = TreemapIconType.circle, - iconSize = const Size(8.0, 8.0), - assert(spacing >= 0); + }) : _type = _LegendType.bar, + iconType = TreemapIconType.circle, + iconSize = const Size(8.0, 8.0), + assert(spacing >= 0); /// Enables a title for the legends to provide a small note about the legends. /// @@ -1465,16 +1465,25 @@ class TreemapLegend extends DiagnosticableTree { } @override - int get hashCode => Object.hash(padding, offset, spacing, direction, - overflowMode, position, textStyle, title); + int get hashCode => Object.hash( + padding, + offset, + spacing, + direction, + overflowMode, + position, + textStyle, + title, + ); @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(EnumProperty<_LegendType>('legendType', _type)); if (padding != null) { - properties - .add(DiagnosticsProperty('padding', padding)); + properties.add( + DiagnosticsProperty('padding', padding), + ); } if (offset != null) { properties.add(DiagnosticsProperty('offset', offset)); @@ -1484,7 +1493,8 @@ class TreemapLegend extends DiagnosticableTree { properties.add(EnumProperty('direction', direction)); } properties.add( - EnumProperty('overflowMode', overflowMode)); + EnumProperty('overflowMode', overflowMode), + ); properties.add(EnumProperty('position', position)); if (textStyle != null) { properties.add(textStyle!.toDiagnosticsNode(name: 'textStyle')); @@ -1496,14 +1506,27 @@ class TreemapLegend extends DiagnosticableTree { if (segmentSize != null) { properties.add(DiagnosticsProperty('segmentSize', segmentSize)); } - properties.add(EnumProperty( - 'labelsPlacement', labelsPlacement)); - properties.add(EnumProperty( - 'edgeLabelsPlacement', edgeLabelsPlacement)); - properties.add(EnumProperty( - 'labelOverflowMode', labelOverflow)); - properties.add(EnumProperty( - 'segmentPaintingStyle', segmentPaintingStyle)); + properties.add( + EnumProperty( + 'labelsPlacement', + labelsPlacement, + ), + ); + properties.add( + EnumProperty( + 'edgeLabelsPlacement', + edgeLabelsPlacement, + ), + ); + properties.add( + EnumProperty('labelOverflowMode', labelOverflow), + ); + properties.add( + EnumProperty( + 'segmentPaintingStyle', + segmentPaintingStyle, + ), + ); } } } @@ -1518,8 +1541,8 @@ class Legend extends StatelessWidget { required this.legend, required this.controller, required this.child, - }) : assert(colorMappers != null || dataSource != null), - super(key: key); + }) : assert(colorMappers != null || dataSource != null), + super(key: key); /// Collection of [TreemapColorMapper] which specifies treemap color based /// on the data. @@ -1553,15 +1576,18 @@ class Legend extends StatelessWidget { final String startValue = _getStartSegmentLabel(colorMapper); items.add(LegendItem(text: startValue, color: colorMapper.color)); } else { - final String text = colorMapper.from != null - ? colorMapper.name ?? colorMapper.to.toString() - : colorMapper.value!; + final String text = + colorMapper.from != null + ? colorMapper.name ?? colorMapper.to.toString() + : colorMapper.value!; items.add(LegendItem(text: text, color: colorMapper.color)); } } else { - final String text = colorMapper.from != null - ? colorMapper.name ?? '${colorMapper.from} - ${colorMapper.to}' - : colorMapper.value!; + final String text = + colorMapper.from != null + ? colorMapper.name ?? + '${colorMapper.from} - ${colorMapper.to}' + : colorMapper.value!; items.add(LegendItem(text: text, color: colorMapper.color)); } } @@ -1612,7 +1638,8 @@ class Legend extends StatelessWidget { } LegendPaintingStyle _getEffectiveSegmentPaintingStyle( - TreemapLegendPaintingStyle paintingStyle) { + TreemapLegendPaintingStyle paintingStyle, + ) { switch (paintingStyle) { case TreemapLegendPaintingStyle.solid: return LegendPaintingStyle.solid; @@ -1622,7 +1649,8 @@ class Legend extends StatelessWidget { } LegendLabelOverflow _getEffectiveLabelOverflow( - TreemapLabelOverflow labelOverflow) { + TreemapLabelOverflow labelOverflow, + ) { switch (labelOverflow) { case TreemapLabelOverflow.visible: return LegendLabelOverflow.visible; @@ -1634,7 +1662,8 @@ class Legend extends StatelessWidget { } LegendEdgeLabelsPlacement _getEffectiveEdgeLabelsPlacement( - TreemapLegendEdgeLabelsPlacement edgeLabelsPlacement) { + TreemapLegendEdgeLabelsPlacement edgeLabelsPlacement, + ) { switch (edgeLabelsPlacement) { case TreemapLegendEdgeLabelsPlacement.center: return LegendEdgeLabelsPlacement.center; @@ -1644,7 +1673,8 @@ class Legend extends StatelessWidget { } LegendLabelsPlacement _getEffectiveLabelPlacement( - TreemapLegendLabelsPlacement labelsPlacement) { + TreemapLegendLabelsPlacement labelsPlacement, + ) { switch (labelsPlacement) { case TreemapLegendLabelsPlacement.betweenItems: return LegendLabelsPlacement.betweenItems; @@ -1667,7 +1697,8 @@ class Legend extends StatelessWidget { } LegendOverflowMode _getEffectiveOverflowMode( - TreemapLegendOverflowMode overflowMode) { + TreemapLegendOverflowMode overflowMode, + ) { switch (overflowMode) { case TreemapLegendOverflowMode.scroll: return LegendOverflowMode.scroll; @@ -1691,9 +1722,7 @@ class Legend extends StatelessWidget { @override Widget build(BuildContext context) { - final TextStyle legendTextStyle = Theme.of(context) - .textTheme - .bodySmall! + final TextStyle legendTextStyle = Theme.of(context).textTheme.bodySmall! .merge(SfTreemapTheme.of(context).legendTextStyle) .merge(legend.textStyle); switch (legend._type) { @@ -1725,14 +1754,17 @@ class Legend extends StatelessWidget { offset: legend.offset, padding: legend.padding, textStyle: legendTextStyle, - labelsPlacement: - _getEffectiveLabelPlacement(_getActualLabelsPlacement()), - edgeLabelsPlacement: - _getEffectiveEdgeLabelsPlacement(legend.edgeLabelsPlacement), + labelsPlacement: _getEffectiveLabelPlacement( + _getActualLabelsPlacement(), + ), + edgeLabelsPlacement: _getEffectiveEdgeLabelsPlacement( + legend.edgeLabelsPlacement, + ), labelOverflow: _getEffectiveLabelOverflow(legend.labelOverflow), segmentSize: legend.segmentSize, - segmentPaintingStyle: - _getEffectiveSegmentPaintingStyle(legend.segmentPaintingStyle), + segmentPaintingStyle: _getEffectiveSegmentPaintingStyle( + legend.segmentPaintingStyle, + ), pointerBuilder: legend.pointerBuilder, pointerColor: legend.pointerColor, pointerSize: diff --git a/packages/syncfusion_flutter_treemap/lib/src/tooltip.dart b/packages/syncfusion_flutter_treemap/lib/src/tooltip.dart index 6ea026620..169edc61b 100644 --- a/packages/syncfusion_flutter_treemap/lib/src/tooltip.dart +++ b/packages/syncfusion_flutter_treemap/lib/src/tooltip.dart @@ -37,7 +37,9 @@ class _TreemapTooltipState extends State @override void initState() { controller = AnimationController( - vsync: this, duration: const Duration(milliseconds: 200)); + vsync: this, + duration: const Duration(milliseconds: 200), + ); super.initState(); } @@ -50,25 +52,33 @@ class _TreemapTooltipState extends State @override Widget build(BuildContext context) { final ThemeData themeData = Theme.of(context); - _isDesktop = kIsWeb || + _isDesktop = + kIsWeb || themeData.platform == TargetPlatform.macOS || themeData.platform == TargetPlatform.windows || themeData.platform == TargetPlatform.linux; final TreemapTooltipSettings settings = widget.settings.copyWith( - color: widget.settings.color ?? - (themeData.brightness == Brightness.light - ? const Color.fromRGBO(117, 117, 117, 1) - : const Color.fromRGBO(245, 245, 245, 1))); + color: + widget.settings.color ?? + (themeData.brightness == Brightness.light + ? const Color.fromRGBO(117, 117, 117, 1) + : const Color.fromRGBO(245, 245, 245, 1)), + ); return _TreemapTooltipRenderObjectWidget( - settings: settings, state: this, child: _child); + settings: settings, + state: this, + child: _child, + ); } } /// A Render object widget which draws tooltip shape. class _TreemapTooltipRenderObjectWidget extends SingleChildRenderObjectWidget { - const _TreemapTooltipRenderObjectWidget( - {Widget? child, required this.settings, required this.state}) - : super(child: child); + const _TreemapTooltipRenderObjectWidget({ + Widget? child, + required this.settings, + required this.state, + }) : super(child: child); final _TreemapTooltipState state; final TreemapTooltipSettings settings; @@ -98,11 +108,13 @@ class RenderTooltip extends RenderProxyBox { required MediaQueryData mediaQueryData, // ignore: library_private_types_in_public_api required _TreemapTooltipState state, - }) : _settings = settings, - _mediaQueryData = mediaQueryData, - _state = state { - _scaleAnimation = - CurvedAnimation(parent: _state.controller, curve: Curves.easeOutBack); + }) : _settings = settings, + _mediaQueryData = mediaQueryData, + _state = state { + _scaleAnimation = CurvedAnimation( + parent: _state.controller, + curve: Curves.easeOutBack, + ); _textDirection = Directionality.of(_state.context); } @@ -146,8 +158,12 @@ class RenderTooltip extends RenderProxyBox { } /// Shows the tooltip. - void show(Offset globalFocalPoint, TreemapTile tile, Size tileSize, - PointerKind kind) { + void show( + Offset globalFocalPoint, + TreemapTile tile, + Size tileSize, + PointerKind kind, + ) { _pointerKind = kind; if (_state._isDesktop && _previousTile == tile) { return; @@ -235,8 +251,16 @@ class RenderTooltip extends RenderProxyBox { _shouldCalculateTooltipPosition = false; } - _tooltipShape.paint(context, offset, _position!, _preferTooltipOnTop, - this, _scaleAnimation, _settings, _textDirection); + _tooltipShape.paint( + context, + offset, + _position!, + _preferTooltipOnTop, + this, + _scaleAnimation, + _settings, + _textDirection, + ); } } @@ -253,8 +277,9 @@ class RenderTooltip extends RenderProxyBox { // Obtaining a tooltip position at 30% of the tile's height. _position = _position! + Offset(_tileSize!.width / 2, _tileSize!.height * 0.3); - _preferTooltipOnTop = - paintBounds.contains(_position! - Offset(0.0, height)); + _preferTooltipOnTop = paintBounds.contains( + _position! - Offset(0.0, height), + ); } } } @@ -267,21 +292,23 @@ class _TooltipShape { /// Paints the tooltip shapes based on the value passed to it. void paint( - PaintingContext context, - Offset offset, - Offset center, - bool preferTooltipOnTop, - RenderProxyBox parentBox, - Animation tooltipAnimation, - TreemapTooltipSettings tooltipSettings, - TextDirection textDirection) { + PaintingContext context, + Offset offset, + Offset center, + bool preferTooltipOnTop, + RenderProxyBox parentBox, + Animation tooltipAnimation, + TreemapTooltipSettings tooltipSettings, + TextDirection textDirection, + ) { const double tooltipTriangleWidth = 12.0; const double halfTooltipTriangleWidth = tooltipTriangleWidth / 2; const double elevation = 0.0; Path path = Path(); - BorderRadius borderRadius = - tooltipSettings.borderRadius.resolve(textDirection); + BorderRadius borderRadius = tooltipSettings.borderRadius.resolve( + textDirection, + ); final double tooltipWidth = parentBox.child!.size.width; double tooltipHeight = parentBox.child!.size.height; final double halfTooltipWidth = tooltipWidth / 2; @@ -292,29 +319,36 @@ class _TooltipShape { double tooltipTriangleOffsetY = tooltipStartPoint - triangleHeight; final double endGlobal = parentBox.size.width - marginSpace; - double rightLineWidth = center.dx + halfTooltipWidth > endGlobal - ? endGlobal - center.dx - : halfTooltipWidth; - final double leftLineWidth = center.dx - halfTooltipWidth < marginSpace - ? center.dx - marginSpace - : tooltipWidth - rightLineWidth; - rightLineWidth = leftLineWidth < halfTooltipWidth - ? halfTooltipWidth - leftLineWidth + rightLineWidth - : rightLineWidth; - - double moveNosePoint = leftLineWidth < tooltipWidth * 0.2 - ? tooltipWidth * 0.2 - leftLineWidth - : 0.0; - moveNosePoint = rightLineWidth < tooltipWidth * 0.2 - ? -(tooltipWidth * 0.2 - rightLineWidth) - : moveNosePoint; - - double shiftText = leftLineWidth > rightLineWidth - ? -(halfTooltipWidth - rightLineWidth) - : 0.0; - shiftText = leftLineWidth < rightLineWidth - ? (halfTooltipWidth - leftLineWidth) - : shiftText; + double rightLineWidth = + center.dx + halfTooltipWidth > endGlobal + ? endGlobal - center.dx + : halfTooltipWidth; + final double leftLineWidth = + center.dx - halfTooltipWidth < marginSpace + ? center.dx - marginSpace + : tooltipWidth - rightLineWidth; + rightLineWidth = + leftLineWidth < halfTooltipWidth + ? halfTooltipWidth - leftLineWidth + rightLineWidth + : rightLineWidth; + + double moveNosePoint = + leftLineWidth < tooltipWidth * 0.2 + ? tooltipWidth * 0.2 - leftLineWidth + : 0.0; + moveNosePoint = + rightLineWidth < tooltipWidth * 0.2 + ? -(tooltipWidth * 0.2 - rightLineWidth) + : moveNosePoint; + + double shiftText = + leftLineWidth > rightLineWidth + ? -(halfTooltipWidth - rightLineWidth) + : 0.0; + shiftText = + leftLineWidth < rightLineWidth + ? (halfTooltipWidth - leftLineWidth) + : shiftText; rightLineWidth = rightLineWidth + elevation; if (!preferTooltipOnTop) { @@ -329,42 +363,54 @@ class _TooltipShape { tooltipHeight *= -1; borderRadius = BorderRadius.only( topRight: Radius.elliptical( - borderRadius.bottomRight.x, -borderRadius.bottomRight.y), + borderRadius.bottomRight.x, + -borderRadius.bottomRight.y, + ), bottomRight: Radius.elliptical( - borderRadius.topRight.x, -borderRadius.topRight.y), + borderRadius.topRight.x, + -borderRadius.topRight.y, + ), topLeft: Radius.elliptical( - borderRadius.bottomLeft.x, -borderRadius.bottomLeft.y), - bottomLeft: - Radius.elliptical(borderRadius.topLeft.x, -borderRadius.topLeft.y), + borderRadius.bottomLeft.x, + -borderRadius.bottomLeft.y, + ), + bottomLeft: Radius.elliptical( + borderRadius.topLeft.x, + -borderRadius.topLeft.y, + ), ); } path = _getTooltipPath( - path, - triangleHeight, - halfTooltipHeight, - halfTooltipTriangleWidth, - tooltipTriangleOffsetY, - moveNosePoint, - rightLineWidth, - leftLineWidth, - borderRadius, - tooltipHeight); + path, + triangleHeight, + halfTooltipHeight, + halfTooltipTriangleWidth, + tooltipTriangleOffsetY, + moveNosePoint, + rightLineWidth, + leftLineWidth, + borderRadius, + tooltipHeight, + ); context.canvas.save(); - context.canvas - .translate(center.dx, center.dy - triangleHeight - halfTooltipHeight); + context.canvas.translate( + center.dx, + center.dy - triangleHeight - halfTooltipHeight, + ); context.canvas.scale(tooltipAnimation.value); // In web HTML rendering, fill color clipped half of its tooltip's size. // To avoid this issue we are drawing stroke before fill. final Color strokeColor = tooltipSettings.borderColor ?? Colors.transparent; - final Paint paint = Paint() - ..color = strokeColor - // We are drawing stroke before fill to avoid tooltip rendering issue in - // a web HTML rendering. Due to this, half of the stroke width only - // visible to us so that we are twice the stroke width. - ..strokeWidth = tooltipSettings.borderWidth * 2 - ..style = PaintingStyle.stroke; + final Paint paint = + Paint() + ..color = strokeColor + // We are drawing stroke before fill to avoid tooltip rendering issue in + // a web HTML rendering. Due to this, half of the stroke width only + // visible to us so that we are twice the stroke width. + ..strokeWidth = tooltipSettings.borderWidth * 2 + ..style = PaintingStyle.stroke; // Drawing stroke. context.canvas.drawPath(path, paint); paint @@ -374,22 +420,25 @@ class _TooltipShape { context.canvas.drawPath(path, paint); context.canvas.clipPath(path); - context.paintChild(parentBox.child!, - offset - _getShiftPosition(offset, center, parentBox)); + context.paintChild( + parentBox.child!, + offset - _getShiftPosition(offset, center, parentBox), + ); context.canvas.restore(); } Path _getTooltipPath( - Path path, - double tooltipTriangleHeight, - double halfTooltipHeight, - double halfTooltipTriangleWidth, - double tooltipTriangleOffsetY, - double moveNosePoint, - double rightLineWidth, - double leftLineWidth, - BorderRadius borderRadius, - double tooltipHeight) { + Path path, + double tooltipTriangleHeight, + double halfTooltipHeight, + double halfTooltipTriangleWidth, + double tooltipTriangleOffsetY, + double moveNosePoint, + double rightLineWidth, + double leftLineWidth, + BorderRadius borderRadius, + double tooltipHeight, + ) { path.reset(); path.moveTo(0, tooltipTriangleHeight + halfTooltipHeight); @@ -399,7 +448,9 @@ class _TooltipShape { // preferTooltipOnTop is false, // \ path.lineTo( - halfTooltipTriangleWidth + moveNosePoint, tooltipTriangleOffsetY); + halfTooltipTriangleWidth + moveNosePoint, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ___ // / @@ -407,7 +458,9 @@ class _TooltipShape { // preferTooltipOnTop is false, // \___ path.lineTo( - rightLineWidth - borderRadius.bottomRight.x, tooltipTriangleOffsetY); + rightLineWidth - borderRadius.bottomRight.x, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ___| // / @@ -415,10 +468,16 @@ class _TooltipShape { // preferTooltipOnTop is false, // \___ // | - path.quadraticBezierTo(rightLineWidth, tooltipTriangleOffsetY, - rightLineWidth, tooltipTriangleOffsetY - borderRadius.bottomRight.y); - path.lineTo(rightLineWidth, - tooltipTriangleOffsetY - tooltipHeight + borderRadius.topRight.y); + path.quadraticBezierTo( + rightLineWidth, + tooltipTriangleOffsetY, + rightLineWidth, + tooltipTriangleOffsetY - borderRadius.bottomRight.y, + ); + path.lineTo( + rightLineWidth, + tooltipTriangleOffsetY - tooltipHeight + borderRadius.topRight.y, + ); // preferTooltipOnTop is true, // _______ // ___| @@ -428,12 +487,15 @@ class _TooltipShape { // \___ // ________| path.quadraticBezierTo( - rightLineWidth, - tooltipTriangleOffsetY - tooltipHeight, - rightLineWidth - borderRadius.topRight.x, - tooltipTriangleOffsetY - tooltipHeight); - path.lineTo(-leftLineWidth + borderRadius.topLeft.x, - tooltipTriangleOffsetY - tooltipHeight); + rightLineWidth, + tooltipTriangleOffsetY - tooltipHeight, + rightLineWidth - borderRadius.topRight.x, + tooltipTriangleOffsetY - tooltipHeight, + ); + path.lineTo( + -leftLineWidth + borderRadius.topLeft.x, + tooltipTriangleOffsetY - tooltipHeight, + ); // preferTooltipOnTop is true, // _______ // | ___| @@ -443,12 +505,15 @@ class _TooltipShape { // \___ // |________| path.quadraticBezierTo( - -leftLineWidth, - tooltipTriangleOffsetY - tooltipHeight, - -leftLineWidth, - tooltipTriangleOffsetY - tooltipHeight + borderRadius.topLeft.y); + -leftLineWidth, + tooltipTriangleOffsetY - tooltipHeight, + -leftLineWidth, + tooltipTriangleOffsetY - tooltipHeight + borderRadius.topLeft.y, + ); path.lineTo( - -leftLineWidth, tooltipTriangleOffsetY - borderRadius.bottomLeft.y); + -leftLineWidth, + tooltipTriangleOffsetY - borderRadius.bottomLeft.y, + ); // preferTooltipOnTop is true, // ________ // |___ ___| @@ -457,10 +522,16 @@ class _TooltipShape { // preferTooltipOnTop is false, // ___ \___ // |________| - path.quadraticBezierTo(-leftLineWidth, tooltipTriangleOffsetY, - -leftLineWidth + borderRadius.bottomLeft.x, tooltipTriangleOffsetY); + path.quadraticBezierTo( + -leftLineWidth, + tooltipTriangleOffsetY, + -leftLineWidth + borderRadius.bottomLeft.x, + tooltipTriangleOffsetY, + ); path.lineTo( - -halfTooltipTriangleWidth + moveNosePoint, tooltipTriangleOffsetY); + -halfTooltipTriangleWidth + moveNosePoint, + tooltipTriangleOffsetY, + ); // preferTooltipOnTop is true, // ________ // |___ ___| @@ -475,7 +546,10 @@ class _TooltipShape { } Offset _getShiftPosition( - Offset offset, Offset center, RenderProxyBox parentBox) { + Offset offset, + Offset center, + RenderProxyBox parentBox, + ) { final Size childSize = parentBox.child!.size; final double halfChildWidth = childSize.width / 2; final double halfChildHeight = childSize.height / 2; @@ -484,8 +558,9 @@ class _TooltipShape { // edge goes out of the map's right edge. if (center.dx + halfChildWidth + marginSpace > parentBox.size.width) { return Offset( - childSize.width + center.dx - parentBox.size.width + marginSpace, - halfChildHeight); + childSize.width + center.dx - parentBox.size.width + marginSpace, + halfChildHeight, + ); } // Shifting the position of the tooltip to the right side, if its left // edge goes out of the map's left edge. diff --git a/packages/syncfusion_flutter_treemap/lib/treemap.dart b/packages/syncfusion_flutter_treemap/lib/treemap.dart index 3fabe3bfd..1b142be33 100644 --- a/packages/syncfusion_flutter_treemap/lib/treemap.dart +++ b/packages/syncfusion_flutter_treemap/lib/treemap.dart @@ -51,8 +51,8 @@ typedef TreemapTileColorValueMapper = dynamic Function(TreemapTile tile); /// * [IndexedStringValueMapper] returns a string based on the given index. /// * [TreemapTileColorValueMapper] returns a dynamic value based on the group /// and parent. -typedef TreemapTileWidgetBuilder = Widget? Function( - BuildContext context, TreemapTile tile); +typedef TreemapTileWidgetBuilder = + Widget? Function(BuildContext context, TreemapTile tile); /// Signature to return a widget based on the given tile. /// @@ -66,8 +66,8 @@ typedef TreemapTileWidgetBuilder = Widget? Function( /// * [TreemapTileColorValueMapper] returns a dynamic value based on the group /// and parent. /// * [TreemapTileWidgetBuilder] returns a widget based on a given tile. -typedef TreemapBreadcrumbBuilder = Widget? Function( - BuildContext context, TreemapTile tile, bool isCurrent); +typedef TreemapBreadcrumbBuilder = + Widget? Function(BuildContext context, TreemapTile tile, bool isCurrent); /// Positions the tiles in the different corners. enum TreemapLayoutDirection { @@ -737,23 +737,45 @@ class TreemapLevel extends DiagnosticableTree { properties.add(ColorProperty('color', color)); } if (border != null) { - properties - .add(DiagnosticsProperty('border', border)); + properties.add( + DiagnosticsProperty('border', border), + ); } if (padding != null) { - properties - .add(DiagnosticsProperty('padding', padding)); + properties.add( + DiagnosticsProperty('padding', padding), + ); } - properties.add(ObjectFlagProperty.has( - 'groupMapper', groupMapper)); - properties.add(ObjectFlagProperty.has( - 'colorValueMapper', colorValueMapper)); - properties.add(ObjectFlagProperty.has( - 'tooltipBuilder', tooltipBuilder)); - properties.add(ObjectFlagProperty.has( - 'labelBuilder', labelBuilder)); - properties.add(ObjectFlagProperty.has( - 'itemBuilder', itemBuilder)); + properties.add( + ObjectFlagProperty.has( + 'groupMapper', + groupMapper, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'colorValueMapper', + colorValueMapper, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'tooltipBuilder', + tooltipBuilder, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'labelBuilder', + labelBuilder, + ), + ); + properties.add( + ObjectFlagProperty.has( + 'itemBuilder', + itemBuilder, + ), + ); } @override @@ -777,7 +799,13 @@ class TreemapLevel extends DiagnosticableTree { @override int get hashCode => Object.hash( - groupMapper, color, border, colorValueMapper, padding, tooltipBuilder); + groupMapper, + color, + border, + colorValueMapper, + padding, + tooltipBuilder, + ); } /// Customized the appearance of the tiles in selection state. @@ -977,8 +1005,9 @@ class TreemapSelectionSettings extends DiagnosticableTree { properties.add(ColorProperty('color', color)); } if (border != null) { - properties - .add(DiagnosticsProperty('border', border)); + properties.add( + DiagnosticsProperty('border', border), + ); } } @@ -1133,9 +1162,7 @@ class TreemapTooltipSettings extends DiagnosticableTree { this.hideDelay = 3.0, this.borderColor, this.borderWidth = 1.0, - this.borderRadius = const BorderRadius.all( - Radius.circular(4.0), - ), + this.borderRadius = const BorderRadius.all(Radius.circular(4.0)), }); /// Fills the tooltip by this color. @@ -1190,8 +1217,9 @@ class TreemapTooltipSettings extends DiagnosticableTree { properties.add(ColorProperty('borderColor', borderColor)); } properties.add(DoubleProperty('borderWidth', borderWidth)); - properties.add(DiagnosticsProperty( - 'borderRadius', borderRadius)); + properties.add( + DiagnosticsProperty('borderRadius', borderRadius), + ); } @override @@ -1224,11 +1252,12 @@ class TreemapTooltipSettings extends DiagnosticableTree { BorderRadiusGeometry? borderRadius, }) { return TreemapTooltipSettings( - color: color ?? this.color, - hideDelay: hideDelay ?? this.hideDelay, - borderColor: borderColor ?? this.borderColor, - borderWidth: borderWidth ?? this.borderWidth, - borderRadius: borderRadius ?? this.borderRadius); + color: color ?? this.color, + hideDelay: hideDelay ?? this.hideDelay, + borderColor: borderColor ?? this.borderColor, + borderWidth: borderWidth ?? this.borderWidth, + borderRadius: borderRadius ?? this.borderRadius, + ); } } @@ -1437,14 +1466,16 @@ class TreemapColorMapper extends DiagnosticableTree { this.minSaturation, this.maxSaturation, this.name, - }) : assert(from != null && to != null && from <= to), - assert((minSaturation == null && maxSaturation == null) || - (minSaturation != null && - maxSaturation != null && - minSaturation < maxSaturation && - (minSaturation >= 0 && minSaturation <= 1) && - (maxSaturation >= 0 && maxSaturation <= 1))), - value = null; + }) : assert(from != null && to != null && from <= to), + assert( + (minSaturation == null && maxSaturation == null) || + (minSaturation != null && + maxSaturation != null && + minSaturation < maxSaturation && + (minSaturation >= 0 && minSaturation <= 1) && + (maxSaturation >= 0 && maxSaturation <= 1)), + ), + value = null; /// Applies the color to the tiles which is equal to the given /// [TreemapColorMapper.value]. The [TreemapColorMapper.value] must not be @@ -1512,11 +1543,11 @@ class TreemapColorMapper extends DiagnosticableTree { /// See also: /// * [SfTreemap.legend], to enable and customize the legend. const TreemapColorMapper.value({required this.value, required this.color}) - : from = null, - to = null, - minSaturation = null, - maxSaturation = null, - name = null; + : from = null, + to = null, + minSaturation = null, + maxSaturation = null, + name = null; /// Specifies the color applies to the tile based on the value returned in /// the [TreemapLevel.colorValueMapper]. @@ -1839,13 +1870,13 @@ class SfTreemap extends StatelessWidget { this.tooltipSettings = const TreemapTooltipSettings(), this.enableDrilldown = false, this.breadcrumbs, - }) : assert(dataCount > 0), - assert(levels.length > 0), - assert(colorMappers == null || colorMappers.length > 0), - assert(!enableDrilldown || (enableDrilldown && breadcrumbs != null)), - sortAscending = false, - _layoutType = LayoutType.squarified, - super(key: key); + }) : assert(dataCount > 0), + assert(levels.length > 0), + assert(colorMappers == null || colorMappers.length > 0), + assert(!enableDrilldown || (enableDrilldown && breadcrumbs != null)), + sortAscending = false, + _layoutType = LayoutType.squarified, + super(key: key); /// Creates a treemap based on the slice algorithm. /// @@ -1960,13 +1991,13 @@ class SfTreemap extends StatelessWidget { this.tileHoverBorder, this.enableDrilldown = false, this.breadcrumbs, - }) : assert(dataCount > 0), - assert(levels.length > 0), - assert(colorMappers == null || colorMappers.length > 0), - assert(!enableDrilldown || (enableDrilldown && breadcrumbs != null)), - layoutDirection = TreemapLayoutDirection.topLeft, - _layoutType = LayoutType.slice, - super(key: key); + }) : assert(dataCount > 0), + assert(levels.length > 0), + assert(colorMappers == null || colorMappers.length > 0), + assert(!enableDrilldown || (enableDrilldown && breadcrumbs != null)), + layoutDirection = TreemapLayoutDirection.topLeft, + _layoutType = LayoutType.slice, + super(key: key); /// Creates a treemap based on the dice algorithm. /// @@ -2080,13 +2111,13 @@ class SfTreemap extends StatelessWidget { this.tileHoverBorder, this.enableDrilldown = false, this.breadcrumbs, - }) : assert(dataCount > 0), - assert(levels.length > 0), - assert(colorMappers == null || colorMappers.length > 0), - assert(!enableDrilldown || (enableDrilldown && breadcrumbs != null)), - _layoutType = LayoutType.dice, - layoutDirection = TreemapLayoutDirection.topLeft, - super(key: key); + }) : assert(dataCount > 0), + assert(levels.length > 0), + assert(colorMappers == null || colorMappers.length > 0), + assert(!enableDrilldown || (enableDrilldown && breadcrumbs != null)), + _layoutType = LayoutType.dice, + layoutDirection = TreemapLayoutDirection.topLeft, + super(key: key); /// Specifies the length of the data source. /// @@ -3040,13 +3071,13 @@ class SfTreemap extends StatelessWidget { colorMappers: colorMappers, legend: legend, tileHoverColor: tileHoverColor, - tileHoverBorder: tileHoverBorder ?? + tileHoverBorder: + tileHoverBorder ?? RoundedRectangleBorder( side: BorderSide( - color: Theme.of(context) - .colorScheme - .onSurface - .withValues(alpha: 0.5), + color: Theme.of( + context, + ).colorScheme.onSurface.withValues(alpha: 0.5), ), ), onSelectionChanged: onSelectionChanged, @@ -3065,28 +3096,45 @@ class SfTreemap extends StatelessWidget { if (tileHoverColor != null) { properties.add(ColorProperty('tileHoverColor', tileHoverColor)); } - properties.add(DiagnosticsProperty( - 'tileHoverBorder', tileHoverBorder)); + properties.add( + DiagnosticsProperty( + 'tileHoverBorder', + tileHoverBorder, + ), + ); if (levels.isNotEmpty) { properties.add(_DebugLevelsTree(levels).toDiagnosticsNode()); } - properties.add(ObjectFlagProperty.has( - 'weightValueMapper', weightValueMapper)); + properties.add( + ObjectFlagProperty.has( + 'weightValueMapper', + weightValueMapper, + ), + ); if (colorMappers != null && colorMappers!.isNotEmpty) { properties.add(_DebugColorMappersTree(colorMappers!).toDiagnosticsNode()); } if (legend != null) { properties.add(legend!.toDiagnosticsNode(name: 'legend')); } - properties.add(ObjectFlagProperty>.has( - 'onSelectionChanged', onSelectionChanged)); - properties - .add(selectionSettings.toDiagnosticsNode(name: 'selectionSettings')); + properties.add( + ObjectFlagProperty>.has( + 'onSelectionChanged', + onSelectionChanged, + ), + ); + properties.add( + selectionSettings.toDiagnosticsNode(name: 'selectionSettings'), + ); properties.add(tooltipSettings.toDiagnosticsNode(name: 'tooltipSettings')); - properties.add(FlagProperty('enableDrilldown', + properties.add( + FlagProperty( + 'enableDrilldown', value: enableDrilldown, ifTrue: 'drilldown is enabled', - ifFalse: 'drilldown is disabled')); + ifFalse: 'drilldown is disabled', + ), + ); if (breadcrumbs != null) { properties.add(breadcrumbs!.toDiagnosticsNode(name: 'breadcrumbs')); } @@ -3124,8 +3172,9 @@ class _DebugColorMappersTree extends DiagnosticableTree { @override List debugDescribeChildren() { if (colorMappers.isNotEmpty) { - return colorMappers - .map((TreemapColorMapper colorMapper) { + return colorMappers.map(( + TreemapColorMapper colorMapper, + ) { return colorMapper.toDiagnosticsNode(); }).toList(); } @@ -3144,10 +3193,11 @@ class _DebugColorMappersTree extends DiagnosticableTree { @immutable class TreemapBreadcrumbs extends DiagnosticableTree { /// Creates a [TreemapBreadcrumbs]. - const TreemapBreadcrumbs( - {required this.builder, - this.divider, - this.position = TreemapBreadcrumbPosition.top}); + const TreemapBreadcrumbs({ + required this.builder, + this.divider, + this.position = TreemapBreadcrumbPosition.top, + }); /// Returns a widget for the breadcrumb divider. /// @@ -3332,10 +3382,12 @@ class TreemapBreadcrumbs extends DiagnosticableTree { void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); - properties - .add(EnumProperty('position', position)); properties.add( - ObjectFlagProperty.has('builder', builder)); + EnumProperty('position', position), + ); + properties.add( + ObjectFlagProperty.has('builder', builder), + ); if (divider != null) { properties.add(ObjectFlagProperty.has('divider', divider)); } diff --git a/packages/syncfusion_flutter_treemap/pubspec.yaml b/packages/syncfusion_flutter_treemap/pubspec.yaml index daad7fa8d..e3273e1e5 100644 --- a/packages/syncfusion_flutter_treemap/pubspec.yaml +++ b/packages/syncfusion_flutter_treemap/pubspec.yaml @@ -1,6 +1,6 @@ name: syncfusion_flutter_treemap description: A Flutter Treemap library for creating interactive treemap to visualize flat and hierarchical data based on squarified, slice, and dice algorithms. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_treemap screenshots: @@ -14,7 +14,7 @@ screenshots: path: screenshots/flutter-treemap-squarified-layout.png environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0 dependencies: flutter: @@ -26,3 +26,8 @@ dependencies: + +flutter: + assets: + - assets/images/ + - assets/fonts/Roboto-Medium.ttf diff --git a/packages/syncfusion_flutter_xlsio/CHANGELOG.md b/packages/syncfusion_flutter_xlsio/CHANGELOG.md index 0365599ad..0305cde4e 100644 --- a/packages/syncfusion_flutter_xlsio/CHANGELOG.md +++ b/packages/syncfusion_flutter_xlsio/CHANGELOG.md @@ -2,6 +2,26 @@ **General** +* Upgraded the archive package. The Flutter XlsIO widget supports archive package version 4.0.0 and above. +* The compatible version of our Flutter XlsIO widget has been updated to Flutter SDK 3.32.0. + + +## [29.2.7] - 27/05/2025 + +**Bugs** + +* Excel file gets corrupted when saving a formula containing single quotes in flutter is now resolved. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter XlsIO widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter XlsIO example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter XlsIO example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_mobile.dart b/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_mobile.dart index c7ddbff8b..856ba8bdb 100644 --- a/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_mobile.dart +++ b/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_mobile.dart @@ -20,8 +20,9 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else { path = await PathProviderPlatform.instance.getApplicationSupportPath(); } - final File file = - File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName'); + final File file = File( + Platform.isWindows ? '$path\\$fileName' : '$path/$fileName', + ); await file.writeAsBytes(bytes, flush: true); if (Platform.isAndroid || Platform.isIOS) { //Launch the file (used open_file package) @@ -31,7 +32,8 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else if (Platform.isMacOS) { await Process.run('open', ['$path/$fileName'], runInShell: true); } else if (Platform.isLinux) { - await Process.run('xdg-open', ['$path/$fileName'], - runInShell: true); + await Process.run('xdg-open', [ + '$path/$fileName', + ], runInShell: true); } } diff --git a/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_web.dart b/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_web.dart index db4c74b5b..6037410a9 100644 --- a/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_web.dart +++ b/packages/syncfusion_flutter_xlsio/example/lib/helper/save_file_web.dart @@ -13,11 +13,11 @@ Future saveAndLaunchFile(List bytes, String fileName) async { ..style.display = 'none' ..download = fileName; -// Insert the new element into the DOM + // Insert the new element into the DOM document.body!.appendChild(anchor); -// Initiate the download + // Initiate the download anchor.click(); -// Clean up the DOM by removing the anchor element + // Clean up the DOM by removing the anchor element document.body!.removeChild(anchor); } diff --git a/packages/syncfusion_flutter_xlsio/example/lib/main.dart b/packages/syncfusion_flutter_xlsio/example/lib/main.dart index 4587eef7c..fac606caa 100644 --- a/packages/syncfusion_flutter_xlsio/example/lib/main.dart +++ b/packages/syncfusion_flutter_xlsio/example/lib/main.dart @@ -26,7 +26,7 @@ class CreateExcelWidget extends StatelessWidget { class CreateExcelStatefulWidget extends StatefulWidget { /// Initalize the instance of the [CreateExcelStatefulWidget] class. const CreateExcelStatefulWidget({Key? key, required this.title}) - : super(key: key); + : super(key: key); /// title. final String title; @@ -39,9 +39,7 @@ class _CreateExcelState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -54,7 +52,7 @@ class _CreateExcelState extends State { ), onPressed: generateExcel, child: const Text('Generate Excel'), - ) + ), ], ), ), diff --git a/packages/syncfusion_flutter_xlsio/example/pubspec.yaml b/packages/syncfusion_flutter_xlsio/example/pubspec.yaml index fc07f9dbd..60ff00bd2 100644 --- a/packages/syncfusion_flutter_xlsio/example/pubspec.yaml +++ b/packages/syncfusion_flutter_xlsio/example/pubspec.yaml @@ -2,7 +2,7 @@ name: xlsio_example description: Demo for creating a Excel file using syncfusion_flutter_xlsio package. environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilter_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilter_impl.dart index ddd585a3f..2a707cc2b 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilter_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilter_impl.dart @@ -19,8 +19,12 @@ import 'text_filter.dart'; /// This class represents single autofilter item. class AutoFilterImpl implements AutoFilter { //Constructor for autofilterimpl class - AutoFilterImpl(AutoFilterCollection parent, Worksheet worksheet, - [int iRow = 0, int lRow = 0]) { + AutoFilterImpl( + AutoFilterCollection parent, + Worksheet worksheet, [ + int iRow = 0, + int lRow = 0, + ]) { intializeConditions(); _autoFilterCollection = parent; _worksheet = worksheet; @@ -236,10 +240,9 @@ class AutoFilterImpl implements AutoFilter { for (int iRow = _iRow + 1; iRow <= _lastRow; iRow++) { if (filterCollection.isNotEmpty) { - if (!filterCollection.containsKey(_worksheet - .getRangeByIndex(iRow, colIndex) - .getText() - ?.toLowerCase())) { + if (!filterCollection.containsKey( + _worksheet.getRangeByIndex(iRow, colIndex).getText()?.toLowerCase(), + )) { _worksheet.getRangeByIndex(iRow, colIndex).showRows(false); } else { _worksheet.getRangeByIndex(iRow, colIndex).showRows(true); @@ -315,8 +318,9 @@ class AutoFilterImpl implements AutoFilter { } break; case DynamicFilterType.nextWeek: - startDate = - currentDate.add(Duration(days: 7 - currentDate.weekday)); + startDate = currentDate.add( + Duration(days: 7 - currentDate.weekday), + ); endDate = startDate.add(const Duration(days: 6)); if ((dateTime!.year >= startDate.year && dateTime.year <= endDate.year) && @@ -328,8 +332,9 @@ class AutoFilterImpl implements AutoFilter { } break; case DynamicFilterType.lastWeek: - endDate = - currentDate.add(Duration(days: -(currentDate.weekday + 1))); + endDate = currentDate.add( + Duration(days: -(currentDate.weekday + 1)), + ); startDate = endDate.add(const Duration(days: -6)); if ((dateTime!.year >= startDate.year && dateTime.year <= endDate.year) && @@ -341,30 +346,34 @@ class AutoFilterImpl implements AutoFilter { } break; case DynamicFilterType.lastMonth: - final Jiffy jiffyLast = - Jiffy.parseFromDateTime(currentDate).add(months: -1); + final Jiffy jiffyLast = Jiffy.parseFromDateTime( + currentDate, + ).add(months: -1); startDate = DateTime( - jiffyLast.year, - jiffyLast.month, - jiffyLast.date, - jiffyLast.hour, - jiffyLast.minute, - jiffyLast.second); + jiffyLast.year, + jiffyLast.month, + jiffyLast.date, + jiffyLast.hour, + jiffyLast.minute, + jiffyLast.second, + ); if ((dateTime!.year == startDate.year) && (dateTime.month == startDate.month)) { isVisible = true; } break; case DynamicFilterType.nextMonth: - final Jiffy jiffyNext = - Jiffy.parseFromDateTime(currentDate).add(months: 1); + final Jiffy jiffyNext = Jiffy.parseFromDateTime( + currentDate, + ).add(months: 1); startDate = DateTime( - jiffyNext.year, - jiffyNext.month, - jiffyNext.date, - jiffyNext.hour, - jiffyNext.minute, - jiffyNext.second); + jiffyNext.year, + jiffyNext.month, + jiffyNext.date, + jiffyNext.hour, + jiffyNext.minute, + jiffyNext.second, + ); if ((dateTime!.year == startDate.year) && (dateTime.month == startDate.month)) { isVisible = true; @@ -396,9 +405,11 @@ class AutoFilterImpl implements AutoFilter { if (currentDate.month % 3 != 0) { temp++; } - for (int monthIndex = temp * 3 - 2; - monthIndex <= temp * 3; - monthIndex++) { + for ( + int monthIndex = temp * 3 - 2; + monthIndex <= temp * 3; + monthIndex++ + ) { if (dateTime!.year == currentDate.year && dateTime.month == monthIndex) { isVisible = true; @@ -413,9 +424,11 @@ class AutoFilterImpl implements AutoFilter { } if (temp == 4) { temp = 1; - for (int monthIndex = (temp * 3) - 2; - monthIndex <= temp * 3; - monthIndex++) { + for ( + int monthIndex = (temp * 3) - 2; + monthIndex <= temp * 3; + monthIndex++ + ) { if (dateTime!.year == currentDate.year + 1 && dateTime.month == monthIndex) { isVisible = true; @@ -424,9 +437,11 @@ class AutoFilterImpl implements AutoFilter { } } else { temp++; - for (int monthIndex = (temp * 3) - 2; - monthIndex <= temp * 3; - monthIndex++) { + for ( + int monthIndex = (temp * 3) - 2; + monthIndex <= temp * 3; + monthIndex++ + ) { if (dateTime!.year == currentDate.year && dateTime.month == monthIndex) { isVisible = true; @@ -442,9 +457,11 @@ class AutoFilterImpl implements AutoFilter { } if (temp == 1) { temp = 4; - for (int monthIndex = (temp * 3) - 2; - monthIndex <= temp * 3; - monthIndex++) { + for ( + int monthIndex = (temp * 3) - 2; + monthIndex <= temp * 3; + monthIndex++ + ) { if (dateTime!.year == currentDate.year - 1 && dateTime.month == monthIndex) { isVisible = true; @@ -453,9 +470,11 @@ class AutoFilterImpl implements AutoFilter { } } else { temp--; - for (int monthIndex = (temp * 3) - 2; - monthIndex <= temp * 3; - monthIndex++) { + for ( + int monthIndex = (temp * 3) - 2; + monthIndex <= temp * 3; + monthIndex++ + ) { if (dateTime!.year == currentDate.year && dateTime.month == monthIndex) { isVisible = true; @@ -605,9 +624,11 @@ class AutoFilterImpl implements AutoFilter { for (int row = filterRange.row + 1; row <= filterRange.lastRow; row++) { final Range range = _worksheet.getRangeByIndex(row, colIndex); if (range.dateTime != null) { - for (int index = 0; - index < _combinationFilter.filterCollection.length; - index++) { + for ( + int index = 0; + index < _combinationFilter.filterCollection.length; + index++ + ) { final MultipleFilter filter = _combinationFilter.filterCollection[index]; if (filter.combinationFilterType == @@ -695,7 +716,12 @@ class AutoFilterImpl implements AutoFilter { int lastRow = filterRange.lastRow; final int lastColumn = filterRange.lastColumn; filterRange = _autoFilterCollection.includeBottomAdjacents( - row, column, lastRow, lastColumn, filterRange); + row, + column, + lastRow, + lastColumn, + filterRange, + ); lastRow = filterRange.lastRow; _rangeList.clear(); for (int rowIndex = row + 1; rowIndex <= lastRow; rowIndex++) { @@ -706,18 +732,24 @@ class AutoFilterImpl implements AutoFilter { ///To set condition to check which row going to hide based on condition operator void setCondition( - ExcelFilterCondition conditionOperator, - ExcelFilterDataType datatype, - Object conditionValue, - int currentAutoFilter, - bool isFirstCondition) { + ExcelFilterCondition conditionOperator, + ExcelFilterDataType datatype, + Object conditionValue, + int currentAutoFilter, + bool isFirstCondition, + ) { if (datatype == ExcelFilterDataType.matchAllBlanks) { _setMatchAllBlanks(); } else if (datatype == ExcelFilterDataType.matchAllNonBlanks) { _setMatchAllNonBlanks(); } else { - _setConditionImpl(conditionOperator, conditionValue, _worksheet, - _rangeList, isFirstCondition); + _setConditionImpl( + conditionOperator, + conditionValue, + _worksheet, + _rangeList, + isFirstCondition, + ); } } @@ -751,11 +783,12 @@ class AutoFilterImpl implements AutoFilter { ///To set the condition Between Two Objects Based On ConditionOpertion void _setConditionImpl( - ExcelFilterCondition conditionOperator, - Object conditionValue, - Worksheet worksheet, - Map range, - bool isFirstCondition) { + ExcelFilterCondition conditionOperator, + Object conditionValue, + Worksheet worksheet, + Map range, + bool isFirstCondition, + ) { for (final Range key in range.keys) { if (conditionValue.runtimeType == double || conditionValue.runtimeType == int) { @@ -791,8 +824,13 @@ class AutoFilterImpl implements AutoFilter { break; } - _getCompareResults(cellvalue, compareValue, conditionOperator, - isFirstCondition, key.row); + _getCompareResults( + cellvalue, + compareValue, + conditionOperator, + isFirstCondition, + key.row, + ); } else if (conditionValue.runtimeType == String) { late Object cellValue, compareValue; @@ -814,15 +852,25 @@ class AutoFilterImpl implements AutoFilter { compareValue = conditionValue.toString().toLowerCase(); break; } - _getCompareResults(cellValue, compareValue, conditionOperator, - isFirstCondition, key.row); + _getCompareResults( + cellValue, + compareValue, + conditionOperator, + isFirstCondition, + key.row, + ); } } } ///To get the result of comparison between two objects based on the condition operator - void _getCompareResults(Object a, Object b, - ExcelFilterCondition conditionOperator, bool isFirstCondition, int key) { + void _getCompareResults( + Object a, + Object b, + ExcelFilterCondition conditionOperator, + bool isFirstCondition, + int key, + ) { late double doubleA; late double doubleB; late String stringA; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofiltercollection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofiltercollection.dart index 24a2a2296..316207abd 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofiltercollection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofiltercollection.dart @@ -61,8 +61,12 @@ class AutoFilterCollection { /// Update range to be filtered. Range _updateFilterRange(Range filterRange) { - _initializeFilterRange(filterRange.row, filterRange.column, - filterRange.lastRow, filterRange.lastColumn); + _initializeFilterRange( + filterRange.row, + filterRange.column, + filterRange.lastRow, + filterRange.lastColumn, + ); final int tempTopRow = _topRow; final int tempLeftColumn = _leftColumn; final int tempBottomRow = _bottomRow; @@ -78,29 +82,51 @@ class AutoFilterCollection { isEmptyCell = true; } filterRange = _includeAdjacents( - _topRow, _leftColumn, _bottomRow, _rightColumn, filterRange, true); + _topRow, + _leftColumn, + _bottomRow, + _rightColumn, + filterRange, + true, + ); if (isEmptyCell) { if (tempTopRow == _topRow) { if (!_isRowNotEmpty( - _topRow, _leftColumn, _rightColumn, filterRange)) { + _topRow, + _leftColumn, + _rightColumn, + filterRange, + )) { _topRow++; } } if (tempLeftColumn == _leftColumn) { if (!_isColumnNotEmpty( - _leftColumn, _topRow, _bottomRow, filterRange)) { + _leftColumn, + _topRow, + _bottomRow, + filterRange, + )) { _leftColumn++; } } if (tempBottomRow == _bottomRow) { if (!_isRowNotEmpty( - _bottomRow, _leftColumn, _rightColumn, filterRange)) { + _bottomRow, + _leftColumn, + _rightColumn, + filterRange, + )) { _bottomRow--; } } if (tempRightColumn == _rightColumn) { if (!_isColumnNotEmpty( - _rightColumn, _topRow, _bottomRow, filterRange)) { + _rightColumn, + _topRow, + _bottomRow, + filterRange, + )) { _rightColumn--; } } @@ -112,7 +138,11 @@ class AutoFilterCollection { /// Initializes the filter range values. void _initializeFilterRange( - int topRow, int leftColumn, int bottomRow, int rightColumn) { + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + ) { _topRow = topRow; _leftColumn = leftColumn; _bottomRow = bottomRow; @@ -143,20 +173,41 @@ class AutoFilterCollection { /// Includes adjacent non-empty cells in the internal /// range object that stores filtered range. - Range _includeAdjacents(int topRow, int leftColumn, int bottomRow, - int rightColumn, Range filterRange, bool isEnd) { + Range _includeAdjacents( + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + Range filterRange, + bool isEnd, + ) { _initializeFilterRange(topRow, leftColumn, bottomRow, rightColumn); _hasAdjacents = false; _getTopAdjacents(topRow, leftColumn, bottomRow, rightColumn, filterRange); _getLeftAdjacents(topRow, leftColumn, bottomRow, rightColumn, filterRange); _getBottomAdjacents( - topRow, leftColumn, bottomRow, rightColumn, filterRange); + topRow, + leftColumn, + bottomRow, + rightColumn, + filterRange, + ); _getRightAdjacents(topRow, leftColumn, bottomRow, rightColumn, filterRange); - filterRange = filterRange.worksheet - .getRangeByIndex(_topRow, _leftColumn, _bottomRow, _rightColumn); + filterRange = filterRange.worksheet.getRangeByIndex( + _topRow, + _leftColumn, + _bottomRow, + _rightColumn, + ); if (_hasAdjacents) { filterRange = _includeAdjacents( - _topRow, _leftColumn, _bottomRow, _rightColumn, filterRange, false); + _topRow, + _leftColumn, + _bottomRow, + _rightColumn, + filterRange, + false, + ); } if (isEnd) { @@ -181,8 +232,13 @@ class AutoFilterCollection { /// Checks for non-empty adjacent cells /// which are above the existing filter range to find the top most row in the filter range. - void _getTopAdjacents(int topRow, int leftColumn, int bottomRow, - int rightColumn, Range filterRange) { + void _getTopAdjacents( + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + Range filterRange, + ) { late int row; if (topRow != 1) { row = topRow - 1; @@ -190,10 +246,11 @@ class AutoFilterCollection { return; } final int maxColumnCount = filterRange.workbook.maxRowCount; - for (int column = leftColumn != 1 ? leftColumn - 1 : leftColumn; - column <= - (rightColumn != maxColumnCount ? rightColumn + 1 : rightColumn); - column++) { + for ( + int column = leftColumn != 1 ? leftColumn - 1 : leftColumn; + column <= (rightColumn != maxColumnCount ? rightColumn + 1 : rightColumn); + column++ + ) { if (filterRange.worksheet.getRangeByIndex(row, column).cells.isEmpty) { _hasAdjacents = true; _topRow = row; @@ -205,8 +262,13 @@ class AutoFilterCollection { /// Checks for non-empty adjacent cells /// which are left to the existing filter range to /// find the left most column in the filter range. - void _getLeftAdjacents(int topRow, int leftColumn, int bottomRow, - int rightColumn, Range filterRange) { + void _getLeftAdjacents( + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + Range filterRange, + ) { int column; if (leftColumn != 1) { column = leftColumn - 1; @@ -214,9 +276,11 @@ class AutoFilterCollection { return; } final int maxRowCount = filterRange.workbook.maxRowCount; - for (int row = topRow != 1 ? topRow - 1 : topRow; - row <= (bottomRow != maxRowCount ? bottomRow + 1 : bottomRow); - row++) { + for ( + int row = topRow != 1 ? topRow - 1 : topRow; + row <= (bottomRow != maxRowCount ? bottomRow + 1 : bottomRow); + row++ + ) { if (filterRange.worksheet.getRangeByIndex(row, column).cells.isEmpty) { _hasAdjacents = true; _leftColumn = column; @@ -227,8 +291,13 @@ class AutoFilterCollection { /// Includes adjacent non-empty cells in the bottom of the internal /// range object that stores filtered range. - void _getBottomAdjacents(int topRow, int leftColumn, int bottomRow, - int rightColumn, Range filterRange) { + void _getBottomAdjacents( + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + Range filterRange, + ) { int row; if (bottomRow != filterRange.workbook.maxRowCount) { @@ -237,10 +306,11 @@ class AutoFilterCollection { return; } final int maxColumnCount = filterRange.workbook.maxColumnCount; - for (int column = leftColumn != 1 ? leftColumn - 1 : leftColumn; - column <= - (rightColumn != maxColumnCount ? rightColumn + 1 : rightColumn); - column++) { + for ( + int column = leftColumn != 1 ? leftColumn - 1 : leftColumn; + column <= (rightColumn != maxColumnCount ? rightColumn + 1 : rightColumn); + column++ + ) { if (filterRange.worksheet.getRangeByIndex(row, column).cells.isEmpty) { _hasAdjacents = true; _bottomRow = row; @@ -251,8 +321,13 @@ class AutoFilterCollection { /// Includes adjacent non-empty cells in the right of the internal range /// object that stores filtered range. - void _getRightAdjacents(int topRow, int leftColumn, int bottomRow, - int rightColumn, Range filterRange) { + void _getRightAdjacents( + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + Range filterRange, + ) { int column; if (rightColumn != filterRange.workbook.maxColumnCount) { column = rightColumn + 1; @@ -260,9 +335,11 @@ class AutoFilterCollection { return; } final int maxRowCount = filterRange.workbook.maxRowCount; - for (int row = topRow != 1 ? topRow - 1 : topRow; - row <= (bottomRow != maxRowCount ? bottomRow + 1 : bottomRow); - row++) { + for ( + int row = topRow != 1 ? topRow - 1 : topRow; + row <= (bottomRow != maxRowCount ? bottomRow + 1 : bottomRow); + row++ + ) { if (filterRange.worksheet.getRangeByIndex(row, column).cells.isEmpty) { _hasAdjacents = true; _rightColumn = column; @@ -281,17 +358,36 @@ class AutoFilterCollection { } ///Set range adjacents for Bottom column - Range includeBottomAdjacents(int topRow, int leftColumn, int bottomRow, - int rightColumn, Range filterRange) { + Range includeBottomAdjacents( + int topRow, + int leftColumn, + int bottomRow, + int rightColumn, + Range filterRange, + ) { _initializeFilterRange(topRow, leftColumn, bottomRow, rightColumn); _hasAdjacents = false; _getBottomAdjacents( - topRow, leftColumn, bottomRow, rightColumn, filterRange); - filterRange = filterRange.worksheet - .getRangeByIndex(_topRow, _leftColumn, _bottomRow, _rightColumn); + topRow, + leftColumn, + bottomRow, + rightColumn, + filterRange, + ); + filterRange = filterRange.worksheet.getRangeByIndex( + _topRow, + _leftColumn, + _bottomRow, + _rightColumn, + ); if (_hasAdjacents) { filterRange = includeBottomAdjacents( - _topRow, _leftColumn, _bottomRow, _rightColumn, filterRange); + _topRow, + _leftColumn, + _bottomRow, + _rightColumn, + filterRange, + ); } return filterRange; } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilterconditon_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilterconditon_impl.dart index 710b12e65..fced36695 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilterconditon_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/autofilterconditon_impl.dart @@ -69,8 +69,13 @@ class AutofilterConditionImpl implements AutoFilterCondition { firstCondition.conditionOperator == conditionOperator) { autoFilter.selectRangesToFilter(); autoFilter.filterType = ExcelFilterType.customFilter; - autoFilter.setCondition(firstCondition.conditionOperator, - firstCondition.dataType, value, autoFilter.colIndex, true); + autoFilter.setCondition( + firstCondition.conditionOperator, + firstCondition.dataType, + value, + autoFilter.colIndex, + true, + ); } } if (autoFilter.isSecondCondition) { @@ -80,12 +85,19 @@ class AutofilterConditionImpl implements AutoFilterCondition { secondCondition.conditionOperator == conditionOperator) { autoFilter.selectRangesToFilter(); autoFilter.filterType = ExcelFilterType.customFilter; - autoFilter.setCondition(secondCondition.conditionOperator, - secondCondition.dataType, value, autoFilter.colIndex, false); + autoFilter.setCondition( + secondCondition.conditionOperator, + secondCondition.dataType, + value, + autoFilter.colIndex, + false, + ); } } autoFilter.showFilteredRow( - autoFilter.firstConditionboolList, autoFilter.secondConditionboolList); + autoFilter.firstConditionboolList, + autoFilter.secondConditionboolList, + ); } ///Get string value @@ -107,8 +119,13 @@ class AutofilterConditionImpl implements AutoFilterCondition { firstCondition.conditionOperator == conditionOperator) { autoFilter.selectRangesToFilter(); autoFilter.filterType = ExcelFilterType.customFilter; - autoFilter.setCondition(firstCondition.conditionOperator, - firstCondition.dataType, value, autoFilter.colIndex, true); + autoFilter.setCondition( + firstCondition.conditionOperator, + firstCondition.dataType, + value, + autoFilter.colIndex, + true, + ); } } @@ -119,12 +136,19 @@ class AutofilterConditionImpl implements AutoFilterCondition { secondCondition.conditionOperator == conditionOperator) { autoFilter.selectRangesToFilter(); autoFilter.filterType = ExcelFilterType.customFilter; - autoFilter.setCondition(secondCondition.conditionOperator, - secondCondition.dataType, value, autoFilter.colIndex, false); + autoFilter.setCondition( + secondCondition.conditionOperator, + secondCondition.dataType, + value, + autoFilter.colIndex, + false, + ); } } autoFilter.showFilteredRow( - autoFilter.firstConditionboolList, autoFilter.secondConditionboolList); + autoFilter.firstConditionboolList, + autoFilter.secondConditionboolList, + ); } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/combination_filter.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/combination_filter.dart index 1f49978a3..9c42fc602 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/combination_filter.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/autoFilters/combination_filter.dart @@ -54,7 +54,6 @@ class CombinationFilter implements Filter { } @override - ///Set filter type set filterType(ExcelFilterType filterType) {} diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/calculate/calc_engine.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/calculate/calc_engine.dart index 39793a228..d707600be 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/calculate/calc_engine.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/calculate/calc_engine.dart @@ -27,7 +27,7 @@ class CalcEngine { _tokenGreaterEq, _tokenNoEqual, _tokenAnd, - _tokenOr + _tokenOr, ]; _dateTime1900Double = Range.toOADate(_dateTime1900); @@ -205,7 +205,7 @@ class CalcEngine { '#DIV/0!', '#NUM!', '#NAME?', - '#NULL!' + '#NULL!', ]; /// The list of error strings which are used within the Essential Calculate internally. Users can make changes to this internal error strings. @@ -241,7 +241,7 @@ class CalcEngine { 'iterations do not converge', ////27 'Control named "{0}" is already registered', ////28 'Calculation overflow', ////29 - 'Missing sheet' ////30 + 'Missing sheet', ////30 ]; /// A static property that gets/sets character by which string starts with, can be treated as formula. @@ -663,14 +663,16 @@ class CalcEngine { return formulaErrorStrings[_badIndex]; } if (_libraryFunctions![name] != null) { - final int j = - formula.substring(i + ii + 1).indexOf(_rightBracket); + final int j = formula + .substring(i + ii + 1) + .indexOf(_rightBracket); String args = formula.substring(i + ii + 2, i + ii + 2 + j - 1); try { final String function = _libraryFunctions![name] as String; - final List argArray = - _splitArgsPreservingQuotedCommas(args); + final List argArray = _splitArgsPreservingQuotedCommas( + args, + ); final StringBuffer sb = StringBuffer(); const bool isFormulaUpdated = false; for (int index = 0; index < argArray.length; index++) { @@ -759,9 +761,10 @@ class CalcEngine { // ignore: prefer_contains formula.substring(i).indexOf('!') == -1) { // ignore: prefer_contains - errIndex = (formula.substring(i).indexOf('#N/A') > -1) - ? (formula.substring(i).indexOf('#N/A') + 4 + i) - : (formula.substring(i).indexOf('?') + 1 + i); + errIndex = + (formula.substring(i).contains('#N/A')) + ? (formula.substring(i).indexOf('#N/A') + 4 + i) + : (formula.substring(i).indexOf('?') + 1 + i); } else { errIndex = formula.substring(i).indexOf('!') + 1 + i; } @@ -894,11 +897,16 @@ class CalcEngine { val = (d1 < d) ? _trueValueStr : _falseValueStr; } } else { - val = (s2.toUpperCase().replaceAll(_tic, '').compareTo( - s1.toUpperCase().replaceAll(_tic, '')) < - 0) - ? _trueValueStr - : _falseValueStr; + val = + (s2 + .toUpperCase() + .replaceAll(_tic, '') + .compareTo( + s1.toUpperCase().replaceAll(_tic, ''), + ) < + 0) + ? _trueValueStr + : _falseValueStr; } } @@ -934,11 +942,16 @@ class CalcEngine { val = (d1 > d) ? _trueValueStr : _falseValueStr; } } else { - val = (s2.toUpperCase().replaceAll(_tic, '').compareTo( - s1.toUpperCase().replaceAll(_tic, '')) > - 0) - ? _trueValueStr - : _falseValueStr; + val = + (s2 + .toUpperCase() + .replaceAll(_tic, '') + .compareTo( + s1.toUpperCase().replaceAll(_tic, ''), + ) > + 0) + ? _trueValueStr + : _falseValueStr; } } @@ -961,17 +974,19 @@ class CalcEngine { d = double.tryParse(s1.replaceAll(_tic, '')); d1 = double.tryParse(s2.replaceAll(_tic, '')); if (d == null && d1 == null) { - val = (s1.replaceAll(_tic, '').toUpperCase() == - s2.replaceAll(_tic, '').toUpperCase()) - ? _trueValueStr - : _falseValueStr; + val = + (s1.replaceAll(_tic, '').toUpperCase() == + s2.replaceAll(_tic, '').toUpperCase()) + ? _trueValueStr + : _falseValueStr; } else { val = _falseValueStr; } } else { - val = (s1.toUpperCase() == s2.toUpperCase()) - ? _trueValueStr - : _falseValueStr; + val = + (s1.toUpperCase() == s2.toUpperCase()) + ? _trueValueStr + : _falseValueStr; } stack.push(val); @@ -1006,11 +1021,16 @@ class CalcEngine { val = (d1 >= d) ? _trueValueStr : _falseValueStr; } } else { - val = (s1.toUpperCase().replaceAll(_tic, '').compareTo( - s2.toUpperCase().replaceAll(_tic, '')) <= - 0) - ? _trueValueStr - : _falseValueStr; + val = + (s1 + .toUpperCase() + .replaceAll(_tic, '') + .compareTo( + s2.toUpperCase().replaceAll(_tic, ''), + ) <= + 0) + ? _trueValueStr + : _falseValueStr; } } stack.push(val); @@ -1045,11 +1065,16 @@ class CalcEngine { val = (d1 >= d) ? _trueValueStr : _falseValueStr; } } else { - val = (s2.toUpperCase().replaceAll(_tic, '').compareTo( - s1.toUpperCase().replaceAll(_tic, '')) >= - 0) - ? _trueValueStr - : _falseValueStr; + val = + (s2 + .toUpperCase() + .replaceAll(_tic, '') + .compareTo( + s1.toUpperCase().replaceAll(_tic, ''), + ) >= + 0) + ? _trueValueStr + : _falseValueStr; } } @@ -1077,18 +1102,20 @@ class CalcEngine { d = double.tryParse(s1.replaceAll(_tic, '')); d1 = double.tryParse(s2.replaceAll(_tic, '')); if (d == null && d1 == null) { - val = (s1.replaceAll(_tic, '').toUpperCase() != - s2.replaceAll(_tic, '').toUpperCase()) - ? _trueValueStr - : _falseValueStr; + val = + (s1.replaceAll(_tic, '').toUpperCase() != + s2.replaceAll(_tic, '').toUpperCase()) + ? _trueValueStr + : _falseValueStr; } else { val = _trueValueStr; } } else { - val = (s1.toUpperCase().replaceAll(_tic, '') != - s2.toUpperCase().replaceAll(_tic, '')) - ? _trueValueStr - : _falseValueStr; + val = + (s1.toUpperCase().replaceAll(_tic, '') != + s2.toUpperCase().replaceAll(_tic, '')) + ? _trueValueStr + : _falseValueStr; } } @@ -1628,7 +1655,8 @@ class CalcEngine { if (_errorStrings.contains(argument1)) { return argument1; } - final bool flag = argument1.replaceAll(_tic, '') == 'true' || + final bool flag = + argument1.replaceAll(_tic, '') == 'true' || argument1.replaceAll(_tic, '') == 'false'; if ((!_isCellReference(s[0]) && !flag && @@ -1731,12 +1759,14 @@ class CalcEngine { } final String sheet = _getSheetToken(r); i = r.indexOf(':'); - int row = (argCount == 1) - ? 1 - : double.tryParse(_getValueFromArg(args[1]))!.toInt(); - int col = (argCount <= 2) - ? 1 - : double.tryParse(_getValueFromArg(args[2]))!.toInt(); + int row = + (argCount == 1) + ? 1 + : double.tryParse(_getValueFromArg(args[1]))!.toInt(); + int col = + (argCount <= 2) + ? 1 + : double.tryParse(_getValueFromArg(args[2]))!.toInt(); int top = _getRowIndex(r.substring(0, i)); int bottom = _getRowIndex(r.substring(i + 1)); if (!(top != -1 || bottom == -1) == (top == -1 || bottom != -1)) { @@ -1948,9 +1978,10 @@ class CalcEngine { return _errorStrings[4]; } d = double.tryParse(s1); - sum &= s1 == '' - ? _trueValueStr.toLowerCase() == 'true' - : ((s1 == _trueValueStr) || d != null && d != 0); + sum &= + s1 == '' + ? _trueValueStr.toLowerCase() == 'true' + : ((s1 == _trueValueStr) || d != null && d != 0); if (!sum) { return _falseValueStr; } @@ -1984,7 +2015,8 @@ class CalcEngine { return _errorStrings[4]; } d = double.tryParse(s1); - sum &= (s1.replaceAll(_tic, '').toLowerCase() == 'true') || + sum &= + (s1.replaceAll(_tic, '').toLowerCase() == 'true') || d != null && d != 0; if (!sum) { return _falseValueStr; @@ -2017,9 +2049,10 @@ class CalcEngine { return _errorStrings[4]; } d = double.tryParse(s1); - sum &= s1 == '' - ? _trueValueStr.toLowerCase() == 'true' - : ((s1 == _trueValueStr) || d != null && d != 0); + sum &= + s1 == '' + ? _trueValueStr.toLowerCase() == 'true' + : ((s1 == _trueValueStr) || d != null && d != 0); if (!sum) { return _falseValueStr; } @@ -2053,7 +2086,8 @@ class CalcEngine { return _errorStrings[4]; } d = double.tryParse(s1); - sum |= (s1.replaceAll(_tic, '').toLowerCase() == 'true') || + sum |= + (s1.replaceAll(_tic, '').toLowerCase() == 'true') || d != null && d != 0; if (sum) { return _trueValueStr; @@ -2239,7 +2273,7 @@ class CalcEngine { date = DateTime.tryParse(o.toString()); return [ (date != null && date.difference(_dateTime1900).inDays >= 0), - date + date, ]; } @@ -2365,7 +2399,7 @@ class CalcEngine { _lastIndexOfAny(text, _tokens) != (text.length - 2)) { text = text.toUpperCase(); } -// ignore: prefer_contains + // ignore: prefer_contains if (text.indexOf(_sheetToken) > -1) { ////Replace sheet references with tokens. final SheetFamilyItem? family = _getSheetFamilyItem(_grid); @@ -2446,8 +2480,8 @@ class CalcEngine { while (rightParens > -1) { int parenCount = 0; int leftParens = rightParens - 1; - while ( - leftParens > -1 && (formula[leftParens] != '(' || parenCount != 0)) { + while (leftParens > -1 && + (formula[leftParens] != '(' || parenCount != 0)) { if (formula[leftParens] == ')') { parenCount++; } else if (formula[leftParens] == ')') { @@ -2481,7 +2515,9 @@ class CalcEngine { _ignoreBracet = false; } final String s = formula.substring( - leftParens, leftParens + rightParens - leftParens + 1); + leftParens, + leftParens + rightParens - leftParens + 1, + ); formula = '${formula.substring(0, i + 1)}q${formula.substring(i + 1, i + 1 + len)}${s.replaceAll('(', _leftBracket).replaceAll(')', _rightBracket)}${formula.substring(rightParens + 1)}'; } else { @@ -2603,7 +2639,7 @@ class CalcEngine { '=', '&', ':', - '%' + '%', ]; if ((tempText.length == 1 && d == 0) || tempText.length - 1 == d && @@ -2622,61 +2658,76 @@ class CalcEngine { bool needToContinue = true; List result; - result = _parseSimpleFromMarkers(text, [_tokenEP, _tokenEM], - [_charEP, _charEM], needToContinue); + result = _parseSimpleFromMarkers( + text, + [_tokenEP, _tokenEM], + [_charEP, _charEM], + needToContinue, + ); text = result[0] as String; needToContinue = result[1] as bool; result = _parseSimpleFromMarkers( - text, [_tokenOr], [_charOr], needToContinue); + text, + [_tokenOr], + [_charOr], + needToContinue, + ); text = result[0] as String; needToContinue = result[1] as bool; if (needToContinue) { result = _parseSimpleFromMarkers( - text, - [_tokenMultiply, _tokenDivide], - [_charMultiply, _charDivide], - needToContinue); + text, + [_tokenMultiply, _tokenDivide], + [_charMultiply, _charDivide], + needToContinue, + ); text = result[0] as String; needToContinue = result[1] as bool; } if (needToContinue) { result = _parseSimpleFromMarkers( - text, - [_tokenAdd, _tokenSubtract], - [_charAdd, _charSubtract], - needToContinue); + text, + [_tokenAdd, _tokenSubtract], + [_charAdd, _charSubtract], + needToContinue, + ); text = result[0] as String; needToContinue = result[1] as bool; } if (needToContinue) { result = _parseSimpleFromMarkers( - text, [_tokenAnd], [_charAnd], needToContinue); + text, + [_tokenAnd], + [_charAnd], + needToContinue, + ); text = result[0] as String; needToContinue = result[1] as bool; } if (needToContinue) { result = _parseSimpleFromMarkers( - text, - [ - _tokenLess, - _tokenGreater, - _tokenEqual, - _tokenLesseq, - _tokenGreaterEq, - _tokenNoEqual - ], - [ - _charLess, - _charGreater, - _charEqual, - _charLesseq, - _charGreaterEq, - _charNoEqual - ], - needToContinue); + text, + [ + _tokenLess, + _tokenGreater, + _tokenEqual, + _tokenLesseq, + _tokenGreaterEq, + _tokenNoEqual, + ], + [ + _charLess, + _charGreater, + _charEqual, + _charLesseq, + _charGreaterEq, + _charNoEqual, + ], + needToContinue, + ); text = result[0] as String; needToContinue = result[1] as bool; } @@ -2684,8 +2735,12 @@ class CalcEngine { return text; } - List _parseSimpleFromMarkers(String text, List markers, - List operators, bool needToContinue) { + List _parseSimpleFromMarkers( + String text, + List markers, + List operators, + bool needToContinue, + ) { int i; String op = ''; for (final String c in operators) { @@ -2726,8 +2781,12 @@ class CalcEngine { ////Leading unary minus. text = text.substring(1).replaceAll('-', '„'); text = '0-$text'; - final List iResult = _parseSimpleFromMarkers(text, - [_tokenSubtract], [_charSubtract], needToContinue); + final List iResult = _parseSimpleFromMarkers( + text, + [_tokenSubtract], + [_charSubtract], + needToContinue, + ); text = iResult[0] as String; needToContinue = iResult[1] as bool; text = text.replaceAll('„', '-'); @@ -2751,7 +2810,8 @@ class CalcEngine { if (!isNotOperator) { if (i < 1 && text[i] != '-') { throw Exception( - formulaErrorStrings[_operatorsCannotStartAnExpression]); + formulaErrorStrings[_operatorsCannotStartAnExpression], + ); } ////Process left argument. @@ -2819,8 +2879,10 @@ class CalcEngine { j--; } - left = - text.substring(j + 1, j + 1 + i - j - 1); ////'n' for number + left = text.substring( + j + 1, + j + 1 + i - j - 1, + ); ////'n' for number leftIndex = j + 1; if (!_findNamedRange) { if (left == _trueValueStr) { @@ -2853,7 +2915,8 @@ class CalcEngine { ////Add error check for 2%. if (j > -1 && period && text[j] == parseDecimalSeparator) { throw Exception( - formulaErrorStrings[_numberContains2DecimalPoints]); + formulaErrorStrings[_numberContains2DecimalPoints], + ); } j = j + 1; @@ -2922,8 +2985,10 @@ class CalcEngine { j = j + 1; left = text.substring(j, j + i - j); - final List leftValue = - _getCellsFromArgs(left, false); + final List leftValue = _getCellsFromArgs( + left, + false, + ); if (leftValue.isNotEmpty) { left = leftValue[0]!; } @@ -2943,7 +3008,8 @@ class CalcEngine { ////Process right argument. if (i == text.length - 1) { throw Exception( - formulaErrorStrings[_expressionCannotEndWithAnOperator]); + formulaErrorStrings[_expressionCannotEndWithAnOperator], + ); } else { j = i + 1; @@ -3076,8 +3142,10 @@ class CalcEngine { right = text.substring(i + 1, i + 1 + j - i); - final List rightValue = - _getCellsFromArgs(right, false); + final List rightValue = _getCellsFromArgs( + right, + false, + ); if (rightValue.isNotEmpty) { right = rightValue[0]!; } @@ -3107,7 +3175,8 @@ class CalcEngine { rightIndex = j + 1; } else { throw Exception( - formulaErrorStrings[_invalidCharactersFollowingAnOperator]); + formulaErrorStrings[_invalidCharactersFollowingAnOperator], + ); } } @@ -3343,13 +3412,15 @@ class CalcEngine { String _getValueComputeFormulaIfNecessary(int row, int col, Worksheet grd) { try { bool alreadyComputed = false; - FormulaInfo? formula = _formulaInfoTable!.containsKey(_cell) - ? _formulaInfoTable![_cell] as FormulaInfo - : null; + FormulaInfo? formula = + _formulaInfoTable!.containsKey(_cell) + ? _formulaInfoTable![_cell] as FormulaInfo + : null; final Object o = grd.getValueRowCol(row, col); - String? val = (o.toString() != '') - ? o.toString() - : ''; ////null; //xx _grid[row, col]; + String? val = + (o.toString() != '') + ? o.toString() + : ''; ////null; //xx _grid[row, col]; DateTime? result; result = DateTime.tryParse(val); if (double.tryParse(val.replaceAll(_tic, '')) == null && result != null) { @@ -3682,7 +3753,9 @@ class CalcEngine { for (final String s in results) { String s1 = s; s1 = _setStrings( - s1, formulaStrings); ////replace tokens with original Strings + s1, + formulaStrings, + ); ////replace tokens with original Strings pieces.add(s1); } return pieces; @@ -3783,8 +3856,9 @@ class CalcEngine { int sheetLoc = text.indexOf(_sheetToken); int start = 0; while (sheetLoc > 0) { - final int colonLoc = - text.substring(start, start + sheetLoc).lastIndexOf(':'); + final int colonLoc = text + .substring(start, start + sheetLoc) + .lastIndexOf(':'); if (colonLoc > -1) { { start = sheetLoc + start; @@ -3950,10 +4024,13 @@ class CalcEngine { // To check if the function contains CELL formula embedded with other formulas like INDEX,IF... final int q1 = _findLastqNotInBrackets(formula.substring(0, q)); - final String s1 = q1 >= 0 - ? formula.substring( - q1, q1 + formula.substring(q1).indexOf(_rightBracket)) - : ''; + final String s1 = + q1 >= 0 + ? formula.substring( + q1, + q1 + formula.substring(q1).indexOf(_rightBracket), + ) + : ''; // Below code has been added to check whether the Value formula is interior of SUMPRODUCT if ((s.contains('qVALUE') || @@ -4089,12 +4166,13 @@ class CalcEngine { final DateTime dt = DateTime.now(); if (excelLikeComputations) { - final DateTime? result = - DateTime.tryParse('${dt.year}/${dt.month}/${dt.day}'); + final DateTime? result = DateTime.tryParse( + '${dt.year}/${dt.month}/${dt.day}', + ); if (result != null) { final String date = DateFormat( - _grid!.workbook.cultureInfo.dateTimeFormat.shortDatePattern) - .format(result); + _grid!.workbook.cultureInfo.dateTimeFormat.shortDatePattern, + ).format(result); return date; } } @@ -4116,9 +4194,10 @@ class CalcEngine { if (!range.contains(parseArgumentSeparator)) { range = _adjustRangeArg(range); } - final List ar = _isSeparatorInTIC(range) ////range.IndexOf(TIC) > 0 - ? _getStringArray(range) - : _splitArgsPreservingQuotedCommas(range); + final List ar = + _isSeparatorInTIC(range) ////range.IndexOf(TIC) > 0 + ? _getStringArray(range) + : _splitArgsPreservingQuotedCommas(range); if (range.isEmpty) { return formulaErrorStrings[_wrongNumberArguments]; } @@ -4157,8 +4236,10 @@ class CalcEngine { } if (excelLikeComputations) { - final String newText = - text.substring(text.indexOf(_tic) + 1, text.lastIndexOf(_tic) - 1); + final String newText = text.substring( + text.indexOf(_tic) + 1, + text.lastIndexOf(_tic) - 1, + ); return newText; } return text; @@ -4269,9 +4350,12 @@ class CalcEngine { while (d < 1) { m--; final DateTime date = DateTime(y, m + 1); - x = DateTime(date.year, date.month, date.day) - .add(const Duration(hours: -1)) - .day; + x = + DateTime( + date.year, + date.month, + date.day, + ).add(const Duration(hours: -1)).day; d = x + d; } } @@ -4375,7 +4459,8 @@ class CalcEngine { col += count - s2.length; } - sumRange = sumRange.substring(0, i + 1) + + sumRange = + sumRange.substring(0, i + 1) + getAlphaLabel(col) + row.toString(); s2 = _getCellsFromArgs(sumRange); @@ -4392,7 +4477,12 @@ class CalcEngine { for (int index = 0; index < count; ++index) { s = _getValueFromArg(s1[index]); //// +criteria; final bool criteriaMatched = _checkForCriteriaMatch( - s.toUpperCase(), op, criteria.toUpperCase(), isNumber, compare); + s.toUpperCase(), + op, + criteria.toUpperCase(), + isNumber, + compare, + ); if (criteriaMatched) { if (isLastcriteria && criterias.length == 1) { cellCount++; @@ -4478,7 +4568,12 @@ class CalcEngine { /// Below method used to find whether the criteria is matched with the Tokens "=",">",">=" or not. bool _checkForCriteriaMatch( - String s, String op, String criteria, bool isNumber, double compare) { + String s, + String op, + String criteria, + bool isNumber, + double compare, + ) { final String tempcriteria = criteria; double? d = 0.0; //Below condition has added to match the number when ita text value.eg(s1=\"2\" and comapre="2") @@ -4513,7 +4608,6 @@ class CalcEngine { } return isMatch; } - // Below code has been added avoid to throw argument exception when criteria length was higher than s length. else if (!isstartswith && !isendswith) { final List criterias = criteria.split('*'); @@ -4540,8 +4634,9 @@ class CalcEngine { } case _tokenGreaterEq: //Below code has been added to compare the value when the criteria is string. - final int tempString = - s.toUpperCase().compareTo(criteria.toUpperCase()); + final int tempString = s.toUpperCase().compareTo( + criteria.toUpperCase(), + ); if (isNumber) { d = double.tryParse(s); final bool value = d != null; @@ -4551,8 +4646,9 @@ class CalcEngine { } case _tokenGreater: //Below code has been added to compare the value when the criteria is string. - final int tempString = - s.toUpperCase().compareTo(criteria.toUpperCase()); + final int tempString = s.toUpperCase().compareTo( + criteria.toUpperCase(), + ); if (isNumber) { d = double.tryParse(s); final bool value = d != null; @@ -4562,8 +4658,9 @@ class CalcEngine { } case _tokenLess: //Below code has been added to compare the value when the criteria is string. - final int tempString = - s.toUpperCase().compareTo(criteria.toUpperCase()); + final int tempString = s.toUpperCase().compareTo( + criteria.toUpperCase(), + ); if (isNumber) { d = double.tryParse(s); final bool value = d != null; @@ -4573,8 +4670,9 @@ class CalcEngine { } case _tokenLesseq: //Below code has been added to compare the value when the criteria is string. - final int tempString = - s.toUpperCase().compareTo(criteria.toUpperCase()); + final int tempString = s.toUpperCase().compareTo( + criteria.toUpperCase(), + ); if (isNumber) { d = double.tryParse(s); final bool value = d != null; @@ -4699,7 +4797,8 @@ class CalcEngine { } else if (startCol != col) { col += count - s2.length; } - calculateRange = calculateRange.substring(0, i + 1) + + calculateRange = + calculateRange.substring(0, i + 1) + getAlphaLabel(col) + row.toString(); s2 = _getCellsFromArgs(calculateRange); @@ -4718,7 +4817,12 @@ class CalcEngine { for (int index = 0; index < count; ++index) { s = _getValueFromArg(s1[index]); final bool criteriaMatched = _checkForCriteriaMatch( - s.toUpperCase(), op, criteria.toUpperCase(), isNumber, compare); + s.toUpperCase(), + op, + criteria.toUpperCase(), + isNumber, + compare, + ); if (criteriaMatched) { //Below code has been modified to check the index of criteria. if (tempList.isNotEmpty && v != 0) { @@ -4891,7 +4995,12 @@ class CalcEngine { s = _getValueFromArg(s1[index]); //// +criteria; //Below condition has been added to check whether the criteria is number, expression or text. For example, criteria can be expressed as 32, ">32", B4, "apples", or "32". final bool criteriaMatched = _checkForCriteriaMatch( - s.toUpperCase(), op, criteria.toUpperCase(), isNumber, compare); + s.toUpperCase(), + op, + criteria.toUpperCase(), + isNumber, + compare, + ); //Below code has been added to count the number of occurences of values which the criteria satisfies. if (criteriaMatched) { if (isCountif && isLastcriteria || @@ -4957,8 +5066,10 @@ class CalcEngine { final int col = d.toInt(); bool match = true, rangeLookup = true; if (s.length == 4) { - match = rangeLookup = (_getValueFromArg(s[3]) == _trueValueStr) || - (_getValueFromArg(s[3].replaceAll(_tic, '')) == '1'); + match = + rangeLookup = + (_getValueFromArg(s[3]) == _trueValueStr) || + (_getValueFromArg(s[3].replaceAll(_tic, '')) == '1'); } d = double.tryParse(lookUp); final bool typeIsNumber = d != null; @@ -5039,13 +5150,19 @@ class CalcEngine { if (!cachingEnabled) { //To avoid grid resetting at run time when the grid has dependent sheets. if (dependentGrid != null) { - s1 = _getValueFromParentObjectGrid(row, col1, true, dependentGrid) - .toUpperCase() - .replaceAll('"', ''); + s1 = _getValueFromParentObjectGrid( + row, + col1, + true, + dependentGrid, + ).toUpperCase().replaceAll('"', ''); } else { - s1 = _getValueFromParentObjectGrid(row, col1, true, _grid) - .toUpperCase() - .replaceAll('"', ''); + s1 = _getValueFromParentObjectGrid( + row, + col1, + true, + _grid, + ).toUpperCase().replaceAll('"', ''); } DateTime? matchDateTime; double? doubleMatchValue; @@ -5119,15 +5236,26 @@ class CalcEngine { //To return proper value when grid type is ICalcData. if (dependentGrid != null) { val = _getValueFromParentObjectGrid( - lastRow, col + col1 - 1, true, dependentGrid); + lastRow, + col + col1 - 1, + true, + dependentGrid, + ); } else { - val = - _getValueFromParentObjectGrid(lastRow, col + col1 - 1, true, _grid); + val = _getValueFromParentObjectGrid( + lastRow, + col + col1 - 1, + true, + _grid, + ); } if (val == '' && - !_getValueFromParentObjectGrid(lastRow, col + col1 - 1, false, _grid) - .toUpperCase() - .startsWith('=IF')) { + !_getValueFromParentObjectGrid( + lastRow, + col + col1 - 1, + false, + _grid, + ).toUpperCase().startsWith('=IF')) { val = '0'; } if (val.isNotEmpty && val[0] == CalcEngine._formulaCharacter) { @@ -5187,13 +5315,18 @@ class CalcEngine { return val.toString(); } - String _getValueFromParentObjectGrid(int row, int col, bool calculateFormula, - [Worksheet? grd]) { + String _getValueFromParentObjectGrid( + int row, + int col, + bool calculateFormula, [ + Worksheet? grd, + ]) { final SheetFamilyItem? family = _getSheetFamilyItem(grd); - String cell1 = (family!.parentObjectToToken == null || - family.parentObjectToToken!.isEmpty) - ? '' - : family.parentObjectToToken![grd].toString(); + String cell1 = + (family!.parentObjectToToken == null || + family.parentObjectToToken!.isEmpty) + ? '' + : family.parentObjectToToken![grd].toString(); cell1 = cell1 + getAlphaLabel(col) + row.toString(); final Worksheet? saveGrid = _grid; final String saveCell = _cell; @@ -5308,7 +5441,8 @@ class CalcEngine { if (height != criteriaHeight) { row = startRow + criteriaHeight; } - sumRange = getAlphaLabel(startCol) + + sumRange = + getAlphaLabel(startCol) + sumRange.substring(1, i + 1) + getAlphaLabel(col) + row.toString(); @@ -5344,7 +5478,12 @@ class CalcEngine { } //Below code has beeb added to calculate SUMIF formula when criteria contains *. final bool criteriaMatched = _checkForCriteriaMatch( - s.toUpperCase(), op, criteria.toUpperCase(), isNumber, compare); + s.toUpperCase(), + op, + criteria.toUpperCase(), + isNumber, + compare, + ); if (criteriaMatched) { s = s2[index]!; s = _getValueFromArg(s); @@ -5402,7 +5541,8 @@ class CalcEngine { // Below code has been added to calculate when the ranges contain array and cell range.("1,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1",G5:G30). else if (ranges[i].startsWith(parseArgumentSeparator) && _isCellReference( - ranges[i].replaceAll(parseArgumentSeparator, ''))) { + ranges[i].replaceAll(parseArgumentSeparator, ''), + )) { ranges[i] = ranges[i].replaceAll(parseArgumentSeparator, ''); } } @@ -5470,20 +5610,25 @@ class CalcEngine { cells ??= _getCellsFromArgs(val); int s = 0; if ((val == '') && (strArray != '')) { - final List args = - _splitArgsPreservingQuotedCommas(strArray); - final List tempLogicList = - args[0].replaceAll(_tic, '').split(';'); - final List tempLogicList1 = - args[1].replaceAll(_tic, '').split(';'); + final List args = _splitArgsPreservingQuotedCommas( + strArray, + ); + final List tempLogicList = args[0] + .replaceAll(_tic, '') + .split(';'); + final List tempLogicList1 = args[1] + .replaceAll(_tic, '') + .split(';'); { for (s = 0; s <= tempLogicList.length - 1; s++) { if (s + 1 != args.length) { - logicTest = _getValueFromArg(_bMarker + - tempLogicList[s] + - tempLogicList1[s] + - logicalVal + - _bMarker); + logicTest = _getValueFromArg( + _bMarker + + tempLogicList[s] + + tempLogicList1[s] + + logicalVal + + _bMarker, + ); } finalStringValue += '$logicTest;'; } @@ -5493,16 +5638,21 @@ class CalcEngine { } else { for (s = 0; s <= cells.length - 1; s++) { logicTest = _getValueFromArg( - _bMarker + cells[s]! + logicalVal + _bMarker); + _bMarker + cells[s]! + logicalVal + _bMarker, + ); finalStringValue += '$logicTest;'; } } if (j == tempr.length - 1) { - strArray = - finalStringValue.substring(0, finalStringValue.length - 1); + strArray = finalStringValue.substring( + 0, + finalStringValue.length - 1, + ); } else { - finalStringValue = - finalStringValue.substring(0, finalStringValue.length - 1); + finalStringValue = finalStringValue.substring( + 0, + finalStringValue.length - 1, + ); strArray += _tic + finalStringValue + _tic + parseArgumentSeparator; } finalStringValue = ''; @@ -5510,7 +5660,12 @@ class CalcEngine { // perform multiplication List result; result = _performMultiplication( - strArray, indexValue, count, vector, errorString); + strArray, + indexValue, + count, + vector, + errorString, + ); indexValue = result[0] as bool; count = result[1] as int; vector = result[2] as List?; @@ -5563,10 +5718,19 @@ class CalcEngine { for (int row = row1; row <= row2; ++row) { for (int col = col1; col <= col2; ++col) { d = double.tryParse( - _getValueFromParentObjectGrid(row, col, true, grd) - .replaceAll(_tic, '')); - final String v = _getValueFromParentObjectGrid(row, col, true, grd) - .replaceAll(_tic, ''); + _getValueFromParentObjectGrid( + row, + col, + true, + grd, + ).replaceAll(_tic, ''), + ); + final String v = _getValueFromParentObjectGrid( + row, + col, + true, + grd, + ).replaceAll(_tic, ''); if (v == 'true' || v == 'false') { indexValue = v.contains('true'); } else { @@ -5605,7 +5769,12 @@ class CalcEngine { // perform multiplication List result; result = _performMultiplication( - tempr, indexValue, count, vector, errorString); + tempr, + indexValue, + count, + vector, + errorString, + ); indexValue = result[0] as bool; count = result[1] as int; vector = result[2] as List?; @@ -5634,8 +5803,13 @@ class CalcEngine { return sum.toString(); } - List _performMultiplication(String strArray, bool? indexValue, - int count, List? vector, String errorString) { + List _performMultiplication( + String strArray, + bool? indexValue, + int count, + List? vector, + String errorString, + ) { // perform multiplication List tempRangs; List temArray; @@ -5643,7 +5817,8 @@ class CalcEngine { double? d = 0; if (strArray.contains(';')) { tempRangs = strArray.split(';'); - final int listLength = tempRangs.length * + final int listLength = + tempRangs.length * _splitArgsPreservingQuotedCommas(tempRangs[0]).length; temArray = List.filled(listLength, ''); } @@ -5651,9 +5826,10 @@ class CalcEngine { else if (strArray.contains(',')) { tempRangs = strArray.split(','); temArray = List.filled( - tempRangs.length * - _splitArgsPreservingQuotedCommas(tempRangs[0]).length, - ''); + tempRangs.length * + _splitArgsPreservingQuotedCommas(tempRangs[0]).length, + '', + ); } else { tempRangs = _splitArgsPreservingQuotedCommas(strArray); temArray = List.filled(tempRangs.length, ''); @@ -5713,8 +5889,9 @@ class CalcEngine { bool nohits = true; range = _adjustRangeArg(range); //Below condition has been modified to calculate when provided the numeric value as string. - final List ranges = - _splitArgsPreservingQuotedCommas(range.replaceAll(_tic, '')); + final List ranges = _splitArgsPreservingQuotedCommas( + range.replaceAll(_tic, ''), + ); for (final String r in ranges) { ////is a cellrange if (r.contains(':')) { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/border.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/border.dart index 83e387127..b33a52c51 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/border.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/border.dart @@ -74,8 +74,9 @@ class CellBorder implements Border { @override set color(String value) { _color = value; - _colorRgb = - Color(int.parse(_color.substring(1, 7), radix: 16) + 0xFF000000); + _colorRgb = Color( + int.parse(_color.substring(1, 7), radix: 16) + 0xFF000000, + ); } late Color _colorRgb; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style.dart index abd9f3006..22334f10d 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style.dart @@ -45,80 +45,70 @@ class CellStyle implements Style { String _backColor = ''; @override - /// Gets/sets back color. String get backColor => _backColor; @override set backColor(String value) { _backColor = value; - _backColorRgb = - Color(int.parse(_backColor.substring(1, 7), radix: 16) + 0xFF000000); + _backColorRgb = Color( + int.parse(_backColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } /// Gets/sets borders. late BordersCollection _borders; @override - /// Gets/sets font name. late String fontName; @override - /// Gets/sets font size. late double fontSize; String _fontColor = ''; @override - /// Gets/sets font color. String get fontColor => _fontColor; @override set fontColor(String value) { _fontColor = value; - _fontColorRgb = - Color(int.parse(_fontColor.substring(1, 7), radix: 16) + 0xFF000000); + _fontColorRgb = Color( + int.parse(_fontColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } @override - /// Gets/sets font italic. late bool italic; @override - /// Gets/sets font bold. late bool bold; @override - /// Gets/sets horizontal alignment. late HAlignType hAlign; @override - /// Gets/sets cell indent. late int indent; @override - /// Gets/sets cell rotation. late int rotation; @override - /// Gets/sets vertical alignment. late VAlignType vAlign; @override - /// Gets/sets font underline. late bool underline; @override - /// Gets/sets cell wraptext. late bool wrapText; @@ -134,19 +124,16 @@ class CellStyle implements Style { int builtinId = 0; @override - /// Gets/Sets cell Lock late bool locked; @override - /// Sets borders. Borders get borders { return _borders; } @override - /// Sets borders. set borders(Borders value) { _borders = value as BordersCollection; @@ -165,14 +152,12 @@ class CellStyle implements Style { } @override - /// Returns or sets the format code for the object. Read/write String. String? get numberFormat { return numberFormatObject.formatString; } @override - /// Sets the number format. set numberFormat(String? value) { numberFormatIndex = book.innerFormats.findOrCreateFormat(value); @@ -188,7 +173,6 @@ class CellStyle implements Style { Color _fontColorRgb = const Color.fromARGB(255, 0, 0, 0); @override - /// Gets/sets back color Rgb. Color get backColorRgb => _backColorRgb; @@ -201,7 +185,6 @@ class CellStyle implements Style { } @override - /// Gets/sets font color Rgb. Color get fontColorRgb => _fontColorRgb; @@ -277,27 +260,27 @@ class CellStyle implements Style { @override // ignore: avoid_equals_and_hash_code_on_mutable_classes int get hashCode => Object.hash( - name, - backColor, - fontName, - fontSize, - fontColor, - italic, - bold, - underline, - wrapText, - hAlign, - vAlign, - indent, - rotation, - index, - builtinId, - numberFormat, - numberFormatIndex, - isGlobalStyle, - locked, - borders, - ); + name, + backColor, + fontName, + fontSize, + fontColor, + italic, + bold, + underline, + wrapText, + hAlign, + vAlign, + indent, + rotation, + index, + builtinId, + numberFormat, + numberFormatIndex, + isGlobalStyle, + locked, + borders, + ); /// clear the borders void clear() { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style_wrapper.dart index 7ad986484..53fe4bc70 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/cell_style_wrapper.dart @@ -519,7 +519,6 @@ class CellStyleWrapper implements Style { } @override - /// Represents the locked. bool get locked { bool locked = true; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/styles_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/styles_collection.dart index 5ab71b07a..3deb1c637 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/styles_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/cell_styles/styles_collection.dart @@ -48,7 +48,7 @@ class StylesCollection { 'nl-BE': r'_(€* #,##0.00_)', 'pl-PL': r'_(#,##0.00_*zł', 'pt-PT': r'_(#,##0.00_*€', - 'ru-RU': r'_(#,##0.00_*₽' + 'ru-RU': r'_(#,##0.00_*₽', }; /// Dictionary. Key - Culture, value - Symbols. @@ -62,7 +62,7 @@ class StylesCollection { 'nl-BE': '€', 'pl-PL': 'zł', 'pt-PT': '€', - 'ru-RU': '₽' + 'ru-RU': '₽', }; /// Default styles names. @@ -128,7 +128,8 @@ class StylesCollection { if (index is String) { if (!_dictStyles.containsKey(index)) { throw Exception( - 'Style with specified name does not exist. Name: $index, value'); + 'Style with specified name does not exist. Name: $index, value', + ); } return _dictStyles[index]; } else { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_impl.dart index bac73957f..7bbcbb2fd 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_impl.dart @@ -11,7 +11,6 @@ class AboveBelowAverageImpl implements AboveBelowAverage { int _stdDevValue = 1; @override - /// Specifies whether the conditional formatting rule looks for cell values above or below the range average or standard deviation. ExcelCFAverageType get averageType { return _averageType; @@ -26,7 +25,6 @@ class AboveBelowAverageImpl implements AboveBelowAverage { } @override - /// Specifies standard deviation number for AboveAverage conditional formatting rule. int get stdDevValue { return _stdDevValue; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_wrapper.dart index cc0c28240..3681348c9 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/above_below_average/above_below_average_wrapper.dart @@ -8,7 +8,9 @@ import '../condformat_wrapper.dart'; class AboveBelowAverageWrapper implements AboveBelowAverage { /// Initializes new instance of the wrapper. AboveBelowAverageWrapper( - AboveBelowAverageImpl aboveAverage, ConditionalFormatWrapper format) { + AboveBelowAverageImpl aboveAverage, + ConditionalFormatWrapper format, + ) { _wrapped = aboveAverage; _format = format; } @@ -21,7 +23,6 @@ class AboveBelowAverageWrapper implements AboveBelowAverage { late ConditionalFormatWrapper _format; @override - /// Specifies whether the conditional formatting rule looks for cell values above or below the range average or standard deviation. ExcelCFAverageType get averageType { return _wrapped.averageType; @@ -33,7 +34,6 @@ class AboveBelowAverageWrapper implements AboveBelowAverage { } @override - /// Specifies standard deviation number for AboveAverage conditional formatting rule. int get stdDevValue { return _wrapped.stdDevValue; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_impl.dart index f358d74da..abf259681 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_impl.dart @@ -19,14 +19,13 @@ class ColorScaleImpl implements ColorScale { static List _defaultColors3 = [ '#F8696B', '#FFEB84', - '#63BE7B' + '#63BE7B', ]; /// A collection of individual ConditionValue objects. List _arrCriteria = []; @override - /// Returns a collection of individual IColorConditionValue objects. // ignore: unnecessary_getters_setters List get criteria { @@ -40,7 +39,6 @@ class ColorScaleImpl implements ColorScale { } @override - /// Sets number of IColorConditionValue objects in the collection. Supported values are 2 and 3. void setConditionCount(int count) { if (count < 2 || count > 3) { @@ -58,15 +56,30 @@ class ColorScaleImpl implements ColorScale { (count == 2) ? _defaultColors2 : _defaultColors3; int iColorIndex = 0; - _arrCriteria.add(ColorConditionValueImpl( - ConditionValueType.lowestValue, '0', arrColors[iColorIndex++])); + _arrCriteria.add( + ColorConditionValueImpl( + ConditionValueType.lowestValue, + '0', + arrColors[iColorIndex++], + ), + ); if (count == 3) { - _arrCriteria.add(ColorConditionValueImpl( - ConditionValueType.percentile, '50', arrColors[iColorIndex++])); + _arrCriteria.add( + ColorConditionValueImpl( + ConditionValueType.percentile, + '50', + arrColors[iColorIndex++], + ), + ); } - _arrCriteria.add(ColorConditionValueImpl( - ConditionValueType.highestValue, '0', arrColors[iColorIndex++])); + _arrCriteria.add( + ColorConditionValueImpl( + ConditionValueType.highestValue, + '0', + arrColors[iColorIndex++], + ), + ); } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_wrapper.dart index 5f35097a5..856f6f50f 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/color_scale/color_scale_wrapper.dart @@ -9,7 +9,9 @@ import 'color_scale.dart'; class ColorScaleWrapper implements ColorScale { /// Initializes new instance of the wrapper. ColorScaleWrapper( - ColorScaleImpl colorScale, ConditionalFormatWrapper format) { + ColorScaleImpl colorScale, + ConditionalFormatWrapper format, + ) { _wrapped = colorScale; _format = format; _updateCollection(_wrapped.criteria); @@ -25,7 +27,6 @@ class ColorScaleWrapper implements ColorScale { List _arrConditions = []; @override - /// Returns a collection of individual _ColorConditionValue objects. // ignore: unnecessary_getters_setters List get criteria { @@ -39,7 +40,6 @@ class ColorScaleWrapper implements ColorScale { } @override - /// Sets number of _ColorConditionValue objects in the collection. Supported values are 2 and 3. void setConditionCount(int count) { beginUpdate(); @@ -77,7 +77,9 @@ class ColorScaleWrapper implements ColorScale { void _add(int count, List arrSource) { for (int i = 0; i < count; i++) { final ColorConditionValueWrapper wrapper = ColorConditionValueWrapper( - arrSource[i] as ColorConditionValueImpl, this); + arrSource[i] as ColorConditionValueImpl, + this, + ); _arrConditions.add(wrapper); } } @@ -97,6 +99,8 @@ class ColorScaleWrapper implements ColorScale { /// Removes wrappers from criteria collection. void _remove(int count) { _arrConditions.removeRange( - _arrConditions.length - count, _arrConditions.length); + _arrConditions.length - count, + _arrConditions.length, + ); } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_collection_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_collection_wrapper.dart index 27510c29d..d8610120d 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_collection_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_collection_wrapper.dart @@ -38,21 +38,18 @@ class CondFormatCollectionWrapper implements ConditionalFormats { } @override - /// Gets the number of conditional formats in the collection. Read-only. int get count { return condFormats!.innerList.length; } @override - /// Gets the number of conditional formats in the collection. Read-only. set count(int value) { condFormats!.innerList.length = value; } @override - /// Adds new condition to the collection. ConditionalFormat addCondition() { if (condFormats == null) { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_wrapper.dart index 056ac9747..44d030b48 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condformat_wrapper.dart @@ -60,21 +60,18 @@ class ConditionalFormatWrapper implements ConditionalFormat { Range? range; @override - /// Gets or sets the type of the conditional format. ExcelCFType get formatType { return getCondition().formatType; } @override - /// Gets or sets the type of the conditional format. set formatType(ExcelCFType value) { getCondition().formatType = value; } @override - /// Gets or sets one of the constants of see cref="CFTimePeriods" enumeration /// which represents the type of the time period. CFTimePeriods get timePeriodType { @@ -82,7 +79,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets or sets one of the constants of see cref="CFTimePeriods" enumeration /// which represents the type of the time period. set timePeriodType(CFTimePeriods value) { @@ -90,245 +86,210 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets or sets the comparison operator for the conditional format. ExcelComparisonOperator get operator { return getCondition().operator; } @override - /// Gets or sets the comparison operator for the conditional format. set operator(ExcelComparisonOperator value) { getCondition().operator = value; } @override - /// Gets or sets a boolean value indicating whether the font is bold. bool get isBold { return getCondition().isBold; } @override - /// Gets or sets a boolean value indicating whether the font is bold. set isBold(bool value) { getCondition().isBold = value; } @override - /// Gets or sets a boolean value indicating whether the font is Italic. bool get isItalic { return getCondition().isItalic; } @override - /// Gets or sets a boolean value indicating whether the font is Italic. set isItalic(bool value) { getCondition().isItalic = value; } @override - /// Gets or sets the font color from predefined colors. String get fontColor { return getCondition().fontColor; } @override - /// Gets or sets the font color from predefined colors. set fontColor(String value) { getCondition().fontColor = value; } @override - /// Gets or sets the underline type for the conditional format. bool get underline { return getCondition().underline; } @override - /// Gets or sets the underline type for the conditional format. set underline(bool value) { getCondition().underline = value; } @override - /// Gets or sets the left border color from predefined colors. String get leftBorderColor { return getCondition().leftBorderColor; } @override - /// Gets or sets the left border color from predefined colors. set leftBorderColor(String value) { getCondition().leftBorderColor = value; } @override - /// Gets or sets the right border color from predefined colors. String get rightBorderColor { return getCondition().rightBorderColor; } @override - /// Gets or sets the right border color from predefined colors. set rightBorderColor(String value) { getCondition().rightBorderColor = value; } @override - /// Gets or sets the top border color from predefined colors. String get topBorderColor { return getCondition().topBorderColor; } @override - /// Gets or sets the top border color from predefined colors. set topBorderColor(String value) { getCondition().topBorderColor = value; } @override - /// Gets or sets the bottom border color from predefined colors. String get bottomBorderColor { return getCondition().bottomBorderColor; } @override - /// Gets or sets the bottom border color from predefined colors. set bottomBorderColor(String value) { getCondition().bottomBorderColor = value; } @override - /// Gets or sets the left border Style from predefined Styles. LineStyle get leftBorderStyle { return getCondition().leftBorderStyle; } @override - /// Gets or sets the left border Style from predefined Styles. set leftBorderStyle(LineStyle value) { getCondition().leftBorderStyle = value; } @override - /// Gets or sets the right border Style from predefined Styles. LineStyle get rightBorderStyle { return getCondition().rightBorderStyle; } @override - /// Gets or sets the right border Style from predefined Styles. set rightBorderStyle(LineStyle value) { getCondition().rightBorderStyle = value; } @override - /// Gets or sets the top border Style from predefined Styles. LineStyle get topBorderStyle { return getCondition().topBorderStyle; } @override - /// Gets or sets the top border Style from predefined Styles. set topBorderStyle(LineStyle value) { getCondition().topBorderStyle = value; } @override - /// Gets or sets the bottom border Style from predefined Styles. LineStyle get bottomBorderStyle { return getCondition().bottomBorderStyle; } @override - /// Gets or sets the bottom border Style from predefined Styles. set bottomBorderStyle(LineStyle value) { getCondition().bottomBorderStyle = value; } @override - /// Gets or sets the value or expression associated with the conditional format. String get firstFormula { return getCondition().firstFormula; } @override - /// Gets or sets the value or expression associated with the conditional format. set firstFormula(String value) { getCondition().firstFormula = value; } @override - /// Gets or sets the value or expression associated with the second conditional format. String get secondFormula { return getCondition().secondFormula; } @override - /// Gets or sets the value or expression associated with the second conditional format. set secondFormula(String value) { getCondition().secondFormula = value; } @override - /// Gets or sets the background color from predefined colors. String get backColor { return getCondition().backColor; } @override - /// Gets or sets the background color from predefined colors. set backColor(String value) { getCondition().backColor = value; } @override - /// Gets or sets number format index of the conditional format rule. String? get numberFormat { return getCondition().numberFormat; } @override - /// Gets or sets number format index of the conditional format rule. set numberFormat(String? value) { getCondition().numberFormat = value; } @override - /// Gets or sets a boolean value that determines if additional formatting rules on the cell should be evaluated /// if the current rule evaluates to True. bool get stopIfTrue { @@ -336,7 +297,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets or sets a boolean value that determines if additional formatting rules on the cell should be evaluated /// if the current rule evaluates to True. set stopIfTrue(bool value) { @@ -344,7 +304,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets or sets the text value used in SpecificText conditional formatting rule. /// The default value is null. String? get text { @@ -352,7 +311,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets or sets the text value used in SpecificText conditional formatting rule. /// The default value is null. set text(String? value) { @@ -365,12 +323,13 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets TopBottom conditional formatting rule. Read-only. TopBottom? get topBottom { if (formatType == ExcelCFType.topBottom) { - _topBottom ??= - TopBottomWrapper(getCondition().topBottom! as TopBottomImpl, this); + _topBottom ??= TopBottomWrapper( + getCondition().topBottom! as TopBottomImpl, + this, + ); } else { _topBottom = null; } @@ -383,12 +342,13 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets AboveBelowAverage conditional formatting rule. Read-only. AboveBelowAverage? get aboveBelowAverage { if (formatType == ExcelCFType.aboveBelowAverage) { _aboveBelowAverage ??= AboveBelowAverageWrapper( - getCondition().aboveBelowAverage! as AboveBelowAverageImpl, this); + getCondition().aboveBelowAverage! as AboveBelowAverageImpl, + this, + ); } else { _aboveBelowAverage = null; } @@ -402,12 +362,13 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets color scale conditional formatting rule. Read-only. ColorScale? get colorScale { if (formatType == ExcelCFType.colorScale) { - _colorScale ??= - ColorScaleWrapper(getCondition().colorScale! as ColorScaleImpl, this); + _colorScale ??= ColorScaleWrapper( + getCondition().colorScale! as ColorScaleImpl, + this, + ); } else { _colorScale = null; } @@ -421,7 +382,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets color scale conditional formatting rule. Read-only. IconSet? get iconSet { if (formatType == ExcelCFType.iconSet) { @@ -439,7 +399,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets color scale conditional formatting rule. Read-only. DataBar? get dataBar { if (formatType == ExcelCFType.dataBar) { @@ -477,7 +436,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets the value or expression associated with the conditional format /// in R1C1 notation. String get firstFormulaR1C1 { @@ -485,7 +443,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// sets the value or expression associated with the conditional format /// in R1C1 notation. set firstFormulaR1C1(String value) { @@ -494,7 +451,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets the value or expression associated with the conditional format /// in R1C1 notation. String get secondFormulaR1C1 { @@ -502,7 +458,6 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// sets the value or expression associated with the conditional format /// in R1C1 notation. set secondFormulaR1C1(String value) { @@ -511,84 +466,72 @@ class ConditionalFormatWrapper implements ConditionalFormat { } @override - /// Gets or sets the font color from Rgb. Color get fontColorRgb { return getCondition().fontColorRgb; } @override - /// Gets or sets the font color from Rgb. set fontColorRgb(Color value) { getCondition().fontColorRgb = value; } @override - /// Gets or sets the background color from Rgb. Color get backColorRgb { return getCondition().backColorRgb; } @override - /// Gets or sets the background color from Rgb. set backColorRgb(Color value) { getCondition().backColorRgb = value; } @override - /// Gets or sets the left border color from Rgb. Color get leftBorderColorRgb { return getCondition().leftBorderColorRgb; } @override - /// Gets or sets the left border color from Rgb. set leftBorderColorRgb(Color value) { getCondition().leftBorderColorRgb = value; } @override - /// Gets or sets the right border color from Rgb. Color get rightBorderColorRgb { return getCondition().rightBorderColorRgb; } @override - /// Gets or sets the right border color from Rgb. set rightBorderColorRgb(Color value) { getCondition().rightBorderColorRgb = value; } @override - /// Gets or sets the top border color from Rgb. Color get topBorderColorRgb { return getCondition().topBorderColorRgb; } @override - /// Gets or sets the top border color from Rgb. set topBorderColorRgb(Color value) { getCondition().topBorderColorRgb = value; } @override - /// Gets or sets the bottom border color from Rgb. Color get bottomBorderColorRgb { return getCondition().bottomBorderColorRgb; } @override - /// Gets or sets the bottom border color from Rgb. set bottomBorderColorRgb(Color value) { getCondition().bottomBorderColorRgb = value; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condition_value.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condition_value.dart index 558db96e5..49d1506e4 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condition_value.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/condition_value.dart @@ -286,19 +286,16 @@ class ConditionValueImpl extends ConditionValue { ConditionValueImpl(this.type, this.value); @override - /// Returns or sets one of the constants of the ConditionValueType enumeration /// which specifies how the threshold values for a data bar, color scale, /// or icon set conditional format are determined. late ConditionValueType type; @override - /// Returns or sets threshold values for the conditional format. late String value; @override - /// Sets the operator for the threshold values in the conditional format. ConditionalFormatOperator operator = ConditionalFormatOperator.greaterThanorEqualTo; @@ -425,37 +422,33 @@ class ColorConditionValueImpl implements ColorConditionValue { late Color _formatColorRgb; @override - /// Returns or sets one of the constants of the ConditionValueType enumeration /// which specifies how the threshold values for a data bar, color scale, /// or icon set conditional format are determined. late ConditionValueType type; @override - /// Returns or sets threshold values for the conditional format. late String value; @override - /// Sets the operator for the threshold values in the conditional format. ConditionalFormatOperator operator = ConditionalFormatOperator.greaterThanorEqualTo; @override - /// The color assigned to the threshold of a color scale conditional format. String get formatColor => _formatColor; @override set formatColor(String value) { _formatColor = value; - _formatColorRgb = - Color(int.parse(_formatColor.substring(1, 7), radix: 16) + 0xFF000000); + _formatColorRgb = Color( + int.parse(_formatColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } @override - /// The color assigned to the threshold of a color scale conditional format in Rgb. Color get formatColorRgb => _formatColorRgb; @@ -478,7 +471,9 @@ class ColorConditionValueImpl implements ColorConditionValue { class ColorConditionValueWrapper extends ColorConditionValue { /// Initializes new instance of the wrapped. ColorConditionValueWrapper( - ColorConditionValueImpl value, ColorScaleWrapper parent) { + ColorConditionValueImpl value, + ColorScaleWrapper parent, + ) { wrapped = value; _parent = parent; } @@ -518,7 +513,6 @@ class ColorConditionValueWrapper extends ColorConditionValue { } @override - /// Returns one of the constants of the XlConditionValueTypes enumeration, /// which specifies how the threshold values for a data bar, color scale, /// or icon set conditional format are determined. Read-only. @@ -536,7 +530,6 @@ class ColorConditionValueWrapper extends ColorConditionValue { } @override - /// Returns or sets the shortest bar or longest bar threshold value for a data /// bar conditional format. String get value { @@ -553,7 +546,6 @@ class ColorConditionValueWrapper extends ColorConditionValue { } @override - /// Returns or sets one of the constants of the ConditionalFormatOperator enumeration, /// which specifes if the threshold is "greater than" or "greater than or equal to" the threshold value. ConditionalFormatOperator get operator { @@ -680,32 +672,31 @@ class IconConditionValueImpl implements IconConditionValue { /// Initializes new instance of the class. IconConditionValueImpl.withType( - this.iconSet, this.index, this.type, this.value); + this.iconSet, + this.index, + this.type, + this.value, + ); @override - /// Returns or sets one of the constants of the IconConditionValueType enumeration. It specifies how the threshold values for icon set conditional format are determined. late ExcelIconSetType iconSet; @override - /// Returns or sets index of the iconset type's individual icon index. late int index; @override - /// Returns or sets one of the constants of the ConditionValueType enumeration /// which specifies how the threshold values for a data bar, color scale, /// or icon set conditional format are determined. late ConditionValueType type; @override - /// Returns or sets threshold values for the conditional format. late String value; @override - /// Sets the operator for the threshold values in the conditional format. ConditionalFormatOperator operator = ConditionalFormatOperator.greaterThanorEqualTo; @@ -715,7 +706,9 @@ class IconConditionValueImpl implements IconConditionValue { class IconConditionValueWrapper implements IconConditionValue { /// Initializes new instance of wrapper. IconConditionValueWrapper( - IconConditionValueImpl value, IconSetWrapper parent) { + IconConditionValueImpl value, + IconSetWrapper parent, + ) { wrapped = value; _parent = parent; } @@ -727,7 +720,6 @@ class IconConditionValueWrapper implements IconConditionValue { late IconSetWrapper _parent; @override - /// Returns or sets IconSet for individual IconSet criteria. ExcelIconSetType get iconSet { return wrapped.iconSet; @@ -741,7 +733,6 @@ class IconConditionValueWrapper implements IconConditionValue { } @override - /// Gets or sets index of the iconset type's individual icon index. int get index { return wrapped.index; @@ -755,7 +746,6 @@ class IconConditionValueWrapper implements IconConditionValue { } @override - /// Gets or sets the condition value type /// which specifies how the threshold values for a data bar, color scale, /// or icon set conditional format are determined. Read-only. @@ -771,7 +761,6 @@ class IconConditionValueWrapper implements IconConditionValue { } @override - /// Gets or sets the shortest bar or longest bar threshold value for a data bar conditional format. String get value { return wrapped.value; @@ -785,7 +774,6 @@ class IconConditionValueWrapper implements IconConditionValue { } @override - /// Gets or sets the operator ConditionalFormatOperator get operator { return wrapped.operator; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_collections.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_collections.dart index 4835b2aaa..060368644 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_collections.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_collections.dart @@ -34,21 +34,18 @@ class ConditionalFormatsImpl implements ConditionalFormats { } @override - /// Gets the number of conditional formats in the collection. Read-only. int get count { return innerList.length; } @override - /// Gets the number of conditional formats in the collection. Read-only. set count(int value) { innerList.length = value; } @override - /// Adds new condition to the collection. ConditionalFormat addCondition() { if (count >= _maxCFNumber) { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_impl.dart index 15a70a259..6dbb98469 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/conditionalformat_impl.dart @@ -154,15 +154,15 @@ class ConditionalFormatImpl implements ConditionalFormat { late String _backColor; @override - /// Gets/sets back color. String get backColor => _backColor; @override set backColor(String value) { _backColor = value; - _backColorRgb = - Color(int.parse(_backColor.substring(1, 7), radix: 16) + 0xFF000000); + _backColorRgb = Color( + int.parse(_backColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } late int numberFormatIndex; @@ -179,28 +179,24 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Returns or sets the format code for the object. Read/write String. String? get numberFormat { return numberFormatObject.formatString; } @override - /// Sets the number format. set numberFormat(String? value) { numberFormatIndex = book.innerFormats.findOrCreateFormat(value); } @override - /// Gets or sets the type of the conditional format. ExcelCFType get formatType { return _formatType; } @override - /// Gets or sets the type of the conditional format. set formatType(ExcelCFType value) { switch (value) { @@ -263,7 +259,6 @@ class ConditionalFormatImpl implements ConditionalFormat { late String _topBorderColor; @override - /// Gets/sets top Border. String get topBorderColor => _topBorderColor; @@ -271,13 +266,13 @@ class ConditionalFormatImpl implements ConditionalFormat { set topBorderColor(String value) { _topBorderColor = value; _topBorderColorRgb = Color( - int.parse(_topBorderColor.substring(1, 7), radix: 16) + 0xFF000000); + int.parse(_topBorderColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } late String _bottomBorderColor; @override - /// Gets/sets top Border. String get bottomBorderColor => _bottomBorderColor; @@ -285,13 +280,13 @@ class ConditionalFormatImpl implements ConditionalFormat { set bottomBorderColor(String value) { _bottomBorderColor = value; _bottomBorderColorRgb = Color( - int.parse(_bottomBorderColor.substring(1, 7), radix: 16) + 0xFF000000); + int.parse(_bottomBorderColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } late String _rightBorderColor; @override - /// Gets/sets right Border. String get rightBorderColor => _rightBorderColor; @@ -299,12 +294,12 @@ class ConditionalFormatImpl implements ConditionalFormat { set rightBorderColor(String value) { _rightBorderColor = value; _rightBorderColorRgb = Color( - int.parse(_rightBorderColor.substring(1, 7), radix: 16) + 0xFF000000); + int.parse(_rightBorderColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } late String _leftBorderColor; @override - /// Gets/sets leftBorder. String get leftBorderColor => _leftBorderColor; @@ -312,26 +307,23 @@ class ConditionalFormatImpl implements ConditionalFormat { set leftBorderColor(String value) { _leftBorderColor = value; _leftBorderColorRgb = Color( - int.parse(_leftBorderColor.substring(1, 7), radix: 16) + 0xFF000000); + int.parse(_leftBorderColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } @override - // Gets or sets right border style late LineStyle rightBorderStyle; @override - // Gets or set bottom border style late LineStyle bottomBorderStyle; @override - // Gets or sets left border style late LineStyle leftBorderStyle; @override - // Gets or sets top border style late LineStyle topBorderStyle; @@ -339,45 +331,39 @@ class ConditionalFormatImpl implements ConditionalFormat { late String _fontColor; @override - /// Gets/sets font color. String get fontColor => _fontColor; @override set fontColor(String value) { _fontColor = value; - _fontColorRgb = - Color(int.parse(_fontColor.substring(1, 7), radix: 16) + 0xFF000000); + _fontColorRgb = Color( + int.parse(_fontColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } @override - /// Gets or sets the comparison operator for the conditional format. late ExcelComparisonOperator operator; @override - /// Gets and sets boolean value indicating whether the font is bold. late bool isBold; @override - /// Gets a boolean value indicating whether the font is italic. late bool isItalic; @override - /// Gets or sets the underline type for the conditional format. late bool underline; @override - /// Gets the text value used in conditional formatting rule. /// The default value is null. String? get text => _text; @override - /// sets the text value used in conditional formatting rule. set text(String? value) { if (value == null || value == '') { @@ -390,19 +376,16 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets or sets a boolean value that determines if additional formatting rules on the cell should be evaluated /// if the current rule evaluates to True. late bool stopIfTrue; @override - /// Gets one of the constants of see cref="CFTimePeriods" enumeration /// which represents the type of the time period. CFTimePeriods get timePeriodType => _cfTimePeriod; @override - /// Sets one of the constants of see cref="CFTimePeriods" enumeration /// which represents the type of the time period. set timePeriodType(CFTimePeriods value) { @@ -413,18 +396,18 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets the value or expression associated with the conditional format. String firstFormula = ''; @override - /// Gets the value or expression associated with the conditional format. String secondFormula = ''; /// Sets the specifed text value for the SpecficText conditional format. void _setSpecificTextString( - ExcelComparisonOperator compOperator, String value) { + ExcelComparisonOperator compOperator, + String value, + ) { String val; switch (compOperator) { case ExcelComparisonOperator.beginsWith: @@ -527,7 +510,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets TopBottom conditional formatting rule. TopBottom? get topBottom { return _topBottom; @@ -539,7 +521,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets AboveBelowAverage conditional formatting rule. AboveBelowAverage? get aboveBelowAverage { return _aboveBelowAverage; @@ -551,7 +532,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Color scale settings. ColorScale? get colorScale { return _colorScale; @@ -563,7 +543,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Color scale settings. IconSet? get iconSet { return _iconSet; @@ -575,7 +554,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets data bar conditional formatting rule. Valid only if FormatType is set to DataBar. DataBar? get dataBar { return _dataBar; @@ -589,13 +567,11 @@ class ConditionalFormatImpl implements ConditionalFormat { late String _firstFormulaR1C1; @override - /// Gets the value or expression associated with the conditional format /// in R1C1 notation. String get firstFormulaR1C1 => _firstFormulaR1C1; @override - /// sets the value or expression associated with the conditional format /// in R1C1 notation. set firstFormulaR1C1(String value) { @@ -615,7 +591,8 @@ class ConditionalFormatImpl implements ConditionalFormat { if (range != null) { final List cells = []; final RegExp regex = RegExp( - r'\R\C(-?\d+)|\R\[(-?\d+)\]\C(-?\d+)|\R(-?\d+)\C(-?\d+)|\R(-?\d+)\C\[(-?\d+)\]|\R\[(-?\d+)\]\C\[(-?\d+)\]|\R\C\[(-?\d+)\]|\R\[(-?\d+)\]\C|\R\C|\R(-?\d+)\C'); + r'\R\C(-?\d+)|\R\[(-?\d+)\]\C(-?\d+)|\R(-?\d+)\C(-?\d+)|\R(-?\d+)\C\[(-?\d+)\]|\R\[(-?\d+)\]\C\[(-?\d+)\]|\R\C\[(-?\d+)\]|\R\[(-?\d+)\]\C|\R\C|\R(-?\d+)\C', + ); final List matches = regex.allMatches(formulaR1C1).toList(); for (final Match match in matches) { cells.add(formulaR1C1.substring(match.start, match.end)); @@ -706,13 +683,11 @@ class ConditionalFormatImpl implements ConditionalFormat { String _secondFormulaR1C1 = ''; @override - /// Gets the value or expression associated with the conditional format /// in R1C1 notation. String get secondFormulaR1C1 => _secondFormulaR1C1; @override - /// sets the value or expression associated with the conditional format /// in R1C1 notation. set secondFormulaR1C1(String value) { @@ -739,7 +714,6 @@ class ConditionalFormatImpl implements ConditionalFormat { late Color _topBorderColorRgb; @override - /// Gets/sets back color Rgb. Color get backColorRgb => _backColorRgb; @@ -750,7 +724,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets/sets font color Rgb. Color get fontColorRgb => _fontColorRgb; @@ -761,7 +734,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets or sets the left border color from Rgb. Color get leftBorderColorRgb => _leftBorderColorRgb; @@ -773,7 +745,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets or sets the right border color from Rgb. Color get rightBorderColorRgb => _rightBorderColorRgb; @@ -785,7 +756,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets or sets the top border color from Rgb. Color get topBorderColorRgb => _topBorderColorRgb; @@ -797,7 +767,6 @@ class ConditionalFormatImpl implements ConditionalFormat { } @override - /// Gets or sets the bottom border color from Rgb. Color get bottomBorderColorRgb => _bottomBorderColorRgb; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_impl.dart index 8045cdee8..65f5286f2 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_impl.dart @@ -71,49 +71,45 @@ class DataBarImpl implements DataBar { String? stGUID; @override - /// A ConditionValue object which specifies how the shortest bar is evaluated /// for a data bar conditional format. - ConditionValue minPoint = - ConditionValueImpl(ConditionValueType.automatic, '0'); + ConditionValue minPoint = ConditionValueImpl( + ConditionValueType.automatic, + '0', + ); @override - /// A ConditionValue object which specifies how the longest bar is evaluated /// for a data bar conditional format. - ConditionValue maxPoint = - ConditionValueImpl(ConditionValueType.automatic, '0'); + ConditionValue maxPoint = ConditionValueImpl( + ConditionValueType.automatic, + '0', + ); @override - /// A value that specifies the length of the longest /// data bar as a percentage of cell width. int percentMax = 100; @override - /// A value that specifies the length of the shortest /// data bar as a percentage of cell width. int percentMin = 0; @override - /// Returns or sets a Boolean value that specifies if the value in the cell /// is displayed if the data bar conditional format is applied to the range. bool showValue = true; @override - /// Represents whether the data bar has a border. bool hasBorder = false; @override - /// Represents the axis position for the data bar. DataBarAxisPosition dataBarAxisPosition = _defaultAxisPosition; @override - /// Represents whether the data bar has a gradient fill. bool get hasGradientFill { return _bHasGradientFill; @@ -126,7 +122,6 @@ class DataBarImpl implements DataBar { } @override - /// Represents the direction of the data bar. DataBarDirection get dataBarDirection { return _direction; @@ -139,7 +134,6 @@ class DataBarImpl implements DataBar { } @override - /// Represents the negative fill color of the data bar. String get negativeFillColor { if (hasDiffNegativeBarColor) { @@ -155,11 +149,11 @@ class DataBarImpl implements DataBar { hasExtensionList = true; hasDiffNegativeBarColor = true; _negativeFillColorRgb = Color( - int.parse(_negativeFillColor.substring(1, 7), radix: 16) + 0xFF000000); + int.parse(_negativeFillColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } @override - /// Represents the negative fill color of the data bar. Color get negativeFillColorRgb { if (hasDiffNegativeBarColor) { @@ -179,7 +173,6 @@ class DataBarImpl implements DataBar { } @override - /// Represents the negative border color of the data bar. String get negativeBorderColor { return _negativeBorderColor; @@ -191,12 +184,11 @@ class DataBarImpl implements DataBar { hasExtensionList = true; hasDiffNegativeBarBorderColor = true; _negativeBorderColorRgb = Color( - int.parse(_negativeBorderColor.substring(1, 7), radix: 16) + - 0xFF000000); + int.parse(_negativeBorderColor.substring(1, 7), radix: 16) + 0xFF000000, + ); } @override - /// Represents the negative border color of the data bar. Color get negativeBorderColorRgb => _negativeBorderColorRgb; @@ -223,23 +215,24 @@ class DataBarImpl implements DataBar { } @override - /// The color of the bars in a data bar conditional format. String get barColor => _barColor; @override set barColor(String value) { _barColor = value; - _barColorRgb = - Color(int.parse(_barColor.substring(1, 7), radix: 16) + 0xFF000000); + _barColorRgb = Color( + int.parse(_barColor.substring(1, 7), radix: 16) + 0xFF000000, + ); hasExtensionList = true; } @override - /// The color of the bars in a data bar conditional format. - Color get barColorRgb => _barColorRgb = - Color(int.parse(_barColor.substring(1, 7), radix: 16) + 0xFF000000); + Color get barColorRgb => + _barColorRgb = Color( + int.parse(_barColor.substring(1, 7), radix: 16) + 0xFF000000, + ); @override set barColorRgb(Color value) { @@ -249,20 +242,19 @@ class DataBarImpl implements DataBar { } @override - /// Represents the axis color of the data bar. String get barAxisColor => _barAxisColor; @override set barAxisColor(String value) { _barAxisColor = value; - _barAxisColorRgb = - Color(int.parse(_barAxisColor.substring(1, 7), radix: 16) + 0xFF000000); + _barAxisColorRgb = Color( + int.parse(_barAxisColor.substring(1, 7), radix: 16) + 0xFF000000, + ); hasExtensionList = true; } @override - /// Represents the axis color of the data bar in Rgb. Color get barAxisColorRgb => _barAxisColorRgb; @@ -274,20 +266,19 @@ class DataBarImpl implements DataBar { } @override - /// Represents the border color of the data bar. String get borderColor => _borderColor; @override set borderColor(String value) { _borderColor = value; - _borderColorRgb = - Color(int.parse(_borderColor.substring(1, 7), radix: 16) + 0xFF000000); + _borderColorRgb = Color( + int.parse(_borderColor.substring(1, 7), radix: 16) + 0xFF000000, + ); hasBorder = true; } @override - /// Represents the border color of the data bar in Rgb. Color get borderColorRgb => _borderColorRgb; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_wrapper.dart index bf6f0e53d..f755bfcdc 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/data_bar/data_bar_wrapper.dart @@ -39,7 +39,6 @@ class DataBarWrapper implements DataBar { } @override - /// Returns a ConditionValue object which specifies how the longest bar is evaluated /// for a data bar conditional format. ConditionValue get maxPoint { @@ -56,7 +55,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets/sets the color of the bars in a data bar conditional format. String get barColor { { @@ -72,7 +70,6 @@ class DataBarWrapper implements DataBar { } @override - /// Returns or sets a value that specifies the length of the longest /// data bar as a percentage of cell width. int get percentMax { @@ -89,7 +86,6 @@ class DataBarWrapper implements DataBar { } @override - /// Returns or sets a value that specifies the length of the shortest /// data bar as a percentage of cell width. int get percentMin { @@ -106,7 +102,6 @@ class DataBarWrapper implements DataBar { } @override - /// Returns or sets a Boolean value that specifies if the value in the cell /// is displayed if the data bar conditional format is applied to the range. bool get showValue { @@ -123,7 +118,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the axis color of the data bar. /// This element MUST exist if and only if axisPosition does not equal "none". String get barAxisColor { @@ -140,7 +134,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the border color of the data bar. /// This element MUST exist if and only if border equals "true". String get borderColor { @@ -157,7 +150,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets whether the data bar has a border. bool get hasBorder { { @@ -171,7 +163,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets whether the data bar has a gradient fill. bool get hasGradientFill { { @@ -185,7 +176,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the direction of the data bar. DataBarDirection get dataBarDirection { { @@ -201,7 +191,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the negative border color of the data bar. /// This element MUST exist if and only if negativeBarborderColorSameAsPositive equals "false" and border equals "true". String get negativeBorderColor { @@ -218,7 +207,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gest or sests the negative fill color of the data bar. /// This element MUST exist if and only if negativebarColorSameAsPositive equals "false". String get negativeFillColor { @@ -233,7 +221,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the axis position for the data bar. DataBarAxisPosition get dataBarAxisPosition { { @@ -260,7 +247,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets/sets the color of the bars in a data bar conditional format. Color get barColorRgb { return _wrapped.barColorRgb; @@ -274,7 +260,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the negative border color of the data bar. /// This element MUST exist if and only if negativeBarborderColorSameAsPositive equals "false" and border equals "true". Color get negativeBorderColorRgb { @@ -289,7 +274,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gest or sests the negative fill color of the data bar. /// This element MUST exist if and only if negativebarColorSameAsPositive equals "false". Color get negativeFillColorRgb { @@ -304,7 +288,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the axis color of the data bar in Rgb. /// This element MUST exist if and only if axisPosition does not equal "none". Color get barAxisColorRgb { @@ -321,7 +304,6 @@ class DataBarWrapper implements DataBar { } @override - /// Gets or sets the border color of the data bar in Rgb. /// This element MUST exist if and only if border equals "true". Color get borderColorRgb { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_impl.dart index 87262364a..de3cfcdcc 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_impl.dart @@ -22,7 +22,6 @@ class IconSetImpl implements IconSet { bool _hasCustomIconSet = false; @override - /// Returns an IconCriteria collection which represents the set of criteria for /// an icon set conditional formatting rule. List get iconCriteria { @@ -37,7 +36,6 @@ class IconSetImpl implements IconSet { } @override - /// Returns or sets an IconSets collection which specifies the icon set used /// in the conditional format. ExcelIconSetType get iconSet { @@ -55,19 +53,16 @@ class IconSetImpl implements IconSet { } @override - /// Returns or sets a Boolean value indicating if the thresholds for an icon /// set conditional format are determined using percentiles. bool percentileValues = false; @override - /// Returns or sets a Boolean value indicating if the order of icons is /// reversed for an icon set. bool reverseOrder = false; @override - /// Returns or sets a Boolean value indicating if only the icon is displayed /// for an icon set conditional format. bool showIconOnly = false; @@ -104,12 +99,18 @@ class IconSetImpl implements IconSet { } _arrCriteria = List.filled( - iCount, IconConditionValueImpl(_iconSet, 0)); + iCount, + IconConditionValueImpl(_iconSet, 0), + ); for (int i = 0; i < iCount; i++) { final int iValue = (i * 100 / iCount).round(); final IconConditionValue criteria = IconConditionValueImpl.withType( - _iconSet, i, ConditionValueType.percent, iValue.toString()); + _iconSet, + i, + ConditionValueType.percent, + iValue.toString(), + ); _arrCriteria[i] = criteria; } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_wrapper.dart index d07eb439b..768a416fa 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/icon_set/icon_set_wrapper.dart @@ -25,7 +25,6 @@ class IconSetWrapper implements IconSet { List _arrConditions = []; @override - /// Returns an IconCriteria collection which represents the set of criteria for /// an icon set conditional formatting rule. List get iconCriteria { @@ -40,7 +39,6 @@ class IconSetWrapper implements IconSet { } @override - /// Returns or sets an IconSets collection which specifies the icon set used /// in the conditional format. ExcelIconSetType get iconSet { @@ -57,7 +55,6 @@ class IconSetWrapper implements IconSet { } @override - /// Returns or sets a Boolean value indicating if the thresholds for an icon /// set conditional format are determined using percentiles. bool get percentileValues { @@ -74,7 +71,6 @@ class IconSetWrapper implements IconSet { } @override - /// Returns or sets a Boolean value indicating if the order of icons is /// reversed for an icon set. bool get reverseOrder { @@ -91,7 +87,6 @@ class IconSetWrapper implements IconSet { } @override - /// Returns or sets a Boolean value indicating if only the icon is displayed /// for an icon set conditional format. bool get showIconOnly { @@ -136,7 +131,9 @@ class IconSetWrapper implements IconSet { void _add(int count, List arrSource) { for (int i = 0; i < count; i++) { final IconConditionValueWrapper wrapper = IconConditionValueWrapper( - arrSource[i] as IconConditionValueImpl, this); + arrSource[i] as IconConditionValueImpl, + this, + ); _arrConditions.add(wrapper); } } @@ -156,6 +153,8 @@ class IconSetWrapper implements IconSet { /// Removes wrappers from criteria collection. void _remove(int count) { _arrConditions.removeRange( - _arrConditions.length - count, _arrConditions.length); + _arrConditions.length - count, + _arrConditions.length, + ); } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_impl.dart index db9ababf1..d2c44eb95 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_impl.dart @@ -8,17 +8,14 @@ class TopBottomImpl implements TopBottom { // ExcelCFTopBottomType _type = ExcelCFTopBottomType.top; @override - /// Specifies whether the ranking is evaluated from the top or bottom. ExcelCFTopBottomType type = ExcelCFTopBottomType.top; @override - /// Specifies whether the rank is determined by a percentage value. bool percent = false; @override - /// Specifies the maximum number or percentage of cells to be highlighted for this conditional formatting rule. int get rank => _rank; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_wrapper.dart index f49e08da9..c7d7e9d79 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/conditional_format/top_bottom/top_bottom_wrapper.dart @@ -20,42 +20,36 @@ class TopBottomWrapper implements TopBottom { late ConditionalFormatWrapper _format; @override - /// Specifies whether the ranking is evaluated from the top or bottom. ExcelCFTopBottomType get type { return _wrapped.type; } @override - /// Specifies whether the ranking is evaluated from the top or bottom. set type(ExcelCFTopBottomType value) { _wrapped.type = value; } @override - /// Specifies whether the rank is determined by a percentage value. bool get percent { return _wrapped.percent; } @override - /// Specifies whether the rank is determined by a percentage value. set percent(bool value) { _wrapped.percent = value; } @override - /// Specifies the maximum number or percentage of cells to be highlighted for this conditional formatting rule. int get rank { return _wrapped.rank; } @override - /// Specifies the maximum number or percentage of cells to be highlighted for this conditional formatting rule. set rank(int value) { _wrapped.rank = value; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_impl.dart index 9db7a6e30..1a509e15a 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_impl.dart @@ -94,7 +94,6 @@ class DataValidationImpl implements DataValidation { late String cellRange; @override - /// gets or sets the dataRange for DataValidation set dataRange(Range value) { dataRangeVal = value; @@ -102,70 +101,60 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the dataRange for DataValidation Range get dataRange { return dataRangeVal; } @override - /// gets or sets the type of allowType for DataValidation ExcelDataValidationType get allowType { return _allowTypeVal; } @override - /// gets or sets the type of allowType for DataValidation set allowType(ExcelDataValidationType value) { _allowTypeVal = value; } @override - /// gets or sets the isListInFormula for DataValidation bool get isListInFormula { return _isListInformulaVal; } @override - /// gets or sets the isListInFormula for DataValidation set isListInFormula(bool value) { _isListInformulaVal = value; } @override - /// gets or sets the comparisonOperator value for DataValidation set comparisonOperator(ExcelDataValidationComparisonOperator value) { _comparisonOperatorVal = value; } @override - /// gets or sets the comparisonOperator value for DataValidation ExcelDataValidationComparisonOperator get comparisonOperator { return _comparisonOperatorVal; } @override - /// gets or sets the firstDateTime for DataValidation DateTime get firstDateTime { return firstDateTimeVal; } @override - /// gets or sets the firstDateTime for DataValidation set firstDateTime(DateTime value) { firstDateTimeVal = value; } @override - /// gets or sets the firstFormula for DataValidation set firstFormula(String value) { if (firstFormula != value) { @@ -174,14 +163,12 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the firstFormula for DataValidation String get firstFormula { return _firstFormulaVal; } @override - /// gets or sets the secondFormula for DataValidation set secondFormula(String value) { if (secondFormula != value) { @@ -190,42 +177,36 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the secondFormula for DataValidation String get secondFormula { return _secondFormulaVal; } @override - /// gets or sets the showErrorBox for DataValidation set showErrorBox(bool value) { _showErrorBoxVal = value; } @override - /// gets or sets the showErrorBox for DataValidation bool get showErrorBox { return _showErrorBoxVal; } @override - /// gets or sets the secondDateTime for DataValidation set secondDateTime(DateTime value) { _secondDateTimeVal = value; } @override - /// gets or sets the secondDateTime for DataValidation DateTime get secondDateTime { return _secondDateTimeVal; } @override - /// gets or sets the errorBoxText for DataValidation set errorBoxText(String value) { _checkLimit('ErrorBoxText', value, _textLimit); @@ -233,14 +214,12 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the errorBoxText for DataValidation String get errorBoxText { return _errorBoxTextVal; } @override - /// gets or sets the errorBoxTitle for DataValidation set errorBoxTitle(String value) { _checkLimit('ErrorBoxTitle', value, _textLimit); @@ -248,14 +227,12 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the errorBoxTitle for DataValidation String get errorBoxTitle { return _errorBoxTitleVal; } @override - /// gets or sets the promptBoxText for DataValidation set promptBoxText(String value) { _checkLimit('PromptBoxText', value, _textLimit); @@ -263,28 +240,24 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the promptBoxText for DataValidation String get promptBoxText { return _promptBoxTextVal; } @override - /// gets or sets the showPromptBox for DataValidation set showPromptBox(bool value) { _showPromptBoxVal = value; } @override - /// gets or sets the showPromptBox for DataValidation bool get showPromptBox { return _showPromptBoxVal; } @override - /// gets or sets the promptBoxTitle for DataValidation set promptBoxTitle(String value) { _checkLimit('PromptBoxTitle', value, _textLimit); @@ -292,98 +265,84 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the promptBoxTitle for DataValidation String get promptBoxTitle { return _promptBoxTitleVal; } @override - /// gets or sets the promptBoxVposition for DataValidation set promptBoxVPosition(int value) { _dataValidationCollection.promptBoxVPositionVal = value; } @override - /// gets or sets the promptBoxVposition for DataValidation int get promptBoxVPosition { return _dataValidationCollection.promptBoxVPositionVal; } @override - /// gets or sets the promptBoxHposition for DataValidation set promptBoxHPosition(int value) { _dataValidationCollection.promptBoxHPositionVal = value; } @override - /// gets or sets the promptBoxHposition for DataValidation int get promptBoxHPosition { return _dataValidationCollection.promptBoxHPositionVal; } @override - /// gets or sets the isPromptBoxPositionFixed for DataValidation set isPromptBoxPositionFixed(bool value) { _dataValidationCollection.isPromptBoxPositionFixedVal = value; } @override - /// gets or sets the isPromptBoxPositionFixed for DataValidation bool get isPromptBoxPositionFixed { return _dataValidationCollection.isPromptBoxPositionFixedVal; } @override - ///gets or sets the isSuppressDropDownArrow for DataValidation set isSuppressDropDownArrow(bool value) { _isSuppressDropDownArrowVal = value; } @override - /// gets or sets the isSuppressDropDownArrow for DataValidation bool get isSuppressDropDownArrow { return _isSuppressDropDownArrowVal; } @override - /// gets or sets the isEmptyCellAllowed for DataValidation set isEmptyCellAllowed(bool value) { _isEmptyCellAllowedVal = value; } @override - /// gets or sets the isEmptyCellAllowed for DataValidation bool get isEmptyCellAllowed { return _isEmptyCellAllowedVal; } @override - /// gets or sets the errorStyle for DataValidation set errorStyle(ExcelDataValidationErrorStyle value) { _errorStyleVal = value; } @override - /// gets or sets the errorStyle for DataValidation ExcelDataValidationErrorStyle get errorStyle { return _errorStyleVal; } @override - /// gets or sets the listOfValues for DataValidation set listOfValues(List value) { _listOfValuesVal = value; @@ -392,7 +351,6 @@ class DataValidationImpl implements DataValidation { } @override - /// gets or sets the listOfValues for DataValidation List get listOfValues { return _listOfValuesVal; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_table.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_table.dart index 1cdf4196e..73ca7aa62 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_table.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_table.dart @@ -29,9 +29,11 @@ class DataValidationTable { /// Represents the method to check whether dataValidation is applied to the cell DataValidationImpl? findDataValidation(String dvValue) { - for (int dvCollection = 0; - dvCollection < dataValidationCollectionList.length; - dvCollection++) { + for ( + int dvCollection = 0; + dvCollection < dataValidationCollectionList.length; + dvCollection++ + ) { final DataValidationImpl? result = dataValidationCollectionList[dvCollection].findByCellIndex(dvValue); if (result != null) { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_wrapper.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_wrapper.dart index a8f587f7a..a51c9f169 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_wrapper.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/datavalidation/datavalidation_wrapper.dart @@ -39,14 +39,12 @@ class DataValidationWrapper implements DataValidation { late DataValidationImpl _mdataValidation; @override - /// gets or sets the type of allowType for DataValidation ExcelDataValidationType get allowType { return _mdataValidation.allowType; } @override - /// gets or sets the allowType for DataValidation set allowType(ExcelDataValidationType value) { if (allowType != value) { @@ -59,14 +57,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the type of comparisonOperator for DataValidation ExcelDataValidationComparisonOperator get comparisonOperator { return _mdataValidation.comparisonOperator; } @override - /// gets or sets the comparisonOperator value for DataValidation set comparisonOperator(ExcelDataValidationComparisonOperator value) { if (comparisonOperator != value) { @@ -75,7 +71,6 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the firstFormula for DataValidation String get firstFormula { if (allowType == ExcelDataValidationType.date) { @@ -88,7 +83,6 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the firstFormula for DataValidation set firstFormula(String value) { if (firstFormula != value) { @@ -97,14 +91,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the firstDateTime for DataValidation DateTime get firstDateTime { return _mdataValidation.firstDateTime; } @override - /// gets or sets the firstDateTime for DataValidation set firstDateTime(DateTime value) { if (firstDateTime != value || firstDateTime == DateTime(1)) { @@ -113,14 +105,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the secondDateTime for DataValidation DateTime get secondDateTime { return _mdataValidation.secondDateTime; } @override - /// gets or sets the secondDateTime for DataValidation set secondDateTime(DateTime value) { if (secondDateTime != value || firstDateTime == DateTime(1)) { @@ -129,7 +119,6 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the secondFormula for DataValidation String get secondFormula { if (allowType == ExcelDataValidationType.date) { @@ -142,7 +131,6 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the secondFormula for DataValidation set secondFormula(String value) { if (secondFormula != value) { @@ -151,14 +139,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the showErrorBox for DataValidation bool get showErrorBox { return _mdataValidation.showErrorBox; } @override - /// gets or sets the showErrorBox for DataValidation set showErrorBox(bool value) { if (showErrorBox != value) { @@ -167,7 +153,6 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the errorBoxText for DataValidation set errorBoxText(String value) { if (errorBoxText != value) { @@ -176,14 +161,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the errorBoxText for DataValidation String get errorBoxText { return _mdataValidation.errorBoxText; } @override - /// gets or sets the errorBoxTitle for DataValidation set errorBoxTitle(String value) { if (errorBoxTitle != value) { @@ -192,14 +175,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the errorBoxTitle for DataValidation String get errorBoxTitle { return _mdataValidation.errorBoxTitle; } @override - /// gets or sets the promptBoxText for DataValidation set promptBoxText(String value) { if (promptBoxText != value) { @@ -208,14 +189,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the promptBoxText for DataValidation String get promptBoxText { return _mdataValidation.promptBoxText; } @override - /// gets or sets the showPromptBox for DataValidation set showPromptBox(bool value) { if (showPromptBox != value) { @@ -224,14 +203,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the showPromptBox for DataValidation bool get showPromptBox { return _mdataValidation.showPromptBox; } @override - /// gets or sets the promptBoxTitle for DataValidation set promptBoxTitle(String value) { if (promptBoxTitle != value) { @@ -240,14 +217,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the promptBoxTitle for DataValidation String get promptBoxTitle { return _mdataValidation.promptBoxTitle; } @override - /// gets or sets the promptBoxVposition for DataValidation set promptBoxVPosition(int value) { if (promptBoxVPosition != value) { @@ -257,14 +232,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the promptBoxVposition for DataValidation int get promptBoxVPosition { return _mdataValidation.promptBoxVPosition; } @override - /// gets or sets the promptBoxHposition for DataValidation set promptBoxHPosition(int value) { if (promptBoxHPosition != value) { @@ -274,14 +247,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the promptBoxHposition for DataValidation int get promptBoxHPosition { return _mdataValidation.promptBoxHPosition; } @override - /// gets or sets the isPromptBoxPositionFixed for DataValidation. set isPromptBoxPositionFixed(bool value) { if (isPromptBoxPositionFixed != value) { @@ -291,14 +262,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the isPromptBoxPositionFixed for DataValidation bool get isPromptBoxPositionFixed { return _mdataValidation.isPromptBoxPositionFixed; } @override - /// gets or sets the isEmptyCellAllowed for DataValidation set isEmptyCellAllowed(bool value) { if (isEmptyCellAllowed != value) { @@ -307,14 +276,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the isEmptyCellAllowed for DataValidation bool get isEmptyCellAllowed { return _mdataValidation.isEmptyCellAllowed; } @override - /// gets or sets the errorStyle for DataValidation set errorStyle(ExcelDataValidationErrorStyle value) { if (errorStyle != value) { @@ -323,14 +290,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the errorStyle for DataValidation ExcelDataValidationErrorStyle get errorStyle { return _mdataValidation.errorStyle; } @override - /// gets or sets the isListInFormula for DataValidation set isListInFormula(bool value) { if (isListInFormula != value) { @@ -339,14 +304,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the isListInFormula for DataValidation bool get isListInFormula { return _mdataValidation.isListInFormula; } @override - /// gets or sets the isSuppressDropDownArrow for DataValidation set isSuppressDropDownArrow(bool value) { if (isSuppressDropDownArrow != value) { @@ -355,14 +318,12 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the isSuppressDropDownArrow for DataValidation bool get isSuppressDropDownArrow { return _mdataValidation.isSuppressDropDownArrow; } @override - /// gets or sets the dataRange for DataValidation set dataRange(Range value) { _mdataValidation.dataRange = value; @@ -370,21 +331,18 @@ class DataValidationWrapper implements DataValidation { } @override - /// gets or sets the dataRange for DataValidation Range get dataRange { return _mdataValidation.dataRange; } @override - /// gets or sets the listOfValues for DataValidation List get listOfValues { return _mdataValidation.listOfValues; } @override - /// gets or sets the listOfValues for DataValidation set listOfValues(List value) { _mdataValidation.listOfValues = value; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_parser.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_parser.dart index b3f5b6463..0be96f5f6 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_parser.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_parser.dart @@ -41,8 +41,8 @@ class FormatParser { /// Regular expression for checking if specified switch argument present in numberformat. static final RegExp numberFormatRegex = - // ignore: use_raw_strings - RegExp('\\[(DBNUM[1-4]{1}|GB[1-4]{1})\\]'); + // ignore: use_raw_strings + RegExp('\\[(DBNUM[1-4]{1}|GB[1-4]{1})\\]'); /// Parses format string. // ignore: unused_element @@ -51,9 +51,10 @@ class FormatParser { final Error error = ArgumentError('strFormat - string cannot be null'); throw error; } - strFormat = numberFormatRegex.hasMatch(strFormat) - ? strFormat.replaceAll(RegExp(r'strFormat'), '') - : strFormat; + strFormat = + numberFormatRegex.hasMatch(strFormat) + ? strFormat.replaceAll(RegExp(r'strFormat'), '') + : strFormat; final int iFormatLength = strFormat.length; if (iFormatLength == 0) { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section.dart index ed69f7894..94ba21d22 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section.dart @@ -25,7 +25,7 @@ class FormatSection { TokenType.string, TokenType.reservedPlace, TokenType.character, - TokenType.color + TokenType.color, ], ExcelFormatType.unknown, [TokenType.general, TokenType.culture], @@ -106,7 +106,7 @@ class FormatSection { TokenType.fraction, TokenType.culture, ], - ExcelFormatType.dateTime + ExcelFormatType.dateTime, ]; /// Break tokens when locating hour token. @@ -314,8 +314,15 @@ class FormatSection { bAddNegative &= dFractionValue > 0; } String strResult; - strResult = _applyFormatNumber(value, bShowReservedSymbols, 0, _iIntegerEnd, - false, _bGroupDigits, bAddNegative); + strResult = _applyFormatNumber( + value, + bShowReservedSymbols, + 0, + _iIntegerEnd, + false, + _bGroupDigits, + bAddNegative, + ); strResult = Worksheet.convertSecondsMinutesToHours(strResult, value); @@ -338,13 +345,14 @@ class FormatSection { /// Applies part of the format tokens to the value. String _applyFormatNumber( - double value, - bool bShowReservedSymbols, - int iStartToken, - int iEndToken, - bool bForward, - bool bGroupDigits, - bool bAddNegativeSign) { + double value, + bool bShowReservedSymbols, + int iStartToken, + int iEndToken, + bool bForward, + bool bGroupDigits, + bool bAddNegativeSign, + ) { final List builder = []; final int iDelta = bForward ? 1 : -1; final int iStart = bForward ? iStartToken : iEndToken; @@ -355,8 +363,12 @@ class FormatSection { for (int i = iStart; _checkCondition(iEnd, bForward, i); i += iDelta) { final FormatTokenBase token = _arrTokens[i]; final double tempValue = originalValue; - String strTokenResult = - token.applyFormat(tempValue, bShowReservedSymbols, culture, this); + String strTokenResult = token.applyFormat( + tempValue, + bShowReservedSymbols, + culture, + this, + ); //If the Month token length is 5 , Ms Excel consider as 1. if (token is MonthToken && @@ -456,11 +468,16 @@ class FormatSection { throw error; } - final bool bMinute = (_findTimeToken(iTokenIndex - 1, _defultBreakHour, - false, [TokenType.hour, TokenType.hour24]) != + final bool bMinute = + (_findTimeToken(iTokenIndex - 1, _defultBreakHour, false, [ + TokenType.hour, + TokenType.hour24, + ]) != -1) || - (_findTimeToken(iTokenIndex + 1, _defultBreakSecond, true, - [TokenType.second, TokenType.secondTotal]) != + (_findTimeToken(iTokenIndex + 1, _defultBreakSecond, true, [ + TokenType.second, + TokenType.secondTotal, + ]) != -1); if (!bMinute) { @@ -471,8 +488,12 @@ class FormatSection { } /// Searches for required time token. - int _findTimeToken(int iTokenIndex, List arrBreakTypes, - bool bForward, List arrTypes) { + int _findTimeToken( + int iTokenIndex, + List arrBreakTypes, + bool bForward, + List arrTypes, + ) { final int iCount = _count; final int iDelta = bForward ? 1 : -1; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section_collection.dart index 0e1e11e78..798c8cfc1 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_section_collection.dart @@ -7,8 +7,10 @@ import 'format_section.dart'; /// Class used for Section Collection. class FormatSectionCollection { /// Initializes a new instance of the FormatSectionCollection class. - FormatSectionCollection(Workbook workbook, - [List? arrTokens]) { + FormatSectionCollection( + Workbook workbook, [ + List? arrTokens, + ]) { _workbook = workbook; innerList = []; if (arrTokens != null) { @@ -123,7 +125,8 @@ class FormatSectionCollection { FormatSection? _getZeroSection() { if (_bConditionalFormat) { throw Exception( - 'This method is not supported for number formats with conditions.'); + 'This method is not supported for number formats with conditions.', + ); } final int iSectionsCount = innerList.length; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/am_pm_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/am_pm_token.dart index d5940242a..2250e5fc5 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/am_pm_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/am_pm_token.dart @@ -29,7 +29,8 @@ class AmPmToken extends FormatTokenBase { if (iIndex < 0 || iIndex > iFormatLength - 1) { final Error error = ArgumentError( - 'iIndex - Value cannot be less than 0 and greater than than format length - 1.'); + 'iIndex - Value cannot be less than 0 and greater than than format length - 1.', + ); throw error; } return tryParseRegex(_aMPMRegex, strFormat, iIndex); @@ -38,8 +39,12 @@ class AmPmToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); final int iHour = date.hour; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/character_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/character_token.dart index 2f039e646..7f9bbebd7 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/character_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/character_token.dart @@ -17,8 +17,9 @@ class CharacterToken extends FormatTokenBase { final int iFormatLength = stringFormat.length; if (iFormatLength == 0) { - final Error error = - ArgumentError('stringFormat - string cannot be empty.'); + final Error error = ArgumentError( + 'stringFormat - string cannot be empty.', + ); throw error; } @@ -47,8 +48,12 @@ class CharacterToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { return strFormat; } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/day_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/day_token.dart index dafb6b629..4c5493d1b 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/day_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/day_token.dart @@ -16,7 +16,6 @@ class DayToken extends FormatTokenBase { String _strFormatLower = ''; @override - /// Tries to parse format string. int tryParse(String stringFormat, int iIndex) { final int iResult = tryParseRegex(_dayRegex, stringFormat, iIndex); @@ -30,8 +29,12 @@ class DayToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { double tempValue = value; if (_strFormatLower.length > 2 && @@ -45,7 +48,6 @@ class DayToken extends FormatTokenBase { } @override - /// Applies format to the value. // ignore: unused_element String applyFormatString(String value, bool bShowHiddenSymbols) { @@ -53,7 +55,6 @@ class DayToken extends FormatTokenBase { } @override - /// Gets type of the token. Read-only. TokenType get tokenType { return TokenType.day; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/decimal_point_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/decimal_point_token.dart index 09753dae3..58f3ab91c 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/decimal_point_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/decimal_point_token.dart @@ -10,8 +10,12 @@ class DecimalPointToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { return strFormat; } @@ -21,14 +25,16 @@ class DecimalPointToken extends FormatTokenBase { final int iFormatLength = stringFormat.length; if (iFormatLength == 0) { - final Error error = - ArgumentError('stringFormat - string cannot be empty'); + final Error error = ArgumentError( + 'stringFormat - string cannot be empty', + ); throw error; } if (iIndex < 0 || iIndex > iFormatLength - 1) { final Error error = ArgumentError( - 'iIndex - Value cannot be less than 0 and greater than than format length - 1.'); + 'iIndex - Value cannot be less than 0 and greater than than format length - 1.', + ); throw error; } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/format_token_base.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/format_token_base.dart index 6369dbefc..3b81d67ed 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/format_token_base.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/format_token_base.dart @@ -14,14 +14,16 @@ abstract class FormatTokenBase { int tryParseRegex(RegExp regex, String stringFormat, int iIndex) { final int iFormatLength = stringFormat.length; if (iFormatLength == 0) { - final Error error = - ArgumentError('stringFormat - string cannot be empty'); + final Error error = ArgumentError( + 'stringFormat - string cannot be empty', + ); throw error; } if (iIndex < 0 || iIndex > iFormatLength) { final Error error = ArgumentError( - 'iIndex - Value cannot be less than 0 or greater than Format Length'); + 'iIndex - Value cannot be less than 0 or greater than Format Length', + ); throw error; } final Match? m = regex.matchAsPrefix(stringFormat, iIndex); @@ -37,8 +39,12 @@ abstract class FormatTokenBase { } /// Applies format to the value. - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section); + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ); /// Applies format to the value. // ignore: unused_element @@ -64,7 +70,11 @@ abstract class FormatTokenBase { /// Searches for string from strings array in the format starting from the specified position. // ignore: unused_element int _findString( - List arrStrings, String strFormat, int iIndex, bool bIgnoreCase) { + List arrStrings, + String strFormat, + int iIndex, + bool bIgnoreCase, + ) { final int iFormatLength = strFormat.length; if (iFormatLength == 0) { @@ -74,7 +84,8 @@ abstract class FormatTokenBase { if (iIndex < 0 || iIndex > iFormatLength - 1) { final Error error = ArgumentError( - 'iIndex - Value cannot be less than 0 and greater than than format length - 1.'); + 'iIndex - Value cannot be less than 0 and greater than than format length - 1.', + ); throw error; } return -1; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/fraction_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/fraction_token.dart index 12f808685..1221bbc2e 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/fraction_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/fraction_token.dart @@ -11,8 +11,12 @@ class FractionToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { return (section.formatType == ExcelFormatType.dateTime) ? culture.dateTimeFormat.dateSeparator : strFormat; @@ -30,7 +34,8 @@ class FractionToken extends FormatTokenBase { if (iIndex < 0 || iIndex > iFormatLength - 1) { final Error error = ArgumentError( - 'iIndex - Value cannot be less than 0 and greater than than format length - 1.'); + 'iIndex - Value cannot be less than 0 and greater than than format length - 1.', + ); throw error; } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_24_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_24_token.dart index fabc3ade1..8bf4fb14d 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_24_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_24_token.dart @@ -18,8 +18,12 @@ class Hour24Token extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { double temp = value; if (temp <= 60) { temp = temp - 1; @@ -27,11 +31,12 @@ class Hour24Token extends FormatTokenBase { final DateTime date = Range.fromOADate(value); double dHour; dHour = temp * FormatConstants.hoursInDay; - dHour = (value > 0) - ? (dHour % 24).ceilToDouble() == date.hour - ? dHour.ceilToDouble() - : dHour.floorToDouble() - : dHour.ceilToDouble(); + dHour = + (value > 0) + ? (dHour % 24).ceilToDouble() == date.hour + ? dHour.ceilToDouble() + : dHour.floorToDouble() + : dHour.ceilToDouble(); if (dHour < 24) { dHour = date.hour.toDouble(); } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_token.dart index 45cbfb294..9ff3248a9 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/hour_token.dart @@ -33,8 +33,12 @@ class HourToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); int iHour = date.hour; if (isAmPm) { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/milli_second_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/milli_second_token.dart index 953d9491d..39f0c27a6 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/milli_second_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/milli_second_token.dart @@ -25,8 +25,12 @@ class MilliSecondToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); int iMilliSecond = date.millisecond; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/minute_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/minute_token.dart index efcf3f708..c2a4feb8c 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/minute_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/minute_token.dart @@ -18,8 +18,12 @@ class MinuteToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); int iMinute = date.minute; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/month_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/month_token.dart index 63723bd0b..989f7c0cd 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/month_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/month_token.dart @@ -23,8 +23,12 @@ class MonthToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); final DateFormat formatter = DateFormat(strFormat.toUpperCase()); final String formatted = formatter.format(date); diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/second_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/second_token.dart index 58459e4d6..a8cbf6cd5 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/second_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/second_token.dart @@ -28,8 +28,12 @@ class SecondToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); int iSecond = date.second; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/significant_digit_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/significant_digit_token.dart index dd3cbc339..ca9f265ec 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/significant_digit_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/significant_digit_token.dart @@ -13,8 +13,12 @@ class SignificantDigitToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { return strFormat; } @@ -33,14 +37,16 @@ class SignificantDigitToken extends FormatTokenBase { final int iFormatLength = stringFormat.length; if (iFormatLength == 0) { - final Error error = - ArgumentError('stringFormat - string cannot be empty'); + final Error error = ArgumentError( + 'stringFormat - string cannot be empty', + ); throw error; } if (iIndex < 0 || iIndex > iFormatLength - 1) { final Error error = ArgumentError( - 'iIndex-Value cannot be less than 0 and greater than format length - 1.'); + 'iIndex-Value cannot be less than 0 and greater than format length - 1.', + ); throw error; } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/unknown_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/unknown_token.dart index 6b64a5837..fae58102d 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/unknown_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/unknown_token.dart @@ -13,8 +13,9 @@ class UnknownToken extends FormatTokenBase { final int iFormatLength = stringFormat.length; if (iFormatLength == 0) { - final Error error = - ArgumentError('stringFormat - string cannot be empty'); + final Error error = ArgumentError( + 'stringFormat - string cannot be empty', + ); throw error; } strFormat = stringFormat[iIndex]; @@ -24,8 +25,12 @@ class UnknownToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { if (strFormat == 'g' || strFormat == 'G') { return ''; } else { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/year_token.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/year_token.dart index 3c32a43ba..77ca5aa05 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/year_token.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/format_tokens/year_token.dart @@ -21,8 +21,12 @@ class YearToken extends FormatTokenBase { /// Applies format to the value. @override - String applyFormat(double value, bool bShowHiddenSymbols, CultureInfo culture, - FormatSection section) { + String applyFormat( + double value, + bool bShowHiddenSymbols, + CultureInfo culture, + FormatSection section, + ) { final DateTime date = Range.fromOADate(value); final int iYear = date.year; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/formats_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/formats_collection.dart index c1def9229..df4ae45ba 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/formats_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/formats/formats_collection.dart @@ -91,7 +91,7 @@ class FormatsCollection { '[h]:mm:ss', 'mm:ss.0', '##0.0E+0', - '@' + '@', ]; /// Maximum number formats count in a workbook. 36 Default + 206 Custom formats. @@ -178,9 +178,11 @@ class FormatsCollection { } if (formatString.contains(_default_exponential.toLowerCase())) { formatString = formatString.replaceAll( - _default_exponential.toLowerCase(), _default_exponential); + _default_exponential.toLowerCase(), + _default_exponential, + ); } -// formatString = GetCustomizedString(formatString); + // formatString = GetCustomizedString(formatString); if (_hashFormatStrings.containsKey(formatString)) { final Format format = _hashFormatStrings[formatString]!; return format.index; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/autofit_manager.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/autofit_manager.dart index e2d117e27..130c3b887 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/autofit_manager.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/autofit_manager.dart @@ -6,7 +6,12 @@ import '../../../xlsio.dart'; class AutoFitManager { /// Intializes the AutoFit Manager. AutoFitManager( - int row, int column, int lastRow, int lastColumn, Range rangeImpl) { + int row, + int column, + int lastRow, + int lastColumn, + Range rangeImpl, + ) { _row = row; _column = column; _lastRow = lastRow; @@ -35,7 +40,11 @@ class AutoFitManager { /// Measures the character ranges. int _measureCharacterRanges( - Style style, String strText, int num1, Rectangle rectF) { + Style style, + String strText, + int num1, + Rectangle rectF, + ) { Font? font2; final _FontStyle regular = _FontStyle._regular; double size = 10; @@ -73,11 +82,18 @@ class AutoFitManager { } /// Measures the character ranges. - int _measureCharacterRangesStyle(_StyleWithText styleWithText, int paramNum, - Rectangle rectF, int column) { + int _measureCharacterRangesStyle( + _StyleWithText styleWithText, + int paramNum, + Rectangle rectF, + int column, + ) { int num = 0; final Font font = _createFont( - styleWithText._fontName, styleWithText._size, styleWithText._style!); + styleWithText._fontName, + styleWithText._size, + styleWithText._style!, + ); int defIndentWidthinPixels = 0; const int defaultPixel = 9; @@ -109,7 +125,7 @@ class AutoFitManager { int num3 = (_measureString(text, font, rectF, false).width + 0.05).toInt() + - paramNum; + paramNum; if (defIndentWidthinPixels > 0) { num3 += defIndentWidthinPixels - paramNum; } @@ -157,13 +173,22 @@ class AutoFitManager { } Rectangle _measureString( - String text, Font font, Rectangle rectF, bool isAutoFitRow) { + String text, + Font font, + Rectangle rectF, + bool isAutoFitRow, + ) { return _book.getMeasuredRectangle(text, font, rectF); } /// Sorts the text to fit. - static void _sortTextToFit(List? list, Font fontImpl, String strText, - bool autoFilter, HAlignType alignment) { + static void _sortTextToFit( + List? list, + Font fontImpl, + String strText, + bool autoFilter, + HAlignType alignment, + ) { final _FontStyle regular = _FontStyle._regular; double size = 10; String name = 'Arial'; @@ -234,8 +259,11 @@ class AutoFitManager { int num4 = 0; final bool autofit = migrantRange.isAutoFitText; - final List result = - Range.isMergedCell(migrantRange, false, num4); + final List result = Range.isMergedCell( + migrantRange, + false, + num4, + ); num4 = result[0] as int; final bool isMerged = result[1] as bool; @@ -266,8 +294,10 @@ class AutoFitManager { } final HAlignType horizontalAlignment = style.hAlign; if (horizontalAlignment == HAlignType.center) { - final Range cellRange = - _rangeImpl.worksheet.getRangeByIndex(row, column++); + final Range cellRange = _rangeImpl.worksheet.getRangeByIndex( + row, + column++, + ); if (column != cellRange.column + 1) { continue; } @@ -275,17 +305,23 @@ class AutoFitManager { _sortTextToFit(arrList, fontImpl, text, false, horizontalAlignment); } else if (hasWrapText) { final int columnWidth = _worksheet.getColumnWidthInPixels(column); - final double textHeight = - calculateWrappedCell(style, text, columnWidth); + final double textHeight = calculateWrappedCell( + style, + text, + columnWidth, + ); final double fitRowHeight = _book.convertFromPixel(textHeight, 6); final double rowHeight = migrantRange.rowHeight; List words; final List wordsN = text.split('\n'); - final List wordNSplit = - wordsN[wordsN.length - 1].split(' '); - words = - List.filled(wordsN.length - 1 + wordNSplit.length, ''); + final List wordNSplit = wordsN[wordsN.length - 1].split( + ' ', + ); + words = List.filled( + wordsN.length - 1 + wordNSplit.length, + '', + ); for (int i = 0; i < wordsN.length - 1; i++) { words[i] = '${wordsN[i]}\n'; } @@ -299,14 +335,20 @@ class AutoFitManager { for (int index = 0; index < words.length; index++) { autoFitText = words[index]; if (autoFitText.isNotEmpty) { - final int length = - _measureCharacterRanges(style, autoFitText, num1, ef); + final int length = _measureCharacterRanges( + style, + autoFitText, + num1, + ef, + ); final CellType cellType = migrantRange.type; final bool isNumberCellType = cellType == CellType.number; if (length < columnWidth || isNumberCellType) { - for (int temp = index + 1; - temp < words.length || temp == 1; - temp++) { + for ( + int temp = index + 1; + temp < words.length || temp == 1; + temp++ + ) { index = temp; if (words.length != 1) { if (!autoFitText.endsWith('\n')) { @@ -315,8 +357,12 @@ class AutoFitManager { index--; } } - final int currentLength = - _measureCharacterRanges(style, autoFitText, num1, ef); + final int currentLength = _measureCharacterRanges( + style, + autoFitText, + num1, + ef, + ); if (wordsN.length == 1 && (currentLength > biggestLength) && rowHeight >= _worksheet.standardHeight && @@ -368,8 +414,12 @@ class AutoFitManager { int num8 = 0; for (int k = 0; k < list3.length; k++) { final _StyleWithText styleWithText = list3[k] as _StyleWithText; - final int num10 = - _measureCharacterRangesStyle(styleWithText, num1, ef, key); + final int num10 = _measureCharacterRangesStyle( + styleWithText, + num1, + ef, + key, + ); if (num8 < num10) { num8 = num10; } @@ -390,7 +440,10 @@ class AutoFitManager { } double calculateWrappedCell( - Style format, String stringValue, int columnWidth) { + Style format, + String stringValue, + int columnWidth, + ) { final Font font = Font(); font.name = format.fontName; font.size = format.fontSize; @@ -401,18 +454,25 @@ class AutoFitManager { if (stringValue.isEmpty) { return 0; } else { - final double calculatedValue = (stringValue.length / 406) * (font.size) + + final double calculatedValue = + (stringValue.length / 406) * (font.size) + (2 * ((font.bold || font.italic) ? 1 : 0)); - num9 = (calculatedValue < columnWidth) - ? columnWidth.toDouble() - : calculatedValue; + num9 = + (calculatedValue < columnWidth) + ? columnWidth.toDouble() + : calculatedValue; num6 = _measureCell(format, stringValue, num9, number, true); return num6; } } - double _measureCell(Style format, String stringValue, double columnWidth, - int number, bool isString) { + double _measureCell( + Style format, + String stringValue, + double columnWidth, + int number, + bool isString, + ) { final Font font = Font(); font.name = format.fontName; font.size = format.fontSize; @@ -528,13 +588,19 @@ class AutoFitManager { } double _measureFontSize( - Style extendedFromat, String stringValue, double columnWidth) { + Style extendedFromat, + String stringValue, + double columnWidth, + ) { if (stringValue.isEmpty) { return 0; } final double size = extendedFromat.fontSize; - final Font font = - _createFont(extendedFromat.fontName, size, _FontStyle._regular); + final Font font = _createFont( + extendedFromat.fontName, + size, + _FontStyle._regular, + ); const double num2 = 0; const double num3 = 0; @@ -611,8 +677,14 @@ class _FontStyle { /// Metrics of the font. class FontMetrics { /// Initialize the font Metrics class with the parameters. - FontMetrics(double ascent, double descent, int linegap, double height, - double superscriptfactor, double subscriptfactor) { + FontMetrics( + double ascent, + double descent, + int linegap, + double height, + double superscriptfactor, + double subscriptfactor, + ) { _ascent = ascent; _descent = descent; _lineGap = linegap; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/enums.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/enums.dart index 23c6ff27d..deb33053f 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/enums.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/enums.dart @@ -13,7 +13,7 @@ enum HAlignType { right, /// General horizontal alignment. - general + general, } ///Specifies the vertical alignment options for cell formatting. @@ -25,7 +25,7 @@ enum VAlignType { center, /// Top vertical alignment. - top + top, } /// Specifies the excel cell types. @@ -88,7 +88,7 @@ enum LineStyle { mediumDashDotDot, ///Specifies the slantedDashDot line style for the cell border. - slantDashDot + slantDashDot, } /// Possible format types. @@ -109,7 +109,6 @@ enum ExcelFormatType { dateTime, /// Represents percentage number format. - percentage, /// Represents currency number format. @@ -279,14 +278,13 @@ enum HyperlinkType { url, /// Represents the File hyperlink type. - file, /// Represents the Unc hyperlink type. unc, /// Represents the Workbook hyperlink type. - workbook + workbook, } /// Represents a possible insert options in Excel. @@ -503,7 +501,7 @@ enum ExcelCFTopBottomType { top, /// Bottom. - bottom + bottom, } /// Specifies whether the AboveBelowAverage conditional formatting rule looks for cell values above or below the average. @@ -524,7 +522,7 @@ enum ExcelCFAverageType { aboveStdDev, /// Below standard deviation - belowStdDev + belowStdDev, } /// Specifies the types of condition values. @@ -551,7 +549,7 @@ enum ConditionValueType { formula, /// Automatic is used - automatic + automatic, } /// Specifies the type of conditions that can be used for Icon sets @@ -560,7 +558,7 @@ enum ConditionalFormatOperator { greaterThan, /// Greater Than or Equal to condition is used [>=]. - greaterThanorEqualTo + greaterThanorEqualTo, } /// Specifies the type of icon set. @@ -623,7 +621,7 @@ enum ExcelIconSetType { threeTriangles, /// 5 Boxes. - fiveBoxes + fiveBoxes, } /// Defines the directions of data bar in conditional formatting. @@ -635,7 +633,7 @@ enum DataBarDirection { leftToRight, /// Represents Right to Left (RTL) direction. - rightToLeft + rightToLeft, } /// Specifies the axis position for a range of cells with conditional formatting as data bars. @@ -647,7 +645,7 @@ enum DataBarAxisPosition { automatic, /// Defines the axis position at the mid point. - middle + middle, } ///Represents a function used for total calculation. @@ -893,7 +891,7 @@ enum ExcelDataValidationType { textLength, /// Represents Formula data type. - formula + formula, } /// Specifies comparison operators for data validation. @@ -920,7 +918,7 @@ enum ExcelDataValidationComparisonOperator { greaterOrEqual, /// Less than or equal to. - lessOrEqual + lessOrEqual, } /// Represents possible error style values. @@ -932,7 +930,7 @@ enum ExcelDataValidationErrorStyle { warning, /// Information icon is displayed. - information + information, } ///Represents filtertype of AutoFilter @@ -953,7 +951,7 @@ enum ExcelFilterType { colorFilter, ///Represents applying Icon Filter for the icons from Conditional Formatting. - iconFilter + iconFilter, } ///Represents filter data type @@ -978,7 +976,7 @@ enum ExcelFilterDataType { matchAllBlanks, ///Represents the MatchAllNonBlanks filter data type. - matchAllNonBlanks + matchAllNonBlanks, } /// Possible conditions in autofilter. @@ -1168,7 +1166,7 @@ enum ExcelLogicalOperator { or, /// Represents the logical AND operation. - and + and, } ///Represents visible/hidden of worksheets. @@ -1177,7 +1175,7 @@ enum WorksheetVisibility { visible, ///Worksheet is hidden to the user. - hidden + hidden, } ///Enumeration of page order for sheet in Excel. @@ -1186,7 +1184,7 @@ enum ExcelPageOrder { downThenOver, ///Represents Over, then down setting. - overThenDown + overThenDown, } ///Enumeration of page orientation types in Excel. @@ -1195,7 +1193,7 @@ enum ExcelPageOrientation { landscape, ///Represents portrait orientation. - portrait + portrait, } ///Enumeration of paper size types in Excel. @@ -1399,7 +1397,7 @@ enum ExcelPaperSize { a3TransversePaper, /// Represents A3 extra transverse paper (322 mm by 445 mm). - a3ExtraTransversePaper + a3ExtraTransversePaper, } ///Enumeration of Replace Error Values when printing in Excel. @@ -1414,7 +1412,7 @@ enum CellErrorPrintOptions { displayed, ///Prints cell errors as #N/A - notAvailable + notAvailable, } /// Possible values for active pane. @@ -1440,5 +1438,5 @@ enum ActivePane { /// This value is also used when only a vertical split has been applied, /// dividing the pane into right and left regions. In that case, this /// value specifies the right pane. - topRight + topRight, } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/serialize_workbook.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/serialize_workbook.dart index c0097023c..14ea474aa 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/serialize_workbook.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/serialize_workbook.dart @@ -76,7 +76,7 @@ class SerializeWorkbook { 'percentile', 'formula', 'autoMin', - 'autoMax' + 'autoMax', ]; /// Names used in xml as IconSet type (order is important). @@ -100,7 +100,7 @@ class SerializeWorkbook { '5Quarters', '3Stars', '3Triangles', - '5Boxes' + '5Boxes', ]; /// Serialize workbook @@ -124,8 +124,9 @@ class SerializeWorkbook { await _saveSharedStringAsync().then((_) async { await _saveStylesAsync().then((_) async { await _saveAppAsync(_workbook.builtInProperties).then((_) async { - await _saveCoreAsync(_workbook.builtInProperties) - .then((_) async { + await _saveCoreAsync(_workbook.builtInProperties).then(( + _, + ) async { await _saveContentTypeAsync().then((_) async { await _saveTopLevelRelationAsync().then((_) async { await _saveWorkbookRelationAsync(); @@ -145,69 +146,98 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('workbook', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - - builder.element('workbookPr', nest: () { - builder.attribute('codeName', 'ThisWorkbook'); - builder.attribute('defaultThemeVersion', '153222'); - }); - _serializeWorkbookProtection(builder); - builder.element('bookViews', nest: () { - builder.element('workbookView', nest: () { - int firstsheet = 0; - if (_workbook.worksheets[0].visibility == - WorksheetVisibility.hidden) { - for (int i = 1; i < _workbook.worksheets.count; i++) { - if (_workbook.worksheets[i].visibility == - WorksheetVisibility.visible) { - firstsheet = i; - break; - } - } - } - builder.attribute('activeTab', firstsheet.toString()); - }); - }); - builder.element('sheets', nest: () { - for (int i = 0; i < _workbook.worksheets.count; i++) { - builder.element('sheet', nest: () { - builder.attribute('name', _workbook.worksheets[i].name); - builder.attribute( - 'sheetId', _workbook.worksheets[i].index.toString()); - if (_workbook.worksheets[i].visibility == - WorksheetVisibility.hidden) { - builder.attribute('state', 'hidden'); + builder.element( + 'workbook', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + + builder.element( + 'workbookPr', + nest: () { + builder.attribute('codeName', 'ThisWorkbook'); + builder.attribute('defaultThemeVersion', '153222'); + }, + ); + _serializeWorkbookProtection(builder); + builder.element( + 'bookViews', + nest: () { + builder.element( + 'workbookView', + nest: () { + int firstsheet = 0; + if (_workbook.worksheets[0].visibility == + WorksheetVisibility.hidden) { + for (int i = 1; i < _workbook.worksheets.count; i++) { + if (_workbook.worksheets[i].visibility == + WorksheetVisibility.visible) { + firstsheet = i; + break; + } + } + } + builder.attribute('activeTab', firstsheet.toString()); + }, + ); + }, + ); + builder.element( + 'sheets', + nest: () { + for (int i = 0; i < _workbook.worksheets.count; i++) { + builder.element( + 'sheet', + nest: () { + builder.attribute('name', _workbook.worksheets[i].name); + builder.attribute( + 'sheetId', + _workbook.worksheets[i].index.toString(), + ); + if (_workbook.worksheets[i].visibility == + WorksheetVisibility.hidden) { + builder.attribute('state', 'hidden'); + } + builder.attribute('r:id', 'rId${i + 1}'); + }, + ); } - builder.attribute('r:id', 'rId${i + 1}'); - }); - } - }); - final List list = _workbook.innerNamesCollection; - if (list.isNotEmpty) { - builder.element('definedNames', nest: () { - for (int i = 0; i < list.length; i++) { - builder.element('definedName', nest: () { - builder.attribute('name', list[i].name); - builder.attribute('comment', list[i].description); - if (list[i].isLocal) { - builder.attribute( - 'localSheetId', - _getLocalSheetIndex(_workbook, list[i]).toString(), + }, + ); + final List list = _workbook.innerNamesCollection; + if (list.isNotEmpty) { + builder.element( + 'definedNames', + nest: () { + for (int i = 0; i < list.length; i++) { + builder.element( + 'definedName', + nest: () { + builder.attribute('name', list[i].name); + builder.attribute('comment', list[i].description); + if (list[i].isLocal) { + builder.attribute( + 'localSheetId', + _getLocalSheetIndex(_workbook, list[i]).toString(), + ); + } + if (!list[i].isVisible) { + builder.attribute('hidden', '1'); + } + builder.text(list[i].value); + }, ); } - if (!list[i].isVisible) { - builder.attribute('hidden', '1'); - } - builder.text(list[i].value); - }); - } - }); - } - }); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/workbook.xml'); @@ -217,69 +247,98 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('workbook', nest: () async { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - - builder.element('workbookPr', nest: () async { - builder.attribute('codeName', 'ThisWorkbook'); - builder.attribute('defaultThemeVersion', '153222'); - }); - _serializeWorkbookProtectionAsync(builder); - builder.element('bookViews', nest: () async { - builder.element('workbookView', nest: () async { - int firstsheet = 0; - if (_workbook.worksheets[0].visibility == - WorksheetVisibility.hidden) { - for (int i = 1; i < _workbook.worksheets.count; i++) { - if (_workbook.worksheets[i].visibility == - WorksheetVisibility.visible) { - firstsheet = i; - break; - } - } - } - builder.attribute('activeTab', firstsheet.toString()); - }); - }); - builder.element('sheets', nest: () async { - for (int i = 0; i < _workbook.worksheets.count; i++) { - builder.element('sheet', nest: () async { - builder.attribute('name', _workbook.worksheets[i].name); - builder.attribute( - 'sheetId', _workbook.worksheets[i].index.toString()); - if (_workbook.worksheets[i].visibility == - WorksheetVisibility.hidden) { - builder.attribute('state', 'hidden'); + builder.element( + 'workbook', + nest: () async { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + + builder.element( + 'workbookPr', + nest: () async { + builder.attribute('codeName', 'ThisWorkbook'); + builder.attribute('defaultThemeVersion', '153222'); + }, + ); + _serializeWorkbookProtectionAsync(builder); + builder.element( + 'bookViews', + nest: () async { + builder.element( + 'workbookView', + nest: () async { + int firstsheet = 0; + if (_workbook.worksheets[0].visibility == + WorksheetVisibility.hidden) { + for (int i = 1; i < _workbook.worksheets.count; i++) { + if (_workbook.worksheets[i].visibility == + WorksheetVisibility.visible) { + firstsheet = i; + break; + } + } + } + builder.attribute('activeTab', firstsheet.toString()); + }, + ); + }, + ); + builder.element( + 'sheets', + nest: () async { + for (int i = 0; i < _workbook.worksheets.count; i++) { + builder.element( + 'sheet', + nest: () async { + builder.attribute('name', _workbook.worksheets[i].name); + builder.attribute( + 'sheetId', + _workbook.worksheets[i].index.toString(), + ); + if (_workbook.worksheets[i].visibility == + WorksheetVisibility.hidden) { + builder.attribute('state', 'hidden'); + } + builder.attribute('r:id', 'rId${i + 1}'); + }, + ); } - builder.attribute('r:id', 'rId${i + 1}'); - }); - } - }); - final List list = _workbook.innerNamesCollection; - if (list.isNotEmpty) { - builder.element('definedNames', nest: () async { - for (int i = 0; i < list.length; i++) { - builder.element('definedName', nest: () async { - builder.attribute('name', list[i].name); - builder.attribute('comment', list[i].description); - if (list[i].isLocal) { - builder.attribute( - 'localSheetId', - _getLocalSheetIndexAsync(_workbook, list[i]).toString(), + }, + ); + final List list = _workbook.innerNamesCollection; + if (list.isNotEmpty) { + builder.element( + 'definedNames', + nest: () async { + for (int i = 0; i < list.length; i++) { + builder.element( + 'definedName', + nest: () async { + builder.attribute('name', list[i].name); + builder.attribute('comment', list[i].description); + if (list[i].isLocal) { + builder.attribute( + 'localSheetId', + _getLocalSheetIndexAsync(_workbook, list[i]).toString(), + ); + } + if (!list[i].isVisible) { + builder.attribute('hidden', '1'); + } + builder.text(list[i].value); + }, ); } - if (!list[i].isVisible) { - builder.attribute('hidden', '1'); - } - builder.text(list[i].value); - }); - } - }); - } - }); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'xl/workbook.xml'); @@ -309,41 +368,73 @@ class SerializeWorkbook { /// Serializes workbook protection options. void _serializeWorkbookProtection(XmlBuilder builder) { if (_workbook.isWindowProtect || _workbook.isCellProtect) { - builder.element('workbookProtection', nest: () { - if (_workbook.password != null) { - final int usPassword = _workbook.isPassword; - if (usPassword != 0) { - builder.attribute('workbookPassword', usPassword.toRadixString(16)); + builder.element( + 'workbookProtection', + nest: () { + if (_workbook.password != null) { + final int usPassword = _workbook.isPassword; + if (usPassword != 0) { + builder.attribute( + 'workbookPassword', + usPassword.toRadixString(16), + ); + } } - } - _serializeAttributes( - builder, 'lockStructure', _workbook.isCellProtect, false); - _serializeAttributes( - builder, 'lockWindows', _workbook.isWindowProtect, false); - }); + _serializeAttributes( + builder, + 'lockStructure', + _workbook.isCellProtect, + false, + ); + _serializeAttributes( + builder, + 'lockWindows', + _workbook.isWindowProtect, + false, + ); + }, + ); } } Future _serializeWorkbookProtectionAsync(XmlBuilder builder) async { if (_workbook.isWindowProtect || _workbook.isCellProtect) { - builder.element('workbookProtection', nest: () async { - if (_workbook.password != null) { - final int usPassword = _workbook.isPassword; - if (usPassword != 0) { - builder.attribute('workbookPassword', usPassword.toRadixString(16)); + builder.element( + 'workbookProtection', + nest: () async { + if (_workbook.password != null) { + final int usPassword = _workbook.isPassword; + if (usPassword != 0) { + builder.attribute( + 'workbookPassword', + usPassword.toRadixString(16), + ); + } } - } - _serializeAttributesAsync( - builder, 'lockStructure', _workbook.isCellProtect, false); - _serializeAttributesAsync( - builder, 'lockWindows', _workbook.isWindowProtect, false); - }); + _serializeAttributesAsync( + builder, + 'lockStructure', + _workbook.isCellProtect, + false, + ); + _serializeAttributesAsync( + builder, + 'lockWindows', + _workbook.isWindowProtect, + false, + ); + }, + ); } } /// serialize Attributes void _serializeAttributes( - XmlBuilder builder, String attributeName, bool value, bool defaultValue) { + XmlBuilder builder, + String attributeName, + bool value, + bool defaultValue, + ) { String? strValue; if (value != defaultValue) { strValue = value ? '1' : '0'; @@ -353,8 +444,12 @@ class SerializeWorkbook { } } - Future _serializeAttributesAsync(XmlBuilder builder, - String attributeName, bool value, bool defaultValue) async { + Future _serializeAttributesAsync( + XmlBuilder builder, + String attributeName, + bool value, + bool defaultValue, + ) async { String? strValue; if (value != defaultValue) { strValue = value ? '1' : '0'; @@ -366,15 +461,23 @@ class SerializeWorkbook { /// Serializes attribute if it differs from default value. void _serializeAttributeInt( - XmlBuilder builder, String attributeName, int value, int defaultValue) { + XmlBuilder builder, + String attributeName, + int value, + int defaultValue, + ) { if (value != defaultValue) { final String strValue = value.toString(); builder.attribute(attributeName, strValue); } } - Future _serializeAttributeIntAsync(XmlBuilder builder, - String attributeName, int value, int defaultValue) async { + Future _serializeAttributeIntAsync( + XmlBuilder builder, + String attributeName, + int value, + int defaultValue, + ) async { if (value != defaultValue) { final String strValue = value.toString(); builder.attribute(attributeName, strValue); @@ -450,302 +553,388 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('worksheet', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - builder.attribute('xmlns:mc', - 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - - builder.element('sheetPr', nest: () { - if (!sheet.isSummaryRowBelow) { - builder.element('OutlinePr', nest: () { - builder.attribute('summaryBelow', '0'); - }); - } - if (sheet.pageSetup.isFitToPage) { - builder.element('pageSetUpPr', nest: () { - builder.attribute('fitToPage', '1'); - }); - } - if (sheet.isTabColorApplied) { - _serializeTabColor(sheet, builder); - } - }); - _saveSheetView(sheet, builder); - builder.element('sheetFormatPr', nest: () { - builder.attribute('defaultRowHeight', sheet.standardHeight.toString()); - }); - - if (sheet.columns.count != 0) { - builder.element('cols', nest: () { - for (int i = 1; i <= sheet.columns.count; i++) { - final Column? column = sheet.columns[i]; - if (column != null) { - builder.element('col', nest: () { - final int iLastColumn = - _findSameColumns(sheet, column.index, _workbook); - builder.attribute('min', column.index.toString()); - builder.attribute('max', iLastColumn.toString()); - i = iLastColumn; - if (column.width != 0) { - final double dWidth = - sheet.evaluateFileColumnWidth(column.width); - builder.attribute('width', dWidth.toString()); - } else { - builder.attribute('width', '8.43'); - } - if (column.isHidden) { - builder.attribute('hidden', '1'); - } - builder.attribute('customWidth', '1'); - }); + builder.element( + 'worksheet', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + builder.attribute( + 'xmlns:mc', + 'http://schemas.openxmlformats.org/markup-compatibility/2006', + ); + + builder.element( + 'sheetPr', + nest: () { + if (!sheet.isSummaryRowBelow) { + builder.element( + 'OutlinePr', + nest: () { + builder.attribute('summaryBelow', '0'); + }, + ); } - } - }); - } - builder.element('sheetData', nest: () { - if (sheet.rows.count != 0) { - for (final Row? row in sheet.rows.innerList) { - if (row != null) { - builder.element('row', nest: () { - builder.attribute('r', row.index.toString()); - if (row.height != 0) { - builder.attribute('ht', row.height.toString()); - builder.attribute('customHeight', '1'); - } - if (row.isHidden) { - builder.attribute('hidden', '1'); - } - if (row.ranges.count != 0) { - for (final Range? cell in row.ranges.innerList) { - if (cell != null) { - if (cell.rowSpan > 0) { - cell.rowSpan -= 1; + if (sheet.pageSetup.isFitToPage) { + builder.element( + 'pageSetUpPr', + nest: () { + builder.attribute('fitToPage', '1'); + }, + ); + } + if (sheet.isTabColorApplied) { + _serializeTabColor(sheet, builder); + } + }, + ); + _saveSheetView(sheet, builder); + builder.element( + 'sheetFormatPr', + nest: () { + builder.attribute( + 'defaultRowHeight', + sheet.standardHeight.toString(), + ); + }, + ); + + if (sheet.columns.count != 0) { + builder.element( + 'cols', + nest: () { + for (int i = 1; i <= sheet.columns.count; i++) { + final Column? column = sheet.columns[i]; + if (column != null) { + builder.element( + 'col', + nest: () { + final int iLastColumn = _findSameColumns( + sheet, + column.index, + _workbook, + ); + builder.attribute('min', column.index.toString()); + builder.attribute('max', iLastColumn.toString()); + i = iLastColumn; + if (column.width != 0) { + final double dWidth = sheet.evaluateFileColumnWidth( + column.width, + ); + builder.attribute('width', dWidth.toString()); + } else { + builder.attribute('width', '8.43'); } - if (cell.columnSpan > 0) { - cell.columnSpan -= 1; + if (column.isHidden) { + builder.attribute('hidden', '1'); } - sheet.mergeCells = - _processMergeCells(cell, row.index, sheet.mergeCells); - if (cell.hasCellStyle || !cell.isDefaultFormat) { - cell.styleIndex = cell.cellStyle.index = - _processCellStyle( - cell.cellStyle as CellStyle, _workbook); - } else { - cell.styleIndex = -1; + builder.attribute('customWidth', '1'); + }, + ); + } + } + }, + ); + } + builder.element( + 'sheetData', + nest: () { + if (sheet.rows.count != 0) { + for (final Row? row in sheet.rows.innerList) { + if (row != null) { + builder.element( + 'row', + nest: () { + builder.attribute('r', row.index.toString()); + if (row.height != 0) { + builder.attribute('ht', row.height.toString()); + builder.attribute('customHeight', '1'); } - builder.element('c', nest: () { - String? strFormula = cell.formula; - builder.attribute('r', cell.addressLocal); - if (cell.saveType != '' && - (strFormula == null || - strFormula == '' || - strFormula[0] != '=' || - cell.saveType == 's')) { - builder.attribute('t', cell.saveType); - } - if (cell.styleIndex > 0) { - builder.attribute('s', cell.styleIndex.toString()); - } - String? cellValue; - if (sheet.calcEngine != null && - cell.number == null && - cell.text == null && - cell.boolean == '' && - cell.errorValue == '') { - cellValue = cell.calculatedValue; - } else if (cell.errorValue != '') { - cellValue = cell.errorValue; - } else if (cell.boolean != '') { - cellValue = cell.boolean; - } else if (cell.number != null) { - cellValue = cell.number.toString(); - } else if (cell.text != null) { - if (cell.saveType == 's' && cell.textIndex != -1) { - cellValue = cell.textIndex.toString(); - } else { - cellValue = cell.text; - } - } - if (strFormula != null && - strFormula != '' && - strFormula[0] == '=' && - cell.saveType != 's') { - if (cell.saveType != '') { - builder.attribute('t', cell.saveType); - } - strFormula = - strFormula.substring(1).replaceAll("'", '"'); - final int i = strFormula.indexOf('!'); - int indexOfOp = (strFormula.contains('+')) - ? strFormula.indexOf('+') - : strFormula.indexOf('-'); - indexOfOp = (indexOfOp == -1) - ? strFormula.indexOf('*') - : indexOfOp; - indexOfOp = (indexOfOp == -1) - ? strFormula.indexOf('/') - : indexOfOp; - - if (i != -1 && - indexOfOp != -1 && - strFormula[i - 1] == '"' && - strFormula[indexOfOp + 1] == '"') { - final String cellRef = - strFormula.substring(0, indexOfOp); - final String operatorString = - strFormula.substring(indexOfOp, indexOfOp + 1); - final String sheetName = - strFormula.substring(indexOfOp + 2, i - 1); - strFormula = - "$cellRef$operatorString'$sheetName'${strFormula.substring(i)}"; - } - if (i != -1 && - strFormula[0] == '"' && - strFormula[i - 1] == '"') { - final String sheetName = - strFormula.substring(1, i - 1); - strFormula = - "'$sheetName'${strFormula.substring(i)}"; - } - if (strFormula.contains('MINIFS')) { - strFormula = strFormula.replaceAllMapped( - RegExp('MINIFS'), - (Match match) => '_xlfn.${match.group(0)}'); - } else if (strFormula.contains('MAXIFS')) { - strFormula = strFormula.replaceAllMapped( - RegExp('MAXIFS'), - (Match match) => '_xlfn.${match.group(0)}'); + if (row.isHidden) { + builder.attribute('hidden', '1'); + } + if (row.ranges.count != 0) { + for (final Range? cell in row.ranges.innerList) { + if (cell != null) { + if (cell.rowSpan > 0) { + cell.rowSpan -= 1; + } + if (cell.columnSpan > 0) { + cell.columnSpan -= 1; + } + sheet.mergeCells = _processMergeCells( + cell, + row.index, + sheet.mergeCells, + ); + if (cell.hasCellStyle || !cell.isDefaultFormat) { + cell.styleIndex = + cell.cellStyle.index = _processCellStyle( + cell.cellStyle as CellStyle, + _workbook, + ); + } else { + cell.styleIndex = -1; + } + builder.element( + 'c', + nest: () { + String? strFormula = cell.formula; + builder.attribute('r', cell.addressLocal); + if (cell.saveType != '' && + (strFormula == null || + strFormula == '' || + strFormula[0] != '=' || + cell.saveType == 's')) { + builder.attribute('t', cell.saveType); + } + if (cell.styleIndex > 0) { + builder.attribute( + 's', + cell.styleIndex.toString(), + ); + } + String? cellValue; + if (sheet.calcEngine != null && + cell.number == null && + cell.text == null && + cell.boolean == '' && + cell.errorValue == '') { + cellValue = cell.calculatedValue; + } else if (cell.errorValue != '') { + cellValue = cell.errorValue; + } else if (cell.boolean != '') { + cellValue = cell.boolean; + } else if (cell.number != null) { + cellValue = cell.number.toString(); + } else if (cell.text != null) { + if (cell.saveType == 's' && + cell.textIndex != -1) { + cellValue = cell.textIndex.toString(); + } else { + cellValue = cell.text; + } + } + if (strFormula != null && + strFormula != '' && + strFormula[0] == '=' && + cell.saveType != 's') { + if (cell.saveType != '') { + builder.attribute('t', cell.saveType); + } + final int i = strFormula.indexOf('!'); + int indexOfOp = + (strFormula.contains('+')) + ? strFormula.indexOf('+') + : strFormula.indexOf('-'); + indexOfOp = + (indexOfOp == -1) + ? strFormula.indexOf('*') + : indexOfOp; + indexOfOp = + (indexOfOp == -1) + ? strFormula.indexOf('/') + : indexOfOp; + + if (i != -1 && + indexOfOp != -1 && + strFormula[i - 1] == '"' && + strFormula[indexOfOp + 1] == '"') { + final String cellRef = strFormula.substring( + 0, + indexOfOp, + ); + final String operatorString = strFormula + .substring(indexOfOp, indexOfOp + 1); + final String sheetName = strFormula + .substring(indexOfOp + 2, i - 1); + strFormula = + "$cellRef$operatorString'$sheetName'${strFormula.substring(i)}"; + } + if (i != -1 && + strFormula[0] == '"' && + strFormula[i - 1] == '"') { + final String sheetName = strFormula + .substring(1, i - 1); + strFormula = + "'$sheetName'${strFormula.substring(i)}"; + } + if (strFormula.contains('MINIFS')) { + strFormula = strFormula.replaceAllMapped( + RegExp('MINIFS'), + (Match match) => + '_xlfn.${match.group(0)}', + ); + } else if (strFormula.contains('MAXIFS')) { + strFormula = strFormula.replaceAllMapped( + RegExp('MAXIFS'), + (Match match) => + '_xlfn.${match.group(0)}', + ); + } + builder.element('f', nest: strFormula); + } + if (cellValue != null && + (cell.saveType == 'str' || + cellValue.isNotEmpty)) { + builder.element('v', nest: cellValue); + } + }, + ); } - builder.element('f', nest: strFormula); - } - if (cellValue != null && - (cell.saveType == 'str' || cellValue.isNotEmpty)) { - builder.element('v', nest: cellValue); } - }); - } - } + } + }, + ); } - }); + } } + }, + ); + if (sheet.isPasswordProtected) { + builder.element( + 'sheetProtection', + nest: () { + if (sheet.algorithmName != null) { + // ignore: unnecessary_null_checks + builder.attribute('algorithmName', sheet.algorithmName!); + builder.attribute('hashValue', base64.encode(sheet.hashValue)); + builder.attribute('saltValue', base64.encode(sheet.saltValue)); + builder.attribute('spinCount', sheet.spinCount); + } else if (sheet.isPassword != 1) { + final String password = sheet.isPassword.toRadixString(16); + builder.attribute('password', password); + } + List attributes; + List flags; + List defaultValues; + attributes = sheet.protectionAttributes; + flags = sheet.flag; + defaultValues = sheet.defaultValues; + // ignore: prefer_final_locals + for (int i = 0, iCount = attributes.length; i < iCount; i++) { + _serializeProtectionAttribute( + builder, + attributes[i], + flags[i], + defaultValues[i], + ); + } + }, + ); + } + //Serializing AutoFilter + _serializeAutoFilters(builder, sheet.autoFilters); + + if (sheet.mergeCells.innerList.isNotEmpty) { + builder.element( + 'mergeCells', + nest: () { + builder.attribute( + 'count', + sheet.mergeCells.innerList.length.toString(), + ); + for (final MergeCell mCell in sheet.mergeCells.innerList) { + builder.element( + 'mergeCell', + nest: () { + builder.attribute('ref', mCell.reference); + }, + ); + } + }, + ); + } + _serializeConditionalFormatting(builder, sheet); + _serializeDataValidations(builder, sheet); + _serializeHyperlinks(builder, sheet); + if (sheet.pageSetup.showGridlines || + sheet.pageSetup.showHeadings || + sheet.pageSetup.isCenterHorizontally || + sheet.pageSetup.isCenterVertically) { + _serializePrintOptions(builder, sheet); + } + _validatePageMargins(sheet); + _serializePageMargins(builder, sheet); + + if (sheet.pageSetup.order == ExcelPageOrder.overThenDown || + sheet.pageSetup.orientation == ExcelPageOrientation.landscape || + sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed || + sheet.pageSetup.isBlackAndWhite || + sheet.pageSetup.isDraft || + (sheet.pageSetup.printQuality != 0 && + sheet.pageSetup.printQuality != 600) || + !sheet.pageSetup.autoFirstPageNumber || + sheet.pageSetup.fitToPagesWide > 1 || + sheet.pageSetup.fitToPagesTall > 1 || + sheet.pageSetup.firstPageNumber != 1 || + sheet.pageSetup.paperSize != ExcelPaperSize.paperA4) { + _serializePageSetup(builder, sheet); + } + builder.element( + 'headerFooter', + nest: () { + builder.attribute('scaleWithDoc', '1'); + builder.attribute('alignWithMargins', '0'); + builder.attribute('differentFirst', '0'); + builder.attribute('differentOddEven', '0'); + }, + ); + + if ((sheet.pictures.count > 0) || + (sheet.charts != null && sheet.chartCount > 0)) { + _workbook.drawingCount++; + _saveDrawings(sheet); + if (sheet.charts != null && sheet.chartCount > 0) { + sheet.charts!.serializeChartsSync(sheet); } - } - }); - if (sheet.isPasswordProtected) { - builder.element('sheetProtection', nest: () { - if (sheet.algorithmName != null) { - // ignore: unnecessary_null_checks - builder.attribute('algorithmName', sheet.algorithmName!); - builder.attribute('hashValue', base64.encode(sheet.hashValue)); - builder.attribute('saltValue', base64.encode(sheet.saltValue)); - builder.attribute('spinCount', sheet.spinCount); - } else if (sheet.isPassword != 1) { - final String password = sheet.isPassword.toRadixString(16); - builder.attribute('password', password); - } - List attributes; - List flags; - List defaultValues; - attributes = sheet.protectionAttributes; - flags = sheet.flag; - defaultValues = sheet.defaultValues; - // ignore: prefer_final_locals - for (int i = 0, iCount = attributes.length; i < iCount; i++) { - _serializeProtectionAttribute( - builder, attributes[i], flags[i], defaultValues[i]); - } - }); - } - //Serializing AutoFilter - _serializeAutoFilters(builder, sheet.autoFilters); - - if (sheet.mergeCells.innerList.isNotEmpty) { - builder.element('mergeCells', nest: () { - builder.attribute( - 'count', sheet.mergeCells.innerList.length.toString()); - for (final MergeCell mCell in sheet.mergeCells.innerList) { - builder.element('mergeCell', nest: () { - builder.attribute('ref', mCell.reference); - }); - } - }); - } - _serializeConditionalFormatting(builder, sheet); - _serializeDataValidations(builder, sheet); - _serializeHyperlinks(builder, sheet); - if (sheet.pageSetup.showGridlines || - sheet.pageSetup.showHeadings || - sheet.pageSetup.isCenterHorizontally || - sheet.pageSetup.isCenterVertically) { - _serializePrintOptions(builder, sheet); - } - _validatePageMargins(sheet); - _serializePageMargins(builder, sheet); - - if (sheet.pageSetup.order == ExcelPageOrder.overThenDown || - sheet.pageSetup.orientation == ExcelPageOrientation.landscape || - sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed || - sheet.pageSetup.isBlackAndWhite || - sheet.pageSetup.isDraft || - (sheet.pageSetup.printQuality != 0 && - sheet.pageSetup.printQuality != 600) || - !sheet.pageSetup.autoFirstPageNumber || - sheet.pageSetup.fitToPagesWide > 1 || - sheet.pageSetup.fitToPagesTall > 1 || - sheet.pageSetup.firstPageNumber != 1 || - sheet.pageSetup.paperSize != ExcelPaperSize.paperA4) { - _serializePageSetup(builder, sheet); - } - builder.element('headerFooter', nest: () { - builder.attribute('scaleWithDoc', '1'); - builder.attribute('alignWithMargins', '0'); - builder.attribute('differentFirst', '0'); - builder.attribute('differentOddEven', '0'); - }); - - if ((sheet.pictures.count > 0) || - (sheet.charts != null && sheet.chartCount > 0)) { - _workbook.drawingCount++; - _saveDrawings(sheet); - if (sheet.charts != null && sheet.chartCount > 0) { - sheet.charts!.serializeChartsSync(sheet); - } - builder.element('drawing', nest: () { - int id = 1; - const String rId = 'rId1'; - if (_relationId.isNotEmpty) { - if (sheet.hyperlinks.count > 0) { - for (int i = 0; i < sheet.hyperlinks.count; i++) { - if (sheet.hyperlinks[i].attachedType == - ExcelHyperlinkAttachedType.range && - sheet.hyperlinks[i].type != HyperlinkType.workbook) { - id++; + builder.element( + 'drawing', + nest: () { + int id = 1; + const String rId = 'rId1'; + if (_relationId.isNotEmpty) { + if (sheet.hyperlinks.count > 0) { + for (int i = 0; i < sheet.hyperlinks.count; i++) { + if (sheet.hyperlinks[i].attachedType == + ExcelHyperlinkAttachedType.range && + sheet.hyperlinks[i].type != HyperlinkType.workbook) { + id++; + } + } } + builder.attribute('r:id', 'rId$id'); + } else { + builder.attribute('r:id', rId); } - } - builder.attribute('r:id', 'rId$id'); - } else { - builder.attribute('r:id', rId); - } - }); - } - - final TableSerialization tableSerialization = - TableSerialization(_workbook); - tableSerialization.serializeTables(builder, sheet); - - builder.element('extLst', nest: () { - _serializeConditionalFormattingExt(builder, sheet); - }); - final List rel = _saveSheetRelations(sheet); - - _addToArchive(rel, 'xl/worksheets/_rels/sheet${index + 1}.xml.rels'); - }); + }, + ); + } + + final TableSerialization tableSerialization = TableSerialization( + _workbook, + ); + tableSerialization.serializeTables(builder, sheet); + + builder.element( + 'extLst', + nest: () { + _serializeConditionalFormattingExt(builder, sheet); + }, + ); + final List rel = _saveSheetRelations(sheet); + + _addToArchive(rel, 'xl/worksheets/_rels/sheet${index + 1}.xml.rels'); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/worksheets/sheet${index + 1}.xml'); @@ -755,275 +944,361 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('worksheet', nest: () async { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - builder.attribute('xmlns:mc', - 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - - builder.element('sheetPr', nest: () async { - if (!sheet.isSummaryRowBelow) { - builder.element('OutlinePr', nest: () async { - builder.attribute('summaryBelow', '0'); - }); - } - if (sheet.pageSetup.isFitToPage) { - builder.element('pageSetUpPr', nest: () async { - builder.attribute('fitToPage', '1'); - }); - } - if (sheet.isTabColorApplied) { - _serializeTabColorAsync(sheet, builder); - } - }); - _saveSheetViewAsync(sheet, builder); - builder.element('sheetFormatPr', nest: () async { - builder.attribute('defaultRowHeight', sheet.standardHeight.toString()); - }); - - if (sheet.columns.count != 0) { - builder.element('cols', nest: () async { - for (int i = 1; i <= sheet.columns.count; i++) { - final Column? column = sheet.columns[i]; - if (column != null) { - builder.element('col', nest: () async { - final int iLastColumn = - _findSameColumns(sheet, column.index, _workbook); - builder.attribute('min', column.index.toString()); - builder.attribute('max', iLastColumn.toString()); - i = iLastColumn; - if (column.width != 0) { - final double dWidth = - sheet.evaluateFileColumnWidth(column.width); - builder.attribute('width', dWidth.toString()); - } else { - builder.attribute('width', '8.43'); - } - if (column.isHidden) { - builder.attribute('hidden', '1'); - } - builder.attribute('customWidth', '1'); - }); + builder.element( + 'worksheet', + nest: () async { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + builder.attribute( + 'xmlns:mc', + 'http://schemas.openxmlformats.org/markup-compatibility/2006', + ); + + builder.element( + 'sheetPr', + nest: () async { + if (!sheet.isSummaryRowBelow) { + builder.element( + 'OutlinePr', + nest: () async { + builder.attribute('summaryBelow', '0'); + }, + ); } - } - }); - } - builder.element('sheetData', nest: () async { - if (sheet.rows.count != 0) { - for (final Row? row in sheet.rows.innerList) { - if (row != null) { - builder.element('row', nest: () async { - builder.attribute('r', row.index.toString()); - if (row.height != 0) { - builder.attribute('ht', row.height.toString()); - builder.attribute('customHeight', '1'); - } - if (row.isHidden) { - builder.attribute('hidden', '1'); - } - if (row.ranges.count != 0) { - for (final Range? cell in row.ranges.innerList) { - if (cell != null) { - if (cell.rowSpan > 0) { - cell.rowSpan -= 1; + if (sheet.pageSetup.isFitToPage) { + builder.element( + 'pageSetUpPr', + nest: () async { + builder.attribute('fitToPage', '1'); + }, + ); + } + if (sheet.isTabColorApplied) { + _serializeTabColorAsync(sheet, builder); + } + }, + ); + _saveSheetViewAsync(sheet, builder); + builder.element( + 'sheetFormatPr', + nest: () async { + builder.attribute( + 'defaultRowHeight', + sheet.standardHeight.toString(), + ); + }, + ); + + if (sheet.columns.count != 0) { + builder.element( + 'cols', + nest: () async { + for (int i = 1; i <= sheet.columns.count; i++) { + final Column? column = sheet.columns[i]; + if (column != null) { + builder.element( + 'col', + nest: () async { + final int iLastColumn = _findSameColumns( + sheet, + column.index, + _workbook, + ); + builder.attribute('min', column.index.toString()); + builder.attribute('max', iLastColumn.toString()); + i = iLastColumn; + if (column.width != 0) { + final double dWidth = sheet.evaluateFileColumnWidth( + column.width, + ); + builder.attribute('width', dWidth.toString()); + } else { + builder.attribute('width', '8.43'); } - if (cell.columnSpan > 0) { - cell.columnSpan -= 1; + if (column.isHidden) { + builder.attribute('hidden', '1'); } - sheet.mergeCells = - _processMergeCells(cell, row.index, sheet.mergeCells); - - if (cell.hasCellStyle || !cell.isDefaultFormat) { - cell.styleIndex = cell.cellStyle.index = - _processCellStyle( - cell.cellStyle as CellStyle, _workbook); - } else { - cell.styleIndex = -1; + builder.attribute('customWidth', '1'); + }, + ); + } + } + }, + ); + } + builder.element( + 'sheetData', + nest: () async { + if (sheet.rows.count != 0) { + for (final Row? row in sheet.rows.innerList) { + if (row != null) { + builder.element( + 'row', + nest: () async { + builder.attribute('r', row.index.toString()); + if (row.height != 0) { + builder.attribute('ht', row.height.toString()); + builder.attribute('customHeight', '1'); } - builder.element('c', nest: () async { - String? strFormula = cell.formula; - builder.attribute('r', cell.addressLocal); - if (cell.saveType != '' && - (strFormula == null || - strFormula == '' || - strFormula[0] != '=' || - cell.saveType == 's')) { - builder.attribute('t', cell.saveType); - } - if (cell.styleIndex > 0) { - builder.attribute('s', cell.styleIndex.toString()); - } - String? cellValue; - if (sheet.calcEngine != null && - cell.number == null && - cell.text == null && - cell.boolean == '' && - cell.errorValue == '') { - cellValue = cell.calculatedValue; - } else if (cell.errorValue != '') { - cellValue = cell.errorValue; - } else if (cell.boolean != '') { - cellValue = cell.boolean; - } else if (cell.number != null) { - cellValue = cell.number.toString(); - } else if (cell.text != null) { - if (cell.saveType == 's' && cell.textIndex != -1) { - cellValue = cell.textIndex.toString(); - } else { - cellValue = cell.text; - } - } - if (strFormula != null && - strFormula != '' && - strFormula[0] == '=' && - cell.saveType != 's') { - if (cell.saveType != '') { - builder.attribute('t', cell.saveType); - } - strFormula = - strFormula.substring(1).replaceAll("'", '"'); - final int i = strFormula.indexOf('!'); - if (i != -1 && - strFormula[0] == '"' && - strFormula[i - 1] == '"') { - final String sheetName = - strFormula.substring(1, i - 1); - strFormula = - "'$sheetName'${strFormula.substring(i)}"; - } - if (strFormula.contains('MINIFS')) { - strFormula = strFormula.replaceAllMapped( - RegExp('MINIFS'), - (Match match) => '_xlfn.${match.group(0)}'); - } else if (strFormula.contains('MAXIFS')) { - strFormula = strFormula.replaceAllMapped( - RegExp('MAXIFS'), - (Match match) => '_xlfn.${match.group(0)}'); + if (row.isHidden) { + builder.attribute('hidden', '1'); + } + if (row.ranges.count != 0) { + for (final Range? cell in row.ranges.innerList) { + if (cell != null) { + if (cell.rowSpan > 0) { + cell.rowSpan -= 1; + } + if (cell.columnSpan > 0) { + cell.columnSpan -= 1; + } + sheet.mergeCells = _processMergeCells( + cell, + row.index, + sheet.mergeCells, + ); + + if (cell.hasCellStyle || !cell.isDefaultFormat) { + cell.styleIndex = + cell.cellStyle.index = _processCellStyle( + cell.cellStyle as CellStyle, + _workbook, + ); + } else { + cell.styleIndex = -1; + } + builder.element( + 'c', + nest: () async { + String? strFormula = cell.formula; + builder.attribute('r', cell.addressLocal); + if (cell.saveType != '' && + (strFormula == null || + strFormula == '' || + strFormula[0] != '=' || + cell.saveType == 's')) { + builder.attribute('t', cell.saveType); + } + if (cell.styleIndex > 0) { + builder.attribute( + 's', + cell.styleIndex.toString(), + ); + } + String? cellValue; + if (sheet.calcEngine != null && + cell.number == null && + cell.text == null && + cell.boolean == '' && + cell.errorValue == '') { + cellValue = cell.calculatedValue; + } else if (cell.errorValue != '') { + cellValue = cell.errorValue; + } else if (cell.boolean != '') { + cellValue = cell.boolean; + } else if (cell.number != null) { + cellValue = cell.number.toString(); + } else if (cell.text != null) { + if (cell.saveType == 's' && + cell.textIndex != -1) { + cellValue = cell.textIndex.toString(); + } else { + cellValue = cell.text; + } + } + if (strFormula != null && + strFormula != '' && + strFormula[0] == '=' && + cell.saveType != 's') { + if (cell.saveType != '') { + builder.attribute('t', cell.saveType); + } + strFormula = strFormula + .substring(1) + .replaceAll("'", '"'); + final int i = strFormula.indexOf('!'); + if (i != -1 && + strFormula[0] == '"' && + strFormula[i - 1] == '"') { + final String sheetName = strFormula + .substring(1, i - 1); + strFormula = + "'$sheetName'${strFormula.substring(i)}"; + } + if (strFormula.contains('MINIFS')) { + strFormula = strFormula.replaceAllMapped( + RegExp('MINIFS'), + (Match match) => + '_xlfn.${match.group(0)}', + ); + } else if (strFormula.contains('MAXIFS')) { + strFormula = strFormula.replaceAllMapped( + RegExp('MAXIFS'), + (Match match) => + '_xlfn.${match.group(0)}', + ); + } + builder.element('f', nest: strFormula); + } + if (cellValue != null && + (cell.saveType == 'str' || + cellValue.isNotEmpty)) { + builder.element('v', nest: cellValue); + } + }, + ); } - builder.element('f', nest: strFormula); - } - if (cellValue != null && - (cell.saveType == 'str' || cellValue.isNotEmpty)) { - builder.element('v', nest: cellValue); } - }); - } - } + } + }, + ); } - }); + } } + }, + ); + if (sheet.isPasswordProtected) { + builder.element( + 'sheetProtection', + nest: () async { + if (sheet.algorithmName != null) { + // ignore: unnecessary_null_checks + builder.attribute('algorithmName', sheet.algorithmName!); + builder.attribute('hashValue', base64.encode(sheet.hashValue)); + builder.attribute('saltValue', base64.encode(sheet.saltValue)); + builder.attribute('spinCount', sheet.spinCount); + } else if (sheet.isPassword != 1) { + final String password = sheet.isPassword.toRadixString(16); + builder.attribute('password', password); + } + List attributes; + List flags; + List defaultValues; + attributes = sheet.protectionAttributes; + flags = sheet.flag; + defaultValues = sheet.defaultValues; + // ignore: prefer_final_locals + for (int i = 0, iCount = attributes.length; i < iCount; i++) { + _serializeProtectionAttributeAsync( + builder, + attributes[i], + flags[i], + defaultValues[i], + ); + } + }, + ); + } + //Serializing AutoFilter + _serializeAutoFiltersAsync(builder, sheet.autoFilters); + if (sheet.mergeCells.innerList.isNotEmpty) { + builder.element( + 'mergeCells', + nest: () async { + builder.attribute( + 'count', + sheet.mergeCells.innerList.length.toString(), + ); + for (final MergeCell mCell in sheet.mergeCells.innerList) { + builder.element( + 'mergeCell', + nest: () async { + builder.attribute('ref', mCell.reference); + }, + ); + } + }, + ); + } + _serializeConditionalFormattingAsync(builder, sheet); + _serializeDataValidationsAsync(builder, sheet); + _serializeHyperlinksAsync(builder, sheet); + if (sheet.pageSetup.showGridlines || + sheet.pageSetup.showHeadings || + sheet.pageSetup.isCenterHorizontally || + sheet.pageSetup.isCenterVertically) { + _serializePrintOptionsAsync(builder, sheet); + } + _validatePageMarginsAsync(sheet); + _serializePageMarginsAsync(builder, sheet); + if (sheet.pageSetup.order == ExcelPageOrder.overThenDown || + sheet.pageSetup.orientation == ExcelPageOrientation.landscape || + sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed || + sheet.pageSetup.isBlackAndWhite || + sheet.pageSetup.isDraft || + (sheet.pageSetup.printQuality != 0 && + sheet.pageSetup.printQuality != 600) || + !sheet.pageSetup.autoFirstPageNumber || + sheet.pageSetup.fitToPagesWide > 1 || + sheet.pageSetup.fitToPagesTall > 1 || + sheet.pageSetup.firstPageNumber != 1 || + sheet.pageSetup.paperSize != ExcelPaperSize.paperA4) { + _serializePageSetupAsync(builder, sheet); + } + builder.element( + 'headerFooter', + nest: () async { + builder.attribute('scaleWithDoc', '1'); + builder.attribute('alignWithMargins', '0'); + builder.attribute('differentFirst', '0'); + builder.attribute('differentOddEven', '0'); + }, + ); + + if ((sheet.pictures.count > 0) || + (sheet.charts != null && sheet.chartCount > 0)) { + _workbook.drawingCount++; + _saveDrawingsAsync(sheet); + if (sheet.charts != null && sheet.chartCount > 0) { + sheet.charts!.serializeCharts(sheet); } - } - }); - if (sheet.isPasswordProtected) { - builder.element('sheetProtection', nest: () async { - if (sheet.algorithmName != null) { - // ignore: unnecessary_null_checks - builder.attribute('algorithmName', sheet.algorithmName!); - builder.attribute('hashValue', base64.encode(sheet.hashValue)); - builder.attribute('saltValue', base64.encode(sheet.saltValue)); - builder.attribute('spinCount', sheet.spinCount); - } else if (sheet.isPassword != 1) { - final String password = sheet.isPassword.toRadixString(16); - builder.attribute('password', password); - } - List attributes; - List flags; - List defaultValues; - attributes = sheet.protectionAttributes; - flags = sheet.flag; - defaultValues = sheet.defaultValues; - // ignore: prefer_final_locals - for (int i = 0, iCount = attributes.length; i < iCount; i++) { - _serializeProtectionAttributeAsync( - builder, attributes[i], flags[i], defaultValues[i]); - } - }); - } - //Serializing AutoFilter - _serializeAutoFiltersAsync(builder, sheet.autoFilters); - if (sheet.mergeCells.innerList.isNotEmpty) { - builder.element('mergeCells', nest: () async { - builder.attribute( - 'count', sheet.mergeCells.innerList.length.toString()); - for (final MergeCell mCell in sheet.mergeCells.innerList) { - builder.element('mergeCell', nest: () async { - builder.attribute('ref', mCell.reference); - }); - } - }); - } - _serializeConditionalFormattingAsync(builder, sheet); - _serializeDataValidationsAsync(builder, sheet); - _serializeHyperlinksAsync(builder, sheet); - if (sheet.pageSetup.showGridlines || - sheet.pageSetup.showHeadings || - sheet.pageSetup.isCenterHorizontally || - sheet.pageSetup.isCenterVertically) { - _serializePrintOptionsAsync(builder, sheet); - } - _validatePageMarginsAsync(sheet); - _serializePageMarginsAsync(builder, sheet); - if (sheet.pageSetup.order == ExcelPageOrder.overThenDown || - sheet.pageSetup.orientation == ExcelPageOrientation.landscape || - sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed || - sheet.pageSetup.isBlackAndWhite || - sheet.pageSetup.isDraft || - (sheet.pageSetup.printQuality != 0 && - sheet.pageSetup.printQuality != 600) || - !sheet.pageSetup.autoFirstPageNumber || - sheet.pageSetup.fitToPagesWide > 1 || - sheet.pageSetup.fitToPagesTall > 1 || - sheet.pageSetup.firstPageNumber != 1 || - sheet.pageSetup.paperSize != ExcelPaperSize.paperA4) { - _serializePageSetupAsync(builder, sheet); - } - builder.element('headerFooter', nest: () async { - builder.attribute('scaleWithDoc', '1'); - builder.attribute('alignWithMargins', '0'); - builder.attribute('differentFirst', '0'); - builder.attribute('differentOddEven', '0'); - }); - - if ((sheet.pictures.count > 0) || - (sheet.charts != null && sheet.chartCount > 0)) { - _workbook.drawingCount++; - _saveDrawingsAsync(sheet); - if (sheet.charts != null && sheet.chartCount > 0) { - sheet.charts!.serializeCharts(sheet); - } - builder.element('drawing', nest: () async { - int id = 1; - const String rId = 'rId1'; - if (_relationId.isNotEmpty) { - if (sheet.hyperlinks.count > 0) { - for (int i = 0; i < sheet.hyperlinks.count; i++) { - if (sheet.hyperlinks[i].attachedType == - ExcelHyperlinkAttachedType.range && - sheet.hyperlinks[i].type != HyperlinkType.workbook) { - id++; + builder.element( + 'drawing', + nest: () async { + int id = 1; + const String rId = 'rId1'; + if (_relationId.isNotEmpty) { + if (sheet.hyperlinks.count > 0) { + for (int i = 0; i < sheet.hyperlinks.count; i++) { + if (sheet.hyperlinks[i].attachedType == + ExcelHyperlinkAttachedType.range && + sheet.hyperlinks[i].type != HyperlinkType.workbook) { + id++; + } + } } + builder.attribute('r:id', 'rId$id'); + } else { + builder.attribute('r:id', rId); } - } - builder.attribute('r:id', 'rId$id'); - } else { - builder.attribute('r:id', rId); - } - }); - } - final TableSerialization tableSerialization = - TableSerialization(_workbook); - tableSerialization.serializeTablesAsync(builder, sheet); - builder.element('extLst', nest: () async { - _serializeConditionalFormattingExtAsync(builder, sheet); - }); - _addToArchiveAsync(_saveSheetRelations(sheet), - 'xl/worksheets/_rels/sheet${index + 1}.xml.rels'); - }); + }, + ); + } + final TableSerialization tableSerialization = TableSerialization( + _workbook, + ); + tableSerialization.serializeTablesAsync(builder, sheet); + builder.element( + 'extLst', + nest: () async { + _serializeConditionalFormattingExtAsync(builder, sheet); + }, + ); + _addToArchiveAsync( + _saveSheetRelations(sheet), + 'xl/worksheets/_rels/sheet${index + 1}.xml.rels', + ); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'xl/worksheets/sheet${index + 1}.xml'); @@ -1031,69 +1306,81 @@ class SerializeWorkbook { /// Serializes worksheet printOptions void _serializePrintOptions(XmlBuilder builder, Worksheet sheet) { - builder.element('printOptions', nest: () { - if (sheet.pageSetup.isCenterHorizontally) { - builder.attribute('horizontalCentered', '1'); - } - if (sheet.pageSetup.isCenterVertically) { - builder.attribute('verticalCentered', '1'); - } - if (sheet.pageSetup.showHeadings) { - builder.attribute('headings', '1'); - } - if (sheet.pageSetup.showGridlines) { - builder.attribute('gridLines', '1'); - } - }); + builder.element( + 'printOptions', + nest: () { + if (sheet.pageSetup.isCenterHorizontally) { + builder.attribute('horizontalCentered', '1'); + } + if (sheet.pageSetup.isCenterVertically) { + builder.attribute('verticalCentered', '1'); + } + if (sheet.pageSetup.showHeadings) { + builder.attribute('headings', '1'); + } + if (sheet.pageSetup.showGridlines) { + builder.attribute('gridLines', '1'); + } + }, + ); } Future _serializePrintOptionsAsync( - XmlBuilder builder, Worksheet sheet) async { - builder.element('printOptions', nest: () async { - if (sheet.pageSetup.isCenterHorizontally) { - builder.attribute('horizontalCentered', '1'); - } - if (sheet.pageSetup.isCenterVertically) { - builder.attribute('verticalCentered', '1'); - } - if (sheet.pageSetup.showHeadings) { - builder.attribute('headings', '1'); - } - if (sheet.pageSetup.showGridlines) { - builder.attribute('gridLines', '1'); - } - }); + XmlBuilder builder, + Worksheet sheet, + ) async { + builder.element( + 'printOptions', + nest: () async { + if (sheet.pageSetup.isCenterHorizontally) { + builder.attribute('horizontalCentered', '1'); + } + if (sheet.pageSetup.isCenterVertically) { + builder.attribute('verticalCentered', '1'); + } + if (sheet.pageSetup.showHeadings) { + builder.attribute('headings', '1'); + } + if (sheet.pageSetup.showGridlines) { + builder.attribute('gridLines', '1'); + } + }, + ); } /// Validate whether Page margins are fit into the Page void _validatePageMargins(Worksheet sheet) { - if ((sheet.pageSetup as PageSetupImpl) - .paperHight - .containsKey(sheet.pageSetup.paperSize) && - (sheet.pageSetup as PageSetupImpl) - .paperWidth - .containsKey(sheet.pageSetup.paperSize)) { + if ((sheet.pageSetup as PageSetupImpl).paperHight.containsKey( + sheet.pageSetup.paperSize, + ) && + (sheet.pageSetup as PageSetupImpl).paperWidth.containsKey( + sheet.pageSetup.paperSize, + )) { final double maxHight = sheet.pageSetup.topMargin + sheet.pageSetup.bottomMargin; final double maxWidth = sheet.pageSetup.leftMargin + sheet.pageSetup.rightMargin; - (sheet.pageSetup as PageSetupImpl) - .paperHight - .forEach((ExcelPaperSize key, double value) { + (sheet.pageSetup as PageSetupImpl).paperHight.forEach(( + ExcelPaperSize key, + double value, + ) { if (sheet.pageSetup.paperSize == key) { if (maxHight > value) { throw Exception( - 'Top Margin and Bottom Margin size exceeds the allowed size'); + 'Top Margin and Bottom Margin size exceeds the allowed size', + ); } } }); - (sheet.pageSetup as PageSetupImpl) - .paperWidth - .forEach((ExcelPaperSize key, double value) { + (sheet.pageSetup as PageSetupImpl).paperWidth.forEach(( + ExcelPaperSize key, + double value, + ) { if (sheet.pageSetup.paperSize == key) { if (maxWidth > value) { throw Exception( - 'Left Margin and Right Margin size exceeds the allowed size'); + 'Left Margin and Right Margin size exceeds the allowed size', + ); } } }); @@ -1101,33 +1388,37 @@ class SerializeWorkbook { } Future _validatePageMarginsAsync(Worksheet sheet) async { - if ((sheet.pageSetup as PageSetupImpl) - .paperHight - .containsKey(sheet.pageSetup.paperSize) && - (sheet.pageSetup as PageSetupImpl) - .paperWidth - .containsKey(sheet.pageSetup.paperSize)) { + if ((sheet.pageSetup as PageSetupImpl).paperHight.containsKey( + sheet.pageSetup.paperSize, + ) && + (sheet.pageSetup as PageSetupImpl).paperWidth.containsKey( + sheet.pageSetup.paperSize, + )) { final double maxHight = sheet.pageSetup.topMargin + sheet.pageSetup.bottomMargin; final double maxWidth = sheet.pageSetup.leftMargin + sheet.pageSetup.rightMargin; - (sheet.pageSetup as PageSetupImpl) - .paperHight - .forEach((ExcelPaperSize key, double value) { + (sheet.pageSetup as PageSetupImpl).paperHight.forEach(( + ExcelPaperSize key, + double value, + ) { if (sheet.pageSetup.paperSize == key) { if (maxHight > value) { throw Exception( - 'Top Margin and Bottom Margin size exceeds the allowed size'); + 'Top Margin and Bottom Margin size exceeds the allowed size', + ); } } }); - (sheet.pageSetup as PageSetupImpl) - .paperWidth - .forEach((ExcelPaperSize key, double value) { + (sheet.pageSetup as PageSetupImpl).paperWidth.forEach(( + ExcelPaperSize key, + double value, + ) { if (sheet.pageSetup.paperSize == key) { if (maxWidth > value) { throw Exception( - 'Left Margin and Right Margin size exceeds the allowed size'); + 'Left Margin and Right Margin size exceeds the allowed size', + ); } } }); @@ -1136,153 +1427,189 @@ class SerializeWorkbook { /// Serializes pageMargins void _serializePageMargins(XmlBuilder builder, Worksheet sheet) { - builder.element('pageMargins', nest: () { - builder.attribute('left', sheet.pageSetup.leftMargin.toString()); - builder.attribute('right', sheet.pageSetup.rightMargin.toString()); - builder.attribute('top', sheet.pageSetup.topMargin.toString()); - builder.attribute('bottom', sheet.pageSetup.bottomMargin.toString()); - builder.attribute('header', sheet.pageSetup.headerMargin.toString()); - builder.attribute('footer', sheet.pageSetup.footerMargin.toString()); - }); + builder.element( + 'pageMargins', + nest: () { + builder.attribute('left', sheet.pageSetup.leftMargin.toString()); + builder.attribute('right', sheet.pageSetup.rightMargin.toString()); + builder.attribute('top', sheet.pageSetup.topMargin.toString()); + builder.attribute('bottom', sheet.pageSetup.bottomMargin.toString()); + builder.attribute('header', sheet.pageSetup.headerMargin.toString()); + builder.attribute('footer', sheet.pageSetup.footerMargin.toString()); + }, + ); } Future _serializePageMarginsAsync( - XmlBuilder builder, Worksheet sheet) async { - builder.element('pageMargins', nest: () async { - builder.attribute('left', sheet.pageSetup.leftMargin.toString()); - builder.attribute('right', sheet.pageSetup.rightMargin.toString()); - builder.attribute('top', sheet.pageSetup.topMargin.toString()); - builder.attribute('bottom', sheet.pageSetup.bottomMargin.toString()); - builder.attribute('header', sheet.pageSetup.headerMargin.toString()); - builder.attribute('footer', sheet.pageSetup.footerMargin.toString()); - }); + XmlBuilder builder, + Worksheet sheet, + ) async { + builder.element( + 'pageMargins', + nest: () async { + builder.attribute('left', sheet.pageSetup.leftMargin.toString()); + builder.attribute('right', sheet.pageSetup.rightMargin.toString()); + builder.attribute('top', sheet.pageSetup.topMargin.toString()); + builder.attribute('bottom', sheet.pageSetup.bottomMargin.toString()); + builder.attribute('header', sheet.pageSetup.headerMargin.toString()); + builder.attribute('footer', sheet.pageSetup.footerMargin.toString()); + }, + ); } /// Serialize pageSetup void _serializePageSetup(XmlBuilder builder, Worksheet sheet) { - builder.element('pageSetup', nest: () { - _serializePaperSize(builder, sheet); + builder.element( + 'pageSetup', + nest: () { + _serializePaperSize(builder, sheet); - if (sheet.pageSetup.firstPageNumber != 1) { - builder.attribute( - 'firstPageNumber', sheet.pageSetup.firstPageNumber.toString()); - } - if (sheet.pageSetup.fitToPagesWide > 1) { - builder.attribute( - 'fitToWidth', sheet.pageSetup.fitToPagesWide.toString()); - } - if (sheet.pageSetup.fitToPagesTall > 1) { - builder.attribute( - 'fitToHeight', sheet.pageSetup.fitToPagesTall.toString()); - } - if (sheet.pageSetup.order == ExcelPageOrder.overThenDown) { - builder.attribute('pageOrder', 'overThenDown'); - } - if (sheet.pageSetup.orientation == ExcelPageOrientation.landscape) { - builder.attribute('orientation', 'landscape'); - } else { - builder.attribute('orientation', 'portrait'); - } - if (sheet.pageSetup.isBlackAndWhite) { - builder.attribute('blackAndWhite', '1'); - } - if (sheet.pageSetup.isDraft) { - builder.attribute('draft', '1'); - } - if (!sheet.pageSetup.autoFirstPageNumber) { - builder.attribute('useFirstPageNumber', '1'); - } - if (sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed) { - switch (sheet.pageSetup.printErrors) { - case CellErrorPrintOptions.blank: - builder.attribute('errors', 'blank'); - break; - case CellErrorPrintOptions.dash: - builder.attribute('errors', 'dash'); - break; - case CellErrorPrintOptions.notAvailable: - builder.attribute('errors', 'NA'); - break; - case CellErrorPrintOptions.displayed: - break; + if (sheet.pageSetup.firstPageNumber != 1) { + builder.attribute( + 'firstPageNumber', + sheet.pageSetup.firstPageNumber.toString(), + ); } - } - if (sheet.pageSetup.printQuality != 0 && - sheet.pageSetup.printQuality != 600) { - if (sheet.pageSetup.printQuality <= 38528) { + if (sheet.pageSetup.fitToPagesWide > 1) { builder.attribute( - 'horizontalDpi', sheet.pageSetup.printQuality.toString()); + 'fitToWidth', + sheet.pageSetup.fitToPagesWide.toString(), + ); + } + if (sheet.pageSetup.fitToPagesTall > 1) { builder.attribute( - 'verticalDpi', sheet.pageSetup.printQuality.toString()); + 'fitToHeight', + sheet.pageSetup.fitToPagesTall.toString(), + ); + } + if (sheet.pageSetup.order == ExcelPageOrder.overThenDown) { + builder.attribute('pageOrder', 'overThenDown'); + } + if (sheet.pageSetup.orientation == ExcelPageOrientation.landscape) { + builder.attribute('orientation', 'landscape'); } else { - builder.attribute('horizontalDpi', '38528'); - builder.attribute('verticalDpi', '38528'); + builder.attribute('orientation', 'portrait'); + } + if (sheet.pageSetup.isBlackAndWhite) { + builder.attribute('blackAndWhite', '1'); + } + if (sheet.pageSetup.isDraft) { + builder.attribute('draft', '1'); + } + if (!sheet.pageSetup.autoFirstPageNumber) { + builder.attribute('useFirstPageNumber', '1'); + } + if (sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed) { + switch (sheet.pageSetup.printErrors) { + case CellErrorPrintOptions.blank: + builder.attribute('errors', 'blank'); + break; + case CellErrorPrintOptions.dash: + builder.attribute('errors', 'dash'); + break; + case CellErrorPrintOptions.notAvailable: + builder.attribute('errors', 'NA'); + break; + case CellErrorPrintOptions.displayed: + break; + } } - } - }); + if (sheet.pageSetup.printQuality != 0 && + sheet.pageSetup.printQuality != 600) { + if (sheet.pageSetup.printQuality <= 38528) { + builder.attribute( + 'horizontalDpi', + sheet.pageSetup.printQuality.toString(), + ); + builder.attribute( + 'verticalDpi', + sheet.pageSetup.printQuality.toString(), + ); + } else { + builder.attribute('horizontalDpi', '38528'); + builder.attribute('verticalDpi', '38528'); + } + } + }, + ); } Future _serializePageSetupAsync( - XmlBuilder builder, Worksheet sheet) async { - builder.element('pageSetup', nest: () async { - _serializePaperSizeAsync(builder, sheet); - if (sheet.pageSetup.firstPageNumber != 1) { - builder.attribute( - 'firstPageNumber', sheet.pageSetup.firstPageNumber.toString()); - } - if (sheet.pageSetup.fitToPagesWide > 1) { - builder.attribute( - 'fitToWidth', sheet.pageSetup.fitToPagesWide.toString()); - } - if (sheet.pageSetup.fitToPagesTall > 1) { - builder.attribute( - 'fitToHeight', sheet.pageSetup.fitToPagesTall.toString()); - } - if (sheet.pageSetup.order == ExcelPageOrder.overThenDown) { - builder.attribute('pageOrder', 'overThenDown'); - } - if (sheet.pageSetup.orientation == ExcelPageOrientation.landscape) { - builder.attribute('orientation', 'landscape'); - } else { - builder.attribute('orientation', 'portrait'); - } - if (sheet.pageSetup.isBlackAndWhite) { - builder.attribute('blackAndWhite', '1'); - } - if (sheet.pageSetup.isDraft) { - builder.attribute('draft', '1'); - } - if (!sheet.pageSetup.autoFirstPageNumber) { - builder.attribute('useFirstPageNumber', '1'); - } - if (sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed) { - switch (sheet.pageSetup.printErrors) { - case CellErrorPrintOptions.blank: - builder.attribute('errors', 'blank'); - break; - case CellErrorPrintOptions.dash: - builder.attribute('errors', 'dash'); - break; - case CellErrorPrintOptions.notAvailable: - builder.attribute('errors', 'NA'); - break; - case CellErrorPrintOptions.displayed: - break; + XmlBuilder builder, + Worksheet sheet, + ) async { + builder.element( + 'pageSetup', + nest: () async { + _serializePaperSizeAsync(builder, sheet); + if (sheet.pageSetup.firstPageNumber != 1) { + builder.attribute( + 'firstPageNumber', + sheet.pageSetup.firstPageNumber.toString(), + ); } - } - if (sheet.pageSetup.printQuality != 0 && - sheet.pageSetup.printQuality != 600) { - if (sheet.pageSetup.printQuality <= 38528) { + if (sheet.pageSetup.fitToPagesWide > 1) { builder.attribute( - 'horizontalDpi', sheet.pageSetup.printQuality.toString()); + 'fitToWidth', + sheet.pageSetup.fitToPagesWide.toString(), + ); + } + if (sheet.pageSetup.fitToPagesTall > 1) { builder.attribute( - 'verticalDpi', sheet.pageSetup.printQuality.toString()); + 'fitToHeight', + sheet.pageSetup.fitToPagesTall.toString(), + ); + } + if (sheet.pageSetup.order == ExcelPageOrder.overThenDown) { + builder.attribute('pageOrder', 'overThenDown'); + } + if (sheet.pageSetup.orientation == ExcelPageOrientation.landscape) { + builder.attribute('orientation', 'landscape'); } else { - builder.attribute('horizontalDpi', '38528'); - builder.attribute('verticalDpi', '38528'); + builder.attribute('orientation', 'portrait'); + } + if (sheet.pageSetup.isBlackAndWhite) { + builder.attribute('blackAndWhite', '1'); + } + if (sheet.pageSetup.isDraft) { + builder.attribute('draft', '1'); + } + if (!sheet.pageSetup.autoFirstPageNumber) { + builder.attribute('useFirstPageNumber', '1'); + } + if (sheet.pageSetup.printErrors != CellErrorPrintOptions.displayed) { + switch (sheet.pageSetup.printErrors) { + case CellErrorPrintOptions.blank: + builder.attribute('errors', 'blank'); + break; + case CellErrorPrintOptions.dash: + builder.attribute('errors', 'dash'); + break; + case CellErrorPrintOptions.notAvailable: + builder.attribute('errors', 'NA'); + break; + case CellErrorPrintOptions.displayed: + break; + } } - } - }); + if (sheet.pageSetup.printQuality != 0 && + sheet.pageSetup.printQuality != 600) { + if (sheet.pageSetup.printQuality <= 38528) { + builder.attribute( + 'horizontalDpi', + sheet.pageSetup.printQuality.toString(), + ); + builder.attribute( + 'verticalDpi', + sheet.pageSetup.printQuality.toString(), + ); + } else { + builder.attribute('horizontalDpi', '38528'); + builder.attribute('verticalDpi', '38528'); + } + } + }, + ); } /// Serialize paperSize @@ -1493,7 +1820,9 @@ class SerializeWorkbook { } Future _serializePaperSizeAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { switch (sheet.pageSetup.paperSize) { case ExcelPaperSize.a2Paper: builder.attribute('paperSize', '66'); @@ -1701,13 +2030,21 @@ class SerializeWorkbook { /// Serializes single protection option. void _serializeProtectionAttribute( - XmlBuilder builder, String attributeName, bool flag, bool defaultValue) { + XmlBuilder builder, + String attributeName, + bool flag, + bool defaultValue, + ) { final bool value = flag; _serializeAttributes(builder, attributeName, value, defaultValue); } - Future _serializeProtectionAttributeAsync(XmlBuilder builder, - String attributeName, bool flag, bool defaultValue) async { + Future _serializeProtectionAttributeAsync( + XmlBuilder builder, + String attributeName, + bool flag, + bool defaultValue, + ) async { final bool value = flag; _serializeAttributesAsync(builder, attributeName, value, defaultValue); } @@ -1719,86 +2056,106 @@ class SerializeWorkbook { final List hyperLinkType = List.filled(iCount, ''); for (int i = 0; i < sheet.hyperlinks.count; i++) { final Hyperlink hyperLink = sheet.hyperlinks[i]; - hyperLinkType[i] = - hyperLink.attachedType.toString().split('.').toList().removeAt(1); + hyperLinkType[i] = hyperLink.attachedType + .toString() + .split('.') + .toList() + .removeAt(1); } if (iCount == 0 || !hyperLinkType.contains('range')) { return; } - builder.element('hyperlinks', nest: () { - int id = 1; - for (final Hyperlink link in sheet.hyperlinks.innerList) { - if (link.attachedType == ExcelHyperlinkAttachedType.range) { - builder.element('hyperlink', nest: () { - if (link.type == HyperlinkType.workbook) { - builder.attribute('ref', link.reference); - builder.attribute('location', link.address); - } else { - builder.attribute('ref', link.reference); - final String rId = 'rId$id'; - builder.attribute('r:id', rId); - _relationId.add(rId); - id++; - } - if (link.screenTip != null) { - // ignore: unnecessary_null_checks - builder.attribute('tooltip', link.screenTip!); - } - if (link.textToDisplay != null) { - // ignore: unnecessary_null_checks - builder.attribute('display', link.textToDisplay!); - } else { - builder.attribute('display', link.address); - } - }); + builder.element( + 'hyperlinks', + nest: () { + int id = 1; + for (final Hyperlink link in sheet.hyperlinks.innerList) { + if (link.attachedType == ExcelHyperlinkAttachedType.range) { + builder.element( + 'hyperlink', + nest: () { + if (link.type == HyperlinkType.workbook) { + builder.attribute('ref', link.reference); + builder.attribute('location', link.address); + } else { + builder.attribute('ref', link.reference); + final String rId = 'rId$id'; + builder.attribute('r:id', rId); + _relationId.add(rId); + id++; + } + if (link.screenTip != null) { + // ignore: unnecessary_null_checks + builder.attribute('tooltip', link.screenTip!); + } + if (link.textToDisplay != null) { + // ignore: unnecessary_null_checks + builder.attribute('display', link.textToDisplay!); + } else { + builder.attribute('display', link.address); + } + }, + ); + } } - } - }); + }, + ); } } Future _serializeHyperlinksAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { if (sheet.hyperlinks.count > 0) { final int iCount = sheet.hyperlinks.count; final List hyperLinkType = List.filled(iCount, ''); for (int i = 0; i < sheet.hyperlinks.count; i++) { final Hyperlink hyperLink = sheet.hyperlinks[i]; - hyperLinkType[i] = - hyperLink.attachedType.toString().split('.').toList().removeAt(1); + hyperLinkType[i] = hyperLink.attachedType + .toString() + .split('.') + .toList() + .removeAt(1); } if (iCount == 0 || !hyperLinkType.contains('range')) { return; } - builder.element('hyperlinks', nest: () async { - int id = 1; - for (final Hyperlink link in sheet.hyperlinks.innerList) { - if (link.attachedType == ExcelHyperlinkAttachedType.range) { - builder.element('hyperlink', nest: () async { - if (link.type == HyperlinkType.workbook) { - builder.attribute('ref', link.reference); - builder.attribute('location', link.address); - } else { - builder.attribute('ref', link.reference); - final String rId = 'rId$id'; - builder.attribute('r:id', rId); - _relationId.add(rId); - id++; - } - if (link.screenTip != null) { - // ignore: unnecessary_null_checks - builder.attribute('tooltip', link.screenTip!); - } - if (link.textToDisplay != null) { - // ignore: unnecessary_null_checks - builder.attribute('display', link.textToDisplay!); - } else { - builder.attribute('display', link.address); - } - }); + builder.element( + 'hyperlinks', + nest: () async { + int id = 1; + for (final Hyperlink link in sheet.hyperlinks.innerList) { + if (link.attachedType == ExcelHyperlinkAttachedType.range) { + builder.element( + 'hyperlink', + nest: () async { + if (link.type == HyperlinkType.workbook) { + builder.attribute('ref', link.reference); + builder.attribute('location', link.address); + } else { + builder.attribute('ref', link.reference); + final String rId = 'rId$id'; + builder.attribute('r:id', rId); + _relationId.add(rId); + id++; + } + if (link.screenTip != null) { + // ignore: unnecessary_null_checks + builder.attribute('tooltip', link.screenTip!); + } + if (link.textToDisplay != null) { + // ignore: unnecessary_null_checks + builder.attribute('display', link.textToDisplay!); + } else { + builder.attribute('display', link.address); + } + }, + ); + } } - } - }); + }, + ); } } @@ -1806,364 +2163,506 @@ class SerializeWorkbook { void _saveDrawings(Worksheet sheet) { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('xdr:wsDr', nest: () { - builder.attribute('xmlns:xdr', - 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); - builder.attribute( - 'xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); - final int chartCount = sheet.chartCount; - if (chartCount != 0 && sheet.charts != null) { - sheet.charts!.serializeChartDrawingSync(builder, sheet); - } - final int idIndex = 0 + chartCount; - final List idRelation = []; - if (sheet.pictures.count != 0) { - int imgId = 0; - int idHyperlink = 1; - int hyperlinkCount = 0; - for (final Picture picture in sheet.pictures.innerList) { - if (picture.height != 0 && picture.width != 0) { - if (picture.lastRow == 0 || picture.lastRow < picture.row) { - _updateLastRowOffset(sheet, picture); - } else if (picture.lastRow != 0) { - picture.lastRowOffset = 0; - } - if (picture.lastColumn == 0 || - picture.lastColumn < picture.column) { - _updateLastColumnOffSet(sheet, picture); - } else if (picture.lastColumn != 0) { - picture.lastColOffset = 0; + builder.element( + 'xdr:wsDr', + nest: () { + builder.attribute( + 'xmlns:xdr', + 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing', + ); + builder.attribute( + 'xmlns:a', + 'http://schemas.openxmlformats.org/drawingml/2006/main', + ); + final int chartCount = sheet.chartCount; + if (chartCount != 0 && sheet.charts != null) { + sheet.charts!.serializeChartDrawingSync(builder, sheet); + } + final int idIndex = 0 + chartCount; + final List idRelation = []; + if (sheet.pictures.count != 0) { + int imgId = 0; + int idHyperlink = 1; + int hyperlinkCount = 0; + for (final Picture picture in sheet.pictures.innerList) { + if (picture.height != 0 && picture.width != 0) { + if (picture.lastRow == 0 || picture.lastRow < picture.row) { + _updateLastRowOffset(sheet, picture); + } else if (picture.lastRow != 0) { + picture.lastRowOffset = 0; + } + if (picture.lastColumn == 0 || + picture.lastColumn < picture.column) { + _updateLastColumnOffSet(sheet, picture); + } else if (picture.lastColumn != 0) { + picture.lastColOffset = 0; + } } - } - imgId++; - builder.element('xdr:twoCellAnchor', nest: () { - builder.attribute('editAs', 'twoCell'); - builder.element('xdr:from', nest: () { - builder.element('xdr:col', nest: picture.column - 1); - builder.element('xdr:colOff', nest: 0); - builder.element('xdr:row', nest: picture.row - 1); - builder.element('xdr:rowOff', nest: 0); - }); - - builder.element('xdr:to', nest: () { - builder.element('xdr:col', nest: picture.lastColumn - 1); - builder.element('xdr:colOff', - nest: picture.lastColOffset.round()); - builder.element('xdr:row', nest: picture.lastRow - 1); - builder.element('xdr:rowOff', - nest: picture.lastRowOffset.round()); - }); - - builder.element('xdr:pic', nest: () { - builder.attribute('macro', ''); - builder.element('xdr:nvPicPr', nest: () { - builder.element('xdr:cNvPr', nest: () { - builder.attribute('id', imgId); - builder.attribute('name', 'Picture$imgId'); - if (picture.isHyperlink) { - builder.element('a:hlinkClick', nest: () { - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - int id = idIndex + imgId + idHyperlink; - String rId = 'rId$id'; - if (idRelation.contains(rId)) { - id = id + 1; - rId = 'rId$id'; - } - builder.attribute('r:id', rId); - idRelation.add(rId); - sheet.hyperlinkRelationId.add(rId); - idHyperlink++; - if (picture.hyperlink != null && - picture.hyperlink!.screenTip != null) { - builder.attribute( - 'tooltip', - // ignore: unnecessary_null_checks - picture.hyperlink!.screenTip!); - } - }); - } - }); - builder.element('xdr:cNvPicPr', nest: () { - builder.element('a:picLocks', nest: () { - builder.attribute('noChangeAspect', 1); - }); - }); - }); - - builder.element('xdr:blipFill', nest: () { - builder.element('a:blip', nest: () { - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - int id; - String rId; - if (idRelation.isEmpty) { - id = idIndex + imgId + hyperlinkCount; - rId = 'rId$id'; - builder.attribute('r:embed', rId); - idRelation.add(rId); - } else { - id = idIndex + imgId + hyperlinkCount; - rId = 'rId$id'; - if (idRelation.contains(rId)) { - id = id + 1; - rId = 'rId$id'; - if (idRelation.contains(rId)) { - id = id + 1; - rId = 'rId$id'; - } - } - builder.attribute('r:embed', rId); - idRelation.add(rId); - if (picture.isHyperlink) { - hyperlinkCount++; - } - } - builder.attribute('cstate', 'print'); - }); - - builder.element('a:stretch', nest: () { - builder.element('a:fillRect', nest: () {}); - }); - }); + imgId++; + builder.element( + 'xdr:twoCellAnchor', + nest: () { + builder.attribute('editAs', 'twoCell'); + builder.element( + 'xdr:from', + nest: () { + builder.element('xdr:col', nest: picture.column - 1); + builder.element('xdr:colOff', nest: 0); + builder.element('xdr:row', nest: picture.row - 1); + builder.element('xdr:rowOff', nest: 0); + }, + ); - builder.element('xdr:spPr', nest: () { - builder.element('a:xfrm', nest: () { - if (picture.rotation != 0 && - picture.rotation <= 3600 && - picture.rotation >= -3600) { - builder.attribute('rot', picture.rotation * 60000); - } - if (picture.verticalFlip) { - builder.attribute('flipV', '1'); - } - if (picture.horizontalFlip) { - builder.attribute('flipH', '1'); - } - builder.element('a:off', nest: () { - builder.attribute('x', '0'); - builder.attribute('y', '0'); - }); - builder.element('a:ext', nest: () { - builder.attribute('cx', '0'); - builder.attribute('cy', '0'); - }); - }); + builder.element( + 'xdr:to', + nest: () { + builder.element('xdr:col', nest: picture.lastColumn - 1); + builder.element( + 'xdr:colOff', + nest: picture.lastColOffset.round(), + ); + builder.element('xdr:row', nest: picture.lastRow - 1); + builder.element( + 'xdr:rowOff', + nest: picture.lastRowOffset.round(), + ); + }, + ); - builder.element('a:prstGeom', nest: () { - builder.attribute('prst', 'rect'); - builder.element('a:avLst', nest: () {}); - }); - }); - }); - builder.element('xdr:clientData', nest: () {}); - }); - final List? imageData = picture.imageData; - _workbook.imageCount += 1; - String imgPath; - if (Picture.isJpeg(imageData)) { - imgPath = 'xl/media/image${_workbook.imageCount}.jpeg'; - if (!_workbook.defaultContentTypes.containsKey('jpeg')) { - _workbook.defaultContentTypes['jpeg'] = 'image/jpeg'; + builder.element( + 'xdr:pic', + nest: () { + builder.attribute('macro', ''); + builder.element( + 'xdr:nvPicPr', + nest: () { + builder.element( + 'xdr:cNvPr', + nest: () { + builder.attribute('id', imgId); + builder.attribute('name', 'Picture$imgId'); + if (picture.isHyperlink) { + builder.element( + 'a:hlinkClick', + nest: () { + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + int id = idIndex + imgId + idHyperlink; + String rId = 'rId$id'; + if (idRelation.contains(rId)) { + id = id + 1; + rId = 'rId$id'; + } + builder.attribute('r:id', rId); + idRelation.add(rId); + sheet.hyperlinkRelationId.add(rId); + idHyperlink++; + if (picture.hyperlink != null && + picture.hyperlink!.screenTip != null) { + builder.attribute( + 'tooltip', + // ignore: unnecessary_null_checks + picture.hyperlink!.screenTip!, + ); + } + }, + ); + } + }, + ); + builder.element( + 'xdr:cNvPicPr', + nest: () { + builder.element( + 'a:picLocks', + nest: () { + builder.attribute('noChangeAspect', 1); + }, + ); + }, + ); + }, + ); + + builder.element( + 'xdr:blipFill', + nest: () { + builder.element( + 'a:blip', + nest: () { + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + int id; + String rId; + if (idRelation.isEmpty) { + id = idIndex + imgId + hyperlinkCount; + rId = 'rId$id'; + builder.attribute('r:embed', rId); + idRelation.add(rId); + } else { + id = idIndex + imgId + hyperlinkCount; + rId = 'rId$id'; + if (idRelation.contains(rId)) { + id = id + 1; + rId = 'rId$id'; + if (idRelation.contains(rId)) { + id = id + 1; + rId = 'rId$id'; + } + } + builder.attribute('r:embed', rId); + idRelation.add(rId); + if (picture.isHyperlink) { + hyperlinkCount++; + } + } + builder.attribute('cstate', 'print'); + }, + ); + + builder.element( + 'a:stretch', + nest: () { + builder.element('a:fillRect', nest: () {}); + }, + ); + }, + ); + + builder.element( + 'xdr:spPr', + nest: () { + builder.element( + 'a:xfrm', + nest: () { + if (picture.rotation != 0 && + picture.rotation <= 3600 && + picture.rotation >= -3600) { + builder.attribute( + 'rot', + picture.rotation * 60000, + ); + } + if (picture.verticalFlip) { + builder.attribute('flipV', '1'); + } + if (picture.horizontalFlip) { + builder.attribute('flipH', '1'); + } + builder.element( + 'a:off', + nest: () { + builder.attribute('x', '0'); + builder.attribute('y', '0'); + }, + ); + builder.element( + 'a:ext', + nest: () { + builder.attribute('cx', '0'); + builder.attribute('cy', '0'); + }, + ); + }, + ); + + builder.element( + 'a:prstGeom', + nest: () { + builder.attribute('prst', 'rect'); + builder.element('a:avLst', nest: () {}); + }, + ); + }, + ); + }, + ); + builder.element('xdr:clientData', nest: () {}); + }, + ); + final List? imageData = picture.imageData; + _workbook.imageCount += 1; + String imgPath; + if (Picture.isJpeg(imageData)) { + imgPath = 'xl/media/image${_workbook.imageCount}.jpeg'; + if (!_workbook.defaultContentTypes.containsKey('jpeg')) { + _workbook.defaultContentTypes['jpeg'] = 'image/jpeg'; + } + } else { + imgPath = 'xl/media/image${_workbook.imageCount}.png'; + if (!_workbook.defaultContentTypes.containsKey('png')) { + _workbook.defaultContentTypes['png'] = 'image/png'; + } } - } else { - imgPath = 'xl/media/image${_workbook.imageCount}.png'; - if (!_workbook.defaultContentTypes.containsKey('png')) { - _workbook.defaultContentTypes['png'] = 'image/png'; + if (imageData != null) { + _addToArchive(imageData, imgPath); } } - if (imageData != null) { - _addToArchive(imageData, imgPath); - } } - } - }); + }, + ); _saveDrawingRelations(sheet); final String stringXml = builder.buildDocument().copy().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/drawings/drawing${_workbook.drawingCount}.xml'); } - Future _saveDrawingsAsync(Worksheet sheet) async { - final XmlBuilder builder = XmlBuilder(); - builder.processing('xml', 'version="1.0"'); - builder.element('xdr:wsDr', nest: () async { - builder.attribute('xmlns:xdr', - 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); - builder.attribute( - 'xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); - final int chartCount = sheet.chartCount; - if (chartCount != 0 && sheet.charts != null) { - sheet.charts!.serializeChartDrawing(builder, sheet); - } - final int idIndex = 0 + chartCount; - final List idRelation = []; - if (sheet.pictures.count != 0) { - int imgId = 0; - int idHyperlink = 1; - int hyperlinkCount = 0; - for (final Picture picture in sheet.pictures.innerList) { - if (picture.height != 0 && picture.width != 0) { - if (picture.lastRow == 0 || picture.lastRow < picture.row) { - _updateLastRowOffsetAsync(sheet, picture); - } else if (picture.lastRow != 0) { - picture.lastRowOffset = 0; - } - if (picture.lastColumn == 0 || - picture.lastColumn < picture.column) { - _updateLastColumnOffSetAsync(sheet, picture); - } else if (picture.lastColumn != 0) { - picture.lastColOffset = 0; - } - } - imgId++; - builder.element('xdr:twoCellAnchor', nest: () async { - builder.attribute('editAs', 'twoCell'); - builder.element('xdr:from', nest: () async { - builder.element('xdr:col', nest: picture.column - 1); - builder.element('xdr:colOff', nest: 0); - builder.element('xdr:row', nest: picture.row - 1); - builder.element('xdr:rowOff', nest: 0); - }); - - builder.element('xdr:to', nest: () async { - builder.element('xdr:col', nest: picture.lastColumn - 1); - builder.element('xdr:colOff', - nest: picture.lastColOffset.round()); - builder.element('xdr:row', nest: picture.lastRow - 1); - builder.element('xdr:rowOff', - nest: picture.lastRowOffset.round()); - }); - - builder.element('xdr:pic', nest: () async { - builder.attribute('macro', ''); - builder.element('xdr:nvPicPr', nest: () async { - builder.element('xdr:cNvPr', nest: () async { - builder.attribute('id', imgId); - builder.attribute('name', 'Picture$imgId'); - if (picture.isHyperlink) { - builder.element('a:hlinkClick', nest: () async { - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - int id = idIndex + imgId + idHyperlink; - String rId = 'rId$id'; - if (idRelation.contains(rId)) { - id = id + 1; - rId = 'rId$id'; - } - builder.attribute('r:id', rId); - idRelation.add(rId); - sheet.hyperlinkRelationId.add(rId); - idHyperlink++; - if (picture.hyperlink != null && - picture.hyperlink!.screenTip != null) { - builder.attribute( - 'tooltip', - // ignore: unnecessary_null_checks - picture.hyperlink!.screenTip!); - } - }); - } - }); - builder.element('xdr:cNvPicPr', nest: () async { - builder.element('a:picLocks', nest: () async { - builder.attribute('noChangeAspect', 1); - }); - }); - }); - - builder.element('xdr:blipFill', nest: () async { - builder.element('a:blip', nest: () async { - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - int id; - String rId; - if (idRelation.isEmpty) { - id = idIndex + imgId + hyperlinkCount; - rId = 'rId$id'; - builder.attribute('r:embed', rId); - idRelation.add(rId); - } else { - id = idIndex + imgId + hyperlinkCount; - rId = 'rId$id'; - if (idRelation.contains(rId)) { - id = id + 1; - rId = 'rId$id'; - if (idRelation.contains(rId)) { - id = id + 1; - rId = 'rId$id'; - } - } - builder.attribute('r:embed', rId); - idRelation.add(rId); - if (picture.isHyperlink) { - hyperlinkCount++; - } - } - builder.attribute('cstate', 'print'); - }); - - builder.element('a:stretch', nest: () async { - builder.element('a:fillRect', nest: () async {}); - }); - }); + Future _saveDrawingsAsync(Worksheet sheet) async { + final XmlBuilder builder = XmlBuilder(); + builder.processing('xml', 'version="1.0"'); + builder.element( + 'xdr:wsDr', + nest: () async { + builder.attribute( + 'xmlns:xdr', + 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing', + ); + builder.attribute( + 'xmlns:a', + 'http://schemas.openxmlformats.org/drawingml/2006/main', + ); + final int chartCount = sheet.chartCount; + if (chartCount != 0 && sheet.charts != null) { + sheet.charts!.serializeChartDrawing(builder, sheet); + } + final int idIndex = 0 + chartCount; + final List idRelation = []; + if (sheet.pictures.count != 0) { + int imgId = 0; + int idHyperlink = 1; + int hyperlinkCount = 0; + for (final Picture picture in sheet.pictures.innerList) { + if (picture.height != 0 && picture.width != 0) { + if (picture.lastRow == 0 || picture.lastRow < picture.row) { + _updateLastRowOffsetAsync(sheet, picture); + } else if (picture.lastRow != 0) { + picture.lastRowOffset = 0; + } + if (picture.lastColumn == 0 || + picture.lastColumn < picture.column) { + _updateLastColumnOffSetAsync(sheet, picture); + } else if (picture.lastColumn != 0) { + picture.lastColOffset = 0; + } + } + imgId++; + builder.element( + 'xdr:twoCellAnchor', + nest: () async { + builder.attribute('editAs', 'twoCell'); + builder.element( + 'xdr:from', + nest: () async { + builder.element('xdr:col', nest: picture.column - 1); + builder.element('xdr:colOff', nest: 0); + builder.element('xdr:row', nest: picture.row - 1); + builder.element('xdr:rowOff', nest: 0); + }, + ); - builder.element('xdr:spPr', nest: () async { - builder.element('a:xfrm', nest: () async { - if (picture.rotation != 0 && - picture.rotation <= 3600 && - picture.rotation >= -3600) { - builder.attribute('rot', picture.rotation * 60000); - } - if (picture.verticalFlip) { - builder.attribute('flipV', '1'); - } - if (picture.horizontalFlip) { - builder.attribute('flipH', '1'); - } - builder.element('a:off', nest: () async { - builder.attribute('x', '0'); - builder.attribute('y', '0'); - }); - builder.element('a:ext', nest: () async { - builder.attribute('cx', '0'); - builder.attribute('cy', '0'); - }); - }); + builder.element( + 'xdr:to', + nest: () async { + builder.element('xdr:col', nest: picture.lastColumn - 1); + builder.element( + 'xdr:colOff', + nest: picture.lastColOffset.round(), + ); + builder.element('xdr:row', nest: picture.lastRow - 1); + builder.element( + 'xdr:rowOff', + nest: picture.lastRowOffset.round(), + ); + }, + ); - builder.element('a:prstGeom', nest: () async { - builder.attribute('prst', 'rect'); - builder.element('a:avLst', nest: () async {}); - }); - }); - }); - builder.element('xdr:clientData', nest: () async {}); - }); - final List? imageData = picture.imageData; - _workbook.imageCount += 1; - String imgPath; - if (Picture.isJpeg(imageData)) { - imgPath = 'xl/media/image${_workbook.imageCount}.jpeg'; - if (!_workbook.defaultContentTypes.containsKey('jpeg')) { - _workbook.defaultContentTypes['jpeg'] = 'image/jpeg'; + builder.element( + 'xdr:pic', + nest: () async { + builder.attribute('macro', ''); + builder.element( + 'xdr:nvPicPr', + nest: () async { + builder.element( + 'xdr:cNvPr', + nest: () async { + builder.attribute('id', imgId); + builder.attribute('name', 'Picture$imgId'); + if (picture.isHyperlink) { + builder.element( + 'a:hlinkClick', + nest: () async { + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + int id = idIndex + imgId + idHyperlink; + String rId = 'rId$id'; + if (idRelation.contains(rId)) { + id = id + 1; + rId = 'rId$id'; + } + builder.attribute('r:id', rId); + idRelation.add(rId); + sheet.hyperlinkRelationId.add(rId); + idHyperlink++; + if (picture.hyperlink != null && + picture.hyperlink!.screenTip != null) { + builder.attribute( + 'tooltip', + // ignore: unnecessary_null_checks + picture.hyperlink!.screenTip!, + ); + } + }, + ); + } + }, + ); + builder.element( + 'xdr:cNvPicPr', + nest: () async { + builder.element( + 'a:picLocks', + nest: () async { + builder.attribute('noChangeAspect', 1); + }, + ); + }, + ); + }, + ); + + builder.element( + 'xdr:blipFill', + nest: () async { + builder.element( + 'a:blip', + nest: () async { + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + int id; + String rId; + if (idRelation.isEmpty) { + id = idIndex + imgId + hyperlinkCount; + rId = 'rId$id'; + builder.attribute('r:embed', rId); + idRelation.add(rId); + } else { + id = idIndex + imgId + hyperlinkCount; + rId = 'rId$id'; + if (idRelation.contains(rId)) { + id = id + 1; + rId = 'rId$id'; + if (idRelation.contains(rId)) { + id = id + 1; + rId = 'rId$id'; + } + } + builder.attribute('r:embed', rId); + idRelation.add(rId); + if (picture.isHyperlink) { + hyperlinkCount++; + } + } + builder.attribute('cstate', 'print'); + }, + ); + + builder.element( + 'a:stretch', + nest: () async { + builder.element('a:fillRect', nest: () async {}); + }, + ); + }, + ); + + builder.element( + 'xdr:spPr', + nest: () async { + builder.element( + 'a:xfrm', + nest: () async { + if (picture.rotation != 0 && + picture.rotation <= 3600 && + picture.rotation >= -3600) { + builder.attribute( + 'rot', + picture.rotation * 60000, + ); + } + if (picture.verticalFlip) { + builder.attribute('flipV', '1'); + } + if (picture.horizontalFlip) { + builder.attribute('flipH', '1'); + } + builder.element( + 'a:off', + nest: () async { + builder.attribute('x', '0'); + builder.attribute('y', '0'); + }, + ); + builder.element( + 'a:ext', + nest: () async { + builder.attribute('cx', '0'); + builder.attribute('cy', '0'); + }, + ); + }, + ); + + builder.element( + 'a:prstGeom', + nest: () async { + builder.attribute('prst', 'rect'); + builder.element('a:avLst', nest: () async {}); + }, + ); + }, + ); + }, + ); + builder.element('xdr:clientData', nest: () async {}); + }, + ); + final List? imageData = picture.imageData; + _workbook.imageCount += 1; + String imgPath; + if (Picture.isJpeg(imageData)) { + imgPath = 'xl/media/image${_workbook.imageCount}.jpeg'; + if (!_workbook.defaultContentTypes.containsKey('jpeg')) { + _workbook.defaultContentTypes['jpeg'] = 'image/jpeg'; + } + } else { + imgPath = 'xl/media/image${_workbook.imageCount}.png'; + if (!_workbook.defaultContentTypes.containsKey('png')) { + _workbook.defaultContentTypes['png'] = 'image/png'; + } } - } else { - imgPath = 'xl/media/image${_workbook.imageCount}.png'; - if (!_workbook.defaultContentTypes.containsKey('png')) { - _workbook.defaultContentTypes['png'] = 'image/png'; + if (imageData != null) { + _addToArchiveAsync(imageData, imgPath); } } - if (imageData != null) { - _addToArchiveAsync(imageData, imgPath); - } } - } - }); + }, + ); _saveDrawingRelationsAsync(sheet); final String stringXml = builder.buildDocument().copy().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync( - bytes, 'xl/drawings/drawing${_workbook.drawingCount}.xml'); + bytes, + 'xl/drawings/drawing${_workbook.drawingCount}.xml', + ); } /// Serialize drawing relations. @@ -2171,162 +2670,212 @@ class SerializeWorkbook { int idIndex = 0; final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/package/2006/relationships'); - if (sheet.chartCount != 0) { - final int length = sheet.chartCount; - for (int i = 1; i <= length; i++) { - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId${idIndex + i}'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'); - builder.attribute('Target', - '/xl/charts/chart${sheet.workbook.chartCount + i}.xml'); - }); - } - idIndex = length; - } - if (sheet.hyperlinks.count > 0) { - final int length = sheet.hyperlinks.count; - int j = 0; - for (int i = 0; i < length; i++) { - if (sheet.hyperlinks[i].attachedType == - ExcelHyperlinkAttachedType.shape) { - builder.element('Relationship', nest: () { - builder.attribute('Id', sheet.hyperlinkRelationId[j]); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'); - if (sheet.hyperlinks[i].type == HyperlinkType.workbook) { - String address = sheet.hyperlinks[i].address; - address = address.startsWith('#') ? address : '#$address'; - builder.attribute('Target', address); - } else { - builder.attribute('Target', sheet.hyperlinks[i].address); - } - if (sheet.hyperlinks[i].type != HyperlinkType.workbook) { - builder.attribute('TargetMode', 'External'); - } - }); - j++; + builder.element( + 'Relationships', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); + if (sheet.chartCount != 0) { + final int length = sheet.chartCount; + for (int i = 1; i <= length; i++) { + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId${idIndex + i}'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', + ); + builder.attribute( + 'Target', + '/xl/charts/chart${sheet.workbook.chartCount + i}.xml', + ); + }, + ); } + idIndex = length; } - } - if (sheet.pictures.count != 0) { - final int length = sheet.pictures.count; - int id = _workbook.imageCount - sheet.pictures.count; - int idHyperlink = 0; - for (int i = 1; i <= length; i++) { - id++; - builder.element('Relationship', nest: () { - String imgPath; - if (Picture.isPng(sheet.pictures[i - 1].imageData)) { - imgPath = '/xl/media/image$id.png'; - } else { - imgPath = '/xl/media/image$id.jpeg'; - } - if (sheet.pictures[i - 1].isHyperlink) { - builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); - builder.attribute('Target', imgPath); - idHyperlink++; - } else { - builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); - builder.attribute('Target', imgPath); + if (sheet.hyperlinks.count > 0) { + final int length = sheet.hyperlinks.count; + int j = 0; + for (int i = 0; i < length; i++) { + if (sheet.hyperlinks[i].attachedType == + ExcelHyperlinkAttachedType.shape) { + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', sheet.hyperlinkRelationId[j]); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', + ); + if (sheet.hyperlinks[i].type == HyperlinkType.workbook) { + String address = sheet.hyperlinks[i].address; + address = address.startsWith('#') ? address : '#$address'; + builder.attribute('Target', address); + } else { + builder.attribute('Target', sheet.hyperlinks[i].address); + } + if (sheet.hyperlinks[i].type != HyperlinkType.workbook) { + builder.attribute('TargetMode', 'External'); + } + }, + ); + j++; } - }); + } } - } - }); + if (sheet.pictures.count != 0) { + final int length = sheet.pictures.count; + int id = _workbook.imageCount - sheet.pictures.count; + int idHyperlink = 0; + for (int i = 1; i <= length; i++) { + id++; + builder.element( + 'Relationship', + nest: () { + String imgPath; + if (Picture.isPng(sheet.pictures[i - 1].imageData)) { + imgPath = '/xl/media/image$id.png'; + } else { + imgPath = '/xl/media/image$id.jpeg'; + } + if (sheet.pictures[i - 1].isHyperlink) { + builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + ); + builder.attribute('Target', imgPath); + idHyperlink++; + } else { + builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + ); + builder.attribute('Target', imgPath); + } + }, + ); + } + } + }, + ); final String stringXml = builder.buildDocument().copy().toString(); final List bytes = utf8.encode(stringXml); _addToArchive( - bytes, 'xl/drawings/_rels/drawing${_workbook.drawingCount}.xml.rels'); + bytes, + 'xl/drawings/_rels/drawing${_workbook.drawingCount}.xml.rels', + ); } Future _saveDrawingRelationsAsync(Worksheet sheet) async { int idIndex = 0; final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () async { - builder.namespace( - 'http://schemas.openxmlformats.org/package/2006/relationships'); - if (sheet.chartCount != 0) { - final int length = sheet.chartCount; - for (int i = 1; i <= length; i++) { - builder.element('Relationship', nest: () async { - builder.attribute('Id', 'rId${idIndex + i}'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'); - builder.attribute('Target', - '/xl/charts/chart${sheet.workbook.chartCount + i}.xml'); - }); - } - idIndex = length; - } - if (sheet.hyperlinks.count > 0) { - final int length = sheet.hyperlinks.count; - int j = 0; - for (int i = 0; i < length; i++) { - if (sheet.hyperlinks[i].attachedType == - ExcelHyperlinkAttachedType.shape) { - builder.element('Relationship', nest: () async { - builder.attribute('Id', sheet.hyperlinkRelationId[j]); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'); - if (sheet.hyperlinks[i].type == HyperlinkType.workbook) { - String address = sheet.hyperlinks[i].address; - address = address.startsWith('#') ? address : '#$address'; - builder.attribute('Target', address); - } else { - builder.attribute('Target', sheet.hyperlinks[i].address); - } - if (sheet.hyperlinks[i].type != HyperlinkType.workbook) { - builder.attribute('TargetMode', 'External'); - } - }); - j++; + builder.element( + 'Relationships', + nest: () async { + builder.namespace( + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); + if (sheet.chartCount != 0) { + final int length = sheet.chartCount; + for (int i = 1; i <= length; i++) { + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', 'rId${idIndex + i}'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', + ); + builder.attribute( + 'Target', + '/xl/charts/chart${sheet.workbook.chartCount + i}.xml', + ); + }, + ); } + idIndex = length; } - } - if (sheet.pictures.count != 0) { - final int length = sheet.pictures.count; - int id = _workbook.imageCount - sheet.pictures.count; - int idHyperlink = 0; - for (int i = 1; i <= length; i++) { - id++; - builder.element('Relationship', nest: () async { - String imgPath; - if (Picture.isPng(sheet.pictures[i - 1].imageData)) { - imgPath = '/xl/media/image$id.png'; - } else { - imgPath = '/xl/media/image$id.jpeg'; - } - if (sheet.pictures[i - 1].isHyperlink) { - builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); - builder.attribute('Target', imgPath); - idHyperlink++; - } else { - builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); - builder.attribute('Target', imgPath); + if (sheet.hyperlinks.count > 0) { + final int length = sheet.hyperlinks.count; + int j = 0; + for (int i = 0; i < length; i++) { + if (sheet.hyperlinks[i].attachedType == + ExcelHyperlinkAttachedType.shape) { + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', sheet.hyperlinkRelationId[j]); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', + ); + if (sheet.hyperlinks[i].type == HyperlinkType.workbook) { + String address = sheet.hyperlinks[i].address; + address = address.startsWith('#') ? address : '#$address'; + builder.attribute('Target', address); + } else { + builder.attribute('Target', sheet.hyperlinks[i].address); + } + if (sheet.hyperlinks[i].type != HyperlinkType.workbook) { + builder.attribute('TargetMode', 'External'); + } + }, + ); + j++; } - }); + } } - } - }); + if (sheet.pictures.count != 0) { + final int length = sheet.pictures.count; + int id = _workbook.imageCount - sheet.pictures.count; + int idHyperlink = 0; + for (int i = 1; i <= length; i++) { + id++; + builder.element( + 'Relationship', + nest: () async { + String imgPath; + if (Picture.isPng(sheet.pictures[i - 1].imageData)) { + imgPath = '/xl/media/image$id.png'; + } else { + imgPath = '/xl/media/image$id.jpeg'; + } + if (sheet.pictures[i - 1].isHyperlink) { + builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + ); + builder.attribute('Target', imgPath); + idHyperlink++; + } else { + builder.attribute('Id', 'rId${idIndex + i + idHyperlink}'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + ); + builder.attribute('Target', imgPath); + } + }, + ); + } + } + }, + ); final String stringXml = builder.buildDocument().copy().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync( - bytes, 'xl/drawings/_rels/drawing${_workbook.drawingCount}.xml.rels'); + bytes, + 'xl/drawings/_rels/drawing${_workbook.drawingCount}.xml.rels', + ); } /// Updates the picture shape last row offset. @@ -2340,9 +2889,9 @@ class SerializeWorkbook { if (sheet.rows.count != 0 && iCurRow - 1 < sheet.rows.count && sheet.rows[iCurRow] != null) { - iRowHeight = _convertToPixels((sheet.rows[iCurRow]!.height == 0) - ? 15 - : sheet.rows[iCurRow]!.height); + iRowHeight = _convertToPixels( + (sheet.rows[iCurRow]!.height == 0) ? 15 : sheet.rows[iCurRow]!.height, + ); } else { iRowHeight = _convertToPixels(15); } @@ -2356,9 +2905,11 @@ class SerializeWorkbook { if (sheet.rows.count != 0 && iCurRow < sheet.rows.count && sheet.rows[iCurRow] != null) { - rowHiddenHeight = _convertToPixels((sheet.rows[iCurRow]!.height == 0) - ? 15 - : sheet.rows[iCurRow]!.height); + rowHiddenHeight = _convertToPixels( + (sheet.rows[iCurRow]!.height == 0) + ? 15 + : sheet.rows[iCurRow]!.height, + ); } else { rowHiddenHeight = _convertToPixels(15); } @@ -2378,7 +2929,9 @@ class SerializeWorkbook { } Future _updateLastRowOffsetAsync( - Worksheet sheet, Picture picture) async { + Worksheet sheet, + Picture picture, + ) async { double iCurHeight = picture.height.toDouble(); int iCurRow = picture.row; int iCurOffset = 0; @@ -2388,9 +2941,9 @@ class SerializeWorkbook { if (sheet.rows.count != 0 && iCurRow - 1 < sheet.rows.count && sheet.rows[iCurRow] != null) { - iRowHeight = _convertToPixels((sheet.rows[iCurRow]!.height == 0) - ? 15 - : sheet.rows[iCurRow]!.height); + iRowHeight = _convertToPixels( + (sheet.rows[iCurRow]!.height == 0) ? 15 : sheet.rows[iCurRow]!.height, + ); } else { iRowHeight = _convertToPixels(15); } @@ -2404,9 +2957,11 @@ class SerializeWorkbook { if (sheet.rows.count != 0 && iCurRow < sheet.rows.count && sheet.rows[iCurRow] != null) { - rowHiddenHeight = _convertToPixels((sheet.rows[iCurRow]!.height == 0) - ? 15 - : sheet.rows[iCurRow]!.height); + rowHiddenHeight = _convertToPixels( + (sheet.rows[iCurRow]!.height == 0) + ? 15 + : sheet.rows[iCurRow]!.height, + ); } else { rowHiddenHeight = _convertToPixels(15); } @@ -2451,8 +3006,9 @@ class SerializeWorkbook { if (sheet.columns.count != 0 && iCurCol - 1 < sheet.columns.count && col != null) { - colHiddenWidth = - _columnWidthToPixels(col.width == 0 ? 8.43 : col.width); + colHiddenWidth = _columnWidthToPixels( + col.width == 0 ? 8.43 : col.width, + ); } else { colHiddenWidth = _columnWidthToPixels(8.43); } @@ -2473,7 +3029,9 @@ class SerializeWorkbook { } Future _updateLastColumnOffSetAsync( - Worksheet sheet, Picture picture) async { + Worksheet sheet, + Picture picture, + ) async { double iCurWidth = picture.width.toDouble(); int iCurCol = picture.column; double iCurOffset = 0; @@ -2498,8 +3056,9 @@ class SerializeWorkbook { if (sheet.columns.count != 0 && iCurCol - 1 < sheet.columns.count && col != null) { - colHiddenWidth = - _columnWidthToPixels(col.width == 0 ? 8.43 : col.width); + colHiddenWidth = _columnWidthToPixels( + col.width == 0 ? 8.43 : col.width, + ); } else { colHiddenWidth = _columnWidthToPixels(8.43); } @@ -2527,11 +3086,13 @@ class SerializeWorkbook { /// Converts column width to pixels. static double _columnWidthToPixels(double val) { const int dDigitWidth = 7; - final double fileWidth = (val > 1) - ? ((val * dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0 - : (val * (dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0; + final double fileWidth = + (val > 1) + ? ((val * dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0 + : (val * (dDigitWidth + 5) / dDigitWidth * 256.0) / 256.0; return _trunc( - ((256 * fileWidth + _trunc(128 / dDigitWidth)) / 256) * dDigitWidth); + ((256 * fileWidth + _trunc(128 / dDigitWidth)) / 256) * dDigitWidth, + ); } /// Trucates the given value. @@ -2544,221 +3105,279 @@ class SerializeWorkbook { List _saveSheetRelations(Worksheet sheet) { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/package/2006/relationships'); + builder.element( + 'Relationships', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); - if (sheet.hyperlinks.count > 0) { - int id = 1; - for (final Hyperlink link in sheet.hyperlinks.innerList) { - if (link.attachedType == ExcelHyperlinkAttachedType.range && - link.type != HyperlinkType.workbook) { - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId$id'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'); - builder.attribute('Target', link.address); - builder.attribute('TargetMode', 'External'); - }); - id++; + if (sheet.hyperlinks.count > 0) { + int id = 1; + for (final Hyperlink link in sheet.hyperlinks.innerList) { + if (link.attachedType == ExcelHyperlinkAttachedType.range && + link.type != HyperlinkType.workbook) { + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId$id'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', + ); + builder.attribute('Target', link.address); + builder.attribute('TargetMode', 'External'); + }, + ); + id++; + } } } - } - if (sheet.pictures.count > 0) { - builder.element('Relationship', nest: () { - int id = 1; - const String rId = 'rId1'; - if (_relationId.isNotEmpty) { - if (sheet.hyperlinks.count > 0) { - for (int i = 0; i < sheet.hyperlinks.count; i++) { - if (sheet.hyperlinks[i].attachedType == - ExcelHyperlinkAttachedType.range && - sheet.hyperlinks[i].type != HyperlinkType.workbook) { - id++; + if (sheet.pictures.count > 0) { + builder.element( + 'Relationship', + nest: () { + int id = 1; + const String rId = 'rId1'; + if (_relationId.isNotEmpty) { + if (sheet.hyperlinks.count > 0) { + for (int i = 0; i < sheet.hyperlinks.count; i++) { + if (sheet.hyperlinks[i].attachedType == + ExcelHyperlinkAttachedType.range && + sheet.hyperlinks[i].type != HyperlinkType.workbook) { + id++; + } + } } + builder.attribute('Id', 'rId$id'); + } else { + builder.attribute('Id', rId); } - } - builder.attribute('Id', 'rId$id'); - } else { - builder.attribute('Id', rId); - } - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing'); - builder.attribute( - 'Target', '../drawings/drawing${_workbook.drawingCount}.xml'); - }); - } else if (sheet.charts != null && sheet.chartCount > 0) { - builder.element('Relationship', nest: () { - int id = 1; - const String rId = 'rId1'; - if (_relationId.isNotEmpty) { - if (sheet.hyperlinks.count > 0) { - for (int i = 0; i < sheet.hyperlinks.count; i++) { - if (sheet.hyperlinks[i].attachedType == - ExcelHyperlinkAttachedType.range && - sheet.hyperlinks[i].type != HyperlinkType.workbook) { - id++; + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing', + ); + builder.attribute( + 'Target', + '../drawings/drawing${_workbook.drawingCount}.xml', + ); + }, + ); + } else if (sheet.charts != null && sheet.chartCount > 0) { + builder.element( + 'Relationship', + nest: () { + int id = 1; + const String rId = 'rId1'; + if (_relationId.isNotEmpty) { + if (sheet.hyperlinks.count > 0) { + for (int i = 0; i < sheet.hyperlinks.count; i++) { + if (sheet.hyperlinks[i].attachedType == + ExcelHyperlinkAttachedType.range && + sheet.hyperlinks[i].type != HyperlinkType.workbook) { + id++; + } + } } + builder.attribute('Id', 'rId$id'); + } else { + builder.attribute('Id', rId); } - } - builder.attribute('Id', 'rId$id'); - } else { - builder.attribute('Id', rId); - } - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing'); - builder.attribute( - 'Target', '../drawings/drawing${_workbook.drawingCount}.xml'); - }); - } - final int length = sheet.tableCollection.count; - int rid; - int index; - int id = 1; - if (length > 0) { - if (sheet.hyperlinks.count > 0) { - for (int hyperlinkCount = 0; + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing', + ); + builder.attribute( + 'Target', + '../drawings/drawing${_workbook.drawingCount}.xml', + ); + }, + ); + } + final int length = sheet.tableCollection.count; + int rid; + int index; + int id = 1; + if (length > 0) { + if (sheet.hyperlinks.count > 0) { + for ( + int hyperlinkCount = 0; hyperlinkCount < sheet.hyperlinks.count; - hyperlinkCount++) { - if (sheet.hyperlinks[hyperlinkCount].attachedType == - ExcelHyperlinkAttachedType.range && - sheet.hyperlinks[hyperlinkCount].type != - HyperlinkType.workbook) { - id++; + hyperlinkCount++ + ) { + if (sheet.hyperlinks[hyperlinkCount].attachedType == + ExcelHyperlinkAttachedType.range && + sheet.hyperlinks[hyperlinkCount].type != + HyperlinkType.workbook) { + id++; + } } } - } - if (sheet.pictures.count > 0) { - for (int pictureCount = 0; + if (sheet.pictures.count > 0) { + for ( + int pictureCount = 0; pictureCount < sheet.pictures.count; - pictureCount++) { - id++; + pictureCount++ + ) { + id++; + } } - } - if (sheet.chartCount > 0) { - for (int chartCount = 0; + if (sheet.chartCount > 0) { + for ( + int chartCount = 0; chartCount < sheet.chartCount; - chartCount++) { - id++; + chartCount++ + ) { + id++; + } } - } - for (int tableCount = _workbook.previousTableCount; + for ( + int tableCount = _workbook.previousTableCount; tableCount < _workbook.tableCount; - tableCount++) { - builder.element('Relationship', nest: () { - rid = id++; - index = tableCount + 1; - builder.attribute('Id', 'rId$rid'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table'); - builder.attribute('Target', '../tables/table$index.xml'); - }); + tableCount++ + ) { + builder.element( + 'Relationship', + nest: () { + rid = id++; + index = tableCount + 1; + builder.attribute('Id', 'rId$rid'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/table', + ); + builder.attribute('Target', '../tables/table$index.xml'); + }, + ); + } + _workbook.previousTableCount = _workbook.tableCount; } - _workbook.previousTableCount = _workbook.tableCount; - } - }); + }, + ); final String stringXml = builder.buildDocument().copy().toString(); return utf8.encode(stringXml); } /// Serialize sheet view. static void _saveSheetView(Worksheet sheet, XmlBuilder builder) { - builder.element('sheetViews', nest: () { - builder.element('sheetView', nest: () { - builder.attribute('workbookViewId', '0'); - if (sheet.isRightToLeft) { - builder.attribute('rightToLeft', '1'); - } - if (!sheet.showGridlines) { - builder.attribute('showGridLines', '0'); - } - if (sheet.isFreezePane || - sheet.verticalSplit != 0 || - sheet.horizontalSplit != 0) { - _savePane(sheet, builder); - } - }); - }); + builder.element( + 'sheetViews', + nest: () { + builder.element( + 'sheetView', + nest: () { + builder.attribute('workbookViewId', '0'); + if (sheet.isRightToLeft) { + builder.attribute('rightToLeft', '1'); + } + if (!sheet.showGridlines) { + builder.attribute('showGridLines', '0'); + } + if (sheet.isFreezePane || + sheet.verticalSplit != 0 || + sheet.horizontalSplit != 0) { + _savePane(sheet, builder); + } + }, + ); + }, + ); } static Future _saveSheetViewAsync( - Worksheet sheet, XmlBuilder builder) async { - builder.element('sheetViews', nest: () async { - builder.element('sheetView', nest: () async { - builder.attribute('workbookViewId', '0'); - if (sheet.isRightToLeft) { - builder.attribute('rightToLeft', '1'); - } - if (!sheet.showGridlines) { - builder.attribute('showGridLines', '0'); - } - if (sheet.isFreezePane || - sheet.verticalSplit != 0 || - sheet.horizontalSplit != 0) { - _savePaneAsync(sheet, builder); - } - }); - }); + Worksheet sheet, + XmlBuilder builder, + ) async { + builder.element( + 'sheetViews', + nest: () async { + builder.element( + 'sheetView', + nest: () async { + builder.attribute('workbookViewId', '0'); + if (sheet.isRightToLeft) { + builder.attribute('rightToLeft', '1'); + } + if (!sheet.showGridlines) { + builder.attribute('showGridLines', '0'); + } + if (sheet.isFreezePane || + sheet.verticalSplit != 0 || + sheet.horizontalSplit != 0) { + _savePaneAsync(sheet, builder); + } + }, + ); + }, + ); } /// Serialize worksheet Pane. static void _savePane(Worksheet sheet, XmlBuilder builder) { - builder.element('pane', nest: () { - if (sheet.verticalSplit != 0) { - builder.attribute('xSplit', sheet.verticalSplit.toString()); - } - if (sheet.horizontalSplit != 0) { - builder.attribute('ySplit', sheet.horizontalSplit.toString()); - } - if (sheet.topLeftCell != '') { - builder.attribute('topLeftCell', sheet.topLeftCell); - } - switch (sheet.activePane) { - case ActivePane.bottomRight: - builder.attribute('activePane', 'bottomRight'); - break; - case ActivePane.bottomLeft: - builder.attribute('activePane', 'bottomLeft'); - break; - case ActivePane.topRight: - builder.attribute('activePane', 'topRight'); - break; - case ActivePane.topLeft: - builder.attribute('activePane', 'topLeft'); - break; - } - builder.attribute('state', 'frozen'); - }); + builder.element( + 'pane', + nest: () { + if (sheet.verticalSplit != 0) { + builder.attribute('xSplit', sheet.verticalSplit.toString()); + } + if (sheet.horizontalSplit != 0) { + builder.attribute('ySplit', sheet.horizontalSplit.toString()); + } + if (sheet.topLeftCell != '') { + builder.attribute('topLeftCell', sheet.topLeftCell); + } + switch (sheet.activePane) { + case ActivePane.bottomRight: + builder.attribute('activePane', 'bottomRight'); + break; + case ActivePane.bottomLeft: + builder.attribute('activePane', 'bottomLeft'); + break; + case ActivePane.topRight: + builder.attribute('activePane', 'topRight'); + break; + case ActivePane.topLeft: + builder.attribute('activePane', 'topLeft'); + break; + } + builder.attribute('state', 'frozen'); + }, + ); } static Future _savePaneAsync( - Worksheet sheet, XmlBuilder builder) async { - builder.element('pane', nest: () async { - if (sheet.verticalSplit != 0) { - builder.attribute('xSplit', sheet.verticalSplit.toString()); - } - if (sheet.horizontalSplit != 0) { - builder.attribute('ySplit', sheet.horizontalSplit.toString()); - } - if (sheet.topLeftCell != '') { - builder.attribute('topLeftCell', sheet.topLeftCell); - } - switch (sheet.activePane) { - case ActivePane.bottomRight: - builder.attribute('activePane', 'bottomRight'); - break; - case ActivePane.bottomLeft: - builder.attribute('activePane', 'bottomLeft'); - break; - case ActivePane.topRight: - builder.attribute('activePane', 'topRight'); - break; - case ActivePane.topLeft: - builder.attribute('activePane', 'topLeft'); - break; - } - builder.attribute('state', 'frozen'); - }); + Worksheet sheet, + XmlBuilder builder, + ) async { + builder.element( + 'pane', + nest: () async { + if (sheet.verticalSplit != 0) { + builder.attribute('xSplit', sheet.verticalSplit.toString()); + } + if (sheet.horizontalSplit != 0) { + builder.attribute('ySplit', sheet.horizontalSplit.toString()); + } + if (sheet.topLeftCell != '') { + builder.attribute('topLeftCell', sheet.topLeftCell); + } + switch (sheet.activePane) { + case ActivePane.bottomRight: + builder.attribute('activePane', 'bottomRight'); + break; + case ActivePane.bottomLeft: + builder.attribute('activePane', 'bottomLeft'); + break; + case ActivePane.topRight: + builder.attribute('activePane', 'topRight'); + break; + case ActivePane.topLeft: + builder.attribute('activePane', 'topLeft'); + break; + } + builder.attribute('state', 'frozen'); + }, + ); } /// Serialize workbook shared string. @@ -2767,25 +3386,39 @@ class SerializeWorkbook { final int length = _workbook.sharedStrings.length; if (length > 0) { builder.processing('xml', 'version="1.0"'); - builder.element('sst', nest: () { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('uniqueCount', length.toString()); - builder.attribute('count', _workbook.sharedStringCount.toString()); - _workbook.sharedStrings.forEach((String key, int value) { - if (key.indexOf('') != 0) { - builder.element('si', nest: () { - builder.element('t', nest: () { - builder.text(key); - }); - }); - } else { - builder.element('si', nest: () { - builder.text(key); - }); - } - }); - }); + builder.element( + 'sst', + nest: () { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute('uniqueCount', length.toString()); + builder.attribute('count', _workbook.sharedStringCount.toString()); + _workbook.sharedStrings.forEach((String key, int value) { + if (key.indexOf('') != 0) { + builder.element( + 'si', + nest: () { + builder.element( + 't', + nest: () { + builder.text(key); + }, + ); + }, + ); + } else { + builder.element( + 'si', + nest: () { + builder.text(key); + }, + ); + } + }); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/sharedStrings.xml'); @@ -2797,25 +3430,39 @@ class SerializeWorkbook { final int length = _workbook.sharedStrings.length; if (length > 0) { builder.processing('xml', 'version="1.0"'); - builder.element('sst', nest: () async { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('uniqueCount', length.toString()); - builder.attribute('count', _workbook.sharedStringCount.toString()); - _workbook.sharedStrings.forEach((String key, int value) { - if (key.indexOf('') != 0) { - builder.element('si', nest: () async { - builder.element('t', nest: () async { - builder.text(key); - }); - }); - } else { - builder.element('si', nest: () async { - builder.text(key); - }); - } - }); - }); + builder.element( + 'sst', + nest: () async { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute('uniqueCount', length.toString()); + builder.attribute('count', _workbook.sharedStringCount.toString()); + _workbook.sharedStrings.forEach((String key, int value) { + if (key.indexOf('') != 0) { + builder.element( + 'si', + nest: () async { + builder.element( + 't', + nest: () async { + builder.text(key); + }, + ); + }, + ); + } else { + builder.element( + 'si', + nest: () async { + builder.text(key); + }, + ); + } + }); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'xl/sharedStrings.xml'); @@ -2827,19 +3474,24 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Properties', nest: () { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'); - builder.element('Application', nest: 'Essential XlsIO'); + builder.element( + 'Properties', + nest: () { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties', + ); + builder.element('Application', nest: 'Essential XlsIO'); - if (builtInProperties.manager != null) { - builder.element('Manager', nest: builtInProperties.manager); - } + if (builtInProperties.manager != null) { + builder.element('Manager', nest: builtInProperties.manager); + } - if (builtInProperties.company != null) { - builder.element('Company', nest: builtInProperties.company); - } - }); + if (builtInProperties.company != null) { + builder.element('Company', nest: builtInProperties.company); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'docProps/app.xml'); @@ -2849,83 +3501,107 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Properties', nest: () async { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'); - builder.element('Application', nest: 'Essential XlsIO'); + builder.element( + 'Properties', + nest: () async { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties', + ); + builder.element('Application', nest: 'Essential XlsIO'); - if (builtInProperties.manager != null) { - builder.element('Manager', nest: builtInProperties.manager); - } + if (builtInProperties.manager != null) { + builder.element('Manager', nest: builtInProperties.manager); + } - if (builtInProperties.company != null) { - builder.element('Company', nest: builtInProperties.company); - } - }); + if (builtInProperties.company != null) { + builder.element('Company', nest: builtInProperties.company); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'docProps/app.xml'); } /// Serialize core properties - void _saveCore(BuiltInProperties builtInProperties) { - final XmlBuilder builder = XmlBuilder(); - - builder.processing('xml', 'version="1.0"'); - builder.element('cp:coreProperties', nest: () { - builder.attribute('xmlns:cp', - 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); - builder.attribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); - builder.attribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); - builder.attribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); - builder.attribute( - 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - final DateTime createdDate = DateTime.now(); - - if (builtInProperties.author != null) { - builder.element('dc:creator', nest: builtInProperties.author); - } - if (builtInProperties.subject != null) { - builder.element('dc:subject', nest: builtInProperties.subject); - } - if (builtInProperties.category != null) { - builder.element('dc:category', nest: builtInProperties.category); - } - if (builtInProperties.comments != null) { - builder.element('dc:description', nest: builtInProperties.comments); - } - if (builtInProperties.title != null) { - builder.element('dc:title', nest: builtInProperties.title); - } - if (builtInProperties.tags != null) { - builder.element('dc:keywords', nest: builtInProperties.tags); - } - if (builtInProperties.status != null) { - builder.element('dc:contentStatus', nest: builtInProperties.status); - } - if (builtInProperties.createdDate != null) { - builder.element('dcterms:created', nest: () { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(builtInProperties.createdDate!.toIso8601String()); - }); - } else { - builder.element('dcterms:created', nest: () { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(createdDate.toIso8601String()); - }); - } - if (builtInProperties.modifiedDate != null) { - builder.element('dcterms:modified', nest: () { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(builtInProperties.modifiedDate!.toIso8601String()); - }); - } else { - builder.element('dcterms:modified', nest: () { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(createdDate.toIso8601String()); - }); - } - }); + void _saveCore(BuiltInProperties builtInProperties) { + final XmlBuilder builder = XmlBuilder(); + + builder.processing('xml', 'version="1.0"'); + builder.element( + 'cp:coreProperties', + nest: () { + builder.attribute( + 'xmlns:cp', + 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties', + ); + builder.attribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + builder.attribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); + builder.attribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); + builder.attribute( + 'xmlns:xsi', + 'http://www.w3.org/2001/XMLSchema-instance', + ); + final DateTime createdDate = DateTime.now(); + + if (builtInProperties.author != null) { + builder.element('dc:creator', nest: builtInProperties.author); + } + if (builtInProperties.subject != null) { + builder.element('dc:subject', nest: builtInProperties.subject); + } + if (builtInProperties.category != null) { + builder.element('dc:category', nest: builtInProperties.category); + } + if (builtInProperties.comments != null) { + builder.element('dc:description', nest: builtInProperties.comments); + } + if (builtInProperties.title != null) { + builder.element('dc:title', nest: builtInProperties.title); + } + if (builtInProperties.tags != null) { + builder.element('dc:keywords', nest: builtInProperties.tags); + } + if (builtInProperties.status != null) { + builder.element('dc:contentStatus', nest: builtInProperties.status); + } + if (builtInProperties.createdDate != null) { + builder.element( + 'dcterms:created', + nest: () { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(builtInProperties.createdDate!.toIso8601String()); + }, + ); + } else { + builder.element( + 'dcterms:created', + nest: () { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(createdDate.toIso8601String()); + }, + ); + } + if (builtInProperties.modifiedDate != null) { + builder.element( + 'dcterms:modified', + nest: () { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(builtInProperties.modifiedDate!.toIso8601String()); + }, + ); + } else { + builder.element( + 'dcterms:modified', + nest: () { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(createdDate.toIso8601String()); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'docProps/core.xml'); @@ -2935,60 +3611,79 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('cp:coreProperties', nest: () async { - builder.attribute('xmlns:cp', - 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); - builder.attribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); - builder.attribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); - builder.attribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); - builder.attribute( - 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); - final DateTime createdDate = DateTime.now(); - - if (builtInProperties.author != null) { - builder.element('dc:creator', nest: builtInProperties.author); - } - if (builtInProperties.subject != null) { - builder.element('dc:subject', nest: builtInProperties.subject); - } - if (builtInProperties.category != null) { - builder.element('dc:category', nest: builtInProperties.category); - } - if (builtInProperties.comments != null) { - builder.element('dc:description', nest: builtInProperties.comments); - } - if (builtInProperties.title != null) { - builder.element('dc:title', nest: builtInProperties.title); - } - if (builtInProperties.tags != null) { - builder.element('dc:keywords', nest: builtInProperties.tags); - } - if (builtInProperties.status != null) { - builder.element('dc:contentStatus', nest: builtInProperties.status); - } - if (builtInProperties.createdDate != null) { - builder.element('dcterms:created', nest: () async { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(builtInProperties.createdDate!.toIso8601String()); - }); - } else { - builder.element('dcterms:created', nest: () async { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(createdDate.toIso8601String()); - }); - } - if (builtInProperties.modifiedDate != null) { - builder.element('dcterms:modified', nest: () async { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(builtInProperties.modifiedDate!.toIso8601String()); - }); - } else { - builder.element('dcterms:modified', nest: () async { - builder.attribute('xsi:type', 'dcterms:W3CDTF'); - builder.text(createdDate.toIso8601String()); - }); - } - }); + builder.element( + 'cp:coreProperties', + nest: () async { + builder.attribute( + 'xmlns:cp', + 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties', + ); + builder.attribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + builder.attribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); + builder.attribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); + builder.attribute( + 'xmlns:xsi', + 'http://www.w3.org/2001/XMLSchema-instance', + ); + final DateTime createdDate = DateTime.now(); + + if (builtInProperties.author != null) { + builder.element('dc:creator', nest: builtInProperties.author); + } + if (builtInProperties.subject != null) { + builder.element('dc:subject', nest: builtInProperties.subject); + } + if (builtInProperties.category != null) { + builder.element('dc:category', nest: builtInProperties.category); + } + if (builtInProperties.comments != null) { + builder.element('dc:description', nest: builtInProperties.comments); + } + if (builtInProperties.title != null) { + builder.element('dc:title', nest: builtInProperties.title); + } + if (builtInProperties.tags != null) { + builder.element('dc:keywords', nest: builtInProperties.tags); + } + if (builtInProperties.status != null) { + builder.element('dc:contentStatus', nest: builtInProperties.status); + } + if (builtInProperties.createdDate != null) { + builder.element( + 'dcterms:created', + nest: () async { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(builtInProperties.createdDate!.toIso8601String()); + }, + ); + } else { + builder.element( + 'dcterms:created', + nest: () async { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(createdDate.toIso8601String()); + }, + ); + } + if (builtInProperties.modifiedDate != null) { + builder.element( + 'dcterms:modified', + nest: () async { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(builtInProperties.modifiedDate!.toIso8601String()); + }, + ); + } else { + builder.element( + 'dcterms:modified', + nest: () async { + builder.attribute('xsi:type', 'dcterms:W3CDTF'); + builder.text(createdDate.toIso8601String()); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'docProps/core.xml'); @@ -2998,107 +3693,175 @@ class SerializeWorkbook { void _saveContentType() { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Types', nest: () { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/package/2006/content-types'); - - builder.element('Default', nest: () { - builder.attribute('Extension', 'xml'); - builder.attribute('ContentType', 'application/xml'); - }); - builder.element('Default', nest: () { - builder.attribute('Extension', 'rels'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-package.relationships+xml'); - }); - builder.element('Override', nest: () { - builder.attribute('PartName', '/xl/styles.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); - }); - builder.element('Override', nest: () { - builder.attribute('PartName', '/xl/workbook.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); - }); - builder.element('Override', nest: () { - builder.attribute('PartName', '/docProps/app.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); - }); - builder.element('Override', nest: () { - builder.attribute('PartName', '/docProps/core.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-package.core-properties+xml'); - }); - final int length = _workbook.worksheets.count; - int drawingIndex = 1; - int chartIndex = 1; - for (int i = 0; i < length; i++) { - final int index = i + 1; - builder.element('Override', nest: () { - builder.attribute('PartName', '/xl/worksheets/sheet$index.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); - }); - if ((_workbook.imageCount > 0 && - _workbook.worksheets[i].pictures.count > 0) || - _workbook.worksheets[i].charts != null && + builder.element( + 'Types', + nest: () { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/package/2006/content-types', + ); + + builder.element( + 'Default', + nest: () { + builder.attribute('Extension', 'xml'); + builder.attribute('ContentType', 'application/xml'); + }, + ); + builder.element( + 'Default', + nest: () { + builder.attribute('Extension', 'rels'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-package.relationships+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/xl/styles.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/xl/workbook.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/docProps/app.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.extended-properties+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/docProps/core.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-package.core-properties+xml', + ); + }, + ); + final int length = _workbook.worksheets.count; + int drawingIndex = 1; + int chartIndex = 1; + for (int i = 0; i < length; i++) { + final int index = i + 1; + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/xl/worksheets/sheet$index.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml', + ); + }, + ); + if ((_workbook.imageCount > 0 && + _workbook.worksheets[i].pictures.count > 0) || + _workbook.worksheets[i].charts != null && + _workbook.worksheets[i].chartCount > 0) { + if (_workbook.worksheets[i].charts != null && _workbook.worksheets[i].chartCount > 0) { - if (_workbook.worksheets[i].charts != null && - _workbook.worksheets[i].chartCount > 0) { - final int chartCount = _workbook.worksheets[i].chartCount; - for (int index = 1; index <= chartCount; index++) { - builder.element('Override', nest: () { - builder.attribute( - 'PartName', '/xl/charts/chart$chartIndex.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); - }); - chartIndex++; + final int chartCount = _workbook.worksheets[i].chartCount; + for (int index = 1; index <= chartCount; index++) { + builder.element( + 'Override', + nest: () { + builder.attribute( + 'PartName', + '/xl/charts/chart$chartIndex.xml', + ); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml', + ); + }, + ); + chartIndex++; + } } + builder.element( + 'Override', + nest: () { + builder.attribute( + 'PartName', + '/xl/drawings/drawing$drawingIndex.xml', + ); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.drawing+xml', + ); + }, + ); + drawingIndex++; } - builder.element('Override', nest: () { - builder.attribute( - 'PartName', '/xl/drawings/drawing$drawingIndex.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.drawing+xml'); - }); - drawingIndex++; } - } - for (int tableCount = 0; + for ( + int tableCount = 0; tableCount < _workbook.tableCount; - tableCount++) { - final int tableIndex = tableCount + 1; - builder.element('Override', nest: () { - builder.attribute('PartName', '/xl/tables/table$tableIndex.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml'); - }); - } - - if (_workbook.imageCount > 0) { - for (final dynamic key in _workbook.defaultContentType.keys) { - builder.element('Default', nest: () { - builder.attribute('Extension', key); - builder.attribute( + tableCount++ + ) { + final int tableIndex = tableCount + 1; + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/xl/tables/table$tableIndex.xml'); + builder.attribute( 'ContentType', - // ignore: unnecessary_null_checks - _workbook.defaultContentTypes[key]!); - }); + 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml', + ); + }, + ); + } + + if (_workbook.imageCount > 0) { + for (final dynamic key in _workbook.defaultContentType.keys) { + builder.element( + 'Default', + nest: () { + builder.attribute('Extension', key); + builder.attribute( + 'ContentType', + // ignore: unnecessary_null_checks + _workbook.defaultContentTypes[key]!, + ); + }, + ); + } } - } - if (_workbook.sharedStringCount > 0) { - builder.element('Override', nest: () { - builder.attribute('PartName', '/xl/sharedStrings.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); - }); - } - }); + if (_workbook.sharedStringCount > 0) { + builder.element( + 'Override', + nest: () { + builder.attribute('PartName', '/xl/sharedStrings.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml', + ); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, '[Content_Types].xml'); @@ -3107,107 +3870,175 @@ class SerializeWorkbook { Future _saveContentTypeAsync() async { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Types', nest: () async { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/package/2006/content-types'); - - builder.element('Default', nest: () async { - builder.attribute('Extension', 'xml'); - builder.attribute('ContentType', 'application/xml'); - }); - builder.element('Default', nest: () async { - builder.attribute('Extension', 'rels'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-package.relationships+xml'); - }); - builder.element('Override', nest: () async { - builder.attribute('PartName', '/xl/styles.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); - }); - builder.element('Override', nest: () async { - builder.attribute('PartName', '/xl/workbook.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); - }); - builder.element('Override', nest: () async { - builder.attribute('PartName', '/docProps/app.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); - }); - builder.element('Override', nest: () async { - builder.attribute('PartName', '/docProps/core.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-package.core-properties+xml'); - }); - final int length = _workbook.worksheets.count; - int drawingIndex = 1; - int chartIndex = 1; - for (int i = 0; i < length; i++) { - final int index = i + 1; - builder.element('Override', nest: () async { - builder.attribute('PartName', '/xl/worksheets/sheet$index.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); - }); - if ((_workbook.imageCount > 0 && - _workbook.worksheets[i].pictures.count > 0) || - _workbook.worksheets[i].charts != null && + builder.element( + 'Types', + nest: () async { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/package/2006/content-types', + ); + + builder.element( + 'Default', + nest: () async { + builder.attribute('Extension', 'xml'); + builder.attribute('ContentType', 'application/xml'); + }, + ); + builder.element( + 'Default', + nest: () async { + builder.attribute('Extension', 'rels'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-package.relationships+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/xl/styles.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/xl/workbook.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/docProps/app.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.extended-properties+xml', + ); + }, + ); + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/docProps/core.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-package.core-properties+xml', + ); + }, + ); + final int length = _workbook.worksheets.count; + int drawingIndex = 1; + int chartIndex = 1; + for (int i = 0; i < length; i++) { + final int index = i + 1; + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/xl/worksheets/sheet$index.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml', + ); + }, + ); + if ((_workbook.imageCount > 0 && + _workbook.worksheets[i].pictures.count > 0) || + _workbook.worksheets[i].charts != null && + _workbook.worksheets[i].chartCount > 0) { + if (_workbook.worksheets[i].charts != null && _workbook.worksheets[i].chartCount > 0) { - if (_workbook.worksheets[i].charts != null && - _workbook.worksheets[i].chartCount > 0) { - final int chartCount = _workbook.worksheets[i].chartCount; - for (int index = 1; index <= chartCount; index++) { - builder.element('Override', nest: () async { - builder.attribute( - 'PartName', '/xl/charts/chart$chartIndex.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); - }); - chartIndex++; + final int chartCount = _workbook.worksheets[i].chartCount; + for (int index = 1; index <= chartCount; index++) { + builder.element( + 'Override', + nest: () async { + builder.attribute( + 'PartName', + '/xl/charts/chart$chartIndex.xml', + ); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml', + ); + }, + ); + chartIndex++; + } } + builder.element( + 'Override', + nest: () async { + builder.attribute( + 'PartName', + '/xl/drawings/drawing$drawingIndex.xml', + ); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.drawing+xml', + ); + }, + ); + drawingIndex++; } - builder.element('Override', nest: () async { - builder.attribute( - 'PartName', '/xl/drawings/drawing$drawingIndex.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.drawing+xml'); - }); - drawingIndex++; } - } - for (int tableCount = 0; + for ( + int tableCount = 0; tableCount < _workbook.tableCount; - tableCount++) { - final int tableIndex = tableCount + 1; - builder.element('Override', nest: () async { - builder.attribute('PartName', '/xl/tables/table$tableIndex.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml'); - }); - } - - if (_workbook.imageCount > 0) { - for (final dynamic key in _workbook.defaultContentType.keys) { - builder.element('Default', nest: () async { - builder.attribute('Extension', key); - builder.attribute( + tableCount++ + ) { + final int tableIndex = tableCount + 1; + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/xl/tables/table$tableIndex.xml'); + builder.attribute( 'ContentType', - // ignore: unnecessary_null_checks - _workbook.defaultContentTypes[key]!); - }); + 'application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml', + ); + }, + ); + } + + if (_workbook.imageCount > 0) { + for (final dynamic key in _workbook.defaultContentType.keys) { + builder.element( + 'Default', + nest: () async { + builder.attribute('Extension', key); + builder.attribute( + 'ContentType', + // ignore: unnecessary_null_checks + _workbook.defaultContentTypes[key]!, + ); + }, + ); + } } - } - if (_workbook.sharedStringCount > 0) { - builder.element('Override', nest: () async { - builder.attribute('PartName', '/xl/sharedStrings.xml'); - builder.attribute('ContentType', - 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); - }); - } - }); + if (_workbook.sharedStringCount > 0) { + builder.element( + 'Override', + nest: () async { + builder.attribute('PartName', '/xl/sharedStrings.xml'); + builder.attribute( + 'ContentType', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml', + ); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, '[Content_Types].xml'); @@ -3218,39 +4049,59 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/package/2006/relationships'); - - final int length = _workbook.worksheets.count; - int count = 0; - int index; - for (int i = 0; i < length; i++, count++) { - builder.element('Relationship', nest: () { - index = i + 1; - builder.attribute('Id', 'rId$index'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet'); - builder.attribute('Target', 'worksheets/sheet$index.xml'); - }); - } - count = ++count; - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId$count'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles'); - builder.attribute('Target', 'styles.xml'); - }); - if (_workbook.sharedStringCount > 0) { + builder.element( + 'Relationships', + nest: () { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); + + final int length = _workbook.worksheets.count; + int count = 0; + int index; + for (int i = 0; i < length; i++, count++) { + builder.element( + 'Relationship', + nest: () { + index = i + 1; + builder.attribute('Id', 'rId$index'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', + ); + builder.attribute('Target', 'worksheets/sheet$index.xml'); + }, + ); + } count = ++count; - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId$count'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings'); - builder.attribute('Target', 'sharedStrings.xml'); - }); - } - }); + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId$count'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', + ); + builder.attribute('Target', 'styles.xml'); + }, + ); + if (_workbook.sharedStringCount > 0) { + count = ++count; + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId$count'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', + ); + builder.attribute('Target', 'sharedStrings.xml'); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/_rels/workbook.xml.rels'); @@ -3260,39 +4111,59 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () async { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/package/2006/relationships'); - - final int length = _workbook.worksheets.count; - int count = 0; - int index; - for (int i = 0; i < length; i++, count++) { - builder.element('Relationship', nest: () async { - index = i + 1; - builder.attribute('Id', 'rId$index'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet'); - builder.attribute('Target', 'worksheets/sheet$index.xml'); - }); - } - count = ++count; - builder.element('Relationship', nest: () async { - builder.attribute('Id', 'rId$count'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles'); - builder.attribute('Target', 'styles.xml'); - }); - if (_workbook.sharedStringCount > 0) { + builder.element( + 'Relationships', + nest: () async { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); + + final int length = _workbook.worksheets.count; + int count = 0; + int index; + for (int i = 0; i < length; i++, count++) { + builder.element( + 'Relationship', + nest: () async { + index = i + 1; + builder.attribute('Id', 'rId$index'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', + ); + builder.attribute('Target', 'worksheets/sheet$index.xml'); + }, + ); + } count = ++count; - builder.element('Relationship', nest: () async { - builder.attribute('Id', 'rId$count'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings'); - builder.attribute('Target', 'sharedStrings.xml'); - }); - } - }); + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', 'rId$count'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', + ); + builder.attribute('Target', 'styles.xml'); + }, + ); + if (_workbook.sharedStringCount > 0) { + count = ++count; + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', 'rId$count'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', + ); + builder.attribute('Target', 'sharedStrings.xml'); + }, + ); + } + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'xl/_rels/workbook.xml.rels'); @@ -3303,31 +4174,51 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/package/2006/relationships'); - - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId1'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument'); - builder.attribute('Target', 'xl/workbook.xml'); - }); - - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId2'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties'); - builder.attribute('Target', 'docProps/app.xml'); - }); - - builder.element('Relationship', nest: () { - builder.attribute('Id', 'rId3'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'); - builder.attribute('Target', 'docProps/core.xml'); - }); - }); + builder.element( + 'Relationships', + nest: () { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); + + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId1'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', + ); + builder.attribute('Target', 'xl/workbook.xml'); + }, + ); + + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId2'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties', + ); + builder.attribute('Target', 'docProps/app.xml'); + }, + ); + + builder.element( + 'Relationship', + nest: () { + builder.attribute('Id', 'rId3'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', + ); + builder.attribute('Target', 'docProps/core.xml'); + }, + ); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, '_rels/.rels'); @@ -3337,31 +4228,51 @@ class SerializeWorkbook { final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('Relationships', nest: () async { - builder.attribute('xmlns', - 'http://schemas.openxmlformats.org/package/2006/relationships'); - - builder.element('Relationship', nest: () async { - builder.attribute('Id', 'rId1'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument'); - builder.attribute('Target', 'xl/workbook.xml'); - }); - - builder.element('Relationship', nest: () async { - builder.attribute('Id', 'rId2'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties'); - builder.attribute('Target', 'docProps/app.xml'); - }); - - builder.element('Relationship', nest: () async { - builder.attribute('Id', 'rId3'); - builder.attribute('Type', - 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'); - builder.attribute('Target', 'docProps/core.xml'); - }); - }); + builder.element( + 'Relationships', + nest: () async { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/package/2006/relationships', + ); + + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', 'rId1'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', + ); + builder.attribute('Target', 'xl/workbook.xml'); + }, + ); + + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', 'rId2'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties', + ); + builder.attribute('Target', 'docProps/app.xml'); + }, + ); + + builder.element( + 'Relationship', + nest: () async { + builder.attribute('Id', 'rId3'); + builder.attribute( + 'Type', + 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', + ); + builder.attribute('Target', 'docProps/core.xml'); + }, + ); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, '_rels/.rels'); @@ -3372,24 +4283,33 @@ class SerializeWorkbook { _updateCellStyleXfs(); final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('styleSheet', nest: () { - builder.attribute( - 'xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('xmlns:mc', - 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - builder.attribute('mc:Ignorable', 'x14ac'); - builder.attribute('xmlns:x14ac', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'); - - _saveNumberFormats(builder); - _saveFonts(builder); - _saveFills(builder); - _saveBorders(builder); - _saveCellStyleXfs(builder); - _saveCellXfs(builder); - _saveGlobalCellstyles(builder); - _serialiseDxfs(builder); - }); + builder.element( + 'styleSheet', + nest: () { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute( + 'xmlns:mc', + 'http://schemas.openxmlformats.org/markup-compatibility/2006', + ); + builder.attribute('mc:Ignorable', 'x14ac'); + builder.attribute( + 'xmlns:x14ac', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac', + ); + + _saveNumberFormats(builder); + _saveFonts(builder); + _saveFills(builder); + _saveBorders(builder); + _saveCellStyleXfs(builder); + _saveCellXfs(builder); + _saveGlobalCellstyles(builder); + _serialiseDxfs(builder); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/styles.xml'); @@ -3399,24 +4319,33 @@ class SerializeWorkbook { _updateCellStyleXfsAsync(); final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('styleSheet', nest: () async { - builder.attribute( - 'xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('xmlns:mc', - 'http://schemas.openxmlformats.org/markup-compatibility/2006'); - builder.attribute('mc:Ignorable', 'x14ac'); - builder.attribute('xmlns:x14ac', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac'); - - _saveNumberFormatsAsync(builder); - _saveFontsAsync(builder); - _saveFillsAsync(builder); - _saveBordersAsync(builder); - _saveCellStyleXfsAsync(builder); - _saveCellXfsAsync(builder); - _saveGlobalCellstylesAsync(builder); - _serialiseDxfsAsync(builder); - }); + builder.element( + 'styleSheet', + nest: () async { + builder.attribute( + 'xmlns', + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute( + 'xmlns:mc', + 'http://schemas.openxmlformats.org/markup-compatibility/2006', + ); + builder.attribute('mc:Ignorable', 'x14ac'); + builder.attribute( + 'xmlns:x14ac', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac', + ); + + _saveNumberFormatsAsync(builder); + _saveFontsAsync(builder); + _saveFillsAsync(builder); + _saveBordersAsync(builder); + _saveCellStyleXfsAsync(builder); + _saveCellXfsAsync(builder); + _saveGlobalCellstylesAsync(builder); + _serialiseDxfsAsync(builder); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'xl/styles.xml'); @@ -3555,8 +4484,9 @@ class SerializeWorkbook { final Format format = _workbook.innerFormats[style.numberFormatIndex]; cellXfs.numberFormatId = format.index; } else { - cellXfs.numberFormatId = - _workbook.innerFormats.createFormat(style.numberFormat); + cellXfs.numberFormatId = _workbook.innerFormats.createFormat( + style.numberFormat, + ); } } else { if (style.numberFormat == 'GENERAL' && style.numberFormatIndex == 14) { @@ -3568,10 +4498,16 @@ class SerializeWorkbook { //Add alignment cellXfs.alignment = Alignment(); cellXfs.alignment!.indent = style.indent; - cellXfs.alignment!.horizontal = - style.hAlign.toString().split('.').toList().removeAt(1); - cellXfs.alignment!.vertical = - style.vAlign.toString().split('.').toList().removeAt(1); + cellXfs.alignment!.horizontal = style.hAlign + .toString() + .split('.') + .toList() + .removeAt(1); + cellXfs.alignment!.vertical = style.vAlign + .toString() + .split('.') + .toList() + .removeAt(1); cellXfs.alignment!.wrapText = style.wrapText ? 1 : 0; cellXfs.alignment!.rotation = style.rotation; @@ -3658,8 +4594,9 @@ class SerializeWorkbook { final Format format = _workbook.innerFormats[style.numberFormatIndex]; cellXfs.numberFormatId = format.index; } else { - cellXfs.numberFormatId = - _workbook.innerFormats.createFormat(style.numberFormat); + cellXfs.numberFormatId = _workbook.innerFormats.createFormat( + style.numberFormat, + ); } } else { if (style.numberFormat == 'GENERAL' && style.numberFormatIndex == 14) { @@ -3671,10 +4608,16 @@ class SerializeWorkbook { //Add alignment cellXfs.alignment = Alignment(); cellXfs.alignment!.indent = style.indent; - cellXfs.alignment!.horizontal = - style.hAlign.toString().split('.').toList().removeAt(1); - cellXfs.alignment!.vertical = - style.vAlign.toString().split('.').toList().removeAt(1); + cellXfs.alignment!.horizontal = style.hAlign + .toString() + .split('.') + .toList() + .removeAt(1); + cellXfs.alignment!.vertical = style.vAlign + .toString() + .split('.') + .toList() + .removeAt(1); cellXfs.alignment!.wrapText = style.wrapText ? 1 : 0; cellXfs.alignment!.rotation = style.rotation; @@ -3696,476 +4639,712 @@ class SerializeWorkbook { void _saveNumberFormats(XmlBuilder builder) { final List arrFormats = _workbook.innerFormats.getUsedFormats(); if (arrFormats.isNotEmpty) { - builder.element('numFmts', nest: () { - builder.attribute('count', arrFormats.length.toString()); - for (int i = 0; i < arrFormats.length; i++) { - builder.element('numFmt', nest: () { - builder.attribute('numFmtId', arrFormats[i].index.toString()); - final String formatString = - arrFormats[i].formatString!.replaceAll("'", '"'); - builder.attribute('formatCode', formatString); - }); - } - }); + builder.element( + 'numFmts', + nest: () { + builder.attribute('count', arrFormats.length.toString()); + for (int i = 0; i < arrFormats.length; i++) { + builder.element( + 'numFmt', + nest: () { + builder.attribute('numFmtId', arrFormats[i].index.toString()); + final String formatString = arrFormats[i].formatString! + .replaceAll("'", '"'); + builder.attribute('formatCode', formatString); + }, + ); + } + }, + ); } } Future _saveNumberFormatsAsync(XmlBuilder builder) async { final List arrFormats = _workbook.innerFormats.getUsedFormats(); if (arrFormats.isNotEmpty) { - builder.element('numFmts', nest: () async { - builder.attribute('count', arrFormats.length.toString()); - for (int i = 0; i < arrFormats.length; i++) { - builder.element('numFmt', nest: () async { - builder.attribute('numFmtId', arrFormats[i].index.toString()); - final String formatString = - arrFormats[i].formatString!.replaceAll("'", '"'); - builder.attribute('formatCode', formatString); - }); - } - }); + builder.element( + 'numFmts', + nest: () async { + builder.attribute('count', arrFormats.length.toString()); + for (int i = 0; i < arrFormats.length; i++) { + builder.element( + 'numFmt', + nest: () async { + builder.attribute('numFmtId', arrFormats[i].index.toString()); + final String formatString = arrFormats[i].formatString! + .replaceAll("'", '"'); + builder.attribute('formatCode', formatString); + }, + ); + } + }, + ); } } /// Serialize fonts. void _saveFonts(XmlBuilder builder) { - builder.element('fonts', nest: () { - builder.attribute('count', _workbook.fonts.length.toString()); - if (_workbook.fonts.isNotEmpty) { - for (int i = 0; i < _workbook.fonts.length; i++) { - final Font font = _workbook.fonts[i]; - builder.element('font', nest: () { - if (font.bold) { - builder.element('b', nest: () {}); - } - if (font.italic) { - builder.element('i', nest: () {}); - } - if (font.underline) { - builder.element('u', nest: () {}); - } - builder.element('sz', nest: () { - builder.attribute('val', font.size.toString()); - }); - builder.element('color', nest: () { - builder.attribute('rgb', font.color); - }); - builder.element('name', nest: () { - builder.attribute('val', font.name); - }); - }); + builder.element( + 'fonts', + nest: () { + builder.attribute('count', _workbook.fonts.length.toString()); + if (_workbook.fonts.isNotEmpty) { + for (int i = 0; i < _workbook.fonts.length; i++) { + final Font font = _workbook.fonts[i]; + builder.element( + 'font', + nest: () { + if (font.bold) { + builder.element('b', nest: () {}); + } + if (font.italic) { + builder.element('i', nest: () {}); + } + if (font.underline) { + builder.element('u', nest: () {}); + } + builder.element( + 'sz', + nest: () { + builder.attribute('val', font.size.toString()); + }, + ); + builder.element( + 'color', + nest: () { + builder.attribute('rgb', font.color); + }, + ); + builder.element( + 'name', + nest: () { + builder.attribute('val', font.name); + }, + ); + }, + ); + } } - } - }); + }, + ); } Future _saveFontsAsync(XmlBuilder builder) async { - builder.element('fonts', nest: () async { - builder.attribute('count', _workbook.fonts.length.toString()); - if (_workbook.fonts.isNotEmpty) { - for (int i = 0; i < _workbook.fonts.length; i++) { - final Font font = _workbook.fonts[i]; - builder.element('font', nest: () async { - if (font.bold) { - builder.element('b', nest: () async {}); - } - if (font.italic) { - builder.element('i', nest: () async {}); - } - if (font.underline) { - builder.element('u', nest: () async {}); - } - builder.element('sz', nest: () async { - builder.attribute('val', font.size.toString()); - }); - builder.element('color', nest: () async { - builder.attribute('rgb', font.color); - }); - builder.element('name', nest: () async { - builder.attribute('val', font.name); - }); - }); + builder.element( + 'fonts', + nest: () async { + builder.attribute('count', _workbook.fonts.length.toString()); + if (_workbook.fonts.isNotEmpty) { + for (int i = 0; i < _workbook.fonts.length; i++) { + final Font font = _workbook.fonts[i]; + builder.element( + 'font', + nest: () async { + if (font.bold) { + builder.element('b', nest: () async {}); + } + if (font.italic) { + builder.element('i', nest: () async {}); + } + if (font.underline) { + builder.element('u', nest: () async {}); + } + builder.element( + 'sz', + nest: () async { + builder.attribute('val', font.size.toString()); + }, + ); + builder.element( + 'color', + nest: () async { + builder.attribute('rgb', font.color); + }, + ); + builder.element( + 'name', + nest: () async { + builder.attribute('val', font.name); + }, + ); + }, + ); + } } - } - }); + }, + ); } /// Serialize fills. void _saveFills(XmlBuilder builder) { - builder.element('fills', nest: () { - builder.attribute('count', (_workbook.fills.length + 2).toString()); - builder.element('fill', nest: () { - builder.element('patternFill', nest: () { - builder.attribute('patternType', 'none'); - }); - }); - builder.element('fill', nest: () { - builder.element('patternFill', nest: () { - builder.attribute('patternType', 'gray125'); - }); - }); - if (_workbook.fills.isNotEmpty) { - _workbook.fills.forEach((String key, int value) { - builder.element('fill', nest: () { - builder.element('patternFill', nest: () { - builder.attribute('patternType', 'solid'); - builder.element('fgColor', nest: () { - builder.attribute('rgb', key); - }); - builder.element('bgColor', nest: () { - builder.attribute('rgb', 'FFFFFFFF'); - }); - }); + builder.element( + 'fills', + nest: () { + builder.attribute('count', (_workbook.fills.length + 2).toString()); + builder.element( + 'fill', + nest: () { + builder.element( + 'patternFill', + nest: () { + builder.attribute('patternType', 'none'); + }, + ); + }, + ); + builder.element( + 'fill', + nest: () { + builder.element( + 'patternFill', + nest: () { + builder.attribute('patternType', 'gray125'); + }, + ); + }, + ); + if (_workbook.fills.isNotEmpty) { + _workbook.fills.forEach((String key, int value) { + builder.element( + 'fill', + nest: () { + builder.element( + 'patternFill', + nest: () { + builder.attribute('patternType', 'solid'); + builder.element( + 'fgColor', + nest: () { + builder.attribute('rgb', key); + }, + ); + builder.element( + 'bgColor', + nest: () { + builder.attribute('rgb', 'FFFFFFFF'); + }, + ); + }, + ); + }, + ); }); - }); - } - }); + } + }, + ); } Future _saveFillsAsync(XmlBuilder builder) async { - builder.element('fills', nest: () async { - builder.attribute('count', (_workbook.fills.length + 2).toString()); - builder.element('fill', nest: () async { - builder.element('patternFill', nest: () async { - builder.attribute('patternType', 'none'); - }); - }); - builder.element('fill', nest: () async { - builder.element('patternFill', nest: () async { - builder.attribute('patternType', 'gray125'); - }); - }); - if (_workbook.fills.isNotEmpty) { - _workbook.fills.forEach((String key, int value) { - builder.element('fill', nest: () async { - builder.element('patternFill', nest: () async { - builder.attribute('patternType', 'solid'); - builder.element('fgColor', nest: () async { - builder.attribute('rgb', key); - }); - builder.element('bgColor', nest: () async { - builder.attribute('rgb', 'FFFFFFFF'); - }); - }); + builder.element( + 'fills', + nest: () async { + builder.attribute('count', (_workbook.fills.length + 2).toString()); + builder.element( + 'fill', + nest: () async { + builder.element( + 'patternFill', + nest: () async { + builder.attribute('patternType', 'none'); + }, + ); + }, + ); + builder.element( + 'fill', + nest: () async { + builder.element( + 'patternFill', + nest: () async { + builder.attribute('patternType', 'gray125'); + }, + ); + }, + ); + if (_workbook.fills.isNotEmpty) { + _workbook.fills.forEach((String key, int value) { + builder.element( + 'fill', + nest: () async { + builder.element( + 'patternFill', + nest: () async { + builder.attribute('patternType', 'solid'); + builder.element( + 'fgColor', + nest: () async { + builder.attribute('rgb', key); + }, + ); + builder.element( + 'bgColor', + nest: () async { + builder.attribute('rgb', 'FFFFFFFF'); + }, + ); + }, + ); + }, + ); }); - }); - } - }); + } + }, + ); } /// Serialize borders. void _saveBorders(XmlBuilder builder) { - builder.element('borders', nest: () { - builder.attribute('count', (_workbook.borders.length + 1).toString()); - builder.element('border', nest: () { - builder.element('left', nest: () {}); - builder.element('right', nest: () {}); - builder.element('top', nest: () {}); - builder.element('bottom', nest: () {}); - builder.element('diagonal', nest: () {}); - }); - if (_workbook.borders.isNotEmpty) { - for (final Borders borders in _workbook.borders) { - if (Workbook.isAllBorder(borders)) { - builder.element('border', nest: () { - _serializeBorder(borders.all, builder, 'left'); - _serializeBorder(borders.all, builder, 'right'); - _serializeBorder(borders.all, builder, 'top'); - _serializeBorder(borders.all, builder, 'bottom'); - _serializeBorder(borders.all, builder, 'diagonal'); - }); - } else { - _serializeBorders(borders, builder); + builder.element( + 'borders', + nest: () { + builder.attribute('count', (_workbook.borders.length + 1).toString()); + builder.element( + 'border', + nest: () { + builder.element('left', nest: () {}); + builder.element('right', nest: () {}); + builder.element('top', nest: () {}); + builder.element('bottom', nest: () {}); + builder.element('diagonal', nest: () {}); + }, + ); + if (_workbook.borders.isNotEmpty) { + for (final Borders borders in _workbook.borders) { + if (Workbook.isAllBorder(borders)) { + builder.element( + 'border', + nest: () { + _serializeBorder(borders.all, builder, 'left'); + _serializeBorder(borders.all, builder, 'right'); + _serializeBorder(borders.all, builder, 'top'); + _serializeBorder(borders.all, builder, 'bottom'); + _serializeBorder(borders.all, builder, 'diagonal'); + }, + ); + } else { + _serializeBorders(borders, builder); + } } } - } - }); + }, + ); } Future _saveBordersAsync(XmlBuilder builder) async { - builder.element('borders', nest: () async { - builder.attribute('count', (_workbook.borders.length + 1).toString()); - builder.element('border', nest: () async { - builder.element('left', nest: () async {}); - builder.element('right', nest: () async {}); - builder.element('top', nest: () async {}); - builder.element('bottom', nest: () async {}); - builder.element('diagonal', nest: () async {}); - }); - if (_workbook.borders.isNotEmpty) { - for (final Borders borders in _workbook.borders) { - if (Workbook.isAllBorder(borders)) { - builder.element('border', nest: () async { - _serializeBorderAsync(borders.all, builder, 'left'); - _serializeBorderAsync(borders.all, builder, 'right'); - _serializeBorderAsync(borders.all, builder, 'top'); - _serializeBorderAsync(borders.all, builder, 'bottom'); - _serializeBorderAsync(borders.all, builder, 'diagonal'); - }); - } else { - _serializeBordersAsync(borders, builder); + builder.element( + 'borders', + nest: () async { + builder.attribute('count', (_workbook.borders.length + 1).toString()); + builder.element( + 'border', + nest: () async { + builder.element('left', nest: () async {}); + builder.element('right', nest: () async {}); + builder.element('top', nest: () async {}); + builder.element('bottom', nest: () async {}); + builder.element('diagonal', nest: () async {}); + }, + ); + if (_workbook.borders.isNotEmpty) { + for (final Borders borders in _workbook.borders) { + if (Workbook.isAllBorder(borders)) { + builder.element( + 'border', + nest: () async { + _serializeBorderAsync(borders.all, builder, 'left'); + _serializeBorderAsync(borders.all, builder, 'right'); + _serializeBorderAsync(borders.all, builder, 'top'); + _serializeBorderAsync(borders.all, builder, 'bottom'); + _serializeBorderAsync(borders.all, builder, 'diagonal'); + }, + ); + } else { + _serializeBordersAsync(borders, builder); + } } } - } - }); + }, + ); } /// serializeBorders collection. void _serializeBorders(Borders borders, XmlBuilder builder) { - builder.element('border', nest: () { - _serializeBorder(borders.left, builder, 'left'); - _serializeBorder(borders.right, builder, 'right'); - _serializeBorder(borders.top, builder, 'top'); - _serializeBorder(borders.bottom, builder, 'bottom'); - }); + builder.element( + 'border', + nest: () { + _serializeBorder(borders.left, builder, 'left'); + _serializeBorder(borders.right, builder, 'right'); + _serializeBorder(borders.top, builder, 'top'); + _serializeBorder(borders.bottom, builder, 'bottom'); + }, + ); } Future _serializeBordersAsync( - Borders borders, XmlBuilder builder) async { - builder.element('border', nest: () async { - _serializeBorderAsync(borders.left, builder, 'left'); - _serializeBorderAsync(borders.right, builder, 'right'); - _serializeBorderAsync(borders.top, builder, 'top'); - _serializeBorderAsync(borders.bottom, builder, 'bottom'); - }); + Borders borders, + XmlBuilder builder, + ) async { + builder.element( + 'border', + nest: () async { + _serializeBorderAsync(borders.left, builder, 'left'); + _serializeBorderAsync(borders.right, builder, 'right'); + _serializeBorderAsync(borders.top, builder, 'top'); + _serializeBorderAsync(borders.bottom, builder, 'bottom'); + }, + ); } /// Serialize borders. void _serializeBorder(Border border, XmlBuilder builder, String borderType) { - builder.element(borderType, nest: () { - builder.attribute( - 'style', border.lineStyle.toString().split('.').toList().removeAt(1)); - builder.element('color', nest: () { - if (border.color.length == 7) { - builder.attribute('rgb', 'FF${border.color.replaceAll('#', '')}'); - } else { - builder.attribute('rgb', border.color); - } - }); - }); + builder.element( + borderType, + nest: () { + builder.attribute( + 'style', + border.lineStyle.toString().split('.').toList().removeAt(1), + ); + builder.element( + 'color', + nest: () { + if (border.color.length == 7) { + builder.attribute('rgb', 'FF${border.color.replaceAll('#', '')}'); + } else { + builder.attribute('rgb', border.color); + } + }, + ); + }, + ); } Future _serializeBorderAsync( - Border border, XmlBuilder builder, String borderType) async { - builder.element(borderType, nest: () async { - builder.attribute( - 'style', border.lineStyle.toString().split('.').toList().removeAt(1)); - builder.element('color', nest: () async { - if (border.color.length == 7) { - builder.attribute('rgb', 'FF${border.color.replaceAll('#', '')}'); - } else { - builder.attribute('rgb', border.color); - } - }); - }); + Border border, + XmlBuilder builder, + String borderType, + ) async { + builder.element( + borderType, + nest: () async { + builder.attribute( + 'style', + border.lineStyle.toString().split('.').toList().removeAt(1), + ); + builder.element( + 'color', + nest: () async { + if (border.color.length == 7) { + builder.attribute('rgb', 'FF${border.color.replaceAll('#', '')}'); + } else { + builder.attribute('rgb', border.color); + } + }, + ); + }, + ); } /// Serialize cell styles xfs. void _saveCellStyleXfs(XmlBuilder builder) { - builder.element('cellStyleXfs', nest: () { - builder.attribute( - 'count', (_workbook.cellStyleXfs.length + 1).toString()); - builder.element('xf', nest: () { - builder.attribute('numFmtId', '0'); - builder.attribute('fontId', '0'); - builder.attribute('fillId', '0'); - builder.attribute('borderId', '0'); - }); - if (_workbook.cellStyleXfs.isNotEmpty) { - for (final CellStyleXfs cellStyleXfs in _workbook.cellStyleXfs) { - builder.element('xf', nest: () { - builder.attribute( - 'numFmtId', cellStyleXfs.numberFormatId.toString()); - builder.attribute('fontId', cellStyleXfs.fontId.toString()); - builder.attribute('fillId', cellStyleXfs.fillId.toString()); - builder.attribute('borderId', cellStyleXfs.borderId.toString()); - }); + builder.element( + 'cellStyleXfs', + nest: () { + builder.attribute( + 'count', + (_workbook.cellStyleXfs.length + 1).toString(), + ); + builder.element( + 'xf', + nest: () { + builder.attribute('numFmtId', '0'); + builder.attribute('fontId', '0'); + builder.attribute('fillId', '0'); + builder.attribute('borderId', '0'); + }, + ); + if (_workbook.cellStyleXfs.isNotEmpty) { + for (final CellStyleXfs cellStyleXfs in _workbook.cellStyleXfs) { + builder.element( + 'xf', + nest: () { + builder.attribute( + 'numFmtId', + cellStyleXfs.numberFormatId.toString(), + ); + builder.attribute('fontId', cellStyleXfs.fontId.toString()); + builder.attribute('fillId', cellStyleXfs.fillId.toString()); + builder.attribute('borderId', cellStyleXfs.borderId.toString()); + }, + ); + } } - } - }); + }, + ); } Future _saveCellStyleXfsAsync(XmlBuilder builder) async { - builder.element('cellStyleXfs', nest: () async { - builder.attribute( - 'count', (_workbook.cellStyleXfs.length + 1).toString()); - builder.element('xf', nest: () async { - builder.attribute('numFmtId', '0'); - builder.attribute('fontId', '0'); - builder.attribute('fillId', '0'); - builder.attribute('borderId', '0'); - }); - if (_workbook.cellStyleXfs.isNotEmpty) { - for (final CellStyleXfs cellStyleXfs in _workbook.cellStyleXfs) { - builder.element('xf', nest: () async { - builder.attribute( - 'numFmtId', cellStyleXfs.numberFormatId.toString()); - builder.attribute('fontId', cellStyleXfs.fontId.toString()); - builder.attribute('fillId', cellStyleXfs.fillId.toString()); - builder.attribute('borderId', cellStyleXfs.borderId.toString()); - }); + builder.element( + 'cellStyleXfs', + nest: () async { + builder.attribute( + 'count', + (_workbook.cellStyleXfs.length + 1).toString(), + ); + builder.element( + 'xf', + nest: () async { + builder.attribute('numFmtId', '0'); + builder.attribute('fontId', '0'); + builder.attribute('fillId', '0'); + builder.attribute('borderId', '0'); + }, + ); + if (_workbook.cellStyleXfs.isNotEmpty) { + for (final CellStyleXfs cellStyleXfs in _workbook.cellStyleXfs) { + builder.element( + 'xf', + nest: () async { + builder.attribute( + 'numFmtId', + cellStyleXfs.numberFormatId.toString(), + ); + builder.attribute('fontId', cellStyleXfs.fontId.toString()); + builder.attribute('fillId', cellStyleXfs.fillId.toString()); + builder.attribute('borderId', cellStyleXfs.borderId.toString()); + }, + ); + } } - } - }); + }, + ); } /// Serialize cell styles xfs. void _saveCellXfs(XmlBuilder builder) { - builder.element('cellXfs', nest: () { - builder.attribute('count', _workbook.cellXfs.length.toString()); - if (_workbook.cellXfs.isNotEmpty) { - for (final CellXfs cellXf in _workbook.cellXfs) { - builder.element('xf', nest: () { - builder.attribute('numFmtId', cellXf.numberFormatId.toString()); - builder.attribute('fontId', cellXf.fontId.toString()); - builder.attribute('fillId', cellXf.fillId.toString()); - builder.attribute('borderId', cellXf.borderId.toString()); - builder.attribute('xfId', cellXf.xfId.toString()); - _saveAlignment(cellXf, builder); - _saveProtection(cellXf, builder); - }); + builder.element( + 'cellXfs', + nest: () { + builder.attribute('count', _workbook.cellXfs.length.toString()); + if (_workbook.cellXfs.isNotEmpty) { + for (final CellXfs cellXf in _workbook.cellXfs) { + builder.element( + 'xf', + nest: () { + builder.attribute('numFmtId', cellXf.numberFormatId.toString()); + builder.attribute('fontId', cellXf.fontId.toString()); + builder.attribute('fillId', cellXf.fillId.toString()); + builder.attribute('borderId', cellXf.borderId.toString()); + builder.attribute('xfId', cellXf.xfId.toString()); + _saveAlignment(cellXf, builder); + _saveProtection(cellXf, builder); + }, + ); + } } - } - }); + }, + ); } Future _saveCellXfsAsync(XmlBuilder builder) async { - builder.element('cellXfs', nest: () async { - builder.attribute('count', _workbook.cellXfs.length.toString()); - if (_workbook.cellXfs.isNotEmpty) { - for (final CellXfs cellXf in _workbook.cellXfs) { - builder.element('xf', nest: () async { - builder.attribute('numFmtId', cellXf.numberFormatId.toString()); - builder.attribute('fontId', cellXf.fontId.toString()); - builder.attribute('fillId', cellXf.fillId.toString()); - builder.attribute('borderId', cellXf.borderId.toString()); - builder.attribute('xfId', cellXf.xfId.toString()); - _saveAlignmentAsync(cellXf, builder); - _saveProtectionAsync(cellXf, builder); - }); + builder.element( + 'cellXfs', + nest: () async { + builder.attribute('count', _workbook.cellXfs.length.toString()); + if (_workbook.cellXfs.isNotEmpty) { + for (final CellXfs cellXf in _workbook.cellXfs) { + builder.element( + 'xf', + nest: () async { + builder.attribute('numFmtId', cellXf.numberFormatId.toString()); + builder.attribute('fontId', cellXf.fontId.toString()); + builder.attribute('fillId', cellXf.fillId.toString()); + builder.attribute('borderId', cellXf.borderId.toString()); + builder.attribute('xfId', cellXf.xfId.toString()); + _saveAlignmentAsync(cellXf, builder); + _saveProtectionAsync(cellXf, builder); + }, + ); + } } - } - }); + }, + ); } ///Serialize Protection. void _saveProtection(CellStyleXfs cellXf, XmlBuilder builder) { if (cellXf.locked != 1) { - builder.element('protection', nest: () { - builder.attribute('locked', cellXf.locked.toString()); - }); + builder.element( + 'protection', + nest: () { + builder.attribute('locked', cellXf.locked.toString()); + }, + ); } } Future _saveProtectionAsync( - CellStyleXfs cellXf, XmlBuilder builder) async { + CellStyleXfs cellXf, + XmlBuilder builder, + ) async { if (cellXf.locked != 1) { - builder.element('protection', nest: () async { - builder.attribute('locked', cellXf.locked.toString()); - }); + builder.element( + 'protection', + nest: () async { + builder.attribute('locked', cellXf.locked.toString()); + }, + ); } } /// Serialize alignment. void _saveAlignment(CellStyleXfs cellXf, XmlBuilder builder) { - builder.element('alignment', nest: () { - if (cellXf.alignment != null) { - if (cellXf.alignment!.horizontal != '') { - builder.attribute( - 'horizontal', cellXf.alignment!.horizontal.toLowerCase()); - } - if (cellXf.alignment!.indent != 0) { - builder.attribute('indent', cellXf.alignment!.indent.toString()); - } else if (cellXf.alignment!.rotation != 0) { - builder.attribute( - 'textRotation', cellXf.alignment!.rotation.toString()); - } - if (cellXf.alignment!.vertical != '') { - builder.attribute( - 'vertical', cellXf.alignment!.vertical.toLowerCase()); + builder.element( + 'alignment', + nest: () { + if (cellXf.alignment != null) { + if (cellXf.alignment!.horizontal != '') { + builder.attribute( + 'horizontal', + cellXf.alignment!.horizontal.toLowerCase(), + ); + } + if (cellXf.alignment!.indent != 0) { + builder.attribute('indent', cellXf.alignment!.indent.toString()); + } else if (cellXf.alignment!.rotation != 0) { + builder.attribute( + 'textRotation', + cellXf.alignment!.rotation.toString(), + ); + } + if (cellXf.alignment!.vertical != '') { + builder.attribute( + 'vertical', + cellXf.alignment!.vertical.toLowerCase(), + ); + } + builder.attribute('wrapText', cellXf.alignment!.wrapText.toString()); } - builder.attribute('wrapText', cellXf.alignment!.wrapText.toString()); - } - }); + }, + ); } Future _saveAlignmentAsync( - CellStyleXfs cellXf, XmlBuilder builder) async { - builder.element('alignment', nest: () async { - if (cellXf.alignment != null) { - if (cellXf.alignment!.horizontal != '') { - builder.attribute( - 'horizontal', cellXf.alignment!.horizontal.toLowerCase()); - } - if (cellXf.alignment!.indent != 0) { - builder.attribute('indent', cellXf.alignment!.indent.toString()); - } else if (cellXf.alignment!.rotation != 0) { - builder.attribute( - 'textRotation', cellXf.alignment!.rotation.toString()); - } - if (cellXf.alignment!.vertical != '') { - builder.attribute( - 'vertical', cellXf.alignment!.vertical.toLowerCase()); + CellStyleXfs cellXf, + XmlBuilder builder, + ) async { + builder.element( + 'alignment', + nest: () async { + if (cellXf.alignment != null) { + if (cellXf.alignment!.horizontal != '') { + builder.attribute( + 'horizontal', + cellXf.alignment!.horizontal.toLowerCase(), + ); + } + if (cellXf.alignment!.indent != 0) { + builder.attribute('indent', cellXf.alignment!.indent.toString()); + } else if (cellXf.alignment!.rotation != 0) { + builder.attribute( + 'textRotation', + cellXf.alignment!.rotation.toString(), + ); + } + if (cellXf.alignment!.vertical != '') { + builder.attribute( + 'vertical', + cellXf.alignment!.vertical.toLowerCase(), + ); + } + builder.attribute('wrapText', cellXf.alignment!.wrapText.toString()); } - builder.attribute('wrapText', cellXf.alignment!.wrapText.toString()); - } - }); + }, + ); } /// Serialize cell styles. void _saveGlobalCellstyles(XmlBuilder builder) { final int length = _workbook.globalStyles.length + 1; - builder.element('cellStyles', nest: () { - builder.attribute('count', length.toString()); - builder.element('cellStyle', nest: () { - builder.attribute('name', 'Normal'); - builder.attribute('xfId', '0'); - builder.attribute('builtinId', '0'); - }); - _workbook.globalStyles.forEach((String key, GlobalStyle value) { - builder.element('cellStyle', nest: () { - if (key != '') { - builder.attribute('name', key); - builder.attribute( - 'xfId', _workbook.globalStyles[key]!.xfId.toString()); - if (_workbook.globalStyles[key]!.builtinId != 0) { - builder.attribute('builtinId', - _workbook.globalStyles[key]!.builtinId.toString()); - } - } + builder.element( + 'cellStyles', + nest: () { + builder.attribute('count', length.toString()); + builder.element( + 'cellStyle', + nest: () { + builder.attribute('name', 'Normal'); + builder.attribute('xfId', '0'); + builder.attribute('builtinId', '0'); + }, + ); + _workbook.globalStyles.forEach((String key, GlobalStyle value) { + builder.element( + 'cellStyle', + nest: () { + if (key != '') { + builder.attribute('name', key); + builder.attribute( + 'xfId', + _workbook.globalStyles[key]!.xfId.toString(), + ); + if (_workbook.globalStyles[key]!.builtinId != 0) { + builder.attribute( + 'builtinId', + _workbook.globalStyles[key]!.builtinId.toString(), + ); + } + } + }, + ); }); - }); - }); + }, + ); } Future _saveGlobalCellstylesAsync(XmlBuilder builder) async { final int length = _workbook.globalStyles.length + 1; - builder.element('cellStyles', nest: () async { - builder.attribute('count', length.toString()); - builder.element('cellStyle', nest: () async { - builder.attribute('name', 'Normal'); - builder.attribute('xfId', '0'); - builder.attribute('builtinId', '0'); - }); - _workbook.globalStyles.forEach((String key, GlobalStyle value) { - builder.element('cellStyle', nest: () async { - if (key != '') { - builder.attribute('name', key); - builder.attribute( - 'xfId', _workbook.globalStyles[key]!.xfId.toString()); - if (_workbook.globalStyles[key]!.builtinId != 0) { - builder.attribute('builtinId', - _workbook.globalStyles[key]!.builtinId.toString()); - } - } + builder.element( + 'cellStyles', + nest: () async { + builder.attribute('count', length.toString()); + builder.element( + 'cellStyle', + nest: () async { + builder.attribute('name', 'Normal'); + builder.attribute('xfId', '0'); + builder.attribute('builtinId', '0'); + }, + ); + _workbook.globalStyles.forEach((String key, GlobalStyle value) { + builder.element( + 'cellStyle', + nest: () async { + if (key != '') { + builder.attribute('name', key); + builder.attribute( + 'xfId', + _workbook.globalStyles[key]!.xfId.toString(), + ); + if (_workbook.globalStyles[key]!.builtinId != 0) { + builder.attribute( + 'builtinId', + _workbook.globalStyles[key]!.builtinId.toString(), + ); + } + } + }, + ); }); - }); - }); + }, + ); } /// Process the Merge cell. MergedCellCollection _processMergeCells( - Range cell, int rowIndex, MergedCellCollection mergeCells) { + Range cell, + int rowIndex, + MergedCellCollection mergeCells, + ) { if (cell.rowSpan != 0 || cell.columnSpan != 0) { final MergeCell mCell = MergeCell(); mCell.x = cell.index; @@ -4173,8 +5352,10 @@ class SerializeWorkbook { mCell.y = rowIndex; mCell.height = cell.rowSpan; final String startCell = Range.getCellName(mCell.y, mCell.x); - final String endCell = - Range.getCellName(rowIndex + mCell.height, cell.index + mCell.width); + final String endCell = Range.getCellName( + rowIndex + mCell.height, + cell.index + mCell.width, + ); mCell.reference = '$startCell:$endCell'; mergeCells.addCell(mCell); final ExtendCell start = ExtendCell(); @@ -4190,7 +5371,10 @@ class SerializeWorkbook { /// Update merged cell styles void _updatedMergedCellStyles( - ExtendCell sCell, ExtendCell eCell, Range cell) { + ExtendCell sCell, + ExtendCell eCell, + Range cell, + ) { final Workbook workbook = cell.workbook; for (int x = sCell.x; x <= eCell.x; x++) { for (int y = sCell.y; y <= eCell.y; y++) { @@ -4215,10 +5399,11 @@ class SerializeWorkbook { } for (int dvTable = 0; dvTable < dataValidationTable.count; dvTable++) { - for (int dvCollection = 0; - dvCollection < - dataValidationTable.dataValidationCollectionList.length; - dvCollection++) { + for ( + int dvCollection = 0; + dvCollection < dataValidationTable.dataValidationCollectionList.length; + dvCollection++ + ) { final DataValidationCollection dataValidationCollection = dataValidationTable.dataValidationCollectionList[dvCollection]; _serializeDataValidationCollection(builder, dataValidationCollection); @@ -4227,7 +5412,9 @@ class SerializeWorkbook { } Future _serializeDataValidationsAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { final DataValidationTable dataValidationTable = sheet.dataValidationTable; if (dataValidationTable.count == 0) { @@ -4235,69 +5422,114 @@ class SerializeWorkbook { } for (int dvTable = 0; dvTable < dataValidationTable.count; dvTable++) { - for (int dvCollection = 0; - dvCollection < - dataValidationTable.dataValidationCollectionList.length; - dvCollection++) { + for ( + int dvCollection = 0; + dvCollection < dataValidationTable.dataValidationCollectionList.length; + dvCollection++ + ) { final DataValidationCollection dataValidationCollection = dataValidationTable.dataValidationCollectionList[dvCollection]; _serializeDataValidationCollectionAsync( - builder, dataValidationCollection); + builder, + dataValidationCollection, + ); } } } ///Serialize DataValidation Collection void _serializeDataValidationCollection( - XmlBuilder builder, DataValidationCollection dataValidationCollection) { + XmlBuilder builder, + DataValidationCollection dataValidationCollection, + ) { if (dataValidationCollection.count == 0) { return; } - builder.element('dataValidations', nest: () { - _serializeAttributeInt( - builder, 'count', dataValidationCollection.count, 0); - - if (dataValidationCollection.isPromptBoxPositionFixedVal) { - _serializeAttributeInt(builder, 'xWindow', - dataValidationCollection.promptBoxVPositionVal, 0); - - _serializeAttributeInt(builder, 'yWindow', - dataValidationCollection.promptBoxHPositionVal, 0); - } - - for (int dvList = 0; + builder.element( + 'dataValidations', + nest: () { + _serializeAttributeInt( + builder, + 'count', + dataValidationCollection.count, + 0, + ); + + if (dataValidationCollection.isPromptBoxPositionFixedVal) { + _serializeAttributeInt( + builder, + 'xWindow', + dataValidationCollection.promptBoxVPositionVal, + 0, + ); + + _serializeAttributeInt( + builder, + 'yWindow', + dataValidationCollection.promptBoxHPositionVal, + 0, + ); + } + + for ( + int dvList = 0; dvList < dataValidationCollection.dataValidationList.length; - dvList++) { - _serializeDataValidation( - builder, dataValidationCollection.dataValidationList[dvList]); - } - }); + dvList++ + ) { + _serializeDataValidation( + builder, + dataValidationCollection.dataValidationList[dvList], + ); + } + }, + ); } - Future _serializeDataValidationCollectionAsync(XmlBuilder builder, - DataValidationCollection dataValidationCollection) async { + Future _serializeDataValidationCollectionAsync( + XmlBuilder builder, + DataValidationCollection dataValidationCollection, + ) async { if (dataValidationCollection.count == 0) { return; } - builder.element('dataValidations', nest: () async { - _serializeAttributeIntAsync( - builder, 'count', dataValidationCollection.count, 0); - if (dataValidationCollection.isPromptBoxPositionFixedVal) { - _serializeAttributeIntAsync(builder, 'xWindow', - dataValidationCollection.promptBoxVPositionVal, 0); - _serializeAttributeIntAsync(builder, 'yWindow', - dataValidationCollection.promptBoxHPositionVal, 0); - } - - for (int dvList = 0; + builder.element( + 'dataValidations', + nest: () async { + _serializeAttributeIntAsync( + builder, + 'count', + dataValidationCollection.count, + 0, + ); + if (dataValidationCollection.isPromptBoxPositionFixedVal) { + _serializeAttributeIntAsync( + builder, + 'xWindow', + dataValidationCollection.promptBoxVPositionVal, + 0, + ); + _serializeAttributeIntAsync( + builder, + 'yWindow', + dataValidationCollection.promptBoxHPositionVal, + 0, + ); + } + + for ( + int dvList = 0; dvList < dataValidationCollection.dataValidationList.length; - dvList++) { - _serializeDataValidationAsync( - builder, dataValidationCollection.dataValidationList[dvList]); - } - }); + dvList++ + ) { + _serializeDataValidationAsync( + builder, + dataValidationCollection.dataValidationList[dvList], + ); + } + }, + ); } ///DataType properties for DataValidation @@ -4345,7 +5577,8 @@ class SerializeWorkbook { ///ComparisonOperator properties for DataValidation String _getComparisonOperator( - ExcelDataValidationComparisonOperator dataValComparisonOperator) { + ExcelDataValidationComparisonOperator dataValComparisonOperator, + ) { switch (dataValComparisonOperator) { case ExcelDataValidationComparisonOperator.equal: return 'equal'; @@ -4374,15 +5607,23 @@ class SerializeWorkbook { } ///method for comparing String value - void _serializeDataValStringAttribute(XmlBuilder builder, - String attributeName, String value, String defaultValue) { + void _serializeDataValStringAttribute( + XmlBuilder builder, + String attributeName, + String value, + String defaultValue, + ) { if (value != defaultValue) { builder.attribute(attributeName, value); } } - Future _serializeDataValStringAttributeAsync(XmlBuilder builder, - String attributeName, String value, String defaultValue) async { + Future _serializeDataValStringAttributeAsync( + XmlBuilder builder, + String attributeName, + String value, + String defaultValue, + ) async { if (value != defaultValue) { builder.attribute(attributeName, value); } @@ -4390,381 +5631,471 @@ class SerializeWorkbook { /// Serialize DataValidation void _serializeDataValidation( - XmlBuilder builder, DataValidationImpl dataValidationImpl) { - builder.element('dataValidation', nest: () { - final ExcelDataValidationType dataType = dataValidationImpl.allowType; - - if (dataType != ExcelDataValidationType.any) { - builder.attribute('type', _getDataType(dataType)); - } - - final ExcelDataValidationErrorStyle errorStyle = - dataValidationImpl.errorStyle; - - if (errorStyle != ExcelDataValidationErrorStyle.stop) { - builder.attribute('errorStyle', _getErrorStyle(errorStyle)); - } - final ExcelDataValidationComparisonOperator comparisonOperator = - dataValidationImpl.comparisonOperator; - - if (comparisonOperator != ExcelDataValidationComparisonOperator.between && - _getDataType(dataType) != 'custom') { - builder.attribute( - 'operator', _getComparisonOperator(comparisonOperator)); - } - - _serializeAttributes( - builder, 'allowBlank', dataValidationImpl.isEmptyCellAllowed, false); + XmlBuilder builder, + DataValidationImpl dataValidationImpl, + ) { + builder.element( + 'dataValidation', + nest: () { + final ExcelDataValidationType dataType = dataValidationImpl.allowType; - _serializeAttributes(builder, 'showDropDown', - dataValidationImpl.isSuppressDropDownArrow, false); + if (dataType != ExcelDataValidationType.any) { + builder.attribute('type', _getDataType(dataType)); + } - _serializeAttributes( - builder, 'showInputMessage', dataValidationImpl.showPromptBox, false); + final ExcelDataValidationErrorStyle errorStyle = + dataValidationImpl.errorStyle; - _serializeAttributes( - builder, 'showErrorMessage', dataValidationImpl.showErrorBox, false); + if (errorStyle != ExcelDataValidationErrorStyle.stop) { + builder.attribute('errorStyle', _getErrorStyle(errorStyle)); + } + final ExcelDataValidationComparisonOperator comparisonOperator = + dataValidationImpl.comparisonOperator; - _serializeDataValStringAttribute( - builder, 'errorTitle', dataValidationImpl.errorBoxTitle, ''); + if (comparisonOperator != + ExcelDataValidationComparisonOperator.between && + _getDataType(dataType) != 'custom') { + builder.attribute( + 'operator', + _getComparisonOperator(comparisonOperator), + ); + } - _serializeDataValStringAttribute( - builder, 'error', dataValidationImpl.errorBoxText, ''); + _serializeAttributes( + builder, + 'allowBlank', + dataValidationImpl.isEmptyCellAllowed, + false, + ); - _serializeDataValStringAttribute( - builder, 'promptTitle', dataValidationImpl.promptBoxTitle, ''); + _serializeAttributes( + builder, + 'showDropDown', + dataValidationImpl.isSuppressDropDownArrow, + false, + ); - _serializeDataValStringAttribute( - builder, 'prompt', dataValidationImpl.promptBoxText, ''); + _serializeAttributes( + builder, + 'showInputMessage', + dataValidationImpl.showPromptBox, + false, + ); - _serializeDataValStringAttribute( - builder, 'sqref', dataValidationImpl.cellRange, ''); + _serializeAttributes( + builder, + 'showErrorMessage', + dataValidationImpl.showErrorBox, + false, + ); + + _serializeDataValStringAttribute( + builder, + 'errorTitle', + dataValidationImpl.errorBoxTitle, + '', + ); + + _serializeDataValStringAttribute( + builder, + 'error', + dataValidationImpl.errorBoxText, + '', + ); + + _serializeDataValStringAttribute( + builder, + 'promptTitle', + dataValidationImpl.promptBoxTitle, + '', + ); + + _serializeDataValStringAttribute( + builder, + 'prompt', + dataValidationImpl.promptBoxText, + '', + ); + + _serializeDataValStringAttribute( + builder, + 'sqref', + dataValidationImpl.cellRange, + '', + ); + + if ('textLength' == _getDataType(dataType) || + 'decimal' == _getDataType(dataType) || + 'whole' == _getDataType(dataType)) { + final String firstFormula = dataValidationImpl.firstFormula; + final String secondFormula = dataValidationImpl.secondFormula; + if (firstFormula != '') { + builder.element('formula1', nest: firstFormula); + } + if (secondFormula != '') { + builder.element('formula2', nest: secondFormula); + } + } else if ('time' == _getDataType(dataType)) { + final String firstFormula = dataValidationImpl.firstFormula; + final String secondFormula = dataValidationImpl.secondFormula; + final List firstFormulaCheck = firstFormula.split(':'); + final List secondFormulaCheck = secondFormula.split(':'); + late Duration duration; + late double firstFormulaVal; + late double secondFormulaVal; + late String firstTimeVal; + late String secondTimeVal; + if (firstFormulaCheck.length == 2) { + final int? hour = int.tryParse(firstFormulaCheck[0]); + final int? min = int.tryParse(firstFormulaCheck[1]); + + if (hour != null && min != null) { + duration = Duration(hours: hour, minutes: min); + + firstFormulaVal = (duration.inMinutes / 60) / 24; + firstTimeVal = firstFormulaVal.toString(); + } else { + firstTimeVal = firstFormula; + } + } - if ('textLength' == _getDataType(dataType) || - 'decimal' == _getDataType(dataType) || - 'whole' == _getDataType(dataType)) { - final String firstFormula = dataValidationImpl.firstFormula; - final String secondFormula = dataValidationImpl.secondFormula; - if (firstFormula != '') { - builder.element('formula1', nest: firstFormula); - } - if (secondFormula != '') { - builder.element('formula2', nest: secondFormula); - } - } else if ('time' == _getDataType(dataType)) { - final String firstFormula = dataValidationImpl.firstFormula; - final String secondFormula = dataValidationImpl.secondFormula; - final List firstFormulaCheck = firstFormula.split(':'); - final List secondFormulaCheck = secondFormula.split(':'); - late Duration duration; - late double firstFormulaVal; - late double secondFormulaVal; - late String firstTimeVal; - late String secondTimeVal; - if (firstFormulaCheck.length == 2) { - final int? hour = int.tryParse(firstFormulaCheck[0]); - final int? min = int.tryParse(firstFormulaCheck[1]); + if (firstFormulaCheck.length == 3) { + final int? hour = int.tryParse(firstFormulaCheck[0]); + final int? min = int.tryParse(firstFormulaCheck[1]); + final int? sec = int.tryParse(firstFormulaCheck[2]); - if (hour != null && min != null) { - duration = Duration(hours: hour, minutes: min); + if (hour != null && min != null && sec != null) { + duration = Duration(hours: hour, minutes: min, seconds: sec); - firstFormulaVal = (duration.inMinutes / 60) / 24; - firstTimeVal = firstFormulaVal.toString(); - } else { - firstTimeVal = firstFormula; + firstFormulaVal = ((duration.inSeconds / 60) / 60) / 24; + firstTimeVal = firstFormulaVal.toString(); + } else { + firstTimeVal = firstFormula; + } } - } - if (firstFormulaCheck.length == 3) { - final int? hour = int.tryParse(firstFormulaCheck[0]); - final int? min = int.tryParse(firstFormulaCheck[1]); - final int? sec = int.tryParse(firstFormulaCheck[2]); + if (secondFormulaCheck.length == 2) { + final int? hour = int.tryParse(secondFormulaCheck[0]); + final int? min = int.tryParse(secondFormulaCheck[1]); - if (hour != null && min != null && sec != null) { - duration = Duration(hours: hour, minutes: min, seconds: sec); + if (hour != null && min != null) { + duration = Duration(hours: hour, minutes: min); - firstFormulaVal = ((duration.inSeconds / 60) / 60) / 24; - firstTimeVal = firstFormulaVal.toString(); - } else { - firstTimeVal = firstFormula; + secondFormulaVal = (duration.inMinutes / 60) / 24; + secondTimeVal = secondFormulaVal.toString(); + } else { + secondTimeVal = secondFormula; + } } - } - if (secondFormulaCheck.length == 2) { - final int? hour = int.tryParse(secondFormulaCheck[0]); - final int? min = int.tryParse(secondFormulaCheck[1]); + if (secondFormulaCheck.length == 3) { + final int? hour = int.tryParse(secondFormulaCheck[0]); + final int? min = int.tryParse(secondFormulaCheck[1]); + final int? sec = int.tryParse(secondFormulaCheck[2]); - if (hour != null && min != null) { - duration = Duration(hours: hour, minutes: min); + if (hour != null && min != null && sec != null) { + duration = Duration(hours: hour, minutes: min, seconds: sec); - secondFormulaVal = (duration.inMinutes / 60) / 24; - secondTimeVal = secondFormulaVal.toString(); - } else { - secondTimeVal = secondFormula; + secondFormulaVal = ((duration.inSeconds / 60) / 60) / 24; + secondTimeVal = secondFormulaVal.toString(); + } else { + secondTimeVal = secondFormula; + } } - } - - if (secondFormulaCheck.length == 3) { - final int? hour = int.tryParse(secondFormulaCheck[0]); - final int? min = int.tryParse(secondFormulaCheck[1]); - final int? sec = int.tryParse(secondFormulaCheck[2]); - - if (hour != null && min != null && sec != null) { - duration = Duration(hours: hour, minutes: min, seconds: sec); - secondFormulaVal = ((duration.inSeconds / 60) / 60) / 24; - secondTimeVal = secondFormulaVal.toString(); - } else { + if (firstFormulaCheck.length != 2 && firstFormulaCheck.length != 3) { + firstTimeVal = firstFormula; + } + if (secondFormulaCheck.length != 2 && + secondFormulaCheck.length != 3) { secondTimeVal = secondFormula; } - } + if (firstTimeVal != '') { + builder.element('formula1', nest: firstTimeVal); + } + if (secondTimeVal != '') { + builder.element('formula2', nest: secondTimeVal); + } + } else if ('list' == _getDataType(dataType)) { + final List firstFormula = dataValidationImpl.listOfValues; + late String listOfValues = ''; + if (firstFormula.isNotEmpty) { + for (int listVal = 0; listVal < firstFormula.length; listVal++) { + late String comma; + if (listVal == 0) { + comma = ''; + } else { + comma = ','; + } - if (firstFormulaCheck.length != 2 && firstFormulaCheck.length != 3) { - firstTimeVal = firstFormula; - } - if (secondFormulaCheck.length != 2 && secondFormulaCheck.length != 3) { - secondTimeVal = secondFormula; - } - if (firstTimeVal != '') { - builder.element('formula1', nest: firstTimeVal); - } - if (secondTimeVal != '') { - builder.element('formula2', nest: secondTimeVal); - } - } else if ('list' == _getDataType(dataType)) { - final List firstFormula = dataValidationImpl.listOfValues; - late String listOfValues = ''; - if (firstFormula.isNotEmpty) { - for (int listVal = 0; listVal < firstFormula.length; listVal++) { - late String comma; - if (listVal == 0) { - comma = ''; - } else { - comma = ','; + listOfValues = listOfValues + comma + firstFormula[listVal]; } - listOfValues = listOfValues + comma + firstFormula[listVal]; - } + builder.element('formula1', nest: '" $listOfValues"'); + } else { + final String firstFormulaSelect = + dataValidationImpl.dataRangeVal.addressGlobal; - builder.element('formula1', nest: '" $listOfValues"'); + builder.element('formula1', nest: firstFormulaSelect); + } + } else if ('custom' == _getDataType(dataType)) { + final String firstFormula = dataValidationImpl.firstFormula; + final String secondFormula = dataValidationImpl.secondFormula; + if (firstFormula.isNotEmpty) { + builder.element('formula1', nest: firstFormula); + } else if (firstFormula == '' && secondFormula.isNotEmpty) { + builder.element('formula1', nest: secondFormula); + } } else { - final String firstFormulaSelect = - dataValidationImpl.dataRangeVal.addressGlobal; - - builder.element('formula1', nest: firstFormulaSelect); - } - } else if ('custom' == _getDataType(dataType)) { - final String firstFormula = dataValidationImpl.firstFormula; - final String secondFormula = dataValidationImpl.secondFormula; - if (firstFormula.isNotEmpty) { - builder.element('formula1', nest: firstFormula); - } else if (firstFormula == '' && secondFormula.isNotEmpty) { - builder.element('formula1', nest: secondFormula); - } - } else { - final DateTime firstDateTime = dataValidationImpl.firstDateTimeVal; - final DateTime secondDateTime = dataValidationImpl.secondDateTime; - final String firstDateTimeVal = - Range.toOADate(firstDateTime).toString(); - final String secondDateTimeVal = - Range.toOADate(secondDateTime).toString(); - if (firstDateTime != DateTime(1)) { - builder.element('formula1', nest: firstDateTimeVal); - } - if (secondDateTime != DateTime(1)) { - builder.element('formula2', nest: secondDateTimeVal); + final DateTime firstDateTime = dataValidationImpl.firstDateTimeVal; + final DateTime secondDateTime = dataValidationImpl.secondDateTime; + final String firstDateTimeVal = + Range.toOADate(firstDateTime).toString(); + final String secondDateTimeVal = + Range.toOADate(secondDateTime).toString(); + if (firstDateTime != DateTime(1)) { + builder.element('formula1', nest: firstDateTimeVal); + } + if (secondDateTime != DateTime(1)) { + builder.element('formula2', nest: secondDateTimeVal); + } } - } - }); + }, + ); } Future _serializeDataValidationAsync( - XmlBuilder builder, DataValidationImpl dataValidationImpl) async { - builder.element('dataValidation', nest: () { - final ExcelDataValidationType dataType = dataValidationImpl.allowType; - - if (dataType != ExcelDataValidationType.any) { - builder.attribute('type', _getDataType(dataType)); - } - - final ExcelDataValidationErrorStyle errorStyle = - dataValidationImpl.errorStyle; - - if (errorStyle != ExcelDataValidationErrorStyle.stop) { - builder.attribute('errorStyle', _getErrorStyle(errorStyle)); - } - final ExcelDataValidationComparisonOperator comparisonOperator = - dataValidationImpl.comparisonOperator; - - if (comparisonOperator != ExcelDataValidationComparisonOperator.between && - _getDataType(dataType) != 'custom') { - builder.attribute( - 'operator', _getComparisonOperator(comparisonOperator)); - } - - _serializeAttributesAsync( - builder, 'allowBlank', dataValidationImpl.isEmptyCellAllowed, false); + XmlBuilder builder, + DataValidationImpl dataValidationImpl, + ) async { + builder.element( + 'dataValidation', + nest: () { + final ExcelDataValidationType dataType = dataValidationImpl.allowType; - _serializeAttributesAsync(builder, 'showDropDown', - dataValidationImpl.isSuppressDropDownArrow, false); + if (dataType != ExcelDataValidationType.any) { + builder.attribute('type', _getDataType(dataType)); + } - _serializeAttributesAsync( - builder, 'showInputMessage', dataValidationImpl.showPromptBox, false); + final ExcelDataValidationErrorStyle errorStyle = + dataValidationImpl.errorStyle; - _serializeAttributesAsync( - builder, 'showErrorMessage', dataValidationImpl.showErrorBox, false); + if (errorStyle != ExcelDataValidationErrorStyle.stop) { + builder.attribute('errorStyle', _getErrorStyle(errorStyle)); + } + final ExcelDataValidationComparisonOperator comparisonOperator = + dataValidationImpl.comparisonOperator; - _serializeDataValStringAttributeAsync( - builder, 'errorTitle', dataValidationImpl.errorBoxTitle, ''); + if (comparisonOperator != + ExcelDataValidationComparisonOperator.between && + _getDataType(dataType) != 'custom') { + builder.attribute( + 'operator', + _getComparisonOperator(comparisonOperator), + ); + } - _serializeDataValStringAttributeAsync( - builder, 'error', dataValidationImpl.errorBoxText, ''); + _serializeAttributesAsync( + builder, + 'allowBlank', + dataValidationImpl.isEmptyCellAllowed, + false, + ); - _serializeDataValStringAttributeAsync( - builder, 'promptTitle', dataValidationImpl.promptBoxTitle, ''); + _serializeAttributesAsync( + builder, + 'showDropDown', + dataValidationImpl.isSuppressDropDownArrow, + false, + ); - _serializeDataValStringAttributeAsync( - builder, 'prompt', dataValidationImpl.promptBoxText, ''); + _serializeAttributesAsync( + builder, + 'showInputMessage', + dataValidationImpl.showPromptBox, + false, + ); - _serializeDataValStringAttributeAsync( - builder, 'sqref', dataValidationImpl.cellRange, ''); + _serializeAttributesAsync( + builder, + 'showErrorMessage', + dataValidationImpl.showErrorBox, + false, + ); + + _serializeDataValStringAttributeAsync( + builder, + 'errorTitle', + dataValidationImpl.errorBoxTitle, + '', + ); + + _serializeDataValStringAttributeAsync( + builder, + 'error', + dataValidationImpl.errorBoxText, + '', + ); + + _serializeDataValStringAttributeAsync( + builder, + 'promptTitle', + dataValidationImpl.promptBoxTitle, + '', + ); + + _serializeDataValStringAttributeAsync( + builder, + 'prompt', + dataValidationImpl.promptBoxText, + '', + ); + + _serializeDataValStringAttributeAsync( + builder, + 'sqref', + dataValidationImpl.cellRange, + '', + ); + + if ('textLength' == _getDataType(dataType) || + 'decimal' == _getDataType(dataType) || + 'whole' == _getDataType(dataType)) { + final String firstFormula = dataValidationImpl.firstFormula; + final String secondFormula = dataValidationImpl.secondFormula; + if (firstFormula != '') { + builder.element('formula1', nest: firstFormula); + } + if (secondFormula != '') { + builder.element('formula2', nest: secondFormula); + } + } else if ('time' == _getDataType(dataType)) { + final String firstFormula = dataValidationImpl.firstFormula; + final String secondFormula = dataValidationImpl.secondFormula; + final List firstFormulaCheck = firstFormula.split(':'); + final List secondFormulaCheck = secondFormula.split(':'); + late Duration duration; + late double firstFormulaVal; + late double secondFormulaVal; + late String firstTimeVal; + late String secondTimeVal; + if (firstFormulaCheck.length == 2) { + final int? hour = int.tryParse(firstFormulaCheck[0]); + final int? min = int.tryParse(firstFormulaCheck[1]); + + if (hour != null && min != null) { + duration = Duration(hours: hour, minutes: min); + + firstFormulaVal = (duration.inMinutes / 60) / 24; + firstTimeVal = firstFormulaVal.toString(); + } else { + firstTimeVal = firstFormula; + } + } - if ('textLength' == _getDataType(dataType) || - 'decimal' == _getDataType(dataType) || - 'whole' == _getDataType(dataType)) { - final String firstFormula = dataValidationImpl.firstFormula; - final String secondFormula = dataValidationImpl.secondFormula; - if (firstFormula != '') { - builder.element('formula1', nest: firstFormula); - } - if (secondFormula != '') { - builder.element('formula2', nest: secondFormula); - } - } else if ('time' == _getDataType(dataType)) { - final String firstFormula = dataValidationImpl.firstFormula; - final String secondFormula = dataValidationImpl.secondFormula; - final List firstFormulaCheck = firstFormula.split(':'); - final List secondFormulaCheck = secondFormula.split(':'); - late Duration duration; - late double firstFormulaVal; - late double secondFormulaVal; - late String firstTimeVal; - late String secondTimeVal; - if (firstFormulaCheck.length == 2) { - final int? hour = int.tryParse(firstFormulaCheck[0]); - final int? min = int.tryParse(firstFormulaCheck[1]); + if (firstFormulaCheck.length == 3) { + final int? hour = int.tryParse(firstFormulaCheck[0]); + final int? min = int.tryParse(firstFormulaCheck[1]); + final int? sec = int.tryParse(firstFormulaCheck[2]); - if (hour != null && min != null) { - duration = Duration(hours: hour, minutes: min); + if (hour != null && min != null && sec != null) { + duration = Duration(hours: hour, minutes: min, seconds: sec); - firstFormulaVal = (duration.inMinutes / 60) / 24; - firstTimeVal = firstFormulaVal.toString(); - } else { - firstTimeVal = firstFormula; + firstFormulaVal = ((duration.inSeconds / 60) / 60) / 24; + firstTimeVal = firstFormulaVal.toString(); + } else { + firstTimeVal = firstFormula; + } } - } - if (firstFormulaCheck.length == 3) { - final int? hour = int.tryParse(firstFormulaCheck[0]); - final int? min = int.tryParse(firstFormulaCheck[1]); - final int? sec = int.tryParse(firstFormulaCheck[2]); + if (secondFormulaCheck.length == 2) { + final int? hour = int.tryParse(secondFormulaCheck[0]); + final int? min = int.tryParse(secondFormulaCheck[1]); - if (hour != null && min != null && sec != null) { - duration = Duration(hours: hour, minutes: min, seconds: sec); + if (hour != null && min != null) { + duration = Duration(hours: hour, minutes: min); - firstFormulaVal = ((duration.inSeconds / 60) / 60) / 24; - firstTimeVal = firstFormulaVal.toString(); - } else { - firstTimeVal = firstFormula; + secondFormulaVal = (duration.inMinutes / 60) / 24; + secondTimeVal = secondFormulaVal.toString(); + } else { + secondTimeVal = secondFormula; + } } - } - if (secondFormulaCheck.length == 2) { - final int? hour = int.tryParse(secondFormulaCheck[0]); - final int? min = int.tryParse(secondFormulaCheck[1]); + if (secondFormulaCheck.length == 3) { + final int? hour = int.tryParse(secondFormulaCheck[0]); + final int? min = int.tryParse(secondFormulaCheck[1]); + final int? sec = int.tryParse(secondFormulaCheck[2]); - if (hour != null && min != null) { - duration = Duration(hours: hour, minutes: min); + if (hour != null && min != null && sec != null) { + duration = Duration(hours: hour, minutes: min, seconds: sec); - secondFormulaVal = (duration.inMinutes / 60) / 24; - secondTimeVal = secondFormulaVal.toString(); - } else { - secondTimeVal = secondFormula; + secondFormulaVal = ((duration.inSeconds / 60) / 60) / 24; + secondTimeVal = secondFormulaVal.toString(); + } else { + secondTimeVal = secondFormula; + } } - } - - if (secondFormulaCheck.length == 3) { - final int? hour = int.tryParse(secondFormulaCheck[0]); - final int? min = int.tryParse(secondFormulaCheck[1]); - final int? sec = int.tryParse(secondFormulaCheck[2]); - - if (hour != null && min != null && sec != null) { - duration = Duration(hours: hour, minutes: min, seconds: sec); - secondFormulaVal = ((duration.inSeconds / 60) / 60) / 24; - secondTimeVal = secondFormulaVal.toString(); - } else { + if (firstFormulaCheck.length != 2 && firstFormulaCheck.length != 3) { + firstTimeVal = firstFormula; + } + if (secondFormulaCheck.length != 2 && + secondFormulaCheck.length != 3) { secondTimeVal = secondFormula; } - } + if (firstTimeVal != '') { + builder.element('formula1', nest: firstTimeVal); + } + if (secondTimeVal != '') { + builder.element('formula2', nest: secondTimeVal); + } + } else if ('list' == _getDataType(dataType)) { + final List firstFormula = dataValidationImpl.listOfValues; + late String listOfValues = ''; + if (firstFormula.isNotEmpty) { + for (int listVal = 0; listVal < firstFormula.length; listVal++) { + late String comma; + if (listVal == 0) { + comma = ''; + } else { + comma = ','; + } - if (firstFormulaCheck.length != 2 && firstFormulaCheck.length != 3) { - firstTimeVal = firstFormula; - } - if (secondFormulaCheck.length != 2 && secondFormulaCheck.length != 3) { - secondTimeVal = secondFormula; - } - if (firstTimeVal != '') { - builder.element('formula1', nest: firstTimeVal); - } - if (secondTimeVal != '') { - builder.element('formula2', nest: secondTimeVal); - } - } else if ('list' == _getDataType(dataType)) { - final List firstFormula = dataValidationImpl.listOfValues; - late String listOfValues = ''; - if (firstFormula.isNotEmpty) { - for (int listVal = 0; listVal < firstFormula.length; listVal++) { - late String comma; - if (listVal == 0) { - comma = ''; - } else { - comma = ','; + listOfValues = listOfValues + comma + firstFormula[listVal]; } - listOfValues = listOfValues + comma + firstFormula[listVal]; - } - - builder.element('formula1', nest: '" $listOfValues"'); - } else { - final String firstFormulaSelect = - dataValidationImpl.dataRangeVal.addressGlobal; + builder.element('formula1', nest: '" $listOfValues"'); + } else { + final String firstFormulaSelect = + dataValidationImpl.dataRangeVal.addressGlobal; - builder.element('formula1', nest: firstFormulaSelect); - } - } else if ('custom' == _getDataType(dataType)) { - final String firstFormula = dataValidationImpl.firstFormula; - final String secondFormula = dataValidationImpl.secondFormula; - if (firstFormula.isNotEmpty) { - builder.element('formula1', nest: firstFormula); - } else if (firstFormula == '' && secondFormula.isNotEmpty) { - builder.element('formula1', nest: secondFormula); - } - } else { - final DateTime firstDateTime = dataValidationImpl.firstDateTimeVal; - final DateTime secondDateTime = dataValidationImpl.secondDateTime; - final String firstDateTimeVal = - Range.toOADate(firstDateTime).toString(); - final String secondDateTimeVal = - Range.toOADate(secondDateTime).toString(); - if (firstDateTime != DateTime(1)) { - builder.element('formula1', nest: firstDateTimeVal); - } - if (secondDateTime != DateTime(1)) { - builder.element('formula2', nest: secondDateTimeVal); + builder.element('formula1', nest: firstFormulaSelect); + } + } else if ('custom' == _getDataType(dataType)) { + final String firstFormula = dataValidationImpl.firstFormula; + final String secondFormula = dataValidationImpl.secondFormula; + if (firstFormula.isNotEmpty) { + builder.element('formula1', nest: firstFormula); + } else if (firstFormula == '' && secondFormula.isNotEmpty) { + builder.element('formula1', nest: secondFormula); + } + } else { + final DateTime firstDateTime = dataValidationImpl.firstDateTimeVal; + final DateTime secondDateTime = dataValidationImpl.secondDateTime; + final String firstDateTimeVal = + Range.toOADate(firstDateTime).toString(); + final String secondDateTimeVal = + Range.toOADate(secondDateTime).toString(); + if (firstDateTime != DateTime(1)) { + builder.element('formula1', nest: firstDateTimeVal); + } + if (secondDateTime != DateTime(1)) { + builder.element('formula2', nest: secondDateTimeVal); + } } - } - }); + }, + ); } void _serializeConditionalFormatting(XmlBuilder builder, Worksheet sheet) { @@ -4776,7 +6107,12 @@ class SerializeWorkbook { final ConditionalFormatsImpl conditionalFormats = sheet.conditionalFormats[i]; final List result = _serializeConditionalFormats( - builder, _iDxfIndex, iPriority, iPriorityCount, conditionalFormats); + builder, + _iDxfIndex, + iPriority, + iPriorityCount, + conditionalFormats, + ); _iDxfIndex = result[0] as int; iPriority = result[1] as int; iPriorityCount = result[2] as int; @@ -4785,7 +6121,9 @@ class SerializeWorkbook { } Future _serializeConditionalFormattingAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { if (sheet.conditionalFormats.isNotEmpty) { final int iCount = sheet.conditionalFormats.length; int iPriority = 1; @@ -4794,7 +6132,12 @@ class SerializeWorkbook { final ConditionalFormatsImpl conditionalFormats = sheet.conditionalFormats[i]; final List result = _serializeConditionalFormats( - builder, _iDxfIndex, iPriority, iPriorityCount, conditionalFormats); + builder, + _iDxfIndex, + iPriority, + iPriorityCount, + conditionalFormats, + ); _iDxfIndex = result[0] as int; iPriority = result[1] as int; iPriorityCount = result[2] as int; @@ -4802,8 +6145,13 @@ class SerializeWorkbook { } } - List _serializeConditionalFormats(XmlBuilder builder, int iDxfIndex, - int iPriority, int iPriorityCount, ConditionalFormatsImpl formats) { + List _serializeConditionalFormats( + XmlBuilder builder, + int iDxfIndex, + int iPriority, + int iPriorityCount, + ConditionalFormatsImpl formats, + ) { final int iRulesCount = formats.count; bool serializeCF = false; if (iRulesCount == 0) { @@ -4828,32 +6176,42 @@ class SerializeWorkbook { } } if (serializeCF) { - builder.element('conditionalFormatting', nest: () { - builder.attribute('sqref', formats.cellList); - int iCount = iRulesCount + iPriorityCount; - iPriorityCount += iRulesCount; - for (int i = 0; i < iRulesCount; i++) { - final ConditionalFormat condition = formats.innerList[i]; - if (!(condition as ConditionalFormatImpl).bCFHasExtensionList) { - final List result = _serializeCondition( - builder, condition, '', iDxfIndex, iPriority, iCount); - iDxfIndex = result[0] as int; - iPriority = result[1] as int; - iCount = result[2] as int; + builder.element( + 'conditionalFormatting', + nest: () { + builder.attribute('sqref', formats.cellList); + int iCount = iRulesCount + iPriorityCount; + iPriorityCount += iRulesCount; + for (int i = 0; i < iRulesCount; i++) { + final ConditionalFormat condition = formats.innerList[i]; + if (!(condition as ConditionalFormatImpl).bCFHasExtensionList) { + final List result = _serializeCondition( + builder, + condition, + '', + iDxfIndex, + iPriority, + iCount, + ); + iDxfIndex = result[0] as int; + iPriority = result[1] as int; + iCount = result[2] as int; + } } - } - }); + }, + ); } return [iDxfIndex, iPriority, iPriorityCount]; } List _serializeCondition( - XmlBuilder builder, - ConditionalFormat condition, - String prefix, - int iDxfIndex, - int iPriority, - int iCount) { + XmlBuilder builder, + ConditionalFormat condition, + String prefix, + int iDxfIndex, + int iPriority, + int iCount, + ) { final ConditionalFormatImpl condFormat = condition as ConditionalFormatImpl; IconSetImpl? iconSet; if (condFormat.iconSet != null) { @@ -4862,125 +6220,182 @@ class SerializeWorkbook { final ExcelCFType cfType = condition.formatType; final ExcelComparisonOperator comparisonOperator = condition.operator; final CFTimePeriods cfTimePeriod = condition.timePeriodType; - builder.element('${prefix}cfRule', nest: () { - builder.attribute('type', _getCFType(cfType, comparisonOperator)); - if (_checkFormat(condition)) { - builder.attribute('dxfId', iDxfIndex.toString()); - iDxfIndex++; - } - if (condition.stopIfTrue) { - builder.attribute('stopIfTrue', '1'); - } - if (cfType == ExcelCFType.cellValue) { - builder.attribute( - 'operator', _getCFComparisonOperatorName(condition.operator)); - } - if (cfType == ExcelCFType.specificText) { - builder.attribute( - 'operator', _getCFComparisonOperatorName(condition.operator)); - // ignore: unnecessary_null_checks - builder.attribute('text', condition.text!); - } - if (cfType == ExcelCFType.timePeriod) { - builder.attribute('timePeriod', _getCFTimePeriodType(cfTimePeriod)); - } - - builder.attribute('priority', iCount); - iCount--; - - if (cfType == ExcelCFType.topBottom) { - _serializeAttributes(builder, 'bottom', - condition.topBottom!.type == ExcelCFTopBottomType.bottom, false); - _serializeAttributes( - builder, 'percent', condition.topBottom!.percent, false); - builder.attribute('rank', condition.topBottom!.rank.toString()); - } - if (cfType == ExcelCFType.aboveBelowAverage) { - final String avgStrType = condition.aboveBelowAverage!.averageType - .toString() - .split('.') - .toList() - .removeAt(1) - .toLowerCase(); - _serializeAttributes( - builder, 'aboveAverage', !avgStrType.contains('below'), true); - _serializeAttributes( - builder, 'equalAverage', avgStrType.contains('equal'), false); - if (avgStrType.contains('stddev')) { + builder.element( + '${prefix}cfRule', + nest: () { + builder.attribute('type', _getCFType(cfType, comparisonOperator)); + if (_checkFormat(condition)) { + builder.attribute('dxfId', iDxfIndex.toString()); + iDxfIndex++; + } + if (condition.stopIfTrue) { + builder.attribute('stopIfTrue', '1'); + } + if (cfType == ExcelCFType.cellValue) { builder.attribute( - 'stdDev', condition.aboveBelowAverage!.stdDevValue.toString()); + 'operator', + _getCFComparisonOperatorName(condition.operator), + ); } - } - if (condition.firstFormula != '') { - String v1 = condition.firstFormula; - if (v1[0] == '=') { - v1 = v1.substring(1); + if (cfType == ExcelCFType.specificText) { + builder.attribute( + 'operator', + _getCFComparisonOperatorName(condition.operator), + ); + // ignore: unnecessary_null_checks + builder.attribute('text', condition.text!); + } + if (cfType == ExcelCFType.timePeriod) { + builder.attribute('timePeriod', _getCFTimePeriodType(cfTimePeriod)); + } + + builder.attribute('priority', iCount); + iCount--; + + if (cfType == ExcelCFType.topBottom) { + _serializeAttributes( + builder, + 'bottom', + condition.topBottom!.type == ExcelCFTopBottomType.bottom, + false, + ); + _serializeAttributes( + builder, + 'percent', + condition.topBottom!.percent, + false, + ); + builder.attribute('rank', condition.topBottom!.rank.toString()); + } + if (cfType == ExcelCFType.aboveBelowAverage) { + final String avgStrType = + condition.aboveBelowAverage!.averageType + .toString() + .split('.') + .toList() + .removeAt(1) + .toLowerCase(); + _serializeAttributes( + builder, + 'aboveAverage', + !avgStrType.contains('below'), + true, + ); + _serializeAttributes( + builder, + 'equalAverage', + avgStrType.contains('equal'), + false, + ); + if (avgStrType.contains('stddev')) { + builder.attribute( + 'stdDev', + condition.aboveBelowAverage!.stdDevValue.toString(), + ); + } } - v1 = v1.replaceAll("'", '"'); - builder.element('${prefix}formula', nest: v1); - } - if (condition.secondFormula != '') { - String v1 = condition.secondFormula; - if (v1[0] == '=') { - v1 = v1.substring(1); + if (condition.firstFormula != '') { + String v1 = condition.firstFormula; + if (v1[0] == '=') { + v1 = v1.substring(1); + } + v1 = v1.replaceAll("'", '"'); + builder.element('${prefix}formula', nest: v1); } - v1 = v1.replaceAll("'", '"'); - builder.element('${prefix}formula', nest: v1); - } - if (cfType == ExcelCFType.dataBar) { - _serializeDataBar(builder, condition.dataBar!); - } - if (cfType == ExcelCFType.colorScale) { - _serializeColorScale(builder, condition.colorScale!); - } else if (cfType == ExcelCFType.iconSet) { - if (condFormat.bCFHasExtensionList || - (iconSet != null && iconSet.isCustom)) { - _serializeIconSet(builder, iconSet!, condFormat.bCFHasExtensionList, - iconSet.isCustom); - } else { - _serializeIconSet(builder, iconSet!, false, false); + if (condition.secondFormula != '') { + String v1 = condition.secondFormula; + if (v1[0] == '=') { + v1 = v1.substring(1); + } + v1 = v1.replaceAll("'", '"'); + builder.element('${prefix}formula', nest: v1); + } + if (cfType == ExcelCFType.dataBar) { + _serializeDataBar(builder, condition.dataBar!); + } + if (cfType == ExcelCFType.colorScale) { + _serializeColorScale(builder, condition.colorScale!); + } else if (cfType == ExcelCFType.iconSet) { + if (condFormat.bCFHasExtensionList || + (iconSet != null && iconSet.isCustom)) { + _serializeIconSet( + builder, + iconSet!, + condFormat.bCFHasExtensionList, + iconSet.isCustom, + ); + } else { + _serializeIconSet(builder, iconSet!, false, false); + } } - } - if (condition.dataBar != null && - (condition.dataBar! as DataBarImpl).hasExtensionList) { - builder.element('extLst', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.element('ext', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - - builder.attribute('uri', '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - - builder.element('x14:id', - nest: (condition.dataBar! as DataBarImpl).stGUID); - }); - }); - } - }); + if (condition.dataBar != null && + (condition.dataBar! as DataBarImpl).hasExtensionList) { + builder.element( + 'extLst', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.element( + 'ext', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + + builder.attribute( + 'uri', + '{B025F937-C7B1-47D3-B67F-A62EFF666E3E}', + ); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + + builder.element( + 'x14:id', + nest: (condition.dataBar! as DataBarImpl).stGUID, + ); + }, + ); + }, + ); + } + }, + ); return [iDxfIndex, iPriority, iCount]; } /// Serializes color scale of conditional format. void _serializeColorScale(XmlBuilder builder, ColorScale colorScale) { - builder.element('colorScale', nest: () { - final List arrConditions = colorScale.criteria; - for (int i = 0; i < arrConditions.length; i++) { - _serializeConditionValueObject( - builder, arrConditions[i], false, false, false); - } + builder.element( + 'colorScale', + nest: () { + final List arrConditions = colorScale.criteria; + for (int i = 0; i < arrConditions.length; i++) { + _serializeConditionValueObject( + builder, + arrConditions[i], + false, + false, + false, + ); + } - for (int i = 0; i < arrConditions.length; i++) { - _serializeRgbColor(builder, 'color', arrConditions[i].formatColor); - } - }); + for (int i = 0; i < arrConditions.length; i++) { + _serializeRgbColor(builder, 'color', arrConditions[i].formatColor); + } + }, + ); } /// Serializes icon set. - void _serializeIconSet(XmlBuilder builder, IconSet iconSet, - bool cfHasExtensionList, bool isCustom) { + void _serializeIconSet( + XmlBuilder builder, + IconSet iconSet, + bool cfHasExtensionList, + bool isCustom, + ) { String element; if (cfHasExtensionList || isCustom) { element = 'x14:iconSet'; @@ -4988,141 +6403,194 @@ class SerializeWorkbook { element = 'iconSet'; } - builder.element(element, nest: () { - final int index = iconSet.iconSet.index; - final String strType = _iconSetTypeNames[index]; + builder.element( + element, + nest: () { + final int index = iconSet.iconSet.index; + final String strType = _iconSetTypeNames[index]; - builder.attribute('iconSet', strType); - _serializeAttributes(builder, 'percent', iconSet.percentileValues, false); - _serializeAttributes(builder, 'reverse', iconSet.reverseOrder, false); - _serializeAttributes(builder, 'showValue', !iconSet.showIconOnly, true); + builder.attribute('iconSet', strType); + _serializeAttributes( + builder, + 'percent', + iconSet.percentileValues, + false, + ); + _serializeAttributes(builder, 'reverse', iconSet.reverseOrder, false); + _serializeAttributes(builder, 'showValue', !iconSet.showIconOnly, true); - if (isCustom) { - _serializeAttributes(builder, 'custom', true, false); - } + if (isCustom) { + _serializeAttributes(builder, 'custom', true, false); + } - final List arrConditions = iconSet.iconCriteria; - for (int i = 0; i < arrConditions.length; i++) { - _serializeConditionValueObject( - builder, arrConditions[i], true, cfHasExtensionList, isCustom); - } - if (isCustom) { + final List arrConditions = iconSet.iconCriteria; for (int i = 0; i < arrConditions.length; i++) { - _serializeCustomCFIcon( - builder, arrConditions[i] as IconConditionValue, true); + _serializeConditionValueObject( + builder, + arrConditions[i], + true, + cfHasExtensionList, + isCustom, + ); + } + if (isCustom) { + for (int i = 0; i < arrConditions.length; i++) { + _serializeCustomCFIcon( + builder, + arrConditions[i] as IconConditionValue, + true, + ); + } } - } - }); + }, + ); } /// Serializes data bar. void _serializeDataBar(XmlBuilder builder, DataBar dataBar) { - builder.element('dataBar', nest: () { - _serializeAttributeInt(builder, 'minLength', dataBar.percentMin, 0); - _serializeAttributeInt(builder, 'maxLength', dataBar.percentMax, 100); - _serializeAttributes(builder, 'showValue', dataBar.showValue, true); - - _serializeConditionValueObjectForDataBar( - builder, dataBar.minPoint, false, true); - _serializeConditionValueObjectForDataBar( - builder, dataBar.maxPoint, false, false); - _serializeRgbColor(builder, 'color', dataBar.barColor); - }); + builder.element( + 'dataBar', + nest: () { + _serializeAttributeInt(builder, 'minLength', dataBar.percentMin, 0); + _serializeAttributeInt(builder, 'maxLength', dataBar.percentMax, 100); + _serializeAttributes(builder, 'showValue', dataBar.showValue, true); + + _serializeConditionValueObjectForDataBar( + builder, + dataBar.minPoint, + false, + true, + ); + _serializeConditionValueObjectForDataBar( + builder, + dataBar.maxPoint, + false, + false, + ); + _serializeRgbColor(builder, 'color', dataBar.barColor); + }, + ); } /// Serializes conditional value object. void _serializeConditionValueObject( - XmlBuilder builder, - ConditionValue conditionValue, - bool isIconSet, - bool cfHasExtensionList, - bool isCustom) { + XmlBuilder builder, + ConditionValue conditionValue, + bool isIconSet, + bool cfHasExtensionList, + bool isCustom, + ) { String prefix = ''; if (cfHasExtensionList || isCustom) { prefix = 'x14:'; } - builder.element('${prefix}cfvo', nest: () { - final int index = conditionValue.type.index; - final String strType = _valueTypes[index]; - String value = conditionValue.value; + builder.element( + '${prefix}cfvo', + nest: () { + final int index = conditionValue.type.index; + final String strType = _valueTypes[index]; + String value = conditionValue.value; - builder.attribute('type', strType); + builder.attribute('type', strType); - if (strType == 'formula' && value.startsWith(Range.equalsSign)) { - value = value.replaceAll(Range.equalsSign, ''); - } + if (strType == 'formula' && value.startsWith(Range.equalsSign)) { + value = value.replaceAll(Range.equalsSign, ''); + } - if (!cfHasExtensionList) { - builder.attribute('val', value); - } else if (!cfHasExtensionList) { - builder.attribute('val', value); - } + if (!cfHasExtensionList) { + builder.attribute('val', value); + } else if (!cfHasExtensionList) { + builder.attribute('val', value); + } - builder.attribute('gte', conditionValue.operator.index.toString()); + builder.attribute('gte', conditionValue.operator.index.toString()); - if (cfHasExtensionList || isCustom) { - builder.element('xm:f', nest: value); - } - }); + if (cfHasExtensionList || isCustom) { + builder.element('xm:f', nest: value); + } + }, + ); } /// Serializes conditional value object. - void _serializeConditionValueObjectForDataBar(XmlBuilder builder, - ConditionValue conditionValue, bool isIconSet, bool isMinPoint) { - builder.element('cfvo', nest: () { - int index = conditionValue.type.index; - if (index == 7) { - if (isMinPoint) { - index = 2; - } else { - index = 3; + void _serializeConditionValueObjectForDataBar( + XmlBuilder builder, + ConditionValue conditionValue, + bool isIconSet, + bool isMinPoint, + ) { + builder.element( + 'cfvo', + nest: () { + int index = conditionValue.type.index; + if (index == 7) { + if (isMinPoint) { + index = 2; + } else { + index = 3; + } } - } - final String strType = _valueTypes[index]; - builder.attribute('type', strType); - builder.attribute('val', conditionValue.value); - if (isIconSet) { - builder.attribute('gte', conditionValue.operator.index.toString()); - } - }); + final String strType = _valueTypes[index]; + builder.attribute('type', strType); + builder.attribute('val', conditionValue.value); + if (isIconSet) { + builder.attribute('gte', conditionValue.operator.index.toString()); + } + }, + ); } /// Serializes Custom iconset object. void _serializeCustomCFIcon( - XmlBuilder builder, IconConditionValue conditionValue, bool isIconSet) { - builder.element('x14:cfIcon', nest: () { - String iconType = ''; - if (conditionValue.iconSet.toString() == '-1') { - iconType = 'NoIcons'; - } else { - iconType = _iconSetTypeNames[conditionValue.iconSet.index]; - } - final String iconIndex = conditionValue.index.toString(); - builder.attribute('iconSet', iconType); - builder.attribute('iconId', iconIndex); - }); + XmlBuilder builder, + IconConditionValue conditionValue, + bool isIconSet, + ) { + builder.element( + 'x14:cfIcon', + nest: () { + String iconType = ''; + if (conditionValue.iconSet.toString() == '-1') { + iconType = 'NoIcons'; + } else { + iconType = _iconSetTypeNames[conditionValue.iconSet.index]; + } + final String iconIndex = conditionValue.index.toString(); + builder.attribute('iconSet', iconType); + builder.attribute('iconId', iconIndex); + }, + ); } /// Serializes Rgb color value. void _serializeRgbColor(XmlBuilder builder, String tagName, String color) { - builder.element(tagName, nest: () { - String colorValue = color; - if (colorValue.length <= 7) { - colorValue = 'FF${color.replaceAll('#', '')}'; - } - builder.attribute('rgb', colorValue); - }); + builder.element( + tagName, + nest: () { + String colorValue = color; + if (colorValue.length <= 7) { + colorValue = 'FF${color.replaceAll('#', '')}'; + } + builder.attribute('rgb', colorValue); + }, + ); } Future _serializeRgbColorAsync( - XmlBuilder builder, String tagName, String color) async { - builder.element(tagName, nest: () async { - String colorValue = color; - if (colorValue.length <= 7) { - colorValue = 'FF${color.replaceAll('#', '')}'; - } - builder.attribute('rgb', colorValue); - }); + XmlBuilder builder, + String tagName, + String color, + ) async { + builder.element( + tagName, + nest: () async { + String colorValue = color; + if (colorValue.length <= 7) { + colorValue = 'FF${color.replaceAll('#', '')}'; + } + builder.attribute('rgb', colorValue); + }, + ); } /// Returns CF type string name. @@ -5182,7 +6650,8 @@ class SerializeWorkbook { /// Returns CF comparison operator string name. String _getCFComparisonOperatorName( - ExcelComparisonOperator comparisonOperator) { + ExcelComparisonOperator comparisonOperator, + ) { switch (comparisonOperator) { case ExcelComparisonOperator.between: return 'between'; @@ -5241,170 +6710,236 @@ class SerializeWorkbook { /// Serialize Dxfs. void _serialiseDxfs(XmlBuilder builder) { - builder.element('dxfs', nest: () { - for (final Worksheet sheet in _workbook.worksheets.innerList) { - if (sheet.autoFilters.innerList.isNotEmpty) { - for (int i = 0; i < sheet.autoFilters.count; i++) { - if (sheet.autoFilters[i].filterType == - ExcelFilterType.colorFilter) { - _serializeDxfColorFilter( - builder, sheet.autoFilters[i] as AutoFilterImpl); + builder.element( + 'dxfs', + nest: () { + for (final Worksheet sheet in _workbook.worksheets.innerList) { + if (sheet.autoFilters.innerList.isNotEmpty) { + for (int i = 0; i < sheet.autoFilters.count; i++) { + if (sheet.autoFilters[i].filterType == + ExcelFilterType.colorFilter) { + _serializeDxfColorFilter( + builder, + sheet.autoFilters[i] as AutoFilterImpl, + ); + } } } - } - if (sheet.conditionalFormats.isNotEmpty) { - final int iCount = sheet.conditionalFormats.length; - for (int i = 0; i < iCount; i++) { - final ConditionalFormatsImpl condFormats = - sheet.conditionalFormats[i]; - for (final ConditionalFormatImpl condition - in condFormats.innerList) { - if (_checkFormat(condition)) { - _serializeDxf(builder, condition); + if (sheet.conditionalFormats.isNotEmpty) { + final int iCount = sheet.conditionalFormats.length; + for (int i = 0; i < iCount; i++) { + final ConditionalFormatsImpl condFormats = + sheet.conditionalFormats[i]; + for (final ConditionalFormatImpl condition + in condFormats.innerList) { + if (_checkFormat(condition)) { + _serializeDxf(builder, condition); + } } } } } - } - }); + }, + ); } Future _serialiseDxfsAsync(XmlBuilder builder) async { - builder.element('dxfs', nest: () async { - for (final Worksheet sheet in _workbook.worksheets.innerList) { - if (sheet.autoFilters.innerList.isNotEmpty) { - for (int i = 0; i < sheet.autoFilters.count; i++) { - if (sheet.autoFilters[i].filterType == - ExcelFilterType.colorFilter) { - _serializeDxfColorFilterAsync( - builder, sheet.autoFilters[i] as AutoFilterImpl); + builder.element( + 'dxfs', + nest: () async { + for (final Worksheet sheet in _workbook.worksheets.innerList) { + if (sheet.autoFilters.innerList.isNotEmpty) { + for (int i = 0; i < sheet.autoFilters.count; i++) { + if (sheet.autoFilters[i].filterType == + ExcelFilterType.colorFilter) { + _serializeDxfColorFilterAsync( + builder, + sheet.autoFilters[i] as AutoFilterImpl, + ); + } } } - } - if (sheet.conditionalFormats.isNotEmpty) { - final int iCount = sheet.conditionalFormats.length; - for (int i = 0; i < iCount; i++) { - final ConditionalFormatsImpl condFormats = - sheet.conditionalFormats[i]; - for (final ConditionalFormatImpl condition - in condFormats.innerList) { - if (_checkFormat(condition)) { - _serializeDxfAsync(builder, condition); + if (sheet.conditionalFormats.isNotEmpty) { + final int iCount = sheet.conditionalFormats.length; + for (int i = 0; i < iCount; i++) { + final ConditionalFormatsImpl condFormats = + sheet.conditionalFormats[i]; + for (final ConditionalFormatImpl condition + in condFormats.innerList) { + if (_checkFormat(condition)) { + _serializeDxfAsync(builder, condition); + } } } } } - } - }); + }, + ); } ///Serialize color filter dxf style. void _serializeDxfColorFilter(XmlBuilder builder, AutoFilterImpl autoFilter) { - builder.element('dxf', nest: () { - _serializeDxfColorFilterFill( - builder, autoFilter.filteredItems as ColorFilter); - }); + builder.element( + 'dxf', + nest: () { + _serializeDxfColorFilterFill( + builder, + autoFilter.filteredItems as ColorFilter, + ); + }, + ); } Future _serializeDxfColorFilterAsync( - XmlBuilder builder, AutoFilterImpl autoFilter) async { - builder.element('dxf', nest: () async { - _serializeDxfColorFilterFillAsync( - builder, autoFilter.filteredItems as ColorFilter); - }); + XmlBuilder builder, + AutoFilterImpl autoFilter, + ) async { + builder.element( + 'dxf', + nest: () async { + _serializeDxfColorFilterFillAsync( + builder, + autoFilter.filteredItems as ColorFilter, + ); + }, + ); } ///Serialize dxf color filter style fill. void _serializeDxfColorFilterFill( - XmlBuilder builder, ColorFilter colorFilter) { + XmlBuilder builder, + ColorFilter colorFilter, + ) { String foreColor; - builder.element('fill', nest: () { - builder.element('patternFill', nest: () { - if (colorFilter.colorFilterType == ExcelColorFilterType.cellColor && - colorFilter.color == '#000000') { - builder.attribute('patternType', 'none'); - } else { - builder.attribute('patternType', 'solid'); - } + builder.element( + 'fill', + nest: () { + builder.element( + 'patternFill', + nest: () { + if (colorFilter.colorFilterType == ExcelColorFilterType.cellColor && + colorFilter.color == '#000000') { + builder.attribute('patternType', 'none'); + } else { + builder.attribute('patternType', 'solid'); + } - if (colorFilter.color == '#000000') { - if (colorFilter.colorFilterType == ExcelColorFilterType.cellColor) { - builder.element('fgColor', nest: () { - builder.attribute('indexed', '64'); - }); - } else { - builder.element('fgColor', nest: () { - builder.attribute('indexed', '66'); - }); - } - } else { - if (colorFilter.color.length == 7) { - foreColor = 'FF${colorFilter.color.replaceAll('#', '')}'; - } else { - foreColor = colorFilter.color; - } - builder.element('fgColor', nest: () { - builder.attribute('rgb', foreColor); - }); - } - }); - }); + if (colorFilter.color == '#000000') { + if (colorFilter.colorFilterType == + ExcelColorFilterType.cellColor) { + builder.element( + 'fgColor', + nest: () { + builder.attribute('indexed', '64'); + }, + ); + } else { + builder.element( + 'fgColor', + nest: () { + builder.attribute('indexed', '66'); + }, + ); + } + } else { + if (colorFilter.color.length == 7) { + foreColor = 'FF${colorFilter.color.replaceAll('#', '')}'; + } else { + foreColor = colorFilter.color; + } + builder.element( + 'fgColor', + nest: () { + builder.attribute('rgb', foreColor); + }, + ); + } + }, + ); + }, + ); } Future _serializeDxfColorFilterFillAsync( - XmlBuilder builder, ColorFilter colorFilter) async { + XmlBuilder builder, + ColorFilter colorFilter, + ) async { String foreColor; - builder.element('fill', nest: () async { - builder.element('patternFill', nest: () async { - if (colorFilter.colorFilterType == ExcelColorFilterType.cellColor && - colorFilter.color == '#000000') { - builder.attribute('patternType', 'none'); - } else { - builder.attribute('patternType', 'solid'); - } + builder.element( + 'fill', + nest: () async { + builder.element( + 'patternFill', + nest: () async { + if (colorFilter.colorFilterType == ExcelColorFilterType.cellColor && + colorFilter.color == '#000000') { + builder.attribute('patternType', 'none'); + } else { + builder.attribute('patternType', 'solid'); + } - if (colorFilter.color == '#000000') { - if (colorFilter.colorFilterType == ExcelColorFilterType.cellColor) { - builder.element('fgColor', nest: () async { - builder.attribute('indexed', '64'); - }); - } else { - builder.element('fgColor', nest: () async { - builder.attribute('indexed', '66'); - }); - } - } else { - if (colorFilter.color.length == 7) { - foreColor = 'FF${colorFilter.color.replaceAll('#', '')}'; - } else { - foreColor = colorFilter.color; - } - builder.element('fgColor', nest: () async { - builder.attribute('rgb', foreColor); - }); - } - }); - }); + if (colorFilter.color == '#000000') { + if (colorFilter.colorFilterType == + ExcelColorFilterType.cellColor) { + builder.element( + 'fgColor', + nest: () async { + builder.attribute('indexed', '64'); + }, + ); + } else { + builder.element( + 'fgColor', + nest: () async { + builder.attribute('indexed', '66'); + }, + ); + } + } else { + if (colorFilter.color.length == 7) { + foreColor = 'FF${colorFilter.color.replaceAll('#', '')}'; + } else { + foreColor = colorFilter.color; + } + builder.element( + 'fgColor', + nest: () async { + builder.attribute('rgb', foreColor); + }, + ); + } + }, + ); + }, + ); } /// Serializes Dxf style. void _serializeDxf(XmlBuilder builder, ConditionalFormatImpl condition) { - builder.element('dxf', nest: () { - _serializeDxfFont(builder, condition); - _serializeDxfNumberFormat(builder, condition); - _serializeDxfFill(builder, condition); - _serializeDxfBorders(builder, condition); - }); + builder.element( + 'dxf', + nest: () { + _serializeDxfFont(builder, condition); + _serializeDxfNumberFormat(builder, condition); + _serializeDxfFill(builder, condition); + _serializeDxfBorders(builder, condition); + }, + ); } Future _serializeDxfAsync( - XmlBuilder builder, ConditionalFormatImpl condition) async { - builder.element('dxf', nest: () async { - _serializeDxfFontAsync(builder, condition); - _serializeDxfNumberFormatAsync(builder, condition); - _serializeDxfFillAsync(builder, condition); - _serializeDxfBordersAsync(builder, condition); - }); + XmlBuilder builder, + ConditionalFormatImpl condition, + ) async { + builder.element( + 'dxf', + nest: () async { + _serializeDxfFontAsync(builder, condition); + _serializeDxfNumberFormatAsync(builder, condition); + _serializeDxfFillAsync(builder, condition); + _serializeDxfBordersAsync(builder, condition); + }, + ); } /// Serializes Dxf style font. @@ -5413,61 +6948,77 @@ class SerializeWorkbook { condition.isItalic || condition.underline || condition.fontColor != '#000000') { - builder.element('font', nest: () { - if (condition.isBold) { - builder.element('b', nest: () {}); - } - if (condition.isItalic) { - builder.element('i', nest: () {}); - } - if (condition.underline) { - builder.element('u', nest: () {}); - } - String fontColor; - if (condition.fontColor.length <= 7) { - fontColor = 'FF${condition.fontColor.replaceAll('#', '')}'; - } else { - fontColor = condition.fontColor; - } - builder.element('color', nest: () { - builder.attribute('rgb', fontColor); - }); - }); + builder.element( + 'font', + nest: () { + if (condition.isBold) { + builder.element('b', nest: () {}); + } + if (condition.isItalic) { + builder.element('i', nest: () {}); + } + if (condition.underline) { + builder.element('u', nest: () {}); + } + String fontColor; + if (condition.fontColor.length <= 7) { + fontColor = 'FF${condition.fontColor.replaceAll('#', '')}'; + } else { + fontColor = condition.fontColor; + } + builder.element( + 'color', + nest: () { + builder.attribute('rgb', fontColor); + }, + ); + }, + ); } } Future _serializeDxfFontAsync( - XmlBuilder builder, ConditionalFormatImpl condition) async { + XmlBuilder builder, + ConditionalFormatImpl condition, + ) async { if (condition.isBold || condition.isItalic || condition.underline || condition.fontColor != '#000000') { - builder.element('font', nest: () async { - if (condition.isBold) { - builder.element('b', nest: () async {}); - } - if (condition.isItalic) { - builder.element('i', nest: () async {}); - } - if (condition.underline) { - builder.element('u', nest: () async {}); - } - String fontColor; - if (condition.fontColor.length <= 7) { - fontColor = 'FF${condition.fontColor.replaceAll('#', '')}'; - } else { - fontColor = condition.fontColor; - } - builder.element('color', nest: () async { - builder.attribute('rgb', fontColor); - }); - }); + builder.element( + 'font', + nest: () async { + if (condition.isBold) { + builder.element('b', nest: () async {}); + } + if (condition.isItalic) { + builder.element('i', nest: () async {}); + } + if (condition.underline) { + builder.element('u', nest: () async {}); + } + String fontColor; + if (condition.fontColor.length <= 7) { + fontColor = 'FF${condition.fontColor.replaceAll('#', '')}'; + } else { + fontColor = condition.fontColor; + } + builder.element( + 'color', + nest: () async { + builder.attribute('rgb', fontColor); + }, + ); + }, + ); } } /// Serializes Dxf number format. void _serializeDxfNumberFormat( - XmlBuilder builder, ConditionalFormatImpl condition) { + XmlBuilder builder, + ConditionalFormatImpl condition, + ) { if (condition.numberFormat != 'General') { int index; Format? format; @@ -5477,16 +7028,24 @@ class SerializeWorkbook { } else { index = _workbook.innerFormats.createFormat(condition.numberFormat); } - builder.element('numFmt', nest: () { - builder.attribute('numFmtId', index.toString()); - final String formatString = format!.formatString!.replaceAll("'", '"'); - builder.attribute('formatCode', formatString); - }); + builder.element( + 'numFmt', + nest: () { + builder.attribute('numFmtId', index.toString()); + final String formatString = format!.formatString!.replaceAll( + "'", + '"', + ); + builder.attribute('formatCode', formatString); + }, + ); } } Future _serializeDxfNumberFormatAsync( - XmlBuilder builder, ConditionalFormatImpl condition) async { + XmlBuilder builder, + ConditionalFormatImpl condition, + ) async { if (condition.numberFormat != 'General') { int index; Format? format; @@ -5496,11 +7055,17 @@ class SerializeWorkbook { } else { index = _workbook.innerFormats.createFormat(condition.numberFormat); } - builder.element('numFmt', nest: () async { - builder.attribute('numFmtId', index.toString()); - final String formatString = format!.formatString!.replaceAll("'", '"'); - builder.attribute('formatCode', formatString); - }); + builder.element( + 'numFmt', + nest: () async { + builder.attribute('numFmtId', index.toString()); + final String formatString = format!.formatString!.replaceAll( + "'", + '"', + ); + builder.attribute('formatCode', formatString); + }, + ); } } @@ -5513,18 +7078,29 @@ class SerializeWorkbook { } else { backColor = condition.backColor; } - builder.element('fill', nest: () { - builder.element('patternFill', nest: () { - builder.element('bgColor', nest: () { - builder.attribute('rgb', backColor); - }); - }); - }); + builder.element( + 'fill', + nest: () { + builder.element( + 'patternFill', + nest: () { + builder.element( + 'bgColor', + nest: () { + builder.attribute('rgb', backColor); + }, + ); + }, + ); + }, + ); } } Future _serializeDxfFillAsync( - XmlBuilder builder, ConditionalFormatImpl condition) async { + XmlBuilder builder, + ConditionalFormatImpl condition, + ) async { String backColor; if (condition.backColor != '#FFFFFF') { if (condition.backColor.length == 7) { @@ -5532,102 +7108,183 @@ class SerializeWorkbook { } else { backColor = condition.backColor; } - builder.element('fill', nest: () async { - builder.element('patternFill', nest: () async { - builder.element('bgColor', nest: () async { - builder.attribute('rgb', backColor); - }); - }); - }); + builder.element( + 'fill', + nest: () async { + builder.element( + 'patternFill', + nest: () async { + builder.element( + 'bgColor', + nest: () async { + builder.attribute('rgb', backColor); + }, + ); + }, + ); + }, + ); } } /// Serializes Dxf borders. void _serializeDxfBorders( - XmlBuilder builder, ConditionalFormatImpl condition) { + XmlBuilder builder, + ConditionalFormatImpl condition, + ) { if (condition.leftBorderStyle != LineStyle.none || condition.rightBorderStyle != LineStyle.none || condition.topBorderStyle != LineStyle.none || condition.bottomBorderStyle != LineStyle.none) { - builder.element('border', nest: () { - if (condition.leftBorderStyle != LineStyle.none) { - _serializeDxfBorder(builder, 'left', condition.leftBorderStyle, - condition.leftBorderColor); - } - if (condition.rightBorderStyle != LineStyle.none) { - _serializeDxfBorder(builder, 'right', condition.rightBorderStyle, - condition.rightBorderColor); - } - if (condition.topBorderStyle != LineStyle.none) { - _serializeDxfBorder(builder, 'top', condition.topBorderStyle, - condition.topBorderColor); - } - if (condition.bottomBorderStyle != LineStyle.none) { - _serializeDxfBorder(builder, 'bottom', condition.bottomBorderStyle, - condition.bottomBorderColor); - } - }); + builder.element( + 'border', + nest: () { + if (condition.leftBorderStyle != LineStyle.none) { + _serializeDxfBorder( + builder, + 'left', + condition.leftBorderStyle, + condition.leftBorderColor, + ); + } + if (condition.rightBorderStyle != LineStyle.none) { + _serializeDxfBorder( + builder, + 'right', + condition.rightBorderStyle, + condition.rightBorderColor, + ); + } + if (condition.topBorderStyle != LineStyle.none) { + _serializeDxfBorder( + builder, + 'top', + condition.topBorderStyle, + condition.topBorderColor, + ); + } + if (condition.bottomBorderStyle != LineStyle.none) { + _serializeDxfBorder( + builder, + 'bottom', + condition.bottomBorderStyle, + condition.bottomBorderColor, + ); + } + }, + ); } } Future _serializeDxfBordersAsync( - XmlBuilder builder, ConditionalFormatImpl condition) async { + XmlBuilder builder, + ConditionalFormatImpl condition, + ) async { if (condition.leftBorderStyle != LineStyle.none || condition.rightBorderStyle != LineStyle.none || condition.topBorderStyle != LineStyle.none || condition.bottomBorderStyle != LineStyle.none) { - builder.element('border', nest: () async { - if (condition.leftBorderStyle != LineStyle.none) { - _serializeDxfBorderAsync(builder, 'left', condition.leftBorderStyle, - condition.leftBorderColor); - } - if (condition.rightBorderStyle != LineStyle.none) { - _serializeDxfBorderAsync(builder, 'right', condition.rightBorderStyle, - condition.rightBorderColor); - } - if (condition.topBorderStyle != LineStyle.none) { - _serializeDxfBorderAsync(builder, 'top', condition.topBorderStyle, - condition.topBorderColor); - } - if (condition.bottomBorderStyle != LineStyle.none) { - _serializeDxfBorderAsync(builder, 'bottom', - condition.bottomBorderStyle, condition.bottomBorderColor); - } - }); + builder.element( + 'border', + nest: () async { + if (condition.leftBorderStyle != LineStyle.none) { + _serializeDxfBorderAsync( + builder, + 'left', + condition.leftBorderStyle, + condition.leftBorderColor, + ); + } + if (condition.rightBorderStyle != LineStyle.none) { + _serializeDxfBorderAsync( + builder, + 'right', + condition.rightBorderStyle, + condition.rightBorderColor, + ); + } + if (condition.topBorderStyle != LineStyle.none) { + _serializeDxfBorderAsync( + builder, + 'top', + condition.topBorderStyle, + condition.topBorderColor, + ); + } + if (condition.bottomBorderStyle != LineStyle.none) { + _serializeDxfBorderAsync( + builder, + 'bottom', + condition.bottomBorderStyle, + condition.bottomBorderColor, + ); + } + }, + ); } } /// Serializes Dxf border. - void _serializeDxfBorder(XmlBuilder builder, String value, - LineStyle borderStyle, String borderColor) { - builder.element(value, nest: () { - final String strStyle = - borderStyle.toString().split('.').toList().removeAt(1).toLowerCase(); - builder.attribute('style', strStyle); - builder.element('color', nest: () { - if (borderColor.length <= 7) { - builder.attribute('rgb', 'FF${borderColor.replaceAll('#', '')}'); - } else { - builder.attribute('rgb', borderColor); - } - }); - }); + void _serializeDxfBorder( + XmlBuilder builder, + String value, + LineStyle borderStyle, + String borderColor, + ) { + builder.element( + value, + nest: () { + final String strStyle = + borderStyle + .toString() + .split('.') + .toList() + .removeAt(1) + .toLowerCase(); + builder.attribute('style', strStyle); + builder.element( + 'color', + nest: () { + if (borderColor.length <= 7) { + builder.attribute('rgb', 'FF${borderColor.replaceAll('#', '')}'); + } else { + builder.attribute('rgb', borderColor); + } + }, + ); + }, + ); } - Future _serializeDxfBorderAsync(XmlBuilder builder, String value, - LineStyle borderStyle, String borderColor) async { - builder.element(value, nest: () async { - final String strStyle = - borderStyle.toString().split('.').toList().removeAt(1).toLowerCase(); - builder.attribute('style', strStyle); - builder.element('color', nest: () async { - if (borderColor.length <= 7) { - builder.attribute('rgb', 'FF${borderColor.replaceAll('#', '')}'); - } else { - builder.attribute('rgb', borderColor); - } - }); - }); + Future _serializeDxfBorderAsync( + XmlBuilder builder, + String value, + LineStyle borderStyle, + String borderColor, + ) async { + builder.element( + value, + nest: () async { + final String strStyle = + borderStyle + .toString() + .split('.') + .toList() + .removeAt(1) + .toLowerCase(); + builder.attribute('style', strStyle); + builder.element( + 'color', + nest: () async { + if (borderColor.length <= 7) { + builder.attribute('rgb', 'FF${borderColor.replaceAll('#', '')}'); + } else { + builder.attribute('rgb', borderColor); + } + }, + ); + }, + ); } /// Serializes conditional formattings. @@ -5640,193 +7297,307 @@ class SerializeWorkbook { int iPriorityCount = 0; if (hasExtensionList) { - builder.element('ext', nest: () { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - - builder.element('x14:conditionalFormattings', nest: () { - for (final ConditionalFormats conditions - in sheet.conditionalFormats) { - for (int i = 0; i < conditions.count; i++) { - final ConditionalFormat condition = - (conditions as ConditionalFormatsImpl).innerList[i]; - final ConditionalFormatImpl format = - condition as ConditionalFormatImpl; - IconSetImpl? iconSet; - if (format.iconSet != null) { - iconSet = format.iconSet! as IconSetImpl; - } - if (format.bCFHasExtensionList) { - final ConditionalFormatsImpl formats = conditions; - format.rangeRefernce = - (formats.cellList.isNotEmpty) ? ' ${formats.cellList}' : ''; - - if ((condition.formatType == ExcelCFType.formula && - condition.firstFormula != '') || - condition.formatType == ExcelCFType.specificText && - condition.firstFormula != '' && - (condition.operator == - ExcelComparisonOperator.beginsWith || - condition.operator == - ExcelComparisonOperator.endsWith || - condition.operator == - ExcelComparisonOperator.containsText || - condition.operator == - ExcelComparisonOperator.notContainsText) || - condition.formatType == ExcelCFType.cellValue && - condition.firstFormula != '' && - (condition.operator == ExcelComparisonOperator.equal || - condition.operator == - ExcelComparisonOperator.notEqual || - condition.operator == - ExcelComparisonOperator.greater || - condition.operator == - ExcelComparisonOperator.greaterOrEqual || - condition.operator == - ExcelComparisonOperator.less || - condition.operator == - ExcelComparisonOperator.lessOrEqual || - (condition.secondFormula != '' && - (condition.operator == - ExcelComparisonOperator.between || - condition.operator == - ExcelComparisonOperator.notBetween)))) { - builder.element('x14:conditionalFormatting', nest: () { - builder.attribute('xmlns:xm', - 'http://schemas.microsoft.com/office/excel/2006/main'); - builder.element('x14:cfRule', nest: () { - builder.attribute('type', - _getCFType(condition.formatType, condition.operator)); - if (format.priority > 1) { + builder.element( + 'ext', + nest: () { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + + builder.element( + 'x14:conditionalFormattings', + nest: () { + for (final ConditionalFormats conditions + in sheet.conditionalFormats) { + for (int i = 0; i < conditions.count; i++) { + final ConditionalFormat condition = + (conditions as ConditionalFormatsImpl).innerList[i]; + final ConditionalFormatImpl format = + condition as ConditionalFormatImpl; + IconSetImpl? iconSet; + if (format.iconSet != null) { + iconSet = format.iconSet! as IconSetImpl; + } + if (format.bCFHasExtensionList) { + final ConditionalFormatsImpl formats = conditions; + format.rangeRefernce = + (formats.cellList.isNotEmpty) + ? ' ${formats.cellList}' + : ''; + + if ((condition.formatType == ExcelCFType.formula && + condition.firstFormula != '') || + condition.formatType == ExcelCFType.specificText && + condition.firstFormula != '' && + (condition.operator == + ExcelComparisonOperator.beginsWith || + condition.operator == + ExcelComparisonOperator.endsWith || + condition.operator == + ExcelComparisonOperator.containsText || + condition.operator == + ExcelComparisonOperator.notContainsText) || + condition.formatType == ExcelCFType.cellValue && + condition.firstFormula != '' && + (condition.operator == + ExcelComparisonOperator.equal || + condition.operator == + ExcelComparisonOperator.notEqual || + condition.operator == + ExcelComparisonOperator.greater || + condition.operator == + ExcelComparisonOperator.greaterOrEqual || + condition.operator == + ExcelComparisonOperator.less || + condition.operator == + ExcelComparisonOperator.lessOrEqual || + (condition.secondFormula != '' && + (condition.operator == + ExcelComparisonOperator.between || + condition.operator == + ExcelComparisonOperator + .notBetween)))) { + builder.element( + 'x14:conditionalFormatting', + nest: () { + builder.attribute( + 'xmlns:xm', + 'http://schemas.microsoft.com/office/excel/2006/main', + ); + builder.element( + 'x14:cfRule', + nest: () { + builder.attribute( + 'type', + _getCFType( + condition.formatType, + condition.operator, + ), + ); + if (format.priority > 1) { + builder.attribute( + 'priority', + format.priority.toString(), + ); + } else { + builder.attribute( + 'priority', + iPriority.toString(), + ); + iPriority++; + } + if (condition.formatType == + ExcelCFType.cellValue || + condition.formatType == + ExcelCFType.specificText) { + builder.attribute( + 'operator', + _getCFComparisonOperatorName( + condition.operator, + ), + ); + } + // writer.WriteAttributeString(IdAttributeName, format.ST_GUID.ToString()); + final ConditionalFormatImpl conFormatImpl = + condition; + final String strFormula1 = + conFormatImpl.firstFormula; + final String strFormula2 = + conFormatImpl.secondFormula; + if (strFormula1 != '' && strFormula1 != '') { + builder.element('xm:f', nest: strFormula1); + } + if (strFormula2 != '' && strFormula2 != '') { + builder.element('xm:f', nest: strFormula2); + } else if (format.range != null) { + builder.element( + 'xm:f', + nest: format.range!.addressGlobal, + ); + } + + builder.element( + 'dxf', + nest: () { + _serializeDxfFont(builder, condition); + _serializeDxfFill(builder, condition); + _serializeDxfBorders(builder, condition); + }, + ); + }, + ); + builder.element( + 'xm:sqref', + nest: format.rangeRefernce, + ); + }, + ); + } + } + if (condition.iconSet != null && + (format.bCFHasExtensionList || + format.iconSet!.iconSet == + ExcelIconSetType.threeStars || + (iconSet != null && iconSet.isCustom) || + format.iconSet!.iconSet == + ExcelIconSetType.fiveBoxes || + format.iconSet!.iconSet == + ExcelIconSetType.threeTriangles)) { + final int iDxfIndex = _iDxfIndex; + + builder.element( + 'x14:conditionalFormatting', + nest: () { builder.attribute( - 'priority', format.priority.toString()); - } else { - builder.attribute('priority', iPriority.toString()); - iPriority++; - } - if (condition.formatType == ExcelCFType.cellValue || - condition.formatType == ExcelCFType.specificText) { - builder.attribute('operator', - _getCFComparisonOperatorName(condition.operator)); - } - // writer.WriteAttributeString(IdAttributeName, format.ST_GUID.ToString()); - final ConditionalFormatImpl conFormatImpl = condition; - final String strFormula1 = conFormatImpl.firstFormula; - final String strFormula2 = conFormatImpl.secondFormula; - if (strFormula1 != '' && strFormula1 != '') { - builder.element('xm:f', nest: strFormula1); - } - if (strFormula2 != '' && strFormula2 != '') { - builder.element('xm:f', nest: strFormula2); - } else if (format.range != null) { - builder.element('xm:f', - nest: format.range!.addressGlobal); - } - - builder.element('dxf', nest: () { - _serializeDxfFont(builder, condition); - _serializeDxfFill(builder, condition); - _serializeDxfBorders(builder, condition); - }); - }); - builder.element('xm:sqref', nest: format.rangeRefernce); - }); + 'xmlns:xm', + 'http://schemas.microsoft.com/office/excel/2006/main', + ); + final List result = _serializeCondition( + builder, + condition, + 'x14:', + iDxfIndex, + iPriority, + iPriorityCount, + ); + _iDxfIndex = result[0] as int; + iPriority = result[1] as int; + iPriorityCount = result[2] as int; + + final ConditionalFormatsImpl formats = conditions; + final String strAddress = + (formats.cellList.isNotEmpty) + ? ' ${formats.cellList}' + : ''; + builder.element('xm:sqref', nest: strAddress); + }, + ); + } + if (condition.dataBar != null && + (condition.dataBar! as DataBarImpl).hasExtensionList) { + final DataBar dataBar = condition.dataBar!; + final DataBarImpl dataBarImpl = dataBar as DataBarImpl; + + builder.element( + 'x14:conditionalFormatting', + nest: () { + builder.element( + 'x14:cfRule', + nest: () { + builder.attribute('type', 'dataBar'); + // ignore: unnecessary_null_checks + builder.attribute('id', dataBarImpl.stGUID!); + + builder.element( + 'x14:dataBar', + nest: () { + builder.attribute( + 'border', + (dataBar.hasBorder) ? '1' : '0', + ); + builder.attribute( + 'gradient', + (dataBar.hasGradientFill) ? '1' : '0', + ); + builder.attribute( + 'minLength', + dataBar.percentMin.toString(), + ); + builder.attribute( + 'maxLength', + dataBar.percentMax.toString(), + ); + builder.attribute( + 'direction', + dataBar.dataBarDirection.toString().substring( + 17, + ), + ); + builder.attribute( + 'negativeBarColorSameAsPositive', + (dataBarImpl.hasDiffNegativeBarColor) + ? '0' + : '1', + ); + builder.attribute( + 'negativeBarBorderColorSameAsPositive', + (dataBarImpl.hasDiffNegativeBarBorderColor) + ? '0' + : '1', + ); + builder.attribute( + 'axisPosition', + dataBar.dataBarAxisPosition + .toString() + .substring(20), + ); + + _serializeConditionValueObjectExt( + builder, + dataBar.minPoint, + false, + true, + ); + _serializeConditionValueObjectExt( + builder, + dataBar.maxPoint, + false, + false, + ); + + if (dataBar.borderColor != '') { + _serializeRgbColor( + builder, + 'x14:borderColor', + dataBar.borderColor, + ); + } + if (dataBar.negativeFillColor != '') { + _serializeRgbColor( + builder, + 'x14:negativeFillColor', + dataBar.negativeFillColor, + ); + } + if (dataBar.negativeBorderColor != '') { + _serializeRgbColor( + builder, + 'x14:negativeBorderColor', + dataBar.negativeBorderColor, + ); + } + if (dataBar.barAxisColor != '') { + _serializeRgbColor( + builder, + 'x14:axisColor', + dataBar.barAxisColor, + ); + } + }, + ); + }, + ); + }, + ); + } } } - if (condition.iconSet != null && - (format.bCFHasExtensionList || - format.iconSet!.iconSet == ExcelIconSetType.threeStars || - (iconSet != null && iconSet.isCustom) || - format.iconSet!.iconSet == ExcelIconSetType.fiveBoxes || - format.iconSet!.iconSet == - ExcelIconSetType.threeTriangles)) { - final int iDxfIndex = _iDxfIndex; - - builder.element('x14:conditionalFormatting', nest: () { - builder.attribute('xmlns:xm', - 'http://schemas.microsoft.com/office/excel/2006/main'); - final List result = _serializeCondition(builder, - condition, 'x14:', iDxfIndex, iPriority, iPriorityCount); - _iDxfIndex = result[0] as int; - iPriority = result[1] as int; - iPriorityCount = result[2] as int; - - final ConditionalFormatsImpl formats = conditions; - final String strAddress = (formats.cellList.isNotEmpty) - ? ' ${formats.cellList}' - : ''; - builder.element('xm:sqref', nest: strAddress); - }); - } - if (condition.dataBar != null && - (condition.dataBar! as DataBarImpl).hasExtensionList) { - final DataBar dataBar = condition.dataBar!; - final DataBarImpl dataBarImpl = dataBar as DataBarImpl; - - builder.element('x14:conditionalFormatting', nest: () { - builder.element('x14:cfRule', nest: () { - builder.attribute('type', 'dataBar'); - // ignore: unnecessary_null_checks - builder.attribute('id', dataBarImpl.stGUID!); - - builder.element('x14:dataBar', nest: () { - builder.attribute( - 'border', (dataBar.hasBorder) ? '1' : '0'); - builder.attribute( - 'gradient', (dataBar.hasGradientFill) ? '1' : '0'); - builder.attribute( - 'minLength', dataBar.percentMin.toString()); - builder.attribute( - 'maxLength', dataBar.percentMax.toString()); - builder.attribute('direction', - dataBar.dataBarDirection.toString().substring(17)); - builder.attribute('negativeBarColorSameAsPositive', - (dataBarImpl.hasDiffNegativeBarColor) ? '0' : '1'); - builder.attribute( - 'negativeBarBorderColorSameAsPositive', - (dataBarImpl.hasDiffNegativeBarBorderColor) - ? '0' - : '1'); - builder.attribute('axisPosition', - dataBar.dataBarAxisPosition.toString().substring(20)); - - _serializeConditionValueObjectExt( - builder, dataBar.minPoint, false, true); - _serializeConditionValueObjectExt( - builder, dataBar.maxPoint, false, false); - - if (dataBar.borderColor != '') { - _serializeRgbColor( - builder, 'x14:borderColor', dataBar.borderColor); - } - if (dataBar.negativeFillColor != '') { - _serializeRgbColor(builder, 'x14:negativeFillColor', - dataBar.negativeFillColor); - } - if (dataBar.negativeBorderColor != '') { - _serializeRgbColor(builder, 'x14:negativeBorderColor', - dataBar.negativeBorderColor); - } - if (dataBar.barAxisColor != '') { - _serializeRgbColor( - builder, 'x14:axisColor', dataBar.barAxisColor); - } - }); - }); - }); - } - } - } - }); - }); + }, + ); + }, + ); } } Future _serializeConditionalFormattingExtAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { final bool hasExtensionList = _hasExtensionListOnCF(sheet); if (!hasExtensionList) { return; @@ -5835,190 +7606,300 @@ class SerializeWorkbook { int iPriorityCount = 0; if (hasExtensionList) { - builder.element('ext', nest: () async { - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); - builder.attribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - - builder.element('x14:conditionalFormattings', nest: () async { - for (final ConditionalFormats conditions - in sheet.conditionalFormats) { - for (int i = 0; i < conditions.count; i++) { - final ConditionalFormat condition = - (conditions as ConditionalFormatsImpl).innerList[i]; - final ConditionalFormatImpl format = - condition as ConditionalFormatImpl; - IconSetImpl? iconSet; - if (format.iconSet != null) { - iconSet = format.iconSet! as IconSetImpl; - } - if (format.bCFHasExtensionList) { - final ConditionalFormatsImpl formats = conditions; - format.rangeRefernce = - (formats.cellList.isNotEmpty) ? ' ${formats.cellList}' : ''; - - if ((condition.formatType == ExcelCFType.formula && - condition.firstFormula != '') || - condition.formatType == ExcelCFType.specificText && - condition.firstFormula != '' && - (condition.operator == - ExcelComparisonOperator.beginsWith || - condition.operator == - ExcelComparisonOperator.endsWith || - condition.operator == - ExcelComparisonOperator.containsText || - condition.operator == - ExcelComparisonOperator.notContainsText) || - condition.formatType == ExcelCFType.cellValue && - condition.firstFormula != '' && - (condition.operator == ExcelComparisonOperator.equal || - condition.operator == - ExcelComparisonOperator.notEqual || - condition.operator == - ExcelComparisonOperator.greater || - condition.operator == - ExcelComparisonOperator.greaterOrEqual || - condition.operator == - ExcelComparisonOperator.less || - condition.operator == - ExcelComparisonOperator.lessOrEqual || - (condition.secondFormula != '' && - (condition.operator == - ExcelComparisonOperator.between || - condition.operator == - ExcelComparisonOperator.notBetween)))) { - builder.element('x14:conditionalFormatting', nest: () async { - builder.attribute('xmlns:xm', - 'http://schemas.microsoft.com/office/excel/2006/main'); - builder.element('x14:cfRule', nest: () async { - builder.attribute('type', - _getCFType(condition.formatType, condition.operator)); - - if (format.priority > 1) { + builder.element( + 'ext', + nest: () async { + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); + builder.attribute('uri', '{78C0D931-6437-407d-A8EE-F0AAD7539E65}'); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + + builder.element( + 'x14:conditionalFormattings', + nest: () async { + for (final ConditionalFormats conditions + in sheet.conditionalFormats) { + for (int i = 0; i < conditions.count; i++) { + final ConditionalFormat condition = + (conditions as ConditionalFormatsImpl).innerList[i]; + final ConditionalFormatImpl format = + condition as ConditionalFormatImpl; + IconSetImpl? iconSet; + if (format.iconSet != null) { + iconSet = format.iconSet! as IconSetImpl; + } + if (format.bCFHasExtensionList) { + final ConditionalFormatsImpl formats = conditions; + format.rangeRefernce = + (formats.cellList.isNotEmpty) + ? ' ${formats.cellList}' + : ''; + + if ((condition.formatType == ExcelCFType.formula && + condition.firstFormula != '') || + condition.formatType == ExcelCFType.specificText && + condition.firstFormula != '' && + (condition.operator == + ExcelComparisonOperator.beginsWith || + condition.operator == + ExcelComparisonOperator.endsWith || + condition.operator == + ExcelComparisonOperator.containsText || + condition.operator == + ExcelComparisonOperator.notContainsText) || + condition.formatType == ExcelCFType.cellValue && + condition.firstFormula != '' && + (condition.operator == + ExcelComparisonOperator.equal || + condition.operator == + ExcelComparisonOperator.notEqual || + condition.operator == + ExcelComparisonOperator.greater || + condition.operator == + ExcelComparisonOperator.greaterOrEqual || + condition.operator == + ExcelComparisonOperator.less || + condition.operator == + ExcelComparisonOperator.lessOrEqual || + (condition.secondFormula != '' && + (condition.operator == + ExcelComparisonOperator.between || + condition.operator == + ExcelComparisonOperator + .notBetween)))) { + builder.element( + 'x14:conditionalFormatting', + nest: () async { + builder.attribute( + 'xmlns:xm', + 'http://schemas.microsoft.com/office/excel/2006/main', + ); + builder.element( + 'x14:cfRule', + nest: () async { + builder.attribute( + 'type', + _getCFType( + condition.formatType, + condition.operator, + ), + ); + + if (format.priority > 1) { + builder.attribute( + 'priority', + format.priority.toString(), + ); + } else { + builder.attribute( + 'priority', + iPriority.toString(), + ); + iPriority++; + } + if (condition.formatType == + ExcelCFType.cellValue || + condition.formatType == + ExcelCFType.specificText) { + builder.attribute( + 'operator', + _getCFComparisonOperatorName( + condition.operator, + ), + ); + } + // writer.WriteAttributeString(IdAttributeName, format.ST_GUID.ToString()); + final ConditionalFormatImpl conFormatImpl = + condition; + final String strFormula1 = + conFormatImpl.firstFormula; + final String strFormula2 = + conFormatImpl.secondFormula; + if (strFormula1 != '' && strFormula1 != '') { + builder.element('xm:f', nest: strFormula1); + } + if (strFormula2 != '' && strFormula2 != '') { + builder.element('xm:f', nest: strFormula2); + } else if (format.range != null) { + builder.element( + 'xm:f', + nest: format.range!.addressGlobal, + ); + } + + builder.element( + 'dxf', + nest: () async { + _serializeDxfFontAsync(builder, condition); + _serializeDxfFillAsync(builder, condition); + _serializeDxfBordersAsync(builder, condition); + }, + ); + }, + ); + builder.element( + 'xm:sqref', + nest: format.rangeRefernce, + ); + }, + ); + } + } + if (condition.iconSet != null && + (format.bCFHasExtensionList || + format.iconSet!.iconSet == + ExcelIconSetType.threeStars || + (iconSet != null && iconSet.isCustom) || + format.iconSet!.iconSet == + ExcelIconSetType.fiveBoxes || + format.iconSet!.iconSet == + ExcelIconSetType.threeTriangles)) { + final int iDxfIndex = _iDxfIndex; + + builder.element( + 'x14:conditionalFormatting', + nest: () { builder.attribute( - 'priority', format.priority.toString()); - } else { - builder.attribute('priority', iPriority.toString()); - iPriority++; - } - if (condition.formatType == ExcelCFType.cellValue || - condition.formatType == ExcelCFType.specificText) { - builder.attribute('operator', - _getCFComparisonOperatorName(condition.operator)); - } - // writer.WriteAttributeString(IdAttributeName, format.ST_GUID.ToString()); - final ConditionalFormatImpl conFormatImpl = condition; - final String strFormula1 = conFormatImpl.firstFormula; - final String strFormula2 = conFormatImpl.secondFormula; - if (strFormula1 != '' && strFormula1 != '') { - builder.element('xm:f', nest: strFormula1); - } - if (strFormula2 != '' && strFormula2 != '') { - builder.element('xm:f', nest: strFormula2); - } else if (format.range != null) { - builder.element('xm:f', - nest: format.range!.addressGlobal); - } - - builder.element('dxf', nest: () async { - _serializeDxfFontAsync(builder, condition); - _serializeDxfFillAsync(builder, condition); - _serializeDxfBordersAsync(builder, condition); - }); - }); - builder.element('xm:sqref', nest: format.rangeRefernce); - }); + 'xmlns:xm', + 'http://schemas.microsoft.com/office/excel/2006/main', + ); + final List result = _serializeCondition( + builder, + condition, + 'x14:', + iDxfIndex, + iPriority, + iPriorityCount, + ); + _iDxfIndex = result[0] as int; + iPriority = result[1] as int; + iPriorityCount = result[2] as int; + + final ConditionalFormatsImpl formats = conditions; + final String strAddress = + (formats.cellList.isNotEmpty) + ? ' ${formats.cellList}' + : ''; + builder.element('xm:sqref', nest: strAddress); + }, + ); + } + if (condition.dataBar != null && + (condition.dataBar! as DataBarImpl).hasExtensionList) { + final DataBar dataBar = condition.dataBar!; + final DataBarImpl dataBarImpl = dataBar as DataBarImpl; + + builder.element( + 'x14:conditionalFormatting', + nest: () async { + builder.element( + 'x14:cfRule', + nest: () async { + builder.attribute('type', 'dataBar'); + // ignore: unnecessary_null_checks + builder.attribute('id', dataBarImpl.stGUID!); + + builder.element( + 'x14:dataBar', + nest: () async { + builder.attribute( + 'border', + (dataBar.hasBorder) ? '1' : '0', + ); + builder.attribute( + 'gradient', + (dataBar.hasGradientFill) ? '1' : '0', + ); + builder.attribute( + 'minLength', + dataBar.percentMin.toString(), + ); + builder.attribute( + 'maxLength', + dataBar.percentMax.toString(), + ); + builder.attribute( + 'direction', + dataBar.dataBarDirection.toString().substring( + 17, + ), + ); + builder.attribute( + 'negativeBarColorSameAsPositive', + (dataBarImpl.hasDiffNegativeBarColor) + ? '0' + : '1', + ); + builder.attribute( + 'negativeBarBorderColorSameAsPositive', + (dataBarImpl.hasDiffNegativeBarBorderColor) + ? '0' + : '1', + ); + builder.attribute( + 'axisPosition', + dataBar.dataBarAxisPosition + .toString() + .substring(20), + ); + + _serializeConditionValueObjectExtAsync( + builder, + dataBar.minPoint, + false, + true, + ); + _serializeConditionValueObjectExtAsync( + builder, + dataBar.maxPoint, + false, + false, + ); + if (dataBar.borderColor != '') { + _serializeRgbColorAsync( + builder, + 'x14:borderColor', + dataBar.borderColor, + ); + } + if (dataBar.negativeFillColor != '') { + _serializeRgbColorAsync( + builder, + 'x14:negativeFillColor', + dataBar.negativeFillColor, + ); + } + if (dataBar.negativeBorderColor != '') { + _serializeRgbColorAsync( + builder, + 'x14:negativeBorderColor', + dataBar.negativeBorderColor, + ); + } + if (dataBar.barAxisColor != '') { + _serializeRgbColorAsync( + builder, + 'x14:axisColor', + dataBar.barAxisColor, + ); + } + }, + ); + }, + ); + }, + ); + } } } - if (condition.iconSet != null && - (format.bCFHasExtensionList || - format.iconSet!.iconSet == ExcelIconSetType.threeStars || - (iconSet != null && iconSet.isCustom) || - format.iconSet!.iconSet == ExcelIconSetType.fiveBoxes || - format.iconSet!.iconSet == - ExcelIconSetType.threeTriangles)) { - final int iDxfIndex = _iDxfIndex; - - builder.element('x14:conditionalFormatting', nest: () { - builder.attribute('xmlns:xm', - 'http://schemas.microsoft.com/office/excel/2006/main'); - final List result = _serializeCondition(builder, - condition, 'x14:', iDxfIndex, iPriority, iPriorityCount); - _iDxfIndex = result[0] as int; - iPriority = result[1] as int; - iPriorityCount = result[2] as int; - - final ConditionalFormatsImpl formats = conditions; - final String strAddress = (formats.cellList.isNotEmpty) - ? ' ${formats.cellList}' - : ''; - builder.element('xm:sqref', nest: strAddress); - }); - } - if (condition.dataBar != null && - (condition.dataBar! as DataBarImpl).hasExtensionList) { - final DataBar dataBar = condition.dataBar!; - final DataBarImpl dataBarImpl = dataBar as DataBarImpl; - - builder.element('x14:conditionalFormatting', nest: () async { - builder.element('x14:cfRule', nest: () async { - builder.attribute('type', 'dataBar'); - // ignore: unnecessary_null_checks - builder.attribute('id', dataBarImpl.stGUID!); - - builder.element('x14:dataBar', nest: () async { - builder.attribute( - 'border', (dataBar.hasBorder) ? '1' : '0'); - builder.attribute( - 'gradient', (dataBar.hasGradientFill) ? '1' : '0'); - builder.attribute( - 'minLength', dataBar.percentMin.toString()); - builder.attribute( - 'maxLength', dataBar.percentMax.toString()); - builder.attribute('direction', - dataBar.dataBarDirection.toString().substring(17)); - builder.attribute('negativeBarColorSameAsPositive', - (dataBarImpl.hasDiffNegativeBarColor) ? '0' : '1'); - builder.attribute( - 'negativeBarBorderColorSameAsPositive', - (dataBarImpl.hasDiffNegativeBarBorderColor) - ? '0' - : '1'); - builder.attribute('axisPosition', - dataBar.dataBarAxisPosition.toString().substring(20)); - - _serializeConditionValueObjectExtAsync( - builder, dataBar.minPoint, false, true); - _serializeConditionValueObjectExtAsync( - builder, dataBar.maxPoint, false, false); - if (dataBar.borderColor != '') { - _serializeRgbColorAsync( - builder, 'x14:borderColor', dataBar.borderColor); - } - if (dataBar.negativeFillColor != '') { - _serializeRgbColorAsync(builder, - 'x14:negativeFillColor', dataBar.negativeFillColor); - } - if (dataBar.negativeBorderColor != '') { - _serializeRgbColorAsync( - builder, - 'x14:negativeBorderColor', - dataBar.negativeBorderColor); - } - if (dataBar.barAxisColor != '') { - _serializeRgbColorAsync( - builder, 'x14:axisColor', dataBar.barAxisColor); - } - }); - }); - }); - } - } - } - }); - }); + }, + ); + }, + ); } } @@ -6064,44 +7945,60 @@ class SerializeWorkbook { } /// Serializes conditional value object. - void _serializeConditionValueObjectExt(XmlBuilder builder, - ConditionValue conditionValue, bool isIconSet, bool isMinPoint) { - builder.element('x14:cfvo', nest: () { - int index = conditionValue.type.index; - if (!isIconSet) { - index = index == 7 - ? isMinPoint - ? 7 - : 8 - : index; - } - final String strType = _valueTypes[index]; - builder.attribute('type', strType); - builder.attribute('val', conditionValue.value); - if (isIconSet) { - builder.attribute('gte', conditionValue.operator.index.toString()); - } - }); - } - - Future _serializeConditionValueObjectExtAsync(XmlBuilder builder, - ConditionValue conditionValue, bool isIconSet, bool isMinPoint) async { - builder.element('x14:cfvo', nest: () async { - int index = conditionValue.type.index; - if (!isIconSet) { - index = index == 7 - ? isMinPoint - ? 7 - : 8 - : index; - } - final String strType = _valueTypes[index]; - builder.attribute('type', strType); - builder.attribute('val', conditionValue.value); - if (isIconSet) { - builder.attribute('gte', conditionValue.operator.index.toString()); - } - }); + void _serializeConditionValueObjectExt( + XmlBuilder builder, + ConditionValue conditionValue, + bool isIconSet, + bool isMinPoint, + ) { + builder.element( + 'x14:cfvo', + nest: () { + int index = conditionValue.type.index; + if (!isIconSet) { + index = + index == 7 + ? isMinPoint + ? 7 + : 8 + : index; + } + final String strType = _valueTypes[index]; + builder.attribute('type', strType); + builder.attribute('val', conditionValue.value); + if (isIconSet) { + builder.attribute('gte', conditionValue.operator.index.toString()); + } + }, + ); + } + + Future _serializeConditionValueObjectExtAsync( + XmlBuilder builder, + ConditionValue conditionValue, + bool isIconSet, + bool isMinPoint, + ) async { + builder.element( + 'x14:cfvo', + nest: () async { + int index = conditionValue.type.index; + if (!isIconSet) { + index = + index == 7 + ? isMinPoint + ? 7 + : 8 + : index; + } + final String strType = _valueTypes[index]; + builder.attribute('type', strType); + builder.attribute('val', conditionValue.value); + if (isIconSet) { + builder.attribute('gte', conditionValue.operator.index.toString()); + } + }, + ); } // Check whether to apply format or not. @@ -6132,7 +8029,10 @@ class SerializeWorkbook { /// Checks whether columns after iColumnIndex have the same settings and /// returns the last number in the sequence. static int _findSameColumns( - Worksheet sheet, int iColumnIndex, Workbook workbook) { + Worksheet sheet, + int iColumnIndex, + Workbook workbook, + ) { final Column? currentColumn = sheet.columns[iColumnIndex]; while (iColumnIndex <= sheet.columns.count) { @@ -6153,23 +8053,28 @@ class SerializeWorkbook { ///Serializes auto filters. void _serializeAutoFilters( - XmlBuilder builder, AutoFilterCollection? autoFilters) { + XmlBuilder builder, + AutoFilterCollection? autoFilters, + ) { if (autoFilters == null || autoFilters.innerList.isEmpty) { return; } if (!_isTableAutoFlter(autoFilters.worksheet)) { - builder.element('autoFilter', nest: () { - builder.attribute('ref', autoFilters.filterRange.addressLocal); + builder.element( + 'autoFilter', + nest: () { + builder.attribute('ref', autoFilters.filterRange.addressLocal); - // ignore: always_specify_types - for (int i = 0; i < autoFilters.count; i++) { - final AutoFilterImpl autoFilter = autoFilters[i] as AutoFilterImpl; + // ignore: always_specify_types + for (int i = 0; i < autoFilters.count; i++) { + final AutoFilterImpl autoFilter = autoFilters[i] as AutoFilterImpl; - if (autoFilter.isFiltered) { - serializeFilterColumn(builder, autoFilter); + if (autoFilter.isFiltered) { + serializeFilterColumn(builder, autoFilter); + } } - } - }); + }, + ); } } @@ -6185,125 +8090,164 @@ class SerializeWorkbook { } Future _serializeAutoFiltersAsync( - XmlBuilder builder, AutoFilterCollection? autoFilters) async { + XmlBuilder builder, + AutoFilterCollection? autoFilters, + ) async { if (autoFilters == null || autoFilters.innerList.isEmpty) { return; } - builder.element('autoFilter', nest: () async { - builder.attribute('ref', autoFilters.filterRange.addressLocal); + builder.element( + 'autoFilter', + nest: () async { + builder.attribute('ref', autoFilters.filterRange.addressLocal); - // ignore: always_specify_types - for (int i = 0; i < autoFilters.count; i++) { - final AutoFilterImpl autoFilter = autoFilters[i] as AutoFilterImpl; + // ignore: always_specify_types + for (int i = 0; i < autoFilters.count; i++) { + final AutoFilterImpl autoFilter = autoFilters[i] as AutoFilterImpl; - if (autoFilter.isFiltered) { - _serializeFilterColumnAsync(builder, autoFilter); + if (autoFilter.isFiltered) { + _serializeFilterColumnAsync(builder, autoFilter); + } } - } - }); + }, + ); } /// Serializes filter column. - void serializeFilterColumn( - XmlBuilder builder, - AutoFilterImpl autoFilter, - ) { - builder.element('filterColumn', nest: () { - _serializeAttributeInt(builder, 'colId', autoFilter.colIndex - 1, -1); - - switch (autoFilter.filterType) { - case ExcelFilterType.combinationFilter: - _serializeFilters(builder, autoFilter); - break; - case ExcelFilterType.customFilter: - _serializeCustomFilter(builder, autoFilter); - break; - case ExcelFilterType.dynamicFilter: - _serializeDateFilter( - builder, autoFilter.filteredItems as DynamicFilter); - break; - case ExcelFilterType.colorFilter: - _serializeColorFilter( - builder, autoFilter.filteredItems as ColorFilter); - break; - case ExcelFilterType.iconFilter: - break; - case ExcelFilterType.notUsed: - break; - } - }); + void serializeFilterColumn(XmlBuilder builder, AutoFilterImpl autoFilter) { + builder.element( + 'filterColumn', + nest: () { + _serializeAttributeInt(builder, 'colId', autoFilter.colIndex - 1, -1); + + switch (autoFilter.filterType) { + case ExcelFilterType.combinationFilter: + _serializeFilters(builder, autoFilter); + break; + case ExcelFilterType.customFilter: + _serializeCustomFilter(builder, autoFilter); + break; + case ExcelFilterType.dynamicFilter: + _serializeDateFilter( + builder, + autoFilter.filteredItems as DynamicFilter, + ); + break; + case ExcelFilterType.colorFilter: + _serializeColorFilter( + builder, + autoFilter.filteredItems as ColorFilter, + ); + break; + case ExcelFilterType.iconFilter: + break; + case ExcelFilterType.notUsed: + break; + } + }, + ); } Future _serializeFilterColumnAsync( XmlBuilder builder, AutoFilterImpl autoFilter, ) async { - builder.element('filterColumn', nest: () async { - _serializeAttributeIntAsync( - builder, 'colId', autoFilter.colIndex - 1, -1); - switch (autoFilter.filterType) { - case ExcelFilterType.combinationFilter: - _serializeFiltersAsync(builder, autoFilter); - break; - case ExcelFilterType.customFilter: - _serializeCustomFilterAsync(builder, autoFilter); - break; - case ExcelFilterType.dynamicFilter: - _serializeDateFilterAsync( - builder, autoFilter.filteredItems as DynamicFilter); - break; - case ExcelFilterType.colorFilter: - _serializeColorFilterAsync( - builder, autoFilter.filteredItems as ColorFilter); - break; - case ExcelFilterType.iconFilter: - break; - case ExcelFilterType.notUsed: - break; - } - }); + builder.element( + 'filterColumn', + nest: () async { + _serializeAttributeIntAsync( + builder, + 'colId', + autoFilter.colIndex - 1, + -1, + ); + switch (autoFilter.filterType) { + case ExcelFilterType.combinationFilter: + _serializeFiltersAsync(builder, autoFilter); + break; + case ExcelFilterType.customFilter: + _serializeCustomFilterAsync(builder, autoFilter); + break; + case ExcelFilterType.dynamicFilter: + _serializeDateFilterAsync( + builder, + autoFilter.filteredItems as DynamicFilter, + ); + break; + case ExcelFilterType.colorFilter: + _serializeColorFilterAsync( + builder, + autoFilter.filteredItems as ColorFilter, + ); + break; + case ExcelFilterType.iconFilter: + break; + case ExcelFilterType.notUsed: + break; + } + }, + ); } /// Serialize color filter. void _serializeColorFilter(XmlBuilder builder, ColorFilter filter) { - builder.element('colorFilter', nest: () { - builder.attribute('dxfId', _iDxfIndex.toString()); - _iDxfIndex++; - if (filter.colorFilterType == ExcelColorFilterType.fontColor) { - builder.attribute('cellColor', '0'); - } - }); + builder.element( + 'colorFilter', + nest: () { + builder.attribute('dxfId', _iDxfIndex.toString()); + _iDxfIndex++; + if (filter.colorFilterType == ExcelColorFilterType.fontColor) { + builder.attribute('cellColor', '0'); + } + }, + ); } Future _serializeColorFilterAsync( - XmlBuilder builder, ColorFilter filter) async { - builder.element('colorFilter', nest: () async { - builder.attribute('dxfId', _iDxfIndex.toString()); - _iDxfIndex++; - if (filter.colorFilterType == ExcelColorFilterType.fontColor) { - builder.attribute('cellColor', '0'); - } - }); + XmlBuilder builder, + ColorFilter filter, + ) async { + builder.element( + 'colorFilter', + nest: () async { + builder.attribute('dxfId', _iDxfIndex.toString()); + _iDxfIndex++; + if (filter.colorFilterType == ExcelColorFilterType.fontColor) { + builder.attribute('cellColor', '0'); + } + }, + ); } /// Serialize the dynmaic filter. void _serializeDateFilter(XmlBuilder builder, DynamicFilter filter) { if (filter.dateFilterType != DynamicFilterType.none) { - builder.element('dynamicFilter', nest: () { - final String? dateTime = - _convertDateFilterTypeToString(filter.dateFilterType); - builder.attribute('type', dateTime.toString()); - }); + builder.element( + 'dynamicFilter', + nest: () { + final String? dateTime = _convertDateFilterTypeToString( + filter.dateFilterType, + ); + builder.attribute('type', dateTime.toString()); + }, + ); } } Future _serializeDateFilterAsync( - XmlBuilder builder, DynamicFilter filter) async { + XmlBuilder builder, + DynamicFilter filter, + ) async { if (filter.dateFilterType != DynamicFilterType.none) { - builder.element('dynamicFilter', nest: () async { - builder.attribute('type', - _convertDateFilterTypeToString(filter.dateFilterType).toString()); - }); + builder.element( + 'dynamicFilter', + nest: () async { + builder.attribute( + 'type', + _convertDateFilterTypeToString(filter.dateFilterType).toString(), + ); + }, + ); } } @@ -6413,29 +8357,43 @@ class SerializeWorkbook { ///SerializeCombination filter void _serializeFilters(XmlBuilder builder, AutoFilterImpl autoFilter) { - builder.element('filters', nest: () { - if (autoFilter.filteredItems.filterType == - ExcelFilterType.combinationFilter) { - _serializeCombinationFilters( - builder, autoFilter.filteredItems as CombinationFilter); - } - }); + builder.element( + 'filters', + nest: () { + if (autoFilter.filteredItems.filterType == + ExcelFilterType.combinationFilter) { + _serializeCombinationFilters( + builder, + autoFilter.filteredItems as CombinationFilter, + ); + } + }, + ); } Future _serializeFiltersAsync( - XmlBuilder builder, AutoFilterImpl autoFilter) async { - builder.element('filters', nest: () async { - if (autoFilter.filteredItems.filterType == - ExcelFilterType.combinationFilter) { - _serializeCombinationFiltersAsync( - builder, autoFilter.filteredItems as CombinationFilter); - } - }); + XmlBuilder builder, + AutoFilterImpl autoFilter, + ) async { + builder.element( + 'filters', + nest: () async { + if (autoFilter.filteredItems.filterType == + ExcelFilterType.combinationFilter) { + _serializeCombinationFiltersAsync( + builder, + autoFilter.filteredItems as CombinationFilter, + ); + } + }, + ); } ///SerializeCombination filter void _serializeCombinationFilters( - XmlBuilder builder, CombinationFilter combinationFilter) { + XmlBuilder builder, + CombinationFilter combinationFilter, + ) { if (combinationFilter.isBlank) { builder.attribute('blank', 1); } @@ -6453,7 +8411,9 @@ class SerializeWorkbook { } Future _serializeCombinationFiltersAsync( - XmlBuilder builder, CombinationFilter combinationFilter) async { + XmlBuilder builder, + CombinationFilter combinationFilter, + ) async { if (combinationFilter.isBlank) { builder.attribute('blank', 1); } @@ -6465,7 +8425,9 @@ class SerializeWorkbook { break; case ExcelCombinationFilterType.dateTimeFilter: _serializeDateTimeFilterAsync( - builder, multipleFilter as DateTimeFilter); + builder, + multipleFilter as DateTimeFilter, + ); break; } } @@ -6475,68 +8437,76 @@ class SerializeWorkbook { void _serializeDateTimeFilter(XmlBuilder builder, DateTimeFilter filter) { final DateTimeFilterType dateGroup = filter.groupingType; final DateTime date = filter.dateTimeValue; - builder.element('dateGroupItem', nest: () { - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.year)) { - builder.attribute('year', date.year.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.month)) { - builder.attribute('month', date.month.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.day)) { - builder.attribute('day', date.day.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.hour)) { - builder.attribute('hour', date.hour.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.minute)) { - builder.attribute('minute', date.minute.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.second)) { - builder.attribute('second', date.second.toString()); - } - final String dateTimeStr = _getDateTimeString(dateGroup); - builder.attribute('dateTimeGrouping', dateTimeStr); - }); + builder.element( + 'dateGroupItem', + nest: () { + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.year)) { + builder.attribute('year', date.year.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.month)) { + builder.attribute('month', date.month.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.day)) { + builder.attribute('day', date.day.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.hour)) { + builder.attribute('hour', date.hour.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.minute)) { + builder.attribute('minute', date.minute.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.second)) { + builder.attribute('second', date.second.toString()); + } + final String dateTimeStr = _getDateTimeString(dateGroup); + builder.attribute('dateTimeGrouping', dateTimeStr); + }, + ); } Future _serializeDateTimeFilterAsync( - XmlBuilder builder, DateTimeFilter filter) async { + XmlBuilder builder, + DateTimeFilter filter, + ) async { final DateTimeFilterType dateGroup = filter.groupingType; final DateTime date = filter.dateTimeValue; - builder.element('dateGroupItem', nest: () { - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.year)) { - builder.attribute('year', date.year.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.month)) { - builder.attribute('month', date.month.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.day)) { - builder.attribute('day', date.day.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.hour)) { - builder.attribute('hour', date.hour.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.minute)) { - builder.attribute('minute', date.minute.toString()); - } - if (_getDateTimevalue(dateGroup) >= - _getDateTimevalue(DateTimeFilterType.second)) { - builder.attribute('second', date.second.toString()); - } - final String dateTimeStr = _getDateTimeString(dateGroup); - builder.attribute('dateTimeGrouping', dateTimeStr); - }); + builder.element( + 'dateGroupItem', + nest: () { + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.year)) { + builder.attribute('year', date.year.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.month)) { + builder.attribute('month', date.month.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.day)) { + builder.attribute('day', date.day.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.hour)) { + builder.attribute('hour', date.hour.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.minute)) { + builder.attribute('minute', date.minute.toString()); + } + if (_getDateTimevalue(dateGroup) >= + _getDateTimevalue(DateTimeFilterType.second)) { + builder.attribute('second', date.second.toString()); + } + final String dateTimeStr = _getDateTimeString(dateGroup); + builder.attribute('dateTimeGrouping', dateTimeStr); + }, + ); } /// Get the int value based on date time grouping type. @@ -6577,64 +8547,104 @@ class SerializeWorkbook { ///Serialization of filter void _serializeFilter(XmlBuilder builder, String strFilterValue) { - builder.element('filter', nest: () { - builder.attribute('val', strFilterValue); - }); + builder.element( + 'filter', + nest: () { + builder.attribute('val', strFilterValue); + }, + ); } Future _serializeFilterAsync( - XmlBuilder builder, String strFilterValue) async { - builder.element('filter', nest: () async { - builder.attribute('val', strFilterValue); - }); + XmlBuilder builder, + String strFilterValue, + ) async { + builder.element( + 'filter', + nest: () async { + builder.attribute('val', strFilterValue); + }, + ); } /// Serializes custom filters. void _serializeCustomFilter(XmlBuilder builder, AutoFilterImpl autoFilter) { - builder.element('customFilters', nest: () { - final bool isAnd = autoFilter.logicalOperator == ExcelLogicalOperator.and; - _serializeAttributes(builder, 'and', isAnd, false); - if (autoFilter.isFirstCondition) { - __serializeCustomFilters( - builder, autoFilter.firstCondition, autoFilter); - } - if (autoFilter.isSecondCondition) { - __serializeCustomFilters( - builder, autoFilter.firstCondition, autoFilter); - __serializeCustomFilters( - builder, autoFilter.secondCondition, autoFilter); - } - }); + builder.element( + 'customFilters', + nest: () { + final bool isAnd = + autoFilter.logicalOperator == ExcelLogicalOperator.and; + _serializeAttributes(builder, 'and', isAnd, false); + if (autoFilter.isFirstCondition) { + __serializeCustomFilters( + builder, + autoFilter.firstCondition, + autoFilter, + ); + } + if (autoFilter.isSecondCondition) { + __serializeCustomFilters( + builder, + autoFilter.firstCondition, + autoFilter, + ); + __serializeCustomFilters( + builder, + autoFilter.secondCondition, + autoFilter, + ); + } + }, + ); } Future _serializeCustomFilterAsync( - XmlBuilder builder, AutoFilterImpl autoFilter) async { - builder.element('customFilters', nest: () async { - final bool isAnd = autoFilter.logicalOperator == ExcelLogicalOperator.and; - _serializeAttributesAsync(builder, 'and', isAnd, false); - if (autoFilter.isFirstCondition) { - __serializeCustomFiltersAsync( - builder, autoFilter.firstCondition, autoFilter); - } - if (autoFilter.isSecondCondition) { - __serializeCustomFiltersAsync( - builder, autoFilter.firstCondition, autoFilter); - __serializeCustomFiltersAsync( - builder, autoFilter.secondCondition, autoFilter); - } - }); + XmlBuilder builder, + AutoFilterImpl autoFilter, + ) async { + builder.element( + 'customFilters', + nest: () async { + final bool isAnd = + autoFilter.logicalOperator == ExcelLogicalOperator.and; + _serializeAttributesAsync(builder, 'and', isAnd, false); + if (autoFilter.isFirstCondition) { + __serializeCustomFiltersAsync( + builder, + autoFilter.firstCondition, + autoFilter, + ); + } + if (autoFilter.isSecondCondition) { + __serializeCustomFiltersAsync( + builder, + autoFilter.firstCondition, + autoFilter, + ); + __serializeCustomFiltersAsync( + builder, + autoFilter.secondCondition, + autoFilter, + ); + } + }, + ); } /// Serializes custom filters. - void __serializeCustomFilters(XmlBuilder builder, - AutoFilterCondition autoFilterCondition, AutoFilterImpl autoFilter) { + void __serializeCustomFilters( + XmlBuilder builder, + AutoFilterCondition autoFilterCondition, + AutoFilterImpl autoFilter, + ) { _customFilterCondition(builder, autoFilterCondition, autoFilter, 0); } Future __serializeCustomFiltersAsync( - XmlBuilder builder, - AutoFilterCondition autoFilterCondition, - AutoFilterImpl autoFilter) async { + XmlBuilder builder, + AutoFilterCondition autoFilterCondition, + AutoFilterImpl autoFilter, + ) async { _customFilterConditionAsync(builder, autoFilterCondition, autoFilter, 0); } @@ -6672,83 +8682,93 @@ class SerializeWorkbook { ///Serialize custom filter void _customFilterCondition( - XmlBuilder builder, - AutoFilterCondition autoFilterCondition, - AutoFilterImpl autoFilter, - int dataindex) { + XmlBuilder builder, + AutoFilterCondition autoFilterCondition, + AutoFilterImpl autoFilter, + int dataindex, + ) { ExcelFilterCondition conditionOperator = autoFilterCondition.conditionOperator; - builder.element('customFilter', nest: () { - if (autoFilterCondition.dataType == - ExcelFilterDataType.matchAllNonBlanks) { - builder.attribute('operator', 'notEqual'); - builder.attribute('val', 0); - } else { - conditionOperator = autoFilterCondition.conditionOperator; - final String operatorValue = - _getAFconditionalOperatorName(conditionOperator); + builder.element( + 'customFilter', + nest: () { + if (autoFilterCondition.dataType == + ExcelFilterDataType.matchAllNonBlanks) { + builder.attribute('operator', 'notEqual'); + builder.attribute('val', 0); + } else { + conditionOperator = autoFilterCondition.conditionOperator; + final String operatorValue = _getAFconditionalOperatorName( + conditionOperator, + ); - if (operatorValue != 'equal') { - builder.attribute('operator', operatorValue); - } - Object strval = _conditionValue(autoFilterCondition); - if (conditionOperator == ExcelFilterCondition.contains || - conditionOperator == ExcelFilterCondition.doesNotContain || - conditionOperator == ExcelFilterCondition.beginsWith || - conditionOperator == ExcelFilterCondition.doesNotBeginWith) { - strval = '$strval*'; - } + if (operatorValue != 'equal') { + builder.attribute('operator', operatorValue); + } + Object strval = _conditionValue(autoFilterCondition); + if (conditionOperator == ExcelFilterCondition.contains || + conditionOperator == ExcelFilterCondition.doesNotContain || + conditionOperator == ExcelFilterCondition.beginsWith || + conditionOperator == ExcelFilterCondition.doesNotBeginWith) { + strval = '$strval*'; + } - if (conditionOperator == ExcelFilterCondition.contains || - conditionOperator == ExcelFilterCondition.doesNotContain || - conditionOperator == ExcelFilterCondition.endsWith || - conditionOperator == ExcelFilterCondition.doesNotEndWith) { - strval = '*$strval'; - } + if (conditionOperator == ExcelFilterCondition.contains || + conditionOperator == ExcelFilterCondition.doesNotContain || + conditionOperator == ExcelFilterCondition.endsWith || + conditionOperator == ExcelFilterCondition.doesNotEndWith) { + strval = '*$strval'; + } - builder.attribute('val', strval); - } - }); + builder.attribute('val', strval); + } + }, + ); } Future _customFilterConditionAsync( - XmlBuilder builder, - AutoFilterCondition autoFilterCondition, - AutoFilterImpl autoFilter, - int dataindex) async { + XmlBuilder builder, + AutoFilterCondition autoFilterCondition, + AutoFilterImpl autoFilter, + int dataindex, + ) async { ExcelFilterCondition conditionOperator = autoFilterCondition.conditionOperator; - builder.element('customFilter', nest: () { - if (autoFilterCondition.dataType == - ExcelFilterDataType.matchAllNonBlanks) { - builder.attribute('operator', 'notEqual'); - builder.attribute('val', 0); - } else { - conditionOperator = autoFilterCondition.conditionOperator; - final String operatorValue = - _getAFconditionalOperatorName(conditionOperator); + builder.element( + 'customFilter', + nest: () { + if (autoFilterCondition.dataType == + ExcelFilterDataType.matchAllNonBlanks) { + builder.attribute('operator', 'notEqual'); + builder.attribute('val', 0); + } else { + conditionOperator = autoFilterCondition.conditionOperator; + final String operatorValue = _getAFconditionalOperatorName( + conditionOperator, + ); - if (operatorValue != 'equal') { - builder.attribute('operator', operatorValue); - } - Object strval = _conditionValue(autoFilterCondition); - if (conditionOperator == ExcelFilterCondition.contains || - conditionOperator == ExcelFilterCondition.doesNotContain || - conditionOperator == ExcelFilterCondition.beginsWith || - conditionOperator == ExcelFilterCondition.doesNotBeginWith) { - strval = '$strval*'; - } + if (operatorValue != 'equal') { + builder.attribute('operator', operatorValue); + } + Object strval = _conditionValue(autoFilterCondition); + if (conditionOperator == ExcelFilterCondition.contains || + conditionOperator == ExcelFilterCondition.doesNotContain || + conditionOperator == ExcelFilterCondition.beginsWith || + conditionOperator == ExcelFilterCondition.doesNotBeginWith) { + strval = '$strval*'; + } - if (conditionOperator == ExcelFilterCondition.contains || - conditionOperator == ExcelFilterCondition.doesNotContain || - conditionOperator == ExcelFilterCondition.endsWith || - conditionOperator == ExcelFilterCondition.doesNotEndWith) { - strval = '*$strval'; - } + if (conditionOperator == ExcelFilterCondition.contains || + conditionOperator == ExcelFilterCondition.doesNotContain || + conditionOperator == ExcelFilterCondition.endsWith || + conditionOperator == ExcelFilterCondition.doesNotEndWith) { + strval = '*$strval'; + } - builder.attribute('val', strval); - } - }); + builder.attribute('val', strval); + } + }, + ); } /// Returns auto filter condition value. @@ -6784,13 +8804,18 @@ class SerializeWorkbook { } else { worksheetTabColor = sheet.tabColor; } - builder.element('tabColor', nest: () { - builder.attribute('rgb', worksheetTabColor); - }); + builder.element( + 'tabColor', + nest: () { + builder.attribute('rgb', worksheetTabColor); + }, + ); } Future _serializeTabColorAsync( - Worksheet sheet, XmlBuilder builder) async { + Worksheet sheet, + XmlBuilder builder, + ) async { String worksheetTabColor = ''; if (sheet.tabColor.length == 7) { @@ -6798,8 +8823,11 @@ class SerializeWorkbook { } else { worksheetTabColor = sheet.tabColor; } - builder.element('tabColor', nest: () async { - builder.attribute('rgb', worksheetTabColor); - }); + builder.element( + 'tabColor', + nest: () async { + builder.attribute('rgb', worksheetTabColor); + }, + ); } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/workbook.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/workbook.dart index 8b4a16391..bc5a5e908 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/workbook.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/general/workbook.dart @@ -158,7 +158,7 @@ class Workbook { 96 / 2.54, // Centimeter 1, // Pixel 96 / 72.0, // Point - 96 / 72.0 / 12700 // EMU + 96 / 72.0 / 12700, // EMU ]; /// Collections store the font metrics details. @@ -1713,7 +1713,7 @@ class Workbook { 556, 500, 556, - 500 + 500, ]; /// Arial bold widths table. @@ -1941,7 +1941,7 @@ class Workbook { 611, 556, 611, - 556 + 556, ]; /// Fixed width of Courier New Font Family. @@ -2172,7 +2172,7 @@ class Workbook { 500, 500, 500, - 500 + 500, ]; /// Times New Roman bold widths table. @@ -2400,7 +2400,7 @@ class Workbook { 556, 500, 556, - 500 + 500, ]; /// Times New Roman italic widths table. @@ -2628,7 +2628,7 @@ class Workbook { 500, 444, 500, - 444 + 444, ]; /// Times New Roman bold italic widths table. @@ -2856,7 +2856,7 @@ class Workbook { 556, 444, 500, - 444 + 444, ]; /// Tahoma widths table. @@ -3178,7 +3178,7 @@ class Workbook { 559, 444, 559, - 444 + 444, ]; /// Tahoma Bold widths table. @@ -3500,7 +3500,7 @@ class Workbook { 622, 525, 622, - 525 + 525, ]; /// Calibri Width Table. @@ -3822,7 +3822,7 @@ class Workbook { 468, 395, 468, - 395 + 395, ]; /// Calibri Bold Width Table. @@ -4144,7 +4144,7 @@ class Workbook { 478, 397, 478, - 397 + 397, ]; /// Calibri Italic Width Table. @@ -4466,7 +4466,7 @@ class Workbook { 468, 395, 468, - 395 + 395, ]; /// Calibri Bold Italic Width Table. @@ -4788,7 +4788,7 @@ class Workbook { 478, 397, 478, - 397 + 397, ]; /// Verdana Widths Table. @@ -5110,7 +5110,7 @@ class Workbook { 685, 525, 685, - 525 + 525, ]; /// Verdana Italic widths table @@ -5432,7 +5432,7 @@ class Workbook { 685, 525, 685, - 525 + 525, ]; /// Verdana Bold Width Table. @@ -5754,7 +5754,7 @@ class Workbook { 691, 596, 691, - 596 + 596, ]; /// Verdana Bold Italics Widths table @@ -6076,7 +6076,7 @@ class Workbook { 691, 596, 691, - 596 + 596, ]; /// Gets or sets the standard font size. @@ -6165,7 +6165,10 @@ class Workbook { /// Initialize the workbook. void _initializeWorkbook( - String? givenCulture, String? givenCurrency, int? count) { + String? givenCulture, + String? givenCurrency, + int? count, + ) { if (givenCulture != null) { culture = givenCulture; } else { @@ -6219,9 +6222,9 @@ class Workbook { isSaving = true; final SerializeWorkbook serializer = SerializeWorkbook(this); serializer.saveInternal(); - final List? bytes = ZipEncoder().encode(archive); + final List bytes = ZipEncoder().encode(archive); isSaving = false; - return bytes!; + return bytes; } /// Saves workbook. @@ -6311,7 +6314,8 @@ class Workbook { } else { fontColor = toCompareStyle.fontColor; } - result = font.color == fontColor && + result = + font.color == fontColor && font.bold == toCompareStyle.bold && font.italic == toCompareStyle.italic && font.underline == toCompareStyle.underline && @@ -6384,7 +6388,8 @@ class Workbook { double fileWidthToPixels(double fileWidth) { final double dDigitWidth = maxDigitWidth; return _truncate( - ((256 * fileWidth + _truncate(128 / dDigitWidth)) / 256) * dDigitWidth); + ((256 * fileWidth + _truncate(128 / dDigitWidth)) / 256) * dDigitWidth, + ); } /// Converts column width in pixels into column width in characters. @@ -6416,55 +6421,145 @@ class Workbook { void _initFontMetricsCollection() { _fontMetricsCollection = {}; //Arial - _fontMetricsCollection!['arial_italic_bold'] = - FontMetrics(962, -228, 0, 962 + 228.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['arial_bold'] = - FontMetrics(962, -228, 0, 962 + 228.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['arial_italic'] = - FontMetrics(931, -225, 0, 931 + 225.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['arial'] = - FontMetrics(931, -225, 0, 931 + 225.toDouble(), 1.52, 1.52); + _fontMetricsCollection!['arial_italic_bold'] = FontMetrics( + 962, + -228, + 0, + 962 + 228.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['arial_bold'] = FontMetrics( + 962, + -228, + 0, + 962 + 228.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['arial_italic'] = FontMetrics( + 931, + -225, + 0, + 931 + 225.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['arial'] = FontMetrics( + 931, + -225, + 0, + 931 + 225.toDouble(), + 1.52, + 1.52, + ); //Times Roman - _fontMetricsCollection!['times_italic_bold'] = - FontMetrics(921, -218, 0, 921 + 218.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['times_bold'] = - FontMetrics(935, -218, 0, 935 + 218.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['times_italic'] = - FontMetrics(883, -217, 0, 883 + 217.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['times'] = - FontMetrics(898, -218, 0, 898 + 218.toDouble(), 1.52, 1.52); + _fontMetricsCollection!['times_italic_bold'] = FontMetrics( + 921, + -218, + 0, + 921 + 218.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['times_bold'] = FontMetrics( + 935, + -218, + 0, + 935 + 218.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['times_italic'] = FontMetrics( + 883, + -217, + 0, + 883 + 217.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['times'] = FontMetrics( + 898, + -218, + 0, + 898 + 218.toDouble(), + 1.52, + 1.52, + ); //Courier - _fontMetricsCollection!['courier_italic_bold'] = - FontMetrics(801, -250, 0, 801 + 250.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['courier_bold'] = - FontMetrics(801, -250, 0, 801 + 250.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['courier_italic'] = - FontMetrics(805, -250, 0, 805 + 250.toDouble(), 1.52, 1.52); - - _fontMetricsCollection!['courier'] = - FontMetrics(805, -250, 0, 805 + 250.toDouble(), 1.52, 1.52); + _fontMetricsCollection!['courier_italic_bold'] = FontMetrics( + 801, + -250, + 0, + 801 + 250.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['courier_bold'] = FontMetrics( + 801, + -250, + 0, + 801 + 250.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['courier_italic'] = FontMetrics( + 805, + -250, + 0, + 805 + 250.toDouble(), + 1.52, + 1.52, + ); + + _fontMetricsCollection!['courier'] = FontMetrics( + 805, + -250, + 0, + 805 + 250.toDouble(), + 1.52, + 1.52, + ); //Tahoma _fontMetricsCollection!['tahoma'] = FontMetrics( - 1000.48828, -206.542969, 0, 1207.03125, 1.53869271, 1.53869271); + 1000.48828, + -206.542969, + 0, + 1207.03125, + 1.53869271, + 1.53869271, + ); //Calibri - _fontMetricsCollection!['calibri'] = - FontMetrics(750.0, -250.0, 221, 1221.0, 1.53869271, 1.53869271); + _fontMetricsCollection!['calibri'] = FontMetrics( + 750.0, + -250.0, + 221, + 1221.0, + 1.53869271, + 1.53869271, + ); //Verdana _fontMetricsCollection!['verdana'] = FontMetrics( - 1005.37109, -209.960938, 0, 1215.332, 1.53869271, 1.53869271); + 1005.37109, + -209.960938, + 0, + 1215.332, + 1.53869271, + 1.53869271, + ); } /// returns the size of the text with font family 'Verdana'. @@ -6662,7 +6757,8 @@ class Workbook { double fontHeight; if (keyValuePairs != null && keyValuePairs[font.size] != null) { fontHeight = keyValuePairs[font.size]!; - originalHeight = convertUnits(fontHeight, 6, 5) * + originalHeight = + convertUnits(fontHeight, 6, 5) * ((strValue.length - strValue.replaceAll('\n', '').length) + 1); } return SizeF(result.fontWidth, originalHeight); @@ -6677,15 +6773,27 @@ class Workbook { /// Measure the Text with a given font. Rectangle getMeasuredRectangle( - String text, Font font, Rectangle bounds) { + String text, + Font font, + Rectangle bounds, + ) { final SizeF size = getTextSizeFromFont(text, font); final double height = (size.fontHeight * 1.03).ceilToDouble(); - final int length = bounds.width == 1800.0 - ? 1 - : _getLengthOfLines( - size.fontWidth, bounds.width.toDouble(), text, font); - final Rectangle result = - Rectangle(0, 0, size.fontWidth.ceil(), height * length); + final int length = + bounds.width == 1800.0 + ? 1 + : _getLengthOfLines( + size.fontWidth, + bounds.width.toDouble(), + text, + font, + ); + final Rectangle result = Rectangle( + 0, + 0, + size.fontWidth.ceil(), + height * length, + ); return result; } @@ -6718,7 +6826,11 @@ class Workbook { /// Calculate the number of lines for the text to fit in the width. int _getLengthOfLines( - double sizeOfText, double widthBound, String text, Font font) { + double sizeOfText, + double widthBound, + String text, + Font font, + ) { int length = 0; double width = 0; double currentWidth = 0; @@ -6790,14 +6902,18 @@ class Workbook { /// saveAsExcel(bytes, 'ExcelWorkbookProtection2.xlsx'); /// workbook.dispose(); /// ``` - void protect(bool isProtectWindow, bool isProtectContent, - [String? sPassword]) { + void protect( + bool isProtectWindow, + bool isProtectContent, [ + String? sPassword, + ]) { if (!isProtectWindow && !isProtectContent) { throw Exception('One of params must be TRUE.'); } if (isCellProtect || isWindowProtect) { throw Exception( - 'Workbook is already protected. Use Unprotect before calling method.'); + 'Workbook is already protected. Use Unprotect before calling method.', + ); } isCellProtect = isProtectContent; isWindowProtect = isProtectWindow; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink.dart index 697147d33..de7a5f215 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink.dart @@ -10,8 +10,12 @@ class Hyperlink { } /// Creates an instance of Hyperlink with parameters. - Hyperlink.add(this.address, - [this.screenTip, this.textToDisplay, HyperlinkType? type]) { + Hyperlink.add( + this.address, [ + this.screenTip, + this.textToDisplay, + HyperlinkType? type, + ]) { if (type != null) { this.type = type; } else { diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink_collection.dart index 4af95613a..aea8d7fbb 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/hyperlinks/hyperlink_collection.dart @@ -47,8 +47,13 @@ class HyperlinkCollection { /// File('Hyperlinks.xlsx').writeAsBytes(bytes); /// workbook.dispose(); /// ``` - Hyperlink add(Range range, HyperlinkType linkType, String address, - [String? screenTip, String? textToDisplay]) { + Hyperlink add( + Range range, + HyperlinkType linkType, + String address, [ + String? screenTip, + String? textToDisplay, + ]) { final Hyperlink hyperlink = Hyperlink(_worksheet); hyperlink.isHyperlinkStyle = range.builtInStyle = BuiltInStyles.hyperlink; hyperlink.row = range.row; @@ -83,8 +88,12 @@ class HyperlinkCollection { /// File('HyperlinksImage.xlsx').writeAsBytes(bytes); /// workbook.dispose(); /// ``` - Hyperlink addImage(Picture picture, HyperlinkType linkType, String address, - [String? screenTip]) { + Hyperlink addImage( + Picture picture, + HyperlinkType linkType, + String address, [ + String? screenTip, + ]) { final Hyperlink hyperlink = Hyperlink(_worksheet); hyperlink.type = linkType; hyperlink.address = address; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/merged_cells/merged_cell_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/merged_cells/merged_cell_collection.dart index 3362f959a..7c7b39f1c 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/merged_cells/merged_cell_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/merged_cells/merged_cell_collection.dart @@ -28,10 +28,14 @@ class MergedCellCollection { final MergeCell intersectingCell = MergeCell(); intersectingCell.x = min(mCell.x, mergeCell.x); intersectingCell.y = min(mCell.y, mergeCell.y); - intersectingCell.width = - max(mCell.width + mCell.y, mergeCell.width + mergeCell.x); - intersectingCell.height = - max(mCell.height + mCell.y, mergeCell.height + mergeCell.y); + intersectingCell.width = max( + mCell.width + mCell.y, + mergeCell.width + mergeCell.x, + ); + intersectingCell.height = max( + mCell.height + mCell.y, + mergeCell.height + mergeCell.y, + ); intersectingCell.reference = '${this[count].reference.split(':')[0]}:${mergeCell.reference.split(':')[1]}'; innerList[count] = intersectingCell; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/page_setup/page_setup_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/page_setup/page_setup_impl.dart index 2bb293335..90035fa1b 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/page_setup/page_setup_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/page_setup/page_setup_impl.dart @@ -97,7 +97,7 @@ class PageSetupImpl implements PageSetup { ExcelPaperSize.a5ExtraPpaper: _convertUnits(235, 'MMtoInch'), ExcelPaperSize.iSOB5ExtraPaper: _convertUnits(276, 'MMtoInch'), ExcelPaperSize.a3TransversePaper: _convertUnits(297, 'MMtoInch'), - ExcelPaperSize.a3ExtraTransversePaper: _convertUnits(445, 'MMtoInch') + ExcelPaperSize.a3ExtraTransversePaper: _convertUnits(445, 'MMtoInch'), }; paperWidth = { ExcelPaperSize.a2Paper: _convertUnits(420, 'MMtoInch'), @@ -165,7 +165,7 @@ class PageSetupImpl implements PageSetup { ExcelPaperSize.a5ExtraPpaper: _convertUnits(174, 'MMtoInch'), ExcelPaperSize.iSOB5ExtraPaper: _convertUnits(210, 'MMtoInch'), ExcelPaperSize.a3TransversePaper: _convertUnits(420, 'MMtoInch'), - ExcelPaperSize.a3ExtraTransversePaper: _convertUnits(322, 'MMtoInch') + ExcelPaperSize.a3ExtraTransversePaper: _convertUnits(322, 'MMtoInch'), }; } @@ -553,7 +553,8 @@ class PageSetupImpl implements PageSetup { /// Converts cell range to Range name. String _convertToRangeName(String input) { final RegExp exp = RegExp( - r'(?[\$]?[A-Za-z]{1,3})(?[\$]?\d+):(?[\$]?[A-Za-z]{1,3})(?[\$]?\d+)'); + r'(?[\$]?[A-Za-z]{1,3})(?[\$]?\d+):(?[\$]?[A-Za-z]{1,3})(?[\$]?\d+)', + ); final RegExpMatch? output = exp.firstMatch(input); final String column1 = output![1].toString(); final String row1 = output[2].toString(); diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/column_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/column_collection.dart index ad19b4ed2..efe69c06f 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/column_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/column_collection.dart @@ -57,8 +57,11 @@ class ColumnCollection { _iCount = (iCount >= iBufCount) ? iCount : iBufCount; - final List list = - List.filled(_iCount, null, growable: true); + final List list = List.filled( + _iCount, + null, + growable: true, + ); list.setAll(0, _innerList); diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range.dart index 7ffa59e6e..9cf94cfc8 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range.dart @@ -294,7 +294,11 @@ class Range { if (formula != null) { if (worksheet.calcEngine != null) { final String cellRef = _getAddressLocalFromCalculatedValue( - row, column, lastRow, lastColumn); + row, + column, + lastRow, + lastColumn, + ); return worksheet.calcEngine!.pullUpdatedValue(cellRef); } return null; @@ -370,9 +374,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).numberFormat = value; } } @@ -455,9 +461,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { final Range range = worksheet.getRangeByIndex(iRow, iCol); range._cellStyle = value; range._setRange(); @@ -549,9 +557,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).rowHeight = value; } } @@ -591,9 +601,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).columnWidth = value; } } @@ -741,9 +753,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).number = number; } } @@ -803,9 +817,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).text = text; if (text.contains('\n')) { worksheet.getRangeByIndex(iRow, iCol).cellStyle.wrapText = true; @@ -902,9 +918,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).dateTime = dateTime; } } @@ -966,9 +984,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).formula = formula; } } @@ -1019,9 +1039,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).value = value; } } @@ -1078,7 +1100,11 @@ class Range { } String _getAddressLocalFromCalculatedValue( - int row, int column, int lastRow, int lastColumn) { + int row, + int column, + int lastRow, + int lastColumn, + ) { final String cell0 = _getCellName(row, column); if (row == lastRow || column == lastColumn) { return cell0; @@ -1159,8 +1185,10 @@ class Range { workbook.cultureInfo.numberFormat.currencySymbol; final int currencyIndex = inputFormat.indexOf(currencySymbol); if (currencyIndex != -1) { - inputFormat = - inputFormat.replaceAll('"$currencySymbol"', currencySymbol); + inputFormat = inputFormat.replaceAll( + '"$currencySymbol"', + currencySymbol, + ); } } return inputFormat; @@ -1201,7 +1229,11 @@ class Range { /// Gets the number or date time. String _getNumberOrDateTime( - Format formatImpl, double? dValue, int row, int column) { + Format formatImpl, + double? dValue, + int row, + int column, + ) { String displayText = ''; final ExcelFormatType formatType1 = formatImpl.getFormatTypeFromDouble(0); @@ -1217,8 +1249,10 @@ class Range { } else if (dValue.isInfinite) { return '#DIV/0!'; } else if (numberFormat != 'General' && numberFormat != '@') { - final NumberFormat formatter = - NumberFormat(numberFormat, workbook.culture); + final NumberFormat formatter = NumberFormat( + numberFormat, + workbook.culture, + ); String displayText = formatter.format(dValue); if (displayText.contains(r'$') || displayText.endsWith('*')) { if (displayText.startsWith('_(')) { @@ -1247,8 +1281,9 @@ class Range { dValue++; } if (dValue > - toOADate(workbook - .cultureInfo.dateTimeFormat.maxSupportedDateTime) || + toOADate( + workbook.cultureInfo.dateTimeFormat.maxSupportedDateTime, + ) || (dValue < 0)) { displayText = '######'; } else { @@ -1268,7 +1303,11 @@ class Range { /// Update the cell value when calc engine is enabled. static void _updateCellValue( - Worksheet worksheet, int column, int row, bool updateCellVaue) { + Worksheet worksheet, + int column, + int row, + bool updateCellVaue, + ) { if (worksheet.calcEngine != null && updateCellVaue) { final String cellRef = getAlphaLabel(column) + row.toString(); worksheet.calcEngine!.pullUpdatedValue(cellRef); @@ -1342,7 +1381,7 @@ class Range { 273, 304, 334, - 365 + 365, ]; final List daysToMonth366 = [ 0, @@ -1357,13 +1396,14 @@ class Range { 274, 305, 335, - 366 + 366, ]; if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { final List days = _isLeapYear(year) ? daysToMonth366 : daysToMonth365; final int y = year - 1; - final int n = y * 365 + + final int n = + y * 365 + ((y ~/ 4) | 0) - ((y ~/ 100) | 0) + ((y ~/ 400) | 0) + @@ -1397,13 +1437,15 @@ class Range { /// Convert date to OA value. static double toOADate(DateTime date) { int ticks = 0; - ticks = _dateToTicks(date.year, date.month, date.day) + + ticks = + _dateToTicks(date.year, date.month, date.day) + _timeToTicks(date.hour, date.minute, date.second); if (ticks == 0) { return 0.0; } const int ticksPerDay = 10000 * 1000 * 60 * 60 * 24; - const int daysTo1899 = (((365 * 4 + 1) * 25 - 1) * 4 + 1) * 4 + + const int daysTo1899 = + (((365 * 4 + 1) * 25 - 1) * 4 + 1) * 4 + ((365 * 4 + 1) * 25 - 1) * 3 - 367; const int doubleDateOffset = daysTo1899 * ticksPerDay; @@ -1429,8 +1471,9 @@ class Range { (mantisaPart * doubleSecondsPerDay * 1000).toInt(); final DateTime minOLEDate = DateTime.parse('1899-12-30 00:00:00'); DateTime oleDateFromValue = minOLEDate.add(Duration(days: integralPart)); - oleDateFromValue = - oleDateFromValue.add(Duration(milliseconds: totalMilliseconds)); + oleDateFromValue = oleDateFromValue.add( + Duration(milliseconds: totalMilliseconds), + ); return oleDateFromValue; } @@ -1446,9 +1489,11 @@ class Range { // ignore: prefer_final_locals for (int iRow = row, iLastRow = lastRow; iRow <= iLastRow; iRow++) { // ignore: prefer_final_locals - for (int iCol = column, iLastCol = lastColumn; - iCol <= iLastCol; - iCol++) { + for ( + int iCol = column, iLastCol = lastColumn; + iCol <= iLastCol; + iCol++ + ) { worksheet.getRangeByIndex(iRow, iCol).cellStyle = globalStyle; } } @@ -1599,8 +1644,13 @@ class Range { throw Exception('lastColumn'); } - final AutoFitManager autoFitManager = - AutoFitManager(iFirstRow, firstColumn, iLastRow, lastColumn, this); + final AutoFitManager autoFitManager = AutoFitManager( + iFirstRow, + firstColumn, + iLastRow, + lastColumn, + this, + ); autoFitManager.measureToFitColumn(); } @@ -1671,7 +1721,9 @@ class Range { '${getColumnName(column)}$row:${getColumnName(lastColumn)}$lastRow'; } return _worksheet.createConditionalFormatWrapper( - this, conditionalFormatValue); + this, + conditionalFormatValue, + ); } /// Releases the unmanaged resources used by the XmlReader and optionally releases the managed resources. diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range_collection.dart index 384345334..0d35b10f3 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/range/range_collection.dart @@ -52,8 +52,11 @@ class RangeCollection { _iCount = (iCount >= iBufCount) ? iCount : iBufCount; - final List list = - List.filled(_iCount, null, growable: true); + final List list = List.filled( + _iCount, + null, + growable: true, + ); list.setAll(0, _innerList); diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltable_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltable_impl.dart index 37dd42e05..995c6e437 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltable_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltable_impl.dart @@ -101,8 +101,12 @@ class ExcelTableImpl implements ExcelTable { if (value) { totalsRowShown = true; if (_location.lastRow < iMaxRow) { - final Range beforeTotalRow = worksheet.getRangeByIndex(_location.row, - _location.column, _location.lastRow, _location.lastColumn); + final Range beforeTotalRow = worksheet.getRangeByIndex( + _location.row, + _location.column, + _location.lastRow, + _location.lastColumn, + ); _location = _checkTotalsRange(beforeTotalRow); _totalRowCount = 1; } @@ -116,7 +120,11 @@ class ExcelTableImpl implements ExcelTable { Range _checkTotalsRange(Range range) { if (range.row <= range.lastRow) { range = worksheet.getRangeByIndex( - range.row, range.column, range.lastRow + 1, range.lastColumn); + range.row, + range.column, + range.lastRow + 1, + range.lastColumn, + ); } return range; } @@ -206,20 +214,34 @@ class ExcelTableImpl implements ExcelTable { if (!worksheet.workbook.isSaving) { if (value == false) { worksheet - .getRangeByIndex(dataRange.row, dataRange.column, dataRange.row, - dataRange.lastColumn) + .getRangeByIndex( + dataRange.row, + dataRange.column, + dataRange.row, + dataRange.lastColumn, + ) .text = ''; - dataRange = worksheet.getRangeByIndex(dataRange.row + 1, - dataRange.column, dataRange.lastRow, dataRange.lastColumn); + dataRange = worksheet.getRangeByIndex( + dataRange.row + 1, + dataRange.column, + dataRange.lastRow, + dataRange.lastColumn, + ); } else { final int iHeaderRow = dataRange.row - 1; - dataRange = worksheet.getRangeByIndex(iHeaderRow, dataRange.column, - dataRange.lastRow, dataRange.lastColumn); + dataRange = worksheet.getRangeByIndex( + iHeaderRow, + dataRange.column, + dataRange.lastRow, + dataRange.lastColumn, + ); final int iFirstColumn = dataRange.column; - for (int columnCount = 0; - columnCount < _columns.length; - columnCount++) { + for ( + int columnCount = 0; + columnCount < _columns.length; + columnCount++ + ) { final int iColumn = iFirstColumn + columnCount; worksheet .getRangeByIndex(iHeaderRow, iColumn, iHeaderRow, iColumn) @@ -284,9 +306,11 @@ class ExcelTableImpl implements ExcelTable { _columns = []; final List columnNames = []; - for (int columnCount = _location.column; - columnCount <= _location.lastColumn; - columnCount++) { + for ( + int columnCount = _location.column; + columnCount <= _location.lastColumn; + columnCount++ + ) { final Range range = worksheet.getRangeByIndex(_location.row, columnCount); String? strColumnName = range.text; if (strColumnName == null || strColumnName.isEmpty) { @@ -299,8 +323,14 @@ class ExcelTableImpl implements ExcelTable { range.text = strColumnName; } columnNames.add(strColumnName); - _columns.add(ExcelTableColumnImpl( - strColumnName, _columns.length + 1, this, columnCount)); + _columns.add( + ExcelTableColumnImpl( + strColumnName, + _columns.length + 1, + this, + columnCount, + ), + ); } updateColumnNames(columnNames); @@ -345,7 +375,8 @@ class ExcelTableImpl implements ExcelTable { if (int.tryParse(name[0]) != null) { throw Exception( - 'This is not a valid name. Name should start with letter or underscore.'); + 'This is not a valid name. Name should start with letter or underscore.', + ); } final List arr = [ '~', @@ -370,7 +401,7 @@ class ExcelTableImpl implements ExcelTable { '<', '>', ',', - ' ' + ' ', ]; for (int arrayLength = 0; arrayLength < arr.length; arrayLength++) { @@ -382,7 +413,8 @@ class ExcelTableImpl implements ExcelTable { } if (count != 0) { throw Exception( - 'This is not a valid name. Name should not contain space or characters not allowed.'); + 'This is not a valid name. Name should not contain space or characters not allowed.', + ); } } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecollection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecollection.dart index 6b108b5a9..aa1d6cbf5 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecollection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecollection.dart @@ -38,8 +38,11 @@ class ExcelTableCollection { final Workbook book = range.worksheet.workbook; range = _checkRange(range); _checkOverlap(range); - final ExcelTableImpl result = - ExcelTableImpl(tableName, range, _tableCollection.length + 1); + final ExcelTableImpl result = ExcelTableImpl( + tableName, + range, + _tableCollection.length + 1, + ); result.name = _isNameExists(tableName); result.dataRange = range; result.index = ++book.maxTableIndex; @@ -66,9 +69,11 @@ class ExcelTableCollection { final int column = range.column; final int lastRow = range.lastRow; final int lastColumn = range.lastColumn; - for (int tableCount = 0; - tableCount < sheet.tableCollection.count; - tableCount++) { + for ( + int tableCount = 0; + tableCount < sheet.tableCollection.count; + tableCount++ + ) { final ExcelTable table = sheet.tableCollection[tableCount]; final int tableRow = table.dataRange.row; final int tableColumn = table.dataRange.column; @@ -77,35 +82,41 @@ class ExcelTableCollection { if ((row > tableRow - 1 && row < tableLastRow + 1) && (column > tableColumn - 1 && column < tableLastColumn + 1)) { throw Exception( - 'A table cannot overlap a range that contains another table'); + 'A table cannot overlap a range that contains another table', + ); } if ((row > tableRow - 1 && row < tableLastRow + 1) && (lastColumn > tableColumn - 1 && lastColumn < tableLastColumn + 1)) { throw Exception( - 'A table cannot overlap a range that contains another table'); + 'A table cannot overlap a range that contains another table', + ); } if ((lastRow > tableRow - 1 && lastRow < tableLastRow + 1) && (column > tableColumn - 1 && column < tableLastColumn + 1)) { throw Exception( - 'A table cannot overlap a range that contains another table'); + 'A table cannot overlap a range that contains another table', + ); } if ((lastRow > tableRow - 1 && lastRow < tableLastRow + 1) && (lastColumn > tableColumn - 1 && lastColumn < tableLastColumn + 1)) { throw Exception( - 'A table cannot overlap a range that contains another table'); + 'A table cannot overlap a range that contains another table', + ); } if ((row < tableRow - 1 && row < tableLastRow + 1) || (lastRow > tableRow - 1 && lastRow < tableLastRow + 1)) { if (tableColumn > column && tableLastColumn < lastColumn) { throw Exception( - 'A table cannot overlap a range that contains another table'); + 'A table cannot overlap a range that contains another table', + ); } } if ((column < tableColumn - 1 && column < tableLastColumn + 1) || (lastColumn > tableColumn - 1 && lastColumn < tableLastColumn + 1)) { if (tableRow > row && tableLastRow < lastRow) { throw Exception( - 'A table cannot overlap a range that contains another table'); + 'A table cannot overlap a range that contains another table', + ); } } } @@ -115,7 +126,11 @@ class ExcelTableCollection { Range _checkRange(Range range) { if (range.row == range.lastRow) { range = _sheet.getRangeByIndex( - range.row, range.column, range.row + 1, range.lastColumn); + range.row, + range.column, + range.row + 1, + range.lastColumn, + ); } return range; } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecolumn_impl.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecolumn_impl.dart index e41fbe72d..9e7da3343 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecolumn_impl.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/exceltablecolumn_impl.dart @@ -9,7 +9,11 @@ import 'exceltablecolumn.dart'; class ExcelTableColumnImpl implements ExcelTableColumn { /// Initializes new instance of the class. ExcelTableColumnImpl( - String name, int index, ExcelTableImpl parentTable, int id) { + String name, + int index, + ExcelTableImpl parentTable, + int id, + ) { _name = name; _index = index; _parentTable = parentTable; @@ -56,9 +60,11 @@ class ExcelTableColumnImpl implements ExcelTableColumn { final List colNames = []; final int firstColumn = tableRange.column - tableColumnIndex; final int lastColumn = tableRange.lastColumn - tableColumnIndex; - for (int columnIndex = firstColumn; - columnIndex <= lastColumn; - columnIndex++) { + for ( + int columnIndex = firstColumn; + columnIndex <= lastColumn; + columnIndex++ + ) { colNames.add(_parentTable.columns[columnIndex].columnName); } colNames.removeAt(setIndex); @@ -76,8 +82,10 @@ class ExcelTableColumnImpl implements ExcelTableColumn { /// Get the total cell for the column. Range get totalCell { final Range location = _parentTable.dataRange; - return location.worksheet - .getRangeByIndex(location.lastRow, location.column + _columnIndex - 1); + return location.worksheet.getRangeByIndex( + location.lastRow, + location.column + _columnIndex - 1, + ); } /// Gets or sets the function used for totals calculation. diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/table_serialization.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/table_serialization.dart index 5d55f49b6..a1c75ecee 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/table_serialization.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/table/table_serialization.dart @@ -31,9 +31,11 @@ class TableSerialization { int id = 1; if (tableCollection.count > 0) { if (sheet.hyperlinks.count > 0) { - for (int hyperlinkIndex = 0; - hyperlinkIndex < sheet.hyperlinks.count; - hyperlinkIndex++) { + for ( + int hyperlinkIndex = 0; + hyperlinkIndex < sheet.hyperlinks.count; + hyperlinkIndex++ + ) { if (sheet.hyperlinks[hyperlinkIndex].attachedType == ExcelHyperlinkAttachedType.range && sheet.hyperlinks[hyperlinkIndex].type != HyperlinkType.workbook) { @@ -42,9 +44,11 @@ class TableSerialization { } } if (sheet.pictures.count > 0) { - for (int imageIndex = 0; - imageIndex < sheet.pictures.count; - imageIndex++) { + for ( + int imageIndex = 0; + imageIndex < sheet.pictures.count; + imageIndex++ + ) { id++; } } @@ -53,25 +57,37 @@ class TableSerialization { id++; } } - builder.element('tableParts', nest: () { - builder.attribute('count', tableCollection.count); - for (int tableCount = 0; + builder.element( + 'tableParts', + nest: () { + builder.attribute('count', tableCollection.count); + for ( + int tableCount = 0; tableCount < tableCollection.count; - tableCount++) { - rid = id++; - final ExcelTable table = tableCollection[tableCount]; - _serializeTable(table, tableCount + 1, sheet); - builder.element('tablePart', nest: () { - builder.attribute('r:id', 'rId$rid'); - }); - } - }); + tableCount++ + ) { + rid = id++; + final ExcelTable table = tableCollection[tableCount]; + _serializeTable(table, tableCount + 1, sheet); + builder.element( + 'tablePart', + nest: () { + builder.attribute('r:id', 'rId$rid'); + }, + ); + } + }, + ); } } /// Serializes attribute if it differs from default value. void _serializeAttributeBool( - XmlBuilder builder, String attributeName, bool value, bool defaultValue) { + XmlBuilder builder, + String attributeName, + bool value, + bool defaultValue, + ) { String? strValue; if (value != defaultValue) { strValue = value ? '1' : '0'; @@ -83,7 +99,11 @@ class TableSerialization { /// Serializes attribute if it differs from default value. void _serializeAttributeInt( - XmlBuilder builder, String attributeName, int value, int defaultValue) { + XmlBuilder builder, + String attributeName, + int value, + int defaultValue, + ) { if (value != defaultValue) { final String strValue = value.toString(); builder.attribute(attributeName, strValue); @@ -91,8 +111,12 @@ class TableSerialization { } /// Serializes attribute if it differs from default value. - void _serializeAttributeString(XmlBuilder builder, String attributeName, - String value, String defaultValue) { + void _serializeAttributeString( + XmlBuilder builder, + String attributeName, + String value, + String defaultValue, + ) { if (value != defaultValue) { builder.attribute(attributeName, value); } @@ -102,46 +126,61 @@ class TableSerialization { void _serializeTable(ExcelTable table, int index, Worksheet sheet) { final XmlBuilder builder = XmlBuilder(); _workbook.tableCount++; - builder.element('table', nest: () { - builder.attribute('id', (table as ExcelTableImpl).tableIndex); - builder.attribute('name', table.tableName); - builder.attribute('displayName', table.displayName); - builder.attribute('ref', table.dataRange.addressLocal); - if (!table.totalsRowShown) { - _serializeAttributeBool(builder, 'totalsRowShown', false, true); - } else { - _serializeAttributeInt( - builder, 'totalsRowCount', table.totalRowCount, 0); - } - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + builder.element( + 'table', + nest: () { + builder.attribute('id', (table as ExcelTableImpl).tableIndex); + builder.attribute('name', table.tableName); + builder.attribute('displayName', table.displayName); + builder.attribute('ref', table.dataRange.addressLocal); + if (!table.totalsRowShown) { + _serializeAttributeBool(builder, 'totalsRowShown', false, true); + } else { + _serializeAttributeInt( + builder, + 'totalsRowCount', + table.totalRowCount, + 0, + ); + } + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); - final ExcelTableImpl typedTable = table; - if (!typedTable.showHeaderRow) { - builder.attribute('headerRowCount', '0'); - } - if (_isTableAutoFlter(sheet)) { - builder.element('autoFilter', nest: () { - builder.attribute('ref', sheet.autoFilters.filterRange.addressLocal); - // ignore: always_specify_types - for (int i = 0; i < sheet.autoFilters.count; i++) { - final AutoFilterImpl autoFilter = - sheet.autoFilters[i] as AutoFilterImpl; - - if (autoFilter.isFiltered) { - final SerializeWorkbook serializeWorkbook = - SerializeWorkbook(sheet.workbook); - serializeWorkbook.serializeFilterColumn(builder, autoFilter); - } - } - }); - } - _serializeTableColumns(builder, table.columns); + final ExcelTableImpl typedTable = table; + if (!typedTable.showHeaderRow) { + builder.attribute('headerRowCount', '0'); + } + if (_isTableAutoFlter(sheet)) { + builder.element( + 'autoFilter', + nest: () { + builder.attribute( + 'ref', + sheet.autoFilters.filterRange.addressLocal, + ); + // ignore: always_specify_types + for (int i = 0; i < sheet.autoFilters.count; i++) { + final AutoFilterImpl autoFilter = + sheet.autoFilters[i] as AutoFilterImpl; + + if (autoFilter.isFiltered) { + final SerializeWorkbook serializeWorkbook = SerializeWorkbook( + sheet.workbook, + ); + serializeWorkbook.serializeFilterColumn(builder, autoFilter); + } + } + }, + ); + } + _serializeTableColumns(builder, table.columns); - _serializeTableStyle(builder, table); + _serializeTableStyle(builder, table); - _serializeTableExtensionList(builder, table); - }); + _serializeTableExtensionList(builder, table); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/tables/table${_workbook.tableCount}.xml'); @@ -167,64 +206,103 @@ class TableSerialization { /// Serialize Columns void _serializeTableColumns( - XmlBuilder builder, List columns) { - builder.element('tableColumns', nest: () { - for (int columnCount = 0; columnCount < columns.length; columnCount++) { - final ExcelTableColumn column = columns[columnCount]; - _serializeTableColumn(builder, column); - } - }); + XmlBuilder builder, + List columns, + ) { + builder.element( + 'tableColumns', + nest: () { + for (int columnCount = 0; columnCount < columns.length; columnCount++) { + final ExcelTableColumn column = columns[columnCount]; + _serializeTableColumn(builder, column); + } + }, + ); } /// Serialize Column. void _serializeTableColumn(XmlBuilder builder, ExcelTableColumn column) { - builder.element('tableColumn', nest: () { - builder.attribute('id', (column as ExcelTableColumnImpl).columnId); - builder.attribute('name', column.columnName); - _serializeAttributeString( - builder, 'totalsRowLabel', column.totalRowLabel, ''); - if (column.totalFormula != ExcelTableTotalFormula.none) { - builder.attribute( - 'totalsRowFunction', _getTotalsCalculation(column.totalFormula)); - } - }); + builder.element( + 'tableColumn', + nest: () { + builder.attribute('id', (column as ExcelTableColumnImpl).columnId); + builder.attribute('name', column.columnName); + _serializeAttributeString( + builder, + 'totalsRowLabel', + column.totalRowLabel, + '', + ); + if (column.totalFormula != ExcelTableTotalFormula.none) { + builder.attribute( + 'totalsRowFunction', + _getTotalsCalculation(column.totalFormula), + ); + } + }, + ); } /// Serialize Table Style. void _serializeTableStyle(XmlBuilder builder, ExcelTable table) { final ExcelTableBuiltInStyle style = table.builtInTableStyle; - builder.element('tableStyleInfo', nest: () { - builder.attribute('name', _getTableStyles(style)); - - builder.attribute( - 'showFirstColumn', (table.showFirstColumn ? 1 : 0).toString()); - builder.attribute( - 'showLastColumn', (table.showLastColumn ? 1 : 0).toString()); - builder.attribute( - 'showRowStripes', (table.showBandedRows ? 1 : 0).toString()); - builder.attribute( - 'showColumnStripes', (table.showBandedColumns ? 1 : 0).toString()); - }); + builder.element( + 'tableStyleInfo', + nest: () { + builder.attribute('name', _getTableStyles(style)); + + builder.attribute( + 'showFirstColumn', + (table.showFirstColumn ? 1 : 0).toString(), + ); + builder.attribute( + 'showLastColumn', + (table.showLastColumn ? 1 : 0).toString(), + ); + builder.attribute( + 'showRowStripes', + (table.showBandedRows ? 1 : 0).toString(), + ); + builder.attribute( + 'showColumnStripes', + (table.showBandedColumns ? 1 : 0).toString(), + ); + }, + ); } /// Serializes the table extension list. void _serializeTableExtensionList(XmlBuilder builder, ExcelTable table) { if (table.altTextTitle.isNotEmpty || table.altTextSummary.isNotEmpty) { - builder.element('extLst', nest: () { - builder.element('ext', nest: () { - builder.attribute('uri', '{504A1905-F514-4f6f-8877-14C23A59335A}'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - builder.element('x14:table', nest: () { - if (table.altTextTitle.isNotEmpty) { - builder.attribute('altText', table.altTextTitle); - } - if (table.altTextSummary.isNotEmpty) { - builder.attribute('altTextSummary', table.altTextSummary); - } - }); - }); - }); + builder.element( + 'extLst', + nest: () { + builder.element( + 'ext', + nest: () { + builder.attribute( + 'uri', + '{504A1905-F514-4f6f-8877-14C23A59335A}', + ); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + builder.element( + 'x14:table', + nest: () { + if (table.altTextTitle.isNotEmpty) { + builder.attribute('altText', table.altTextTitle); + } + if (table.altTextSummary.isNotEmpty) { + builder.attribute('altTextSummary', table.altTextSummary); + } + }, + ); + }, + ); + }, + ); } } @@ -458,9 +536,11 @@ class TableSerialization { int id = 1; if (tableCollection.count > 0) { if (sheet.hyperlinks.count > 0) { - for (int hyperlinkIndex = 0; - hyperlinkIndex < sheet.hyperlinks.count; - hyperlinkIndex++) { + for ( + int hyperlinkIndex = 0; + hyperlinkIndex < sheet.hyperlinks.count; + hyperlinkIndex++ + ) { if (sheet.hyperlinks[hyperlinkIndex].attachedType == ExcelHyperlinkAttachedType.range && sheet.hyperlinks[hyperlinkIndex].type != HyperlinkType.workbook) { @@ -469,31 +549,45 @@ class TableSerialization { } } if (sheet.pictures.count > 0) { - for (int imageIndex = 0; - imageIndex < sheet.pictures.count; - imageIndex++) { + for ( + int imageIndex = 0; + imageIndex < sheet.pictures.count; + imageIndex++ + ) { id++; } } - builder.element('tableParts', nest: () async { - builder.attribute('count', tableCollection.count); - for (int tableCount = 0; + builder.element( + 'tableParts', + nest: () async { + builder.attribute('count', tableCollection.count); + for ( + int tableCount = 0; tableCount < tableCollection.count; - tableCount++) { - rid = id++; - final ExcelTable table = tableCollection[tableCount]; - _serializeTableAsync(table, tableCount + 1); - builder.element('tablePart', nest: () { - builder.attribute('r:id', 'rId$rid'); - }); - } - }); + tableCount++ + ) { + rid = id++; + final ExcelTable table = tableCollection[tableCount]; + _serializeTableAsync(table, tableCount + 1); + builder.element( + 'tablePart', + nest: () { + builder.attribute('r:id', 'rId$rid'); + }, + ); + } + }, + ); } } /// Serializes attribute if it differs from default value. - Future _serializeAttributeBoolAsync(XmlBuilder builder, - String attributeName, bool value, bool defaultValue) async { + Future _serializeAttributeBoolAsync( + XmlBuilder builder, + String attributeName, + bool value, + bool defaultValue, + ) async { String? strValue; if (value != defaultValue) { strValue = value ? '1' : '0'; @@ -504,8 +598,12 @@ class TableSerialization { } /// Serializes attribute if it differs from default value. - Future _serializeAttributeIntAsync(XmlBuilder builder, - String attributeName, int value, int defaultValue) async { + Future _serializeAttributeIntAsync( + XmlBuilder builder, + String attributeName, + int value, + int defaultValue, + ) async { if (value != defaultValue) { final String strValue = value.toString(); builder.attribute(attributeName, strValue); @@ -513,8 +611,12 @@ class TableSerialization { } /// Serializes attribute if it differs from default value. - Future _serializeAttributeStringAsync(XmlBuilder builder, - String attributeName, String value, String defaultValue) async { + Future _serializeAttributeStringAsync( + XmlBuilder builder, + String attributeName, + String value, + String defaultValue, + ) async { if (value != defaultValue) { builder.attribute(attributeName, value); } @@ -524,29 +626,37 @@ class TableSerialization { Future _serializeTableAsync(ExcelTable table, int index) async { final XmlBuilder builder = XmlBuilder(); _workbook.tableCount++; - builder.element('table', nest: () async { - builder.attribute('id', (table as ExcelTableImpl).tableIndex); - builder.attribute('name', table.tableName); - builder.attribute('displayName', table.displayName); - builder.attribute('ref', table.dataRange.addressLocal); - if (!table.totalsRowShown) { - _serializeAttributeBoolAsync(builder, 'totalsRowShown', false, true); - } else { - _serializeAttributeIntAsync( - builder, 'totalsRowCount', table.totalRowCount, 0); - } - builder.namespace( - 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + builder.element( + 'table', + nest: () async { + builder.attribute('id', (table as ExcelTableImpl).tableIndex); + builder.attribute('name', table.tableName); + builder.attribute('displayName', table.displayName); + builder.attribute('ref', table.dataRange.addressLocal); + if (!table.totalsRowShown) { + _serializeAttributeBoolAsync(builder, 'totalsRowShown', false, true); + } else { + _serializeAttributeIntAsync( + builder, + 'totalsRowCount', + table.totalRowCount, + 0, + ); + } + builder.namespace( + 'http://schemas.openxmlformats.org/spreadsheetml/2006/main', + ); - final ExcelTableImpl typedTable = table; - if (!typedTable.showHeaderRow) { - builder.attribute('headerRowCount', '0'); - } + final ExcelTableImpl typedTable = table; + if (!typedTable.showHeaderRow) { + builder.attribute('headerRowCount', '0'); + } - _serializeTableColumnsAsync(builder, table.columns); - _serializeTableStyleAsync(builder, table); - _serializeTableExtensionListAsync(builder, table); - }); + _serializeTableColumnsAsync(builder, table.columns); + _serializeTableStyleAsync(builder, table); + _serializeTableExtensionListAsync(builder, table); + }, + ); final String stringXml = builder.buildDocument().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync(bytes, 'xl/tables/table${_workbook.tableCount}.xml'); @@ -560,66 +670,111 @@ class TableSerialization { /// Serialize Columns Future _serializeTableColumnsAsync( - XmlBuilder builder, List columns) async { - builder.element('tableColumns', nest: () async { - for (int columnCount = 0; columnCount < columns.length; columnCount++) { - final ExcelTableColumn column = columns[columnCount]; - _serializeTableColumnAsync(builder, column); - } - }); + XmlBuilder builder, + List columns, + ) async { + builder.element( + 'tableColumns', + nest: () async { + for (int columnCount = 0; columnCount < columns.length; columnCount++) { + final ExcelTableColumn column = columns[columnCount]; + _serializeTableColumnAsync(builder, column); + } + }, + ); } /// Serialize Column. Future _serializeTableColumnAsync( - XmlBuilder builder, ExcelTableColumn column) async { - builder.element('tableColumn', nest: () async { - builder.attribute('id', (column as ExcelTableColumnImpl).columnId); - builder.attribute('name', column.columnName); - _serializeAttributeStringAsync( - builder, 'totalsRowLabel', column.totalRowLabel, ''); - if (column.totalFormula != ExcelTableTotalFormula.none) { - builder.attribute( - 'totalsRowFunction', _getTotalsCalculation(column.totalFormula)); - } - }); + XmlBuilder builder, + ExcelTableColumn column, + ) async { + builder.element( + 'tableColumn', + nest: () async { + builder.attribute('id', (column as ExcelTableColumnImpl).columnId); + builder.attribute('name', column.columnName); + _serializeAttributeStringAsync( + builder, + 'totalsRowLabel', + column.totalRowLabel, + '', + ); + if (column.totalFormula != ExcelTableTotalFormula.none) { + builder.attribute( + 'totalsRowFunction', + _getTotalsCalculation(column.totalFormula), + ); + } + }, + ); } /// Serialize Table Style. Future _serializeTableStyleAsync( - XmlBuilder builder, ExcelTable table) async { + XmlBuilder builder, + ExcelTable table, + ) async { final ExcelTableBuiltInStyle style = table.builtInTableStyle; - builder.element('tableStyleInfo', nest: () async { - builder.attribute('name', _getTableStyles(style)); - builder.attribute( - 'showFirstColumn', (table.showFirstColumn ? 1 : 0).toString()); - builder.attribute( - 'showLastColumn', (table.showLastColumn ? 1 : 0).toString()); - builder.attribute( - 'showRowStripes', (table.showBandedRows ? 1 : 0).toString()); - builder.attribute( - 'showColumnStripes', (table.showBandedColumns ? 1 : 0).toString()); - }); + builder.element( + 'tableStyleInfo', + nest: () async { + builder.attribute('name', _getTableStyles(style)); + builder.attribute( + 'showFirstColumn', + (table.showFirstColumn ? 1 : 0).toString(), + ); + builder.attribute( + 'showLastColumn', + (table.showLastColumn ? 1 : 0).toString(), + ); + builder.attribute( + 'showRowStripes', + (table.showBandedRows ? 1 : 0).toString(), + ); + builder.attribute( + 'showColumnStripes', + (table.showBandedColumns ? 1 : 0).toString(), + ); + }, + ); } /// Serializes the table extension list. Future _serializeTableExtensionListAsync( - XmlBuilder builder, ExcelTable table) async { + XmlBuilder builder, + ExcelTable table, + ) async { if (table.altTextTitle.isNotEmpty || table.altTextSummary.isNotEmpty) { - builder.element('extLst', nest: () { - builder.element('ext', nest: () { - builder.attribute('uri', '{504A1905-F514-4f6f-8877-14C23A59335A}'); - builder.attribute('xmlns:x14', - 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main'); - builder.element('x14:table', nest: () { - if (table.altTextTitle.isNotEmpty) { - builder.attribute('altText', table.altTextTitle); - } - if (table.altTextSummary.isNotEmpty) { - builder.attribute('altTextSummary', table.altTextSummary); - } - }); - }); - }); + builder.element( + 'extLst', + nest: () { + builder.element( + 'ext', + nest: () { + builder.attribute( + 'uri', + '{504A1905-F514-4f6f-8877-14C23A59335A}', + ); + builder.attribute( + 'xmlns:x14', + 'http://schemas.microsoft.com/office/spreadsheetml/2009/9/main', + ); + builder.element( + 'x14:table', + nest: () { + if (table.altTextTitle.isNotEmpty) { + builder.attribute('altText', table.altTextTitle); + } + if (table.altTextSummary.isNotEmpty) { + builder.attribute('altTextSummary', table.altTextSummary); + } + }, + ); + }, + ); + }, + ); } } } diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet.dart index 4a76b6014..f1c661ab5 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet.dart @@ -362,7 +362,8 @@ class Worksheet { if (book.worksheets.innerList.length <= 1 && visibilty == WorksheetVisibility.hidden) { throw Exception( - 'A workbook must contain at least one visible worksheet.'); + 'A workbook must contain at least one visible worksheet.', + ); } else { _visibility = visibilty; } @@ -375,7 +376,8 @@ class Worksheet { column < 1 || column > workbook.maxColumnCount) { throw Exception( - 'Specified argument was out of the range of valid values.'); + 'Specified argument was out of the range of valid values.', + ); } } @@ -389,8 +391,12 @@ class Worksheet { /// File('Range.xlsx').writeAsBytes(bytes); /// workbook.dispose(); /// ``` - Range getRangeByIndex(int rowIndex, int columnIndex, - [int lastRowIndex = -1, int lastColumnIndex = -1]) { + Range getRangeByIndex( + int rowIndex, + int columnIndex, [ + int lastRowIndex = -1, + int lastColumnIndex = -1, + ]) { checkRange(rowIndex, columnIndex); if (lastRowIndex != -1 && lastColumnIndex != -1) { checkRange(lastRowIndex, lastColumnIndex); @@ -433,8 +439,9 @@ class Worksheet { } else if (cellReference.length < 2) { throw Exception('cellReference cannot be less then 2 symbols'); } else if (cellReference.isEmpty) { - final Error error = - ArgumentError('cellReference - Value cannot be empty.'); + final Error error = ArgumentError( + 'cellReference - Value cannot be empty.', + ); throw error; } final List cells = cellReference.split(':'); @@ -471,13 +478,16 @@ class Worksheet { } if (cellReference.length < 2) { final Error error = ArgumentError( - 'cellReference - name cannot be less then 2 symbols.'); + 'cellReference - name cannot be less then 2 symbols.', + ); throw error; } final String strNumber = cellReference.substring(iDigitStart); - final String strAlpha = - cellReference.substring(iLetterStart, iLetterCount); + final String strAlpha = cellReference.substring( + iLetterStart, + iLetterCount, + ); if (i == 0) { firstRow = lastRow = int.parse(strNumber); @@ -505,13 +515,15 @@ class Worksheet { final String decimalSeparator = currentCulture.numberFormat.numberDecimalSeparator; final RegExp regex = RegExp( - '([0-9]*:[0-9]*:[0-9]*"$decimalSeparator[0-9]*|[0-9]*:[0-9]*:[0-9]*|[0-9]*:[0-9]*"$decimalSeparator[0-9]*|[0-9]*:[0-9]*)'); + '([0-9]*:[0-9]*:[0-9]*"$decimalSeparator[0-9]*|[0-9]*:[0-9]*:[0-9]*|[0-9]*:[0-9]*"$decimalSeparator[0-9]*|[0-9]*:[0-9]*)', + ); final List matches = regex.allMatches(value).toList(); for (final Match match in matches) { final String semiColon = currentCulture.dateTimeFormat.timeSeparator; const String valueFormat = SecondToken.defaultFormatLong; - final List timeValues = - match.pattern.toString().split(semiColon); + final List timeValues = match.pattern.toString().split( + semiColon, + ); final int minutesValue = Range.fromOADate(dNumber).minute; String updatedValue = timeValues[0]; int updateMinutesValue = 0; @@ -521,16 +533,20 @@ class Worksheet { if (updateMinutesValue == 60) { updatedValue = (int.parse(timeValues[0]) + 1).toString(); // .toString(valueFormat); - updatedValue = updatedValue + + updatedValue = + updatedValue + semiColon + timeValues[timeValues.length - 1].replaceAll( - timeValues[timeValues.length - 1], valueFormat); + timeValues[timeValues.length - 1], + valueFormat, + ); value = value.replaceAll(match.pattern.toString(), updatedValue); } break; case 3: final int secondsValue = Range.fromOADate(dNumber).second; - final int updatedSecondsValue = secondsValue + + final int updatedSecondsValue = + secondsValue + (timeValues[timeValues.length - 1].contains(decimalSeparator) ? 0 : 1); @@ -539,28 +555,37 @@ class Worksheet { if (updateMinutesValue == 60) { updatedValue = (int.parse(timeValues[0]) + 1).toString(); // .toString(valueFormat); - updatedValue = updatedValue + + updatedValue = + updatedValue + semiColon + valueFormat + semiColon + - timeValues[timeValues.length - 1] - .replaceAll(secondsValue.toString(), valueFormat); + timeValues[timeValues.length - 1].replaceAll( + secondsValue.toString(), + valueFormat, + ); } else { - updatedValue = timeValues[0] + + updatedValue = + timeValues[0] + semiColon + updateMinutesValue.toString() + // .toString(valueFormat) semiColon + - timeValues[timeValues.length - 1] - .replaceAll(secondsValue.toString(), valueFormat); + timeValues[timeValues.length - 1].replaceAll( + secondsValue.toString(), + valueFormat, + ); } } else { - updatedValue = timeValues[0] + + updatedValue = + timeValues[0] + semiColon + timeValues[1] + semiColon + timeValues[timeValues.length - 1].replaceAll( - secondsValue.toString(), updatedSecondsValue.toString()); + secondsValue.toString(), + updatedSecondsValue.toString(), + ); } value = value.replaceAll(match.pattern.toString(), updatedValue); break; @@ -590,8 +615,9 @@ class Worksheet { /// ``` int getColumnIndex(String columnName) { if (columnName.isEmpty) { - final Error error = - ArgumentError('columnName - name cannot be less then 1 symbols.'); + final Error error = ArgumentError( + 'columnName - name cannot be less then 1 symbols.', + ); throw error; } @@ -601,7 +627,8 @@ class Worksheet { for (int i = 0, len = columnName.length; i < len; i++) { final String currentChar = columnName[i]; iColumn *= 26; - iColumn += 1 + + iColumn += + 1 + ((currentChar.codeUnitAt(0) >= 'a'.codeUnitAt(0)) ? (currentChar.codeUnitAt(0) - 'a'.codeUnitAt(0)) : (currentChar.codeUnitAt(0) - 'A'.codeUnitAt(0))); @@ -698,7 +725,7 @@ class Worksheet { final CultureInfo cultureInfo = book.getCultureInfo(); final bool bDateTime = !value.contains(cultureInfo.dateTimeFormat.dateSeparator) && - dateValue != null; + dateValue != null; bool isNumber = doubleValue != null; bool isboolean = false; bool iserrorStrings = false; @@ -753,8 +780,9 @@ class Worksheet { bool _checkIsNumber(String value, CultureInfo cultureInfo) { bool isNumber = true; if (value.contains(cultureInfo.numberFormat.numberDecimalSeparator)) { - final RegExp decimalSepRegex = - RegExp('[${cultureInfo.numberFormat.numberDecimalSeparator}]'); + final RegExp decimalSepRegex = RegExp( + '[${cultureInfo.numberFormat.numberDecimalSeparator}]', + ); final List decimalSepMatches = decimalSepRegex.allMatches(value).toList(); //Checks whether the value has more than one decimal point. @@ -762,18 +790,24 @@ class Worksheet { return false; } // Checks group separator before and after the decimal point. else if (value.contains(cultureInfo.numberFormat.numberGroupSeparator)) { - final int decimalIndex = - value.indexOf(cultureInfo.numberFormat.numberDecimalSeparator); + final int decimalIndex = value.indexOf( + cultureInfo.numberFormat.numberDecimalSeparator, + ); final String beforeDecimalValue = value.substring(0, decimalIndex); - final String afterDecimalValue = - value.substring(decimalIndex + 1, value.length - 1 - decimalIndex); - - if (afterDecimalValue - .contains(cultureInfo.numberFormat.numberGroupSeparator)) { + final String afterDecimalValue = value.substring( + decimalIndex + 1, + value.length - 1 - decimalIndex, + ); + + if (afterDecimalValue.contains( + cultureInfo.numberFormat.numberGroupSeparator, + )) { return false; } else { - isNumber = - _checkGroupSeparatorPosition(beforeDecimalValue, cultureInfo); + isNumber = _checkGroupSeparatorPosition( + beforeDecimalValue, + cultureInfo, + ); } } } else { @@ -791,8 +825,9 @@ class Worksheet { revStr = revStr + value[i]; } - final RegExp groupSepRegex = - RegExp('[${cultureInfo.numberFormat.numberGroupSeparator}]'); + final RegExp groupSepRegex = RegExp( + '[${cultureInfo.numberFormat.numberGroupSeparator}]', + ); final List groupSepMatches = groupSepRegex.allMatches(value).toList(); @@ -981,7 +1016,11 @@ class Worksheet { /// ``` void autoFitColumn(int colIndex) { final Range range = getRangeByIndex( - getFirstRow(), getFirstColumn(), getLastRow(), getLastColumn()); + getFirstRow(), + getFirstColumn(), + getLastRow(), + getLastColumn(), + ); range.autoFitToColumn(colIndex, colIndex); } @@ -1028,7 +1067,8 @@ class Worksheet { double getColumnWidth(int iColumnIndex) { if (iColumnIndex < 1 || iColumnIndex > book.maxColumnCount) { throw Exception( - 'Value cannot be less 1 and greater than max column index.'); + 'Value cannot be less 1 and greater than max column index.', + ); } return _innerGetColumnWidth(iColumnIndex); } @@ -1069,8 +1109,12 @@ class Worksheet { if (row != null) { final int firstColumn = getFirstColumn(); final int lastColumn = getLastColumn(); - final Range rowRange = - getRangeByIndex(iRow, firstColumn, iRow, lastColumn); + final Range rowRange = getRangeByIndex( + iRow, + firstColumn, + iRow, + lastColumn, + ); if (firstColumn > 0 && lastColumn > 0 && @@ -1145,8 +1189,12 @@ class Worksheet { if (range.rowSpan > 1) { continue; } - final List result = - _measureCell(range, true, false, isMergedAndWrapped); + final List result = _measureCell( + range, + true, + false, + isMergedAndWrapped, + ); curSize = result[0] as SizeF; isMergedAndWrapped = result[1] as bool; if (maxSize.fontHeight < curSize.fontHeight && @@ -1189,7 +1237,11 @@ class Worksheet { /// Sets inner row height. void setRowHeight( - int iRowIndex, double value, bool bIsBadFontHeight, int units) { + int iRowIndex, + double value, + bool bIsBadFontHeight, + int units, + ) { value = book.convertUnits(value, units, 6); Row? rowObj = rows[iRowIndex]; @@ -1204,8 +1256,12 @@ class Worksheet { } /// Gets size of string that contain cell found by cellindex. - List _measureCell(Range range, bool bAutoFitRows, - bool ignoreRotation, bool bIsMergedAndWrapped) { + List _measureCell( + Range range, + bool bAutoFitRows, + bool ignoreRotation, + bool bIsMergedAndWrapped, + ) { final int iColumn = range.column; bool isMerged = false; final String? strText = range.text; @@ -1231,8 +1287,10 @@ class Worksheet { double colWidth = getColumnWidthInPixels(iColumn).toDouble(); double defWidth = 0; if (indentLevel > 0 || rotation == 255) { - final Font fontStyle = - Font.withNameSize(format.fontName, format.fontSize); + final Font fontStyle = Font.withNameSize( + format.fontName, + format.fontSize, + ); const Rectangle rectF = Rectangle(0, 0, 1800, 100); defWidth = book.getMeasuredRectangle('0', fontStyle, rectF).width + 0.05; @@ -1254,7 +1312,10 @@ class Worksheet { range.formula == null) && workbook.standardFontSize != format.fontSize)) { final double value = _autoFitManager.calculateWrappedCell( - format, strText, colWidth.toInt()); + format, + strText, + colWidth.toInt(), + ); if (range.number != null) { curSize.fontWidth = value; } else { @@ -1267,22 +1328,33 @@ class Worksheet { if (!ignoreRotation && !isMerged && rotation > 0) { if (rotation == 255) { - curSize.fontWidth = book.convertToPixels( - _autoFitManager.calculateWrappedCell( - format, strText, defWidth.toInt()), - 6) - + curSize.fontWidth = + book.convertToPixels( + _autoFitManager.calculateWrappedCell( + format, + strText, + defWidth.toInt(), + ), + 6, + ) - defWidth; } else if (rotation != 90 && rotation != 180) { - curSize.fontWidth = - _updateTextWidthOrHeightByRotation(curSize, rotation, false); + curSize.fontWidth = _updateTextWidthOrHeightByRotation( + curSize, + rotation, + false, + ); } } } else { curSize = _updateAutofitByIndent(curSize, format); if (!ignoreRotation) { - curSize.fontWidth = - _updateTextWidthOrHeightByRotation(curSize, rotation, false); + curSize.fontWidth = _updateTextWidthOrHeightByRotation( + curSize, + rotation, + false, + ); } } bIsMergedAndWrapped = isMerged && format.wrapText; @@ -1303,7 +1375,10 @@ class Worksheet { /// Updates text width by rotation. double _updateTextWidthOrHeightByRotation( - SizeF size, int rotation, bool bUpdateHeight) { + SizeF size, + int rotation, + bool bUpdateHeight, + ) { if (rotation == 0) { return bUpdateHeight ? size.fontHeight : size.fontWidth; } @@ -1355,8 +1430,11 @@ class Worksheet { /// File('InsertRow.xlsx').writeAsBytes(bytes); /// workbook.dispose(); /// ``` - void insertRow(int rowIndex, - [int? rowCount, ExcelInsertOptions? insertOptions]) { + void insertRow( + int rowIndex, [ + int? rowCount, + ExcelInsertOptions? insertOptions, + ]) { if (rowIndex < 1 || rowIndex > workbook.maxRowCount) { throw Exception('rowIndex'); } @@ -1405,9 +1483,11 @@ class Worksheet { if (rows[i - 1]!.height != 0) { rows[i]!.height = rows[i - 1]!.height; } - for (int z = 1; - z <= rows[i - 1]!.ranges.innerList.length; - z++) { + for ( + int z = 1; + z <= rows[i - 1]!.ranges.innerList.length; + z++ + ) { if (rows[i - 1]!.ranges[z] != null) { rows[i]!.ranges[z] = Range(this); rows[i]!.ranges[z]!.index = rows[i - 1]!.ranges[z]!.index; @@ -1427,9 +1507,11 @@ class Worksheet { if (rows[i + 1]!.height != 0) { rows[i]!.height = rows[i + 1]!.height; } - for (int z = 1; - z <= rows[i + 1]!.ranges.innerList.length; - z++) { + for ( + int z = 1; + z <= rows[i + 1]!.ranges.innerList.length; + z++ + ) { if (rows[i + 1]!.ranges[z] != null) { rows[i]!.ranges[z] = Range(this); rows[i]!.ranges[z]!.index = rows[i + 1]!.ranges[z]!.index; @@ -1557,11 +1639,15 @@ class Worksheet { /// File('InsertColumn.xlsx').writeAsBytes(bytes); /// workbook.dispose(); /// ``` - void insertColumn(int columnIndex, - [int? columnCount, ExcelInsertOptions? insertOptions]) { + void insertColumn( + int columnIndex, [ + int? columnCount, + ExcelInsertOptions? insertOptions, + ]) { if (columnIndex < 1 || columnIndex > workbook.maxColumnCount) { throw Exception( - 'Value cannot be less 1 and greater than max column index.'); + 'Value cannot be less 1 and greater than max column index.', + ); } columnCount ??= 1; if (columnCount < 0) { @@ -1744,7 +1830,8 @@ class Worksheet { void deleteColumn(int columnIndex, [int? columnCount]) { if (columnIndex < 1 || columnIndex > workbook.maxColumnCount) { throw Exception( - 'Value cannot be less 1 and greater than max column index.'); + 'Value cannot be less 1 and greater than max column index.', + ); } columnCount ??= 1; if (columnCount < 0) { @@ -1832,7 +1919,8 @@ class Worksheet { bool isPasswordProtected = false; ExcelSheetProtectionOption _prepareProtectionOptions( - ExcelSheetProtectionOption options) { + ExcelSheetProtectionOption options, + ) { options.content = false; return options; } @@ -1869,11 +1957,13 @@ class Worksheet { void protect(String password, [ExcelSheetProtectionOption? options]) { if (isPasswordProtected) { throw Exception( - 'Sheet is already protected, before use unprotect method'); + 'Sheet is already protected, before use unprotect method', + ); } if (password.length > _maxPassWordLength) { throw Exception( - "Length of the password can't be more than $_maxPassWordLength"); + "Length of the password can't be more than $_maxPassWordLength", + ); } if (options == null) { options = ExcelSheetProtectionOption(); @@ -1964,9 +2054,11 @@ class Worksheet { } int usHash = 0; // ignore: prefer_final_locals - for (int iCharIndex = 0, len = password.length; - iCharIndex < len; - iCharIndex++) { + for ( + int iCharIndex = 0, len = password.length; + iCharIndex < len; + iCharIndex++ + ) { List bits = _getCharBits15(password[iCharIndex]); bits = _rotateBits(bits, iCharIndex + 1); final int curNumber = _getUInt16FromBits(bits); @@ -2085,7 +2177,8 @@ class Worksheet { if (iColumnIndex < 1 || iColumnIndex > book.maxColumnCount) { throw Exception( - 'Value cannot be less 1 and greater than max column index.'); + 'Value cannot be less 1 and greater than max column index.', + ); } final double widthInChars = _innerGetColumnWidth(iColumnIndex); @@ -2153,7 +2246,8 @@ class Worksheet { void setRowHeightInPixels(int iRowIndex, double rowHeight) { if (iRowIndex < 1 || iRowIndex > book.maxRowCount) { throw Exception( - 'iRowIndex ,Value cannot be less 1 and greater than max row index.'); + 'iRowIndex ,Value cannot be less 1 and greater than max row index.', + ); } if (rowHeight < 0) { @@ -2167,7 +2261,8 @@ class Worksheet { void _setColumnWidth(int iColumn, double value) { if (iColumn < 1 || iColumn > book.maxColumnCount) { throw Exception( - 'Column index cannot be larger then 256 or less then one'); + 'Column index cannot be larger then 256 or less then one', + ); } final double iOldValue = _innerGetColumnWidth(iColumn); if (iOldValue != value) { @@ -2222,7 +2317,11 @@ class Worksheet { /// workbook.dispose(); /// ``` int importList( - List arrObject, int firstRow, int firstColumn, bool isVertical) { + List arrObject, + int firstRow, + int firstColumn, + bool isVertical, + ) { if (firstRow < 1 || firstRow > book.maxRowCount) { throw Exception('firstRow is not proper'); } @@ -2240,8 +2339,8 @@ class Worksheet { } else { elementsToImport = min(firstColumn + arrObject.length - 1, book.maxColumnCount) - - firstColumn + - 1; + firstColumn + + 1; } Range range; @@ -2343,7 +2442,10 @@ class Worksheet { /// } /// ``` void importData( - List excelDataRows, int rowIndex, int colIndex) { + List excelDataRows, + int rowIndex, + int colIndex, + ) { for (int i = 0; i <= excelDataRows.length; i++) { final ExcelDataRow dataRow = i > 0 ? excelDataRows[i - 1] : excelDataRows[i]; @@ -2355,8 +2457,13 @@ class Worksheet { } else if (dataCell.value != null) { if (dataCell.value is Hyperlink) { final Hyperlink link = dataCell.value! as Hyperlink; - hyperlinks.add(range, link.type, link.address, link.screenTip, - link.textToDisplay); + hyperlinks.add( + range, + link.type, + link.address, + link.screenTip, + link.textToDisplay, + ); } else if (dataCell.value is Picture) { final Picture picture = dataCell.value! as Picture; picture.row = range.row; @@ -2365,7 +2472,11 @@ class Worksheet { final Hyperlink? link = picture.hyperlink; if (link != null) { hyperlinks.addImage( - picture, link.type, link.address, link.screenTip); + picture, + link.type, + link.address, + link.screenTip, + ); } final int width = picture.width; final int height = picture.height; @@ -2375,7 +2486,9 @@ class Worksheet { } if (range.rowHeight < height) { range.setRowHeight( - book.convertFromPixel(height.toDouble(), 6), true); + book.convertFromPixel(height.toDouble(), 6), + true, + ); } } else { range.value = dataCell.value; diff --git a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet_collection.dart b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet_collection.dart index 7e2079a06..d60e476eb 100644 --- a/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet_collection.dart +++ b/packages/syncfusion_flutter_xlsio/lib/src/xlsio/worksheet/worksheet_collection.dart @@ -122,7 +122,8 @@ class WorksheetCollection { } if (innerList.length - 1 < destinationIndex) { throw Exception( - 'destinationIndex should be in the range of worksheet count'); + 'destinationIndex should be in the range of worksheet count', + ); } if (destinationIndex < 0) { throw Exception('destinationIndex should be starts from 0'); diff --git a/packages/syncfusion_flutter_xlsio/lib/xlsio.dart b/packages/syncfusion_flutter_xlsio/lib/xlsio.dart index a248b0cb4..090b13e78 100644 --- a/packages/syncfusion_flutter_xlsio/lib/xlsio.dart +++ b/packages/syncfusion_flutter_xlsio/lib/xlsio.dart @@ -61,8 +61,7 @@ export 'src/xlsio/conditional_format/condition_value.dart' export 'src/xlsio/conditional_format/conditionalformat.dart' show ConditionalFormat; export 'src/xlsio/conditional_format/conditionalformat_collections.dart' - show ConditionalFormats - hide ConditionalFormatsImpl; + show ConditionalFormats; export 'src/xlsio/conditional_format/conditionalformat_impl.dart' hide ConditionalFormatImpl; export 'src/xlsio/conditional_format/data_bar/data_bar.dart' show DataBar; diff --git a/packages/syncfusion_flutter_xlsio/pubspec.yaml b/packages/syncfusion_flutter_xlsio/pubspec.yaml index 881286005..6a388e975 100644 --- a/packages/syncfusion_flutter_xlsio/pubspec.yaml +++ b/packages/syncfusion_flutter_xlsio/pubspec.yaml @@ -1,16 +1,16 @@ name: syncfusion_flutter_xlsio description: Flutter XlsIO is a Dart library for creating Excel documents with formulas, charts, images, hyperlinks, autofit rows and columns, and more. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_flutter_xlsio environment: - sdk: ">=3.4.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter xml: ">=5.1.0 <7.0.0" - archive: ">=3.6.1 <4.0.0" + archive: ">=4.0.0 <5.0.0" image: ">=3.0.1 <5.0.0" intl: '>=0.18.1 <0.21.0' crypto: ">=3.0.0 <4.0.0" diff --git a/packages/syncfusion_localizations/CHANGELOG.md b/packages/syncfusion_localizations/CHANGELOG.md index b781d5a4b..8fa1ceb97 100644 --- a/packages/syncfusion_localizations/CHANGELOG.md +++ b/packages/syncfusion_localizations/CHANGELOG.md @@ -2,6 +2,18 @@ **General** +* The compatible version of our Flutter localizations widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 + +**General** + * The compatible version of our Flutter localizations widget has been updated to Flutter SDK 3.29.0. * The Syncfusion® Flutter localizations example sample have been updated to support [kotlin build scripts](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply) in Android platform. * The Syncfusion® Flutter localizations example sample have been updated to support [Swift package manager](https://docs.flutter.dev/packages-and-plugins/swift-package-manager/for-app-developers) in macOS and iOS platforms. diff --git a/packages/syncfusion_localizations/example/lib/main.dart b/packages/syncfusion_localizations/example/lib/main.dart index 1b8009362..f0867e63f 100644 --- a/packages/syncfusion_localizations/example/lib/main.dart +++ b/packages/syncfusion_localizations/example/lib/main.dart @@ -17,7 +17,7 @@ class CalendarApp extends StatelessWidget { localizationsDelegates: [ GlobalMaterialLocalizations.delegate, // ... app-specific localization delegate[s] here - SfGlobalLocalizations.delegate + SfGlobalLocalizations.delegate, ], //ignore: always_specify_types supportedLocales: const [ @@ -43,23 +43,38 @@ class _MyHomePageState extends State<_MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( - body: SfCalendar( - view: CalendarView.month, - dataSource: _MeetingDataSource(_getDataSource()), - monthViewSettings: MonthViewSettings( + body: SfCalendar( + view: CalendarView.month, + dataSource: _MeetingDataSource(_getDataSource()), + monthViewSettings: MonthViewSettings( appointmentDisplayMode: MonthAppointmentDisplayMode.appointment, - showAgenda: true), - )); + showAgenda: true, + ), + ), + ); } List<_Meeting> _getDataSource() { final List<_Meeting> meetings = <_Meeting>[]; final DateTime today = DateTime.now(); - final DateTime startTime = - DateTime(today.year, today.month, today.day, 9, 0, 0); + final DateTime startTime = DateTime( + today.year, + today.month, + today.day, + 9, + 0, + 0, + ); final DateTime endTime = startTime.add(const Duration(hours: 2)); - meetings.add(_Meeting( - 'Conference', startTime, endTime, const Color(0xFF0F8644), false)); + meetings.add( + _Meeting( + 'Conference', + startTime, + endTime, + const Color(0xFF0F8644), + false, + ), + ); return meetings; } } diff --git a/packages/syncfusion_localizations/example/pubspec.yaml b/packages/syncfusion_localizations/example/pubspec.yaml index 0da8c2bd3..7bea5f83e 100644 --- a/packages/syncfusion_localizations/example/pubspec.yaml +++ b/packages/syncfusion_localizations/example/pubspec.yaml @@ -3,15 +3,15 @@ description: This project holds information about the usage of the syncfusion_lo version: 1.0.0 environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter - syncfusion_localizations: ^27.1.53 - syncfusion_flutter_calendar: ^27.1.53 + syncfusion_localizations: ^29.2.7 + syncfusion_flutter_calendar: ^29.2.7 cupertino_icons: '^1.0.8' flutter: diff --git a/packages/syncfusion_localizations/lib/src/global_localizations.dart b/packages/syncfusion_localizations/lib/src/global_localizations.dart index 594b5794a..3be05276c 100644 --- a/packages/syncfusion_localizations/lib/src/global_localizations.dart +++ b/packages/syncfusion_localizations/lib/src/global_localizations.dart @@ -39,8 +39,8 @@ abstract class SfGlobalLocalizations implements SfLocalizations { const SfGlobalLocalizations({ required String localeName, // ignore: unnecessary_null_comparison - }) : assert(localeName != null), - _localeName = localeName; + }) : assert(localeName != null), + _localeName = localeName; // ignore: unused_field final String _localeName; //ignore: public_member_api_docs @@ -63,9 +63,7 @@ abstract class SfGlobalLocalizations implements SfLocalizations { /// ``` /// static const List> delegates = - >[ - SfGlobalLocalizations.delegate, - ]; + >[SfGlobalLocalizations.delegate]; } class _SfLocalizationsDelegate extends LocalizationsDelegate { @@ -82,17 +80,18 @@ class _SfLocalizationsDelegate extends LocalizationsDelegate { Future load(Locale locale) { assert(isSupported(locale)); return _loadedTranslations.putIfAbsent(locale, () { - final String localeName = - intl.Intl.canonicalizedLocale(locale.toString()); + final String localeName = intl.Intl.canonicalizedLocale( + locale.toString(), + ); assert( locale.toString() == localeName, 'Flutter does not support the non-standard locale form $locale (which ' 'might be $localeName', ); - return SynchronousFuture(getSyncfusionTranslation( - locale, - )!); + return SynchronousFuture( + getSyncfusionTranslation(locale)!, + ); }); } @@ -100,6 +99,7 @@ class _SfLocalizationsDelegate extends LocalizationsDelegate { bool shouldReload(_SfLocalizationsDelegate old) => false; @override - String toString() => 'SfGlobalLocalizations.delegate(' + String toString() => + 'SfGlobalLocalizations.delegate(' '${kSyncfusionSupportedLanguages.length} locales)'; } diff --git a/packages/syncfusion_localizations/lib/src/l10n/generated_syncfusion_localizations.dart b/packages/syncfusion_localizations/lib/src/l10n/generated_syncfusion_localizations.dart index 6adde4a48..919f810fe 100644 --- a/packages/syncfusion_localizations/lib/src/l10n/generated_syncfusion_localizations.dart +++ b/packages/syncfusion_localizations/lib/src/l10n/generated_syncfusion_localizations.dart @@ -16,11 +16,8 @@ import '../global_localizations.dart'; /// The translations for Afrikaans (`af`). class SfLocalizationsAf extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsAf class - const SfLocalizationsAf({ - String localeName = 'af', - }) : super( - localeName: localeName, - ); + const SfLocalizationsAf({String localeName = 'af'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Na'; @@ -89,7 +86,10 @@ class SfLocalizationsAf extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Begin nie met'; @@ -205,7 +205,9 @@ class SfLocalizationsAf extends SfGlobalLocalizations { @override String get pdfInvalidPageNumberLabel => - r'Voer asseblief ' "'" r'n geldige nommer in'; + r'Voer asseblief ' + "'" + r'n geldige nommer in'; @override String get pdfNoBookmarksLabel => r'Geen boekmerke gevind nie'; @@ -253,10 +255,16 @@ class SfLocalizationsAf extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Onderstreep'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -280,16 +288,25 @@ class SfLocalizationsAf extends SfGlobalLocalizations { String get series => r'Reeks'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. ek'; @@ -362,11 +379,8 @@ class SfLocalizationsAf extends SfGlobalLocalizations { /// The translations for Amharic (`am`). class SfLocalizationsAm extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsAm class - const SfLocalizationsAm({ - String localeName = 'am', - }) : super( - localeName: localeName, - ); + const SfLocalizationsAm({String localeName = 'am'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'በኋላ'; @@ -702,11 +716,8 @@ class SfLocalizationsAm extends SfGlobalLocalizations { /// The translations for Arabic (`ar`). class SfLocalizationsAr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsAr class - const SfLocalizationsAr({ - String localeName = 'ar', - }) : super( - localeName: localeName, - ); + const SfLocalizationsAr({String localeName = 'ar'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'بعد، بعدما'; @@ -1047,11 +1058,8 @@ class SfLocalizationsAr extends SfGlobalLocalizations { /// The translations for Azerbaijani (`az`). class SfLocalizationsAz extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsAz class - const SfLocalizationsAz({ - String localeName = 'az', - }) : super( - localeName: localeName, - ); + const SfLocalizationsAz({String localeName = 'az'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'sonra'; @@ -1394,11 +1402,8 @@ class SfLocalizationsAz extends SfGlobalLocalizations { /// The translations for Belarusian (`be`). class SfLocalizationsBe extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsBe class - const SfLocalizationsBe({ - String localeName = 'be', - }) : super( - localeName: localeName, - ); + const SfLocalizationsBe({String localeName = 'be'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Пасля'; @@ -1665,10 +1670,18 @@ class SfLocalizationsBe extends SfGlobalLocalizations { String get shawwalLabel => r'Шаўваль'; @override - String get shortDhualhiLabel => r'Зу' "'" r'л-Х'; + String get shortDhualhiLabel => + r'Зу' + "'" + r'л-Х'; @override - String get shortDhualqiLabel => r'Зу' "'" r'л-К' "'" r'ю'; + String get shortDhualqiLabel => + r'Зу' + "'" + r'л-К' + "'" + r'ю'; @override String get shortJumada1Label => r'Джам. я'; @@ -1741,11 +1754,8 @@ class SfLocalizationsBe extends SfGlobalLocalizations { /// The translations for Bulgarian (`bg`). class SfLocalizationsBg extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsBg class - const SfLocalizationsBg({ - String localeName = 'bg', - }) : super( - localeName: localeName, - ); + const SfLocalizationsBg({String localeName = 'bg'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'След'; @@ -2088,11 +2098,8 @@ class SfLocalizationsBg extends SfGlobalLocalizations { /// The translations for Bengali Bangla (`bn`). class SfLocalizationsBn extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsBn class - const SfLocalizationsBn({ - String localeName = 'bn', - }) : super( - localeName: localeName, - ); + const SfLocalizationsBn({String localeName = 'bn'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'পরে'; @@ -2327,7 +2334,10 @@ class SfLocalizationsBn extends SfGlobalLocalizations { String get rabi1Label => r'রবিউল আউয়াল'; @override - String get rabi2Label => r'রাবি' "'" r'আল-থানি'; + String get rabi2Label => + r'রাবি' + "'" + r'আল-থানি'; @override String get rajabLabel => r'রজব'; @@ -2351,7 +2361,10 @@ class SfLocalizationsBn extends SfGlobalLocalizations { String get series => r'সিরিজ'; @override - String get shaabanLabel => r'শা' "'" r'বান'; + String get shaabanLabel => + r'শা' + "'" + r'বান'; @override String get shawwalLabel => r'শাওয়াল'; @@ -2433,11 +2446,8 @@ class SfLocalizationsBn extends SfGlobalLocalizations { /// The translations for Bosnian (`bs`). class SfLocalizationsBs extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsBs class - const SfLocalizationsBs({ - String localeName = 'bs', - }) : super( - localeName: localeName, - ); + const SfLocalizationsBs({String localeName = 'bs'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Poslije'; @@ -2507,7 +2517,10 @@ class SfLocalizationsBs extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ne počinje sa'; @@ -2671,10 +2684,16 @@ class SfLocalizationsBs extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Podvući'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -2698,16 +2717,25 @@ class SfLocalizationsBs extends SfGlobalLocalizations { String get series => r'Serije'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. I'; @@ -2780,11 +2808,8 @@ class SfLocalizationsBs extends SfGlobalLocalizations { /// The translations for Catalan Valencian (`ca`). class SfLocalizationsCa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsCa class - const SfLocalizationsCa({ - String localeName = 'ca', - }) : super( - localeName: localeName, - ); + const SfLocalizationsCa({String localeName = 'ca'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Després'; @@ -2854,7 +2879,10 @@ class SfLocalizationsCa extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'No comença amb'; @@ -2926,7 +2954,10 @@ class SfLocalizationsCa extends SfGlobalLocalizations { String get ofDataPagerLabel => r'de'; @override - String get okDataGridFilteringLabel => r'D' "'" r'acord'; + String get okDataGridFilteringLabel => + r'D' + "'" + r'acord'; @override String get orDataGridFilteringLabel => r'O'; @@ -2948,7 +2979,10 @@ class SfLocalizationsCa extends SfGlobalLocalizations { String get passwordDialogInvalidPasswordLabel => r'contrasenya invàlida'; @override - String get pdfBookmarksLabel => r'Adreces d' "'" r'interès'; + String get pdfBookmarksLabel => + r'Adreces d' + "'" + r'interès'; @override String get pdfEnterPageNumberLabel => r'Introduïu el número de pàgina'; @@ -2973,13 +3007,20 @@ class SfLocalizationsCa extends SfGlobalLocalizations { @override String get pdfNoBookmarksLabel => - r'No s' "'" r'han trobat adreces d' "'" r'interès'; + r'No s' + "'" + r'han trobat adreces d' + "'" + r'interès'; @override String get pdfPaginationDialogCancelLabel => r'Cancel·lar'; @override - String get pdfPaginationDialogOkLabel => r'D' "'" r'acord'; + String get pdfPaginationDialogOkLabel => + r'D' + "'" + r'acord'; @override String get pdfPasswordDialogCancelLabel => r'Cancel·lar'; @@ -3019,10 +3060,16 @@ class SfLocalizationsCa extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Subratllar'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -3046,16 +3093,25 @@ class SfLocalizationsCa extends SfGlobalLocalizations { String get series => r'Sèrie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. jo'; @@ -3128,11 +3184,8 @@ class SfLocalizationsCa extends SfGlobalLocalizations { /// The translations for Czech (`cs`). class SfLocalizationsCs extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsCs class - const SfLocalizationsCs({ - String localeName = 'cs', - }) : super( - localeName: localeName, - ); + const SfLocalizationsCs({String localeName = 'cs'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Po'; @@ -3201,7 +3254,10 @@ class SfLocalizationsCs extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Nezačíná s'; @@ -3365,10 +3421,16 @@ class SfLocalizationsCs extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Zdůraznit'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -3392,16 +3454,25 @@ class SfLocalizationsCs extends SfGlobalLocalizations { String get series => r'Série'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. já'; @@ -3474,11 +3545,8 @@ class SfLocalizationsCs extends SfGlobalLocalizations { /// The translations for Danish (`da`). class SfLocalizationsDa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsDa class - const SfLocalizationsDa({ - String localeName = 'da', - }) : super( - localeName: localeName, - ); + const SfLocalizationsDa({String localeName = 'da'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Efter'; @@ -3547,7 +3615,10 @@ class SfLocalizationsDa extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Begynder ikke med'; @@ -3711,10 +3782,16 @@ class SfLocalizationsDa extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Understrege'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -3738,16 +3815,25 @@ class SfLocalizationsDa extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. jeg'; @@ -3820,11 +3906,8 @@ class SfLocalizationsDa extends SfGlobalLocalizations { /// The translations for German (`de`). class SfLocalizationsDe extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsDe class - const SfLocalizationsDe({ - String localeName = 'de', - }) : super( - localeName: localeName, - ); + const SfLocalizationsDe({String localeName = 'de'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Nach'; @@ -4060,10 +4143,16 @@ class SfLocalizationsDe extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Unterstreichen'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -4093,10 +4182,16 @@ class SfLocalizationsDe extends SfGlobalLocalizations { String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. ich'; @@ -4169,11 +4264,8 @@ class SfLocalizationsDe extends SfGlobalLocalizations { /// The translations for Modern Greek (`el`). class SfLocalizationsEl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsEl class - const SfLocalizationsEl({ - String localeName = 'el', - }) : super( - localeName: localeName, - ); + const SfLocalizationsEl({String localeName = 'el'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Μετά'; @@ -4243,7 +4335,10 @@ class SfLocalizationsEl extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Δεν ξεκινά με'; @@ -4410,10 +4505,16 @@ class SfLocalizationsEl extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Υπογράμμιση'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Ραμπί' "'" r' αλ-θάνι'; + String get rabi2Label => + r'Ραμπί' + "'" + r' αλ-θάνι'; @override String get rajabLabel => r'Ρατζάμπ'; @@ -4437,16 +4538,25 @@ class SfLocalizationsEl extends SfGlobalLocalizations { String get series => r'Σειρά'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. Εγώ'; @@ -4520,11 +4630,8 @@ class SfLocalizationsEl extends SfGlobalLocalizations { /// The translations for English (`en`). class SfLocalizationsEn extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsEn class - const SfLocalizationsEn({ - String localeName = 'en', - }) : super( - localeName: localeName, - ); + const SfLocalizationsEn({String localeName = 'en'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'After'; @@ -4593,7 +4700,10 @@ class SfLocalizationsEn extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Does Not Begin With'; @@ -4757,10 +4867,16 @@ class SfLocalizationsEn extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Underline'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -4784,16 +4900,25 @@ class SfLocalizationsEn extends SfGlobalLocalizations { String get series => r'Series'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. I'; @@ -4866,11 +4991,8 @@ class SfLocalizationsEn extends SfGlobalLocalizations { /// The translations for Spanish Castilian (`es`). class SfLocalizationsEs extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsEs class - const SfLocalizationsEs({ - String localeName = 'es', - }) : super( - localeName: localeName, - ); + const SfLocalizationsEs({String localeName = 'es'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Después'; @@ -4940,7 +5062,10 @@ class SfLocalizationsEs extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hiyyah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'no comienza con'; @@ -5131,16 +5256,25 @@ class SfLocalizationsEs extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. yo'; @@ -5213,11 +5347,8 @@ class SfLocalizationsEs extends SfGlobalLocalizations { /// The translations for Estonian (`et`). class SfLocalizationsEt extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsEt class - const SfLocalizationsEt({ - String localeName = 'et', - }) : super( - localeName: localeName, - ); + const SfLocalizationsEt({String localeName = 'et'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Pärast'; @@ -5286,7 +5417,10 @@ class SfLocalizationsEt extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ei alga'; @@ -5450,10 +5584,16 @@ class SfLocalizationsEt extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Allajoonimine'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -5477,16 +5617,25 @@ class SfLocalizationsEt extends SfGlobalLocalizations { String get series => r'seeria'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. I'; @@ -5559,11 +5708,8 @@ class SfLocalizationsEt extends SfGlobalLocalizations { /// The translations for Basque (`eu`). class SfLocalizationsEu extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsEu class - const SfLocalizationsEu({ - String localeName = 'eu', - }) : super( - localeName: localeName, - ); + const SfLocalizationsEu({String localeName = 'eu'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Ondoren'; @@ -5632,7 +5778,10 @@ class SfLocalizationsEu extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ez Da Hasten'; @@ -5797,10 +5946,16 @@ class SfLocalizationsEu extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Azpimarratu'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -5824,16 +5979,25 @@ class SfLocalizationsEu extends SfGlobalLocalizations { String get series => r'Seriea'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Salto. I'; @@ -5906,11 +6070,8 @@ class SfLocalizationsEu extends SfGlobalLocalizations { /// The translations for Persian (`fa`). class SfLocalizationsFa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsFa class - const SfLocalizationsFa({ - String localeName = 'fa', - }) : super( - localeName: localeName, - ); + const SfLocalizationsFa({String localeName = 'fa'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'بعد از'; @@ -6251,11 +6412,8 @@ class SfLocalizationsFa extends SfGlobalLocalizations { /// The translations for Finnish (`fi`). class SfLocalizationsFi extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsFi class - const SfLocalizationsFi({ - String localeName = 'fi', - }) : super( - localeName: localeName, - ); + const SfLocalizationsFi({String localeName = 'fi'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Jälkeen'; @@ -6324,7 +6482,10 @@ class SfLocalizationsFi extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ei ala'; @@ -6490,10 +6651,16 @@ class SfLocalizationsFi extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Alleviivaus'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -6517,16 +6684,25 @@ class SfLocalizationsFi extends SfGlobalLocalizations { String get series => r'Sarja'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. minä'; @@ -6599,11 +6775,8 @@ class SfLocalizationsFi extends SfGlobalLocalizations { /// The translations for Filipino Pilipino (`fil`). class SfLocalizationsFil extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsFil class - const SfLocalizationsFil({ - String localeName = 'fil', - }) : super( - localeName: localeName, - ); + const SfLocalizationsFil({String localeName = 'fil'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Pagkatapos'; @@ -6673,7 +6846,10 @@ class SfLocalizationsFil extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Hindi Nagsisimula Sa'; @@ -6838,10 +7014,16 @@ class SfLocalizationsFil extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Salungguhit'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -6865,16 +7047,25 @@ class SfLocalizationsFil extends SfGlobalLocalizations { String get series => r'Serye'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. ako'; @@ -6950,11 +7141,8 @@ class SfLocalizationsFil extends SfGlobalLocalizations { /// The translations for French (`fr`). class SfLocalizationsFr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsFr class - const SfLocalizationsFr({ - String localeName = 'fr', - }) : super( - localeName: localeName, - ); + const SfLocalizationsFr({String localeName = 'fr'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Après'; @@ -7024,7 +7212,10 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhou al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhou al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ne commence pas par'; @@ -7036,7 +7227,10 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get doesNotEndWithDataGridFilteringLabel => r'Ne se termine pas par'; @override - String get doesNotEqualDataGridFilteringLabel => r'N' "'" r'est pas égal'; + String get doesNotEqualDataGridFilteringLabel => + r'N' + "'" + r'est pas égal'; @override String get emptyDataGridFilteringLabel => r'Vide'; @@ -7073,7 +7267,10 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get muharramLabel => r'Mouharram'; @override - String get noEventsCalendarLabel => r'Pas d' "'" r'événements'; + String get noEventsCalendarLabel => + r'Pas d' + "'" + r'événements'; @override String get noMatchesDataGridFilteringLabel => r'Pas de correspondance'; @@ -7097,7 +7294,10 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get ofDataPagerLabel => r'de'; @override - String get okDataGridFilteringLabel => r'D' "'" r'ACCORD'; + String get okDataGridFilteringLabel => + r'D' + "'" + r'ACCORD'; @override String get orDataGridFilteringLabel => r'Ou'; @@ -7141,7 +7341,9 @@ class SfLocalizationsFr extends SfGlobalLocalizations { @override String get pdfInvalidPageNumberLabel => - r'S' "'" r'il vous plait, entrez un nombre valide'; + r'S' + "'" + r'il vous plait, entrez un nombre valide'; @override String get pdfNoBookmarksLabel => r'Aucun signet trouvé'; @@ -7190,10 +7392,16 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Souligner'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -7217,16 +7425,25 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get series => r'Série'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. je'; @@ -7290,7 +7507,10 @@ class SfLocalizationsFr extends SfGlobalLocalizations { String get textFiltersDataGridFilteringLabel => r'Filtres de texte'; @override - String get todayLabel => r'Aujourd' "'" r'hui'; + String get todayLabel => + r'Aujourd' + "'" + r'hui'; @override String get weeknumberLabel => r'Semaine'; @@ -7299,11 +7519,8 @@ class SfLocalizationsFr extends SfGlobalLocalizations { /// The translations for Galician (`gl`). class SfLocalizationsGl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsGl class - const SfLocalizationsGl({ - String localeName = 'gl', - }) : super( - localeName: localeName, - ); + const SfLocalizationsGl({String localeName = 'gl'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Despois'; @@ -7373,7 +7590,10 @@ class SfLocalizationsGl extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Non Comeza Con'; @@ -7536,10 +7756,16 @@ class SfLocalizationsGl extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Subliñado'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -7563,16 +7789,25 @@ class SfLocalizationsGl extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. eu'; @@ -7645,11 +7880,8 @@ class SfLocalizationsGl extends SfGlobalLocalizations { /// The translations for Gujarati (`gu`). class SfLocalizationsGu extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsGu class - const SfLocalizationsGu({ - String localeName = 'gu', - }) : super( - localeName: localeName, - ); + const SfLocalizationsGu({String localeName = 'gu'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'પછી'; @@ -7991,11 +8223,8 @@ class SfLocalizationsGu extends SfGlobalLocalizations { /// The translations for Hebrew (`he`). class SfLocalizationsHe extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsHe class - const SfLocalizationsHe({ - String localeName = 'he', - }) : super( - localeName: localeName, - ); + const SfLocalizationsHe({String localeName = 'he'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'לאחר'; @@ -8061,7 +8290,10 @@ class SfLocalizationsHe extends SfGlobalLocalizations { String get daySpanCountLabel => r'יְוֹם'; @override - String get dhualhiLabel => r'דהו אל-היג' "'" r'ה'; + String get dhualhiLabel => + r'דהו אל-היג' + "'" + r'ה'; @override String get dhualqiLabel => r'דהו אל-קיאדה'; @@ -8097,10 +8329,18 @@ class SfLocalizationsHe extends SfGlobalLocalizations { String get greaterThanOrEqualDataGridFilteringLabel => r'גדול או שווה'; @override - String get jumada1Label => r'ג' "'" r'ומדה אל-אוול'; + String get jumada1Label => + r'ג' + "'" + r'ומדה אל-אוול'; @override - String get jumada2Label => r'ג' "'" r'ומדה אל-ת' "'" r'אני'; + String get jumada2Label => + r'ג' + "'" + r'ומדה אל-ת' + "'" + r'אני'; @override String get lessThanDataGridFilteringLabel => r'פחות מ'; @@ -8233,7 +8473,10 @@ class SfLocalizationsHe extends SfGlobalLocalizations { String get rabi2Label => r'רבי אל-תאני'; @override - String get rajabLabel => r'רג' "'" r'אב'; + String get rajabLabel => + r'רג' + "'" + r'אב'; @override String get ramadanLabel => r'רמדאן'; @@ -8260,16 +8503,29 @@ class SfLocalizationsHe extends SfGlobalLocalizations { String get shawwalLabel => r'שווואל'; @override - String get shortDhualhiLabel => r'דהו' "'" "'" r'ל-ה'; + String get shortDhualhiLabel => + r'דהו' + "'" + "'" + r'ל-ה'; @override - String get shortDhualqiLabel => r'דהו' "'" r'ל-ק'; + String get shortDhualqiLabel => + r'דהו' + "'" + r'ל-ק'; @override - String get shortJumada1Label => r'ג' "'" r'אם. אני'; + String get shortJumada1Label => + r'ג' + "'" + r'אם. אני'; @override - String get shortJumada2Label => r'ג' "'" r'אם. II'; + String get shortJumada2Label => + r'ג' + "'" + r'אם. II'; @override String get shortMuharramLabel => r'מוה.'; @@ -8281,7 +8537,10 @@ class SfLocalizationsHe extends SfGlobalLocalizations { String get shortRabi2Label => r'רבי. II'; @override - String get shortRajabLabel => r'ראג' "'" r'.'; + String get shortRajabLabel => + r'ראג' + "'" + r'.'; @override String get shortRamadanLabel => r'RAM.'; @@ -8299,7 +8558,11 @@ class SfLocalizationsHe extends SfGlobalLocalizations { String get showRowsWhereDataGridFilteringLabel => r'הצג שורות היכן'; @override - String get sortAToZDataGridFilteringLabel => r'מיין מא' "'" r' עד ת' "'"; + String get sortAToZDataGridFilteringLabel => + r'מיין מא' + "'" + r' עד ת' + "'"; @override String get sortAndFilterDataGridFilteringLabel => r'מיון ומסנן'; @@ -8336,11 +8599,8 @@ class SfLocalizationsHe extends SfGlobalLocalizations { /// The translations for Hindi (`hi`). class SfLocalizationsHi extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsHi class - const SfLocalizationsHi({ - String localeName = 'hi', - }) : super( - localeName: localeName, - ); + const SfLocalizationsHi({String localeName = 'hi'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'बाद में'; @@ -8576,7 +8836,10 @@ class SfLocalizationsHi extends SfGlobalLocalizations { String get rabi1Label => r'रबी अल-अव्वल'; @override - String get rabi2Label => r'रबी ' "'" r'अल-थानी'; + String get rabi2Label => + r'रबी ' + "'" + r'अल-थानी'; @override String get rajabLabel => r'रज्जब'; @@ -8683,11 +8946,8 @@ class SfLocalizationsHi extends SfGlobalLocalizations { /// The translations for Croatian (`hr`). class SfLocalizationsHr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsHr class - const SfLocalizationsHr({ - String localeName = 'hr', - }) : super( - localeName: localeName, - ); + const SfLocalizationsHr({String localeName = 'hr'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Nakon'; @@ -8757,7 +9017,10 @@ class SfLocalizationsHr extends SfGlobalLocalizations { String get dhualhiLabel => r'zul-hidždže'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ne počinje s'; @@ -8920,10 +9183,16 @@ class SfLocalizationsHr extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Podvući'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Radžeb'; @@ -8947,7 +9216,10 @@ class SfLocalizationsHr extends SfGlobalLocalizations { String get series => r'Niz'; @override - String get shaabanLabel => r'ša' "'" r'aban'; + String get shaabanLabel => + r'ša' + "'" + r'aban'; @override String get shawwalLabel => r'ševval'; @@ -9029,11 +9301,8 @@ class SfLocalizationsHr extends SfGlobalLocalizations { /// The translations for Hungarian (`hu`). class SfLocalizationsHu extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsHu class - const SfLocalizationsHu({ - String localeName = 'hu', - }) : super( - localeName: localeName, - ); + const SfLocalizationsHu({String localeName = 'hu'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Után'; @@ -9102,7 +9371,10 @@ class SfLocalizationsHu extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Nem azzal kezdődik'; @@ -9269,10 +9541,16 @@ class SfLocalizationsHu extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Aláhúzás'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -9296,16 +9574,25 @@ class SfLocalizationsHu extends SfGlobalLocalizations { String get series => r'Sorozat'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. én'; @@ -9378,11 +9665,8 @@ class SfLocalizationsHu extends SfGlobalLocalizations { /// The translations for Armenian (`hy`). class SfLocalizationsHy extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsHy class - const SfLocalizationsHy({ - String localeName = 'hy', - }) : super( - localeName: localeName, - ); + const SfLocalizationsHy({String localeName = 'hy'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'հետո'; @@ -9726,11 +10010,8 @@ class SfLocalizationsHy extends SfGlobalLocalizations { /// The translations for Indonesian (`id`). class SfLocalizationsId extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsId class - const SfLocalizationsId({ - String localeName = 'id', - }) : super( - localeName: localeName, - ); + const SfLocalizationsId({String localeName = 'id'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Setelah'; @@ -9965,10 +10246,16 @@ class SfLocalizationsId extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Menggarisbawahi'; @override - String get rabi1Label => r'Rabi' "'" r' al-awal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -9992,7 +10279,10 @@ class SfLocalizationsId extends SfGlobalLocalizations { String get series => r'Seri'; @override - String get shaabanLabel => r'Sya' "'" r'ban'; + String get shaabanLabel => + r'Sya' + "'" + r'ban'; @override String get shawwalLabel => r'Syawal'; @@ -10074,11 +10364,8 @@ class SfLocalizationsId extends SfGlobalLocalizations { /// The translations for Icelandic (`is`). class SfLocalizationsIs extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsIs class - const SfLocalizationsIs({ - String localeName = 'is', - }) : super( - localeName: localeName, - ); + const SfLocalizationsIs({String localeName = 'is'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Eftir'; @@ -10147,7 +10434,10 @@ class SfLocalizationsIs extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Byrjar ekki á'; @@ -10311,10 +10601,16 @@ class SfLocalizationsIs extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Undirstrika'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -10338,16 +10634,25 @@ class SfLocalizationsIs extends SfGlobalLocalizations { String get series => r'Röð'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. ég'; @@ -10420,11 +10725,8 @@ class SfLocalizationsIs extends SfGlobalLocalizations { /// The translations for Italian (`it`). class SfLocalizationsIt extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsIt class - const SfLocalizationsIt({ - String localeName = 'it', - }) : super( - localeName: localeName, - ); + const SfLocalizationsIt({String localeName = 'it'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Dopo'; @@ -10658,10 +10960,16 @@ class SfLocalizationsIt extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Sottolineare'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -10685,16 +10993,25 @@ class SfLocalizationsIt extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. io'; @@ -10767,11 +11084,8 @@ class SfLocalizationsIt extends SfGlobalLocalizations { /// The translations for Japanese (`ja`). class SfLocalizationsJa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsJa class - const SfLocalizationsJa({ - String localeName = 'ja', - }) : super( - localeName: localeName, - ); + const SfLocalizationsJa({String localeName = 'ja'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'後'; @@ -11108,11 +11422,8 @@ class SfLocalizationsJa extends SfGlobalLocalizations { /// The translations for Georgian (`ka`). class SfLocalizationsKa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsKa class - const SfLocalizationsKa({ - String localeName = 'ka', - }) : super( - localeName: localeName, - ); + const SfLocalizationsKa({String localeName = 'ka'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'შემდეგ'; @@ -11453,11 +11764,8 @@ class SfLocalizationsKa extends SfGlobalLocalizations { /// The translations for Kazakh (`kk`). class SfLocalizationsKk extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsKk class - const SfLocalizationsKk({ - String localeName = 'kk', - }) : super( - localeName: localeName, - ); + const SfLocalizationsKk({String localeName = 'kk'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Кейін'; @@ -11689,10 +11997,16 @@ class SfLocalizationsKk extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Астын сызу'; @override - String get rabi1Label => r'Раби' "'" r' әл-әууәл'; + String get rabi1Label => + r'Раби' + "'" + r' әл-әууәл'; @override - String get rabi2Label => r'Раби' "'" r' әл-Тани'; + String get rabi2Label => + r'Раби' + "'" + r' әл-Тани'; @override String get rajabLabel => r'Ражаб'; @@ -11799,11 +12113,8 @@ class SfLocalizationsKk extends SfGlobalLocalizations { /// The translations for Khmer Central Khmer (`km`). class SfLocalizationsKm extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsKm class - const SfLocalizationsKm({ - String localeName = 'km', - }) : super( - localeName: localeName, - ); + const SfLocalizationsKm({String localeName = 'km'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'បន្ទាប់ពី'; @@ -11872,7 +12183,10 @@ class SfLocalizationsKm extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'មិនចាប់ផ្តើមជាមួយ'; @@ -12069,10 +12383,16 @@ class SfLocalizationsKm extends SfGlobalLocalizations { String get shawwalLabel => r'សាវ៉ាវ'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'ជុម ខ្ញុំ'; @@ -12145,11 +12465,8 @@ class SfLocalizationsKm extends SfGlobalLocalizations { /// The translations for Kannada (`kn`). class SfLocalizationsKn extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsKn class - const SfLocalizationsKn({ - String localeName = 'kn', - }) : super( - localeName: localeName, - ); + const SfLocalizationsKn({String localeName = 'kn'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => '\u{ca8}\u{c82}\u{ca4}\u{cb0}'; @@ -12565,11 +12882,8 @@ class SfLocalizationsKn extends SfGlobalLocalizations { /// The translations for Korean (`ko`). class SfLocalizationsKo extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsKo class - const SfLocalizationsKo({ - String localeName = 'ko', - }) : super( - localeName: localeName, - ); + const SfLocalizationsKo({String localeName = 'ko'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'후에'; @@ -12905,11 +13219,8 @@ class SfLocalizationsKo extends SfGlobalLocalizations { /// The translations for Kirghiz Kyrgyz (`ky`). class SfLocalizationsKy extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsKy class - const SfLocalizationsKy({ - String localeName = 'ky', - }) : super( - localeName: localeName, - ); + const SfLocalizationsKy({String localeName = 'ky'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Кийин'; @@ -13251,11 +13562,8 @@ class SfLocalizationsKy extends SfGlobalLocalizations { /// The translations for Lao (`lo`). class SfLocalizationsLo extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsLo class - const SfLocalizationsLo({ - String localeName = 'lo', - }) : super( - localeName: localeName, - ); + const SfLocalizationsLo({String localeName = 'lo'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'ຫຼັງຈາກ'; @@ -13325,7 +13633,10 @@ class SfLocalizationsLo extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'ບໍ່ໄດ້ເລີ່ມຕົ້ນດ້ວຍ'; @@ -13488,10 +13799,16 @@ class SfLocalizationsLo extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'ຂີດເສັ້ນລຸ່ມ'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -13521,10 +13838,16 @@ class SfLocalizationsLo extends SfGlobalLocalizations { String get shawwalLabel => r'ຊະວາວ'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'ຈູມ. I'; @@ -13597,11 +13920,8 @@ class SfLocalizationsLo extends SfGlobalLocalizations { /// The translations for Lithuanian (`lt`). class SfLocalizationsLt extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsLt class - const SfLocalizationsLt({ - String localeName = 'lt', - }) : super( - localeName: localeName, - ); + const SfLocalizationsLt({String localeName = 'lt'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Po to'; @@ -13670,7 +13990,10 @@ class SfLocalizationsLt extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Neprasideda su'; @@ -13833,7 +14156,10 @@ class SfLocalizationsLt extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Pabraukite'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override String get rabi2Label => r'Rabis al-Thanis'; @@ -13866,10 +14192,16 @@ class SfLocalizationsLt extends SfGlobalLocalizations { String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. aš'; @@ -13942,11 +14274,8 @@ class SfLocalizationsLt extends SfGlobalLocalizations { /// The translations for Latvian (`lv`). class SfLocalizationsLv extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsLv class - const SfLocalizationsLv({ - String localeName = 'lv', - }) : super( - localeName: localeName, - ); + const SfLocalizationsLv({String localeName = 'lv'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Pēc'; @@ -14015,7 +14344,10 @@ class SfLocalizationsLv extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hidžja'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Nesākas ar'; @@ -14180,7 +14512,10 @@ class SfLocalizationsLv extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Pasvītrot'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override String get rabi2Label => r'Rabī al-tani'; @@ -14213,10 +14548,16 @@ class SfLocalizationsLv extends SfGlobalLocalizations { String get shawwalLabel => r'Šovals'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. es'; @@ -14289,11 +14630,8 @@ class SfLocalizationsLv extends SfGlobalLocalizations { /// The translations for Macedonian (`mk`). class SfLocalizationsMk extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsMk class - const SfLocalizationsMk({ - String localeName = 'mk', - }) : super( - localeName: localeName, - ); + const SfLocalizationsMk({String localeName = 'mk'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'По'; @@ -14565,7 +14903,10 @@ class SfLocalizationsMk extends SfGlobalLocalizations { String get shortDhualhiLabel => r'Дул-Х'; @override - String get shortDhualqiLabel => r'Ду' "'" r'л-К'; + String get shortDhualqiLabel => + r'Ду' + "'" + r'л-К'; @override String get shortJumada1Label => r'Џум. Јас'; @@ -14638,11 +14979,8 @@ class SfLocalizationsMk extends SfGlobalLocalizations { /// The translations for Malayalam (`ml`). class SfLocalizationsMl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsMl class - const SfLocalizationsMl({ - String localeName = 'ml', - }) : super( - localeName: localeName, - ); + const SfLocalizationsMl({String localeName = 'ml'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'ശേഷം'; @@ -14987,11 +15325,8 @@ class SfLocalizationsMl extends SfGlobalLocalizations { /// The translations for Mongolian (`mn`). class SfLocalizationsMn extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsMn class - const SfLocalizationsMn({ - String localeName = 'mn', - }) : super( - localeName: localeName, - ); + const SfLocalizationsMn({String localeName = 'mn'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Дараа'; @@ -15224,10 +15559,16 @@ class SfLocalizationsMn extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Доогуур зур'; @override - String get rabi1Label => r'Раби' "'" r' аль-аввал'; + String get rabi1Label => + r'Раби' + "'" + r' аль-аввал'; @override - String get rabi2Label => r'Раби' "'" r' аль-Тани'; + String get rabi2Label => + r'Раби' + "'" + r' аль-Тани'; @override String get rajabLabel => r'Ражаб'; @@ -15333,11 +15674,8 @@ class SfLocalizationsMn extends SfGlobalLocalizations { /// The translations for Marathi (`mr`). class SfLocalizationsMr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsMr class - const SfLocalizationsMr({ - String localeName = 'mr', - }) : super( - localeName: localeName, - ); + const SfLocalizationsMr({String localeName = 'mr'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'नंतर'; @@ -15680,11 +16018,8 @@ class SfLocalizationsMr extends SfGlobalLocalizations { /// The translations for Malay (`ms`). class SfLocalizationsMs extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsMs class - const SfLocalizationsMs({ - String localeName = 'ms', - }) : super( - localeName: localeName, - ); + const SfLocalizationsMs({String localeName = 'ms'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Selepas'; @@ -15753,7 +16088,10 @@ class SfLocalizationsMs extends SfGlobalLocalizations { String get dhualhiLabel => r'Dzulhijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Tidak Bermula Dengan'; @@ -15919,10 +16257,16 @@ class SfLocalizationsMs extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Garis bawah'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -15946,7 +16290,10 @@ class SfLocalizationsMs extends SfGlobalLocalizations { String get series => r'Siri'; @override - String get shaabanLabel => r'Sya' "'" r'aban'; + String get shaabanLabel => + r'Sya' + "'" + r'aban'; @override String get shawwalLabel => r'Syawal'; @@ -16028,11 +16375,8 @@ class SfLocalizationsMs extends SfGlobalLocalizations { /// The translations for Burmese (`my`). class SfLocalizationsMy extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsMy class - const SfLocalizationsMy({ - String localeName = 'my', - }) : super( - localeName: localeName, - ); + const SfLocalizationsMy({String localeName = 'my'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'ပြီးနောက်'; @@ -16102,7 +16446,10 @@ class SfLocalizationsMy extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'ဖြင့် မစတင်ပါ။'; @@ -16268,10 +16615,16 @@ class SfLocalizationsMy extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'မျဉ်းသား'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'ရာဂျပ်'; @@ -16295,16 +16648,25 @@ class SfLocalizationsMy extends SfGlobalLocalizations { String get series => r'စီးရီး'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum ငါ'; @@ -16377,11 +16739,8 @@ class SfLocalizationsMy extends SfGlobalLocalizations { /// The translations for Norwegian Bokmål (`nb`). class SfLocalizationsNb extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsNb class - const SfLocalizationsNb({ - String localeName = 'nb', - }) : super( - localeName: localeName, - ); + const SfLocalizationsNb({String localeName = 'nb'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Etter'; @@ -16450,7 +16809,10 @@ class SfLocalizationsNb extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Begynner ikke med'; @@ -16614,10 +16976,16 @@ class SfLocalizationsNb extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Understrek'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -16641,16 +17009,25 @@ class SfLocalizationsNb extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. Jeg'; @@ -16723,11 +17100,8 @@ class SfLocalizationsNb extends SfGlobalLocalizations { /// The translations for Nepali (`ne`). class SfLocalizationsNe extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsNe class - const SfLocalizationsNe({ - String localeName = 'ne', - }) : super( - localeName: localeName, - ); + const SfLocalizationsNe({String localeName = 'ne'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'पछि'; @@ -17072,11 +17446,8 @@ class SfLocalizationsNe extends SfGlobalLocalizations { /// The translations for Dutch Flemish (`nl`). class SfLocalizationsNl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsNl class - const SfLocalizationsNl({ - String localeName = 'nl', - }) : super( - localeName: localeName, - ); + const SfLocalizationsNl({String localeName = 'nl'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Na'; @@ -17145,7 +17516,10 @@ class SfLocalizationsNl extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Begint niet met'; @@ -17224,7 +17598,10 @@ class SfLocalizationsNl extends SfGlobalLocalizations { String get orDataGridFilteringLabel => r'Of'; @override - String get pagesDataPagerLabel => r'Pagina' "'" r's'; + String get pagesDataPagerLabel => + r'Pagina' + "'" + r's'; @override String get passwordDialogContentLabel => @@ -17291,10 +17668,16 @@ class SfLocalizationsNl extends SfGlobalLocalizations { String get pdfSignaturePadDialogPenColorLabel => r'Pen Kleur'; @override - String get rabi1Label => r'Rabi' "'" r' al-Awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-Awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get pdfSignaturePadDialogSaveLabel => r'Opslaan'; @@ -17336,7 +17719,10 @@ class SfLocalizationsNl extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @@ -17345,7 +17731,10 @@ class SfLocalizationsNl extends SfGlobalLocalizations { String get shortDhualhiLabel => r'Dhul-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. l'; @@ -17418,11 +17807,8 @@ class SfLocalizationsNl extends SfGlobalLocalizations { /// The translations for Norwegian (`no`). class SfLocalizationsNo extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsNo class - const SfLocalizationsNo({ - String localeName = 'no', - }) : super( - localeName: localeName, - ); + const SfLocalizationsNo({String localeName = 'no'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Etter'; @@ -17491,7 +17877,10 @@ class SfLocalizationsNo extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Begynner ikke med'; @@ -17655,10 +18044,16 @@ class SfLocalizationsNo extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Understrek'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -17682,16 +18077,25 @@ class SfLocalizationsNo extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. Jeg'; @@ -17764,11 +18168,8 @@ class SfLocalizationsNo extends SfGlobalLocalizations { /// The translations for Oriya (`or`). class SfLocalizationsOr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsOr class - const SfLocalizationsOr({ - String localeName = 'or', - }) : super( - localeName: localeName, - ); + const SfLocalizationsOr({String localeName = 'or'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'ପରେ'; @@ -18004,10 +18405,16 @@ class SfLocalizationsOr extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'ଅଣ୍ଡରଲାଇନ୍ |'; @override - String get rabi1Label => r'ରବି ' "'" r'ଅଲ-ଅୱାଲ୍ |'; + String get rabi1Label => + r'ରବି ' + "'" + r'ଅଲ-ଅୱାଲ୍ |'; @override - String get rabi2Label => r'ରବି ' "'" r'ଅଲ-ଥାନି |'; + String get rabi2Label => + r'ରବି ' + "'" + r'ଅଲ-ଥାନି |'; @override String get rajabLabel => r'ରାଜାବ'; @@ -18114,11 +18521,8 @@ class SfLocalizationsOr extends SfGlobalLocalizations { /// The translations for Panjabi Punjabi (`pa`). class SfLocalizationsPa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsPa class - const SfLocalizationsPa({ - String localeName = 'pa', - }) : super( - localeName: localeName, - ); + const SfLocalizationsPa({String localeName = 'pa'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'ਤੋਂ ਬਾਅਦ'; @@ -18288,11 +18692,16 @@ class SfLocalizationsPa extends SfGlobalLocalizations { String get pdfEnterPageNumberLabel => r'ਪੰਨਾ ਨੰਬਰ ਦਰਜ ਕਰੋ'; @override - String get pdfGoToPageLabel => r'ਪੰਨੇ ' "'" r'ਤੇ ਜਾਓ'; + String get pdfGoToPageLabel => + r'ਪੰਨੇ ' + "'" + r'ਤੇ ਜਾਓ'; @override String get pdfHyperlinkContentLabel => - r'ਕੀ ਤੁਸੀਂ ' "'" r'ਤੇ ਪੰਨਾ ਖੋਲ੍ਹਣਾ ਚਾਹੁੰਦੇ ਹੋ'; + r'ਕੀ ਤੁਸੀਂ ' + "'" + r'ਤੇ ਪੰਨਾ ਖੋਲ੍ਹਣਾ ਚਾਹੁੰਦੇ ਹੋ'; @override String get pdfHyperlinkDialogCancelLabel => r'ਰੱਦ ਕਰੋ'; @@ -18461,11 +18870,8 @@ class SfLocalizationsPa extends SfGlobalLocalizations { /// The translations for Polish (`pl`). class SfLocalizationsPl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsPl class - const SfLocalizationsPl({ - String localeName = 'pl', - }) : super( - localeName: localeName, - ); + const SfLocalizationsPl({String localeName = 'pl'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Później'; @@ -18534,7 +18940,10 @@ class SfLocalizationsPl extends SfGlobalLocalizations { String get dhualhiLabel => r'Du al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Nie zaczyna się od'; @@ -18685,7 +19094,10 @@ class SfLocalizationsPl extends SfGlobalLocalizations { String get rabi1Label => r'Rabi al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Radżab'; @@ -18724,16 +19136,25 @@ class SfLocalizationsPl extends SfGlobalLocalizations { String get series => r'Seria'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'sok. I'; @@ -18806,11 +19227,8 @@ class SfLocalizationsPl extends SfGlobalLocalizations { /// The translations for Pushto Pashto (`ps`). class SfLocalizationsPs extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsPs class - const SfLocalizationsPs({ - String localeName = 'ps', - }) : super( - localeName: localeName, - ); + const SfLocalizationsPs({String localeName = 'ps'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'وروسته'; @@ -19153,11 +19571,8 @@ class SfLocalizationsPs extends SfGlobalLocalizations { /// The translations for Portuguese (`pt`). class SfLocalizationsPt extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsPt class - const SfLocalizationsPt({ - String localeName = 'pt', - }) : super( - localeName: localeName, - ); + const SfLocalizationsPt({String localeName = 'pt'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Depois'; @@ -19227,7 +19642,10 @@ class SfLocalizationsPt extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Não começa com'; @@ -19390,10 +19808,16 @@ class SfLocalizationsPt extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Sublinhado'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -19417,16 +19841,25 @@ class SfLocalizationsPt extends SfGlobalLocalizations { String get series => r'Series'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. EU'; @@ -19499,11 +19932,8 @@ class SfLocalizationsPt extends SfGlobalLocalizations { /// The translations for Portuguese, as used in Portugal (`pt_PT`). class SfLocalizationsPtPt extends SfLocalizationsPt { /// Creating an argument constructor of SfLocalizationsPtPt class - const SfLocalizationsPtPt({ - String localeName = 'pt_PT', - }) : super( - localeName: localeName, - ); + const SfLocalizationsPtPt({String localeName = 'pt_PT'}) + : super(localeName: localeName); @override String get pdfEnterPageNumberLabel => r'Digite o número da página'; @@ -19515,11 +19945,8 @@ class SfLocalizationsPtPt extends SfLocalizationsPt { /// The translations for Romanian Moldavian Moldovan (`ro`). class SfLocalizationsRo extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsRo class - const SfLocalizationsRo({ - String localeName = 'ro', - }) : super( - localeName: localeName, - ); + const SfLocalizationsRo({String localeName = 'ro'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'După'; @@ -19589,7 +20016,10 @@ class SfLocalizationsRo extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Nu Începe Cu'; @@ -19753,10 +20183,16 @@ class SfLocalizationsRo extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Subliniați'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -19780,16 +20216,25 @@ class SfLocalizationsRo extends SfGlobalLocalizations { String get series => r'Serie'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. eu'; @@ -19862,11 +20307,8 @@ class SfLocalizationsRo extends SfGlobalLocalizations { /// The translations for Russian (`ru`). class SfLocalizationsRu extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsRu class - const SfLocalizationsRu({ - String localeName = 'ru', - }) : super( - localeName: localeName, - ); + const SfLocalizationsRu({String localeName = 'ru'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'После'; @@ -20208,11 +20650,8 @@ class SfLocalizationsRu extends SfGlobalLocalizations { /// The translations for Sinhala Sinhalese (`si`). class SfLocalizationsSi extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSi class - const SfLocalizationsSi({ - String localeName = 'si', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSi({String localeName = 'si'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'පසු'; @@ -20281,7 +20720,10 @@ class SfLocalizationsSi extends SfGlobalLocalizations { String get dhualhiLabel => r'ඩු අල්-හිජ්ජා'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'සමඟ ආරම්භ නොවේ'; @@ -20554,11 +20996,8 @@ class SfLocalizationsSi extends SfGlobalLocalizations { /// The translations for Slovak (`sk`). class SfLocalizationsSk extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSk class - const SfLocalizationsSk({ - String localeName = 'sk', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSk({String localeName = 'sk'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Po'; @@ -20627,7 +21066,10 @@ class SfLocalizationsSk extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Nezačína s'; @@ -20791,10 +21233,16 @@ class SfLocalizationsSk extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Zdôrazniť'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -20818,16 +21266,25 @@ class SfLocalizationsSk extends SfGlobalLocalizations { String get series => r'séria'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. ja'; @@ -20900,11 +21357,8 @@ class SfLocalizationsSk extends SfGlobalLocalizations { /// The translations for Slovenian (`sl`). class SfLocalizationsSl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSl class - const SfLocalizationsSl({ - String localeName = 'sl', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSl({String localeName = 'sl'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Po'; @@ -20973,7 +21427,10 @@ class SfLocalizationsSl extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Se ne začne z'; @@ -21136,10 +21593,16 @@ class SfLocalizationsSl extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Podčrtaj'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -21163,16 +21626,25 @@ class SfLocalizationsSl extends SfGlobalLocalizations { String get series => r'serija'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. jaz'; @@ -21245,11 +21717,8 @@ class SfLocalizationsSl extends SfGlobalLocalizations { /// The translations for Albanian (`sq`). class SfLocalizationsSq extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSq class - const SfLocalizationsSq({ - String localeName = 'sq', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSq({String localeName = 'sq'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Pas'; @@ -21485,10 +21954,16 @@ class SfLocalizationsSq extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Nënvizoj'; @override - String get rabi1Label => r'Rabi' "'" r'ul-evvel'; + String get rabi1Label => + r'Rabi' + "'" + r'ul-evvel'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rexheb'; @@ -21521,7 +21996,10 @@ class SfLocalizationsSq extends SfGlobalLocalizations { String get shortDhualhiLabel => r'Dhul-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-K'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-K'; @override String get shortJumada1Label => r'Jum. I'; @@ -21594,11 +22072,8 @@ class SfLocalizationsSq extends SfGlobalLocalizations { /// The translations for Serbian (`sr`). class SfLocalizationsSr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSr class - const SfLocalizationsSr({ - String localeName = 'sr', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSr({String localeName = 'sr'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'После'; @@ -21668,7 +22143,10 @@ class SfLocalizationsSr extends SfGlobalLocalizations { String get dhualhiLabel => r'Дху ал-Хијјах'; @override - String get dhualqiLabel => r'Дху ал-Ки' "'" r'дах'; + String get dhualqiLabel => + r'Дху ал-Ки' + "'" + r'дах'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Не почиње са'; @@ -21832,10 +22310,16 @@ class SfLocalizationsSr extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Подвући'; @override - String get rabi1Label => r'Раби' "'" r' ал-аввал'; + String get rabi1Label => + r'Раби' + "'" + r' ал-аввал'; @override - String get rabi2Label => r'Раби' "'" r' ал-тхани'; + String get rabi2Label => + r'Раби' + "'" + r' ал-тхани'; @override String get rajabLabel => r'Раџаб'; @@ -21859,16 +22343,25 @@ class SfLocalizationsSr extends SfGlobalLocalizations { String get series => r'Сериес'; @override - String get shaabanLabel => r'Сха' "'" r'абан'; + String get shaabanLabel => + r'Сха' + "'" + r'абан'; @override String get shawwalLabel => r'Схаввал'; @override - String get shortDhualhiLabel => r'Дху' "'" r'л-Х'; + String get shortDhualhiLabel => + r'Дху' + "'" + r'л-Х'; @override - String get shortDhualqiLabel => r'Дху' "'" r'л-К'; + String get shortDhualqiLabel => + r'Дху' + "'" + r'л-К'; @override String get shortJumada1Label => r'Јум. И'; @@ -21941,21 +22434,15 @@ class SfLocalizationsSr extends SfGlobalLocalizations { /// The translations for Serbian, using the Cyrillic script (`sr_Cyrl`). class SfLocalizationsSrCyrl extends SfLocalizationsSr { /// Creating an argument constructor of SfLocalizationsSrCyrl class - const SfLocalizationsSrCyrl({ - String localeName = 'sr_Cyrl', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSrCyrl({String localeName = 'sr_Cyrl'}) + : super(localeName: localeName); } /// The translations for Swedish (`sv`). class SfLocalizationsSv extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSv class - const SfLocalizationsSv({ - String localeName = 'sv', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSv({String localeName = 'sv'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Efter'; @@ -22024,7 +22511,10 @@ class SfLocalizationsSv extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Börjar inte med'; @@ -22189,10 +22679,16 @@ class SfLocalizationsSv extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Understrykning'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -22216,16 +22712,25 @@ class SfLocalizationsSv extends SfGlobalLocalizations { String get series => r'Serier'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. jag'; @@ -22298,11 +22803,8 @@ class SfLocalizationsSv extends SfGlobalLocalizations { /// The translations for Swahili (`sw`). class SfLocalizationsSw extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsSw class - const SfLocalizationsSw({ - String localeName = 'sw', - }) : super( - localeName: localeName, - ); + const SfLocalizationsSw({String localeName = 'sw'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Baada ya'; @@ -22371,7 +22873,10 @@ class SfLocalizationsSw extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Huanza Na'; @@ -22535,10 +23040,16 @@ class SfLocalizationsSw extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Piga mstari'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -22562,16 +23073,25 @@ class SfLocalizationsSw extends SfGlobalLocalizations { String get series => r'Msururu'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. I'; @@ -22644,11 +23164,8 @@ class SfLocalizationsSw extends SfGlobalLocalizations { /// The translations for Tamil (`ta`). class SfLocalizationsTa extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsTa class - const SfLocalizationsTa({ - String localeName = 'ta', - }) : super( - localeName: localeName, - ); + const SfLocalizationsTa({String localeName = 'ta'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'பிறகு'; @@ -22717,7 +23234,10 @@ class SfLocalizationsTa extends SfGlobalLocalizations { String get dhualhiLabel => r'து அல்-ஹிஜ்ஜா'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'உடன் தொடங்கவில்லை'; @@ -22996,11 +23516,8 @@ class SfLocalizationsTa extends SfGlobalLocalizations { /// The translations for Telugu (`te`). class SfLocalizationsTe extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsTe class - const SfLocalizationsTe({ - String localeName = 'te', - }) : super( - localeName: localeName, - ); + const SfLocalizationsTe({String localeName = 'te'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'తర్వాత'; @@ -23069,7 +23586,10 @@ class SfLocalizationsTe extends SfGlobalLocalizations { String get dhualhiLabel => r'ధు అల్-హిజ్జా'; @override - String get dhualqiLabel => r'ధు అల్-కి' "'" r'దా'; + String get dhualqiLabel => + r'ధు అల్-కి' + "'" + r'దా'; @override String get doesNotBeginWithDataGridFilteringLabel => r'తో ప్రారంభం కాదు'; @@ -23348,11 +23868,8 @@ class SfLocalizationsTe extends SfGlobalLocalizations { /// The translations for Thai (`th`). class SfLocalizationsTh extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsTh class - const SfLocalizationsTh({ - String localeName = 'th', - }) : super( - localeName: localeName, - ); + const SfLocalizationsTh({String localeName = 'th'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'หลังจาก'; @@ -23692,11 +24209,8 @@ class SfLocalizationsTh extends SfGlobalLocalizations { /// The translations for Tagalog (`tl`). class SfLocalizationsTl extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsTl class - const SfLocalizationsTl({ - String localeName = 'tl', - }) : super( - localeName: localeName, - ); + const SfLocalizationsTl({String localeName = 'tl'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Pagkatapos'; @@ -23766,7 +24280,10 @@ class SfLocalizationsTl extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Hindi Nagsisimula Sa'; @@ -23931,10 +24448,16 @@ class SfLocalizationsTl extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Salungguhit'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -23958,16 +24481,25 @@ class SfLocalizationsTl extends SfGlobalLocalizations { String get series => r'Serye'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. ako'; @@ -24043,11 +24575,8 @@ class SfLocalizationsTl extends SfGlobalLocalizations { /// The translations for Turkish (`tr`). class SfLocalizationsTr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsTr class - const SfLocalizationsTr({ - String localeName = 'tr', - }) : super( - localeName: localeName, - ); + const SfLocalizationsTr({String localeName = 'tr'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Sonrasında'; @@ -24117,7 +24646,10 @@ class SfLocalizationsTr extends SfGlobalLocalizations { String get dhualhiLabel => r'Zilhicce'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'İle Başlamıyor'; @@ -24283,10 +24815,16 @@ class SfLocalizationsTr extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Altını çizmek'; @override - String get rabi1Label => r'Rabi' "'" r'ul-evvel'; + String get rabi1Label => + r'Rabi' + "'" + r'ul-evvel'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Recep'; @@ -24356,7 +24894,11 @@ class SfLocalizationsTr extends SfGlobalLocalizations { @override String get sortAToZDataGridFilteringLabel => - r'A' "'" r'dan Z' "'" r'ye Sırala'; + r'A' + "'" + r'dan Z' + "'" + r'ye Sırala'; @override String get sortAndFilterDataGridFilteringLabel => r'Sırala ve Filtrele'; @@ -24379,7 +24921,11 @@ class SfLocalizationsTr extends SfGlobalLocalizations { @override String get sortZToADataGridFilteringLabel => - r'Z' "'" r'den A' "'" r'ya Sırala'; + r'Z' + "'" + r'den A' + "'" + r'ya Sırala'; @override String get textFiltersDataGridFilteringLabel => r'Metin Filtreleri'; @@ -24394,11 +24940,8 @@ class SfLocalizationsTr extends SfGlobalLocalizations { /// The translations for Ukrainian (`uk`). class SfLocalizationsUk extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsUk class - const SfLocalizationsUk({ - String localeName = 'uk', - }) : super( - localeName: localeName, - ); + const SfLocalizationsUk({String localeName = 'uk'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'після'; @@ -24663,10 +25206,18 @@ class SfLocalizationsUk extends SfGlobalLocalizations { String get shawwalLabel => r'Шавваль'; @override - String get shortDhualhiLabel => r'Зу' "'" r'л-Х'; + String get shortDhualhiLabel => + r'Зу' + "'" + r'л-Х'; @override - String get shortDhualqiLabel => r'Зу' "'" r'л-К' "'" r'ю'; + String get shortDhualqiLabel => + r'Зу' + "'" + r'л-К' + "'" + r'ю'; @override String get shortJumada1Label => r'стрибати я'; @@ -24739,11 +25290,8 @@ class SfLocalizationsUk extends SfGlobalLocalizations { /// The translations for Urdu (`ur`). class SfLocalizationsUr extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsUr class - const SfLocalizationsUr({ - String localeName = 'ur', - }) : super( - localeName: localeName, - ); + const SfLocalizationsUr({String localeName = 'ur'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'کے بعد'; @@ -25085,11 +25633,8 @@ class SfLocalizationsUr extends SfGlobalLocalizations { /// The translations for Uzbek (`uz`). class SfLocalizationsUz extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsUz class - const SfLocalizationsUz({ - String localeName = 'uz', - }) : super( - localeName: localeName, - ); + const SfLocalizationsUz({String localeName = 'uz'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Keyin'; @@ -25173,7 +25718,10 @@ class SfLocalizationsUz extends SfGlobalLocalizations { String get doesNotEqualDataGridFilteringLabel => r'Teng emas'; @override - String get emptyDataGridFilteringLabel => r'Bo' "'" r'sh'; + String get emptyDataGridFilteringLabel => + r'Bo' + "'" + r'sh'; @override String get endsWithDataGridFilteringLabel => r'Bilan tugaydi'; @@ -25215,7 +25763,10 @@ class SfLocalizationsUz extends SfGlobalLocalizations { String get noSelectedDateCalendarLabel => r'Tanlangan sana yo‘q'; @override - String get notEmptyDataGridFilteringLabel => r'Bo' "'" r'sh emas'; + String get notEmptyDataGridFilteringLabel => + r'Bo' + "'" + r'sh emas'; @override String get notNullDataGridFilteringLabel => r'Null emas'; @@ -25258,7 +25809,10 @@ class SfLocalizationsUz extends SfGlobalLocalizations { String get pdfEnterPageNumberLabel => r'Sahifa raqamini kiriting'; @override - String get pdfGoToPageLabel => r'Sahifaga o' "'" r'tish'; + String get pdfGoToPageLabel => + r'Sahifaga o' + "'" + r'tish'; @override String get pdfHyperlinkContentLabel => r'sahifani ochmoqchimisiz'; @@ -25312,7 +25866,10 @@ class SfLocalizationsUz extends SfGlobalLocalizations { String get pdfTextSelectionMenuHighlightLabel => r'Ajratish'; @override - String get pdfTextSelectionMenuSquigglyLabel => r'Buzg' "'" r'unchi'; + String get pdfTextSelectionMenuSquigglyLabel => + r'Buzg' + "'" + r'unchi'; @override String get pdfTextSelectionMenuStrikethroughLabel => r'Chizilgan'; @@ -25321,10 +25878,16 @@ class SfLocalizationsUz extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'tagiga chizish'; @override - String get rabi1Label => r'Rabi' "'" r'ul-avval'; + String get rabi1Label => + r'Rabi' + "'" + r'ul-avval'; @override - String get rabi2Label => r'Rabi' "'" r' as-saniy'; + String get rabi2Label => + r'Rabi' + "'" + r' as-saniy'; @override String get rajabLabel => r'Rajab'; @@ -25348,7 +25911,10 @@ class SfLocalizationsUz extends SfGlobalLocalizations { String get series => r'Seriya'; @override - String get shaabanLabel => r'Sha' "'" r'bon'; + String get shaabanLabel => + r'Sha' + "'" + r'bon'; @override String get shawwalLabel => r'Shavvol'; @@ -25391,7 +25957,9 @@ class SfLocalizationsUz extends SfGlobalLocalizations { @override String get showRowsWhereDataGridFilteringLabel => - r'Qaerda qatorlarni ko' "'" r'rsatish'; + r'Qaerda qatorlarni ko' + "'" + r'rsatish'; @override String get sortAToZDataGridFilteringLabel => r'A dan Z gacha tartiblang'; @@ -25431,11 +25999,8 @@ class SfLocalizationsUz extends SfGlobalLocalizations { /// The translations for Vietnamese (`vi`). class SfLocalizationsVi extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsVi class - const SfLocalizationsVi({ - String localeName = 'vi', - }) : super( - localeName: localeName, - ); + const SfLocalizationsVi({String localeName = 'vi'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Sau'; @@ -25505,7 +26070,10 @@ class SfLocalizationsVi extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'không bắt đầu bằng'; @@ -25667,10 +26235,16 @@ class SfLocalizationsVi extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'gạch chân'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -25694,16 +26268,25 @@ class SfLocalizationsVi extends SfGlobalLocalizations { String get series => r'Loạt'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. Tôi'; @@ -25776,11 +26359,8 @@ class SfLocalizationsVi extends SfGlobalLocalizations { /// The translations for Chinese (`zh`). class SfLocalizationsZh extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsZh class - const SfLocalizationsZh({ - String localeName = 'zh', - }) : super( - localeName: localeName, - ); + const SfLocalizationsZh({String localeName = 'zh'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'后'; @@ -25849,7 +26429,10 @@ class SfLocalizationsZh extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'不以开头'; @@ -26044,10 +26627,16 @@ class SfLocalizationsZh extends SfGlobalLocalizations { String get shawwalLabel => r'肖瓦尔'; @override - String get shortDhualhiLabel => r'Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'滚。我'; @@ -26116,21 +26705,15 @@ class SfLocalizationsZh extends SfGlobalLocalizations { /// The translations for Chinese, using the Han script (`zh_Hans`). class SfLocalizationsZhHans extends SfLocalizationsZh { /// Creating an argument constructor of SfLocalizationsZhHans class - const SfLocalizationsZhHans({ - String localeName = 'zh_Hans', - }) : super( - localeName: localeName, - ); + const SfLocalizationsZhHans({String localeName = 'zh_Hans'}) + : super(localeName: localeName); } /// The translations for Chinese, using the Han script (`zh_Hant`). class SfLocalizationsZhHant extends SfLocalizationsZh { /// Creating an argument constructor of SfLocalizationsZhHant class - const SfLocalizationsZhHant({ - String localeName = 'zh_Hant', - }) : super( - localeName: localeName, - ); + const SfLocalizationsZhHant({String localeName = 'zh_Hant'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'後'; @@ -26355,21 +26938,15 @@ class SfLocalizationsZhHant extends SfLocalizationsZh { /// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`). class SfLocalizationsZhHantHk extends SfLocalizationsZhHant { /// Creating an argument constructor of SfLocalizationsZhHantHk class - const SfLocalizationsZhHantHk({ - String localeName = 'zh_Hant_HK', - }) : super( - localeName: localeName, - ); + const SfLocalizationsZhHantHk({String localeName = 'zh_Hant_HK'}) + : super(localeName: localeName); } /// The translations for Chinese, as used in Taiwan, using the Han script (`zh_Hant_TW`). class SfLocalizationsZhHantTw extends SfLocalizationsZhHant { /// Creating an argument constructor of SfLocalizationsZhHantTw class - const SfLocalizationsZhHantTw({ - String localeName = 'zh_Hant_TW', - }) : super( - localeName: localeName, - ); + const SfLocalizationsZhHantTw({String localeName = 'zh_Hant_TW'}) + : super(localeName: localeName); @override String get pdfPasswordDialogOpenLabel => r'打開'; @@ -26384,11 +26961,8 @@ class SfLocalizationsZhHantTw extends SfLocalizationsZhHant { /// The translations for Zulu (`zu`). class SfLocalizationsZu extends SfGlobalLocalizations { /// Creating an argument constructor of SfLocalizationsZu class - const SfLocalizationsZu({ - String localeName = 'zu', - }) : super( - localeName: localeName, - ); + const SfLocalizationsZu({String localeName = 'zu'}) + : super(localeName: localeName); @override String get afterDataGridFilteringLabel => r'Ngemva'; @@ -26459,7 +27033,10 @@ class SfLocalizationsZu extends SfGlobalLocalizations { String get dhualhiLabel => r'Dhu al-Hijjah'; @override - String get dhualqiLabel => r'Dhu al-Qi' "'" r'dah'; + String get dhualqiLabel => + r'Dhu al-Qi' + "'" + r'dah'; @override String get doesNotBeginWithDataGridFilteringLabel => r'Ayiqali Nge'; @@ -26624,10 +27201,16 @@ class SfLocalizationsZu extends SfGlobalLocalizations { String get pdfTextSelectionMenuUnderlineLabel => r'Dwebela'; @override - String get rabi1Label => r'Rabi' "'" r' al-awwal'; + String get rabi1Label => + r'Rabi' + "'" + r' al-awwal'; @override - String get rabi2Label => r'Rabi' "'" r' al-thani'; + String get rabi2Label => + r'Rabi' + "'" + r' al-thani'; @override String get rajabLabel => r'Rajab'; @@ -26651,16 +27234,25 @@ class SfLocalizationsZu extends SfGlobalLocalizations { String get series => r'Uchungechunge'; @override - String get shaabanLabel => r'Sha' "'" r'aban'; + String get shaabanLabel => + r'Sha' + "'" + r'aban'; @override String get shawwalLabel => r'Shawwal'; @override - String get shortDhualhiLabel => r'U-Dhu' "'" r'l-H'; + String get shortDhualhiLabel => + r'U-Dhu' + "'" + r'l-H'; @override - String get shortDhualqiLabel => r'Dhu' "'" r'l-Q'; + String get shortDhualqiLabel => + r'Dhu' + "'" + r'l-Q'; @override String get shortJumada1Label => r'Jum. I'; @@ -26731,85 +27323,86 @@ class SfLocalizationsZu extends SfGlobalLocalizations { } /// The set of supported languages, as language code strings. -final Set kSyncfusionSupportedLanguages = - HashSet.from(const [ - 'af', // Afrikaans - 'am', // Amharic - 'ar', // Arabic - 'az', // Azerbaijani - 'be', // Belarusian - 'bg', // Bulgarian - 'bn', // Bengali Bangla - 'bs', // Bosnian - 'ca', // Catalan Valencian - 'cs', // Czech - 'da', // Danish - 'de', // German - 'el', // Modern Greek - 'en', // English - 'es', // Spanish Castilian - 'et', // Estonian - 'eu', // Basque - 'fa', // Persian - 'fi', // Finnish - 'fil', // Filipino Pilipino - 'fr', // French - 'gl', // Galician - 'gu', // Gujarati - 'he', // Hebrew - 'hi', // Hindi - 'hr', // Croatian - 'hu', // Hungarian - 'hy', // Armenian - 'id', // Indonesian - 'is', // Icelandic - 'it', // Italian - 'ja', // Japanese - 'ka', // Georgian - 'kk', // Kazakh - 'km', // Khmer Central Khmer - 'kn', // Kannada - 'ko', // Korean - 'ky', // Kirghiz Kyrgyz - 'lo', // Lao - 'lt', // Lithuanian - 'lv', // Latvian - 'mk', // Macedonian - 'ml', // Malayalam - 'mn', // Mongolian - 'mr', // Marathi - 'ms', // Malay - 'my', // Burmese - 'nb', // Norwegian Bokmål - 'ne', // Nepali - 'nl', // Dutch Flemish - 'no', // Norwegian - 'or', // Oriya - 'pa', // Panjabi Punjabi - 'pl', // Polish - 'ps', // Pushto Pashto - 'pt', // Portuguese - 'ro', // Romanian Moldavian Moldovan - 'ru', // Russian - 'si', // Sinhala Sinhalese - 'sk', // Slovak - 'sl', // Slovenian - 'sq', // Albanian - 'sr', // Serbian - 'sv', // Swedish - 'sw', // Swahili - 'ta', // Tamil - 'te', // Telugu - 'th', // Thai - 'tl', // Tagalog - 'tr', // Turkish - 'uk', // Ukrainian - 'ur', // Urdu - 'uz', // Uzbek - 'vi', // Vietnamese - 'zh', // Chinese - 'zu', // Zulu -]); +final Set kSyncfusionSupportedLanguages = HashSet.from( + const [ + 'af', // Afrikaans + 'am', // Amharic + 'ar', // Arabic + 'az', // Azerbaijani + 'be', // Belarusian + 'bg', // Bulgarian + 'bn', // Bengali Bangla + 'bs', // Bosnian + 'ca', // Catalan Valencian + 'cs', // Czech + 'da', // Danish + 'de', // German + 'el', // Modern Greek + 'en', // English + 'es', // Spanish Castilian + 'et', // Estonian + 'eu', // Basque + 'fa', // Persian + 'fi', // Finnish + 'fil', // Filipino Pilipino + 'fr', // French + 'gl', // Galician + 'gu', // Gujarati + 'he', // Hebrew + 'hi', // Hindi + 'hr', // Croatian + 'hu', // Hungarian + 'hy', // Armenian + 'id', // Indonesian + 'is', // Icelandic + 'it', // Italian + 'ja', // Japanese + 'ka', // Georgian + 'kk', // Kazakh + 'km', // Khmer Central Khmer + 'kn', // Kannada + 'ko', // Korean + 'ky', // Kirghiz Kyrgyz + 'lo', // Lao + 'lt', // Lithuanian + 'lv', // Latvian + 'mk', // Macedonian + 'ml', // Malayalam + 'mn', // Mongolian + 'mr', // Marathi + 'ms', // Malay + 'my', // Burmese + 'nb', // Norwegian Bokmål + 'ne', // Nepali + 'nl', // Dutch Flemish + 'no', // Norwegian + 'or', // Oriya + 'pa', // Panjabi Punjabi + 'pl', // Polish + 'ps', // Pushto Pashto + 'pt', // Portuguese + 'ro', // Romanian Moldavian Moldovan + 'ru', // Russian + 'si', // Sinhala Sinhalese + 'sk', // Slovak + 'sl', // Slovenian + 'sq', // Albanian + 'sr', // Serbian + 'sv', // Swedish + 'sw', // Swahili + 'ta', // Tamil + 'te', // Telugu + 'th', // Thai + 'tl', // Tagalog + 'tr', // Turkish + 'uk', // Ukrainian + 'ur', // Urdu + 'uz', // Uzbek + 'vi', // Vietnamese + 'zh', // Chinese + 'zu', // Zulu + ], +); /// Creates a [SfGlobalLocalizations] instance for the given `locale`. /// @@ -26901,9 +27494,7 @@ final Set kSyncfusionSupportedLanguages = /// /// Generally speaking, this method is only intended to be used by /// [SfGlobalLocalizations.delegate]. -SfGlobalLocalizations? getSyncfusionTranslation( - Locale locale, -) { +SfGlobalLocalizations? getSyncfusionTranslation(Locale locale) { switch (locale.languageCode) { case 'af': return const SfLocalizationsAf(); @@ -27096,7 +27687,9 @@ SfGlobalLocalizations? getSyncfusionTranslation( case 'zu': return const SfLocalizationsZu(); } - assert(false, - 'getSyncfusionTranslation() called for unsupported locale "$locale"'); + assert( + false, + 'getSyncfusionTranslation() called for unsupported locale "$locale"', + ); return null; } diff --git a/packages/syncfusion_localizations/pubspec.yaml b/packages/syncfusion_localizations/pubspec.yaml index d6563751b..06639979b 100644 --- a/packages/syncfusion_localizations/pubspec.yaml +++ b/packages/syncfusion_localizations/pubspec.yaml @@ -1,11 +1,11 @@ name: syncfusion_localizations description: Syncfusion Localizations package contains localized text for 77 cultures for all the applicable Syncfusion Flutter Widgets. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_localizations environment: - sdk: ">=3.4.0 <4.0.0" + sdk: ^3.7.0 dependencies: flutter: @@ -18,4 +18,4 @@ dependencies: -flutter: +flutter: \ No newline at end of file diff --git a/packages/syncfusion_officechart/CHANGELOG.md b/packages/syncfusion_officechart/CHANGELOG.md index 5e2e7a49f..99e7ed336 100644 --- a/packages/syncfusion_officechart/CHANGELOG.md +++ b/packages/syncfusion_officechart/CHANGELOG.md @@ -1,4 +1,17 @@ -## [Unreleased] +## Unreleased + +**General** + +* Upgraded the archive package. The Flutter XlsIO widget supports archive package version 4.0.0 and above. +* The compatible version of our Flutter OfficeChart widget has been updated to Flutter SDK 3.32.0 + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 **General** diff --git a/packages/syncfusion_officechart/example/lib/helper/save_file_mobile.dart b/packages/syncfusion_officechart/example/lib/helper/save_file_mobile.dart index c7ddbff8b..856ba8bdb 100644 --- a/packages/syncfusion_officechart/example/lib/helper/save_file_mobile.dart +++ b/packages/syncfusion_officechart/example/lib/helper/save_file_mobile.dart @@ -20,8 +20,9 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else { path = await PathProviderPlatform.instance.getApplicationSupportPath(); } - final File file = - File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName'); + final File file = File( + Platform.isWindows ? '$path\\$fileName' : '$path/$fileName', + ); await file.writeAsBytes(bytes, flush: true); if (Platform.isAndroid || Platform.isIOS) { //Launch the file (used open_file package) @@ -31,7 +32,8 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else if (Platform.isMacOS) { await Process.run('open', ['$path/$fileName'], runInShell: true); } else if (Platform.isLinux) { - await Process.run('xdg-open', ['$path/$fileName'], - runInShell: true); + await Process.run('xdg-open', [ + '$path/$fileName', + ], runInShell: true); } } diff --git a/packages/syncfusion_officechart/example/lib/main.dart b/packages/syncfusion_officechart/example/lib/main.dart index 8ff37e99f..00312ea6a 100644 --- a/packages/syncfusion_officechart/example/lib/main.dart +++ b/packages/syncfusion_officechart/example/lib/main.dart @@ -28,7 +28,7 @@ class CreateOfficeChartWidget extends StatelessWidget { class CreateOfficeChartStatefulWidget extends StatefulWidget { /// Initalize the instance of the [CreateOfficeChartStatefulWidget] class. const CreateOfficeChartStatefulWidget({Key? key, required this.title}) - : super(key: key); + : super(key: key); /// title. final String title; @@ -41,9 +41,7 @@ class _CreateOfficeChartState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -56,7 +54,7 @@ class _CreateOfficeChartState extends State { ), onPressed: generateOfficeChart, child: const Text('Generate Excel Chart'), - ) + ), ], ), ), diff --git a/packages/syncfusion_officechart/example/pubspec.yaml b/packages/syncfusion_officechart/example/pubspec.yaml index cd3895881..3aad8e935 100644 --- a/packages/syncfusion_officechart/example/pubspec.yaml +++ b/packages/syncfusion_officechart/example/pubspec.yaml @@ -2,7 +2,7 @@ name: officechart_example description: Demo for creating a Excel file with chart using syncfusion_officechart package. environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_officechart/lib/src/chart/chart_collection.dart b/packages/syncfusion_officechart/lib/src/chart/chart_collection.dart index 37ee276ff..340860a7d 100644 --- a/packages/syncfusion_officechart/lib/src/chart/chart_collection.dart +++ b/packages/syncfusion_officechart/lib/src/chart/chart_collection.dart @@ -103,7 +103,9 @@ class ChartCollection extends ChartHelper { /// Serialize the chart drawings. @override Future serializeChartDrawing( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { _chartSerialization ??= ChartSerialization(sheet.workbook); _chartSerialization!.serializeChartDrawingAsync(builder, sheet); diff --git a/packages/syncfusion_officechart/lib/src/chart/chart_impl.dart b/packages/syncfusion_officechart/lib/src/chart/chart_impl.dart index f031afe35..76d03612b 100644 --- a/packages/syncfusion_officechart/lib/src/chart/chart_impl.dart +++ b/packages/syncfusion_officechart/lib/src/chart/chart_impl.dart @@ -54,7 +54,7 @@ class Chart { ExcelChartType.bar, ExcelChartType.column, ExcelChartType.columnClustered3D, - ExcelChartType.barClustered3D + ExcelChartType.barClustered3D, ]; /// Represent the stacked chart collection. @@ -65,7 +65,7 @@ class Chart { ExcelChartType.lineMarkersStacked, ExcelChartType.areaStacked, ExcelChartType.columnStacked3D, - ExcelChartType.barStacked3D + ExcelChartType.barStacked3D, ]; /// Represent 100% charts.Here each value in a series is shown as a portion of 100%. @@ -561,7 +561,8 @@ class Chart { if (dataRange == null && iCount != 0) { final Error error = ArgumentError( - 'This property supported only in chart where can detect data range.'); + 'This property supported only in chart where can detect data range.', + ); throw error; } @@ -984,7 +985,11 @@ class Chart { /// Finds the category range in the specified chart range. // ignore: unused_element Range _getCategoryRange( - Range chartValues, Range values, double count, bool bIsInRow) { + Range chartValues, + Range values, + double count, + bool bIsInRow, + ) { final int firstRow = chartValues.row; final int lastRow = chartValues.lastRow; final int firstColumn = chartValues.column; @@ -994,28 +999,57 @@ class Chart { values = chartValues; return chartValues; } - result = bIsInRow - ? chartValues.worksheet - .getRangeByIndex(firstRow, firstColumn, lastRow, firstColumn) - : chartValues.worksheet - .getRangeByIndex(firstRow, firstColumn, firstRow, lastColumn); + result = + bIsInRow + ? chartValues.worksheet.getRangeByIndex( + firstRow, + firstColumn, + lastRow, + firstColumn, + ) + : chartValues.worksheet.getRangeByIndex( + firstRow, + firstColumn, + firstRow, + lastColumn, + ); if (firstRow == lastRow && firstColumn == lastColumn) { values = result; } else if (firstRow == lastRow) { - values = bIsInRow - ? chartValues.worksheet - .getRangeByIndex(firstRow, firstColumn, lastRow, lastColumn) - : chartValues - ..worksheet.getRangeByIndex(firstRow, firstColumn, lastRow, lastColumn); + values = + bIsInRow + ? chartValues.worksheet.getRangeByIndex( + firstRow, + firstColumn, + lastRow, + lastColumn, + ) + : chartValues + ..worksheet.getRangeByIndex( + firstRow, + firstColumn, + lastRow, + lastColumn, + ); } else { - final int add = bIsInRow - ? (firstColumn == lastColumn ? 0 : 1) - : (firstRow == lastRow ? 0 : 1); - values = bIsInRow - ? chartValues.worksheet - .getRangeByIndex(firstRow, firstColumn + add, lastRow, lastColumn) - : chartValues.worksheet.getRangeByIndex( - firstRow + add, firstColumn, lastRow, lastColumn); + final int add = + bIsInRow + ? (firstColumn == lastColumn ? 0 : 1) + : (firstRow == lastRow ? 0 : 1); + values = + bIsInRow + ? chartValues.worksheet.getRangeByIndex( + firstRow, + firstColumn + add, + lastRow, + lastColumn, + ) + : chartValues.worksheet.getRangeByIndex( + firstRow + add, + firstColumn, + lastRow, + lastColumn, + ); } return result; } @@ -1029,8 +1063,11 @@ class Chart { Range? serieValue, serieNameRange, axisRange; - serieNameRange = - _getSerieOrAxisRange(_dataRange, _bSeriesInRows, serieValue); + serieNameRange = _getSerieOrAxisRange( + _dataRange, + _bSeriesInRows, + serieValue, + ); axisRange = _getSerieOrAxisRange(_serieValue, !_bSeriesInRows, _serieValue); // } if (!_validateSerieRangeForChartType(_serieValue, type, _bSeriesInRows)) { @@ -1042,13 +1079,19 @@ class Chart { int iIndex = 0; if (serieNameRange != null && axisRange != null) { - iIndex = _bSeriesInRows - ? axisRange.lastRow - axisRange.row + 1 - : axisRange.lastColumn - axisRange.column + 1; + iIndex = + _bSeriesInRows + ? axisRange.lastRow - axisRange.row + 1 + : axisRange.lastColumn - axisRange.column + 1; } _updateSeriesByDataRange( - _serieValue, serieNameRange, axisRange, iIndex, _bSeriesInRows); + _serieValue, + serieNameRange, + axisRange, + iIndex, + _bSeriesInRows, + ); } /// Gets data range that represents series name or category axis. @@ -1069,11 +1112,13 @@ class Chart { bool bIsName = false; for (int i = iFirsCount; i < iLastCount && !bIsName; i++) { - final Range curRange = bIsInRow - ? range.worksheet.getRangeByIndex(iRowColumn, i) - : range.worksheet.getRangeByIndex(i, iRowColumn); + final Range curRange = + bIsInRow + ? range.worksheet.getRangeByIndex(iRowColumn, i) + : range.worksheet.getRangeByIndex(i, iRowColumn); - bIsName = (curRange.number != null && + bIsName = + (curRange.number != null && curRange.dateTime == null && curRange.text == null) || (curRange.dateTime == null && @@ -1092,24 +1137,47 @@ class Chart { return null; } - final Range result = bIsInRow - ? range.worksheet - .getRangeByIndex(iFirstLen, iFirsCount, iRowColumn, iIndex) - : range.worksheet - .getRangeByIndex(iFirsCount, iFirstLen, iIndex, iRowColumn); - - serieRange = bIsInRow - ? range.worksheet.getRangeByIndex( - range.row, result.lastColumn + 1, range.lastRow, range.lastColumn) - : range.worksheet.getRangeByIndex( - result.lastRow + 1, range.column, range.lastRow, range.lastColumn); + final Range result = + bIsInRow + ? range.worksheet.getRangeByIndex( + iFirstLen, + iFirsCount, + iRowColumn, + iIndex, + ) + : range.worksheet.getRangeByIndex( + iFirsCount, + iFirstLen, + iIndex, + iRowColumn, + ); + + serieRange = + bIsInRow + ? range.worksheet.getRangeByIndex( + range.row, + result.lastColumn + 1, + range.lastRow, + range.lastColumn, + ) + : range.worksheet.getRangeByIndex( + result.lastRow + 1, + range.column, + range.lastRow, + range.lastColumn, + ); _serieValue = serieRange; return result; } /// Updates series value by data range. - void _updateSeriesByDataRange(Range? serieValue, Range? serieNameRange, - Range? axisRange, int iIndex, bool isSeriesInRows) { + void _updateSeriesByDataRange( + Range? serieValue, + Range? serieNameRange, + Range? axisRange, + int iIndex, + bool isSeriesInRows, + ) { Worksheet? sheet; if (serieValue != null) { sheet = serieValue.worksheet; @@ -1120,11 +1188,20 @@ class Chart { sheet ??= _worksheet; final int iLen = _series.count; for (int i = 0; i < iLen; i++) { - final Range value = isSeriesInRows - ? sheet.getRangeByIndex(serieValue!.row + i, serieValue.column, - serieValue.row + i, serieValue.lastColumn) - : sheet.getRangeByIndex(serieValue!.row, serieValue.column + i, - serieValue.lastRow, serieValue.column + i); + final Range value = + isSeriesInRows + ? sheet.getRangeByIndex( + serieValue!.row + i, + serieValue.column, + serieValue.row + i, + serieValue.lastColumn, + ) + : sheet.getRangeByIndex( + serieValue!.row, + serieValue.column + i, + serieValue.lastRow, + serieValue.column + i, + ); final ChartSerie serie = series[i]; serie.name = 'Serie${i + 1}'; @@ -1136,25 +1213,43 @@ class Chart { iAddIndex += isSeriesInRows ? serieNameRange.row : serieNameRange.column; - String? formula = isSeriesInRows - ? sheet - .getRangeByIndex(iAddIndex + i, serieNameRange.column, - iAddIndex + i, serieNameRange.lastColumn) - .addressGlobal - : sheet - .getRangeByIndex(serieNameRange.row, iAddIndex + i, - serieNameRange.lastRow, iAddIndex + i) - .addressGlobal; + String? formula = + isSeriesInRows + ? sheet + .getRangeByIndex( + iAddIndex + i, + serieNameRange.column, + iAddIndex + i, + serieNameRange.lastColumn, + ) + .addressGlobal + : sheet + .getRangeByIndex( + serieNameRange.row, + iAddIndex + i, + serieNameRange.lastRow, + iAddIndex + i, + ) + .addressGlobal; serie.nameOrFormula = formula; - formula = isSeriesInRows - ? sheet - .getRangeByIndex(iAddIndex + i, serieNameRange.column, - iAddIndex + i, serieNameRange.lastColumn) - .text - : sheet - .getRangeByIndex(serieNameRange.row, iAddIndex + i, - serieNameRange.lastRow, iAddIndex + i) - .text; + formula = + isSeriesInRows + ? sheet + .getRangeByIndex( + iAddIndex + i, + serieNameRange.column, + iAddIndex + i, + serieNameRange.lastColumn, + ) + .text + : sheet + .getRangeByIndex( + serieNameRange.row, + iAddIndex + i, + serieNameRange.lastRow, + iAddIndex + i, + ) + .text; serie.name = formula; } } @@ -1162,15 +1257,19 @@ class Chart { /// Validates Series range for min Series count of custom chart type. bool _validateSerieRangeForChartType( - Range? serieValue, ExcelChartType type, bool isSeriesInRows) { + Range? serieValue, + ExcelChartType type, + bool isSeriesInRows, + ) { if (serieValue == null) { final Error error = ArgumentError('serieValue - Value cannot be null'); throw error; } - final int iSeriesInRangeCount = isSeriesInRows - ? serieValue.lastRow - serieValue.row + 1 - : serieValue.lastColumn - serieValue.column + 1; + final int iSeriesInRangeCount = + isSeriesInRows + ? serieValue.lastRow - serieValue.row + 1 + : serieValue.lastColumn - serieValue.column + 1; final int iSeriesCount = _series.count; final bool bRemove = iSeriesCount > iSeriesInRangeCount; final int iStart = bRemove ? iSeriesInRangeCount : iSeriesCount; diff --git a/packages/syncfusion_officechart/lib/src/chart/chart_serialization.dart b/packages/syncfusion_officechart/lib/src/chart/chart_serialization.dart index 267a6dfb1..4f7a64657 100644 --- a/packages/syncfusion_officechart/lib/src/chart/chart_serialization.dart +++ b/packages/syncfusion_officechart/lib/src/chart/chart_serialization.dart @@ -26,7 +26,7 @@ class ChartSerialization { ExcelChartLinePattern.longDash: 'lgDash', ExcelChartLinePattern.dashDot: 'dashDot', ExcelChartLinePattern.longDashDot: 'lgDashDot', - ExcelChartLinePattern.longDashDotDot: 'lgDashDotDot' + ExcelChartLinePattern.longDashDotDot: 'lgDashDotDot', }; /// serializes charts from the worksheet. @@ -35,41 +35,66 @@ class ChartSerialization { sheet.workbook.chartCount++; final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('c:chartSpace', nest: () { - builder.attribute( - 'xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - builder.attribute('xmlns:c', - 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - - if (chart.hasPlotArea) { - builder.element('c:roundedCorners', nest: () { - builder.attribute('val', 0); - }); - } - builder.element('c:chart', nest: () { - if (chart.hasTitle) { - _serializeTitle(builder, chart.chartTitleArea); - } - if (chart.is3DChart) { - _serializeView3D(builder, chart); - } - _serializePlotArea(builder, chart); - if (chart.series.count > 0 && chart.hasLegend) { - _serializeLegend(builder, chart.legend!); + builder.element( + 'c:chartSpace', + nest: () { + builder.attribute( + 'xmlns:a', + 'http://schemas.openxmlformats.org/drawingml/2006/main', + ); + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + builder.attribute( + 'xmlns:c', + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + ); + + if (chart.hasPlotArea) { + builder.element( + 'c:roundedCorners', + nest: () { + builder.attribute('val', 0); + }, + ); } - builder.element('c:plotVisOnly', nest: () { - builder.attribute('val', '1'); - }); - builder.element('c:dispBlanksAs', nest: () { - builder.attribute('val', 'gap'); - }); - }); - _serializeFill( - builder, chart.linePattern, chart.linePatternColor, false); - _serializePrinterSettings(builder, chart); - }); + builder.element( + 'c:chart', + nest: () { + if (chart.hasTitle) { + _serializeTitle(builder, chart.chartTitleArea); + } + if (chart.is3DChart) { + _serializeView3D(builder, chart); + } + _serializePlotArea(builder, chart); + if (chart.series.count > 0 && chart.hasLegend) { + _serializeLegend(builder, chart.legend!); + } + builder.element( + 'c:plotVisOnly', + nest: () { + builder.attribute('val', '1'); + }, + ); + builder.element( + 'c:dispBlanksAs', + nest: () { + builder.attribute('val', 'gap'); + }, + ); + }, + ); + _serializeFill( + builder, + chart.linePattern, + chart.linePatternColor, + false, + ); + _serializePrinterSettings(builder, chart); + }, + ); final String stringXml = builder.buildDocument().copy().toString(); final List bytes = utf8.encode(stringXml); _addToArchive(bytes, 'xl/charts/chart${sheet.workbook.chartCount}.xml'); @@ -83,96 +108,162 @@ class ChartSerialization { /// serializes chart's legend. void _serializeLegend(XmlBuilder builder, ChartLegend chartLegend) { - builder.element('c:legend', nest: () { - builder.element('c:legendPos', nest: () { - final ExcelLegendPosition legendPostion = chartLegend.position; - final String positionStr = legendPostion == ExcelLegendPosition.bottom - ? 'b' - : legendPostion == ExcelLegendPosition.left - ? 'l' - : legendPostion == ExcelLegendPosition.right + builder.element( + 'c:legend', + nest: () { + builder.element( + 'c:legendPos', + nest: () { + final ExcelLegendPosition legendPostion = chartLegend.position; + final String positionStr = + legendPostion == ExcelLegendPosition.bottom + ? 'b' + : legendPostion == ExcelLegendPosition.left + ? 'l' + : legendPostion == ExcelLegendPosition.right ? 'r' : legendPostion == ExcelLegendPosition.top - ? 't' - : 'r'; - builder.attribute('val', positionStr); - }); - if (chartLegend.hasTextArea) { - _serializeDefaultTextAreaProperties(builder, chartLegend.textArea); - } - builder.element('c:layout', nest: () {}); - builder.element('c:overlay', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:spPr', nest: () {}); - }); + ? 't' + : 'r'; + builder.attribute('val', positionStr); + }, + ); + if (chartLegend.hasTextArea) { + _serializeDefaultTextAreaProperties(builder, chartLegend.textArea); + } + builder.element('c:layout', nest: () {}); + builder.element( + 'c:overlay', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element('c:spPr', nest: () {}); + }, + ); } /// serializes chart's drawing. void _serializeChartDrawing(XmlBuilder builder, Worksheet sheet) { for (final Chart chart in (sheet.charts! as ChartCollection).innerList) { - builder.element('xdr:twoCellAnchor', nest: () { - builder.attribute('editAs', 'twoCell'); - builder.element('xdr:from', nest: () { - builder.element('xdr:col', - nest: chart.leftColumn > 0 ? chart.leftColumn - 1 : 0); - builder.element('xdr:colOff', nest: 0); - builder.element('xdr:row', - nest: chart.topRow > 0 ? chart.topRow - 1 : 0); - builder.element('xdr:rowOff', nest: 0); - }); - - builder.element('xdr:to', nest: () { - builder.element('xdr:col', - nest: chart.rightColumn > 0 - ? chart.rightColumn - 1 - : chart.leftColumn + 7); - builder.element('xdr:colOff', nest: 0); - builder.element('xdr:row', - nest: chart.bottomRow > 0 - ? chart.bottomRow - 1 - : chart.topRow + 15); - builder.element('xdr:rowOff', nest: 0); - }); - - builder.element('xdr:graphicFrame', nest: () { - builder.attribute('macro', ''); - builder.element('xdr:nvGraphicFramePr', nest: () { - builder.element('xdr:cNvPr', nest: () { - builder.attribute( - 'id', 1024 + sheet.workbook.chartCount + chart.index); - builder.attribute( - 'name', 'Chart ${sheet.workbook.chartCount + chart.index}'); - }); - builder.element('xdr:cNvGraphicFramePr', nest: () {}); - }); - builder.element('xdr:xfrm', nest: () { - builder.element('a:off', nest: () { - builder.attribute('x', '0'); - builder.attribute('y', 0); - }); - builder.element('a:ext', nest: () { - builder.attribute('cx', '0'); - builder.attribute('cy', 0); - }); - }); - builder.element('a:graphic', nest: () { - builder.element('a:graphicData', nest: () { - builder.attribute('uri', - 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - - builder.element('c:chart', nest: () { - builder.attribute('p7:id', 'rId${chart.index}'); - builder.attribute('xmlns:p7', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - builder.attribute('xmlns:c', - 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - }); - }); - }); - }); - builder.element('xdr:clientData', nest: () {}); - }); + builder.element( + 'xdr:twoCellAnchor', + nest: () { + builder.attribute('editAs', 'twoCell'); + builder.element( + 'xdr:from', + nest: () { + builder.element( + 'xdr:col', + nest: chart.leftColumn > 0 ? chart.leftColumn - 1 : 0, + ); + builder.element('xdr:colOff', nest: 0); + builder.element( + 'xdr:row', + nest: chart.topRow > 0 ? chart.topRow - 1 : 0, + ); + builder.element('xdr:rowOff', nest: 0); + }, + ); + + builder.element( + 'xdr:to', + nest: () { + builder.element( + 'xdr:col', + nest: + chart.rightColumn > 0 + ? chart.rightColumn - 1 + : chart.leftColumn + 7, + ); + builder.element('xdr:colOff', nest: 0); + builder.element( + 'xdr:row', + nest: + chart.bottomRow > 0 + ? chart.bottomRow - 1 + : chart.topRow + 15, + ); + builder.element('xdr:rowOff', nest: 0); + }, + ); + + builder.element( + 'xdr:graphicFrame', + nest: () { + builder.attribute('macro', ''); + builder.element( + 'xdr:nvGraphicFramePr', + nest: () { + builder.element( + 'xdr:cNvPr', + nest: () { + builder.attribute( + 'id', + 1024 + sheet.workbook.chartCount + chart.index, + ); + builder.attribute( + 'name', + 'Chart ${sheet.workbook.chartCount + chart.index}', + ); + }, + ); + builder.element('xdr:cNvGraphicFramePr', nest: () {}); + }, + ); + builder.element( + 'xdr:xfrm', + nest: () { + builder.element( + 'a:off', + nest: () { + builder.attribute('x', '0'); + builder.attribute('y', 0); + }, + ); + builder.element( + 'a:ext', + nest: () { + builder.attribute('cx', '0'); + builder.attribute('cy', 0); + }, + ); + }, + ); + builder.element( + 'a:graphic', + nest: () { + builder.element( + 'a:graphicData', + nest: () { + builder.attribute( + 'uri', + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + ); + + builder.element( + 'c:chart', + nest: () { + builder.attribute('p7:id', 'rId${chart.index}'); + builder.attribute( + 'xmlns:p7', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + builder.attribute( + 'xmlns:c', + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + ); + }, + ); + }, + ); + }, + ); + }, + ); + builder.element('xdr:clientData', nest: () {}); + }, + ); } } @@ -183,132 +274,227 @@ class ChartSerialization { /// serialize default text area properties. void _serializeDefaultTextAreaProperties( - XmlBuilder builder, ChartTextArea textArea) { - builder.element('c:txPr', nest: () { - builder.element('a:bodyPr ', nest: () {}); - builder.element('a:lstStyle ', nest: () {}); - builder.element('a:p', nest: () { - builder.element('a:pPr', nest: () { - builder.element('a:defRPr', nest: () { - final double size = textArea.size * 100; - builder.attribute('sz', size.toInt().toString()); - builder.attribute('b', textArea.bold ? '1' : '0'); - builder.attribute('i', textArea.italic ? '1' : '0'); - if (textArea.color != '' && textArea.color != 'FF000000') { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', textArea.color.replaceAll('#', '')); - }); - }); - } - builder.element('a:latin', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:cs', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - }); - }); - builder.element('a:endParaRPr', nest: () { - builder.attribute('lang', 'en-US'); - }); - }); - }); + XmlBuilder builder, + ChartTextArea textArea, + ) { + builder.element( + 'c:txPr', + nest: () { + builder.element('a:bodyPr ', nest: () {}); + builder.element('a:lstStyle ', nest: () {}); + builder.element( + 'a:p', + nest: () { + builder.element( + 'a:pPr', + nest: () { + builder.element( + 'a:defRPr', + nest: () { + final double size = textArea.size * 100; + builder.attribute('sz', size.toInt().toString()); + builder.attribute('b', textArea.bold ? '1' : '0'); + builder.attribute('i', textArea.italic ? '1' : '0'); + if (textArea.color != '' && textArea.color != 'FF000000') { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute( + 'val', + textArea.color.replaceAll('#', ''), + ); + }, + ); + }, + ); + } + builder.element( + 'a:latin', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:cs', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + }, + ); + }, + ); + builder.element( + 'a:endParaRPr', + nest: () { + builder.attribute('lang', 'en-US'); + }, + ); + }, + ); + }, + ); } /// serialize printer settings of charts void _serializePrinterSettings(XmlBuilder builder, Chart chart) { - builder.element('c:printSettings', nest: () { - builder.element('c:headerFooter', nest: () { - builder.attribute('scaleWithDoc', '1'); - builder.attribute('alignWithMargins', '0'); - builder.attribute('differentFirst', '0'); - builder.attribute('differentOddEven', '0'); - }); - builder.element('c:pageMargins', nest: () { - builder.attribute('l', '0.7'); - builder.attribute('r', '0.7'); - builder.attribute('t', '0.75'); - builder.attribute('b', '0.75'); - builder.attribute('header', '0.3'); - builder.attribute('footer', '0.3'); - }); - }); + builder.element( + 'c:printSettings', + nest: () { + builder.element( + 'c:headerFooter', + nest: () { + builder.attribute('scaleWithDoc', '1'); + builder.attribute('alignWithMargins', '0'); + builder.attribute('differentFirst', '0'); + builder.attribute('differentOddEven', '0'); + }, + ); + builder.element( + 'c:pageMargins', + nest: () { + builder.attribute('l', '0.7'); + builder.attribute('r', '0.7'); + builder.attribute('t', '0.75'); + builder.attribute('b', '0.75'); + builder.attribute('header', '0.3'); + builder.attribute('footer', '0.3'); + }, + ); + }, + ); } /// serialize chart title. void _serializeTitle(XmlBuilder builder, ChartTextArea chartTextArea) { - builder.element('c:title', nest: () { - if (chartTextArea.hasText) { - builder.element('c:tx', nest: () { - builder.element('c:rich', nest: () { - builder.element('a:bodyPr ', nest: () {}); - builder.element('a:lstStyle', nest: () {}); - builder.element('a:p', nest: () { - builder.element('a:pPr', nest: () { - builder.attribute('algn', 'ctr'); - builder.element('a:defRPr', nest: () {}); - }); - builder.element('a:r', nest: () { - _serializeParagraphRunProperties(builder, chartTextArea); - builder.element('a:t', nest: () { - builder.text(chartTextArea.text!); - }); - }); - }); - }); - }); - } - builder.element('c:layout', nest: () {}); - builder.element('c:overlay', nest: () { - builder.attribute('val', chartTextArea.overlay ? '1' : '0'); - }); - _serializeFill(builder, ExcelChartLinePattern.none, null, false); - }); + builder.element( + 'c:title', + nest: () { + if (chartTextArea.hasText) { + builder.element( + 'c:tx', + nest: () { + builder.element( + 'c:rich', + nest: () { + builder.element('a:bodyPr ', nest: () {}); + builder.element('a:lstStyle', nest: () {}); + builder.element( + 'a:p', + nest: () { + builder.element( + 'a:pPr', + nest: () { + builder.attribute('algn', 'ctr'); + builder.element('a:defRPr', nest: () {}); + }, + ); + builder.element( + 'a:r', + nest: () { + _serializeParagraphRunProperties( + builder, + chartTextArea, + ); + builder.element( + 'a:t', + nest: () { + builder.text(chartTextArea.text!); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + builder.element('c:layout', nest: () {}); + builder.element( + 'c:overlay', + nest: () { + builder.attribute('val', chartTextArea.overlay ? '1' : '0'); + }, + ); + _serializeFill(builder, ExcelChartLinePattern.none, null, false); + }, + ); } /// serialize paragraph run properties. void _serializeParagraphRunProperties( - XmlBuilder builder, ChartTextArea textArea) { - builder.element('a:rPr', nest: () { - builder.attribute('lang', 'en-US'); - final double size = textArea.size * 100; - builder.attribute('sz', size.toInt().toString()); - builder.attribute('b', textArea.bold ? '1' : '0'); - builder.attribute('i', textArea.italic ? '1' : '0'); - builder.attribute('baseline', '0'); - if (textArea.color != '' && textArea.color != 'FF000000') { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', textArea.color.replaceAll('#', '')); - }); - }); - } - builder.element('a:latin', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:ea', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:cs', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - }); + XmlBuilder builder, + ChartTextArea textArea, + ) { + builder.element( + 'a:rPr', + nest: () { + builder.attribute('lang', 'en-US'); + final double size = textArea.size * 100; + builder.attribute('sz', size.toInt().toString()); + builder.attribute('b', textArea.bold ? '1' : '0'); + builder.attribute('i', textArea.italic ? '1' : '0'); + builder.attribute('baseline', '0'); + if (textArea.color != '' && textArea.color != 'FF000000') { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', textArea.color.replaceAll('#', '')); + }, + ); + }, + ); + } + builder.element( + 'a:latin', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:ea', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:cs', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + }, + ); } /// serialize plotarea of the chart void _serializePlotArea(XmlBuilder builder, Chart chart) { - builder.element('c:plotArea', nest: () { - builder.element('c:layout', nest: () {}); - if (chart.series.count > 0) { - _serializeMainChartTypeTag(builder, chart); - } else { - _serializeEmptyChart(builder, chart); - _serializeAxes(builder, chart); - } - _serializeFill(builder, chart.plotArea.linePattern, - chart.plotArea.linePatternColor, false); - }); + builder.element( + 'c:plotArea', + nest: () { + builder.element('c:layout', nest: () {}); + if (chart.series.count > 0) { + _serializeMainChartTypeTag(builder, chart); + } else { + _serializeEmptyChart(builder, chart); + _serializeAxes(builder, chart); + } + _serializeFill( + builder, + chart.plotArea.linePattern, + chart.plotArea.linePatternColor, + false, + ); + }, + ); } /// serializes main chart tag. @@ -378,87 +564,135 @@ class ChartSerialization { /// serializes Line chart. void _serializeLineChart(XmlBuilder builder, Chart chart) { final ExcelChartType type = chart.series[0].serieType; - builder.element('c:lineChart', nest: () { - _serializeChartGrouping(builder, chart); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - } - if (type == ExcelChartType.lineMarkers || - type == ExcelChartType.lineMarkersStacked || - type == ExcelChartType.lineMarkersStacked100) { - builder.element('c:marker', nest: () { - builder.attribute('val', 1); - }); - } - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:lineChart', + nest: () { + _serializeChartGrouping(builder, chart); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + } + if (type == ExcelChartType.lineMarkers || + type == ExcelChartType.lineMarkersStacked || + type == ExcelChartType.lineMarkersStacked100) { + builder.element( + 'c:marker', + nest: () { + builder.attribute('val', 1); + }, + ); + } + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxes(builder, chart); } /// serializes Bar/ColumnClustered chart. void _serializeBarChart(XmlBuilder builder, Chart chart) { late int gapwidth; - builder.element('c:barChart', nest: () { - final String strDirection = - chart.chartType.toString().contains('bar') ? 'bar' : 'col'; - builder.element('c:barDir', nest: () { - builder.attribute('val', strDirection); - }); - _serializeChartGrouping(builder, chart); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; - } - builder.element('c:gapWidth', nest: () { - builder.attribute('val', gapwidth); - }); - if (chart.getIsStacked(chart.chartType) || - chart.getIs100(chart.chartType)) { - builder.element('c:overlap', nest: () { - builder.attribute('val', '100'); - }); - } - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:barChart', + nest: () { + final String strDirection = + chart.chartType.toString().contains('bar') ? 'bar' : 'col'; + builder.element( + 'c:barDir', + nest: () { + builder.attribute('val', strDirection); + }, + ); + _serializeChartGrouping(builder, chart); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; + } + builder.element( + 'c:gapWidth', + nest: () { + builder.attribute('val', gapwidth); + }, + ); + if (chart.getIsStacked(chart.chartType) || + chart.getIs100(chart.chartType)) { + builder.element( + 'c:overlap', + nest: () { + builder.attribute('val', '100'); + }, + ); + } + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxes(builder, chart); } /// serializes Area chart. void _serializeAreaChart(XmlBuilder builder, Chart chart) { - builder.element('c:areaChart', nest: () { - _serializeChartGrouping(builder, chart); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - } - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:areaChart', + nest: () { + _serializeChartGrouping(builder, chart); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + } + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxes(builder, chart); } @@ -474,278 +708,482 @@ class ChartSerialization { } else { strGrouping = 'standard'; } - builder.element('c:grouping', nest: () { - builder.attribute('val', strGrouping); - }); + builder.element( + 'c:grouping', + nest: () { + builder.attribute('val', strGrouping); + }, + ); } /// serializes pie chart. void _serializePieChart(XmlBuilder builder, Chart chart) { - builder.element('c:pieChart', nest: () { - builder.element('c:varyColors', nest: () { - builder.attribute('val', 1); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - } - builder.element('c:firstSliceAng', nest: () { - builder.attribute('val', 0); - }); - }); + builder.element( + 'c:pieChart', + nest: () { + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 1); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + } + builder.element( + 'c:firstSliceAng', + nest: () { + builder.attribute('val', 0); + }, + ); + }, + ); } /// serializes series of chart. void _serializeSerie(XmlBuilder builder, ChartSerie firstSerie) { final ExcelChartType type = firstSerie.serieType; - builder.element('c:ser', nest: () { - builder.element('c:idx', nest: () { - builder.attribute('val', firstSerie.index); - }); - builder.element('c:order', nest: () { - builder.attribute('val', firstSerie.index); - }); - if (firstSerie.isDefaultName) { - builder.element('c:tx', nest: () { - final String strName = firstSerie.nameOrFormula; - if (strName.isNotEmpty) { - _serializeStringReference( - builder, strName, firstSerie, 'text', null); - } - }); - } - - if (firstSerie.serieFormat.pieExplosionPercent != 0 || - (type == ExcelChartType.doughnutExploded && - firstSerie.chart.series.count == 1)) { - builder.element('c:explosion', nest: () { - builder.attribute('val', firstSerie.serieFormat.pieExplosionPercent); - }); - } - if (type == ExcelChartType.stockOpenHighLowClose || - type == ExcelChartType.stockVolumeHighLowClose || - type == ExcelChartType.stockVolumeOpenHighLowClose) { - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () { - builder.element('a:noFill', nest: () {}); - }); - }); - } else if (type == ExcelChartType.stockHighLowClose) { - if (firstSerie.index == 2) { - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () { - builder.attribute('w', '3175'); - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', '000000'); - }); - }); - builder.element('a:prstDash', nest: () { - builder.attribute('val', 'solid'); - }); - }); - }); - } else { - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () { - builder.element('a:noFill', nest: () {}); - }); - }); + builder.element( + 'c:ser', + nest: () { + builder.element( + 'c:idx', + nest: () { + builder.attribute('val', firstSerie.index); + }, + ); + builder.element( + 'c:order', + nest: () { + builder.attribute('val', firstSerie.index); + }, + ); + if (firstSerie.isDefaultName) { + builder.element( + 'c:tx', + nest: () { + final String strName = firstSerie.nameOrFormula; + if (strName.isNotEmpty) { + _serializeStringReference( + builder, + strName, + firstSerie, + 'text', + null, + ); + } + }, + ); } - } - if (firstSerie.linePattern != ExcelChartLinePattern.none) { - _serializeFill( - builder, firstSerie.linePattern, firstSerie.linePatternColor, true); - } - - _serializeMarker(builder, firstSerie); - if (firstSerie.dataLabels.isValue) { - builder.element('c:dLbls', nest: () { - if (firstSerie.dataLabels.numberFormat != null && - firstSerie.dataLabels.numberFormat != '' && - firstSerie.dataLabels.numberFormat != 'General') { - builder.element('c:numFmt', nest: () { + if (firstSerie.serieFormat.pieExplosionPercent != 0 || + (type == ExcelChartType.doughnutExploded && + firstSerie.chart.series.count == 1)) { + builder.element( + 'c:explosion', + nest: () { builder.attribute( - 'formatCode', - // ignore: unnecessary_null_checks - firstSerie.dataLabels.numberFormat!); - builder.attribute('sourceLinked', '0'); - }); - } - builder.element('c:spPr', nest: () { - builder.element('a:noFill', nest: () {}); - builder.element('a:ln', nest: () { - builder.element('a:noFill', nest: () {}); - }); - builder.element('a:effectLst', nest: () {}); - }); - final ChartTextArea textArea = firstSerie.dataLabels.textArea; - _serializeChartTextArea(builder, textArea); - builder.element('c:showLegendKey', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showVal', nest: () { - builder.attribute('val', firstSerie.dataLabels.isValue ? 1 : 0); - }); - builder.element('c:showCatName', nest: () { - builder.attribute( - 'val', firstSerie.dataLabels.isCategoryName ? 1 : 0); - }); - builder.element('c:showSerName', nest: () { - builder.attribute( - 'val', firstSerie.dataLabels.isSeriesName ? 1 : 0); - }); - builder.element('c:showPercent', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showBubbleSize', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showLeaderLines', nest: () { - builder.attribute('val', 0); - }); - }); - } - if (firstSerie.categoryLabels != null) { - final Range firstRange = firstSerie.chart.worksheet.getRangeByIndex( - firstSerie.categoryLabels!.row, firstSerie.categoryLabels!.column); - builder.element('c:cat', nest: () { - Worksheet tempSheet = firstSerie.chart.worksheet; - if (firstSerie.categoryLabels!.addressGlobal != '') { - for (final Worksheet sheet - in firstSerie.chart.worksheet.workbook.worksheets.innerList) { - if (firstSerie.categoryLabels!.addressGlobal - .contains(RegExp('${sheet.name}!')) || - firstSerie.categoryLabels!.addressGlobal - .contains(RegExp("${sheet.name}'!"))) { - tempSheet = sheet; - break; - } - } - } - if (firstRange.text == null && firstRange.number != null) { - builder.element('c:numRef', nest: () { - builder.element('c:f', - nest: firstSerie.categoryLabels!.addressGlobal); - final Range firstRange = firstSerie.chart.worksheet - .getRangeByIndex(firstSerie.categoryLabels!.row, - firstSerie.categoryLabels!.column); - builder.element('c:numCache', nest: () { - if (firstRange.numberFormat != null && - firstRange.numberFormat != 'General') { - builder.element('c:formatCode', - nest: firstRange.numberFormat); - } - _serializeNumCacheValues(builder, firstSerie, tempSheet); - }); - }); + 'val', + firstSerie.serieFormat.pieExplosionPercent, + ); + }, + ); + } + if (type == ExcelChartType.stockOpenHighLowClose || + type == ExcelChartType.stockVolumeHighLowClose || + type == ExcelChartType.stockVolumeOpenHighLowClose) { + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:ln', + nest: () { + builder.element('a:noFill', nest: () {}); + }, + ); + }, + ); + } else if (type == ExcelChartType.stockHighLowClose) { + if (firstSerie.index == 2) { + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:ln', + nest: () { + builder.attribute('w', '3175'); + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', '000000'); + }, + ); + }, + ); + builder.element( + 'a:prstDash', + nest: () { + builder.attribute('val', 'solid'); + }, + ); + }, + ); + }, + ); } else { - _serializeStringReference( - builder, - firstSerie.categoryLabels!.addressGlobal, - firstSerie, - 'cat', - tempSheet); + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:ln', + nest: () { + builder.element('a:noFill', nest: () {}); + }, + ); + }, + ); } - }); - } - if (firstSerie.values != null) { - builder.element('c:val', nest: () { - builder.element('c:numRef', nest: () { - builder.element('c:f', nest: firstSerie.values!.addressGlobal); - final Range firstRange = firstSerie.chart.worksheet.getRangeByIndex( - firstSerie.values!.row, firstSerie.values!.column); - Worksheet tempSheet = firstSerie.chart.worksheet; - if (firstSerie.values!.addressGlobal != '') { - for (final Worksheet sheet - in firstSerie.chart.worksheet.workbook.worksheets.innerList) { - if (firstSerie.values!.addressGlobal - .contains(RegExp('${sheet.name}!')) || - firstSerie.values!.addressGlobal - .contains(RegExp("${sheet.name}'!"))) { - tempSheet = sheet; - break; + } + if (firstSerie.linePattern != ExcelChartLinePattern.none) { + _serializeFill( + builder, + firstSerie.linePattern, + firstSerie.linePatternColor, + true, + ); + } + + _serializeMarker(builder, firstSerie); + + if (firstSerie.dataLabels.isValue) { + builder.element( + 'c:dLbls', + nest: () { + if (firstSerie.dataLabels.numberFormat != null && + firstSerie.dataLabels.numberFormat != '' && + firstSerie.dataLabels.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () { + builder.attribute( + 'formatCode', + // ignore: unnecessary_null_checks + firstSerie.dataLabels.numberFormat!, + ); + builder.attribute('sourceLinked', '0'); + }, + ); + } + builder.element( + 'c:spPr', + nest: () { + builder.element('a:noFill', nest: () {}); + builder.element( + 'a:ln', + nest: () { + builder.element('a:noFill', nest: () {}); + }, + ); + builder.element('a:effectLst', nest: () {}); + }, + ); + final ChartTextArea textArea = firstSerie.dataLabels.textArea; + _serializeChartTextArea(builder, textArea); + builder.element( + 'c:showLegendKey', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showVal', + nest: () { + builder.attribute( + 'val', + firstSerie.dataLabels.isValue ? 1 : 0, + ); + }, + ); + builder.element( + 'c:showCatName', + nest: () { + builder.attribute( + 'val', + firstSerie.dataLabels.isCategoryName ? 1 : 0, + ); + }, + ); + builder.element( + 'c:showSerName', + nest: () { + builder.attribute( + 'val', + firstSerie.dataLabels.isSeriesName ? 1 : 0, + ); + }, + ); + builder.element( + 'c:showPercent', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showBubbleSize', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showLeaderLines', + nest: () { + builder.attribute('val', 0); + }, + ); + }, + ); + } + if (firstSerie.categoryLabels != null) { + final Range firstRange = firstSerie.chart.worksheet.getRangeByIndex( + firstSerie.categoryLabels!.row, + firstSerie.categoryLabels!.column, + ); + builder.element( + 'c:cat', + nest: () { + Worksheet tempSheet = firstSerie.chart.worksheet; + if (firstSerie.categoryLabels!.addressGlobal != '') { + for (final Worksheet sheet + in firstSerie + .chart + .worksheet + .workbook + .worksheets + .innerList) { + if (firstSerie.categoryLabels!.addressGlobal.contains( + RegExp('${sheet.name}!'), + ) || + firstSerie.categoryLabels!.addressGlobal.contains( + RegExp("${sheet.name}'!"), + )) { + tempSheet = sheet; + break; + } } } - } - builder.element('c:numCache', nest: () { - if (firstRange.numberFormat != null && - firstRange.numberFormat != 'General') { - builder.element('c:formatCode', nest: firstRange.numberFormat); + if (firstRange.text == null && firstRange.number != null) { + builder.element( + 'c:numRef', + nest: () { + builder.element( + 'c:f', + nest: firstSerie.categoryLabels!.addressGlobal, + ); + final Range firstRange = firstSerie.chart.worksheet + .getRangeByIndex( + firstSerie.categoryLabels!.row, + firstSerie.categoryLabels!.column, + ); + builder.element( + 'c:numCache', + nest: () { + if (firstRange.numberFormat != null && + firstRange.numberFormat != 'General') { + builder.element( + 'c:formatCode', + nest: firstRange.numberFormat, + ); + } + _serializeNumCacheValues( + builder, + firstSerie, + tempSheet, + ); + }, + ); + }, + ); } else { - builder.element('c:formatCode', nest: 'General'); + _serializeStringReference( + builder, + firstSerie.categoryLabels!.addressGlobal, + firstSerie, + 'cat', + tempSheet, + ); } - _serializeNumCacheValues(builder, firstSerie, tempSheet); - }); - }); - }); - } - if (firstSerie.serieType.toString().contains('line') || - firstSerie.serieType.toString().contains('stock')) { - builder.element('c:smooth', nest: () { - builder.attribute('val', 0); - }); - } - }); + }, + ); + } + if (firstSerie.values != null) { + builder.element( + 'c:val', + nest: () { + builder.element( + 'c:numRef', + nest: () { + builder.element( + 'c:f', + nest: firstSerie.values!.addressGlobal, + ); + final Range firstRange = firstSerie.chart.worksheet + .getRangeByIndex( + firstSerie.values!.row, + firstSerie.values!.column, + ); + Worksheet tempSheet = firstSerie.chart.worksheet; + if (firstSerie.values!.addressGlobal != '') { + for (final Worksheet sheet + in firstSerie + .chart + .worksheet + .workbook + .worksheets + .innerList) { + if (firstSerie.values!.addressGlobal.contains( + RegExp('${sheet.name}!'), + ) || + firstSerie.values!.addressGlobal.contains( + RegExp("${sheet.name}'!"), + )) { + tempSheet = sheet; + break; + } + } + } + builder.element( + 'c:numCache', + nest: () { + if (firstRange.numberFormat != null && + firstRange.numberFormat != 'General') { + builder.element( + 'c:formatCode', + nest: firstRange.numberFormat, + ); + } else { + builder.element('c:formatCode', nest: 'General'); + } + _serializeNumCacheValues(builder, firstSerie, tempSheet); + }, + ); + }, + ); + }, + ); + } + if (firstSerie.serieType.toString().contains('line') || + firstSerie.serieType.toString().contains('stock')) { + builder.element( + 'c:smooth', + nest: () { + builder.attribute('val', 0); + }, + ); + } + }, + ); } /// serializes chart text area. void _serializeChartTextArea(XmlBuilder builder, ChartTextArea textArea) { - builder.element('c:txPr', nest: () { - builder.element('a:bodyPr ', nest: () {}); - builder.element('a:lstStyle', nest: () {}); - builder.element('a:p', nest: () { - builder.element('a:pPr', nest: () { - builder.element('a:defRPr', nest: () { - final double size = textArea.size * 100; - builder.attribute('sz', size.toInt().toString()); - builder.attribute('b', textArea.bold ? '1' : '0'); - builder.attribute('i', textArea.italic ? '1' : '0'); - builder.attribute('baseline', '0'); - if (textArea.color != '' && textArea.color != 'FF000000') { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', textArea.color.replaceAll('#', '')); - }); - }); - } - builder.element('a:latin', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:ea', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:cs', nest: () { - builder.attribute('typeface', textArea.fontName); - }); - }); - }); - }); - }); + builder.element( + 'c:txPr', + nest: () { + builder.element('a:bodyPr ', nest: () {}); + builder.element('a:lstStyle', nest: () {}); + builder.element( + 'a:p', + nest: () { + builder.element( + 'a:pPr', + nest: () { + builder.element( + 'a:defRPr', + nest: () { + final double size = textArea.size * 100; + builder.attribute('sz', size.toInt().toString()); + builder.attribute('b', textArea.bold ? '1' : '0'); + builder.attribute('i', textArea.italic ? '1' : '0'); + builder.attribute('baseline', '0'); + if (textArea.color != '' && textArea.color != 'FF000000') { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute( + 'val', + textArea.color.replaceAll('#', ''), + ); + }, + ); + }, + ); + } + builder.element( + 'a:latin', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:ea', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:cs', + nest: () { + builder.attribute('typeface', textArea.fontName); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); } /// serializes number cache values. void _serializeNumCacheValues( - XmlBuilder builder, ChartSerie firstSerie, Worksheet dataSheet) { + XmlBuilder builder, + ChartSerie firstSerie, + Worksheet dataSheet, + ) { final Range? serieRange = firstSerie.values; if (serieRange != null) { final int count = serieRange.count; final int serieStartRow = serieRange.row; final int serieStartColumn = serieRange.column; - builder.element('c:ptCount', nest: () { - builder.attribute('val', count); - }); + builder.element( + 'c:ptCount', + nest: () { + builder.attribute('val', count); + }, + ); int index = 0; while (index < count) { - final double? value = dataSheet - .getRangeByIndex(serieStartRow + index, serieStartColumn) - .number; + final double? value = + dataSheet + .getRangeByIndex(serieStartRow + index, serieStartColumn) + .number; if (value != null) { - builder.element('c:pt', nest: () { - builder.attribute('idx', index); - builder.element('c:v', nest: value); - }); + builder.element( + 'c:pt', + nest: () { + builder.attribute('idx', index); + builder.element('c:v', nest: value); + }, + ); } index++; } @@ -753,44 +1191,65 @@ class ChartSerialization { } /// serializes string cache reference. - void _serializeStringReference(XmlBuilder builder, String range, - ChartSerie firstSerie, String tagName, Worksheet? dataSheet) { - builder.element('c:strRef', nest: () { - builder.element('c:f', nest: range); - builder.element('c:strCache', nest: () { - if (tagName == 'cat') { - _serializeCategoryTagCacheValues(builder, firstSerie, dataSheet); - } else { - _serializeTextTagCacheValues(builder, firstSerie); - } - }); - }); + void _serializeStringReference( + XmlBuilder builder, + String range, + ChartSerie firstSerie, + String tagName, + Worksheet? dataSheet, + ) { + builder.element( + 'c:strRef', + nest: () { + builder.element('c:f', nest: range); + builder.element( + 'c:strCache', + nest: () { + if (tagName == 'cat') { + _serializeCategoryTagCacheValues(builder, firstSerie, dataSheet); + } else { + _serializeTextTagCacheValues(builder, firstSerie); + } + }, + ); + }, + ); } /// serializes catergory cache values. void _serializeCategoryTagCacheValues( - XmlBuilder builder, ChartSerie firstSerie, Worksheet? dataSheet) { + XmlBuilder builder, + ChartSerie firstSerie, + Worksheet? dataSheet, + ) { // ignore: unnecessary_nullable_for_final_variable_declarations final Range? serieRange = firstSerie.categoryLabels; if (serieRange != null) { final int count = serieRange.count; final int serieStartRow = serieRange.row; final int serieStartColumn = serieRange.column; - builder.element('c:ptCount', nest: () { - builder.attribute('val', count); - }); + builder.element( + 'c:ptCount', + nest: () { + builder.attribute('val', count); + }, + ); int index = 0; while (index < count) { - final String? value = dataSheet != null - ? dataSheet - .getRangeByIndex(serieStartRow + index, serieStartColumn) - .text - : ''; + final String? value = + dataSheet != null + ? dataSheet + .getRangeByIndex(serieStartRow + index, serieStartColumn) + .text + : ''; if (value != null) { - builder.element('c:pt', nest: () { - builder.attribute('idx', index); - builder.element('c:v', nest: value); - }); + builder.element( + 'c:pt', + nest: () { + builder.attribute('idx', index); + builder.element('c:v', nest: value); + }, + ); } index++; } @@ -799,52 +1258,86 @@ class ChartSerialization { /// serializes text cache values. void _serializeTextTagCacheValues(XmlBuilder builder, ChartSerie firstSerie) { - builder.element('c:ptCount', nest: () { - builder.attribute('val', 1); - }); - builder.element('c:pt', nest: () { - builder.attribute('idx', 0); - if (firstSerie.name != null) { - builder.element('c:v', nest: firstSerie.name); - } - }); + builder.element( + 'c:ptCount', + nest: () { + builder.attribute('val', 1); + }, + ); + builder.element( + 'c:pt', + nest: () { + builder.attribute('idx', 0); + if (firstSerie.name != null) { + builder.element('c:v', nest: firstSerie.name); + } + }, + ); } /// serializes fill for the charts. - void _serializeFill(XmlBuilder builder, ExcelChartLinePattern linePattern, - String? lineColor, bool hasSerie) { - builder.element('c:spPr', nest: () { - if (lineColor == null) { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', 'FFFFFF'); - }); - }); - } - builder.element('a:ln', nest: () { - if (linePattern != ExcelChartLinePattern.none) { - if (!hasSerie || lineColor != null) { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - if (lineColor != null) { - builder.attribute('val', lineColor.replaceAll('#', '')); - } else { - builder.attribute('val', '0070C0'); - } - }); - }); - } - if (linePattern != ExcelChartLinePattern.solid) { - builder.element('a:prstDash', nest: () { - builder.attribute('val', _linePattern[linePattern]); - }); - } - } else { - builder.element('a:noFill', nest: () {}); + void _serializeFill( + XmlBuilder builder, + ExcelChartLinePattern linePattern, + String? lineColor, + bool hasSerie, + ) { + builder.element( + 'c:spPr', + nest: () { + if (lineColor == null) { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', 'FFFFFF'); + }, + ); + }, + ); } - builder.element('a:round', nest: () {}); - }); - }); + builder.element( + 'a:ln', + nest: () { + if (linePattern != ExcelChartLinePattern.none) { + if (!hasSerie || lineColor != null) { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + if (lineColor != null) { + builder.attribute( + 'val', + lineColor.replaceAll('#', ''), + ); + } else { + builder.attribute('val', '0070C0'); + } + }, + ); + }, + ); + } + if (linePattern != ExcelChartLinePattern.solid) { + builder.element( + 'a:prstDash', + nest: () { + builder.attribute('val', _linePattern[linePattern]); + }, + ); + } + } else { + builder.element('a:noFill', nest: () {}); + } + builder.element('a:round', nest: () {}); + }, + ); + }, + ); } /// serializes axies of the series. @@ -859,179 +1352,323 @@ class ChartSerialization { /// serializes empty charts. void _serializeEmptyChart(XmlBuilder builder, Chart chart) { - builder.element('c:barChart', nest: () { - builder.element('c:barDir', nest: () { - builder.attribute('val', 'col'); - }); - builder.element('c:grouping', nest: () { - builder.attribute('val', 'clustered'); - }); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - _serializeEmptyChartDataLabels(builder); - builder.element('c:gapWidth', nest: () { - builder.attribute('val', 150); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:barChart', + nest: () { + builder.element( + 'c:barDir', + nest: () { + builder.attribute('val', 'col'); + }, + ); + builder.element( + 'c:grouping', + nest: () { + builder.attribute('val', 'clustered'); + }, + ); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + _serializeEmptyChartDataLabels(builder); + builder.element( + 'c:gapWidth', + nest: () { + builder.attribute('val', 150); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + }, + ); } /// serializes category axis of the chart. void _serializeCategoryAxis(XmlBuilder builder, ChartCategoryAxis axis) { - builder.element('c:catAx', nest: () { - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:scaling', nest: () { - builder.element('c:orientation', nest: () { - builder.attribute('val', 'minMax'); - }); - }); - builder.element('c:delete', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:axPos', nest: () { - builder.attribute('val', 'b'); - }); - if (axis.hasAxisTitle) { - _serializeChartTextArea(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - builder.element('c:majorTickMark', nest: () { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () {}); - }); - builder.element('c:crossAx', nest: () { - builder.attribute('val', 57253888); - }); - builder.element('c:crosses', nest: () { - builder.attribute('val', 'autoZero'); - }); - builder.element('c:auto', nest: () { - builder.attribute('val', 1); - }); - builder.element('c:lblAlgn', nest: () { - builder.attribute('val', 'ctr'); - }); - builder.element('c:lblOffset', nest: () { - builder.attribute('val', 100); - }); - builder.element('c:noMultiLvlLbl', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:tickMarkSkip', nest: () { - builder.attribute('val', 1); - }); - }); + builder.element( + 'c:catAx', + nest: () { + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:scaling', + nest: () { + builder.element( + 'c:orientation', + nest: () { + builder.attribute('val', 'minMax'); + }, + ); + }, + ); + builder.element( + 'c:delete', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:axPos', + nest: () { + builder.attribute('val', 'b'); + }, + ); + if (axis.hasAxisTitle) { + _serializeChartTextArea(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + builder.element( + 'c:majorTickMark', + nest: () { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () { + builder.element('a:ln', nest: () {}); + }, + ); + builder.element( + 'c:crossAx', + nest: () { + builder.attribute('val', 57253888); + }, + ); + builder.element( + 'c:crosses', + nest: () { + builder.attribute('val', 'autoZero'); + }, + ); + builder.element( + 'c:auto', + nest: () { + builder.attribute('val', 1); + }, + ); + builder.element( + 'c:lblAlgn', + nest: () { + builder.attribute('val', 'ctr'); + }, + ); + builder.element( + 'c:lblOffset', + nest: () { + builder.attribute('val', 100); + }, + ); + builder.element( + 'c:noMultiLvlLbl', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:tickMarkSkip', + nest: () { + builder.attribute('val', 1); + }, + ); + }, + ); } /// serializes Value axis of the chart. void _serializeValueAxis(XmlBuilder builder, ChartValueAxis axis) { - builder.element('c:valAx', nest: () { - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - builder.element('c:scaling', nest: () { - builder.element('c:orientation', nest: () { - builder.attribute('val', 'minMax'); - }); - if (!axis.isAutoMax) { - builder.element('c:max', nest: () { - builder.attribute('val', axis.maximumValue); - }); - } - if (axis.isAutoMin) { - builder.element('c:min', nest: () { - builder.attribute('val', axis.minimumValue); - }); - } - }); - builder.element('c:delete', nest: () { - builder.attribute('val', '0'); - }); - builder.element('c:axPos', nest: () { - builder.attribute('val', 'l'); - }); - if (axis.hasAxisTitle) { - _serializeChartTextArea(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - if (axis.hasMajorGridLines) { - builder.element('c:majorGridlines', nest: () {}); - } - builder.element('c:majorTickMark', nest: () { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () {}); - }); - builder.element('c:crossAx', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:crosses', nest: () { - builder.attribute('val', 'autoZero'); - }); - final Chart chart = axis.parentChart; - final String strCrossBetween = - chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; - builder.element('c:crossBetween', nest: () { - builder.attribute('val', strCrossBetween); - }); - }); + builder.element( + 'c:valAx', + nest: () { + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + builder.element( + 'c:scaling', + nest: () { + builder.element( + 'c:orientation', + nest: () { + builder.attribute('val', 'minMax'); + }, + ); + if (!axis.isAutoMax) { + builder.element( + 'c:max', + nest: () { + builder.attribute('val', axis.maximumValue); + }, + ); + } + if (axis.isAutoMin) { + builder.element( + 'c:min', + nest: () { + builder.attribute('val', axis.minimumValue); + }, + ); + } + }, + ); + builder.element( + 'c:delete', + nest: () { + builder.attribute('val', '0'); + }, + ); + builder.element( + 'c:axPos', + nest: () { + builder.attribute('val', 'l'); + }, + ); + if (axis.hasAxisTitle) { + _serializeChartTextArea(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + if (axis.hasMajorGridLines) { + builder.element('c:majorGridlines', nest: () {}); + } + builder.element( + 'c:majorTickMark', + nest: () { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () { + builder.element('a:ln', nest: () {}); + }, + ); + builder.element( + 'c:crossAx', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:crosses', + nest: () { + builder.attribute('val', 'autoZero'); + }, + ); + final Chart chart = axis.parentChart; + final String strCrossBetween = + chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; + builder.element( + 'c:crossBetween', + nest: () { + builder.attribute('val', strCrossBetween); + }, + ); + }, + ); } /// serializes empty chart's datalabels. void _serializeEmptyChartDataLabels(XmlBuilder builder) { - builder.element('c:dLbls', nest: () { - builder.element('c:showLegendKey', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showVal', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showCatName', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showSerName', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showPercent', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:showBubbleSize', nest: () { - builder.attribute('val', 0); - }); - }); + builder.element( + 'c:dLbls', + nest: () { + builder.element( + 'c:showLegendKey', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showVal', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showCatName', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showSerName', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showPercent', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showBubbleSize', + nest: () { + builder.attribute('val', 0); + }, + ); + }, + ); } /// Add the workbook data with filename to ZipArchive. @@ -1043,29 +1680,47 @@ class ChartSerialization { /// Serialize line 3D Chart. void _serializeLine3DChart(XmlBuilder builder, Chart chart) { late int gapdepth; - builder.element('c:line3DChart', nest: () { - _serializeChartGrouping(builder, chart); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; - } - builder.element('c:gapDepth', nest: () { - builder.attribute('val', gapdepth); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 63149376); - }); - }); + builder.element( + 'c:line3DChart', + nest: () { + _serializeChartGrouping(builder, chart); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; + } + builder.element( + 'c:gapDepth', + nest: () { + builder.attribute('val', gapdepth); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 63149376); + }, + ); + }, + ); _serializeAxes(builder, chart); } @@ -1073,77 +1728,116 @@ class ChartSerialization { void _serializeView3D(XmlBuilder builder, Chart chart) { final ChartSeriesCollection firstSerie = chart.series; - builder.element('c:view3D', nest: () { - if (!chart.isdefaultElevation) { - builder.element('c:rotX', nest: () { - builder.attribute('val', chart.elevation); - }); - } - if (firstSerie.innerList[0].serieType == ExcelChartType.pie3D) { - for (int i = 0; i < chart.series.count; i++) { - chart.rotation = - chart.series[i].serieFormat.commonSerieOptions.firstSliceAngle; + builder.element( + 'c:view3D', + nest: () { + if (!chart.isdefaultElevation) { + builder.element( + 'c:rotX', + nest: () { + builder.attribute('val', chart.elevation); + }, + ); } - } - if (!chart.isDefaultRotation) { - builder.element('c:rotY', nest: () { - builder.attribute('val', chart.rotation); - }); - } - builder.element('c:depthPercent', nest: () { - builder.attribute('val', chart.depthPercent); - }); - builder.element('c:rAngAx', nest: () { - int defaultValue = 0; - - if (chart.rightAngleAxes || chart.isColumnOrBar) { - defaultValue = 1; + if (firstSerie.innerList[0].serieType == ExcelChartType.pie3D) { + for (int i = 0; i < chart.series.count; i++) { + chart.rotation = + chart.series[i].serieFormat.commonSerieOptions.firstSliceAngle; + } } + if (!chart.isDefaultRotation) { + builder.element( + 'c:rotY', + nest: () { + builder.attribute('val', chart.rotation); + }, + ); + } + builder.element( + 'c:depthPercent', + nest: () { + builder.attribute('val', chart.depthPercent); + }, + ); + builder.element( + 'c:rAngAx', + nest: () { + int defaultValue = 0; + + if (chart.rightAngleAxes || chart.isColumnOrBar) { + defaultValue = 1; + } - builder.attribute('val', defaultValue); - }); - builder.element('perspective', nest: () { - builder.attribute('val', chart.perspective * 2); - }); - }); + builder.attribute('val', defaultValue); + }, + ); + builder.element( + 'perspective', + nest: () { + builder.attribute('val', chart.perspective * 2); + }, + ); + }, + ); } /// Serialize bar3D chart. void _serializeBar3DChart(XmlBuilder builder, Chart chart) { late int gapdepth; late int gapwidth; - builder.element('c:bar3DChart', nest: () { - final String strDirection = - chart.chartType.toString().contains('bar') ? 'bar' : 'col'; - - builder.element('c:barDir', nest: () { - builder.attribute('val', strDirection); - }); - - _serializeChartGrouping(builder, chart); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; - gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; - } + builder.element( + 'c:bar3DChart', + nest: () { + final String strDirection = + chart.chartType.toString().contains('bar') ? 'bar' : 'col'; + + builder.element( + 'c:barDir', + nest: () { + builder.attribute('val', strDirection); + }, + ); + + _serializeChartGrouping(builder, chart); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; + gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; + } - builder.element('c:gapWidth', nest: () { - builder.attribute('val', gapwidth); - }); - builder.element('c:gapDepth', nest: () { - builder.attribute('val', gapdepth); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:gapWidth', + nest: () { + builder.attribute('val', gapwidth); + }, + ); + builder.element( + 'c:gapDepth', + nest: () { + builder.attribute('val', gapdepth); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxes(builder, chart); } @@ -1158,46 +1852,74 @@ class ChartSerialization { } else if (type == ExcelChartType.pieBar) { isPieOrBar = 'bar'; } - builder.element('c:ofPieChart', nest: () { - builder.element('c:ofPieType', nest: () { - builder.attribute('val', isPieOrBar); - }); - builder.element('c:varyColors', nest: () { - builder.attribute('val', 1); - }); + builder.element( + 'c:ofPieChart', + nest: () { + builder.element( + 'c:ofPieType', + nest: () { + builder.attribute('val', isPieOrBar); + }, + ); + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 1); + }, + ); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - pieSecondSize = firstSerie.serieFormat.commonSerieOptions.pieSecondSize; - gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; - } + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + pieSecondSize = + firstSerie.serieFormat.commonSerieOptions.pieSecondSize; + gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; + } - builder.element('c:gapWidth', nest: () { - builder.attribute('val', gapwidth); - }); - builder.element('c:secondPieSize', nest: () { - builder.attribute('val', pieSecondSize); - }); - builder.element('c:serLines', nest: () { - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () {}); - }); - }); - }); + builder.element( + 'c:gapWidth', + nest: () { + builder.attribute('val', gapwidth); + }, + ); + builder.element( + 'c:secondPieSize', + nest: () { + builder.attribute('val', pieSecondSize); + }, + ); + builder.element( + 'c:serLines', + nest: () { + builder.element( + 'c:spPr', + nest: () { + builder.element('a:ln', nest: () {}); + }, + ); + }, + ); + }, + ); } ///Serialize pie 3D chart. void _serializeOfPie3DChart(XmlBuilder builder, Chart chart) { - builder.element('c:pie3DChart', nest: () { - builder.element('c:varyColors', nest: () { - builder.attribute('val', 1); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - } - }); + builder.element( + 'c:pie3DChart', + nest: () { + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 1); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + } + }, + ); } /// Serializes stock chart. @@ -1205,106 +1927,189 @@ class ChartSerialization { final ExcelChartType type = chart.series.innerList[0].serieType; if (type == ExcelChartType.stockVolumeOpenHighLowClose || type == ExcelChartType.stockVolumeHighLowClose) { - builder.element('c:barChart', nest: () { - builder.element('c:barDir', nest: () { - builder.attribute('val', 'col'); - }); - builder.element('c:grouping', nest: () { - builder.attribute('val', 'clustered'); - }); - - builder.element('c:varyColors', nest: () { - builder.attribute('val', 0); - }); - - final ChartSerie firstSerie = chart.series[0]; - _serializeSerie(builder, firstSerie); - - builder.element('c:gapWidth', nest: () { - builder.attribute( - 'val', firstSerie.serieFormat.commonSerieOptions.gapWidth); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 57253888); - }); - }); - } - builder.element('c:stockChart', nest: () { - if (type == ExcelChartType.stockHighLowClose || - type == ExcelChartType.stockOpenHighLowClose) { - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; + builder.element( + 'c:barChart', + nest: () { + builder.element( + 'c:barDir', + nest: () { + builder.attribute('val', 'col'); + }, + ); + builder.element( + 'c:grouping', + nest: () { + builder.attribute('val', 'clustered'); + }, + ); + + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 0); + }, + ); + + final ChartSerie firstSerie = chart.series[0]; _serializeSerie(builder, firstSerie); - } - } else if (type == ExcelChartType.stockVolumeHighLowClose || - type == ExcelChartType.stockVolumeOpenHighLowClose) { - for (int i = 0; i < chart.series.count; i++) { - if ((type == ExcelChartType.stockVolumeOpenHighLowClose || - type == ExcelChartType.stockVolumeHighLowClose) && - chart.series.innerList[0] != chart.series.innerList[i]) { + + builder.element( + 'c:gapWidth', + nest: () { + builder.attribute( + 'val', + firstSerie.serieFormat.commonSerieOptions.gapWidth, + ); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 57253888); + }, + ); + }, + ); + } + builder.element( + 'c:stockChart', + nest: () { + if (type == ExcelChartType.stockHighLowClose || + type == ExcelChartType.stockOpenHighLowClose) { + for (int i = 0; i < chart.series.count; i++) { final ChartSerie firstSerie = chart.series[i]; _serializeSerie(builder, firstSerie); } + } else if (type == ExcelChartType.stockVolumeHighLowClose || + type == ExcelChartType.stockVolumeOpenHighLowClose) { + for (int i = 0; i < chart.series.count; i++) { + if ((type == ExcelChartType.stockVolumeOpenHighLowClose || + type == ExcelChartType.stockVolumeHighLowClose) && + chart.series.innerList[0] != chart.series.innerList[i]) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + } + } } - } - builder.element('c:hiLowLines', nest: () { - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', '000000'); - }); - }); - builder.element('a:prstDash', nest: () { - builder.attribute('val', 'solid'); - }); - }); - }); - }); - if (type == ExcelChartType.stockOpenHighLowClose || - type == ExcelChartType.stockVolumeOpenHighLowClose) { - builder.element('c:upDownBars', nest: () { - builder.element('c:gapWidth', nest: () { - builder.attribute('val', '100'); - }); - builder.element('c:upBars', nest: () { - builder.element('c:spPr', nest: () { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', 'FFFFFF'); - }); - }); - }); - }); - builder.element('c:downBars', nest: () { - builder.element('c:spPr', nest: () { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', '000000'); - }); - }); - }); - }); - }); - } - if (chart.series[0].serieFormat.markerStyle != - ExcelChartMarkerType.none) { - builder.element('c:marker', nest: () { - builder.attribute('val', 1); - }); - } + builder.element( + 'c:hiLowLines', + nest: () { + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:ln', + nest: () { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', '000000'); + }, + ); + }, + ); + builder.element( + 'a:prstDash', + nest: () { + builder.attribute('val', 'solid'); + }, + ); + }, + ); + }, + ); + }, + ); + if (type == ExcelChartType.stockOpenHighLowClose || + type == ExcelChartType.stockVolumeOpenHighLowClose) { + builder.element( + 'c:upDownBars', + nest: () { + builder.element( + 'c:gapWidth', + nest: () { + builder.attribute('val', '100'); + }, + ); + builder.element( + 'c:upBars', + nest: () { + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', 'FFFFFF'); + }, + ); + }, + ); + }, + ); + }, + ); + builder.element( + 'c:downBars', + nest: () { + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', '000000'); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + if (chart.series[0].serieFormat.markerStyle != + ExcelChartMarkerType.none) { + builder.element( + 'c:marker', + nest: () { + builder.attribute('val', 1); + }, + ); + } - builder.element('c:axId', nest: () { - builder.attribute('val', 62908672); - }); - builder.element('c:axId', nest: () { - builder.attribute('val', 61870848); - }); - }); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 62908672); + }, + ); + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', 61870848); + }, + ); + }, + ); if (type == ExcelChartType.stockVolumeOpenHighLowClose || type == ExcelChartType.stockVolumeHighLowClose) { _serializeAxesforStockChart(builder, chart, 59983360, 57253888, true); @@ -1316,170 +2121,300 @@ class ChartSerialization { ///serialize stock axes void _serializeAxesforStockChart( - XmlBuilder builder, Chart chart, int axisId, int crossAx, bool isBar) { + XmlBuilder builder, + Chart chart, + int axisId, + int crossAx, + bool isBar, + ) { if (chart.isCategoryAxisAvail) { _serializeCategoryAxisForStock( - builder, chart.primaryCategoryAxis, axisId, crossAx, isBar); + builder, + chart.primaryCategoryAxis, + axisId, + crossAx, + isBar, + ); } if (chart.isValueAxisAvail) { _serializeValueAxisForStockchart( - builder, chart.primaryCategoryAxis, axisId, crossAx, isBar); + builder, + chart.primaryCategoryAxis, + axisId, + crossAx, + isBar, + ); } } ///Serialize catogory axis for stock chart - void _serializeCategoryAxisForStock(XmlBuilder builder, - ChartCategoryAxis axis, int axisId, int crossAx, bool isBar) { - builder.element('c:catAx', nest: () { - builder.element('c:axId', nest: () { - builder.attribute('val', axisId); - }); - builder.element('c:scaling', nest: () { - builder.element('c:orientation', nest: () { - builder.attribute('val', 'minMax'); - }); - }); - int delete = 0; - String axpos = 'b'; - if (!isBar) { - delete = 1; - axpos = 't'; - } - builder.element('c:delete', nest: () { - builder.attribute('val', delete); - }); - builder.element('c:axPos', nest: () { - builder.attribute('val', axpos); - }); - if (axis.hasAxisTitle) { - _serializeChartTextArea(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - builder.element('c:majorTickMark', nest: () { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () { - if (!isBar) { - builder.attribute('w', 12700); - } - }); - }); - builder.element('c:crossAx', nest: () { - builder.attribute('val', crossAx); - }); - builder.element('c:crosses', nest: () { - builder.attribute('val', 'autoZero'); - }); - builder.element('c:auto', nest: () { - builder.attribute('val', 1); - }); - builder.element('c:lblAlgn', nest: () { - builder.attribute('val', 'ctr'); - }); - builder.element('c:lblOffset', nest: () { - builder.attribute('val', 100); - }); - builder.element('c:noMultiLvlLbl', nest: () { - builder.attribute('val', 0); - }); - builder.element('c:tickMarkSkip', nest: () { - builder.attribute('val', 1); - }); - }); + void _serializeCategoryAxisForStock( + XmlBuilder builder, + ChartCategoryAxis axis, + int axisId, + int crossAx, + bool isBar, + ) { + builder.element( + 'c:catAx', + nest: () { + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', axisId); + }, + ); + builder.element( + 'c:scaling', + nest: () { + builder.element( + 'c:orientation', + nest: () { + builder.attribute('val', 'minMax'); + }, + ); + }, + ); + int delete = 0; + String axpos = 'b'; + if (!isBar) { + delete = 1; + axpos = 't'; + } + builder.element( + 'c:delete', + nest: () { + builder.attribute('val', delete); + }, + ); + builder.element( + 'c:axPos', + nest: () { + builder.attribute('val', axpos); + }, + ); + if (axis.hasAxisTitle) { + _serializeChartTextArea(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + builder.element( + 'c:majorTickMark', + nest: () { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:ln', + nest: () { + if (!isBar) { + builder.attribute('w', 12700); + } + }, + ); + }, + ); + builder.element( + 'c:crossAx', + nest: () { + builder.attribute('val', crossAx); + }, + ); + builder.element( + 'c:crosses', + nest: () { + builder.attribute('val', 'autoZero'); + }, + ); + builder.element( + 'c:auto', + nest: () { + builder.attribute('val', 1); + }, + ); + builder.element( + 'c:lblAlgn', + nest: () { + builder.attribute('val', 'ctr'); + }, + ); + builder.element( + 'c:lblOffset', + nest: () { + builder.attribute('val', 100); + }, + ); + builder.element( + 'c:noMultiLvlLbl', + nest: () { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:tickMarkSkip', + nest: () { + builder.attribute('val', 1); + }, + ); + }, + ); } ///Serialize value axis for stock chart - void _serializeValueAxisForStockchart(XmlBuilder builder, - ChartCategoryAxis axis, int axisId, int crossAx, bool isBar) { - builder.element('c:valAx', nest: () { - builder.element('c:axId', nest: () { - builder.attribute('val', crossAx); - }); - builder.element('c:scaling', nest: () { - builder.element('c:orientation', nest: () { - builder.attribute('val', 'minMax'); - }); - if (!axis.isAutoMax) { - builder.element('c:max', nest: () { - builder.attribute('val', axis.maximumValue); - }); - } - if (axis.isAutoMin) { - builder.element('c:min', nest: () { - builder.attribute('val', axis.minimumValue); - }); - } - }); - builder.element('c:delete', nest: () { - builder.attribute('val', '0'); - }); - String axpos = 'l'; - - if (!isBar) { - axpos = 'r'; - } + void _serializeValueAxisForStockchart( + XmlBuilder builder, + ChartCategoryAxis axis, + int axisId, + int crossAx, + bool isBar, + ) { + builder.element( + 'c:valAx', + nest: () { + builder.element( + 'c:axId', + nest: () { + builder.attribute('val', crossAx); + }, + ); + builder.element( + 'c:scaling', + nest: () { + builder.element( + 'c:orientation', + nest: () { + builder.attribute('val', 'minMax'); + }, + ); + if (!axis.isAutoMax) { + builder.element( + 'c:max', + nest: () { + builder.attribute('val', axis.maximumValue); + }, + ); + } + if (axis.isAutoMin) { + builder.element( + 'c:min', + nest: () { + builder.attribute('val', axis.minimumValue); + }, + ); + } + }, + ); + builder.element( + 'c:delete', + nest: () { + builder.attribute('val', '0'); + }, + ); + String axpos = 'l'; + + if (!isBar) { + axpos = 'r'; + } - builder.element('c:axPos', nest: () { - builder.attribute('val', axpos); - }); + builder.element( + 'c:axPos', + nest: () { + builder.attribute('val', axpos); + }, + ); - if (axpos == 'l') { - builder.element('c:majorGridlines', nest: () {}); - } + if (axpos == 'l') { + builder.element('c:majorGridlines', nest: () {}); + } - if (axis.hasAxisTitle) { - _serializeChartTextArea(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - if (axis.hasMajorGridLines) { - builder.element('c:majorGridlines', nest: () {}); - } - builder.element('c:majorTickMark', nest: () { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () { - builder.element('a:ln', nest: () {}); - }); - builder.element('c:crossAx', nest: () { - builder.attribute('val', axisId); - }); - String crosses = 'autoZero'; - if (!isBar) { - crosses = 'max'; - } - builder.element('c:crosses', nest: () { - builder.attribute('val', crosses); - }); - final Chart chart = axis.parentChart; - final String strCrossBetween = - chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; - builder.element('c:crossBetween', nest: () { - builder.attribute('val', strCrossBetween); - }); - }); + if (axis.hasAxisTitle) { + _serializeChartTextArea(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + if (axis.hasMajorGridLines) { + builder.element('c:majorGridlines', nest: () {}); + } + builder.element( + 'c:majorTickMark', + nest: () { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () { + builder.element('a:ln', nest: () {}); + }, + ); + builder.element( + 'c:crossAx', + nest: () { + builder.attribute('val', axisId); + }, + ); + String crosses = 'autoZero'; + if (!isBar) { + crosses = 'max'; + } + builder.element( + 'c:crosses', + nest: () { + builder.attribute('val', crosses); + }, + ); + final Chart chart = axis.parentChart; + final String strCrossBetween = + chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; + builder.element( + 'c:crossBetween', + nest: () { + builder.attribute('val', strCrossBetween); + }, + ); + }, + ); } ///Serialize doughnut/doughnut_exploded charts @@ -1487,26 +2422,38 @@ class ChartSerialization { late int doughnutHoleSize; late int firstSliceAngle; - builder.element('c:doughnutChart', nest: () { - builder.element('c:varyColors', nest: () { - builder.attribute('val', 1); - }); - - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerie(builder, firstSerie); - firstSliceAngle = - firstSerie.serieFormat.commonSerieOptions.firstSliceAngle; - doughnutHoleSize = - firstSerie.serieFormat.commonSerieOptions.holeSizePercent; - } - builder.element('c:firstSliceAng', nest: () { - builder.attribute('val', firstSliceAngle); - }); - builder.element('c:holeSize', nest: () { - builder.attribute('val', doughnutHoleSize); - }); - }); + builder.element( + 'c:doughnutChart', + nest: () { + builder.element( + 'c:varyColors', + nest: () { + builder.attribute('val', 1); + }, + ); + + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerie(builder, firstSerie); + firstSliceAngle = + firstSerie.serieFormat.commonSerieOptions.firstSliceAngle; + doughnutHoleSize = + firstSerie.serieFormat.commonSerieOptions.holeSizePercent; + } + builder.element( + 'c:firstSliceAng', + nest: () { + builder.attribute('val', firstSliceAngle); + }, + ); + builder.element( + 'c:holeSize', + nest: () { + builder.attribute('val', doughnutHoleSize); + }, + ); + }, + ); } ///Serialize marker for stock and line charts @@ -1521,30 +2468,47 @@ class ChartSerialization { type == ExcelChartType.stockVolumeOpenHighLowClose || type == ExcelChartType.stockVolumeHighLowClose || type == ExcelChartType.stockOpenHighLowClose)) { - builder.element('c:marker', nest: () { - builder.element('c:symbol', nest: () { - builder.attribute('val', 'none'); - }); - }); + builder.element( + 'c:marker', + nest: () { + builder.element( + 'c:symbol', + nest: () { + builder.attribute('val', 'none'); + }, + ); + }, + ); } else if ((firstSerie.serieFormat.markerStyle == ExcelChartMarkerType.none) && (type == ExcelChartType.lineMarkers || type == ExcelChartType.lineMarkersStacked || type == ExcelChartType.lineMarkersStacked100)) { - builder.element('c:marker', nest: () { - builder.element('c:symbol', nest: () { - builder.attribute('val', 'circle'); - }); - builder.element('c:size', nest: () { - builder.attribute('val', '5'); - }); - }); + builder.element( + 'c:marker', + nest: () { + builder.element( + 'c:symbol', + nest: () { + builder.attribute('val', 'circle'); + }, + ); + builder.element( + 'c:size', + nest: () { + builder.attribute('val', '5'); + }, + ); + }, + ); } else if (firstSerie.serieFormat.markerStyle != ExcelChartMarkerType.none) { - final String markerBackgroundColor = - firstSerie.serieFormat.markerBackgroundColor.replaceAll('#', ''); - final String markerBorderColor = - firstSerie.serieFormat.markerBorderColor.replaceAll('#', ''); + final String markerBackgroundColor = firstSerie + .serieFormat + .markerBackgroundColor + .replaceAll('#', ''); + final String markerBorderColor = firstSerie.serieFormat.markerBorderColor + .replaceAll('#', ''); late String exclMarkertype; if (firstSerie.serieFormat.markerStyle == ExcelChartMarkerType.diamond) { exclMarkertype = 'diamond'; @@ -1571,28 +2535,55 @@ class ChartSerialization { exclMarkertype = 'star'; } - builder.element('c:marker', nest: () { - builder.element('c:symbol', nest: () { - builder.attribute('val', exclMarkertype); - }); - builder.element('c:size', nest: () { - builder.attribute('val', '5'); - }); - builder.element('c:spPr', nest: () { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', markerBackgroundColor); - }); - }); - builder.element('a:ln', nest: () { - builder.element('a:solidFill', nest: () { - builder.element('a:srgbClr', nest: () { - builder.attribute('val', markerBorderColor); - }); - }); - }); - }); - }); + builder.element( + 'c:marker', + nest: () { + builder.element( + 'c:symbol', + nest: () { + builder.attribute('val', exclMarkertype); + }, + ); + builder.element( + 'c:size', + nest: () { + builder.attribute('val', '5'); + }, + ); + builder.element( + 'c:spPr', + nest: () { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', markerBackgroundColor); + }, + ); + }, + ); + builder.element( + 'a:ln', + nest: () { + builder.element( + 'a:solidFill', + nest: () { + builder.element( + 'a:srgbClr', + nest: () { + builder.attribute('val', markerBorderColor); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); } } @@ -1602,45 +2593,72 @@ class ChartSerialization { sheet.workbook.chartCount++; final XmlBuilder builder = XmlBuilder(); builder.processing('xml', 'version="1.0"'); - builder.element('c:chartSpace', nest: () async { - builder.attribute( - 'xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); - builder.attribute('xmlns:r', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - builder.attribute('xmlns:c', - 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - - if (chart.hasPlotArea) { - builder.element('c:roundedCorners', nest: () async { - builder.attribute('val', 0); - }); - } - builder.element('c:chart', nest: () async { - if (chart.hasTitle) { - _serializeTitleAsync(builder, chart.chartTitleArea); - } - if (chart.is3DChart) { - _serializeView3DAsync(builder, chart); - } - _serializePlotAreaAsync(builder, chart); - if (chart.series.count > 0 && chart.hasLegend) { - _serializeLegendAsync(builder, chart.legend!); + builder.element( + 'c:chartSpace', + nest: () async { + builder.attribute( + 'xmlns:a', + 'http://schemas.openxmlformats.org/drawingml/2006/main', + ); + builder.attribute( + 'xmlns:r', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + builder.attribute( + 'xmlns:c', + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + ); + + if (chart.hasPlotArea) { + builder.element( + 'c:roundedCorners', + nest: () async { + builder.attribute('val', 0); + }, + ); } - builder.element('c:plotVisOnly', nest: () async { - builder.attribute('val', '1'); - }); - builder.element('c:dispBlanksAs', nest: () async { - builder.attribute('val', 'gap'); - }); - }); - _serializeFillAsync( - builder, chart.linePattern, chart.linePatternColor, false); - _serializePrinterSettingsAsync(builder, chart); - }); + builder.element( + 'c:chart', + nest: () async { + if (chart.hasTitle) { + _serializeTitleAsync(builder, chart.chartTitleArea); + } + if (chart.is3DChart) { + _serializeView3DAsync(builder, chart); + } + _serializePlotAreaAsync(builder, chart); + if (chart.series.count > 0 && chart.hasLegend) { + _serializeLegendAsync(builder, chart.legend!); + } + builder.element( + 'c:plotVisOnly', + nest: () async { + builder.attribute('val', '1'); + }, + ); + builder.element( + 'c:dispBlanksAs', + nest: () async { + builder.attribute('val', 'gap'); + }, + ); + }, + ); + _serializeFillAsync( + builder, + chart.linePattern, + chart.linePatternColor, + false, + ); + _serializePrinterSettingsAsync(builder, chart); + }, + ); final String stringXml = builder.buildDocument().copy().toString(); final List bytes = utf8.encode(stringXml); _addToArchiveAsync( - bytes, 'xl/charts/chart${sheet.workbook.chartCount}.xml'); + bytes, + 'xl/charts/chart${sheet.workbook.chartCount}.xml', + ); } } @@ -1651,242 +2669,418 @@ class ChartSerialization { /// serializes chart's legend. Future _serializeLegendAsync( - XmlBuilder builder, ChartLegend chartLegend) async { - builder.element('c:legend', nest: () async { - builder.element('c:legendPos', nest: () async { - final ExcelLegendPosition legendPostion = chartLegend.position; - final String positionStr = legendPostion == ExcelLegendPosition.bottom - ? 'b' - : legendPostion == ExcelLegendPosition.left - ? 'l' - : legendPostion == ExcelLegendPosition.right + XmlBuilder builder, + ChartLegend chartLegend, + ) async { + builder.element( + 'c:legend', + nest: () async { + builder.element( + 'c:legendPos', + nest: () async { + final ExcelLegendPosition legendPostion = chartLegend.position; + final String positionStr = + legendPostion == ExcelLegendPosition.bottom + ? 'b' + : legendPostion == ExcelLegendPosition.left + ? 'l' + : legendPostion == ExcelLegendPosition.right ? 'r' : legendPostion == ExcelLegendPosition.top - ? 't' - : 'r'; - builder.attribute('val', positionStr); - }); - if (chartLegend.hasTextArea) { - _serializeDefaultTextAreaPropertiesAsync(builder, chartLegend.textArea); - } - builder.element('c:layout', nest: () async {}); - builder.element('c:overlay', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:spPr', nest: () async {}); - }); + ? 't' + : 'r'; + builder.attribute('val', positionStr); + }, + ); + if (chartLegend.hasTextArea) { + _serializeDefaultTextAreaPropertiesAsync( + builder, + chartLegend.textArea, + ); + } + builder.element('c:layout', nest: () async {}); + builder.element( + 'c:overlay', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element('c:spPr', nest: () async {}); + }, + ); } /// serializes chart's drawing. Future _serializeChartDrawingAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { for (final Chart chart in (sheet.charts! as ChartCollection).innerList) { - builder.element('xdr:twoCellAnchor', nest: () async { - builder.attribute('editAs', 'twoCell'); - builder.element('xdr:from', nest: () async { - builder.element('xdr:col', - nest: chart.leftColumn > 0 ? chart.leftColumn - 1 : 0); - builder.element('xdr:colOff', nest: 0); - builder.element('xdr:row', - nest: chart.topRow > 0 ? chart.topRow - 1 : 0); - builder.element('xdr:rowOff', nest: 0); - }); - - builder.element('xdr:to', nest: () async { - builder.element('xdr:col', - nest: chart.rightColumn > 0 - ? chart.rightColumn - 1 - : chart.leftColumn + 7); - builder.element('xdr:colOff', nest: 0); - builder.element('xdr:row', - nest: chart.bottomRow > 0 - ? chart.bottomRow - 1 - : chart.topRow + 15); - builder.element('xdr:rowOff', nest: 0); - }); - - builder.element('xdr:graphicFrame', nest: () async { - builder.attribute('macro', ''); - builder.element('xdr:nvGraphicFramePr', nest: () async { - builder.element('xdr:cNvPr', nest: () async { - builder.attribute( - 'id', 1024 + sheet.workbook.chartCount + chart.index); - builder.attribute( - 'name', 'Chart ${sheet.workbook.chartCount + chart.index}'); - }); - builder.element('xdr:cNvGraphicFramePr', nest: () async {}); - }); - builder.element('xdr:xfrm', nest: () async { - builder.element('a:off', nest: () async { - builder.attribute('x', '0'); - builder.attribute('y', 0); - }); - builder.element('a:ext', nest: () async { - builder.attribute('cx', '0'); - builder.attribute('cy', 0); - }); - }); - builder.element('a:graphic', nest: () async { - builder.element('a:graphicData', nest: () async { - builder.attribute('uri', - 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - - builder.element('c:chart', nest: () async { - builder.attribute('p7:id', 'rId${chart.index}'); - builder.attribute('xmlns:p7', - 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); - builder.attribute('xmlns:c', - 'http://schemas.openxmlformats.org/drawingml/2006/chart'); - }); - }); - }); - }); - builder.element('xdr:clientData', nest: () async {}); - }); + builder.element( + 'xdr:twoCellAnchor', + nest: () async { + builder.attribute('editAs', 'twoCell'); + builder.element( + 'xdr:from', + nest: () async { + builder.element( + 'xdr:col', + nest: chart.leftColumn > 0 ? chart.leftColumn - 1 : 0, + ); + builder.element('xdr:colOff', nest: 0); + builder.element( + 'xdr:row', + nest: chart.topRow > 0 ? chart.topRow - 1 : 0, + ); + builder.element('xdr:rowOff', nest: 0); + }, + ); + + builder.element( + 'xdr:to', + nest: () async { + builder.element( + 'xdr:col', + nest: + chart.rightColumn > 0 + ? chart.rightColumn - 1 + : chart.leftColumn + 7, + ); + builder.element('xdr:colOff', nest: 0); + builder.element( + 'xdr:row', + nest: + chart.bottomRow > 0 + ? chart.bottomRow - 1 + : chart.topRow + 15, + ); + builder.element('xdr:rowOff', nest: 0); + }, + ); + + builder.element( + 'xdr:graphicFrame', + nest: () async { + builder.attribute('macro', ''); + builder.element( + 'xdr:nvGraphicFramePr', + nest: () async { + builder.element( + 'xdr:cNvPr', + nest: () async { + builder.attribute( + 'id', + 1024 + sheet.workbook.chartCount + chart.index, + ); + builder.attribute( + 'name', + 'Chart ${sheet.workbook.chartCount + chart.index}', + ); + }, + ); + builder.element('xdr:cNvGraphicFramePr', nest: () async {}); + }, + ); + builder.element( + 'xdr:xfrm', + nest: () async { + builder.element( + 'a:off', + nest: () async { + builder.attribute('x', '0'); + builder.attribute('y', 0); + }, + ); + builder.element( + 'a:ext', + nest: () async { + builder.attribute('cx', '0'); + builder.attribute('cy', 0); + }, + ); + }, + ); + builder.element( + 'a:graphic', + nest: () async { + builder.element( + 'a:graphicData', + nest: () async { + builder.attribute( + 'uri', + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + ); + + builder.element( + 'c:chart', + nest: () async { + builder.attribute('p7:id', 'rId${chart.index}'); + builder.attribute( + 'xmlns:p7', + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', + ); + builder.attribute( + 'xmlns:c', + 'http://schemas.openxmlformats.org/drawingml/2006/chart', + ); + }, + ); + }, + ); + }, + ); + }, + ); + builder.element('xdr:clientData', nest: () async {}); + }, + ); } } // ignore: public_member_api_docs Future serializeChartDrawingAsync( - XmlBuilder builder, Worksheet sheet) async { + XmlBuilder builder, + Worksheet sheet, + ) async { _serializeChartDrawingAsync(builder, sheet); } /// serialize default text area properties. Future _serializeDefaultTextAreaPropertiesAsync( - XmlBuilder builder, ChartTextArea textArea) async { - builder.element('c:txPr', nest: () async { - builder.element('a:bodyPr ', nest: () async {}); - builder.element('a:lstStyle ', nest: () async {}); - builder.element('a:p', nest: () async { - builder.element('a:pPr', nest: () async { - builder.element('a:defRPr', nest: () async { - final double size = textArea.size * 100; - builder.attribute('sz', size.toInt().toString()); - builder.attribute('b', textArea.bold ? '1' : '0'); - builder.attribute('i', textArea.italic ? '1' : '0'); - if (textArea.color != '' && textArea.color != 'FF000000') { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', textArea.color.replaceAll('#', '')); - }); - }); - } - builder.element('a:latin', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:cs', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - }); - }); - builder.element('a:endParaRPr', nest: () async { - builder.attribute('lang', 'en-US'); - }); - }); - }); + XmlBuilder builder, + ChartTextArea textArea, + ) async { + builder.element( + 'c:txPr', + nest: () async { + builder.element('a:bodyPr ', nest: () async {}); + builder.element('a:lstStyle ', nest: () async {}); + builder.element( + 'a:p', + nest: () async { + builder.element( + 'a:pPr', + nest: () async { + builder.element( + 'a:defRPr', + nest: () async { + final double size = textArea.size * 100; + builder.attribute('sz', size.toInt().toString()); + builder.attribute('b', textArea.bold ? '1' : '0'); + builder.attribute('i', textArea.italic ? '1' : '0'); + if (textArea.color != '' && textArea.color != 'FF000000') { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute( + 'val', + textArea.color.replaceAll('#', ''), + ); + }, + ); + }, + ); + } + builder.element( + 'a:latin', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:cs', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + }, + ); + }, + ); + builder.element( + 'a:endParaRPr', + nest: () async { + builder.attribute('lang', 'en-US'); + }, + ); + }, + ); + }, + ); } /// serialize printer settings of charts Future _serializePrinterSettingsAsync( - XmlBuilder builder, Chart chart) async { - builder.element('c:printSettings', nest: () async { - builder.element('c:headerFooter', nest: () async { - builder.attribute('scaleWithDoc', '1'); - builder.attribute('alignWithMargins', '0'); - builder.attribute('differentFirst', '0'); - builder.attribute('differentOddEven', '0'); - }); - builder.element('c:pageMargins', nest: () async { - builder.attribute('l', '0.7'); - builder.attribute('r', '0.7'); - builder.attribute('t', '0.75'); - builder.attribute('b', '0.75'); - builder.attribute('header', '0.3'); - builder.attribute('footer', '0.3'); - }); - }); + XmlBuilder builder, + Chart chart, + ) async { + builder.element( + 'c:printSettings', + nest: () async { + builder.element( + 'c:headerFooter', + nest: () async { + builder.attribute('scaleWithDoc', '1'); + builder.attribute('alignWithMargins', '0'); + builder.attribute('differentFirst', '0'); + builder.attribute('differentOddEven', '0'); + }, + ); + builder.element( + 'c:pageMargins', + nest: () async { + builder.attribute('l', '0.7'); + builder.attribute('r', '0.7'); + builder.attribute('t', '0.75'); + builder.attribute('b', '0.75'); + builder.attribute('header', '0.3'); + builder.attribute('footer', '0.3'); + }, + ); + }, + ); } /// serialize chart title. Future _serializeTitleAsync( - XmlBuilder builder, ChartTextArea chartTextArea) async { - builder.element('c:title', nest: () async { - if (chartTextArea.hasText) { - builder.element('c:tx', nest: () async { - builder.element('c:rich', nest: () async { - builder.element('a:bodyPr ', nest: () async {}); - builder.element('a:lstStyle', nest: () async {}); - builder.element('a:p', nest: () async { - builder.element('a:pPr', nest: () async { - builder.attribute('algn', 'ctr'); - builder.element('a:defRPr', nest: () async {}); - }); - builder.element('a:r', nest: () async { - _serializeParagraphRunPropertiesAsync(builder, chartTextArea); - builder.element('a:t', nest: () async { - builder.text(chartTextArea.text!); - }); - }); - }); - }); - }); - } - builder.element('c:layout', nest: () async {}); - builder.element('c:overlay', nest: () async { - builder.attribute('val', chartTextArea.overlay ? '1' : '0'); - }); - _serializeFillAsync(builder, ExcelChartLinePattern.none, null, false); - }); + XmlBuilder builder, + ChartTextArea chartTextArea, + ) async { + builder.element( + 'c:title', + nest: () async { + if (chartTextArea.hasText) { + builder.element( + 'c:tx', + nest: () async { + builder.element( + 'c:rich', + nest: () async { + builder.element('a:bodyPr ', nest: () async {}); + builder.element('a:lstStyle', nest: () async {}); + builder.element( + 'a:p', + nest: () async { + builder.element( + 'a:pPr', + nest: () async { + builder.attribute('algn', 'ctr'); + builder.element('a:defRPr', nest: () async {}); + }, + ); + builder.element( + 'a:r', + nest: () async { + _serializeParagraphRunPropertiesAsync( + builder, + chartTextArea, + ); + builder.element( + 'a:t', + nest: () async { + builder.text(chartTextArea.text!); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + builder.element('c:layout', nest: () async {}); + builder.element( + 'c:overlay', + nest: () async { + builder.attribute('val', chartTextArea.overlay ? '1' : '0'); + }, + ); + _serializeFillAsync(builder, ExcelChartLinePattern.none, null, false); + }, + ); } /// serialize paragraph run properties. Future _serializeParagraphRunPropertiesAsync( - XmlBuilder builder, ChartTextArea textArea) async { - builder.element('a:rPr', nest: () async { - builder.attribute('lang', 'en-US'); - final double size = textArea.size * 100; - builder.attribute('sz', size.toInt().toString()); - builder.attribute('b', textArea.bold ? '1' : '0'); - builder.attribute('i', textArea.italic ? '1' : '0'); - builder.attribute('baseline', '0'); - if (textArea.color != '' && textArea.color != 'FF000000') { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', textArea.color.replaceAll('#', '')); - }); - }); - } - builder.element('a:latin', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:ea', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:cs', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - }); + XmlBuilder builder, + ChartTextArea textArea, + ) async { + builder.element( + 'a:rPr', + nest: () async { + builder.attribute('lang', 'en-US'); + final double size = textArea.size * 100; + builder.attribute('sz', size.toInt().toString()); + builder.attribute('b', textArea.bold ? '1' : '0'); + builder.attribute('i', textArea.italic ? '1' : '0'); + builder.attribute('baseline', '0'); + if (textArea.color != '' && textArea.color != 'FF000000') { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', textArea.color.replaceAll('#', '')); + }, + ); + }, + ); + } + builder.element( + 'a:latin', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:ea', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:cs', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + }, + ); } /// serialize plotarea of the chart Future _serializePlotAreaAsync(XmlBuilder builder, Chart chart) async { - builder.element('c:plotArea', nest: () async { - builder.element('c:layout', nest: () async {}); - if (chart.series.count > 0) { - _serializeMainChartTypeTagAsync(builder, chart); - } else { - _serializeEmptyChartAsync(builder, chart); - _serializeAxesAsync(builder, chart); - } - _serializeFillAsync(builder, chart.plotArea.linePattern, - chart.plotArea.linePatternColor, false); - }); + builder.element( + 'c:plotArea', + nest: () async { + builder.element('c:layout', nest: () async {}); + if (chart.series.count > 0) { + _serializeMainChartTypeTagAsync(builder, chart); + } else { + _serializeEmptyChartAsync(builder, chart); + _serializeAxesAsync(builder, chart); + } + _serializeFillAsync( + builder, + chart.plotArea.linePattern, + chart.plotArea.linePatternColor, + false, + ); + }, + ); } /// serializes main chart tag. Future _serializeMainChartTypeTagAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { switch (chart.chartType) { case ExcelChartType.column: case ExcelChartType.columnStacked: @@ -1952,93 +3146,143 @@ class ChartSerialization { /// serializes Line chart. Future _serializeLineChartAsync(XmlBuilder builder, Chart chart) async { final ExcelChartType type = chart.series[0].serieType; - builder.element('c:lineChart', nest: () async { - _serializeChartGroupingAsync(builder, chart); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - } - if (type == ExcelChartType.lineMarkers || - type == ExcelChartType.lineMarkersStacked || - type == ExcelChartType.lineMarkersStacked100) { - builder.element('c:marker', nest: () async { - builder.attribute('val', 1); - }); - } - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:lineChart', + nest: () async { + _serializeChartGroupingAsync(builder, chart); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + } + if (type == ExcelChartType.lineMarkers || + type == ExcelChartType.lineMarkersStacked || + type == ExcelChartType.lineMarkersStacked100) { + builder.element( + 'c:marker', + nest: () async { + builder.attribute('val', 1); + }, + ); + } + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxesAsync(builder, chart); } /// serializes Bar/ColumnClustered chart. Future _serializeBarChartAsync(XmlBuilder builder, Chart chart) async { late int gapwidth; - builder.element('c:barChart', nest: () async { - final String strDirection = - chart.chartType.toString().contains('bar') ? 'bar' : 'col'; - builder.element('c:barDir', nest: () async { - builder.attribute('val', strDirection); - }); - _serializeChartGroupingAsync(builder, chart); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; - } - builder.element('c:gapWidth', nest: () async { - builder.attribute('val', gapwidth); - }); - if (chart.getIsStacked(chart.chartType) || - chart.getIs100(chart.chartType)) { - builder.element('c:overlap', nest: () async { - builder.attribute('val', '100'); - }); - } - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:barChart', + nest: () async { + final String strDirection = + chart.chartType.toString().contains('bar') ? 'bar' : 'col'; + builder.element( + 'c:barDir', + nest: () async { + builder.attribute('val', strDirection); + }, + ); + _serializeChartGroupingAsync(builder, chart); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; + } + builder.element( + 'c:gapWidth', + nest: () async { + builder.attribute('val', gapwidth); + }, + ); + if (chart.getIsStacked(chart.chartType) || + chart.getIs100(chart.chartType)) { + builder.element( + 'c:overlap', + nest: () async { + builder.attribute('val', '100'); + }, + ); + } + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxesAsync(builder, chart); } /// serializes Area chart. Future _serializeAreaChartAsync(XmlBuilder builder, Chart chart) async { - builder.element('c:areaChart', nest: () async { - _serializeChartGroupingAsync(builder, chart); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - } - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:areaChart', + nest: () async { + _serializeChartGroupingAsync(builder, chart); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + } + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxesAsync(builder, chart); } /// serialize chart grouping. Future _serializeChartGroupingAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { String strGrouping; if (chart.getIsClustered(chart.chartType)) { strGrouping = 'clustered'; @@ -2049,276 +3293,487 @@ class ChartSerialization { } else { strGrouping = 'standard'; } - builder.element('c:grouping', nest: () async { - builder.attribute('val', strGrouping); - }); + builder.element( + 'c:grouping', + nest: () async { + builder.attribute('val', strGrouping); + }, + ); } /// serializes pie chart. Future _serializePieChartAsync(XmlBuilder builder, Chart chart) async { - builder.element('c:pieChart', nest: () async { - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 1); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - } - builder.element('c:firstSliceAng', nest: () async { - builder.attribute('val', 0); - }); - }); + builder.element( + 'c:pieChart', + nest: () async { + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 1); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + } + builder.element( + 'c:firstSliceAng', + nest: () async { + builder.attribute('val', 0); + }, + ); + }, + ); } /// serializes series of chart. Future _serializeSerieAsync( - XmlBuilder builder, ChartSerie firstSerie) async { + XmlBuilder builder, + ChartSerie firstSerie, + ) async { final ExcelChartType type = firstSerie.serieType; - builder.element('c:ser', nest: () async { - builder.element('c:idx', nest: () async { - builder.attribute('val', firstSerie.index); - }); - builder.element('c:order', nest: () async { - builder.attribute('val', firstSerie.index); - }); - if (firstSerie.isDefaultName) { - builder.element('c:tx', nest: () async { - final String strName = firstSerie.nameOrFormula; - if (strName.isNotEmpty) { - _serializeStringReferenceAsync( - builder, strName, firstSerie, 'text', null); - } - }); - } - - if (firstSerie.serieFormat.pieExplosionPercent != 0 || - (type == ExcelChartType.doughnutExploded && - firstSerie.chart.series.count == 1)) { - builder.element('c:explosion', nest: () async { - builder.attribute('val', firstSerie.serieFormat.pieExplosionPercent); - }); - } - if (type == ExcelChartType.stockOpenHighLowClose || - type == ExcelChartType.stockVolumeHighLowClose || - type == ExcelChartType.stockVolumeOpenHighLowClose) { - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async { - builder.element('a:noFill', nest: () async {}); - }); - }); - } else if (type == ExcelChartType.stockHighLowClose) { - if (firstSerie.index == 2) { - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async { - builder.attribute('w', '3175'); - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', '000000'); - }); - }); - builder.element('a:prstDash', nest: () async { - builder.attribute('val', 'solid'); - }); - }); - }); - } else { - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async { - builder.element('a:noFill', nest: () async {}); - }); - }); + builder.element( + 'c:ser', + nest: () async { + builder.element( + 'c:idx', + nest: () async { + builder.attribute('val', firstSerie.index); + }, + ); + builder.element( + 'c:order', + nest: () async { + builder.attribute('val', firstSerie.index); + }, + ); + if (firstSerie.isDefaultName) { + builder.element( + 'c:tx', + nest: () async { + final String strName = firstSerie.nameOrFormula; + if (strName.isNotEmpty) { + _serializeStringReferenceAsync( + builder, + strName, + firstSerie, + 'text', + null, + ); + } + }, + ); } - } - if (firstSerie.linePattern != ExcelChartLinePattern.none) { - _serializeFillAsync( - builder, firstSerie.linePattern, firstSerie.linePatternColor, true); - } - - _serializeMarkerAsync(builder, firstSerie); - if (firstSerie.dataLabels.isValue) { - builder.element('c:dLbls', nest: () async { - final format = firstSerie.dataLabels.numberFormat; - if (format != null && format.isNotEmpty && format != 'General') { - builder.element('c:numFmt', nest: () async { - builder.attribute('formatCode', format); - builder.attribute('sourceLinked', '0'); - }); - } - builder.element('c:spPr', nest: () async { - builder.element('a:noFill', nest: () async {}); - builder.element('a:ln', nest: () async { - builder.element('a:noFill', nest: () async {}); - }); - builder.element('a:effectLst', nest: () async {}); - }); - final ChartTextArea textArea = firstSerie.dataLabels.textArea; - _serializeChartTextAreaAsync(builder, textArea); - builder.element('c:showLegendKey', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showVal', nest: () async { - builder.attribute('val', firstSerie.dataLabels.isValue ? 1 : 0); - }); - builder.element('c:showCatName', nest: () async { - builder.attribute( - 'val', firstSerie.dataLabels.isCategoryName ? 1 : 0); - }); - builder.element('c:showSerName', nest: () async { - builder.attribute( - 'val', firstSerie.dataLabels.isSeriesName ? 1 : 0); - }); - builder.element('c:showPercent', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showBubbleSize', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showLeaderLines', nest: () async { - builder.attribute('val', 0); - }); - }); - } - if (firstSerie.categoryLabels != null) { - final Range firstRange = firstSerie.chart.worksheet.getRangeByIndex( - firstSerie.categoryLabels!.row, firstSerie.categoryLabels!.column); - builder.element('c:cat', nest: () async { - Worksheet tempSheet = firstSerie.chart.worksheet; - if (firstSerie.categoryLabels!.addressGlobal != '') { - for (final Worksheet sheet - in firstSerie.chart.worksheet.workbook.worksheets.innerList) { - if (firstSerie.categoryLabels!.addressGlobal - .contains(RegExp('${sheet.name}!')) || - firstSerie.categoryLabels!.addressGlobal - .contains(RegExp("${sheet.name}'!"))) { - tempSheet = sheet; - break; - } - } - } - if (firstRange.text == null && firstRange.number != null) { - builder.element('c:numRef', nest: () async { - builder.element('c:f', - nest: firstSerie.categoryLabels!.addressGlobal); - final Range firstRange = firstSerie.chart.worksheet - .getRangeByIndex(firstSerie.categoryLabels!.row, - firstSerie.categoryLabels!.column); - builder.element('c:numCache', nest: () async { - if (firstRange.numberFormat != null && - firstRange.numberFormat != 'General') { - builder.element('c:formatCode', - nest: firstRange.numberFormat); - } - _serializeNumCacheValuesAsync(builder, firstSerie, tempSheet); - }); - }); + if (firstSerie.serieFormat.pieExplosionPercent != 0 || + (type == ExcelChartType.doughnutExploded && + firstSerie.chart.series.count == 1)) { + builder.element( + 'c:explosion', + nest: () async { + builder.attribute( + 'val', + firstSerie.serieFormat.pieExplosionPercent, + ); + }, + ); + } + if (type == ExcelChartType.stockOpenHighLowClose || + type == ExcelChartType.stockVolumeHighLowClose || + type == ExcelChartType.stockVolumeOpenHighLowClose) { + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:ln', + nest: () async { + builder.element('a:noFill', nest: () async {}); + }, + ); + }, + ); + } else if (type == ExcelChartType.stockHighLowClose) { + if (firstSerie.index == 2) { + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:ln', + nest: () async { + builder.attribute('w', '3175'); + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', '000000'); + }, + ); + }, + ); + builder.element( + 'a:prstDash', + nest: () async { + builder.attribute('val', 'solid'); + }, + ); + }, + ); + }, + ); } else { - _serializeStringReferenceAsync( - builder, - firstSerie.categoryLabels!.addressGlobal, - firstSerie, - 'cat', - tempSheet); + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:ln', + nest: () async { + builder.element('a:noFill', nest: () async {}); + }, + ); + }, + ); } - }); - } - if (firstSerie.values != null) { - builder.element('c:val', nest: () async { - builder.element('c:numRef', nest: () async { - builder.element('c:f', nest: firstSerie.values!.addressGlobal); - final Range firstRange = firstSerie.chart.worksheet.getRangeByIndex( - firstSerie.values!.row, firstSerie.values!.column); - Worksheet tempSheet = firstSerie.chart.worksheet; - if (firstSerie.values!.addressGlobal != '') { - for (final Worksheet sheet - in firstSerie.chart.worksheet.workbook.worksheets.innerList) { - if (firstSerie.values!.addressGlobal - .contains(RegExp('${sheet.name}!')) || - firstSerie.values!.addressGlobal - .contains(RegExp("${sheet.name}'!"))) { - tempSheet = sheet; - break; + } + if (firstSerie.linePattern != ExcelChartLinePattern.none) { + _serializeFillAsync( + builder, + firstSerie.linePattern, + firstSerie.linePatternColor, + true, + ); + } + + _serializeMarkerAsync(builder, firstSerie); + + if (firstSerie.dataLabels.isValue) { + builder.element( + 'c:dLbls', + nest: () async { + final format = firstSerie.dataLabels.numberFormat; + if (format != null && format.isNotEmpty && format != 'General') { + builder.element( + 'c:numFmt', + nest: () async { + builder.attribute('formatCode', format); + builder.attribute('sourceLinked', '0'); + }, + ); + } + builder.element( + 'c:spPr', + nest: () async { + builder.element('a:noFill', nest: () async {}); + builder.element( + 'a:ln', + nest: () async { + builder.element('a:noFill', nest: () async {}); + }, + ); + builder.element('a:effectLst', nest: () async {}); + }, + ); + final ChartTextArea textArea = firstSerie.dataLabels.textArea; + _serializeChartTextAreaAsync(builder, textArea); + builder.element( + 'c:showLegendKey', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showVal', + nest: () async { + builder.attribute( + 'val', + firstSerie.dataLabels.isValue ? 1 : 0, + ); + }, + ); + builder.element( + 'c:showCatName', + nest: () async { + builder.attribute( + 'val', + firstSerie.dataLabels.isCategoryName ? 1 : 0, + ); + }, + ); + builder.element( + 'c:showSerName', + nest: () async { + builder.attribute( + 'val', + firstSerie.dataLabels.isSeriesName ? 1 : 0, + ); + }, + ); + builder.element( + 'c:showPercent', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showBubbleSize', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showLeaderLines', + nest: () async { + builder.attribute('val', 0); + }, + ); + }, + ); + } + if (firstSerie.categoryLabels != null) { + final Range firstRange = firstSerie.chart.worksheet.getRangeByIndex( + firstSerie.categoryLabels!.row, + firstSerie.categoryLabels!.column, + ); + builder.element( + 'c:cat', + nest: () async { + Worksheet tempSheet = firstSerie.chart.worksheet; + if (firstSerie.categoryLabels!.addressGlobal != '') { + for (final Worksheet sheet + in firstSerie + .chart + .worksheet + .workbook + .worksheets + .innerList) { + if (firstSerie.categoryLabels!.addressGlobal.contains( + RegExp('${sheet.name}!'), + ) || + firstSerie.categoryLabels!.addressGlobal.contains( + RegExp("${sheet.name}'!"), + )) { + tempSheet = sheet; + break; + } } } - } - builder.element('c:numCache', nest: () async { - if (firstRange.numberFormat != null && - firstRange.numberFormat != 'General') { - builder.element('c:formatCode', nest: firstRange.numberFormat); + if (firstRange.text == null && firstRange.number != null) { + builder.element( + 'c:numRef', + nest: () async { + builder.element( + 'c:f', + nest: firstSerie.categoryLabels!.addressGlobal, + ); + final Range firstRange = firstSerie.chart.worksheet + .getRangeByIndex( + firstSerie.categoryLabels!.row, + firstSerie.categoryLabels!.column, + ); + builder.element( + 'c:numCache', + nest: () async { + if (firstRange.numberFormat != null && + firstRange.numberFormat != 'General') { + builder.element( + 'c:formatCode', + nest: firstRange.numberFormat, + ); + } + _serializeNumCacheValuesAsync( + builder, + firstSerie, + tempSheet, + ); + }, + ); + }, + ); } else { - builder.element('c:formatCode', nest: 'General'); + _serializeStringReferenceAsync( + builder, + firstSerie.categoryLabels!.addressGlobal, + firstSerie, + 'cat', + tempSheet, + ); } - _serializeNumCacheValuesAsync(builder, firstSerie, tempSheet); - }); - }); - }); - } - if (firstSerie.serieType.toString().contains('line') || - firstSerie.serieType.toString().contains('stock')) { - builder.element('c:smooth', nest: () async { - builder.attribute('val', 0); - }); - } - }); + }, + ); + } + if (firstSerie.values != null) { + builder.element( + 'c:val', + nest: () async { + builder.element( + 'c:numRef', + nest: () async { + builder.element( + 'c:f', + nest: firstSerie.values!.addressGlobal, + ); + final Range firstRange = firstSerie.chart.worksheet + .getRangeByIndex( + firstSerie.values!.row, + firstSerie.values!.column, + ); + Worksheet tempSheet = firstSerie.chart.worksheet; + if (firstSerie.values!.addressGlobal != '') { + for (final Worksheet sheet + in firstSerie + .chart + .worksheet + .workbook + .worksheets + .innerList) { + if (firstSerie.values!.addressGlobal.contains( + RegExp('${sheet.name}!'), + ) || + firstSerie.values!.addressGlobal.contains( + RegExp("${sheet.name}'!"), + )) { + tempSheet = sheet; + break; + } + } + } + builder.element( + 'c:numCache', + nest: () async { + if (firstRange.numberFormat != null && + firstRange.numberFormat != 'General') { + builder.element( + 'c:formatCode', + nest: firstRange.numberFormat, + ); + } else { + builder.element('c:formatCode', nest: 'General'); + } + _serializeNumCacheValuesAsync( + builder, + firstSerie, + tempSheet, + ); + }, + ); + }, + ); + }, + ); + } + if (firstSerie.serieType.toString().contains('line') || + firstSerie.serieType.toString().contains('stock')) { + builder.element( + 'c:smooth', + nest: () async { + builder.attribute('val', 0); + }, + ); + } + }, + ); } /// serializes chart text area. Future _serializeChartTextAreaAsync( - XmlBuilder builder, ChartTextArea textArea) async { - builder.element('c:txPr', nest: () async { - builder.element('a:bodyPr ', nest: () async {}); - builder.element('a:lstStyle', nest: () async {}); - builder.element('a:p', nest: () async { - builder.element('a:pPr', nest: () async { - builder.element('a:defRPr', nest: () async { - final double size = textArea.size * 100; - builder.attribute('sz', size.toInt().toString()); - builder.attribute('b', textArea.bold ? '1' : '0'); - builder.attribute('i', textArea.italic ? '1' : '0'); - builder.attribute('baseline', '0'); - if (textArea.color != '' && textArea.color != 'FF000000') { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', textArea.color.replaceAll('#', '')); - }); - }); - } - builder.element('a:latin', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:ea', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - builder.element('a:cs', nest: () async { - builder.attribute('typeface', textArea.fontName); - }); - }); - }); - }); - }); + XmlBuilder builder, + ChartTextArea textArea, + ) async { + builder.element( + 'c:txPr', + nest: () async { + builder.element('a:bodyPr ', nest: () async {}); + builder.element('a:lstStyle', nest: () async {}); + builder.element( + 'a:p', + nest: () async { + builder.element( + 'a:pPr', + nest: () async { + builder.element( + 'a:defRPr', + nest: () async { + final double size = textArea.size * 100; + builder.attribute('sz', size.toInt().toString()); + builder.attribute('b', textArea.bold ? '1' : '0'); + builder.attribute('i', textArea.italic ? '1' : '0'); + builder.attribute('baseline', '0'); + if (textArea.color != '' && textArea.color != 'FF000000') { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute( + 'val', + textArea.color.replaceAll('#', ''), + ); + }, + ); + }, + ); + } + builder.element( + 'a:latin', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:ea', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + builder.element( + 'a:cs', + nest: () async { + builder.attribute('typeface', textArea.fontName); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); } /// serializes number cache values. Future _serializeNumCacheValuesAsync( - XmlBuilder builder, ChartSerie firstSerie, Worksheet dataSheet) async { + XmlBuilder builder, + ChartSerie firstSerie, + Worksheet dataSheet, + ) async { final Range? serieRange = firstSerie.values; if (serieRange != null) { final int count = serieRange.count; final int serieStartRow = serieRange.row; final int serieStartColumn = serieRange.column; - builder.element('c:ptCount', nest: () async { - builder.attribute('val', count); - }); + builder.element( + 'c:ptCount', + nest: () async { + builder.attribute('val', count); + }, + ); int index = 0; while (index < count) { - final double? value = dataSheet - .getRangeByIndex(serieStartRow + index, serieStartColumn) - .number; + final double? value = + dataSheet + .getRangeByIndex(serieStartRow + index, serieStartColumn) + .number; if (value != null) { - builder.element('c:pt', nest: () async { - builder.attribute('idx', index); - builder.element('c:v', nest: value); - }); + builder.element( + 'c:pt', + nest: () async { + builder.attribute('idx', index); + builder.element('c:v', nest: value); + }, + ); } index++; } @@ -2326,44 +3781,69 @@ class ChartSerialization { } /// serializes string cache reference. - Future _serializeStringReferenceAsync(XmlBuilder builder, String range, - ChartSerie firstSerie, String tagName, Worksheet? dataSheet) async { - builder.element('c:strRef', nest: () async { - builder.element('c:f', nest: range); - builder.element('c:strCache', nest: () async { - if (tagName == 'cat') { - _serializeCategoryTagCacheValuesAsync(builder, firstSerie, dataSheet); - } else { - _serializeTextTagCacheValuesAsync(builder, firstSerie); - } - }); - }); + Future _serializeStringReferenceAsync( + XmlBuilder builder, + String range, + ChartSerie firstSerie, + String tagName, + Worksheet? dataSheet, + ) async { + builder.element( + 'c:strRef', + nest: () async { + builder.element('c:f', nest: range); + builder.element( + 'c:strCache', + nest: () async { + if (tagName == 'cat') { + _serializeCategoryTagCacheValuesAsync( + builder, + firstSerie, + dataSheet, + ); + } else { + _serializeTextTagCacheValuesAsync(builder, firstSerie); + } + }, + ); + }, + ); } /// serializes catergory cache values. Future _serializeCategoryTagCacheValuesAsync( - XmlBuilder builder, ChartSerie firstSerie, Worksheet? dataSheet) async { + XmlBuilder builder, + ChartSerie firstSerie, + Worksheet? dataSheet, + ) async { // ignore: unnecessary_nullable_for_final_variable_declarations final Range? serieRange = firstSerie.categoryLabels; if (serieRange != null) { final int count = serieRange.count; final int serieStartRow = serieRange.row; final int serieStartColumn = serieRange.column; - builder.element('c:ptCount', nest: () async { - builder.attribute('val', count); - }); + builder.element( + 'c:ptCount', + nest: () async { + builder.attribute('val', count); + }, + ); int index = 0; while (index < count) { - final String? value = dataSheet != null - ? dataSheet - .getRangeByIndex(serieStartRow + index, serieStartColumn) - .text - : ''; + final String? value = + dataSheet != null + ? dataSheet + .getRangeByIndex(serieStartRow + index, serieStartColumn) + .text + : ''; if (value != null) { - builder.element('c:pt', nest: () async { - builder.attribute('idx', index); - builder.element('c:v', nest: value); - }); + builder.element( + 'c:pt', + nest: () async { + builder.attribute('idx', index); + builder.element('c:v', nest: value); + }, + ); } index++; } @@ -2372,56 +3852,89 @@ class ChartSerialization { /// serializes text cache values. Future _serializeTextTagCacheValuesAsync( - XmlBuilder builder, ChartSerie firstSerie) async { - builder.element('c:ptCount', nest: () async { - builder.attribute('val', 1); - }); - builder.element('c:pt', nest: () async { - builder.attribute('idx', 0); - if (firstSerie.name != null) { - builder.element('c:v', nest: firstSerie.name); - } - }); + XmlBuilder builder, + ChartSerie firstSerie, + ) async { + builder.element( + 'c:ptCount', + nest: () async { + builder.attribute('val', 1); + }, + ); + builder.element( + 'c:pt', + nest: () async { + builder.attribute('idx', 0); + if (firstSerie.name != null) { + builder.element('c:v', nest: firstSerie.name); + } + }, + ); } /// serializes fill for the charts. Future _serializeFillAsync( - XmlBuilder builder, - ExcelChartLinePattern linePattern, - String? lineColor, - bool hasSerie) async { - builder.element('c:spPr', nest: () async { - if (lineColor == null) { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', 'FFFFFF'); - }); - }); - } - builder.element('a:ln', nest: () async { - if (linePattern != ExcelChartLinePattern.none) { - if (!hasSerie || lineColor != null) { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - if (lineColor != null) { - builder.attribute('val', lineColor.replaceAll('#', '')); - } else { - builder.attribute('val', '0070C0'); - } - }); - }); - } - if (linePattern != ExcelChartLinePattern.solid) { - builder.element('a:prstDash', nest: () async { - builder.attribute('val', _linePattern[linePattern]); - }); - } - } else { - builder.element('a:noFill', nest: () async {}); + XmlBuilder builder, + ExcelChartLinePattern linePattern, + String? lineColor, + bool hasSerie, + ) async { + builder.element( + 'c:spPr', + nest: () async { + if (lineColor == null) { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', 'FFFFFF'); + }, + ); + }, + ); } - builder.element('a:round', nest: () async {}); - }); - }); + builder.element( + 'a:ln', + nest: () async { + if (linePattern != ExcelChartLinePattern.none) { + if (!hasSerie || lineColor != null) { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + if (lineColor != null) { + builder.attribute( + 'val', + lineColor.replaceAll('#', ''), + ); + } else { + builder.attribute('val', '0070C0'); + } + }, + ); + }, + ); + } + if (linePattern != ExcelChartLinePattern.solid) { + builder.element( + 'a:prstDash', + nest: () async { + builder.attribute('val', _linePattern[linePattern]); + }, + ); + } + } else { + builder.element('a:noFill', nest: () async {}); + } + builder.element('a:round', nest: () async {}); + }, + ); + }, + ); } /// serializes axies of the series. @@ -2436,182 +3949,332 @@ class ChartSerialization { /// serializes empty charts. Future _serializeEmptyChartAsync( - XmlBuilder builder, Chart chart) async { - builder.element('c:barChart', nest: () async { - builder.element('c:barDir', nest: () async { - builder.attribute('val', 'col'); - }); - builder.element('c:grouping', nest: () async { - builder.attribute('val', 'clustered'); - }); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - _serializeEmptyChartDataLabelsAsync(builder); - builder.element('c:gapWidth', nest: () async { - builder.attribute('val', 150); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - }); + XmlBuilder builder, + Chart chart, + ) async { + builder.element( + 'c:barChart', + nest: () async { + builder.element( + 'c:barDir', + nest: () async { + builder.attribute('val', 'col'); + }, + ); + builder.element( + 'c:grouping', + nest: () async { + builder.attribute('val', 'clustered'); + }, + ); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + _serializeEmptyChartDataLabelsAsync(builder); + builder.element( + 'c:gapWidth', + nest: () async { + builder.attribute('val', 150); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + }, + ); } /// serializes category axis of the chart. Future _serializeCategoryAxisAsync( - XmlBuilder builder, ChartCategoryAxis axis) async { - builder.element('c:catAx', nest: () async { - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:scaling', nest: () async { - builder.element('c:orientation', nest: () async { - builder.attribute('val', 'minMax'); - }); - }); - builder.element('c:delete', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:axPos', nest: () async { - builder.attribute('val', 'b'); - }); - if (axis.hasAxisTitle) { - _serializeChartTextAreaAsync(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () async { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - builder.element('c:majorTickMark', nest: () async { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () async { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () async { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async {}); - }); - builder.element('c:crossAx', nest: () async { - builder.attribute('val', 57253888); - }); - builder.element('c:crosses', nest: () async { - builder.attribute('val', 'autoZero'); - }); - builder.element('c:auto', nest: () async { - builder.attribute('val', 1); - }); - builder.element('c:lblAlgn', nest: () async { - builder.attribute('val', 'ctr'); - }); - builder.element('c:lblOffset', nest: () async { - builder.attribute('val', 100); - }); - builder.element('c:noMultiLvlLbl', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:tickMarkSkip', nest: () async { - builder.attribute('val', 1); - }); - }); + XmlBuilder builder, + ChartCategoryAxis axis, + ) async { + builder.element( + 'c:catAx', + nest: () async { + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:scaling', + nest: () async { + builder.element( + 'c:orientation', + nest: () async { + builder.attribute('val', 'minMax'); + }, + ); + }, + ); + builder.element( + 'c:delete', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:axPos', + nest: () async { + builder.attribute('val', 'b'); + }, + ); + if (axis.hasAxisTitle) { + _serializeChartTextAreaAsync(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () async { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + builder.element( + 'c:majorTickMark', + nest: () async { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () async { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () async { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () async { + builder.element('a:ln', nest: () async {}); + }, + ); + builder.element( + 'c:crossAx', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + builder.element( + 'c:crosses', + nest: () async { + builder.attribute('val', 'autoZero'); + }, + ); + builder.element( + 'c:auto', + nest: () async { + builder.attribute('val', 1); + }, + ); + builder.element( + 'c:lblAlgn', + nest: () async { + builder.attribute('val', 'ctr'); + }, + ); + builder.element( + 'c:lblOffset', + nest: () async { + builder.attribute('val', 100); + }, + ); + builder.element( + 'c:noMultiLvlLbl', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:tickMarkSkip', + nest: () async { + builder.attribute('val', 1); + }, + ); + }, + ); } /// serializes Value axis of the chart. Future _serializeValueAxisAsync( - XmlBuilder builder, ChartValueAxis axis) async { - builder.element('c:valAx', nest: () async { - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - builder.element('c:scaling', nest: () async { - builder.element('c:orientation', nest: () async { - builder.attribute('val', 'minMax'); - }); - if (!axis.isAutoMax) { - builder.element('c:max', nest: () async { - builder.attribute('val', axis.maximumValue); - }); - } - if (axis.isAutoMin) { - builder.element('c:min', nest: () async { - builder.attribute('val', axis.minimumValue); - }); - } - }); - builder.element('c:delete', nest: () async { - builder.attribute('val', '0'); - }); - builder.element('c:axPos', nest: () async { - builder.attribute('val', 'l'); - }); - if (axis.hasAxisTitle) { - _serializeChartTextAreaAsync(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () async { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - if (axis.hasMajorGridLines) { - builder.element('c:majorGridlines', nest: () async {}); - } - builder.element('c:majorTickMark', nest: () async { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () async { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () async { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async {}); - }); - builder.element('c:crossAx', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:crosses', nest: () async { - builder.attribute('val', 'autoZero'); - }); - final Chart chart = axis.parentChart; - final String strCrossBetween = - chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; - builder.element('c:crossBetween', nest: () async { - builder.attribute('val', strCrossBetween); - }); - }); + XmlBuilder builder, + ChartValueAxis axis, + ) async { + builder.element( + 'c:valAx', + nest: () async { + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + builder.element( + 'c:scaling', + nest: () async { + builder.element( + 'c:orientation', + nest: () async { + builder.attribute('val', 'minMax'); + }, + ); + if (!axis.isAutoMax) { + builder.element( + 'c:max', + nest: () async { + builder.attribute('val', axis.maximumValue); + }, + ); + } + if (axis.isAutoMin) { + builder.element( + 'c:min', + nest: () async { + builder.attribute('val', axis.minimumValue); + }, + ); + } + }, + ); + builder.element( + 'c:delete', + nest: () async { + builder.attribute('val', '0'); + }, + ); + builder.element( + 'c:axPos', + nest: () async { + builder.attribute('val', 'l'); + }, + ); + if (axis.hasAxisTitle) { + _serializeChartTextAreaAsync(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () async { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + if (axis.hasMajorGridLines) { + builder.element('c:majorGridlines', nest: () async {}); + } + builder.element( + 'c:majorTickMark', + nest: () async { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () async { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () async { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () async { + builder.element('a:ln', nest: () async {}); + }, + ); + builder.element( + 'c:crossAx', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:crosses', + nest: () async { + builder.attribute('val', 'autoZero'); + }, + ); + final Chart chart = axis.parentChart; + final String strCrossBetween = + chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; + builder.element( + 'c:crossBetween', + nest: () async { + builder.attribute('val', strCrossBetween); + }, + ); + }, + ); } /// serializes empty chart's datalabels. Future _serializeEmptyChartDataLabelsAsync(XmlBuilder builder) async { - builder.element('c:dLbls', nest: () async { - builder.element('c:showLegendKey', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showVal', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showCatName', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showSerName', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showPercent', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:showBubbleSize', nest: () async { - builder.attribute('val', 0); - }); - }); + builder.element( + 'c:dLbls', + nest: () async { + builder.element( + 'c:showLegendKey', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showVal', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showCatName', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showSerName', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showPercent', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:showBubbleSize', + nest: () async { + builder.attribute('val', 0); + }, + ); + }, + ); } /// Add the workbook data with filename to ZipArchive. @@ -2622,31 +4285,51 @@ class ChartSerialization { /// Serialize line 3D Chart. Future _serializeLine3DChartAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { late int gapdepth; - builder.element('c:line3DChart', nest: () async { - _serializeChartGroupingAsync(builder, chart); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; - } - builder.element('c:gapDepth', nest: () async { - builder.attribute('val', gapdepth); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 63149376); - }); - }); + builder.element( + 'c:line3DChart', + nest: () async { + _serializeChartGroupingAsync(builder, chart); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; + } + builder.element( + 'c:gapDepth', + nest: () async { + builder.attribute('val', gapdepth); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 63149376); + }, + ); + }, + ); _serializeAxesAsync(builder, chart); } @@ -2654,84 +4337,127 @@ class ChartSerialization { Future _serializeView3DAsync(XmlBuilder builder, Chart chart) async { final ChartSeriesCollection firstSerie = chart.series; - builder.element('c:view3D', nest: () async { - if (!chart.isdefaultElevation) { - builder.element('c:rotX', nest: () async { - builder.attribute('val', chart.elevation); - }); - } - if (firstSerie.innerList[0].serieType == ExcelChartType.pie3D) { - for (int i = 0; i < chart.series.count; i++) { - chart.rotation = - chart.series[i].serieFormat.commonSerieOptions.firstSliceAngle; + builder.element( + 'c:view3D', + nest: () async { + if (!chart.isdefaultElevation) { + builder.element( + 'c:rotX', + nest: () async { + builder.attribute('val', chart.elevation); + }, + ); } - } - if (!chart.isDefaultRotation) { - builder.element('c:rotY', nest: () async { - builder.attribute('val', chart.rotation); - }); - } - builder.element('c:depthPercent', nest: () async { - builder.attribute('val', chart.depthPercent); - }); - builder.element('c:rAngAx', nest: () async { - int defaultValue = 0; - - if (chart.rightAngleAxes || chart.isColumnOrBar) { - defaultValue = 1; + if (firstSerie.innerList[0].serieType == ExcelChartType.pie3D) { + for (int i = 0; i < chart.series.count; i++) { + chart.rotation = + chart.series[i].serieFormat.commonSerieOptions.firstSliceAngle; + } + } + if (!chart.isDefaultRotation) { + builder.element( + 'c:rotY', + nest: () async { + builder.attribute('val', chart.rotation); + }, + ); } + builder.element( + 'c:depthPercent', + nest: () async { + builder.attribute('val', chart.depthPercent); + }, + ); + builder.element( + 'c:rAngAx', + nest: () async { + int defaultValue = 0; + + if (chart.rightAngleAxes || chart.isColumnOrBar) { + defaultValue = 1; + } - builder.attribute('val', defaultValue); - }); - builder.element('perspective', nest: () async { - builder.attribute('val', chart.perspective * 2); - }); - }); + builder.attribute('val', defaultValue); + }, + ); + builder.element( + 'perspective', + nest: () async { + builder.attribute('val', chart.perspective * 2); + }, + ); + }, + ); } /// Serialize bar3D chart. Future _serializeBar3DChartAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { late int gapdepth; late int gapwidth; - builder.element('c:bar3DChart', nest: () async { - final String strDirection = - chart.chartType.toString().contains('bar') ? 'bar' : 'col'; - - builder.element('c:barDir', nest: () async { - builder.attribute('val', strDirection); - }); - - _serializeChartGroupingAsync(builder, chart); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; - gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; - } + builder.element( + 'c:bar3DChart', + nest: () async { + final String strDirection = + chart.chartType.toString().contains('bar') ? 'bar' : 'col'; + + builder.element( + 'c:barDir', + nest: () async { + builder.attribute('val', strDirection); + }, + ); + + _serializeChartGroupingAsync(builder, chart); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + gapdepth = firstSerie.serieFormat.commonSerieOptions.gapDepth; + gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; + } - builder.element('c:gapWidth', nest: () async { - builder.attribute('val', gapwidth); - }); - builder.element('c:gapDepth', nest: () async { - builder.attribute('val', gapdepth); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - }); + builder.element( + 'c:gapWidth', + nest: () async { + builder.attribute('val', gapwidth); + }, + ); + builder.element( + 'c:gapDepth', + nest: () async { + builder.attribute('val', gapdepth); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + }, + ); _serializeAxesAsync(builder, chart); } // Serializes pie of pie or pie of bar chart. Future _serializeOfPieChartAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { late int gapwidth; late int pieSecondSize; final ExcelChartType type = chart.series[0].serieType; @@ -2741,366 +4467,642 @@ class ChartSerialization { } else if (type == ExcelChartType.pieBar) { isPieOrBar = 'bar'; } - builder.element('c:ofPieChart', nest: () async { - builder.element('c:ofPieType', nest: () async { - builder.attribute('val', isPieOrBar); - }); - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 1); - }); + builder.element( + 'c:ofPieChart', + nest: () async { + builder.element( + 'c:ofPieType', + nest: () async { + builder.attribute('val', isPieOrBar); + }, + ); + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 1); + }, + ); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - pieSecondSize = firstSerie.serieFormat.commonSerieOptions.pieSecondSize; - gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; - } + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + pieSecondSize = + firstSerie.serieFormat.commonSerieOptions.pieSecondSize; + gapwidth = firstSerie.serieFormat.commonSerieOptions.gapWidth; + } - builder.element('c:gapWidth', nest: () async { - builder.attribute('val', gapwidth); - }); - builder.element('c:secondPieSize', nest: () async { - builder.attribute('val', pieSecondSize); - }); - builder.element('c:serLines', nest: () async { - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async {}); - }); - }); - }); + builder.element( + 'c:gapWidth', + nest: () async { + builder.attribute('val', gapwidth); + }, + ); + builder.element( + 'c:secondPieSize', + nest: () async { + builder.attribute('val', pieSecondSize); + }, + ); + builder.element( + 'c:serLines', + nest: () async { + builder.element( + 'c:spPr', + nest: () async { + builder.element('a:ln', nest: () async {}); + }, + ); + }, + ); + }, + ); } ///Serialize pie 3D chart. Future _serializeOfPie3DChartAsync( - XmlBuilder builder, Chart chart) async { - builder.element('c:pie3DChart', nest: () async { - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 1); - }); - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - } - }); + XmlBuilder builder, + Chart chart, + ) async { + builder.element( + 'c:pie3DChart', + nest: () async { + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 1); + }, + ); + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + } + }, + ); } /// Serializes stock chart. Future _serializeStockChartAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { final ExcelChartType type = chart.series.innerList[0].serieType; if (type == ExcelChartType.stockVolumeOpenHighLowClose || type == ExcelChartType.stockVolumeHighLowClose) { - builder.element('c:barChart', nest: () async { - builder.element('c:barDir', nest: () async { - builder.attribute('val', 'col'); - }); - builder.element('c:grouping', nest: () async { - builder.attribute('val', 'clustered'); - }); - - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 0); - }); - - final ChartSerie firstSerie = chart.series[0]; - _serializeSerieAsync(builder, firstSerie); - - builder.element('c:gapWidth', nest: () async { - builder.attribute( - 'val', firstSerie.serieFormat.commonSerieOptions.gapWidth); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 59983360); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 57253888); - }); - }); - } - builder.element('c:stockChart', nest: () async { - if (type == ExcelChartType.stockHighLowClose || - type == ExcelChartType.stockOpenHighLowClose) { - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; + builder.element( + 'c:barChart', + nest: () async { + builder.element( + 'c:barDir', + nest: () async { + builder.attribute('val', 'col'); + }, + ); + builder.element( + 'c:grouping', + nest: () async { + builder.attribute('val', 'clustered'); + }, + ); + + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 0); + }, + ); + + final ChartSerie firstSerie = chart.series[0]; _serializeSerieAsync(builder, firstSerie); - } - } else if (type == ExcelChartType.stockVolumeHighLowClose || - type == ExcelChartType.stockVolumeOpenHighLowClose) { - for (int i = 0; i < chart.series.count; i++) { - if ((type == ExcelChartType.stockVolumeOpenHighLowClose || - type == ExcelChartType.stockVolumeHighLowClose) && - chart.series.innerList[0] != chart.series.innerList[i]) { + + builder.element( + 'c:gapWidth', + nest: () async { + builder.attribute( + 'val', + firstSerie.serieFormat.commonSerieOptions.gapWidth, + ); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 59983360); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 57253888); + }, + ); + }, + ); + } + builder.element( + 'c:stockChart', + nest: () async { + if (type == ExcelChartType.stockHighLowClose || + type == ExcelChartType.stockOpenHighLowClose) { + for (int i = 0; i < chart.series.count; i++) { final ChartSerie firstSerie = chart.series[i]; _serializeSerieAsync(builder, firstSerie); } + } else if (type == ExcelChartType.stockVolumeHighLowClose || + type == ExcelChartType.stockVolumeOpenHighLowClose) { + for (int i = 0; i < chart.series.count; i++) { + if ((type == ExcelChartType.stockVolumeOpenHighLowClose || + type == ExcelChartType.stockVolumeHighLowClose) && + chart.series.innerList[0] != chart.series.innerList[i]) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + } + } } - } - builder.element('c:hiLowLines', nest: () async { - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', '000000'); - }); - }); - builder.element('a:prstDash', nest: () async { - builder.attribute('val', 'solid'); - }); - }); - }); - }); - if (type == ExcelChartType.stockOpenHighLowClose || - type == ExcelChartType.stockVolumeOpenHighLowClose) { - builder.element('c:upDownBars', nest: () async { - builder.element('c:gapWidth', nest: () async { - builder.attribute('val', '100'); - }); - builder.element('c:upBars', nest: () async { - builder.element('c:spPr', nest: () async { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', 'FFFFFF'); - }); - }); - }); - }); - builder.element('c:downBars', nest: () async { - builder.element('c:spPr', nest: () async { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', '000000'); - }); - }); - }); - }); - }); - } - if (chart.series[0].serieFormat.markerStyle != - ExcelChartMarkerType.none) { - builder.element('c:marker', nest: () async { - builder.attribute('val', 1); - }); - } + builder.element( + 'c:hiLowLines', + nest: () async { + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:ln', + nest: () async { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', '000000'); + }, + ); + }, + ); + builder.element( + 'a:prstDash', + nest: () async { + builder.attribute('val', 'solid'); + }, + ); + }, + ); + }, + ); + }, + ); + if (type == ExcelChartType.stockOpenHighLowClose || + type == ExcelChartType.stockVolumeOpenHighLowClose) { + builder.element( + 'c:upDownBars', + nest: () async { + builder.element( + 'c:gapWidth', + nest: () async { + builder.attribute('val', '100'); + }, + ); + builder.element( + 'c:upBars', + nest: () async { + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', 'FFFFFF'); + }, + ); + }, + ); + }, + ); + }, + ); + builder.element( + 'c:downBars', + nest: () async { + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', '000000'); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); + } + if (chart.series[0].serieFormat.markerStyle != + ExcelChartMarkerType.none) { + builder.element( + 'c:marker', + nest: () async { + builder.attribute('val', 1); + }, + ); + } - builder.element('c:axId', nest: () async { - builder.attribute('val', 62908672); - }); - builder.element('c:axId', nest: () async { - builder.attribute('val', 61870848); - }); - }); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 62908672); + }, + ); + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', 61870848); + }, + ); + }, + ); if (type == ExcelChartType.stockVolumeOpenHighLowClose || type == ExcelChartType.stockVolumeHighLowClose) { _serializeAxesforStockChartAsync( - builder, chart, 59983360, 57253888, true); + builder, + chart, + 59983360, + 57253888, + true, + ); _serializeAxesforStockChartAsync( - builder, chart, 62908672, 61870848, false); + builder, + chart, + 62908672, + 61870848, + false, + ); } else { _serializeAxesforStockChartAsync( - builder, chart, 62908672, 61870848, true); + builder, + chart, + 62908672, + 61870848, + true, + ); } } ///serialize stock axes - Future _serializeAxesforStockChartAsync(XmlBuilder builder, Chart chart, - int axisId, int crossAx, bool isBar) async { + Future _serializeAxesforStockChartAsync( + XmlBuilder builder, + Chart chart, + int axisId, + int crossAx, + bool isBar, + ) async { if (chart.isCategoryAxisAvail) { _serializeCategoryAxisForStockAsync( - builder, chart.primaryCategoryAxis, axisId, crossAx, isBar); + builder, + chart.primaryCategoryAxis, + axisId, + crossAx, + isBar, + ); } if (chart.isValueAxisAvail) { _serializeValueAxisForStockchartAsync( - builder, chart.primaryCategoryAxis, axisId, crossAx, isBar); + builder, + chart.primaryCategoryAxis, + axisId, + crossAx, + isBar, + ); } } ///Serialize catogory axis for stock chart - Future _serializeCategoryAxisForStockAsync(XmlBuilder builder, - ChartCategoryAxis axis, int axisId, int crossAx, bool isBar) async { - builder.element('c:catAx', nest: () async { - builder.element('c:axId', nest: () async { - builder.attribute('val', axisId); - }); - builder.element('c:scaling', nest: () async { - builder.element('c:orientation', nest: () async { - builder.attribute('val', 'minMax'); - }); - }); - int delete = 0; - String axpos = 'b'; - if (!isBar) { - delete = 1; - axpos = 't'; - } - builder.element('c:delete', nest: () async { - builder.attribute('val', delete); - }); - builder.element('c:axPos', nest: () async { - builder.attribute('val', axpos); - }); - if (axis.hasAxisTitle) { - _serializeChartTextAreaAsync(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () async { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - builder.element('c:majorTickMark', nest: () async { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () async { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () async { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async { - if (!isBar) { - builder.attribute('w', 12700); - } - }); - }); - builder.element('c:crossAx', nest: () async { - builder.attribute('val', crossAx); - }); - builder.element('c:crosses', nest: () async { - builder.attribute('val', 'autoZero'); - }); - builder.element('c:auto', nest: () async { - builder.attribute('val', 1); - }); - builder.element('c:lblAlgn', nest: () async { - builder.attribute('val', 'ctr'); - }); - builder.element('c:lblOffset', nest: () async { - builder.attribute('val', 100); - }); - builder.element('c:noMultiLvlLbl', nest: () async { - builder.attribute('val', 0); - }); - builder.element('c:tickMarkSkip', nest: () async { - builder.attribute('val', 1); - }); - }); + Future _serializeCategoryAxisForStockAsync( + XmlBuilder builder, + ChartCategoryAxis axis, + int axisId, + int crossAx, + bool isBar, + ) async { + builder.element( + 'c:catAx', + nest: () async { + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', axisId); + }, + ); + builder.element( + 'c:scaling', + nest: () async { + builder.element( + 'c:orientation', + nest: () async { + builder.attribute('val', 'minMax'); + }, + ); + }, + ); + int delete = 0; + String axpos = 'b'; + if (!isBar) { + delete = 1; + axpos = 't'; + } + builder.element( + 'c:delete', + nest: () async { + builder.attribute('val', delete); + }, + ); + builder.element( + 'c:axPos', + nest: () async { + builder.attribute('val', axpos); + }, + ); + if (axis.hasAxisTitle) { + _serializeChartTextAreaAsync(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () async { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + builder.element( + 'c:majorTickMark', + nest: () async { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () async { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () async { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:ln', + nest: () async { + if (!isBar) { + builder.attribute('w', 12700); + } + }, + ); + }, + ); + builder.element( + 'c:crossAx', + nest: () async { + builder.attribute('val', crossAx); + }, + ); + builder.element( + 'c:crosses', + nest: () async { + builder.attribute('val', 'autoZero'); + }, + ); + builder.element( + 'c:auto', + nest: () async { + builder.attribute('val', 1); + }, + ); + builder.element( + 'c:lblAlgn', + nest: () async { + builder.attribute('val', 'ctr'); + }, + ); + builder.element( + 'c:lblOffset', + nest: () async { + builder.attribute('val', 100); + }, + ); + builder.element( + 'c:noMultiLvlLbl', + nest: () async { + builder.attribute('val', 0); + }, + ); + builder.element( + 'c:tickMarkSkip', + nest: () async { + builder.attribute('val', 1); + }, + ); + }, + ); } ///Serialize value axis for stock chart - Future _serializeValueAxisForStockchartAsync(XmlBuilder builder, - ChartCategoryAxis axis, int axisId, int crossAx, bool isBar) async { - builder.element('c:valAx', nest: () async { - builder.element('c:axId', nest: () async { - builder.attribute('val', crossAx); - }); - builder.element('c:scaling', nest: () async { - builder.element('c:orientation', nest: () async { - builder.attribute('val', 'minMax'); - }); - if (!axis.isAutoMax) { - builder.element('c:max', nest: () async { - builder.attribute('val', axis.maximumValue); - }); - } - if (axis.isAutoMin) { - builder.element('c:min', nest: () async { - builder.attribute('val', axis.minimumValue); - }); - } - }); - builder.element('c:delete', nest: () async { - builder.attribute('val', '0'); - }); - String axpos = 'l'; - - if (!isBar) { - axpos = 'r'; - } + Future _serializeValueAxisForStockchartAsync( + XmlBuilder builder, + ChartCategoryAxis axis, + int axisId, + int crossAx, + bool isBar, + ) async { + builder.element( + 'c:valAx', + nest: () async { + builder.element( + 'c:axId', + nest: () async { + builder.attribute('val', crossAx); + }, + ); + builder.element( + 'c:scaling', + nest: () async { + builder.element( + 'c:orientation', + nest: () async { + builder.attribute('val', 'minMax'); + }, + ); + if (!axis.isAutoMax) { + builder.element( + 'c:max', + nest: () async { + builder.attribute('val', axis.maximumValue); + }, + ); + } + if (axis.isAutoMin) { + builder.element( + 'c:min', + nest: () async { + builder.attribute('val', axis.minimumValue); + }, + ); + } + }, + ); + builder.element( + 'c:delete', + nest: () async { + builder.attribute('val', '0'); + }, + ); + String axpos = 'l'; + + if (!isBar) { + axpos = 'r'; + } - builder.element('c:axPos', nest: () async { - builder.attribute('val', axpos); - }); + builder.element( + 'c:axPos', + nest: () async { + builder.attribute('val', axpos); + }, + ); - if (axpos == 'l') { - builder.element('c:majorGridlines', nest: () async {}); - } + if (axpos == 'l') { + builder.element('c:majorGridlines', nest: () async {}); + } - if (axis.hasAxisTitle) { - _serializeChartTextAreaAsync(builder, axis.titleArea); - } - if (axis.numberFormat != '' && axis.numberFormat != 'General') { - builder.element('c:numFmt', nest: () async { - builder.attribute('formatCode', axis.numberFormat); - builder.attribute('sourceLinked', '0'); - }); - } - if (axis.hasMajorGridLines) { - builder.element('c:majorGridlines', nest: () async {}); - } - builder.element('c:majorTickMark', nest: () async { - builder.attribute('val', 'out'); - }); - builder.element('c:minorTickMark', nest: () async { - builder.attribute('val', 'none'); - }); - builder.element('c:tickLblPos', nest: () async { - builder.attribute('val', 'nextTo'); - }); - builder.element('c:spPr', nest: () async { - builder.element('a:ln', nest: () async {}); - }); - builder.element('c:crossAx', nest: () async { - builder.attribute('val', axisId); - }); - String crosses = 'autoZero'; - if (!isBar) { - crosses = 'max'; - } - builder.element('c:crosses', nest: () async { - builder.attribute('val', crosses); - }); - final Chart chart = axis.parentChart; - final String strCrossBetween = - chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; - builder.element('c:crossBetween', nest: () async { - builder.attribute('val', strCrossBetween); - }); - }); + if (axis.hasAxisTitle) { + _serializeChartTextAreaAsync(builder, axis.titleArea); + } + if (axis.numberFormat != '' && axis.numberFormat != 'General') { + builder.element( + 'c:numFmt', + nest: () async { + builder.attribute('formatCode', axis.numberFormat); + builder.attribute('sourceLinked', '0'); + }, + ); + } + if (axis.hasMajorGridLines) { + builder.element('c:majorGridlines', nest: () async {}); + } + builder.element( + 'c:majorTickMark', + nest: () async { + builder.attribute('val', 'out'); + }, + ); + builder.element( + 'c:minorTickMark', + nest: () async { + builder.attribute('val', 'none'); + }, + ); + builder.element( + 'c:tickLblPos', + nest: () async { + builder.attribute('val', 'nextTo'); + }, + ); + builder.element( + 'c:spPr', + nest: () async { + builder.element('a:ln', nest: () async {}); + }, + ); + builder.element( + 'c:crossAx', + nest: () async { + builder.attribute('val', axisId); + }, + ); + String crosses = 'autoZero'; + if (!isBar) { + crosses = 'max'; + } + builder.element( + 'c:crosses', + nest: () async { + builder.attribute('val', crosses); + }, + ); + final Chart chart = axis.parentChart; + final String strCrossBetween = + chart.primaryCategoryAxis.isBetween ? 'between' : 'midCat'; + builder.element( + 'c:crossBetween', + nest: () async { + builder.attribute('val', strCrossBetween); + }, + ); + }, + ); } ///Serialize doughnut/doughnut_exploded charts Future _serializedoughnutchartAsync( - XmlBuilder builder, Chart chart) async { + XmlBuilder builder, + Chart chart, + ) async { late int doughnutHoleSize; late int firstSliceAngle; - builder.element('c:doughnutChart', nest: () async { - builder.element('c:varyColors', nest: () async { - builder.attribute('val', 1); - }); - - for (int i = 0; i < chart.series.count; i++) { - final ChartSerie firstSerie = chart.series[i]; - _serializeSerieAsync(builder, firstSerie); - firstSliceAngle = - firstSerie.serieFormat.commonSerieOptions.firstSliceAngle; - doughnutHoleSize = - firstSerie.serieFormat.commonSerieOptions.holeSizePercent; - } - builder.element('c:firstSliceAng', nest: () async { - builder.attribute('val', firstSliceAngle); - }); - builder.element('c:holeSize', nest: () async { - builder.attribute('val', doughnutHoleSize); - }); - }); + builder.element( + 'c:doughnutChart', + nest: () async { + builder.element( + 'c:varyColors', + nest: () async { + builder.attribute('val', 1); + }, + ); + + for (int i = 0; i < chart.series.count; i++) { + final ChartSerie firstSerie = chart.series[i]; + _serializeSerieAsync(builder, firstSerie); + firstSliceAngle = + firstSerie.serieFormat.commonSerieOptions.firstSliceAngle; + doughnutHoleSize = + firstSerie.serieFormat.commonSerieOptions.holeSizePercent; + } + builder.element( + 'c:firstSliceAng', + nest: () async { + builder.attribute('val', firstSliceAngle); + }, + ); + builder.element( + 'c:holeSize', + nest: () async { + builder.attribute('val', doughnutHoleSize); + }, + ); + }, + ); } ///Serialize marker for stock and line charts Future _serializeMarkerAsync( - XmlBuilder builder, ChartSerie firstSerie) async { + XmlBuilder builder, + ChartSerie firstSerie, + ) async { final ExcelChartType type = firstSerie.serieType; if ((firstSerie.serieFormat.markerStyle == ExcelChartMarkerType.none) && @@ -3111,30 +5113,47 @@ class ChartSerialization { type == ExcelChartType.stockVolumeOpenHighLowClose || type == ExcelChartType.stockVolumeHighLowClose || type == ExcelChartType.stockOpenHighLowClose)) { - builder.element('c:marker', nest: () async { - builder.element('c:symbol', nest: () async { - builder.attribute('val', 'none'); - }); - }); + builder.element( + 'c:marker', + nest: () async { + builder.element( + 'c:symbol', + nest: () async { + builder.attribute('val', 'none'); + }, + ); + }, + ); } else if ((firstSerie.serieFormat.markerStyle == ExcelChartMarkerType.none) && (type == ExcelChartType.lineMarkers || type == ExcelChartType.lineMarkersStacked || type == ExcelChartType.lineMarkersStacked100)) { - builder.element('c:marker', nest: () async { - builder.element('c:symbol', nest: () async { - builder.attribute('val', 'circle'); - }); - builder.element('c:size', nest: () async { - builder.attribute('val', '5'); - }); - }); + builder.element( + 'c:marker', + nest: () async { + builder.element( + 'c:symbol', + nest: () async { + builder.attribute('val', 'circle'); + }, + ); + builder.element( + 'c:size', + nest: () async { + builder.attribute('val', '5'); + }, + ); + }, + ); } else if (firstSerie.serieFormat.markerStyle != ExcelChartMarkerType.none) { - final String markerBackgroundColor = - firstSerie.serieFormat.markerBackgroundColor.replaceAll('#', ''); - final String markerBorderColor = - firstSerie.serieFormat.markerBorderColor.replaceAll('#', ''); + final String markerBackgroundColor = firstSerie + .serieFormat + .markerBackgroundColor + .replaceAll('#', ''); + final String markerBorderColor = firstSerie.serieFormat.markerBorderColor + .replaceAll('#', ''); late String exclMarkertype; if (firstSerie.serieFormat.markerStyle == ExcelChartMarkerType.diamond) { exclMarkertype = 'diamond'; @@ -3161,28 +5180,55 @@ class ChartSerialization { exclMarkertype = 'star'; } - builder.element('c:marker', nest: () async { - builder.element('c:symbol', nest: () async { - builder.attribute('val', exclMarkertype); - }); - builder.element('c:size', nest: () async { - builder.attribute('val', '5'); - }); - builder.element('c:spPr', nest: () async { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', markerBackgroundColor); - }); - }); - builder.element('a:ln', nest: () async { - builder.element('a:solidFill', nest: () async { - builder.element('a:srgbClr', nest: () async { - builder.attribute('val', markerBorderColor); - }); - }); - }); - }); - }); + builder.element( + 'c:marker', + nest: () async { + builder.element( + 'c:symbol', + nest: () async { + builder.attribute('val', exclMarkertype); + }, + ); + builder.element( + 'c:size', + nest: () async { + builder.attribute('val', '5'); + }, + ); + builder.element( + 'c:spPr', + nest: () async { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', markerBackgroundColor); + }, + ); + }, + ); + builder.element( + 'a:ln', + nest: () async { + builder.element( + 'a:solidFill', + nest: () async { + builder.element( + 'a:srgbClr', + nest: () async { + builder.attribute('val', markerBorderColor); + }, + ); + }, + ); + }, + ); + }, + ); + }, + ); } } } diff --git a/packages/syncfusion_officechart/pubspec.yaml b/packages/syncfusion_officechart/pubspec.yaml index 283583ea9..bf993b9ce 100644 --- a/packages/syncfusion_officechart/pubspec.yaml +++ b/packages/syncfusion_officechart/pubspec.yaml @@ -1,19 +1,17 @@ name: syncfusion_officechart description: Syncfusion Flutter Office Chart is a library written natively in Dart for creating Office charts from scratch. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_officechart environment: - sdk: ">=3.4.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter xml: ">=5.1.0 <7.0.0" - archive: ">=3.1.2 <4.1.0" + archive: ">=4.0.0 <5.0.0" syncfusion_flutter_xlsio: path: ../syncfusion_flutter_xlsio - - diff --git a/packages/syncfusion_officecore/CHANGELOG.md b/packages/syncfusion_officecore/CHANGELOG.md index a4414325a..e85ec0b05 100644 --- a/packages/syncfusion_officecore/CHANGELOG.md +++ b/packages/syncfusion_officecore/CHANGELOG.md @@ -1,4 +1,16 @@ -## [Unreleased] +## Unreleased + +**General** + +* The compatible version of our Flutter OfficeCore widget has been updated to Flutter SDK 3.32.0. + +## [29.1.39] - 22/04/2025 + +**General** + +* The minimum Dart version has been updated to 3.7. + +## [29.1.33] - 25/03/2025 **General** @@ -29,7 +41,7 @@ **General** -* The compatible version of our Flutter OfficeCore widget has been updated to Flutter SDK 3.24.0. +* The compatible version of our Flutter OfficeCore widget has been updated to Flutter SDK 3.24.0. ## [18.3.35-beta] - 10/01/2020 diff --git a/packages/syncfusion_officecore/example/lib/helper/save_file_mobile.dart b/packages/syncfusion_officecore/example/lib/helper/save_file_mobile.dart index c7ddbff8b..856ba8bdb 100644 --- a/packages/syncfusion_officecore/example/lib/helper/save_file_mobile.dart +++ b/packages/syncfusion_officecore/example/lib/helper/save_file_mobile.dart @@ -20,8 +20,9 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else { path = await PathProviderPlatform.instance.getApplicationSupportPath(); } - final File file = - File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName'); + final File file = File( + Platform.isWindows ? '$path\\$fileName' : '$path/$fileName', + ); await file.writeAsBytes(bytes, flush: true); if (Platform.isAndroid || Platform.isIOS) { //Launch the file (used open_file package) @@ -31,7 +32,8 @@ Future saveAndLaunchFile(List bytes, String fileName) async { } else if (Platform.isMacOS) { await Process.run('open', ['$path/$fileName'], runInShell: true); } else if (Platform.isLinux) { - await Process.run('xdg-open', ['$path/$fileName'], - runInShell: true); + await Process.run('xdg-open', [ + '$path/$fileName', + ], runInShell: true); } } diff --git a/packages/syncfusion_officecore/example/lib/main.dart b/packages/syncfusion_officecore/example/lib/main.dart index 70987a3da..ba32e636b 100644 --- a/packages/syncfusion_officecore/example/lib/main.dart +++ b/packages/syncfusion_officecore/example/lib/main.dart @@ -26,7 +26,7 @@ class CreateExcelWidget extends StatelessWidget { class CreateExcelStatefulWidget extends StatefulWidget { /// Initalize the instance of the [CreateExcelStatefulWidget] class. const CreateExcelStatefulWidget({Key? key, required this.title}) - : super(key: key); + : super(key: key); /// title. final String title; @@ -39,9 +39,7 @@ class _CreateExcelState extends State { @override Widget build(BuildContext context) { return Scaffold( - appBar: AppBar( - title: Text(widget.title), - ), + appBar: AppBar(title: Text(widget.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, @@ -54,7 +52,7 @@ class _CreateExcelState extends State { ), onPressed: generateExcel, child: const Text('Generate Excel'), - ) + ), ], ), ), diff --git a/packages/syncfusion_officecore/example/pubspec.yaml b/packages/syncfusion_officecore/example/pubspec.yaml index 87e3faf01..a91707fc9 100644 --- a/packages/syncfusion_officecore/example/pubspec.yaml +++ b/packages/syncfusion_officecore/example/pubspec.yaml @@ -2,7 +2,7 @@ name: officecore_example description: Demo for creating a Excel file using syncfusion_flutter_officecore package. environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_officecore/pubspec.yaml b/packages/syncfusion_officecore/pubspec.yaml index d04ba99e2..ffd4350a0 100644 --- a/packages/syncfusion_officecore/pubspec.yaml +++ b/packages/syncfusion_officecore/pubspec.yaml @@ -1,10 +1,10 @@ name: syncfusion_officecore description: Syncfusion Flutter Office Core is a dependant library for Syncfusion Flutter XlsIO, written natively in Dart for creating Excel from scratch. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_officecore environment: - sdk: ">=3.3.0 <4.0.0" + sdk: ^3.7.0-0 dependencies: flutter: diff --git a/packages/syncfusion_pdfviewer_android/.gitignore b/packages/syncfusion_pdfviewer_android/.gitignore new file mode 100644 index 000000000..e7d347d9d --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/.gitignore @@ -0,0 +1,33 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +build/ diff --git a/packages/syncfusion_pdfviewer_android/.metadata b/packages/syncfusion_pdfviewer_android/.metadata new file mode 100644 index 000000000..cd12fae18 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "be698c48a6750c8cb8e61c740ca9991bb947aba2" + channel: "stable" + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 + base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 + - platform: android + create_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 + base_revision: be698c48a6750c8cb8e61c740ca9991bb947aba2 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/syncfusion_pdfviewer_android/CHANGELOG.md b/packages/syncfusion_pdfviewer_android/CHANGELOG.md new file mode 100644 index 000000000..fb70942b0 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/CHANGELOG.md @@ -0,0 +1,3 @@ +## Undefined + +* Initial release. \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/LICENSE b/packages/syncfusion_pdfviewer_android/LICENSE new file mode 100644 index 000000000..02291f801 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/LICENSE @@ -0,0 +1,12 @@ +Syncfusion® License + +Syncfusion® Flutter PDF Viewer package is available under the Syncfusion® Essential Studio® program, and can be licensed either under the Syncfusion® Community License Program or the Syncfusion® commercial license. + +To be qualified for the Syncfusion® Community License Program you must have a gross revenue of less than one (1) million U.S. dollars ($1,000,000.00 USD) per year and have less than five (5) developers in your organization, and agree to be bound by the Syncfusion® terms and conditions. + +Customers who do not qualify for the community license can contact sales@syncfusion.com for commercial licensing options. + +Under no circumstances can you use this product without (1) either a Community License or a commercial license and (2) without agreeing and abiding by the Syncfusion® license containing all terms and conditions. + +The Syncfusion® license that contains the terms and conditions can be found at +https://www.syncfusion.com/content/downloads/syncfusion_license.pdf \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/README.md b/packages/syncfusion_pdfviewer_android/README.md new file mode 100644 index 000000000..582d9c034 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/README.md @@ -0,0 +1,65 @@ +![syncfusion_flutter_pdfviewer](https://cdn.syncfusion.com/content/images/pdfviewer-banner.png) + +# Flutter PDF Viewer Android + +The Android implementation of the [Syncfusion® Flutter PDF Viewer](https://pub.dev/packages/syncfusion_flutter_pdfviewer) plugin. This implementation uses PDFium, an open-source PDF rendering engine, to enable high-performance rendering of password-protected PDF files specifically on Android devices running API level below 35. + +**Disclaimer:** This is a commercial package. To use this package, you need to have either a Syncfusion® commercial license or [Free Syncfusion® Community license](https://www.syncfusion.com/products/communitylicense). For more details, please check the [LICENSE](https://github.com/syncfusion/flutter-examples/blob/master/LICENSE) file. + +**Note:** +This is an optional package with limited Android support. Please note that this package is not compatible with Android devices running API level 35 (Android 15) and above + +## Table of contents +- [Get the demo application](#get-the-demo-application) +- [Useful links](#other-useful-links) +- [Installation](#installation) +- [Support and feedback](#support-and-feedback) +- [About Syncfusion®](#about-syncfusion) + +## Get the demo application + +Explore the full capabilities of our Flutter widgets on your device by installing our sample browser applications from the below app stores, and view samples code in GitHub. + +

+ + + +

+

+ + +

+ +## Other useful links + +Take a look at the following to learn more about Syncfusion® Flutter PDF Viewer: + +* [Syncfusion® Flutter PDF Viewer product page](https://www.syncfusion.com/flutter-widgets/flutter-pdf-viewer) +* [User guide documentation](https://help.syncfusion.com/flutter/pdf-viewer/overview) + +## Installation + +Install the latest version of [syncfusion_flutter_pdfviewer](https://pub.dev/packages/syncfusion_flutter_pdfviewer/install) and [syncfusion_pdfviewer_android](https://pub.dev/packages/syncfusion_pdfviewer_android/install) from [pub](https://pub.dev/publishers/syncfusion.com/packages). + +### Import the package + +This package is an optional Pdfium implementation of `syncfusion_flutter_pdfviewer` for the Android platform since version `29.2.9`. It is not imported by default. You can import it by adding the following dependency to your `pubspec.yaml` file: + +```yaml +dependencies: + ... + syncfusion_flutter_pdfviewer: ^29.2.9 + syncfusion_pdfviewer_android: ^29.2.9 + ... +``` + +## Support and Feedback + +* For any other queries, reach our [Syncfusion® support team](https://support.syncfusion.com/support/tickets/create) or post the queries through the [Community forums](https://www.syncfusion.com/forums) and submit a feature request or a bug through our [Feedback portal](https://www.syncfusion.com/feedback/flutter). +* To renew the subscription, click [renew](https://www.syncfusion.com/sales/products) or contact our sales team at salessupport@syncfusion.com | Toll Free: 1-888-9 DOTNET. + +## About Syncfusion® + +Founded in 2001 and headquartered in Research Triangle Park, N.C., Syncfusion® has more than 20,000 customers and more than 1 million users, including large financial institutions, Fortune 500 companies, and global IT consultancies. + +Today we provide 1,000+ controls and frameworks for web ([ASP.NET Core](https://www.syncfusion.com/aspnet-core-ui-controls), [ASP.NET MVC](https://www.syncfusion.com/aspnet-mvc-ui-controls), [ASP.NET WebForms](https://www.syncfusion.com/jquery/aspnet-web-forms-ui-controls), [JavaScript](https://www.syncfusion.com/javascript-ui-controls), [Angular](https://www.syncfusion.com/angular-ui-components), [React](https://www.syncfusion.com/react-ui-components), [Vue](https://www.syncfusion.com/vue-ui-components), [Flutter](https://www.syncfusion.com/flutter-widgets), and [Blazor](https://www.syncfusion.com/blazor-components)), mobile ([Xamarin](https://www.syncfusion.com/xamarin-ui-controls), [.NET MAUI](https://www.syncfusion.com/maui-controls), [Flutter](https://www.syncfusion.com/flutter-widgets), [UWP](https://www.syncfusion.com/uwp-ui-controls), and [JavaScript](https://www.syncfusion.com/javascript-ui-controls)), and desktop development ([Flutter](https://www.syncfusion.com/flutter-widgets), [WinForms](https://www.syncfusion.com/winforms-ui-controls), [WPF](https://www.syncfusion.com/wpf-ui-controls), [UWP](https://www.syncfusion.com/uwp-ui-controls), [.NET MAUI](https://www.syncfusion.com/maui-controls), and [WinUI](https://www.syncfusion.com/winui-controls)). We provide ready-to deploy enterprise software for dashboards, reports, data integration, and big data processing. Many customers have saved millions in licensing fees by deploying our software. \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/analysis_options.yaml b/packages/syncfusion_pdfviewer_android/analysis_options.yaml new file mode 100644 index 000000000..b08414c80 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/android/.gitignore b/packages/syncfusion_pdfviewer_android/android/.gitignore new file mode 100644 index 000000000..161bdcdaf --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/packages/syncfusion_pdfviewer_android/android/CMakeLists.txt b/packages/syncfusion_pdfviewer_android/android/CMakeLists.txt new file mode 100644 index 000000000..37ccf7527 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/CMakeLists.txt @@ -0,0 +1,21 @@ +cmake_minimum_required(VERSION 3.14) +project(syncfusion_pdfviewer_android) + +add_library(pdfium_wrapper SHARED + src/main/cpp/pdfium_wrapper_jni.cpp +) + +add_library(pdfium SHARED IMPORTED) +set_target_properties(pdfium PROPERTIES IMPORTED_LOCATION + ${CMAKE_SOURCE_DIR}/src/main/jniLibs/pdfium/${ANDROID_ABI}/libpdfium.so +) + +target_include_directories(pdfium_wrapper PRIVATE + src/main/cpp + ${CMAKE_SOURCE_DIR}/src/main/cpp/pdfium/include +) + +target_link_libraries( + pdfium_wrapper + pdfium +) \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/android/build.gradle b/packages/syncfusion_pdfviewer_android/android/build.gradle new file mode 100644 index 000000000..fe99e21a6 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/build.gradle @@ -0,0 +1,55 @@ +group = "com.syncfusion.syncfusion_pdfviewer_android" +version = "1.0" + +buildscript { + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:8.7.3") + } +} + +rootProject.allprojects { + repositories { + google() + mavenCentral() + } +} + +apply plugin: "com.android.library" + +android { + namespace = "com.syncfusion.flutter.pdfviewer.android" + + compileSdk = 35 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + defaultConfig { + minSdk = 21 + } + + externalNativeBuild { + cmake { + path "CMakeLists.txt" + } + } + + sourceSets { + main { + jniLibs.srcDirs = ['src/main/jniLibs/pdfium'] + } + } + + defaultConfig { + ndk { + abiFilters "armeabi-v7a", "arm64-v8a", "x86_64" + } + } +} diff --git a/packages/syncfusion_pdfviewer_android/android/settings.gradle b/packages/syncfusion_pdfviewer_android/android/settings.gradle new file mode 100644 index 000000000..086ff02e6 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'syncfusion_pdfviewer_android' diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/AndroidManifest.xml b/packages/syncfusion_pdfviewer_android/android/src/main/AndroidManifest.xml new file mode 100644 index 000000000..a2f47b605 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/src/main/AndroidManifest.xml @@ -0,0 +1,2 @@ + + diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/cpp/pdfium/include/fpdfview.h b/packages/syncfusion_pdfviewer_android/android/src/main/cpp/pdfium/include/fpdfview.h new file mode 100644 index 000000000..96b50e1d7 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/src/main/cpp/pdfium/include/fpdfview.h @@ -0,0 +1,1468 @@ +// Copyright 2014 The PDFium Authors +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com + +// This is the main header file for embedders of PDFium. It provides APIs to +// initialize the library, load documents, and render pages, amongst other +// things. +// +// NOTE: None of the PDFium APIs are thread-safe. They expect to be called +// from a single thread. Barring that, embedders are required to ensure (via +// a mutex or similar) that only a single PDFium call can be made at a time. +// +// NOTE: External docs refer to this file as "fpdfview.h", so do not rename +// despite lack of consistency with other public files. + +#ifndef PUBLIC_FPDFVIEW_H_ +#define PUBLIC_FPDFVIEW_H_ + +// clang-format off + +#include + +#if defined(_WIN32) && !defined(__WINDOWS__) +#include +#endif + +#ifdef PDF_ENABLE_XFA +// PDF_USE_XFA is set in confirmation that this version of PDFium can support +// XFA forms as requested by the PDF_ENABLE_XFA setting. +#define PDF_USE_XFA +#endif // PDF_ENABLE_XFA + +// PDF object types +#define FPDF_OBJECT_UNKNOWN 0 +#define FPDF_OBJECT_BOOLEAN 1 +#define FPDF_OBJECT_NUMBER 2 +#define FPDF_OBJECT_STRING 3 +#define FPDF_OBJECT_NAME 4 +#define FPDF_OBJECT_ARRAY 5 +#define FPDF_OBJECT_DICTIONARY 6 +#define FPDF_OBJECT_STREAM 7 +#define FPDF_OBJECT_NULLOBJ 8 +#define FPDF_OBJECT_REFERENCE 9 + +// PDF text rendering modes +typedef enum { + FPDF_TEXTRENDERMODE_UNKNOWN = -1, + FPDF_TEXTRENDERMODE_FILL = 0, + FPDF_TEXTRENDERMODE_STROKE = 1, + FPDF_TEXTRENDERMODE_FILL_STROKE = 2, + FPDF_TEXTRENDERMODE_INVISIBLE = 3, + FPDF_TEXTRENDERMODE_FILL_CLIP = 4, + FPDF_TEXTRENDERMODE_STROKE_CLIP = 5, + FPDF_TEXTRENDERMODE_FILL_STROKE_CLIP = 6, + FPDF_TEXTRENDERMODE_CLIP = 7, + FPDF_TEXTRENDERMODE_LAST = FPDF_TEXTRENDERMODE_CLIP, +} FPDF_TEXT_RENDERMODE; + +// PDF types - use incomplete types (never completed) to force API type safety. +typedef struct fpdf_action_t__* FPDF_ACTION; +typedef struct fpdf_annotation_t__* FPDF_ANNOTATION; +typedef struct fpdf_attachment_t__* FPDF_ATTACHMENT; +typedef struct fpdf_avail_t__* FPDF_AVAIL; +typedef struct fpdf_bitmap_t__* FPDF_BITMAP; +typedef struct fpdf_bookmark_t__* FPDF_BOOKMARK; +typedef struct fpdf_clippath_t__* FPDF_CLIPPATH; +typedef struct fpdf_dest_t__* FPDF_DEST; +typedef struct fpdf_document_t__* FPDF_DOCUMENT; +typedef struct fpdf_font_t__* FPDF_FONT; +typedef struct fpdf_form_handle_t__* FPDF_FORMHANDLE; +typedef const struct fpdf_glyphpath_t__* FPDF_GLYPHPATH; +typedef struct fpdf_javascript_action_t* FPDF_JAVASCRIPT_ACTION; +typedef struct fpdf_link_t__* FPDF_LINK; +typedef struct fpdf_page_t__* FPDF_PAGE; +typedef struct fpdf_pagelink_t__* FPDF_PAGELINK; +typedef struct fpdf_pageobject_t__* FPDF_PAGEOBJECT; // (text, path, etc.) +typedef struct fpdf_pageobjectmark_t__* FPDF_PAGEOBJECTMARK; +typedef const struct fpdf_pagerange_t__* FPDF_PAGERANGE; +typedef const struct fpdf_pathsegment_t* FPDF_PATHSEGMENT; +typedef struct fpdf_schhandle_t__* FPDF_SCHHANDLE; +typedef const struct fpdf_signature_t__* FPDF_SIGNATURE; +typedef void* FPDF_SKIA_CANVAS; // Passed into Skia as an SkCanvas. +typedef struct fpdf_structelement_t__* FPDF_STRUCTELEMENT; +typedef const struct fpdf_structelement_attr_t__* FPDF_STRUCTELEMENT_ATTR; +typedef const struct fpdf_structelement_attr_value_t__* +FPDF_STRUCTELEMENT_ATTR_VALUE; +typedef struct fpdf_structtree_t__* FPDF_STRUCTTREE; +typedef struct fpdf_textpage_t__* FPDF_TEXTPAGE; +typedef struct fpdf_widget_t__* FPDF_WIDGET; +typedef struct fpdf_xobject_t__* FPDF_XOBJECT; + +// Basic data types +typedef int FPDF_BOOL; +typedef int FPDF_RESULT; +typedef unsigned long FPDF_DWORD; +typedef float FS_FLOAT; + +// Duplex types +typedef enum _FPDF_DUPLEXTYPE_ { + DuplexUndefined = 0, + Simplex, + DuplexFlipShortEdge, + DuplexFlipLongEdge +} FPDF_DUPLEXTYPE; + +// String types +typedef unsigned short FPDF_WCHAR; + +// The public PDFium API uses three types of strings: byte string, wide string +// (UTF-16LE encoded), and platform dependent string. + +// Public PDFium API type for byte strings. +typedef const char* FPDF_BYTESTRING; + +// The public PDFium API always uses UTF-16LE encoded wide strings, each +// character uses 2 bytes (except surrogation), with the low byte first. +typedef const FPDF_WCHAR* FPDF_WIDESTRING; + +// Structure for persisting a string beyond the duration of a callback. +// Note: although represented as a char*, string may be interpreted as +// a UTF-16LE formated string. Used only by XFA callbacks. +typedef struct FPDF_BSTR_ { + char* str; // String buffer, manipulate only with FPDF_BStr_* methods. + int len; // Length of the string, in bytes. +} FPDF_BSTR; + +// For Windows programmers: In most cases it's OK to treat FPDF_WIDESTRING as a +// Windows unicode string, however, special care needs to be taken if you +// expect to process Unicode larger than 0xffff. +// +// For Linux/Unix programmers: most compiler/library environments use 4 bytes +// for a Unicode character, and you have to convert between FPDF_WIDESTRING and +// system wide string by yourself. +typedef const char* FPDF_STRING; + +// Matrix for transformation, in the form [a b c d e f], equivalent to: +// | a b 0 | +// | c d 0 | +// | e f 1 | +// +// Translation is performed with [1 0 0 1 tx ty]. +// Scaling is performed with [sx 0 0 sy 0 0]. +// See PDF Reference 1.7, 4.2.2 Common Transformations for more. +typedef struct _FS_MATRIX_ { + float a; + float b; + float c; + float d; + float e; + float f; +} FS_MATRIX; + +// Rectangle area(float) in device or page coordinate system. +typedef struct _FS_RECTF_ { + // The x-coordinate of the left-top corner. + float left; + // The y-coordinate of the left-top corner. + float top; + // The x-coordinate of the right-bottom corner. + float right; + // The y-coordinate of the right-bottom corner. + float bottom; +} * FS_LPRECTF, FS_RECTF; + +// Const Pointer to FS_RECTF structure. +typedef const FS_RECTF* FS_LPCRECTF; + +// Rectangle size. Coordinate system agnostic. +typedef struct FS_SIZEF_ { + float width; + float height; +} * FS_LPSIZEF, FS_SIZEF; + +// Const Pointer to FS_SIZEF structure. +typedef const FS_SIZEF* FS_LPCSIZEF; + +// 2D Point. Coordinate system agnostic. +typedef struct FS_POINTF_ { + float x; + float y; +} * FS_LPPOINTF, FS_POINTF; + +// Const Pointer to FS_POINTF structure. +typedef const FS_POINTF* FS_LPCPOINTF; + +typedef struct _FS_QUADPOINTSF { + FS_FLOAT x1; + FS_FLOAT y1; + FS_FLOAT x2; + FS_FLOAT y2; + FS_FLOAT x3; + FS_FLOAT y3; + FS_FLOAT x4; + FS_FLOAT y4; +} FS_QUADPOINTSF; + +// Annotation enums. +typedef int FPDF_ANNOTATION_SUBTYPE; +typedef int FPDF_ANNOT_APPEARANCEMODE; + +// Dictionary value types. +typedef int FPDF_OBJECT_TYPE; + +#if defined(WIN32) +#if defined(FPDF_IMPLEMENTATION) +#define FPDF_EXPORT __declspec(dllexport) +#else +#define FPDF_EXPORT __declspec(dllimport) +#endif // defined(FPDF_IMPLEMENTATION) +#else +#if defined(FPDF_IMPLEMENTATION) +#define FPDF_EXPORT __attribute__((visibility("default"))) +#else +#define FPDF_EXPORT +#endif // defined(FPDF_IMPLEMENTATION) +#endif // defined(WIN32) + +#if defined(WIN32) && defined(FPDFSDK_EXPORTS) +#define FPDF_CALLCONV __stdcall +#else +#define FPDF_CALLCONV +#endif + +// Exported Functions +#ifdef __cplusplus +extern "C" { +#endif + +// PDF renderer types - Experimental. +// Selection of 2D graphics library to use for rendering to FPDF_BITMAPs. +typedef enum { + // Anti-Grain Geometry - https://sourceforge.net/projects/agg/ + FPDF_RENDERERTYPE_AGG = 0, + // Skia - https://skia.org/ + FPDF_RENDERERTYPE_SKIA = 1, +} FPDF_RENDERER_TYPE; + +// Process-wide options for initializing the library. +typedef struct FPDF_LIBRARY_CONFIG_ { + // Version number of the interface. Currently must be 2. + // Support for version 1 will be deprecated in the future. + int version; + + // Array of paths to scan in place of the defaults when using built-in + // FXGE font loading code. The array is terminated by a NULL pointer. + // The Array may be NULL itself to use the default paths. May be ignored + // entirely depending upon the platform. + const char** m_pUserFontPaths; + + // Version 2. + + // Pointer to the v8::Isolate to use, or NULL to force PDFium to create one. + void* m_pIsolate; + + // The embedder data slot to use in the v8::Isolate to store PDFium's + // per-isolate data. The value needs to be in the range + // [0, |v8::Internals::kNumIsolateDataLots|). Note that 0 is fine for most + // embedders. + unsigned int m_v8EmbedderSlot; + + // Version 3 - Experimental. + + // Pointer to the V8::Platform to use. + void* m_pPlatform; + + // Version 4 - Experimental. + + // Explicit specification of core renderer to use. |m_RendererType| must be + // a valid value for |FPDF_LIBRARY_CONFIG| versions of this level or higher, + // or else the initialization will fail with an immediate crash. + // Note that use of a specified |FPDF_RENDERER_TYPE| value for which the + // corresponding render library is not included in the build will similarly + // fail with an immediate crash. + FPDF_RENDERER_TYPE m_RendererType; +} FPDF_LIBRARY_CONFIG; + +// Function: FPDF_InitLibraryWithConfig +// Initialize the PDFium library and allocate global resources for it. +// Parameters: +// config - configuration information as above. +// Return value: +// None. +// Comments: +// You have to call this function before you can call any PDF +// processing functions. +FPDF_EXPORT void FPDF_CALLCONV +FPDF_InitLibraryWithConfig(const FPDF_LIBRARY_CONFIG* config); + +// Function: FPDF_InitLibrary +// Initialize the PDFium library (alternative form). +// Parameters: +// None +// Return value: +// None. +// Comments: +// Convenience function to call FPDF_InitLibraryWithConfig() with a +// default configuration for backwards compatibility purposes. New +// code should call FPDF_InitLibraryWithConfig() instead. This will +// be deprecated in the future. +FPDF_EXPORT void FPDF_CALLCONV FPDF_InitLibrary(); + +// Function: FPDF_DestroyLibrary +// Release global resources allocated to the PDFium library by +// FPDF_InitLibrary() or FPDF_InitLibraryWithConfig(). +// Parameters: +// None. +// Return value: +// None. +// Comments: +// After this function is called, you must not call any PDF +// processing functions. +// +// Calling this function does not automatically close other +// objects. It is recommended to close other objects before +// closing the library with this function. +FPDF_EXPORT void FPDF_CALLCONV FPDF_DestroyLibrary(); + +// Policy for accessing the local machine time. +#define FPDF_POLICY_MACHINETIME_ACCESS 0 + +// Function: FPDF_SetSandBoxPolicy +// Set the policy for the sandbox environment. +// Parameters: +// policy - The specified policy for setting, for example: +// FPDF_POLICY_MACHINETIME_ACCESS. +// enable - True to enable, false to disable the policy. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_SetSandBoxPolicy(FPDF_DWORD policy, + FPDF_BOOL enable); + +#if defined(_WIN32) +// Experimental API. +// Function: FPDF_SetPrintMode +// Set printing mode when printing on Windows. +// Parameters: +// mode - FPDF_PRINTMODE_EMF to output EMF (default) +// FPDF_PRINTMODE_TEXTONLY to output text only (for charstream +// devices) +// FPDF_PRINTMODE_POSTSCRIPT2 to output level 2 PostScript into +// EMF as a series of GDI comments. +// FPDF_PRINTMODE_POSTSCRIPT3 to output level 3 PostScript into +// EMF as a series of GDI comments. +// FPDF_PRINTMODE_POSTSCRIPT2_PASSTHROUGH to output level 2 +// PostScript via ExtEscape() in PASSTHROUGH mode. +// FPDF_PRINTMODE_POSTSCRIPT3_PASSTHROUGH to output level 3 +// PostScript via ExtEscape() in PASSTHROUGH mode. +// FPDF_PRINTMODE_EMF_IMAGE_MASKS to output EMF, with more +// efficient processing of documents containing image masks. +// FPDF_PRINTMODE_POSTSCRIPT3_TYPE42 to output level 3 +// PostScript with embedded Type 42 fonts, when applicable, into +// EMF as a series of GDI comments. +// FPDF_PRINTMODE_POSTSCRIPT3_TYPE42_PASSTHROUGH to output level +// 3 PostScript with embedded Type 42 fonts, when applicable, +// via ExtEscape() in PASSTHROUGH mode. +// Return value: +// True if successful, false if unsuccessful (typically invalid input). +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_SetPrintMode(int mode); +#endif // defined(_WIN32) + +// Function: FPDF_LoadDocument +// Open and load a PDF document. +// Parameters: +// file_path - Path to the PDF file (including extension). +// password - A string used as the password for the PDF file. +// If no password is needed, empty or NULL can be used. +// See comments below regarding the encoding. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// Loaded document can be closed by FPDF_CloseDocument(). +// If this function fails, you can use FPDF_GetLastError() to retrieve +// the reason why it failed. +// +// The encoding for |file_path| is UTF-8. +// +// The encoding for |password| can be either UTF-8 or Latin-1. PDFs, +// depending on the security handler revision, will only accept one or +// the other encoding. If |password|'s encoding and the PDF's expected +// encoding do not match, FPDF_LoadDocument() will automatically +// convert |password| to the other encoding. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadDocument(FPDF_STRING file_path, FPDF_BYTESTRING password); + +// Function: FPDF_LoadMemDocument +// Open and load a PDF document from memory. +// Parameters: +// data_buf - Pointer to a buffer containing the PDF document. +// size - Number of bytes in the PDF document. +// password - A string used as the password for the PDF file. +// If no password is needed, empty or NULL can be used. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// The memory buffer must remain valid when the document is open. +// The loaded document can be closed by FPDF_CloseDocument. +// If this function fails, you can use FPDF_GetLastError() to retrieve +// the reason why it failed. +// +// See the comments for FPDF_LoadDocument() regarding the encoding for +// |password|. +// Notes: +// If PDFium is built with the XFA module, the application should call +// FPDF_LoadXFA() function after the PDF document loaded to support XFA +// fields defined in the fpdfformfill.h file. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadMemDocument(const void* data_buf, int size, FPDF_BYTESTRING password); + +// Experimental API. +// Function: FPDF_LoadMemDocument64 +// Open and load a PDF document from memory. +// Parameters: +// data_buf - Pointer to a buffer containing the PDF document. +// size - Number of bytes in the PDF document. +// password - A string used as the password for the PDF file. +// If no password is needed, empty or NULL can be used. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// The memory buffer must remain valid when the document is open. +// The loaded document can be closed by FPDF_CloseDocument. +// If this function fails, you can use FPDF_GetLastError() to retrieve +// the reason why it failed. +// +// See the comments for FPDF_LoadDocument() regarding the encoding for +// |password|. +// Notes: +// If PDFium is built with the XFA module, the application should call +// FPDF_LoadXFA() function after the PDF document loaded to support XFA +// fields defined in the fpdfformfill.h file. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadMemDocument64(const void* data_buf, + size_t size, + FPDF_BYTESTRING password); + +// Structure for custom file access. +typedef struct { + // File length, in bytes. + unsigned long m_FileLen; + + // A function pointer for getting a block of data from a specific position. + // Position is specified by byte offset from the beginning of the file. + // The pointer to the buffer is never NULL and the size is never 0. + // The position and size will never go out of range of the file length. + // It may be possible for PDFium to call this function multiple times for + // the same position. + // Return value: should be non-zero if successful, zero for error. + int (*m_GetBlock)(void* param, + unsigned long position, + unsigned char* pBuf, + unsigned long size); + + // A custom pointer for all implementation specific data. This pointer will + // be used as the first parameter to the m_GetBlock callback. + void* m_Param; +} FPDF_FILEACCESS; + +// Structure for file reading or writing (I/O). +// +// Note: This is a handler and should be implemented by callers, +// and is only used from XFA. +typedef struct FPDF_FILEHANDLER_ { + // User-defined data. + // Note: Callers can use this field to track controls. + void* clientData; + + // Callback function to release the current file stream object. + // + // Parameters: + // clientData - Pointer to user-defined data. + // Returns: + // None. + void (*Release)(void* clientData); + + // Callback function to retrieve the current file stream size. + // + // Parameters: + // clientData - Pointer to user-defined data. + // Returns: + // Size of file stream. + FPDF_DWORD (*GetSize)(void* clientData); + + // Callback function to read data from the current file stream. + // + // Parameters: + // clientData - Pointer to user-defined data. + // offset - Offset position starts from the beginning of file + // stream. This parameter indicates reading position. + // buffer - Memory buffer to store data which are read from + // file stream. This parameter should not be NULL. + // size - Size of data which should be read from file stream, + // in bytes. The buffer indicated by |buffer| must be + // large enough to store specified data. + // Returns: + // 0 for success, other value for failure. + FPDF_RESULT (*ReadBlock)(void* clientData, + FPDF_DWORD offset, + void* buffer, + FPDF_DWORD size); + + // Callback function to write data into the current file stream. + // + // Parameters: + // clientData - Pointer to user-defined data. + // offset - Offset position starts from the beginning of file + // stream. This parameter indicates writing position. + // buffer - Memory buffer contains data which is written into + // file stream. This parameter should not be NULL. + // size - Size of data which should be written into file + // stream, in bytes. + // Returns: + // 0 for success, other value for failure. + FPDF_RESULT (*WriteBlock)(void* clientData, + FPDF_DWORD offset, + const void* buffer, + FPDF_DWORD size); + // Callback function to flush all internal accessing buffers. + // + // Parameters: + // clientData - Pointer to user-defined data. + // Returns: + // 0 for success, other value for failure. + FPDF_RESULT (*Flush)(void* clientData); + + // Callback function to change file size. + // + // Description: + // This function is called under writing mode usually. Implementer + // can determine whether to realize it based on application requests. + // Parameters: + // clientData - Pointer to user-defined data. + // size - New size of file stream, in bytes. + // Returns: + // 0 for success, other value for failure. + FPDF_RESULT (*Truncate)(void* clientData, FPDF_DWORD size); +} FPDF_FILEHANDLER; + +// Function: FPDF_LoadCustomDocument +// Load PDF document from a custom access descriptor. +// Parameters: +// pFileAccess - A structure for accessing the file. +// password - Optional password for decrypting the PDF file. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// The application must keep the file resources |pFileAccess| points to +// valid until the returned FPDF_DOCUMENT is closed. |pFileAccess| +// itself does not need to outlive the FPDF_DOCUMENT. +// +// The loaded document can be closed with FPDF_CloseDocument(). +// +// See the comments for FPDF_LoadDocument() regarding the encoding for +// |password|. +// Notes: +// If PDFium is built with the XFA module, the application should call +// FPDF_LoadXFA() function after the PDF document loaded to support XFA +// fields defined in the fpdfformfill.h file. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadCustomDocument(FPDF_FILEACCESS* pFileAccess, FPDF_BYTESTRING password); + +// Function: FPDF_GetFileVersion +// Get the file version of the given PDF document. +// Parameters: +// doc - Handle to a document. +// fileVersion - The PDF file version. File version: 14 for 1.4, 15 +// for 1.5, ... +// Return value: +// True if succeeds, false otherwise. +// Comments: +// If the document was created by FPDF_CreateNewDocument, +// then this function will always fail. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_GetFileVersion(FPDF_DOCUMENT doc, + int* fileVersion); + +#define FPDF_ERR_SUCCESS 0 // No error. +#define FPDF_ERR_UNKNOWN 1 // Unknown error. +#define FPDF_ERR_FILE 2 // File not found or could not be opened. +#define FPDF_ERR_FORMAT 3 // File not in PDF format or corrupted. +#define FPDF_ERR_PASSWORD 4 // Password required or incorrect password. +#define FPDF_ERR_SECURITY 5 // Unsupported security scheme. +#define FPDF_ERR_PAGE 6 // Page not found or content error. +#ifdef PDF_ENABLE_XFA +#define FPDF_ERR_XFALOAD 7 // Load XFA error. +#define FPDF_ERR_XFALAYOUT 8 // Layout XFA error. +#endif // PDF_ENABLE_XFA + +// Function: FPDF_GetLastError +// Get last error code when a function fails. +// Parameters: +// None. +// Return value: +// A 32-bit integer indicating error code as defined above. +// Comments: +// If the previous SDK call succeeded, the return value of this +// function is not defined. This function only works in conjunction +// with APIs that mention FPDF_GetLastError() in their documentation. +FPDF_EXPORT unsigned long FPDF_CALLCONV FPDF_GetLastError(); + +// Experimental API. +// Function: FPDF_DocumentHasValidCrossReferenceTable +// Whether the document's cross reference table is valid or not. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// True if the PDF parser did not encounter problems parsing the cross +// reference table. False if the parser could not parse the cross +// reference table and the table had to be rebuild from other data +// within the document. +// Comments: +// The return value can change over time as the PDF parser evolves. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV +FPDF_DocumentHasValidCrossReferenceTable(FPDF_DOCUMENT document); + +// Experimental API. +// Function: FPDF_GetTrailerEnds +// Get the byte offsets of trailer ends. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument(). +// buffer - The address of a buffer that receives the +// byte offsets. +// length - The size, in ints, of |buffer|. +// Return value: +// Returns the number of ints in the buffer on success, 0 on error. +// +// |buffer| is an array of integers that describes the exact byte offsets of the +// trailer ends in the document. If |length| is less than the returned length, +// or |document| or |buffer| is NULL, |buffer| will not be modified. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_GetTrailerEnds(FPDF_DOCUMENT document, + unsigned int* buffer, + unsigned long length); + +// Function: FPDF_GetDocPermissions +// Get file permission flags of the document. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// A 32-bit integer indicating permission flags. Please refer to the +// PDF Reference for detailed descriptions. If the document is not +// protected or was unlocked by the owner, 0xffffffff will be returned. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_GetDocPermissions(FPDF_DOCUMENT document); + +// Function: FPDF_GetDocUserPermissions +// Get user file permission flags of the document. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// A 32-bit integer indicating permission flags. Please refer to the +// PDF Reference for detailed descriptions. If the document is not +// protected, 0xffffffff will be returned. Always returns user +// permissions, even if the document was unlocked by the owner. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_GetDocUserPermissions(FPDF_DOCUMENT document); + +// Function: FPDF_GetSecurityHandlerRevision +// Get the revision for the security handler. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// The security handler revision number. Please refer to the PDF +// Reference for a detailed description. If the document is not +// protected, -1 will be returned. +FPDF_EXPORT int FPDF_CALLCONV +FPDF_GetSecurityHandlerRevision(FPDF_DOCUMENT document); + +// Function: FPDF_GetPageCount +// Get total number of pages in the document. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument. +// Return value: +// Total number of pages in the document. +FPDF_EXPORT int FPDF_CALLCONV FPDF_GetPageCount(FPDF_DOCUMENT document); + +// Function: FPDF_LoadPage +// Load a page inside the document. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument +// page_index - Index number of the page. 0 for the first page. +// Return value: +// A handle to the loaded page, or NULL if page load fails. +// Comments: +// The loaded page can be rendered to devices using FPDF_RenderPage. +// The loaded page can be closed using FPDF_ClosePage. +FPDF_EXPORT FPDF_PAGE FPDF_CALLCONV FPDF_LoadPage(FPDF_DOCUMENT document, + int page_index); + +// Experimental API +// Function: FPDF_GetPageWidthF +// Get page width. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage(). +// Return value: +// Page width (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm). +FPDF_EXPORT float FPDF_CALLCONV FPDF_GetPageWidthF(FPDF_PAGE page); + +// Function: FPDF_GetPageWidth +// Get page width. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// Return value: +// Page width (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm). +// Note: +// Prefer FPDF_GetPageWidthF() above. This will be deprecated in the +// future. +FPDF_EXPORT double FPDF_CALLCONV FPDF_GetPageWidth(FPDF_PAGE page); + +// Experimental API +// Function: FPDF_GetPageHeightF +// Get page height. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage(). +// Return value: +// Page height (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm) +FPDF_EXPORT float FPDF_CALLCONV FPDF_GetPageHeightF(FPDF_PAGE page); + +// Function: FPDF_GetPageHeight +// Get page height. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// Return value: +// Page height (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm) +// Note: +// Prefer FPDF_GetPageHeightF() above. This will be deprecated in the +// future. +FPDF_EXPORT double FPDF_CALLCONV FPDF_GetPageHeight(FPDF_PAGE page); + +// Experimental API. +// Function: FPDF_GetPageBoundingBox +// Get the bounding box of the page. This is the intersection between +// its media box and its crop box. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// rect - Pointer to a rect to receive the page bounding box. +// On an error, |rect| won't be filled. +// Return value: +// True for success. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_GetPageBoundingBox(FPDF_PAGE page, + FS_RECTF* rect); + +// Experimental API. +// Function: FPDF_GetPageSizeByIndexF +// Get the size of the page at the given index. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument(). +// page_index - Page index, zero for the first page. +// size - Pointer to a FS_SIZEF to receive the page size. +// (in points). +// Return value: +// Non-zero for success. 0 for error (document or page not found). +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV +FPDF_GetPageSizeByIndexF(FPDF_DOCUMENT document, + int page_index, + FS_SIZEF* size); + +// Function: FPDF_GetPageSizeByIndex +// Get the size of the page at the given index. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument. +// page_index - Page index, zero for the first page. +// width - Pointer to a double to receive the page width +// (in points). +// height - Pointer to a double to receive the page height +// (in points). +// Return value: +// Non-zero for success. 0 for error (document or page not found). +// Note: +// Prefer FPDF_GetPageSizeByIndexF() above. This will be deprecated in +// the future. +FPDF_EXPORT int FPDF_CALLCONV FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, + int page_index, + double* width, + double* height); + +// Page rendering flags. They can be combined with bit-wise OR. +// +// Set if annotations are to be rendered. +#define FPDF_ANNOT 0x01 +// Set if using text rendering optimized for LCD display. This flag will only +// take effect if anti-aliasing is enabled for text. +#define FPDF_LCD_TEXT 0x02 +// Don't use the native text output available on some platforms +#define FPDF_NO_NATIVETEXT 0x04 +// Grayscale output. +#define FPDF_GRAYSCALE 0x08 +// Obsolete, has no effect, retained for compatibility. +#define FPDF_DEBUG_INFO 0x80 +// Obsolete, has no effect, retained for compatibility. +#define FPDF_NO_CATCH 0x100 +// Limit image cache size. +#define FPDF_RENDER_LIMITEDIMAGECACHE 0x200 +// Always use halftone for image stretching. +#define FPDF_RENDER_FORCEHALFTONE 0x400 +// Render for printing. +#define FPDF_PRINTING 0x800 +// Set to disable anti-aliasing on text. This flag will also disable LCD +// optimization for text rendering. +#define FPDF_RENDER_NO_SMOOTHTEXT 0x1000 +// Set to disable anti-aliasing on images. +#define FPDF_RENDER_NO_SMOOTHIMAGE 0x2000 +// Set to disable anti-aliasing on paths. +#define FPDF_RENDER_NO_SMOOTHPATH 0x4000 +// Set whether to render in a reverse Byte order, this flag is only used when +// rendering to a bitmap. +#define FPDF_REVERSE_BYTE_ORDER 0x10 +// Set whether fill paths need to be stroked. This flag is only used when +// FPDF_COLORSCHEME is passed in, since with a single fill color for paths the +// boundaries of adjacent fill paths are less visible. +#define FPDF_CONVERT_FILL_TO_STROKE 0x20 + +// Struct for color scheme. +// Each should be a 32-bit value specifying the color, in 8888 ARGB format. +typedef struct FPDF_COLORSCHEME_ { + FPDF_DWORD path_fill_color; + FPDF_DWORD path_stroke_color; + FPDF_DWORD text_fill_color; + FPDF_DWORD text_stroke_color; +} FPDF_COLORSCHEME; + +#ifdef _WIN32 +// Function: FPDF_RenderPage +// Render contents of a page to a device (screen, bitmap, or printer). +// This function is only supported on Windows. +// Parameters: +// dc - Handle to the device context. +// page - Handle to the page. Returned by FPDF_LoadPage. +// start_x - Left pixel position of the display area in +// device coordinates. +// start_y - Top pixel position of the display area in device +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// flags - 0 for normal display, or combination of flags +// defined above. +// Return value: +// Returns true if the page is rendered successfully, false otherwise. + +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_RenderPage(HDC dc, + FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + int flags); +#endif + +// Function: FPDF_RenderPageBitmap +// Render contents of a page to a device independent bitmap. +// Parameters: +// bitmap - Handle to the device independent bitmap (as the +// output buffer). The bitmap handle can be created +// by FPDFBitmap_Create or retrieved from an image +// object by FPDFImageObj_GetBitmap. +// page - Handle to the page. Returned by FPDF_LoadPage +// start_x - Left pixel position of the display area in +// bitmap coordinates. +// start_y - Top pixel position of the display area in bitmap +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// flags - 0 for normal display, or combination of the Page +// Rendering flags defined above. With the FPDF_ANNOT +// flag, it renders all annotations that do not require +// user-interaction, which are all annotations except +// widget and popup annotations. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, + FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + int flags); + +// Function: FPDF_RenderPageBitmapWithMatrix +// Render contents of a page to a device independent bitmap. +// Parameters: +// bitmap - Handle to the device independent bitmap (as the +// output buffer). The bitmap handle can be created +// by FPDFBitmap_Create or retrieved by +// FPDFImageObj_GetBitmap. +// page - Handle to the page. Returned by FPDF_LoadPage. +// matrix - The transform matrix, which must be invertible. +// See PDF Reference 1.7, 4.2.2 Common Transformations. +// clipping - The rect to clip to in device coords. +// flags - 0 for normal display, or combination of the Page +// Rendering flags defined above. With the FPDF_ANNOT +// flag, it renders all annotations that do not require +// user-interaction, which are all annotations except +// widget and popup annotations. +// Return value: +// None. Note that behavior is undefined if det of |matrix| is 0. +FPDF_EXPORT void FPDF_CALLCONV +FPDF_RenderPageBitmapWithMatrix(FPDF_BITMAP bitmap, + FPDF_PAGE page, + const FS_MATRIX* matrix, + const FS_RECTF* clipping, + int flags); + +#if defined(PDF_USE_SKIA) +// Experimental API. +// Function: FPDF_RenderPageSkia +// Render contents of a page to a Skia SkCanvas. +// Parameters: +// canvas - SkCanvas to render to. +// page - Handle to the page. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_RenderPageSkia(FPDF_SKIA_CANVAS canvas, + FPDF_PAGE page, + int size_x, + int size_y); +#endif + +// Function: FPDF_ClosePage +// Close a loaded PDF page. +// Parameters: +// page - Handle to the loaded page. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_ClosePage(FPDF_PAGE page); + +// Function: FPDF_CloseDocument +// Close a loaded PDF document. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_CloseDocument(FPDF_DOCUMENT document); + +// Function: FPDF_DeviceToPage +// Convert the screen coordinates of a point to page coordinates. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// start_x - Left pixel position of the display area in +// device coordinates. +// start_y - Top pixel position of the display area in device +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// device_x - X value in device coordinates to be converted. +// device_y - Y value in device coordinates to be converted. +// page_x - A pointer to a double receiving the converted X +// value in page coordinates. +// page_y - A pointer to a double receiving the converted Y +// value in page coordinates. +// Return value: +// Returns true if the conversion succeeds, and |page_x| and |page_y| +// successfully receives the converted coordinates. +// Comments: +// The page coordinate system has its origin at the left-bottom corner +// of the page, with the X-axis on the bottom going to the right, and +// the Y-axis on the left side going up. +// +// NOTE: this coordinate system can be altered when you zoom, scroll, +// or rotate a page, however, a point on the page should always have +// the same coordinate values in the page coordinate system. +// +// The device coordinate system is device dependent. For screen device, +// its origin is at the left-top corner of the window. However this +// origin can be altered by the Windows coordinate transformation +// utilities. +// +// You must make sure the start_x, start_y, size_x, size_y +// and rotate parameters have exactly same values as you used in +// the FPDF_RenderPage() function call. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_DeviceToPage(FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + int device_x, + int device_y, + double* page_x, + double* page_y); + +// Function: FPDF_PageToDevice +// Convert the page coordinates of a point to screen coordinates. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// start_x - Left pixel position of the display area in +// device coordinates. +// start_y - Top pixel position of the display area in device +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// page_x - X value in page coordinates. +// page_y - Y value in page coordinate. +// device_x - A pointer to an integer receiving the result X +// value in device coordinates. +// device_y - A pointer to an integer receiving the result Y +// value in device coordinates. +// Return value: +// Returns true if the conversion succeeds, and |device_x| and +// |device_y| successfully receives the converted coordinates. +// Comments: +// See comments for FPDF_DeviceToPage(). +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_PageToDevice(FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + double page_x, + double page_y, + int* device_x, + int* device_y); + +// Function: FPDFBitmap_Create +// Create a device independent bitmap (FXDIB). +// Parameters: +// width - The number of pixels in width for the bitmap. +// Must be greater than 0. +// height - The number of pixels in height for the bitmap. +// Must be greater than 0. +// alpha - A flag indicating whether the alpha channel is used. +// Non-zero for using alpha, zero for not using. +// Return value: +// The created bitmap handle, or NULL if a parameter error or out of +// memory. +// Comments: +// The bitmap always uses 4 bytes per pixel. The first byte is always +// double word aligned. +// +// The byte order is BGRx (the last byte unused if no alpha channel) or +// BGRA. +// +// The pixels in a horizontal line are stored side by side, with the +// left most pixel stored first (with lower memory address). +// Each line uses width * 4 bytes. +// +// Lines are stored one after another, with the top most line stored +// first. There is no gap between adjacent lines. +// +// This function allocates enough memory for holding all pixels in the +// bitmap, but it doesn't initialize the buffer. Applications can use +// FPDFBitmap_FillRect() to fill the bitmap using any color. If the OS +// allows it, this function can allocate up to 4 GB of memory. +FPDF_EXPORT FPDF_BITMAP FPDF_CALLCONV FPDFBitmap_Create(int width, + int height, + int alpha); + +// More DIB formats +// Unknown or unsupported format. +#define FPDFBitmap_Unknown 0 +// Gray scale bitmap, one byte per pixel. +#define FPDFBitmap_Gray 1 +// 3 bytes per pixel, byte order: blue, green, red. +#define FPDFBitmap_BGR 2 +// 4 bytes per pixel, byte order: blue, green, red, unused. +#define FPDFBitmap_BGRx 3 +// 4 bytes per pixel, byte order: blue, green, red, alpha. +// Pixel components are independent of alpha. +#define FPDFBitmap_BGRA 4 +// 4 bytes per pixel, byte order: blue, green, red, alpha. +// Pixel components are premultiplied by alpha. +// Note that this is experimental and only supported when rendering with +// |FPDF_RENDERER_TYPE| is set to |FPDF_RENDERERTYPE_SKIA|. +#define FPDFBitmap_BGRA_Premul 5 + +// Function: FPDFBitmap_CreateEx +// Create a device independent bitmap (FXDIB) +// Parameters: +// width - The number of pixels in width for the bitmap. +// Must be greater than 0. +// height - The number of pixels in height for the bitmap. +// Must be greater than 0. +// format - A number indicating for bitmap format, as defined +// above. +// first_scan - A pointer to the first byte of the first line if +// using an external buffer. If this parameter is NULL, +// then a new buffer will be created. +// stride - Number of bytes for each scan line. The value must +// be 0 or greater. When the value is 0, +// FPDFBitmap_CreateEx() will automatically calculate +// the appropriate value using |width| and |format|. +// When using an external buffer, it is recommended for +// the caller to pass in the value. +// When not using an external buffer, it is recommended +// for the caller to pass in 0. +// Return value: +// The bitmap handle, or NULL if parameter error or out of memory. +// Comments: +// Similar to FPDFBitmap_Create function, but allows for more formats +// and an external buffer is supported. The bitmap created by this +// function can be used in any place that a FPDF_BITMAP handle is +// required. +// +// If an external buffer is used, then the caller should destroy the +// buffer. FPDFBitmap_Destroy() will not destroy the buffer. +// +// It is recommended to use FPDFBitmap_GetStride() to get the stride +// value. +FPDF_EXPORT FPDF_BITMAP FPDF_CALLCONV FPDFBitmap_CreateEx(int width, + int height, + int format, + void* first_scan, + int stride); + +// Function: FPDFBitmap_GetFormat +// Get the format of the bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The format of the bitmap. +// Comments: +// Only formats supported by FPDFBitmap_CreateEx are supported by this +// function; see the list of such formats above. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetFormat(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_FillRect +// Fill a rectangle in a bitmap. +// Parameters: +// bitmap - The handle to the bitmap. Returned by +// FPDFBitmap_Create. +// left - The left position. Starting from 0 at the +// left-most pixel. +// top - The top position. Starting from 0 at the +// top-most line. +// width - Width in pixels to be filled. +// height - Height in pixels to be filled. +// color - A 32-bit value specifing the color, in 8888 ARGB +// format. +// Return value: +// Returns whether the operation succeeded or not. +// Comments: +// This function sets the color and (optionally) alpha value in the +// specified region of the bitmap. +// +// NOTE: If the alpha channel is used, this function does NOT +// composite the background with the source color, instead the +// background will be replaced by the source color and the alpha. +// +// If the alpha channel is not used, the alpha parameter is ignored. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDFBitmap_FillRect(FPDF_BITMAP bitmap, + int left, + int top, + int width, + int height, + FPDF_DWORD color); + +// Function: FPDFBitmap_GetBuffer +// Get data buffer of a bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The pointer to the first byte of the bitmap buffer. +// Comments: +// The stride may be more than width * number of bytes per pixel +// +// Applications can use this function to get the bitmap buffer pointer, +// then manipulate any color and/or alpha values for any pixels in the +// bitmap. +// +// Use FPDFBitmap_GetFormat() to find out the format of the data. +FPDF_EXPORT void* FPDF_CALLCONV FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_GetWidth +// Get width of a bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The width of the bitmap in pixels. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetWidth(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_GetHeight +// Get height of a bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The height of the bitmap in pixels. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetHeight(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_GetStride +// Get number of bytes for each line in the bitmap buffer. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The number of bytes for each line in the bitmap buffer. +// Comments: +// The stride may be more than width * number of bytes per pixel. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetStride(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_Destroy +// Destroy a bitmap and release all related buffers. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// None. +// Comments: +// This function will not destroy any external buffers provided when +// the bitmap was created. +FPDF_EXPORT void FPDF_CALLCONV FPDFBitmap_Destroy(FPDF_BITMAP bitmap); + +// Function: FPDF_VIEWERREF_GetPrintScaling +// Whether the PDF document prefers to be scaled or not. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// None. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document); + +// Function: FPDF_VIEWERREF_GetNumCopies +// Returns the number of copies to be printed. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// The number of copies to be printed. +FPDF_EXPORT int FPDF_CALLCONV +FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document); + +// Function: FPDF_VIEWERREF_GetPrintPageRange +// Page numbers to initialize print dialog box when file is printed. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// The print page range to be used for printing. +FPDF_EXPORT FPDF_PAGERANGE FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document); + +// Experimental API. +// Function: FPDF_VIEWERREF_GetPrintPageRangeCount +// Returns the number of elements in a FPDF_PAGERANGE. +// Parameters: +// pagerange - Handle to the page range. +// Return value: +// The number of elements in the page range. Returns 0 on error. +FPDF_EXPORT size_t FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintPageRangeCount(FPDF_PAGERANGE pagerange); + +// Experimental API. +// Function: FPDF_VIEWERREF_GetPrintPageRangeElement +// Returns an element from a FPDF_PAGERANGE. +// Parameters: +// pagerange - Handle to the page range. +// index - Index of the element. +// Return value: +// The value of the element in the page range at a given index. +// Returns -1 on error. +FPDF_EXPORT int FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintPageRangeElement(FPDF_PAGERANGE pagerange, size_t index); + +// Function: FPDF_VIEWERREF_GetDuplex +// Returns the paper handling option to be used when printing from +// the print dialog. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// The paper handling option to be used when printing. +FPDF_EXPORT FPDF_DUPLEXTYPE FPDF_CALLCONV +FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document); + +// Function: FPDF_VIEWERREF_GetName +// Gets the contents for a viewer ref, with a given key. The value must +// be of type "name". +// Parameters: +// document - Handle to the loaded document. +// key - Name of the key in the viewer pref dictionary, +// encoded in UTF-8. +// buffer - Caller-allocate buffer to receive the key, or NULL +// - to query the required length. +// length - Length of the buffer. +// Return value: +// The number of bytes in the contents, including the NULL terminator. +// Thus if the return value is 0, then that indicates an error, such +// as when |document| is invalid. If |length| is less than the required +// length, or |buffer| is NULL, |buffer| will not be modified. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_VIEWERREF_GetName(FPDF_DOCUMENT document, + FPDF_BYTESTRING key, + char* buffer, + unsigned long length); + +// Function: FPDF_CountNamedDests +// Get the count of named destinations in the PDF document. +// Parameters: +// document - Handle to a document +// Return value: +// The count of named destinations. +FPDF_EXPORT FPDF_DWORD FPDF_CALLCONV +FPDF_CountNamedDests(FPDF_DOCUMENT document); + +// Function: FPDF_GetNamedDestByName +// Get a the destination handle for the given name. +// Parameters: +// document - Handle to the loaded document. +// name - The name of a destination. +// Return value: +// The handle to the destination. +FPDF_EXPORT FPDF_DEST FPDF_CALLCONV +FPDF_GetNamedDestByName(FPDF_DOCUMENT document, FPDF_BYTESTRING name); + +// Function: FPDF_GetNamedDest +// Get the named destination by index. +// Parameters: +// document - Handle to a document +// index - The index of a named destination. +// buffer - The buffer to store the destination name, +// used as wchar_t*. +// buflen [in/out] - Size of the buffer in bytes on input, +// length of the result in bytes on output +// or -1 if the buffer is too small. +// Return value: +// The destination handle for a given index, or NULL if there is no +// named destination corresponding to |index|. +// Comments: +// Call this function twice to get the name of the named destination: +// 1) First time pass in |buffer| as NULL and get buflen. +// 2) Second time pass in allocated |buffer| and buflen to retrieve +// |buffer|, which should be used as wchar_t*. +// +// If buflen is not sufficiently large, it will be set to -1 upon +// return. +FPDF_EXPORT FPDF_DEST FPDF_CALLCONV FPDF_GetNamedDest(FPDF_DOCUMENT document, + int index, + void* buffer, + long* buflen); + +// Experimental API. +// Function: FPDF_GetXFAPacketCount +// Get the number of valid packets in the XFA entry. +// Parameters: +// document - Handle to the document. +// Return value: +// The number of valid packets, or -1 on error. +FPDF_EXPORT int FPDF_CALLCONV FPDF_GetXFAPacketCount(FPDF_DOCUMENT document); + +// Experimental API. +// Function: FPDF_GetXFAPacketName +// Get the name of a packet in the XFA array. +// Parameters: +// document - Handle to the document. +// index - Index number of the packet. 0 for the first packet. +// buffer - Buffer for holding the name of the XFA packet. +// buflen - Length of |buffer| in bytes. +// Return value: +// The length of the packet name in bytes, or 0 on error. +// +// |document| must be valid and |index| must be in the range [0, N), where N is +// the value returned by FPDF_GetXFAPacketCount(). +// |buffer| is only modified if it is non-NULL and |buflen| is greater than or +// equal to the length of the packet name. The packet name includes a +// terminating NUL character. |buffer| is unmodified on error. +FPDF_EXPORT unsigned long FPDF_CALLCONV FPDF_GetXFAPacketName( + FPDF_DOCUMENT document, + int index, + void* buffer, + unsigned long buflen); + +// Experimental API. +// Function: FPDF_GetXFAPacketContent +// Get the content of a packet in the XFA array. +// Parameters: +// document - Handle to the document. +// index - Index number of the packet. 0 for the first packet. +// buffer - Buffer for holding the content of the XFA packet. +// buflen - Length of |buffer| in bytes. +// out_buflen - Pointer to the variable that will receive the minimum +// buffer size needed to contain the content of the XFA +// packet. +// Return value: +// Whether the operation succeeded or not. +// +// |document| must be valid and |index| must be in the range [0, N), where N is +// the value returned by FPDF_GetXFAPacketCount(). |out_buflen| must not be +// NULL. When the aforementioned arguments are valid, the operation succeeds, +// and |out_buflen| receives the content size. |buffer| is only modified if +// |buffer| is non-null and long enough to contain the content. Callers must +// check both the return value and the input |buflen| is no less than the +// returned |out_buflen| before using the data in |buffer|. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_GetXFAPacketContent( + FPDF_DOCUMENT document, + int index, + void* buffer, + unsigned long buflen, + unsigned long* out_buflen); + +#ifdef PDF_ENABLE_V8 +// Function: FPDF_GetRecommendedV8Flags +// Returns a space-separated string of command line flags that are +// recommended to be passed into V8 via V8::SetFlagsFromString() +// prior to initializing the PDFium library. +// Parameters: +// None. +// Return value: +// NUL-terminated string of the form "--flag1 --flag2". +// The caller must not attempt to modify or free the result. +FPDF_EXPORT const char* FPDF_CALLCONV FPDF_GetRecommendedV8Flags(); + +// Experimental API. +// Function: FPDF_GetArrayBufferAllocatorSharedInstance() +// Helper function for initializing V8 isolates that will +// use PDFium's internal memory management. +// Parameters: +// None. +// Return Value: +// Pointer to a suitable v8::ArrayBuffer::Allocator, returned +// as void for C compatibility. +// Notes: +// Use is optional, but allows external creation of isolates +// matching the ones PDFium will make when none is provided +// via |FPDF_LIBRARY_CONFIG::m_pIsolate|. +// +// Can only be called when the library is in an uninitialized or +// destroyed state. +FPDF_EXPORT void* FPDF_CALLCONV FPDF_GetArrayBufferAllocatorSharedInstance(); +#endif // PDF_ENABLE_V8 + +#ifdef PDF_ENABLE_XFA +// Function: FPDF_BStr_Init +// Helper function to initialize a FPDF_BSTR. +FPDF_EXPORT FPDF_RESULT FPDF_CALLCONV FPDF_BStr_Init(FPDF_BSTR* bstr); + +// Function: FPDF_BStr_Set +// Helper function to copy string data into the FPDF_BSTR. +FPDF_EXPORT FPDF_RESULT FPDF_CALLCONV FPDF_BStr_Set(FPDF_BSTR* bstr, + const char* cstr, + int length); + +// Function: FPDF_BStr_Clear +// Helper function to clear a FPDF_BSTR. +FPDF_EXPORT FPDF_RESULT FPDF_CALLCONV FPDF_BStr_Clear(FPDF_BSTR* bstr); +#endif // PDF_ENABLE_XFA + +#ifdef __cplusplus +} +#endif + +#endif // PUBLIC_FPDFVIEW_H_ diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/cpp/pdfium_wrapper_jni.cpp b/packages/syncfusion_pdfviewer_android/android/src/main/cpp/pdfium_wrapper_jni.cpp new file mode 100644 index 000000000..1b68bbb90 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/src/main/cpp/pdfium_wrapper_jni.cpp @@ -0,0 +1,189 @@ +#include +#include +#include + +extern "C" { + +static void* pdfiumLibHandle = nullptr; + +JNIEXPORT jboolean JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_initLibrary(JNIEnv* env, jobject thiz) { + const char* libName = "libpdfium.so"; + + pdfiumLibHandle = dlopen(libName, RTLD_NOW | RTLD_LOCAL); + if (!pdfiumLibHandle) { + return JNI_FALSE; + } + FPDF_InitLibraryWithConfig(nullptr); + return JNI_TRUE; +} + +JNIEXPORT void JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_destroyLibrary(JNIEnv* env, jobject thiz) { + FPDF_DestroyLibrary(); + if (pdfiumLibHandle) { + dlclose(pdfiumLibHandle); + pdfiumLibHandle = nullptr; + } +} + +JNIEXPORT jlong JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_loadDocument(JNIEnv* env, jobject thiz, jbyteArray pdfData, jstring password) { + if (!pdfiumLibHandle) { + return 0; + } + if (pdfData == nullptr) { + return 0; + } + + jbyte* buffer = env->GetByteArrayElements(pdfData, nullptr); + jsize length = env->GetArrayLength(pdfData); + const char* pwd = password ? env->GetStringUTFChars(password, nullptr) : nullptr; + + FPDF_DOCUMENT doc = FPDF_LoadMemDocument64(buffer, (size_t)length, pwd); + env->ReleaseByteArrayElements(pdfData, buffer, JNI_ABORT); + if (pwd) { + env->ReleaseStringUTFChars(password, pwd); + } + if (!doc) { + return 0; + } + + return reinterpret_cast(doc); +} + +JNIEXPORT void JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_closeDocument(JNIEnv* env, jobject thiz, jlong docHandle) { + if (!pdfiumLibHandle) { + return; + } + FPDF_DOCUMENT doc = reinterpret_cast(docHandle); + if (doc) { + FPDF_CloseDocument(doc); + } +} + +JNIEXPORT jint JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_getPageCount(JNIEnv* env, jobject thiz, jlong docHandle) { + if (!pdfiumLibHandle) { + return -1; + } + FPDF_DOCUMENT doc = reinterpret_cast(docHandle); + return doc ? FPDF_GetPageCount(doc) : -1; +} + +JNIEXPORT jfloat JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_getPageWidth(JNIEnv* env, jobject thiz, jlong docHandle, jint index) { + if (!pdfiumLibHandle) { + return -1; + } + FPDF_DOCUMENT doc = reinterpret_cast(docHandle); + if (!doc) return -1; + + FPDF_PAGE page = FPDF_LoadPage(doc, index); + if (!page) return -1; + jfloat width = FPDF_GetPageWidthF(page); + FPDF_ClosePage(page); + return width; +} + +JNIEXPORT jfloat JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_getPageHeight(JNIEnv* env, jobject thiz, jlong docHandle, jint index) { + if (!pdfiumLibHandle) { + return -1; + } + FPDF_DOCUMENT doc = reinterpret_cast(docHandle); + if (!doc) return -1; + + FPDF_PAGE page = FPDF_LoadPage(doc, index); + if (!page) return -1; + + jfloat height = FPDF_GetPageHeightF(page); + FPDF_ClosePage(page); + return height; +} + +JNIEXPORT jbyteArray JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_renderPage(JNIEnv* env, jobject thiz, jlong docHandle, jint pageIndex, jint width, jint height) { + if (!pdfiumLibHandle) { + return nullptr; + } + FPDF_DOCUMENT doc = reinterpret_cast(docHandle); + if (!doc) return nullptr; + + FPDF_PAGE page = FPDF_LoadPage(doc, pageIndex); + if (!page) return nullptr; + + FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0); + if (!bitmap) { + FPDF_ClosePage(page); + return nullptr; + } + + FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF); + FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, FPDF_LCD_TEXT | FPDF_REVERSE_BYTE_ORDER); + + void* buffer = FPDFBitmap_GetBuffer(bitmap); + int stride = FPDFBitmap_GetStride(bitmap); + int totalSize = stride * height; + + jbyteArray result = env->NewByteArray(totalSize); + if (result != nullptr) { + env->SetByteArrayRegion(result, 0, totalSize, (jbyte*)buffer); + } + + FPDFBitmap_Destroy(bitmap); + FPDF_ClosePage(page); + + return result; +} + +JNIEXPORT jbyteArray JNICALL +Java_com_syncfusion_flutter_pdfviewer_android_PdfiumAdapter_renderTile(JNIEnv* env, jobject thiz, + jlong docHandle, + jint pageIndex, + jfloat x, jfloat y, + jint width, jint height, + jfloat scale) { + if (!pdfiumLibHandle) { + return nullptr; + } + FPDF_DOCUMENT doc = reinterpret_cast(docHandle); + if (!doc) return nullptr; + + FPDF_PAGE page = FPDF_LoadPage(doc, pageIndex); + if (!page) return nullptr; + + FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0); + if (!bitmap) { + FPDF_ClosePage(page); + return nullptr; + } + + FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF); + + FS_MATRIX matrix = { + scale, 0, 0, + scale, -x * scale, -y * scale + }; + + FS_RECTF clip = {0, 0, (float)(width * scale), (float)(height * scale)}; + + FPDF_RenderPageBitmapWithMatrix(bitmap, page, &matrix, &clip, FPDF_LCD_TEXT | FPDF_REVERSE_BYTE_ORDER); + + void* buffer = FPDFBitmap_GetBuffer(bitmap); + int stride = FPDFBitmap_GetStride(bitmap); + int totalSize = stride * height; + + jbyteArray result = env->NewByteArray(totalSize); + if (result != nullptr) { + env->SetByteArrayRegion(result, 0, totalSize, (jbyte*)buffer); + } + + FPDFBitmap_Destroy(bitmap); + FPDF_ClosePage(page); + + return result; +} + +} // extern "C" diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/java/com/syncfusion/flutter/pdfviewer/android/PdfiumAdapter.java b/packages/syncfusion_pdfviewer_android/android/src/main/java/com/syncfusion/flutter/pdfviewer/android/PdfiumAdapter.java new file mode 100644 index 000000000..c930f9f33 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/src/main/java/com/syncfusion/flutter/pdfviewer/android/PdfiumAdapter.java @@ -0,0 +1,90 @@ +package com.syncfusion.flutter.pdfviewer.android; + +/** + * PdfiumAdapter provides methods to interact + * with native PDFium libraries for rendering and processing PDFs. + */ +public class PdfiumAdapter { + + static { + // Load the native PDFium wrapper library which acts as a wrapper built via CMake + System.loadLibrary("pdfium_wrapper"); + } + + /** + * Initializes the PDFium library for usage. + */ + public static native boolean initLibrary(); + + /** + * Destroys the PDFium library and cleans up any resources used. + */ + public static native void destroyLibrary(); + + /** + * Loads a PDF document using byte data and an optional password for encrypted PDFs. + * + * @param data the byte array representing the PDF document + * @param password the password for encrypted PDFs (pass an empty string if not needed) + * @return long representing the handle or reference to the loaded document + */ + public static native long loadDocument(byte[] data, String password); + + /** + * Closes the specified PDF document and releases resources tied to it. + * + * @param docHandle the handle to the loaded PDF document + */ + public static native void closeDocument(long docHandle); + + /** + * Retrieves the total number of pages in the specified PDF document. + * + * @param docHandle the handle to the loaded PDF document + * @return the number of pages in the PDF document + */ + public static native int getPageCount(long docHandle); + + /** + * Retrieves the width of a specific page in the PDF document. + * + * @param docHandle the handle to the loaded PDF document + * @param index the page index for which the width is needed + * @return the width of the page in points + */ + public static native float getPageWidth(long docHandle, int index); + + /** + * Retrieves the height of a specific page in the PDF document. + * + * @param docHandle the handle to the loaded PDF document + * @param index the page index for which the height is needed + * @return the height of the page in points + */ + public static native float getPageHeight(long docHandle, int index); + /** + * Renders a specific page of the PDF as an image. + * + * @param docHandle the handle to the loaded PDF document + * @param pageIndex the index of the page to render + * @param width the desired width of the rendered output + * @param height the desired height of the rendered output + * @return a byte array representing the rendered image of the page + */ + public static native byte[] renderPage(long docHandle, int pageIndex, int width, int height); + + /** + * Renders a specific tile of the page to handle large pages efficiently. + * + * @param docHandle the handle to the loaded PDF document + * @param pageIndex the index of the page + * @param x the x coordinate of the tile's top-left corner + * @param y the y coordinate of the tile's top-left corner + * @param width the width of the tile to render + * @param height the height of the tile to render + * @param scale the scale factor for rendering + * @return a byte array representing the rendered tile image + */ + public static native byte[] renderTile(long docHandle, int pageIndex, float x, float y, int width, int height, float scale); +} + diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/java/com/syncfusion/flutter/pdfviewer/android/SyncfusionFlutterPdfViewerPdfiumPlugin.java b/packages/syncfusion_pdfviewer_android/android/src/main/java/com/syncfusion/flutter/pdfviewer/android/SyncfusionFlutterPdfViewerPdfiumPlugin.java new file mode 100644 index 000000000..797bd0015 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/android/src/main/java/com/syncfusion/flutter/pdfviewer/android/SyncfusionFlutterPdfViewerPdfiumPlugin.java @@ -0,0 +1,210 @@ +package com.syncfusion.flutter.pdfviewer.android; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Color; +import android.graphics.Matrix; +import android.graphics.Rect; +import android.graphics.pdf.PdfRenderer; +import android.os.Build; +import android.os.ParcelFileDescriptor; + +import androidx.annotation.NonNull; +import androidx.annotation.RequiresApi; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import io.flutter.plugin.common.MethodChannel.MethodCallHandler; +import io.flutter.plugin.common.MethodChannel.Result; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; + +@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) +public class SyncfusionFlutterPdfViewerPdfiumPlugin implements FlutterPlugin, MethodCallHandler { + private MethodChannel channel; + private ExecutorService executorService; + + private HashMap documentHandleMap = new HashMap<>(); + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) { + if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + boolean initSuccess = PdfiumAdapter.initLibrary(); + if (initSuccess) { + channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "syncfusion_flutter_pdfviewer"); + channel.setMethodCallHandler(this); + executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); + } + } + } + + @Override + public void onMethodCall(@NonNull final MethodCall call, @NonNull final Result result) { + switch (call.method) { + case "getPage": + getPage(call, result); + break; + case "getTileImage": + getTileImage(call, result); + break; + case "initializePdfRenderer": + initializePdfRenderer(call, result); + break; + case "getPagesWidth": + getPagesWidth(call, result); + break; + case "getPagesHeight": + getPagesHeight(call, result); + break; + case "closeDocument": + closeDocument(call, result); + break; + default: + result.notImplemented(); + break; + } + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + if (channel != null) { + channel.setMethodCallHandler(null); + } + if (executorService != null && !executorService.isShutdown()) { + executorService.shutdown(); + } + PdfiumAdapter.destroyLibrary(); + } + + private void getPage(MethodCall call, Result result) { + int pageIndex = call.argument("index"); + int width = call.argument("width"); + int height = call.argument("height"); + String documentID = call.argument("documentID"); + + Long docHandle = documentHandleMap.get(documentID); + + if (docHandle == null) { + result.error("ERROR", "Document not found", null); + } + + try { + byte[] imageBytes = PdfiumAdapter.renderPage(docHandle, pageIndex - 1, width, height); + result.success(imageBytes); + } catch (Exception e) { + result.error(e.getMessage(), e.getLocalizedMessage(), e.getMessage()); + } + } + + private void getTileImage(MethodCall call, Result result) { + int pageNumber = call.argument("pageNumber"); + double scale = call.argument("scale"); + double x = call.argument("x"); + double y = call.argument("y"); + double width = call.argument("width"); + double height = call.argument("height"); + String documentID = call.argument("documentID"); + Long docHandle = documentHandleMap.get(documentID); + + if (docHandle == null) { + result.error("ERROR", "Document not found", null); + } + + try { + byte[] imageBytes = PdfiumAdapter.renderTile(docHandle, pageNumber - 1, (float) x, (float) y, (int)width, (int)height, (float) scale); + result.success(imageBytes); + } catch (Exception e) { + result.error(e.getMessage(), e.getLocalizedMessage(), e.getMessage()); + } + } + + private void initializePdfRenderer(MethodCall call, Result result) { + executorService.execute(() -> { + byte[] bytes = call.argument("documentBytes"); + String documentID = call.argument("documentID"); + String password = call.argument("password"); + + try { + if (password == null) { + password = ""; + } + long docHandle = PdfiumAdapter.loadDocument(bytes, password); + documentHandleMap.put(documentID, docHandle); + int pageCount = PdfiumAdapter.getPageCount(docHandle); + result.success(String.valueOf(pageCount)); + } catch (SecurityException e) { + result.error("PASSWORD_ERROR", "Incorrect password or document is encrypted", null); + } catch (Exception e) { + result.error("PDF_RENDERER_ERROR", e.getMessage(), null); + } + }); + } + + private void getPagesWidth(MethodCall call, Result result) { + String documentID = (String) call.arguments; + Long docHandle = documentHandleMap.get(documentID); + + if (docHandle == null) { + result.error("ERROR", "Document not found", null); + } + + executorService.execute(() -> { + try { + int count = PdfiumAdapter.getPageCount(docHandle); + double[] pageWidth = new double[count]; + for (int i = 0; i < count; i++) { + pageWidth[i] = PdfiumAdapter.getPageWidth(docHandle, i); + } + result.success(pageWidth); + } catch (Exception e) { + result.error("PAGE_WIDTH_ERROR", e.getMessage(), null); + } + }); + } + + private void getPagesHeight(MethodCall call, Result result) { + String documentID = (String) call.arguments; + Long docHandle = documentHandleMap.get(documentID); + + if (docHandle == null) { + result.error("ERROR", "Document not found", null); + } + + executorService.execute(() -> { + try { + int count = PdfiumAdapter.getPageCount(docHandle); + double[] pageHeight = new double[count]; + for (int i = 0; i < count; i++) { + pageHeight[i] = PdfiumAdapter.getPageHeight(docHandle, i); + } + result.success(pageHeight); + } catch (Exception e) { + result.error("PAGE_HEIGHT_ERROR", e.getMessage(), null); + } + }); + } + + private void closeDocument(MethodCall call, Result result) { + String documentID = (String) call.arguments; + Long docHandle = documentHandleMap.get(documentID); + + if (docHandle == null) { + result.error("ERROR", "Document not found", null); + } + PdfiumAdapter.closeDocument(docHandle); + documentHandleMap.remove(docHandle); + result.success(true); + } +} \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/arm64-v8a/libpdfium.so b/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/arm64-v8a/libpdfium.so new file mode 100644 index 000000000..3483071f5 Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/arm64-v8a/libpdfium.so differ diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/armeabi-v7a/libpdfium.so b/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/armeabi-v7a/libpdfium.so new file mode 100644 index 000000000..09e9fff91 Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/armeabi-v7a/libpdfium.so differ diff --git a/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/x86_64/libpdfium.so b/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/x86_64/libpdfium.so new file mode 100644 index 000000000..7c11d96f3 Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/android/src/main/jniLibs/pdfium/x86_64/libpdfium.so differ diff --git a/packages/syncfusion_pdfviewer_android/example/.gitignore b/packages/syncfusion_pdfviewer_android/example/.gitignore new file mode 100644 index 000000000..79c113f9b --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/syncfusion_pdfviewer_android/example/README.md b/packages/syncfusion_pdfviewer_android/example/README.md new file mode 100644 index 000000000..127423976 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/README.md @@ -0,0 +1,3 @@ +# syncfusion_pdfviewer_windows_example + +Demonstrates how to use the syncfusion_pdfviewer_windows plugin. diff --git a/packages/syncfusion_pdfviewer_android/example/analysis_options.yaml b/packages/syncfusion_pdfviewer_android/example/analysis_options.yaml new file mode 100644 index 000000000..b08414c80 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/example/android/.gitignore b/packages/syncfusion_pdfviewer_android/example/android/.gitignore new file mode 100644 index 000000000..be3943c96 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/build.gradle.kts b/packages/syncfusion_pdfviewer_android/example/android/app/build.gradle.kts new file mode 100644 index 000000000..9abd2e485 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.application") + id("kotlin-android") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +android { + namespace = "com.syncfusion.syncfusion_pdfviewer_android_example" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.syncfusion.syncfusion_pdfviewer_android_example" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } +} + +flutter { + source = "../.." +} diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/debug/AndroidManifest.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/AndroidManifest.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..bf6faa7c6 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/java/com/example/example/MainActivity.java b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/java/com/example/example/MainActivity.java new file mode 100644 index 000000000..59f336d2e --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/java/com/example/example/MainActivity.java @@ -0,0 +1,6 @@ +package com.example.example; + +import io.flutter.embedding.android.FlutterActivity; + +public class MainActivity extends FlutterActivity { +} diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/drawable-v21/launch_background.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 000000000..f74085f3f --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/drawable/launch_background.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 000000000..304732f88 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 000000000..db77bb4b7 Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 000000000..17987b79b Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 000000000..09d439148 Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..d5f1c8d34 Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 000000000..4d6372eeb Binary files /dev/null and b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/values-night/styles.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 000000000..06952be74 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/values/styles.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..cb1ef8805 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/app/src/profile/AndroidManifest.xml b/packages/syncfusion_pdfviewer_android/example/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 000000000..399f6981d --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/packages/syncfusion_pdfviewer_android/example/android/build.gradle.kts b/packages/syncfusion_pdfviewer_android/example/android/build.gradle.kts new file mode 100644 index 000000000..89176ef44 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/build.gradle.kts @@ -0,0 +1,21 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = rootProject.layout.buildDirectory.dir("../../build").get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/packages/syncfusion_pdfviewer_android/example/android/gradle.properties b/packages/syncfusion_pdfviewer_android/example/android/gradle.properties new file mode 100644 index 000000000..f018a6181 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +android.enableJetifier=true diff --git a/packages/syncfusion_pdfviewer_android/example/android/gradle/wrapper/gradle-wrapper.properties b/packages/syncfusion_pdfviewer_android/example/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..ac3b47926 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-all.zip diff --git a/packages/syncfusion_pdfviewer_android/example/android/settings.gradle.kts b/packages/syncfusion_pdfviewer_android/example/android/settings.gradle.kts new file mode 100644 index 000000000..ab39a10a2 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/android/settings.gradle.kts @@ -0,0 +1,25 @@ +pluginManagement { + val flutterSdkPath = run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "8.7.3" apply false + id("org.jetbrains.kotlin.android") version "2.1.0" apply false +} + +include(":app") diff --git a/packages/syncfusion_pdfviewer_android/example/lib/main.dart b/packages/syncfusion_pdfviewer_android/example/lib/main.dart new file mode 100644 index 000000000..d26dc20be --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/lib/main.dart @@ -0,0 +1,50 @@ +import 'package:flutter/material.dart'; +import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; + +void main() { + runApp( + MaterialApp( + title: 'Syncfusion PDF Viewer Demo', + theme: ThemeData(useMaterial3: false), + home: const HomePage(), + ), + ); +} + +/// Represents Homepage for Navigation +class HomePage extends StatefulWidget { + const HomePage({Key? key}) : super(key: key); + + @override + _HomePage createState() => _HomePage(); +} + +class _HomePage extends State { + final GlobalKey _pdfViewerKey = GlobalKey(); + + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Syncfusion Flutter PDF Viewer'), + actions: [ + IconButton( + icon: const Icon(Icons.bookmark, color: Colors.white), + onPressed: () { + _pdfViewerKey.currentState?.openBookmarkView(); + }, + ), + ], + ), + body: SfPdfViewer.network( + 'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf', + key: _pdfViewerKey, + ), + ); + } +} diff --git a/packages/syncfusion_pdfviewer_android/example/pubspec.yaml b/packages/syncfusion_pdfviewer_android/example/pubspec.yaml new file mode 100644 index 000000000..487ee2ac7 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/example/pubspec.yaml @@ -0,0 +1,18 @@ +name: syncfusion_pdfviewer_android_example +description: "Demonstrates how to use the syncfusion_pdfviewer_android plugin." +publish_to: 'none' + +environment: + sdk: ^3.7.0-0 + +dependencies: + flutter: + sdk: flutter + syncfusion_flutter_pdfviewer: + +dev_dependencies: + flutter_test: + sdk: flutter + +flutter: + uses-material-design: true \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_android/pubspec.yaml b/packages/syncfusion_pdfviewer_android/pubspec.yaml new file mode 100644 index 000000000..8d2d3ebc7 --- /dev/null +++ b/packages/syncfusion_pdfviewer_android/pubspec.yaml @@ -0,0 +1,24 @@ +name: syncfusion_pdfviewer_android +description: An optional Android platform implementation of the Flutter PDF Viewer library that lets you view PDF documents seamlessly and efficiently, which uses PDFium for rendering. +version: 30.1.1 +homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_pdfviewer_android + +environment: + sdk: ^3.7.0-0 + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + +flutter: + plugin: + platforms: + android: + package: com.syncfusion.flutter.pdfviewer.android + pluginClass: SyncfusionFlutterPdfViewerPdfiumPlugin diff --git a/packages/syncfusion_pdfviewer_linux/.gitignore b/packages/syncfusion_pdfviewer_linux/.gitignore new file mode 100644 index 000000000..ac5aa9893 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/.gitignore @@ -0,0 +1,29 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +build/ diff --git a/packages/syncfusion_pdfviewer_linux/CHANGELOG.md b/packages/syncfusion_pdfviewer_linux/CHANGELOG.md new file mode 100644 index 000000000..fb70942b0 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/CHANGELOG.md @@ -0,0 +1,3 @@ +## Undefined + +* Initial release. \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/LICENSE b/packages/syncfusion_pdfviewer_linux/LICENSE new file mode 100644 index 000000000..02291f801 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/LICENSE @@ -0,0 +1,12 @@ +Syncfusion® License + +Syncfusion® Flutter PDF Viewer package is available under the Syncfusion® Essential Studio® program, and can be licensed either under the Syncfusion® Community License Program or the Syncfusion® commercial license. + +To be qualified for the Syncfusion® Community License Program you must have a gross revenue of less than one (1) million U.S. dollars ($1,000,000.00 USD) per year and have less than five (5) developers in your organization, and agree to be bound by the Syncfusion® terms and conditions. + +Customers who do not qualify for the community license can contact sales@syncfusion.com for commercial licensing options. + +Under no circumstances can you use this product without (1) either a Community License or a commercial license and (2) without agreeing and abiding by the Syncfusion® license containing all terms and conditions. + +The Syncfusion® license that contains the terms and conditions can be found at +https://www.syncfusion.com/content/downloads/syncfusion_license.pdf \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/README.md b/packages/syncfusion_pdfviewer_linux/README.md new file mode 100644 index 000000000..8c16f986a --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/README.md @@ -0,0 +1,61 @@ +![syncfusion_flutter_pdfviewer](https://cdn.syncfusion.com/content/images/pdfviewer-banner.png) + +# Flutter PDF Viewer Linux + +This is the Linux implementation of [Syncfusion® Flutter PDF Viewer](https://pub.dev/packages/syncfusion_flutter_pdfviewer) plugin. + +**Disclaimer:** This is a commercial package. To use this package, you need to have either a Syncfusion® commercial license or [free Syncfusion® Community License](https://www.syncfusion.com/products/communitylicense). For more details, please check the [LICENSE](https://github.com/syncfusion/flutter-examples/blob/master/LICENSE) file. + +## Table of contents +- [Get the demo application](#get-the-demo-application) +- [Useful links](#other-useful-links) +- [Installation](#installation) +- [Support and feedback](#support-and-feedback) +- [About Syncfusion®](#about-syncfusion) + +## Get the demo application + +Explore the full capabilities of our Flutter widgets on your device by installing our sample browser applications from the following app stores. View the sample code in GitHub. + +

+ + + +

+

+ + +

+ +## Other useful links + +Take a look at the following to learn more about the Syncfusion® Flutter PDF Viewer: + +* [Syncfusion® Flutter PDF Viewer product page](https://www.syncfusion.com/flutter-widgets/flutter-pdf-viewer) +* [User guide documentation](https://help.syncfusion.com/flutter/pdf-viewer/overview) + +## Installation + +Install the latest version of [syncfusion_flutter_pdfviewer](https://pub.dev/packages/syncfusion_flutter_pdfviewer/install) from [pub.dev](https://pub.dev/publishers/syncfusion.com/packages). + +### Import the package + +This package is an endorsed implementation of `syncfusion_flutter_pdfviewer` for the Linux platform since version `30.1.37`, so it gets automatically added to your dependencies when you depend on package `syncfusion_flutter_pdfviewer`. + +```yaml +dependencies: + ... + syncfusion_flutter_pdfviewer: ^30.1.27 + ... +``` + +## Support and feedback + +* For any queries, reach out to our [Syncfusion® support team](https://support.syncfusion.com/support/tickets/create) or post them through the [community forums](https://www.syncfusion.com/forums). Please submit feature requests and bug reports through our [feedback portal](https://www.syncfusion.com/feedback/flutter). +* To renew your subscription, click [renew](https://www.syncfusion.com/sales/products) or contact our sales team at salessupport@syncfusion.com | Toll Free: 1-888-9 DOTNET. + +## About Syncfusion® + +Founded in 2001 and headquartered in Research Triangle Park, N.C., Syncfusion® has more than 20,000 customers and more than 1 million users, including large financial institutions, Fortune 500 companies, and global IT consultancies. + +Today we provide 1,000+ controls and frameworks for web ([ASP.NET Core](https://www.syncfusion.com/aspnet-core-ui-controls), [ASP.NET MVC](https://www.syncfusion.com/aspnet-mvc-ui-controls), [ASP.NET WebForms](https://www.syncfusion.com/jquery/aspnet-web-forms-ui-controls), [JavaScript](https://www.syncfusion.com/javascript-ui-controls), [Angular](https://www.syncfusion.com/angular-ui-components), [React](https://www.syncfusion.com/react-ui-components), [Vue](https://www.syncfusion.com/vue-ui-components), [Flutter](https://www.syncfusion.com/flutter-widgets), and [Blazor](https://www.syncfusion.com/blazor-components)), mobile ([Xamarin](https://www.syncfusion.com/xamarin-ui-controls), [.NET MAUI](https://www.syncfusion.com/maui-controls), [Flutter](https://www.syncfusion.com/flutter-widgets), [UWP](https://www.syncfusion.com/uwp-ui-controls), and [JavaScript](https://www.syncfusion.com/javascript-ui-controls)), and desktop development ([Flutter](https://www.syncfusion.com/flutter-widgets), [WinForms](https://www.syncfusion.com/winforms-ui-controls), [WPF](https://www.syncfusion.com/wpf-ui-controls), [UWP](https://www.syncfusion.com/uwp-ui-controls), [.NET MAUI](https://www.syncfusion.com/maui-controls), and [WinUI](https://www.syncfusion.com/winui-controls)). We provide ready-to deploy enterprise software for dashboards, reports, data integration, and big data processing. Many customers have saved millions in licensing fees by deploying our software. \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/analysis_options.yaml b/packages/syncfusion_pdfviewer_linux/analysis_options.yaml new file mode 100644 index 000000000..a8c45a74c --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/analysis_options.yaml @@ -0,0 +1,6 @@ +analyzer: + errors: + lines_longer_than_80_chars: ignore + include_file_not_found: ignore + uri_does_not_exist: ignore + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/example/.gitignore b/packages/syncfusion_pdfviewer_linux/example/.gitignore new file mode 100644 index 000000000..29a3a5017 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/.gitignore @@ -0,0 +1,43 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/syncfusion_pdfviewer_linux/example/README.md b/packages/syncfusion_pdfviewer_linux/example/README.md new file mode 100644 index 000000000..1640e7da2 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/README.md @@ -0,0 +1,16 @@ +# syncfusion_pdfviewer_linux_example + +Demonstrates how to use the syncfusion_pdfviewer_linux plugin. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/packages/syncfusion_pdfviewer_linux/example/analysis_options.yaml b/packages/syncfusion_pdfviewer_linux/example/analysis_options.yaml new file mode 100644 index 000000000..b08414c80 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/example/lib/main.dart b/packages/syncfusion_pdfviewer_linux/example/lib/main.dart new file mode 100644 index 000000000..461b7d9af --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/lib/main.dart @@ -0,0 +1,44 @@ +import 'package:flutter/material.dart'; +import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart'; + +void main() { + runApp( + const MaterialApp( + title: 'Syncfusion PDF Viewer Demo for Linux', + home: HomePage(), + ), + ); +} + +/// Represents Homepage for Navigation +class HomePage extends StatefulWidget { + const HomePage({super.key}); + + @override + State createState() => _HomePage(); +} + +class _HomePage extends State { + final GlobalKey _pdfViewerKey = GlobalKey(); + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar( + title: const Text('Syncfusion Flutter PDF Viewer'), + actions: [ + IconButton( + icon: const Icon(Icons.bookmark, color: Colors.white), + onPressed: () { + _pdfViewerKey.currentState?.openBookmarkView(); + }, + ), + ], + ), + body: SfPdfViewer.network( + 'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf', + key: _pdfViewerKey, + ), + ); + } +} diff --git a/packages/syncfusion_pdfviewer_linux/example/linux/.gitignore b/packages/syncfusion_pdfviewer_linux/example/linux/.gitignore new file mode 100644 index 000000000..d3896c984 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/packages/syncfusion_pdfviewer_linux/example/linux/CMakeLists.txt b/packages/syncfusion_pdfviewer_linux/example/linux/CMakeLists.txt new file mode 100644 index 000000000..d58abf066 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/linux/CMakeLists.txt @@ -0,0 +1,144 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.10) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "syncfusion_pdfviewer_linux_example") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.syncfusion_pdfviewer_linux") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Define the application target. To change its name, change BINARY_NAME above, +# not the value here, or `flutter run` will no longer work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/packages/syncfusion_pdfviewer_linux/example/linux/flutter/CMakeLists.txt b/packages/syncfusion_pdfviewer_linux/example/linux/flutter/CMakeLists.txt new file mode 100644 index 000000000..d5bd01648 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/packages/syncfusion_pdfviewer_linux/example/linux/main.cc b/packages/syncfusion_pdfviewer_linux/example/linux/main.cc new file mode 100644 index 000000000..e7c5c5437 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/linux/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/packages/syncfusion_pdfviewer_linux/example/linux/my_application.cc b/packages/syncfusion_pdfviewer_linux/example/linux/my_application.cc new file mode 100644 index 000000000..997583188 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/linux/my_application.cc @@ -0,0 +1,124 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "syncfusion_pdfviewer_linux_example"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "syncfusion_pdfviewer_linux_example"); + } + + gtk_window_set_default_size(window, 1280, 720); + gtk_widget_show(GTK_WIDGET(window)); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + //MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, + "flags", G_APPLICATION_NON_UNIQUE, + nullptr)); +} diff --git a/packages/syncfusion_pdfviewer_linux/example/linux/my_application.h b/packages/syncfusion_pdfviewer_linux/example/linux/my_application.h new file mode 100644 index 000000000..72271d5e4 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/linux/my_application.h @@ -0,0 +1,18 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/packages/syncfusion_pdfviewer_linux/example/pubspec.yaml b/packages/syncfusion_pdfviewer_linux/example/pubspec.yaml new file mode 100644 index 000000000..44a765562 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/example/pubspec.yaml @@ -0,0 +1,18 @@ +name: syncfusion_pdfviewer_linux_example +description: "Demonstrates how to use the syncfusion_pdfviewer_linux plugin." +publish_to: 'none' + +environment: + sdk: ^3.7.0-0 + +dependencies: + flutter: + sdk: flutter + syncfusion_flutter_pdfviewer: + +dev_dependencies: + flutter_test: + sdk: flutter + +flutter: + uses-material-design: true diff --git a/packages/syncfusion_pdfviewer_linux/linux/CMakeLists.txt b/packages/syncfusion_pdfviewer_linux/linux/CMakeLists.txt new file mode 100644 index 000000000..fcb6e49c4 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/linux/CMakeLists.txt @@ -0,0 +1,45 @@ +cmake_minimum_required(VERSION 3.10) +project(syncfusion_pdfviewer_linux LANGUAGES CXX) + +# Determine the CPU architecture +if(CMAKE_SYSTEM_PROCESSOR MATCHES "aarch64") + set(PDFIUM_ARCH "arm64") +else() + set(PDFIUM_ARCH "x64") +endif() + +find_path(PDFium_INCLUDE_DIR + NAMES "fpdfview.h" + PATHS "${CMAKE_CURRENT_LIST_DIR}/include/pdfium" +) + +find_file(PDFium_LIBRARY + NAMES "libpdfium.so" + PATHS "${CMAKE_CURRENT_LIST_DIR}/include/pdfium/${PDFIUM_ARCH}/bin" +) + +find_package_handle_standard_args(PDFium REQUIRED_VARS PDFium_LIBRARY PDFium_INCLUDE_DIR) + +add_library(pdfium SHARED IMPORTED) +set_target_properties(pdfium PROPERTIES + IMPORTED_LOCATION "${PDFium_LIBRARY}" + INTERFACE_INCLUDE_DIRECTORIES "${PDFium_INCLUDE_DIR}" +) + +set(PLUGIN_NAME "syncfusion_pdfviewer_linux_plugin") + +add_library(${PLUGIN_NAME} SHARED + pdfviewer.cpp + pdfviewer.h + syncfusion_pdfviewer_linux_plugin.cc +) + +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden +) + +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) +target_include_directories(${PLUGIN_NAME} INTERFACE "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter pdfium PkgConfig::GTK) + +set(syncfusion_pdfviewer_linux_bundled_libraries "${PDFium_LIBRARY}" PARENT_SCOPE) \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/arm64/bin/libpdfium.so b/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/arm64/bin/libpdfium.so new file mode 100644 index 000000000..e12f2a382 Binary files /dev/null and b/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/arm64/bin/libpdfium.so differ diff --git a/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/fpdfview.h b/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/fpdfview.h new file mode 100644 index 000000000..779fa5fb9 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/fpdfview.h @@ -0,0 +1,1401 @@ +// Copyright 2014 PDFium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com + +// NOTE: External docs refer to this file as "fpdfview.h", so do not rename +// despite lack of consistency with other public files. + +#ifndef PUBLIC_FPDFVIEW_H_ +#define PUBLIC_FPDFVIEW_H_ + +// clang-format off + +#include + +#if defined(_WIN32) && !defined(__WINDOWS__) +#include +#endif + +#ifdef PDF_ENABLE_XFA +// PDF_USE_XFA is set in confirmation that this version of PDFium can support +// XFA forms as requested by the PDF_ENABLE_XFA setting. +#define PDF_USE_XFA +#endif // PDF_ENABLE_XFA + +// PDF object types +#define FPDF_OBJECT_UNKNOWN 0 +#define FPDF_OBJECT_BOOLEAN 1 +#define FPDF_OBJECT_NUMBER 2 +#define FPDF_OBJECT_STRING 3 +#define FPDF_OBJECT_NAME 4 +#define FPDF_OBJECT_ARRAY 5 +#define FPDF_OBJECT_DICTIONARY 6 +#define FPDF_OBJECT_STREAM 7 +#define FPDF_OBJECT_NULLOBJ 8 +#define FPDF_OBJECT_REFERENCE 9 + +// PDF text rendering modes +typedef enum { + FPDF_TEXTRENDERMODE_UNKNOWN = -1, + FPDF_TEXTRENDERMODE_FILL = 0, + FPDF_TEXTRENDERMODE_STROKE = 1, + FPDF_TEXTRENDERMODE_FILL_STROKE = 2, + FPDF_TEXTRENDERMODE_INVISIBLE = 3, + FPDF_TEXTRENDERMODE_FILL_CLIP = 4, + FPDF_TEXTRENDERMODE_STROKE_CLIP = 5, + FPDF_TEXTRENDERMODE_FILL_STROKE_CLIP = 6, + FPDF_TEXTRENDERMODE_CLIP = 7, + FPDF_TEXTRENDERMODE_LAST = FPDF_TEXTRENDERMODE_CLIP, +} FPDF_TEXT_RENDERMODE; + +// PDF types - use incomplete types (never completed) to force API type safety. +typedef struct fpdf_action_t__* FPDF_ACTION; +typedef struct fpdf_annotation_t__* FPDF_ANNOTATION; +typedef struct fpdf_attachment_t__* FPDF_ATTACHMENT; +typedef struct fpdf_avail_t__* FPDF_AVAIL; +typedef struct fpdf_bitmap_t__* FPDF_BITMAP; +typedef struct fpdf_bookmark_t__* FPDF_BOOKMARK; +typedef struct fpdf_clippath_t__* FPDF_CLIPPATH; +typedef struct fpdf_dest_t__* FPDF_DEST; +typedef struct fpdf_document_t__* FPDF_DOCUMENT; +typedef struct fpdf_font_t__* FPDF_FONT; +typedef struct fpdf_form_handle_t__* FPDF_FORMHANDLE; +typedef const struct fpdf_glyphpath_t__* FPDF_GLYPHPATH; +typedef struct fpdf_javascript_action_t* FPDF_JAVASCRIPT_ACTION; +typedef struct fpdf_link_t__* FPDF_LINK; +typedef struct fpdf_page_t__* FPDF_PAGE; +typedef struct fpdf_pagelink_t__* FPDF_PAGELINK; +typedef struct fpdf_pageobject_t__* FPDF_PAGEOBJECT; // (text, path, etc.) +typedef struct fpdf_pageobjectmark_t__* FPDF_PAGEOBJECTMARK; +typedef struct fpdf_pagerange_t__* FPDF_PAGERANGE; +typedef const struct fpdf_pathsegment_t* FPDF_PATHSEGMENT; +typedef void* FPDF_RECORDER; // Passed into skia. +typedef struct fpdf_schhandle_t__* FPDF_SCHHANDLE; +typedef struct fpdf_signature_t__* FPDF_SIGNATURE; +typedef struct fpdf_structelement_t__* FPDF_STRUCTELEMENT; +typedef struct fpdf_structtree_t__* FPDF_STRUCTTREE; +typedef struct fpdf_textpage_t__* FPDF_TEXTPAGE; +typedef struct fpdf_widget_t__* FPDF_WIDGET; +typedef struct fpdf_xobject_t__* FPDF_XOBJECT; + +// Basic data types +typedef int FPDF_BOOL; +typedef int FPDF_RESULT; +typedef unsigned long FPDF_DWORD; +typedef float FS_FLOAT; + +// Duplex types +typedef enum _FPDF_DUPLEXTYPE_ { + DuplexUndefined = 0, + Simplex, + DuplexFlipShortEdge, + DuplexFlipLongEdge +} FPDF_DUPLEXTYPE; + +// String types +typedef unsigned short FPDF_WCHAR; + +// FPDFSDK may use three types of strings: byte string, wide string (UTF-16LE +// encoded), and platform dependent string +typedef const char* FPDF_BYTESTRING; + +// FPDFSDK always uses UTF-16LE encoded wide strings, each character uses 2 +// bytes (except surrogation), with the low byte first. +typedef const unsigned short* FPDF_WIDESTRING; + +// Structure for persisting a string beyond the duration of a callback. +// Note: although represented as a char*, string may be interpreted as +// a UTF-16LE formated string. Used only by XFA callbacks. +typedef struct FPDF_BSTR_ { + char* str; // String buffer, manipulate only with FPDF_BStr_* methods. + int len; // Length of the string, in bytes. +} FPDF_BSTR; + +// For Windows programmers: In most cases it's OK to treat FPDF_WIDESTRING as a +// Windows unicode string, however, special care needs to be taken if you +// expect to process Unicode larger than 0xffff. +// +// For Linux/Unix programmers: most compiler/library environments use 4 bytes +// for a Unicode character, and you have to convert between FPDF_WIDESTRING and +// system wide string by yourself. +typedef const char* FPDF_STRING; + +// Matrix for transformation, in the form [a b c d e f], equivalent to: +// | a b 0 | +// | c d 0 | +// | e f 1 | +// +// Translation is performed with [1 0 0 1 tx ty]. +// Scaling is performed with [sx 0 0 sy 0 0]. +// See PDF Reference 1.7, 4.2.2 Common Transformations for more. +typedef struct _FS_MATRIX_ { + float a; + float b; + float c; + float d; + float e; + float f; +} FS_MATRIX; + +// Rectangle area(float) in device or page coordinate system. +typedef struct _FS_RECTF_ { + // The x-coordinate of the left-top corner. + float left; + // The y-coordinate of the left-top corner. + float top; + // The x-coordinate of the right-bottom corner. + float right; + // The y-coordinate of the right-bottom corner. + float bottom; +} * FS_LPRECTF, FS_RECTF; + +// Const Pointer to FS_RECTF structure. +typedef const FS_RECTF* FS_LPCRECTF; + +// Rectangle size. Coordinate system agnostic. +typedef struct FS_SIZEF_ { + float width; + float height; +} * FS_LPSIZEF, FS_SIZEF; + +// Const Pointer to FS_SIZEF structure. +typedef const FS_SIZEF* FS_LPCSIZEF; + +// 2D Point. Coordinate system agnostic. +typedef struct FS_POINTF_ { + float x; + float y; +} * FS_LPPOINTF, FS_POINTF; + +// Const Pointer to FS_POINTF structure. +typedef const FS_POINTF* FS_LPCPOINTF; + +// Annotation enums. +typedef int FPDF_ANNOTATION_SUBTYPE; +typedef int FPDF_ANNOT_APPEARANCEMODE; + +// Dictionary value types. +typedef int FPDF_OBJECT_TYPE; + +#if defined(COMPONENT_BUILD) +// FPDF_EXPORT should be consistent with |export| in the pdfium_fuzzer +// template in testing/fuzzers/BUILD.gn. +#if defined(WIN32) +#if defined(FPDF_IMPLEMENTATION) +#define FPDF_EXPORT __declspec(dllexport) +#else +#define FPDF_EXPORT __declspec(dllimport) +#endif // defined(FPDF_IMPLEMENTATION) +#else +#if defined(FPDF_IMPLEMENTATION) +#define FPDF_EXPORT __attribute__((visibility("default"))) +#else +#define FPDF_EXPORT +#endif // defined(FPDF_IMPLEMENTATION) +#endif // defined(WIN32) +#else +#define FPDF_EXPORT +#endif // defined(COMPONENT_BUILD) + +#if defined(WIN32) && defined(FPDFSDK_EXPORTS) +#define FPDF_CALLCONV __stdcall +#else +#define FPDF_CALLCONV +#endif + +// Exported Functions +#ifdef __cplusplus +extern "C" { +#endif + +// Function: FPDF_InitLibrary +// Initialize the FPDFSDK library +// Parameters: +// None +// Return value: +// None. +// Comments: +// Convenience function to call FPDF_InitLibraryWithConfig() for +// backwards compatibility purposes. This will be deprecated in the +// future. +FPDF_EXPORT void FPDF_CALLCONV FPDF_InitLibrary(); + +// Process-wide options for initializing the library. +typedef struct FPDF_LIBRARY_CONFIG_ { + // Version number of the interface. Currently must be 2. + // Support for version 1 will be deprecated in the future. + int version; + + // Array of paths to scan in place of the defaults when using built-in + // FXGE font loading code. The array is terminated by a NULL pointer. + // The Array may be NULL itself to use the default paths. May be ignored + // entirely depending upon the platform. + const char** m_pUserFontPaths; + + // Version 2. + + // Pointer to the v8::Isolate to use, or NULL to force PDFium to create one. + void* m_pIsolate; + + // The embedder data slot to use in the v8::Isolate to store PDFium's + // per-isolate data. The value needs to be in the range + // [0, |v8::Internals::kNumIsolateDataLots|). Note that 0 is fine for most + // embedders. + unsigned int m_v8EmbedderSlot; + + // Version 3 - Experimantal, + + // Pointer to the V8::Platform to use. + void* m_pPlatform; + +} FPDF_LIBRARY_CONFIG; + +// Function: FPDF_InitLibraryWithConfig +// Initialize the FPDFSDK library +// Parameters: +// config - configuration information as above. +// Return value: +// None. +// Comments: +// You have to call this function before you can call any PDF +// processing functions. +FPDF_EXPORT void FPDF_CALLCONV +FPDF_InitLibraryWithConfig(const FPDF_LIBRARY_CONFIG* config); + +// Function: FPDF_DestroyLibary +// Release all resources allocated by the FPDFSDK library. +// Parameters: +// None. +// Return value: +// None. +// Comments: +// You can call this function to release all memory blocks allocated by +// the library. +// After this function is called, you should not call any PDF +// processing functions. +FPDF_EXPORT void FPDF_CALLCONV FPDF_DestroyLibrary(); + +// Policy for accessing the local machine time. +#define FPDF_POLICY_MACHINETIME_ACCESS 0 + +// Function: FPDF_SetSandBoxPolicy +// Set the policy for the sandbox environment. +// Parameters: +// policy - The specified policy for setting, for example: +// FPDF_POLICY_MACHINETIME_ACCESS. +// enable - True to enable, false to disable the policy. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_SetSandBoxPolicy(FPDF_DWORD policy, + FPDF_BOOL enable); + +#if defined(_WIN32) +// Experimental API. +// Function: FPDF_SetPrintMode +// Set printing mode when printing on Windows. +// Parameters: +// mode - FPDF_PRINTMODE_EMF to output EMF (default) +// FPDF_PRINTMODE_TEXTONLY to output text only (for charstream +// devices) +// FPDF_PRINTMODE_POSTSCRIPT2 to output level 2 PostScript into +// EMF as a series of GDI comments. +// FPDF_PRINTMODE_POSTSCRIPT3 to output level 3 PostScript into +// EMF as a series of GDI comments. +// FPDF_PRINTMODE_POSTSCRIPT2_PASSTHROUGH to output level 2 +// PostScript via ExtEscape() in PASSTHROUGH mode. +// FPDF_PRINTMODE_POSTSCRIPT3_PASSTHROUGH to output level 3 +// PostScript via ExtEscape() in PASSTHROUGH mode. +// FPDF_PRINTMODE_EMF_IMAGE_MASKS to output EMF, with more +// efficient processing of documents containing image masks. +// FPDF_PRINTMODE_POSTSCRIPT3_TYPE42 to output level 3 +// PostScript with embedded Type 42 fonts, when applicable, into +// EMF as a series of GDI comments. +// FPDF_PRINTMODE_POSTSCRIPT3_TYPE42_PASSTHROUGH to output level +// 3 PostScript with embedded Type 42 fonts, when applicable, +// via ExtEscape() in PASSTHROUGH mode. +// Return value: +// True if successful, false if unsuccessful (typically invalid input). +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_SetPrintMode(int mode); +#endif // defined(_WIN32) + +// Function: FPDF_LoadDocument +// Open and load a PDF document. +// Parameters: +// file_path - Path to the PDF file (including extension). +// password - A string used as the password for the PDF file. +// If no password is needed, empty or NULL can be used. +// See comments below regarding the encoding. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// Loaded document can be closed by FPDF_CloseDocument(). +// If this function fails, you can use FPDF_GetLastError() to retrieve +// the reason why it failed. +// +// The encoding for |password| can be either UTF-8 or Latin-1. PDFs, +// depending on the security handler revision, will only accept one or +// the other encoding. If |password|'s encoding and the PDF's expected +// encoding do not match, FPDF_LoadDocument() will automatically +// convert |password| to the other encoding. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadDocument(FPDF_STRING file_path, FPDF_BYTESTRING password); + +// Function: FPDF_LoadMemDocument +// Open and load a PDF document from memory. +// Parameters: +// data_buf - Pointer to a buffer containing the PDF document. +// size - Number of bytes in the PDF document. +// password - A string used as the password for the PDF file. +// If no password is needed, empty or NULL can be used. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// The memory buffer must remain valid when the document is open. +// The loaded document can be closed by FPDF_CloseDocument. +// If this function fails, you can use FPDF_GetLastError() to retrieve +// the reason why it failed. +// +// See the comments for FPDF_LoadDocument() regarding the encoding for +// |password|. +// Notes: +// If PDFium is built with the XFA module, the application should call +// FPDF_LoadXFA() function after the PDF document loaded to support XFA +// fields defined in the fpdfformfill.h file. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadMemDocument(const void* data_buf, int size, FPDF_BYTESTRING password); + +// Experimental API. +// Function: FPDF_LoadMemDocument64 +// Open and load a PDF document from memory. +// Parameters: +// data_buf - Pointer to a buffer containing the PDF document. +// size - Number of bytes in the PDF document. +// password - A string used as the password for the PDF file. +// If no password is needed, empty or NULL can be used. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// The memory buffer must remain valid when the document is open. +// The loaded document can be closed by FPDF_CloseDocument. +// If this function fails, you can use FPDF_GetLastError() to retrieve +// the reason why it failed. +// +// See the comments for FPDF_LoadDocument() regarding the encoding for +// |password|. +// Notes: +// If PDFium is built with the XFA module, the application should call +// FPDF_LoadXFA() function after the PDF document loaded to support XFA +// fields defined in the fpdfformfill.h file. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadMemDocument64(const void* data_buf, + size_t size, + FPDF_BYTESTRING password); + +// Structure for custom file access. +typedef struct { + // File length, in bytes. + unsigned long m_FileLen; + + // A function pointer for getting a block of data from a specific position. + // Position is specified by byte offset from the beginning of the file. + // The pointer to the buffer is never NULL and the size is never 0. + // The position and size will never go out of range of the file length. + // It may be possible for FPDFSDK to call this function multiple times for + // the same position. + // Return value: should be non-zero if successful, zero for error. + int (*m_GetBlock)(void* param, + unsigned long position, + unsigned char* pBuf, + unsigned long size); + + // A custom pointer for all implementation specific data. This pointer will + // be used as the first parameter to the m_GetBlock callback. + void* m_Param; +} FPDF_FILEACCESS; + +/* + * Structure for file reading or writing (I/O). + * + * Note: This is a handler and should be implemented by callers, + * and is only used from XFA. + */ +typedef struct FPDF_FILEHANDLER_ { + /* + * User-defined data. + * Note: Callers can use this field to track controls. + */ + void* clientData; + + /* + * Callback function to release the current file stream object. + * + * Parameters: + * clientData - Pointer to user-defined data. + * Returns: + * None. + */ + void (*Release)(void* clientData); + + /* + * Callback function to retrieve the current file stream size. + * + * Parameters: + * clientData - Pointer to user-defined data. + * Returns: + * Size of file stream. + */ + FPDF_DWORD (*GetSize)(void* clientData); + + /* + * Callback function to read data from the current file stream. + * + * Parameters: + * clientData - Pointer to user-defined data. + * offset - Offset position starts from the beginning of file + * stream. This parameter indicates reading position. + * buffer - Memory buffer to store data which are read from + * file stream. This parameter should not be NULL. + * size - Size of data which should be read from file stream, + * in bytes. The buffer indicated by |buffer| must be + * large enough to store specified data. + * Returns: + * 0 for success, other value for failure. + */ + FPDF_RESULT (*ReadBlock)(void* clientData, + FPDF_DWORD offset, + void* buffer, + FPDF_DWORD size); + + /* + * Callback function to write data into the current file stream. + * + * Parameters: + * clientData - Pointer to user-defined data. + * offset - Offset position starts from the beginning of file + * stream. This parameter indicates writing position. + * buffer - Memory buffer contains data which is written into + * file stream. This parameter should not be NULL. + * size - Size of data which should be written into file + * stream, in bytes. + * Returns: + * 0 for success, other value for failure. + */ + FPDF_RESULT (*WriteBlock)(void* clientData, + FPDF_DWORD offset, + const void* buffer, + FPDF_DWORD size); + /* + * Callback function to flush all internal accessing buffers. + * + * Parameters: + * clientData - Pointer to user-defined data. + * Returns: + * 0 for success, other value for failure. + */ + FPDF_RESULT (*Flush)(void* clientData); + + /* + * Callback function to change file size. + * + * Description: + * This function is called under writing mode usually. Implementer + * can determine whether to realize it based on application requests. + * Parameters: + * clientData - Pointer to user-defined data. + * size - New size of file stream, in bytes. + * Returns: + * 0 for success, other value for failure. + */ + FPDF_RESULT (*Truncate)(void* clientData, FPDF_DWORD size); +} FPDF_FILEHANDLER; + +// Function: FPDF_LoadCustomDocument +// Load PDF document from a custom access descriptor. +// Parameters: +// pFileAccess - A structure for accessing the file. +// password - Optional password for decrypting the PDF file. +// Return value: +// A handle to the loaded document, or NULL on failure. +// Comments: +// The application must keep the file resources |pFileAccess| points to +// valid until the returned FPDF_DOCUMENT is closed. |pFileAccess| +// itself does not need to outlive the FPDF_DOCUMENT. +// +// The loaded document can be closed with FPDF_CloseDocument(). +// +// See the comments for FPDF_LoadDocument() regarding the encoding for +// |password|. +// Notes: +// If PDFium is built with the XFA module, the application should call +// FPDF_LoadXFA() function after the PDF document loaded to support XFA +// fields defined in the fpdfformfill.h file. +FPDF_EXPORT FPDF_DOCUMENT FPDF_CALLCONV +FPDF_LoadCustomDocument(FPDF_FILEACCESS* pFileAccess, FPDF_BYTESTRING password); + +// Function: FPDF_GetFileVersion +// Get the file version of the given PDF document. +// Parameters: +// doc - Handle to a document. +// fileVersion - The PDF file version. File version: 14 for 1.4, 15 +// for 1.5, ... +// Return value: +// True if succeeds, false otherwise. +// Comments: +// If the document was created by FPDF_CreateNewDocument, +// then this function will always fail. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_GetFileVersion(FPDF_DOCUMENT doc, + int* fileVersion); + +#define FPDF_ERR_SUCCESS 0 // No error. +#define FPDF_ERR_UNKNOWN 1 // Unknown error. +#define FPDF_ERR_FILE 2 // File not found or could not be opened. +#define FPDF_ERR_FORMAT 3 // File not in PDF format or corrupted. +#define FPDF_ERR_PASSWORD 4 // Password required or incorrect password. +#define FPDF_ERR_SECURITY 5 // Unsupported security scheme. +#define FPDF_ERR_PAGE 6 // Page not found or content error. +#ifdef PDF_ENABLE_XFA +#define FPDF_ERR_XFALOAD 7 // Load XFA error. +#define FPDF_ERR_XFALAYOUT 8 // Layout XFA error. +#endif // PDF_ENABLE_XFA + +// Function: FPDF_GetLastError +// Get last error code when a function fails. +// Parameters: +// None. +// Return value: +// A 32-bit integer indicating error code as defined above. +// Comments: +// If the previous SDK call succeeded, the return value of this +// function is not defined. +FPDF_EXPORT unsigned long FPDF_CALLCONV FPDF_GetLastError(); + +// Experimental API. +// Function: FPDF_DocumentHasValidCrossReferenceTable +// Whether the document's cross reference table is valid or not. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// True if the PDF parser did not encounter problems parsing the cross +// reference table. False if the parser could not parse the cross +// reference table and the table had to be rebuild from other data +// within the document. +// Comments: +// The return value can change over time as the PDF parser evolves. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV +FPDF_DocumentHasValidCrossReferenceTable(FPDF_DOCUMENT document); + +// Experimental API. +// Function: FPDF_GetTrailerEnds +// Get the byte offsets of trailer ends. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument(). +// buffer - The address of a buffer that receives the +// byte offsets. +// length - The size, in ints, of |buffer|. +// Return value: +// Returns the number of ints in the buffer on success, 0 on error. +// +// |buffer| is an array of integers that describes the exact byte offsets of the +// trailer ends in the document. If |length| is less than the returned length, +// or |document| or |buffer| is NULL, |buffer| will not be modified. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_GetTrailerEnds(FPDF_DOCUMENT document, + unsigned int* buffer, + unsigned long length); + +// Function: FPDF_GetDocPermission +// Get file permission flags of the document. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// A 32-bit integer indicating permission flags. Please refer to the +// PDF Reference for detailed descriptions. If the document is not +// protected, 0xffffffff will be returned. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_GetDocPermissions(FPDF_DOCUMENT document); + +// Function: FPDF_GetSecurityHandlerRevision +// Get the revision for the security handler. +// Parameters: +// document - Handle to a document. Returned by FPDF_LoadDocument. +// Return value: +// The security handler revision number. Please refer to the PDF +// Reference for a detailed description. If the document is not +// protected, -1 will be returned. +FPDF_EXPORT int FPDF_CALLCONV +FPDF_GetSecurityHandlerRevision(FPDF_DOCUMENT document); + +// Function: FPDF_GetPageCount +// Get total number of pages in the document. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument. +// Return value: +// Total number of pages in the document. +FPDF_EXPORT int FPDF_CALLCONV FPDF_GetPageCount(FPDF_DOCUMENT document); + +// Function: FPDF_LoadPage +// Load a page inside the document. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument +// page_index - Index number of the page. 0 for the first page. +// Return value: +// A handle to the loaded page, or NULL if page load fails. +// Comments: +// The loaded page can be rendered to devices using FPDF_RenderPage. +// The loaded page can be closed using FPDF_ClosePage. +FPDF_EXPORT FPDF_PAGE FPDF_CALLCONV FPDF_LoadPage(FPDF_DOCUMENT document, + int page_index); + +// Experimental API +// Function: FPDF_GetPageWidthF +// Get page width. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage(). +// Return value: +// Page width (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm). +FPDF_EXPORT float FPDF_CALLCONV FPDF_GetPageWidthF(FPDF_PAGE page); + +// Function: FPDF_GetPageWidth +// Get page width. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// Return value: +// Page width (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm). +// Note: +// Prefer FPDF_GetPageWidthF() above. This will be deprecated in the +// future. +FPDF_EXPORT double FPDF_CALLCONV FPDF_GetPageWidth(FPDF_PAGE page); + +// Experimental API +// Function: FPDF_GetPageHeightF +// Get page height. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage(). +// Return value: +// Page height (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm) +FPDF_EXPORT float FPDF_CALLCONV FPDF_GetPageHeightF(FPDF_PAGE page); + +// Function: FPDF_GetPageHeight +// Get page height. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// Return value: +// Page height (excluding non-displayable area) measured in points. +// One point is 1/72 inch (around 0.3528 mm) +// Note: +// Prefer FPDF_GetPageHeightF() above. This will be deprecated in the +// future. +FPDF_EXPORT double FPDF_CALLCONV FPDF_GetPageHeight(FPDF_PAGE page); + +// Experimental API. +// Function: FPDF_GetPageBoundingBox +// Get the bounding box of the page. This is the intersection between +// its media box and its crop box. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// rect - Pointer to a rect to receive the page bounding box. +// On an error, |rect| won't be filled. +// Return value: +// True for success. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_GetPageBoundingBox(FPDF_PAGE page, + FS_RECTF* rect); + +// Experimental API. +// Function: FPDF_GetPageSizeByIndexF +// Get the size of the page at the given index. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument(). +// page_index - Page index, zero for the first page. +// size - Pointer to a FS_SIZEF to receive the page size. +// (in points). +// Return value: +// Non-zero for success. 0 for error (document or page not found). +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV +FPDF_GetPageSizeByIndexF(FPDF_DOCUMENT document, + int page_index, + FS_SIZEF* size); + +// Function: FPDF_GetPageSizeByIndex +// Get the size of the page at the given index. +// Parameters: +// document - Handle to document. Returned by FPDF_LoadDocument. +// page_index - Page index, zero for the first page. +// width - Pointer to a double to receive the page width +// (in points). +// height - Pointer to a double to receive the page height +// (in points). +// Return value: +// Non-zero for success. 0 for error (document or page not found). +// Note: +// Prefer FPDF_GetPageSizeByIndexF() above. This will be deprecated in +// the future. +FPDF_EXPORT int FPDF_CALLCONV FPDF_GetPageSizeByIndex(FPDF_DOCUMENT document, + int page_index, + double* width, + double* height); + +// Page rendering flags. They can be combined with bit-wise OR. +// +// Set if annotations are to be rendered. +#define FPDF_ANNOT 0x01 +// Set if using text rendering optimized for LCD display. This flag will only +// take effect if anti-aliasing is enabled for text. +#define FPDF_LCD_TEXT 0x02 +// Don't use the native text output available on some platforms +#define FPDF_NO_NATIVETEXT 0x04 +// Grayscale output. +#define FPDF_GRAYSCALE 0x08 +// Obsolete, has no effect, retained for compatibility. +#define FPDF_DEBUG_INFO 0x80 +// Obsolete, has no effect, retained for compatibility. +#define FPDF_NO_CATCH 0x100 +// Limit image cache size. +#define FPDF_RENDER_LIMITEDIMAGECACHE 0x200 +// Always use halftone for image stretching. +#define FPDF_RENDER_FORCEHALFTONE 0x400 +// Render for printing. +#define FPDF_PRINTING 0x800 +// Set to disable anti-aliasing on text. This flag will also disable LCD +// optimization for text rendering. +#define FPDF_RENDER_NO_SMOOTHTEXT 0x1000 +// Set to disable anti-aliasing on images. +#define FPDF_RENDER_NO_SMOOTHIMAGE 0x2000 +// Set to disable anti-aliasing on paths. +#define FPDF_RENDER_NO_SMOOTHPATH 0x4000 +// Set whether to render in a reverse Byte order, this flag is only used when +// rendering to a bitmap. +#define FPDF_REVERSE_BYTE_ORDER 0x10 +// Set whether fill paths need to be stroked. This flag is only used when +// FPDF_COLORSCHEME is passed in, since with a single fill color for paths the +// boundaries of adjacent fill paths are less visible. +#define FPDF_CONVERT_FILL_TO_STROKE 0x20 + +// Struct for color scheme. +// Each should be a 32-bit value specifying the color, in 8888 ARGB format. +typedef struct FPDF_COLORSCHEME_ { + FPDF_DWORD path_fill_color; + FPDF_DWORD path_stroke_color; + FPDF_DWORD text_fill_color; + FPDF_DWORD text_stroke_color; +} FPDF_COLORSCHEME; + +#ifdef _WIN32 +// Function: FPDF_RenderPage +// Render contents of a page to a device (screen, bitmap, or printer). +// This function is only supported on Windows. +// Parameters: +// dc - Handle to the device context. +// page - Handle to the page. Returned by FPDF_LoadPage. +// start_x - Left pixel position of the display area in +// device coordinates. +// start_y - Top pixel position of the display area in device +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// flags - 0 for normal display, or combination of flags +// defined above. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_RenderPage(HDC dc, + FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + int flags); +#endif + +// Function: FPDF_RenderPageBitmap +// Render contents of a page to a device independent bitmap. +// Parameters: +// bitmap - Handle to the device independent bitmap (as the +// output buffer). The bitmap handle can be created +// by FPDFBitmap_Create or retrieved from an image +// object by FPDFImageObj_GetBitmap. +// page - Handle to the page. Returned by FPDF_LoadPage +// start_x - Left pixel position of the display area in +// bitmap coordinates. +// start_y - Top pixel position of the display area in bitmap +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// flags - 0 for normal display, or combination of the Page +// Rendering flags defined above. With the FPDF_ANNOT +// flag, it renders all annotations that do not require +// user-interaction, which are all annotations except +// widget and popup annotations. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_RenderPageBitmap(FPDF_BITMAP bitmap, + FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + int flags); + +// Function: FPDF_RenderPageBitmapWithMatrix +// Render contents of a page to a device independent bitmap. +// Parameters: +// bitmap - Handle to the device independent bitmap (as the +// output buffer). The bitmap handle can be created +// by FPDFBitmap_Create or retrieved by +// FPDFImageObj_GetBitmap. +// page - Handle to the page. Returned by FPDF_LoadPage. +// matrix - The transform matrix, which must be invertible. +// See PDF Reference 1.7, 4.2.2 Common Transformations. +// clipping - The rect to clip to in device coords. +// flags - 0 for normal display, or combination of the Page +// Rendering flags defined above. With the FPDF_ANNOT +// flag, it renders all annotations that do not require +// user-interaction, which are all annotations except +// widget and popup annotations. +// Return value: +// None. Note that behavior is undefined if det of |matrix| is 0. +FPDF_EXPORT void FPDF_CALLCONV +FPDF_RenderPageBitmapWithMatrix(FPDF_BITMAP bitmap, + FPDF_PAGE page, + const FS_MATRIX* matrix, + const FS_RECTF* clipping, + int flags); + +#if defined(_SKIA_SUPPORT_) +FPDF_EXPORT FPDF_RECORDER FPDF_CALLCONV FPDF_RenderPageSkp(FPDF_PAGE page, + int size_x, + int size_y); +#endif + +// Function: FPDF_ClosePage +// Close a loaded PDF page. +// Parameters: +// page - Handle to the loaded page. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_ClosePage(FPDF_PAGE page); + +// Function: FPDF_CloseDocument +// Close a loaded PDF document. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// None. +FPDF_EXPORT void FPDF_CALLCONV FPDF_CloseDocument(FPDF_DOCUMENT document); + +// Function: FPDF_DeviceToPage +// Convert the screen coordinates of a point to page coordinates. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// start_x - Left pixel position of the display area in +// device coordinates. +// start_y - Top pixel position of the display area in device +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// device_x - X value in device coordinates to be converted. +// device_y - Y value in device coordinates to be converted. +// page_x - A pointer to a double receiving the converted X +// value in page coordinates. +// page_y - A pointer to a double receiving the converted Y +// value in page coordinates. +// Return value: +// Returns true if the conversion succeeds, and |page_x| and |page_y| +// successfully receives the converted coordinates. +// Comments: +// The page coordinate system has its origin at the left-bottom corner +// of the page, with the X-axis on the bottom going to the right, and +// the Y-axis on the left side going up. +// +// NOTE: this coordinate system can be altered when you zoom, scroll, +// or rotate a page, however, a point on the page should always have +// the same coordinate values in the page coordinate system. +// +// The device coordinate system is device dependent. For screen device, +// its origin is at the left-top corner of the window. However this +// origin can be altered by the Windows coordinate transformation +// utilities. +// +// You must make sure the start_x, start_y, size_x, size_y +// and rotate parameters have exactly same values as you used in +// the FPDF_RenderPage() function call. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_DeviceToPage(FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + int device_x, + int device_y, + double* page_x, + double* page_y); + +// Function: FPDF_PageToDevice +// Convert the page coordinates of a point to screen coordinates. +// Parameters: +// page - Handle to the page. Returned by FPDF_LoadPage. +// start_x - Left pixel position of the display area in +// device coordinates. +// start_y - Top pixel position of the display area in device +// coordinates. +// size_x - Horizontal size (in pixels) for displaying the page. +// size_y - Vertical size (in pixels) for displaying the page. +// rotate - Page orientation: +// 0 (normal) +// 1 (rotated 90 degrees clockwise) +// 2 (rotated 180 degrees) +// 3 (rotated 90 degrees counter-clockwise) +// page_x - X value in page coordinates. +// page_y - Y value in page coordinate. +// device_x - A pointer to an integer receiving the result X +// value in device coordinates. +// device_y - A pointer to an integer receiving the result Y +// value in device coordinates. +// Return value: +// Returns true if the conversion succeeds, and |device_x| and +// |device_y| successfully receives the converted coordinates. +// Comments: +// See comments for FPDF_DeviceToPage(). +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_PageToDevice(FPDF_PAGE page, + int start_x, + int start_y, + int size_x, + int size_y, + int rotate, + double page_x, + double page_y, + int* device_x, + int* device_y); + +// Function: FPDFBitmap_Create +// Create a device independent bitmap (FXDIB). +// Parameters: +// width - The number of pixels in width for the bitmap. +// Must be greater than 0. +// height - The number of pixels in height for the bitmap. +// Must be greater than 0. +// alpha - A flag indicating whether the alpha channel is used. +// Non-zero for using alpha, zero for not using. +// Return value: +// The created bitmap handle, or NULL if a parameter error or out of +// memory. +// Comments: +// The bitmap always uses 4 bytes per pixel. The first byte is always +// double word aligned. +// +// The byte order is BGRx (the last byte unused if no alpha channel) or +// BGRA. +// +// The pixels in a horizontal line are stored side by side, with the +// left most pixel stored first (with lower memory address). +// Each line uses width * 4 bytes. +// +// Lines are stored one after another, with the top most line stored +// first. There is no gap between adjacent lines. +// +// This function allocates enough memory for holding all pixels in the +// bitmap, but it doesn't initialize the buffer. Applications can use +// FPDFBitmap_FillRect() to fill the bitmap using any color. If the OS +// allows it, this function can allocate up to 4 GB of memory. +FPDF_EXPORT FPDF_BITMAP FPDF_CALLCONV FPDFBitmap_Create(int width, + int height, + int alpha); + +// More DIB formats +// Unknown or unsupported format. +#define FPDFBitmap_Unknown 0 +// Gray scale bitmap, one byte per pixel. +#define FPDFBitmap_Gray 1 +// 3 bytes per pixel, byte order: blue, green, red. +#define FPDFBitmap_BGR 2 +// 4 bytes per pixel, byte order: blue, green, red, unused. +#define FPDFBitmap_BGRx 3 +// 4 bytes per pixel, byte order: blue, green, red, alpha. +#define FPDFBitmap_BGRA 4 + +// Function: FPDFBitmap_CreateEx +// Create a device independent bitmap (FXDIB) +// Parameters: +// width - The number of pixels in width for the bitmap. +// Must be greater than 0. +// height - The number of pixels in height for the bitmap. +// Must be greater than 0. +// format - A number indicating for bitmap format, as defined +// above. +// first_scan - A pointer to the first byte of the first line if +// using an external buffer. If this parameter is NULL, +// then the a new buffer will be created. +// stride - Number of bytes for each scan line, for external +// buffer only. +// Return value: +// The bitmap handle, or NULL if parameter error or out of memory. +// Comments: +// Similar to FPDFBitmap_Create function, but allows for more formats +// and an external buffer is supported. The bitmap created by this +// function can be used in any place that a FPDF_BITMAP handle is +// required. +// +// If an external buffer is used, then the application should destroy +// the buffer by itself. FPDFBitmap_Destroy function will not destroy +// the buffer. +FPDF_EXPORT FPDF_BITMAP FPDF_CALLCONV FPDFBitmap_CreateEx(int width, + int height, + int format, + void* first_scan, + int stride); + +// Function: FPDFBitmap_GetFormat +// Get the format of the bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The format of the bitmap. +// Comments: +// Only formats supported by FPDFBitmap_CreateEx are supported by this +// function; see the list of such formats above. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetFormat(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_FillRect +// Fill a rectangle in a bitmap. +// Parameters: +// bitmap - The handle to the bitmap. Returned by +// FPDFBitmap_Create. +// left - The left position. Starting from 0 at the +// left-most pixel. +// top - The top position. Starting from 0 at the +// top-most line. +// width - Width in pixels to be filled. +// height - Height in pixels to be filled. +// color - A 32-bit value specifing the color, in 8888 ARGB +// format. +// Return value: +// None. +// Comments: +// This function sets the color and (optionally) alpha value in the +// specified region of the bitmap. +// +// NOTE: If the alpha channel is used, this function does NOT +// composite the background with the source color, instead the +// background will be replaced by the source color and the alpha. +// +// If the alpha channel is not used, the alpha parameter is ignored. +FPDF_EXPORT void FPDF_CALLCONV FPDFBitmap_FillRect(FPDF_BITMAP bitmap, + int left, + int top, + int width, + int height, + FPDF_DWORD color); + +// Function: FPDFBitmap_GetBuffer +// Get data buffer of a bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The pointer to the first byte of the bitmap buffer. +// Comments: +// The stride may be more than width * number of bytes per pixel +// +// Applications can use this function to get the bitmap buffer pointer, +// then manipulate any color and/or alpha values for any pixels in the +// bitmap. +// +// The data is in BGRA format. Where the A maybe unused if alpha was +// not specified. +FPDF_EXPORT void* FPDF_CALLCONV FPDFBitmap_GetBuffer(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_GetWidth +// Get width of a bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The width of the bitmap in pixels. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetWidth(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_GetHeight +// Get height of a bitmap. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The height of the bitmap in pixels. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetHeight(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_GetStride +// Get number of bytes for each line in the bitmap buffer. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// The number of bytes for each line in the bitmap buffer. +// Comments: +// The stride may be more than width * number of bytes per pixel. +FPDF_EXPORT int FPDF_CALLCONV FPDFBitmap_GetStride(FPDF_BITMAP bitmap); + +// Function: FPDFBitmap_Destroy +// Destroy a bitmap and release all related buffers. +// Parameters: +// bitmap - Handle to the bitmap. Returned by FPDFBitmap_Create +// or FPDFImageObj_GetBitmap. +// Return value: +// None. +// Comments: +// This function will not destroy any external buffers provided when +// the bitmap was created. +FPDF_EXPORT void FPDF_CALLCONV FPDFBitmap_Destroy(FPDF_BITMAP bitmap); + +// Function: FPDF_VIEWERREF_GetPrintScaling +// Whether the PDF document prefers to be scaled or not. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// None. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintScaling(FPDF_DOCUMENT document); + +// Function: FPDF_VIEWERREF_GetNumCopies +// Returns the number of copies to be printed. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// The number of copies to be printed. +FPDF_EXPORT int FPDF_CALLCONV +FPDF_VIEWERREF_GetNumCopies(FPDF_DOCUMENT document); + +// Function: FPDF_VIEWERREF_GetPrintPageRange +// Page numbers to initialize print dialog box when file is printed. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// The print page range to be used for printing. +FPDF_EXPORT FPDF_PAGERANGE FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintPageRange(FPDF_DOCUMENT document); + +// Experimental API. +// Function: FPDF_VIEWERREF_GetPrintPageRangeCount +// Returns the number of elements in a FPDF_PAGERANGE. +// Parameters: +// pagerange - Handle to the page range. +// Return value: +// The number of elements in the page range. Returns 0 on error. +FPDF_EXPORT size_t FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintPageRangeCount(FPDF_PAGERANGE pagerange); + +// Experimental API. +// Function: FPDF_VIEWERREF_GetPrintPageRangeElement +// Returns an element from a FPDF_PAGERANGE. +// Parameters: +// pagerange - Handle to the page range. +// index - Index of the element. +// Return value: +// The value of the element in the page range at a given index. +// Returns -1 on error. +FPDF_EXPORT int FPDF_CALLCONV +FPDF_VIEWERREF_GetPrintPageRangeElement(FPDF_PAGERANGE pagerange, size_t index); + +// Function: FPDF_VIEWERREF_GetDuplex +// Returns the paper handling option to be used when printing from +// the print dialog. +// Parameters: +// document - Handle to the loaded document. +// Return value: +// The paper handling option to be used when printing. +FPDF_EXPORT FPDF_DUPLEXTYPE FPDF_CALLCONV +FPDF_VIEWERREF_GetDuplex(FPDF_DOCUMENT document); + +// Function: FPDF_VIEWERREF_GetName +// Gets the contents for a viewer ref, with a given key. The value must +// be of type "name". +// Parameters: +// document - Handle to the loaded document. +// key - Name of the key in the viewer pref dictionary, +// encoded in UTF-8. +// buffer - A string to write the contents of the key to. +// length - Length of the buffer. +// Return value: +// The number of bytes in the contents, including the NULL terminator. +// Thus if the return value is 0, then that indicates an error, such +// as when |document| is invalid or |buffer| is NULL. If |length| is +// less than the returned length, or |buffer| is NULL, |buffer| will +// not be modified. +FPDF_EXPORT unsigned long FPDF_CALLCONV +FPDF_VIEWERREF_GetName(FPDF_DOCUMENT document, + FPDF_BYTESTRING key, + char* buffer, + unsigned long length); + +// Function: FPDF_CountNamedDests +// Get the count of named destinations in the PDF document. +// Parameters: +// document - Handle to a document +// Return value: +// The count of named destinations. +FPDF_EXPORT FPDF_DWORD FPDF_CALLCONV +FPDF_CountNamedDests(FPDF_DOCUMENT document); + +// Function: FPDF_GetNamedDestByName +// Get a the destination handle for the given name. +// Parameters: +// document - Handle to the loaded document. +// name - The name of a destination. +// Return value: +// The handle to the destination. +FPDF_EXPORT FPDF_DEST FPDF_CALLCONV +FPDF_GetNamedDestByName(FPDF_DOCUMENT document, FPDF_BYTESTRING name); + +// Function: FPDF_GetNamedDest +// Get the named destination by index. +// Parameters: +// document - Handle to a document +// index - The index of a named destination. +// buffer - The buffer to store the destination name, +// used as wchar_t*. +// buflen [in/out] - Size of the buffer in bytes on input, +// length of the result in bytes on output +// or -1 if the buffer is too small. +// Return value: +// The destination handle for a given index, or NULL if there is no +// named destination corresponding to |index|. +// Comments: +// Call this function twice to get the name of the named destination: +// 1) First time pass in |buffer| as NULL and get buflen. +// 2) Second time pass in allocated |buffer| and buflen to retrieve +// |buffer|, which should be used as wchar_t*. +// +// If buflen is not sufficiently large, it will be set to -1 upon +// return. +FPDF_EXPORT FPDF_DEST FPDF_CALLCONV FPDF_GetNamedDest(FPDF_DOCUMENT document, + int index, + void* buffer, + long* buflen); + +// Experimental API. +// Function: FPDF_GetXFAPacketCount +// Get the number of valid packets in the XFA entry. +// Parameters: +// document - Handle to the document. +// Return value: +// The number of valid packets, or -1 on error. +FPDF_EXPORT int FPDF_CALLCONV FPDF_GetXFAPacketCount(FPDF_DOCUMENT document); + +// Experimental API. +// Function: FPDF_GetXFAPacketName +// Get the name of a packet in the XFA array. +// Parameters: +// document - Handle to the document. +// index - Index number of the packet. 0 for the first packet. +// buffer - Buffer for holding the name of the XFA packet. +// buflen - Length of |buffer| in bytes. +// Return value: +// The length of the packet name in bytes, or 0 on error. +// +// |document| must be valid and |index| must be in the range [0, N), where N is +// the value returned by FPDF_GetXFAPacketCount(). +// |buffer| is only modified if it is non-NULL and |buflen| is greater than or +// equal to the length of the packet name. The packet name includes a +// terminating NUL character. |buffer| is unmodified on error. +FPDF_EXPORT unsigned long FPDF_CALLCONV FPDF_GetXFAPacketName( + FPDF_DOCUMENT document, + int index, + void* buffer, + unsigned long buflen); + +// Experimental API. +// Function: FPDF_GetXFAPacketContent +// Get the content of a packet in the XFA array. +// Parameters: +// document - Handle to the document. +// index - Index number of the packet. 0 for the first packet. +// buffer - Buffer for holding the content of the XFA packet. +// buflen - Length of |buffer| in bytes. +// out_buflen - Pointer to the variable that will receive the minimum +// buffer size needed to contain the content of the XFA +// packet. +// Return value: +// Whether the operation succeeded or not. +// +// |document| must be valid and |index| must be in the range [0, N), where N is +// the value returned by FPDF_GetXFAPacketCount(). |out_buflen| must not be +// NULL. When the aforementioned arguments are valid, the operation succeeds, +// and |out_buflen| receives the content size. |buffer| is only modified if +// |buffer| is non-null and long enough to contain the content. Callers must +// check both the return value and the input |buflen| is no less than the +// returned |out_buflen| before using the data in |buffer|. +FPDF_EXPORT FPDF_BOOL FPDF_CALLCONV FPDF_GetXFAPacketContent( + FPDF_DOCUMENT document, + int index, + void* buffer, + unsigned long buflen, + unsigned long* out_buflen); + +#ifdef PDF_ENABLE_V8 +// Function: FPDF_GetRecommendedV8Flags +// Returns a space-separated string of command line flags that are +// recommended to be passed into V8 via V8::SetFlagsFromString() +// prior to initializing the PDFium library. +// Parameters: +// None. +// Return value: +// NUL-terminated string of the form "--flag1 --flag2". +// The caller must not attempt to modify or free the result. +FPDF_EXPORT const char* FPDF_CALLCONV FPDF_GetRecommendedV8Flags(); + +// Experimental API. +// Function: FPDF_GetArrayBufferAllocatorSharedInstance() +// Helper function for initializing V8 isolates that will +// use PDFium's internal memory management. +// Parameters: +// None. +// Return Value: +// Pointer to a suitable v8::ArrayBuffer::Allocator, returned +// as void for C compatibility. +// Notes: +// Use is optional, but allows external creation of isolates +// matching the ones PDFium will make when none is provided +// via |FPDF_LIBRARY_CONFIG::m_pIsolate|. +FPDF_EXPORT void* FPDF_CALLCONV FPDF_GetArrayBufferAllocatorSharedInstance(); +#endif // PDF_ENABLE_V8 + +#ifdef PDF_ENABLE_XFA +// Function: FPDF_BStr_Init +// Helper function to initialize a FPDF_BSTR. +FPDF_EXPORT FPDF_RESULT FPDF_CALLCONV FPDF_BStr_Init(FPDF_BSTR* bstr); + +// Function: FPDF_BStr_Set +// Helper function to copy string data into the FPDF_BSTR. +FPDF_EXPORT FPDF_RESULT FPDF_CALLCONV FPDF_BStr_Set(FPDF_BSTR* bstr, + const char* cstr, + int length); + +// Function: FPDF_BStr_Clear +// Helper function to clear a FPDF_BSTR. +FPDF_EXPORT FPDF_RESULT FPDF_CALLCONV FPDF_BStr_Clear(FPDF_BSTR* bstr); +#endif // PDF_ENABLE_XFA + +#ifdef __cplusplus +} +#endif + +#endif // PUBLIC_FPDFVIEW_H_ diff --git a/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/x64/bin/libpdfium.so b/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/x64/bin/libpdfium.so new file mode 100644 index 000000000..952ac45c2 Binary files /dev/null and b/packages/syncfusion_pdfviewer_linux/linux/include/pdfium/x64/bin/libpdfium.so differ diff --git a/packages/syncfusion_pdfviewer_linux/linux/include/syncfusion_pdfviewer_linux/syncfusion_pdfviewer_linux_plugin.h b/packages/syncfusion_pdfviewer_linux/linux/include/syncfusion_pdfviewer_linux/syncfusion_pdfviewer_linux_plugin.h new file mode 100644 index 000000000..f79c6e126 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/linux/include/syncfusion_pdfviewer_linux/syncfusion_pdfviewer_linux_plugin.h @@ -0,0 +1,26 @@ +#ifndef FLUTTER_PLUGIN_SYNCFUSION_PDFVIEWER_LINUX_PLUGIN_H_ +#define FLUTTER_PLUGIN_SYNCFUSION_PDFVIEWER_LINUX_PLUGIN_H_ + +#include + +G_BEGIN_DECLS + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) +#else +#define FLUTTER_PLUGIN_EXPORT +#endif + +typedef struct _SyncfusionPdfviewerLinuxPlugin SyncfusionPdfviewerLinuxPlugin; +typedef struct { + GObjectClass parent_class; +} SyncfusionPdfviewerLinuxPluginClass; + +FLUTTER_PLUGIN_EXPORT GType syncfusion_pdfviewer_linux_plugin_get_type(); + +FLUTTER_PLUGIN_EXPORT void syncfusion_pdfviewer_linux_plugin_register_with_registrar( + FlPluginRegistrar* registrar); + +G_END_DECLS + +#endif // FLUTTER_PLUGIN_SYNCFUSION_PDFVIEWER_LINUX_PLUGIN_H_ diff --git a/packages/syncfusion_pdfviewer_linux/linux/pdfviewer.cpp b/packages/syncfusion_pdfviewer_linux/linux/pdfviewer.cpp new file mode 100644 index 000000000..a0c0ebc54 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/linux/pdfviewer.cpp @@ -0,0 +1,108 @@ +#include +#include +#include + +#include "pdfviewer.h" + +namespace pdfviewer +{ + struct GStringHash + { + std::size_t operator()(const GString *gs) const + { + return g_str_hash(gs->str); + } + }; + + struct GStringEqual + { + bool operator()(const GString *a, const GString *b) const + { + return g_str_equal(a->str, b->str); + } + }; + + // Repository to store active PDF documents + std::unordered_map documentRepo; + + // Function to retrieve a PDF document by ID + PdfDocument *GetPdfDocument(const gchar *doc_id) + { + if (!doc_id) + return nullptr; + + GString tmp = GString{(gchar *)doc_id, strlen(doc_id), 0}; + auto it = documentRepo.find(&tmp); + if (it != documentRepo.end()) + { + return it->second; + } + return nullptr; + } + + // Function to close a PDF document by ID + gboolean ClosePdfDocument(const gchar *doc_id) + { + if (!doc_id) + return FALSE; + + GString tmp = GString{(gchar *)doc_id, strlen(doc_id), 0}; + auto it = documentRepo.find(&tmp); + + if (it != documentRepo.end()) + { + FPDF_CloseDocument(it->second->pdfDocument()); + delete it->second; + g_string_free(it->first, TRUE); + documentRepo.erase(it); + if (documentRepo.empty()) + { + FPDF_DestroyLibrary(); + } + return TRUE; + } + return FALSE; + } + + // Function to initialize the PDF renderer + PdfDocument *InitializePdfRenderer(GBytes *data, const gchar *password, const gchar *doc_id) + { + if (!data || !doc_id) + return nullptr; + + if (documentRepo.empty()) + { + FPDF_InitLibraryWithConfig(nullptr); + } + + PdfDocument *doc = new PdfDocument(data, password, doc_id); + if (!doc->pdfDocument()) + { + delete doc; + return nullptr; + } + + documentRepo[g_string_new(doc_id)] = doc; + return doc; + } + + // PdfDocument constructor + PdfDocument::PdfDocument(GBytes *data, const gchar *password, const gchar *id) + : data_(g_bytes_ref(data)), document_id_(g_strdup(id)), pdf_document_(nullptr) + { + gsize data_size; + const guint8 *data_bytes = static_cast(g_bytes_get_data(data, &data_size)); + pdf_document_ = FPDF_LoadMemDocument64(data_bytes, data_size, password); + + if (!pdf_document_) + { + } + } + + // PdfDocument destructor + PdfDocument::~PdfDocument() + { + g_bytes_unref(data_); + g_free(document_id_); + } +} // namespace pdfviewer \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/linux/pdfviewer.h b/packages/syncfusion_pdfviewer_linux/linux/pdfviewer.h new file mode 100644 index 000000000..c7a18b843 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/linux/pdfviewer.h @@ -0,0 +1,28 @@ +#include +#include + +namespace pdfviewer { + + class PdfDocument { + public: + // Constructor initializes the document with data, password and its ID + PdfDocument(GBytes* data, const gchar *password, const gchar *id); + ~PdfDocument(); + + // Accessor for document ID + const gchar* documentID() const { return document_id_; } + + // Accessor for document + FPDF_DOCUMENT pdfDocument() const { return pdf_document_; } + + private: + GBytes* data_; + gchar* document_id_; + FPDF_DOCUMENT pdf_document_; + }; + + PdfDocument* InitializePdfRenderer(GBytes* data, const gchar *password, const gchar *doc_id); + PdfDocument* GetPdfDocument(const gchar *doc_id); + gboolean ClosePdfDocument(const gchar *doc_id); + +} // namespace pdfviewer \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/linux/syncfusion_pdfviewer_linux_plugin.cc b/packages/syncfusion_pdfviewer_linux/linux/syncfusion_pdfviewer_linux_plugin.cc new file mode 100644 index 000000000..038de9eb8 --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/linux/syncfusion_pdfviewer_linux_plugin.cc @@ -0,0 +1,314 @@ +#include "include/syncfusion_pdfviewer_linux/syncfusion_pdfviewer_linux_plugin.h" + +#include +#include +#include +#include + +#include "pdfviewer.h" +#include "fpdfview.h" + +#define SYNCFUSION_PDFVIEWER_LINUX_PLUGIN(obj) \ + (G_TYPE_CHECK_INSTANCE_CAST((obj), syncfusion_pdfviewer_linux_plugin_get_type(), SyncfusionPdfviewerLinuxPlugin)) + +struct _SyncfusionPdfviewerLinuxPlugin +{ + GObject parent_instance; +}; + +G_DEFINE_TYPE(SyncfusionPdfviewerLinuxPlugin, syncfusion_pdfviewer_linux_plugin, g_object_get_type()) + +// Forward declarations for method handlers +FlMethodResponse *InitializePDFRenderer(FlMethodCall *method_call); +FlMethodResponse *GetPagesHeight(FlMethodCall *method_call); +FlMethodResponse *GetPagesWidth(FlMethodCall *method_call); +FlMethodResponse *GetPdfPageImage(FlMethodCall *method_call); +FlMethodResponse *GetPdfPageTileImage(FlMethodCall *method_call); +FlMethodResponse *CloseDocument(FlMethodCall *method_call); + +// Helper function for creating error responses +static FlMethodResponse *create_error_response(const gchar *code, const gchar *message) +{ + return FL_METHOD_RESPONSE(fl_method_error_response_new(code, message, nullptr)); +} + +// Method call handler to map method names to appropriate functions +static void syncfusion_pdfviewer_linux_plugin_handle_method_call( + SyncfusionPdfviewerLinuxPlugin *self, + FlMethodCall *method_call) +{ + g_autoptr(FlMethodResponse) response = nullptr; + const gchar *method = fl_method_call_get_name(method_call); + + if (g_strcmp0(method, "initializePdfRenderer") == 0) + { + response = InitializePDFRenderer(method_call); + } + else if (g_strcmp0(method, "getPagesHeight") == 0) + { + response = GetPagesHeight(method_call); + } + else if (g_strcmp0(method, "getPagesWidth") == 0) + { + response = GetPagesWidth(method_call); + } + else if (g_strcmp0(method, "getPage") == 0) + { + response = GetPdfPageImage(method_call); + } + else if (g_strcmp0(method, "getTileImage") == 0) + { + response = GetPdfPageTileImage(method_call); + } + else if (g_strcmp0(method, "closeDocument") == 0) + { + response = CloseDocument(method_call); + } + else + { + response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); + } + + fl_method_call_respond(method_call, response, nullptr); +} + +// Initialization and disposal methods +static void syncfusion_pdfviewer_linux_plugin_dispose(GObject *object) +{ + G_OBJECT_CLASS(syncfusion_pdfviewer_linux_plugin_parent_class)->dispose(object); +} + +static void syncfusion_pdfviewer_linux_plugin_class_init(SyncfusionPdfviewerLinuxPluginClass *klass) +{ + G_OBJECT_CLASS(klass)->dispose = syncfusion_pdfviewer_linux_plugin_dispose; +} + +static void syncfusion_pdfviewer_linux_plugin_init(SyncfusionPdfviewerLinuxPlugin *self) {} + +static void method_call_cb(FlMethodChannel *channel, FlMethodCall *method_call, gpointer user_data) +{ + SyncfusionPdfviewerLinuxPlugin *plugin = SYNCFUSION_PDFVIEWER_LINUX_PLUGIN(user_data); + syncfusion_pdfviewer_linux_plugin_handle_method_call(plugin, method_call); +} + +// Plugin registration +void syncfusion_pdfviewer_linux_plugin_register_with_registrar(FlPluginRegistrar *registrar) +{ + SyncfusionPdfviewerLinuxPlugin *plugin = SYNCFUSION_PDFVIEWER_LINUX_PLUGIN( + g_object_new(syncfusion_pdfviewer_linux_plugin_get_type(), nullptr)); + + g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); + g_autoptr(FlMethodChannel) channel = + fl_method_channel_new(fl_plugin_registrar_get_messenger(registrar), + "syncfusion_flutter_pdfviewer", + FL_METHOD_CODEC(codec)); + fl_method_channel_set_method_call_handler(channel, method_call_cb, + g_object_ref(plugin), + g_object_unref); + + g_object_unref(plugin); +} + +// Function to initialize PDF renderer +FlMethodResponse *InitializePDFRenderer(FlMethodCall *method_call) +{ + FlValue *args = fl_method_call_get_args(method_call); + if (args != nullptr && fl_value_get_type(args) == FL_VALUE_TYPE_MAP) + { + FlValue *idKey = fl_value_lookup_string(args, "documentID"); + const gchar *documentID = idKey ? fl_value_get_string(idKey) : ""; + + FlValue *documentBytesKey = fl_value_lookup_string(args, "documentBytes"); + const uint8_t *bytesValue = documentBytesKey ? fl_value_get_uint8_list(documentBytesKey) : nullptr; + gsize size = fl_value_get_length(documentBytesKey); + + FlValue *passwordKey = fl_value_lookup_string(args, "password"); + const gchar *password = ""; + if (passwordKey && fl_value_get_type(passwordKey) == FL_VALUE_TYPE_STRING) { + password = fl_value_get_string(passwordKey); + } + + if (documentID && bytesValue != nullptr && size > 0) + { + g_autoptr(GBytes) data = g_bytes_new(bytesValue, size); + auto document = pdfviewer::InitializePdfRenderer(data, password, documentID); + if (document) + { + int pageCount = FPDF_GetPageCount(document->pdfDocument()); + FlValue *result = fl_value_new_string(g_strdup_printf("%d", pageCount)); + return FL_METHOD_RESPONSE(fl_method_success_response_new(result)); + } + } + } + return create_error_response("InvalidArguments", "Initialization failed"); +} + +// Function to get pages' heights +FlMethodResponse *GetPagesHeight(FlMethodCall *method_call) +{ + FlValue *args = fl_method_call_get_args(method_call); + const gchar *documentID = fl_value_get_string(args) ?: ""; + + if (!documentID) + return create_error_response("InvalidArguments", "Document ID not provided"); + + auto documentPtr = pdfviewer::GetPdfDocument(documentID); + if (!documentPtr) + return create_error_response("DocumentNotFound", "Document not found"); + + int pageCount = FPDF_GetPageCount(documentPtr->pdfDocument()); + FlValue *flPageHeights = fl_value_new_list(); + + for (int i = 0; i < pageCount; ++i) + { + FPDF_PAGE page = FPDF_LoadPage(documentPtr->pdfDocument(), i); + if (page) + { + double height = FPDF_GetPageHeightF(page); + fl_value_append_take(flPageHeights, fl_value_new_float(height)); + FPDF_ClosePage(page); + } + } + return FL_METHOD_RESPONSE(fl_method_success_response_new(flPageHeights)); +} + +// Function to get pages' widths +FlMethodResponse *GetPagesWidth(FlMethodCall *method_call) +{ + FlValue *args = fl_method_call_get_args(method_call); + const gchar *documentID = fl_value_get_string(args) ?: ""; + + if (!documentID) + return create_error_response("InvalidArguments", "Document ID not provided"); + + auto documentPtr = pdfviewer::GetPdfDocument(documentID); + if (!documentPtr) + return create_error_response("DocumentNotFound", "Document not found"); + + int pageCount = FPDF_GetPageCount(documentPtr->pdfDocument()); + FlValue *flPageWidths = fl_value_new_list(); + + for (int i = 0; i < pageCount; ++i) + { + FPDF_PAGE page = FPDF_LoadPage(documentPtr->pdfDocument(), i); + if (page) + { + double width = FPDF_GetPageWidthF(page); + fl_value_append_take(flPageWidths, fl_value_new_float(width)); + FPDF_ClosePage(page); + } + } + return FL_METHOD_RESPONSE(fl_method_success_response_new(flPageWidths)); +} + +// Function to convert FPDF_BITMAP to FlValue using a raw array +FlValue *ConvertBitmapToFlValue(FPDF_BITMAP bitmap, int width, int height) +{ + // Calculate buffer size: width * height * 4 (for RGBA) + size_t bufferSize = width * height * 4; + + // Allocate memory for the raw array + std::vector imageData(bufferSize); + + // Copy data from the bitmap to the raw array + std::memcpy(imageData.data(), FPDFBitmap_GetBuffer(bitmap), bufferSize); + + // Create an FlValue from the raw array + return fl_value_new_uint8_list(imageData.data(), bufferSize); +} + +// Function to get a page's image +FlMethodResponse *GetPdfPageImage(FlMethodCall *method_call) +{ + FlValue *args = fl_method_call_get_args(method_call); + if (args == nullptr || fl_value_get_type(args) != FL_VALUE_TYPE_MAP) + return create_error_response("InvalidArguments", "Invalid arguments"); + + int index = fl_value_get_int(fl_value_lookup_string(args, "index")); + int width = fl_value_get_int(fl_value_lookup_string(args, "width")); + int height = fl_value_get_int(fl_value_lookup_string(args, "height")); + const gchar *documentID = fl_value_get_string(fl_value_lookup_string(args, "documentID")); + + if (!documentID) + return create_error_response("InvalidArguments", "Document ID not provided"); + + auto documentPtr = pdfviewer::GetPdfDocument(documentID); + if (!documentPtr) + return create_error_response("DocumentNotFound", "Document not found"); + + FPDF_DOCUMENT document = documentPtr->pdfDocument(); + FPDF_PAGE page = FPDF_LoadPage(document, index - 1); + if (!page) + return create_error_response("PageNotFound", "Page not found"); + + FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0); + FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF); + FPDF_RenderPageBitmap(bitmap, page, 0, 0, width, height, 0, FPDF_LCD_TEXT | FPDF_REVERSE_BYTE_ORDER); + + // Convert and get FlValue + FlValue *result = ConvertBitmapToFlValue(bitmap, width, height); + + FPDFBitmap_Destroy(bitmap); + FPDF_ClosePage(page); + + return FL_METHOD_RESPONSE(fl_method_success_response_new(result)); +} + +// Function to get tile image from a PDF page +FlMethodResponse *GetPdfPageTileImage(FlMethodCall *method_call) +{ + FlValue *args = fl_method_call_get_args(method_call); + if (args == nullptr || fl_value_get_type(args) != FL_VALUE_TYPE_MAP) + return create_error_response("InvalidArguments", "Invalid arguments"); + + int pageNumber = fl_value_get_int(fl_value_lookup_string(args, "pageNumber")); + double scale = fl_value_get_float(fl_value_lookup_string(args, "scale")); + const gchar *documentID = fl_value_get_string(fl_value_lookup_string(args, "documentID")); + double x = fl_value_get_float(fl_value_lookup_string(args, "x")); + double y = fl_value_get_float(fl_value_lookup_string(args, "y")); + int width = static_cast(fl_value_get_float(fl_value_lookup_string(args, "width"))); + int height = static_cast(fl_value_get_float(fl_value_lookup_string(args, "height"))); + + if (!documentID) + return create_error_response("InvalidArguments", "Document ID not provided"); + + auto documentPtr = pdfviewer::GetPdfDocument(documentID); + if (!documentPtr) + return create_error_response("DocumentNotFound", "Document not found"); + + FPDF_DOCUMENT document = documentPtr->pdfDocument(); + FPDF_PAGE page = FPDF_LoadPage(document, pageNumber - 1); + if (!page) + return create_error_response("PageNotFound", "Page not found"); + + FS_MATRIX matrix = {static_cast(scale), 0, 0, static_cast(scale), + static_cast(-x * scale), static_cast(-y * scale)}; + FS_RECTF rect = {0, 0, static_cast(width * scale), static_cast(height * scale)}; + + FPDF_BITMAP bitmap = FPDFBitmap_Create(width, height, 0); + FPDFBitmap_FillRect(bitmap, 0, 0, width, height, 0xFFFFFFFF); + FPDF_RenderPageBitmapWithMatrix(bitmap, page, &matrix, &rect, FPDF_LCD_TEXT | FPDF_REVERSE_BYTE_ORDER); + + // Convert and get FlValue + FlValue *result = ConvertBitmapToFlValue(bitmap, width, height); + + FPDFBitmap_Destroy(bitmap); + FPDF_ClosePage(page); + + return FL_METHOD_RESPONSE(fl_method_success_response_new(result)); +} + +// Function to close a PDF document +FlMethodResponse *CloseDocument(FlMethodCall *method_call) +{ + FlValue *args = fl_method_call_get_args(method_call); + const gchar *documentID = args ? fl_value_get_string(args) : ""; + + if (documentID) + { + pdfviewer::ClosePdfDocument(documentID); + return FL_METHOD_RESPONSE(fl_method_success_response_new(fl_value_new_string("Success"))); + } + + return create_error_response("Error", "Document ID not provided"); +} \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_linux/pubspec.yaml b/packages/syncfusion_pdfviewer_linux/pubspec.yaml new file mode 100644 index 000000000..2d9e9685b --- /dev/null +++ b/packages/syncfusion_pdfviewer_linux/pubspec.yaml @@ -0,0 +1,23 @@ +name: syncfusion_pdfviewer_linux +description: Linux platform implementation of the Flutter PDF Viewer library that lets you view the PDF documents seamlessly and efficiently. +version: 30.1.37 +homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_pdfviewer_linux + +environment: + sdk: ^3.7.0-0 + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + +flutter: + plugin: + platforms: + linux: + pluginClass: SyncfusionPdfviewerLinuxPlugin diff --git a/packages/syncfusion_pdfviewer_macos/example/analysis_options.yaml b/packages/syncfusion_pdfviewer_macos/example/analysis_options.yaml new file mode 100644 index 000000000..b08414c80 --- /dev/null +++ b/packages/syncfusion_pdfviewer_macos/example/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_macos/example/pubspec.yaml b/packages/syncfusion_pdfviewer_macos/example/pubspec.yaml index 9db085bc0..c23fe0086 100644 --- a/packages/syncfusion_pdfviewer_macos/example/pubspec.yaml +++ b/packages/syncfusion_pdfviewer_macos/example/pubspec.yaml @@ -1,34 +1,18 @@ name: syncfusion_pdfviewer_macos_example description: Demonstrates how to use the syncfusion_pdfviewer plugin in macOS platform. - -# The following line prevents the package from being accidentally published to -# pub.dev using `pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev +publish_to: 'none' environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter - syncfusion_flutter_pdfviewer: - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.5 - dev_dependencies: flutter_test: sdk: flutter -# 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. 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 diff --git a/packages/syncfusion_pdfviewer_macos/macos/syncfusion_pdfviewer_macos/Sources/syncfusion_pdfviewer_macos/SyncfusionFlutterPdfviewerPlugin.swift b/packages/syncfusion_pdfviewer_macos/macos/syncfusion_pdfviewer_macos/Sources/syncfusion_pdfviewer_macos/SyncfusionFlutterPdfviewerPlugin.swift index 332a37b15..eb029dc78 100644 --- a/packages/syncfusion_pdfviewer_macos/macos/syncfusion_pdfviewer_macos/Sources/syncfusion_pdfviewer_macos/SyncfusionFlutterPdfviewerPlugin.swift +++ b/packages/syncfusion_pdfviewer_macos/macos/syncfusion_pdfviewer_macos/Sources/syncfusion_pdfviewer_macos/SyncfusionFlutterPdfviewerPlugin.swift @@ -51,10 +51,18 @@ public class SyncfusionFlutterPdfViewerPlugin: NSObject, FlutterPlugin { guard let args = argument as? [String: Any] else {return} guard let documentBytes = args["documentBytes"] as? FlutterStandardTypedData else {return} guard let currentDocumentID = args["documentID"] as? String else {return} + let password = args["password"] as? String let byte = [UInt8](documentBytes.data) guard let cfData = CFDataCreate(nil, byte, byte.count) else {return} guard let dataProvider = CGDataProvider(data: cfData) else {return} guard let document = CGPDFDocument(dataProvider) else {return} + if let password = password, document.isEncrypted { + let unlocked = document.unlockWithPassword(password) + if !unlocked { + result(FlutterError(code: "PDF_UNLOCK_FAILED", message: "Failed to unlock the PDF with the provided password", details: nil)) + return + } + } documentRepo.updateValue(document, forKey: currentDocumentID) let pageCount = NSNumber(value: document.numberOfPages) result(pageCount.stringValue); diff --git a/packages/syncfusion_pdfviewer_macos/pubspec.yaml b/packages/syncfusion_pdfviewer_macos/pubspec.yaml index 46638307c..4a2ea05b8 100644 --- a/packages/syncfusion_pdfviewer_macos/pubspec.yaml +++ b/packages/syncfusion_pdfviewer_macos/pubspec.yaml @@ -1,11 +1,11 @@ name: syncfusion_pdfviewer_macos description: macOS platform implementation of the Flutter PDF Viewer library that lets you view the PDF documents seamlessly and efficiently. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_pdfviewer_macos environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 flutter: '>=1.20.0' dependencies: @@ -23,4 +23,4 @@ flutter: plugin: platforms: macos: - pluginClass: SyncfusionFlutterPdfViewerPlugin + pluginClass: SyncfusionFlutterPdfViewerPlugin \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_web/example/analysis_options.yaml b/packages/syncfusion_pdfviewer_web/example/analysis_options.yaml new file mode 100644 index 000000000..b08414c80 --- /dev/null +++ b/packages/syncfusion_pdfviewer_web/example/analysis_options.yaml @@ -0,0 +1,3 @@ +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_web/example/pubspec.yaml b/packages/syncfusion_pdfviewer_web/example/pubspec.yaml index 6e33683f0..9b9259e12 100644 --- a/packages/syncfusion_pdfviewer_web/example/pubspec.yaml +++ b/packages/syncfusion_pdfviewer_web/example/pubspec.yaml @@ -1,33 +1,18 @@ name: syncfusion_pdfviewer_web_example description: Demonstrates how to use the syncfusion_pdfviewer_web with the help of syncfusion_flutter_pdfviewer plugin. - -# The following line prevents the package from being accidentally published to -# pub.dev using `pub publish`. This is preferred for private packages. -publish_to: 'none' # Remove this line if you wish to publish to pub.dev +publish_to: 'none' environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 dependencies: flutter: sdk: flutter syncfusion_flutter_pdfviewer: - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.5 - dev_dependencies: flutter_test: sdk: flutter -# 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. 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 diff --git a/packages/syncfusion_pdfviewer_web/example/web/index.html b/packages/syncfusion_pdfviewer_web/example/web/index.html index 43a592132..69c627f8b 100644 --- a/packages/syncfusion_pdfviewer_web/example/web/index.html +++ b/packages/syncfusion_pdfviewer_web/example/web/index.html @@ -38,8 +38,8 @@ diff --git a/packages/syncfusion_pdfviewer_web/lib/pdfviewer_web.dart b/packages/syncfusion_pdfviewer_web/lib/pdfviewer_web.dart index b9c3c480c..a5672fcd6 100644 --- a/packages/syncfusion_pdfviewer_web/lib/pdfviewer_web.dart +++ b/packages/syncfusion_pdfviewer_web/lib/pdfviewer_web.dart @@ -20,10 +20,13 @@ class SyncfusionFlutterPdfViewerPlugin extends PdfViewerPlatform { @override Future initializePdfRenderer( Uint8List documentBytes, - String documentID, - ) async { - Settings documentData = Settings() - ..data = Uint8List.fromList(documentBytes).toJS; + String documentID, [ + String? password, + ]) async { + Settings documentData = + Settings() + ..data = Uint8List.fromList(documentBytes).toJS + ..password = password; final documentLoader = PdfJs.getDocument(documentData); final PdfJsDoc pdfJsDoc = await documentLoader.promise.toDart; final int pagesCount = pdfJsDoc.numPages; @@ -115,10 +118,11 @@ class SyncfusionFlutterPdfViewerPlugin extends PdfViewerPlatform { canvas ..height = height.toInt() ..width = width.toInt(); - final renderSettings = Settings() - ..canvasContext = canvas.context2D - ..viewport = viewport - ..annotationMode = 0; + final renderSettings = + Settings() + ..canvasContext = canvas.context2D + ..viewport = viewport + ..annotationMode = 0; await (page.render(renderSettings)).promise.toDart; return canvas.context2D .getImageData(0, 0, width.toInt(), height.toInt()) @@ -153,10 +157,11 @@ class SyncfusionFlutterPdfViewerPlugin extends PdfViewerPlatform { canvas ..width = fullWidth ..height = fullHeight; - final renderSettings = Settings() - ..canvasContext = canvas.context2D - ..viewport = viewport - ..annotationMode = 0; + final renderSettings = + Settings() + ..canvasContext = canvas.context2D + ..viewport = viewport + ..annotationMode = 0; await (page.render(renderSettings)).promise.toDart; return canvas.context2D .getImageData(0, 0, fullWidth.toInt(), fullHeight.toInt()) diff --git a/packages/syncfusion_pdfviewer_web/lib/src/pdfjs.dart b/packages/syncfusion_pdfviewer_web/lib/src/pdfjs.dart index 83e214bbd..b78b5a4ea 100644 --- a/packages/syncfusion_pdfviewer_web/lib/src/pdfjs.dart +++ b/packages/syncfusion_pdfviewer_web/lib/src/pdfjs.dart @@ -20,6 +20,7 @@ extension type Settings._(JSObject _) implements JSObject { num annotationMode, double offsetX, double offsetY, + String? password, }); external set data(JSUint8Array value); external set scale(double value); @@ -28,6 +29,7 @@ extension type Settings._(JSObject _) implements JSObject { external set annotationMode(num value); external set offsetX(double value); external set offsetY(double value); + external set password(String? value); } extension type PdfJsDocLoader(JSObject _) implements JSObject { diff --git a/packages/syncfusion_pdfviewer_web/pubspec.yaml b/packages/syncfusion_pdfviewer_web/pubspec.yaml index 055ccedac..2103f8fa7 100644 --- a/packages/syncfusion_pdfviewer_web/pubspec.yaml +++ b/packages/syncfusion_pdfviewer_web/pubspec.yaml @@ -1,11 +1,11 @@ name: syncfusion_pdfviewer_web description: Web platform implementation of the Flutter PDF Viewer library that lets you view the PDF documents seamlessly and efficiently. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_pdfviewer_web environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 flutter: '>=1.20.0' dependencies: @@ -17,8 +17,6 @@ dependencies: syncfusion_pdfviewer_platform_interface: path: ../syncfusion_flutter_pdfviewer_platform_interface - - flutter: @@ -26,4 +24,4 @@ flutter: platforms: web: pluginClass: SyncfusionFlutterPdfViewerPlugin - fileName: pdfviewer_web.dart + fileName: pdfviewer_web.dart \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_windows/example/analysis_options.yaml b/packages/syncfusion_pdfviewer_windows/example/analysis_options.yaml index 61b6c4de1..b08414c80 100644 --- a/packages/syncfusion_pdfviewer_windows/example/analysis_options.yaml +++ b/packages/syncfusion_pdfviewer_windows/example/analysis_options.yaml @@ -1,29 +1,3 @@ -# This file configures the analyzer, which statically analyzes Dart code to -# check for errors, warnings, and lints. -# -# The issues identified by the analyzer are surfaced in the UI of Dart-enabled -# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be -# invoked from the command line by running `flutter analyze`. - -# The following line activates a set of recommended lints for Flutter apps, -# packages, and plugins designed to encourage good coding practices. -include: package:flutter_lints/flutter.yaml - -linter: - # The lint rules applied to this project can be customized in the - # section below to disable rules from the `package:flutter_lints/flutter.yaml` - # included above or to enable additional rules. A list of all available lints - # and their documentation is published at - # https://dart-lang.github.io/linter/lints/index.html. - # - # Instead of disabling a lint rule for the entire project in the - # section below, it can also be suppressed for a single line of code - # or a specific dart file by using the `// ignore: name_of_lint` and - # `// ignore_for_file: name_of_lint` syntax on the line or in the file - # producing the lint. - rules: - # avoid_print: false # Uncomment to disable the `avoid_print` rule - # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule - -# Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options +analyzer: + errors: + invalid_dependency: ignore \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_windows/example/pubspec.yaml b/packages/syncfusion_pdfviewer_windows/example/pubspec.yaml index 5bce45697..e780a9673 100644 --- a/packages/syncfusion_pdfviewer_windows/example/pubspec.yaml +++ b/packages/syncfusion_pdfviewer_windows/example/pubspec.yaml @@ -1,78 +1,18 @@ name: syncfusion_pdfviewer_windows_example description: Demonstrates how to use the syncfusion_pdfviewer_windows plugin. - -# 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 +publish_to: 'none' environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.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 - syncfusion_flutter_pdfviewer: - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^1.0.5 - 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: ^1.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. 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: - # - 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 + uses-material-design: true \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_windows/pubspec.yaml b/packages/syncfusion_pdfviewer_windows/pubspec.yaml index ca6a1bfca..0b26ca3c0 100644 --- a/packages/syncfusion_pdfviewer_windows/pubspec.yaml +++ b/packages/syncfusion_pdfviewer_windows/pubspec.yaml @@ -1,22 +1,21 @@ name: syncfusion_pdfviewer_windows description: Windows platform implementation of the Flutter PDF Viewer library that lets you view the PDF documents seamlessly and efficiently. -version: 29.1.33 +version: 30.1.37 homepage: https://github.com/syncfusion/flutter-widgets/tree/master/packages/syncfusion_pdfviewer_windows environment: - sdk: '>=3.4.0 <4.0.0' + sdk: ^3.7.0-0 flutter: '>=2.5.0' dependencies: flutter: sdk: flutter -dev_dependencies: - flutter_lints: ^1.0.0 + flutter: plugin: platforms: windows: - pluginClass: SyncfusionPdfviewerWindowsPlugin + pluginClass: SyncfusionPdfviewerWindowsPlugin \ No newline at end of file diff --git a/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.cpp b/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.cpp index 0e4817642..e616cbc54 100644 --- a/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.cpp +++ b/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.cpp @@ -45,24 +45,24 @@ namespace pdfviewer documentRepo.erase(docID); } - std::shared_ptr initializePdfRenderer(std::vector data, std::string docID) + std::shared_ptr initializePdfRenderer(std::vector data, std::string password, std::string docID) { if (documentRepo.size() == 0) { FPDF_InitLibraryWithConfig(nullptr); } - std::shared_ptr doc = std::make_shared(data, docID); + std::shared_ptr doc = std::make_shared(data, password, docID); documentRepo[docID] = doc; return doc; } - PdfDocument::PdfDocument(std::vector dataRef, std::string id) : documentID{id} + PdfDocument::PdfDocument(std::vector dataRef, std::string password, std::string id) : documentID{id} { data.swap(dataRef); - pdfDocument = FPDF_LoadMemDocument64(data.data(), data.size(), nullptr); + pdfDocument = FPDF_LoadMemDocument64(data.data(), data.size(), password.c_str()); } PdfDocument::~PdfDocument() {} diff --git a/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.h b/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.h index 413e2359d..e8651008b 100644 --- a/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.h +++ b/packages/syncfusion_pdfviewer_windows/windows/pdfviewer.h @@ -15,7 +15,7 @@ namespace pdfviewer std::vector data; public: - PdfDocument(std::vector data, std::string id); + PdfDocument(std::vector data, std::string password, std::string id); ~PdfDocument(); @@ -23,7 +23,7 @@ namespace pdfviewer std::string documentID; }; - std::shared_ptr initializePdfRenderer(std::vector data, std::string docID); + std::shared_ptr initializePdfRenderer(std::vector data, std::string password, std::string docID); std::shared_ptr getPdfDocument(std::string docID); void closePdfDocument(std::string docID); } diff --git a/packages/syncfusion_pdfviewer_windows/windows/syncfusion_pdfviewer_windows_plugin.cpp b/packages/syncfusion_pdfviewer_windows/windows/syncfusion_pdfviewer_windows_plugin.cpp index 0c97e6269..0e7ae3e44 100644 --- a/packages/syncfusion_pdfviewer_windows/windows/syncfusion_pdfviewer_windows_plugin.cpp +++ b/packages/syncfusion_pdfviewer_windows/windows/syncfusion_pdfviewer_windows_plugin.cpp @@ -75,10 +75,20 @@ namespace pdfviewer const auto *arguments = std::get_if(method_call.arguments()); auto documentBytes = arguments->find(flutter::EncodableValue("documentBytes")); auto documentID = arguments->find(flutter::EncodableValue("documentID")); - auto id = std::get(documentID->second); + auto passwordIter = arguments->find(flutter::EncodableValue("password")); + auto bytes = std::get>(documentBytes->second); - std::shared_ptr document = initializePdfRenderer(bytes, id); - int pageCount = FPDF_GetPageCount(document->pdfDocument); + std::optional password; + if (passwordIter != arguments->end()) { + const auto& passwordValue = passwordIter->second; + if (!passwordValue.IsNull()) { + password = std::get(passwordValue); + } + } + + std::string docID = std::get(documentID->second); + std::shared_ptr pdfDoc = initializePdfRenderer(bytes, password.value_or(""), docID); + int pageCount = FPDF_GetPageCount(pdfDoc->pdfDocument); result->Success(flutter::EncodableValue(std::to_string(pageCount))); }